diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 4b9f069ab..30af24bd2 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -29,6 +29,7 @@ RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ gpg \ gnupg2 \ libusb-1.0-0-dev \ + libuv1-dev \ libi2c-dev \ libxcb-xkb-dev \ libxkbcommon-dev \ diff --git a/.github/ISSUE_TEMPLATE/Bug Report.yml b/.github/ISSUE_TEMPLATE/Bug Report.yml index f638b9018..bc77e8c1b 100644 --- a/.github/ISSUE_TEMPLATE/Bug Report.yml +++ b/.github/ISSUE_TEMPLATE/Bug Report.yml @@ -72,6 +72,15 @@ body: validations: required: true + - type: checkboxes + id: mui + attributes: + label: Is this bug report about any UI component firmware like InkHUD or Meshtatic UI (MUI)? + options: + - label: Meshtastic UI aka MUI colorTFT + - label: InkHUD ePaper + - label: OLED slide UI on any display + - type: input id: version attributes: diff --git a/.github/actions/setup-native/action.yml b/.github/actions/setup-native/action.yml index 36c95d943..05f95cd40 100644 --- a/.github/actions/setup-native/action.yml +++ b/.github/actions/setup-native/action.yml @@ -11,4 +11,4 @@ runs: - name: Install libs needed for native build shell: bash run: | - sudo apt-get install -y libbluetooth-dev libgpiod-dev libyaml-cpp-dev openssl libssl-dev libulfius-dev liborcania-dev libusb-1.0-0-dev libi2c-dev + sudo apt-get install -y libbluetooth-dev libgpiod-dev libyaml-cpp-dev openssl libssl-dev libulfius-dev liborcania-dev libusb-1.0-0-dev libi2c-dev libuv1-dev diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 6ccb4a105..a15b34aae 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,7 +1,6 @@ +## 🙏 Thank you for sending in a pull request, here's some tips to get started! + ### ❌ (Please delete all these tips and replace them with your text) ❌ - -## Thank you for sending in a pull request, here's some tips to get started! - - Before starting on some new big chunk of code, it it is optional but highly recommended to open an issue first to say "Hey, I think this idea X should be implemented and I'm starting work on it. My general plan is Y, any feedback is appreciated." This will allow other devs to potentially save you time by not accidentially duplicating work etc... @@ -12,4 +11,17 @@ - If your PR fixes a bug, mention "fixes #bugnum" somewhere in your pull request description. - If your other co-developers have comments on your PR please tweak as needed. - Please also enable "Allow edits by maintainers". +- Please do not submit untested code. +- If you do not have the affected hardware to test your code changes adequately against regressions, please indicate this, so that contributors and commnunity members can help test your changes. - If your PR gets accepted you can request a "Contributor" role in the Meshtastic Discord + + +## 🤝 Attestations +- [ ] I have tested that my proposed changes behave as described. +- [ ] I have tested that my proposed changes do not cause any obvious regressions on the following devices: + - [ ] Heltec (Lora32) V3 + - [ ] LilyGo T-Deck + - [ ] LilyGo T-Beam + - [ ] RAK WisBlock 4631 + - [ ] Seeed Studio T-1000E tracker card + - [ ] Other (please specify below) diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index b0561679a..4c570c856 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -9,14 +9,14 @@ plugins: lint: enabled: - prettier@3.5.3 - - trufflehog@3.88.17 - - yamllint@1.36.0 + - trufflehog@3.88.20 + - yamllint@1.37.0 - bandit@1.8.3 - - checkov@3.2.386 + - checkov@3.2.394 - terrascan@1.19.9 - - trivy@0.60.0 + - trivy@0.61.0 - taplo@0.9.3 - - ruff@0.10.0 + - ruff@0.11.2 - isort@6.0.1 - markdownlint@0.44.0 - oxipng@9.1.4 @@ -28,7 +28,7 @@ lint: - shellcheck@0.10.0 - black@25.1.0 - git-diff-check - - gitleaks@8.24.0 + - gitleaks@8.24.2 - clang-format@16.0.3 ignore: - linters: [ALL] diff --git a/Dockerfile b/Dockerfile index fd1bb6164..733a46325 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ ENV TZ=Etc/UTC ENV PIP_ROOT_USER_ACTION=ignore RUN apt-get update && apt-get install --no-install-recommends -y \ wget g++ zip git ca-certificates \ - libgpiod-dev libyaml-cpp-dev libbluetooth-dev libi2c-dev \ + libgpiod-dev libyaml-cpp-dev libbluetooth-dev libi2c-dev libuv1-dev \ libusb-1.0-0-dev libulfius-dev liborcania-dev libssl-dev pkg-config \ && apt-get clean && rm -rf /var/lib/apt/lists/* \ && pip install --no-cache-dir -U platformio \ @@ -38,7 +38,7 @@ ENV TZ=Etc/UTC USER root RUN apt-get update && apt-get --no-install-recommends -y install \ - libc-bin libc6 libgpiod2 libyaml-cpp0.7 libi2c0 libulfius2.7 libusb-1.0-0-dev liborcania2.3 libssl3 \ + libc-bin libc6 libgpiod2 libyaml-cpp0.7 libi2c0 libuv1 libusb-1.0-0-dev liborcania2.3 libulfius2.7 libssl3 \ && apt-get clean && rm -rf /var/lib/apt/lists/* \ && mkdir -p /var/lib/meshtasticd \ && mkdir -p /etc/meshtasticd/config.d \ diff --git a/alpine.Dockerfile b/alpine.Dockerfile index b6d91a75a..17afc2964 100644 --- a/alpine.Dockerfile +++ b/alpine.Dockerfile @@ -9,7 +9,7 @@ FROM python:3.13-alpine3.21 AS builder ENV PIP_ROOT_USER_ACTION=ignore RUN apk --no-cache add \ bash g++ libstdc++-dev linux-headers zip git ca-certificates libgpiod-dev yaml-cpp-dev bluez-dev \ - libusb-dev i2c-tools-dev openssl-dev pkgconf argp-standalone \ + libusb-dev i2c-tools-dev libuv-dev openssl-dev pkgconf argp-standalone \ && rm -rf /var/cache/apk/* \ && pip install --no-cache-dir -U platformio \ && mkdir /tmp/firmware @@ -32,7 +32,7 @@ FROM alpine:3.21 USER root RUN apk --no-cache add \ - libstdc++ libgpiod yaml-cpp libusb i2c-tools \ + libstdc++ libgpiod yaml-cpp libusb i2c-tools libuv \ && rm -rf /var/cache/apk/* \ && mkdir -p /var/lib/meshtasticd \ && mkdir -p /etc/meshtasticd/config.d \ diff --git a/arch/esp32/esp32.ini b/arch/esp32/esp32.ini index 256781ba1..df3778002 100644 --- a/arch/esp32/esp32.ini +++ b/arch/esp32/esp32.ini @@ -45,11 +45,11 @@ lib_deps = ${networking_base.lib_deps} ${environmental_base.lib_deps} ${radiolib_base.lib_deps} - https://github.com/meshtastic/esp32_https_server.git#23665b3adc080a311dcbb586ed5941b5f94d6ea2 + https://github.com/meshtastic/esp32_https_server/archive/23665b3adc080a311dcbb586ed5941b5f94d6ea2.zip h2zero/NimBLE-Arduino@^1.4.3 - https://github.com/dbinfrago/libpax.git#3cdc0371c375676a97967547f4065607d4c53fd1 + https://github.com/dbinfrago/libpax/archive/3cdc0371c375676a97967547f4065607d4c53fd1.zip lewisxhe/XPowersLib@^0.2.7 - https://github.com/meshtastic/ESP32_Codec2.git#633326c78ac251c059ab3a8c430fcdf25b41672f + https://github.com/meshtastic/ESP32_Codec2/archive/633326c78ac251c059ab3a8c430fcdf25b41672f.zip rweather/Crypto@^0.4.0 lib_ignore = diff --git a/arch/esp32/esp32c6.ini b/arch/esp32/esp32c6.ini index d0425812f..dba3bac08 100644 --- a/arch/esp32/esp32c6.ini +++ b/arch/esp32/esp32c6.ini @@ -1,6 +1,6 @@ [esp32c6_base] extends = esp32_base -platform = https://github.com/Jason2866/platform-espressif32.git#22faa566df8c789000f8136cd8d0aca49617af55 +platform = https://github.com/Jason2866/platform-espressif32/archive/22faa566df8c789000f8136cd8d0aca49617af55.zip build_flags = ${arduino_base.build_flags} -Wall @@ -25,7 +25,7 @@ lib_deps = ${environmental_base.lib_deps} ${radiolib_base.lib_deps} lewisxhe/XPowersLib@^0.2.7 - https://github.com/meshtastic/ESP32_Codec2.git#633326c78ac251c059ab3a8c430fcdf25b41672f + https://github.com/meshtastic/ESP32_Codec2/archive/633326c78ac251c059ab3a8c430fcdf25b41672f.zip rweather/Crypto@^0.4.0 build_src_filter = diff --git a/arch/nrf52/nrf52.ini b/arch/nrf52/nrf52.ini index d4e88af1f..ca12be6b1 100644 --- a/arch/nrf52/nrf52.ini +++ b/arch/nrf52/nrf52.ini @@ -1,10 +1,10 @@ [nrf52_base] ; Instead of the standard nordicnrf52 platform, we use our fork which has our added variant files -platform = platformio/nordicnrf52@^10.7.0 +platform = platformio/nordicnrf52@^10.8.0 extends = arduino_base platform_packages = ; our custom Git version until they merge our PR - platformio/framework-arduinoadafruitnrf52 @ https://github.com/meshtastic/Adafruit_nRF52_Arduino.git#e13f5820002a4fb2a5e6754b42ace185277e5adf + platformio/framework-arduinoadafruitnrf52 @ https://github.com/meshtastic/Adafruit_nRF52_Arduino#e13f5820002a4fb2a5e6754b42ace185277e5adf platformio/toolchain-gccarmnoneeabi@~1.90301.0 build_type = debug diff --git a/arch/nrf52/nrf52840.ini b/arch/nrf52/nrf52840.ini index a13a600f3..0dab5d9ba 100644 --- a/arch/nrf52/nrf52840.ini +++ b/arch/nrf52/nrf52840.ini @@ -6,7 +6,7 @@ build_flags = ${nrf52_base.build_flags} lib_deps = ${nrf52_base.lib_deps} ${environmental_base.lib_deps} - https://github.com/Kongduino/Adafruit_nRFCrypto.git#e31a8825ea3300b163a0a3c1ddd5de34e10e1371 + https://github.com/Kongduino/Adafruit_nRFCrypto/archive/e31a8825ea3300b163a0a3c1ddd5de34e10e1371.zip ; Common NRF52 debugging settings follow. See the Meshtastic developer docs for how to connect SWD debugging probes to your board. diff --git a/arch/portduino/portduino.ini b/arch/portduino/portduino.ini index 7ea6a77a2..e0488aeff 100644 --- a/arch/portduino/portduino.ini +++ b/arch/portduino/portduino.ini @@ -1,6 +1,6 @@ ; The Portduino based 'native' environment. Currently supported on Linux targets with real LoRa hardware (or simulated). [portduino_base] -platform = https://github.com/meshtastic/platform-native.git#562d189828f09fbf4c4093b3c0104bae9d8e9ff9 +platform = https://github.com/meshtastic/platform-native/archive/c5bd469ab9b5a6966321e09557b27d906961da63.zip framework = arduino build_src_filter = @@ -26,7 +26,7 @@ lib_deps = ${radiolib_base.lib_deps} rweather/Crypto@^0.4.0 lovyan03/LovyanGFX@^1.2.0 - https://github.com/pine64/libch341-spi-userspace#a9b17e3452f7fb747000d9b4ad4409155b39f6ef + https://github.com/pine64/libch341-spi-userspace/archive/a9b17e3452f7fb747000d9b4ad4409155b39f6ef.zip build_flags = ${arduino_base.build_flags} @@ -34,10 +34,12 @@ build_flags = -Isrc/platform/portduino -DRADIOLIB_EEPROM_UNSUPPORTED -DPORTDUINO_LINUX_HARDWARE + -DHAS_UDP_MULTICAST -lpthread -lstdc++fs -lbluetooth -lgpiod -lyaml-cpp -li2c + -luv -std=c++17 diff --git a/arch/rp2xx0/rp2040.ini b/arch/rp2xx0/rp2040.ini index 1542dbee7..33fcfb211 100644 --- a/arch/rp2xx0/rp2040.ini +++ b/arch/rp2xx0/rp2040.ini @@ -1,8 +1,8 @@ ; Common settings for rp2040 Processor based targets [rp2040_base] -platform = https://github.com/maxgerhardt/platform-raspberrypi.git#76ecf3c7e9dd4503af0331154c4ca1cddc4b03e5 ; For arduino-pico >= 4.4.3 +platform = https://github.com/maxgerhardt/platform-raspberrypi#76ecf3c7e9dd4503af0331154c4ca1cddc4b03e5 ; For arduino-pico >= 4.4.3 extends = arduino_base -platform_packages = framework-arduinopico@https://github.com/earlephilhower/arduino-pico.git#4.4.3 +platform_packages = framework-arduinopico@https://github.com/earlephilhower/arduino-pico#4.4.3 board_build.core = earlephilhower board_build.filesystem_size = 0.5m diff --git a/arch/rp2xx0/rp2350.ini b/arch/rp2xx0/rp2350.ini index 6f1e4400e..841035c80 100644 --- a/arch/rp2xx0/rp2350.ini +++ b/arch/rp2xx0/rp2350.ini @@ -1,8 +1,8 @@ ; Common settings for rp2040 Processor based targets [rp2350_base] -platform = https://github.com/maxgerhardt/platform-raspberrypi.git#76ecf3c7e9dd4503af0331154c4ca1cddc4b03e5 ; For arduino-pico >= 4.4.3 +platform = https://github.com/maxgerhardt/platform-raspberrypi#76ecf3c7e9dd4503af0331154c4ca1cddc4b03e5 ; For arduino-pico >= 4.4.3 extends = arduino_base -platform_packages = framework-arduinopico@https://github.com/earlephilhower/arduino-pico.git#4.4.3 +platform_packages = framework-arduinopico@https://github.com/earlephilhower/arduino-pico#4.4.3 board_build.core = earlephilhower board_build.filesystem_size = 0.5m diff --git a/arch/stm32/stm32.ini b/arch/stm32/stm32.ini index efa1ab0e4..c1b58bb82 100644 --- a/arch/stm32/stm32.ini +++ b/arch/stm32/stm32.ini @@ -1,13 +1,14 @@ [stm32_base] extends = arduino_base -platform = platformio/ststm32 -platform_packages = platformio/framework-arduinoststm32@^4.20900.0 +platform = ststm32 +platform_packages = platformio/framework-arduinoststm32@https://github.com/stm32duino/Arduino_Core_STM32/archive/2.10.1.zip +extra_scripts = + ${env.extra_scripts} + post:extra_scripts/extra_stm32.py build_type = release -;board_build.flash_offset = 0x08000000 - -build_flags = +build_flags = ${arduino_base.build_flags} -flto -Isrc/platform/stm32wl -g @@ -18,27 +19,24 @@ build_flags = -DMESHTASTIC_EXCLUDE_SCREEN -DMESHTASTIC_EXCLUDE_MQTT -DMESHTASTIC_EXCLUDE_BLUETOOTH - -DMESHTASTIC_EXCLUDE_PKI -DMESHTASTIC_EXCLUDE_GPS -; -DVECT_TAB_OFFSET=0x08000000 - -DconfigUSE_CMSIS_RTOS_V2=1 -; -DSPI_MODE_0=SPI_MODE0 + ;-DDEBUG_MUTE -fmerge-all-constants -ffunction-sections -fdata-sections - -build_src_filter = + +build_src_filter = ${arduino_base.build_src_filter} - - - - - - - - - - - - - - board_upload.offset_address = 0x08000000 upload_protocol = stlink +debug_tool = stlink lib_deps = ${env.lib_deps} - charlesbaynham/OSFS@^1.2.3 - jgromes/RadioLib@7.0.2 - https://github.com/caveman99/Crypto.git#f61ae26a53f7a2d0ba5511625b8bf8eff3a35d5e + ${radiolib_base.lib_deps} + https://github.com/caveman99/Crypto/archive/eae9c768054118a9399690f8af202853d1ae8516.zip lib_ignore = mathertel/OneButton@2.6.1 - Wire \ No newline at end of file + Wire diff --git a/bin/config-dist.yaml b/bin/config-dist.yaml index da4c192c7..722f80fae 100644 --- a/bin/config-dist.yaml +++ b/bin/config-dist.yaml @@ -6,6 +6,12 @@ ### Including the "Module:" line! --- Lora: + # Default to auto-detecting the module type + # This will be overridden by configs from config.d + Module: auto + +# # Uncomment to enable Simulation mode, or use --sim +# Module: sim # Module: sx1262 # Waveshare SX1302 LISTEN ONLY AT THIS TIME! # CS: 7 diff --git a/bin/config.d/lora-Adafruit-RFM9x b/bin/config.d/lora-Adafruit-RFM9x deleted file mode 100644 index 2d64f1f91..000000000 --- a/bin/config.d/lora-Adafruit-RFM9x +++ /dev/null @@ -1,5 +0,0 @@ -# Module: RF95 # Adafruit RFM9x -# Reset: 25 -# CS: 7 -# IRQ: 22 -# Busy: 23 \ No newline at end of file diff --git a/bin/config.d/lora-Adafruit-RFM9x.yaml b/bin/config.d/lora-Adafruit-RFM9x.yaml new file mode 100644 index 000000000..20295dc72 --- /dev/null +++ b/bin/config.d/lora-Adafruit-RFM9x.yaml @@ -0,0 +1,6 @@ +Lora: + Module: RF95 # Adafruit RFM9x + Reset: 25 + CS: 7 + IRQ: 22 +# Busy: 23 diff --git a/bin/device-install.bat b/bin/device-install.bat index 3ffca0b63..594d973f5 100755 --- a/bin/device-install.bat +++ b/bin/device-install.bat @@ -17,8 +17,8 @@ SET "LOGCOUNTER=0" SET "S3=s3 v3 t-deck wireless-paper wireless-tracker station-g2 unphone" SET "C3=esp32c3" @REM FIXME: Determine flash size from PlatformIO variant, this is unmaintainable. -SET "BIGDB_8MB=picomputer-s3 unphone seeed-sensecap-indicator crowpanel-esp32s3 heltec_capsule_sensor_v3 heltec-v3 heltec-vision-master-e213 heltec-vision-master-e290 heltec-vision-master-t190 heltec-wireless-paper heltec-wireless-tracker heltec-wsl-v3 icarus seeed-xiao-s3 tbeam-s3-core tracksenger" -SET "BIGDB_16MB=t-deck mesh-tab t-energy-s3 dreamcatcher ESP32-S3-Pico m5stack-cores3 station-g2 t-eth-elite t-watch-s3" +SET "BIGDB_8MB=picomputer-s3 unphone seeed-sensecap-indicator crowpanel-esp32s3 heltec_capsule_sensor_v3 heltec-v3 heltec-vision-master-e213 heltec-vision-master-e290 heltec-vision-master-t190 heltec-wireless-paper heltec-wireless-tracker heltec-wsl-v3 icarus seeed-xiao-s3 tbeam-s3-core t-watch-s3 tracksenger" +SET "BIGDB_16MB=t-deck mesh-tab t-energy-s3 dreamcatcher ESP32-S3-Pico m5stack-cores3 station-g2 t-eth-elite" GOTO getopts :help diff --git a/bin/device-install.sh b/bin/device-install.sh index b5322b9d1..bacf48f69 100755 --- a/bin/device-install.sh +++ b/bin/device-install.sh @@ -22,6 +22,7 @@ BIGDB_8MB=( "icarus" "seeed-xiao-s3" "tbeam-s3-core" + "t-watch-s3" "tracksenger" ) BIGDB_16MB=( @@ -33,7 +34,6 @@ BIGDB_16MB=( "m5stack-cores3" "station-g2" "t-eth-elite" - "t-watch-s3" ) S3_VARIANTS=( "s3" diff --git a/boards/ThinkNode-M1.json b/boards/ThinkNode-M1.json new file mode 100644 index 000000000..e55da3ec7 --- /dev/null +++ b/boards/ThinkNode-M1.json @@ -0,0 +1,53 @@ +{ + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" + }, + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DARDUINO_NRF52840_TTGO_EINK -DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + ["0x239A", "0x4405"], + ["0x239A", "0x0029"], + ["0x239A", "0x002A"] + ], + "usb_product": "elecrow_eink", + "mcu": "nrf52840", + "variant": "ELECROW-ThinkNode-M1", + "variants_dir": "variants", + "bsp": { + "name": "adafruit" + }, + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" + }, + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": ["bluetooth"], + "debug": { + "jlink_device": "nRF52840_xxAA", + "onboard_tools": ["jlink"], + "svd_path": "nrf52840.svd", + "openocd_target": "nrf52840-mdk-rs" + }, + "frameworks": ["arduino"], + "name": "elecrow eink", + "upload": { + "maximum_ram_size": 248832, + "maximum_size": 815104, + "speed": 115200, + "protocol": "nrfutil", + "protocols": ["jlink", "nrfjprog", "nrfutil", "stlink"], + "use_1200bps_touch": true, + "require_upload_port": true, + "wait_for_upload_port": true + }, + "url": "FIXME", + "vendor": "ELECROW" +} diff --git a/boards/t-watch-s3.json b/boards/t-watch-s3.json index e6e363305..5d4afd322 100644 --- a/boards/t-watch-s3.json +++ b/boards/t-watch-s3.json @@ -23,7 +23,7 @@ "mcu": "esp32s3", "variant": "t-watch-s3" }, - "connectivity": ["wifi"], + "connectivity": ["wifi", "bluetooth"], "debug": { "openocd_target": "esp32s3.cfg" }, diff --git a/debian/control b/debian/control index b3a8eb58e..693cd6aa5 100644 --- a/debian/control +++ b/debian/control @@ -17,6 +17,7 @@ Build-Depends: debhelper-compat (= 13), libbluetooth-dev, libusb-1.0-0-dev, libi2c-dev, + libuv1-dev, openssl, libssl-dev, libulfius-dev, diff --git a/extra_scripts/extra_stm32.py b/extra_scripts/extra_stm32.py new file mode 100755 index 000000000..f3bd8c514 --- /dev/null +++ b/extra_scripts/extra_stm32.py @@ -0,0 +1,22 @@ +# trunk-ignore-all(ruff/F821) +# trunk-ignore-all(flake8/F821): For SConstruct imports + +Import("env") +# Custom HEX from ELF +env.AddPostAction( + "$BUILD_DIR/${PROGNAME}.elf", + env.VerboseAction( + " ".join( + [ + "$OBJCOPY", + "-O", + "ihex", + "-R", + ".eeprom", + "$BUILD_DIR/${PROGNAME}.elf", + "$BUILD_DIR/${PROGNAME}.hex", + ] + ), + "Building $BUILD_DIR/${PROGNAME}.hex", + ), +) diff --git a/meshtasticd.spec.rpkg b/meshtasticd.spec.rpkg index 0a0f03557..a09261056 100644 --- a/meshtasticd.spec.rpkg +++ b/meshtasticd.spec.rpkg @@ -36,6 +36,7 @@ BuildRequires: pkgconfig(libgpiod) BuildRequires: pkgconfig(bluez) BuildRequires: pkgconfig(libusb-1.0) BuildRequires: libi2c-devel +BuildRequires: pkgconfig(libuv) # Web components: BuildRequires: pkgconfig(openssl) BuildRequires: pkgconfig(liborcania) diff --git a/platformio.ini b/platformio.ini index 7f71d2f58..010aea90f 100644 --- a/platformio.ini +++ b/platformio.ini @@ -56,11 +56,11 @@ build_flags = -Wno-missing-field-initializers monitor_speed = 115200 monitor_filters = direct lib_deps = - https://github.com/meshtastic/esp8266-oled-ssd1306.git#e16cee124fe26490cb14880c679321ad8ac89c95 + https://github.com/meshtastic/esp8266-oled-ssd1306/archive/e16cee124fe26490cb14880c679321ad8ac89c95.zip mathertel/OneButton@2.6.1 - https://github.com/meshtastic/arduino-fsm.git#7db3702bf0cfe97b783d6c72595e3f38e0b19159 - https://github.com/meshtastic/TinyGPSPlus.git#71a82db35f3b973440044c476d4bcdc673b104f4 - https://github.com/meshtastic/ArduinoThread.git#7c3ee9e1951551b949763b1f5280f8db1fa4068d + https://github.com/meshtastic/arduino-fsm/archive/7db3702bf0cfe97b783d6c72595e3f38e0b19159.zip + https://github.com/meshtastic/TinyGPSPlus/archive/71a82db35f3b973440044c476d4bcdc673b104f4.zip + https://github.com/meshtastic/ArduinoThread/archive/7c3ee9e1951551b949763b1f5280f8db1fa4068d.zip nanopb/Nanopb@0.4.91 erriez/ErriezCRC32@1.0.1 @@ -94,18 +94,18 @@ lib_deps = [device-ui_base] lib_deps = - https://github.com/meshtastic/device-ui.git#74e739ed4532ca10393df9fc89ae5a22f0bab2b1 + https://github.com/meshtastic/device-ui/archive/99171e87a70452395b56cce713a951c1c2964370.zip ; Common libs for environmental measurements in telemetry module ; (not included in native / portduino) [environmental_base] lib_deps = - adafruit/Adafruit BusIO@1.16.2 - adafruit/Adafruit Unified Sensor@1.1.14 + adafruit/Adafruit BusIO@1.17.0 + adafruit/Adafruit Unified Sensor@1.1.15 adafruit/Adafruit BMP280 Library@2.6.8 adafruit/Adafruit BMP085 Library@1.2.4 adafruit/Adafruit BME280 Library@2.2.4 - adafruit/Adafruit BMP3XX Library@2.1.5 + adafruit/Adafruit BMP3XX Library@2.1.6 adafruit/Adafruit DPS310@1.1.5 adafruit/Adafruit MCP9808 Library@2.0.2 adafruit/Adafruit INA260 Library@1.5.2 @@ -114,27 +114,27 @@ lib_deps = adafruit/Adafruit SHTC3 Library@1.0.1 adafruit/Adafruit LPS2X@2.0.6 adafruit/Adafruit SHT31 Library@2.2.2 - adafruit/Adafruit PM25 AQI Sensor@1.1.1 + adafruit/Adafruit PM25 AQI Sensor@1.2.0 adafruit/Adafruit MPU6050@2.2.6 adafruit/Adafruit LIS3DH@1.3.0 adafruit/Adafruit AHTX0@2.0.5 - adafruit/Adafruit LSM6DS@4.7.3 + adafruit/Adafruit LSM6DS@4.7.4 adafruit/Adafruit VEML7700 Library@2.1.6 adafruit/Adafruit SHT4x Library@1.0.5 adafruit/Adafruit TSL2591 Library@1.4.5 sparkfun/SparkFun Qwiic Scale NAU7802 Arduino Library@1.0.6 - sparkfun/SparkFun 9DoF IMU Breakout - ICM 20948 - Arduino Library@1.2.13 + sparkfun/SparkFun 9DoF IMU Breakout - ICM 20948 - Arduino Library@1.3.0 ClosedCube OPT3001@1.1.2 emotibit/EmotiBit MLX90632@1.0.8 adafruit/Adafruit MLX90614 Library@2.1.5 - https://github.com/boschsensortec/Bosch-BSEC2-Library#v1.7.2502 + https://github.com/boschsensortec/Bosch-BSEC2-Library/archive/v1.7.2502.zip boschsensortec/BME68x Sensor Library@1.1.40407 - https://github.com/KodinLanewave/INA3221@1.0.1 + https://github.com/KodinLanewave/INA3221/archive/1.0.1.zip mprograms/QMC5883LCompass@1.2.3 dfrobot/DFRobot_RTU@1.0.3 - https://github.com/meshtastic/DFRobot_LarkWeatherStation#4de3a9cadef0f6a5220a8a906cf9775b02b0040d - https://github.com/DFRobot/DFRobot_RainfallSensor#38fea5e02b40a5430be6dab39a99a6f6347d667e - robtillaart/INA226@0.6.0 + https://github.com/meshtastic/DFRobot_LarkWeatherStation/archive/4de3a9cadef0f6a5220a8a906cf9775b02b0040d.zip + https://github.com/DFRobot/DFRobot_RainfallSensor/archive/38fea5e02b40a5430be6dab39a99a6f6347d667e.zip + robtillaart/INA226@0.6.4 ; Health Sensor Libraries sparkfun/SparkFun MAX3010x Pulse and Proximity Sensor Library@1.1.2 diff --git a/protobufs b/protobufs index 14ec20586..484d002a5 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit 14ec205865592fcfa798065bb001a549fc77b438 +Subproject commit 484d002a52bc20fa9f91ebf1b216d585c5f93a1b diff --git a/src/AudioThread.h b/src/AudioThread.h index 6d560ec55..04ff64a6e 100644 --- a/src/AudioThread.h +++ b/src/AudioThread.h @@ -41,10 +41,8 @@ class AudioThread : public concurrency::OSThread delete i2sRtttl; i2sRtttl = nullptr; } - if (rtttlFile != nullptr) { - delete rtttlFile; - rtttlFile = nullptr; - } + delete rtttlFile; + rtttlFile = nullptr; setCPUFast(false); } diff --git a/src/ButtonThread.cpp b/src/ButtonThread.cpp index ec0bc5fc2..2363f804c 100644 --- a/src/ButtonThread.cpp +++ b/src/ButtonThread.cpp @@ -47,7 +47,7 @@ ButtonThread::ButtonThread() : OSThread("Button") #ifdef USERPREFS_BUTTON_PIN int pin = config.device.button_gpio ? config.device.button_gpio : USERPREFS_BUTTON_PIN; // Resolved button pin #endif -#if defined(HELTEC_CAPSULE_SENSOR_V3) +#if defined(HELTEC_CAPSULE_SENSOR_V3) || defined(HELTEC_SENSOR_HUB) this->userButton = OneButton(pin, false, false); #elif defined(BUTTON_ACTIVE_LOW) this->userButton = OneButton(pin, BUTTON_ACTIVE_LOW, BUTTON_ACTIVE_PULLUP); @@ -73,23 +73,28 @@ ButtonThread::ButtonThread() : OSThread("Button") userButton.setDebounceMs(1); userButton.attachDoubleClick(userButtonDoublePressed); userButton.attachMultiClick(userButtonMultiPressed, this); // Reference to instance: get click count from non-static OneButton -#ifndef T_DECK // T-Deck immediately wakes up after shutdown, so disable this function +#if !defined(T_DECK) && \ + !defined( \ + ELECROW_ThinkNode_M2) // T-Deck immediately wakes up after shutdown, Thinknode M2 has this on the smaller ALT button userButton.attachLongPressStart(userButtonPressedLongStart); userButton.attachLongPressStop(userButtonPressedLongStop); #endif #endif #ifdef BUTTON_PIN_ALT - userButtonAlt = OneButton(BUTTON_PIN_ALT, true, true); +#if defined(ELECROW_ThinkNode_M2) + this->userButtonAlt = OneButton(BUTTON_PIN_ALT, false, false); +#else + this->userButtonAlt = OneButton(BUTTON_PIN_ALT, true, true); +#endif #ifdef INPUT_PULLUP_SENSE // Some platforms (nrf52) have a SENSE variant which allows wake from sleep - override what OneButton did pinMode(BUTTON_PIN_ALT, INPUT_PULLUP_SENSE); #endif - userButtonAlt.attachClick(userButtonPressed); + userButtonAlt.attachClick(userButtonPressedScreen); userButtonAlt.setClickMs(BUTTON_CLICK_MS); userButtonAlt.setPressMs(BUTTON_LONGPRESS_MS); userButtonAlt.setDebounceMs(1); - userButtonAlt.attachDoubleClick(userButtonDoublePressed); userButtonAlt.attachLongPressStart(userButtonPressedLongStart); userButtonAlt.attachLongPressStop(userButtonPressedLongStop); #endif @@ -117,6 +122,40 @@ int32_t ButtonThread::runOnce() canSleep = true; // Assume we should not keep the board awake #if defined(BUTTON_PIN) || defined(USERPREFS_BUTTON_PIN) + // #if defined(ELECROW_ThinkNode_M1) || defined(ELECROW_ThinkNode_M2) + // buzzer_updata(); + // if (buttonPressed) { + // buttonPressed = false; // 清除标志 + // LOG_INFO("PIN_BUTTON2 pressed!"); // 串口打印信息 + // // off_currentTime = millis(); + // while (digitalRead(PIN_BUTTON2) == HIGH) { + // if (cont < 40) { + // // unsigned long currentTime = millis(); // 获取当前时间 + // // if (currentTime - off_currentTime >= 1000) { + // cont++; + // // off_currentTime = currentTime; + // // } + // delay(100); + // } else { + + // currentState = OFF; + // isBuzzing = false; + // cont = 0; + // BEEP_STATE = false; + // analogWrite(M2_buzzer, 0); + // pinMode(M2_buzzer, INPUT); + // screen->setOn(false); + // cont = 0; + // LOG_INFO("GGGGGGGGGGGGGGGGGGGGGGGGG"); + // pinMode(1, OUTPUT); + // digitalWrite(1, LOW); + // pinMode(6, OUTPUT); + // digitalWrite(6, LOW); + // } + // } + // } + + // #endif userButton.tick(); canSleep &= userButton.isIdle(); #elif defined(ARCH_PORTDUINO) @@ -166,6 +205,14 @@ int32_t ButtonThread::runOnce() break; } + case BUTTON_EVENT_PRESSED_SCREEN: { + // turn screen on or off + screen_flag = !screen_flag; + if (screen) + screen->setOn(screen_flag); + break; + } + case BUTTON_EVENT_DOUBLE_PRESSED: { LOG_BUTTON("Double press!"); service->refreshLocalMeshNode(); @@ -192,7 +239,16 @@ int32_t ButtonThread::runOnce() screen->forceDisplay(true); // Force a new UI frame, then force an EInk update } break; +#elif defined(ELECROW_ThinkNode_M2) + case 3: + LOG_INFO("3 clicks: toggle buzzer"); + buzzer_flag = !buzzer_flag; + if (buzzer_flag) { + playBeep(); + } + break; #endif + #if defined(USE_EINK) && defined(PIN_EINK_EN) // i.e. T-Echo // 4 clicks: toggle backlight case 4: diff --git a/src/ButtonThread.h b/src/ButtonThread.h index 54b833d03..a8f1f77c3 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -24,6 +24,7 @@ class ButtonThread : public concurrency::OSThread enum ButtonEventType { BUTTON_EVENT_NONE, BUTTON_EVENT_PRESSED, + BUTTON_EVENT_PRESSED_SCREEN, BUTTON_EVENT_DOUBLE_PRESSED, BUTTON_EVENT_MULTI_PRESSED, BUTTON_EVENT_LONG_PRESSED, @@ -42,7 +43,6 @@ class ButtonThread : public concurrency::OSThread int beforeLightSleep(void *unused); int afterLightSleep(esp_sleep_wakeup_cause_t cause); #endif - private: #if defined(BUTTON_PIN) || defined(ARCH_PORTDUINO) || defined(USERPREFS_BUTTON_PIN) static OneButton userButton; // Static - accessed from an interrupt @@ -64,6 +64,8 @@ class ButtonThread : public concurrency::OSThread // set during IRQ static volatile ButtonEventType btnEvent; + bool buzzer_flag = false; + bool screen_flag = true; // Store click count during callback, for later use volatile int multipressClickCount = 0; @@ -72,6 +74,12 @@ class ButtonThread : public concurrency::OSThread // IRQ callbacks static void userButtonPressed() { btnEvent = BUTTON_EVENT_PRESSED; } + static void userButtonPressedScreen() + { + if (millis() > c_holdOffTime) { + btnEvent = BUTTON_EVENT_PRESSED_SCREEN; + } + } static void userButtonDoublePressed() { btnEvent = BUTTON_EVENT_DOUBLE_PRESSED; } static void userButtonMultiPressed(void *callerThread); // Retrieve click count from non-static Onebutton while still valid static void userButtonPressedLongStart(); diff --git a/src/FSCommon.cpp b/src/FSCommon.cpp index 31fe69c93..88f0764b5 100644 --- a/src/FSCommon.cpp +++ b/src/FSCommon.cpp @@ -29,30 +29,6 @@ SPIClass SPI1(HSPI); #endif // HAS_SDCARD -#if defined(ARCH_STM32WL) - -uint16_t OSFS::startOfEEPROM = 1; -uint16_t OSFS::endOfEEPROM = 2048; - -// 3) How do I read from the medium? -void OSFS::readNBytes(uint16_t address, unsigned int num, byte *output) -{ - for (uint16_t i = address; i < address + num; i++) { - *output = EEPROM.read(i); - output++; - } -} - -// 4) How to I write to the medium? -void OSFS::writeNBytes(uint16_t address, unsigned int num, const byte *input) -{ - for (uint16_t i = address; i < address + num; i++) { - EEPROM.update(i, *input); - input++; - } -} -#endif - /** * @brief Copies a file from one location to another. * @@ -62,33 +38,7 @@ void OSFS::writeNBytes(uint16_t address, unsigned int num, const byte *input) */ bool copyFile(const char *from, const char *to) { -#ifdef ARCH_STM32WL - unsigned char cbuffer[2048]; - - // Var to hold the result of actions - OSFS::result r; - - r = OSFS::getFile(from, cbuffer); - - if (r == notfound) { - LOG_ERROR("Failed to open source file %s", from); - return false; - } else if (r == noerr) { - r = OSFS::newFile(to, cbuffer, true); - if (r == noerr) { - return true; - } else { - LOG_ERROR("OSFS Error %d", r); - return false; - } - - } else { - LOG_ERROR("OSFS Error %d", r); - return false; - } - return true; - -#elif defined(FSCom) +#ifdef FSCom // take SPI Lock concurrency::LockGuard g(spiLock); unsigned char cbuffer[16]; @@ -127,13 +77,7 @@ bool copyFile(const char *from, const char *to) */ bool renameFile(const char *pathFrom, const char *pathTo) { -#ifdef ARCH_STM32WL - if (copyFile(pathFrom, pathTo) && (OSFS::deleteFile(pathFrom) == OSFS::result::NO_ERROR)) { - return true; - } else { - return false; - } -#elif defined(FSCom) +#ifdef FSCom #ifdef ARCH_ESP32 // take SPI Lock diff --git a/src/FSCommon.h b/src/FSCommon.h index 10ce4aeec..fdc0b76ec 100644 --- a/src/FSCommon.h +++ b/src/FSCommon.h @@ -15,13 +15,11 @@ #endif #if defined(ARCH_STM32WL) -// STM32WL series 2 Kbytes (8 rows of 256 bytes) -#include -#include - -// Useful consts -const OSFS::result noerr = OSFS::result::NO_ERROR; -const OSFS::result notfound = OSFS::result::FILE_NOT_FOUND; +// STM32WL +#include "LittleFS.h" +#define FSCom InternalFS +#define FSBegin() FSCom.begin() +using namespace STM32_LittleFS_Namespace; #endif #if defined(ARCH_RP2040) diff --git a/src/Power.cpp b/src/Power.cpp index 5768e9908..0dec0fc21 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -391,7 +391,7 @@ class AnalogBatteryLevel : public HasBatteryLevel virtual bool isVbusIn() override { #ifdef EXT_PWR_DETECT -#ifdef HELTEC_CAPSULE_SENSOR_V3 +#if defined(HELTEC_CAPSULE_SENSOR_V3) || defined(HELTEC_SENSOR_HUB) // if external powered that pin will be pulled down if (digitalRead(EXT_PWR_DETECT) == LOW) { return true; @@ -533,6 +533,9 @@ Power::Power() : OSThread("Power") { statusHandler = {}; low_voltage_counter = 0; +#if defined(ELECROW_ThinkNode_M1) || defined(POWER_CFG) + low_voltage_counter_led3 = 0; +#endif #ifdef DEBUG_HEAP lastheap = memGet.getFreeHeap(); #endif @@ -541,7 +544,7 @@ Power::Power() : OSThread("Power") bool Power::analogInit() { #ifdef EXT_PWR_DETECT -#ifdef HELTEC_CAPSULE_SENSOR_V3 +#if defined(HELTEC_CAPSULE_SENSOR_V3) || defined(HELTEC_SENSOR_HUB) pinMode(EXT_PWR_DETECT, INPUT_PULLUP); #else pinMode(EXT_PWR_DETECT, INPUT); @@ -668,12 +671,12 @@ void Power::readPowerStatus() int8_t batteryChargePercent = -1; OptionalBool usbPowered = OptUnknown; OptionalBool hasBattery = OptUnknown; // These must be static because NRF_APM code doesn't run every time - OptionalBool isCharging = OptUnknown; + OptionalBool isChargingNow = OptUnknown; if (batteryLevel) { hasBattery = batteryLevel->isBatteryConnect() ? OptTrue : OptFalse; usbPowered = batteryLevel->isVbusIn() ? OptTrue : OptFalse; - isCharging = batteryLevel->isCharging() ? OptTrue : OptFalse; + isChargingNow = batteryLevel->isCharging() ? OptTrue : OptFalse; if (hasBattery) { batteryVoltageMv = batteryLevel->getBattVoltage(); // If the AXP192 returns a valid battery percentage, use it @@ -702,17 +705,20 @@ void Power::readPowerStatus() // If changed to DISCONNECTED if (nrf_usb_state == NRFX_POWER_USB_STATE_DISCONNECTED) - isCharging = usbPowered = OptFalse; + isChargingNow = usbPowered = OptFalse; // If changed to CONNECTED / READY else - isCharging = usbPowered = OptTrue; + isChargingNow = usbPowered = OptTrue; #endif // Notify any status instances that are observing us - const PowerStatus powerStatus2 = PowerStatus(hasBattery, usbPowered, isCharging, batteryVoltageMv, batteryChargePercent); + const PowerStatus powerStatus2 = PowerStatus(hasBattery, usbPowered, isChargingNow, batteryVoltageMv, batteryChargePercent); LOG_DEBUG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d", powerStatus2.getHasUSB(), powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); +#if defined(ELECROW_ThinkNode_M1) || defined(POWER_CFG) + power_num = powerStatus2.getBatteryVoltageMv(); +#endif newStatus.notifyObservers(&powerStatus2); #ifdef DEBUG_HEAP if (lastheap != memGet.getFreeHeap()) { @@ -756,9 +762,13 @@ void Power::readPowerStatus() // If we have a battery at all and it is less than 0%, force deep sleep if we have more than 10 low readings in // a row. NOTE: min LiIon/LiPo voltage is 2.0 to 2.5V, current OCV min is set to 3100 that is large enough. // + if (batteryLevel && powerStatus2.getHasBattery() && !powerStatus2.getHasUSB()) { if (batteryLevel->getBattVoltage() < OCV[NUM_OCV_POINTS - 1]) { low_voltage_counter++; +#if defined(ELECROW_ThinkNode_M1) + low_voltage_counter_led3 = low_voltage_counter; +#endif LOG_DEBUG("Low voltage counter: %d/10", low_voltage_counter); if (low_voltage_counter > 10) { #ifdef ARCH_NRF52 @@ -771,7 +781,13 @@ void Power::readPowerStatus() } } else { low_voltage_counter = 0; +#if defined(ELECROW_ThinkNode_M1) + low_voltage_counter_led3 = low_voltage_counter; +#endif } +#ifdef POWER_CFG + low_voltage_counter_led3 = low_voltage_counter; +#endif } } diff --git a/src/buzz/buzz.cpp b/src/buzz/buzz.cpp index 8db9602bc..6ba2f4140 100644 --- a/src/buzz/buzz.cpp +++ b/src/buzz/buzz.cpp @@ -30,8 +30,11 @@ struct ToneDuration { #define NOTE_B3 247 #define NOTE_CS4 277 -const int DURATION_1_8 = 125; // 1/8 note -const int DURATION_1_4 = 250; // 1/4 note +const int DURATION_1_8 = 125; // 1/8 note +const int DURATION_1_4 = 250; // 1/4 note +const int DURATION_1_2 = 500; // 1/2 note +const int DURATION_3_4 = 750; // 1/4 note +const int DURATION_1_1 = 1000; // 1/1 note void playTones(const ToneDuration *tone_durations, int size) { @@ -55,6 +58,12 @@ void playBeep() playTones(melody, sizeof(melody) / sizeof(ToneDuration)); } +void playLongBeep() +{ + ToneDuration melody[] = {{NOTE_B3, DURATION_1_1}}; + playTones(melody, sizeof(melody) / sizeof(ToneDuration)); +} + void playGPSEnableBeep() { ToneDuration melody[] = {{NOTE_C3, DURATION_1_8}, {NOTE_FS3, DURATION_1_4}, {NOTE_CS4, DURATION_1_4}}; diff --git a/src/buzz/buzz.h b/src/buzz/buzz.h index c52c3020c..adeaca73d 100644 --- a/src/buzz/buzz.h +++ b/src/buzz/buzz.h @@ -1,6 +1,7 @@ #pragma once void playBeep(); +void playLongBeep(); void playStartMelody(); void playShutdownMelody(); void playGPSEnableBeep(); diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 7f490ea3c..41a2ff980 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -981,15 +981,16 @@ void GPS::down() setPowerState(GPS_IDLE); else { - // Check whether the GPS hardware is capable of GPS_SOFTSLEEP - // If not, fallback to GPS_HARDSLEEP instead +// Check whether the GPS hardware is capable of GPS_SOFTSLEEP +// If not, fallback to GPS_HARDSLEEP instead +#ifdef PIN_GPS_STANDBY // L76B, L76K and clones have a standby pin + bool softsleepSupported = true; +#else bool softsleepSupported = false; +#endif // U-blox is supported via PMREQ if (IS_ONE_OF(gnssModel, GNSS_MODEL_UBLOX6, GNSS_MODEL_UBLOX7, GNSS_MODEL_UBLOX8, GNSS_MODEL_UBLOX9, GNSS_MODEL_UBLOX10)) softsleepSupported = true; -#ifdef PIN_GPS_STANDBY // L76B, L76K and clones have a standby pin - softsleepSupported = true; -#endif if (softsleepSupported) { // How long does gps_update_interval need to be, for GPS_HARDSLEEP to become more efficient than @@ -1200,12 +1201,12 @@ GnssModel_t GPS::probe(int serialSpeed) PROBE_SIMPLE("LC86", "$PQTMVERNO*58", "$PQTMVERNO,LC86", GNSS_MODEL_AG3352, 500); PROBE_SIMPLE("L76K", "$PCAS06,0*1B", "$GPTXT,01,01,02,SW=", GNSS_MODEL_MTK, 500); - // Close all NMEA sentences, valid for L76B MTK platform (Waveshare Pico GPS) + // Close all NMEA sentences, valid for MTK3333 and MTK3339 platforms _serial_gps->write("$PMTK514,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*2E\r\n"); delay(20); std::vector mtk = {{"L76B", "Quectel-L76B", GNSS_MODEL_MTK_L76B}, {"PA1616S", "1616S", GNSS_MODEL_MTK_PA1616S}, - {"LS20031", "MC-1513", GNSS_MODEL_LS20031}}; + {"LS20031", "MC-1513", GNSS_MODEL_MTK_L76B}}; PROBE_FAMILY("MTK Family", "$PMTK605*31", mtk, 500); uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00}; diff --git a/src/graphics/EInkDisplay2.cpp b/src/graphics/EInkDisplay2.cpp index a640e3560..96c6b44c1 100644 --- a/src/graphics/EInkDisplay2.cpp +++ b/src/graphics/EInkDisplay2.cpp @@ -128,16 +128,24 @@ bool EInkDisplay::connect() #ifdef PIN_EINK_EN // backlight power, HIGH is backlight on, LOW is off pinMode(PIN_EINK_EN, OUTPUT); +#ifdef ELECROW_ThinkNode_M1 digitalWrite(PIN_EINK_EN, LOW); +#else + digitalWrite(PIN_EINK_EN, HIGH); +#endif #endif -#if defined(TTGO_T_ECHO) +#if defined(TTGO_T_ECHO) || defined(ELECROW_ThinkNode_M1) { auto lowLevel = new EINK_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY, SPI1); adafruitDisplay = new GxEPD2_BW(*lowLevel); adafruitDisplay->init(); +#ifdef ELECROW_ThinkNode_M1 + adafruitDisplay->setRotation(4); +#else adafruitDisplay->setRotation(3); +#endif adafruitDisplay->setPartialWindow(0, 0, displayWidth, displayHeight); } #elif defined(MESHLINK) @@ -166,7 +174,8 @@ bool EInkDisplay::connect() } #elif defined(HELTEC_WIRELESS_PAPER_V1_0) || defined(HELTEC_WIRELESS_PAPER) || defined(HELTEC_VISION_MASTER_E213) || \ - defined(HELTEC_VISION_MASTER_E290) || defined(TLORA_T3S3_EPAPER) || defined(CROWPANEL_ESP32S3_5_EPAPER) + defined(HELTEC_VISION_MASTER_E290) || defined(TLORA_T3S3_EPAPER) || defined(CROWPANEL_ESP32S3_5_EPAPER) || \ + defined(CROWPANEL_ESP32S3_4_EPAPER) || defined(CROWPANEL_ESP32S3_2_EPAPER) { // Start HSPI hspi = new SPIClass(HSPI); @@ -182,7 +191,7 @@ bool EInkDisplay::connect() // Init GxEPD2 adafruitDisplay->init(); adafruitDisplay->setRotation(3); -#if defined(CROWPANEL_ESP32S3_5_EPAPER) +#if defined(CROWPANEL_ESP32S3_5_EPAPER) || defined(CROWPANEL_ESP32S3_4_EPAPER) adafruitDisplay->setRotation(0); #endif } diff --git a/src/graphics/EInkDisplay2.h b/src/graphics/EInkDisplay2.h index efbf45f0f..9c1c8d18e 100644 --- a/src/graphics/EInkDisplay2.h +++ b/src/graphics/EInkDisplay2.h @@ -68,7 +68,8 @@ class EInkDisplay : public OLEDDisplay // If display uses HSPI #if defined(HELTEC_WIRELESS_PAPER) || defined(HELTEC_WIRELESS_PAPER_V1_0) || defined(HELTEC_VISION_MASTER_E213) || \ - defined(HELTEC_VISION_MASTER_E290) || defined(TLORA_T3S3_EPAPER) || defined(CROWPANEL_ESP32S3_5_EPAPER) + defined(HELTEC_VISION_MASTER_E290) || defined(TLORA_T3S3_EPAPER) || defined(CROWPANEL_ESP32S3_5_EPAPER) || \ + defined(CROWPANEL_ESP32S3_4_EPAPER) || defined(CROWPANEL_ESP32S3_2_EPAPER) SPIClass *hspi = NULL; #endif diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index 0c18f3287..e27495f54 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -1641,6 +1641,11 @@ void Screen::handleSetOn(bool on, FrameCallback einkScreensaver) setScreensaverFrames(einkScreensaver); #endif LOG_INFO("Turn off screen"); +#ifdef ELECROW_ThinkNode_M1 + if (digitalRead(PIN_EINK_EN) == HIGH) { + digitalWrite(PIN_EINK_EN, LOW); + } +#endif dispdev->displayOff(); #ifdef USE_ST7789 SPI1.end(); @@ -2664,14 +2669,19 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // minutes %= 60; // hours %= 24; + // Show uptime as days, hours, minutes OR seconds + std::string uptime = screen->drawTimeDelta(days, hours, minutes, seconds); + + // Line 1 (Still) + display->drawString(x + SCREEN_WIDTH - display->getStringWidth(uptime.c_str()), y, uptime.c_str()); + if (config.display.heading_bold) + display->drawString(x - 1 + SCREEN_WIDTH - display->getStringWidth(uptime.c_str()), y, uptime.c_str()); + display->setColor(WHITE); // Setup string to assemble analogClock string std::string analogClock = ""; - // Show uptime as days, hours, minutes OR seconds - std::string uptime = screen->drawTimeDelta(days, hours, minutes, seconds); - uint32_t rtc_sec = getValidTime(RTCQuality::RTCQualityDevice, true); // Display local timezone if (rtc_sec > 0) { long hms = rtc_sec % SEC_PER_DAY; @@ -2704,9 +2714,6 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat analogClock += timebuf; } - // Line 1 - display->drawString(x + SCREEN_WIDTH - display->getStringWidth(uptime.c_str()), y, uptime.c_str()); - // Line 2 display->drawString(x, y + FONT_HEIGHT_SMALL * 1, analogClock.c_str()); @@ -2728,7 +2735,7 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat drawGPSpowerstat(display, x, y + FONT_HEIGHT_SMALL * 2, gpsStatus); } #endif - /* Display a heartbeat pixel that blinks every time the frame is redrawn */ +/* Display a heartbeat pixel that blinks every time the frame is redrawn */ #ifdef SHOW_REDRAWS if (heartbeat) display->setPixel(0, 0); diff --git a/src/graphics/ScreenFonts.h b/src/graphics/ScreenFonts.h index 910d1b0b9..079a3e282 100644 --- a/src/graphics/ScreenFonts.h +++ b/src/graphics/ScreenFonts.h @@ -16,6 +16,10 @@ #include "graphics/fonts/OLEDDisplayFontsCS.h" #endif +#ifdef CROWPANEL_ESP32S3_5_EPAPER +#include "graphics/fonts/EinkDisplayFonts.h" +#endif + #ifdef OLED_PL #define FONT_SMALL_LOCAL ArialMT_Plain_10_PL #else @@ -74,13 +78,12 @@ #endif #if defined(CROWPANEL_ESP32S3_5_EPAPER) -#include "graphics/fonts/EinkDisplayFonts.h" #undef FONT_SMALL #undef FONT_MEDIUM #undef FONT_LARGE -#define FONT_SMALL FONT_LARGE_LOCAL // Height: 30 -#define FONT_MEDIUM FONT_LARGE_LOCAL // Height: 30 -#define FONT_LARGE FONT_LARGE_LOCAL // Height: 30 +#define FONT_SMALL Monospaced_plain_30 +#define FONT_MEDIUM Monospaced_plain_30 +#define FONT_LARGE Monospaced_plain_30 #endif #define _fontHeight(font) ((font)[1] + 1) // height is position 1 diff --git a/src/graphics/niche/Drivers/EInk/EInk.cpp b/src/graphics/niche/Drivers/EInk/EInk.cpp index 043788b13..cd2e9dc98 100644 --- a/src/graphics/niche/Drivers/EInk/EInk.cpp +++ b/src/graphics/niche/Drivers/EInk/EInk.cpp @@ -6,7 +6,7 @@ using namespace NicheGraphics::Drivers; // Separate from EInk::begin method, as derived class constructors can probably supply these parameters as constants EInk::EInk(uint16_t width, uint16_t height, UpdateTypes supported) - : concurrency::OSThread("E-Ink Driver"), width(width), height(height), supportedUpdateTypes(supported) + : concurrency::OSThread("EInkDriver"), width(width), height(height), supportedUpdateTypes(supported) { OSThread::disable(); } @@ -31,8 +31,8 @@ bool EInk::supports(UpdateTypes type) void EInk::beginPolling(uint32_t interval, uint32_t expectedDuration) { updateRunning = true; - updateBegunAt = millis(); pollingInterval = interval; + pollingBegunAt = millis(); // To minimize load, we can choose to delay polling for a few seconds, if we know roughly how long the update will take // By default, expectedDuration is 0, and we'll start polling immediately @@ -45,10 +45,26 @@ void EInk::beginPolling(uint32_t interval, uint32_t expectedDuration) // This is what allows us to update the display asynchronously int32_t EInk::runOnce() { + // Check for polling timeout + // Manually set at 10 seconds, in case some big task holds up the firmware's cooperative multitasking + if (millis() - pollingBegunAt > 10000) + failed = true; + + // Handle failure + // - polling timeout + // - other error (derived classes) + if (failed) { + LOG_WARN("Display update failed. Check wiring & power supply."); + updateRunning = false; + failed = false; + return disable(); + } + + // If update not yet done if (!isUpdateDone()) return pollingInterval; // Poll again in a few ms - // If update done: + // If update done finalizeUpdate(); // Any post-update code: power down panel hardware, hibernate, etc updateRunning = false; // Change what we report via EInk::busy() return disable(); // Stop polling diff --git a/src/graphics/niche/Drivers/EInk/EInk.h b/src/graphics/niche/Drivers/EInk/EInk.h index facb8ce72..3c51d4f1d 100644 --- a/src/graphics/niche/Drivers/EInk/EInk.h +++ b/src/graphics/niche/Drivers/EInk/EInk.h @@ -24,7 +24,7 @@ class EInk : private concurrency::OSThread enum UpdateTypes : uint8_t { UNSPECIFIED = 0, FULL = 1 << 0, - FAST = 1 << 1, + FAST = 1 << 1, // "Partial Refresh" }; EInk(uint16_t width, uint16_t height, UpdateTypes supported); @@ -41,14 +41,15 @@ class EInk : private concurrency::OSThread void beginPolling(uint32_t interval, uint32_t expectedDuration); // Begin checking repeatedly if update finished virtual bool isUpdateDone() = 0; // Check once if update finished virtual void finalizeUpdate() {} // Run any post-update code + bool failed = false; // If an error occurred during update private: int32_t runOnce() override; // Repeated checking if update finished const UpdateTypes supportedUpdateTypes; // Capabilities of a derived display class bool updateRunning = false; // see EInk::busy() - uint32_t updateBegunAt = 0; // For initial pause before polling for update completion uint32_t pollingInterval = 0; // How often to check if update complete (ms) + uint32_t pollingBegunAt = 0; // To timeout during polling }; } // namespace NicheGraphics::Drivers diff --git a/src/graphics/niche/Drivers/EInk/HINK_E042A87.cpp b/src/graphics/niche/Drivers/EInk/HINK_E042A87.cpp new file mode 100644 index 000000000..1b72bc4a9 --- /dev/null +++ b/src/graphics/niche/Drivers/EInk/HINK_E042A87.cpp @@ -0,0 +1,58 @@ +#include "./HINK_E042A87.h" + +#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS + +using namespace NicheGraphics::Drivers; + +// Load settings about how the pixels are moved from old state to new state during a refresh +// - manually specified, +// - or with stored values from displays OTP memory +void HINK_E042A87::configWaveform() +{ + sendCommand(0x3C); // Border waveform: + sendData(0x01); // Follow LUT for VSH1 + + sendCommand(0x18); // Temperature sensor: + sendData(0x80); // Use internal temperature sensor to select an appropriate refresh waveform +} + +// Describes the sequence of events performed by the displays controller IC during a refresh +// Includes "power up", "load settings from memory", "update the pixels", etc +void HINK_E042A87::configUpdateSequence() +{ + switch (updateType) { + case FAST: + sendCommand(0x21); // Use both "old" and "new" image memory (differential) + sendData(0x00); + sendData(0x00); + + sendCommand(0x22); // Set "update sequence" + sendData(0xFF); // Differential, load waveform from OTP + break; + + case FULL: + default: + sendCommand(0x21); // Bypass "old" image memory (non-differential) + sendData(0x40); + sendData(0x00); + + sendCommand(0x22); // Set "update sequence": + sendData(0xF7); // Non-differential, load waveform from OTP + break; + } +} + +// Once the refresh operation has been started, +// begin periodically polling the display to check for completion, using the normal Meshtastic threading code +// Only used when refresh is "async" +void HINK_E042A87::detachFromUpdate() +{ + switch (updateType) { + case FAST: + return beginPolling(50, 1000); // At least 1 second, then check every 50ms + case FULL: + default: + return beginPolling(100, 3500); // At least 3.5 seconds, then check every 100ms + } +} +#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS \ No newline at end of file diff --git a/src/graphics/niche/Drivers/EInk/HINK_E042A87.h b/src/graphics/niche/Drivers/EInk/HINK_E042A87.h new file mode 100644 index 000000000..ac03b65ef --- /dev/null +++ b/src/graphics/niche/Drivers/EInk/HINK_E042A87.h @@ -0,0 +1,43 @@ +/* + +E-Ink display driver + - HINK-E042A87 + - Manufacturer: Holitech + - Size: 4.2 inch + - Resolution: 400px x 300px + - Flex connector marking: HINK-E042A07-FPC-A1 + - Silver sticker with QR code, marked: HE042A87 + + Note: as of Feb. 2025, these panels are used for "WeActStudio 4.2in B&W" display modules + +*/ + +#pragma once + +#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS + +#include "configuration.h" + +#include "./SSD16XX.h" + +namespace NicheGraphics::Drivers +{ +class HINK_E042A87 : public SSD16XX +{ + // Display properties + private: + static constexpr uint32_t width = 400; + static constexpr uint32_t height = 300; + static constexpr UpdateTypes supported = (UpdateTypes)(FULL | FAST); + + public: + HINK_E042A87() : SSD16XX(width, height, supported) {} + + protected: + void configWaveform() override; + void configUpdateSequence() override; + void detachFromUpdate() override; +}; + +} // namespace NicheGraphics::Drivers +#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS \ No newline at end of file diff --git a/src/graphics/niche/Drivers/EInk/README.md b/src/graphics/niche/Drivers/EInk/README.md index 04a23a31f..eca91c6a8 100644 --- a/src/graphics/niche/Drivers/EInk/README.md +++ b/src/graphics/niche/Drivers/EInk/README.md @@ -28,6 +28,17 @@ void setupNicheGraphics() } ``` +- [Methods](#methods) + - [`update(uint8_t *imageData, UpdateTypes type)`](#updateuint8_t-imagedata-updatetypes-type) + - [`await()`](#await) + - [`supports(UpdateTypes type)`](#supportsupdatetypes-type) + - [`busy()`](#busy) + - [`width()`](#width) + - [`height()`](#height) +- [Supporting New Displays](#supporting-new-displays) + - [Controller IC](#controller-ic) + - [Finding Information](#finding-information) + ## Methods ### `update(uint8_t *imageData, UpdateTypes type)` @@ -37,7 +48,7 @@ Update the image on the display - _`imageData`_ to draw to the display. - _`type`_ which type of update to perform. - `FULL` - - `FAST` + - `FAST` (partial refresh) - (Other custom types may be possible) The imageData is a 1-bit image. X-Pixels are 8-per byte, with the MSB being the leftmost pixel. This was not an InkHUD design decision; it is the raw format accepted by the E-Ink display controllers ICs. @@ -83,3 +94,39 @@ Width of the display, in pixels. Note: most displays are portrait. Your UI will ### `height()` Height of the display, in pixels. Note: most displays are portrait. Your UI will need to implement rotation in software. + +## Supporting New Displays + +_This topic is not covered in depth, but these notes may be helpful._ + +The `InkHUD::Drivers::EInk` class contains only the mechanism for implementing an E-Ink driver on-top of Meshtastic's `OSThread`. A driver for a specific display needs to extend this class. + +### Controller IC + +If your display uses a controller IC from Solomon Systech, you can probably extend the existing `Drivers::SSD16XX` class, making only minor modifications. + +At this stage, displays using controller ICS from other manufacturers (UltraChip, Fitipower, etc) need to manually implemented. See `Drivers::LCMEN2R13EFC1` for an example. + +Generic base classes for manufacturers other than Solomon Systech might be added here in future. + +### Finding Information + +#### Flex-Connector Labels + +The orange flex-connector attached to E-Ink displays is often printed with an identifying label. This is not a _totally_ unique identifier, but does give a very strong clue as to the true model of the display, which can be used to search out further information. + +#### Datasheets + +The manufacturer of a DIY display module may publish a datasheet. These are often incomplete, but might reveal the true model of the display, or the controller IC. + +If you can determine the true model name of the display, you can likely find a more complete datasheet on the display manufacturer's website. This will often provide a "typical operating sequence"; a general overview of the code used to drive the display + +#### Example Code + +The manufacturer of a DIY module may publish example code. You may have more luck finding example code published by the display manufacturer themselves, if you can determine the true model of the panel. These examples are a very valuable reference. + +#### Other E-Ink drivers + +Libraries like ZinggJM's GxEPD2 can be valuable sources of information, although your panel may not be _specifically_ supported, and only _compatible_ with a driver there, so some caution is advised. + +The display selection file in GxEPD2's Hello World example is also a useful resource for matching "flex connector labels" with display models, but the flex connector label is _not_ a unique identifier, so this is only another clue. diff --git a/src/graphics/niche/Drivers/EInk/SSD16XX.cpp b/src/graphics/niche/Drivers/EInk/SSD16XX.cpp index 07d02a2ae..5a5397dbd 100644 --- a/src/graphics/niche/Drivers/EInk/SSD16XX.cpp +++ b/src/graphics/niche/Drivers/EInk/SSD16XX.cpp @@ -37,11 +37,26 @@ void SSD16XX::begin(SPIClass *spi, uint8_t pin_dc, uint8_t pin_cs, uint8_t pin_b reset(); } -void SSD16XX::wait() +// Poll the displays busy pin until an operation is complete +// Timeout and set fail flag if something went wrong and the display got stuck +void SSD16XX::wait(uint32_t timeout) { + // Don't bother waiting if part of the update sequence failed + // In that situation, we're now just failing-through the process, until we can try again with next update. + if (failed) + return; + + uint32_t startMs = millis(); + // Busy when HIGH - while (digitalRead(pin_busy) == HIGH) + while (digitalRead(pin_busy) == HIGH) { + // Check for timeout + if (millis() - startMs > timeout) { + failed = true; + break; + } yield(); + } } void SSD16XX::reset() @@ -50,8 +65,9 @@ void SSD16XX::reset() if (pin_rst != 0xFF) { pinMode(pin_rst, OUTPUT); digitalWrite(pin_rst, LOW); - delay(50); - pinMode(pin_rst, INPUT_PULLUP); + delay(10); + digitalWrite(pin_rst, HIGH); + delay(10); wait(); } @@ -61,6 +77,11 @@ void SSD16XX::reset() void SSD16XX::sendCommand(const uint8_t command) { + // Abort if part of the update sequence failed + // This will unlock again once we have failed-through the entire process + if (failed) + return; + spi->beginTransaction(spiSettings); digitalWrite(pin_dc, LOW); // DC pin low indicates command digitalWrite(pin_cs, LOW); @@ -77,6 +98,11 @@ void SSD16XX::sendData(uint8_t data) void SSD16XX::sendData(const uint8_t *data, uint32_t size) { + // Abort if part of the update sequence failed + // This will unlock again once we have failed-through the entire process + if (failed) + return; + spi->beginTransaction(spiSettings); digitalWrite(pin_dc, HIGH); // DC pin HIGH indicates data, instead of command digitalWrite(pin_cs, LOW); diff --git a/src/graphics/niche/Drivers/EInk/SSD16XX.h b/src/graphics/niche/Drivers/EInk/SSD16XX.h index 88fe4dc25..799a378c0 100644 --- a/src/graphics/niche/Drivers/EInk/SSD16XX.h +++ b/src/graphics/niche/Drivers/EInk/SSD16XX.h @@ -27,7 +27,7 @@ class SSD16XX : public EInk virtual void update(uint8_t *imageData, UpdateTypes type) override; protected: - virtual void wait(); + virtual void wait(uint32_t timeout = 1000); virtual void reset(); virtual void sendCommand(const uint8_t command); virtual void sendData(const uint8_t data); diff --git a/src/graphics/niche/InkHUD/Applet.cpp b/src/graphics/niche/InkHUD/Applet.cpp index 9fda9a87e..6c6245ec3 100644 --- a/src/graphics/niche/InkHUD/Applet.cpp +++ b/src/graphics/niche/InkHUD/Applet.cpp @@ -582,9 +582,12 @@ std::string InkHUD::Applet::getTimeString(uint32_t epochSeconds) uint32_t hour = hms / SEC_PER_HOUR; uint32_t min = (hms % SEC_PER_HOUR) / SEC_PER_MIN; - // Format the clock string + // Format the clock string, either 12 hour or 24 hour char clockStr[11]; - sprintf(clockStr, "%u:%02u %s", (hour % 12 == 0 ? 12 : hour % 12), min, hour > 11 ? "PM" : "AM"); + if (config.display.use_12h_clock) + sprintf(clockStr, "%u:%02u %s", (hour % 12 == 0 ? 12 : hour % 12), min, hour > 11 ? "PM" : "AM"); + else + sprintf(clockStr, "%02u:%02u", hour, min); return clockStr; } @@ -799,7 +802,7 @@ uint16_t InkHUD::Applet::getLogoHeight(uint16_t limitWidth, uint16_t limitHeight // // \\ */ -void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height) +void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height, Color color) { struct Point { int x; @@ -905,24 +908,24 @@ void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width, Point aq2{a2.x - fromPath.x, a2.y - fromPath.y}; Point aq3{a2.x + fromPath.x, a2.y + fromPath.y}; Point aq4{a1.x + fromPath.x, a1.y + fromPath.y}; - fillTriangle(aq1.x, aq1.y, aq2.x, aq2.y, aq3.x, aq3.y, BLACK); - fillTriangle(aq1.x, aq1.y, aq3.x, aq3.y, aq4.x, aq4.y, BLACK); + fillTriangle(aq1.x, aq1.y, aq2.x, aq2.y, aq3.x, aq3.y, color); + fillTriangle(aq1.x, aq1.y, aq3.x, aq3.y, aq4.x, aq4.y, color); // Make the path thick: path b becomes quad b Point bq1{b1.x - fromPath.x, b1.y - fromPath.y}; Point bq2{b2.x - fromPath.x, b2.y - fromPath.y}; Point bq3{b2.x + fromPath.x, b2.y + fromPath.y}; Point bq4{b1.x + fromPath.x, b1.y + fromPath.y}; - fillTriangle(bq1.x, bq1.y, bq2.x, bq2.y, bq3.x, bq3.y, BLACK); - fillTriangle(bq1.x, bq1.y, bq3.x, bq3.y, bq4.x, bq4.y, BLACK); + fillTriangle(bq1.x, bq1.y, bq2.x, bq2.y, bq3.x, bq3.y, color); + fillTriangle(bq1.x, bq1.y, bq3.x, bq3.y, bq4.x, bq4.y, color); // Make the path thick: path c becomes quad c Point cq1{c1.x - fromPath.x, c1.y + fromPath.y}; Point cq2{c2.x - fromPath.x, c2.y + fromPath.y}; Point cq3{c2.x + fromPath.x, c2.y - fromPath.y}; Point cq4{c1.x + fromPath.x, c1.y - fromPath.y}; - fillTriangle(cq1.x, cq1.y, cq2.x, cq2.y, cq3.x, cq3.y, BLACK); - fillTriangle(cq1.x, cq1.y, cq3.x, cq3.y, cq4.x, cq4.y, BLACK); + fillTriangle(cq1.x, cq1.y, cq2.x, cq2.y, cq3.x, cq3.y, color); + fillTriangle(cq1.x, cq1.y, cq3.x, cq3.y, cq4.x, cq4.y, color); // Radius the intersection of quad b and quad c /* @@ -941,7 +944,7 @@ void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width, // The radius for the cap *should* be the same as logoTh, but it's not, due to accumulated rounding // We get better results just re-deriving it int16_t capRad = sqrt(pow(fromPath.x, 2) + pow(fromPath.y, 2)); - fillCircle(b2.x, b2.y, capRad, BLACK); + fillCircle(b2.x, b2.y, capRad, color); } } diff --git a/src/graphics/niche/InkHUD/Applet.h b/src/graphics/niche/InkHUD/Applet.h index 028b24f9c..8f4466647 100644 --- a/src/graphics/niche/InkHUD/Applet.h +++ b/src/graphics/niche/InkHUD/Applet.h @@ -130,7 +130,8 @@ class Applet : public GFX static constexpr float LOGO_ASPECT_RATIO = 1.9; // Width:Height for drawing the Meshtastic logo uint16_t getLogoWidth(uint16_t limitWidth, uint16_t limitHeight); // Size Meshtastic logo to fit within region uint16_t getLogoHeight(uint16_t limitWidth, uint16_t limitHeight); // Size Meshtastic logo to fit within region - void drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height); // Draw the meshtastic logo + void drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height, + Color color = BLACK); // Draw the Meshtastic logo std::string hexifyNodeNum(NodeNum num); // Style as !0123abdc SignalStrength getSignalStrength(float snr, float rssi); // Interpret SNR and RSSI, as an easy to understand value diff --git a/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp b/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp index 17458ab96..b12ea4809 100644 --- a/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp +++ b/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp @@ -8,7 +8,7 @@ using namespace NicheGraphics; // Our basic example doesn't do anything useful. It just passively prints some text. void InkHUD::BasicExampleApplet::onRender() { - print("Hello, World!"); + printAt(0, 0, "Hello, World!"); } #endif \ No newline at end of file diff --git a/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp b/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp index e31f534ac..6b02f4c92 100644 --- a/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp +++ b/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp @@ -4,11 +4,12 @@ using namespace NicheGraphics; -// We configured MeshModule API to call this method when we receive a new text message +// We configured the Module API to call this method when we receive a new text message ProcessMessage InkHUD::NewMsgExampleApplet::handleReceived(const meshtastic_MeshPacket &mp) { // Abort if applet fully deactivated + // Don't waste time: we wouldn't be rendered anyway if (!isActive()) return ProcessMessage::CONTINUE; @@ -25,7 +26,7 @@ ProcessMessage InkHUD::NewMsgExampleApplet::handleReceived(const meshtastic_Mesh requestUpdate(); } - // Tell MeshModule API to continue informing other firmware components about this message + // Tell Module API to continue informing other firmware components about this message // We're not the only component which is interested in new text messages return ProcessMessage::CONTINUE; } diff --git a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp index 24c2d88a4..520b3ef65 100644 --- a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp +++ b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp @@ -34,7 +34,15 @@ void InkHUD::LogoApplet::onRender() int16_t logoCX = X(0.5); int16_t logoCY = Y(0.5 - 0.05); - drawLogo(logoCX, logoCY, logoW, logoH); + // Invert colors if black-on-white + // Used during shutdown, to resport display health + // Todo: handle this in InkHUD::Renderer instead + if (inverted) { + fillScreen(BLACK); + setTextColor(WHITE); + } + + drawLogo(logoCX, logoCY, logoW, logoH, inverted ? WHITE : BLACK); if (!textLeft.empty()) { setFont(fontSmall); @@ -74,13 +82,45 @@ void InkHUD::LogoApplet::onBackground() // Begin displaying the screen which is shown at shutdown void InkHUD::LogoApplet::onShutdown() { + bringToForeground(); + + textLeft = ""; + textRight = ""; + textTitle = "Shutting Down..."; + fontTitle = fontSmall; + + // Draw a shutting down screen, twice. + // Once white on black, once black on white. + // Intention is to restore display health. + + inverted = true; + inkhud->forceUpdate(Drivers::EInk::FULL, false); + delay(1000); // Cooldown. Back to back updates aren't great for health. + inverted = false; + inkhud->forceUpdate(Drivers::EInk::FULL, false); + delay(1000); // Cooldown + + // Prepare for the powered-off screen now + // We can change these values because the initial "shutting down" screen has already rendered at this point textLeft = ""; textRight = ""; textTitle = owner.short_name; fontTitle = fontLarge; + // This is then drawn by InkHUD::Events::onShutdown, with a blocking FULL update, after InkHUD's flash write is complete +} + +void InkHUD::LogoApplet::onReboot() +{ bringToForeground(); - // This is then drawn by InkHUD::Events::onShutdown, with a blocking FULL update + + textLeft = ""; + textRight = ""; + textTitle = "Rebooting..."; + fontTitle = fontSmall; + + inkhud->forceUpdate(Drivers::EInk::FULL, false); + // Perform the update right now, waiting here until complete } int32_t InkHUD::LogoApplet::runOnce() diff --git a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h index b55d4a2d9..3f604baed 100644 --- a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h +++ b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h @@ -25,6 +25,7 @@ class LogoApplet : public SystemApplet, public concurrency::OSThread void onForeground() override; void onBackground() override; void onShutdown() override; + void onReboot() override; protected: int32_t runOnce() override; @@ -33,6 +34,7 @@ class LogoApplet : public SystemApplet, public concurrency::OSThread std::string textRight; std::string textTitle; AppletFont fontTitle; + bool inverted = false; // Invert colors. Used during shutdown, to restore display health. }; } // namespace NicheGraphics::InkHUD diff --git a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h index 6950bb110..4f8205647 100644 --- a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h +++ b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h @@ -22,15 +22,17 @@ enum MenuAction { SEND_POSITION, SHUTDOWN, NEXT_TILE, + TOGGLE_BACKLIGHT, + TOGGLE_GPS, + ENABLE_BLUETOOTH, TOGGLE_APPLET, - ACTIVATE_APPLETS, // Todo: remove? Possible redundant, handled by TOGGLE_APPLET? TOGGLE_AUTOSHOW_APPLET, SET_RECENTS, ROTATE, LAYOUT, TOGGLE_BATTERY_ICON, TOGGLE_NOTIFICATIONS, - TOGGLE_BACKLIGHT, + TOGGLE_12H_CLOCK, }; } // namespace NicheGraphics::InkHUD diff --git a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp index 7397f7e9f..f59579230 100644 --- a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp +++ b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp @@ -5,8 +5,13 @@ #include "RTC.h" #include "airtime.h" +#include "main.h" #include "power.h" +#if !MESHTASTIC_EXCLUDE_GPS +#include "GPS.h" +#endif + using namespace NicheGraphics; static constexpr uint8_t MENU_TIMEOUT_SEC = 60; // How many seconds before menu auto-closes @@ -27,8 +32,6 @@ InkHUD::MenuApplet::MenuApplet() : concurrency::OSThread("MenuApplet") } } -void InkHUD::MenuApplet::onActivate() {} - void InkHUD::MenuApplet::onForeground() { // We do need this before we render, but we can optimize by just calculating it once now @@ -161,12 +164,6 @@ void InkHUD::MenuApplet::execute(MenuItem item) case TOGGLE_APPLET: settings->userApplets.active[cursor] = !settings->userApplets.active[cursor]; inkhud->updateAppletSelection(); - // requestUpdate(Drivers::EInk::UpdateTypes::FULL); // Select FULL, seeing how this action doesn't auto exit - break; - - case ACTIVATE_APPLETS: - // Todo: remove this action? Already handled by TOGGLE_APPLET? - inkhud->updateAppletSelection(); break; case TOGGLE_AUTOSHOW_APPLET: @@ -205,6 +202,25 @@ void InkHUD::MenuApplet::execute(MenuItem item) backlight->latch(); break; + case TOGGLE_12H_CLOCK: + config.display.use_12h_clock = !config.display.use_12h_clock; + nodeDB->saveToDisk(SEGMENT_CONFIG); + break; + + case TOGGLE_GPS: + gps->toggleGpsMode(); + nodeDB->saveToDisk(SEGMENT_CONFIG); + break; + + case ENABLE_BLUETOOTH: + // This helps users recover from a bad wifi config + LOG_INFO("Enabling Bluetooth"); + config.network.wifi_enabled = false; + config.bluetooth.enabled = true; + nodeDB->saveToDisk(); + rebootAtMsec = millis() + 2000; + break; + default: LOG_WARN("Action not implemented"); } @@ -242,13 +258,21 @@ void InkHUD::MenuApplet::showPage(MenuPage page) case OPTIONS: // Optional: backlight - if (settings->optionalMenuItems.backlight) { - assert(backlight); + if (settings->optionalMenuItems.backlight) items.push_back(MenuItem(backlight->isLatched() ? "Backlight Off" : "Keep Backlight On", // Label MenuAction::TOGGLE_BACKLIGHT, // Action MenuPage::EXIT // Exit once complete )); - } + + // Optional: GPS + if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_DISABLED) + items.push_back(MenuItem("Enable GPS", MenuAction::TOGGLE_GPS, MenuPage::EXIT)); + if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_ENABLED) + items.push_back(MenuItem("Disable GPS", MenuAction::TOGGLE_GPS, MenuPage::EXIT)); + + // Optional: Enable Bluetooth, in case of lost wifi connection + if (!config.bluetooth.enabled || config.network.wifi_enabled) + items.push_back(MenuItem("Enable Bluetooth", MenuAction::ENABLE_BLUETOOTH, MenuPage::EXIT)); items.push_back(MenuItem("Applets", MenuPage::APPLETS)); items.push_back(MenuItem("Auto-show", MenuPage::AUTOSHOW)); @@ -260,26 +284,14 @@ void InkHUD::MenuApplet::showPage(MenuPage page) &settings->optionalFeatures.notifications)); items.push_back(MenuItem("Battery Icon", MenuAction::TOGGLE_BATTERY_ICON, MenuPage::OPTIONS, &settings->optionalFeatures.batteryIcon)); - - // TODO - GPS and Wifi switches - /* - // Optional: has GPS - if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_DISABLED) - items.push_back(MenuItem("Enable GPS", MenuPage::EXIT)); // TODO - if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_ENABLED) - items.push_back(MenuItem("Disable GPS", MenuPage::EXIT)); // TODO - - // Optional: using wifi - if (!config.bluetooth.enabled) - items.push_back(MenuItem("Enable Bluetooth", MenuPage::EXIT)); // TODO: escape hatch if wifi configured wrong - */ - + items.push_back( + MenuItem("12-Hour Clock", MenuAction::TOGGLE_12H_CLOCK, MenuPage::OPTIONS, &config.display.use_12h_clock)); items.push_back(MenuItem("Exit", MenuPage::EXIT)); break; case APPLETS: populateAppletPage(); - items.push_back(MenuItem("Exit", MenuAction::ACTIVATE_APPLETS)); + items.push_back(MenuItem("Exit", MenuPage::EXIT)); break; case AUTOSHOW: @@ -293,7 +305,6 @@ void InkHUD::MenuApplet::showPage(MenuPage page) case EXIT: sendToBackground(); // Menu applet dismissed, allow normal behavior to resume - // requestUpdate(Drivers::EInk::UpdateTypes::FULL); break; default: diff --git a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h index fe72d826b..d9297c8ed 100644 --- a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h +++ b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h @@ -21,7 +21,6 @@ class MenuApplet : public SystemApplet, public concurrency::OSThread { public: MenuApplet(); - void onActivate() override; void onForeground() override; void onBackground() override; void onButtonShortPress() override; diff --git a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp index 1abf3ccfa..82a196cb1 100644 --- a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp +++ b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp @@ -207,8 +207,6 @@ void InkHUD::TipsApplet::onBackground() inkhud->forceUpdate(EInk::UpdateTypes::FULL); } -void InkHUD::TipsApplet::onActivate() {} - // While our SystemApplet::handleInput flag is true void InkHUD::TipsApplet::onButtonShortPress() { diff --git a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h index e7bb7bedc..db88585e9 100644 --- a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h +++ b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h @@ -33,7 +33,6 @@ class TipsApplet : public SystemApplet TipsApplet(); void onRender() override; - void onActivate() override; void onForeground() override; void onBackground() override; void onButtonShortPress() override; diff --git a/src/graphics/niche/InkHUD/Events.cpp b/src/graphics/niche/InkHUD/Events.cpp index 10072b302..ddd01b7e1 100644 --- a/src/graphics/niche/InkHUD/Events.cpp +++ b/src/graphics/niche/InkHUD/Events.cpp @@ -70,6 +70,9 @@ void InkHUD::Events::onButtonLong() // Returns 0 to signal that we agree to sleep now int InkHUD::Events::beforeDeepSleep(void *unused) { + // If a previous display update is in progress, wait for it to complete. + inkhud->awaitUpdate(); + // Notify all applets that we're shutting down for (Applet *ua : inkhud->userApplets) { ua->onDeactivate(); @@ -87,9 +90,12 @@ int InkHUD::Events::beforeDeepSleep(void *unused) inkhud->persistence->saveSettings(); inkhud->persistence->saveLatestMessage(); - // LogoApplet::onShutdown will have requested an update, to draw the shutdown screen - // Draw that now, and wait here until the update is complete + // LogoApplet::onShutdown attempted to heal the display by drawing a "shutting down" screen twice, + // then prepared a final powered-off screen for us, which shows device shortname. + // We're updating to show that one now. + inkhud->forceUpdate(Drivers::EInk::UpdateTypes::FULL, false); + delay(1000); // Cooldown, before potentially yanking display power return 0; // We agree: deep sleep now } @@ -106,16 +112,16 @@ int InkHUD::Events::beforeReboot(void *unused) a->onDeactivate(); a->onShutdown(); } - for (Applet *sa : inkhud->systemApplets) { + for (SystemApplet *sa : inkhud->systemApplets) { // Note: no onDeactivate. System applets are always active. - sa->onShutdown(); + sa->onReboot(); } inkhud->persistence->saveSettings(); inkhud->persistence->saveLatestMessage(); // Note: no forceUpdate call here - // Because OSThread will not be given another chance to run before reboot, this means that no display update will occur + // We don't have any final screen to draw, although LogoApplet::onReboot did already display a "rebooting" screen return 0; // No special status to report. Ignored anyway by this Observable } diff --git a/src/graphics/niche/InkHUD/Persistence.h b/src/graphics/niche/InkHUD/Persistence.h index 28841d4d9..40f1dd521 100644 --- a/src/graphics/niche/InkHUD/Persistence.h +++ b/src/graphics/niche/InkHUD/Persistence.h @@ -99,7 +99,7 @@ class Persistence // Rotation of the display // Multiples of 90 degrees clockwise // Most commonly: rotation is 0 when flex connector is oriented below display - uint8_t rotation = 1; + uint8_t rotation = 0; // How long do we consider another node to be "active"? // Used when applets want to filter for "active nodes" only diff --git a/src/graphics/niche/InkHUD/README.md b/src/graphics/niche/InkHUD/README.md deleted file mode 100644 index 8d788ffa8..000000000 --- a/src/graphics/niche/InkHUD/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# InkHUD - -A heads-up-display for E-Ink devices, intended to supplement a connected phone / client. Implemented as a "NicheGraphics" UI. - -Supported devices (as of 1st Feb. 2025): - -- Heltec Vision Master E213 -- Heltec Vision Master E290 -- Heltec Wireless Paper V1.1 -- LILYGO T-Echo - -More to follow diff --git a/src/graphics/niche/InkHUD/SystemApplet.h b/src/graphics/niche/InkHUD/SystemApplet.h index 0f8ceedc7..7ee47eeb9 100644 --- a/src/graphics/niche/InkHUD/SystemApplet.h +++ b/src/graphics/niche/InkHUD/SystemApplet.h @@ -26,6 +26,8 @@ class SystemApplet : public Applet bool lockRendering = false; // - prevent other applets from being rendered during an update bool lockRequests = false; // - prevent other applets from triggering display updates + virtual void onReboot() { onShutdown(); } // - handle reboot specially + // Other system applets may take precedence over our own system applet though // The order an applet is passed to WindowManager::addSystemApplet determines this hierarchy (added earlier = higher rank) diff --git a/src/graphics/niche/InkHUD/docs/README.md b/src/graphics/niche/InkHUD/docs/README.md new file mode 100644 index 000000000..07fe6c942 --- /dev/null +++ b/src/graphics/niche/InkHUD/docs/README.md @@ -0,0 +1,640 @@ +# InkHUD + +This document is intended as a reference for maintainers. A haphazard collection of notes which _might_ be helpful. + +self deprecating meme + +--- + +- [Purpose](#purpose) +- [Design Principles](#design-principles) + - [Self-Contained](#self-contained) + - [Static](#static) + - [Non-interactive](#non-interactive) + - [Customizable](#customizable) + - [Event-Driven Rendering](#event-driven-rendering) + - [No `#ifdef` spaghetti](#no-ifdef-spaghetti) +- [The Implementation](#the-implementation) +- [The Rendering Process](#the-rendering-process) +- [Concepts](#concepts) + - [NicheGraphics Framework](#nichegraphics-framework) + - [NicheGraphics E-Ink Drivers](#nichegraphics-e-ink-drivers) + - [InkHUD Applets](#inkhud-applets) +- [Adding a Variant](#adding-a-variant) + - [platformio.ini](#platformioini) + - [nicheGraphics.h](#nichegraphicsh) +- [Class Notes](#class-notes) + - [`InkHUD::InkHUD`](#inkhudinkhud) + - [`InkHUD::Persistence`](#inkhudpersistence) + - [`InkHUD::Persistence::Settings`](#inkhudpersistencesettings) + - [`InkHUD::Persistence::LatestMessage`](#inkhudpersistencelatestmessage) + - [`InkHUD::WindowManager`](#inkhudwindowmanager) + - [`InkHUD::Renderer`](#inkhudrenderer) + - [`InkHUD::Renderer::DisplayHealth`](#inkhudrendererdisplayhealth) + - [`InkHUD::Events`](#inkhudevents) + - [`InkHUD::Applet`](#inkhudapplet) + - [`InkHUD::SystemApplet`](#inkhudsystemapplet) + - [`InkHUD::Tile`](#inkhudtile) + - [`InkHUD::AppletFont`](#inkhudappletfont) + +## Purpose + +InkHUD is a minimal UI for E-Ink devices. It displays the user's choice of info, as statically as possible, to minimize the amount of display refreshing. + +It is intended to supplement a connected client app. + +## Design Principles + +### Self-Contained + +- Keep InkHUD code within `/src/graphics/niche/InkHUD`. +- Place reusable components within `/src/graphics/niche`, for other UIs to take advantage of. +- Interact with the firmware code using the **Module API**, **Observables**, and other similarly non-intrusive hooks. + +### Static + +Information should be displayed as statically as possible. Unnecessary updates should be avoided. + +As as example, fixed timestamps are used instead of `X seconds ago` labels, as these need to be constantly updated to remain current. + +### Non-interactive + +InkHUD aims to be a "heads up display". The intention is for the user to glance at the display. The intention is _not_ for the user to frequently interact with the display. + +Some interactivity is tolerated as a means to an end: the display _should_ be customizable, but this should be minimized as much as possible. + +_Edit: there's significant demand for keyboard support, so some sort of free-text feature will need to be added eventually, although it does go against the original design principles._ + +### Customizable + +The user should be given the choice to decide which information they would like to receive, and how they would like to receive it. + +### Event-Driven Rendering + +The display image does not update "automatically". Individual applets are responsible for deciding when they have new information to show, and then requesting a display update. + +### No `#ifdef` spaghetti + +**Don't** use preprocessor macros for device-specific configuration. This should be achieved with config methods, in [`nicheGraphics.h`](#nichegraphicsh). + +**Do** use preprocessor macros to guard all files + +- `#ifdef MESHTASTIC_INCLUDE_INKHUD` for InkHUD files +- `#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS` for reusable components (drivers, etc) + +## The Implementation + +- Variant's platformio.ini file extends `inkhud` (defined in InkHUD/PlatformioConfig.ini) + - original screen class suppressed: `MESHTASTIC_EXCLUDE_SCREEN` + - ButtonThread suppressed: `HAS_BUTTON=0` + - NicheGraphics components included: `MESHTASTIC_INCLUDE_NICHE_GRAPHICS` + - InkHUD components included: `MESHTASTIC_INCLUDE_INKHUD` +- `main.cpp` + - includes `nicheGraphics.h` (from variant folder) + - calls `setupNicheGraphics`, (from nicheGraphics.h) +- `nicheGraphics.h` + - includes InkHUD components + - includes shared NicheGraphics components + - `setupNicheGraphics` + - configures and connects components + - `inkhud->begin` + +## The Rendering Process + +(animated diagram) + +animated process diagram of InkHUD rendering + +An overview: + +- A component calls `requestUpdate` (applets only) or `InkHUD::forceUpdate` +- `Renderer` schedules a render cycle for the next loop(), using `Renderer::runOnce` +- `Renderer` determines whether the update request is valid +- `Renderer` asks relevant applets to render +- Applet dimensions are updated (by Applet's `Tile`) +- Applets generate pixel output, and pass this to their `Tile` +- Tiles shift these "relative" pixels to their true region, for multiplexing +- Tiles pass the pixels to `Renderer` +- `Renderer` applies any global display rotation to the pixels +- `Renderer` combines the pixels into the finished image +- The finished image is passed to the display driver, starting the physical update process + +## Concepts + +### NicheGraphics Framework + +InkHUD is implemented as a _NicheGraphics_ UI. + +Intended as a pattern / philosophy for implementing self-contained UIs, to suit various niche devices, which are best served by their own custom user interface. + +Hypothetical examples: E-Ink, 1602 LCDs, tiny OLEDs, smart watches, etc + +A NicheGraphics UI: + +- Is self-contained +- Makes use of the loose collection of resources (drivers, input methods, etc) gathered in the `/src/graphics/niche` folder. +- Implements a `setupNicheGraphics()` method. + +### NicheGraphics E-Ink Drivers + +InkHUD uses a set of custom E-Ink drivers. These are not based on GxEPD2, or any other code base. They are written directly on-top of the Meshtastic firmware, to make use of the OSThread class for asynchronous display updates. + +Interacting with the drivers is straightforward. InkHUD generates a frame of 1-bit image data. This image data is passed to the driver, along with the type of refresh to use (FULL or FAST). + +`driver->update(uint8_t* buffer, EInk::UpdateTypes::FULL)` + +For more information, see the documentation in `src/graphics/niche/Drivers/EInk` + +### InkHUD Applets + +An InkHUD applet is a class which generates a screen of info for the display. + +Consider: `DMApplet.h` (displays most recent direct message) and `RecentsList.h` (displays a list of recently heard nodes) + +- Applets are modular: they are easy to write, and easy to implement. Users select which applets they want, using the menu. +- Applets use responsive design. They should scale for different screens / layouts / fonts. +- Applets decide when to update. They use the Module API, Observers, etc, to retrieve information, and request a display update when they have something interesting to show. + +See `src/graphics/niche/InkHUD/Applets/Examples` for example code. + +#### Writing an Applet + +Your new applet class will inherit `InkHUD::Applet`. + +```cpp +class BasicExampleApplet : public Applet +{ + public: + // You must have an onRender() method + // All drawing happens here + + void onRender() override; +}; +``` + +The `onRender` method is called when the display image is redrawn. This can happen at any time, so be ready! + +```cpp +// All drawing happens here +// Our basic example doesn't do anything useful. It just passively prints some text. +void InkHUD::BasicExampleApplet::onRender() +{ + printAt(0, 0, "Hello, world!"); +} +``` + +Your applet will need to scale automatically, to suit a variety of screens / layouts / fonts. Make sure you draw relative to applet's size. + +| edge | coordinate | shorthand | +| ------ | ---------- | --------- | +| left | 0 | `X(0.0)` | +| top | 0 | `Y(0.0)` | +| right | `width()` | `X(1.0)` | +| bottom | `height()` | `Y(1.0)` | + +The same principles apply for drawing text. Methods like `AppletFont::lineHeight` and `getTextWidth` are useful here. + +```cpp +std::string line1 = "Line 1"; +printAt(0, Y(0.5), line1); +drawRect(0, Y(0.5), getTextWidth(line1), fontSmall.lineHeight(), BLACK); +``` + +Your applet will only be redrawn when _something_ requests a display update. Your applet is welcome to request a display update, when it determines that it has new info to display, by calling `requestUpdate`. + +Exactly how you determine this, depends on what your applet actually does. Here's a code snippet from one of the example applets. The applet is requesting an update when a new message is received. + +```cpp +// We configured the Module API to call this method when we receive a new text message +ProcessMessage InkHUD::NewMsgExampleApplet::handleReceived(const meshtastic_MeshPacket &mp) +{ + + // Abort if applet fully deactivated + // Don't waste time: we wouldn't be rendered anyway + if (!isActive()) + return ProcessMessage::CONTINUE; + + // Check that this is an incoming message + // Outgoing messages (sent by us) will also call handleReceived + + if (!isFromUs(&mp)) { + // Store the sender's nodenum + // We need to keep this information, so we can re-use it anytime render() is called + haveMessage = true; + fromWho = mp.from; + + // Tell InkHUD that we have something new to show on the screen + requestUpdate(); + } + + // Tell Module API to continue informing other firmware components about this message + // We're not the only component which is interested in new text messages + return ProcessMessage::CONTINUE; +} +``` + +#### Implementing an Applet + +Incorporating your new applet into InkHUD is easy. + +In a variant's `nicheGraphics.h`: + +- `#include` your applet +- `inkhud->addApplet("My Applet", new InkHUD::MyApplet);` + +You will need to add these lines to any variants which will use your applet. + +#### Applet Bases + +If you need to create several similar applets, it might make sense to create a reusable base class. Several of these already exist in `src/graphics/niche/InkHUD/Applets/Bases`, but use these with caution, as they may be modified in future. + +#### System Applets + +So far, we have been talking about "user applets". We also recognize a separate category of "system applets". These handle things like the menu, and the boot screen. These often need special handling, and need to be implemented manually. + +## Adding a Variant + +In `/variants//`: + +### platformio.ini + +Extend `inkhud`, then combine with any other platformio config your hardware variant requires. + +_(Example shows only config required by InkHUD. This is not a complete `env` definition.)_ + +```ini +[env:YOUR_VARIANT-inkhud] +extends = esp32s3_base, inkhud ; or nrf52840_base, etc + +build_src_filter = +${esp32_base.build_src_filter} +${inkhud.build_src_filter} + +build_flags = +${esp32s3_base.build_flags} +${inkhud.build_flags} + +lib_deps = +${inkhud.lib_deps} ; InkHUD libs first, so we get GFXRoot instead of AdafruitGFX +${esp32s3_base.lib_deps} +``` + +### nicheGraphics.h + +⚠ Wrap this file in `#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS` + +`nicheGraphics.h` should be placed in the same folder as your variant's `platformio.ini`. If this is not possible, modify `build_src_filter`. + +`nicheGraphics.h` should contain a `setupNicheGraphics` method, which creates and configures the various components for InkHUD. + +- Display + - Start SPI + - Create display driver +- InkHUD + - Create InkHUD instance + - Set E-Ink fast refresh limit (`setDisplayResilience`) + - Set fonts + - Set default user-settings + - Select applets to build (`addApplet`) + - Start InkHUD +- Buttons + - Setup `TwoButton` driver (user button, optional "auxiliary" button) + - Connect to InkHUD handlers (use lambdas) + +For well commented examples, see: + +- `variants/heltec_vision_master_e290/nicheGraphics.h` (ESP32) +- `variants/t-echo/nicheGraphics.h` (NRF52) + +## Class Notes + +### `InkHUD::InkHUD` + +_`src/graphics/niche/InkHUD/InkHUD.h`_ + +- singleton +- mediator between other InkHUD components + +#### `getInstance()` + +Gets access to the class. +First `getInstance` call instantiates the class, and the subclasses: + +- `InkHUD::Persistence` +- `InkHUD::WindowManager` +- `InkHUD::Renderer` +- `InkHUD::Events` + +For convenience, many InkHUD components call this on `begin`, and store it as `InkHUD* inkhud`. + +--- + +### `InkHUD::Persistence` + +_`src/graphics/niche/InkHUD/Persistence.h`_ + +Stores InkHUD data in flash + +- settings +- most recent text message received (both for broadcast and DM) + +In rare cases, applets may store their own specific data separately (e.g. `ThreadedMessageApplet`) + +Data saved only on shutdown / reboot. Not saved if power is removed unexpectedly. + +--- + +### `InkHUD::Persistence::Settings` + +_`src/graphics/niche/InkHUD/Persistence.h`_ + +Settings which relate to InkHUD. Mostly user's customization, but some values record the UI's state (e.g. `tips.safeShutdownSeen`) + +- stored using `FlashData.h` (a shared Niche Graphics tool) +- not encoded as protobufs +- serialized directly as bytes of struct + +#### Defaults + +Global default values are set when the struct is defined (Persistence.h). +Per-variant defaults are set by modifying the values of the settings instance during `setupNicheGraphics()`, before `inkhud->begin` is called. + +```cpp +inkhud->persistence->settings.userTiles.count = 2; +inkhud->persistence->settings.userTiles.maxCount = 4; +inkhud->persistence->settings.rotation = 3; +``` + +By modifying the values at this point, they will be used if we fail to load previous settings from flash (not yet saved, old version, etc) + +--- + +### `InkHUD::Persistence::LatestMessage` + +_`src/graphics/niche/InkHUD/Persistence.h`_ + +Most recently received text message + +- most recent DM +- most recent broadcast + +Collected here, so various user applets don't all have to store their own copy of this info. + +We are unable to use `devicestate.rx_text_message` for this purpose, because: + +- it is cleared by an outgoing text message +- we want to store both a recent broadcast and a recent DM + +#### Saving / Loading + +_A bit of a hack.._ +Stored to flash using `InkHUD::MessageStore`, which is really intended for storing a thread of messages (see `ThreadedMessageApplet`). Used because it stores strings more efficiently than `FlashData.h`. + +The hack is: + +- If most recent message was a DM, we only store the DM. +- If most recent message was a broadcast, we store both a DM and a broadcast. The DM may be 0-length string. + +--- + +### `InkHUD::WindowManager` + +_`src/graphics/niche/InkHUD/WindowManager.h`_ + +Manages which applets are shown, and their size / position (by manipulating the "tiles") + +- owns the `Tile` instances +- creates and destroys tiles; sets size and position: + - at startup + - at runtime, when config changes (layout, rotation, etc) +- activates (or deactivates) applets +- cycling through applets (e.g. on button press) + +The window manager doesn't process pixels; that is handled by the `InkHUD::Tile` objects. + +Note: Some of the methods (incl. `changeLayout`, `changeActivatedApplets`) don't trigger changes themselves. They should be called _after_ the relevant values in `inkhud->persistence->settings` have been modified. + +--- + +### `InkHUD::Renderer` + +_`src/graphics/niche/InkHUD/Renderer.h`_ + +Get pixel output from applets (via a tile), combine, and pass to the driver. + +- triggered by `requestUpdate` or `forceUpdate` +- not run immediately: allows multiple applets to share one render cycle +- calls `Applet::onRender` for relevant applets +- applies global rotation +- passes finalized image to driver + +`requestUpdate` is for applets (user or system). Renderer will honor the request if the applet is visible. `forceUpdate` can be used anywhere, but not from user applets, please. + +#### Asynchronous updates + +`requestUpdate` and `forceUpdate` do not block code execution. They schedule rendering for "ASAP", using `Renderer::runOnce`. Renderer then gets pixel output from relevant applets, and hands the assembled image to the driver. Driver's update process is also asynchronous. If the driver is busy when `requestUpdate` or `forceUpdate` is called, another rendering will run as soon as possible. This is handled by `Renderer::runOnce` + +#### Blocking updates + +If needed, call `forceUpdate` with the optional argument `async=false` to wait while an update runs (> 1 second). Additionally, the `awaitUpdate` method can be used to block until any previous update has completed. An example usage of this is waiting to draw the shutdown screen. + +#### Global rotation + +The exact size / position / rotation of InkHUD applets is configurable by the user. To achieve this, applets draw pixels between 0,0 and `Applet::width()`, `Applet::height()` + +- **Scaling**: Applet's `width()` and `height()` are set by `Tile` before rendering starts +- **Translation**: `Tile` shifts applet pixels up/down/left/right +- **Rotation**: `Renderer` rotates all pixels it receives, before placing them into the final image buffer + +--- + +### `InkHUD::Renderer::DisplayHealth` + +_`src/graphics/niche/InkHUD/DisplayHealth.h`_ + +Responsible for maintaining display health, by optimizing the ratio of FAST vs FULL refreshes + +- count number of FAST vs FULL refreshes (debt) +- suggest either FAST or FULL type +- periodically FULL refresh the display unprovoked, if needed + +#### Background Info + +When the image on an E-Ink display is updated, different procedures can be used to move the pixels to their new states. We have defined two procedures: `FAST` and `FULL`. + +A `FAST` update moves pixels directly from their old position, to their new position. This is aesthetically pleasing, and quick, _but_ it is challenging for the display hardware. If used excessively, pixels can build up residual charge, which negatively impacts the display's lifespan and image quality. + +A `FULL` update first moves all pixels between black and white, before letting them eventually settle at their final position. This causes an unpleasant flashing of the display image, but is best for the display health and image quality. + +Most displays readily tolerate `FAST` updates, so long as a `FULL` update is occasionally performed. How often this `FULL` update is required depends on the display model. + +#### Debt + +`InkHUD::DisplayHealth` records how many `FAST` refreshes have occurred since the previous `FULL` refresh. + +This is referred to as the "full refresh debt". + +If an update of a specific type (`FULL` / `FAST`) is requested / forced, this will be granted. + +If an update is requested / forced _without_ a specified type (`UpdateTypes::UNSPECIFIED`), `DisplayHealth` will select either `FAST` or `FULL`, in an attempt to maintain a target ratio of fast to full updates. + +This target is set by `InkHUD::setDisplayResilience`, when setting up in `nichegraphics.h` + +If an _excessive_ amount of `FAST` refreshes are performed back-to-back, `DisplayHealth` will begin artificially inflating the full refresh debt. This will cause the next few `UNSPECIFIED` updates to _all_ be performed as `FULL`, while the debt is paid down. + +This system of "full refresh debt" allows us to increase perceived responsiveness by tolerating additional strain on the display during periods of user interaction, and attempting to "repair the damage" later, once user interaction ceases. + +#### Maintenance + +The system of "full refresh debt" assumes that the display will perform many updates of `UNSPECIFIED` type between periods of user interaction. Depending on the amount of mesh traffic / applet selection, this may not be the case. + +If debt is particularly high, and no updates are taking place organically, `DisplayHealth` will begin infrequently performing `FULL` updates, purely to pay down the full refresh debt. + +--- + +### `InkHUD::Events` + +Handles events which impact the InkHUD system generally (e.g. shutdown, button press). + +Applets themselves do also listen separately for various events, but for the purpose of gathering information which they would like to display. + +#### Buttons + +Button input is sometimes handled by a system applet. `InkHUD::Events` determines whether the button should be handled by a specific system applet, or should instead trigger a default behavior + +--- + +### `InkHUD::Applet` + +A base class for applets. An applet is one "program", which may show info on the display. + +To oversimplify, all of the InkHUD code "under the hood" only exists to support applets. Applets are what actually shows useful information to the user. This base class exposes the functionality needed to write an applet. + +#### Drawing Methods + +`Applet` implements most AdafruitGFX drawing methods. Exception is the text handling. `printAt`, `printWrapped`, and `printThick` should be used instead. These are intended to be more convenient, but they also implement the character substitution system which powers the foreign alphabet support. + +`Applet` also adds methods for drawing several design elements which are re-used commonly though-out InkHUD. + +#### InkHUD Events + +Applets undergo a number of state changes: activated / deactivated by user, brought to foreground / hidden to background by user button press, etc. The `Applet` class provides a set of virtual methods, which an applet can override to appropriately handle these events. + +The `onRender` virtual method is one example. This is called when an applet is rendered, and should execute all drawing code. An applet _must_ implement this method. + +#### Responsive Design + +An applet's size will vary depending on the screen size, and the user's layout (multiplexing). Immediately before `onRender` is called, an applet's dimensions are updated, so that `width()` and `height()` will give the required size. The applet should draw its graphical elements relative to these values. The methods `X(float)` and `Y(float)` are also provided for convenience. + +| edge | coordinate | shorthand | +| ------ | ---------- | --------- | +| left | 0 | `X(0.0)` | +| top | 0 | `Y(0.0)` | +| right | `width()` | `X(1.0)` | +| bottom | `height()` | `Y(1.0)` | + +The same principles apply for drawing text. Methods like `AppletFont::lineHeight` and `getTextWidth` are useful here. + +Applets should always draw relative to their top left corner, at _x=0, y=0._ The applet's pixels are automatically moved to the correct position on-screen by an InkHUD::Tile. + +#### User Applets + +User applets are the "normal" applets, each one displaying a specific set of information to the user. They can be activated / deactivated at run-time using the on-screen menu. Examples include `DMApplet.h` and `PositionsApplet.h`. User applets are not expected to interact with lower layers of the InkHUD code. + +Users applets are instantiated in a variant's `setupNicheGraphics` method, and passed to `InkHUD::addApplet`. Their class should not be mentioned elsewhere, so that its code can be stripped away during compilation if a variant does not implement the specific applet. Internal processing of user applets treats them all as the generic `Applet` type only. + +#### Activated / Deactivated + +User applets can be activated or deactivated. This changes at run-time: the user selects which applets should be active using the on-screen menu. An applet should not process data while it is deactivated. It can unobserve any observables, ignore `handleReceived` calls, etc. + +An applet can implement the virtual `onActivate` and `onDeactivate` methods to handle this change in state. It can check this state internally by calling `isActive`. + +System applets cannot be deactivated. + +#### Foreground / Background + +An activated applet can either be _foreground_ or _background_. A foreground applet is one which will be rendered to a tile when the screen updates. A background applet will not be drawn. The applet cycling which takes place when the user button is pressed is implemented using foreground / background. + +Regardless of whether it is foreground or background, an activated applet should continue to collect / process data, and request update when it has new info to display. This is because of the _autoshow_ mechanic, which might bring a background applet to foreground in order to display its data. If an applet remains background, its update requests will be safely ignored. + +#### Autoshow + +Autoshow is a feature which allows the user to select which applets (if any) they would like to be shown automatically. If autoshow is enabled for an applet, it will be brought to foreground when it has new information to display. The user grants this privilege on a per-applet basis, using the on-screen menu. If an event causes an applet to be autoshown, NotificationApplet should not be shown for the same event. + +An applet needs to decide when it has information worthy of autoshowing. It signals this by calling `requestAutoshow`, in addition to the usual `requestUpdate` call. + +--- + +### `InkHUD::SystemApplet` + +_System applets_ are applets with special roles, which require special handling. Examples include `BatteryIconApplet.h` and `LogoApplet.h`. These are manually implemented, one-by-one, in `WindowManager.h`. + +This class is a slight extension of `Applet`. It adds extra flags for some special features which are restricted to system applets: exclusive use of the display, and the handling of user input. Having a separate system applet class also allows us to make it clear within the code when system applets are being handled, rather than user applets + +We store reference to these as a `vector`. This parallels how we treat user applets, and makes rendering convenient. +Because system applets do have unique roles, there are times when we will need to interact with a specific applet. Rather than keeping an extra set of references, we access them from the `vector`. Use `InkHUD::getSystemApplet` to access the applet by its `Applet::name` value, and then typecast. + +--- + +### `InkHUD::Tile` + +A tile represents a region of the display. A tile controls the size and position of an applet. + +For an applet to render, it must be assigned to a tile. When an applet is assigned to a tile, the two become linked. The applet is aware of the tile; the tile is aware of the applet. Applets cannot share a tile; assigning a different applet will remove any existing link. + +Before an applet renders, its width and height are set to the dimensions of the tile. During `onRender`, an applet's drawing methods generate pixels between _x=0, y=0_ and _x=Applet::width(), y=Applet::height()_. These pixels are passed to its tile's `Tile::handleAppletPixel` method. The tile then applies x and y offset, "translating" these pixels to the tile's region of the display. These translated pixels are then passed on to the `InkHUD::Renderer`. + +![depiction of a tile translating applet pixels](./tile_translation.png) + +#### User Tiles + +_User applets_ are the "normal" applets. They can be activated / deactivated at run-time using the on-screen menu. User applets are rendered to one of the **user tiles**. + +The user can customize the "layout", using the on-screen menu. Depending on their selected layout, a certain number of _user tiles_ are created. These tiles are automatically positioned and sized so that they fill the entire screen. + +Often, a user will have enabled more applets than they have tiles. Pressing the user-button will cycle through these applets. The old applet is sent to _background_, the new applet is brought to _foreground_. When a user applet is brought to foreground, it becomes assigned to a user tile (the focused tile). When it renders, its size will be set by this tile, and its pixels will be translated to this tile's region. The user applet which was sent to background loses its assignment; it no longer has an assigned tile. + +#### Focused Tile + +The focused tile is one of the user tiles. This is tile whose applet will change when the user button is pressed. This also the tile where the menu will appear on longpress. The focused tile is identified by its index in `vector userTiles`. + +#### Highlighting + +In addition to the user button, some devices have a second "auxiliary button". The function of this button can vary from device to device, but it is sometimes used to focus a different tile. When this happens, the newly focused tile is temporarily "highlighted", by drawing it with a border. This border is automatically removed after several seconds. As drawing code may only be executed by applets, this highlighting is a collaborative effort between a `Tile` and an `Applet`: performed in `Applet::render`, after the virtual `onRender` method has already run. + +Highlighting is only used when `nextTile` is fired by an aux button. It does not occur if performed via the on-screen menu. + +#### System Tiles + +_System applets_ are applets with special roles, which require special handling. Examples include `BatteryIconApplet.h` and `LogoApplet.h`. _Mostly_, these applets do not render to user tiles. Instead, they are given their own unique tile, which is positioned / dimensioned manually. The only reference we keep to these special tiles is stored within the linked system applet. They can be accessed with `Applet::getTile`. + +--- + +### `InkHUD::AppletFont` + +Wrapper which extends the functionality of an AdafruitGFX font. + +#### Dimension Info + +The AppletFont class pre-calculates some info about a font's dimensions, which is useful for design (`AppletFont::lineHeight`), and is used to power InkHUD's custom text handling. + +The default AdafruitGFX text handling places characters "upon a line", as if hand-written on a sheet of ruled paper. `InkHUD::AppletFont` measures the character set of the font, so that we instead draw fixed-height lines of text, positioned by the bounding box, with optional horizontal and vertical alignment. + +![text origins in InkHUD vs AdafruitGFX](./appletfont.png) + +The height of this box is `AppletFont::lineHeight`, which is the height of the tallest character in the font. This gives us a fixed-height for text, which is much tighter than with AdafruitGFX's default line spacing. + +#### UTF-8 Substitutions + +To enable non-English text, the `AppletFont` class includes a mechanism to detect specific UTF-8 characters, and replace them with alternative glyphs from the AdafruitGFX font. This can be used to remap characters for a custom font, or to offer a suitable ASCII replacement. + +```cpp +// With a custom font +// ї is ASCII 0xBF, in Windows-1251 encoding +addSubstitution("ї", "\xBF"); + +// Substitution (with a default font) +addSubstitution("ö", "oe"); +``` + +These substitutions should be performed in a variant's `setupNicheGraphics` method. For convenience, some common ASCII encodings have ready-to-go sets of substitutions you can apply, for example `AppletFont::addSubstitutionsWin1251` diff --git a/src/graphics/niche/InkHUD/docs/appletfont.png b/src/graphics/niche/InkHUD/docs/appletfont.png new file mode 100644 index 000000000..f0b11d323 Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/appletfont.png differ diff --git a/src/graphics/niche/InkHUD/docs/disclaimer.jpg b/src/graphics/niche/InkHUD/docs/disclaimer.jpg new file mode 100644 index 000000000..d4c2c890e Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/disclaimer.jpg differ diff --git a/src/graphics/niche/InkHUD/docs/rendering.gif b/src/graphics/niche/InkHUD/docs/rendering.gif new file mode 100644 index 000000000..cb712381b Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/rendering.gif differ diff --git a/src/graphics/niche/InkHUD/docs/tile_translation.png b/src/graphics/niche/InkHUD/docs/tile_translation.png new file mode 100644 index 000000000..7bbf63643 Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/tile_translation.png differ diff --git a/src/graphics/niche/Inputs/TwoButton.cpp b/src/graphics/niche/Inputs/TwoButton.cpp index 10d89ef41..b270d56cf 100644 --- a/src/graphics/niche/Inputs/TwoButton.cpp +++ b/src/graphics/niche/Inputs/TwoButton.cpp @@ -2,6 +2,7 @@ #include "./TwoButton.h" +#include "NodeDB.h" // For the helper function TwoButton::getUserButtonPin #include "PowerFSM.h" #include "sleep.h" @@ -57,14 +58,47 @@ void TwoButton::stop() detachInterrupt(buttons[1].pin); } +// Attempt to resolve a GPIO pin for the user button, honoring userPrefs.jsonc and device settings +// This helper method isn't used by the TweButton class itself, it could be moved elsewhere. +// Intention is to pass this value to TwoButton::setWiring in the setupNicheGraphics method. +uint8_t TwoButton::getUserButtonPin() +{ + uint8_t pin = 0xFF; // Unset + + // Use default pin for variant, if no better source +#ifdef BUTTON_PIN + pin = BUTTON_PIN; +#endif + + // From userPrefs.jsonc, if set +#ifdef USERPREFS_BUTTON_PIN + pin = USERPREFS_BUTTON_PIN; +#endif + + // From user's override in device settings, if set + if (config.device.button_gpio) + pin = config.device.button_gpio; + + return pin; +} + // Configures the wiring and logic of either button // Called when outlining your NicheGraphics implementation, in variant/nicheGraphics.cpp void TwoButton::setWiring(uint8_t whichButton, uint8_t pin, bool internalPullup) { + // Prevent the same GPIO being assigned to multiple buttons + // Allows an edge case when the user remaps hardware buttons using device settings, due to a broken user button + for (uint8_t i = 0; i < whichButton; i++) { + if (buttons[i].pin == pin) { + LOG_WARN("Attempted reuse of GPIO %d. Ignoring assignment whichButton=%d", pin, whichButton); + return; + } + } + assert(whichButton < 2); buttons[whichButton].pin = pin; - buttons[whichButton].activeLogic = LOW; - buttons[whichButton].mode = internalPullup ? INPUT_PULLUP : INPUT; // fix me + buttons[whichButton].activeLogic = LOW; // Unimplemented + buttons[whichButton].mode = internalPullup ? INPUT_PULLUP : INPUT; pinMode(buttons[whichButton].pin, buttons[whichButton].mode); } diff --git a/src/graphics/niche/Inputs/TwoButton.h b/src/graphics/niche/Inputs/TwoButton.h index 1e1576256..f1e18dd89 100644 --- a/src/graphics/niche/Inputs/TwoButton.h +++ b/src/graphics/niche/Inputs/TwoButton.h @@ -30,6 +30,8 @@ class TwoButton : protected concurrency::OSThread public: typedef std::function Callback; + static uint8_t getUserButtonPin(); // Resolve the GPIO, considering the various possible source of definition + static TwoButton *getInstance(); // Create or get the singleton instance void start(); // Start handling button input void stop(); // Stop handling button input (disconnect ISRs for sleep) @@ -62,7 +64,7 @@ class TwoButton : protected concurrency::OSThread public: // Per-button config uint8_t pin = 0xFF; // 0xFF: unset - bool activeLogic = LOW; // Active LOW by default. Todo: remove, unused + bool activeLogic = LOW; // Active LOW by default. Currently unimplemented. uint8_t mode = INPUT; // Whether to use internal pull up / pull down resistors uint32_t debounceLength = 50; // Minimum length for shortpress, in ms uint32_t longpressLength = 500; // How long after button down to fire longpress, in ms diff --git a/src/graphics/tftSetup.cpp b/src/graphics/tftSetup.cpp index c31659c62..cacb02694 100644 --- a/src/graphics/tftSetup.cpp +++ b/src/graphics/tftSetup.cpp @@ -119,7 +119,7 @@ void tftSetup(void) #ifdef ARCH_ESP32 tftSleepObserver.observe(¬ifyLightSleep); endSleepObserver.observe(¬ifyLightSleepEnd); - xTaskCreatePinnedToCore(tft_task_handler, "tft", 8192, NULL, 1, NULL, 0); + xTaskCreatePinnedToCore(tft_task_handler, "tft", 10240, NULL, 1, NULL, 0); #endif } diff --git a/src/main.cpp b/src/main.cpp index 797d911d1..05eeef2ae 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -262,6 +262,32 @@ void printInfo() #ifndef PIO_UNIT_TESTING void setup() { + +#ifdef POWER_CHRG + pinMode(POWER_CHRG, OUTPUT); + digitalWrite(POWER_CHRG, HIGH); +#endif + +#if defined(PIN_POWER_EN) + pinMode(PIN_POWER_EN, OUTPUT); + digitalWrite(PIN_POWER_EN, HIGH); +#endif + +#ifdef LED_POWER + pinMode(LED_POWER, OUTPUT); + digitalWrite(LED_POWER, HIGH); +#endif + +#ifdef POWER_LED + pinMode(POWER_LED, OUTPUT); + digitalWrite(POWER_LED, HIGH); +#endif + +#ifdef USER_LED + pinMode(USER_LED, OUTPUT); + digitalWrite(USER_LED, LOW); +#endif + #if defined(T_DECK) // GPIO10 manages all peripheral power supplies // Turn on peripheral power immediately after MUC starts. @@ -325,13 +351,6 @@ void setup() initDeepSleep(); - // power on peripherals -#if defined(PIN_POWER_EN) - pinMode(PIN_POWER_EN, OUTPUT); - digitalWrite(PIN_POWER_EN, HIGH); - // digitalWrite(PIN_POWER_EN1, INPUT); -#endif - #if defined(LORA_TCXO_GPIO) pinMode(LORA_TCXO_GPIO, OUTPUT); digitalWrite(LORA_TCXO_GPIO, HIGH); @@ -822,6 +841,13 @@ void setup() #ifdef HAS_UDP_MULTICAST LOG_DEBUG("Start multicast thread"); udpThread = new UdpMulticastThread(); +#ifdef ARCH_PORTDUINO + // FIXME: portduino does not ever call onNetworkConnected so call it here because I don't know what happen if I call + // onNetworkConnected there + if (config.network.enabled_protocols & meshtastic_Config_NetworkConfig_ProtocolFlags_UDP_BROADCAST) { + udpThread->start(); + } +#endif #endif service = new MeshService(); service->init(); @@ -1248,6 +1274,19 @@ extern meshtastic_DeviceMetadata getDeviceMetadata() deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_AMBIENTLIGHTING_CONFIG; #endif +// No bluetooth on these targets (yet): +// Pico W / 2W may get it at some point +// Portduino and ESP32-C6 are excluded because we don't have a working bluetooth stacks integrated yet. +#if defined(ARCH_RP2040) || defined(ARCH_PORTDUINO) || defined(ARCH_STM32WL) || defined(CONFIG_IDF_TARGET_ESP32C6) + deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_BLUETOOTH_CONFIG; +#endif + +#if defined(ARCH_NRF52) && !HAS_ETHERNET // nrf52 doesn't have network unless it's a RAK ethernet gateway currently + deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_NETWORK_CONFIG; // No network on nRF52 +#elif defined(ARCH_RP2040) && !HAS_WIFI && !HAS_ETHERNET + deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_NETWORK_CONFIG; // No network on RP2040 +#endif + #if !(MESHTASTIC_EXCLUDE_PKI) deviceMetadata.hasPKC = true; #endif @@ -1296,5 +1335,4 @@ void loop() mainDelay.delay(delayMsec); } } - #endif diff --git a/src/mesh/Channels.cpp b/src/mesh/Channels.cpp index f1d4926db..4d061f80f 100644 --- a/src/mesh/Channels.cpp +++ b/src/mesh/Channels.cpp @@ -347,7 +347,7 @@ bool Channels::anyMqttEnabled() { #if USERPREFS_EVENT_MODE // Don't publish messages on the public MQTT broker if we are in event mode - if (mqtt && mqtt.isUsingDefaultServer()) { + if (mqtt && mqtt->isUsingDefaultServer()) { return false; } #endif diff --git a/src/mesh/CryptoEngine.cpp b/src/mesh/CryptoEngine.cpp index 4613a6218..d32b73855 100644 --- a/src/mesh/CryptoEngine.cpp +++ b/src/mesh/CryptoEngine.cpp @@ -161,10 +161,8 @@ void CryptoEngine::hash(uint8_t *bytes, size_t numBytes) void CryptoEngine::aesSetKey(const uint8_t *key_bytes, size_t key_len) { - if (aes) { - delete aes; - aes = nullptr; - } + delete aes; + aes = nullptr; if (key_len != 0) { aes = new AESSmall256(); aes->setKey(key_bytes, key_len); @@ -225,10 +223,8 @@ void CryptoEngine::decrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes // Generic implementation of AES-CTR encryption. void CryptoEngine::encryptAESCtr(CryptoKey _key, uint8_t *_nonce, size_t numBytes, uint8_t *bytes) { - if (ctr) { - delete ctr; - ctr = nullptr; - } + delete ctr; + ctr = nullptr; if (_key.length == 16) ctr = new CTR(); else diff --git a/src/mesh/MeshService.cpp b/src/mesh/MeshService.cpp index f293559ad..297c7b2ed 100644 --- a/src/mesh/MeshService.cpp +++ b/src/mesh/MeshService.cpp @@ -309,7 +309,10 @@ void MeshService::sendToPhone(meshtastic_MeshPacket *p) } } - assert(toPhoneQueue.enqueue(p, 0)); + if (toPhoneQueue.enqueue(p, 0) == false) { + LOG_CRIT("Failed to queue a packet into toPhoneQueue!"); + abort(); + } fromNum++; } @@ -323,7 +326,10 @@ void MeshService::sendMqttMessageToClientProxy(meshtastic_MqttClientProxyMessage releaseMqttClientProxyMessageToPool(d); } - assert(toPhoneMqttProxyQueue.enqueue(m, 0)); + if (toPhoneMqttProxyQueue.enqueue(m, 0) == false) { + LOG_CRIT("Failed to queue a packet into toPhoneMqttProxyQueue!"); + abort(); + } fromNum++; } @@ -337,7 +343,10 @@ void MeshService::sendClientNotification(meshtastic_ClientNotification *n) releaseClientNotificationToPool(d); } - assert(toPhoneClientNotificationQueue.enqueue(n, 0)); + if (toPhoneClientNotificationQueue.enqueue(n, 0) == false) { + LOG_CRIT("Failed to queue a notification into toPhoneClientNotificationQueue!"); + abort(); + } fromNum++; } diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index e8efa7566..3f79d18e6 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -51,6 +51,10 @@ #include #endif +#if defined(ARCH_ESP32) && !MESHTASTIC_EXCLUDE_WIFI +#include +#endif + NodeDB *nodeDB = nullptr; // we have plenty of ram so statically alloc this tempbuf (for now) @@ -624,6 +628,27 @@ void NodeDB::installDefaultConfig(bool preserveKey = false) meshtastic_Config_PositionConfig_PositionFlags_SPEED | meshtastic_Config_PositionConfig_PositionFlags_HEADING | meshtastic_Config_PositionConfig_PositionFlags_DOP | meshtastic_Config_PositionConfig_PositionFlags_SATINVIEW); +// Set default value for 'Mesh via UDP' +#if HAS_UDP_MULTICAST +#ifdef USERPREFS_NETWORK_ENABLED_PROTOCOLS + config.network.enabled_protocols = USERPREFS_NETWORK_ENABLED_PROTOCOLS; +#else + config.network.enabled_protocols = 1; +#endif +#endif + +#ifdef USERPREFS_NETWORK_WIFI_ENABLED + config.network.wifi_enabled = USERPREFS_NETWORK_WIFI_ENABLED; +#endif + +#ifdef USERPREFS_NETWORK_WIFI_SSID + strncpy(config.network.wifi_ssid, USERPREFS_NETWORK_WIFI_SSID, sizeof(config.network.wifi_ssid)); +#endif + +#ifdef USERPREFS_NETWORK_WIFI_PSK + strncpy(config.network.wifi_psk, USERPREFS_NETWORK_WIFI_PSK, sizeof(config.network.wifi_psk)); +#endif + #ifdef DISPLAY_FLIP_SCREEN config.display.flip_screen = true; #endif @@ -635,6 +660,12 @@ void NodeDB::installDefaultConfig(bool preserveKey = false) config.display.wake_on_tap_or_motion = true; #endif +#if defined(ARCH_ESP32) && !MESHTASTIC_EXCLUDE_WIFI + if (WiFiOTA::isUpdated()) { + WiFiOTA::recoverConfig(&config.network); + } +#endif + initConfigIntervals(); } @@ -1030,8 +1061,8 @@ void NodeDB::loadFromDisk() // if (state != LoadFileResult::LOAD_SUCCESS) { // installDefaultDeviceState(); // Our in RAM copy might now be corrupt //} else { - if (devicestate.version < DEVICESTATE_MIN_VER) { - LOG_WARN("Devicestate %d is old, discard", devicestate.version); + if ((state != LoadFileResult::LOAD_SUCCESS) || (devicestate.version < DEVICESTATE_MIN_VER)) { + LOG_WARN("Devicestate %d is old or invalid, discard", devicestate.version); installDefaultDeviceState(); } else { LOG_INFO("Loaded saved devicestate version %d", devicestate.version); @@ -1427,13 +1458,14 @@ bool NodeDB::updateUser(uint32_t nodeId, meshtastic_User &p, uint8_t channelInde #if !(MESHTASTIC_EXCLUDE_PKI) if (p.public_key.size > 0) { printBytes("Incoming Pubkey: ", p.public_key.bytes, 32); - if (info->user.public_key.size > 0) { // if we have a key for this user already, don't overwrite with a new one - LOG_INFO("Public Key set for node, not updating!"); - // we copy the key into the incoming packet, to prevent overwrite - memcpy(p.public_key.bytes, info->user.public_key.bytes, 32); - } else { - LOG_INFO("Update Node Pubkey!"); - } + } + if (info->user.public_key.size > 0) { // if we have a key for this user already, don't overwrite with a new one + LOG_INFO("Public Key set for node, not updating!"); + // we copy the key into the incoming packet, to prevent overwrite + p.public_key.size = 32; + memcpy(p.public_key.bytes, info->user.public_key.bytes, 32); + } else if (p.public_key.size > 0) { + LOG_INFO("Update Node Pubkey!"); } #endif diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 992f38ff4..b8b7ee610 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -188,7 +188,7 @@ ErrorCode Router::sendLocal(meshtastic_MeshPacket *p, RxSource src) // don't override if a channel was requested and no need to set it when PKI is enforced if (!p->channel && !p->pki_encrypted && !isBroadcast(p->to)) { - meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(p->to); + meshtastic_NodeInfoLite const *node = nodeDB->getMeshNode(p->to); if (node) { p->channel = node->channel; LOG_DEBUG("localSend to channel %d", p->channel); @@ -688,7 +688,7 @@ void Router::perhapsHandleReceived(meshtastic_MeshPacket *p) return; } - meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(p->from); + meshtastic_NodeInfoLite const *node = nodeDB->getMeshNode(p->from); if (node != NULL && node->is_ignored) { LOG_DEBUG("Ignore msg, 0x%x is ignored", p->from); packetPool.release(p); diff --git a/src/mesh/STM32WLE5JCInterface.cpp b/src/mesh/STM32WLE5JCInterface.cpp index ad1f675b6..6a340dd28 100644 --- a/src/mesh/STM32WLE5JCInterface.cpp +++ b/src/mesh/STM32WLE5JCInterface.cpp @@ -18,8 +18,10 @@ bool STM32WLE5JCInterface::init() { RadioLibInterface::init(); - // https://github.com/Seeed-Studio/LoRaWan-E5-Node/blob/main/Middlewares/Third_Party/SubGHz_Phy/stm32_radio_driver/radio_driver.c +// https://github.com/Seeed-Studio/LoRaWan-E5-Node/blob/main/Middlewares/Third_Party/SubGHz_Phy/stm32_radio_driver/radio_driver.c +#if (!defined(_VARIANT_RAK3172_)) setTCXOVoltage(1.7); +#endif lora.setRfSwitchTable(rfswitch_pins, rfswitch_table); @@ -42,4 +44,4 @@ bool STM32WLE5JCInterface::init() return res == RADIOLIB_ERR_NONE; } -#endif // ARCH_STM32WL \ No newline at end of file +#endif // ARCH_STM32WL diff --git a/src/mesh/generated/meshtastic/mesh.pb.h b/src/mesh/generated/meshtastic/mesh.pb.h index 991aeb8d2..defaaad28 100644 --- a/src/mesh/generated/meshtastic/mesh.pb.h +++ b/src/mesh/generated/meshtastic/mesh.pb.h @@ -235,6 +235,8 @@ typedef enum _meshtastic_HardwareModel { meshtastic_HardwareModel_THINKNODE_M2 = 90, /* Lilygo T-ETH-Elite */ meshtastic_HardwareModel_T_ETH_ELITE = 91, + /* Heltec HRI-3621 industrial probe */ + meshtastic_HardwareModel_HELTEC_SENSOR_HUB = 92, /* ------------------------------------------------------------------------------------------------------------------------------------------ Reserved ID For developing private Ports. These will show up in live traffic sparsely, so we can use a high number. Keep it within 8 bits. ------------------------------------------------------------------------------------------------------------------------------------------ */ @@ -324,7 +326,11 @@ typedef enum _meshtastic_ExcludedModules { /* Detection Sensor module */ meshtastic_ExcludedModules_DETECTIONSENSOR_CONFIG = 2048, /* Paxcounter module */ - meshtastic_ExcludedModules_PAXCOUNTER_CONFIG = 4096 + meshtastic_ExcludedModules_PAXCOUNTER_CONFIG = 4096, + /* Bluetooth config (not technically a module, but used to indicate bluetooth capabilities) */ + meshtastic_ExcludedModules_BLUETOOTH_CONFIG = 8192, + /* Network config (not technically a module, but used to indicate network capabilities) */ + meshtastic_ExcludedModules_NETWORK_CONFIG = 16384 } meshtastic_ExcludedModules; /* How the location was acquired: manual, onboard GPS, external (EUD) GPS */ @@ -1120,8 +1126,8 @@ extern "C" { #define _meshtastic_CriticalErrorCode_ARRAYSIZE ((meshtastic_CriticalErrorCode)(meshtastic_CriticalErrorCode_FLASH_CORRUPTION_UNRECOVERABLE+1)) #define _meshtastic_ExcludedModules_MIN meshtastic_ExcludedModules_EXCLUDED_NONE -#define _meshtastic_ExcludedModules_MAX meshtastic_ExcludedModules_PAXCOUNTER_CONFIG -#define _meshtastic_ExcludedModules_ARRAYSIZE ((meshtastic_ExcludedModules)(meshtastic_ExcludedModules_PAXCOUNTER_CONFIG+1)) +#define _meshtastic_ExcludedModules_MAX meshtastic_ExcludedModules_NETWORK_CONFIG +#define _meshtastic_ExcludedModules_ARRAYSIZE ((meshtastic_ExcludedModules)(meshtastic_ExcludedModules_NETWORK_CONFIG+1)) #define _meshtastic_Position_LocSource_MIN meshtastic_Position_LocSource_LOC_UNSET #define _meshtastic_Position_LocSource_MAX meshtastic_Position_LocSource_LOC_EXTERNAL diff --git a/src/mesh/mesh-pb-constants.h b/src/mesh/mesh-pb-constants.h index 1c86653dc..f748d295e 100644 --- a/src/mesh/mesh-pb-constants.h +++ b/src/mesh/mesh-pb-constants.h @@ -18,6 +18,10 @@ #define MAX_RX_TOPHONE 32 #endif +/// Verify baseline assumption of node size. If it increases, we need to reevaluate +/// the impact of its memory footprint, notably on MAX_NUM_NODES. +static_assert(sizeof(meshtastic_NodeInfoLite) <= 192, "NodeInfoLite size increased. Reconsider impact on MAX_NUM_NODES."); + /// max number of nodes allowed in the nodeDB #ifndef MAX_NUM_NODES #if defined(ARCH_STM32WL) diff --git a/src/mesh/udp/UdpMulticastThread.h b/src/mesh/udp/UdpMulticastThread.h index e5eb28d00..88824dc4d 100644 --- a/src/mesh/udp/UdpMulticastThread.h +++ b/src/mesh/udp/UdpMulticastThread.h @@ -22,8 +22,13 @@ class UdpMulticastThread : public concurrency::OSThread void start() { - if (udp.listenMulticast(udpIpAddress, UDP_MULTICAST_DEFAUL_PORT)) { + if (udp.listenMulticast(udpIpAddress, UDP_MULTICAST_DEFAUL_PORT, 64)) { +#ifndef ARCH_PORTDUINO + // FIXME(PORTDUINO): arduino lacks IPAddress::toString() LOG_DEBUG("UDP Listening on IP: %s", WiFi.localIP().toString().c_str()); +#else + LOG_DEBUG("UDP Listening"); +#endif udp.onPacket([this](AsyncUDPPacket packet) { onReceive(packet); }); } else { LOG_DEBUG("Failed to listen on UDP"); @@ -33,7 +38,10 @@ class UdpMulticastThread : public concurrency::OSThread void onReceive(AsyncUDPPacket packet) { size_t packetLength = packet.length(); +#ifndef ARCH_PORTDUINO + // FIXME(PORTDUINO): arduino lacks IPAddress::toString() LOG_DEBUG("UDP broadcast from: %s, len=%u", packet.remoteIP().toString().c_str(), packetLength); +#endif meshtastic_MeshPacket mp; LOG_DEBUG("Decoding MeshPacket from UDP len=%u", packetLength); bool isPacketDecoded = pb_decode_from_bytes(packet.data(), packetLength, &meshtastic_MeshPacket_msg, &mp); @@ -48,9 +56,14 @@ class UdpMulticastThread : public concurrency::OSThread bool onSend(const meshtastic_MeshPacket *mp) { - if (!mp || WiFi.status() != WL_CONNECTED) { + if (!mp || !udp) { return false; } +#ifndef ARCH_PORTDUINO + if (WiFi.status() != WL_CONNECTED) { + return false; + } +#endif LOG_DEBUG("Broadcasting packet over UDP (id=%u)", mp->id); uint8_t buffer[meshtastic_MeshPacket_size]; size_t encodedLength = pb_encode_to_bytes(buffer, sizeof(buffer), &meshtastic_MeshPacket_msg, mp); @@ -70,4 +83,4 @@ class UdpMulticastThread : public concurrency::OSThread IPAddress udpIpAddress; AsyncUDP udp; }; -#endif // ARCH_ESP32 \ No newline at end of file +#endif // HAS_UDP_MULTICAST \ No newline at end of file diff --git a/src/mesh/wifi/WiFiAPClient.cpp b/src/mesh/wifi/WiFiAPClient.cpp index 92388d52a..e050c2057 100644 --- a/src/mesh/wifi/WiFiAPClient.cpp +++ b/src/mesh/wifi/WiFiAPClient.cpp @@ -133,7 +133,7 @@ static void onNetworkConnected() } #if HAS_UDP_MULTICAST - if (udpThread) { + if (udpThread && config.network.enabled_protocols & meshtastic_Config_NetworkConfig_ProtocolFlags_UDP_BROADCAST) { udpThread->start(); } #endif @@ -163,7 +163,7 @@ static int32_t reconnectWiFi() delay(5000); if (!WiFi.isConnected()) { -#ifdef CONFIG_IDF_TARGET_ESP32C3 +#ifdef ARCH_ESP32 WiFi.mode(WIFI_MODE_NULL); WiFi.useStaticBuffers(true); WiFi.mode(WIFI_STA); diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index ae25ea3fc..88109bc78 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -10,6 +10,9 @@ #if defined(ARCH_ESP32) && !MESHTASTIC_EXCLUDE_BLUETOOTH #include "BleOta.h" #endif +#if defined(ARCH_ESP32) && !MESHTASTIC_EXCLUDE_WIFI +#include "WiFiOTA.h" +#endif #include "Router.h" #include "configuration.h" #include "main.h" @@ -194,19 +197,23 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta } case meshtastic_AdminMessage_reboot_ota_seconds_tag: { int32_t s = r->reboot_ota_seconds; -#if defined(ARCH_ESP32) && !MESHTASTIC_EXCLUDE_BLUETOOTH - if (BleOta::getOtaAppVersion().isEmpty()) { - LOG_INFO("No OTA firmware available, scheduling regular reboot in %d seconds", s); - screen->startAlert("Rebooting..."); - } else { +#if defined(ARCH_ESP32) +#if !MESHTASTIC_EXCLUDE_BLUETOOTH + if (!BleOta::getOtaAppVersion().isEmpty()) { screen->startFirmwareUpdateScreen(); BleOta::switchToOtaApp(); - LOG_INFO("Reboot to OTA in %d seconds", s); + LOG_INFO("Rebooting to BLE OTA"); } -#else - LOG_INFO("Not on ESP32, scheduling regular reboot in %d seconds", s); - screen->startAlert("Rebooting..."); #endif +#if !MESHTASTIC_EXCLUDE_WIFI + if (WiFiOTA::trySwitchToOTA()) { + screen->startFirmwareUpdateScreen(); + WiFiOTA::saveConfig(&config.network); + LOG_INFO("Rebooting to WiFi OTA"); + } +#endif +#endif + LOG_INFO("Reboot in %d seconds", s); rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000); break; } @@ -258,7 +265,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta disableBluetooth(); LOG_INFO("Commit transaction for edited settings"); hasOpenEditTransaction = false; - saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); + saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS | SEGMENT_NODEDATABASE); break; } case meshtastic_AdminMessage_get_device_connection_status_request_tag: { @@ -327,7 +334,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta node->position = TypeConversions::ConvertToPositionLite(r->set_fixed_position); nodeDB->setLocalPosition(r->set_fixed_position); config.position.fixed_position = true; - saveChanges(SEGMENT_DEVICESTATE | SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false); + saveChanges(SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false); #if !MESHTASTIC_EXCLUDE_GPS if (gps != nullptr) gps->enable(); @@ -340,7 +347,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta LOG_INFO("Client received remove_fixed_position command"); nodeDB->clearLocalPosition(); config.position.fixed_position = false; - saveChanges(SEGMENT_DEVICESTATE | SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false); + saveChanges(SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false); break; } case meshtastic_AdminMessage_set_time_only_tag: { @@ -567,7 +574,6 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c) config.has_position = true; config.position = c.payload_variant.position; // Save nodedb as well in case we got a fixed position packet - saveChanges(SEGMENT_DEVICESTATE, false); break; case meshtastic_Config_power_tag: LOG_INFO("Set config: Power"); diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index f386147d0..e2a4a970c 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -7,7 +7,9 @@ #include "input/SerialKeyboardImpl.h" #include "input/TrackballInterruptImpl1.h" #include "input/UpDownInterruptImpl1.h" +#if !MESHTASTIC_EXCLUDE_I2C #include "input/cardKbI2cImpl.h" +#endif #include "input/kbMatrixImpl.h" #endif #if !MESHTASTIC_EXCLUDE_ADMIN diff --git a/src/modules/RangeTestModule.cpp b/src/modules/RangeTestModule.cpp index cad1d51f1..6f3d69acf 100644 --- a/src/modules/RangeTestModule.cpp +++ b/src/modules/RangeTestModule.cpp @@ -31,7 +31,7 @@ uint32_t packetSequence = 0; int32_t RangeTestModule::runOnce() { -#if defined(ARCH_ESP32) || defined(ARCH_NRF52) +#if defined(ARCH_ESP32) || defined(ARCH_NRF52) || defined(ARCH_PORTDUINO) /* Uncomment the preferences below if you want to use the module @@ -130,7 +130,7 @@ void RangeTestModuleRadio::sendPayload(NodeNum dest, bool wantReplies) ProcessMessage RangeTestModuleRadio::handleReceived(const meshtastic_MeshPacket &mp) { -#if defined(ARCH_ESP32) || defined(ARCH_NRF52) +#if defined(ARCH_ESP32) || defined(ARCH_NRF52) || defined(ARCH_PORTDUINO) if (moduleConfig.range_test.enabled) { diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 811d1ec91..e088b4612 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -60,7 +60,7 @@ SerialModule *serialModule; SerialModuleRadio *serialModuleRadio; -#if defined(TTGO_T_ECHO) || defined(CANARYONE) || defined(MESHLINK) +#if defined(TTGO_T_ECHO) || defined(CANARYONE) || defined(MESHLINK) || defined(ELECROW_ThinkNode_M1) SerialModule::SerialModule() : StreamAPI(&Serial), concurrency::OSThread("Serial") {} static Print *serialPrint = &Serial; #elif defined(CONFIG_IDF_TARGET_ESP32C6) @@ -158,7 +158,7 @@ int32_t SerialModule::runOnce() Serial.begin(baud); Serial.setTimeout(moduleConfig.serial.timeout > 0 ? moduleConfig.serial.timeout : TIMEOUT); } -#elif !defined(TTGO_T_ECHO) && !defined(CANARYONE) && !defined(MESHLINK) +#elif !defined(TTGO_T_ECHO) && !defined(CANARYONE) && !defined(MESHLINK) && !defined(ELECROW_ThinkNode_M1) if (moduleConfig.serial.rxd && moduleConfig.serial.txd) { #ifdef ARCH_RP2040 Serial2.setFIFOSize(RX_BUFFER); @@ -214,7 +214,7 @@ int32_t SerialModule::runOnce() } } -#if !defined(TTGO_T_ECHO) && !defined(CANARYONE) && !defined(MESHLINK) +#if !defined(TTGO_T_ECHO) && !defined(CANARYONE) && !defined(MESHLINK) && !defined(ELECROW_ThinkNode_M1) else if ((moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_WS85)) { processWXSerial(); @@ -408,6 +408,49 @@ uint32_t SerialModule::getBaudRate() return BAUD; } +// Add this structure to help with parsing WindGust = 24.4 serial lines. +struct ParsedLine { + String name; + String value; +}; + +/** + * Parse a line of format "Name = Value" into name/value pair + * @param line Input line to parse + * @return ParsedLine containing name and value, or empty strings if parse failed + */ +ParsedLine parseLine(const char *line) +{ + ParsedLine result = {"", ""}; + + // Find equals sign + const char *equals = strchr(line, '='); + if (!equals) { + return result; + } + + // Extract name by copying substring + char nameBuf[64]; // Temporary buffer + size_t nameLen = equals - line; + if (nameLen >= sizeof(nameBuf)) { + nameLen = sizeof(nameBuf) - 1; + } + strncpy(nameBuf, line, nameLen); + nameBuf[nameLen] = '\0'; + + // Create trimmed name string + String name = String(nameBuf); + name.trim(); + + // Extract value after equals sign + String value = String(equals + 1); + value.trim(); + + result.name = name; + result.value = value; + return result; +} + /** * Process the received weather station serial data, extract wind, voltage, and temperature information, * calculate averages and send telemetry data over the mesh network. @@ -416,7 +459,8 @@ uint32_t SerialModule::getBaudRate() */ void SerialModule::processWXSerial() { -#if !defined(TTGO_T_ECHO) && !defined(CANARYONE) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(MESHLINK) +#if !defined(TTGO_T_ECHO) && !defined(CANARYONE) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(MESHLINK) && \ + !defined(ELECROW_ThinkNode_M1) static unsigned int lastAveraged = 0; static unsigned int averageIntervalMillis = 300000; // 5 minutes hard coded. static double dir_sum_sin = 0; @@ -452,6 +496,7 @@ void SerialModule::processWXSerial() // WindSpeed = 0.5 // WindGust = 0.6 // GXTS04Temp = 24.4 + // Temperature = 23.4 // WS80 // RainIntSum = 0 // Rain = 0.0 @@ -468,81 +513,56 @@ void SerialModule::processWXSerial() // Extract the current line char line[meshtastic_Constants_DATA_PAYLOAD_LEN]; memset(line, '\0', sizeof(line)); - memcpy(line, &serialBytes[lineStart], lineEnd - lineStart); - if (strstr(line, "Wind") != NULL) // we have a wind line - { - gotwind = true; - // Find the positions of "=" signs in the line - char *windDirPos = strstr(line, "WindDir = "); - char *windSpeedPos = strstr(line, "WindSpeed = "); - char *windGustPos = strstr(line, "WindGust = "); + if (lineEnd - lineStart < sizeof(line) - 1) { + memcpy(line, &serialBytes[lineStart], lineEnd - lineStart); - if (windDirPos != NULL) { - // Extract data after "=" for WindDir - strcpy(windDir, windDirPos + 15); // Add 15 to skip "WindDir = " - double radians = GeoCoord::toRadians(strtof(windDir, nullptr)); - dir_sum_sin += sin(radians); - dir_sum_cos += cos(radians); - dirCount++; - } else if (windSpeedPos != NULL) { - // Extract data after "=" for WindSpeed - strcpy(windVel, windSpeedPos + 15); // Add 15 to skip "WindSpeed = " - float newv = strtof(windVel, nullptr); - velSum += newv; - velCount++; - if (newv < lull || lull == -1) - lull = newv; - - } else if (windGustPos != NULL) { - strcpy(windGust, windGustPos + 15); // Add 15 to skip "WindSpeed = " - float newg = strtof(windGust, nullptr); - if (newg > gust) - gust = newg; - } - - // these are also voltage data we care about possibly - } else if (strstr(line, "BatVoltage") != NULL) { // we have a battVoltage line - char *batVoltagePos = strstr(line, "BatVoltage = "); - if (batVoltagePos != NULL) { - strcpy(batVoltage, batVoltagePos + 17); // 18 for ws 80, 17 for ws85 - batVoltageF = strtof(batVoltage, nullptr); - break; // last possible data we want so break - } - } else if (strstr(line, "CapVoltage") != NULL) { // we have a cappVoltage line - char *capVoltagePos = strstr(line, "CapVoltage = "); - if (capVoltagePos != NULL) { - strcpy(capVoltage, capVoltagePos + 17); // 18 for ws 80, 17 for ws85 - capVoltageF = strtof(capVoltage, nullptr); - } - // GXTS04Temp = 24.4 - } else if (strstr(line, "GXTS04Temp") != NULL) { // we have a temperature line - char *tempPos = strstr(line, "GXTS04Temp = "); - if (tempPos != NULL) { - strcpy(temperature, tempPos + 15); // 15 spaces for ws85 - temperatureF = strtof(temperature, nullptr); - } - - } else if (strstr(line, "RainIntSum") != NULL) { // we have a rainsum line - // LOG_INFO(line); - char *pos = strstr(line, "RainIntSum = "); - if (pos != NULL) { - strcpy(rainStr, pos + 17); // 17 spaces for ws85 - rainSum = int(strtof(rainStr, nullptr)); - } - - } else if (strstr(line, "Rain") != NULL) { // we have a rain line - if (strstr(line, "WaveRain") == NULL) { // skip WaveRain lines though. - // LOG_INFO(line); - char *pos = strstr(line, "Rain = "); - if (pos != NULL) { - strcpy(rainStr, pos + 17); // 17 spaces for ws85 + ParsedLine parsed = parseLine(line); + if (parsed.name.length() > 0) { + if (parsed.name == "WindDir") { + strlcpy(windDir, parsed.value.c_str(), sizeof(windDir)); + double radians = GeoCoord::toRadians(strtof(windDir, nullptr)); + dir_sum_sin += sin(radians); + dir_sum_cos += cos(radians); + dirCount++; + gotwind = true; + } else if (parsed.name == "WindSpeed") { + strlcpy(windVel, parsed.value.c_str(), sizeof(windVel)); + float newv = strtof(windVel, nullptr); + velSum += newv; + velCount++; + if (newv < lull || lull == -1) { + lull = newv; + } + gotwind = true; + } else if (parsed.name == "WindGust") { + strlcpy(windGust, parsed.value.c_str(), sizeof(windGust)); + float newg = strtof(windGust, nullptr); + if (newg > gust) { + gust = newg; + } + gotwind = true; + } else if (parsed.name == "BatVoltage") { + strlcpy(batVoltage, parsed.value.c_str(), sizeof(batVoltage)); + batVoltageF = strtof(batVoltage, nullptr); + break; // last possible data we want so break + } else if (parsed.name == "CapVoltage") { + strlcpy(capVoltage, parsed.value.c_str(), sizeof(capVoltage)); + capVoltageF = strtof(capVoltage, nullptr); + } else if (parsed.name == "GXTS04Temp" || parsed.name == "Temperature") { + strlcpy(temperature, parsed.value.c_str(), sizeof(temperature)); + temperatureF = strtof(temperature, nullptr); + } else if (parsed.name == "RainIntSum") { + strlcpy(rainStr, parsed.value.c_str(), sizeof(rainStr)); + rainSum = int(strtof(rainStr, nullptr)); + } else if (parsed.name == "Rain") { + strlcpy(rainStr, parsed.value.c_str(), sizeof(rainStr)); rain = strtof(rainStr, nullptr); } } - } - // Update lineStart for the next line - lineStart = lineEnd + 1; + // Update lineStart for the next line + lineStart = lineEnd + 1; + } } } break; @@ -554,7 +574,7 @@ void SerialModule::processWXSerial() } if (gotwind) { - LOG_INFO("WS85 : %i %.1fg%.1f %.1fv %.1fv %.1fC rain: %.1f, %i sum", atoi(windDir), strtof(windVel, nullptr), + LOG_INFO("WS8X : %i %.1fg%.1f %.1fv %.1fv %.1fC rain: %.1f, %i sum", atoi(windDir), strtof(windVel, nullptr), strtof(windGust, nullptr), batVoltageF, capVoltageF, temperatureF, rain, rainSum); } if (gotwind && !Throttle::isWithinTimespanMs(lastAveraged, averageIntervalMillis)) { @@ -604,7 +624,7 @@ void SerialModule::processWXSerial() m.variant.environment_metrics.wind_lull = lull; m.variant.environment_metrics.has_wind_lull = true; - LOG_INFO("WS85 Transmit speed=%fm/s, direction=%d , lull=%f, gust=%f, voltage=%f temperature=%f", + LOG_INFO("WS8X Transmit speed=%fm/s, direction=%d , lull=%f, gust=%f, voltage=%f temperature=%f", m.variant.environment_metrics.wind_speed, m.variant.environment_metrics.wind_direction, m.variant.environment_metrics.wind_lull, m.variant.environment_metrics.wind_gust, m.variant.environment_metrics.voltage, m.variant.environment_metrics.temperature); diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index 8835c985d..8c0507e77 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -98,7 +98,8 @@ int32_t EnvironmentTelemetryModule::runOnce() // moduleConfig.telemetry.environment_screen_enabled = 1; // moduleConfig.telemetry.environment_update_interval = 15; - if (!(moduleConfig.telemetry.environment_measurement_enabled || moduleConfig.telemetry.environment_screen_enabled)) { + if (!(moduleConfig.telemetry.environment_measurement_enabled || moduleConfig.telemetry.environment_screen_enabled || + ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE)) { // If this module is not enabled, and the user doesn't want the display screen don't waste any OSThread time on it return disable(); } @@ -107,7 +108,7 @@ int32_t EnvironmentTelemetryModule::runOnce() // This is the first time the OSThread library has called this function, so do some setup firstTime = 0; - if (moduleConfig.telemetry.environment_measurement_enabled) { + if (moduleConfig.telemetry.environment_measurement_enabled || ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE) { LOG_INFO("Environment Telemetry: init"); #ifdef SENSECAP_INDICATOR result = indicatorSensor.runOnce(); @@ -178,7 +179,7 @@ int32_t EnvironmentTelemetryModule::runOnce() return result == UINT32_MAX ? disable() : setStartDelay(); } else { // if we somehow got to a second run of this module with measurement disabled, then just wait forever - if (!moduleConfig.telemetry.environment_measurement_enabled) { + if (!moduleConfig.telemetry.environment_measurement_enabled && !ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE) { return disable(); } else { #if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR_EXTERNAL diff --git a/src/modules/Telemetry/EnvironmentTelemetry.h b/src/modules/Telemetry/EnvironmentTelemetry.h index 6e0f850ef..d70c063fc 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.h +++ b/src/modules/Telemetry/EnvironmentTelemetry.h @@ -3,6 +3,11 @@ #if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR #pragma once + +#ifndef ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE +#define ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE 0 +#endif + #include "../mesh/generated/meshtastic/telemetry.pb.h" #include "NodeDB.h" #include "ProtobufModule.h" diff --git a/src/motion/AccelerometerThread.h b/src/motion/AccelerometerThread.h index 6e517d6b0..dd6413d64 100755 --- a/src/motion/AccelerometerThread.h +++ b/src/motion/AccelerometerThread.h @@ -160,13 +160,11 @@ class AccelerometerThread : public concurrency::OSThread void clean() { isInitialised = false; - if (sensor != nullptr) { - delete sensor; - sensor = nullptr; - } + delete sensor; + sensor = nullptr; } }; #endif -#endif \ No newline at end of file +#endif diff --git a/src/platform/esp32/WiFiOTA.cpp b/src/platform/esp32/WiFiOTA.cpp new file mode 100644 index 000000000..eac124dda --- /dev/null +++ b/src/platform/esp32/WiFiOTA.cpp @@ -0,0 +1,92 @@ +#include "WiFiOTA.h" +#include "configuration.h" +#include +#include + +namespace WiFiOTA +{ + +static const char *nvsNamespace = "ota-wifi"; +static const char *appProjectName = "OTA-WiFi"; + +static bool updated = false; + +bool isUpdated() +{ + return updated; +} + +void initialize() +{ + Preferences prefs; + prefs.begin(nvsNamespace); + if (prefs.getBool("updated")) { + LOG_INFO("First boot after OTA update"); + updated = true; + prefs.putBool("updated", false); + } + prefs.end(); +} + +void recoverConfig(meshtastic_Config_NetworkConfig *network) +{ + LOG_INFO("Recovering WiFi settings after OTA update"); + + Preferences prefs; + prefs.begin(nvsNamespace, true); + String ssid = prefs.getString("ssid"); + String psk = prefs.getString("psk"); + prefs.end(); + + network->wifi_enabled = true; + strncpy(network->wifi_ssid, ssid.c_str(), sizeof(network->wifi_ssid)); + strncpy(network->wifi_psk, psk.c_str(), sizeof(network->wifi_psk)); +} + +void saveConfig(meshtastic_Config_NetworkConfig *network) +{ + LOG_INFO("Saving WiFi settings for upcoming OTA update"); + + Preferences prefs; + prefs.begin(nvsNamespace); + prefs.putString("ssid", network->wifi_ssid); + prefs.putString("psk", network->wifi_psk); + prefs.putBool("updated", false); + prefs.end(); +} + +const esp_partition_t *getAppPartition() +{ + return esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL); +} + +bool getAppDesc(const esp_partition_t *part, esp_app_desc_t *app_desc) +{ + if (esp_ota_get_partition_description(part, app_desc) != ESP_OK) + return false; + if (strcmp(app_desc->project_name, appProjectName) != 0) + return false; + return true; +} + +bool trySwitchToOTA() +{ + const esp_partition_t *part = getAppPartition(); + esp_app_desc_t app_desc; + if (!getAppDesc(part, &app_desc)) + return false; + if (esp_ota_set_boot_partition(part) != ESP_OK) + return false; + return true; +} + +String getVersion() +{ + const esp_partition_t *part = getAppPartition(); + esp_app_desc_t app_desc; + if (!getAppDesc(part, &app_desc)) + return String(); + return String(app_desc.version); +} + +} // namespace WiFiOTA diff --git a/src/platform/esp32/WiFiOTA.h b/src/platform/esp32/WiFiOTA.h new file mode 100644 index 000000000..61860ed5e --- /dev/null +++ b/src/platform/esp32/WiFiOTA.h @@ -0,0 +1,18 @@ +#ifndef WIFIOTA_H +#define WIFIOTA_H + +#include "mesh-pb-constants.h" +#include + +namespace WiFiOTA +{ +void initialize(); +bool isUpdated(); + +void recoverConfig(meshtastic_Config_NetworkConfig *network); +void saveConfig(meshtastic_Config_NetworkConfig *network); +bool trySwitchToOTA(); +String getVersion(); +} // namespace WiFiOTA + +#endif // WIFIOTA_H diff --git a/src/platform/esp32/architecture.h b/src/platform/esp32/architecture.h index e4f8b49a0..0af6d4d04 100644 --- a/src/platform/esp32/architecture.h +++ b/src/platform/esp32/architecture.h @@ -144,6 +144,8 @@ #define HW_VENDOR meshtastic_HardwareModel_HELTEC_HT62 #elif defined(EBYTE_ESP32_S3) #define HW_VENDOR meshtastic_HardwareModel_EBYTE_ESP32_S3 +#elif defined(ELECROW_ThinkNode_M2) +#define HW_VENDOR meshtastic_HardwareModel_THINKNODE_M2 #elif defined(ESP32_S3_PICO) #define HW_VENDOR meshtastic_HardwareModel_ESP32_S3_PICO #elif defined(SENSELORA_S3) @@ -178,6 +180,8 @@ #define HW_VENDOR meshtastic_HardwareModel_MESH_TAB #elif defined(T_ETH_ELITE) #define HW_VENDOR meshtastic_HardwareModel_T_ETH_ELITE +#elif defined(HELTEC_SENSOR_HUB) +#define HW_VENDOR meshtastic_HardwareModel_HELTEC_SENSOR_HUB #endif // ----------------------------------------------------------------------------- diff --git a/src/platform/esp32/main-esp32.cpp b/src/platform/esp32/main-esp32.cpp index 3b3557e95..ab1e5c922 100644 --- a/src/platform/esp32/main-esp32.cpp +++ b/src/platform/esp32/main-esp32.cpp @@ -9,6 +9,8 @@ #include "nimble/NimbleBluetooth.h" #endif +#include + #if HAS_WIFI #include "mesh/wifi/WiFiAPClient.h" #endif @@ -107,6 +109,11 @@ void esp32Setup() randomSeed(seed); */ +#ifdef POWER_FULL + pinMode(POWER_FULL, INPUT); + pinMode(7, INPUT); +#endif + LOG_DEBUG("Total heap: %d", ESP.getHeapSize()); LOG_DEBUG("Free heap: %d", ESP.getFreeHeap()); LOG_DEBUG("Total PSRAM: %d", ESP.getPsramSize()); @@ -139,12 +146,19 @@ void esp32Setup() #if !MESHTASTIC_EXCLUDE_BLUETOOTH String BLEOTA = BleOta::getOtaAppVersion(); if (BLEOTA.isEmpty()) { - LOG_INFO("No OTA firmware available"); + LOG_INFO("No BLE OTA firmware available"); } else { - LOG_INFO("OTA firmware version %s", BLEOTA.c_str()); + LOG_INFO("BLE OTA firmware version %s", BLEOTA.c_str()); } -#else - LOG_INFO("No OTA firmware available"); +#endif +#if !MESHTASTIC_EXCLUDE_WIFI + String version = WiFiOTA::getVersion(); + if (version.isEmpty()) { + LOG_INFO("No WiFi OTA firmware available"); + } else { + LOG_INFO("WiFi OTA firmware version %s", version.c_str()); + } + WiFiOTA::initialize(); #endif // enableModemSleep(); diff --git a/src/platform/nrf52/architecture.h b/src/platform/nrf52/architecture.h index bf7fce29a..4e8823063 100644 --- a/src/platform/nrf52/architecture.h +++ b/src/platform/nrf52/architecture.h @@ -53,6 +53,8 @@ #define HW_VENDOR meshtastic_HardwareModel_RAK4631 #elif defined(TTGO_T_ECHO) #define HW_VENDOR meshtastic_HardwareModel_T_ECHO +#elif defined(ELECROW_ThinkNode_M1) +#define HW_VENDOR meshtastic_HardwareModel_THINKNODE_M1 #elif defined(NANO_G2_ULTRA) #define HW_VENDOR meshtastic_HardwareModel_NANO_G2_ULTRA #elif defined(CANARYONE) @@ -75,6 +77,8 @@ #define HW_VENDOR meshtastic_HardwareModel_PRIVATE_HW #elif defined(HELTEC_T114) #define HW_VENDOR meshtastic_HardwareModel_HELTEC_MESH_NODE_T114 +#elif defined(MESHLINK) +#define HW_VENDOR meshtastic_HardwareModel_MESHLINK #elif defined(SEEED_XIAO_NRF52840_KIT) #define HW_VENDOR meshtastic_HardwareModel_XIAO_NRF52_KIT #else @@ -129,4 +133,4 @@ #if !defined(PIN_SERIAL_RX) && !defined(NRF52840_XXAA) // No serial ports on this board - ONLY use segger in memory console #define USE_SEGGER -#endif \ No newline at end of file +#endif diff --git a/src/platform/nrf52/main-nrf52.cpp b/src/platform/nrf52/main-nrf52.cpp index 8483d21c6..53971e95a 100644 --- a/src/platform/nrf52/main-nrf52.cpp +++ b/src/platform/nrf52/main-nrf52.cpp @@ -235,6 +235,14 @@ void nrf52InitSemiHosting() void nrf52Setup() { +#ifdef USB_CHECK + pinMode(USB_CHECK, INPUT); +#endif + +#ifdef ADC_V + pinMode(ADC_V, INPUT); +#endif + uint32_t why = NRF_POWER->RESETREAS; // per // https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.nrf52832.ps.v1.1%2Fpower.html @@ -275,9 +283,11 @@ void cpuDeepSleep(uint32_t msecToWake) Wire.end(); #endif SPI.end(); +#if SPI_INTERFACES_COUNT > 1 + SPI1.end(); +#endif // This may cause crashes as debug messages continue to flow. Serial.end(); - #ifdef PIN_SERIAL_RX1 Serial1.end(); #endif @@ -315,6 +325,31 @@ void cpuDeepSleep(uint32_t msecToWake) detachInterrupt(PIN_GPS_PPS); detachInterrupt(PIN_BUTTON1); #endif + +#ifdef ELECROW_ThinkNode_M1 + for (int pin = 0; pin < 48; pin++) { + if (pin == 17 || pin == 19 || pin == 20 || pin == 22 || pin == 23 || pin == 24 || pin == 25 || pin == 9 || pin == 10 || + pin == PIN_BUTTON1 || pin == PIN_BUTTON2) { + continue; + } + pinMode(pin, OUTPUT); + } + for (int pin = 0; pin < 48; pin++) { + if (pin == 17 || pin == 19 || pin == 20 || pin == 22 || pin == 23 || pin == 24 || pin == 25 || pin == 9 || pin == 10 || + pin == PIN_BUTTON1 || pin == PIN_BUTTON2) { + continue; + } + digitalWrite(pin, LOW); + } + for (int pin = 0; pin < 48; pin++) { + if (pin == 17 || pin == 19 || pin == 20 || pin == 22 || pin == 23 || pin == 24 || pin == 25 || pin == 9 || pin == 10 || + pin == PIN_BUTTON1 || pin == PIN_BUTTON2) { + continue; + } + NRF_GPIO->DIRCLR = (1 << pin); + } +#endif + // Sleepy trackers or sensors can low power "sleep" // Don't enter this if we're sleeping portMAX_DELAY, since that's a shutdown event if (msecToWake != portMAX_DELAY && @@ -333,6 +368,17 @@ void cpuDeepSleep(uint32_t msecToWake) // FIXME, use system off mode with ram retention for key state? // FIXME, use non-init RAM per // https://devzone.nordicsemi.com/f/nordic-q-a/48919/ram-retention-settings-with-softdevice-enabled + +#ifdef ELECROW_ThinkNode_M1 + nrf_gpio_cfg_input(PIN_BUTTON1, NRF_GPIO_PIN_PULLUP); // Configure the pin to be woken up as an input + nrf_gpio_pin_sense_t sense = NRF_GPIO_PIN_SENSE_LOW; + nrf_gpio_cfg_sense_set(PIN_BUTTON1, sense); + + nrf_gpio_cfg_input(PIN_BUTTON2, NRF_GPIO_PIN_PULLUP); + nrf_gpio_pin_sense_t sense1 = NRF_GPIO_PIN_SENSE_LOW; + nrf_gpio_cfg_sense_set(PIN_BUTTON2, sense1); +#endif + auto ok = sd_power_system_off(); if (ok != NRF_SUCCESS) { LOG_ERROR("FIXME: Ignoring soft device (EasyDMA pending?) and forcing system-off!"); diff --git a/src/platform/portduino/PortduinoGlue.cpp b/src/platform/portduino/PortduinoGlue.cpp index 9da65c92c..a4050e702 100644 --- a/src/platform/portduino/PortduinoGlue.cpp +++ b/src/platform/portduino/PortduinoGlue.cpp @@ -33,6 +33,7 @@ std::ofstream traceFile; Ch341Hal *ch341Hal = nullptr; char *configPath = nullptr; char *optionMac = nullptr; +bool forceSimulated = false; // FIXME - move setBluetoothEnable into a HALPlatform class void setBluetoothEnable(bool enable) @@ -61,6 +62,9 @@ static error_t parse_opt(int key, char *arg, struct argp_state *state) case 'c': configPath = arg; break; + case 's': + forceSimulated = true; + break; case 'h': optionMac = arg; break; @@ -78,6 +82,7 @@ void portduinoCustomInit() static struct argp_option options[] = {{"port", 'p', "PORT", 0, "The TCP port to use."}, {"config", 'c', "CONFIG_PATH", 0, "Full path of the .yaml config file to use."}, {"hwid", 'h', "HWID", 0, "The mac address to assign to this virtual machine"}, + {"sim", 's', 0, 0, "Run in Simulated radio mode"}, {0}}; static void *childArguments; static char doc[] = "Meshtastic native build."; @@ -157,7 +162,9 @@ void portduinoSetup() YAML::Node yamlConfig; - if (configPath != nullptr) { + if (forceSimulated == true) { + settingsMap[use_simradio] = true; + } else if (configPath != nullptr) { if (loadConfig(configPath)) { std::cout << "Using " << configPath << " as config file" << std::endl; } else { @@ -179,7 +186,12 @@ void portduinoSetup() exit(EXIT_FAILURE); } } else { - std::cout << "No 'config.yaml' found, running simulated." << std::endl; + std::cout << "No 'config.yaml' found..." << std::endl; + settingsMap[use_simradio] = true; + } + + if (settingsMap[use_simradio] == true) { + std::cout << "Running in simulated mode." << std::endl; settingsMap[maxnodes] = 200; // Default to 200 nodes settingsMap[logoutputlevel] = level_debug; // Default to debug // Set the random seed equal to TCPPort to have a different seed per instance @@ -197,6 +209,56 @@ void portduinoSetup() } } } + + // If LoRa `Module: auto` (default in config.yaml), + // attempt to auto config based on Product Strings + if (settingsMap[use_autoconf] == true) { + char autoconf_product[96] = {0}; + // Try CH341 + try { + std::cout << "autoconf: Looking for CH341 device..." << std::endl; + ch341Hal = + new Ch341Hal(0, settingsStrings[lora_usb_serial_num], settingsMap[lora_usb_vid], settingsMap[lora_usb_pid]); + ch341Hal->getProductString(autoconf_product, 95); + delete ch341Hal; + std::cout << "autoconf: Found CH341 device " << autoconf_product << std::endl; + } catch (...) { + std::cout << "autoconf: Could not locate CH341 device" << std::endl; + } + // Try Pi HAT+ + std::cout << "autoconf: Looking for Pi HAT+..." << std::endl; + if (access("/proc/device-tree/hat/product", R_OK) == 0) { + std::ifstream hatProductFile("/proc/device-tree/hat/product"); + if (hatProductFile.is_open()) { + hatProductFile.read(autoconf_product, 95); + hatProductFile.close(); + } + std::cout << "autoconf: Found Pi HAT+ " << autoconf_product << " at /proc/device-tree/hat/product" << std::endl; + } else { + std::cout << "autoconf: Could not locate Pi HAT+ at /proc/device-tree/hat/product" << std::endl; + } + // Load the config file based on the product string + if (strlen(autoconf_product) > 0) { + // From configProducts map in PortduinoGlue.h + std::string product_config = ""; + try { + product_config = configProducts.at(autoconf_product); + } catch (std::out_of_range &e) { + std::cerr << "autoconf: Unable to find config for " << autoconf_product << std::endl; + exit(EXIT_FAILURE); + } + if (loadConfig(("/etc/meshtasticd/available.d/" + product_config).c_str())) { + std::cout << "autoconf: Using " << product_config << " as config file for " << autoconf_product << std::endl; + } else { + std::cerr << "autoconf: Unable to use " << product_config << " as config file for " << autoconf_product + << std::endl; + exit(EXIT_FAILURE); + } + } else { + std::cerr << "autoconf: Could not locate any devices" << std::endl; + } + } + // if we're using a usermode driver, we need to initialize it here, to get a serial number back for mac address uint8_t dmac[6] = {0}; if (settingsStrings[spidev] == "ch341") { @@ -210,7 +272,10 @@ void portduinoSetup() } char serial[9] = {0}; ch341Hal->getSerialString(serial, 8); - std::cout << "Serial " << serial << std::endl; + std::cout << "CH341 Serial " << serial << std::endl; + char product_string[96] = {0}; + ch341Hal->getProductString(product_string, 95); + std::cout << "CH341 Product " << product_string << std::endl; if (strlen(serial) == 8 && settingsStrings[mac_address].length() < 12) { uint8_t hash[32] = {0}; memcpy(hash, serial, 8); @@ -355,8 +420,9 @@ bool loadConfig(const char *configPath) const struct { configNames cfgName; std::string strName; - } loraModules[] = {{use_rf95, "RF95"}, {use_sx1262, "sx1262"}, {use_sx1268, "sx1268"}, {use_sx1280, "sx1280"}, - {use_lr1110, "lr1110"}, {use_lr1120, "lr1120"}, {use_lr1121, "lr1121"}, {use_llcc68, "LLCC68"}}; + } loraModules[] = {{use_simradio, "sim"}, {use_autoconf, "auto"}, {use_rf95, "RF95"}, {use_sx1262, "sx1262"}, + {use_sx1268, "sx1268"}, {use_sx1280, "sx1280"}, {use_lr1110, "lr1110"}, {use_lr1120, "lr1120"}, + {use_lr1121, "lr1121"}, {use_llcc68, "LLCC68"}}; for (auto &loraModule : loraModules) { settingsMap[loraModule.cfgName] = false; } diff --git a/src/platform/portduino/PortduinoGlue.h b/src/platform/portduino/PortduinoGlue.h index a52ca88f8..a7aea1c3e 100644 --- a/src/platform/portduino/PortduinoGlue.h +++ b/src/platform/portduino/PortduinoGlue.h @@ -1,9 +1,18 @@ #pragma once #include #include +#include #include "platform/portduino/USBHal.h" +// Product strings for auto-configuration +// {"PRODUCT_STRING", "CONFIG.YAML"} +// YAML paths are relative to `meshtastic/available.d` +inline const std::unordered_map configProducts = {{"MESHTOAD", "lora-usb-meshtoad-e22.yaml"}, + {"MESHSTICK", "lora-meshstick-1262.yaml"}, + {"MESHADV-PI", "lora-MeshAdv-900M30S.yaml"}, + {"POWERPI", "lora-MeshAdv-900M30S.yaml"}}; + enum configNames { default_gpiochip, cs_pin, @@ -34,6 +43,8 @@ enum configNames { rf95_max_power, dio2_as_rf_switch, dio3_tcxo_voltage, + use_simradio, + use_autoconf, use_rf95, use_sx1262, use_sx1268, diff --git a/src/platform/portduino/USBHal.h b/src/platform/portduino/USBHal.h index 0d6b361f4..ce2a5cfd3 100644 --- a/src/platform/portduino/USBHal.h +++ b/src/platform/portduino/USBHal.h @@ -61,6 +61,12 @@ class Ch341Hal : public RadioLibHal strncpy(_serial, pinedio.serial_number, len); } + void getProductString(char *_product_string, size_t len) + { + len = len > 95 ? 95 : len; + strncpy(_product_string, pinedio.product_string, len); + } + void init() override {} void term() override {} diff --git a/src/platform/stm32wl/LittleFS.cpp b/src/platform/stm32wl/LittleFS.cpp new file mode 100644 index 000000000..40f32eca8 --- /dev/null +++ b/src/platform/stm32wl/LittleFS.cpp @@ -0,0 +1,198 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 hathach 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 "LittleFS.h" +#include "stm32wlxx_hal_flash.h" + +/********************************************************************************************************************** + * Macro definitions + **********************************************************************************************************************/ +/** This macro is used to suppress compiler messages about a parameter not being used in a function. */ +#define LFS_UNUSED(p) (void)((p)) + +#define STM32WL_PAGE_SIZE (FLASH_PAGE_SIZE) +#define STM32WL_PAGE_COUNT (FLASH_PAGE_NB) +#define STM32WL_FLASH_BASE (FLASH_BASE) + +/* + * FLASH_SIZE from stm32wle5xx.h will read the actual FLASH size from the chip. + * FLASH_END_ADDR is calculated from FLASH_SIZE. + * Use the last 28 KiB of the FLASH + */ +#define LFS_FLASH_TOTAL_SIZE (14 * 2048) /* needs to be a multiple of LFS_BLOCK_SIZE */ +#define LFS_BLOCK_SIZE (2048) +#define LFS_FLASH_ADDR_END (FLASH_END_ADDR) +#define LFS_FLASH_ADDR_BASE (LFS_FLASH_ADDR_END - LFS_FLASH_TOTAL_SIZE + 1) + +#if !CFG_DEBUG +#define _LFS_DBG(fmt, ...) +#else +#define _LFS_DBG(fmt, ...) printf("%s:%d (%s): " fmt "\n", __FILE__, __LINE__, __func__, __VA_ARGS__) +#endif + +//--------------------------------------------------------------------+ +// LFS Disk IO +//--------------------------------------------------------------------+ + +static int _internal_flash_read(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, void *buffer, lfs_size_t size) +{ + LFS_UNUSED(c); + + if (!buffer || !size) { + _LFS_DBG("%s Invalid parameter!\r\n", __func__); + return LFS_ERR_INVAL; + } + + lfs_block_t address = LFS_FLASH_ADDR_BASE + (block * STM32WL_PAGE_SIZE + off); + + memcpy(buffer, (void *)address, size); + + return LFS_ERR_OK; +} + +// Program a region in a block. The block must have previously +// been erased. Negative error codes are propogated to the user. +// May return LFS_ERR_CORRUPT if the block should be considered bad. +static int _internal_flash_prog(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, const void *buffer, lfs_size_t size) +{ + lfs_block_t address = LFS_FLASH_ADDR_BASE + (block * STM32WL_PAGE_SIZE + off); + HAL_StatusTypeDef hal_rc = HAL_OK; + uint32_t dw_count = size / 8; + uint64_t *bufp = (uint64_t *)buffer; + + LFS_UNUSED(c); + + _LFS_DBG("Programming %d bytes/%d doublewords at address 0x%08x/block %d, offset %d.", size, dw_count, address, block, off); + if (HAL_FLASH_Unlock() != HAL_OK) { + return LFS_ERR_IO; + } + for (uint32_t i = 0; i < dw_count; i++) { + if ((address < LFS_FLASH_ADDR_BASE) || (address > LFS_FLASH_ADDR_END)) { + _LFS_DBG("Wanted to program out of bound of FLASH: 0x%08x.\n", address); + HAL_FLASH_Lock(); + return LFS_ERR_INVAL; + } + hal_rc = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, address, *bufp); + if (hal_rc != HAL_OK) { + /* Error occurred while writing data in Flash memory. + * User can add here some code to deal with this error. + */ + _LFS_DBG("Program error at (0x%08x), 0x%X, error: 0x%08x\n", address, hal_rc, HAL_FLASH_GetError()); + } + address += 8; + bufp += 1; + } + if (HAL_FLASH_Lock() != HAL_OK) { + return LFS_ERR_IO; + } + + return hal_rc == HAL_OK ? LFS_ERR_OK : LFS_ERR_IO; // If HAL_OK, return LFS_ERR_OK, else return LFS_ERR_IO +} + +// Erase a block. A block must be erased before being programmed. +// The state of an erased block is undefined. Negative error codes +// are propogated to the user. +// May return LFS_ERR_CORRUPT if the block should be considered bad. +static int _internal_flash_erase(const struct lfs_config *c, lfs_block_t block) +{ + lfs_block_t address = LFS_FLASH_ADDR_BASE + (block * STM32WL_PAGE_SIZE); + HAL_StatusTypeDef hal_rc; + FLASH_EraseInitTypeDef EraseInitStruct = {.TypeErase = FLASH_TYPEERASE_PAGES, .Page = 0, .NbPages = 1}; + uint32_t PAGEError = 0; + + LFS_UNUSED(c); + + if ((address < LFS_FLASH_ADDR_BASE) || (address > LFS_FLASH_ADDR_END)) { + _LFS_DBG("Wanted to erase out of bound of FLASH: 0x%08x.\n", address); + return LFS_ERR_INVAL; + } + /* calculate the absolute page, i.e. what the ST wants */ + EraseInitStruct.Page = (address - STM32WL_FLASH_BASE) / STM32WL_PAGE_SIZE; + _LFS_DBG("Erasing block %d at 0x%08x... ", block, address); + HAL_FLASH_Unlock(); + hal_rc = HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError); + HAL_FLASH_Lock(); + + return hal_rc == HAL_OK ? LFS_ERR_OK : LFS_ERR_IO; // If HAL_OK, return LFS_ERR_OK, else return LFS_ERR_IO +} + +// Sync the state of the underlying block device. Negative error codes +// are propogated to the user. +static int _internal_flash_sync(const struct lfs_config *c) +{ + LFS_UNUSED(c); + // write function performs no caching. No need for sync. + + return LFS_ERR_OK; +} + +static struct lfs_config _InternalFSConfig = {.context = NULL, + + .read = _internal_flash_read, + .prog = _internal_flash_prog, + .erase = _internal_flash_erase, + .sync = _internal_flash_sync, + + .read_size = LFS_BLOCK_SIZE, + .prog_size = LFS_BLOCK_SIZE, + .block_size = LFS_BLOCK_SIZE, + .block_count = LFS_FLASH_TOTAL_SIZE / LFS_BLOCK_SIZE, + .lookahead = 128, + + .read_buffer = NULL, + .prog_buffer = NULL, + .lookahead_buffer = NULL, + .file_buffer = NULL}; + +LittleFS InternalFS; + +//--------------------------------------------------------------------+ +// +//--------------------------------------------------------------------+ + +LittleFS::LittleFS(void) : STM32_LittleFS(&_InternalFSConfig) {} + +bool LittleFS::begin(void) +{ + if (FLASH_BASE >= LFS_FLASH_ADDR_BASE) { + /* There is not enough space on this device for a filesystem. */ + return false; + } + // failed to mount, erase all pages then format and mount again + if (!STM32_LittleFS::begin()) { + // Erase all pages of internal flash region for Filesystem. + for (uint32_t addr = LFS_FLASH_ADDR_BASE; addr < (LFS_FLASH_ADDR_END + 1); addr += STM32WL_PAGE_SIZE) { + _internal_flash_erase(&_InternalFSConfig, (addr - LFS_FLASH_ADDR_BASE) / STM32WL_PAGE_SIZE); + } + + // lfs format + this->format(); + + // mount again if still failed, give up + if (!STM32_LittleFS::begin()) + return false; + } + + return true; +} diff --git a/src/platform/stm32wl/LittleFS.h b/src/platform/stm32wl/LittleFS.h new file mode 100644 index 000000000..6c3c47f91 --- /dev/null +++ b/src/platform/stm32wl/LittleFS.h @@ -0,0 +1,41 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 hathach for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef INTERNALFILESYSTEM_H_ +#define INTERNALFILESYSTEM_H_ + +#include "STM32_LittleFS.h" + +class LittleFS : public STM32_LittleFS +{ + public: + LittleFS(void); + + // overwrite to also perform low level format (sector erase of whole flash region) + bool begin(void); +}; + +extern LittleFS InternalFS; + +#endif /* INTERNALFILESYSTEM_H_ */ diff --git a/src/platform/stm32wl/STM32_LittleFS.cpp b/src/platform/stm32wl/STM32_LittleFS.cpp new file mode 100644 index 000000000..97e79e61e --- /dev/null +++ b/src/platform/stm32wl/STM32_LittleFS.cpp @@ -0,0 +1,283 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach 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 "STM32_LittleFS.h" +#include +#include + +#define memclr(buffer, size) memset(buffer, 0, size) +#define varclr(_var) memclr(_var, sizeof(*(_var))) + +using namespace STM32_LittleFS_Namespace; + +//--------------------------------------------------------------------+ +// Implementation +//--------------------------------------------------------------------+ + +STM32_LittleFS::STM32_LittleFS(void) : STM32_LittleFS(NULL) {} + +STM32_LittleFS::STM32_LittleFS(struct lfs_config *cfg) +{ + varclr(&_lfs); + _lfs_cfg = cfg; + _mounted = false; +} + +STM32_LittleFS::~STM32_LittleFS() {} + +// Initialize and mount the file system +// Return true if mounted successfully else probably corrupted. +// User should format the disk and try again +bool STM32_LittleFS::begin(struct lfs_config *cfg) +{ + _lockFS(); + + bool ret; + // not a loop, just an quick way to short-circuit on error + do { + if (_mounted) { + ret = true; + break; + } + if (cfg) { + _lfs_cfg = cfg; + } + if (nullptr == _lfs_cfg) { + ret = false; + break; + } + // actually attempt to mount, and log error if one occurs + int err = lfs_mount(&_lfs, _lfs_cfg); + PRINT_LFS_ERR(err); + _mounted = (err == LFS_ERR_OK); + ret = _mounted; + } while (0); + + _unlockFS(); + return ret; +} + +// Tear down and unmount file system +void STM32_LittleFS::end(void) +{ + _lockFS(); + + if (_mounted) { + _mounted = false; + int err = lfs_unmount(&_lfs); + PRINT_LFS_ERR(err); + (void)err; + } + + _unlockFS(); +} + +bool STM32_LittleFS::format(void) +{ + _lockFS(); + + int err = LFS_ERR_OK; + bool attemptMount = _mounted; + // not a loop, just an quick way to short-circuit on error + do { + // if already mounted: umount first -> format -> remount + if (_mounted) { + _mounted = false; + err = lfs_unmount(&_lfs); + if (LFS_ERR_OK != err) { + PRINT_LFS_ERR(err); + break; + } + } + err = lfs_format(&_lfs, _lfs_cfg); + if (LFS_ERR_OK != err) { + PRINT_LFS_ERR(err); + break; + } + + if (attemptMount) { + err = lfs_mount(&_lfs, _lfs_cfg); + if (LFS_ERR_OK != err) { + PRINT_LFS_ERR(err); + break; + } + _mounted = true; + } + // success! + } while (0); + + _unlockFS(); + return LFS_ERR_OK == err; +} + +// Open a file or folder +STM32_LittleFS_Namespace::File STM32_LittleFS::open(char const *filepath, uint8_t mode) +{ + // No lock is required here ... the File() object will synchronize with the mutex provided + return STM32_LittleFS_Namespace::File(filepath, mode, *this); +} + +// Check if file or folder exists +bool STM32_LittleFS::exists(char const *filepath) +{ + struct lfs_info info; + _lockFS(); + + bool ret = (0 == lfs_stat(&_lfs, filepath, &info)); + + _unlockFS(); + return ret; +} + +// Create a directory, create intermediate parent if needed +bool STM32_LittleFS::mkdir(char const *filepath) +{ + bool ret = true; + const char *slash = filepath; + if (slash[0] == '/') + slash++; // skip root '/' + + _lockFS(); + + // make intermediate parent directory(ies) + while (NULL != (slash = strchr(slash, '/'))) { + char parent[slash - filepath + 1] = {0}; + memcpy(parent, filepath, slash - filepath); + + int rc = lfs_mkdir(&_lfs, parent); + if (rc != LFS_ERR_OK && rc != LFS_ERR_EXIST) { + PRINT_LFS_ERR(rc); + ret = false; + break; + } + slash++; + } + // make the final requested directory + if (ret) { + int rc = lfs_mkdir(&_lfs, filepath); + if (rc != LFS_ERR_OK && rc != LFS_ERR_EXIST) { + PRINT_LFS_ERR(rc); + ret = false; + } + } + + _unlockFS(); + return ret; +} + +// Remove a file +bool STM32_LittleFS::remove(char const *filepath) +{ + _lockFS(); + + int err = lfs_remove(&_lfs, filepath); + PRINT_LFS_ERR(err); + + _unlockFS(); + return LFS_ERR_OK == err; +} + +// Rename a file +bool STM32_LittleFS::rename(char const *oldfilepath, char const *newfilepath) +{ + _lockFS(); + + int err = lfs_rename(&_lfs, oldfilepath, newfilepath); + PRINT_LFS_ERR(err); + + _unlockFS(); + return LFS_ERR_OK == err; +} + +// Remove a folder +bool STM32_LittleFS::rmdir(char const *filepath) +{ + _lockFS(); + + int err = lfs_remove(&_lfs, filepath); + PRINT_LFS_ERR(err); + + _unlockFS(); + return LFS_ERR_OK == err; +} + +// Remove a folder recursively +bool STM32_LittleFS::rmdir_r(char const *filepath) +{ + /* lfs is modified to remove non-empty folder, + According to below issue, comment these 2 line won't corrupt filesystem + at least when using LFS v1. If moving to LFS v2, see tracked issue + to see if issues (such as the orphans in threaded linked list) are resolved. + https://github.com/ARMmbed/littlefs/issues/43 + */ + _lockFS(); + + int err = lfs_remove(&_lfs, filepath); + PRINT_LFS_ERR(err); + + _unlockFS(); + return LFS_ERR_OK == err; +} + +//------------- Debug -------------// +#if CFG_DEBUG + +const char *dbg_strerr_lfs(int32_t err) +{ + switch (err) { + case LFS_ERR_OK: + return "LFS_ERR_OK"; + case LFS_ERR_IO: + return "LFS_ERR_IO"; + case LFS_ERR_CORRUPT: + return "LFS_ERR_CORRUPT"; + case LFS_ERR_NOENT: + return "LFS_ERR_NOENT"; + case LFS_ERR_EXIST: + return "LFS_ERR_EXIST"; + case LFS_ERR_NOTDIR: + return "LFS_ERR_NOTDIR"; + case LFS_ERR_ISDIR: + return "LFS_ERR_ISDIR"; + case LFS_ERR_NOTEMPTY: + return "LFS_ERR_NOTEMPTY"; + case LFS_ERR_BADF: + return "LFS_ERR_BADF"; + case LFS_ERR_INVAL: + return "LFS_ERR_INVAL"; + case LFS_ERR_NOSPC: + return "LFS_ERR_NOSPC"; + case LFS_ERR_NOMEM: + return "LFS_ERR_NOMEM"; + + default: + static char errcode[10]; + sprintf(errcode, "%ld", err); + return errcode; + } + + return NULL; +} + +#endif diff --git a/src/platform/stm32wl/STM32_LittleFS.h b/src/platform/stm32wl/STM32_LittleFS.h new file mode 100644 index 000000000..9460ffa81 --- /dev/null +++ b/src/platform/stm32wl/STM32_LittleFS.h @@ -0,0 +1,107 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef STM32_LITTLEFS_H_ +#define STM32_LITTLEFS_H_ + +#include + +// Internal Flash uses ARM Little FileSystem +// https://github.com/ARMmbed/littlefs +#include "../../freertosinc.h" // tied to FreeRTOS for serialization +#include "STM32_LittleFS_File.h" +#include "littlefs/lfs.h" + +class STM32_LittleFS +{ + public: + STM32_LittleFS(void); + explicit STM32_LittleFS(struct lfs_config *cfg); + virtual ~STM32_LittleFS(); + + bool begin(struct lfs_config *cfg = NULL); + void end(void); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + STM32_LittleFS_Namespace::File open(char const *filename, uint8_t mode = STM32_LittleFS_Namespace::FILE_O_READ); + + // Methods to determine if the requested file path exists. + bool exists(char const *filepath); + + // Create the requested directory hierarchy--if intermediate directories + // do not exist they will be created. + bool mkdir(char const *filepath); + + // Delete the file. + bool remove(char const *filepath); + + // Rename the file. + bool rename(char const *oldfilepath, char const *newfilepath); + + // Delete a folder (must be empty) + bool rmdir(char const *filepath); + + // Delete a folder (recursively) + bool rmdir_r(char const *filepath); + + // format file system + bool format(void); + + /*------------------------------------------------------------------*/ + /* INTERNAL USAGE ONLY + * Although declare as public, it is meant to be invoked by internal + * code. User should not call these directly + *------------------------------------------------------------------*/ + lfs_t *_getFS(void) { return &_lfs; } + void _lockFS(void) + { /* no-op */ + } + void _unlockFS(void) + { /* no-op */ + } + + protected: + bool _mounted; + struct lfs_config *_lfs_cfg; + lfs_t _lfs; +}; + +#if !CFG_DEBUG +#define VERIFY_LFS(...) _GET_3RD_ARG(__VA_ARGS__, VERIFY_ERR_2ARGS, VERIFY_ERR_1ARGS)(__VA_ARGS__, NULL) +#define PRINT_LFS_ERR(_err) +#else +#define VERIFY_LFS(...) _GET_3RD_ARG(__VA_ARGS__, VERIFY_ERR_2ARGS, VERIFY_ERR_1ARGS)(__VA_ARGS__, dbg_strerr_lfs) +#define PRINT_LFS_ERR(_err) \ + do { \ + if (_err) { \ + printf("%s:%d, LFS error: %d\n", __FILE__, __LINE__, _err); \ + } \ + } while (0) // LFS_ERR are of type int, VERIFY_MESS expects long_int + +const char *dbg_strerr_lfs(int32_t err); +#endif + +#endif /* STM32_LITTLEFS_H_ */ diff --git a/src/platform/stm32wl/STM32_LittleFS_File.cpp b/src/platform/stm32wl/STM32_LittleFS_File.cpp new file mode 100644 index 000000000..349187a02 --- /dev/null +++ b/src/platform/stm32wl/STM32_LittleFS_File.cpp @@ -0,0 +1,393 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach 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 "STM32_LittleFS.h" +#include + +#define rtos_malloc malloc +#define rtos_free free + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ + +using namespace STM32_LittleFS_Namespace; + +File::File(STM32_LittleFS &fs) +{ + _fs = &fs; + _is_dir = false; + _name[0] = 0; + _name[LFS_NAME_MAX] = 0; + _dir_path = NULL; + + _dir = NULL; + _file = NULL; +} + +File::File(char const *filename, uint8_t mode, STM32_LittleFS &fs) : File(fs) +{ + // public constructor calls public API open(), which will obtain the mutex + this->open(filename, mode); +} + +bool File::_open_file(char const *filepath, uint8_t mode) +{ + int flags = (mode == FILE_O_READ) ? LFS_O_RDONLY : (mode == FILE_O_WRITE) ? (LFS_O_RDWR | LFS_O_CREAT) : 0; + + if (flags) { + _file = (lfs_file_t *)rtos_malloc(sizeof(lfs_file_t)); + if (!_file) + return false; + + int rc = lfs_file_open(_fs->_getFS(), _file, filepath, flags); + + if (rc) { + // failed to open + PRINT_LFS_ERR(rc); + // free memory + rtos_free(_file); + _file = NULL; + return false; + } + + // move to end of file + if (mode == FILE_O_WRITE) + lfs_file_seek(_fs->_getFS(), _file, 0, LFS_SEEK_END); + + _is_dir = false; + } + + return true; +} + +bool File::_open_dir(char const *filepath) +{ + _dir = (lfs_dir_t *)rtos_malloc(sizeof(lfs_dir_t)); + if (!_dir) + return false; + + int rc = lfs_dir_open(_fs->_getFS(), _dir, filepath); + + if (rc) { + // failed to open + PRINT_LFS_ERR(rc); + // free memory + rtos_free(_dir); + _dir = NULL; + return false; + } + + _is_dir = true; + + _dir_path = (char *)rtos_malloc(strlen(filepath) + 1); + strcpy(_dir_path, filepath); + + return true; +} + +bool File::open(char const *filepath, uint8_t mode) +{ + bool ret = false; + _fs->_lockFS(); + + ret = this->_open(filepath, mode); + + _fs->_unlockFS(); + return ret; +} + +bool File::_open(char const *filepath, uint8_t mode) +{ + bool ret = false; + + // close if currently opened + if (this->isOpen()) + _close(); + + struct lfs_info info; + int rc = lfs_stat(_fs->_getFS(), filepath, &info); + + if (LFS_ERR_OK == rc) { + // file existed, open file or directory accordingly + ret = (info.type == LFS_TYPE_REG) ? _open_file(filepath, mode) : _open_dir(filepath); + } else if (LFS_ERR_NOENT == rc) { + // file not existed, only proceed with FILE_O_WRITE mode + if (mode == FILE_O_WRITE) + ret = _open_file(filepath, mode); + } else { + PRINT_LFS_ERR(rc); + } + + // save bare file name + if (ret) { + char const *splash = strrchr(filepath, '/'); + strncpy(_name, splash ? (splash + 1) : filepath, LFS_NAME_MAX); + } + return ret; +} + +size_t File::write(uint8_t ch) +{ + return write(&ch, 1); +} + +size_t File::write(uint8_t const *buf, size_t size) +{ + lfs_ssize_t wrcount = 0; + _fs->_lockFS(); + + if (!this->_is_dir) { + wrcount = lfs_file_write(_fs->_getFS(), _file, buf, size); + if (wrcount < 0) { + wrcount = 0; + } + } + + _fs->_unlockFS(); + return wrcount; +} + +int File::read(void) +{ + // this thin wrapper relies on called function to synchronize + int ret = -1; + uint8_t ch; + if (read(&ch, 1) > 0) { + ret = static_cast(ch); + } + return ret; +} + +int File::read(void *buf, uint16_t nbyte) +{ + int ret = 0; + _fs->_lockFS(); + + if (!this->_is_dir) { + ret = lfs_file_read(_fs->_getFS(), _file, buf, nbyte); + } + + _fs->_unlockFS(); + return ret; +} + +int File::peek(void) +{ + int ret = -1; + _fs->_lockFS(); + + if (!this->_is_dir) { + uint32_t pos = lfs_file_tell(_fs->_getFS(), _file); + uint8_t ch = 0; + if (lfs_file_read(_fs->_getFS(), _file, &ch, 1) > 0) { + ret = static_cast(ch); + } + (void)lfs_file_seek(_fs->_getFS(), _file, pos, LFS_SEEK_SET); + } + + _fs->_unlockFS(); + return ret; +} + +int File::available(void) +{ + int ret = 0; + _fs->_lockFS(); + + if (!this->_is_dir) { + uint32_t file_size = lfs_file_size(_fs->_getFS(), _file); + uint32_t pos = lfs_file_tell(_fs->_getFS(), _file); + ret = file_size - pos; + } + + _fs->_unlockFS(); + return ret; +} + +bool File::seek(uint32_t pos) +{ + bool ret = false; + _fs->_lockFS(); + + if (!this->_is_dir) { + ret = lfs_file_seek(_fs->_getFS(), _file, pos, LFS_SEEK_SET) >= 0; + } + + _fs->_unlockFS(); + return ret; +} + +uint32_t File::position(void) +{ + uint32_t ret = 0; + _fs->_lockFS(); + + if (!this->_is_dir) { + ret = lfs_file_tell(_fs->_getFS(), _file); + } + + _fs->_unlockFS(); + return ret; +} + +uint32_t File::size(void) +{ + uint32_t ret = 0; + _fs->_lockFS(); + + if (!this->_is_dir) { + ret = lfs_file_size(_fs->_getFS(), _file); + } + + _fs->_unlockFS(); + return ret; +} + +bool File::truncate(uint32_t pos) +{ + int32_t ret = LFS_ERR_ISDIR; + _fs->_lockFS(); + if (!this->_is_dir) { + ret = lfs_file_truncate(_fs->_getFS(), _file, pos); + } + _fs->_unlockFS(); + return (ret == 0); +} + +bool File::truncate(void) +{ + int32_t ret = LFS_ERR_ISDIR; + _fs->_lockFS(); + if (!this->_is_dir) { + uint32_t pos = lfs_file_tell(_fs->_getFS(), _file); + ret = lfs_file_truncate(_fs->_getFS(), _file, pos); + } + _fs->_unlockFS(); + return (ret == 0); +} + +void File::flush(void) +{ + _fs->_lockFS(); + + if (!this->_is_dir) { + lfs_file_sync(_fs->_getFS(), _file); + } + + _fs->_unlockFS(); + return; +} + +void File::close(void) +{ + _fs->_lockFS(); + this->_close(); + _fs->_unlockFS(); +} + +void File::_close(void) +{ + if (this->isOpen()) { + if (this->_is_dir) { + lfs_dir_close(_fs->_getFS(), _dir); + rtos_free(_dir); + _dir = NULL; + + if (this->_dir_path) + rtos_free(_dir_path); + _dir_path = NULL; + } else { + lfs_file_close(this->_fs->_getFS(), _file); + rtos_free(_file); + _file = NULL; + } + } +} + +File::operator bool(void) +{ + return isOpen(); +} + +bool File::isOpen(void) +{ + return (_file != NULL) || (_dir != NULL); +} + +// WARNING -- although marked as `const`, the values pointed +// to may change. For example, if the same File +// object has `open()` called with a different +// file or directory name, this same pointer will +// suddenly (unexpectedly?) have different values. +char const *File::name(void) +{ + return this->_name; +} + +bool File::isDirectory(void) +{ + return this->_is_dir; +} + +File File::openNextFile(uint8_t mode) +{ + _fs->_lockFS(); + + File ret(*_fs); + if (this->_is_dir) { + struct lfs_info info; + int rc; + + // lfs_dir_read returns 0 when reaching end of directory, 1 if found an entry + // Skip the "." and ".." entries ... + do { + rc = lfs_dir_read(_fs->_getFS(), _dir, &info); + } while (rc == 1 && (!strcmp(".", info.name) || !strcmp("..", info.name))); + + if (rc == 1) { + // string cat name with current folder + char filepath[strlen(_dir_path) + 1 + strlen(info.name) + 1]; // potential for significant stack usage + strcpy(filepath, _dir_path); + if (!(_dir_path[0] == '/' && _dir_path[1] == 0)) + strcat(filepath, "/"); // only add '/' if cwd is not root + strcat(filepath, info.name); + + (void)ret._open(filepath, mode); // return value is ignored ... caller is expected to check isOpened() + } else if (rc < 0) { + PRINT_LFS_ERR(rc); + } + } + _fs->_unlockFS(); + return ret; +} + +void File::rewindDirectory(void) +{ + _fs->_lockFS(); + if (this->_is_dir) { + lfs_dir_rewind(_fs->_getFS(), _dir); + } + _fs->_unlockFS(); +} diff --git a/src/platform/stm32wl/STM32_LittleFS_File.h b/src/platform/stm32wl/STM32_LittleFS_File.h new file mode 100644 index 000000000..2b48b02e0 --- /dev/null +++ b/src/platform/stm32wl/STM32_LittleFS_File.h @@ -0,0 +1,108 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach for Adafruit Industries + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef STM32_LITTLEFS_FILE_H_ +#define STM32_LITTLEFS_FILE_H_ + +#include "littlefs/lfs.h" + +// Forward declaration +class STM32_LittleFS; + +namespace STM32_LittleFS_Namespace +{ + +// avoid conflict with other FileSystem FILE_READ/FILE_WRITE +enum { + FILE_O_READ = 0, + FILE_O_WRITE = 1, +}; + +class File : public Stream +{ + public: + explicit File(STM32_LittleFS &fs); + File(char const *filename, uint8_t mode, STM32_LittleFS &fs); + + public: + bool open(char const *filename, uint8_t mode); + + //------------- Stream API -------------// + virtual size_t write(uint8_t ch); + virtual size_t write(uint8_t const *buf, size_t size); + size_t write(const char *str) + { + if (str == NULL) + return 0; + return write((const uint8_t *)str, strlen(str)); + } + size_t write(const char *buffer, size_t size) { return write((const uint8_t *)buffer, size); } + + virtual int read(void); + int read(void *buf, uint16_t nbyte); + + virtual int peek(void); + virtual int available(void); + virtual void flush(void); + + bool seek(uint32_t pos); + uint32_t position(void); + uint32_t size(void); + + bool truncate(uint32_t pos); + bool truncate(void); + + void close(void); + + operator bool(void); + + bool isOpen(void); + char const *name(void); + + bool isDirectory(void); + File openNextFile(uint8_t mode = FILE_O_READ); + void rewindDirectory(void); + + private: + STM32_LittleFS *_fs; + + bool _is_dir; + + union { + lfs_file_t *_file; + lfs_dir_t *_dir; + }; + + char *_dir_path; + char _name[LFS_NAME_MAX + 1]; + + bool _open(char const *filepath, uint8_t mode); + bool _open_file(char const *filepath, uint8_t mode); + bool _open_dir(char const *filepath); + void _close(void); +}; + +} // namespace STM32_LittleFS_Namespace + +#endif /* STM32_LITTLEFS_FILE_H_ */ diff --git a/src/platform/stm32wl/littlefs/lfs.c b/src/platform/stm32wl/littlefs/lfs.c new file mode 100644 index 000000000..5dc4c7669 --- /dev/null +++ b/src/platform/stm32wl/littlefs/lfs.c @@ -0,0 +1,2525 @@ +/* + * The little filesystem + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#include "lfs.h" +#include "lfs_util.h" + +#include + +/// Caching block device operations /// +static int lfs_cache_read(lfs_t *lfs, lfs_cache_t *rcache, const lfs_cache_t *pcache, lfs_block_t block, lfs_off_t off, + void *buffer, lfs_size_t size) +{ + uint8_t *data = buffer; + LFS_ASSERT(block < lfs->cfg->block_count); + + while (size > 0) { + if (pcache && block == pcache->block && off >= pcache->off && off < pcache->off + lfs->cfg->prog_size) { + // is already in pcache? + lfs_size_t diff = lfs_min(size, lfs->cfg->prog_size - (off - pcache->off)); + memcpy(data, &pcache->buffer[off - pcache->off], diff); + + data += diff; + off += diff; + size -= diff; + continue; + } + + if (block == rcache->block && off >= rcache->off && off < rcache->off + lfs->cfg->read_size) { + // is already in rcache? + lfs_size_t diff = lfs_min(size, lfs->cfg->read_size - (off - rcache->off)); + memcpy(data, &rcache->buffer[off - rcache->off], diff); + + data += diff; + off += diff; + size -= diff; + continue; + } + + if (off % lfs->cfg->read_size == 0 && size >= lfs->cfg->read_size) { + // bypass cache? + lfs_size_t diff = size - (size % lfs->cfg->read_size); + int err = lfs->cfg->read(lfs->cfg, block, off, data, diff); + if (err) { + return err; + } + + data += diff; + off += diff; + size -= diff; + continue; + } + + // load to cache, first condition can no longer fail + rcache->block = block; + rcache->off = off - (off % lfs->cfg->read_size); + int err = lfs->cfg->read(lfs->cfg, rcache->block, rcache->off, rcache->buffer, lfs->cfg->read_size); + if (err) { + return err; + } + } + + return 0; +} + +static int lfs_cache_cmp(lfs_t *lfs, lfs_cache_t *rcache, const lfs_cache_t *pcache, lfs_block_t block, lfs_off_t off, + const void *buffer, lfs_size_t size) +{ + const uint8_t *data = buffer; + + for (lfs_off_t i = 0; i < size; i++) { + uint8_t c; + int err = lfs_cache_read(lfs, rcache, pcache, block, off + i, &c, 1); + if (err) { + return err; + } + + if (c != data[i]) { + return false; + } + } + + return true; +} + +static int lfs_cache_crc(lfs_t *lfs, lfs_cache_t *rcache, const lfs_cache_t *pcache, lfs_block_t block, lfs_off_t off, + lfs_size_t size, uint32_t *crc) +{ + for (lfs_off_t i = 0; i < size; i++) { + uint8_t c; + int err = lfs_cache_read(lfs, rcache, pcache, block, off + i, &c, 1); + if (err) { + return err; + } + + lfs_crc(crc, &c, 1); + } + + return 0; +} + +static inline void lfs_cache_drop(lfs_t *lfs, lfs_cache_t *rcache) +{ + // do not zero, cheaper if cache is readonly or only going to be + // written with identical data (during relocates) + (void)lfs; + rcache->block = 0xffffffff; +} + +static inline void lfs_cache_zero(lfs_t *lfs, lfs_cache_t *pcache) +{ + // zero to avoid information leak + memset(pcache->buffer, 0xff, lfs->cfg->prog_size); + pcache->block = 0xffffffff; +} + +static int lfs_cache_flush(lfs_t *lfs, lfs_cache_t *pcache, lfs_cache_t *rcache) +{ + if (pcache->block != 0xffffffff) { + int err = lfs->cfg->prog(lfs->cfg, pcache->block, pcache->off, pcache->buffer, lfs->cfg->prog_size); + if (err) { + return err; + } + + if (rcache) { + int res = lfs_cache_cmp(lfs, rcache, NULL, pcache->block, pcache->off, pcache->buffer, lfs->cfg->prog_size); + if (res < 0) { + return res; + } + + if (!res) { + return LFS_ERR_CORRUPT; + } + } + + lfs_cache_zero(lfs, pcache); + } + + return 0; +} + +static int lfs_cache_prog(lfs_t *lfs, lfs_cache_t *pcache, lfs_cache_t *rcache, lfs_block_t block, lfs_off_t off, + const void *buffer, lfs_size_t size) +{ + const uint8_t *data = buffer; + LFS_ASSERT(block < lfs->cfg->block_count); + + while (size > 0) { + if (block == pcache->block && off >= pcache->off && off < pcache->off + lfs->cfg->prog_size) { + // is already in pcache? + lfs_size_t diff = lfs_min(size, lfs->cfg->prog_size - (off - pcache->off)); + memcpy(&pcache->buffer[off - pcache->off], data, diff); + + data += diff; + off += diff; + size -= diff; + + if (off % lfs->cfg->prog_size == 0) { + // eagerly flush out pcache if we fill up + int err = lfs_cache_flush(lfs, pcache, rcache); + if (err) { + return err; + } + } + + continue; + } + + // pcache must have been flushed, either by programming and + // entire block or manually flushing the pcache + LFS_ASSERT(pcache->block == 0xffffffff); + + if (off % lfs->cfg->prog_size == 0 && size >= lfs->cfg->prog_size) { + // bypass pcache? + lfs_size_t diff = size - (size % lfs->cfg->prog_size); + int err = lfs->cfg->prog(lfs->cfg, block, off, data, diff); + if (err) { + return err; + } + + if (rcache) { + int res = lfs_cache_cmp(lfs, rcache, NULL, block, off, data, diff); + if (res < 0) { + return res; + } + + if (!res) { + return LFS_ERR_CORRUPT; + } + } + + data += diff; + off += diff; + size -= diff; + continue; + } + + // prepare pcache, first condition can no longer fail + pcache->block = block; + pcache->off = off - (off % lfs->cfg->prog_size); + } + + return 0; +} + +/// General lfs block device operations /// +static int lfs_bd_read(lfs_t *lfs, lfs_block_t block, lfs_off_t off, void *buffer, lfs_size_t size) +{ + // if we ever do more than writes to alternating pairs, + // this may need to consider pcache + return lfs_cache_read(lfs, &lfs->rcache, NULL, block, off, buffer, size); +} + +static int lfs_bd_prog(lfs_t *lfs, lfs_block_t block, lfs_off_t off, const void *buffer, lfs_size_t size) +{ + return lfs_cache_prog(lfs, &lfs->pcache, NULL, block, off, buffer, size); +} + +static int lfs_bd_cmp(lfs_t *lfs, lfs_block_t block, lfs_off_t off, const void *buffer, lfs_size_t size) +{ + return lfs_cache_cmp(lfs, &lfs->rcache, NULL, block, off, buffer, size); +} + +static int lfs_bd_crc(lfs_t *lfs, lfs_block_t block, lfs_off_t off, lfs_size_t size, uint32_t *crc) +{ + return lfs_cache_crc(lfs, &lfs->rcache, NULL, block, off, size, crc); +} + +static int lfs_bd_erase(lfs_t *lfs, lfs_block_t block) +{ + return lfs->cfg->erase(lfs->cfg, block); +} + +static int lfs_bd_sync(lfs_t *lfs) +{ + lfs_cache_drop(lfs, &lfs->rcache); + + int err = lfs_cache_flush(lfs, &lfs->pcache, NULL); + if (err) { + return err; + } + + return lfs->cfg->sync(lfs->cfg); +} + +/// Internal operations predeclared here /// +int lfs_traverse(lfs_t *lfs, int (*cb)(void *, lfs_block_t), void *data); +static int lfs_pred(lfs_t *lfs, const lfs_block_t dir[2], lfs_dir_t *pdir); +static int lfs_parent(lfs_t *lfs, const lfs_block_t dir[2], lfs_dir_t *parent, lfs_entry_t *entry); +static int lfs_moved(lfs_t *lfs, const void *e); +static int lfs_relocate(lfs_t *lfs, const lfs_block_t oldpair[2], const lfs_block_t newpair[2]); +int lfs_deorphan(lfs_t *lfs); + +/// Block allocator /// +static int lfs_alloc_lookahead(void *p, lfs_block_t block) +{ + lfs_t *lfs = p; + + lfs_block_t off = ((block - lfs->free.off) + lfs->cfg->block_count) % lfs->cfg->block_count; + + if (off < lfs->free.size) { + lfs->free.buffer[off / 32] |= 1U << (off % 32); + } + + return 0; +} + +static int lfs_alloc(lfs_t *lfs, lfs_block_t *block) +{ + while (true) { + while (lfs->free.i != lfs->free.size) { + lfs_block_t off = lfs->free.i; + lfs->free.i += 1; + lfs->free.ack -= 1; + + if (!(lfs->free.buffer[off / 32] & (1U << (off % 32)))) { + // found a free block + *block = (lfs->free.off + off) % lfs->cfg->block_count; + + // eagerly find next off so an alloc ack can + // discredit old lookahead blocks + while (lfs->free.i != lfs->free.size && (lfs->free.buffer[lfs->free.i / 32] & (1U << (lfs->free.i % 32)))) { + lfs->free.i += 1; + lfs->free.ack -= 1; + } + + return 0; + } + } + + // check if we have looked at all blocks since last ack + if (lfs->free.ack == 0) { + LFS_WARN("No more free space %" PRIu32, lfs->free.i + lfs->free.off); + return LFS_ERR_NOSPC; + } + + lfs->free.off = (lfs->free.off + lfs->free.size) % lfs->cfg->block_count; + lfs->free.size = lfs_min(lfs->cfg->lookahead, lfs->free.ack); + lfs->free.i = 0; + + // find mask of free blocks from tree + memset(lfs->free.buffer, 0, lfs->cfg->lookahead / 8); + int err = lfs_traverse(lfs, lfs_alloc_lookahead, lfs); + if (err) { + return err; + } + } +} + +static void lfs_alloc_ack(lfs_t *lfs) +{ + lfs->free.ack = lfs->cfg->block_count; +} + +/// Endian swapping functions /// +static void lfs_dir_fromle32(struct lfs_disk_dir *d) +{ + d->rev = lfs_fromle32(d->rev); + d->size = lfs_fromle32(d->size); + d->tail[0] = lfs_fromle32(d->tail[0]); + d->tail[1] = lfs_fromle32(d->tail[1]); +} + +static void lfs_dir_tole32(struct lfs_disk_dir *d) +{ + d->rev = lfs_tole32(d->rev); + d->size = lfs_tole32(d->size); + d->tail[0] = lfs_tole32(d->tail[0]); + d->tail[1] = lfs_tole32(d->tail[1]); +} + +static void lfs_entry_fromle32(struct lfs_disk_entry *d) +{ + d->u.dir[0] = lfs_fromle32(d->u.dir[0]); + d->u.dir[1] = lfs_fromle32(d->u.dir[1]); +} + +static void lfs_entry_tole32(struct lfs_disk_entry *d) +{ + d->u.dir[0] = lfs_tole32(d->u.dir[0]); + d->u.dir[1] = lfs_tole32(d->u.dir[1]); +} + +static void lfs_superblock_fromle32(struct lfs_disk_superblock *d) +{ + d->root[0] = lfs_fromle32(d->root[0]); + d->root[1] = lfs_fromle32(d->root[1]); + d->block_size = lfs_fromle32(d->block_size); + d->block_count = lfs_fromle32(d->block_count); + d->version = lfs_fromle32(d->version); +} + +static void lfs_superblock_tole32(struct lfs_disk_superblock *d) +{ + d->root[0] = lfs_tole32(d->root[0]); + d->root[1] = lfs_tole32(d->root[1]); + d->block_size = lfs_tole32(d->block_size); + d->block_count = lfs_tole32(d->block_count); + d->version = lfs_tole32(d->version); +} + +/// Metadata pair and directory operations /// +static inline void lfs_pairswap(lfs_block_t pair[2]) +{ + lfs_block_t t = pair[0]; + pair[0] = pair[1]; + pair[1] = t; +} + +static inline bool lfs_pairisnull(const lfs_block_t pair[2]) +{ + return pair[0] == 0xffffffff || pair[1] == 0xffffffff; +} + +static inline int lfs_paircmp(const lfs_block_t paira[2], const lfs_block_t pairb[2]) +{ + return !(paira[0] == pairb[0] || paira[1] == pairb[1] || paira[0] == pairb[1] || paira[1] == pairb[0]); +} + +static inline bool lfs_pairsync(const lfs_block_t paira[2], const lfs_block_t pairb[2]) +{ + return (paira[0] == pairb[0] && paira[1] == pairb[1]) || (paira[0] == pairb[1] && paira[1] == pairb[0]); +} + +static inline lfs_size_t lfs_entry_size(const lfs_entry_t *entry) +{ + return 4 + entry->d.elen + entry->d.alen + entry->d.nlen; +} + +static int lfs_dir_alloc(lfs_t *lfs, lfs_dir_t *dir) +{ + // allocate pair of dir blocks + for (int i = 0; i < 2; i++) { + int err = lfs_alloc(lfs, &dir->pair[i]); + if (err) { + return err; + } + } + + // rather than clobbering one of the blocks we just pretend + // the revision may be valid + int err = lfs_bd_read(lfs, dir->pair[0], 0, &dir->d.rev, 4); + if (err && err != LFS_ERR_CORRUPT) { + return err; + } + + if (err != LFS_ERR_CORRUPT) { + dir->d.rev = lfs_fromle32(dir->d.rev); + } + + // set defaults + dir->d.rev += 1; + dir->d.size = sizeof(dir->d) + 4; + dir->d.tail[0] = 0xffffffff; + dir->d.tail[1] = 0xffffffff; + dir->off = sizeof(dir->d); + + // don't write out yet, let caller take care of that + return 0; +} + +static int lfs_dir_fetch(lfs_t *lfs, lfs_dir_t *dir, const lfs_block_t pair[2]) +{ + // copy out pair, otherwise may be aliasing dir + const lfs_block_t tpair[2] = {pair[0], pair[1]}; + bool valid = false; + + // check both blocks for the most recent revision + for (int i = 0; i < 2; i++) { + struct lfs_disk_dir test; + int err = lfs_bd_read(lfs, tpair[i], 0, &test, sizeof(test)); + lfs_dir_fromle32(&test); + if (err) { + if (err == LFS_ERR_CORRUPT) { + continue; + } + return err; + } + + if (valid && lfs_scmp(test.rev, dir->d.rev) < 0) { + continue; + } + + if ((0x7fffffff & test.size) < sizeof(test) + 4 || (0x7fffffff & test.size) > lfs->cfg->block_size) { + continue; + } + + uint32_t crc = 0xffffffff; + lfs_dir_tole32(&test); + lfs_crc(&crc, &test, sizeof(test)); + lfs_dir_fromle32(&test); + err = lfs_bd_crc(lfs, tpair[i], sizeof(test), (0x7fffffff & test.size) - sizeof(test), &crc); + if (err) { + if (err == LFS_ERR_CORRUPT) { + continue; + } + return err; + } + + if (crc != 0) { + continue; + } + + valid = true; + + // setup dir in case it's valid + dir->pair[0] = tpair[(i + 0) % 2]; + dir->pair[1] = tpair[(i + 1) % 2]; + dir->off = sizeof(dir->d); + dir->d = test; + } + + if (!valid) { + LFS_ERROR("Corrupted dir pair at %" PRIu32 " %" PRIu32, tpair[0], tpair[1]); + return LFS_ERR_CORRUPT; + } + + return 0; +} + +struct lfs_region { + lfs_off_t oldoff; + lfs_size_t oldlen; + const void *newdata; + lfs_size_t newlen; +}; + +static int lfs_dir_commit(lfs_t *lfs, lfs_dir_t *dir, const struct lfs_region *regions, int count) +{ + // increment revision count + dir->d.rev += 1; + + // keep pairs in order such that pair[0] is most recent + lfs_pairswap(dir->pair); + for (int i = 0; i < count; i++) { + dir->d.size += regions[i].newlen - regions[i].oldlen; + } + + const lfs_block_t oldpair[2] = {dir->pair[0], dir->pair[1]}; + bool relocated = false; + + while (true) { + + int err = lfs_bd_erase(lfs, dir->pair[0]); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + uint32_t crc = 0xffffffff; + lfs_dir_tole32(&dir->d); + lfs_crc(&crc, &dir->d, sizeof(dir->d)); + err = lfs_bd_prog(lfs, dir->pair[0], 0, &dir->d, sizeof(dir->d)); + lfs_dir_fromle32(&dir->d); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + int i = 0; + lfs_off_t oldoff = sizeof(dir->d); + lfs_off_t newoff = sizeof(dir->d); + while (newoff < (0x7fffffff & dir->d.size) - 4) { + if (i < count && regions[i].oldoff == oldoff) { + lfs_crc(&crc, regions[i].newdata, regions[i].newlen); + err = lfs_bd_prog(lfs, dir->pair[0], newoff, regions[i].newdata, regions[i].newlen); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + oldoff += regions[i].oldlen; + newoff += regions[i].newlen; + i += 1; + } else { + uint8_t data; + err = lfs_bd_read(lfs, oldpair[1], oldoff, &data, 1); + if (err) { + return err; + } + + lfs_crc(&crc, &data, 1); + err = lfs_bd_prog(lfs, dir->pair[0], newoff, &data, 1); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + oldoff += 1; + newoff += 1; + } + } + + crc = lfs_tole32(crc); + err = lfs_bd_prog(lfs, dir->pair[0], newoff, &crc, 4); + crc = lfs_fromle32(crc); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + err = lfs_bd_sync(lfs); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + // successful commit, check checksum to make sure + uint32_t ncrc = 0xffffffff; + err = lfs_bd_crc(lfs, dir->pair[0], 0, (0x7fffffff & dir->d.size) - 4, &ncrc); + if (err) { + return err; + } + + if (ncrc != crc) { + goto relocate; + } + + break; + relocate: + // commit was corrupted + LFS_DEBUG("Bad block at %" PRIu32, dir->pair[0]); + + // drop caches and prepare to relocate block + relocated = true; + lfs_cache_drop(lfs, &lfs->pcache); + + // can't relocate superblock, filesystem is now frozen + if (lfs_paircmp(oldpair, (const lfs_block_t[2]){0, 1}) == 0) { + LFS_WARN("Superblock %" PRIu32 " has become unwritable", oldpair[0]); + return LFS_ERR_CORRUPT; + } + + // relocate half of pair + err = lfs_alloc(lfs, &dir->pair[0]); + if (err) { + return err; + } + } + + if (relocated) { + // update references if we relocated + LFS_DEBUG("Relocating %" PRIu32 " %" PRIu32 " to %" PRIu32 " %" PRIu32, oldpair[0], oldpair[1], dir->pair[0], + dir->pair[1]); + int err = lfs_relocate(lfs, oldpair, dir->pair); + if (err) { + return err; + } + } + + // shift over any directories that are affected + for (lfs_dir_t *d = lfs->dirs; d; d = d->next) { + if (lfs_paircmp(d->pair, dir->pair) == 0) { + d->pair[0] = dir->pair[0]; + d->pair[1] = dir->pair[1]; + } + } + + return 0; +} + +static int lfs_dir_update(lfs_t *lfs, lfs_dir_t *dir, lfs_entry_t *entry, const void *data) +{ + lfs_entry_tole32(&entry->d); + int err = lfs_dir_commit(lfs, dir, + (struct lfs_region[]){{entry->off, sizeof(entry->d), &entry->d, sizeof(entry->d)}, + {entry->off + sizeof(entry->d), entry->d.nlen, data, entry->d.nlen}}, + data ? 2 : 1); + lfs_entry_fromle32(&entry->d); + return err; +} + +static int lfs_dir_append(lfs_t *lfs, lfs_dir_t *dir, lfs_entry_t *entry, const void *data) +{ + // check if we fit, if top bit is set we do not and move on + while (true) { + if (dir->d.size + lfs_entry_size(entry) <= lfs->cfg->block_size) { + entry->off = dir->d.size - 4; + + lfs_entry_tole32(&entry->d); + int err = lfs_dir_commit( + lfs, dir, + (struct lfs_region[]){{entry->off, 0, &entry->d, sizeof(entry->d)}, {entry->off, 0, data, entry->d.nlen}}, 2); + lfs_entry_fromle32(&entry->d); + return err; + } + + // we need to allocate a new dir block + if (!(0x80000000 & dir->d.size)) { + lfs_dir_t olddir = *dir; + int err = lfs_dir_alloc(lfs, dir); + if (err) { + return err; + } + + dir->d.tail[0] = olddir.d.tail[0]; + dir->d.tail[1] = olddir.d.tail[1]; + entry->off = dir->d.size - 4; + lfs_entry_tole32(&entry->d); + err = lfs_dir_commit( + lfs, dir, + (struct lfs_region[]){{entry->off, 0, &entry->d, sizeof(entry->d)}, {entry->off, 0, data, entry->d.nlen}}, 2); + lfs_entry_fromle32(&entry->d); + if (err) { + return err; + } + + olddir.d.size |= 0x80000000; + olddir.d.tail[0] = dir->pair[0]; + olddir.d.tail[1] = dir->pair[1]; + return lfs_dir_commit(lfs, &olddir, NULL, 0); + } + + int err = lfs_dir_fetch(lfs, dir, dir->d.tail); + if (err) { + return err; + } + } +} + +static int lfs_dir_remove(lfs_t *lfs, lfs_dir_t *dir, lfs_entry_t *entry) +{ + // check if we should just drop the directory block + if ((dir->d.size & 0x7fffffff) == sizeof(dir->d) + 4 + lfs_entry_size(entry)) { + lfs_dir_t pdir; + int res = lfs_pred(lfs, dir->pair, &pdir); + if (res < 0) { + return res; + } + + if (pdir.d.size & 0x80000000) { + pdir.d.size &= dir->d.size | 0x7fffffff; + pdir.d.tail[0] = dir->d.tail[0]; + pdir.d.tail[1] = dir->d.tail[1]; + return lfs_dir_commit(lfs, &pdir, NULL, 0); + } + } + + // shift out the entry + int err = lfs_dir_commit(lfs, dir, + (struct lfs_region[]){ + {entry->off, lfs_entry_size(entry), NULL, 0}, + }, + 1); + if (err) { + return err; + } + + // shift over any files/directories that are affected + for (lfs_file_t *f = lfs->files; f; f = f->next) { + if (lfs_paircmp(f->pair, dir->pair) == 0) { + if (f->poff == entry->off) { + f->pair[0] = 0xffffffff; + f->pair[1] = 0xffffffff; + } else if (f->poff > entry->off) { + f->poff -= lfs_entry_size(entry); + } + } + } + + for (lfs_dir_t *d = lfs->dirs; d; d = d->next) { + if (lfs_paircmp(d->pair, dir->pair) == 0) { + if (d->off > entry->off) { + d->off -= lfs_entry_size(entry); + d->pos -= lfs_entry_size(entry); + } + } + } + + return 0; +} + +static int lfs_dir_next(lfs_t *lfs, lfs_dir_t *dir, lfs_entry_t *entry) +{ + while (dir->off + sizeof(entry->d) > (0x7fffffff & dir->d.size) - 4) { + if (!(0x80000000 & dir->d.size)) { + entry->off = dir->off; + return LFS_ERR_NOENT; + } + + int err = lfs_dir_fetch(lfs, dir, dir->d.tail); + if (err) { + return err; + } + + dir->off = sizeof(dir->d); + dir->pos += sizeof(dir->d) + 4; + } + + int err = lfs_bd_read(lfs, dir->pair[0], dir->off, &entry->d, sizeof(entry->d)); + lfs_entry_fromle32(&entry->d); + if (err) { + return err; + } + + entry->off = dir->off; + dir->off += lfs_entry_size(entry); + dir->pos += lfs_entry_size(entry); + return 0; +} + +static int lfs_dir_find(lfs_t *lfs, lfs_dir_t *dir, lfs_entry_t *entry, const char **path) +{ + const char *pathname = *path; + size_t pathlen; + entry->d.type = LFS_TYPE_DIR; + entry->d.elen = sizeof(entry->d) - 4; + entry->d.alen = 0; + entry->d.nlen = 0; + entry->d.u.dir[0] = lfs->root[0]; + entry->d.u.dir[1] = lfs->root[1]; + + while (true) { + nextname: + // skip slashes + pathname += strspn(pathname, "/"); + pathlen = strcspn(pathname, "/"); + + // skip '.' and root '..' + if ((pathlen == 1 && memcmp(pathname, ".", 1) == 0) || (pathlen == 2 && memcmp(pathname, "..", 2) == 0)) { + pathname += pathlen; + goto nextname; + } + + // skip if matched by '..' in name + const char *suffix = pathname + pathlen; + size_t sufflen; + int depth = 1; + while (true) { + suffix += strspn(suffix, "/"); + sufflen = strcspn(suffix, "/"); + if (sufflen == 0) { + break; + } + + if (sufflen == 2 && memcmp(suffix, "..", 2) == 0) { + depth -= 1; + if (depth == 0) { + pathname = suffix + sufflen; + goto nextname; + } + } else { + depth += 1; + } + + suffix += sufflen; + } + + // found path + if (pathname[0] == '\0') { + return 0; + } + + // update what we've found + *path = pathname; + + // continue on if we hit a directory + if (entry->d.type != LFS_TYPE_DIR) { + return LFS_ERR_NOTDIR; + } + + int err = lfs_dir_fetch(lfs, dir, entry->d.u.dir); + if (err) { + return err; + } + + // find entry matching name + while (true) { + err = lfs_dir_next(lfs, dir, entry); + if (err) { + return err; + } + + if (((0x7f & entry->d.type) != LFS_TYPE_REG && (0x7f & entry->d.type) != LFS_TYPE_DIR) || entry->d.nlen != pathlen) { + continue; + } + + int res = lfs_bd_cmp(lfs, dir->pair[0], entry->off + 4 + entry->d.elen + entry->d.alen, pathname, pathlen); + if (res < 0) { + return res; + } + + // found match + if (res) { + break; + } + } + + // check that entry has not been moved + if (entry->d.type & 0x80) { + int moved = lfs_moved(lfs, &entry->d.u); + if (moved) { + return (moved < 0) ? moved : LFS_ERR_NOENT; + } + + entry->d.type &= ~0x80; + } + + // to next name + pathname += pathlen; + } +} + +/// Top level directory operations /// +int lfs_mkdir(lfs_t *lfs, const char *path) +{ + // deorphan if we haven't yet, needed at most once after poweron + if (!lfs->deorphaned) { + int err = lfs_deorphan(lfs); + if (err) { + return err; + } + } + + // fetch parent directory + lfs_dir_t cwd; + lfs_entry_t entry; + int err = lfs_dir_find(lfs, &cwd, &entry, &path); + if (err != LFS_ERR_NOENT || strchr(path, '/') != NULL) { + return err ? err : LFS_ERR_EXIST; + } + + // build up new directory + lfs_alloc_ack(lfs); + + lfs_dir_t dir; + err = lfs_dir_alloc(lfs, &dir); + if (err) { + return err; + } + dir.d.tail[0] = cwd.d.tail[0]; + dir.d.tail[1] = cwd.d.tail[1]; + + err = lfs_dir_commit(lfs, &dir, NULL, 0); + if (err) { + return err; + } + + entry.d.type = LFS_TYPE_DIR; + entry.d.elen = sizeof(entry.d) - 4; + entry.d.alen = 0; + entry.d.nlen = strlen(path); + entry.d.u.dir[0] = dir.pair[0]; + entry.d.u.dir[1] = dir.pair[1]; + + cwd.d.tail[0] = dir.pair[0]; + cwd.d.tail[1] = dir.pair[1]; + + err = lfs_dir_append(lfs, &cwd, &entry, path); + if (err) { + return err; + } + + lfs_alloc_ack(lfs); + return 0; +} + +int lfs_dir_open(lfs_t *lfs, lfs_dir_t *dir, const char *path) +{ + dir->pair[0] = lfs->root[0]; + dir->pair[1] = lfs->root[1]; + + lfs_entry_t entry; + int err = lfs_dir_find(lfs, dir, &entry, &path); + if (err) { + return err; + } else if (entry.d.type != LFS_TYPE_DIR) { + return LFS_ERR_NOTDIR; + } + + err = lfs_dir_fetch(lfs, dir, entry.d.u.dir); + if (err) { + return err; + } + + // setup head dir + // special offset for '.' and '..' + dir->head[0] = dir->pair[0]; + dir->head[1] = dir->pair[1]; + dir->pos = sizeof(dir->d) - 2; + dir->off = sizeof(dir->d); + + // add to list of directories + dir->next = lfs->dirs; + lfs->dirs = dir; + + return 0; +} + +int lfs_dir_close(lfs_t *lfs, lfs_dir_t *dir) +{ + // remove from list of directories + for (lfs_dir_t **p = &lfs->dirs; *p; p = &(*p)->next) { + if (*p == dir) { + *p = dir->next; + break; + } + } + + return 0; +} + +int lfs_dir_read(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info) +{ + memset(info, 0, sizeof(*info)); + + // special offset for '.' and '..' + if (dir->pos == sizeof(dir->d) - 2) { + info->type = LFS_TYPE_DIR; + strcpy(info->name, "."); + dir->pos += 1; + return 1; + } else if (dir->pos == sizeof(dir->d) - 1) { + info->type = LFS_TYPE_DIR; + strcpy(info->name, ".."); + dir->pos += 1; + return 1; + } + + lfs_entry_t entry; + while (true) { + int err = lfs_dir_next(lfs, dir, &entry); + if (err) { + return (err == LFS_ERR_NOENT) ? 0 : err; + } + + if ((0x7f & entry.d.type) != LFS_TYPE_REG && (0x7f & entry.d.type) != LFS_TYPE_DIR) { + continue; + } + + // check that entry has not been moved + if (entry.d.type & 0x80) { + int moved = lfs_moved(lfs, &entry.d.u); + if (moved < 0) { + return moved; + } + + if (moved) { + continue; + } + + entry.d.type &= ~0x80; + } + + break; + } + + info->type = entry.d.type; + if (info->type == LFS_TYPE_REG) { + info->size = entry.d.u.file.size; + } + + int err = lfs_bd_read(lfs, dir->pair[0], entry.off + 4 + entry.d.elen + entry.d.alen, info->name, entry.d.nlen); + if (err) { + return err; + } + + return 1; +} + +int lfs_dir_seek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off) +{ + // simply walk from head dir + int err = lfs_dir_rewind(lfs, dir); + if (err) { + return err; + } + dir->pos = off; + + while (off > (0x7fffffff & dir->d.size)) { + off -= 0x7fffffff & dir->d.size; + if (!(0x80000000 & dir->d.size)) { + return LFS_ERR_INVAL; + } + + err = lfs_dir_fetch(lfs, dir, dir->d.tail); + if (err) { + return err; + } + } + + dir->off = off; + return 0; +} + +int lfs_dir_rewind(lfs_t *lfs, lfs_dir_t *dir) +{ + // reload the head dir + int err = lfs_dir_fetch(lfs, dir, dir->head); + if (err) { + return err; + } + + dir->pair[0] = dir->head[0]; + dir->pair[1] = dir->head[1]; + dir->pos = sizeof(dir->d) - 2; + dir->off = sizeof(dir->d); + return 0; +} + +/// File index list operations /// +static int lfs_ctz_index(lfs_t *lfs, lfs_off_t *off) +{ + lfs_off_t size = *off; + lfs_off_t b = lfs->cfg->block_size - 2 * 4; + lfs_off_t i = size / b; + if (i == 0) { + return 0; + } + + i = (size - 4 * (lfs_popc(i - 1) + 2)) / b; + *off = size - b * i - 4 * lfs_popc(i); + return i; +} + +static int lfs_ctz_find(lfs_t *lfs, lfs_cache_t *rcache, const lfs_cache_t *pcache, lfs_block_t head, lfs_size_t size, + lfs_size_t pos, lfs_block_t *block, lfs_off_t *off) +{ + if (size == 0) { + *block = 0xffffffff; + *off = 0; + return 0; + } + + lfs_off_t current = lfs_ctz_index(lfs, &(lfs_off_t){size - 1}); + lfs_off_t target = lfs_ctz_index(lfs, &pos); + + while (current > target) { + lfs_size_t skip = lfs_min(lfs_npw2(current - target + 1) - 1, lfs_ctz(current)); + + int err = lfs_cache_read(lfs, rcache, pcache, head, 4 * skip, &head, 4); + head = lfs_fromle32(head); + if (err) { + return err; + } + + LFS_ASSERT(head >= 2 && head <= lfs->cfg->block_count); + current -= 1 << skip; + } + + *block = head; + *off = pos; + return 0; +} + +static int lfs_ctz_extend(lfs_t *lfs, lfs_cache_t *rcache, lfs_cache_t *pcache, lfs_block_t head, lfs_size_t size, + lfs_block_t *block, lfs_off_t *off) +{ + while (true) { + // go ahead and grab a block + lfs_block_t nblock; + int err = lfs_alloc(lfs, &nblock); + if (err) { + return err; + } + LFS_ASSERT(nblock >= 2 && nblock <= lfs->cfg->block_count); + + if (true) { + err = lfs_bd_erase(lfs, nblock); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + if (size == 0) { + *block = nblock; + *off = 0; + return 0; + } + + size -= 1; + lfs_off_t index = lfs_ctz_index(lfs, &size); + size += 1; + + // just copy out the last block if it is incomplete + if (size != lfs->cfg->block_size) { + for (lfs_off_t i = 0; i < size; i++) { + uint8_t data; + err = lfs_cache_read(lfs, rcache, NULL, head, i, &data, 1); + if (err) { + return err; + } + + err = lfs_cache_prog(lfs, pcache, rcache, nblock, i, &data, 1); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + } + + *block = nblock; + *off = size; + return 0; + } + + // append block + index += 1; + lfs_size_t skips = lfs_ctz(index) + 1; + + for (lfs_off_t i = 0; i < skips; i++) { + head = lfs_tole32(head); + err = lfs_cache_prog(lfs, pcache, rcache, nblock, 4 * i, &head, 4); + head = lfs_fromle32(head); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + if (i != skips - 1) { + err = lfs_cache_read(lfs, rcache, NULL, head, 4 * i, &head, 4); + head = lfs_fromle32(head); + if (err) { + return err; + } + } + + LFS_ASSERT(head >= 2 && head <= lfs->cfg->block_count); + } + + *block = nblock; + *off = 4 * skips; + return 0; + } + + relocate: + LFS_DEBUG("Bad block at %" PRIu32, nblock); + + // just clear cache and try a new block + lfs_cache_drop(lfs, &lfs->pcache); + } +} + +static int lfs_ctz_traverse(lfs_t *lfs, lfs_cache_t *rcache, const lfs_cache_t *pcache, lfs_block_t head, lfs_size_t size, + int (*cb)(void *, lfs_block_t), void *data) +{ + if (size == 0) { + return 0; + } + + lfs_off_t index = lfs_ctz_index(lfs, &(lfs_off_t){size - 1}); + + while (true) { + int err = cb(data, head); + if (err) { + return err; + } + + if (index == 0) { + return 0; + } + + lfs_block_t heads[2]; + int count = 2 - (index & 1); + err = lfs_cache_read(lfs, rcache, pcache, head, 0, &heads, count * 4); + heads[0] = lfs_fromle32(heads[0]); + heads[1] = lfs_fromle32(heads[1]); + if (err) { + return err; + } + + for (int i = 0; i < count - 1; i++) { + err = cb(data, heads[i]); + if (err) { + return err; + } + } + + head = heads[count - 1]; + index -= count; + } +} + +/// Top level file operations /// +int lfs_file_opencfg(lfs_t *lfs, lfs_file_t *file, const char *path, int flags, const struct lfs_file_config *cfg) +{ + // deorphan if we haven't yet, needed at most once after poweron + if ((flags & 3) != LFS_O_RDONLY && !lfs->deorphaned) { + int err = lfs_deorphan(lfs); + if (err) { + return err; + } + } + + // allocate entry for file if it doesn't exist + lfs_dir_t cwd; + lfs_entry_t entry; + int err = lfs_dir_find(lfs, &cwd, &entry, &path); + if (err && (err != LFS_ERR_NOENT || strchr(path, '/') != NULL)) { + return err; + } + + if (err == LFS_ERR_NOENT) { + if (!(flags & LFS_O_CREAT)) { + return LFS_ERR_NOENT; + } + + // create entry to remember name + entry.d.type = LFS_TYPE_REG; + entry.d.elen = sizeof(entry.d) - 4; + entry.d.alen = 0; + entry.d.nlen = strlen(path); + entry.d.u.file.head = 0xffffffff; + entry.d.u.file.size = 0; + err = lfs_dir_append(lfs, &cwd, &entry, path); + if (err) { + return err; + } + } else if (entry.d.type == LFS_TYPE_DIR) { + return LFS_ERR_ISDIR; + } else if (flags & LFS_O_EXCL) { + return LFS_ERR_EXIST; + } + + // setup file struct + file->cfg = cfg; + file->pair[0] = cwd.pair[0]; + file->pair[1] = cwd.pair[1]; + file->poff = entry.off; + file->head = entry.d.u.file.head; + file->size = entry.d.u.file.size; + file->flags = flags; + file->pos = 0; + + if (flags & LFS_O_TRUNC) { + if (file->size != 0) { + file->flags |= LFS_F_DIRTY; + } + file->head = 0xffffffff; + file->size = 0; + } + + // allocate buffer if needed + file->cache.block = 0xffffffff; + if (file->cfg && file->cfg->buffer) { + file->cache.buffer = file->cfg->buffer; + } else if (lfs->cfg->file_buffer) { + if (lfs->files) { + // already in use + return LFS_ERR_NOMEM; + } + file->cache.buffer = lfs->cfg->file_buffer; + } else if ((file->flags & 3) == LFS_O_RDONLY) { + file->cache.buffer = lfs_malloc(lfs->cfg->read_size); + if (!file->cache.buffer) { + return LFS_ERR_NOMEM; + } + } else { + file->cache.buffer = lfs_malloc(lfs->cfg->prog_size); + if (!file->cache.buffer) { + return LFS_ERR_NOMEM; + } + } + + // zero to avoid information leak + lfs_cache_drop(lfs, &file->cache); + if ((file->flags & 3) != LFS_O_RDONLY) { + lfs_cache_zero(lfs, &file->cache); + } + + // add to list of files + file->next = lfs->files; + lfs->files = file; + + return 0; +} + +int lfs_file_open(lfs_t *lfs, lfs_file_t *file, const char *path, int flags) +{ + return lfs_file_opencfg(lfs, file, path, flags, NULL); +} + +int lfs_file_close(lfs_t *lfs, lfs_file_t *file) +{ + int err = lfs_file_sync(lfs, file); + + // remove from list of files + for (lfs_file_t **p = &lfs->files; *p; p = &(*p)->next) { + if (*p == file) { + *p = file->next; + break; + } + } + + // clean up memory + if (!(file->cfg && file->cfg->buffer) && !lfs->cfg->file_buffer) { + lfs_free(file->cache.buffer); + } + + return err; +} + +static int lfs_file_relocate(lfs_t *lfs, lfs_file_t *file) +{ +relocate: + LFS_DEBUG("Bad block at %" PRIu32, file->block); + + // just relocate what exists into new block + lfs_block_t nblock; + int err = lfs_alloc(lfs, &nblock); + if (err) { + return err; + } + + err = lfs_bd_erase(lfs, nblock); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + // either read from dirty cache or disk + for (lfs_off_t i = 0; i < file->off; i++) { + uint8_t data; + err = lfs_cache_read(lfs, &lfs->rcache, &file->cache, file->block, i, &data, 1); + if (err) { + return err; + } + + err = lfs_cache_prog(lfs, &lfs->pcache, &lfs->rcache, nblock, i, &data, 1); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + } + + // copy over new state of file + memcpy(file->cache.buffer, lfs->pcache.buffer, lfs->cfg->prog_size); + file->cache.block = lfs->pcache.block; + file->cache.off = lfs->pcache.off; + lfs_cache_zero(lfs, &lfs->pcache); + + file->block = nblock; + return 0; +} + +static int lfs_file_flush(lfs_t *lfs, lfs_file_t *file) +{ + if (file->flags & LFS_F_READING) { + // just drop read cache + lfs_cache_drop(lfs, &file->cache); + file->flags &= ~LFS_F_READING; + } + + if (file->flags & LFS_F_WRITING) { + lfs_off_t pos = file->pos; + + // copy over anything after current branch + lfs_file_t orig = { + .head = file->head, + .size = file->size, + .flags = LFS_O_RDONLY, + .pos = file->pos, + .cache = lfs->rcache, + }; + lfs_cache_drop(lfs, &lfs->rcache); + + while (file->pos < file->size) { + // copy over a byte at a time, leave it up to caching + // to make this efficient + uint8_t data; + lfs_ssize_t res = lfs_file_read(lfs, &orig, &data, 1); + if (res < 0) { + return res; + } + + res = lfs_file_write(lfs, file, &data, 1); + if (res < 0) { + return res; + } + + // keep our reference to the rcache in sync + if (lfs->rcache.block != 0xffffffff) { + lfs_cache_drop(lfs, &orig.cache); + lfs_cache_drop(lfs, &lfs->rcache); + } + } + + // write out what we have + while (true) { + int err = lfs_cache_flush(lfs, &file->cache, &lfs->rcache); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + return err; + } + + break; + relocate: + err = lfs_file_relocate(lfs, file); + if (err) { + return err; + } + } + + // actual file updates + file->head = file->block; + file->size = file->pos; + file->flags &= ~LFS_F_WRITING; + file->flags |= LFS_F_DIRTY; + + file->pos = pos; + } + + return 0; +} + +int lfs_file_sync(lfs_t *lfs, lfs_file_t *file) +{ + int err = lfs_file_flush(lfs, file); + if (err) { + return err; + } + + if ((file->flags & LFS_F_DIRTY) && !(file->flags & LFS_F_ERRED) && !lfs_pairisnull(file->pair)) { + // update dir entry + lfs_dir_t cwd; + err = lfs_dir_fetch(lfs, &cwd, file->pair); + if (err) { + return err; + } + + lfs_entry_t entry = {.off = file->poff}; + err = lfs_bd_read(lfs, cwd.pair[0], entry.off, &entry.d, sizeof(entry.d)); + lfs_entry_fromle32(&entry.d); + if (err) { + return err; + } + + LFS_ASSERT(entry.d.type == LFS_TYPE_REG); + entry.d.u.file.head = file->head; + entry.d.u.file.size = file->size; + + err = lfs_dir_update(lfs, &cwd, &entry, NULL); + if (err) { + return err; + } + + file->flags &= ~LFS_F_DIRTY; + } + + return 0; +} + +lfs_ssize_t lfs_file_read(lfs_t *lfs, lfs_file_t *file, void *buffer, lfs_size_t size) +{ + uint8_t *data = buffer; + lfs_size_t nsize = size; + + if ((file->flags & 3) == LFS_O_WRONLY) { + return LFS_ERR_BADF; + } + + if (file->flags & LFS_F_WRITING) { + // flush out any writes + int err = lfs_file_flush(lfs, file); + if (err) { + return err; + } + } + + if (file->pos >= file->size) { + // eof if past end + return 0; + } + + size = lfs_min(size, file->size - file->pos); + nsize = size; + + while (nsize > 0) { + // check if we need a new block + if (!(file->flags & LFS_F_READING) || file->off == lfs->cfg->block_size) { + int err = lfs_ctz_find(lfs, &file->cache, NULL, file->head, file->size, file->pos, &file->block, &file->off); + if (err) { + return err; + } + + file->flags |= LFS_F_READING; + } + + // read as much as we can in current block + lfs_size_t diff = lfs_min(nsize, lfs->cfg->block_size - file->off); + int err = lfs_cache_read(lfs, &file->cache, NULL, file->block, file->off, data, diff); + if (err) { + return err; + } + + file->pos += diff; + file->off += diff; + data += diff; + nsize -= diff; + } + + return size; +} + +lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file, const void *buffer, lfs_size_t size) +{ + const uint8_t *data = buffer; + lfs_size_t nsize = size; + + if ((file->flags & 3) == LFS_O_RDONLY) { + return LFS_ERR_BADF; + } + + if (file->flags & LFS_F_READING) { + // drop any reads + int err = lfs_file_flush(lfs, file); + if (err) { + return err; + } + } + + if ((file->flags & LFS_O_APPEND) && file->pos < file->size) { + file->pos = file->size; + } + + if (!(file->flags & LFS_F_WRITING) && file->pos > file->size) { + // fill with zeros + lfs_off_t pos = file->pos; + file->pos = file->size; + + while (file->pos < pos) { + lfs_ssize_t res = lfs_file_write(lfs, file, &(uint8_t){0}, 1); + if (res < 0) { + return res; + } + } + } + + while (nsize > 0) { + // check if we need a new block + if (!(file->flags & LFS_F_WRITING) || file->off == lfs->cfg->block_size) { + if (!(file->flags & LFS_F_WRITING) && file->pos > 0) { + // find out which block we're extending from + int err = lfs_ctz_find(lfs, &file->cache, NULL, file->head, file->size, file->pos - 1, &file->block, &file->off); + if (err) { + file->flags |= LFS_F_ERRED; + return err; + } + + // mark cache as dirty since we may have read data into it + lfs_cache_zero(lfs, &file->cache); + } + + // extend file with new blocks + lfs_alloc_ack(lfs); + int err = lfs_ctz_extend(lfs, &lfs->rcache, &file->cache, file->block, file->pos, &file->block, &file->off); + if (err) { + file->flags |= LFS_F_ERRED; + return err; + } + + file->flags |= LFS_F_WRITING; + } + + // program as much as we can in current block + lfs_size_t diff = lfs_min(nsize, lfs->cfg->block_size - file->off); + while (true) { + int err = lfs_cache_prog(lfs, &file->cache, &lfs->rcache, file->block, file->off, data, diff); + if (err) { + if (err == LFS_ERR_CORRUPT) { + goto relocate; + } + file->flags |= LFS_F_ERRED; + return err; + } + + break; + relocate: + err = lfs_file_relocate(lfs, file); + if (err) { + file->flags |= LFS_F_ERRED; + return err; + } + } + + file->pos += diff; + file->off += diff; + data += diff; + nsize -= diff; + + lfs_alloc_ack(lfs); + } + + file->flags &= ~LFS_F_ERRED; + return size; +} + +lfs_soff_t lfs_file_seek(lfs_t *lfs, lfs_file_t *file, lfs_soff_t off, int whence) +{ + // write out everything beforehand, may be noop if rdonly + int err = lfs_file_flush(lfs, file); + if (err) { + return err; + } + + // update pos + if (whence == LFS_SEEK_SET) { + file->pos = off; + } else if (whence == LFS_SEEK_CUR) { + if (off < 0 && (lfs_off_t)-off > file->pos) { + return LFS_ERR_INVAL; + } + + file->pos = file->pos + off; + } else if (whence == LFS_SEEK_END) { + if (off < 0 && (lfs_off_t)-off > file->size) { + return LFS_ERR_INVAL; + } + + file->pos = file->size + off; + } + + return file->pos; +} + +int lfs_file_truncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size) +{ + if ((file->flags & 3) == LFS_O_RDONLY) { + return LFS_ERR_BADF; + } + + lfs_off_t oldsize = lfs_file_size(lfs, file); + if (size < oldsize) { + // need to flush since directly changing metadata + int err = lfs_file_flush(lfs, file); + if (err) { + return err; + } + + // lookup new head in ctz skip list + err = lfs_ctz_find(lfs, &file->cache, NULL, file->head, file->size, size, &file->head, &(lfs_off_t){0}); + if (err) { + return err; + } + + file->size = size; + file->flags |= LFS_F_DIRTY; + } else if (size > oldsize) { + lfs_off_t pos = file->pos; + + // flush+seek if not already at end + if (file->pos != oldsize) { + int err = lfs_file_seek(lfs, file, 0, LFS_SEEK_END); + if (err < 0) { + return err; + } + } + + // fill with zeros + while (file->pos < size) { + lfs_ssize_t res = lfs_file_write(lfs, file, &(uint8_t){0}, 1); + if (res < 0) { + return res; + } + } + + // restore pos + int err = lfs_file_seek(lfs, file, pos, LFS_SEEK_SET); + if (err < 0) { + return err; + } + } + + return 0; +} + +lfs_soff_t lfs_file_tell(lfs_t *lfs, lfs_file_t const *file) +{ + (void)lfs; + return file->pos; +} + +int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file) +{ + lfs_soff_t res = lfs_file_seek(lfs, file, 0, LFS_SEEK_SET); + if (res < 0) { + return res; + } + + return 0; +} + +lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file) +{ + (void)lfs; + if (file->flags & LFS_F_WRITING) { + return lfs_max(file->pos, file->size); + } else { + return file->size; + } +} + +/// General fs operations /// +int lfs_stat(lfs_t *lfs, const char *path, struct lfs_info *info) +{ + lfs_dir_t cwd; + lfs_entry_t entry; + int err = lfs_dir_find(lfs, &cwd, &entry, &path); + if (err) { + return err; + } + + memset(info, 0, sizeof(*info)); + info->type = entry.d.type; + if (info->type == LFS_TYPE_REG) { + info->size = entry.d.u.file.size; + } + + if (lfs_paircmp(entry.d.u.dir, lfs->root) == 0) { + strcpy(info->name, "/"); + } else { + err = lfs_bd_read(lfs, cwd.pair[0], entry.off + 4 + entry.d.elen + entry.d.alen, info->name, entry.d.nlen); + if (err) { + return err; + } + } + + return 0; +} + +int lfs_remove(lfs_t *lfs, const char *path) +{ + // deorphan if we haven't yet, needed at most once after poweron + if (!lfs->deorphaned) { + int err = lfs_deorphan(lfs); + if (err) { + return err; + } + } + + lfs_dir_t cwd; + lfs_entry_t entry; + int err = lfs_dir_find(lfs, &cwd, &entry, &path); + if (err) { + return err; + } + + lfs_dir_t dir; + if (entry.d.type == LFS_TYPE_DIR) { + // must be empty before removal, checking size + // without masking top bit checks for any case where + // dir is not empty + err = lfs_dir_fetch(lfs, &dir, entry.d.u.dir); + if (err) { + return err; + } /* else if (dir.d.size != sizeof(dir.d)+4) { + return LFS_ERR_NOTEMPTY; + } allow to remove non-empty folder, + According to below issue, comment these 2 line won't corrupt filesystem + https://github.com/ARMmbed/littlefs/issues/43 */ + } + + // remove the entry + err = lfs_dir_remove(lfs, &cwd, &entry); + if (err) { + return err; + } + + // if we were a directory, find pred, replace tail + if (entry.d.type == LFS_TYPE_DIR) { + int res = lfs_pred(lfs, dir.pair, &cwd); + if (res < 0) { + return res; + } + + LFS_ASSERT(res); // must have pred + cwd.d.tail[0] = dir.d.tail[0]; + cwd.d.tail[1] = dir.d.tail[1]; + + err = lfs_dir_commit(lfs, &cwd, NULL, 0); + if (err) { + return err; + } + } + + return 0; +} + +int lfs_rename(lfs_t *lfs, const char *oldpath, const char *newpath) +{ + // deorphan if we haven't yet, needed at most once after poweron + if (!lfs->deorphaned) { + int err = lfs_deorphan(lfs); + if (err) { + return err; + } + } + + // find old entry + lfs_dir_t oldcwd; + lfs_entry_t oldentry; + int err = lfs_dir_find(lfs, &oldcwd, &oldentry, &oldpath); + if (err) { + return err; + } + + // allocate new entry + lfs_dir_t newcwd; + lfs_entry_t preventry; + err = lfs_dir_find(lfs, &newcwd, &preventry, &newpath); + if (err && (err != LFS_ERR_NOENT || strchr(newpath, '/') != NULL)) { + return err; + } + + bool prevexists = (err != LFS_ERR_NOENT); + bool samepair = (lfs_paircmp(oldcwd.pair, newcwd.pair) == 0); + + // must have same type + if (prevexists && preventry.d.type != oldentry.d.type) { + return LFS_ERR_ISDIR; + } + + lfs_dir_t dir; + if (prevexists && preventry.d.type == LFS_TYPE_DIR) { + // must be empty before removal, checking size + // without masking top bit checks for any case where + // dir is not empty + err = lfs_dir_fetch(lfs, &dir, preventry.d.u.dir); + if (err) { + return err; + } else if (dir.d.size != sizeof(dir.d) + 4) { + return LFS_ERR_NOTEMPTY; + } + } + + // mark as moving + oldentry.d.type |= 0x80; + err = lfs_dir_update(lfs, &oldcwd, &oldentry, NULL); + if (err) { + return err; + } + + // update pair if newcwd == oldcwd + if (samepair) { + newcwd = oldcwd; + } + + // move to new location + lfs_entry_t newentry = preventry; + newentry.d = oldentry.d; + newentry.d.type &= ~0x80; + newentry.d.nlen = strlen(newpath); + + if (prevexists) { + err = lfs_dir_update(lfs, &newcwd, &newentry, newpath); + if (err) { + return err; + } + } else { + err = lfs_dir_append(lfs, &newcwd, &newentry, newpath); + if (err) { + return err; + } + } + + // update pair if newcwd == oldcwd + if (samepair) { + oldcwd = newcwd; + } + + // remove old entry + err = lfs_dir_remove(lfs, &oldcwd, &oldentry); + if (err) { + return err; + } + + // if we were a directory, find pred, replace tail + if (prevexists && preventry.d.type == LFS_TYPE_DIR) { + int res = lfs_pred(lfs, dir.pair, &newcwd); + if (res < 0) { + return res; + } + + LFS_ASSERT(res); // must have pred + newcwd.d.tail[0] = dir.d.tail[0]; + newcwd.d.tail[1] = dir.d.tail[1]; + + err = lfs_dir_commit(lfs, &newcwd, NULL, 0); + if (err) { + return err; + } + } + + return 0; +} + +/// Filesystem operations /// +static void lfs_deinit(lfs_t *lfs) +{ + // free allocated memory + if (!lfs->cfg->read_buffer) { + lfs_free(lfs->rcache.buffer); + } + + if (!lfs->cfg->prog_buffer) { + lfs_free(lfs->pcache.buffer); + } + + if (!lfs->cfg->lookahead_buffer) { + lfs_free(lfs->free.buffer); + } +} + +static int lfs_init(lfs_t *lfs, const struct lfs_config *cfg) +{ + lfs->cfg = cfg; + + // setup read cache + if (lfs->cfg->read_buffer) { + lfs->rcache.buffer = lfs->cfg->read_buffer; + } else { + lfs->rcache.buffer = lfs_malloc(lfs->cfg->read_size); + if (!lfs->rcache.buffer) { + goto cleanup; + } + } + + // setup program cache + if (lfs->cfg->prog_buffer) { + lfs->pcache.buffer = lfs->cfg->prog_buffer; + } else { + lfs->pcache.buffer = lfs_malloc(lfs->cfg->prog_size); + if (!lfs->pcache.buffer) { + goto cleanup; + } + } + + // zero to avoid information leaks + lfs_cache_zero(lfs, &lfs->pcache); + lfs_cache_drop(lfs, &lfs->rcache); + + // setup lookahead, round down to nearest 32-bits + LFS_ASSERT(lfs->cfg->lookahead % 32 == 0); + LFS_ASSERT(lfs->cfg->lookahead > 0); + if (lfs->cfg->lookahead_buffer) { + lfs->free.buffer = lfs->cfg->lookahead_buffer; + } else { + lfs->free.buffer = lfs_malloc(lfs->cfg->lookahead / 8); + if (!lfs->free.buffer) { + goto cleanup; + } + } + + // check that program and read sizes are multiples of the block size + LFS_ASSERT(lfs->cfg->prog_size % lfs->cfg->read_size == 0); + LFS_ASSERT(lfs->cfg->block_size % lfs->cfg->prog_size == 0); + + // check that the block size is large enough to fit ctz pointers + LFS_ASSERT(4 * lfs_npw2(0xffffffff / (lfs->cfg->block_size - 2 * 4)) <= lfs->cfg->block_size); + + // setup default state + lfs->root[0] = 0xffffffff; + lfs->root[1] = 0xffffffff; + lfs->files = NULL; + lfs->dirs = NULL; + lfs->deorphaned = false; + + return 0; + +cleanup: + lfs_deinit(lfs); + return LFS_ERR_NOMEM; +} + +int lfs_format(lfs_t *lfs, const struct lfs_config *cfg) +{ + int err = 0; + if (true) { + err = lfs_init(lfs, cfg); + if (err) { + return err; + } + + // create free lookahead + memset(lfs->free.buffer, 0, lfs->cfg->lookahead / 8); + lfs->free.off = 0; + lfs->free.size = lfs_min(lfs->cfg->lookahead, lfs->cfg->block_count); + lfs->free.i = 0; + lfs_alloc_ack(lfs); + + // create superblock dir + lfs_dir_t superdir; + err = lfs_dir_alloc(lfs, &superdir); + if (err) { + goto cleanup; + } + + // write root directory + lfs_dir_t root; + err = lfs_dir_alloc(lfs, &root); + if (err) { + goto cleanup; + } + + err = lfs_dir_commit(lfs, &root, NULL, 0); + if (err) { + goto cleanup; + } + + lfs->root[0] = root.pair[0]; + lfs->root[1] = root.pair[1]; + + // write superblocks + lfs_superblock_t superblock = { + .off = sizeof(superdir.d), + .d.type = LFS_TYPE_SUPERBLOCK, + .d.elen = sizeof(superblock.d) - sizeof(superblock.d.magic) - 4, + .d.nlen = sizeof(superblock.d.magic), + .d.version = LFS_DISK_VERSION, + .d.magic = {"littlefs"}, + .d.block_size = lfs->cfg->block_size, + .d.block_count = lfs->cfg->block_count, + .d.root = {lfs->root[0], lfs->root[1]}, + }; + superdir.d.tail[0] = root.pair[0]; + superdir.d.tail[1] = root.pair[1]; + superdir.d.size = sizeof(superdir.d) + sizeof(superblock.d) + 4; + + // write both pairs to be safe + lfs_superblock_tole32(&superblock.d); + bool valid = false; + for (int i = 0; i < 2; i++) { + err = lfs_dir_commit( + lfs, &superdir, + (struct lfs_region[]){{sizeof(superdir.d), sizeof(superblock.d), &superblock.d, sizeof(superblock.d)}}, 1); + if (err && err != LFS_ERR_CORRUPT) { + goto cleanup; + } + + valid = valid || !err; + } + + if (!valid) { + err = LFS_ERR_CORRUPT; + goto cleanup; + } + + // sanity check that fetch works + err = lfs_dir_fetch(lfs, &superdir, (const lfs_block_t[2]){0, 1}); + if (err) { + goto cleanup; + } + + lfs_alloc_ack(lfs); + } + +cleanup: + lfs_deinit(lfs); + return err; +} + +int lfs_mount(lfs_t *lfs, const struct lfs_config *cfg) +{ + int err = 0; + if (true) { + err = lfs_init(lfs, cfg); + if (err) { + return err; + } + + // setup free lookahead + lfs->free.off = 0; + lfs->free.size = 0; + lfs->free.i = 0; + lfs_alloc_ack(lfs); + + // load superblock + lfs_dir_t dir; + lfs_superblock_t superblock; + err = lfs_dir_fetch(lfs, &dir, (const lfs_block_t[2]){0, 1}); + if (err && err != LFS_ERR_CORRUPT) { + goto cleanup; + } + + if (!err) { + err = lfs_bd_read(lfs, dir.pair[0], sizeof(dir.d), &superblock.d, sizeof(superblock.d)); + lfs_superblock_fromle32(&superblock.d); + if (err) { + goto cleanup; + } + + lfs->root[0] = superblock.d.root[0]; + lfs->root[1] = superblock.d.root[1]; + } + + if (err || memcmp(superblock.d.magic, "littlefs", 8) != 0) { + LFS_ERROR("Invalid superblock at %d %d", 0, 1); + err = LFS_ERR_CORRUPT; + goto cleanup; + } + + uint16_t major_version = (0xffff & (superblock.d.version >> 16)); + uint16_t minor_version = (0xffff & (superblock.d.version >> 0)); + if ((major_version != LFS_DISK_VERSION_MAJOR || minor_version > LFS_DISK_VERSION_MINOR)) { + LFS_ERROR("Invalid version %d.%d", major_version, minor_version); + err = LFS_ERR_INVAL; + goto cleanup; + } + + return 0; + } + +cleanup: + + lfs_deinit(lfs); + return err; +} + +int lfs_unmount(lfs_t *lfs) +{ + lfs_deinit(lfs); + return 0; +} + +/// Littlefs specific operations /// +int lfs_traverse(lfs_t *lfs, int (*cb)(void *, lfs_block_t), void *data) +{ + if (lfs_pairisnull(lfs->root)) { + return 0; + } + + // iterate over metadata pairs + lfs_dir_t dir; + lfs_entry_t entry; + lfs_block_t cwd[2] = {0, 1}; + + while (true) { + for (int i = 0; i < 2; i++) { + int err = cb(data, cwd[i]); + if (err) { + return err; + } + } + + int err = lfs_dir_fetch(lfs, &dir, cwd); + if (err) { + return err; + } + + // iterate over contents + while (dir.off + sizeof(entry.d) <= (0x7fffffff & dir.d.size) - 4) { + err = lfs_bd_read(lfs, dir.pair[0], dir.off, &entry.d, sizeof(entry.d)); + lfs_entry_fromle32(&entry.d); + if (err) { + return err; + } + + dir.off += lfs_entry_size(&entry); + if ((0x70 & entry.d.type) == (0x70 & LFS_TYPE_REG)) { + err = lfs_ctz_traverse(lfs, &lfs->rcache, NULL, entry.d.u.file.head, entry.d.u.file.size, cb, data); + if (err) { + return err; + } + } + } + + cwd[0] = dir.d.tail[0]; + cwd[1] = dir.d.tail[1]; + + if (lfs_pairisnull(cwd)) { + break; + } + } + + // iterate over any open files + for (lfs_file_t *f = lfs->files; f; f = f->next) { + if (f->flags & LFS_F_DIRTY) { + int err = lfs_ctz_traverse(lfs, &lfs->rcache, &f->cache, f->head, f->size, cb, data); + if (err) { + return err; + } + } + + if (f->flags & LFS_F_WRITING) { + int err = lfs_ctz_traverse(lfs, &lfs->rcache, &f->cache, f->block, f->pos, cb, data); + if (err) { + return err; + } + } + } + + return 0; +} + +static int lfs_pred(lfs_t *lfs, const lfs_block_t dir[2], lfs_dir_t *pdir) +{ + if (lfs_pairisnull(lfs->root)) { + return 0; + } + + // iterate over all directory directory entries + int err = lfs_dir_fetch(lfs, pdir, (const lfs_block_t[2]){0, 1}); + if (err) { + return err; + } + + while (!lfs_pairisnull(pdir->d.tail)) { + if (lfs_paircmp(pdir->d.tail, dir) == 0) { + return true; + } + + err = lfs_dir_fetch(lfs, pdir, pdir->d.tail); + if (err) { + return err; + } + } + + return false; +} + +static int lfs_parent(lfs_t *lfs, const lfs_block_t dir[2], lfs_dir_t *parent, lfs_entry_t *entry) +{ + if (lfs_pairisnull(lfs->root)) { + return 0; + } + + parent->d.tail[0] = 0; + parent->d.tail[1] = 1; + + // iterate over all directory directory entries + while (!lfs_pairisnull(parent->d.tail)) { + int err = lfs_dir_fetch(lfs, parent, parent->d.tail); + if (err) { + return err; + } + + while (true) { + err = lfs_dir_next(lfs, parent, entry); + if (err && err != LFS_ERR_NOENT) { + return err; + } + + if (err == LFS_ERR_NOENT) { + break; + } + + if (((0x70 & entry->d.type) == (0x70 & LFS_TYPE_DIR)) && lfs_paircmp(entry->d.u.dir, dir) == 0) { + return true; + } + } + } + + return false; +} + +static int lfs_moved(lfs_t *lfs, const void *e) +{ + if (lfs_pairisnull(lfs->root)) { + return 0; + } + + // skip superblock + lfs_dir_t cwd; + int err = lfs_dir_fetch(lfs, &cwd, (const lfs_block_t[2]){0, 1}); + if (err) { + return err; + } + + // iterate over all directory directory entries + lfs_entry_t entry; + while (!lfs_pairisnull(cwd.d.tail)) { + err = lfs_dir_fetch(lfs, &cwd, cwd.d.tail); + if (err) { + return err; + } + + while (true) { + err = lfs_dir_next(lfs, &cwd, &entry); + if (err && err != LFS_ERR_NOENT) { + return err; + } + + if (err == LFS_ERR_NOENT) { + break; + } + + if (!(0x80 & entry.d.type) && memcmp(&entry.d.u, e, sizeof(entry.d.u)) == 0) { + return true; + } + } + } + + return false; +} + +static int lfs_relocate(lfs_t *lfs, const lfs_block_t oldpair[2], const lfs_block_t newpair[2]) +{ + // find parent + lfs_dir_t parent; + lfs_entry_t entry; + int res = lfs_parent(lfs, oldpair, &parent, &entry); + if (res < 0) { + return res; + } + + if (res) { + // update disk, this creates a desync + entry.d.u.dir[0] = newpair[0]; + entry.d.u.dir[1] = newpair[1]; + + int err = lfs_dir_update(lfs, &parent, &entry, NULL); + if (err) { + return err; + } + + // update internal root + if (lfs_paircmp(oldpair, lfs->root) == 0) { + LFS_DEBUG("Relocating root %" PRIu32 " %" PRIu32, newpair[0], newpair[1]); + lfs->root[0] = newpair[0]; + lfs->root[1] = newpair[1]; + } + + // clean up bad block, which should now be a desync + return lfs_deorphan(lfs); + } + + // find pred + res = lfs_pred(lfs, oldpair, &parent); + if (res < 0) { + return res; + } + + if (res) { + // just replace bad pair, no desync can occur + parent.d.tail[0] = newpair[0]; + parent.d.tail[1] = newpair[1]; + + return lfs_dir_commit(lfs, &parent, NULL, 0); + } + + // couldn't find dir, must be new + return 0; +} + +int lfs_deorphan(lfs_t *lfs) +{ + lfs->deorphaned = true; + + if (lfs_pairisnull(lfs->root)) { + return 0; + } + + lfs_dir_t pdir = {.d.size = 0x80000000}; + lfs_dir_t cwd = {.d.tail[0] = 0, .d.tail[1] = 1}; + + // iterate over all directory directory entries + for (lfs_size_t i = 0; i < lfs->cfg->block_count; i++) { + if (lfs_pairisnull(cwd.d.tail)) { + return 0; + } + + int err = lfs_dir_fetch(lfs, &cwd, cwd.d.tail); + if (err) { + return err; + } + + // check head blocks for orphans + if (!(0x80000000 & pdir.d.size)) { + // check if we have a parent + lfs_dir_t parent; + lfs_entry_t entry; + int res = lfs_parent(lfs, pdir.d.tail, &parent, &entry); + if (res < 0) { + return res; + } + + if (!res) { + // we are an orphan + LFS_DEBUG("Found orphan %" PRIu32 " %" PRIu32, pdir.d.tail[0], pdir.d.tail[1]); + + pdir.d.tail[0] = cwd.d.tail[0]; + pdir.d.tail[1] = cwd.d.tail[1]; + + err = lfs_dir_commit(lfs, &pdir, NULL, 0); + if (err) { + return err; + } + + return 0; + } + + if (!lfs_pairsync(entry.d.u.dir, pdir.d.tail)) { + // we have desynced + LFS_DEBUG("Found desync %" PRIu32 " %" PRIu32, entry.d.u.dir[0], entry.d.u.dir[1]); + + pdir.d.tail[0] = entry.d.u.dir[0]; + pdir.d.tail[1] = entry.d.u.dir[1]; + + err = lfs_dir_commit(lfs, &pdir, NULL, 0); + if (err) { + return err; + } + + return 0; + } + } + + // check entries for moves + lfs_entry_t entry; + while (true) { + err = lfs_dir_next(lfs, &cwd, &entry); + if (err && err != LFS_ERR_NOENT) { + return err; + } + + if (err == LFS_ERR_NOENT) { + break; + } + + // found moved entry + if (entry.d.type & 0x80) { + int moved = lfs_moved(lfs, &entry.d.u); + if (moved < 0) { + return moved; + } + + if (moved) { + LFS_DEBUG("Found move %" PRIu32 " %" PRIu32, entry.d.u.dir[0], entry.d.u.dir[1]); + err = lfs_dir_remove(lfs, &cwd, &entry); + if (err) { + return err; + } + } else { + LFS_DEBUG("Found partial move %" PRIu32 " %" PRIu32, entry.d.u.dir[0], entry.d.u.dir[1]); + entry.d.type &= ~0x80; + err = lfs_dir_update(lfs, &cwd, &entry, NULL); + if (err) { + return err; + } + } + } + } + + memcpy(&pdir, &cwd, sizeof(pdir)); + } + + // If we reached here, we have more directory pairs than blocks in the + // filesystem... So something must be horribly wrong + return LFS_ERR_CORRUPT; +} diff --git a/src/platform/stm32wl/littlefs/lfs.h b/src/platform/stm32wl/littlefs/lfs.h new file mode 100644 index 000000000..c6ed1d622 --- /dev/null +++ b/src/platform/stm32wl/littlefs/lfs.h @@ -0,0 +1,468 @@ +/* + * The little filesystem + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef LFS_H +#define LFS_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/// Version info /// + +// Software library version +// Major (top-nibble), incremented on backwards incompatible changes +// Minor (bottom-nibble), incremented on feature additions +#define LFS_VERSION 0x00010006 +#define LFS_VERSION_MAJOR (0xffff & (LFS_VERSION >> 16)) +#define LFS_VERSION_MINOR (0xffff & (LFS_VERSION >> 0)) + +// Version of On-disk data structures +// Major (top-nibble), incremented on backwards incompatible changes +// Minor (bottom-nibble), incremented on feature additions +#define LFS_DISK_VERSION 0x00010001 +#define LFS_DISK_VERSION_MAJOR (0xffff & (LFS_DISK_VERSION >> 16)) +#define LFS_DISK_VERSION_MINOR (0xffff & (LFS_DISK_VERSION >> 0)) + +/// Definitions /// + +// Type definitions +typedef uint32_t lfs_size_t; +typedef uint32_t lfs_off_t; + +typedef int32_t lfs_ssize_t; +typedef int32_t lfs_soff_t; + +typedef uint32_t lfs_block_t; + +// Max name size in bytes +#ifndef LFS_NAME_MAX +#define LFS_NAME_MAX 255 +#endif + +// Possible error codes, these are negative to allow +// valid positive return values +enum lfs_error { + LFS_ERR_OK = 0, // No error + LFS_ERR_IO = -5, // Error during device operation + LFS_ERR_CORRUPT = -52, // Corrupted + LFS_ERR_NOENT = -2, // No directory entry + LFS_ERR_EXIST = -17, // Entry already exists + LFS_ERR_NOTDIR = -20, // Entry is not a dir + LFS_ERR_ISDIR = -21, // Entry is a dir + LFS_ERR_NOTEMPTY = -39, // Dir is not empty + LFS_ERR_BADF = -9, // Bad file number + LFS_ERR_INVAL = -22, // Invalid parameter + LFS_ERR_NOSPC = -28, // No space left on device + LFS_ERR_NOMEM = -12, // No more memory available +}; + +// File types +enum lfs_type { + LFS_TYPE_REG = 0x11, + LFS_TYPE_DIR = 0x22, + LFS_TYPE_SUPERBLOCK = 0x2e, +}; + +// File open flags +enum lfs_open_flags { + // open flags + LFS_O_RDONLY = 1, // Open a file as read only + LFS_O_WRONLY = 2, // Open a file as write only + LFS_O_RDWR = 3, // Open a file as read and write + LFS_O_CREAT = 0x0100, // Create a file if it does not exist + LFS_O_EXCL = 0x0200, // Fail if a file already exists + LFS_O_TRUNC = 0x0400, // Truncate the existing file to zero size + LFS_O_APPEND = 0x0800, // Move to end of file on every write + + // internally used flags + LFS_F_DIRTY = 0x10000, // File does not match storage + LFS_F_WRITING = 0x20000, // File has been written since last flush + LFS_F_READING = 0x40000, // File has been read since last flush + LFS_F_ERRED = 0x80000, // An error occured during write +}; + +// File seek flags +enum lfs_whence_flags { + LFS_SEEK_SET = 0, // Seek relative to an absolute position + LFS_SEEK_CUR = 1, // Seek relative to the current file position + LFS_SEEK_END = 2, // Seek relative to the end of the file +}; + +// Configuration provided during initialization of the littlefs +struct lfs_config { + // Opaque user provided context that can be used to pass + // information to the block device operations + void *context; + + // Read a region in a block. Negative error codes are propogated + // to the user. + int (*read)(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, void *buffer, lfs_size_t size); + + // Program a region in a block. The block must have previously + // been erased. Negative error codes are propogated to the user. + // May return LFS_ERR_CORRUPT if the block should be considered bad. + int (*prog)(const struct lfs_config *c, lfs_block_t block, lfs_off_t off, const void *buffer, lfs_size_t size); + + // Erase a block. A block must be erased before being programmed. + // The state of an erased block is undefined. Negative error codes + // are propogated to the user. + // May return LFS_ERR_CORRUPT if the block should be considered bad. + int (*erase)(const struct lfs_config *c, lfs_block_t block); + + // Sync the state of the underlying block device. Negative error codes + // are propogated to the user. + int (*sync)(const struct lfs_config *c); + + // Minimum size of a block read. This determines the size of read buffers. + // This may be larger than the physical read size to improve performance + // by caching more of the block device. + lfs_size_t read_size; + + // Minimum size of a block program. This determines the size of program + // buffers. This may be larger than the physical program size to improve + // performance by caching more of the block device. + // Must be a multiple of the read size. + lfs_size_t prog_size; + + // Size of an erasable block. This does not impact ram consumption and + // may be larger than the physical erase size. However, this should be + // kept small as each file currently takes up an entire block. + // Must be a multiple of the program size. + lfs_size_t block_size; + + // Number of erasable blocks on the device. + lfs_size_t block_count; + + // Number of blocks to lookahead during block allocation. A larger + // lookahead reduces the number of passes required to allocate a block. + // The lookahead buffer requires only 1 bit per block so it can be quite + // large with little ram impact. Should be a multiple of 32. + lfs_size_t lookahead; + + // Optional, statically allocated read buffer. Must be read sized. + void *read_buffer; + + // Optional, statically allocated program buffer. Must be program sized. + void *prog_buffer; + + // Optional, statically allocated lookahead buffer. Must be 1 bit per + // lookahead block. + void *lookahead_buffer; + + // Optional, statically allocated buffer for files. Must be program sized. + // If enabled, only one file may be opened at a time. + void *file_buffer; +}; + +// Optional configuration provided during lfs_file_opencfg +struct lfs_file_config { + // Optional, statically allocated buffer for files. Must be program sized. + // If NULL, malloc will be used by default. + void *buffer; +}; + +// File info structure +struct lfs_info { + // Type of the file, either LFS_TYPE_REG or LFS_TYPE_DIR + uint8_t type; + + // Size of the file, only valid for REG files + lfs_size_t size; + + // Name of the file stored as a null-terminated string + char name[LFS_NAME_MAX + 1]; +}; + +/// littlefs data structures /// +typedef struct lfs_entry { + lfs_off_t off; + + struct lfs_disk_entry { + uint8_t type; + uint8_t elen; + uint8_t alen; + uint8_t nlen; + union { + struct { + lfs_block_t head; + lfs_size_t size; + } file; + lfs_block_t dir[2]; + } u; + } d; +} lfs_entry_t; + +typedef struct lfs_cache { + lfs_block_t block; + lfs_off_t off; + uint8_t *buffer; +} lfs_cache_t; + +typedef struct lfs_file { + struct lfs_file *next; + lfs_block_t pair[2]; + lfs_off_t poff; + + lfs_block_t head; + lfs_size_t size; + + const struct lfs_file_config *cfg; + uint32_t flags; + lfs_off_t pos; + lfs_block_t block; + lfs_off_t off; + lfs_cache_t cache; +} lfs_file_t; + +typedef struct lfs_dir { + struct lfs_dir *next; + lfs_block_t pair[2]; + lfs_off_t off; + + lfs_block_t head[2]; + lfs_off_t pos; + + struct lfs_disk_dir { + uint32_t rev; + lfs_size_t size; + lfs_block_t tail[2]; + } d; +} lfs_dir_t; + +typedef struct lfs_superblock { + lfs_off_t off; + + struct lfs_disk_superblock { + uint8_t type; + uint8_t elen; + uint8_t alen; + uint8_t nlen; + lfs_block_t root[2]; + uint32_t block_size; + uint32_t block_count; + uint32_t version; + char magic[8]; + } d; +} lfs_superblock_t; + +typedef struct lfs_free { + lfs_block_t off; + lfs_block_t size; + lfs_block_t i; + lfs_block_t ack; + uint32_t *buffer; +} lfs_free_t; + +// The littlefs type +typedef struct lfs { + const struct lfs_config *cfg; + + lfs_block_t root[2]; + lfs_file_t *files; + lfs_dir_t *dirs; + + lfs_cache_t rcache; + lfs_cache_t pcache; + + lfs_free_t free; + bool deorphaned; +} lfs_t; + +/// Filesystem functions /// + +// Format a block device with the littlefs +// +// Requires a littlefs object and config struct. This clobbers the littlefs +// object, and does not leave the filesystem mounted. The config struct must +// be zeroed for defaults and backwards compatibility. +// +// Returns a negative error code on failure. +int lfs_format(lfs_t *lfs, const struct lfs_config *config); + +// Mounts a littlefs +// +// Requires a littlefs object and config struct. Multiple filesystems +// may be mounted simultaneously with multiple littlefs objects. Both +// lfs and config must be allocated while mounted. The config struct must +// be zeroed for defaults and backwards compatibility. +// +// Returns a negative error code on failure. +int lfs_mount(lfs_t *lfs, const struct lfs_config *config); + +// Unmounts a littlefs +// +// Does nothing besides releasing any allocated resources. +// Returns a negative error code on failure. +int lfs_unmount(lfs_t *lfs); + +/// General operations /// + +// Removes a file or directory +// +// If removing a directory, the directory must be empty. +// Returns a negative error code on failure. +int lfs_remove(lfs_t *lfs, const char *path); + +// Rename or move a file or directory +// +// If the destination exists, it must match the source in type. +// If the destination is a directory, the directory must be empty. +// +// Returns a negative error code on failure. +int lfs_rename(lfs_t *lfs, const char *oldpath, const char *newpath); + +// Find info about a file or directory +// +// Fills out the info structure, based on the specified file or directory. +// Returns a negative error code on failure. +int lfs_stat(lfs_t *lfs, const char *path, struct lfs_info *info); + +/// File operations /// + +// Open a file +// +// The mode that the file is opened in is determined by the flags, which +// are values from the enum lfs_open_flags that are bitwise-ored together. +// +// Returns a negative error code on failure. +int lfs_file_open(lfs_t *lfs, lfs_file_t *file, const char *path, int flags); + +// Open a file with extra configuration +// +// The mode that the file is opened in is determined by the flags, which +// are values from the enum lfs_open_flags that are bitwise-ored together. +// +// The config struct provides additional config options per file as described +// above. The config struct must be allocated while the file is open, and the +// config struct must be zeroed for defaults and backwards compatibility. +// +// Returns a negative error code on failure. +int lfs_file_opencfg(lfs_t *lfs, lfs_file_t *file, const char *path, int flags, const struct lfs_file_config *config); + +// Close a file +// +// Any pending writes are written out to storage as though +// sync had been called and releases any allocated resources. +// +// Returns a negative error code on failure. +int lfs_file_close(lfs_t *lfs, lfs_file_t *file); + +// Synchronize a file on storage +// +// Any pending writes are written out to storage. +// Returns a negative error code on failure. +int lfs_file_sync(lfs_t *lfs, lfs_file_t *file); + +// Read data from file +// +// Takes a buffer and size indicating where to store the read data. +// Returns the number of bytes read, or a negative error code on failure. +lfs_ssize_t lfs_file_read(lfs_t *lfs, lfs_file_t *file, void *buffer, lfs_size_t size); + +// Write data to file +// +// Takes a buffer and size indicating the data to write. The file will not +// actually be updated on the storage until either sync or close is called. +// +// Returns the number of bytes written, or a negative error code on failure. +lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file, const void *buffer, lfs_size_t size); + +// Change the position of the file +// +// The change in position is determined by the offset and whence flag. +// Returns the old position of the file, or a negative error code on failure. +lfs_soff_t lfs_file_seek(lfs_t *lfs, lfs_file_t *file, lfs_soff_t off, int whence); + +// Truncates the size of the file to the specified size +// +// Returns a negative error code on failure. +int lfs_file_truncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size); + +// Return the position of the file +// +// Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_CUR) +// Returns the position of the file, or a negative error code on failure. +lfs_soff_t lfs_file_tell(lfs_t *lfs, const lfs_file_t *file); + +// Change the position of the file to the beginning of the file +// +// Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_CUR) +// Returns a negative error code on failure. +int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file); + +// Return the size of the file +// +// Similar to lfs_file_seek(lfs, file, 0, LFS_SEEK_END) +// Returns the size of the file, or a negative error code on failure. +lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file); + +/// Directory operations /// + +// Create a directory +// +// Returns a negative error code on failure. +int lfs_mkdir(lfs_t *lfs, const char *path); + +// Open a directory +// +// Once open a directory can be used with read to iterate over files. +// Returns a negative error code on failure. +int lfs_dir_open(lfs_t *lfs, lfs_dir_t *dir, const char *path); + +// Close a directory +// +// Releases any allocated resources. +// Returns a negative error code on failure. +int lfs_dir_close(lfs_t *lfs, lfs_dir_t *dir); + +// Read an entry in the directory +// +// Fills out the info structure, based on the specified file or directory. +// Returns a negative error code on failure. +int lfs_dir_read(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info); + +// Change the position of the directory +// +// The new off must be a value previous returned from tell and specifies +// an absolute offset in the directory seek. +// +// Returns a negative error code on failure. +int lfs_dir_seek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off); + +// Change the position of the directory to the beginning of the directory +// +// Returns a negative error code on failure. +int lfs_dir_rewind(lfs_t *lfs, lfs_dir_t *dir); + +/// Miscellaneous littlefs specific operations /// + +// Traverse through all blocks in use by the filesystem +// +// The provided callback will be called with each block address that is +// currently in use by the filesystem. This can be used to determine which +// blocks are in use or how much of the storage is available. +// +// Returns a negative error code on failure. +int lfs_traverse(lfs_t *lfs, int (*cb)(void *, lfs_block_t), void *data); + +// Prunes any recoverable errors that may have occured in the filesystem +// +// Not needed to be called by user unless an operation is interrupted +// but the filesystem is still mounted. This is already called on first +// allocation. +// +// Returns a negative error code on failure. +int lfs_deorphan(lfs_t *lfs); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/src/platform/stm32wl/littlefs/lfs_util.c b/src/platform/stm32wl/littlefs/lfs_util.c new file mode 100644 index 000000000..0b352c51f --- /dev/null +++ b/src/platform/stm32wl/littlefs/lfs_util.c @@ -0,0 +1,28 @@ +/* + * lfs util functions + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#include "lfs_util.h" + +// Only compile if user does not provide custom config +#ifndef LFS_CONFIG + +// Software CRC implementation with small lookup table +void lfs_crc(uint32_t *restrict crc, const void *buffer, size_t size) +{ + static const uint32_t rtable[16] = { + 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c, + }; + + const uint8_t *data = buffer; + + for (size_t i = 0; i < size; i++) { + *crc = (*crc >> 4) ^ rtable[(*crc ^ (data[i] >> 0)) & 0xf]; + *crc = (*crc >> 4) ^ rtable[(*crc ^ (data[i] >> 4)) & 0xf]; + } +} + +#endif diff --git a/src/platform/stm32wl/littlefs/lfs_util.h b/src/platform/stm32wl/littlefs/lfs_util.h new file mode 100644 index 000000000..5c8469f88 --- /dev/null +++ b/src/platform/stm32wl/littlefs/lfs_util.h @@ -0,0 +1,199 @@ +/* + * lfs utility functions + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef LFS_UTIL_H +#define LFS_UTIL_H + +// Users can override lfs_util.h with their own configuration by defining +// LFS_CONFIG as a header file to include (-DLFS_CONFIG=lfs_config.h). +// +// If LFS_CONFIG is used, none of the default utils will be emitted and must be +// provided by the config file. To start I would suggest copying lfs_util.h and +// modifying as needed. +#ifdef LFS_CONFIG +#define LFS_STRINGIZE(x) LFS_STRINGIZE2(x) +#define LFS_STRINGIZE2(x) #x +#include LFS_STRINGIZE(LFS_CONFIG) +#else + +// System includes +#include +#include +#include + +#ifndef LFS_NO_MALLOC +#include +#endif +#ifndef LFS_NO_ASSERT +#include +#endif + +#if !CFG_DEBUG +#define LFS_NO_DEBUG +#define LFS_NO_WARN +#define LFS_NO_ERROR +#endif + +#if !defined(LFS_NO_DEBUG) || !defined(LFS_NO_WARN) || !defined(LFS_NO_ERROR) +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// Macros, may be replaced by system specific wrappers. Arguments to these +// macros must not have side-effects as the macros can be removed for a smaller +// code footprint + +// Logging functions +#ifndef LFS_NO_DEBUG +#define LFS_DEBUG(fmt, ...) printf("lfs debug:%d: " fmt "\n", __LINE__, __VA_ARGS__) +#else +#define LFS_DEBUG(fmt, ...) +#endif + +#ifndef LFS_NO_WARN +#define LFS_WARN(fmt, ...) printf("lfs warn:%d: " fmt "\n", __LINE__, __VA_ARGS__) +#else +#define LFS_WARN(fmt, ...) +#endif + +#ifndef LFS_NO_ERROR +#define LFS_ERROR(fmt, ...) printf("lfs error:%d: " fmt "\n", __LINE__, __VA_ARGS__) +#else +#define LFS_ERROR(fmt, ...) +#endif + +// Runtime assertions +#ifndef LFS_NO_ASSERT +#define LFS_ASSERT(test) assert(test) +#else +#define LFS_ASSERT(test) +#endif + +// Builtin functions, these may be replaced by more efficient +// toolchain-specific implementations. LFS_NO_INTRINSICS falls back to a more +// expensive basic C implementation for debugging purposes + +// Min/max functions for unsigned 32-bit numbers +static inline uint32_t lfs_max(uint32_t a, uint32_t b) +{ + return (a > b) ? a : b; +} + +static inline uint32_t lfs_min(uint32_t a, uint32_t b) +{ + return (a < b) ? a : b; +} + +// Find the next smallest power of 2 less than or equal to a +static inline uint32_t lfs_npw2(uint32_t a) +{ +#if !defined(LFS_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM)) + return 32 - __builtin_clz(a - 1); +#else + uint32_t r = 0; + uint32_t s; + a -= 1; + s = (a > 0xffff) << 4; + a >>= s; + r |= s; + s = (a > 0xff) << 3; + a >>= s; + r |= s; + s = (a > 0xf) << 2; + a >>= s; + r |= s; + s = (a > 0x3) << 1; + a >>= s; + r |= s; + return (r | (a >> 1)) + 1; +#endif +} + +// Count the number of trailing binary zeros in a +// lfs_ctz(0) may be undefined +static inline uint32_t lfs_ctz(uint32_t a) +{ +#if !defined(LFS_NO_INTRINSICS) && defined(__GNUC__) + return __builtin_ctz(a); +#else + return lfs_npw2((a & -a) + 1) - 1; +#endif +} + +// Count the number of binary ones in a +static inline uint32_t lfs_popc(uint32_t a) +{ +#if !defined(LFS_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM)) + return __builtin_popcount(a); +#else + a = a - ((a >> 1) & 0x55555555); + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); + return (((a + (a >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24; +#endif +} + +// Find the sequence comparison of a and b, this is the distance +// between a and b ignoring overflow +static inline int lfs_scmp(uint32_t a, uint32_t b) +{ + return (int)(unsigned)(a - b); +} + +// Convert from 32-bit little-endian to native order +static inline uint32_t lfs_fromle32(uint32_t a) +{ +#if !defined(LFS_NO_INTRINSICS) && ((defined(BYTE_ORDER) && BYTE_ORDER == ORDER_LITTLE_ENDIAN) || \ + (defined(__BYTE_ORDER) && __BYTE_ORDER == __ORDER_LITTLE_ENDIAN) || \ + (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) + return a; +#elif !defined(LFS_NO_INTRINSICS) && \ + ((defined(BYTE_ORDER) && BYTE_ORDER == ORDER_BIG_ENDIAN) || (defined(__BYTE_ORDER) && __BYTE_ORDER == __ORDER_BIG_ENDIAN) || \ + (defined(__BYTE_ORDER__) && __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); +#endif +} + +// Convert to 32-bit little-endian from native order +static inline uint32_t lfs_tole32(uint32_t a) +{ + return lfs_fromle32(a); +} + +// Calculate CRC-32 with polynomial = 0x04c11db7 +void lfs_crc(uint32_t *crc, const void *buffer, size_t size); + +// Allocate memory, only used if buffers are not provided to littlefs +static inline void *lfs_malloc(size_t size) +{ +#ifndef LFS_NO_MALLOC + return malloc(size); +#else + (void)size; + return NULL; +#endif +} + +// Deallocate memory, only used if buffers are not provided to littlefs +static inline void lfs_free(void *p) +{ +#ifndef LFS_NO_MALLOC + free(p); +#else + (void)p; +#endif +} + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif +#endif diff --git a/src/power.h b/src/power.h index e9c0deb7c..97944fef7 100644 --- a/src/power.h +++ b/src/power.h @@ -84,6 +84,11 @@ class Power : private concurrency::OSThread void setStatusHandler(meshtastic::PowerStatus *handler) { statusHandler = handler; } const uint16_t OCV[11] = {OCV_ARRAY}; +#if defined(ELECROW_ThinkNode_M1) || defined(POWER_CFG) + uint8_t low_voltage_counter_led3; + int power_num = 0; +#endif + protected: meshtastic::PowerStatus *statusHandler; diff --git a/src/shutdown.h b/src/shutdown.h index c2ba6f670..f02cb7964 100644 --- a/src/shutdown.h +++ b/src/shutdown.h @@ -32,6 +32,8 @@ void powerCommandsCheck() delete screen; LOG_DEBUG("final reboot!"); reboot(); +#elif defined(ARCH_STM32WL) + HAL_NVIC_SystemReset(); #else rebootAtMsec = -1; LOG_WARN("FIXME implement reboot for this platform. Note that some settings require a restart to be applied"); diff --git a/src/sleep.cpp b/src/sleep.cpp index 202b8c354..02fa8d871 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -228,6 +228,7 @@ void doDeepSleep(uint32_t msecToWake, bool skipPreflight = false, bool skipSaveN } #ifdef PIN_POWER_EN + digitalWrite(PIN_POWER_EN, LOW); pinMode(PIN_POWER_EN, INPUT); // power off peripherals // pinMode(PIN_POWER_EN1, INPUT_PULLDOWN); #endif diff --git a/userPrefs.jsonc b/userPrefs.jsonc index 6a3fdbb55..d522ad272 100644 --- a/userPrefs.jsonc +++ b/userPrefs.jsonc @@ -40,5 +40,9 @@ // "USERPREFS_OEM_IMAGE_WIDTH": "50", // "USERPREFS_OEM_IMAGE_HEIGHT": "28", // "USERPREFS_OEM_IMAGE_DATA": "{ 0x00, 0x00, 0xF0, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x00, 0x00, 0x00, 0xC0, 0x07, 0x80, 0x0F, 0x00, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x18, 0xFF, 0xFF, 0x61, 0x00, 0x00, 0x00, 0x0C, 0xFF, 0xFF, 0xC7, 0x00, 0x00, 0x00, 0x0C, 0xFF, 0xFF, 0xC7, 0x00, 0x00, 0x00, 0x18, 0xFF, 0xFF, 0x67, 0x00, 0x00, 0x00, 0x18, 0x1F, 0xF0, 0x67, 0x00, 0x00, 0x00, 0x30, 0x1F, 0xF8, 0x33, 0x00, 0x00, 0x00, 0x30, 0x00, 0xFC, 0x31, 0x00, 0x00, 0x00, 0x60, 0x00, 0xFE, 0x18, 0x00, 0x00, 0x00, 0x60, 0x00, 0x7E, 0x18, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x3F, 0x0C, 0x00, 0x00, 0x00, 0xC0, 0x80, 0x1F, 0x0C, 0x00, 0x00, 0x00, 0x80, 0x81, 0x1F, 0x06, 0x00, 0x00, 0x00, 0x80, 0xC1, 0x0F, 0x06, 0x00, 0x00, 0x00, 0x00, 0xC3, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0xC3, 0x0F, 0x03, 0x00, 0x00, 0x00, 0x00, 0xE6, 0x8F, 0x01, 0x00, 0x00, 0x00, 0x00, 0xEE, 0xC7, 0x01, 0x00, 0x00, 0x00, 0x00, 0x0C, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x07, 0x00, 0x00, 0x00}", + // "USERPREFS_NETWORK_ENABLED_PROTOCOLS": "1", // Enable UDP mesh + // "USERPREFS_NETWORK_WIFI_ENABLED": "true", + // "USERPREFS_NETWORK_WIFI_SSID": "wifi_ssid", + // "USERPREFS_NETWORK_WIFI_PSK": "wifi_psk", "USERPREFS_TZ_STRING": "tzplaceholder " } diff --git a/variants/CDEBYTE_E77-MBL/platformio.ini b/variants/CDEBYTE_E77-MBL/platformio.ini index a8d90f676..8a8002086 100644 --- a/variants/CDEBYTE_E77-MBL/platformio.ini +++ b/variants/CDEBYTE_E77-MBL/platformio.ini @@ -1,8 +1,7 @@ [env:CDEBYTE_E77-MBL] extends = stm32_base -; `ebyte_e77_dev` was added in this commit. Remove when a new release is used in the base. -platform = https://github.com/platformio/platform-ststm32.git#3208828db447f4373cd303b7f7393c8fc0dae623 board = ebyte_e77_dev +board_upload.maximum_size = 233472 ; reserve the last 28KB for filesystem board_level = extra build_flags = ${stm32_base.build_flags} @@ -11,31 +10,19 @@ build_flags = -DPIN_SERIAL_RX=PA3 -DPIN_SERIAL_TX=PA2 -DHAL_DAC_MODULE_ONLY - -DHAL_ADC_MODULE_DISABLED - -DHAL_COMP_MODULE_DISABLED - -DHAL_CRC_MODULE_DISABLED - -DHAL_CRYP_MODULE_DISABLED - -DHAL_GTZC_MODULE_DISABLED - -DHAL_HSEM_MODULE_DISABLED - -DHAL_I2C_MODULE_DISABLED - -DHAL_I2S_MODULE_DISABLED - -DHAL_IPCC_MODULE_DISABLED - -DHAL_IRDA_MODULE_DISABLED - -DHAL_IWDG_MODULE_DISABLED - -DHAL_LPTIM_MODULE_DISABLED - -DHAL_PKA_MODULE_DISABLED - -DHAL_RNG_MODULE_DISABLED - -DHAL_RTC_MODULE_DISABLED - -DHAL_SMARTCARD_MODULE_DISABLED - -DHAL_SMBUS_MODULE_DISABLED - -DHAL_TIM_MODULE_DISABLED - -DHAL_WWDG_MODULE_DISABLED - -DHAL_EXTI_MODULE_DISABLED - -DHAL_SAI_MODULE_DISABLED - -DHAL_ICACHE_MODULE_DISABLED + -DHAL_RNG_MODULE_ENABLED -DRADIOLIB_EXCLUDE_SX128X=1 -DRADIOLIB_EXCLUDE_SX127X=1 -DRADIOLIB_EXCLUDE_LR11X0=1 -; -D PIO_FRAMEWORK_ARDUINO_NANOLIB_FLOAT_PRINTF + -DMESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR=1 + -DMESHTASTIC_EXCLUDE_I2C=1 + -DMESHTASTIC_EXCLUDE_WIFI=1 + -DMESHTASTIC_EXCLUDE_BLUETOOTH=1 + -DMESHTASTIC_EXCLUDE_GPS=1 + -DMESHTASTIC_EXCLUDE_SCREEN=1 + -DMESHTASTIC_EXCLUDE_MQTT=1 + -DMESHTASTIC_EXCLUDE_POWERMON=1 + ;-DPIO_FRAMEWORK_ARDUINO_NANOLIB_FLOAT_PRINTF + ;-DCFG_DEBUG upload_port = stlink \ No newline at end of file diff --git a/variants/ELECROW-ThinkNode-M1/platformio.ini b/variants/ELECROW-ThinkNode-M1/platformio.ini new file mode 100644 index 000000000..f37f6d310 --- /dev/null +++ b/variants/ELECROW-ThinkNode-M1/platformio.ini @@ -0,0 +1,29 @@ +; First prototype eink/nrf52840/sx1262 device +[env:thinknode_m1] +extends = nrf52840_base +board = ThinkNode-M1 +board_check = true +debug_tool = jlink + +# add -DCFG_SYSVIEW if you want to use the Segger systemview tool for OS profiling. +build_flags = ${nrf52840_base.build_flags} -Ivariants/ELECROW-ThinkNode-M1 + -DELECROW_ThinkNode_M1 + -DGPS_POWER_TOGGLE + -L "${platformio.libdeps_dir}/${this.__env__}/bsec2/src/cortex-m4/fpv4-sp-d16-hard" + -DEINK_DISPLAY_MODEL=GxEPD2_154_D67 + -DEINK_WIDTH=200 + -DEINK_HEIGHT=200 + -DUSE_EINK_DYNAMICDISPLAY ; Enable Dynamic EInk + -DEINK_LIMIT_FASTREFRESH=10 ; How many consecutive fast-refreshes are permitted //20 + -DEINK_LIMIT_RATE_BACKGROUND_SEC=10 ; Minimum interval between BACKGROUND updates //30 + -DEINK_LIMIT_RATE_RESPONSIVE_SEC=1 ; Minimum interval between RESPONSIVE updates +; -DEINK_LIMIT_GHOSTING_PX=2000 ; (Optional) How much image ghosting is tolerated + -DEINK_BACKGROUND_USES_FAST ; (Optional) Use FAST refresh for both BACKGROUND and RESPONSIVE, until a limit is reached. + +build_src_filter = ${nrf52_base.build_src_filter} +<../variants/ELECROW-ThinkNode-M1> +lib_deps = + ${nrf52840_base.lib_deps} + https://github.com/meshtastic/GxEPD2/archive/33db3fa8ee6fc47d160bdb44f8f127c9a9203a10.zip + lewisxhe/PCF8563_Library@^1.0.1 + khoih-prog/nRF52_PWM@^1.0.1 +;upload_protocol = fs \ No newline at end of file diff --git a/variants/ELECROW-ThinkNode-M1/variant.cpp b/variants/ELECROW-ThinkNode-M1/variant.cpp new file mode 100644 index 000000000..cae079b74 --- /dev/null +++ b/variants/ELECROW-ThinkNode-M1/variant.cpp @@ -0,0 +1,44 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + Copyright (c) 2016 Sandeep Mistry All right reserved. + Copyright (c) 2018, Adafruit Industries (adafruit.com) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "variant.h" +#include "nrf.h" +#include "wiring_constants.h" +#include "wiring_digital.h" + +const uint32_t g_ADigitalPinMap[] = { + // P0 - pins 0 and 1 are hardwired for xtal and should never be enabled + 0xff, 0xff, 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, 29, 30, 31, + + // P1 + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47}; + +void initVariant() +{ + // LED1 & LED2 + pinMode(PIN_LED1, OUTPUT); + ledOff(PIN_LED1); + + pinMode(PIN_LED2, OUTPUT); + ledOff(PIN_LED2); + + pinMode(PIN_LED3, OUTPUT); + ledOff(PIN_LED3); +} diff --git a/variants/ELECROW-ThinkNode-M1/variant.h b/variants/ELECROW-ThinkNode-M1/variant.h new file mode 100644 index 000000000..3bfa360f6 --- /dev/null +++ b/variants/ELECROW-ThinkNode-M1/variant.h @@ -0,0 +1,205 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + Copyright (c) 2016 Sandeep Mistry All right reserved. + Copyright (c) 2018, Adafruit Industries (adafruit.com) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU Lesser General Public License for more details. + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _VARIANT_ELECROW_EINK_V1_0_ +#define _VARIANT_ELECROW_EINK_V1_0_ + +/** Master clock frequency */ +#define VARIANT_MCK (64000000ul) + +#define USE_LFXO // Board uses 32khz crystal for LF + +/*---------------------------------------------------------------------------- + * Headers + *----------------------------------------------------------------------------*/ + +#include "WVariant.h" + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// Number of pins defined in PinDescription array +// 在PinDescription数组中定义的引脚数 +#define PINS_COUNT (48) +#define NUM_DIGITAL_PINS (48) +#define NUM_ANALOG_INPUTS (1) +#define NUM_ANALOG_OUTPUTS (0) + +#define PIN_LED1 -1 +#define PIN_LED2 -1 +#define PIN_LED3 -1 + +// LED +#define POWER_LED (32 + 6) // red +#define LED_POWER (32 + 4) +#define USER_LED (0 + 13) // green +// USB_CHECK +#define USB_CHECK (32 + 3) +#define ADC_V (0 + 8) + +#define LED_RED PIN_LED3 +#define LED_BLUE PIN_LED1 +#define LED_GREEN PIN_LED2 +#define LED_BUILTIN LED_BLUE +#define LED_CONN PIN_GREEN +#define LED_STATE_ON 0 // State when LED is lit // LED灯亮时的状态 +#define M1_buzzer (0 + 6) +/* + * Buttons + */ +#define PIN_BUTTON2 (32 + 10) +#define PIN_BUTTON1 (32 + 7) + +// #define PIN_BUTTON1 (0 + 11) +// #define PIN_BUTTON1 (32 + 7) + +// #define BUTTON_CLICK_MS 400 +// #define BUTTON_TOUCH_MS 200 + +/* + * Analog pins + */ +#define PIN_A0 (4) // Battery ADC + +#define BATTERY_PIN PIN_A0 + +static const uint8_t A0 = PIN_A0; + +#define ADC_RESOLUTION 14 + +#define PIN_NFC1 (9) +#define PIN_NFC2 (10) + +/*Wire Interfaces*/ +#define WIRE_INTERFACES_COUNT 1 + +#define PIN_WIRE_SDA (26) +#define PIN_WIRE_SCL (27) + +/* touch sensor, active high */ + +#define TP_SER_IO (0 + 11) + +#define PIN_RTC_INT (0 + 16) // Interrupt from the PCF8563 RTC + +/* +External serial flash WP25R1635FZUIL0 +*/ + +// QSPI Pins +#define PIN_QSPI_SCK (32 + 14) +#define PIN_QSPI_CS (32 + 15) +#define PIN_QSPI_IO0 (32 + 12) // MOSI if using two bit interface +#define PIN_QSPI_IO1 (32 + 13) // MISO if using two bit interface +#define PIN_QSPI_IO2 (0 + 7) // WP if using two bit interface (i.e. not used) +#define PIN_QSPI_IO3 (0 + 5) // HOLD if using two bit interface (i.e. not used) + +// On-board QSPI Flash +#define EXTERNAL_FLASH_DEVICES MX25R1635F +#define EXTERNAL_FLASH_USE_QSPI + +/* + * Lora radio + */ +#define SX126X_POWER_EN (0 + 21) +#define USE_SX1262 +#define SX126X_CS (0 + 24) // FIXME - we really should define LORA_CS instead +#define SX126X_DIO1 (0 + 20) +// Note DIO2 is attached internally to the module to an analog switch for TX/RX switching +// #define SX1262_DIO3 (0 + 21) // This is used as an *output* from the sx1262 and connected internally to power the tcxo, do not +// drive from the main +#define SX126X_BUSY (0 + 17) +#define SX126X_RESET (0 + 25) +#define SX126X_DIO2_AS_RF_SWITCH +#define SX126X_DIO3_TCXO_VOLTAGE 3.3 + +#define PIN_EINK_EN (32 + 11) // Note: this is really just backlight power +#define PIN_EINK_CS (0 + 30) +#define PIN_EINK_BUSY (0 + 3) +#define PIN_EINK_DC (0 + 28) +#define PIN_EINK_RES (0 + 2) +#define PIN_EINK_SCLK (0 + 31) +#define PIN_EINK_MOSI (0 + 29) // also called SDI + +// Controls power for all peripherals (eink + GPS + LoRa + Sensor) +#define PIN_POWER_EN (0 + 12) + +#define USE_EINK + +#define PIN_SPI1_MISO (32 + 7) +#define PIN_SPI1_MOSI PIN_EINK_MOSI +#define PIN_SPI1_SCK PIN_EINK_SCLK + +/* + * GPS pins + */ +// #define HAS_GPS 1 +#define GPS_L76K +#define GPS_BAUDRATE 9600 +#define PIN_GPS_REINIT (32 + 5) // An output to reset L76K GPS. As per datasheet, low for > 100ms will reset the L76K +#define PIN_GPS_STANDBY (32 + 2) // An output to wake GPS, low means allow sleep, high means force wake +// Seems to be missing on this new board +// #define PIN_GPS_PPS (32 + 4) // Pulse per second input from the GPS +#define GPS_TX_PIN (32 + 9) // This is for bits going TOWARDS the CPU +#define GPS_RX_PIN (32 + 8) // This is for bits going TOWARDS the GPS + +#define GPS_THREAD_INTERVAL 50 + +#define PIN_GPS_PPS (32 + 1) // GPS开关判断 + +#define PIN_SERIAL1_RX GPS_TX_PIN +#define PIN_SERIAL1_TX GPS_RX_PIN + +// PCF8563 RTC Module +#define PCF8563_RTC 0x51 + +/* + * SPI Interfaces + */ +#define SPI_INTERFACES_COUNT 2 + +// For LORA, spi 0 +#define PIN_SPI_MISO (0 + 23) +#define PIN_SPI_MOSI (0 + 22) +#define PIN_SPI_SCK (0 + 19) + +#define PIN_PWR_EN (0 + 6) + +// To debug via the segger JLINK console rather than the CDC-ACM serial device +// #define USE_SEGGER + +// Battery +// The battery sense is hooked to pin A0 (4) +// it is defined in the anlaolgue pin section of this file +// and has 12 bit resolution +#define BATTERY_SENSE_RESOLUTION_BITS 12 +#define BATTERY_SENSE_RESOLUTION 4096.0 +#undef AREF_VOLTAGE +#define AREF_VOLTAGE 3.0 +#define VBAT_AR_INTERNAL AR_INTERNAL_3_0 +#define ADC_MULTIPLIER (2.02F) + +// #define HAS_RTC 0 +// #define HAS_SCREEN 0 + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/variants/ELECROW-ThinkNode-M2/pins_arduino.h b/variants/ELECROW-ThinkNode-M2/pins_arduino.h new file mode 100644 index 000000000..46415d30f --- /dev/null +++ b/variants/ELECROW-ThinkNode-M2/pins_arduino.h @@ -0,0 +1,28 @@ +// Need this file for ESP32-S3 +// No need to modify this file, changes to pins imported from variant.h +// Most is similar to https://github.com/espressif/arduino-esp32/blob/master/variants/esp32s3/pins_arduino.h + +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include +#include + +#define USB_VID 0x303a +#define USB_PID 0x1001 + +// Serial +static const uint8_t TX = UART_TX; +static const uint8_t RX = UART_RX; + +// Default SPI will be mapped to Radio +static const uint8_t SS = LORA_CS; +static const uint8_t SCK = LORA_SCK; +static const uint8_t MOSI = LORA_MOSI; +static const uint8_t MISO = LORA_MISO; + +// The default Wire will be mapped to PMU and RTC +static const uint8_t SCL = I2C_SCL; +static const uint8_t SDA = I2C_SDA; + +#endif /* Pins_Arduino_h */ diff --git a/variants/ELECROW-ThinkNode-M2/platformio.ini b/variants/ELECROW-ThinkNode-M2/platformio.ini new file mode 100644 index 000000000..c08c94a71 --- /dev/null +++ b/variants/ELECROW-ThinkNode-M2/platformio.ini @@ -0,0 +1,7 @@ +[env:thinknode_m2] +extends = esp32s3_base +board = ESP32-S3-WROOM-1-N4 +build_flags = + ${esp32s3_base.build_flags} + -D ELECROW_ThinkNode_M2 + -I variants/ELECROW-ThinkNode-M2 diff --git a/variants/ELECROW-ThinkNode-M2/variant.h b/variants/ELECROW-ThinkNode-M2/variant.h new file mode 100644 index 000000000..801d5606f --- /dev/null +++ b/variants/ELECROW-ThinkNode-M2/variant.h @@ -0,0 +1,64 @@ +// Status +#define LED_PIN_POWER 1 +#define BIAS_T_ENABLE LED_PIN_POWER +#define BIAS_T_VALUE HIGH + +#define PIN_BUTTON1 47 // 功能键 +#define PIN_BUTTON2 4 // 电源键 + +#define POWER_CFG +#define POWER_CHRG 6 +#define POWER_FULL 42 + +#define PIN_BUZZER 5 + +#define I2C_SCL 15 +#define I2C_SDA 16 + +#define UART_TX 43 +#define UART_RX 44 + +#define VEXT_ENABLE 46 // for OLED +#define VEXT_ON_VALUE HIGH + +#define SX126X_CS 10 +#define LORA_SCK 12 +#define LORA_MOSI 11 +#define LORA_MISO 13 +#define SX126X_RESET 21 +#define SX126X_BUSY 14 +#define SX126X_DIO1 3 +#define SX126X_DIO2_AS_RF_SWITCH +// #define SX126X_DIO3 9 +#define SX126X_DIO3_TCXO_VOLTAGE 3.3 + +#define SX126X_MAX_POWER 22 // SX126xInterface.cpp defaults to 22 if not defined, but here we define it for good practice +#define USE_SX1262 +#define LORA_CS SX126X_CS // FIXME: for some reason both are used in /src +#define LORA_DIO1 SX126X_DIO1 +#define SX126X_POWER_EN 48 + +// Battery +// #define BATTERY_PIN 2 +#define BATTERY_PIN 17 +// #define ADC_CHANNEL ADC1_GPIO2_CHANNEL +#define ADC_CHANNEL ADC2_GPIO17_CHANNEL +#define BATTERY_SENSE_RESOLUTION_BITS 12 +#define BATTERY_SENSE_RESOLUTION 4096.0 +#undef AREF_VOLTAGE +#define AREF_VOLTAGE 3.0 +#define VBAT_AR_INTERNAL AR_INTERNAL_3_0 +#define ADC_MULTIPLIER (1.548F) +#define BAT_MEASURE_ADC_UNIT 2 + +#define HAS_SCREEN 1 +#define USE_SH1106 1 + +// PCF8563 RTC Module +// #define PCF8563_RTC 0x51 +// #define PIN_RTC_INT 48 // Interrupt from the PCF8563 RTC +#define HAS_RTC 0 +#define HAS_GPS 0 + +#define BUTTON_PIN PIN_BUTTON1 +#define BUTTON_PIN_ALT PIN_BUTTON2 diff --git a/variants/MakePython_nRF52840_eink/platformio.ini b/variants/MakePython_nRF52840_eink/platformio.ini index b7ce97dcb..9e2d5bbf7 100644 --- a/variants/MakePython_nRF52840_eink/platformio.ini +++ b/variants/MakePython_nRF52840_eink/platformio.ini @@ -11,7 +11,7 @@ build_flags = ${nrf52840_base.build_flags} -Ivariants/MakePython_nRF52840_eink - build_src_filter = ${nrf52_base.build_src_filter} +<../variants/MakePython_nRF52840_eink> lib_deps = ${nrf52840_base.lib_deps} - https://github.com/meshtastic/ESP32_Codec2.git#633326c78ac251c059ab3a8c430fcdf25b41672f + https://github.com/meshtastic/ESP32_Codec2/archive/633326c78ac251c059ab3a8c430fcdf25b41672f.zip zinggjm/GxEPD2@^1.6.2 debug_tool = jlink ;upload_port = /dev/ttyACM4 \ No newline at end of file diff --git a/variants/MakePython_nRF52840_oled/platformio.ini b/variants/MakePython_nRF52840_oled/platformio.ini index 0146385e0..25dd36c08 100644 --- a/variants/MakePython_nRF52840_oled/platformio.ini +++ b/variants/MakePython_nRF52840_oled/platformio.ini @@ -7,5 +7,5 @@ build_flags = ${nrf52840_base.build_flags} -Ivariants/MakePython_nRF52840_oled - build_src_filter = ${nrf52_base.build_src_filter} +<../variants/MakePython_nRF52840_oled> lib_deps = ${nrf52840_base.lib_deps} - https://github.com/meshtastic/ESP32_Codec2.git#633326c78ac251c059ab3a8c430fcdf25b41672f + https://github.com/meshtastic/ESP32_Codec2/archive/633326c78ac251c059ab3a8c430fcdf25b41672f.zip debug_tool = jlink diff --git a/variants/crowpanel-esp32s3-5-epaper/platformio.ini b/variants/crowpanel-esp32s3-5-epaper/platformio.ini index 36816d616..f1257a979 100644 --- a/variants/crowpanel-esp32s3-5-epaper/platformio.ini +++ b/variants/crowpanel-esp32s3-5-epaper/platformio.ini @@ -24,7 +24,7 @@ build_flags = ;-DEINK_LIMIT_RATE_RESPONSIVE_SEC=1 lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2 + https://github.com/meshtastic/GxEPD2/archive/33db3fa8ee6fc47d160bdb44f8f127c9a9203a10.zip [env:crowpanel-esp32s3-4-epaper] extends = esp32s3_base @@ -39,7 +39,7 @@ board = esp32-s3-devkitc-1 board_level = extra upload_protocol = esptool build_flags = - ${esp32_base.build_flags} -D CROWPANEL_ESP32S3_5_EPAPER -I variants/crowpanel-esp32s3-5-epaper + ${esp32_base.build_flags} -D CROWPANEL_ESP32S3_4_EPAPER -I variants/crowpanel-esp32s3-5-epaper -D PRIVATE_HW -DBOARD_HAS_PSRAM -DGPS_POWER_TOGGLE @@ -52,7 +52,7 @@ build_flags = ;-DEINK_LIMIT_RATE_RESPONSIVE_SEC=1 lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2 + https://github.com/meshtastic/GxEPD2/archive/33db3fa8ee6fc47d160bdb44f8f127c9a9203a10.zip [env:crowpanel-esp32s3-2-epaper] extends = esp32s3_base @@ -67,7 +67,7 @@ board = esp32-s3-devkitc-1 board_level = extra upload_protocol = esptool build_flags = - ${esp32_base.build_flags} -D CROWPANEL_ESP32S3_5_EPAPER -I variants/crowpanel-esp32s3-5-epaper + ${esp32_base.build_flags} -D CROWPANEL_ESP32S3_2_EPAPER -I variants/crowpanel-esp32s3-5-epaper -D PRIVATE_HW -DBOARD_HAS_PSRAM -DGPS_POWER_TOGGLE @@ -80,4 +80,4 @@ build_flags = ;-DEINK_LIMIT_RATE_RESPONSIVE_SEC=1 lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2 + https://github.com/meshtastic/GxEPD2/archive/33db3fa8ee6fc47d160bdb44f8f127c9a9203a10.zip diff --git a/variants/hackerboxes_esp32_io/platformio.ini b/variants/hackerboxes_esp32_io/platformio.ini new file mode 100644 index 000000000..f024dac3e --- /dev/null +++ b/variants/hackerboxes_esp32_io/platformio.ini @@ -0,0 +1,12 @@ +[env:hackerboxes-esp32-io] +extends = esp32_base +board = esp32dev +board_level = extra +build_flags = + ${esp32_base.build_flags} + -D PRIVATE_HW + -I variants/hackerboxes_esp32_io +monitor_speed = 115200 +upload_protocol = esptool +;upload_port = /dev/ttyUSB0 +upload_speed = 921600 \ No newline at end of file diff --git a/variants/hackerboxes_esp32_io/variant.h b/variants/hackerboxes_esp32_io/variant.h new file mode 100644 index 000000000..06f0032ee --- /dev/null +++ b/variants/hackerboxes_esp32_io/variant.h @@ -0,0 +1,30 @@ +#define BUTTON_PIN 0 + +// HACKBOX LoRa IO Kit +// Uses a ESP-32-WROOM and a RA-01SH (SX1262) LoRa Board + +#define LED_PIN 2 // LED +#define LED_STATE_ON 1 // State when LED is lit + +#define HAS_SCREEN 0 +#define HAS_GPS 0 +#undef GPS_RX_PIN +#undef GPS_TX_PIN + +#define USE_SX1262 +#define LORA_SCK 18 +#define LORA_MISO 19 +#define LORA_MOSI 23 +#define LORA_CS 5 +#define LORA_DIO0 RADIOLIB_NC +#define LORA_RESET 27 +#define LORA_DIO1 33 +#define LORA_DIO2 RADIOLIB_NC +#define LORA_BUSY 32 + +#define SX126X_DIO2_AS_RF_SWITCH +#define SX126X_CS LORA_CS +#define SX126X_DIO1 LORA_DIO1 +#define SX126X_BUSY LORA_BUSY +#define SX126X_RESET LORA_RESET +#define SX126X_MAX_POWER 22 // Max power of the RA-01SH is 22db \ No newline at end of file diff --git a/variants/hackerboxes_esp32c3_oled/platformio.ini b/variants/hackerboxes_esp32c3_oled/platformio.ini new file mode 100644 index 000000000..4fcbf2ade --- /dev/null +++ b/variants/hackerboxes_esp32c3_oled/platformio.ini @@ -0,0 +1,14 @@ +[env:hackerboxes-esp32c3-oled] +extends = esp32c3_base +board = esp32-c3-devkitm-1 +board_level = extra +build_flags = + ${esp32_base.build_flags} + -D PRIVATE_HW + -D ARDUINO_USB_MODE=1 + -D ARDUINO_USB_CDC_ON_BOOT=1 + -I variants/hackerboxes_esp32c3_oled +monitor_speed = 115200 +upload_protocol = esptool +;upload_port = /dev/ttyUSB0 +upload_speed = 921600 \ No newline at end of file diff --git a/variants/hackerboxes_esp32c3_oled/variant.h b/variants/hackerboxes_esp32c3_oled/variant.h new file mode 100644 index 000000000..7432a9941 --- /dev/null +++ b/variants/hackerboxes_esp32c3_oled/variant.h @@ -0,0 +1,36 @@ +#define BUTTON_PIN 9 + +// Hackerboxes LoRa ESP32-C3 OLED Kit +// Uses a ESP32-C3 OLED Board and a RA-01SH (SX1262) LoRa Board + +#define LED_PIN 8 // LED +#define LED_STATE_ON 1 // State when LED is lit + +#define HAS_SCREEN 0 +#define HAS_GPS 0 +#undef GPS_RX_PIN +#undef GPS_TX_PIN + +// #define USE_SSD1306_72_40 +// #define I2C_SDA 5 // I2C pins for this board +// #define I2C_SCL 6 // +// #define TFT_WIDTH 72 +// #define TFT_HEIGHT 40 + +#define USE_SX1262 +#define LORA_SCK 4 +#define LORA_MISO 7 +#define LORA_MOSI 3 +#define LORA_CS 1 +#define LORA_DIO0 RADIOLIB_NC +#define LORA_RESET 0 +#define LORA_DIO1 20 +#define LORA_DIO2 RADIOLIB_NC +#define LORA_BUSY 10 + +#define SX126X_DIO2_AS_RF_SWITCH +#define SX126X_CS LORA_CS +#define SX126X_DIO1 LORA_DIO1 +#define SX126X_BUSY LORA_BUSY +#define SX126X_RESET LORA_RESET +#define SX126X_MAX_POWER 22 // Max power of the RA-01SH is 22db \ No newline at end of file diff --git a/variants/heltec_mesh_node_t114/platformio.ini b/variants/heltec_mesh_node_t114/platformio.ini index 1b06c7f5e..4f83d8516 100644 --- a/variants/heltec_mesh_node_t114/platformio.ini +++ b/variants/heltec_mesh_node_t114/platformio.ini @@ -14,4 +14,4 @@ build_src_filter = ${nrf52_base.build_src_filter} +<../variants/heltec_mesh_node lib_deps = ${nrf52840_base.lib_deps} lewisxhe/PCF8563_Library@^1.0.1 - https://github.com/meshtastic/st7789#bd33ea58ddfe4a5e4a66d53300ccbd38d66ac21f \ No newline at end of file + https://github.com/meshtastic/st7789/archive/bd33ea58ddfe4a5e4a66d53300ccbd38d66ac21f.zip \ No newline at end of file diff --git a/variants/heltec_sensor_hub/platformio.ini b/variants/heltec_sensor_hub/platformio.ini new file mode 100644 index 000000000..53f84fab4 --- /dev/null +++ b/variants/heltec_sensor_hub/platformio.ini @@ -0,0 +1,11 @@ +[env:heltec_sensor_hub] +extends = esp32s3_base +board = heltec_wifi_lora_32_V3 +board_check = true + +build_flags = + ${esp32s3_base.build_flags} -I variants/heltec_sensor_hub + -D HELTEC_SENSOR_HUB + +lib_deps = ${esp32s3_base.lib_deps} + adafruit/Adafruit NeoPixel @ ^1.12.0 diff --git a/variants/heltec_sensor_hub/variant.h b/variants/heltec_sensor_hub/variant.h new file mode 100644 index 000000000..771cefee3 --- /dev/null +++ b/variants/heltec_sensor_hub/variant.h @@ -0,0 +1,46 @@ +#define EXT_PWR_DETECT 20 + +#define BUTTON_PIN 17 + +#define BATTERY_PIN 7 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage +#define ADC_CHANNEL ADC1_GPIO7_CHANNEL +#define ADC_ATTENUATION ADC_ATTEN_DB_2_5 // lower dB for high resistance voltage divider +#define ADC_MULTIPLIER (4.9 * 1.045) +#define ADC_CTRL 34 // active HIGH, powers the voltage divider. Only on 1.1 +#define ADC_CTRL_ENABLED HIGH + +#define HAS_NEOPIXEL // Enable the use of neopixels +#define NEOPIXEL_COUNT 1 // How many neopixels are connected +#define NEOPIXEL_DATA 18 // gpio pin used to send data to the neopixels +#define NEOPIXEL_TYPE (NEO_GRB + NEO_KHZ800) // type of neopixels in use + +#define USE_SX1262 +#define LORA_DIO0 RADIOLIB_NC +#define LORA_RESET 12 +#define LORA_DIO1 14 // SX1262 IRQ +#define LORA_DIO2 13 // SX1262 BUSY + +#define LORA_SCK 9 +#define LORA_MISO 11 +#define LORA_MOSI 10 +#define LORA_CS 8 + +#define SX126X_CS LORA_CS +#define SX126X_DIO1 LORA_DIO1 +#define SX126X_BUSY LORA_DIO2 +#define SX126X_RESET LORA_RESET + +#define SX126X_DIO2_AS_RF_SWITCH +#define SX126X_DIO3_TCXO_VOLTAGE 1.8 + +#define I2C_SDA 1 +#define I2C_SCL 2 +#define HAS_SCREEN 0 +#define SENSOR_POWER_CTRL_PIN 33 +#define SENSOR_POWER_ON 1 + +#define PERIPHERAL_WARMUP_MS 100 + +#define ESP32S3_WAKE_TYPE ESP_EXT1_WAKEUP_ANY_HIGH + +#define ENVIRONMENTAL_TELEMETRY_MODULE_ENABLE 1 \ No newline at end of file diff --git a/variants/heltec_vision_master_e213/nicheGraphics.h b/variants/heltec_vision_master_e213/nicheGraphics.h index b14c72896..d6983bafe 100644 --- a/variants/heltec_vision_master_e213/nicheGraphics.h +++ b/variants/heltec_vision_master_e213/nicheGraphics.h @@ -67,25 +67,20 @@ void setupNicheGraphics() InkHUD::Applet::fontSmall.addSubstitutionsWin1251(); */ - // Init settings, and customize defaults + // Customize default settings inkhud->persistence->settings.userTiles.maxCount = 2; // How many tiles can the display handle? inkhud->persistence->settings.rotation = 3; // 270 degrees clockwise inkhud->persistence->settings.userTiles.count = 1; // One tile only by default, keep things simple for new users inkhud->persistence->settings.optionalMenuItems.nextTile = false; // Behavior handled by aux button instead // Pick applets - // Note: order of applets determines priority of "auto-show" feature - // Optional arguments for defaults: - // - is activated? - // - is autoshown? - // - is foreground on a specific tile (index)? inkhud->addApplet("All Messages", new InkHUD::AllMessageApplet, true, true); // Activated, autoshown - inkhud->addApplet("DMs", new InkHUD::DMApplet); - inkhud->addApplet("Channel 0", new InkHUD::ThreadedMessageApplet(0)); - inkhud->addApplet("Channel 1", new InkHUD::ThreadedMessageApplet(1)); - inkhud->addApplet("Positions", new InkHUD::PositionsApplet, true); // Activated - inkhud->addApplet("Recents List", new InkHUD::RecentsListApplet); - inkhud->addApplet("Heard", new InkHUD::HeardApplet, true, false, 0); // Activated, not autoshown, default on tile 0 + inkhud->addApplet("DMs", new InkHUD::DMApplet); // Inactive + inkhud->addApplet("Channel 0", new InkHUD::ThreadedMessageApplet(0)); // Inactive + inkhud->addApplet("Channel 1", new InkHUD::ThreadedMessageApplet(1)); // Inactive + inkhud->addApplet("Positions", new InkHUD::PositionsApplet, true); // Activated + inkhud->addApplet("Recents List", new InkHUD::RecentsListApplet); // Inactive + inkhud->addApplet("Heard", new InkHUD::HeardApplet, true, false, 0); // Activated, not autoshown, default on tile 0 // inkhud->addApplet("Basic", new InkHUD::BasicExampleApplet); // inkhud->addApplet("NewMsg", new InkHUD::NewMsgExampleApplet); @@ -100,7 +95,7 @@ void setupNicheGraphics() constexpr uint8_t AUX_BUTTON = 1; // Setup the main user button - buttons->setWiring(MAIN_BUTTON, BUTTON_PIN); + buttons->setWiring(MAIN_BUTTON, Inputs::TwoButton::getUserButtonPin()); buttons->setHandlerShortPress(MAIN_BUTTON, []() { InkHUD::InkHUD::getInstance()->shortpress(); }); buttons->setHandlerLongPress(MAIN_BUTTON, []() { InkHUD::InkHUD::getInstance()->longpress(); }); diff --git a/variants/heltec_vision_master_e213/platformio.ini b/variants/heltec_vision_master_e213/platformio.ini index 4bed30324..037d10168 100644 --- a/variants/heltec_vision_master_e213/platformio.ini +++ b/variants/heltec_vision_master_e213/platformio.ini @@ -16,7 +16,7 @@ build_flags = -DEINK_HASQUIRK_GHOSTING ; Display model is identified as "prone to ghosting" lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2#b202ebfec6a4821e098cf7a625ba0f6f2400292d + https://github.com/meshtastic/GxEPD2/archive/b202ebfec6a4821e098cf7a625ba0f6f2400292d.zip lewisxhe/PCF8563_Library@^1.0.1 upload_speed = 115200 diff --git a/variants/heltec_vision_master_e290/nicheGraphics.h b/variants/heltec_vision_master_e290/nicheGraphics.h index c14ee76ec..c2f26c7ff 100644 --- a/variants/heltec_vision_master_e290/nicheGraphics.h +++ b/variants/heltec_vision_master_e290/nicheGraphics.h @@ -19,7 +19,7 @@ Different NicheGraphics UIs and different hardware variants will each have their // InkHUD-specific components // --------------------------- -#include "graphics/niche/InkHUD/WindowManager.h" +#include "graphics/niche/InkHUD/InkHUD.h" // Applets #include "graphics/niche/InkHUD/Applets/User/AllMessage/AllMessageApplet.h" @@ -80,25 +80,27 @@ void setupNicheGraphics() InkHUD::Applet::fontSmall.addSubstitutionsWin1251(); */ - // Init settings, and customize defaults + // Customize default settings inkhud->persistence->settings.userTiles.maxCount = 2; // How many tiles can the display handle? inkhud->persistence->settings.rotation = 1; // 90 degrees clockwise inkhud->persistence->settings.userTiles.count = 1; // One tile only by default, keep things simple for new users inkhud->persistence->settings.optionalMenuItems.nextTile = false; // Behavior handled by aux button instead // Pick applets - // Note: order of applets determines priority of "auto-show" feature - // Optional arguments for defaults: - // - is activated? - // - is autoshown? - // - is foreground on a specific tile (index)? + + // Order of applets determines priority of "auto-show" feature. + // Optional arguments for default state: + // - is activated? + // - is autoshown? + // - is foreground on a specific tile (index)? + inkhud->addApplet("All Messages", new InkHUD::AllMessageApplet, true, true); // Activated, autoshown - inkhud->addApplet("DMs", new InkHUD::DMApplet); - inkhud->addApplet("Channel 0", new InkHUD::ThreadedMessageApplet(0)); - inkhud->addApplet("Channel 1", new InkHUD::ThreadedMessageApplet(1)); - inkhud->addApplet("Positions", new InkHUD::PositionsApplet, true); // Activated - inkhud->addApplet("Recents List", new InkHUD::RecentsListApplet); - inkhud->addApplet("Heard", new InkHUD::HeardApplet, true, false, 0); // Activated, not autoshown, default on tile 0 + inkhud->addApplet("DMs", new InkHUD::DMApplet); // Inactive + inkhud->addApplet("Channel 0", new InkHUD::ThreadedMessageApplet(0)); // Inactive + inkhud->addApplet("Channel 1", new InkHUD::ThreadedMessageApplet(1)); // Inactive + inkhud->addApplet("Positions", new InkHUD::PositionsApplet, true); // Activated + inkhud->addApplet("Recents List", new InkHUD::RecentsListApplet); // Inactive + inkhud->addApplet("Heard", new InkHUD::HeardApplet, true, false, 0); // Activated, not autoshown, default on tile 0 // inkhud->addApplet("Basic", new InkHUD::BasicExampleApplet); // inkhud->addApplet("NewMsg", new InkHUD::NewMsgExampleApplet); @@ -111,7 +113,7 @@ void setupNicheGraphics() Inputs::TwoButton *buttons = Inputs::TwoButton::getInstance(); // A shared NicheGraphics component // Setup the main user button (0) - buttons->setWiring(0, BUTTON_PIN); + buttons->setWiring(0, Inputs::TwoButton::getUserButtonPin()); buttons->setHandlerShortPress(0, []() { InkHUD::InkHUD::getInstance()->shortpress(); }); buttons->setHandlerLongPress(0, []() { InkHUD::InkHUD::getInstance()->longpress(); }); diff --git a/variants/heltec_vision_master_e290/platformio.ini b/variants/heltec_vision_master_e290/platformio.ini index d28c2015b..6952e9f9e 100644 --- a/variants/heltec_vision_master_e290/platformio.ini +++ b/variants/heltec_vision_master_e290/platformio.ini @@ -20,7 +20,7 @@ build_flags = lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2#448c8538129fde3d02a7cb5e6fc81971ad92547f + https://github.com/meshtastic/GxEPD2/archive/448c8538129fde3d02a7cb5e6fc81971ad92547f.zip lewisxhe/PCF8563_Library@^1.0.1 upload_speed = 115200 diff --git a/variants/heltec_vision_master_t190/platformio.ini b/variants/heltec_vision_master_t190/platformio.ini index 53b56f57d..7f55a1be7 100644 --- a/variants/heltec_vision_master_t190/platformio.ini +++ b/variants/heltec_vision_master_t190/platformio.ini @@ -9,5 +9,5 @@ build_flags = lib_deps = ${esp32s3_base.lib_deps} lewisxhe/PCF8563_Library@^1.0.1 - https://github.com/meshtastic/st7789#bd33ea58ddfe4a5e4a66d53300ccbd38d66ac21f + https://github.com/meshtastic/st7789/archive/bd33ea58ddfe4a5e4a66d53300ccbd38d66ac21f.zip upload_speed = 921600 \ No newline at end of file diff --git a/variants/heltec_wireless_paper/nicheGraphics.h b/variants/heltec_wireless_paper/nicheGraphics.h index 44405b8f6..5e938fa64 100644 --- a/variants/heltec_wireless_paper/nicheGraphics.h +++ b/variants/heltec_wireless_paper/nicheGraphics.h @@ -67,26 +67,21 @@ void setupNicheGraphics() InkHUD::Applet::fontSmall.addSubstitutionsWin1251(); */ - // Init settings, and customize defaults + // Customize default settings inkhud->persistence->settings.userTiles.maxCount = 2; // How many tiles can the display handle? inkhud->persistence->settings.rotation = 3; // 270 degrees clockwise inkhud->persistence->settings.userTiles.count = 1; // One tile only by default, keep things simple for new users // Pick applets - // Note: order of applets determines priority of "auto-show" feature - // Optional arguments for defaults: - // - is activated? - // - is autoshown? - // - is foreground on a specific tile (index)? inkhud->addApplet("All Messages", new InkHUD::AllMessageApplet, true, true); // Activated, autoshown - inkhud->addApplet("DMs", new InkHUD::DMApplet); - inkhud->addApplet("Channel 0", new InkHUD::ThreadedMessageApplet(0)); - inkhud->addApplet("Channel 1", new InkHUD::ThreadedMessageApplet(1)); - inkhud->addApplet("Positions", new InkHUD::PositionsApplet, true); // Activated - inkhud->addApplet("Recents List", new InkHUD::RecentsListApplet); - inkhud->addApplet("Heard", new InkHUD::HeardApplet, true, false, 0); // Activated, not autoshown, default on tile 0 + inkhud->addApplet("DMs", new InkHUD::DMApplet); // Inactive + inkhud->addApplet("Channel 0", new InkHUD::ThreadedMessageApplet(0)); // Inactive + inkhud->addApplet("Channel 1", new InkHUD::ThreadedMessageApplet(1)); // Inactive + inkhud->addApplet("Positions", new InkHUD::PositionsApplet, true); // Activated + inkhud->addApplet("Recents List", new InkHUD::RecentsListApplet); // Inactive + inkhud->addApplet("Heard", new InkHUD::HeardApplet, true, false, 0); // Activated, not autoshown, default on tile 0 // inkhud->addApplet("Basic", new InkHUD::BasicExampleApplet); - // inkhud->addApplet("NewMsg", new InkHUD::NewMsgExampleApplet); + // inkhud->addApplet("NewMsg", new InkHUD::NewMsgExampleApplet); // Start running InkHUD inkhud->begin(); @@ -98,7 +93,7 @@ void setupNicheGraphics() constexpr uint8_t MAIN_BUTTON = 0; // Setup the main user button - buttons->setWiring(MAIN_BUTTON, BUTTON_PIN); + buttons->setWiring(MAIN_BUTTON, Inputs::TwoButton::getUserButtonPin()); buttons->setHandlerShortPress(MAIN_BUTTON, []() { InkHUD::InkHUD::getInstance()->shortpress(); }); buttons->setHandlerLongPress(MAIN_BUTTON, []() { InkHUD::InkHUD::getInstance()->longpress(); }); diff --git a/variants/heltec_wireless_paper/platformio.ini b/variants/heltec_wireless_paper/platformio.ini index bd25a932a..51430ebff 100644 --- a/variants/heltec_wireless_paper/platformio.ini +++ b/variants/heltec_wireless_paper/platformio.ini @@ -17,7 +17,7 @@ build_flags = -D EINK_HASQUIRK_GHOSTING ; Display model is identified as "prone to ghosting" lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2#b202ebfec6a4821e098cf7a625ba0f6f2400292d + https://github.com/meshtastic/GxEPD2/archive/b202ebfec6a4821e098cf7a625ba0f6f2400292d.zip lewisxhe/PCF8563_Library@^1.0.1 upload_speed = 115200 diff --git a/variants/heltec_wireless_paper_v1/platformio.ini b/variants/heltec_wireless_paper_v1/platformio.ini index ec5fe2408..44b0606af 100644 --- a/variants/heltec_wireless_paper_v1/platformio.ini +++ b/variants/heltec_wireless_paper_v1/platformio.ini @@ -15,6 +15,6 @@ build_flags = -D EINK_LIMIT_GHOSTING_PX=2000 ; (Optional) How much image ghosting is tolerated lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2#55f618961db45a23eff0233546430f1e5a80f63a + https://github.com/meshtastic/GxEPD2/archive/55f618961db45a23eff0233546430f1e5a80f63a.zip lewisxhe/PCF8563_Library@^1.0.1 upload_speed = 115200 \ No newline at end of file diff --git a/variants/meshlink/platformio.ini b/variants/meshlink/platformio.ini index 180dddd49..ec3506b0e 100644 --- a/variants/meshlink/platformio.ini +++ b/variants/meshlink/platformio.ini @@ -23,7 +23,7 @@ build_flags = ${nrf52840_base.build_flags} -I variants/meshlink -D MESHLINK build_src_filter = ${nrf52_base.build_src_filter} +<../variants/meshlink> lib_deps = ${nrf52840_base.lib_deps} - https://github.com/meshtastic/GxEPD2#55f618961db45a23eff0233546430f1e5a80f63a + https://github.com/meshtastic/GxEPD2/archive/55f618961db45a23eff0233546430f1e5a80f63a.zip debug_tool = jlink ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) ; Note: as of 6/2013 the serial/bootloader based programming takes approximately 30 seconds diff --git a/variants/meshlink_eink/platformio.ini b/variants/meshlink_eink/platformio.ini index db3647e73..f8ee96fc3 100644 --- a/variants/meshlink_eink/platformio.ini +++ b/variants/meshlink_eink/platformio.ini @@ -23,7 +23,7 @@ build_flags = ${nrf52840_base.build_flags} -I variants/meshlink_eink -D MESHLINK build_src_filter = ${nrf52_base.build_src_filter} +<../variants/meshlink_eink> lib_deps = ${nrf52840_base.lib_deps} - https://github.com/meshtastic/GxEPD2#55f618961db45a23eff0233546430f1e5a80f63a + https://github.com/meshtastic/GxEPD2/archive/55f618961db45a23eff0233546430f1e5a80f63a.zip debug_tool = jlink ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) ; Note: as of 6/2013 the serial/bootloader based programming takes approximately 30 seconds diff --git a/variants/monteops_hw1/platformio.ini b/variants/monteops_hw1/platformio.ini index eaa246526..1464ca7e7 100644 --- a/variants/monteops_hw1/platformio.ini +++ b/variants/monteops_hw1/platformio.ini @@ -9,7 +9,7 @@ build_src_filter = ${nrf52_base.build_src_filter} +<../variants/monteops_hw1> +< lib_deps = ${nrf52840_base.lib_deps} ${networking_base.lib_deps} - https://github.com/RAKWireless/RAK13800-W5100S.git#1.0.2 + https://github.com/RAKWireless/RAK13800-W5100S/archive/1.0.2.zip debug_tool = jlink ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) ;upload_protocol = jlink diff --git a/variants/portduino/platformio.ini b/variants/portduino/platformio.ini index 9bf3313ce..7a3392eb4 100644 --- a/variants/portduino/platformio.ini +++ b/variants/portduino/platformio.ini @@ -27,6 +27,7 @@ build_flags = ${native_base.build_flags} -Os -lX11 -linput -lxkbcommon -ffunctio -D USE_X11=1 -D HAS_TFT=1 -D HAS_SCREEN=0 + -D LV_CACHE_DEF_SIZE=6291456 -D LV_BUILD_TEST=0 -D LV_USE_LIBINPUT=1 -D LV_LVGL_H_INCLUDE_SIMPLE @@ -56,7 +57,7 @@ build_flags = ${native_base.build_flags} -O0 -fsanitize=address -lX11 -linput -l -D USE_X11=1 -D HAS_TFT=1 -D HAS_SCREEN=0 -; -D CALIBRATE_TOUCH=0 + -D LV_CACHE_DEF_SIZE=6291456 -D LV_BUILD_TEST=0 -D LV_USE_LOG=1 -D LV_USE_SYSMON=1 diff --git a/variants/radiomaster_900_bandit/platformio.ini b/variants/radiomaster_900_bandit/platformio.ini index 010791d8a..f87025937 100644 --- a/variants/radiomaster_900_bandit/platformio.ini +++ b/variants/radiomaster_900_bandit/platformio.ini @@ -13,4 +13,4 @@ board_build.f_cpu = 240000000L upload_protocol = esptool lib_deps = ${esp32_base.lib_deps} - https://github.com/gjelsoe/STK8xxx-Accelerometer.git#v0.1.1 + https://github.com/gjelsoe/STK8xxx-Accelerometer/archive/v0.1.1.zip diff --git a/variants/rak11310/platformio.ini b/variants/rak11310/platformio.ini index 6e718a651..c87304e61 100644 --- a/variants/rak11310/platformio.ini +++ b/variants/rak11310/platformio.ini @@ -15,6 +15,6 @@ lib_deps = ${rp2040_base.lib_deps} ${networking_base.lib_deps} melopero/Melopero RV3028@^1.1.0 - https://github.com/RAKWireless/RAK13800-W5100S.git#1.0.2 + https://github.com/RAKWireless/RAK13800-W5100S/archive/1.0.2.zip debug_build_flags = ${rp2040_base.build_flags}, -g debug_tool = cmsis-dap ; for e.g. Picotool \ No newline at end of file diff --git a/variants/rak2560/platformio.ini b/variants/rak2560/platformio.ini index 956f573c5..faed231f1 100644 --- a/variants/rak2560/platformio.ini +++ b/variants/rak2560/platformio.ini @@ -15,7 +15,7 @@ lib_deps = ${nrf52840_base.lib_deps} ${networking_base.lib_deps} melopero/Melopero RV3028@^1.1.0 - https://github.com/beegee-tokyo/RAK-OneWireSerial.git#0.0.2 + https://github.com/beegee-tokyo/RAK-OneWireSerial/archive/0.0.2.zip debug_tool = jlink ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) ;upload_protocol = jlink diff --git a/variants/rak3172/platformio.ini b/variants/rak3172/platformio.ini index 58ea32088..456697aef 100644 --- a/variants/rak3172/platformio.ini +++ b/variants/rak3172/platformio.ini @@ -1,36 +1,23 @@ [env:rak3172] extends = stm32_base board = wiscore_rak3172 +board_upload.maximum_size = 233472 ; reserve the last 28KB for filesystem build_flags = ${stm32_base.build_flags} -Ivariants/rak3172 - -DSERIAL_UART_INSTANCE=1 - -DPIN_SERIAL_RX=PB7 - -DPIN_SERIAL_TX=PB6 -DHAL_DAC_MODULE_ONLY - -DHAL_ADC_MODULE_DISABLED - -DHAL_COMP_MODULE_DISABLED - -DHAL_CRC_MODULE_DISABLED - -DHAL_CRYP_MODULE_DISABLED - -DHAL_GTZC_MODULE_DISABLED - -DHAL_HSEM_MODULE_DISABLED - -DHAL_I2C_MODULE_DISABLED - -DHAL_I2S_MODULE_DISABLED - -DHAL_IPCC_MODULE_DISABLED - -DHAL_IRDA_MODULE_DISABLED - -DHAL_IWDG_MODULE_DISABLED - -DHAL_LPTIM_MODULE_DISABLED - -DHAL_PKA_MODULE_DISABLED - -DHAL_RNG_MODULE_DISABLED - -DHAL_RTC_MODULE_DISABLED - -DHAL_SMARTCARD_MODULE_DISABLED - -DHAL_SMBUS_MODULE_DISABLED - -DHAL_TIM_MODULE_DISABLED - -DHAL_WWDG_MODULE_DISABLED - -DHAL_EXTI_MODULE_DISABLED - -DHAL_SAI_MODULE_DISABLED - -DHAL_ICACHE_MODULE_DISABLED + -DHAL_RNG_MODULE_ENABLED -DRADIOLIB_EXCLUDE_SX128X=1 -DRADIOLIB_EXCLUDE_SX127X=1 -DRADIOLIB_EXCLUDE_LR11X0=1 -upload_port = stlink \ No newline at end of file + -DMESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR=1 + -DMESHTASTIC_EXCLUDE_I2C=1 + -DMESHTASTIC_EXCLUDE_WIFI=1 + -DMESHTASTIC_EXCLUDE_BLUETOOTH=1 + -DMESHTASTIC_EXCLUDE_GPS=1 + -DMESHTASTIC_EXCLUDE_SCREEN=1 + -DMESHTASTIC_EXCLUDE_MQTT=1 + -DMESHTASTIC_EXCLUDE_POWERMON=1 + ;-DPIO_FRAMEWORK_ARDUINO_NANOLIB_FLOAT_PRINTF + ;-DCFG_DEBUG +upload_port = stlink diff --git a/variants/rak3172/variant.h b/variants/rak3172/variant.h index dd12fe393..45752b481 100644 --- a/variants/rak3172/variant.h +++ b/variants/rak3172/variant.h @@ -1,3 +1,8 @@ +/* +STM32WLE5 Core Module for LoRaWAN® RAK3372 +https://store.rakwireless.com/products/wisblock-core-module-rak3372 +*/ + /* This variant is a work in progress. Do not expect a working Meshtastic device with this target. @@ -8,4 +13,7 @@ Do not expect a working Meshtastic device with this target. #define USE_STM32WLx -#endif \ No newline at end of file +#define LED_PIN PA0 // Green LED +#define LED_STATE_ON 1 + +#endif diff --git a/variants/rak4631/platformio.ini b/variants/rak4631/platformio.ini index ced93df66..1c6bdabcf 100644 --- a/variants/rak4631/platformio.ini +++ b/variants/rak4631/platformio.ini @@ -17,9 +17,9 @@ lib_deps = ${nrf52840_base.lib_deps} ${networking_base.lib_deps} melopero/Melopero RV3028@^1.1.0 - https://github.com/RAKWireless/RAK13800-W5100S.git#1.0.2 + https://github.com/RAKWireless/RAK13800-W5100S/archive/1.0.2.zip rakwireless/RAKwireless NCP5623 RGB LED library@^1.0.2 - https://github.com/RAKWireless/RAK12034-BMX160.git#dcead07ffa267d3c906e9ca4a1330ab989e957e2 + https://github.com/RAKWireless/RAK12034-BMX160/archive/dcead07ffa267d3c906e9ca4a1330ab989e957e2.zip ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) ; Note: as of 6/2013 the serial/bootloader based programming takes approximately 30 seconds @@ -41,7 +41,7 @@ build_flags = lib_deps = ${env:rak4631.lib_deps} - https://github.com/geeksville/Armduino-Semihosting.git#35b538fdf208c3530c1434cd099a08e486672ee4 + https://github.com/geeksville/Armduino-Semihosting/archive/35b538fdf208c3530c1434cd099a08e486672ee4.zip ; NOTE: the pyocd support for semihosting is buggy. So I switched to using the builtin platformio support for the stlink adapter which worked much better. ; However the built in openocd version in platformio has buggy support for TCP to semihosting. diff --git a/variants/rak4631_eth_gw/platformio.ini b/variants/rak4631_eth_gw/platformio.ini index a624d0381..e3da21c55 100644 --- a/variants/rak4631_eth_gw/platformio.ini +++ b/variants/rak4631_eth_gw/platformio.ini @@ -27,9 +27,9 @@ lib_deps = ${nrf52840_base.lib_deps} ${networking_base.lib_deps} melopero/Melopero RV3028@^1.1.0 - https://github.com/RAKWireless/RAK13800-W5100S.git#1.0.2 + https://github.com/RAKWireless/RAK13800-W5100S/archive/1.0.2.zip rakwireless/RAKwireless NCP5623 RGB LED library@^1.0.2 - https://github.com/meshtastic/RAK12034-BMX160.git#4821355fb10390ba8557dc43ca29a023bcfbb9d9 + https://github.com/meshtastic/RAK12034-BMX160/archive/4821355fb10390ba8557dc43ca29a023bcfbb9d9.zip bblanchon/ArduinoJson @ 6.21.4 ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) ; Note: as of 6/2013 the serial/bootloader based programming takes approximately 30 seconds @@ -51,7 +51,7 @@ build_flags = lib_deps = ${env:rak4631_eth_gw.lib_deps} - https://github.com/geeksville/Armduino-Semihosting.git#35b538fdf208c3530c1434cd099a08e486672ee4 + https://github.com/geeksville/Armduino-Semihosting/archive/35b538fdf208c3530c1434cd099a08e486672ee4.zip ; NOTE: the pyocd support for semihosting is buggy. So I switched to using the builtin platformio support for the stlink adapter which worked much better. ; However the built in openocd version in platformio has buggy support for TCP to semihosting. diff --git a/variants/rak_wismeshtap/platformio.ini b/variants/rak_wismeshtap/platformio.ini index bcf46b90d..78472783e 100644 --- a/variants/rak_wismeshtap/platformio.ini +++ b/variants/rak_wismeshtap/platformio.ini @@ -18,7 +18,7 @@ lib_deps = ${nrf52840_base.lib_deps} ${networking_base.lib_deps} melopero/Melopero RV3028@^1.1.0 - https://github.com/RAKWireless/RAK13800-W5100S.git#1.0.2 + https://github.com/RAKWireless/RAK13800-W5100S/archive/1.0.2.zip rakwireless/RAKwireless NCP5623 RGB LED library@^1.0.2 bodmer/TFT_eSPI beegee-tokyo/RAKwireless RAK12034@^1.0.0 diff --git a/variants/rpipico2w/platformio.ini b/variants/rpipico2w/platformio.ini index 351774221..282be1a42 100644 --- a/variants/rpipico2w/platformio.ini +++ b/variants/rpipico2w/platformio.ini @@ -23,8 +23,9 @@ build_flags = ${rp2350_base.build_flags} -DHAS_WIFI=1 -L "${platformio.libdeps_dir}/${this.__env__}/bsec2/src/cortex-m33" -fexceptions # for exception handling in MQTT + -DHAS_UDP_MULTICAST=1 build_src_filter = ${rp2350_base.build_src_filter} + lib_deps = ${rp2350_base.lib_deps} ${networking_base.lib_deps} -debug_build_flags = ${rp2350_base.build_flags}, -g \ No newline at end of file +debug_build_flags = ${rp2350_base.build_flags}, -g diff --git a/variants/rpipicow/platformio.ini b/variants/rpipicow/platformio.ini index 7a43ece3b..4b714434a 100644 --- a/variants/rpipicow/platformio.ini +++ b/variants/rpipicow/platformio.ini @@ -10,9 +10,10 @@ build_flags = ${rp2040_base.build_flags} -DHW_SPI1_DEVICE -L "${platformio.libdeps_dir}/${this.__env__}/bsec2/src/cortex-m0plus" -fexceptions # for exception handling in MQTT + -DHAS_UDP_MULTICAST=1 build_src_filter = ${rp2040_base.build_src_filter} + lib_deps = ${rp2040_base.lib_deps} ${networking_base.lib_deps} debug_build_flags = ${rp2040_base.build_flags}, -g -debug_tool = cmsis-dap ; for e.g. Picotool \ No newline at end of file +debug_tool = cmsis-dap ; for e.g. Picotool diff --git a/variants/seeed-sensecap-indicator/platformio.ini b/variants/seeed-sensecap-indicator/platformio.ini index da11953b7..fb51d77c3 100644 --- a/variants/seeed-sensecap-indicator/platformio.ini +++ b/variants/seeed-sensecap-indicator/platformio.ini @@ -2,7 +2,7 @@ [env:seeed-sensecap-indicator] extends = esp32s3_base platform_packages = - platformio/framework-arduinoespressif32 @ https://github.com/mverch67/arduino-esp32.git#aef7fef6de3329ed6f75512d46d63bba12b09bb5 ; add_tca9535 (based on 2.0.16) + platformio/framework-arduinoespressif32 @ https://github.com/mverch67/arduino-esp32/archive/aef7fef6de3329ed6f75512d46d63bba12b09bb5.zip ; add_tca9535 (based on 2.0.16) board = seeed-sensecap-indicator board_check = true @@ -24,7 +24,7 @@ build_flags = ${esp32_base.build_flags} -DUSE_ARDUINO_HAL_GPIO lib_deps = ${esp32s3_base.lib_deps} - https://github.com/mverch67/LovyanGFX#develop + https://github.com/mverch67/LovyanGFX/archive/4c76238c1344162a234ae917b27651af146d6fb2.zip earlephilhower/ESP8266Audio@^1.9.9 earlephilhower/ESP8266SAM@^1.0.1 @@ -49,7 +49,7 @@ build_flags = -D HAS_SCREEN=0 -D HAS_TFT=1 -D DISPLAY_SET_RESOLUTION - -D USE_I2S_BUZZER + -D USE_PIN_BUZZER -D RAM_SIZE=4096 -D LV_LVGL_H_INCLUDE_SIMPLE -D LV_CONF_INCLUDE_SIMPLE @@ -65,10 +65,9 @@ build_flags = -D LGFX_DRIVER=LGFX_INDICATOR -D GFX_DRIVER_INC=\"graphics/LGFX/LGFX_INDICATOR.h\" -D VIEW_320x240 -; -D USE_DOUBLE_BUFFER -D USE_PACKET_API lib_deps = ${env:seeed-sensecap-indicator.lib_deps} ${device-ui_base.lib_deps} - https://github.com/bitbank2/bb_captouch.git#8f2f06462ff597847921739376a299db93612417 ; alternative touch library supporting FT6x36 + https://github.com/mverch67/bb_captouch/archive/8626412fe650d808a267791c0eae6e5860c85a5d.zip ; alternative touch library supporting FT6x36 diff --git a/variants/t-deck/platformio.ini b/variants/t-deck/platformio.ini index 4671a5a9b..14fbee6cf 100644 --- a/variants/t-deck/platformio.ini +++ b/variants/t-deck/platformio.ini @@ -42,7 +42,7 @@ build_flags = -D HAS_SCREEN=0 -D HAS_TFT=1 -D USE_I2S_BUZZER - -D RAM_SIZE=4096 + -D RAM_SIZE=5120 -D LV_LVGL_H_INCLUDE_SIMPLE -D LV_CONF_INCLUDE_SIMPLE -D LV_COMP_CONF_INCLUDE_SIMPLE @@ -66,6 +66,7 @@ build_flags = -D VIEW_320x240 ; -D USE_DOUBLE_BUFFER -D USE_PACKET_API + -D MAP_FULL_REDRAW lib_deps = ${env:t-deck.lib_deps} diff --git a/variants/t-echo/nicheGraphics.h b/variants/t-echo/nicheGraphics.h index f0ffe4108..f5dde6b19 100644 --- a/variants/t-echo/nicheGraphics.h +++ b/variants/t-echo/nicheGraphics.h @@ -68,8 +68,7 @@ void setupNicheGraphics() InkHUD::Applet::fontSmall.addSubstitutionsWin1251(); */ - // Init settings, and customize defaults - // Values ignored individually if found saved to flash + // Customize default settings inkhud->persistence->settings.userTiles.maxCount = 2; // Two applets side-by-side inkhud->persistence->settings.rotation = 3; // 270 degrees clockwise inkhud->persistence->settings.optionalFeatures.batteryIcon = true; // Device definitely has a battery @@ -105,7 +104,8 @@ void setupNicheGraphics() constexpr uint8_t TOUCH_BUTTON = 1; // Setup the main user button - buttons->setWiring(MAIN_BUTTON, BUTTON_PIN, LOW); + buttons->setWiring(MAIN_BUTTON, Inputs::TwoButton::getUserButtonPin()); + buttons->setTiming(MAIN_BUTTON, 75, 500); buttons->setHandlerShortPress(MAIN_BUTTON, []() { InkHUD::InkHUD::getInstance()->shortpress(); }); buttons->setHandlerLongPress(MAIN_BUTTON, []() { InkHUD::InkHUD::getInstance()->longpress(); }); diff --git a/variants/t-echo/platformio.ini b/variants/t-echo/platformio.ini index e01befb45..59fd52ccd 100644 --- a/variants/t-echo/platformio.ini +++ b/variants/t-echo/platformio.ini @@ -20,7 +20,7 @@ build_flags = ${nrf52840_base.build_flags} -Ivariants/t-echo build_src_filter = ${nrf52_base.build_src_filter} +<../variants/t-echo> lib_deps = ${nrf52840_base.lib_deps} - https://github.com/meshtastic/GxEPD2#55f618961db45a23eff0233546430f1e5a80f63a + https://github.com/meshtastic/GxEPD2/archive/55f618961db45a23eff0233546430f1e5a80f63a.zip lewisxhe/PCF8563_Library@^1.0.1 ;upload_protocol = fs diff --git a/variants/t-eth-elite/platformio.ini b/variants/t-eth-elite/platformio.ini index ec6c82a5d..d6f415f3d 100644 --- a/variants/t-eth-elite/platformio.ini +++ b/variants/t-eth-elite/platformio.ini @@ -14,4 +14,4 @@ lib_ignore = lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/ETHClass2#v1.0.0 + https://github.com/meshtastic/ETHClass2/archive/v1.0.0.zip diff --git a/variants/t-watch-s3/platformio.ini b/variants/t-watch-s3/platformio.ini index f98237943..d650b1f11 100644 --- a/variants/t-watch-s3/platformio.ini +++ b/variants/t-watch-s3/platformio.ini @@ -3,7 +3,7 @@ extends = esp32s3_base board = t-watch-s3 board_check = true -board_build.partitions = default_16MB.csv +board_build.partitions = default_8MB.csv upload_protocol = esptool build_flags = ${esp32_base.build_flags} diff --git a/variants/tlora_t3s3_epaper/platformio.ini b/variants/tlora_t3s3_epaper/platformio.ini index 3f3b3fe50..87351e586 100644 --- a/variants/tlora_t3s3_epaper/platformio.ini +++ b/variants/tlora_t3s3_epaper/platformio.ini @@ -15,4 +15,4 @@ build_flags = lib_deps = ${esp32s3_base.lib_deps} - https://github.com/meshtastic/GxEPD2#b202ebfec6a4821e098cf7a625ba0f6f2400292d + https://github.com/meshtastic/GxEPD2/archive/b202ebfec6a4821e098cf7a625ba0f6f2400292d.zip diff --git a/variants/tracker-t1000-e/platformio.ini b/variants/tracker-t1000-e/platformio.ini index 0bce9fbb5..8c3c97e6c 100644 --- a/variants/tracker-t1000-e/platformio.ini +++ b/variants/tracker-t1000-e/platformio.ini @@ -9,7 +9,7 @@ board_build.ldscript = src/platform/nrf52/nrf52840_s140_v7.ld build_src_filter = ${nrf52_base.build_src_filter} +<../variants/tracker-t1000-e> lib_deps = ${nrf52840_base.lib_deps} - https://github.com/meshtastic/QMA6100P_Arduino_Library.git#14c900b8b2e4feaac5007a7e41e0c1b7f0841136 + https://github.com/meshtastic/QMA6100P_Arduino_Library/archive/14c900b8b2e4feaac5007a7e41e0c1b7f0841136.zip debug_tool = jlink ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) upload_protocol = nrfutil \ No newline at end of file diff --git a/variants/wio-e5/platformio.ini b/variants/wio-e5/platformio.ini index e9d4ca946..e746ae2f0 100644 --- a/variants/wio-e5/platformio.ini +++ b/variants/wio-e5/platformio.ini @@ -1,6 +1,7 @@ [env:wio-e5] extends = stm32_base board = lora_e5_dev_board +board_upload.maximum_size = 233472 ; reserve the last 28KB for filesystem build_flags = ${stm32_base.build_flags} -Ivariants/wio-e5 @@ -8,31 +9,19 @@ build_flags = -DPIN_SERIAL_RX=PB7 -DPIN_SERIAL_TX=PB6 -DHAL_DAC_MODULE_ONLY - -DHAL_ADC_MODULE_DISABLED - -DHAL_COMP_MODULE_DISABLED - -DHAL_CRC_MODULE_DISABLED - -DHAL_CRYP_MODULE_DISABLED - -DHAL_GTZC_MODULE_DISABLED - -DHAL_HSEM_MODULE_DISABLED - -DHAL_I2C_MODULE_DISABLED - -DHAL_I2S_MODULE_DISABLED - -DHAL_IPCC_MODULE_DISABLED - -DHAL_IRDA_MODULE_DISABLED - -DHAL_IWDG_MODULE_DISABLED - -DHAL_LPTIM_MODULE_DISABLED - -DHAL_PKA_MODULE_DISABLED - -DHAL_RNG_MODULE_DISABLED - -DHAL_RTC_MODULE_DISABLED - -DHAL_SMARTCARD_MODULE_DISABLED - -DHAL_SMBUS_MODULE_DISABLED - -DHAL_TIM_MODULE_DISABLED - -DHAL_WWDG_MODULE_DISABLED - -DHAL_EXTI_MODULE_DISABLED - -DHAL_SAI_MODULE_DISABLED - -DHAL_ICACHE_MODULE_DISABLED + -DHAL_RNG_MODULE_ENABLED -DRADIOLIB_EXCLUDE_SX128X=1 -DRADIOLIB_EXCLUDE_SX127X=1 -DRADIOLIB_EXCLUDE_LR11X0=1 -; -D PIO_FRAMEWORK_ARDUINO_NANOLIB_FLOAT_PRINTF + -DMESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR=1 + -DMESHTASTIC_EXCLUDE_I2C=1 + -DMESHTASTIC_EXCLUDE_WIFI=1 + -DMESHTASTIC_EXCLUDE_BLUETOOTH=1 + -DMESHTASTIC_EXCLUDE_GPS=1 + -DMESHTASTIC_EXCLUDE_SCREEN=1 + -DMESHTASTIC_EXCLUDE_MQTT=1 + -DMESHTASTIC_EXCLUDE_POWERMON=1 + ;-DPIO_FRAMEWORK_ARDUINO_NANOLIB_FLOAT_PRINTF + ;-DCFG_DEBUG upload_port = stlink \ No newline at end of file diff --git a/variants/wio-e5/variant.h b/variants/wio-e5/variant.h index 1de424d1d..5421eaeb9 100644 --- a/variants/wio-e5/variant.h +++ b/variants/wio-e5/variant.h @@ -17,4 +17,9 @@ Do not expect a working Meshtastic device with this target. #define LED_PIN PB5 #define LED_STATE_ON 1 +#if (defined(LED_BUILTIN) && LED_BUILTIN == PNUM_NOT_DEFINED) +#undef LED_BUILTIN +#define LED_BUILTIN (LED_PIN) +#endif + #endif diff --git a/variants/xiao_ble/variant.h b/variants/xiao_ble/variant.h index a86ddfde2..d00f8be89 100644 --- a/variants/xiao_ble/variant.h +++ b/variants/xiao_ble/variant.h @@ -143,9 +143,10 @@ static const uint8_t SCK = PIN_SPI_SCK; #define SX126X_DIO2_AS_RF_SWITCH #define SX126X_DIO3_TCXO_VOLTAGE 1.8 #ifdef EBYTE_E22_900M30S -// 10dB PA gain and 30dB rated output; based on PA output table from Ebyte Robin -#define REGULATORY_GAIN_LORA 10 -#define SX126X_MAX_POWER 20 +// 10dB PA gain and 30dB rated output; based on measurements from +// https://github.com/S5NC/EBYTE_ESP32-S3/blob/main/E22-900M30S%20power%20output%20testing.txt +#define REGULATORY_GAIN_LORA 7 +#define SX126X_MAX_POWER 22 #endif #ifdef EBYTE_E22_900M33S // 25dB PA gain and 33dB rated output; based on TX Power Curve from E22-900M33S_UserManual_EN_v1.0.pdf diff --git a/version.properties b/version.properties index 79fae04ed..0b46aeec6 100644 --- a/version.properties +++ b/version.properties @@ -1,4 +1,4 @@ [VERSION] major = 2 minor = 6 -build = 1 +build = 5