diff --git a/.gitattributes b/.gitattributes index 5dc46e6b3..584097061 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ * text=auto eol=lf *.{cmd,[cC][mM][dD]} text eol=crlf -*.{bat,[bB][aA][tT]} text eol=crlf \ No newline at end of file +*.{bat,[bB][aA][tT]} text eol=crlf +*.{sh,[sS][hH]} text eol=lf diff --git a/bin/build-esp32.sh b/bin/build-esp32.sh index 6068eb256..547a046f6 100755 --- a/bin/build-esp32.sh +++ b/bin/build-esp32.sh @@ -2,8 +2,8 @@ set -e -VERSION=`bin/buildinfo.py long` -SHORT_VERSION=`bin/buildinfo.py short` +VERSION=$(bin/buildinfo.py long) +SHORT_VERSION=$(bin/buildinfo.py short) OUTDIR=release/ @@ -11,7 +11,7 @@ rm -f $OUTDIR/firmware* rm -r $OUTDIR/* || true # Important to pull latest version of libs into all device flavors, otherwise some devices might be stale -platformio pkg update +platformio pkg update echo "Building for $1 with $PLATFORMIO_BUILD_FLAGS" rm -f .pio/build/$1/firmware.* diff --git a/bin/build-native.sh b/bin/build-native.sh index 8bc262860..cc9fcb7ed 100755 --- a/bin/build-native.sh +++ b/bin/build-native.sh @@ -2,8 +2,8 @@ set -e -VERSION=`bin/buildinfo.py long` -SHORT_VERSION=`bin/buildinfo.py short` +VERSION=$(bin/buildinfo.py long) +SHORT_VERSION=$(bin/buildinfo.py short) OUTDIR=release/ @@ -13,11 +13,10 @@ mkdir -p $OUTDIR/ rm -r $OUTDIR/* || true # Important to pull latest version of libs into all device flavors, otherwise some devices might be stale -platformio pkg update +platformio pkg update pio run --environment native cp .pio/build/native/program $OUTDIR/meshtasticd_linux_amd64 cp bin/device-install.* $OUTDIR cp bin/device-update.* $OUTDIR - diff --git a/bin/build-nrf52.sh b/bin/build-nrf52.sh index a9980f486..c3a59dcbe 100755 --- a/bin/build-nrf52.sh +++ b/bin/build-nrf52.sh @@ -2,8 +2,8 @@ set -e -VERSION=`bin/buildinfo.py long` -SHORT_VERSION=`bin/buildinfo.py short` +VERSION=$(bin/buildinfo.py long) +SHORT_VERSION=$(bin/buildinfo.py short) OUTDIR=release/ @@ -11,7 +11,7 @@ rm -f $OUTDIR/firmware* rm -r $OUTDIR/* || true # Important to pull latest version of libs into all device flavors, otherwise some devices might be stale -platformio pkg update +platformio pkg update echo "Building for $1 with $PLATFORMIO_BUILD_FLAGS" rm -f .pio/build/$1/firmware.* diff --git a/bin/build-rpi2040.sh b/bin/build-rpi2040.sh index fe0725085..8eebfc8f1 100755 --- a/bin/build-rpi2040.sh +++ b/bin/build-rpi2040.sh @@ -2,8 +2,8 @@ set -e -VERSION=`bin/buildinfo.py long` -SHORT_VERSION=`bin/buildinfo.py short` +VERSION=$(bin/buildinfo.py long) +SHORT_VERSION=$(bin/buildinfo.py short) OUTDIR=release/ @@ -11,7 +11,7 @@ rm -f $OUTDIR/firmware* rm -r $OUTDIR/* || true # Important to pull latest version of libs into all device flavors, otherwise some devices might be stale -platformio pkg update +platformio pkg update echo "Building for $1 with $PLATFORMIO_BUILD_FLAGS" rm -f .pio/build/$1/firmware.* diff --git a/bin/check-all.sh b/bin/check-all.sh index e6db5b959..4f6a78b03 100755 --- a/bin/check-all.sh +++ b/bin/check-all.sh @@ -4,23 +4,23 @@ set -e -VERSION=`bin/buildinfo.py long` +VERSION=$(bin/buildinfo.py long) # The shell vars the build tool expects to find export APP_VERSION=$VERSION if [[ $# -gt 0 ]]; then - # can override which environment by passing arg - BOARDS="$@" + # can override which environment by passing arg + BOARDS="$@" else - BOARDS="tlora-v2 tlora-v1 tlora_v1_3 tlora-v2-1-1.6 tbeam heltec-v1 heltec-v2.0 heltec-v2.1 tbeam0.7 meshtastic-diy-v1 rak4631 rak4631_eink rak11200 t-echo pca10059_diy_eink" + BOARDS="tlora-v2 tlora-v1 tlora_v1_3 tlora-v2-1-1.6 tbeam heltec-v1 heltec-v2.0 heltec-v2.1 tbeam0.7 meshtastic-diy-v1 rak4631 rak4631_eink rak11200 t-echo pca10059_diy_eink" fi echo "BOARDS:${BOARDS}" CHECK="" for BOARD in $BOARDS; do - CHECK="${CHECK} -e ${BOARD}" + CHECK="${CHECK} -e ${BOARD}" done pio check --flags "-DAPP_VERSION=${APP_VERSION} --suppressions-list=suppressions.txt" $CHECK --skip-packages --pattern="src/" --fail-on-defect=low --fail-on-defect=medium --fail-on-defect=high diff --git a/bin/check-dependencies.sh b/bin/check-dependencies.sh index 27372487f..a686c414b 100644 --- a/bin/check-dependencies.sh +++ b/bin/check-dependencies.sh @@ -5,17 +5,17 @@ set -e if [[ $# -gt 0 ]]; then - # can override which environment by passing arg - BOARDS="$@" + # can override which environment by passing arg + BOARDS="$@" else - BOARDS="rak4631 rak4631_eink t-echo pca10059_diy_eink pico rak11200 tlora-v2 tlora-v1 tlora_v1_3 tlora-v2-1-1.6 tbeam heltec-v1 heltec-v2.0 heltec-v2.1 tbeam0.7 meshtastic-diy-v1 nano-g1 station-g1 m5stack-core m5stack-coreink tbeam-s3-core" + BOARDS="rak4631 rak4631_eink t-echo pca10059_diy_eink pico rak11200 tlora-v2 tlora-v1 tlora_v1_3 tlora-v2-1-1.6 tbeam heltec-v1 heltec-v2.0 heltec-v2.1 tbeam0.7 meshtastic-diy-v1 nano-g1 station-g1 m5stack-core m5stack-coreink tbeam-s3-core" fi echo "BOARDS:${BOARDS}" CHECK="" for BOARD in $BOARDS; do - CHECK="${CHECK} -e ${BOARD}" + CHECK="${CHECK} -e ${BOARD}" done echo $CHECK diff --git a/bin/device-install.sh b/bin/device-install.sh index ca60740ab..90ed32286 100755 --- a/bin/device-install.sh +++ b/bin/device-install.sh @@ -1,12 +1,12 @@ #!/bin/sh -PYTHON=${PYTHON:-$(which python3 python|head -n 1)} +PYTHON=${PYTHON:-$(which python3 python | head -n 1)} set -e # Usage info show_help() { -cat << EOF + cat <&2 - exit 1 - ;; - esac + case "${opt}" in + h) + show_help + exit 0 + ;; + p) + export ESPTOOL_PORT=${OPTARG} + ;; + P) + PYTHON=${OPTARG} + ;; + f) + FILENAME=${OPTARG} + ;; + *) + echo "Invalid flag." + show_help >&2 + exit 1 + ;; + esac done -shift "$((OPTIND-1))" +shift "$((OPTIND - 1))" [ -z "$FILENAME" -a -n "$1" ] && { - FILENAME=$1 - shift + FILENAME=$1 + shift } if [ -f "${FILENAME}" ] && [ ! -z "${FILENAME##*"update"*}" ]; then echo "Trying to flash ${FILENAME}, but first erasing and writing system information" - "$PYTHON" -m esptool erase_flash - "$PYTHON" -m esptool write_flash 0x00 ${FILENAME} - "$PYTHON" -m esptool write_flash 0x260000 bleota.bin - "$PYTHON" -m esptool write_flash 0x300000 littlefs-*.bin + "$PYTHON" -m esptool erase_flash + "$PYTHON" -m esptool write_flash 0x00 ${FILENAME} + "$PYTHON" -m esptool write_flash 0x260000 bleota.bin + "$PYTHON" -m esptool write_flash 0x300000 littlefs-*.bin else show_help diff --git a/bin/device-update.sh b/bin/device-update.sh index 7233f61f6..6640741c0 100755 --- a/bin/device-update.sh +++ b/bin/device-update.sh @@ -1,10 +1,10 @@ #!/bin/sh -PYTHON=${PYTHON:-$(which python3 python|head -n 1)} +PYTHON=${PYTHON:-$(which python3 python | head -n 1)} # Usage info show_help() { -cat << EOF + cat <&2 - exit 1 - ;; - esac + case "${opt}" in + h) + show_help + exit 0 + ;; + p) + export ESPTOOL_PORT=${OPTARG} + ;; + P) + PYTHON=${OPTARG} + ;; + f) + FILENAME=${OPTARG} + ;; + *) + echo "Invalid flag." + show_help >&2 + exit 1 + ;; + esac done -shift "$((OPTIND-1))" +shift "$((OPTIND - 1))" [ -z "$FILENAME" -a -n "$1" ] && { - FILENAME=$1 - shift + FILENAME=$1 + shift } if [ -f "${FILENAME}" ] && [ -z "${FILENAME##*"update"*}" ]; then diff --git a/bin/dump-ram-users.sh b/bin/dump-ram-users.sh index 3cc3ce5dc..1fc5ebe45 100755 --- a/bin/dump-ram-users.sh +++ b/bin/dump-ram-users.sh @@ -2,4 +2,4 @@ arm-none-eabi-readelf -s -e .pio/build/nrf52dk/firmware.elf | head -80 -nm -CSr --size-sort .pio/build/nrf52dk/firmware.elf | grep '^200' +nm -CSr --size-sort .pio/build/nrf52dk/firmware.elf | grep '^200' diff --git a/bin/gen-images.sh b/bin/gen-images.sh index 0c10fddb8..b6a4b2fe0 100755 --- a/bin/gen-images.sh +++ b/bin/gen-images.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -set -e +set -e # regen the design bins first cd design diff --git a/bin/promote-release.sh b/bin/promote-release.sh index f96d2a568..9edafd83c 100755 --- a/bin/promote-release.sh +++ b/bin/promote-release.sh @@ -1,10 +1,10 @@ #!/usr/bin/env bash -set -e +set -e echo "This script is only for developers who are publishing new builds on github. Most users don't need it" -VERSION=`bin/buildinfo.py long` +VERSION=$(bin/buildinfo.py long) # Must have a V prefix to trigger github git tag "v${VERSION}" diff --git a/bin/test-simulator.sh b/bin/test-simulator.sh index 3c5f8f811..132f621a9 100755 --- a/bin/test-simulator.sh +++ b/bin/test-simulator.sh @@ -8,4 +8,3 @@ sleep 20 # 5 seconds was not enough echo "Simulator started, launching python test..." python3 -c 'from meshtastic.test import testSimulator; testSimulator()' - diff --git a/boards/eink0.1.json b/boards/eink0.1.json index 1c5614896..28862c5d4 100644 --- a/boards/eink0.1.json +++ b/boards/eink0.1.json @@ -7,12 +7,7 @@ "cpu": "cortex-m4", "extra_flags": "-DARDUINO_NRF52840_TTGO_EINK -DNRF52840_XXAA", "f_cpu": "64000000L", - "hwids": [ - [ - "0x239A", - "0x4405" - ] - ], + "hwids": [["0x239A", "0x4405"]], "usb_product": "TTGO_eink", "mcu": "nrf52840", "variant": "eink0.1", @@ -30,19 +25,13 @@ "settings_addr": "0xFF000" } }, - "connectivity": [ - "bluetooth" - ], + "connectivity": ["bluetooth"], "debug": { "jlink_device": "nRF52840_xxAA", - "onboard_tools": [ - "jlink" - ], + "onboard_tools": ["jlink"], "svd_path": "nrf52840.svd" }, - "frameworks": [ - "arduino" - ], + "frameworks": ["arduino"], "name": "TTGO eink (Adafruit BSP)", "upload": { "maximum_ram_size": 248832, @@ -50,12 +39,8 @@ "require_upload_port": true, "speed": 115200, "protocol": "jlink", - "protocols": [ - "jlink", - "nrfjprog", - "stlink" - ] + "protocols": ["jlink", "nrfjprog", "stlink"] }, "url": "FIXME", "vendor": "TTGO" -} \ No newline at end of file +} diff --git a/boards/generic_wl5e.json b/boards/generic_wl5e.json index 87e140435..433c55b59 100644 --- a/boards/generic_wl5e.json +++ b/boards/generic_wl5e.json @@ -9,9 +9,7 @@ "product_line": "STM32WLE5xx" }, "debug": { - "default_tools": [ - "stlink" - ], + "default_tools": ["stlink"], "jlink_device": "STM32WLE5CC", "openocd_target": "stm32wlx", "svd_path": "STM32WLE5_CM4.svd" @@ -22,9 +20,7 @@ "maximum_ram_size": 65536, "maximum_size": 262144, "protocol": "cmsis-dap", - "protocols": [ - "cmsis-dap" - ] + "protocols": ["cmsis-dap"] }, "url": "https://www.st.com/en/microcontrollers-microprocessors/stm32wl-series.html", "vendor": "ST" diff --git a/boards/lora_isp4520.json b/boards/lora_isp4520.json index 180cd2fe7..971512b28 100644 --- a/boards/lora_isp4520.json +++ b/boards/lora_isp4520.json @@ -19,16 +19,12 @@ "sd_fwid": "0x00B7" } }, - "connectivity": [ - "bluetooth" - ], + "connectivity": ["bluetooth"], "debug": { "jlink_device": "nRF52832_xxAA", "svd_path": "nrf52.svd" }, - "frameworks": [ - "arduino" - ], + "frameworks": ["arduino"], "name": "lora ISP4520", "upload": { "maximum_ram_size": 65536, @@ -36,13 +32,8 @@ "require_upload_port": true, "speed": 115200, "protocol": "nrfutil", - "protocols": [ - "jlink", - "nrfjprog", - "nrfutil", - "stlink" - ] + "protocols": ["jlink", "nrfjprog", "nrfutil", "stlink"] }, "url": "", "vendor": "PsiSoft" -} \ No newline at end of file +} diff --git a/boards/nordic_pca10059.json b/boards/nordic_pca10059.json index b3d2cc7bd..214c2851d 100644 --- a/boards/nordic_pca10059.json +++ b/boards/nordic_pca10059.json @@ -1,72 +1,51 @@ { - "build": { - "arduino": { - "ldscript": "nrf52840_s140_v6.ld" - }, - "core": "nRF5", - "cpu": "cortex-m4", - "extra_flags": "-DARDUINO_NRF52840_FEATHER -DNRF52840_XXAA", - "f_cpu": "64000000L", - "hwids": [ - [ - "0x239A", - "0x8029" - ], - [ - "0x239A", - "0x0029" - ], - [ - "0x239A", - "0x002A" - ], - [ - "0x239A", - "0x802A" - ] - ], - "usb_product": "PCA10059", - "mcu": "nrf52840", - "variant": "nRF52840 Dongle", - "bsp": { - "name": "adafruit" - }, - "softdevice": { - "sd_flags": "-DS140", - "sd_name": "s140", - "sd_version": "6.1.1", - "sd_fwid": "0x00B6" - }, - "bootloader": { - "settings_addr": "0xFF000" - } + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" }, - "connectivity": [ - "bluetooth" + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DARDUINO_NRF52840_FEATHER -DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + ["0x239A", "0x8029"], + ["0x239A", "0x0029"], + ["0x239A", "0x002A"], + ["0x239A", "0x802A"] ], - "debug": { - "jlink_device": "nRF52840_xxAA", - "svd_path": "nrf52840.svd" + "usb_product": "PCA10059", + "mcu": "nrf52840", + "variant": "nRF52840 Dongle", + "bsp": { + "name": "adafruit" }, - "frameworks": [ - "arduino" - ], - "name": "nRF52840 Dongle", - "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 + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" }, - "url": "https://www.nordicsemi.com/Products/Development-hardware/nrf52840-dongle", - "vendor": "Nordic Semiconductor" + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": ["bluetooth"], + "debug": { + "jlink_device": "nRF52840_xxAA", + "svd_path": "nrf52840.svd" + }, + "frameworks": ["arduino"], + "name": "nRF52840 Dongle", + "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": "https://www.nordicsemi.com/Products/Development-hardware/nrf52840-dongle", + "vendor": "Nordic Semiconductor" } diff --git a/boards/nrf52840_dk.json b/boards/nrf52840_dk.json index 27824178c..8d07575bf 100644 --- a/boards/nrf52840_dk.json +++ b/boards/nrf52840_dk.json @@ -1,47 +1,46 @@ { - "build": { - "arduino": { - "ldscript": "nrf52840_s140_v6.ld" - }, - "core": "nRF5", - "cpu": "cortex-m4", - "extra_flags": "-DARDUINO_NRF52840_PCA10056 -DNRF52840_XXAA", - "f_cpu": "64000000L", - "hwids": [["0x239A", "0x4404"]], - "usb_product": "nrf52840dk", - "mcu": "nrf52840", - "variant": "pca10056", - "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" - } + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" }, - "connectivity": ["bluetooth"], - "debug": { - "jlink_device": "nRF52840_xxAA", - "onboard_tools": ["jlink"], - "svd_path": "nrf52840.svd" + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DARDUINO_NRF52840_PCA10056 -DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [["0x239A", "0x4404"]], + "usb_product": "nrf52840dk", + "mcu": "nrf52840", + "variant": "pca10056", + "variants_dir": "variants", + "bsp": { + "name": "adafruit" }, - "frameworks": ["arduino"], - "name": "A modified NRF52840-DK devboard (Adafruit BSP)", - "upload": { - "maximum_ram_size": 248832, - "maximum_size": 815104, - "require_upload_port": true, - "speed": 115200, - "protocol": "jlink", - "protocols": ["jlink", "nrfjprog", "stlink"] + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" }, - "url": "https://meshtastic.org/", - "vendor": "Nordic Semi" - } - \ No newline at end of file + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": ["bluetooth"], + "debug": { + "jlink_device": "nRF52840_xxAA", + "onboard_tools": ["jlink"], + "svd_path": "nrf52840.svd" + }, + "frameworks": ["arduino"], + "name": "A modified NRF52840-DK devboard (Adafruit BSP)", + "upload": { + "maximum_ram_size": 248832, + "maximum_size": 815104, + "require_upload_port": true, + "speed": 115200, + "protocol": "jlink", + "protocols": ["jlink", "nrfjprog", "stlink"] + }, + "url": "https://meshtastic.org/", + "vendor": "Nordic Semi" +} diff --git a/boards/t-echo.json b/boards/t-echo.json index da67ef05e..9cb48b41a 100644 --- a/boards/t-echo.json +++ b/boards/t-echo.json @@ -7,12 +7,7 @@ "cpu": "cortex-m4", "extra_flags": "-DARDUINO_NRF52840_TTGO_EINK -DNRF52840_XXAA", "f_cpu": "64000000L", - "hwids": [ - [ - "0x239A", - "0x4405" - ] - ], + "hwids": [["0x239A", "0x4405"]], "usb_product": "TTGO_eink", "mcu": "nrf52840", "variant": "t-echo", @@ -30,35 +25,24 @@ "settings_addr": "0xFF000" } }, - "connectivity": [ - "bluetooth" - ], + "connectivity": ["bluetooth"], "debug": { "jlink_device": "nRF52840_xxAA", - "onboard_tools": [ - "jlink" - ], + "onboard_tools": ["jlink"], "svd_path": "nrf52840.svd" }, - "frameworks": [ - "arduino" - ], + "frameworks": ["arduino"], "name": "TTGO eink (Adafruit BSP)", - "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 + "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": "TTGO" -} \ No newline at end of file +} diff --git a/boards/tbeam-s3-core.json b/boards/tbeam-s3-core.json index 06d93c6a0..767791d35 100644 --- a/boards/tbeam-s3-core.json +++ b/boards/tbeam-s3-core.json @@ -15,24 +15,15 @@ "f_cpu": "240000000L", "f_flash": "80000000L", "flash_mode": "dio", - "hwids": [ - [ - "0X303A", - "0x1001" - ] - ], + "hwids": [["0X303A", "0x1001"]], "mcu": "esp32s3", "variant": "tbeam-s3-core" }, - "connectivity": [ - "wifi" - ], + "connectivity": ["wifi"], "debug": { "openocd_target": "esp32s3.cfg" }, - "frameworks": [ - "arduino" - ], + "frameworks": ["arduino"], "name": "LilyGo TBeam-S3-Core", "upload": { "flash_size": "8MB", @@ -43,4 +34,4 @@ }, "url": "http://www.lilygo.cn/", "vendor": "LilyGo" -} \ No newline at end of file +} diff --git a/boards/tlora-t3s3-v1.json b/boards/tlora-t3s3-v1.json index 36a54ad2b..5af53084f 100644 --- a/boards/tlora-t3s3-v1.json +++ b/boards/tlora-t3s3-v1.json @@ -14,25 +14,15 @@ "f_cpu": "240000000L", "f_flash": "80000000L", "flash_mode": "dio", - "hwids": [ - [ - "0X303A", - "0x1001" - ] - ], + "hwids": [["0X303A", "0x1001"]], "mcu": "esp32s3", "variant": "tlora-t3s3-v1" }, - "connectivity": [ - "wifi" - ], + "connectivity": ["wifi"], "debug": { "openocd_target": "esp32s3.cfg" }, - "frameworks": [ - "arduino", - "espidf" - ], + "frameworks": ["arduino", "espidf"], "name": "LilyGo TLora-T3S3-V1", "upload": { "flash_size": "4MB", @@ -44,4 +34,4 @@ }, "url": "http://www.lilygo.cn/", "vendor": "LilyGo" -} \ No newline at end of file +} diff --git a/boards/wiscore_rak11200.json b/boards/wiscore_rak11200.json index 6d794b14a..33d16ba77 100644 --- a/boards/wiscore_rak11200.json +++ b/boards/wiscore_rak11200.json @@ -1,6 +1,6 @@ { "build": { - "arduino":{ + "arduino": { "ldscript": "esp32_out.ld" }, "core": "esp32", @@ -11,26 +11,14 @@ "mcu": "esp32", "variant": "WisCore_RAK11200_Board" }, - "connectivity": [ - "wifi", - "bluetooth", - "ethernet", - "can" - ], - "frameworks": [ - "arduino", - "espidf" - ], + "connectivity": ["wifi", "bluetooth", "ethernet", "can"], + "frameworks": ["arduino", "espidf"], "name": "WisCore RAK11200 Board", "upload": { "flash_size": "4MB", "maximum_ram_size": 327680, "maximum_size": 4194304, - "protocols": [ - "esptool", - "espota", - "ftdi" - ], + "protocols": ["esptool", "espota", "ftdi"], "require_upload_port": true, "speed": 460800 }, diff --git a/boards/wiscore_rak4600.json b/boards/wiscore_rak4600.json index 56f73f4b5..9969ef26e 100644 --- a/boards/wiscore_rak4600.json +++ b/boards/wiscore_rak4600.json @@ -8,22 +8,10 @@ "extra_flags": "-DNRF52832_XXAA -DNRF52", "f_cpu": "64000000L", "hwids": [ - [ - "0x239A", - "0x8029" - ], - [ - "0x239A", - "0x0029" - ], - [ - "0x239A", - "0x002A" - ], - [ - "0x239A", - "0x802A" - ] + ["0x239A", "0x8029"], + ["0x239A", "0x0029"], + ["0x239A", "0x002A"], + ["0x239A", "0x802A"] ], "usb_product": "Feather nRF52832 Express", "mcu": "nrf52832", @@ -41,17 +29,12 @@ "variant": "nrf52_adafruit_feather" } }, - "connectivity": [ - "bluetooth" - ], + "connectivity": ["bluetooth"], "debug": { "jlink_device": "nRF52832_xxAA", "svd_path": "nrf52.svd" }, - "frameworks": [ - "arduino", - "zephyr" - ], + "frameworks": ["arduino", "zephyr"], "name": "Adafruit Bluefruit nRF52832 Feather", "upload": { "maximum_ram_size": 65536, @@ -59,13 +42,8 @@ "require_upload_port": true, "speed": 115200, "protocol": "nrfutil", - "protocols": [ - "jlink", - "nrfjprog", - "nrfutil", - "stlink" - ] + "protocols": ["jlink", "nrfjprog", "nrfutil", "stlink"] }, "url": "https://www.adafruit.com/product/3406", "vendor": "Adafruit" -} \ No newline at end of file +} diff --git a/boards/wiscore_rak4631.json b/boards/wiscore_rak4631.json index 40c93ff04..149492688 100644 --- a/boards/wiscore_rak4631.json +++ b/boards/wiscore_rak4631.json @@ -1,72 +1,51 @@ { - "build": { - "arduino": { - "ldscript": "nrf52840_s140_v6.ld" - }, - "core": "nRF5", - "cpu": "cortex-m4", - "extra_flags": "-DARDUINO_NRF52840_FEATHER -DNRF52840_XXAA", - "f_cpu": "64000000L", - "hwids": [ - [ - "0x239A", - "0x8029" - ], - [ - "0x239A", - "0x0029" - ], - [ - "0x239A", - "0x002A" - ], - [ - "0x239A", - "0x802A" - ] - ], - "usb_product": "WisCore RAK4631 Board", - "mcu": "nrf52840", - "variant": "WisCore_RAK4631_Board", - "bsp": { - "name": "adafruit" - }, - "softdevice": { - "sd_flags": "-DS140", - "sd_name": "s140", - "sd_version": "6.1.1", - "sd_fwid": "0x00B6" - }, - "bootloader": { - "settings_addr": "0xFF000" - } + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" }, - "connectivity": [ - "bluetooth" + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DARDUINO_NRF52840_FEATHER -DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + ["0x239A", "0x8029"], + ["0x239A", "0x0029"], + ["0x239A", "0x002A"], + ["0x239A", "0x802A"] ], - "debug": { - "jlink_device": "nRF52840_xxAA", - "svd_path": "nrf52840.svd" + "usb_product": "WisCore RAK4631 Board", + "mcu": "nrf52840", + "variant": "WisCore_RAK4631_Board", + "bsp": { + "name": "adafruit" }, - "frameworks": [ - "arduino" - ], - "name": "WisCore RAK4631 Board", - "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 + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" }, - "url": "https://www.rakwireless.com", - "vendor": "RAKwireless" -} \ No newline at end of file + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": ["bluetooth"], + "debug": { + "jlink_device": "nRF52840_xxAA", + "svd_path": "nrf52840.svd" + }, + "frameworks": ["arduino"], + "name": "WisCore RAK4631 Board", + "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": "https://www.rakwireless.com", + "vendor": "RAKwireless" +} diff --git a/docker-compose.yml b/docker-compose.yml index 33af95fd2..82f2647e8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,6 @@ services: replicas: 4 networks: - mesh - + networks: - mesh: \ No newline at end of file + mesh: diff --git a/src/BluetoothCommon.cpp b/src/BluetoothCommon.cpp index 728b6f360..53faae997 100644 --- a/src/BluetoothCommon.cpp +++ b/src/BluetoothCommon.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "BluetoothCommon.h" +#include "configuration.h" // NRF52 wants these constants as byte arrays // Generated here https://yupana-engineering.com/online-uuid-to-c-array-converter - but in REVERSE BYTE ORDER diff --git a/src/FSCommon.cpp b/src/FSCommon.cpp index e072e54fb..32e5d7e28 100644 --- a/src/FSCommon.cpp +++ b/src/FSCommon.cpp @@ -1,26 +1,24 @@ -#include "configuration.h" #include "FSCommon.h" +#include "configuration.h" #ifdef HAS_SDCARD -#include #include +#include - -#ifdef SDCARD_USE_SPI1 +#ifdef SDCARD_USE_SPI1 SPIClass SPI1(HSPI); #define SDHandler SPI1 #endif +#endif // HAS_SDCARD -#endif //HAS_SDCARD - -bool copyFile(const char* from, const char* to) +bool copyFile(const char *from, const char *to) { #ifdef FSCom unsigned char cbuffer[16]; - + File f1 = FSCom.open(from, FILE_O_READ); - if (!f1){ + if (!f1) { LOG_ERROR("Failed to open source file %s\n", from); return false; } @@ -30,55 +28,55 @@ bool copyFile(const char* from, const char* to) LOG_ERROR("Failed to open destination file %s\n", to); return false; } - + while (f1.available() > 0) { byte i = f1.read(cbuffer, 16); f2.write(cbuffer, i); } - + f2.close(); f1.close(); return true; #endif } -bool renameFile(const char* pathFrom, const char* pathTo) +bool renameFile(const char *pathFrom, const char *pathTo) { #ifdef FSCom #ifdef ARCH_ESP32 // rename was fixed for ESP32 IDF LittleFS in April return FSCom.rename(pathFrom, pathTo); #else - if (copyFile(pathFrom, pathTo) && FSCom.remove(pathFrom) ) { + if (copyFile(pathFrom, pathTo) && FSCom.remove(pathFrom)) { return true; - } else{ + } else { return false; } #endif #endif } -void listDir(const char * dirname, uint8_t levels, boolean del = false) +void listDir(const char *dirname, uint8_t levels, boolean del = false) { #ifdef FSCom #if (defined(ARCH_ESP32) || defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) char buffer[255]; #endif File root = FSCom.open(dirname, FILE_O_READ); - if(!root){ + if (!root) { return; } - if(!root.isDirectory()){ + if (!root.isDirectory()) { return; } File file = root.openNextFile(); - while(file){ - if(file.isDirectory() && !String(file.name()).endsWith(".")) { - if(levels){ + while (file) { + if (file.isDirectory() && !String(file.name()).endsWith(".")) { + if (levels) { #ifdef ARCH_ESP32 - listDir(file.path(), levels -1, del); - if(del) { + listDir(file.path(), levels - 1, del); + if (del) { LOG_DEBUG("Removing %s\n", file.path()); strncpy(buffer, file.path(), sizeof(buffer)); file.close(); @@ -87,33 +85,33 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) file.close(); } #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) - listDir(file.name(), levels -1, del); - if(del) { + listDir(file.name(), levels - 1, del); + if (del) { LOG_DEBUG("Removing %s\n", file.name()); strncpy(buffer, file.name(), sizeof(buffer)); file.close(); FSCom.rmdir(buffer); } else { file.close(); - } + } #else - listDir(file.name(), levels -1, del); + listDir(file.name(), levels - 1, del); file.close(); #endif } } else { #ifdef ARCH_ESP32 - if(del) { + if (del) { LOG_DEBUG("Deleting %s\n", file.path()); strncpy(buffer, file.path(), sizeof(buffer)); file.close(); FSCom.remove(buffer); } else { - LOG_DEBUG(" %s (%i Bytes)\n", file.path(), file.size()); + LOG_DEBUG(" %s (%i Bytes)\n", file.path(), file.size()); file.close(); } #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) - if(del) { + if (del) { LOG_DEBUG("Deleting %s\n", file.name()); strncpy(buffer, file.name(), sizeof(buffer)); file.close(); @@ -125,12 +123,12 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) #else LOG_DEBUG(" %s (%i Bytes)\n", file.name(), file.size()); file.close(); -#endif +#endif } file = root.openNextFile(); } -#ifdef ARCH_ESP32 - if(del) { +#ifdef ARCH_ESP32 + if (del) { LOG_DEBUG("Removing %s\n", root.path()); strncpy(buffer, root.path(), sizeof(buffer)); root.close(); @@ -139,7 +137,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) root.close(); } #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) - if(del) { + if (del) { LOG_DEBUG("Removing %s\n", root.name()); strncpy(buffer, root.name(), sizeof(buffer)); root.close(); @@ -153,7 +151,7 @@ void listDir(const char * dirname, uint8_t levels, boolean del = false) #endif } -void rmDir(const char * dirname) +void rmDir(const char *dirname) { #ifdef FSCom #if (defined(ARCH_ESP32) || defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) @@ -168,8 +166,7 @@ void rmDir(const char * dirname) void fsInit() { #ifdef FSCom - if (!FSBegin()) - { + if (!FSBegin()) { LOG_ERROR("Filesystem mount Failed.\n"); // assert(0); This auto-formats the partition, so no need to fail here. } @@ -182,7 +179,6 @@ void fsInit() #endif } - void setupSDCard() { #ifdef HAS_SDCARD @@ -190,12 +186,12 @@ void setupSDCard() if (!SD.begin(SDCARD_CS, SDHandler)) { LOG_DEBUG("No SD_MMC card detected\n"); - return ; + return; } uint8_t cardType = SD.cardType(); if (cardType == CARD_NONE) { LOG_DEBUG("No SD_MMC card attached\n"); - return ; + return; } LOG_DEBUG("SD_MMC Card Type: "); if (cardType == CARD_MMC) { @@ -214,6 +210,3 @@ void setupSDCard() LOG_DEBUG("Used space: %llu MB\n", SD.usedBytes() / (1024 * 1024)); #endif } - - - diff --git a/src/FSCommon.h b/src/FSCommon.h index f4c1372a1..98d3911d7 100644 --- a/src/FSCommon.h +++ b/src/FSCommon.h @@ -40,8 +40,8 @@ using namespace Adafruit_LittleFS_Namespace; #endif void fsInit(); -bool copyFile(const char* from, const char* to); -bool renameFile(const char* pathFrom, const char* pathTo); -void listDir(const char * dirname, uint8_t levels, boolean del); -void rmDir(const char * dirname); +bool copyFile(const char *from, const char *to); +bool renameFile(const char *pathFrom, const char *pathTo); +void listDir(const char *dirname, uint8_t levels, boolean del); +void rmDir(const char *dirname); void setupSDCard(); \ No newline at end of file diff --git a/src/GPSStatus.h b/src/GPSStatus.h index c76b66103..bf8903f80 100644 --- a/src/GPSStatus.h +++ b/src/GPSStatus.h @@ -20,7 +20,7 @@ class GPSStatus : public Status bool hasLock = false; // default to false, until we complete our first read bool isConnected = false; // Do we have a GPS we are talking to - bool isPowerSaving = false; //Are we in power saving state + bool isPowerSaving = false; // Are we in power saving state Position p = Position_init_default; @@ -47,7 +47,7 @@ class GPSStatus : public Status bool getIsConnected() const { return isConnected; } - bool getIsPowerSaving() const { return isPowerSaving;} + bool getIsPowerSaving() const { return isPowerSaving; } int32_t getLatitude() const { @@ -88,22 +88,31 @@ class GPSStatus : public Status } } - uint32_t getDOP() const { return p.PDOP; } + uint32_t getDOP() const + { + return p.PDOP; + } - uint32_t getHeading() const { return p.ground_track; } + uint32_t getHeading() const + { + return p.ground_track; + } - uint32_t getNumSatellites() const { return p.sats_in_view; } + uint32_t getNumSatellites() const + { + return p.sats_in_view; + } bool matches(const GPSStatus *newStatus) const { #ifdef GPS_EXTRAVERBOSE LOG_DEBUG("GPSStatus.match() new pos@%x to old pos@%x\n", newStatus->p.pos_timestamp, p.pos_timestamp); #endif - return (newStatus->hasLock != hasLock || newStatus->isConnected != isConnected || newStatus->isPowerSaving !=isPowerSaving || - newStatus->p.latitude_i != p.latitude_i || newStatus->p.longitude_i != p.longitude_i || - newStatus->p.altitude != p.altitude || newStatus->p.altitude_hae != p.altitude_hae || - newStatus->p.PDOP != p.PDOP || newStatus->p.ground_track != p.ground_track || - newStatus->p.ground_speed != p.ground_speed || + return (newStatus->hasLock != hasLock || newStatus->isConnected != isConnected || + newStatus->isPowerSaving != isPowerSaving || newStatus->p.latitude_i != p.latitude_i || + newStatus->p.longitude_i != p.longitude_i || newStatus->p.altitude != p.altitude || + newStatus->p.altitude_hae != p.altitude_hae || newStatus->p.PDOP != p.PDOP || + newStatus->p.ground_track != p.ground_track || newStatus->p.ground_speed != p.ground_speed || newStatus->p.sats_in_view != p.sats_in_view); } diff --git a/src/NodeStatus.h b/src/NodeStatus.h index 7c0477cf6..e6bf31aed 100644 --- a/src/NodeStatus.h +++ b/src/NodeStatus.h @@ -1,83 +1,68 @@ #pragma once -#include #include "Status.h" #include "configuration.h" +#include -namespace meshtastic { +namespace meshtastic +{ - /// Describes the state of the NodeDB system. - class NodeStatus : public Status +/// Describes the state of the NodeDB system. +class NodeStatus : public Status +{ + + private: + CallbackObserver statusObserver = + CallbackObserver(this, &NodeStatus::updateStatus); + + uint8_t numOnline = 0; + uint8_t numTotal = 0; + + uint8_t lastNumTotal = 0; + + public: + bool forceUpdate = false; + + NodeStatus() { statusType = STATUS_TYPE_NODE; } + NodeStatus(uint8_t numOnline, uint8_t numTotal, bool forceUpdate = false) : Status() { + this->forceUpdate = forceUpdate; + this->numOnline = numOnline; + this->numTotal = numTotal; + } + NodeStatus(const NodeStatus &); + NodeStatus &operator=(const NodeStatus &); - private: - CallbackObserver statusObserver = CallbackObserver(this, &NodeStatus::updateStatus); + void observe(Observable *source) { statusObserver.observe(source); } - uint8_t numOnline = 0; - uint8_t numTotal = 0; + uint8_t getNumOnline() const { return numOnline; } - uint8_t lastNumTotal = 0; + uint8_t getNumTotal() const { return numTotal; } - public: - bool forceUpdate = false; + uint8_t getLastNumTotal() const { return lastNumTotal; } - NodeStatus() { - statusType = STATUS_TYPE_NODE; - } - NodeStatus( uint8_t numOnline, uint8_t numTotal, bool forceUpdate = false ) : Status() + bool matches(const NodeStatus *newStatus) const + { + return (newStatus->getNumOnline() != numOnline || newStatus->getNumTotal() != numTotal); + } + int updateStatus(const NodeStatus *newStatus) + { + // Only update the status if values have actually changed + lastNumTotal = numTotal; + bool isDirty; { - this->forceUpdate = forceUpdate; - this->numOnline = numOnline; - this->numTotal = numTotal; + isDirty = matches(newStatus); + initialized = true; + numOnline = newStatus->getNumOnline(); + numTotal = newStatus->getNumTotal(); } - NodeStatus(const NodeStatus &); - NodeStatus &operator=(const NodeStatus &); - - void observe(Observable *source) - { - statusObserver.observe(source); + if (isDirty || newStatus->forceUpdate) { + LOG_DEBUG("Node status update: %d online, %d total\n", numOnline, numTotal); + onNewStatus.notifyObservers(this); } + return 0; + } +}; - uint8_t getNumOnline() const - { - return numOnline; - } - - uint8_t getNumTotal() const - { - return numTotal; - } - - uint8_t getLastNumTotal() const - { - return lastNumTotal; - } - - bool matches(const NodeStatus *newStatus) const - { - return ( - newStatus->getNumOnline() != numOnline || - newStatus->getNumTotal() != numTotal - ); - } - int updateStatus(const NodeStatus *newStatus) { - // Only update the status if values have actually changed - lastNumTotal = numTotal; - bool isDirty; - { - isDirty = matches(newStatus); - initialized = true; - numOnline = newStatus->getNumOnline(); - numTotal = newStatus->getNumTotal(); - } - if(isDirty || newStatus->forceUpdate) { - LOG_DEBUG("Node status update: %d online, %d total\n", numOnline, numTotal); - onNewStatus.notifyObservers(this); - } - return 0; - } - - }; - -} +} // namespace meshtastic extern meshtastic::NodeStatus *nodeStatus; \ No newline at end of file diff --git a/src/OSTimer.cpp b/src/OSTimer.cpp index a0161cd42..0f7177a87 100644 --- a/src/OSTimer.cpp +++ b/src/OSTimer.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "OSTimer.h" +#include "configuration.h" /** * Schedule a callback to run. The callback must _not_ block, though it is called from regular thread level (not ISR) diff --git a/src/Observer.cpp b/src/Observer.cpp index 6d1124684..bc938d965 100644 --- a/src/Observer.cpp +++ b/src/Observer.cpp @@ -1,3 +1,2 @@ -#include "configuration.h" #include "Observer.h" - +#include "configuration.h" diff --git a/src/Observer.h b/src/Observer.h index 4c09101fb..555dcd1e9 100644 --- a/src/Observer.h +++ b/src/Observer.h @@ -10,7 +10,7 @@ template class Observable; */ template class Observer { - std::list *> observed; + std::list *> observed; public: virtual ~Observer(); @@ -87,7 +87,7 @@ template class Observable template Observer::~Observer() { for (typename std::list *>::const_iterator iterator = observed.begin(); iterator != observed.end(); - ++iterator) { + ++iterator) { (*iterator)->removeObserver(this); } observed.clear(); diff --git a/src/Power.cpp b/src/Power.cpp index 1ea5b72b3..082c05181 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -1,16 +1,16 @@ #include "power.h" #include "NodeDB.h" #include "PowerFSM.h" +#include "buzz/buzz.h" #include "configuration.h" #include "main.h" #include "sleep.h" #include "utils.h" -#include "buzz/buzz.h" #ifdef HAS_PMU -#include "XPowersLibInterface.hpp" -#include "XPowersAXP2101.tpp" #include "XPowersAXP192.tpp" +#include "XPowersAXP2101.tpp" +#include "XPowersLibInterface.hpp" XPowersLibInterface *PMU = NULL; #else // Copy of the base class defined in axp20x.h. @@ -108,20 +108,20 @@ class AnalogBatteryLevel : public HasBatteryLevel #ifdef BATTERY_PIN // Override variant or default ADC_MULTIPLIER if we have the override pref - float operativeAdcMultiplier = config.power.adc_multiplier_override > 0 - ? config.power.adc_multiplier_override - : ADC_MULTIPLIER; + float operativeAdcMultiplier = + config.power.adc_multiplier_override > 0 ? config.power.adc_multiplier_override : ADC_MULTIPLIER; // Do not call analogRead() often. const uint32_t min_read_interval = 5000; if (millis() - last_read_time_ms > min_read_interval) { last_read_time_ms = millis(); -//Set the number of samples, it has an effect of increasing sensitivity, especially in complex electromagnetic environment. + // Set the number of samples, it has an effect of increasing sensitivity, especially in complex electromagnetic + // environment. uint32_t raw = 0; - for(uint32_t i=0; i chargingVolt; } + virtual bool isVbusIn() override + { + return getBattVoltage() > chargingVolt; + } /// Assume charging if we have a battery and external power is connected. /// we can't be smart enough to say 'full'? - virtual bool isCharging() override { return isBatteryConnect() && isVbusIn(); } + virtual bool isCharging() override + { + return isBatteryConnect() && isVbusIn(); + } private: /// If we see a battery voltage higher than physics allows - assume charger is pumping @@ -159,16 +168,16 @@ class AnalogBatteryLevel : public HasBatteryLevel #ifndef BAT_FULLVOLT #define BAT_FULLVOLT 4200 -#endif +#endif #ifndef BAT_EMPTYVOLT #define BAT_EMPTYVOLT 3270 -#endif +#endif #ifndef BAT_CHARGINGVOLT #define BAT_CHARGINGVOLT 4210 -#endif +#endif #ifndef BAT_NOBATVOLT #define BAT_NOBATVOLT 2230 -#endif +#endif /// For heltecs with no battery connected, the measured voltage is 2204, so raising to 2230 from 2100 const float fullVolt = BAT_FULLVOLT, emptyVolt = BAT_EMPTYVOLT, chargingVolt = BAT_CHARGINGVOLT, noBatVolt = BAT_NOBATVOLT; @@ -238,12 +247,12 @@ void Power::shutdown() { screen->setOn(false); #if defined(USE_EINK) && defined(PIN_EINK_EN) - digitalWrite(PIN_EINK_EN, LOW); //power off backlight first + digitalWrite(PIN_EINK_EN, LOW); // power off backlight first #endif #ifdef HAS_PMU LOG_INFO("Shutting down\n"); - if(PMU) { + if (PMU) { PMU->setChargingLedMode(XPOWERS_CHG_LED_OFF); PMU->shutdown(); } @@ -290,15 +299,16 @@ void Power::readPowerStatus() if (lastheap != ESP.getFreeHeap()) { LOG_DEBUG("Threads running:"); int running = 0; - for(int i = 0; i < MAX_THREADS; i++){ + for (int i = 0; i < MAX_THREADS; i++) { auto thread = concurrency::mainController.get(i); - if((thread != nullptr) && (thread->enabled)) { + if ((thread != nullptr) && (thread->enabled)) { LOG_DEBUG(" %s", thread->ThreadName.c_str()); running++; } } LOG_DEBUG("\n"); - LOG_DEBUG("Heap status: %d/%d bytes free (%d), running %d/%d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), ESP.getFreeHeap() - lastheap, running, concurrency::mainController.size(false)); + LOG_DEBUG("Heap status: %d/%d bytes free (%d), running %d/%d threads\n", ESP.getFreeHeap(), ESP.getHeapSize(), + ESP.getFreeHeap() - lastheap, running, concurrency::mainController.size(false)); lastheap = ESP.getFreeHeap(); } #endif @@ -312,7 +322,7 @@ void Power::readPowerStatus() LOG_DEBUG("Warning RAK4631 Low voltage counter: %d/10\n", low_voltage_counter); if (low_voltage_counter > 10) { // We can't trigger deep sleep on NRF52, it's freezing the board - //powerFSM.trigger(EVENT_LOW_BATTERY); + // powerFSM.trigger(EVENT_LOW_BATTERY); LOG_DEBUG("Low voltage detected, but not triggering deep sleep\n"); } } else { @@ -338,11 +348,11 @@ int32_t Power::runOnce() #ifdef HAS_PMU // WE no longer use the IRQ line to wake the CPU (due to false wakes from sleep), but we do poll // the IRQ status by reading the registers over I2C - if(PMU) { + if (PMU) { PMU->getIrqStatus(); - if(PMU->isVbusRemoveIrq()){ + if (PMU->isVbusRemoveIrq()) { LOG_INFO("USB unplugged\n"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } @@ -388,24 +398,24 @@ int32_t Power::runOnce() share the same i2c bus, instead use ssd1306 sleep mode DCDC2 -> unused DCDC3 0.7-3.5V @ 700mA max -> ESP32 (keep this on!) LDO1 30mA -> charges GPS backup battery // charges the tiny J13 battery by the GPS to power the GPS ram (for a couple of days), can not be turned off LDO2 200mA -> LORA LDO3 200mA -> GPS - * + * */ bool Power::axpChipInit() { #ifdef HAS_PMU - TwoWire * w = NULL; + TwoWire *w = NULL; // Use macro to distinguish which wire is used by PMU #ifdef PMU_USE_WIRE1 - w = &Wire1; + w = &Wire1; #else - w = &Wire; + w = &Wire; #endif /** - * It is not necessary to specify the wire pin, + * It is not necessary to specify the wire pin, * just input the wire, because the wire has been initialized in main.cpp */ if (!PMU) { @@ -431,11 +441,11 @@ bool Power::axpChipInit() } if (!PMU) { - /* - * In XPowersLib, if the XPowersAXPxxx object is released, Wire.end() will be called at the same time. - * In order not to affect other devices, if the initialization of the PMU fails, Wire needs to be re-initialized once, - * if there are multiple devices sharing the bus. - * * */ + /* + * In XPowersLib, if the XPowersAXPxxx object is released, Wire.end() will be called at the same time. + * In order not to affect other devices, if the initialization of the PMU fails, Wire needs to be re-initialized once, + * if there are multiple devices sharing the bus. + * * */ #ifndef PMU_USE_WIRE1 w->begin(I2C_SDA, I2C_SCL); #endif @@ -445,48 +455,45 @@ bool Power::axpChipInit() batteryLevel = PMU; if (PMU->getChipModel() == XPOWERS_AXP192) { - + // lora radio power channel PMU->setPowerChannelVoltage(XPOWERS_LDO2, 3300); PMU->enablePowerOutput(XPOWERS_LDO2); - // oled module power channel, - // disable it will cause abnormal communication between boot and AXP power supply, + // disable it will cause abnormal communication between boot and AXP power supply, // do not turn it off PMU->setPowerChannelVoltage(XPOWERS_DCDC1, 3300); // enable oled power PMU->enablePowerOutput(XPOWERS_DCDC1); - // gnss module power channel - now turned on in setGpsPower PMU->setPowerChannelVoltage(XPOWERS_LDO3, 3300); // PMU->enablePowerOutput(XPOWERS_LDO3); - - //protected oled power source + // protected oled power source PMU->setProtectedChannel(XPOWERS_DCDC1); - //protected esp32 power source + // protected esp32 power source PMU->setProtectedChannel(XPOWERS_DCDC3); - //disable not use channel + // disable not use channel PMU->disablePowerOutput(XPOWERS_DCDC2); - //disable all axp chip interrupt + // disable all axp chip interrupt PMU->disableIRQ(XPOWERS_AXP192_ALL_IRQ); // Set constant current charging current PMU->setChargerConstantCurr(XPOWERS_AXP192_CHG_CUR_450MA); - //Set up the charging voltage + // Set up the charging voltage PMU->setChargeTargetVoltage(XPOWERS_AXP192_CHG_VOL_4V2); } else if (PMU->getChipModel() == XPOWERS_AXP2101) { - // t-beam s3 core + // t-beam s3 core /** - * gnss module power channel + * gnss module power channel * The default ALDO4 is off, you need to turn on the GNSS power first, otherwise it will be invalid during initialization */ PMU->setPowerChannelVoltage(XPOWERS_ALDO4, 3300); @@ -496,51 +503,50 @@ bool Power::axpChipInit() PMU->setPowerChannelVoltage(XPOWERS_ALDO3, 3300); PMU->enablePowerOutput(XPOWERS_ALDO3); - // m.2 interface + // m.2 interface PMU->setPowerChannelVoltage(XPOWERS_DCDC3, 3300); PMU->enablePowerOutput(XPOWERS_DCDC3); /** - * ALDO2 cannot be turned off. - * It is a necessary condition for sensor communication. - * It must be turned on to properly access the sensor and screen - * It is also responsible for the power supply of PCF8563 - */ + * ALDO2 cannot be turned off. + * It is a necessary condition for sensor communication. + * It must be turned on to properly access the sensor and screen + * It is also responsible for the power supply of PCF8563 + */ PMU->setPowerChannelVoltage(XPOWERS_ALDO2, 3300); PMU->enablePowerOutput(XPOWERS_ALDO2); - // 6-axis , magnetometer ,bme280 , oled screen power channel + // 6-axis , magnetometer ,bme280 , oled screen power channel PMU->setPowerChannelVoltage(XPOWERS_ALDO1, 3300); PMU->enablePowerOutput(XPOWERS_ALDO1); - // sdcard power channle + // sdcard power channle PMU->setPowerChannelVoltage(XPOWERS_BLDO1, 3300); PMU->enablePowerOutput(XPOWERS_BLDO1); - + // PMU->setPowerChannelVoltage(XPOWERS_DCDC4, 3300); // PMU->enablePowerOutput(XPOWERS_DCDC4); - //not use channel - PMU->disablePowerOutput(XPOWERS_DCDC2); //not elicited - PMU->disablePowerOutput(XPOWERS_DCDC5); //not elicited - PMU->disablePowerOutput(XPOWERS_DLDO1); //Invalid power channel, it does not exist - PMU->disablePowerOutput(XPOWERS_DLDO2); //Invalid power channel, it does not exist + // not use channel + PMU->disablePowerOutput(XPOWERS_DCDC2); // not elicited + PMU->disablePowerOutput(XPOWERS_DCDC5); // not elicited + PMU->disablePowerOutput(XPOWERS_DLDO1); // Invalid power channel, it does not exist + PMU->disablePowerOutput(XPOWERS_DLDO2); // Invalid power channel, it does not exist PMU->disablePowerOutput(XPOWERS_VBACKUP); - //disable all axp chip interrupt + // disable all axp chip interrupt PMU->disableIRQ(XPOWERS_AXP2101_ALL_IRQ); - //Set the constant current charging current of AXP2101, temporarily use 500mA by default + // Set the constant current charging current of AXP2101, temporarily use 500mA by default PMU->setChargerConstantCurr(XPOWERS_AXP2101_CHG_CUR_500MA); - //Set up the charging voltage + // Set up the charging voltage PMU->setChargeTargetVoltage(XPOWERS_AXP2101_CHG_VOL_4V2); } - PMU->clearIrqStatus(); - // TBeam1.1 /T-Beam S3-Core has no external TS detection, + // TBeam1.1 /T-Beam S3-Core has no external TS detection, // it needs to be disabled, otherwise it will cause abnormal charging PMU->disableTSPinMeasure(); @@ -550,40 +556,52 @@ bool Power::axpChipInit() LOG_DEBUG("=======================================================================\n"); if (PMU->isChannelAvailable(XPOWERS_DCDC1)) { - LOG_DEBUG("DC1 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC1)); + LOG_DEBUG("DC1 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC1) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_DCDC1)); } if (PMU->isChannelAvailable(XPOWERS_DCDC2)) { - LOG_DEBUG("DC2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC2)); + LOG_DEBUG("DC2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC2) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_DCDC2)); } if (PMU->isChannelAvailable(XPOWERS_DCDC3)) { - LOG_DEBUG("DC3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC3)); + LOG_DEBUG("DC3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC3) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_DCDC3)); } if (PMU->isChannelAvailable(XPOWERS_DCDC4)) { - LOG_DEBUG("DC4 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC4) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_DCDC4)); + LOG_DEBUG("DC4 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC4) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_DCDC4)); } if (PMU->isChannelAvailable(XPOWERS_LDO2)) { - LOG_DEBUG("LDO2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_LDO2)); + LOG_DEBUG("LDO2 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO2) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_LDO2)); } if (PMU->isChannelAvailable(XPOWERS_LDO3)) { - LOG_DEBUG("LDO3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_LDO3)); + LOG_DEBUG("LDO3 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_LDO3) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_LDO3)); } if (PMU->isChannelAvailable(XPOWERS_ALDO1)) { - LOG_DEBUG("ALDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO1)); + LOG_DEBUG("ALDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO1) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_ALDO1)); } if (PMU->isChannelAvailable(XPOWERS_ALDO2)) { - LOG_DEBUG("ALDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO2)); + LOG_DEBUG("ALDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO2) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_ALDO2)); } if (PMU->isChannelAvailable(XPOWERS_ALDO3)) { - LOG_DEBUG("ALDO3: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO3) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO3)); + LOG_DEBUG("ALDO3: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO3) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_ALDO3)); } if (PMU->isChannelAvailable(XPOWERS_ALDO4)) { - LOG_DEBUG("ALDO4: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO4) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_ALDO4)); + LOG_DEBUG("ALDO4: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_ALDO4) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_ALDO4)); } if (PMU->isChannelAvailable(XPOWERS_BLDO1)) { - LOG_DEBUG("BLDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO1) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_BLDO1)); + LOG_DEBUG("BLDO1: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO1) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_BLDO1)); } if (PMU->isChannelAvailable(XPOWERS_BLDO2)) { - LOG_DEBUG("BLDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_BLDO2)); + LOG_DEBUG("BLDO2: %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_BLDO2) ? "+" : "-", + PMU->getPowerChannelVoltage(XPOWERS_BLDO2)); } LOG_DEBUG("=======================================================================\n"); @@ -597,30 +615,29 @@ bool Power::axpChipInit() PMU->setSysPowerDownVoltage(2600); #endif - #ifdef PMU_IRQ - uint64_t pmuIrqMask = 0; + uint64_t pmuIrqMask = 0; - if (PMU->getChipModel() == XPOWERS_AXP192) { - pmuIrqMask = XPOWERS_AXP192_VBUS_INSERT_IRQ | XPOWERS_AXP192_BAT_INSERT_IRQ | XPOWERS_AXP192_PKEY_SHORT_IRQ; - } else if (PMU->getChipModel() == XPOWERS_AXP2101) { - pmuIrqMask = XPOWERS_AXP2101_VBUS_INSERT_IRQ | XPOWERS_AXP2101_BAT_INSERT_IRQ | XPOWERS_AXP2101_PKEY_SHORT_IRQ; - } + if (PMU->getChipModel() == XPOWERS_AXP192) { + pmuIrqMask = XPOWERS_AXP192_VBUS_INSERT_IRQ | XPOWERS_AXP192_BAT_INSERT_IRQ | XPOWERS_AXP192_PKEY_SHORT_IRQ; + } else if (PMU->getChipModel() == XPOWERS_AXP2101) { + pmuIrqMask = XPOWERS_AXP2101_VBUS_INSERT_IRQ | XPOWERS_AXP2101_BAT_INSERT_IRQ | XPOWERS_AXP2101_PKEY_SHORT_IRQ; + } - pinMode(PMU_IRQ, INPUT); - attachInterrupt( - PMU_IRQ, [] { pmu_irq = true; }, FALLING); + pinMode(PMU_IRQ, INPUT); + attachInterrupt( + PMU_IRQ, [] { pmu_irq = true; }, FALLING); - // we do not look for AXPXXX_CHARGING_FINISHED_IRQ & AXPXXX_CHARGING_IRQ because it occurs repeatedly while there is - // no battery also it could cause inadvertent waking from light sleep just because the battery filled - // we don't look for AXPXXX_BATT_REMOVED_IRQ because it occurs repeatedly while no battery installed - // we don't look at AXPXXX_VBUS_REMOVED_IRQ because we don't have anything hooked to vbus - PMU->enableIRQ(pmuIrqMask); + // we do not look for AXPXXX_CHARGING_FINISHED_IRQ & AXPXXX_CHARGING_IRQ because it occurs repeatedly while there is + // no battery also it could cause inadvertent waking from light sleep just because the battery filled + // we don't look for AXPXXX_BATT_REMOVED_IRQ because it occurs repeatedly while no battery installed + // we don't look at AXPXXX_VBUS_REMOVED_IRQ because we don't have anything hooked to vbus + PMU->enableIRQ(pmuIrqMask); - PMU->clearIrqStatus(); + PMU->clearIrqStatus(); #endif /*PMU_IRQ*/ - readPowerStatus(); + readPowerStatus(); pmu_found = true; diff --git a/src/PowerFSM.cpp b/src/PowerFSM.cpp index d5235c00b..632e18083 100644 --- a/src/PowerFSM.cpp +++ b/src/PowerFSM.cpp @@ -11,10 +11,10 @@ /// Should we behave as if we have AC power now? static bool isPowered() { - // Circumvent the battery sensing logic and assumes constant power if no battery pin or power mgmt IC - #if !defined(BATTERY_PIN) && !defined(HAS_AXP192) && !defined(HAS_AXP2101) - return true; - #endif +// Circumvent the battery sensing logic and assumes constant power if no battery pin or power mgmt IC +#if !defined(BATTERY_PIN) && !defined(HAS_AXP192) && !defined(HAS_AXP2101) + return true; +#endif bool isRouter = (config.device.role == Config_DeviceConfig_Role_ROUTER ? 1 : 0); @@ -199,7 +199,8 @@ static void onEnter() uint32_t now = millis(); - if ((now - lastPingMs) > 30 * 1000) { // if more than a minute since our last press, ask node we are looking at to update their state + if ((now - lastPingMs) > + 30 * 1000) { // if more than a minute since our last press, ask node we are looking at to update their state if (displayedNodeNum) service.sendNetworkPing(displayedNodeNum, true); // Refresh the currently displayed node lastPingMs = now; @@ -249,7 +250,8 @@ void PowerFSM_setup() // We need this transition, because we might not transition if we were waiting to enter light-sleep, because when we wake from // light sleep we _always_ transition to NB or dark and - powerFSM.add_transition(&stateLS, isRouter ? &stateNB : &stateDARK, EVENT_PACKET_FOR_PHONE, NULL, "Received packet, exiting light sleep"); + powerFSM.add_transition(&stateLS, isRouter ? &stateNB : &stateDARK, EVENT_PACKET_FOR_PHONE, NULL, + "Received packet, exiting light sleep"); powerFSM.add_transition(&stateNB, &stateNB, EVENT_PACKET_FOR_PHONE, NULL, "Received packet, resetting win wake"); // Handle press events - note: we ignore button presses when in API mode @@ -258,7 +260,8 @@ void PowerFSM_setup() powerFSM.add_transition(&stateDARK, &stateON, EVENT_PRESS, NULL, "Press"); powerFSM.add_transition(&statePOWER, &statePOWER, EVENT_PRESS, screenPress, "Press"); powerFSM.add_transition(&stateON, &stateON, EVENT_PRESS, screenPress, "Press"); // reenter On to restart our timers - powerFSM.add_transition(&stateSERIAL, &stateSERIAL, EVENT_PRESS, screenPress, "Press"); // Allow button to work while in serial API + powerFSM.add_transition(&stateSERIAL, &stateSERIAL, EVENT_PRESS, screenPress, + "Press"); // Allow button to work while in serial API // Handle critically low power battery by forcing deep sleep powerFSM.add_transition(&stateBOOT, &stateSDS, EVENT_LOW_BATTERY, NULL, "LowBat"); @@ -324,7 +327,9 @@ void PowerFSM_setup() powerFSM.add_transition(&stateDARK, &stateDARK, EVENT_CONTACT_FROM_PHONE, NULL, "Contact from phone"); - powerFSM.add_timed_transition(&stateON, &stateDARK, getConfiguredOrDefaultMs(config.display.screen_on_secs, default_screen_on_secs), NULL, "Screen-on timeout"); + powerFSM.add_timed_transition(&stateON, &stateDARK, + getConfiguredOrDefaultMs(config.display.screen_on_secs, default_screen_on_secs), NULL, + "Screen-on timeout"); #ifdef ARCH_ESP32 State *lowPowerState = &stateLS; @@ -332,14 +337,18 @@ void PowerFSM_setup() // See: https://github.com/meshtastic/firmware/issues/1071 if (isRouter || config.power.is_power_saving) { - powerFSM.add_timed_transition(&stateNB, &stateLS, getConfiguredOrDefaultMs(config.power.min_wake_secs, default_min_wake_secs), NULL, "Min wake timeout"); - powerFSM.add_timed_transition(&stateDARK, &stateLS, getConfiguredOrDefaultMs(config.power.wait_bluetooth_secs, default_wait_bluetooth_secs), NULL, "Bluetooth timeout"); + powerFSM.add_timed_transition(&stateNB, &stateLS, + getConfiguredOrDefaultMs(config.power.min_wake_secs, default_min_wake_secs), NULL, + "Min wake timeout"); + powerFSM.add_timed_transition(&stateDARK, &stateLS, + getConfiguredOrDefaultMs(config.power.wait_bluetooth_secs, default_wait_bluetooth_secs), + NULL, "Bluetooth timeout"); } if (config.power.sds_secs != UINT32_MAX) - powerFSM.add_timed_transition(lowPowerState, &stateSDS, getConfiguredOrDefaultMs(config.power.sds_secs), NULL, "mesh timeout"); + powerFSM.add_timed_transition(lowPowerState, &stateSDS, getConfiguredOrDefaultMs(config.power.sds_secs), NULL, + "mesh timeout"); #endif - powerFSM.run_machine(); // run one interation of the state machine, so we run our on enter tasks for the initial DARK state } diff --git a/src/PowerFSM.h b/src/PowerFSM.h index 63506337d..6692172f4 100644 --- a/src/PowerFSM.h +++ b/src/PowerFSM.h @@ -19,8 +19,8 @@ #define EVENT_POWER_CONNECTED 13 #define EVENT_POWER_DISCONNECTED 14 #define EVENT_FIRMWARE_UPDATE 15 // We just received a new firmware update packet from the phone -#define EVENT_SHUTDOWN 16 //force a full shutdown now (not just sleep) -#define EVENT_INPUT 17 // input broker wants something, we need to wake up and enable screen +#define EVENT_SHUTDOWN 16 // force a full shutdown now (not just sleep) +#define EVENT_INPUT 17 // input broker wants something, we need to wake up and enable screen extern Fsm powerFSM; extern State statePOWER, stateSERIAL; diff --git a/src/PowerFSMThread.h b/src/PowerFSMThread.h index f45eec2f7..4ebc14a1e 100644 --- a/src/PowerFSMThread.h +++ b/src/PowerFSMThread.h @@ -26,9 +26,10 @@ class PowerFSMThread : public OSThread if (powerStatus->getHasUSB()) { timeLastPowered = millis(); - } else if (config.power.on_battery_shutdown_after_secs > 0 && - config.power.on_battery_shutdown_after_secs != UINT32_MAX && - millis() > (timeLastPowered + getConfiguredOrDefaultMs(config.power.on_battery_shutdown_after_secs))) { // shutdown after 30 minutes unpowered + } else if (config.power.on_battery_shutdown_after_secs > 0 && config.power.on_battery_shutdown_after_secs != UINT32_MAX && + millis() > (timeLastPowered + + getConfiguredOrDefaultMs( + config.power.on_battery_shutdown_after_secs))) { // shutdown after 30 minutes unpowered powerFSM.trigger(EVENT_SHUTDOWN); } diff --git a/src/RedirectablePrint.cpp b/src/RedirectablePrint.cpp index 74b44dd86..f316785f0 100644 --- a/src/RedirectablePrint.cpp +++ b/src/RedirectablePrint.cpp @@ -1,12 +1,12 @@ -#include "configuration.h" #include "RedirectablePrint.h" -#include "RTC.h" #include "NodeDB.h" +#include "RTC.h" #include "concurrency/OSThread.h" +#include "configuration.h" #include +#include #include #include -#include /** * A printer that doesn't go anywhere @@ -42,7 +42,8 @@ size_t RedirectablePrint::vprintf(const char *format, va_list arg) size_t len = vsnprintf(printBuf, sizeof(printBuf), format, copy); va_end(copy); - // If the resulting string is longer than sizeof(printBuf)-1 characters, the remaining characters are still counted for the return value + // If the resulting string is longer than sizeof(printBuf)-1 characters, the remaining characters are still counted for the + // return value if (len > sizeof(printBuf) - 1) { len = sizeof(printBuf) - 1; @@ -104,30 +105,34 @@ size_t RedirectablePrint::log(const char *logLevel, const char *format, ...) return r; } -void RedirectablePrint::hexDump(const char *logLevel, unsigned char *buf, uint16_t len) { - const char alphabet[17] = "0123456789abcdef"; - log(logLevel, " +------------------------------------------------+ +----------------+\n"); - log(logLevel, " |.0 .1 .2 .3 .4 .5 .6 .7 .8 .9 .a .b .c .d .e .f | | ASCII |\n"); - for (uint16_t i = 0; i < len; i += 16) { - if (i % 128 == 0) - log(logLevel, " +------------------------------------------------+ +----------------+\n"); - char s[] = "| | | |\n"; - uint8_t ix = 1, iy = 52; - for (uint8_t j = 0; j < 16; j++) { - if (i + j < len) { - uint8_t c = buf[i + j]; - s[ix++] = alphabet[(c >> 4) & 0x0F]; - s[ix++] = alphabet[c & 0x0F]; - ix++; - if (c > 31 && c < 128) s[iy++] = c; - else s[iy++] = '.'; - } +void RedirectablePrint::hexDump(const char *logLevel, unsigned char *buf, uint16_t len) +{ + const char alphabet[17] = "0123456789abcdef"; + log(logLevel, " +------------------------------------------------+ +----------------+\n"); + log(logLevel, " |.0 .1 .2 .3 .4 .5 .6 .7 .8 .9 .a .b .c .d .e .f | | ASCII |\n"); + for (uint16_t i = 0; i < len; i += 16) { + if (i % 128 == 0) + log(logLevel, " +------------------------------------------------+ +----------------+\n"); + char s[] = "| | | |\n"; + uint8_t ix = 1, iy = 52; + for (uint8_t j = 0; j < 16; j++) { + if (i + j < len) { + uint8_t c = buf[i + j]; + s[ix++] = alphabet[(c >> 4) & 0x0F]; + s[ix++] = alphabet[c & 0x0F]; + ix++; + if (c > 31 && c < 128) + s[iy++] = c; + else + s[iy++] = '.'; + } + } + uint8_t index = i / 16; + if (i < 256) + log(logLevel, " "); + log(logLevel, "%02x", index); + log(logLevel, "."); + log(logLevel, s); } - uint8_t index = i / 16; - if (i < 256) log(logLevel, " "); - log(logLevel, "%02x",index); - log(logLevel, "."); - log(logLevel, s); - } - log(logLevel, " +------------------------------------------------+ +----------------+\n"); + log(logLevel, " +------------------------------------------------+ +----------------+\n"); } diff --git a/src/RedirectablePrint.h b/src/RedirectablePrint.h index 7aaeb4a47..659b6e10d 100644 --- a/src/RedirectablePrint.h +++ b/src/RedirectablePrint.h @@ -29,12 +29,12 @@ class RedirectablePrint : public Print /** * Debug logging print message - * + * * If the provide format string ends with a newline we assume it is the final print of a single * log message. Otherwise we assume more prints will come before the log message ends. This * allows you to call logDebug a few times to build up a single log message line if you wish. */ - size_t log(const char *logLevel, const char *format, ...) __attribute__ ((format (printf, 3, 4))); + size_t log(const char *logLevel, const char *format, ...) __attribute__((format(printf, 3, 4))); /** like printf but va_list based */ size_t vprintf(const char *format, va_list arg); diff --git a/src/SPILock.cpp b/src/SPILock.cpp index 06163f67a..13fa556fc 100644 --- a/src/SPILock.cpp +++ b/src/SPILock.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "SPILock.h" +#include "configuration.h" #include #include diff --git a/src/SerialConsole.cpp b/src/SerialConsole.cpp index b66eae455..91b4e2826 100644 --- a/src/SerialConsole.cpp +++ b/src/SerialConsole.cpp @@ -49,7 +49,8 @@ int32_t SerialConsole::runOnce() return runOncePart(); } -void SerialConsole::flush() { +void SerialConsole::flush() +{ Port.flush(); } @@ -74,7 +75,7 @@ bool SerialConsole::handleToRadio(const uint8_t *buf, size_t len) canWrite = true; return StreamAPI::handleToRadio(buf, len); - }else{ + } else { return false; } } \ No newline at end of file diff --git a/src/SerialConsole.h b/src/SerialConsole.h index f5e2077ba..f8891ba14 100644 --- a/src/SerialConsole.h +++ b/src/SerialConsole.h @@ -29,7 +29,6 @@ class SerialConsole : public StreamAPI, public RedirectablePrint, private concur void flush(); protected: - /// Check the current underlying physical link to see if the client is currently connected virtual bool checkIsConnected() override; }; diff --git a/src/Status.h b/src/Status.h index 4f0c71445..65f3a252f 100644 --- a/src/Status.h +++ b/src/Status.h @@ -8,65 +8,49 @@ #define STATUS_TYPE_GPS 2 #define STATUS_TYPE_NODE 3 - namespace meshtastic { - // A base class for observable status - class Status +// A base class for observable status +class Status +{ + protected: + // Allows us to observe an Observable + CallbackObserver statusObserver = + CallbackObserver(this, &Status::updateStatus); + bool initialized = false; + // Workaround for no typeid support + int statusType = 0; + + public: + // Allows us to generate observable events + Observable onNewStatus; + + // Enable polymorphism ? + virtual ~Status() = default; + + Status() { - protected: - // Allows us to observe an Observable - CallbackObserver statusObserver = CallbackObserver(this, &Status::updateStatus); - bool initialized = false; - // Workaround for no typeid support - int statusType = 0; - - public: - // Allows us to generate observable events - Observable onNewStatus; - - // Enable polymorphism ? - virtual ~Status() = default; - - Status() { - if (!statusType) - { - statusType = STATUS_TYPE_BASE; - } + if (!statusType) { + statusType = STATUS_TYPE_BASE; } + } - // Prevent object copy/move - Status(const Status &) = delete; - Status &operator=(const Status &) = delete; + // Prevent object copy/move + Status(const Status &) = delete; + Status &operator=(const Status &) = delete; - // Start observing a source of data - void observe(Observable *source) - { - statusObserver.observe(source); - } + // Start observing a source of data + void observe(Observable *source) { statusObserver.observe(source); } - // Determines whether or not existing data matches the data in another Status instance - bool matches(const Status *otherStatus) const - { - return true; - } + // Determines whether or not existing data matches the data in another Status instance + bool matches(const Status *otherStatus) const { return true; } - bool isInitialized() const - { - return initialized; - } + bool isInitialized() const { return initialized; } - int getStatusType() const - { - return statusType; - } + int getStatusType() const { return statusType; } - // Called when the Observable we're observing generates a new notification - int updateStatus(const Status *newStatus) - { - return 0; - } - - }; + // Called when the Observable we're observing generates a new notification + int updateStatus(const Status *newStatus) { return 0; } }; +}; // namespace meshtastic diff --git a/src/airtime.cpp b/src/airtime.cpp index fcd725538..7be4c5b0d 100644 --- a/src/airtime.cpp +++ b/src/airtime.cpp @@ -34,11 +34,13 @@ uint8_t AirTime::currentPeriodIndex() return ((getSecondsSinceBoot() / SECONDS_PER_PERIOD) % PERIODS_TO_LOG); } -uint8_t AirTime::getPeriodUtilMinute() { +uint8_t AirTime::getPeriodUtilMinute() +{ return (getSecondsSinceBoot() / 10) % CHANNEL_UTILIZATION_PERIODS; } -uint8_t AirTime::getPeriodUtilHour() { +uint8_t AirTime::getPeriodUtilHour() +{ return (getSecondsSinceBoot() / 60) % MINUTES_IN_HOUR; } @@ -119,23 +121,23 @@ float AirTime::utilizationTXPercent() bool AirTime::isTxAllowedChannelUtil(bool polite) { - uint8_t percentage = (polite ? polite_channel_util_percent : max_channel_util_percent); + uint8_t percentage = (polite ? polite_channel_util_percent : max_channel_util_percent); if (channelUtilizationPercent() < percentage) { - return true; + return true; } else { LOG_WARN("Channel utilization is >%d percent. Skipping this opportunity to send.\n", percentage); return false; } } - -bool AirTime::isTxAllowedAirUtil() +bool AirTime::isTxAllowedAirUtil() { if (!config.lora.override_duty_cycle && myRegion->dutyCycle < 100) { if (utilizationTXPercent() < myRegion->dutyCycle * polite_duty_cycle_percent / 100) { - return true; + return true; } else { - LOG_WARN("Tx air utilization is >%f percent. Skipping this opportunity to send.\n", myRegion->dutyCycle * polite_duty_cycle_percent / 100); + LOG_WARN("Tx air utilization is >%f percent. Skipping this opportunity to send.\n", + myRegion->dutyCycle * polite_duty_cycle_percent / 100); return false; } } @@ -143,21 +145,19 @@ bool AirTime::isTxAllowedAirUtil() } // Get the amount of minutes we have to be silent before we can send again -uint8_t AirTime::getSilentMinutes(float txPercent, float dutyCycle) -{ - float newTxPercent = txPercent; - for (int8_t i = MINUTES_IN_HOUR-1; i >= 0; --i) { - newTxPercent -= ((float)this->utilizationTX[i] / (MS_IN_MINUTE * MINUTES_IN_HOUR / 100)); - if (newTxPercent < dutyCycle) - return MINUTES_IN_HOUR-1-i; - } +uint8_t AirTime::getSilentMinutes(float txPercent, float dutyCycle) +{ + float newTxPercent = txPercent; + for (int8_t i = MINUTES_IN_HOUR - 1; i >= 0; --i) { + newTxPercent -= ((float)this->utilizationTX[i] / (MS_IN_MINUTE * MINUTES_IN_HOUR / 100)); + if (newTxPercent < dutyCycle) + return MINUTES_IN_HOUR - 1 - i; + } - return MINUTES_IN_HOUR; + return MINUTES_IN_HOUR; } - -AirTime::AirTime() : concurrency::OSThread("AirTime"),airtimes({}) { -} +AirTime::AirTime() : concurrency::OSThread("AirTime"), airtimes({}) {} int32_t AirTime::runOnce() { @@ -213,14 +213,14 @@ int32_t AirTime::runOnce() // Update channel_utilization every second. myNodeInfo.air_util_tx = airTime->utilizationTXPercent(); } -/* - LOG_DEBUG("utilPeriodTX %d TX Airtime %3.2f%\n", utilPeriodTX, airTime->utilizationTXPercent()); - for (uint32_t i = 0; i < MINUTES_IN_HOUR; i++) { - LOG_DEBUG( - "%d,", this->utilizationTX[i] - ); - } - LOG_DEBUG("\n"); -*/ + /* + LOG_DEBUG("utilPeriodTX %d TX Airtime %3.2f%\n", utilPeriodTX, airTime->utilizationTXPercent()); + for (uint32_t i = 0; i < MINUTES_IN_HOUR; i++) { + LOG_DEBUG( + "%d,", this->utilizationTX[i] + ); + } + LOG_DEBUG("\n"); + */ return (1000 * 1); } diff --git a/src/airtime.h b/src/airtime.h index e454b35ad..cb5f8bf6d 100644 --- a/src/airtime.h +++ b/src/airtime.h @@ -1,10 +1,10 @@ #pragma once +#include "MeshRadio.h" #include "concurrency/OSThread.h" #include "configuration.h" #include #include -#include "MeshRadio.h" /* TX_LOG - Time on air this device has transmitted @@ -33,7 +33,6 @@ #define MS_IN_MINUTE (SECONDS_IN_MINUTE * 1000) #define MS_IN_HOUR (MINUTES_IN_HOUR * SECONDS_IN_MINUTE * 1000) - enum reportTypes { TX_LOG, RX_LOG, RX_ALL_LOG }; void logAirtime(reportTypes reportType, uint32_t airtime_ms); @@ -60,7 +59,7 @@ class AirTime : private concurrency::OSThread uint32_t getSecondsSinceBoot(); uint32_t *airtimeReport(reportTypes reportType); uint8_t getSilentMinutes(float txPercent, float dutyCycle); - bool isTxAllowedChannelUtil(bool polite=false); + bool isTxAllowedChannelUtil(bool polite = false); bool isTxAllowedAirUtil(); private: @@ -70,7 +69,7 @@ class AirTime : private concurrency::OSThread uint32_t secSinceBoot = 0; uint8_t max_channel_util_percent = 40; uint8_t polite_channel_util_percent = 25; - uint8_t polite_duty_cycle_percent = 50; // half of Duty Cycle allowance is ok for metadata + uint8_t polite_duty_cycle_percent = 50; // half of Duty Cycle allowance is ok for metadata struct airtimeStruct { uint32_t periodTX[PERIODS_TO_LOG]; // AirTime transmitted diff --git a/src/buzz/buzz.cpp b/src/buzz/buzz.cpp index 262cd20b9..e42a9c203 100644 --- a/src/buzz/buzz.cpp +++ b/src/buzz/buzz.cpp @@ -1,6 +1,6 @@ #include "buzz.h" -#include "configuration.h" #include "NodeDB.h" +#include "configuration.h" #if !defined(ARCH_ESP32) && !defined(ARCH_RP2040) && !defined(ARCH_PORTDUINO) #include "Tone.h" @@ -11,8 +11,8 @@ extern "C" void delay(uint32_t dwMs); #endif struct ToneDuration { - int frequency_khz; - int duration_ms; + int frequency_khz; + int duration_ms; }; // Some common frequencies. @@ -30,40 +30,39 @@ 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 -void playTones(const ToneDuration *tone_durations, int size) { +void playTones(const ToneDuration *tone_durations, int size) +{ #ifdef PIN_BUZZER - if (!config.device.buzzer_gpio) - config.device.buzzer_gpio = PIN_BUZZER; + if (!config.device.buzzer_gpio) + config.device.buzzer_gpio = PIN_BUZZER; #endif - if (config.device.buzzer_gpio) { - for (int i = 0; i < size; i++) { - const auto &tone_duration = tone_durations[i]; - tone(config.device.buzzer_gpio, tone_duration.frequency_khz, tone_duration.duration_ms); - // to distinguish the notes, set a minimum time between them. - delay(1.3 * tone_duration.duration_ms); + if (config.device.buzzer_gpio) { + for (int i = 0; i < size; i++) { + const auto &tone_duration = tone_durations[i]; + tone(config.device.buzzer_gpio, tone_duration.frequency_khz, tone_duration.duration_ms); + // to distinguish the notes, set a minimum time between them. + delay(1.3 * tone_duration.duration_ms); + } } - } } - -void playBeep() { - ToneDuration melody[] = {{NOTE_B3, DURATION_1_4}}; - playTones(melody, sizeof(melody) / sizeof(ToneDuration)); +void playBeep() +{ + ToneDuration melody[] = {{NOTE_B3, DURATION_1_4}}; + playTones(melody, sizeof(melody) / sizeof(ToneDuration)); } -void playStartMelody() { - ToneDuration melody[] = {{NOTE_FS3, DURATION_1_8}, - {NOTE_AS3, DURATION_1_8}, - {NOTE_CS4, DURATION_1_4}}; - playTones(melody, sizeof(melody) / sizeof(ToneDuration)); +void playStartMelody() +{ + ToneDuration melody[] = {{NOTE_FS3, DURATION_1_8}, {NOTE_AS3, DURATION_1_8}, {NOTE_CS4, DURATION_1_4}}; + playTones(melody, sizeof(melody) / sizeof(ToneDuration)); } -void playShutdownMelody() { - ToneDuration melody[] = {{NOTE_CS4, DURATION_1_8}, - {NOTE_AS3, DURATION_1_8}, - {NOTE_FS3, DURATION_1_4}}; - playTones(melody, sizeof(melody) / sizeof(ToneDuration)); +void playShutdownMelody() +{ + ToneDuration melody[] = {{NOTE_CS4, DURATION_1_8}, {NOTE_AS3, DURATION_1_8}, {NOTE_FS3, DURATION_1_4}}; + playTones(melody, sizeof(melody) / sizeof(ToneDuration)); } diff --git a/src/commands.h b/src/commands.h index b52ed5db4..7c7595143 100644 --- a/src/commands.h +++ b/src/commands.h @@ -4,15 +4,15 @@ */ enum class Cmd { - INVALID, - SET_ON, - SET_OFF, - ON_PRESS, - START_BLUETOOTH_PIN_SCREEN, - START_FIRMWARE_UPDATE_SCREEN, - STOP_BLUETOOTH_PIN_SCREEN, - STOP_BOOT_SCREEN, - PRINT, - START_SHUTDOWN_SCREEN, - START_REBOOT_SCREEN, + INVALID, + SET_ON, + SET_OFF, + ON_PRESS, + START_BLUETOOTH_PIN_SCREEN, + START_FIRMWARE_UPDATE_SCREEN, + STOP_BLUETOOTH_PIN_SCREEN, + STOP_BOOT_SCREEN, + PRINT, + START_SHUTDOWN_SCREEN, + START_REBOOT_SCREEN, }; \ No newline at end of file diff --git a/src/concurrency/BinarySemaphoreFreeRTOS.cpp b/src/concurrency/BinarySemaphoreFreeRTOS.cpp index 4d6d40d78..36e55eae7 100644 --- a/src/concurrency/BinarySemaphoreFreeRTOS.cpp +++ b/src/concurrency/BinarySemaphoreFreeRTOS.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "concurrency/BinarySemaphoreFreeRTOS.h" +#include "configuration.h" #include #ifdef HAS_FREE_RTOS diff --git a/src/concurrency/BinarySemaphorePosix.cpp b/src/concurrency/BinarySemaphorePosix.cpp index 0de52b322..dc49a489b 100644 --- a/src/concurrency/BinarySemaphorePosix.cpp +++ b/src/concurrency/BinarySemaphorePosix.cpp @@ -1,18 +1,14 @@ -#include "configuration.h" #include "concurrency/BinarySemaphorePosix.h" +#include "configuration.h" #ifndef HAS_FREE_RTOS namespace concurrency { -BinarySemaphorePosix::BinarySemaphorePosix() -{ -} +BinarySemaphorePosix::BinarySemaphorePosix() {} -BinarySemaphorePosix::~BinarySemaphorePosix() -{ -} +BinarySemaphorePosix::~BinarySemaphorePosix() {} /** * Returns false if we timed out @@ -23,13 +19,9 @@ bool BinarySemaphorePosix::take(uint32_t msec) return false; } -void BinarySemaphorePosix::give() -{ -} +void BinarySemaphorePosix::give() {} -IRAM_ATTR void BinarySemaphorePosix::giveFromISR(BaseType_t *pxHigherPriorityTaskWoken) -{ -} +IRAM_ATTR void BinarySemaphorePosix::giveFromISR(BaseType_t *pxHigherPriorityTaskWoken) {} } // namespace concurrency diff --git a/src/concurrency/InterruptableDelay.cpp b/src/concurrency/InterruptableDelay.cpp index 7bddea68d..b9606e23a 100644 --- a/src/concurrency/InterruptableDelay.cpp +++ b/src/concurrency/InterruptableDelay.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "concurrency/InterruptableDelay.h" +#include "configuration.h" namespace concurrency { diff --git a/src/concurrency/InterruptableDelay.h b/src/concurrency/InterruptableDelay.h index b0d4b009f..2b499073a 100644 --- a/src/concurrency/InterruptableDelay.h +++ b/src/concurrency/InterruptableDelay.h @@ -2,7 +2,6 @@ #include "../freertosinc.h" - #ifdef HAS_FREE_RTOS #include "concurrency/BinarySemaphoreFreeRTOS.h" #define BinarySemaphore BinarySemaphoreFreeRTOS diff --git a/src/concurrency/Lock.cpp b/src/concurrency/Lock.cpp index 50ce6a00f..11501359b 100644 --- a/src/concurrency/Lock.cpp +++ b/src/concurrency/Lock.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "Lock.h" +#include "configuration.h" #include namespace concurrency diff --git a/src/concurrency/LockGuard.cpp b/src/concurrency/LockGuard.cpp index 1c4d9e2e6..d855266cb 100644 --- a/src/concurrency/LockGuard.cpp +++ b/src/concurrency/LockGuard.cpp @@ -1,7 +1,8 @@ -#include "configuration.h" #include "LockGuard.h" +#include "configuration.h" -namespace concurrency { +namespace concurrency +{ LockGuard::LockGuard(Lock *lock) : lock(lock) { diff --git a/src/concurrency/LockGuard.h b/src/concurrency/LockGuard.h index 89c288f6a..647e7960d 100644 --- a/src/concurrency/LockGuard.h +++ b/src/concurrency/LockGuard.h @@ -2,7 +2,8 @@ #include "Lock.h" -namespace concurrency { +namespace concurrency +{ /** * @brief RAII lock guard diff --git a/src/concurrency/NotifiedWorkerThread.cpp b/src/concurrency/NotifiedWorkerThread.cpp index ccdc8fa2b..39a594c5a 100644 --- a/src/concurrency/NotifiedWorkerThread.cpp +++ b/src/concurrency/NotifiedWorkerThread.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "NotifiedWorkerThread.h" +#include "configuration.h" #include "main.h" namespace concurrency @@ -80,11 +80,9 @@ void NotifiedWorkerThread::checkNotification() } } - - int32_t NotifiedWorkerThread::runOnce() { - enabled = false; // Only run once per notification + enabled = false; // Only run once per notification checkNotification(); return RUN_SAME; diff --git a/src/concurrency/NotifiedWorkerThread.h b/src/concurrency/NotifiedWorkerThread.h index 83e73a571..7a150b0b0 100644 --- a/src/concurrency/NotifiedWorkerThread.h +++ b/src/concurrency/NotifiedWorkerThread.h @@ -41,9 +41,9 @@ class NotifiedWorkerThread : public OSThread /// just calls checkNotification() virtual int32_t runOnce() override; - /// Sometimes we might want to check notifications independently of when our thread was getting woken up (i.e. if we are about to change - /// radio transmit/receive modes we want to handle any pending interrupts first). You can call this method and if any notifications are currently - /// pending they will be handled immediately. + /// Sometimes we might want to check notifications independently of when our thread was getting woken up (i.e. if we are about + /// to change radio transmit/receive modes we want to handle any pending interrupts first). You can call this method and if + /// any notifications are currently pending they will be handled immediately. void checkNotification(); private: diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index 2e5ee0ba8..af50d28f5 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "OSThread.h" +#include "configuration.h" #include namespace concurrency @@ -76,7 +76,7 @@ void OSThread::run() { #ifdef DEBUG_HEAP auto heap = ESP.getFreeHeap(); -#endif +#endif currentThread = this; auto newDelay = runOnce(); #ifdef DEBUG_HEAP @@ -95,11 +95,11 @@ void OSThread::run() currentThread = NULL; } -int32_t OSThread::disable() +int32_t OSThread::disable() { enabled = false; setInterval(INT32_MAX); - + return INT32_MAX; } diff --git a/src/configuration.h b/src/configuration.h index 67862609a..6181034a5 100644 --- a/src/configuration.h +++ b/src/configuration.h @@ -27,10 +27,10 @@ along with this program. If not, see . #include #ifdef RV3028_RTC - #include "Melopero_RV3028.h" +#include "Melopero_RV3028.h" #endif #ifdef PCF8563_RTC - #include "pcf8563.h" +#include "pcf8563.h" #endif // ----------------------------------------------------------------------------- @@ -42,7 +42,8 @@ along with this program. If not, see . #error APP_VERSION must be set by the build environment #endif -// FIXME: This is still needed by the Bluetooth Stack and needs to be replaced by something better. Remnant of the old versioning system. +// FIXME: This is still needed by the Bluetooth Stack and needs to be replaced by something better. Remnant of the old versioning +// system. #ifndef HW_VERSION #define HW_VERSION "1.0" #endif @@ -64,13 +65,13 @@ along with this program. If not, see . // Nop definition for these attributes that are specific to ESP32 #ifndef EXT_RAM_ATTR - #define EXT_RAM_ATTR +#define EXT_RAM_ATTR #endif #ifndef IRAM_ATTR - #define IRAM_ATTR +#define IRAM_ATTR #endif #ifndef RTC_DATA_ATTR - #define RTC_DATA_ATTR +#define RTC_DATA_ATTR #endif // ----------------------------------------------------------------------------- @@ -80,7 +81,7 @@ along with this program. If not, see . // Disable use of the NTP library and related features // #define DISABLE_NTP -// Disable the welcome screen and allow +// Disable the welcome screen and allow //#define DISABLE_WELCOME_UNSET // ----------------------------------------------------------------------------- @@ -135,49 +136,49 @@ along with this program. If not, see . /* Step #1: offer chance for variant-specific defines */ #include "variant.h" -/* Step #2: follow with defines common to the architecture; +/* Step #2: follow with defines common to the architecture; also enable HAS_ option not specifically disabled by variant.h */ #include "architecture.h" /* Step #3: mop up with disabled values for HAS_ options not handled by the above two */ #ifndef HAS_WIFI - #define HAS_WIFI 0 +#define HAS_WIFI 0 #endif #ifndef HAS_ETHERNET - #define HAS_ETHERNET 0 +#define HAS_ETHERNET 0 #endif #ifndef HAS_SCREEN - #define HAS_SCREEN 0 +#define HAS_SCREEN 0 #endif #ifndef HAS_WIRE - #define HAS_WIRE 0 +#define HAS_WIRE 0 #endif #ifndef HAS_GPS - #define HAS_GPS 0 +#define HAS_GPS 0 #endif #ifndef HAS_BUTTON - #define HAS_BUTTON 0 +#define HAS_BUTTON 0 #endif #ifndef HAS_TELEMETRY - #define HAS_TELEMETRY 0 +#define HAS_TELEMETRY 0 #endif #ifndef HAS_RADIO - #define HAS_RADIO 0 +#define HAS_RADIO 0 #endif #ifndef HAS_RTC - #define HAS_RTC 0 +#define HAS_RTC 0 #endif #ifndef HAS_CPU_SHUTDOWN - #define HAS_CPU_SHUTDOWN 0 +#define HAS_CPU_SHUTDOWN 0 #endif #ifndef HAS_BLUETOOTH - #define HAS_BLUETOOTH 0 +#define HAS_BLUETOOTH 0 #endif -#include "RF95Configuration.h" #include "DebugConfiguration.h" +#include "RF95Configuration.h" #ifndef HW_VENDOR - #error HW_VENDOR must be defined +#error HW_VENDOR must be defined #endif diff --git a/src/detect/einkScan.h b/src/detect/einkScan.h index a7a855709..8d82f4f81 100644 --- a/src/detect/einkScan.h +++ b/src/detect/einkScan.h @@ -6,42 +6,49 @@ void d_writeCommand(uint8_t c) { - SPI1.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); - if (PIN_EINK_DC >= 0) digitalWrite(PIN_EINK_DC, LOW); - if (PIN_EINK_CS >= 0) digitalWrite(PIN_EINK_CS, LOW); - SPI1.transfer(c); - if (PIN_EINK_CS >= 0) digitalWrite(PIN_EINK_CS, HIGH); - if (PIN_EINK_DC >= 0) digitalWrite(PIN_EINK_DC, HIGH); - SPI1.endTransaction(); + SPI1.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); + if (PIN_EINK_DC >= 0) + digitalWrite(PIN_EINK_DC, LOW); + if (PIN_EINK_CS >= 0) + digitalWrite(PIN_EINK_CS, LOW); + SPI1.transfer(c); + if (PIN_EINK_CS >= 0) + digitalWrite(PIN_EINK_CS, HIGH); + if (PIN_EINK_DC >= 0) + digitalWrite(PIN_EINK_DC, HIGH); + SPI1.endTransaction(); } void d_writeData(uint8_t d) { - SPI1.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); - if (PIN_EINK_CS >= 0) digitalWrite(PIN_EINK_CS, LOW); - SPI1.transfer(d); - if (PIN_EINK_CS >= 0) digitalWrite(PIN_EINK_CS, HIGH); - SPI1.endTransaction(); + SPI1.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); + if (PIN_EINK_CS >= 0) + digitalWrite(PIN_EINK_CS, LOW); + SPI1.transfer(d); + if (PIN_EINK_CS >= 0) + digitalWrite(PIN_EINK_CS, HIGH); + SPI1.endTransaction(); } unsigned long d_waitWhileBusy(uint16_t busy_time) { - if (PIN_EINK_BUSY >= 0) - { - delay(1); // add some margin to become active - unsigned long start = micros(); - while (1) - { - if (digitalRead(PIN_EINK_BUSY) != HIGH) break; - delay(1); - if (digitalRead(PIN_EINK_BUSY) != HIGH) break; - if (micros() - start > 10000000) break; - } - unsigned long elapsed = micros() - start; - (void) start; - return elapsed; - } - else return busy_time; + if (PIN_EINK_BUSY >= 0) { + delay(1); // add some margin to become active + unsigned long start = micros(); + while (1) { + if (digitalRead(PIN_EINK_BUSY) != HIGH) + break; + delay(1); + if (digitalRead(PIN_EINK_BUSY) != HIGH) + break; + if (micros() - start > 10000000) + break; + } + unsigned long elapsed = micros() - start; + (void)start; + return elapsed; + } else + return busy_time; } void scanEInkDevice(void) @@ -51,10 +58,10 @@ void scanEInkDevice(void) d_writeData(0x83); d_writeCommand(0x20); eink_found = (d_waitWhileBusy(150) > 0) ? true : false; - if(eink_found) - LOG_DEBUG("EInk display found\n"); + if (eink_found) + LOG_DEBUG("EInk display found\n"); else - LOG_DEBUG("EInk display not found\n"); + LOG_DEBUG("EInk display not found\n"); SPI1.end(); } #endif diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 1814261a4..c3a7bd6cf 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -21,45 +21,45 @@ GPS *gps; /// only init that port once. static bool didSerialInit; -bool GPS::getACK(uint8_t c, uint8_t i) { - uint8_t b; - uint8_t ack = 0; - const uint8_t ackP[2] = {c, i}; - uint8_t buf[10] = {0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}; - unsigned long startTime = millis(); +bool GPS::getACK(uint8_t c, uint8_t i) +{ + uint8_t b; + uint8_t ack = 0; + const uint8_t ackP[2] = {c, i}; + uint8_t buf[10] = {0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}; + unsigned long startTime = millis(); - for (int j = 2; j < 6; j++) { - buf[8] += buf[j]; - buf[9] += buf[8]; - } + for (int j = 2; j < 6; j++) { + buf[8] += buf[j]; + buf[9] += buf[8]; + } - for (int j = 0; j < 2; j++) { - buf[6 + j] = ackP[j]; - buf[8] += buf[6 + j]; - buf[9] += buf[8]; - } + for (int j = 0; j < 2; j++) { + buf[6 + j] = ackP[j]; + buf[8] += buf[6 + j]; + buf[9] += buf[8]; + } - while (1) { - if (ack > 9) { - return true; + while (1) { + if (ack > 9) { + return true; + } + if (millis() - startTime > 1000) { + return false; + } + if (_serial_gps->available()) { + b = _serial_gps->read(); + if (b == buf[ack]) { + ack++; + } else { + ack = 0; + } + } } - if (millis() - startTime > 1000) { - return false; - } - if (_serial_gps->available()) { - b = _serial_gps->read(); - if (b == buf[ack]) { - ack++; - } - else { - ack = 0; - } - } - } } /** - * @brief + * @brief * @note New method, this method can wait for the specified class and message ID, and return the payload * @param *buffer: The message buffer, if there is a response payload message, it will be returned through the buffer parameter * @param size: size of buffer @@ -69,22 +69,22 @@ bool GPS::getACK(uint8_t c, uint8_t i) { */ int GPS::getAck(uint8_t *buffer, uint16_t size, uint8_t requestedClass, uint8_t requestedID) { - uint16_t ubxFrameCounter = 0; - uint32_t startTime = millis(); - uint16_t needRead; + uint16_t ubxFrameCounter = 0; + uint32_t startTime = millis(); + uint16_t needRead; while (millis() - startTime < 800) { while (_serial_gps->available()) { int c = _serial_gps->read(); switch (ubxFrameCounter) { case 0: - //ubxFrame 'μ' - if (c == 0xB5) { + // ubxFrame 'μ' + if (c == 0xB5) { ubxFrameCounter++; } break; case 1: - //ubxFrame 'b' + // ubxFrame 'b' if (c == 0x62) { ubxFrameCounter++; } else { @@ -92,7 +92,7 @@ int GPS::getAck(uint8_t *buffer, uint16_t size, uint8_t requestedClass, uint8_t } break; case 2: - //Class + // Class if (c == requestedClass) { ubxFrameCounter++; } else { @@ -100,7 +100,7 @@ int GPS::getAck(uint8_t *buffer, uint16_t size, uint8_t requestedClass, uint8_t } break; case 3: - //Message ID + // Message ID if (c == requestedID) { ubxFrameCounter++; } else { @@ -108,13 +108,13 @@ int GPS::getAck(uint8_t *buffer, uint16_t size, uint8_t requestedClass, uint8_t } break; case 4: - //Payload lenght lsb + // Payload lenght lsb needRead = c; ubxFrameCounter++; break; case 5: - //Payload lenght msb - needRead |= (c << 8); + // Payload lenght msb + needRead |= (c << 8); ubxFrameCounter++; break; case 6: @@ -145,41 +145,41 @@ bool GPS::setupGPS() didSerialInit = true; #ifdef ARCH_ESP32 - // In esp32 framework, setRxBufferSize needs to be initialized before Serial - _serial_gps->setRxBufferSize(2048); // the default is 256 + // In esp32 framework, setRxBufferSize needs to be initialized before Serial + _serial_gps->setRxBufferSize(2048); // the default is 256 #endif -// if the overrides are not dialled in, set them from the board definitions, if they exist + // if the overrides are not dialled in, set them from the board definitions, if they exist #if defined(GPS_RX_PIN) -if (!config.position.rx_gpio) - config.position.rx_gpio = GPS_RX_PIN; + if (!config.position.rx_gpio) + config.position.rx_gpio = GPS_RX_PIN; #endif #if defined(GPS_TX_PIN) -if (!config.position.tx_gpio) - config.position.tx_gpio = GPS_TX_PIN; + if (!config.position.tx_gpio) + config.position.tx_gpio = GPS_TX_PIN; #endif // ESP32 has a special set of parameters vs other arduino ports #if defined(ARCH_ESP32) - if(config.position.rx_gpio) + if (config.position.rx_gpio) _serial_gps->begin(GPS_BAUDRATE, SERIAL_8N1, config.position.rx_gpio, config.position.tx_gpio); #else _serial_gps->begin(GPS_BAUDRATE); #endif /* - * T-Beam-S3-Core will be preset to use gps Probe here, and other boards will not be changed first - */ - gnssModel = probe(); + * T-Beam-S3-Core will be preset to use gps Probe here, and other boards will not be changed first + */ + gnssModel = probe(); - if(gnssModel == GNSS_MODEL_MTK){ + if (gnssModel == GNSS_MODEL_MTK) { /* - * t-beam-s3-core uses the same L76K GNSS module as t-echo. - * Unlike t-echo, L76K uses 9600 baud rate for communication by default. - * */ - // _serial_gps->begin(9600); //The baud rate of 9600 has been initialized at the beginning of setupGPS, this line is the redundant part - // delay(250); + * t-beam-s3-core uses the same L76K GNSS module as t-echo. + * Unlike t-echo, L76K uses 9600 baud rate for communication by default. + * */ + // _serial_gps->begin(9600); //The baud rate of 9600 has been initialized at the beginning of setupGPS, this line + // is the redundant part delay(250); // Initialize the L76K Chip, use GPS + GLONASS _serial_gps->write("$PCAS04,5*1C\r\n"); @@ -191,10 +191,10 @@ if (!config.position.tx_gpio) _serial_gps->write("$PCAS11,3*1E\r\n"); delay(250); - }else if(gnssModel == GNSS_MODEL_UBLOX){ + } else if (gnssModel == GNSS_MODEL_UBLOX) { /* - tips: NMEA Only should not be set here, otherwise initializing Ublox gnss module again after + tips: NMEA Only should not be set here, otherwise initializing Ublox gnss module again after setting will not output command messages in UART1, resulting in unrecognized module information // Set the UART port to output NMEA only @@ -204,13 +204,14 @@ if (!config.position.tx_gpio) if (!getACK(0x06, 0x00)) { LOG_WARN("Unable to enable NMEA Mode.\n"); return true; - } + } */ - // ublox-M10S can be compatible with UBLOX traditional protocol, so the following sentence settings are also valid + // ublox-M10S can be compatible with UBLOX traditional protocol, so the following sentence settings are also valid // disable GGL - byte _message_GGL[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x01, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x05, 0x3A}; + byte _message_GGL[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x01, + 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x05, 0x3A}; _serial_gps->write(_message_GGL, sizeof(_message_GGL)); if (!getACK(0x06, 0x01)) { LOG_WARN("Unable to disable NMEA GGL.\n"); @@ -218,7 +219,8 @@ if (!config.position.tx_gpio) } // disable GSA - byte _message_GSA[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x02, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x06, 0x41}; + byte _message_GSA[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x02, + 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x06, 0x41}; _serial_gps->write(_message_GSA, sizeof(_message_GSA)); if (!getACK(0x06, 0x01)) { LOG_WARN("Unable to disable NMEA GSA.\n"); @@ -226,7 +228,8 @@ if (!config.position.tx_gpio) } // disable GSV - byte _message_GSV[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x03, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x07, 0x48}; + byte _message_GSV[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x03, + 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x07, 0x48}; _serial_gps->write(_message_GSV, sizeof(_message_GSV)); if (!getACK(0x06, 0x01)) { LOG_WARN("Unable to disable NMEA GSV.\n"); @@ -234,7 +237,8 @@ if (!config.position.tx_gpio) } // disable VTG - byte _message_VTG[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x05, 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x09, 0x56}; + byte _message_VTG[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x05, + 0x01, 0x00, 0x01, 0x01, 0x01, 0x01, 0x09, 0x56}; _serial_gps->write(_message_VTG, sizeof(_message_VTG)); if (!getACK(0x06, 0x01)) { LOG_WARN("Unable to disable NMEA VTG.\n"); @@ -242,7 +246,8 @@ if (!config.position.tx_gpio) } // enable RMC - byte _message_RMC[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x09, 0x54}; + byte _message_RMC[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x04, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x09, 0x54}; _serial_gps->write(_message_RMC, sizeof(_message_RMC)); if (!getACK(0x06, 0x01)) { LOG_WARN("Unable to enable NMEA RMC.\n"); @@ -250,7 +255,8 @@ if (!config.position.tx_gpio) } // enable GGA - byte _message_GGA[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x05, 0x38}; + byte _message_GGA[] = {0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x00, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x05, 0x38}; _serial_gps->write(_message_GGA, sizeof(_message_GGA)); if (!getACK(0x06, 0x01)) { LOG_WARN("Unable to enable NMEA GGA.\n"); @@ -270,9 +276,9 @@ bool GPS::setup() #endif #ifdef HAS_PMU -if(config.position.gps_enabled){ - setGPSPower(true); -} + if (config.position.gps_enabled) { + setGPSPower(true); + } #endif #ifdef PIN_GPS_RESET @@ -289,7 +295,7 @@ if(config.position.gps_enabled){ notifyDeepSleepObserver.observe(¬ifyDeepSleep); notifyGPSSleepObserver.observe(¬ifyGPSSleep); } - if (config.position.gps_enabled==false) { + if (config.position.gps_enabled == false) { setAwake(false); doGPSpowersave(false); } @@ -401,7 +407,7 @@ uint32_t GPS::getSleepTime() const if (t == UINT32_MAX) return t; // already maxint - + return t * 1000; } @@ -425,9 +431,9 @@ int32_t GPS::runOnce() // if we have received valid NMEA claim we are connected setConnected(); } else { - if((config.position.gps_enabled == 1) && (gnssModel == GNSS_MODEL_UBLOX)){ + if ((config.position.gps_enabled == 1) && (gnssModel == GNSS_MODEL_UBLOX)) { // reset the GPS on next bootup - if(devicestate.did_gps_reset && (millis() > 60000) && !hasFlow()) { + if (devicestate.did_gps_reset && (millis() > 60000) && !hasFlow()) { LOG_DEBUG("GPS is not communicating, trying factory reset on next bootup.\n"); devicestate.did_gps_reset = false; nodeDB.saveDeviceStateToDisk(); @@ -544,10 +550,10 @@ GnssModel_t GPS::probe() // we use autodetect, only T-BEAM S3 for now... uint8_t buffer[256]; /* - * The GNSS module information variable is temporarily placed inside the function body, - * if it needs to be used elsewhere, it can be moved to the outside - * */ - struct uBloxGnssModelInfo info ; + * The GNSS module information variable is temporarily placed inside the function body, + * if it needs to be used elsewhere, it can be moved to the outside + * */ + struct uBloxGnssModelInfo info; memset(&info, 0, sizeof(struct uBloxGnssModelInfo)); @@ -561,10 +567,10 @@ GnssModel_t GPS::probe() while (millis() < startTimeout) { if (_serial_gps->available()) { String ver = _serial_gps->readStringUntil('\r'); - // Get module info , If the correct header is returned, + // Get module info , If the correct header is returned, // it can be determined that it is the MTK chip int index = ver.indexOf("$"); - if(index != -1){ + if (index != -1) { ver = ver.substring(index); if (ver.startsWith("$GPTXT,01,01,02")) { LOG_INFO("L76K GNSS init succeeded, using L76K GNSS Module\n"); @@ -573,7 +579,6 @@ GnssModel_t GPS::probe() } } } - uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x0E, 0x30}; _serial_gps->write(cfg_rate, sizeof(cfg_rate)); @@ -581,10 +586,10 @@ GnssModel_t GPS::probe() if (!getAck(buffer, 256, 0x06, 0x08)) { LOG_WARN("Failed to find UBlox & MTK GNSS Module\n"); return GNSS_MODEL_UNKONW; - } + } // Get Ublox gnss module hardware and software info - uint8_t cfg_get_hw[] = {0xB5, 0x62, 0x0A, 0x04, 0x00, 0x00, 0x0E, 0x34}; + uint8_t cfg_get_hw[] = {0xB5, 0x62, 0x0A, 0x04, 0x00, 0x00, 0x0E, 0x34}; _serial_gps->write(cfg_get_hw, sizeof(cfg_get_hw)); uint16_t len = getAck(buffer, 256, 0x0A, 0x04); @@ -611,27 +616,27 @@ GnssModel_t GPS::probe() } LOG_DEBUG("Module Info : \n"); - LOG_DEBUG("Soft version: %s\n",info.swVersion); - LOG_DEBUG("Hard version: %s\n",info.hwVersion); - LOG_DEBUG("Extensions:%d\n",info.extensionNo); + LOG_DEBUG("Soft version: %s\n", info.swVersion); + LOG_DEBUG("Hard version: %s\n", info.hwVersion); + LOG_DEBUG("Extensions:%d\n", info.extensionNo); for (int i = 0; i < info.extensionNo; i++) { - LOG_DEBUG(" %s\n",info.extension[i]); + LOG_DEBUG(" %s\n", info.extension[i]); } - memset(buffer,0,sizeof(buffer)); + memset(buffer, 0, sizeof(buffer)); - //tips: extensionNo field is 0 on some 6M GNSS modules + // tips: extensionNo field is 0 on some 6M GNSS modules for (int i = 0; i < info.extensionNo; ++i) { if (!strncmp(info.extension[i], "OD=", 3)) { strncpy((char *)buffer, &(info.extension[i][3]), sizeof(buffer)); - LOG_DEBUG("GetModel:%s\n",(char *)buffer); + LOG_DEBUG("GetModel:%s\n", (char *)buffer); } } } - if (strlen((char*)buffer)) { - LOG_INFO("UBlox GNSS init succeeded, using UBlox %s GNSS Module\n" , buffer); - }else{ + if (strlen((char *)buffer)) { + LOG_INFO("UBlox GNSS init succeeded, using UBlox %s GNSS Module\n", buffer); + } else { LOG_INFO("UBlox GNSS init succeeded, using UBlox GNSS Module\n"); } @@ -662,8 +667,7 @@ GPS *createGps() new_gps->setup(); return new_gps; } - } - else{ + } else { GPS *new_gps = new NMEAGPS(); new_gps->setup(); return new_gps; diff --git a/src/gps/GPS.h b/src/gps/GPS.h index 5d24268d7..a3703187c 100644 --- a/src/gps/GPS.h +++ b/src/gps/GPS.h @@ -4,19 +4,18 @@ #include "Observer.h" #include "concurrency/OSThread.h" - -struct uBloxGnssModelInfo { - char swVersion[30]; - char hwVersion[10]; +struct uBloxGnssModelInfo { + char swVersion[30]; + char hwVersion[10]; uint8_t extensionNo; - char extension[10][30]; -} ; + char extension[10][30]; +}; -typedef enum{ - GNSS_MODEL_MTK, - GNSS_MODEL_UBLOX, - GNSS_MODEL_UNKONW, -}GnssModel_t; +typedef enum { + GNSS_MODEL_MTK, + GNSS_MODEL_UBLOX, + GNSS_MODEL_UNKONW, +} GnssModel_t; // Generate a string representation of DOP const char *getDOPString(uint32_t dop); @@ -78,7 +77,7 @@ class GPS : private concurrency::OSThread /// Return true if we are connected to a GPS bool isConnected() const { return hasGPS; } - bool isPowerSaving() const { return !config.position.gps_enabled;} + bool isPowerSaving() const { return !config.position.gps_enabled; } /** * Restart our lock attempt - try to get and broadcast a GPS reading ASAP @@ -164,7 +163,7 @@ class GPS : private concurrency::OSThread virtual int32_t runOnce() override; - // Get GNSS model + // Get GNSS model GnssModel_t probe(); int getAck(uint8_t *buffer, uint16_t size, uint8_t requestedClass, uint8_t requestedID); @@ -173,8 +172,8 @@ class GPS : private concurrency::OSThread GnssModel_t gnssModel = GNSS_MODEL_UNKONW; }; -// Creates an instance of the GPS class. +// Creates an instance of the GPS class. // Returns the new instance or null if the GPS is not present. -GPS* createGps(); +GPS *createGps(); extern GPS *gps; diff --git a/src/gps/GeoCoord.cpp b/src/gps/GeoCoord.cpp index 13c24b701..9d5e6315e 100644 --- a/src/gps/GeoCoord.cpp +++ b/src/gps/GeoCoord.cpp @@ -1,21 +1,25 @@ #include "GeoCoord.h" -GeoCoord::GeoCoord() { +GeoCoord::GeoCoord() +{ _dirty = true; } -GeoCoord::GeoCoord (int32_t lat, int32_t lon, int32_t alt) : _latitude(lat), _longitude(lon), _altitude(alt) { +GeoCoord::GeoCoord(int32_t lat, int32_t lon, int32_t alt) : _latitude(lat), _longitude(lon), _altitude(alt) +{ GeoCoord::setCoords(); } -GeoCoord::GeoCoord (float lat, float lon, int32_t alt) : _altitude(alt) { +GeoCoord::GeoCoord(float lat, float lon, int32_t alt) : _altitude(alt) +{ // Change decimial reprsentation to int32_t. I.e., 12.345 becomes 123450000 _latitude = int32_t(lat * 1e+7); _longitude = int32_t(lon * 1e+7); GeoCoord::setCoords(); } -GeoCoord::GeoCoord(double lat, double lon, int32_t alt): _altitude(alt) { +GeoCoord::GeoCoord(double lat, double lon, int32_t alt) : _altitude(alt) +{ // Change decimial reprsentation to int32_t. I.e., 12.345 becomes 123450000 _latitude = int32_t(lat * 1e+7); _longitude = int32_t(lon * 1e+7); @@ -23,7 +27,8 @@ GeoCoord::GeoCoord(double lat, double lon, int32_t alt): _altitude(alt) { } // Initialize all the coordinate systems -void GeoCoord::setCoords() { +void GeoCoord::setCoords() +{ double lat = _latitude * 1e-7; double lon = _longitude * 1e-7; GeoCoord::latLongToDMS(lat, lon, _dms); @@ -34,9 +39,10 @@ void GeoCoord::setCoords() { _dirty = false; } -void GeoCoord::updateCoords(int32_t lat, int32_t lon, int32_t alt) { +void GeoCoord::updateCoords(int32_t lat, int32_t lon, int32_t alt) +{ // If marked dirty or new coordiantes - if(_dirty || _latitude != lat || _longitude != lon || _altitude != alt) { + if (_dirty || _latitude != lat || _longitude != lon || _altitude != alt) { _dirty = true; _latitude = lat; _longitude = lon; @@ -45,25 +51,26 @@ void GeoCoord::updateCoords(int32_t lat, int32_t lon, int32_t alt) { } } -void GeoCoord::updateCoords(const double lat, const double lon, const int32_t alt) { +void GeoCoord::updateCoords(const double lat, const double lon, const int32_t alt) +{ int32_t iLat = lat * 1e+7; int32_t iLon = lon * 1e+7; // If marked dirty or new coordiantes - if(_dirty || _latitude != iLat || _longitude != iLon || _altitude != alt) { + if (_dirty || _latitude != iLat || _longitude != iLon || _altitude != alt) { _dirty = true; _latitude = iLat; _longitude = iLon; _altitude = alt; setCoords(); } - } -void GeoCoord::updateCoords(const float lat, const float lon, const int32_t alt) { +void GeoCoord::updateCoords(const float lat, const float lon, const int32_t alt) +{ int32_t iLat = lat * 1e+7; int32_t iLon = lon * 1e+7; // If marked dirty or new coordiantes - if(_dirty || _latitude != iLat || _longitude != iLon || _altitude != alt) { + if (_dirty || _latitude != iLat || _longitude != iLon || _altitude != alt) { _dirty = true; _latitude = iLat; _longitude = iLon; @@ -73,12 +80,15 @@ void GeoCoord::updateCoords(const float lat, const float lon, const int32_t alt) } /** - * Converts lat long coordinates from decimal degrees to degrees minutes seconds format. + * Converts lat long coordinates from decimal degrees to degrees minutes seconds format. * DD°MM'SS"C DDD°MM'SS"C */ -void GeoCoord::latLongToDMS(const double lat, const double lon, DMS &dms) { - if (lat < 0) dms.latCP = 'S'; - else dms.latCP = 'N'; +void GeoCoord::latLongToDMS(const double lat, const double lon, DMS &dms) +{ + if (lat < 0) + dms.latCP = 'S'; + else + dms.latCP = 'N'; double latDeg = lat; @@ -90,8 +100,10 @@ void GeoCoord::latLongToDMS(const double lat, const double lon, DMS &dms) { dms.latMin = floor(latMin); dms.latSec = (latMin - dms.latMin) * 60; - if (lon < 0) dms.lonCP = 'W'; - else dms.lonCP = 'E'; + if (lon < 0) + dms.lonCP = 'W'; + else + dms.lonCP = 'E'; double lonDeg = lon; @@ -108,52 +120,64 @@ void GeoCoord::latLongToDMS(const double lat, const double lon, DMS &dms) { * Converts lat long coordinates to UTM. * based on this: https://github.com/walvok/LatLonToUTM/blob/master/latlon_utm.ino */ -void GeoCoord::latLongToUTM(const double lat, const double lon, UTM &utm) { +void GeoCoord::latLongToUTM(const double lat, const double lon, UTM &utm) +{ const std::string latBands = "CDEFGHJKLMNPQRSTUVWXX"; - utm.zone = int((lon + 180)/6 + 1); - utm.band = latBands[int(lat/8 + 10)]; - double a = 6378137; // WGS84 - equatorial radius - double k0 = 0.9996; // UTM point scale on the central meridian - double eccSquared = 0.00669438; // eccentricity squared - double lonTemp = (lon + 180) - int((lon + 180)/360) * 360 - 180; //Make sure the longitude is between -180.00 .. 179.9 + utm.zone = int((lon + 180) / 6 + 1); + utm.band = latBands[int(lat / 8 + 10)]; + double a = 6378137; // WGS84 - equatorial radius + double k0 = 0.9996; // UTM point scale on the central meridian + double eccSquared = 0.00669438; // eccentricity squared + double lonTemp = (lon + 180) - int((lon + 180) / 360) * 360 - 180; // Make sure the longitude is between -180.00 .. 179.9 double latRad = toRadians(lat); double lonRad = toRadians(lonTemp); // Special Zones for Norway and Svalbard - if( lat >= 56.0 && lat < 64.0 && lonTemp >= 3.0 && lonTemp < 12.0 ) // Norway + if (lat >= 56.0 && lat < 64.0 && lonTemp >= 3.0 && lonTemp < 12.0) // Norway utm.zone = 32; - if( lat >= 72.0 && lat < 84.0 ) { // Svalbard - if ( lonTemp >= 0.0 && lonTemp < 9.0 ) utm.zone = 31; - else if( lonTemp >= 9.0 && lonTemp < 21.0 ) utm.zone = 33; - else if( lonTemp >= 21.0 && lonTemp < 33.0 ) utm.zone = 35; - else if( lonTemp >= 33.0 && lonTemp < 42.0 ) utm.zone = 37; + if (lat >= 72.0 && lat < 84.0) { // Svalbard + if (lonTemp >= 0.0 && lonTemp < 9.0) + utm.zone = 31; + else if (lonTemp >= 9.0 && lonTemp < 21.0) + utm.zone = 33; + else if (lonTemp >= 21.0 && lonTemp < 33.0) + utm.zone = 35; + else if (lonTemp >= 33.0 && lonTemp < 42.0) + utm.zone = 37; } - - double lonOrigin = (utm.zone - 1)*6 - 180 + 3; // puts origin in middle of zone + + double lonOrigin = (utm.zone - 1) * 6 - 180 + 3; // puts origin in middle of zone double lonOriginRad = toRadians(lonOrigin); - double eccPrimeSquared = (eccSquared)/(1 - eccSquared); - double N = a/sqrt(1 - eccSquared*sin(latRad)*sin(latRad)); - double T = tan(latRad)*tan(latRad); - double C = eccPrimeSquared*cos(latRad)*cos(latRad); - double A = cos(latRad)*(lonRad - lonOriginRad); - double M = a*((1 - eccSquared/4 - 3*eccSquared*eccSquared/64 - 5*eccSquared*eccSquared*eccSquared/256)*latRad - - (3*eccSquared/8 + 3*eccSquared*eccSquared/32 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(2*latRad) - + (15*eccSquared*eccSquared/256 + 45*eccSquared*eccSquared*eccSquared/1024)*sin(4*latRad) - - (35*eccSquared*eccSquared*eccSquared/3072)*sin(6*latRad)); - utm.easting = (double)(k0*N*(A+(1-T+C)*pow(A, 3)/6 + (5-18*T+T*T+72*C-58*eccPrimeSquared)*A*A*A*A*A/120) - + 500000.0); - utm.northing = (double)(k0*(M+N*tan(latRad)*(A*A/2+(5-T+9*C+4*C*C)*A*A*A*A/24 - + (61-58*T+T*T+600*C-330*eccPrimeSquared)*A*A*A*A*A*A/720))); - - if(lat < 0) - utm.northing += 10000000.0; //10000000 meter offset for southern hemisphere + double eccPrimeSquared = (eccSquared) / (1 - eccSquared); + double N = a / sqrt(1 - eccSquared * sin(latRad) * sin(latRad)); + double T = tan(latRad) * tan(latRad); + double C = eccPrimeSquared * cos(latRad) * cos(latRad); + double A = cos(latRad) * (lonRad - lonOriginRad); + double M = + a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * latRad - + (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * + sin(2 * latRad) + + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * sin(4 * latRad) - + (35 * eccSquared * eccSquared * eccSquared / 3072) * sin(6 * latRad)); + utm.easting = (double)(k0 * N * + (A + (1 - T + C) * pow(A, 3) / 6 + + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120) + + 500000.0); + utm.northing = + (double)(k0 * (M + N * tan(latRad) * + (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24 + + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720))); + + if (lat < 0) + utm.northing += 10000000.0; // 10000000 meter offset for southern hemisphere } // Converts lat long coordinates to an MGRS. -void GeoCoord::latLongToMGRS(const double lat, const double lon, MGRS &mgrs) { - const std::string e100kLetters[3] = { "ABCDEFGH", "JKLMNPQR", "STUVWXYZ" }; - const std::string n100kLetters[2] = { "ABCDEFGHJKLMNPQRSTUV", "FGHJKLMNPQRSTUVABCDE" }; +void GeoCoord::latLongToMGRS(const double lat, const double lon, MGRS &mgrs) +{ + const std::string e100kLetters[3] = {"ABCDEFGH", "JKLMNPQR", "STUVWXYZ"}; + const std::string n100kLetters[2] = {"ABCDEFGHJKLMNPQRSTUV", "FGHJKLMNPQRSTUVABCDE"}; UTM utm; latLongToUTM(lat, lon, utm); mgrs.zone = utm.zone; @@ -161,7 +185,7 @@ void GeoCoord::latLongToMGRS(const double lat, const double lon, MGRS &mgrs) { double col = floor(utm.easting / 100000); mgrs.east100k = e100kLetters[(mgrs.zone - 1) % 3][col - 1]; double row = (int32_t)floor(utm.northing / 100000.0) % 20; - mgrs.north100k = n100kLetters[(mgrs.zone-1)%2][row]; + mgrs.north100k = n100kLetters[(mgrs.zone - 1) % 2][row]; mgrs.easting = (int32_t)utm.easting % 100000; mgrs.northing = (int32_t)utm.northing % 100000; } @@ -170,52 +194,54 @@ void GeoCoord::latLongToMGRS(const double lat, const double lon, MGRS &mgrs) { * Converts lat long coordinates to Ordnance Survey Grid Reference (UK National Grid Ref). * Based on: https://www.movable-type.co.uk/scripts/latlong-os-gridref.html */ -void GeoCoord::latLongToOSGR(const double lat, const double lon, OSGR &osgr) { +void GeoCoord::latLongToOSGR(const double lat, const double lon, OSGR &osgr) +{ const char letter[] = "ABCDEFGHJKLMNOPQRSTUVWXYZ"; // No 'I' in OSGR - double a = 6377563.396; // Airy 1830 semi-major axis - double b = 6356256.909; // Airy 1830 semi-minor axis - double f0 = 0.9996012717; // National Grid point scale factor on the central meridian - double phi0 = toRadians(49); + double a = 6377563.396; // Airy 1830 semi-major axis + double b = 6356256.909; // Airy 1830 semi-minor axis + double f0 = 0.9996012717; // National Grid point scale factor on the central meridian + double phi0 = toRadians(49); double lambda0 = toRadians(-2); double n0 = -100000; double e0 = 400000; - double e2 = 1 - (b*b)/(a*a); // eccentricity squared - double n = (a - b)/(a + b); - + double e2 = 1 - (b * b) / (a * a); // eccentricity squared + double n = (a - b) / (a + b); + double osgb_Latitude; double osgb_Longitude; convertWGS84ToOSGB36(lat, lon, osgb_Latitude, osgb_Longitude); - double phi = osgb_Latitude; // already in radians + double phi = osgb_Latitude; // already in radians double lambda = osgb_Longitude; // already in radians double v = a * f0 / sqrt(1 - e2 * sin(phi) * sin(phi)); double rho = a * f0 * (1 - e2) / pow(1 - e2 * sin(phi) * sin(phi), 1.5); double eta2 = v / rho - 1; - double mA = (1 + n + (5/4)*n*n + (5/4)*n*n*n) * (phi - phi0); - double mB = (3*n + 3*n*n + (21/8)*n*n*n) * sin(phi - phi0) * cos(phi + phi0); + double mA = (1 + n + (5 / 4) * n * n + (5 / 4) * n * n * n) * (phi - phi0); + double mB = (3 * n + 3 * n * n + (21 / 8) * n * n * n) * sin(phi - phi0) * cos(phi + phi0); // loss of precision in mC & mD due to floating point rounding can cause innaccuracy of northing by a few meters - double mC = (15/8*n*n + 15/8*n*n*n) * sin(2*(phi - phi0)) * cos(2*(phi + phi0)); - double mD = (35/24)*n*n*n * sin(3*(phi - phi0)) * cos(3*(phi + phi0)); - double m = b*f0*(mA - mB + mC - mD); + double mC = (15 / 8 * n * n + 15 / 8 * n * n * n) * sin(2 * (phi - phi0)) * cos(2 * (phi + phi0)); + double mD = (35 / 24) * n * n * n * sin(3 * (phi - phi0)) * cos(3 * (phi + phi0)); + double m = b * f0 * (mA - mB + mC - mD); - double cos3Phi = cos(phi)*cos(phi)*cos(phi); - double cos5Phi = cos3Phi*cos(phi)*cos(phi); - double tan2Phi = tan(phi)*tan(phi); - double tan4Phi = tan2Phi*tan2Phi; + double cos3Phi = cos(phi) * cos(phi) * cos(phi); + double cos5Phi = cos3Phi * cos(phi) * cos(phi); + double tan2Phi = tan(phi) * tan(phi); + double tan4Phi = tan2Phi * tan2Phi; double I = m + n0; - double II = (v/2)*sin(phi)*cos(phi); - double III = (v/24)*sin(phi)*cos3Phi*(5 - tan2Phi + 9*eta2); - double IIIA = (v/720)*sin(phi)*cos5Phi*(61 - 58*tan2Phi + tan4Phi); - double IV = v*cos(phi); - double V = (v/6)*cos3Phi*(v/rho - tan2Phi); - double VI = (v/120)*cos5Phi*(5 - 18*tan2Phi + tan4Phi + 14*eta2 - 58*tan2Phi*eta2); + double II = (v / 2) * sin(phi) * cos(phi); + double III = (v / 24) * sin(phi) * cos3Phi * (5 - tan2Phi + 9 * eta2); + double IIIA = (v / 720) * sin(phi) * cos5Phi * (61 - 58 * tan2Phi + tan4Phi); + double IV = v * cos(phi); + double V = (v / 6) * cos3Phi * (v / rho - tan2Phi); + double VI = (v / 120) * cos5Phi * (5 - 18 * tan2Phi + tan4Phi + 14 * eta2 - 58 * tan2Phi * eta2); double deltaLambda = lambda - lambda0; - double deltaLambda2 = deltaLambda*deltaLambda; - double northing = I + II*deltaLambda2 + III*deltaLambda2*deltaLambda2 + IIIA*deltaLambda2*deltaLambda2*deltaLambda2; - double easting = e0 + IV*deltaLambda + V*deltaLambda2*deltaLambda + VI*deltaLambda2*deltaLambda2*deltaLambda; + double deltaLambda2 = deltaLambda * deltaLambda; + double northing = + I + II * deltaLambda2 + III * deltaLambda2 * deltaLambda2 + IIIA * deltaLambda2 * deltaLambda2 * deltaLambda2; + double easting = e0 + IV * deltaLambda + V * deltaLambda2 * deltaLambda + VI * deltaLambda2 * deltaLambda2 * deltaLambda; if (easting < 0 || easting > 700000 || northing < 0 || northing > 1300000) // Check if out of boundaries - osgr = { 'I', 'I', 0, 0 }; + osgr = {'I', 'I', 0, 0}; else { uint32_t e100k = floor(easting / 100000); uint32_t n100k = floor(northing / 100000); @@ -232,7 +258,8 @@ void GeoCoord::latLongToOSGR(const double lat, const double lon, OSGR &osgr) { * Converts lat long coordinates to Open Location Code. * Based on: https://github.com/google/open-location-code/blob/main/c/src/olc.c */ -void GeoCoord::latLongToOLC(double lat, double lon, OLC &olc) { +void GeoCoord::latLongToOLC(double lat, double lon, OLC &olc) +{ char tempCode[] = "1234567890abc"; const char kAlphabet[] = "23456789CFGHJMPQRVWX"; double latitude; @@ -258,7 +285,7 @@ void GeoCoord::latLongToOLC(double lat, double lon, OLC &olc) { lat_val += latitude * 2.5e7; lng_val += longitude * 8.192e6; size_t pos = OLC_CODE_LEN; - + if (OLC_CODE_LEN > 10) { // Compute grid part of code if needed for (size_t i = 0; i < 5; i++) { int lat_digit = lat_val % 5; @@ -272,9 +299,9 @@ void GeoCoord::latLongToOLC(double lat, double lon, OLC &olc) { lat_val /= pow(5, 5); lng_val /= pow(4, 5); } - + pos = 10; - + for (size_t i = 0; i < 5; i++) { // Compute pair section of code int lat_ndx = lat_val % 20; int lng_ndx = lng_val % 20; @@ -286,7 +313,7 @@ void GeoCoord::latLongToOLC(double lat, double lon, OLC &olc) { if (i == 0) tempCode[pos--] = '+'; } - + if (OLC_CODE_LEN < 9) { // Add padding if needed for (size_t i = OLC_CODE_LEN; i < 9; i++) tempCode[i] = '0'; @@ -300,50 +327,52 @@ void GeoCoord::latLongToOLC(double lat, double lon, OLC &olc) { for (size_t i = 0; i < char_count; i++) { olc.code[i] = tempCode[i]; } - olc.code[char_count] = '\0'; + olc.code[char_count] = '\0'; } // Converts the coordinate in WGS84 datum to the OSGB36 datum. -void GeoCoord::convertWGS84ToOSGB36(const double lat, const double lon, double &osgb_Latitude, double &osgb_Longitude) { +void GeoCoord::convertWGS84ToOSGB36(const double lat, const double lon, double &osgb_Latitude, double &osgb_Longitude) +{ // Convert lat long to cartesian double phi = toRadians(lat); double lambda = toRadians(lon); - double h = 0.0; // No OSTN height data used, some loss of accuracy (up to 5m) - double wgsA = 6378137; // WGS84 datum semi major axis + double h = 0.0; // No OSTN height data used, some loss of accuracy (up to 5m) + double wgsA = 6378137; // WGS84 datum semi major axis double wgsF = 1 / 298.257223563; // WGS84 datum flattening - double ecc = 2*wgsF - wgsF*wgsF; + double ecc = 2 * wgsF - wgsF * wgsF; double vee = wgsA / sqrt(1 - ecc * pow(sin(phi), 2)); double wgsX = (vee + h) * cos(phi) * cos(lambda); double wgsY = (vee + h) * cos(phi) * sin(lambda); double wgsZ = ((1 - ecc) * vee + h) * sin(phi); // 7-parameter Helmert transform - double tx = -446.448; // x shift in meters - double ty = 125.157; // y shift in meters - double tz = -542.060; // z shift in meters - double s = 20.4894/1e6 + 1; // scale normalized parts per million to (s + 1) - double rx = toRadians(-0.1502/3600); // x rotation normalize arcseconds to radians - double ry = toRadians(-0.2470/3600); // y rotation normalize arcseconds to radians - double rz = toRadians(-0.8421/3600); // z rotation normalize arcseconds to radians - double osgbX = tx + wgsX*s - wgsY*rz + wgsZ*ry; - double osgbY = ty + wgsX*rz + wgsY*s - wgsZ*rx; - double osgbZ = tz - wgsX*ry + wgsY*rx + wgsZ*s; + double tx = -446.448; // x shift in meters + double ty = 125.157; // y shift in meters + double tz = -542.060; // z shift in meters + double s = 20.4894 / 1e6 + 1; // scale normalized parts per million to (s + 1) + double rx = toRadians(-0.1502 / 3600); // x rotation normalize arcseconds to radians + double ry = toRadians(-0.2470 / 3600); // y rotation normalize arcseconds to radians + double rz = toRadians(-0.8421 / 3600); // z rotation normalize arcseconds to radians + double osgbX = tx + wgsX * s - wgsY * rz + wgsZ * ry; + double osgbY = ty + wgsX * rz + wgsY * s - wgsZ * rx; + double osgbZ = tz - wgsX * ry + wgsY * rx + wgsZ * s; // Convert cartesian to lat long - double airyA = 6377563.396; // Airy1830 datum semi major axis - double airyB = 6356256.909; // Airy1830 datum semi minor axis - double airyF = 1/ 299.3249646; // Airy1830 datum flattening - double airyEcc = 2*airyF - airyF*airyF; + double airyA = 6377563.396; // Airy1830 datum semi major axis + double airyB = 6356256.909; // Airy1830 datum semi minor axis + double airyF = 1 / 299.3249646; // Airy1830 datum flattening + double airyEcc = 2 * airyF - airyF * airyF; double airyEcc2 = airyEcc / (1 - airyEcc); - double p = sqrt(osgbX*osgbX + osgbY*osgbY); - double R = sqrt(p*p + osgbZ*osgbZ); - double tanBeta = (airyB*osgbZ) / (airyA*p) * (1 + airyEcc2*airyB/R); - double sinBeta = tanBeta / sqrt(1 + tanBeta*tanBeta); + double p = sqrt(osgbX * osgbX + osgbY * osgbY); + double R = sqrt(p * p + osgbZ * osgbZ); + double tanBeta = (airyB * osgbZ) / (airyA * p) * (1 + airyEcc2 * airyB / R); + double sinBeta = tanBeta / sqrt(1 + tanBeta * tanBeta); double cosBeta = sinBeta / tanBeta; - osgb_Latitude = atan2(osgbZ + airyEcc2*airyB*sinBeta*sinBeta*sinBeta, p - airyEcc*airyA*cosBeta*cosBeta*cosBeta); // leave in radians - osgb_Longitude = atan2(osgbY, osgbX); // leave in radians - //osgb height = p*cos(osgb.latitude) + osgbZ*sin(osgb.latitude) - - //(airyA*airyA/(airyA / sqrt(1 - airyEcc*sin(osgb.latitude)*sin(osgb.latitude)))); // Not used, no OSTN data + osgb_Latitude = atan2(osgbZ + airyEcc2 * airyB * sinBeta * sinBeta * sinBeta, + p - airyEcc * airyA * cosBeta * cosBeta * cosBeta); // leave in radians + osgb_Longitude = atan2(osgbY, osgbX); // leave in radians + // osgb height = p*cos(osgb.latitude) + osgbZ*sin(osgb.latitude) - + //(airyA*airyA/(airyA / sqrt(1 - airyEcc*sin(osgb.latitude)*sin(osgb.latitude)))); // Not used, no OSTN data } /// Ported from my old java code, returns distance in meters along the globe @@ -397,12 +426,13 @@ float GeoCoord::bearing(double lat1, double lon1, double lat2, double lon2) * @brief Convert from meters to range in radians on a great circle * @param range_meters * The range in meters - * @return range in radians on a great circle + * @return range in radians on a great circle */ -float GeoCoord::rangeMetersToRadians(double range_meters) { +float GeoCoord::rangeMetersToRadians(double range_meters) +{ // 1 nm is 1852 meters double distance_nm = range_meters * 1852; - return (PI / (180 * 60)) *distance_nm; + return (PI / (180 * 60)) * distance_nm; } /** @@ -410,22 +440,27 @@ float GeoCoord::rangeMetersToRadians(double range_meters) { * @brief Convert from radians to range in meters on a great circle * @param range_radians * The range in radians - * @return Range in meters on a great circle + * @return Range in meters on a great circle */ -float GeoCoord::rangeRadiansToMeters(double range_radians) { +float GeoCoord::rangeRadiansToMeters(double range_radians) +{ double distance_nm = ((180 * 60) / PI) * range_radians; // 1 meter is 0.000539957 nm return distance_nm * 0.000539957; } // Find distance from point to passed in point -int32_t GeoCoord::distanceTo(const GeoCoord& pointB) { - return latLongToMeter(this->getLatitude() * 1e-7, this->getLongitude() * 1e-7, pointB.getLatitude() * 1e-7, pointB.getLongitude() * 1e-7); +int32_t GeoCoord::distanceTo(const GeoCoord &pointB) +{ + return latLongToMeter(this->getLatitude() * 1e-7, this->getLongitude() * 1e-7, pointB.getLatitude() * 1e-7, + pointB.getLongitude() * 1e-7); } // Find bearing from point to passed in point -int32_t GeoCoord::bearingTo(const GeoCoord& pointB) { - return bearing(this->getLatitude() * 1e-7, this->getLongitude() * 1e-7, pointB.getLatitude() * 1e-7, pointB.getLongitude() * 1e-7); +int32_t GeoCoord::bearingTo(const GeoCoord &pointB) +{ + return bearing(this->getLatitude() * 1e-7, this->getLongitude() * 1e-7, pointB.getLatitude() * 1e-7, + pointB.getLongitude() * 1e-7); } /** @@ -436,8 +471,9 @@ int32_t GeoCoord::bearingTo(const GeoCoord& pointB) { * @param range_meters * range in meters * @return GeoCoord object of point at bearing and range from initial point -*/ -std::shared_ptr GeoCoord::pointAtDistance(double bearing, double range_meters) { + */ +std::shared_ptr GeoCoord::pointAtDistance(double bearing, double range_meters) +{ double range_radians = rangeMetersToRadians(range_meters); double lat1 = this->getLatitude() * 1e-7; double lon1 = this->getLongitude() * 1e-7; @@ -446,5 +482,4 @@ std::shared_ptr GeoCoord::pointAtDistance(double bearing, double range double lon = fmod(lon1 - dlon + PI, 2 * PI) - PI; return std::make_shared(double(lat), double(lon), this->getAltitude()); - } diff --git a/src/gps/GeoCoord.h b/src/gps/GeoCoord.h index 02980ea05..28e9e14e9 100644 --- a/src/gps/GeoCoord.h +++ b/src/gps/GeoCoord.h @@ -1,26 +1,27 @@ #pragma once #include -#include -#include #include +#include #include -#include -#include #include +#include +#include +#include #define PI 3.1415926535897932384626433832795 #define OLC_CODE_LEN 11 // Helper functions // Raises a number to an exponent, handling negative exponents. -static inline double pow_neg(double base, double exponent) { - if (exponent == 0) { - return 1; - } else if (exponent > 0) { - return pow(base, exponent); - } - return 1 / pow(base, -exponent); +static inline double pow_neg(double base, double exponent) +{ + if (exponent == 0) { + return 1; + } else if (exponent > 0) { + return pow(base, exponent); + } + return 1 / pow(base, -exponent); } static inline double toRadians(double deg) @@ -35,8 +36,7 @@ static inline double toDegrees(double r) // GeoCoord structs/classes // A struct to hold the data for a DMS coordinate. -struct DMS -{ +struct DMS { uint8_t latDeg; uint8_t latMin; uint32_t latSec; @@ -48,8 +48,7 @@ struct DMS }; // A struct to hold the data for a UTM coordinate, this is also used when creating an MGRS coordinate. -struct UTM -{ +struct UTM { uint8_t zone; char band; uint32_t easting; @@ -57,8 +56,7 @@ struct UTM }; // A struct to hold the data for a MGRS coordinate. -struct MGRS -{ +struct MGRS { uint8_t zone; char band; char east100k; @@ -80,85 +78,85 @@ struct OLC { char code[OLC_CODE_LEN + 1]; // +1 for null termination }; -class GeoCoord { - private: - int32_t _latitude = 0; - int32_t _longitude = 0; - int32_t _altitude = 0; +class GeoCoord +{ + private: + int32_t _latitude = 0; + int32_t _longitude = 0; + int32_t _altitude = 0; - DMS _dms = {}; - UTM _utm = {}; - MGRS _mgrs = {}; - OSGR _osgr = {}; - OLC _olc = {}; + DMS _dms = {}; + UTM _utm = {}; + MGRS _mgrs = {}; + OSGR _osgr = {}; + OLC _olc = {}; - bool _dirty = true; + bool _dirty = true; - void setCoords(); + void setCoords(); - public: - GeoCoord(); - GeoCoord(int32_t lat, int32_t lon, int32_t alt); - GeoCoord(double lat, double lon, int32_t alt); - GeoCoord(float lat, float lon, int32_t alt); + public: + GeoCoord(); + GeoCoord(int32_t lat, int32_t lon, int32_t alt); + GeoCoord(double lat, double lon, int32_t alt); + GeoCoord(float lat, float lon, int32_t alt); - void updateCoords(const int32_t lat, const int32_t lon, const int32_t alt); - void updateCoords(const double lat, const double lon, const int32_t alt); - void updateCoords(const float lat, const float lon, const int32_t alt); + void updateCoords(const int32_t lat, const int32_t lon, const int32_t alt); + void updateCoords(const double lat, const double lon, const int32_t alt); + void updateCoords(const float lat, const float lon, const int32_t alt); - // Conversions - static void latLongToDMS(const double lat, const double lon, DMS &dms); - static void latLongToUTM(const double lat, const double lon, UTM &utm); - static void latLongToMGRS(const double lat, const double lon, MGRS &mgrs); - static void latLongToOSGR(const double lat, const double lon, OSGR &osgr); - static void latLongToOLC(const double lat, const double lon, OLC &olc); - static void convertWGS84ToOSGB36(const double lat, const double lon, double &osgb_Latitude, double &osgb_Longitude); - static float latLongToMeter(double lat_a, double lng_a, double lat_b, double lng_b); - static float bearing(double lat1, double lon1, double lat2, double lon2); - static float rangeRadiansToMeters(double range_radians); - static float rangeMetersToRadians(double range_meters); + // Conversions + static void latLongToDMS(const double lat, const double lon, DMS &dms); + static void latLongToUTM(const double lat, const double lon, UTM &utm); + static void latLongToMGRS(const double lat, const double lon, MGRS &mgrs); + static void latLongToOSGR(const double lat, const double lon, OSGR &osgr); + static void latLongToOLC(const double lat, const double lon, OLC &olc); + static void convertWGS84ToOSGB36(const double lat, const double lon, double &osgb_Latitude, double &osgb_Longitude); + static float latLongToMeter(double lat_a, double lng_a, double lat_b, double lng_b); + static float bearing(double lat1, double lon1, double lat2, double lon2); + static float rangeRadiansToMeters(double range_radians); + static float rangeMetersToRadians(double range_meters); - // Point to point conversions - int32_t distanceTo(const GeoCoord& pointB); - int32_t bearingTo(const GeoCoord& pointB); - std::shared_ptr pointAtDistance(double bearing, double range); + // Point to point conversions + int32_t distanceTo(const GeoCoord &pointB); + int32_t bearingTo(const GeoCoord &pointB); + std::shared_ptr pointAtDistance(double bearing, double range); - // Lat lon alt getters - int32_t getLatitude() const { return _latitude; } - int32_t getLongitude() const { return _longitude; } - int32_t getAltitude() const { return _altitude; } + // Lat lon alt getters + int32_t getLatitude() const { return _latitude; } + int32_t getLongitude() const { return _longitude; } + int32_t getAltitude() const { return _altitude; } - // DMS getters - uint8_t getDMSLatDeg() const { return _dms.latDeg; } - uint8_t getDMSLatMin() const { return _dms.latMin; } - uint32_t getDMSLatSec() const { return _dms.latSec; } - char getDMSLatCP() const { return _dms.latCP; } - uint8_t getDMSLonDeg() const { return _dms.lonDeg; } - uint8_t getDMSLonMin() const { return _dms.lonMin; } - uint32_t getDMSLonSec() const { return _dms.lonSec; } - char getDMSLonCP() const { return _dms.lonCP; } + // DMS getters + uint8_t getDMSLatDeg() const { return _dms.latDeg; } + uint8_t getDMSLatMin() const { return _dms.latMin; } + uint32_t getDMSLatSec() const { return _dms.latSec; } + char getDMSLatCP() const { return _dms.latCP; } + uint8_t getDMSLonDeg() const { return _dms.lonDeg; } + uint8_t getDMSLonMin() const { return _dms.lonMin; } + uint32_t getDMSLonSec() const { return _dms.lonSec; } + char getDMSLonCP() const { return _dms.lonCP; } - // UTM getters - uint8_t getUTMZone() const { return _utm.zone; } - char getUTMBand() const { return _utm.band; } - uint32_t getUTMEasting() const { return _utm.easting; } - uint32_t getUTMNorthing() const { return _utm.northing; } + // UTM getters + uint8_t getUTMZone() const { return _utm.zone; } + char getUTMBand() const { return _utm.band; } + uint32_t getUTMEasting() const { return _utm.easting; } + uint32_t getUTMNorthing() const { return _utm.northing; } - // MGRS getters - uint8_t getMGRSZone() const { return _mgrs.zone; } - char getMGRSBand() const { return _mgrs.band; } - char getMGRSEast100k() const { return _mgrs.east100k; } - char getMGRSNorth100k() const { return _mgrs.north100k; } - uint32_t getMGRSEasting() const { return _mgrs.easting; } - uint32_t getMGRSNorthing() const { return _mgrs.northing; } + // MGRS getters + uint8_t getMGRSZone() const { return _mgrs.zone; } + char getMGRSBand() const { return _mgrs.band; } + char getMGRSEast100k() const { return _mgrs.east100k; } + char getMGRSNorth100k() const { return _mgrs.north100k; } + uint32_t getMGRSEasting() const { return _mgrs.easting; } + uint32_t getMGRSNorthing() const { return _mgrs.northing; } - // OSGR getters - char getOSGRE100k() const { return _osgr.e100k; } - char getOSGRN100k() const { return _osgr.n100k; } - uint32_t getOSGREasting() const { return _osgr.easting; } - uint32_t getOSGRNorthing() const { return _osgr.northing; } + // OSGR getters + char getOSGRE100k() const { return _osgr.e100k; } + char getOSGRN100k() const { return _osgr.n100k; } + uint32_t getOSGREasting() const { return _osgr.easting; } + uint32_t getOSGRNorthing() const { return _osgr.northing; } - // OLC getter - void getOLCCode(char* code) { strncpy(code, _olc.code, OLC_CODE_LEN + 1); } // +1 for null termination + // OLC getter + void getOLCCode(char *code) { strncpy(code, _olc.code, OLC_CODE_LEN + 1); } // +1 for null termination }; - diff --git a/src/gps/NMEAGPS.cpp b/src/gps/NMEAGPS.cpp index a89083c0e..b7da07934 100644 --- a/src/gps/NMEAGPS.cpp +++ b/src/gps/NMEAGPS.cpp @@ -1,12 +1,12 @@ -#include "configuration.h" #include "NMEAGPS.h" #include "RTC.h" +#include "configuration.h" #include // GPS solutions older than this will be rejected - see TinyGPSDatum::age() -#define GPS_SOL_EXPIRY_MS 5000 // in millis. give 1 second time to combine different sentences. NMEA Frequency isn't higher anyway -#define NMEA_MSG_GXGSA "GNGSA" // GSA message (GPGSA, GNGSA etc) +#define GPS_SOL_EXPIRY_MS 5000 // in millis. give 1 second time to combine different sentences. NMEA Frequency isn't higher anyway +#define NMEA_MSG_GXGSA "GNGSA" // GSA message (GPGSA, GNGSA etc) static int32_t toDegInt(RawDegrees d) { @@ -20,19 +20,18 @@ static int32_t toDegInt(RawDegrees d) bool NMEAGPS::factoryReset() { #ifdef PIN_GPS_REINIT - //The L76K GNSS on the T-Echo requires the RESET pin to be pulled LOW + // The L76K GNSS on the T-Echo requires the RESET pin to be pulled LOW digitalWrite(PIN_GPS_REINIT, 0); pinMode(PIN_GPS_REINIT, OUTPUT); - delay(150); //The L76K datasheet calls for at least 100MS delay + delay(150); // The L76K datasheet calls for at least 100MS delay digitalWrite(PIN_GPS_REINIT, 1); -#endif +#endif // send the UBLOX Factory Reset Command regardless of detect state, something is very wrong, just assume it's UBLOX. // Factory Reset - byte _message_reset[] = {0xB5, 0x62, 0x06, 0x09, 0x0D, 0x00, 0xFF, - 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xFF, 0xFF, 0x00, 0x00, 0x17, 0x2B, 0x7E}; - _serial_gps->write(_message_reset,sizeof(_message_reset)); + byte _message_reset[] = {0xB5, 0x62, 0x06, 0x09, 0x0D, 0x00, 0xFF, 0xFB, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x17, 0x2B, 0x7E}; + _serial_gps->write(_message_reset, sizeof(_message_reset)); delay(1000); return true; } @@ -40,7 +39,7 @@ bool NMEAGPS::factoryReset() bool NMEAGPS::setupGPS() { GPS::setupGPS(); - + #ifdef PIN_GPS_PPS // pulse per second // FIXME - move into shared GPS code @@ -84,8 +83,9 @@ The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of s t.tm_mon = d.month() - 1; t.tm_year = d.year() - 1900; t.tm_isdst = false; - if (t.tm_mon > -1){ - LOG_DEBUG("NMEA GPS time %02d-%02d-%02d %02d:%02d:%02d\n", d.year(), d.month(), t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); + if (t.tm_mon > -1) { + LOG_DEBUG("NMEA GPS time %02d-%02d-%02d %02d:%02d:%02d\n", d.year(), d.month(), t.tm_mday, t.tm_hour, t.tm_min, + t.tm_sec); perhapsSetRTC(RTCQualityGPS, t); return true; } else @@ -102,47 +102,44 @@ The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of s */ bool NMEAGPS::lookForLocation() { - // By default, TinyGPS++ does not parse GPGSA lines, which give us + // By default, TinyGPS++ does not parse GPGSA lines, which give us // the 2D/3D fixType (see NMEAGPS.h) // At a minimum, use the fixQuality indicator in GPGGA (FIXME?) fixQual = reader.fixQuality(); #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS - fixType = atoi(gsafixtype.value()); // will set to zero if no data + fixType = atoi(gsafixtype.value()); // will set to zero if no data // LOG_DEBUG("FIX QUAL=%d, TYPE=%d\n", fixQual, fixType); #endif // check if GPS has an acceptable lock - if (! hasLock()) + if (!hasLock()) return false; #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("AGE: LOC=%d FIX=%d DATE=%d TIME=%d\n", - reader.location.age(), + LOG_DEBUG("AGE: LOC=%d FIX=%d DATE=%d TIME=%d\n", reader.location.age(), #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS - gsafixtype.age(), + gsafixtype.age(), #else - 0, + 0, #endif - reader.date.age(), reader.time.age()); -#endif // GPS_EXTRAVERBOSE + reader.date.age(), reader.time.age()); +#endif // GPS_EXTRAVERBOSE // check if a complete GPS solution set is available for reading // tinyGPSDatum::age() also includes isValid() test // FIXME - if (! ((reader.location.age() < GPS_SOL_EXPIRY_MS) && + if (!((reader.location.age() < GPS_SOL_EXPIRY_MS) && #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS - (gsafixtype.age() < GPS_SOL_EXPIRY_MS) && + (gsafixtype.age() < GPS_SOL_EXPIRY_MS) && #endif - (reader.time.age() < GPS_SOL_EXPIRY_MS) && - (reader.date.age() < GPS_SOL_EXPIRY_MS))) - { + (reader.time.age() < GPS_SOL_EXPIRY_MS) && (reader.date.age() < GPS_SOL_EXPIRY_MS))) { LOG_WARN("SOME data is TOO OLD: LOC %u, TIME %u, DATE %u\n", reader.location.age(), reader.time.age(), reader.date.age()); return false; } // Is this a new point or are we re-reading the previous one? - if (! reader.location.isUpdated()) + if (!reader.location.isUpdated()) return false; // We know the solution is fresh and valid, so just read the data @@ -150,14 +147,14 @@ bool NMEAGPS::lookForLocation() // Bail out EARLY to avoid overwriting previous good data (like #857) if (toDegInt(loc.lat) > 900000000) { -#ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("Bail out EARLY on LAT %i\n",toDegInt(loc.lat)); +#ifdef GPS_EXTRAVERBOSE + LOG_DEBUG("Bail out EARLY on LAT %i\n", toDegInt(loc.lat)); #endif return false; } if (toDegInt(loc.lng) > 1800000000) { -#ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("Bail out EARLY on LNG %i\n",toDegInt(loc.lng)); +#ifdef GPS_EXTRAVERBOSE + LOG_DEBUG("Bail out EARLY on LNG %i\n", toDegInt(loc.lng)); #endif return false; } @@ -209,11 +206,11 @@ bool NMEAGPS::lookForLocation() } if (reader.course.isUpdated() && reader.course.isValid()) { - if (reader.course.value() < 36000) { // sanity check - p.ground_track = reader.course.value() * 1e3; // Scale the heading (in degrees * 10^-2) to match the expected degrees * 10^-5 + if (reader.course.value() < 36000) { // sanity check + p.ground_track = + reader.course.value() * 1e3; // Scale the heading (in degrees * 10^-2) to match the expected degrees * 10^-5 } else { - LOG_WARN("BOGUS course.value() REJECTED: %d\n", - reader.course.value()); + LOG_WARN("BOGUS course.value() REJECTED: %d\n", reader.course.value()); } } @@ -224,14 +221,13 @@ bool NMEAGPS::lookForLocation() return true; } - bool NMEAGPS::hasLock() { // Using GPGGA fix quality indicator if (fixQual >= 1 && fixQual <= 5) { #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS // Use GPGSA fix type 2D/3D (better) if available - if (fixType == 3 || fixType == 0) // zero means "no data received" + if (fixType == 3 || fixType == 0) // zero means "no data received" #endif return true; } diff --git a/src/gps/NMEAGPS.h b/src/gps/NMEAGPS.h index c97be08ce..82e691717 100644 --- a/src/gps/NMEAGPS.h +++ b/src/gps/NMEAGPS.h @@ -12,14 +12,14 @@ class NMEAGPS : public GPS { TinyGPSPlus reader; - uint8_t fixQual = 0; // fix quality from GPGGA + uint8_t fixQual = 0; // fix quality from GPGGA #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS // (20210908) TinyGps++ can only read the GPGSA "FIX TYPE" field // via optional feature "custom fields", currently disabled (bug #525) - TinyGPSCustom gsafixtype; // custom extract fix type from GPGSA - TinyGPSCustom gsapdop; // custom extract PDOP from GPGSA - uint8_t fixType = 0; // fix type from GPGSA + TinyGPSCustom gsafixtype; // custom extract fix type from GPGSA + TinyGPSCustom gsapdop; // custom extract PDOP from GPGSA + uint8_t fixType = 0; // fix type from GPGSA #endif public: @@ -29,9 +29,9 @@ class NMEAGPS : public GPS protected: /** Subclasses should look for serial rx characters here and feed it to their GPS parser - * + * * Return true if we received a valid message from the GPS - */ + */ virtual bool whileIdle() override; /** diff --git a/src/gps/NMEAWPL.cpp b/src/gps/NMEAWPL.cpp index 8fafc6ba0..232218b34 100644 --- a/src/gps/NMEAWPL.cpp +++ b/src/gps/NMEAWPL.cpp @@ -18,15 +18,11 @@ uint32_t printWPL(char *buf, size_t bufsz, const Position &pos, const char *name) { - GeoCoord geoCoord(pos.latitude_i,pos.longitude_i,pos.altitude); - uint32_t len = snprintf(buf, bufsz, "$GNWPL,%02d%07.4f,%c,%03d%07.4f,%c,%s", - geoCoord.getDMSLatDeg(), - (abs(geoCoord.getLatitude()) - geoCoord.getDMSLatDeg() * 1e+7) * 6e-6, - geoCoord.getDMSLatCP(), - geoCoord.getDMSLonDeg(), - (abs(geoCoord.getLongitude()) - geoCoord.getDMSLonDeg() * 1e+7) * 6e-6, - geoCoord.getDMSLonCP(), - name); + GeoCoord geoCoord(pos.latitude_i, pos.longitude_i, pos.altitude); + uint32_t len = snprintf(buf, bufsz, "$GNWPL,%02d%07.4f,%c,%03d%07.4f,%c,%s", geoCoord.getDMSLatDeg(), + (abs(geoCoord.getLatitude()) - geoCoord.getDMSLatDeg() * 1e+7) * 6e-6, geoCoord.getDMSLatCP(), + geoCoord.getDMSLonDeg(), (abs(geoCoord.getLongitude()) - geoCoord.getDMSLonDeg() * 1e+7) * 6e-6, + geoCoord.getDMSLonCP(), name); uint32_t chk = 0; for (uint32_t i = 1; i < len; i++) { chk ^= buf[i]; @@ -51,35 +47,21 @@ uint32_t printWPL(char *buf, size_t bufsz, const Position &pos, const char *name * 8 Horizontal Dilution of precision (meters) * 9 Antenna Altitude above/below mean-sea-level (geoid) (in meters) * 10 Units of antenna altitude, meters - * 11 Geoidal separation, the difference between the WGS-84 earth ellipsoid and mean-sea-level (geoid), "-" means mean-sea-level below ellipsoid - * 12 Units of geoidal separation, meters - * 13 Age of differential GPS data, time in seconds since last SC104 type 1 or 9 update, null field when DGPS is not used - * 14 Differential reference station ID, 0000-1023 - * 15 Checksum + * 11 Geoidal separation, the difference between the WGS-84 earth ellipsoid and mean-sea-level (geoid), "-" means mean-sea-level + * below ellipsoid 12 Units of geoidal separation, meters 13 Age of differential GPS data, time in seconds since last SC104 type 1 + * or 9 update, null field when DGPS is not used 14 Differential reference station ID, 0000-1023 15 Checksum * ------------------------------------------- */ uint32_t printGGA(char *buf, size_t bufsz, const Position &pos) { - GeoCoord geoCoord(pos.latitude_i,pos.longitude_i,pos.altitude); - uint32_t len = snprintf(buf, bufsz, "$GNGGA,%06u.%03u,%02d%07.4f,%c,%03d%07.4f,%c,%u,%02u,%04u,%04d,%c,%04d,%c,%d,%04d", - pos.time / 1000, - pos.time % 1000, - geoCoord.getDMSLatDeg(), - (abs(geoCoord.getLatitude()) - geoCoord.getDMSLatDeg() * 1e+7) * 6e-6, - geoCoord.getDMSLatCP(), - geoCoord.getDMSLonDeg(), - (abs(geoCoord.getLongitude()) - geoCoord.getDMSLonDeg() * 1e+7) * 6e-6, - geoCoord.getDMSLonCP(), - pos.fix_type, - pos.sats_in_view, - pos.HDOP, - geoCoord.getAltitude(), - 'M', - pos.altitude_geoidal_separation, - 'M', - 0, - 0); + GeoCoord geoCoord(pos.latitude_i, pos.longitude_i, pos.altitude); + uint32_t len = + snprintf(buf, bufsz, "$GNGGA,%06u.%03u,%02d%07.4f,%c,%03d%07.4f,%c,%u,%02u,%04u,%04d,%c,%04d,%c,%d,%04d", pos.time / 1000, + pos.time % 1000, geoCoord.getDMSLatDeg(), (abs(geoCoord.getLatitude()) - geoCoord.getDMSLatDeg() * 1e+7) * 6e-6, + geoCoord.getDMSLatCP(), geoCoord.getDMSLonDeg(), + (abs(geoCoord.getLongitude()) - geoCoord.getDMSLonDeg() * 1e+7) * 6e-6, geoCoord.getDMSLonCP(), pos.fix_type, + pos.sats_in_view, pos.HDOP, geoCoord.getAltitude(), 'M', pos.altitude_geoidal_separation, 'M', 0, 0); uint32_t chk = 0; for (uint32_t i = 1; i < len; i++) { diff --git a/src/gps/NMEAWPL.h b/src/gps/NMEAWPL.h index ee79ffd08..9017c8797 100644 --- a/src/gps/NMEAWPL.h +++ b/src/gps/NMEAWPL.h @@ -1,7 +1,7 @@ #pragma once -#include #include "main.h" +#include uint32_t printWPL(char *buf, size_t bufsz, const Position &pos, const char *name); uint32_t printGGA(char *buf, size_t bufsz, const Position &pos); diff --git a/src/gps/RTC.cpp b/src/gps/RTC.cpp index e61991917..2e25949af 100644 --- a/src/gps/RTC.cpp +++ b/src/gps/RTC.cpp @@ -20,7 +20,7 @@ void readFromRTC() { struct timeval tv; /* btw settimeofday() is helpfull here too*/ #ifdef RV3028_RTC - if(rtc_found == RV3028_RTC) { + if (rtc_found == RV3028_RTC) { uint32_t now = millis(); Melopero_RV3028 rtc; rtc.initI2C(); @@ -41,7 +41,7 @@ void readFromRTC() } } #elif defined(PCF8563_RTC) - if(rtc_found == PCF8563_RTC) { + if (rtc_found == PCF8563_RTC) { uint32_t now = millis(); PCF8563_Class rtc; #ifdef RTC_USE_WIRE1 @@ -66,7 +66,7 @@ void readFromRTC() currentQuality = RTCQualityDevice; } } -#else +#else if (!gettimeofday(&tv, NULL)) { uint32_t now = millis(); LOG_DEBUG("Read RTC time as %ld\n", tv.tv_sec); @@ -87,12 +87,11 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv) currentQuality = q; shouldSet = true; LOG_DEBUG("Upgrading time to RTC %ld secs (quality %d)\n", tv->tv_sec, q); - } else if(q == RTCQualityGPS && (now - lastSetMsec) > (12 * 60 * 60 * 1000UL)) { + } else if (q == RTCQualityGPS && (now - lastSetMsec) > (12 * 60 * 60 * 1000UL)) { // Every 12 hrs we will slam in a new GPS time, to correct for local RTC clock drift shouldSet = true; LOG_DEBUG("Reapplying external time to correct clock drift %ld secs\n", tv->tv_sec); - } - else + } else shouldSet = false; if (shouldSet) { @@ -104,24 +103,26 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv) // If this platform has a setable RTC, set it #ifdef RV3028_RTC - if(rtc_found == RV3028_RTC) { + if (rtc_found == RV3028_RTC) { Melopero_RV3028 rtc; rtc.initI2C(); tm *t = localtime(&tv->tv_sec); rtc.setTime(t->tm_year + 1900, t->tm_mon + 1, t->tm_wday, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); - LOG_DEBUG("RV3028_RTC setTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); + LOG_DEBUG("RV3028_RTC setTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, + t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); } #elif defined(PCF8563_RTC) - if(rtc_found == PCF8563_RTC) { + if (rtc_found == PCF8563_RTC) { PCF8563_Class rtc; #ifdef RTC_USE_WIRE1 - rtc.begin(Wire1); + rtc.begin(Wire1); #else - rtc.begin(); + rtc.begin(); #endif tm *t = localtime(&tv->tv_sec); rtc.setDateTime(t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); - LOG_DEBUG("PCF8563_RTC setDateTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); + LOG_DEBUG("PCF8563_RTC setDateTime %02d-%02d-%02d %02d:%02d:%02d %ld\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, + t->tm_hour, t->tm_min, t->tm_sec, tv->tv_sec); } #elif defined(ARCH_ESP32) settimeofday(tv, NULL); @@ -160,7 +161,7 @@ bool perhapsSetRTC(RTCQuality q, struct tm &t) uint32_t getTime() { - return (((uint32_t) millis() - timeStartMsec) / 1000) + zeroOffsetSecs; + return (((uint32_t)millis() - timeStartMsec) / 1000) + zeroOffsetSecs; } uint32_t getValidTime(RTCQuality minQuality) diff --git a/src/graphics/fonts/OLEDDisplayFontsRU.cpp b/src/graphics/fonts/OLEDDisplayFontsRU.cpp index 6ce18c9d1..fa055d8b5 100644 --- a/src/graphics/fonts/OLEDDisplayFontsRU.cpp +++ b/src/graphics/fonts/OLEDDisplayFontsRU.cpp @@ -2,425 +2,425 @@ // Font generated or edited with the glyphEditor const uint8_t ArialMT_Plain_10_RU[] PROGMEM = { - 0x0A, // Width: 10 - 0x0D, // Height: 13 - 0x20, // First char: 32 - 0xE0, // Number of chars: 224 - - // Jump Table: - 0xFF, 0xFF, 0x00, 0x0A, // 32 - 0x00, 0x00, 0x04, 0x03, // 33 - 0x00, 0x04, 0x05, 0x04, // 34 - 0x00, 0x09, 0x09, 0x06, // 35 - 0x00, 0x12, 0x0A, 0x06, // 36 - 0x00, 0x1C, 0x10, 0x09, // 37 - 0x00, 0x2C, 0x0E, 0x08, // 38 - 0x00, 0x3A, 0x01, 0x02, // 39 - 0x00, 0x3B, 0x06, 0x04, // 40 - 0x00, 0x41, 0x06, 0x04, // 41 - 0x00, 0x47, 0x05, 0x04, // 42 - 0x00, 0x4C, 0x09, 0x06, // 43 - 0x00, 0x55, 0x04, 0x03, // 44 - 0x00, 0x59, 0x03, 0x03, // 45 - 0x00, 0x5C, 0x04, 0x03, // 46 - 0x00, 0x60, 0x05, 0x04, // 47 - 0x00, 0x65, 0x0A, 0x06, // 48 - 0x00, 0x6F, 0x08, 0x05, // 49 - 0x00, 0x77, 0x0A, 0x06, // 50 - 0x00, 0x81, 0x0A, 0x06, // 51 - 0x00, 0x8B, 0x0B, 0x07, // 52 - 0x00, 0x96, 0x0A, 0x06, // 53 - 0x00, 0xA0, 0x0A, 0x06, // 54 - 0x00, 0xAA, 0x09, 0x06, // 55 - 0x00, 0xB3, 0x0A, 0x06, // 56 - 0x00, 0xBD, 0x0A, 0x06, // 57 - 0x00, 0xC7, 0x04, 0x03, // 58 - 0x00, 0xCB, 0x04, 0x03, // 59 - 0x00, 0xCF, 0x0A, 0x06, // 60 - 0x00, 0xD9, 0x09, 0x06, // 61 - 0x00, 0xE2, 0x09, 0x06, // 62 - 0x00, 0xEB, 0x0B, 0x07, // 63 - 0x00, 0xF6, 0x14, 0x0B, // 64 - 0x01, 0x0A, 0x0E, 0x08, // 65 - 0x01, 0x18, 0x0C, 0x07, // 66 - 0x01, 0x24, 0x0C, 0x07, // 67 - 0x01, 0x30, 0x0B, 0x07, // 68 - 0x01, 0x3B, 0x0C, 0x07, // 69 - 0x01, 0x47, 0x09, 0x06, // 70 - 0x01, 0x50, 0x0D, 0x08, // 71 - 0x01, 0x5D, 0x0C, 0x07, // 72 - 0x01, 0x69, 0x04, 0x03, // 73 - 0x01, 0x6D, 0x08, 0x05, // 74 - 0x01, 0x75, 0x0E, 0x08, // 75 - 0x01, 0x83, 0x0C, 0x07, // 76 - 0x01, 0x8F, 0x10, 0x09, // 77 - 0x01, 0x9F, 0x0C, 0x07, // 78 - 0x01, 0xAB, 0x0E, 0x08, // 79 - 0x01, 0xB9, 0x0B, 0x07, // 80 - 0x01, 0xC4, 0x0E, 0x08, // 81 - 0x01, 0xD2, 0x0C, 0x07, // 82 - 0x01, 0xDE, 0x0C, 0x07, // 83 - 0x01, 0xEA, 0x0B, 0x07, // 84 - 0x01, 0xF5, 0x0C, 0x07, // 85 - 0x02, 0x01, 0x0D, 0x08, // 86 - 0x02, 0x0E, 0x11, 0x0A, // 87 - 0x02, 0x1F, 0x0E, 0x08, // 88 - 0x02, 0x2D, 0x0D, 0x08, // 89 - 0x02, 0x3A, 0x0C, 0x07, // 90 - 0x02, 0x46, 0x06, 0x04, // 91 - 0x02, 0x4C, 0x06, 0x04, // 92 - 0x02, 0x52, 0x04, 0x03, // 93 - 0x02, 0x56, 0x09, 0x06, // 94 - 0x02, 0x5F, 0x0C, 0x07, // 95 - 0x02, 0x6B, 0x03, 0x03, // 96 - 0x02, 0x6E, 0x0A, 0x06, // 97 - 0x02, 0x78, 0x0A, 0x06, // 98 - 0x02, 0x82, 0x0A, 0x06, // 99 - 0x02, 0x8C, 0x0A, 0x06, // 100 - 0x02, 0x96, 0x0A, 0x06, // 101 - 0x02, 0xA0, 0x05, 0x04, // 102 - 0x02, 0xA5, 0x0A, 0x06, // 103 - 0x02, 0xAF, 0x0A, 0x06, // 104 - 0x02, 0xB9, 0x04, 0x03, // 105 - 0x02, 0xBD, 0x04, 0x03, // 106 - 0x02, 0xC1, 0x08, 0x05, // 107 - 0x02, 0xC9, 0x04, 0x03, // 108 - 0x02, 0xCD, 0x10, 0x09, // 109 - 0x02, 0xDD, 0x0A, 0x06, // 110 - 0x02, 0xE7, 0x0A, 0x06, // 111 - 0x02, 0xF1, 0x0A, 0x06, // 112 - 0x02, 0xFB, 0x0A, 0x06, // 113 - 0x03, 0x05, 0x05, 0x04, // 114 - 0x03, 0x0A, 0x08, 0x05, // 115 - 0x03, 0x12, 0x06, 0x04, // 116 - 0x03, 0x18, 0x0A, 0x06, // 117 - 0x03, 0x22, 0x09, 0x06, // 118 - 0x03, 0x2B, 0x0E, 0x08, // 119 - 0x03, 0x39, 0x0A, 0x06, // 120 - 0x03, 0x43, 0x09, 0x06, // 121 - 0x03, 0x4C, 0x0A, 0x06, // 122 - 0x03, 0x56, 0x06, 0x04, // 123 - 0x03, 0x5C, 0x04, 0x03, // 124 - 0x03, 0x60, 0x05, 0x04, // 125 - 0x03, 0x65, 0x09, 0x06, // 126 - 0xFF, 0xFF, 0x00, 0x0A, // 127 - 0xFF, 0xFF, 0x00, 0x0A, // 128 - 0xFF, 0xFF, 0x00, 0x0A, // 129 - 0xFF, 0xFF, 0x00, 0x0A, // 130 - 0xFF, 0xFF, 0x00, 0x0A, // 131 - 0xFF, 0xFF, 0x00, 0x0A, // 132 - 0xFF, 0xFF, 0x00, 0x0A, // 133 - 0xFF, 0xFF, 0x00, 0x0A, // 134 - 0xFF, 0xFF, 0x00, 0x0A, // 135 - 0xFF, 0xFF, 0x00, 0x0A, // 136 - 0xFF, 0xFF, 0x00, 0x0A, // 137 - 0xFF, 0xFF, 0x00, 0x0A, // 138 - 0xFF, 0xFF, 0x00, 0x0A, // 139 - 0xFF, 0xFF, 0x00, 0x0A, // 140 - 0xFF, 0xFF, 0x00, 0x0A, // 141 - 0xFF, 0xFF, 0x00, 0x0A, // 142 - 0xFF, 0xFF, 0x00, 0x0A, // 143 - 0xFF, 0xFF, 0x00, 0x0A, // 144 - 0xFF, 0xFF, 0x00, 0x0A, // 145 - 0xFF, 0xFF, 0x00, 0x0A, // 146 - 0xFF, 0xFF, 0x00, 0x0A, // 147 - 0xFF, 0xFF, 0x00, 0x0A, // 148 - 0xFF, 0xFF, 0x00, 0x0A, // 149 - 0xFF, 0xFF, 0x00, 0x0A, // 150 - 0xFF, 0xFF, 0x00, 0x0A, // 151 - 0xFF, 0xFF, 0x00, 0x0A, // 152 - 0xFF, 0xFF, 0x00, 0x0A, // 153 - 0xFF, 0xFF, 0x00, 0x0A, // 154 - 0xFF, 0xFF, 0x00, 0x0A, // 155 - 0xFF, 0xFF, 0x00, 0x0A, // 156 - 0xFF, 0xFF, 0x00, 0x0A, // 157 - 0xFF, 0xFF, 0x00, 0x0A, // 158 - 0xFF, 0xFF, 0x00, 0x0A, // 159 - 0xFF, 0xFF, 0x00, 0x0A, // 160 - 0x03, 0x6E, 0x04, 0x03, // 161 - 0x03, 0x72, 0x0A, 0x06, // 162 - 0x03, 0x7C, 0x0C, 0x07, // 163 - 0x03, 0x88, 0x0A, 0x06, // 164 - 0x03, 0x92, 0x0A, 0x06, // 165 - 0x03, 0x9C, 0x04, 0x03, // 166 - 0x03, 0xA0, 0x0A, 0x06, // 167 - 0x03, 0xAA, 0x0C, 0x07, // 168 - 0x03, 0xB6, 0x0D, 0x08, // 169 - 0x03, 0xC3, 0x07, 0x05, // 170 - 0x03, 0xCA, 0x0A, 0x06, // 171 - 0x03, 0xD4, 0x09, 0x06, // 172 - 0x03, 0xDD, 0x03, 0x03, // 173 - 0x03, 0xE0, 0x0D, 0x08, // 174 - 0x03, 0xED, 0x0B, 0x07, // 175 - 0x03, 0xF8, 0x07, 0x05, // 176 - 0x03, 0xFF, 0x0A, 0x06, // 177 - 0x04, 0x09, 0x05, 0x04, // 178 - 0x04, 0x0E, 0x05, 0x04, // 179 - 0x04, 0x13, 0x05, 0x04, // 180 - 0x04, 0x18, 0x0A, 0x06, // 181 - 0x04, 0x22, 0x09, 0x06, // 182 - 0x04, 0x2B, 0x03, 0x03, // 183 - 0x04, 0x2E, 0x0B, 0x07, // 184 - 0x04, 0x39, 0x0B, 0x07, // 185 - 0x04, 0x44, 0x07, 0x05, // 186 - 0x04, 0x4B, 0x0A, 0x06, // 187 - 0x04, 0x55, 0x10, 0x09, // 188 - 0x04, 0x65, 0x10, 0x09, // 189 - 0x04, 0x75, 0x10, 0x09, // 190 - 0x04, 0x85, 0x0A, 0x06, // 191 - 0x04, 0x8F, 0x0C, 0x07, // 192 - 0x04, 0x9B, 0x0C, 0x07, // 193 - 0x04, 0xA7, 0x0C, 0x07, // 194 - 0x04, 0xB3, 0x0B, 0x07, // 195 - 0x04, 0xBE, 0x0C, 0x07, // 196 - 0x04, 0xCA, 0x0C, 0x07, // 197 - 0x04, 0xD6, 0x0C, 0x07, // 198 - 0x04, 0xE2, 0x0C, 0x07, // 199 - 0x04, 0xEE, 0x0C, 0x07, // 200 - 0x04, 0xFA, 0x0C, 0x07, // 201 - 0x05, 0x06, 0x0C, 0x07, // 202 - 0x05, 0x12, 0x0C, 0x07, // 203 - 0x05, 0x1E, 0x0C, 0x07, // 204 - 0x05, 0x2A, 0x0C, 0x07, // 205 - 0x05, 0x36, 0x0C, 0x07, // 206 - 0x05, 0x42, 0x0C, 0x07, // 207 - 0x05, 0x4E, 0x0B, 0x07, // 208 - 0x05, 0x59, 0x0C, 0x07, // 209 - 0x05, 0x65, 0x0B, 0x07, // 210 - 0x05, 0x70, 0x0C, 0x07, // 211 - 0x05, 0x7C, 0x0B, 0x07, // 212 - 0x05, 0x87, 0x0C, 0x07, // 213 - 0x05, 0x93, 0x0C, 0x07, // 214 - 0x05, 0x9F, 0x0C, 0x07, // 215 - 0x05, 0xAB, 0x0C, 0x07, // 216 - 0x05, 0xB7, 0x0E, 0x08, // 217 - 0x05, 0xC5, 0x0C, 0x07, // 218 - 0x05, 0xD1, 0x0C, 0x07, // 219 - 0x05, 0xDD, 0x0C, 0x07, // 220 - 0x05, 0xE9, 0x0C, 0x07, // 221 - 0x05, 0xF5, 0x0C, 0x07, // 222 - 0x06, 0x01, 0x0C, 0x07, // 223 - 0x06, 0x0D, 0x0C, 0x07, // 224 - 0x06, 0x19, 0x0C, 0x07, // 225 - 0x06, 0x25, 0x0C, 0x07, // 226 - 0x06, 0x31, 0x0B, 0x07, // 227 - 0x06, 0x3C, 0x0C, 0x07, // 228 - 0x06, 0x48, 0x0B, 0x07, // 229 - 0x06, 0x53, 0x0C, 0x07, // 230 - 0x06, 0x5F, 0x0C, 0x07, // 231 - 0x06, 0x6B, 0x0C, 0x07, // 232 - 0x06, 0x77, 0x0C, 0x07, // 233 - 0x06, 0x83, 0x0C, 0x07, // 234 - 0x06, 0x8F, 0x0C, 0x07, // 235 - 0x06, 0x9B, 0x0C, 0x07, // 236 - 0x06, 0xA7, 0x0C, 0x07, // 237 - 0x06, 0xB3, 0x0C, 0x07, // 238 - 0x06, 0xBF, 0x0C, 0x07, // 239 - 0x06, 0xCB, 0x0B, 0x07, // 240 - 0x06, 0xD6, 0x0C, 0x07, // 241 - 0x06, 0xE2, 0x0B, 0x07, // 242 - 0x06, 0xED, 0x0C, 0x07, // 243 - 0x06, 0xF9, 0x0B, 0x07, // 244 - 0x07, 0x04, 0x0C, 0x07, // 245 - 0x07, 0x10, 0x0C, 0x07, // 246 - 0x07, 0x1C, 0x0C, 0x07, // 247 - 0x07, 0x28, 0x0C, 0x07, // 248 - 0x07, 0x34, 0x0E, 0x08, // 249 - 0x07, 0x42, 0x0C, 0x07, // 250 - 0x07, 0x4E, 0x0C, 0x07, // 251 - 0x07, 0x5A, 0x0C, 0x07, // 252 - 0x07, 0x66, 0x0C, 0x07, // 253 - 0x07, 0x72, 0x0C, 0x07, // 254 - 0x07, 0x7E, 0x0C, 0x07, // 255 - - // Font Data: - 0x00, 0x00, 0xF8, 0x02, // 33 - 0x38, 0x00, 0x00, 0x00, 0x38, // 34 - 0xA0, 0x03, 0xE0, 0x00, 0xB8, 0x03, 0xE0, 0x00, 0xB8, // 35 - 0x30, 0x01, 0x28, 0x02, 0xF8, 0x07, 0x48, 0x02, 0x90, 0x01, // 36 - 0x00, 0x00, 0x30, 0x00, 0x48, 0x00, 0x30, 0x03, 0xC0, 0x00, 0xB0, 0x01, 0x48, 0x02, 0x80, 0x01, // 37 - 0x80, 0x01, 0x50, 0x02, 0x68, 0x02, 0xA8, 0x02, 0x18, 0x01, 0x80, 0x03, 0x80, 0x02, // 38 - 0x38, // 39 - 0xE0, 0x03, 0x10, 0x04, 0x08, 0x08, // 40 - 0x08, 0x08, 0x10, 0x04, 0xE0, 0x03, // 41 - 0x28, 0x00, 0x18, 0x00, 0x28, // 42 - 0x40, 0x00, 0x40, 0x00, 0xF0, 0x01, 0x40, 0x00, 0x40, // 43 - 0x00, 0x00, 0x00, 0x06, // 44 - 0x80, 0x00, 0x80, // 45 - 0x00, 0x00, 0x00, 0x02, // 46 - 0x00, 0x03, 0xE0, 0x00, 0x18, // 47 - 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0xF0, 0x01, // 48 - 0x00, 0x00, 0x20, 0x00, 0x10, 0x00, 0xF8, 0x03, // 49 - 0x10, 0x02, 0x08, 0x03, 0x88, 0x02, 0x48, 0x02, 0x30, 0x02, // 50 - 0x10, 0x01, 0x08, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 51 - 0xC0, 0x00, 0xA0, 0x00, 0x90, 0x00, 0x88, 0x00, 0xF8, 0x03, 0x80, // 52 - 0x60, 0x01, 0x38, 0x02, 0x28, 0x02, 0x28, 0x02, 0xC8, 0x01, // 53 - 0xF0, 0x01, 0x28, 0x02, 0x28, 0x02, 0x28, 0x02, 0xD0, 0x01, // 54 - 0x08, 0x00, 0x08, 0x03, 0xC8, 0x00, 0x38, 0x00, 0x08, // 55 - 0xB0, 0x01, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 56 - 0x70, 0x01, 0x88, 0x02, 0x88, 0x02, 0x88, 0x02, 0xF0, 0x01, // 57 - 0x00, 0x00, 0x20, 0x02, // 58 - 0x00, 0x00, 0x20, 0x06, // 59 - 0x00, 0x00, 0x40, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0x10, 0x01, // 60 - 0xA0, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0xA0, // 61 - 0x00, 0x00, 0x10, 0x01, 0xA0, 0x00, 0xA0, 0x00, 0x40, // 62 - 0x10, 0x00, 0x08, 0x00, 0x08, 0x00, 0xC8, 0x02, 0x48, 0x00, 0x30, // 63 - 0x00, 0x00, 0xC0, 0x03, 0x30, 0x04, 0xD0, 0x09, 0x28, 0x0A, 0x28, 0x0A, 0xC8, 0x0B, 0x68, 0x0A, 0x10, 0x05, 0xE0, 0x04, // 64 - 0x00, 0x02, 0xC0, 0x01, 0xB0, 0x00, 0x88, 0x00, 0xB0, 0x00, 0xC0, 0x01, 0x00, 0x02, // 65 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xF0, 0x01, // 66 - 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0x10, 0x01, // 67 - 0x00, 0x00, 0xF8, 0x03, 0x08, 0x02, 0x08, 0x02, 0x10, 0x01, 0xE0, // 68 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, // 69 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0x08, // 70 - 0x00, 0x00, 0xE0, 0x00, 0x10, 0x01, 0x08, 0x02, 0x48, 0x02, 0x50, 0x01, 0xC0, // 71 - 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0xF8, 0x03, // 72 - 0x00, 0x00, 0xF8, 0x03, // 73 - 0x00, 0x03, 0x00, 0x02, 0x00, 0x02, 0xF8, 0x01, // 74 - 0x00, 0x00, 0xF8, 0x03, 0x80, 0x00, 0x60, 0x00, 0x90, 0x00, 0x08, 0x01, 0x00, 0x02, // 75 - 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, // 76 - 0x00, 0x00, 0xF8, 0x03, 0x30, 0x00, 0xC0, 0x01, 0x00, 0x02, 0xC0, 0x01, 0x30, 0x00, 0xF8, 0x03, // 77 - 0x00, 0x00, 0xF8, 0x03, 0x30, 0x00, 0x40, 0x00, 0x80, 0x01, 0xF8, 0x03, // 78 - 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0xF0, 0x01, // 79 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0x48, 0x00, 0x30, // 80 - 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x03, 0x08, 0x03, 0xF0, 0x02, // 81 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0xC8, 0x00, 0x30, 0x03, // 82 - 0x00, 0x00, 0x30, 0x01, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x90, 0x01, // 83 - 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, // 84 - 0x00, 0x00, 0xF8, 0x01, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0xF8, 0x01, // 85 - 0x08, 0x00, 0x70, 0x00, 0x80, 0x01, 0x00, 0x02, 0x80, 0x01, 0x70, 0x00, 0x08, // 86 - 0x18, 0x00, 0xE0, 0x01, 0x00, 0x02, 0xF0, 0x01, 0x08, 0x00, 0xF0, 0x01, 0x00, 0x02, 0xE0, 0x01, 0x18, // 87 - 0x00, 0x02, 0x08, 0x01, 0x90, 0x00, 0x60, 0x00, 0x90, 0x00, 0x08, 0x01, 0x00, 0x02, // 88 - 0x08, 0x00, 0x10, 0x00, 0x20, 0x00, 0xC0, 0x03, 0x20, 0x00, 0x10, 0x00, 0x08, // 89 - 0x08, 0x03, 0x88, 0x02, 0xC8, 0x02, 0x68, 0x02, 0x38, 0x02, 0x18, 0x02, // 90 - 0x00, 0x00, 0xF8, 0x0F, 0x08, 0x08, // 91 - 0x18, 0x00, 0xE0, 0x00, 0x00, 0x03, // 92 - 0x08, 0x08, 0xF8, 0x0F, // 93 - 0x40, 0x00, 0x30, 0x00, 0x08, 0x00, 0x30, 0x00, 0x40, // 94 - 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, // 95 - 0x08, 0x00, 0x10, // 96 - 0x00, 0x00, 0x00, 0x03, 0xA0, 0x02, 0xA0, 0x02, 0xE0, 0x03, // 97 - 0x00, 0x00, 0xF8, 0x03, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 98 - 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0x40, 0x01, // 99 - 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0xF8, 0x03, // 100 - 0x00, 0x00, 0xC0, 0x01, 0xA0, 0x02, 0xA0, 0x02, 0xC0, 0x02, // 101 - 0x20, 0x00, 0xF0, 0x03, 0x28, // 102 - 0x00, 0x00, 0xC0, 0x05, 0x20, 0x0A, 0x20, 0x0A, 0xE0, 0x07, // 103 - 0x00, 0x00, 0xF8, 0x03, 0x20, 0x00, 0x20, 0x00, 0xC0, 0x03, // 104 - 0x00, 0x00, 0xE8, 0x03, // 105 - 0x00, 0x08, 0xE8, 0x07, // 106 - 0xF8, 0x03, 0x80, 0x00, 0xC0, 0x01, 0x20, 0x02, // 107 - 0x00, 0x00, 0xF8, 0x03, // 108 - 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0xC0, 0x03, // 109 - 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0xC0, 0x03, // 110 - 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 111 - 0x00, 0x00, 0xE0, 0x0F, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 112 - 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0xE0, 0x0F, // 113 - 0x00, 0x00, 0xE0, 0x03, 0x20, // 114 - 0x40, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0x20, 0x01, // 115 - 0x20, 0x00, 0xF8, 0x03, 0x20, 0x02, // 116 - 0x00, 0x00, 0xE0, 0x01, 0x00, 0x02, 0x00, 0x02, 0xE0, 0x03, // 117 - 0x20, 0x00, 0xC0, 0x01, 0x00, 0x02, 0xC0, 0x01, 0x20, // 118 - 0xE0, 0x01, 0x00, 0x02, 0xC0, 0x01, 0x20, 0x00, 0xC0, 0x01, 0x00, 0x02, 0xE0, 0x01, // 119 - 0x20, 0x02, 0x40, 0x01, 0x80, 0x00, 0x40, 0x01, 0x20, 0x02, // 120 - 0x20, 0x00, 0xC0, 0x09, 0x00, 0x06, 0xC0, 0x01, 0x20, // 121 - 0x20, 0x02, 0x20, 0x03, 0xA0, 0x02, 0x60, 0x02, 0x20, 0x02, // 122 - 0x80, 0x00, 0x78, 0x0F, 0x08, 0x08, // 123 - 0x00, 0x00, 0xF8, 0x0F, // 124 - 0x08, 0x08, 0x78, 0x0F, 0x80, // 125 - 0xC0, 0x00, 0x40, 0x00, 0xC0, 0x00, 0x80, 0x00, 0xC0, // 126 - 0x00, 0x00, 0xA0, 0x0F, // 161 - 0x00, 0x00, 0xC0, 0x01, 0xA0, 0x0F, 0x78, 0x02, 0x40, 0x01, // 162 - 0x40, 0x02, 0x70, 0x03, 0xC8, 0x02, 0x48, 0x02, 0x08, 0x02, 0x10, 0x02, // 163 - 0x00, 0x00, 0xE0, 0x01, 0x20, 0x01, 0x20, 0x01, 0xE0, 0x01, // 164 - 0x48, 0x01, 0x70, 0x01, 0xC0, 0x03, 0x70, 0x01, 0x48, 0x01, // 165 - 0x00, 0x00, 0x38, 0x0F, // 166 - 0xD0, 0x04, 0x28, 0x09, 0x48, 0x09, 0x48, 0x0A, 0x90, 0x05, // 167 - 0x00, 0x00, 0xE0, 0x03, 0xA8, 0x02, 0xA0, 0x02, 0xA8, 0x02, 0x20, 0x02, // 168 - 0xE0, 0x00, 0x10, 0x01, 0x48, 0x02, 0xA8, 0x02, 0xA8, 0x02, 0x10, 0x01, 0xE0, // 169 - 0x68, 0x00, 0x68, 0x00, 0x68, 0x00, 0x78, // 170 - 0x00, 0x00, 0x80, 0x01, 0x40, 0x02, 0x80, 0x01, 0x40, 0x02, // 171 - 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0xE0, // 172 - 0x80, 0x00, 0x80, // 173 - 0xE0, 0x00, 0x10, 0x01, 0xE8, 0x02, 0x68, 0x02, 0xC8, 0x02, 0x10, 0x01, 0xE0, // 174 - 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, // 175 - 0x00, 0x00, 0x38, 0x00, 0x28, 0x00, 0x38, // 176 - 0x40, 0x02, 0x40, 0x02, 0xF0, 0x03, 0x40, 0x02, 0x40, 0x02, // 177 - 0x48, 0x00, 0x68, 0x00, 0x58, // 178 - 0x48, 0x00, 0x58, 0x00, 0x68, // 179 - 0x00, 0x00, 0x10, 0x00, 0x08, // 180 - 0x00, 0x00, 0xE0, 0x0F, 0x00, 0x02, 0x00, 0x02, 0xE0, 0x03, // 181 - 0x70, 0x00, 0xF8, 0x0F, 0x08, 0x00, 0xF8, 0x0F, 0x08, // 182 - 0x00, 0x00, 0x40, // 183 - 0x00, 0x00, 0xC0, 0x01, 0xA8, 0x02, 0xA0, 0x02, 0xA8, 0x02, 0xC0, // 184 - 0x00, 0x00, 0xF0, 0x03, 0x40, 0x00, 0x80, 0x00, 0xF8, 0x03, 0x08, // 185 - 0x30, 0x00, 0x48, 0x00, 0x48, 0x00, 0x30, // 186 - 0x00, 0x00, 0x40, 0x02, 0x80, 0x01, 0x40, 0x02, 0x80, 0x01, // 187 - 0x00, 0x00, 0x10, 0x02, 0x78, 0x01, 0xC0, 0x00, 0x20, 0x01, 0x90, 0x01, 0xC8, 0x03, 0x00, 0x01, // 188 - 0x00, 0x00, 0x10, 0x02, 0x78, 0x01, 0x80, 0x00, 0x60, 0x00, 0x50, 0x02, 0x48, 0x03, 0xC0, 0x02, // 189 - 0x48, 0x00, 0x58, 0x00, 0x68, 0x03, 0x80, 0x00, 0x60, 0x01, 0x90, 0x01, 0xC8, 0x03, 0x00, 0x01, // 190 - 0x00, 0x00, 0x00, 0x06, 0x00, 0x09, 0xA0, 0x09, 0x00, 0x04, // 191 - 0x00, 0x00, 0xF0, 0x03, 0x88, 0x00, 0x88, 0x00, 0x88, 0x00, 0xF0, 0x03, // 192 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x88, 0x01, // 193 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 194 - 0x00, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x18, // 195 - 0x00, 0x00, 0x00, 0x02, 0xFC, 0x03, 0x04, 0x02, 0xFC, 0x03, 0x00, 0x02, // 196 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x08, 0x02, // 197 - 0x00, 0x00, 0xB8, 0x03, 0x40, 0x00, 0xF8, 0x03, 0x40, 0x00, 0xB8, 0x03, // 198 - 0x00, 0x00, 0x08, 0x02, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 199 - 0x00, 0x00, 0xF8, 0x03, 0x80, 0x00, 0x40, 0x00, 0x20, 0x00, 0xF8, 0x03, // 200 - 0x00, 0x00, 0xE0, 0x03, 0x08, 0x01, 0x90, 0x00, 0x48, 0x00, 0xE0, 0x03, // 201 - 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0xA0, 0x00, 0x10, 0x01, 0x08, 0x02, // 202 - 0x00, 0x00, 0x00, 0x02, 0xF0, 0x01, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, // 203 - 0x00, 0x00, 0xF8, 0x03, 0x10, 0x00, 0x60, 0x00, 0x10, 0x00, 0xF8, 0x03, // 204 - 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0xF8, 0x03, // 205 - 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0xF0, 0x01, // 206 - 0x00, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, // 207 - 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0x48, 0x00, 0x30, // 208 - 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0x10, 0x01, // 209 - 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, // 210 - 0x00, 0x00, 0x38, 0x00, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0xF8, 0x01, // 211 - 0x00, 0x00, 0x70, 0x00, 0x88, 0x00, 0xF8, 0x03, 0x88, 0x00, 0x70, // 212 - 0x00, 0x00, 0x18, 0x03, 0xA0, 0x00, 0x40, 0x00, 0xA0, 0x00, 0x18, 0x03, // 213 - 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x02, // 214 - 0x00, 0x00, 0x38, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0xF8, 0x03, // 215 - 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, // 216 - 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x06, // 217 - 0x00, 0x00, 0x08, 0x00, 0xF8, 0x03, 0x40, 0x02, 0x40, 0x02, 0x80, 0x01, // 218 - 0x00, 0x00, 0xF8, 0x03, 0x40, 0x02, 0x40, 0x02, 0x80, 0x01, 0xF8, 0x03, // 219 - 0x00, 0x00, 0xF8, 0x03, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x80, 0x01, // 220 - 0x00, 0x00, 0x10, 0x01, 0x08, 0x02, 0x48, 0x02, 0x48, 0x02, 0xF0, 0x01, // 221 - 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0xF0, 0x01, 0x08, 0x02, 0xF0, 0x01, // 222 - 0x00, 0x00, 0x30, 0x02, 0x48, 0x01, 0xC8, 0x00, 0x48, 0x00, 0xF8, 0x03, // 223 - 0x00, 0x00, 0x00, 0x01, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xC0, 0x03, // 224 - 0x00, 0x00, 0xE0, 0x01, 0x50, 0x02, 0x50, 0x02, 0x48, 0x02, 0x88, 0x01, // 225 - 0x00, 0x00, 0xE0, 0x03, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0x40, 0x01, // 226 - 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x60, // 227 - 0x00, 0x00, 0x00, 0x02, 0xC0, 0x03, 0x20, 0x02, 0xE0, 0x03, 0x00, 0x02, // 228 - 0x00, 0x00, 0xC0, 0x01, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xC0, // 229 - 0x00, 0x00, 0x60, 0x03, 0x80, 0x00, 0xE0, 0x03, 0x80, 0x00, 0x60, 0x03, // 230 - 0x00, 0x00, 0x20, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0x40, 0x01, // 231 - 0x00, 0x00, 0xE0, 0x03, 0x00, 0x01, 0x80, 0x00, 0x40, 0x00, 0xE0, 0x03, // 232 - 0x00, 0x00, 0xE0, 0x03, 0x00, 0x01, 0x98, 0x00, 0x40, 0x00, 0xE0, 0x03, // 233 - 0x00, 0x00, 0xE0, 0x03, 0x80, 0x00, 0x80, 0x00, 0x40, 0x01, 0x20, 0x02, // 234 - 0x00, 0x00, 0x00, 0x02, 0xC0, 0x01, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, // 235 - 0x00, 0x00, 0xE0, 0x03, 0x40, 0x00, 0x80, 0x00, 0x40, 0x00, 0xE0, 0x03, // 236 - 0x00, 0x00, 0xE0, 0x03, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0xE0, 0x03, // 237 - 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 238 - 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, // 239 - 0x00, 0x00, 0xE0, 0x03, 0xA0, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0x40, // 240 - 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0x20, 0x02, 0x40, 0x02, // 241 - 0x00, 0x00, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, // 242 - 0x00, 0x00, 0x60, 0x00, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0xE0, 0x01, // 243 - 0x00, 0x00, 0xC0, 0x00, 0x20, 0x01, 0xE0, 0x03, 0x20, 0x01, 0xC0, // 244 - 0x00, 0x00, 0x20, 0x02, 0x40, 0x01, 0x80, 0x00, 0x40, 0x01, 0x20, 0x02, // 245 - 0x00, 0x00, 0xE0, 0x03, 0x00, 0x02, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x02, // 246 - 0x00, 0x00, 0x60, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0xE0, 0x03, // 247 - 0x00, 0x00, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, // 248 - 0x00, 0x00, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x06, // 249 - 0x00, 0x00, 0x20, 0x00, 0xE0, 0x03, 0x80, 0x02, 0x80, 0x02, 0x00, 0x01, // 250 - 0x00, 0x00, 0xE0, 0x03, 0x80, 0x02, 0x80, 0x02, 0x00, 0x01, 0xE0, 0x03, // 251 - 0x00, 0x00, 0xE0, 0x03, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x00, 0x01, // 252 - 0x00, 0x00, 0x40, 0x01, 0x20, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xC0, 0x01, // 253 - 0x00, 0x00, 0xE0, 0x03, 0x80, 0x00, 0xC0, 0x01, 0x20, 0x02, 0xC0, 0x01, // 254 - 0x00, 0x00, 0x40, 0x02, 0xA0, 0x01, 0xA0, 0x00, 0xA0, 0x00, 0xE0, 0x03, // 255 + 0x0A, // Width: 10 + 0x0D, // Height: 13 + 0x20, // First char: 32 + 0xE0, // Number of chars: 224 + + // Jump Table: + 0xFF, 0xFF, 0x00, 0x0A, // 32 + 0x00, 0x00, 0x04, 0x03, // 33 + 0x00, 0x04, 0x05, 0x04, // 34 + 0x00, 0x09, 0x09, 0x06, // 35 + 0x00, 0x12, 0x0A, 0x06, // 36 + 0x00, 0x1C, 0x10, 0x09, // 37 + 0x00, 0x2C, 0x0E, 0x08, // 38 + 0x00, 0x3A, 0x01, 0x02, // 39 + 0x00, 0x3B, 0x06, 0x04, // 40 + 0x00, 0x41, 0x06, 0x04, // 41 + 0x00, 0x47, 0x05, 0x04, // 42 + 0x00, 0x4C, 0x09, 0x06, // 43 + 0x00, 0x55, 0x04, 0x03, // 44 + 0x00, 0x59, 0x03, 0x03, // 45 + 0x00, 0x5C, 0x04, 0x03, // 46 + 0x00, 0x60, 0x05, 0x04, // 47 + 0x00, 0x65, 0x0A, 0x06, // 48 + 0x00, 0x6F, 0x08, 0x05, // 49 + 0x00, 0x77, 0x0A, 0x06, // 50 + 0x00, 0x81, 0x0A, 0x06, // 51 + 0x00, 0x8B, 0x0B, 0x07, // 52 + 0x00, 0x96, 0x0A, 0x06, // 53 + 0x00, 0xA0, 0x0A, 0x06, // 54 + 0x00, 0xAA, 0x09, 0x06, // 55 + 0x00, 0xB3, 0x0A, 0x06, // 56 + 0x00, 0xBD, 0x0A, 0x06, // 57 + 0x00, 0xC7, 0x04, 0x03, // 58 + 0x00, 0xCB, 0x04, 0x03, // 59 + 0x00, 0xCF, 0x0A, 0x06, // 60 + 0x00, 0xD9, 0x09, 0x06, // 61 + 0x00, 0xE2, 0x09, 0x06, // 62 + 0x00, 0xEB, 0x0B, 0x07, // 63 + 0x00, 0xF6, 0x14, 0x0B, // 64 + 0x01, 0x0A, 0x0E, 0x08, // 65 + 0x01, 0x18, 0x0C, 0x07, // 66 + 0x01, 0x24, 0x0C, 0x07, // 67 + 0x01, 0x30, 0x0B, 0x07, // 68 + 0x01, 0x3B, 0x0C, 0x07, // 69 + 0x01, 0x47, 0x09, 0x06, // 70 + 0x01, 0x50, 0x0D, 0x08, // 71 + 0x01, 0x5D, 0x0C, 0x07, // 72 + 0x01, 0x69, 0x04, 0x03, // 73 + 0x01, 0x6D, 0x08, 0x05, // 74 + 0x01, 0x75, 0x0E, 0x08, // 75 + 0x01, 0x83, 0x0C, 0x07, // 76 + 0x01, 0x8F, 0x10, 0x09, // 77 + 0x01, 0x9F, 0x0C, 0x07, // 78 + 0x01, 0xAB, 0x0E, 0x08, // 79 + 0x01, 0xB9, 0x0B, 0x07, // 80 + 0x01, 0xC4, 0x0E, 0x08, // 81 + 0x01, 0xD2, 0x0C, 0x07, // 82 + 0x01, 0xDE, 0x0C, 0x07, // 83 + 0x01, 0xEA, 0x0B, 0x07, // 84 + 0x01, 0xF5, 0x0C, 0x07, // 85 + 0x02, 0x01, 0x0D, 0x08, // 86 + 0x02, 0x0E, 0x11, 0x0A, // 87 + 0x02, 0x1F, 0x0E, 0x08, // 88 + 0x02, 0x2D, 0x0D, 0x08, // 89 + 0x02, 0x3A, 0x0C, 0x07, // 90 + 0x02, 0x46, 0x06, 0x04, // 91 + 0x02, 0x4C, 0x06, 0x04, // 92 + 0x02, 0x52, 0x04, 0x03, // 93 + 0x02, 0x56, 0x09, 0x06, // 94 + 0x02, 0x5F, 0x0C, 0x07, // 95 + 0x02, 0x6B, 0x03, 0x03, // 96 + 0x02, 0x6E, 0x0A, 0x06, // 97 + 0x02, 0x78, 0x0A, 0x06, // 98 + 0x02, 0x82, 0x0A, 0x06, // 99 + 0x02, 0x8C, 0x0A, 0x06, // 100 + 0x02, 0x96, 0x0A, 0x06, // 101 + 0x02, 0xA0, 0x05, 0x04, // 102 + 0x02, 0xA5, 0x0A, 0x06, // 103 + 0x02, 0xAF, 0x0A, 0x06, // 104 + 0x02, 0xB9, 0x04, 0x03, // 105 + 0x02, 0xBD, 0x04, 0x03, // 106 + 0x02, 0xC1, 0x08, 0x05, // 107 + 0x02, 0xC9, 0x04, 0x03, // 108 + 0x02, 0xCD, 0x10, 0x09, // 109 + 0x02, 0xDD, 0x0A, 0x06, // 110 + 0x02, 0xE7, 0x0A, 0x06, // 111 + 0x02, 0xF1, 0x0A, 0x06, // 112 + 0x02, 0xFB, 0x0A, 0x06, // 113 + 0x03, 0x05, 0x05, 0x04, // 114 + 0x03, 0x0A, 0x08, 0x05, // 115 + 0x03, 0x12, 0x06, 0x04, // 116 + 0x03, 0x18, 0x0A, 0x06, // 117 + 0x03, 0x22, 0x09, 0x06, // 118 + 0x03, 0x2B, 0x0E, 0x08, // 119 + 0x03, 0x39, 0x0A, 0x06, // 120 + 0x03, 0x43, 0x09, 0x06, // 121 + 0x03, 0x4C, 0x0A, 0x06, // 122 + 0x03, 0x56, 0x06, 0x04, // 123 + 0x03, 0x5C, 0x04, 0x03, // 124 + 0x03, 0x60, 0x05, 0x04, // 125 + 0x03, 0x65, 0x09, 0x06, // 126 + 0xFF, 0xFF, 0x00, 0x0A, // 127 + 0xFF, 0xFF, 0x00, 0x0A, // 128 + 0xFF, 0xFF, 0x00, 0x0A, // 129 + 0xFF, 0xFF, 0x00, 0x0A, // 130 + 0xFF, 0xFF, 0x00, 0x0A, // 131 + 0xFF, 0xFF, 0x00, 0x0A, // 132 + 0xFF, 0xFF, 0x00, 0x0A, // 133 + 0xFF, 0xFF, 0x00, 0x0A, // 134 + 0xFF, 0xFF, 0x00, 0x0A, // 135 + 0xFF, 0xFF, 0x00, 0x0A, // 136 + 0xFF, 0xFF, 0x00, 0x0A, // 137 + 0xFF, 0xFF, 0x00, 0x0A, // 138 + 0xFF, 0xFF, 0x00, 0x0A, // 139 + 0xFF, 0xFF, 0x00, 0x0A, // 140 + 0xFF, 0xFF, 0x00, 0x0A, // 141 + 0xFF, 0xFF, 0x00, 0x0A, // 142 + 0xFF, 0xFF, 0x00, 0x0A, // 143 + 0xFF, 0xFF, 0x00, 0x0A, // 144 + 0xFF, 0xFF, 0x00, 0x0A, // 145 + 0xFF, 0xFF, 0x00, 0x0A, // 146 + 0xFF, 0xFF, 0x00, 0x0A, // 147 + 0xFF, 0xFF, 0x00, 0x0A, // 148 + 0xFF, 0xFF, 0x00, 0x0A, // 149 + 0xFF, 0xFF, 0x00, 0x0A, // 150 + 0xFF, 0xFF, 0x00, 0x0A, // 151 + 0xFF, 0xFF, 0x00, 0x0A, // 152 + 0xFF, 0xFF, 0x00, 0x0A, // 153 + 0xFF, 0xFF, 0x00, 0x0A, // 154 + 0xFF, 0xFF, 0x00, 0x0A, // 155 + 0xFF, 0xFF, 0x00, 0x0A, // 156 + 0xFF, 0xFF, 0x00, 0x0A, // 157 + 0xFF, 0xFF, 0x00, 0x0A, // 158 + 0xFF, 0xFF, 0x00, 0x0A, // 159 + 0xFF, 0xFF, 0x00, 0x0A, // 160 + 0x03, 0x6E, 0x04, 0x03, // 161 + 0x03, 0x72, 0x0A, 0x06, // 162 + 0x03, 0x7C, 0x0C, 0x07, // 163 + 0x03, 0x88, 0x0A, 0x06, // 164 + 0x03, 0x92, 0x0A, 0x06, // 165 + 0x03, 0x9C, 0x04, 0x03, // 166 + 0x03, 0xA0, 0x0A, 0x06, // 167 + 0x03, 0xAA, 0x0C, 0x07, // 168 + 0x03, 0xB6, 0x0D, 0x08, // 169 + 0x03, 0xC3, 0x07, 0x05, // 170 + 0x03, 0xCA, 0x0A, 0x06, // 171 + 0x03, 0xD4, 0x09, 0x06, // 172 + 0x03, 0xDD, 0x03, 0x03, // 173 + 0x03, 0xE0, 0x0D, 0x08, // 174 + 0x03, 0xED, 0x0B, 0x07, // 175 + 0x03, 0xF8, 0x07, 0x05, // 176 + 0x03, 0xFF, 0x0A, 0x06, // 177 + 0x04, 0x09, 0x05, 0x04, // 178 + 0x04, 0x0E, 0x05, 0x04, // 179 + 0x04, 0x13, 0x05, 0x04, // 180 + 0x04, 0x18, 0x0A, 0x06, // 181 + 0x04, 0x22, 0x09, 0x06, // 182 + 0x04, 0x2B, 0x03, 0x03, // 183 + 0x04, 0x2E, 0x0B, 0x07, // 184 + 0x04, 0x39, 0x0B, 0x07, // 185 + 0x04, 0x44, 0x07, 0x05, // 186 + 0x04, 0x4B, 0x0A, 0x06, // 187 + 0x04, 0x55, 0x10, 0x09, // 188 + 0x04, 0x65, 0x10, 0x09, // 189 + 0x04, 0x75, 0x10, 0x09, // 190 + 0x04, 0x85, 0x0A, 0x06, // 191 + 0x04, 0x8F, 0x0C, 0x07, // 192 + 0x04, 0x9B, 0x0C, 0x07, // 193 + 0x04, 0xA7, 0x0C, 0x07, // 194 + 0x04, 0xB3, 0x0B, 0x07, // 195 + 0x04, 0xBE, 0x0C, 0x07, // 196 + 0x04, 0xCA, 0x0C, 0x07, // 197 + 0x04, 0xD6, 0x0C, 0x07, // 198 + 0x04, 0xE2, 0x0C, 0x07, // 199 + 0x04, 0xEE, 0x0C, 0x07, // 200 + 0x04, 0xFA, 0x0C, 0x07, // 201 + 0x05, 0x06, 0x0C, 0x07, // 202 + 0x05, 0x12, 0x0C, 0x07, // 203 + 0x05, 0x1E, 0x0C, 0x07, // 204 + 0x05, 0x2A, 0x0C, 0x07, // 205 + 0x05, 0x36, 0x0C, 0x07, // 206 + 0x05, 0x42, 0x0C, 0x07, // 207 + 0x05, 0x4E, 0x0B, 0x07, // 208 + 0x05, 0x59, 0x0C, 0x07, // 209 + 0x05, 0x65, 0x0B, 0x07, // 210 + 0x05, 0x70, 0x0C, 0x07, // 211 + 0x05, 0x7C, 0x0B, 0x07, // 212 + 0x05, 0x87, 0x0C, 0x07, // 213 + 0x05, 0x93, 0x0C, 0x07, // 214 + 0x05, 0x9F, 0x0C, 0x07, // 215 + 0x05, 0xAB, 0x0C, 0x07, // 216 + 0x05, 0xB7, 0x0E, 0x08, // 217 + 0x05, 0xC5, 0x0C, 0x07, // 218 + 0x05, 0xD1, 0x0C, 0x07, // 219 + 0x05, 0xDD, 0x0C, 0x07, // 220 + 0x05, 0xE9, 0x0C, 0x07, // 221 + 0x05, 0xF5, 0x0C, 0x07, // 222 + 0x06, 0x01, 0x0C, 0x07, // 223 + 0x06, 0x0D, 0x0C, 0x07, // 224 + 0x06, 0x19, 0x0C, 0x07, // 225 + 0x06, 0x25, 0x0C, 0x07, // 226 + 0x06, 0x31, 0x0B, 0x07, // 227 + 0x06, 0x3C, 0x0C, 0x07, // 228 + 0x06, 0x48, 0x0B, 0x07, // 229 + 0x06, 0x53, 0x0C, 0x07, // 230 + 0x06, 0x5F, 0x0C, 0x07, // 231 + 0x06, 0x6B, 0x0C, 0x07, // 232 + 0x06, 0x77, 0x0C, 0x07, // 233 + 0x06, 0x83, 0x0C, 0x07, // 234 + 0x06, 0x8F, 0x0C, 0x07, // 235 + 0x06, 0x9B, 0x0C, 0x07, // 236 + 0x06, 0xA7, 0x0C, 0x07, // 237 + 0x06, 0xB3, 0x0C, 0x07, // 238 + 0x06, 0xBF, 0x0C, 0x07, // 239 + 0x06, 0xCB, 0x0B, 0x07, // 240 + 0x06, 0xD6, 0x0C, 0x07, // 241 + 0x06, 0xE2, 0x0B, 0x07, // 242 + 0x06, 0xED, 0x0C, 0x07, // 243 + 0x06, 0xF9, 0x0B, 0x07, // 244 + 0x07, 0x04, 0x0C, 0x07, // 245 + 0x07, 0x10, 0x0C, 0x07, // 246 + 0x07, 0x1C, 0x0C, 0x07, // 247 + 0x07, 0x28, 0x0C, 0x07, // 248 + 0x07, 0x34, 0x0E, 0x08, // 249 + 0x07, 0x42, 0x0C, 0x07, // 250 + 0x07, 0x4E, 0x0C, 0x07, // 251 + 0x07, 0x5A, 0x0C, 0x07, // 252 + 0x07, 0x66, 0x0C, 0x07, // 253 + 0x07, 0x72, 0x0C, 0x07, // 254 + 0x07, 0x7E, 0x0C, 0x07, // 255 + + // Font Data: + 0x00, 0x00, 0xF8, 0x02, // 33 + 0x38, 0x00, 0x00, 0x00, 0x38, // 34 + 0xA0, 0x03, 0xE0, 0x00, 0xB8, 0x03, 0xE0, 0x00, 0xB8, // 35 + 0x30, 0x01, 0x28, 0x02, 0xF8, 0x07, 0x48, 0x02, 0x90, 0x01, // 36 + 0x00, 0x00, 0x30, 0x00, 0x48, 0x00, 0x30, 0x03, 0xC0, 0x00, 0xB0, 0x01, 0x48, 0x02, 0x80, 0x01, // 37 + 0x80, 0x01, 0x50, 0x02, 0x68, 0x02, 0xA8, 0x02, 0x18, 0x01, 0x80, 0x03, 0x80, 0x02, // 38 + 0x38, // 39 + 0xE0, 0x03, 0x10, 0x04, 0x08, 0x08, // 40 + 0x08, 0x08, 0x10, 0x04, 0xE0, 0x03, // 41 + 0x28, 0x00, 0x18, 0x00, 0x28, // 42 + 0x40, 0x00, 0x40, 0x00, 0xF0, 0x01, 0x40, 0x00, 0x40, // 43 + 0x00, 0x00, 0x00, 0x06, // 44 + 0x80, 0x00, 0x80, // 45 + 0x00, 0x00, 0x00, 0x02, // 46 + 0x00, 0x03, 0xE0, 0x00, 0x18, // 47 + 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0xF0, 0x01, // 48 + 0x00, 0x00, 0x20, 0x00, 0x10, 0x00, 0xF8, 0x03, // 49 + 0x10, 0x02, 0x08, 0x03, 0x88, 0x02, 0x48, 0x02, 0x30, 0x02, // 50 + 0x10, 0x01, 0x08, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 51 + 0xC0, 0x00, 0xA0, 0x00, 0x90, 0x00, 0x88, 0x00, 0xF8, 0x03, 0x80, // 52 + 0x60, 0x01, 0x38, 0x02, 0x28, 0x02, 0x28, 0x02, 0xC8, 0x01, // 53 + 0xF0, 0x01, 0x28, 0x02, 0x28, 0x02, 0x28, 0x02, 0xD0, 0x01, // 54 + 0x08, 0x00, 0x08, 0x03, 0xC8, 0x00, 0x38, 0x00, 0x08, // 55 + 0xB0, 0x01, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 56 + 0x70, 0x01, 0x88, 0x02, 0x88, 0x02, 0x88, 0x02, 0xF0, 0x01, // 57 + 0x00, 0x00, 0x20, 0x02, // 58 + 0x00, 0x00, 0x20, 0x06, // 59 + 0x00, 0x00, 0x40, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0x10, 0x01, // 60 + 0xA0, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0xA0, // 61 + 0x00, 0x00, 0x10, 0x01, 0xA0, 0x00, 0xA0, 0x00, 0x40, // 62 + 0x10, 0x00, 0x08, 0x00, 0x08, 0x00, 0xC8, 0x02, 0x48, 0x00, 0x30, // 63 + 0x00, 0x00, 0xC0, 0x03, 0x30, 0x04, 0xD0, 0x09, 0x28, 0x0A, 0x28, 0x0A, 0xC8, 0x0B, 0x68, 0x0A, 0x10, 0x05, 0xE0, 0x04, // 64 + 0x00, 0x02, 0xC0, 0x01, 0xB0, 0x00, 0x88, 0x00, 0xB0, 0x00, 0xC0, 0x01, 0x00, 0x02, // 65 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xF0, 0x01, // 66 + 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0x10, 0x01, // 67 + 0x00, 0x00, 0xF8, 0x03, 0x08, 0x02, 0x08, 0x02, 0x10, 0x01, 0xE0, // 68 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, // 69 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0x08, // 70 + 0x00, 0x00, 0xE0, 0x00, 0x10, 0x01, 0x08, 0x02, 0x48, 0x02, 0x50, 0x01, 0xC0, // 71 + 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0xF8, 0x03, // 72 + 0x00, 0x00, 0xF8, 0x03, // 73 + 0x00, 0x03, 0x00, 0x02, 0x00, 0x02, 0xF8, 0x01, // 74 + 0x00, 0x00, 0xF8, 0x03, 0x80, 0x00, 0x60, 0x00, 0x90, 0x00, 0x08, 0x01, 0x00, 0x02, // 75 + 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, // 76 + 0x00, 0x00, 0xF8, 0x03, 0x30, 0x00, 0xC0, 0x01, 0x00, 0x02, 0xC0, 0x01, 0x30, 0x00, 0xF8, 0x03, // 77 + 0x00, 0x00, 0xF8, 0x03, 0x30, 0x00, 0x40, 0x00, 0x80, 0x01, 0xF8, 0x03, // 78 + 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0xF0, 0x01, // 79 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0x48, 0x00, 0x30, // 80 + 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x03, 0x08, 0x03, 0xF0, 0x02, // 81 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0xC8, 0x00, 0x30, 0x03, // 82 + 0x00, 0x00, 0x30, 0x01, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x90, 0x01, // 83 + 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, // 84 + 0x00, 0x00, 0xF8, 0x01, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0xF8, 0x01, // 85 + 0x08, 0x00, 0x70, 0x00, 0x80, 0x01, 0x00, 0x02, 0x80, 0x01, 0x70, 0x00, 0x08, // 86 + 0x18, 0x00, 0xE0, 0x01, 0x00, 0x02, 0xF0, 0x01, 0x08, 0x00, 0xF0, 0x01, 0x00, 0x02, 0xE0, 0x01, 0x18, // 87 + 0x00, 0x02, 0x08, 0x01, 0x90, 0x00, 0x60, 0x00, 0x90, 0x00, 0x08, 0x01, 0x00, 0x02, // 88 + 0x08, 0x00, 0x10, 0x00, 0x20, 0x00, 0xC0, 0x03, 0x20, 0x00, 0x10, 0x00, 0x08, // 89 + 0x08, 0x03, 0x88, 0x02, 0xC8, 0x02, 0x68, 0x02, 0x38, 0x02, 0x18, 0x02, // 90 + 0x00, 0x00, 0xF8, 0x0F, 0x08, 0x08, // 91 + 0x18, 0x00, 0xE0, 0x00, 0x00, 0x03, // 92 + 0x08, 0x08, 0xF8, 0x0F, // 93 + 0x40, 0x00, 0x30, 0x00, 0x08, 0x00, 0x30, 0x00, 0x40, // 94 + 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, // 95 + 0x08, 0x00, 0x10, // 96 + 0x00, 0x00, 0x00, 0x03, 0xA0, 0x02, 0xA0, 0x02, 0xE0, 0x03, // 97 + 0x00, 0x00, 0xF8, 0x03, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 98 + 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0x40, 0x01, // 99 + 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0xF8, 0x03, // 100 + 0x00, 0x00, 0xC0, 0x01, 0xA0, 0x02, 0xA0, 0x02, 0xC0, 0x02, // 101 + 0x20, 0x00, 0xF0, 0x03, 0x28, // 102 + 0x00, 0x00, 0xC0, 0x05, 0x20, 0x0A, 0x20, 0x0A, 0xE0, 0x07, // 103 + 0x00, 0x00, 0xF8, 0x03, 0x20, 0x00, 0x20, 0x00, 0xC0, 0x03, // 104 + 0x00, 0x00, 0xE8, 0x03, // 105 + 0x00, 0x08, 0xE8, 0x07, // 106 + 0xF8, 0x03, 0x80, 0x00, 0xC0, 0x01, 0x20, 0x02, // 107 + 0x00, 0x00, 0xF8, 0x03, // 108 + 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0xC0, 0x03, // 109 + 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0xC0, 0x03, // 110 + 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 111 + 0x00, 0x00, 0xE0, 0x0F, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 112 + 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0xE0, 0x0F, // 113 + 0x00, 0x00, 0xE0, 0x03, 0x20, // 114 + 0x40, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0x20, 0x01, // 115 + 0x20, 0x00, 0xF8, 0x03, 0x20, 0x02, // 116 + 0x00, 0x00, 0xE0, 0x01, 0x00, 0x02, 0x00, 0x02, 0xE0, 0x03, // 117 + 0x20, 0x00, 0xC0, 0x01, 0x00, 0x02, 0xC0, 0x01, 0x20, // 118 + 0xE0, 0x01, 0x00, 0x02, 0xC0, 0x01, 0x20, 0x00, 0xC0, 0x01, 0x00, 0x02, 0xE0, 0x01, // 119 + 0x20, 0x02, 0x40, 0x01, 0x80, 0x00, 0x40, 0x01, 0x20, 0x02, // 120 + 0x20, 0x00, 0xC0, 0x09, 0x00, 0x06, 0xC0, 0x01, 0x20, // 121 + 0x20, 0x02, 0x20, 0x03, 0xA0, 0x02, 0x60, 0x02, 0x20, 0x02, // 122 + 0x80, 0x00, 0x78, 0x0F, 0x08, 0x08, // 123 + 0x00, 0x00, 0xF8, 0x0F, // 124 + 0x08, 0x08, 0x78, 0x0F, 0x80, // 125 + 0xC0, 0x00, 0x40, 0x00, 0xC0, 0x00, 0x80, 0x00, 0xC0, // 126 + 0x00, 0x00, 0xA0, 0x0F, // 161 + 0x00, 0x00, 0xC0, 0x01, 0xA0, 0x0F, 0x78, 0x02, 0x40, 0x01, // 162 + 0x40, 0x02, 0x70, 0x03, 0xC8, 0x02, 0x48, 0x02, 0x08, 0x02, 0x10, 0x02, // 163 + 0x00, 0x00, 0xE0, 0x01, 0x20, 0x01, 0x20, 0x01, 0xE0, 0x01, // 164 + 0x48, 0x01, 0x70, 0x01, 0xC0, 0x03, 0x70, 0x01, 0x48, 0x01, // 165 + 0x00, 0x00, 0x38, 0x0F, // 166 + 0xD0, 0x04, 0x28, 0x09, 0x48, 0x09, 0x48, 0x0A, 0x90, 0x05, // 167 + 0x00, 0x00, 0xE0, 0x03, 0xA8, 0x02, 0xA0, 0x02, 0xA8, 0x02, 0x20, 0x02, // 168 + 0xE0, 0x00, 0x10, 0x01, 0x48, 0x02, 0xA8, 0x02, 0xA8, 0x02, 0x10, 0x01, 0xE0, // 169 + 0x68, 0x00, 0x68, 0x00, 0x68, 0x00, 0x78, // 170 + 0x00, 0x00, 0x80, 0x01, 0x40, 0x02, 0x80, 0x01, 0x40, 0x02, // 171 + 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0xE0, // 172 + 0x80, 0x00, 0x80, // 173 + 0xE0, 0x00, 0x10, 0x01, 0xE8, 0x02, 0x68, 0x02, 0xC8, 0x02, 0x10, 0x01, 0xE0, // 174 + 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, // 175 + 0x00, 0x00, 0x38, 0x00, 0x28, 0x00, 0x38, // 176 + 0x40, 0x02, 0x40, 0x02, 0xF0, 0x03, 0x40, 0x02, 0x40, 0x02, // 177 + 0x48, 0x00, 0x68, 0x00, 0x58, // 178 + 0x48, 0x00, 0x58, 0x00, 0x68, // 179 + 0x00, 0x00, 0x10, 0x00, 0x08, // 180 + 0x00, 0x00, 0xE0, 0x0F, 0x00, 0x02, 0x00, 0x02, 0xE0, 0x03, // 181 + 0x70, 0x00, 0xF8, 0x0F, 0x08, 0x00, 0xF8, 0x0F, 0x08, // 182 + 0x00, 0x00, 0x40, // 183 + 0x00, 0x00, 0xC0, 0x01, 0xA8, 0x02, 0xA0, 0x02, 0xA8, 0x02, 0xC0, // 184 + 0x00, 0x00, 0xF0, 0x03, 0x40, 0x00, 0x80, 0x00, 0xF8, 0x03, 0x08, // 185 + 0x30, 0x00, 0x48, 0x00, 0x48, 0x00, 0x30, // 186 + 0x00, 0x00, 0x40, 0x02, 0x80, 0x01, 0x40, 0x02, 0x80, 0x01, // 187 + 0x00, 0x00, 0x10, 0x02, 0x78, 0x01, 0xC0, 0x00, 0x20, 0x01, 0x90, 0x01, 0xC8, 0x03, 0x00, 0x01, // 188 + 0x00, 0x00, 0x10, 0x02, 0x78, 0x01, 0x80, 0x00, 0x60, 0x00, 0x50, 0x02, 0x48, 0x03, 0xC0, 0x02, // 189 + 0x48, 0x00, 0x58, 0x00, 0x68, 0x03, 0x80, 0x00, 0x60, 0x01, 0x90, 0x01, 0xC8, 0x03, 0x00, 0x01, // 190 + 0x00, 0x00, 0x00, 0x06, 0x00, 0x09, 0xA0, 0x09, 0x00, 0x04, // 191 + 0x00, 0x00, 0xF0, 0x03, 0x88, 0x00, 0x88, 0x00, 0x88, 0x00, 0xF0, 0x03, // 192 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x88, 0x01, // 193 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 194 + 0x00, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x18, // 195 + 0x00, 0x00, 0x00, 0x02, 0xFC, 0x03, 0x04, 0x02, 0xFC, 0x03, 0x00, 0x02, // 196 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0x08, 0x02, // 197 + 0x00, 0x00, 0xB8, 0x03, 0x40, 0x00, 0xF8, 0x03, 0x40, 0x00, 0xB8, 0x03, // 198 + 0x00, 0x00, 0x08, 0x02, 0x48, 0x02, 0x48, 0x02, 0x48, 0x02, 0xB0, 0x01, // 199 + 0x00, 0x00, 0xF8, 0x03, 0x80, 0x00, 0x40, 0x00, 0x20, 0x00, 0xF8, 0x03, // 200 + 0x00, 0x00, 0xE0, 0x03, 0x08, 0x01, 0x90, 0x00, 0x48, 0x00, 0xE0, 0x03, // 201 + 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0xA0, 0x00, 0x10, 0x01, 0x08, 0x02, // 202 + 0x00, 0x00, 0x00, 0x02, 0xF0, 0x01, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, // 203 + 0x00, 0x00, 0xF8, 0x03, 0x10, 0x00, 0x60, 0x00, 0x10, 0x00, 0xF8, 0x03, // 204 + 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0xF8, 0x03, // 205 + 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0xF0, 0x01, // 206 + 0x00, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, // 207 + 0x00, 0x00, 0xF8, 0x03, 0x48, 0x00, 0x48, 0x00, 0x48, 0x00, 0x30, // 208 + 0x00, 0x00, 0xF0, 0x01, 0x08, 0x02, 0x08, 0x02, 0x08, 0x02, 0x10, 0x01, // 209 + 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0xF8, 0x03, 0x08, 0x00, 0x08, // 210 + 0x00, 0x00, 0x38, 0x00, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0xF8, 0x01, // 211 + 0x00, 0x00, 0x70, 0x00, 0x88, 0x00, 0xF8, 0x03, 0x88, 0x00, 0x70, // 212 + 0x00, 0x00, 0x18, 0x03, 0xA0, 0x00, 0x40, 0x00, 0xA0, 0x00, 0x18, 0x03, // 213 + 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x02, // 214 + 0x00, 0x00, 0x38, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0xF8, 0x03, // 215 + 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, // 216 + 0x00, 0x00, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x02, 0xF8, 0x03, 0x00, 0x06, // 217 + 0x00, 0x00, 0x08, 0x00, 0xF8, 0x03, 0x40, 0x02, 0x40, 0x02, 0x80, 0x01, // 218 + 0x00, 0x00, 0xF8, 0x03, 0x40, 0x02, 0x40, 0x02, 0x80, 0x01, 0xF8, 0x03, // 219 + 0x00, 0x00, 0xF8, 0x03, 0x40, 0x02, 0x40, 0x02, 0x40, 0x02, 0x80, 0x01, // 220 + 0x00, 0x00, 0x10, 0x01, 0x08, 0x02, 0x48, 0x02, 0x48, 0x02, 0xF0, 0x01, // 221 + 0x00, 0x00, 0xF8, 0x03, 0x40, 0x00, 0xF0, 0x01, 0x08, 0x02, 0xF0, 0x01, // 222 + 0x00, 0x00, 0x30, 0x02, 0x48, 0x01, 0xC8, 0x00, 0x48, 0x00, 0xF8, 0x03, // 223 + 0x00, 0x00, 0x00, 0x01, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xC0, 0x03, // 224 + 0x00, 0x00, 0xE0, 0x01, 0x50, 0x02, 0x50, 0x02, 0x48, 0x02, 0x88, 0x01, // 225 + 0x00, 0x00, 0xE0, 0x03, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0x40, 0x01, // 226 + 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x60, // 227 + 0x00, 0x00, 0x00, 0x02, 0xC0, 0x03, 0x20, 0x02, 0xE0, 0x03, 0x00, 0x02, // 228 + 0x00, 0x00, 0xC0, 0x01, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xC0, // 229 + 0x00, 0x00, 0x60, 0x03, 0x80, 0x00, 0xE0, 0x03, 0x80, 0x00, 0x60, 0x03, // 230 + 0x00, 0x00, 0x20, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0x40, 0x01, // 231 + 0x00, 0x00, 0xE0, 0x03, 0x00, 0x01, 0x80, 0x00, 0x40, 0x00, 0xE0, 0x03, // 232 + 0x00, 0x00, 0xE0, 0x03, 0x00, 0x01, 0x98, 0x00, 0x40, 0x00, 0xE0, 0x03, // 233 + 0x00, 0x00, 0xE0, 0x03, 0x80, 0x00, 0x80, 0x00, 0x40, 0x01, 0x20, 0x02, // 234 + 0x00, 0x00, 0x00, 0x02, 0xC0, 0x01, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, // 235 + 0x00, 0x00, 0xE0, 0x03, 0x40, 0x00, 0x80, 0x00, 0x40, 0x00, 0xE0, 0x03, // 236 + 0x00, 0x00, 0xE0, 0x03, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0xE0, 0x03, // 237 + 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0x20, 0x02, 0xC0, 0x01, // 238 + 0x00, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, // 239 + 0x00, 0x00, 0xE0, 0x03, 0xA0, 0x00, 0xA0, 0x00, 0xA0, 0x00, 0x40, // 240 + 0x00, 0x00, 0xC0, 0x01, 0x20, 0x02, 0x20, 0x02, 0x20, 0x02, 0x40, 0x02, // 241 + 0x00, 0x00, 0x20, 0x00, 0x20, 0x00, 0xE0, 0x03, 0x20, 0x00, 0x20, // 242 + 0x00, 0x00, 0x60, 0x00, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0xE0, 0x01, // 243 + 0x00, 0x00, 0xC0, 0x00, 0x20, 0x01, 0xE0, 0x03, 0x20, 0x01, 0xC0, // 244 + 0x00, 0x00, 0x20, 0x02, 0x40, 0x01, 0x80, 0x00, 0x40, 0x01, 0x20, 0x02, // 245 + 0x00, 0x00, 0xE0, 0x03, 0x00, 0x02, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x02, // 246 + 0x00, 0x00, 0x60, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0xE0, 0x03, // 247 + 0x00, 0x00, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, // 248 + 0x00, 0x00, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x02, 0xE0, 0x03, 0x00, 0x06, // 249 + 0x00, 0x00, 0x20, 0x00, 0xE0, 0x03, 0x80, 0x02, 0x80, 0x02, 0x00, 0x01, // 250 + 0x00, 0x00, 0xE0, 0x03, 0x80, 0x02, 0x80, 0x02, 0x00, 0x01, 0xE0, 0x03, // 251 + 0x00, 0x00, 0xE0, 0x03, 0x80, 0x02, 0x80, 0x02, 0x80, 0x02, 0x00, 0x01, // 252 + 0x00, 0x00, 0x40, 0x01, 0x20, 0x02, 0xA0, 0x02, 0xA0, 0x02, 0xC0, 0x01, // 253 + 0x00, 0x00, 0xE0, 0x03, 0x80, 0x00, 0xC0, 0x01, 0x20, 0x02, 0xC0, 0x01, // 254 + 0x00, 0x00, 0x40, 0x02, 0xA0, 0x01, 0xA0, 0x00, 0xA0, 0x00, 0xE0, 0x03, // 255 }; \ No newline at end of file diff --git a/src/graphics/images.h b/src/graphics/images.h index 9bf66a3a3..b1818e32c 100644 --- a/src/graphics/images.h +++ b/src/graphics/images.h @@ -6,24 +6,27 @@ const uint8_t SATELLITE_IMAGE[] PROGMEM = {0x00, 0x08, 0x00, 0x1C, 0x00, 0x0E, 0 0xF8, 0x00, 0xF0, 0x01, 0xE0, 0x03, 0xC8, 0x01, 0x9C, 0x54, 0x0E, 0x52, 0x07, 0x48, 0x02, 0x26, 0x00, 0x10, 0x00, 0x0E}; -const uint8_t imgSatellite[] PROGMEM = { 0x70, 0x71, 0x22, 0xFA, 0xFA, 0x22, 0x71, 0x70 }; -const uint8_t imgUSB[] PROGMEM = { 0x60, 0x60, 0x30, 0x18, 0x18, 0x18, 0x24, 0x42, 0x42, 0x42, 0x42, 0x7E, 0x24, 0x24, 0x24, 0x3C }; -const uint8_t imgPower[] PROGMEM = { 0x40, 0x40, 0x40, 0x58, 0x48, 0x08, 0x08, 0x08, 0x1C, 0x22, 0x22, 0x41, 0x7F, 0x22, 0x22, 0x22 }; -const uint8_t imgUser[] PROGMEM = { 0x3C, 0x42, 0x99, 0xA5, 0xA5, 0x99, 0x42, 0x3C }; -const uint8_t imgPositionEmpty[] PROGMEM = { 0x20, 0x30, 0x28, 0x24, 0x42, 0xFF }; -const uint8_t imgPositionSolid[] PROGMEM = { 0x20, 0x30, 0x38, 0x3C, 0x7E, 0xFF }; +const uint8_t imgSatellite[] PROGMEM = {0x70, 0x71, 0x22, 0xFA, 0xFA, 0x22, 0x71, 0x70}; +const uint8_t imgUSB[] PROGMEM = {0x60, 0x60, 0x30, 0x18, 0x18, 0x18, 0x24, 0x42, 0x42, 0x42, 0x42, 0x7E, 0x24, 0x24, 0x24, 0x3C}; +const uint8_t imgPower[] PROGMEM = {0x40, 0x40, 0x40, 0x58, 0x48, 0x08, 0x08, 0x08, + 0x1C, 0x22, 0x22, 0x41, 0x7F, 0x22, 0x22, 0x22}; +const uint8_t imgUser[] PROGMEM = {0x3C, 0x42, 0x99, 0xA5, 0xA5, 0x99, 0x42, 0x3C}; +const uint8_t imgPositionEmpty[] PROGMEM = {0x20, 0x30, 0x28, 0x24, 0x42, 0xFF}; +const uint8_t imgPositionSolid[] PROGMEM = {0x20, 0x30, 0x38, 0x3C, 0x7E, 0xFF}; #if defined(USE_EINK) || defined(ILI9341_DRIVER) || defined(ST7735_CS) -const uint8_t imgQuestionL1[] PROGMEM = { 0xff, 0x01, 0x01, 0x32, 0x7b, 0x49, 0x49, 0x6f, 0x26, 0x01, 0x01, 0xff }; -const uint8_t imgQuestionL2[] PROGMEM = { 0x0f, 0x08, 0x08, 0x08, 0x06, 0x0f, 0x0f, 0x06, 0x08, 0x08, 0x08, 0x0f }; -const uint8_t imgInfoL1[] PROGMEM = { 0xff, 0x01, 0x01, 0x01, 0x1e, 0x7f, 0x1e, 0x01, 0x01, 0x01, 0x01, 0xff }; -const uint8_t imgInfoL2[] PROGMEM = { 0x0f, 0x08, 0x08, 0x08, 0x06, 0x0f, 0x0f, 0x06, 0x08, 0x08, 0x08, 0x0f }; -const uint8_t imgSFL1[] PROGMEM = { 0xb6, 0x8f, 0x19, 0x11, 0x31, 0xe3, 0xc2, 0x01, 0x01, 0xf9, 0xf9, 0x89, 0x89, 0x89, 0x09, 0xeb}; -const uint8_t imgSFL2[] PROGMEM = { 0x0e, 0x09, 0x09, 0x09, 0x09, 0x09, 0x08, 0x08, 0x00, 0x0f, 0x0f, 0x00, 0x08, 0x08, 0x08, 0x0f}; +const uint8_t imgQuestionL1[] PROGMEM = {0xff, 0x01, 0x01, 0x32, 0x7b, 0x49, 0x49, 0x6f, 0x26, 0x01, 0x01, 0xff}; +const uint8_t imgQuestionL2[] PROGMEM = {0x0f, 0x08, 0x08, 0x08, 0x06, 0x0f, 0x0f, 0x06, 0x08, 0x08, 0x08, 0x0f}; +const uint8_t imgInfoL1[] PROGMEM = {0xff, 0x01, 0x01, 0x01, 0x1e, 0x7f, 0x1e, 0x01, 0x01, 0x01, 0x01, 0xff}; +const uint8_t imgInfoL2[] PROGMEM = {0x0f, 0x08, 0x08, 0x08, 0x06, 0x0f, 0x0f, 0x06, 0x08, 0x08, 0x08, 0x0f}; +const uint8_t imgSFL1[] PROGMEM = {0xb6, 0x8f, 0x19, 0x11, 0x31, 0xe3, 0xc2, 0x01, + 0x01, 0xf9, 0xf9, 0x89, 0x89, 0x89, 0x09, 0xeb}; +const uint8_t imgSFL2[] PROGMEM = {0x0e, 0x09, 0x09, 0x09, 0x09, 0x09, 0x08, 0x08, + 0x00, 0x0f, 0x0f, 0x00, 0x08, 0x08, 0x08, 0x0f}; #else -const uint8_t imgInfo[] PROGMEM = { 0xff, 0x81, 0x00, 0xfb, 0xfb, 0x00, 0x81, 0xff }; -const uint8_t imgQuestion[] PROGMEM = { 0xbf, 0x41, 0xc0, 0x8b, 0xdb, 0x70, 0xa1, 0xdf }; -const uint8_t imgSF[] PROGMEM = { 0xd2, 0xb7, 0xad, 0xbb, 0x92, 0x01, 0xfd, 0xfd, 0x15, 0x85, 0xf5}; +const uint8_t imgInfo[] PROGMEM = {0xff, 0x81, 0x00, 0xfb, 0xfb, 0x00, 0x81, 0xff}; +const uint8_t imgQuestion[] PROGMEM = {0xbf, 0x41, 0xc0, 0x8b, 0xdb, 0x70, 0xa1, 0xdf}; +const uint8_t imgSF[] PROGMEM = {0xd2, 0xb7, 0xad, 0xbb, 0x92, 0x01, 0xfd, 0xfd, 0x15, 0x85, 0xf5}; #endif #include "img/icon.xbm" diff --git a/src/input/InputBroker.cpp b/src/input/InputBroker.cpp index 09e04602d..b06c7400f 100644 --- a/src/input/InputBroker.cpp +++ b/src/input/InputBroker.cpp @@ -3,9 +3,7 @@ InputBroker *inputBroker; -InputBroker::InputBroker() -{ -}; +InputBroker::InputBroker(){}; void InputBroker::registerSource(Observable *source) { @@ -14,7 +12,7 @@ void InputBroker::registerSource(Observable *source) int InputBroker::handleInputEvent(const InputEvent *event) { - powerFSM.trigger(EVENT_INPUT); - this->notifyObservers(event); - return 0; + powerFSM.trigger(EVENT_INPUT); + this->notifyObservers(event); + return 0; } \ No newline at end of file diff --git a/src/input/InputBroker.h b/src/input/InputBroker.h index ab264d192..d73e6657a 100644 --- a/src/input/InputBroker.h +++ b/src/input/InputBroker.h @@ -5,12 +5,11 @@ #define MATRIXKEY 0xFE typedef struct _InputEvent { - const char* source; + const char *source; char inputEvent; char kbchar; } InputEvent; -class InputBroker : - public Observable +class InputBroker : public Observable { CallbackObserver inputEventObserver = CallbackObserver(this, &InputBroker::handleInputEvent); diff --git a/src/input/RotaryEncoderInterruptImpl1.h b/src/input/RotaryEncoderInterruptImpl1.h index aeafeeca7..1bdb3a5a5 100644 --- a/src/input/RotaryEncoderInterruptImpl1.h +++ b/src/input/RotaryEncoderInterruptImpl1.h @@ -8,8 +8,7 @@ * to your device as you wish, but you always need to have separate event * handlers, thus you need to have a RotaryEncoderInterrupt implementation. */ -class RotaryEncoderInterruptImpl1 : - public RotaryEncoderInterruptBase +class RotaryEncoderInterruptImpl1 : public RotaryEncoderInterruptBase { public: RotaryEncoderInterruptImpl1(); diff --git a/src/input/UpDownInterruptBase.cpp b/src/input/UpDownInterruptBase.cpp index 5a0f25158..7c340bab0 100644 --- a/src/input/UpDownInterruptBase.cpp +++ b/src/input/UpDownInterruptBase.cpp @@ -1,16 +1,13 @@ -#include "configuration.h" #include "UpDownInterruptBase.h" +#include "configuration.h" -UpDownInterruptBase::UpDownInterruptBase( - const char *name) +UpDownInterruptBase::UpDownInterruptBase(const char *name) { this->_originName = name; } -void UpDownInterruptBase::init( - uint8_t pinDown, uint8_t pinUp, uint8_t pinPress, - char eventDown, char eventUp, char eventPressed, - void (*onIntDown)(), void (*onIntUp)(), void (*onIntPress)()) +void UpDownInterruptBase::init(uint8_t pinDown, uint8_t pinUp, uint8_t pinPress, char eventDown, char eventUp, char eventPressed, + void (*onIntDown)(), void (*onIntUp)(), void (*onIntPress)()) { this->_pinDown = pinDown; this->_pinUp = pinUp; @@ -26,8 +23,7 @@ void UpDownInterruptBase::init( attachInterrupt(this->_pinDown, onIntDown, RISING); attachInterrupt(this->_pinUp, onIntUp, RISING); - LOG_DEBUG("GPIO initialized (%d, %d, %d)\n", - this->_pinDown, this->_pinUp, pinPress); + LOG_DEBUG("GPIO initialized (%d, %d, %d)\n", this->_pinDown, this->_pinUp, pinPress); } void UpDownInterruptBase::intPressHandler() diff --git a/src/input/UpDownInterruptImpl1.h b/src/input/UpDownInterruptImpl1.h index acdb7953c..17420db95 100644 --- a/src/input/UpDownInterruptImpl1.h +++ b/src/input/UpDownInterruptImpl1.h @@ -1,8 +1,7 @@ #pragma once #include "UpDownInterruptBase.h" -class UpDownInterruptImpl1 : - public UpDownInterruptBase +class UpDownInterruptImpl1 : public UpDownInterruptBase { public: UpDownInterruptImpl1(); diff --git a/src/input/cardKbI2cImpl.cpp b/src/input/cardKbI2cImpl.cpp index 3d30fb867..e1639270a 100644 --- a/src/input/cardKbI2cImpl.cpp +++ b/src/input/cardKbI2cImpl.cpp @@ -3,15 +3,11 @@ CardKbI2cImpl *cardKbI2cImpl; -CardKbI2cImpl::CardKbI2cImpl() : - KbI2cBase("cardKB") -{ -} +CardKbI2cImpl::CardKbI2cImpl() : KbI2cBase("cardKB") {} void CardKbI2cImpl::init() { - if (cardkb_found != CARDKB_ADDR) - { + if (cardkb_found != CARDKB_ADDR) { disable(); return; } diff --git a/src/input/cardKbI2cImpl.h b/src/input/cardKbI2cImpl.h index cd6ee8d47..1e6e87dfd 100644 --- a/src/input/cardKbI2cImpl.h +++ b/src/input/cardKbI2cImpl.h @@ -9,8 +9,7 @@ * to your device as you wish, but you always need to have separate event * handlers, thus you need to have a RotaryEncoderInterrupt implementation. */ -class CardKbI2cImpl : - public KbI2cBase +class CardKbI2cImpl : public KbI2cBase { public: CardKbI2cImpl(); diff --git a/src/input/kbI2cBase.cpp b/src/input/kbI2cBase.cpp index a857bae77..ca0ce2361 100644 --- a/src/input/kbI2cBase.cpp +++ b/src/input/kbI2cBase.cpp @@ -12,32 +12,32 @@ KbI2cBase::KbI2cBase(const char *name) : concurrency::OSThread(name) uint8_t read_from_14004(uint8_t reg, uint8_t *data, uint8_t length) { - uint8_t readflag = 0; - Wire.beginTransmission(CARDKB_ADDR); - Wire.write(reg); - Wire.endTransmission(); // stop transmitting - delay(20); - Wire.requestFrom(CARDKB_ADDR, (int)length); - int i = 0; - while ( Wire.available() ) // slave may send less than requested - { - data[i++] = Wire.read(); // receive a byte as a proper uint8_t - readflag = 1; - } - return readflag; + uint8_t readflag = 0; + Wire.beginTransmission(CARDKB_ADDR); + Wire.write(reg); + Wire.endTransmission(); // stop transmitting + delay(20); + Wire.requestFrom(CARDKB_ADDR, (int)length); + int i = 0; + while (Wire.available()) // slave may send less than requested + { + data[i++] = Wire.read(); // receive a byte as a proper uint8_t + readflag = 1; + } + return readflag; } void write_to_14004(uint8_t reg, uint8_t data) { - Wire.beginTransmission(CARDKB_ADDR); - Wire.write(reg); - Wire.write(data); - Wire.endTransmission(); // stop transmitting + Wire.beginTransmission(CARDKB_ADDR); + Wire.write(reg); + Wire.write(data); + Wire.endTransmission(); // stop transmitting } int32_t KbI2cBase::runOnce() { - if (cardkb_found != CARDKB_ADDR){ + if (cardkb_found != CARDKB_ADDR) { // Input device is not detected. return INT32_MAX; } @@ -48,7 +48,7 @@ int32_t KbI2cBase::runOnce() uint8_t PrintDataBuf = 0; if (read_from_14004(0x01, rDataBuf, 0x04) == 1) { for (uint8_t aCount = 0; aCount < 0x04; aCount++) { - for (uint8_t bCount = 0; bCount < 0x04; bCount++ ) { + for (uint8_t bCount = 0; bCount < 0x04; bCount++) { if (((rDataBuf[aCount] >> bCount) & 0x01) == 0x01) { PrintDataBuf = aCount * 0x04 + bCount + 1; } @@ -97,7 +97,7 @@ int32_t KbI2cBase::runOnce() case 0x0d: // Enter e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_SELECT; break; - case 0x00: //nopress + case 0x00: // nopress e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; break; default: // all other keys diff --git a/src/input/kbI2cBase.h b/src/input/kbI2cBase.h index 2fdacbc28..c661f95c5 100644 --- a/src/input/kbI2cBase.h +++ b/src/input/kbI2cBase.h @@ -1,11 +1,9 @@ #pragma once -#include "SinglePortModule.h" // TODO: what header file to include? #include "InputBroker.h" +#include "SinglePortModule.h" // TODO: what header file to include? -class KbI2cBase : - public Observable, - public concurrency::OSThread +class KbI2cBase : public Observable, public concurrency::OSThread { public: explicit KbI2cBase(const char *name); diff --git a/src/mesh/Channels.cpp b/src/mesh/Channels.cpp index f9b3eb9b8..fc7d62bbb 100644 --- a/src/mesh/Channels.cpp +++ b/src/mesh/Channels.cpp @@ -120,7 +120,7 @@ CryptoKey Channels::getKey(ChannelIndex chIndex) else if (oemStore.oem_aes_key.size > 1) { // Use the OEM key LOG_DEBUG("Using OEM Key with %d bytes\n", oemStore.oem_aes_key.size); - memcpy(k.bytes, oemStore.oem_aes_key.bytes , oemStore.oem_aes_key.size); + memcpy(k.bytes, oemStore.oem_aes_key.bytes, oemStore.oem_aes_key.size); k.length = oemStore.oem_aes_key.size; // Bump up the last byte of PSK as needed uint8_t *last = k.bytes + oemStore.oem_aes_key.size - 1; @@ -196,7 +196,7 @@ Channel &Channels::getByIndex(ChannelIndex chIndex) Channel *ch = channelFile.channels + chIndex; return *ch; } else { - LOG_ERROR("Invalid channel index %d > %d, malformed packet received?\n", chIndex , channelFile.channels_count); + LOG_ERROR("Invalid channel index %d > %d, malformed packet received?\n", chIndex, channelFile.channels_count); static Channel *ch = (Channel *)malloc(sizeof(Channel)); memset(ch, 0, sizeof(Channel)); @@ -207,7 +207,7 @@ Channel &Channels::getByIndex(ChannelIndex chIndex) } } -Channel &Channels::getByName(const char* chName) +Channel &Channels::getByName(const char *chName) { for (ChannelIndex i = 0; i < getNumChannels(); i++) { if (strcasecmp(getGlobalId(i), chName) == 0) { @@ -267,8 +267,7 @@ const char *Channels::getName(size_t chIndex) channelName = "Invalid"; break; } - } - else { + } else { channelName = "Custom"; } } diff --git a/src/mesh/Channels.h b/src/mesh/Channels.h index 79e96b7f6..ebf836cb7 100644 --- a/src/mesh/Channels.h +++ b/src/mesh/Channels.h @@ -29,7 +29,6 @@ class Channels int16_t hashes[MAX_NUM_CHANNELS] = {}; public: - Channels() {} /// Well known channel names @@ -40,8 +39,8 @@ class Channels /** Return the Channel for a specified index */ Channel &getByIndex(ChannelIndex chIndex); - /** Return the Channel for a specified name, return primary if not found. */ - Channel &getByName(const char* chName); + /** Return the Channel for a specified name, return primary if not found. */ + Channel &getByName(const char *chName); /** Using the index inside the channel, update the specified channel's settings and role. If this channel is being promoted * to be primary, force all other channels to be secondary. diff --git a/src/mesh/CryptoEngine.cpp b/src/mesh/CryptoEngine.cpp index 55535a0a8..9b5810650 100644 --- a/src/mesh/CryptoEngine.cpp +++ b/src/mesh/CryptoEngine.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "CryptoEngine.h" +#include "configuration.h" void CryptoEngine::setKey(const CryptoKey &k) { diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index b6c093e22..dfbc20202 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -31,10 +31,10 @@ void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c) { bool isAck = ((c && c->error_reason == Routing_Error_NONE)); // consider only ROUTING_APP message without error as ACK if (isAck && p->to != getNodeNum()) { - // do not flood direct message that is ACKed + // do not flood direct message that is ACKed LOG_DEBUG("Receiving an ACK not for me, but don't need to rebroadcast this direct message anymore.\n"); - Router::cancelSending(p->to, p->decoded.request_id); // cancel rebroadcast for this DM - } + Router::cancelSending(p->to, p->decoded.request_id); // cancel rebroadcast for this DM + } if ((p->to != getNodeNum()) && (p->hop_limit > 0) && (getFrom(p) != getNodeNum())) { if (p->id != 0) { if (config.device.role != Config_DeviceConfig_Role_CLIENT_MUTE) { diff --git a/src/mesh/InterfacesTemplates.cpp b/src/mesh/InterfacesTemplates.cpp index d8f84c487..73b0bdfbc 100644 --- a/src/mesh/InterfacesTemplates.cpp +++ b/src/mesh/InterfacesTemplates.cpp @@ -1,9 +1,9 @@ -#include "SX126xInterface.h" #include "SX126xInterface.cpp" -#include "SX128xInterface.h" +#include "SX126xInterface.h" #include "SX128xInterface.cpp" -#include "api/ServerAPI.h" +#include "SX128xInterface.h" #include "api/ServerAPI.cpp" +#include "api/ServerAPI.h" // We need this declaration for proper linking in derived classes template class SX126xInterface; diff --git a/src/mesh/LLCC68Interface.cpp b/src/mesh/LLCC68Interface.cpp index 013b31b40..05c3c241d 100644 --- a/src/mesh/LLCC68Interface.cpp +++ b/src/mesh/LLCC68Interface.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "LLCC68Interface.h" +#include "configuration.h" #include "error.h" LLCC68Interface::LLCC68Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, diff --git a/src/mesh/MeshModule.cpp b/src/mesh/MeshModule.cpp index 34a40d795..79b206547 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -1,8 +1,8 @@ -#include "configuration.h" #include "MeshModule.h" #include "Channels.h" #include "MeshService.h" #include "NodeDB.h" +#include "configuration.h" #include "modules/RoutingModule.h" #include @@ -106,8 +106,8 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) /// Is the channel this packet arrived on acceptable? (security check) /// Note: we can't know channel names for encrypted packets, so those are NEVER sent to boundChannel modules - /// Also: if a packet comes in on the local PC interface, we don't check for bound channels, because it is TRUSTED and it needs to - /// to be able to fetch the initial admin packets without yet knowing any channels. + /// Also: if a packet comes in on the local PC interface, we don't check for bound channels, because it is TRUSTED and + /// it needs to to be able to fetch the initial admin packets without yet knowing any channels. bool rxChannelOk = !pi.boundChannel || (mp.from == 0) || (strcasecmp(ch->settings.name, pi.boundChannel) == 0); @@ -161,7 +161,7 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) printPacket("Sending response", currentReply); service.sendToMesh(currentReply); currentReply = NULL; - } else if(mp.from != ourNodeNum) { + } else if (mp.from != ourNodeNum) { // Note: if the message started with the local node we don't want to send a no response reply // No one wanted to reply to this requst, tell the requster that happened @@ -175,9 +175,8 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) } if (!moduleFound) - LOG_DEBUG("No modules interested in portnum=%d, src=%s\n", - mp.decoded.portnum, - (src == RX_SRC_LOCAL) ? "LOCAL":"REMOTE"); + LOG_DEBUG("No modules interested in portnum=%d, src=%s\n", mp.decoded.portnum, + (src == RX_SRC_LOCAL) ? "LOCAL" : "REMOTE"); } MeshPacket *MeshModule::allocReply() @@ -235,14 +234,12 @@ std::vector MeshModule::GetMeshModulesWithUIFrames() return modulesWithUIFrames; } -void MeshModule::observeUIEvents( - Observer *observer) +void MeshModule::observeUIEvents(Observer *observer) { if (modules) { for (auto i = modules->begin(); i != modules->end(); ++i) { auto &pi = **i; - Observable *observable = - pi.getUIFrameObservable(); + Observable *observable = pi.getUIFrameObservable(); if (observable != NULL) { LOG_DEBUG("Module wants a UI Frame\n"); observer->observe(observable); @@ -251,24 +248,19 @@ void MeshModule::observeUIEvents( } } -AdminMessageHandleResult MeshModule::handleAdminMessageForAllPlugins(const MeshPacket &mp, AdminMessage *request, AdminMessage *response) +AdminMessageHandleResult MeshModule::handleAdminMessageForAllPlugins(const MeshPacket &mp, AdminMessage *request, + AdminMessage *response) { AdminMessageHandleResult handled = AdminMessageHandleResult::NOT_HANDLED; if (modules) { for (auto i = modules->begin(); i != modules->end(); ++i) { auto &pi = **i; AdminMessageHandleResult h = pi.handleAdminMessageForModule(mp, request, response); - if (h == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) - { + if (h == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) { // In case we have a response it always has priority. - LOG_DEBUG("Reply prepared by module '%s' of variant: %d\n", - pi.name, - response->which_payload_variant); + LOG_DEBUG("Reply prepared by module '%s' of variant: %d\n", pi.name, response->which_payload_variant); handled = h; - } - else if ((handled != AdminMessageHandleResult::HANDLED_WITH_RESPONSE) && - (h == AdminMessageHandleResult::HANDLED)) - { + } else if ((handled != AdminMessageHandleResult::HANDLED_WITH_RESPONSE) && (h == AdminMessageHandleResult::HANDLED)) { // In case the message is handled it should be populated, but will not overwrite // a result with response. handled = h; diff --git a/src/mesh/MeshModule.h b/src/mesh/MeshModule.h index c6f10f138..fcde7a305 100644 --- a/src/mesh/MeshModule.h +++ b/src/mesh/MeshModule.h @@ -10,15 +10,14 @@ #endif /** handleReceived return enumeration - * + * * Use ProcessMessage::CONTINUE to allows other modules to process a message. - * + * * Use ProcessMessage::STOP to stop further message processing. */ -enum class ProcessMessage -{ - CONTINUE = 0, - STOP = 1, +enum class ProcessMessage { + CONTINUE = 0, + STOP = 1, }; /** @@ -27,8 +26,7 @@ enum class ProcessMessage * If response is also prepared for the request, then HANDLED_WITH_RESPONSE * should be returned. */ -enum class AdminMessageHandleResult -{ +enum class AdminMessageHandleResult { NOT_HANDLED = 0, HANDLED = 1, HANDLED_WITH_RESPONSE = 2, @@ -70,10 +68,13 @@ class MeshModule static std::vector GetMeshModulesWithUIFrames(); static void observeUIEvents(Observer *observer); - static AdminMessageHandleResult handleAdminMessageForAllPlugins( - const MeshPacket &mp, AdminMessage *request, AdminMessage *response); + static AdminMessageHandleResult handleAdminMessageForAllPlugins(const MeshPacket &mp, AdminMessage *request, + AdminMessage *response); #if HAS_SCREEN - virtual void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) { return; } + virtual void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) + { + return; + } #endif protected: const char *name; @@ -127,9 +128,13 @@ class MeshModule /** Called to handle a particular incoming message - @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it + @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for + it */ - virtual ProcessMessage handleReceived(const MeshPacket &mp) { return ProcessMessage::CONTINUE; } + virtual ProcessMessage handleReceived(const MeshPacket &mp) + { + return ProcessMessage::CONTINUE; + } /** Messages can be received that have the want_response bit set. If set, this callback will be invoked * so that subclasses can (optionally) send a response back to the original sender. @@ -142,26 +147,35 @@ class MeshModule /*** * @return true if you want to be alloced a UI screen frame */ - virtual bool wantUIFrame() { return false; } - virtual Observable* getUIFrameObservable() { return NULL; } + virtual bool wantUIFrame() + { + return false; + } + virtual Observable *getUIFrameObservable() + { + return NULL; + } MeshPacket *allocAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex); /// Send an error response for the specified packet. MeshPacket *allocErrorResponse(Routing_Error err, const MeshPacket *p); - /** - * @brief An admin message arrived to AdminModule. Module was asked whether it want to handle the request. - * - * @param mp The mesh packet arrived. - * @param request The AdminMessage request extracted from the packet. - * @param response The prepared response - * @return AdminMessageHandleResult - * HANDLED if message was handled - * HANDLED_WITH_RESPONSE if a response is also prepared and to be sent. - */ - virtual AdminMessageHandleResult handleAdminMessageForModule( - const MeshPacket &mp, AdminMessage *request, AdminMessage *response) { return AdminMessageHandleResult::NOT_HANDLED; }; + /** + * @brief An admin message arrived to AdminModule. Module was asked whether it want to handle the request. + * + * @param mp The mesh packet arrived. + * @param request The AdminMessage request extracted from the packet. + * @param response The prepared response + * @return AdminMessageHandleResult + * HANDLED if message was handled + * HANDLED_WITH_RESPONSE if a response is also prepared and to be sent. + */ + virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, + AdminMessage *response) + { + return AdminMessageHandleResult::NOT_HANDLED; + }; private: /** diff --git a/src/mesh/MeshPacketQueue.cpp b/src/mesh/MeshPacketQueue.cpp index 9af381a0e..f14ca58ae 100644 --- a/src/mesh/MeshPacketQueue.cpp +++ b/src/mesh/MeshPacketQueue.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "MeshPacketQueue.h" +#include "configuration.h" #include #include @@ -26,7 +26,8 @@ bool CompareMeshPacketFunc(const MeshPacket *p1, const MeshPacket *p2) MeshPacketQueue::MeshPacketQueue(size_t _maxLen) : maxLen(_maxLen) {} -bool MeshPacketQueue::empty() { +bool MeshPacketQueue::empty() +{ return queue.empty(); } @@ -40,8 +41,9 @@ void fixPriority(MeshPacket *p) if (p->priority == MeshPacket_Priority_UNSET) { // if acks give high priority // if a reliable message give a bit higher default priority - p->priority = (p->decoded.portnum == PortNum_ROUTING_APP) ? MeshPacket_Priority_ACK : - (p->want_ack ? MeshPacket_Priority_RELIABLE : MeshPacket_Priority_DEFAULT); + p->priority = (p->decoded.portnum == PortNum_ROUTING_APP) + ? MeshPacket_Priority_ACK + : (p->want_ack ? MeshPacket_Priority_RELIABLE : MeshPacket_Priority_DEFAULT); } } @@ -99,7 +101,8 @@ MeshPacket *MeshPacketQueue::remove(NodeNum from, PacketId id) } /** Attempt to find and remove a packet from this queue. Returns the packet which was removed from the queue */ -bool MeshPacketQueue::replaceLowerPriorityPacket(MeshPacket *p) { +bool MeshPacketQueue::replaceLowerPriorityPacket(MeshPacket *p) +{ std::sort_heap(queue.begin(), queue.end(), &CompareMeshPacketFunc); // sort ascending based on priority (0 -> 127) // find first packet which does not compare less (in priority) than parameter packet @@ -119,7 +122,7 @@ bool MeshPacketQueue::replaceLowerPriorityPacket(MeshPacket *p) { if (getPriority(p) > getPriority(*low)) { packetPool.release(*low); // deallocate and drop the packet we're replacing - *low = p; // replace low-pri packet at this position with incoming packet with higher priority + *low = p; // replace low-pri packet at this position with incoming packet with higher priority } std::make_heap(queue.begin(), queue.end(), &CompareMeshPacketFunc); diff --git a/src/mesh/MeshPacketQueue.h b/src/mesh/MeshPacketQueue.h index 51dc34cb5..dd348bec6 100644 --- a/src/mesh/MeshPacketQueue.h +++ b/src/mesh/MeshPacketQueue.h @@ -4,7 +4,6 @@ #include - /** * A priority queue of packets */ @@ -13,7 +12,8 @@ class MeshPacketQueue size_t maxLen; std::vector queue; - /** Replace a lower priority package in the queue with 'mp' (provided there are lower pri packages). Return true if replaced. */ + /** Replace a lower priority package in the queue with 'mp' (provided there are lower pri packages). Return true if replaced. + */ bool replaceLowerPriorityPacket(MeshPacket *mp); public: diff --git a/src/mesh/MeshService.cpp b/src/mesh/MeshService.cpp index 9a6fa984c..55a1f66c3 100644 --- a/src/mesh/MeshService.cpp +++ b/src/mesh/MeshService.cpp @@ -2,9 +2,9 @@ #include #include -#include "GPS.h" #include "../concurrency/Periodic.h" #include "BluetoothCommon.h" // needed for updateBatteryLevel, FIXME, eventually when we pull mesh out into a lib we shouldn't be whacking bluetooth from here +#include "GPS.h" #include "MeshService.h" #include "NodeDB.h" #include "PowerFSM.h" @@ -59,7 +59,7 @@ Allocator &queueStatusPool = staticQueueStatusPool; MeshService::MeshService() : toPhoneQueue(MAX_RX_TOPHONE), toPhoneQueueStatusQueue(MAX_RX_TOPHONE) { - lastQueueStatus = { 0, 0, 16, 0 }; + lastQueueStatus = {0, 0, 16, 0}; } void MeshService::init() @@ -132,7 +132,7 @@ void MeshService::reloadOwner(bool shouldSave) */ void MeshService::handleToRadio(MeshPacket &p) { - #ifdef ARCH_PORTDUINO +#ifdef ARCH_PORTDUINO // Simulates device is receiving a packet via the LoRa chip if (p.decoded.portnum == PortNum_SIMULATOR_APP) { // Simulator packet (=Compressed packet) is encapsulated in a MeshPacket, so need to unwrap first @@ -140,21 +140,22 @@ void MeshService::handleToRadio(MeshPacket &p) Compressed *decoded = NULL; if (p.which_payload_variant == MeshPacket_decoded_tag) { memset(&scratch, 0, sizeof(scratch)); - p.decoded.payload.size = pb_decode_from_bytes(p.decoded.payload.bytes, p.decoded.payload.size, &Compressed_msg, &scratch); + p.decoded.payload.size = + pb_decode_from_bytes(p.decoded.payload.bytes, p.decoded.payload.size, &Compressed_msg, &scratch); if (p.decoded.payload.size) { decoded = &scratch; // Extract the original payload and replace memcpy(&p.decoded.payload, &decoded->data, sizeof(decoded->data)); - // Switch the port from PortNum_SIMULATOR_APP back to the original PortNum + // Switch the port from PortNum_SIMULATOR_APP back to the original PortNum p.decoded.portnum = decoded->portnum; } else LOG_ERROR("Error decoding protobuf for simulator message!\n"); } // Let SimRadio receive as if it did via its LoRa chip - SimRadio::instance->startReceive(&p); - return; + SimRadio::instance->startReceive(&p); + return; } - #endif +#endif if (p.from != 0) { // We don't let phones assign nodenums to their sent messages LOG_WARN("phone tried to pick a nodenum, we don't allow that.\n"); p.from = 0; @@ -323,7 +324,7 @@ int MeshService::onGPSChanged(const meshtastic::GPSStatus *newStatus) return 0; } -bool MeshService::isToPhoneQueueEmpty() +bool MeshService::isToPhoneQueueEmpty() { return toPhoneQueue.isEmpty(); } diff --git a/src/mesh/MeshService.h b/src/mesh/MeshService.h index 31b63bd3f..fceafbab4 100644 --- a/src/mesh/MeshService.h +++ b/src/mesh/MeshService.h @@ -80,7 +80,7 @@ class MeshService /** The radioConfig object just changed, call this to force the hw to change to the new settings * @return true if client devices should be sent a new set of radio configs */ - bool reloadConfig(int saveWhat=SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); + bool reloadConfig(int saveWhat = SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); /// The owner User record just got updated, update our node DB and broadcast the info into the mesh void reloadOwner(bool shouldSave = true); @@ -100,7 +100,7 @@ class MeshService /// Pull the latest power and time info into my nodeinfo NodeInfo *refreshMyNodeInfo(); - /// Send a packet to the phone + /// Send a packet to the phone void sendToPhone(MeshPacket *p); bool isToPhoneQueueEmpty(); diff --git a/src/mesh/MeshTypes.h b/src/mesh/MeshTypes.h index c08637385..ad21bf1bc 100644 --- a/src/mesh/MeshTypes.h +++ b/src/mesh/MeshTypes.h @@ -19,9 +19,9 @@ typedef uint32_t PacketId; // A packet sequence number * Source of a received message */ enum RxSource { - RX_SRC_LOCAL, // message was generated locally - RX_SRC_RADIO, // message was received from radio mesh - RX_SRC_USER // message was received from end-user device + RX_SRC_LOCAL, // message was generated locally + RX_SRC_RADIO, // message was received from radio mesh + RX_SRC_USER // message was received from end-user device }; /** diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index 076f56af6..7a2f0483e 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -13,9 +13,9 @@ #include "error.h" #include "main.h" #include "mesh-pb-constants.h" +#include #include #include -#include #ifdef ARCH_ESP32 #include "mesh/http/WiFiAPClient.h" @@ -81,7 +81,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) radioGeneration++; if (factory_reset) { - didFactoryReset = factoryReset(); + didFactoryReset = factoryReset(); } if (channelFile.channels_count != MAX_NUM_CHANNELS) { @@ -121,7 +121,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) return didFactoryReset; } -bool NodeDB::factoryReset() +bool NodeDB::factoryReset() { LOG_INFO("Performing factory reset!\n"); // first, remove the "/prefs" (this removes most prefs) @@ -160,8 +160,9 @@ void NodeDB::installDefaultConfig() config.has_power = true; config.has_network = true; config.has_bluetooth = true; - config.lora.tx_enabled = true; // FIXME: maybe false in the future, and setting region to enable it. (unset region forces it off) - config.lora.override_duty_cycle = false; + config.lora.tx_enabled = + true; // FIXME: maybe false in the future, and setting region to enable it. (unset region forces it off) + config.lora.override_duty_cycle = false; config.lora.region = Config_LoRaConfig_RegionCode_UNSET; config.lora.modem_preset = Config_LoRaConfig_ModemPreset_LONG_FAST; config.lora.hop_limit = HOP_RELIABLE; @@ -178,14 +179,16 @@ void NodeDB::installDefaultConfig() #else bool hasScreen = screen_found; #endif - config.bluetooth.mode = hasScreen ? Config_BluetoothConfig_PairingMode_RANDOM_PIN : Config_BluetoothConfig_PairingMode_FIXED_PIN; + config.bluetooth.mode = + hasScreen ? Config_BluetoothConfig_PairingMode_RANDOM_PIN : Config_BluetoothConfig_PairingMode_FIXED_PIN; // for backward compat, default position flags are ALT+MSL - config.position.position_flags = (Config_PositionConfig_PositionFlags_ALTITUDE | Config_PositionConfig_PositionFlags_ALTITUDE_MSL); - + config.position.position_flags = + (Config_PositionConfig_PositionFlags_ALTITUDE | Config_PositionConfig_PositionFlags_ALTITUDE_MSL); + initConfigIntervals(); } -void NodeDB::initConfigIntervals() +void NodeDB::initConfigIntervals() { config.position.gps_update_interval = default_gps_update_interval; config.position.gps_attempt_time = default_gps_attempt_time; @@ -196,7 +199,7 @@ void NodeDB::initConfigIntervals() config.power.min_wake_secs = default_min_wake_secs; config.power.sds_secs = default_sds_secs; config.power.wait_bluetooth_secs = default_wait_bluetooth_secs; - + config.display.screen_on_secs = default_screen_on_secs; } @@ -204,7 +207,7 @@ void NodeDB::installDefaultModuleConfig() { LOG_INFO("Installing default ModuleConfig\n"); memset(&moduleConfig, 0, sizeof(ModuleConfig)); - + moduleConfig.version = DEVICESTATE_CUR_VER; moduleConfig.has_mqtt = true; moduleConfig.has_range_test = true; @@ -221,7 +224,7 @@ void NodeDB::installDefaultModuleConfig() initModuleConfigIntervals(); } -void NodeDB::initModuleConfigIntervals() +void NodeDB::initModuleConfigIntervals() { moduleConfig.telemetry.device_update_interval = default_broadcast_interval_secs; moduleConfig.telemetry.environment_update_interval = default_broadcast_interval_secs; @@ -247,7 +250,7 @@ void NodeDB::installDefaultDeviceState() memset(&devicestate, 0, sizeof(DeviceState)); *numNodes = 0; - + // init our devicestate with valid flags so protobuf writing/reading will work devicestate.has_my_node = true; devicestate.has_owner = true; @@ -285,7 +288,8 @@ void NodeDB::init() myNodeInfo.max_channels = MAX_NUM_CHANNELS; // tell others the max # of channels we can understand - myNodeInfo.error_code = CriticalErrorCode_NONE; // For the error code, only show values from this boot (discard value from flash) + myNodeInfo.error_code = + CriticalErrorCode_NONE; // For the error code, only show values from this boot (discard value from flash) myNodeInfo.error_address = 0; // likewise - we always want the app requirements to come from the running appload @@ -364,7 +368,6 @@ static const char *moduleConfigFileName = "/prefs/module.proto"; static const char *channelFileName = "/prefs/channels.proto"; static const char *oemConfigFile = "/oem/oem.proto"; - /** Load a protobuf from a file, return true for success */ bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, void *dest_struct) { @@ -422,7 +425,8 @@ void NodeDB::loadFromDisk() } } - if (!loadProto(moduleConfigFileName, LocalModuleConfig_size, sizeof(LocalModuleConfig), &LocalModuleConfig_msg, &moduleConfig)) { + if (!loadProto(moduleConfigFileName, LocalModuleConfig_size, sizeof(LocalModuleConfig), &LocalModuleConfig_msg, + &moduleConfig)) { installDefaultModuleConfig(); // Our in RAM copy might now be corrupt } else { if (moduleConfig.version < DEVICESTATE_MIN_VER) { @@ -478,9 +482,9 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ #ifdef ARCH_NRF52 static uint8_t failedCounter = 0; failedCounter++; - if(failedCounter >= 2){ + if (failedCounter >= 2) { FSCom.format(); - //After formatting, the device needs to be restarted + // After formatting, the device needs to be restarted nodeDB.resetRadioConfig(true); } #endif @@ -501,7 +505,7 @@ void NodeDB::saveChannelsToDisk() } } -void NodeDB::saveDeviceStateToDisk() +void NodeDB::saveDeviceStateToDisk() { if (!devicestate.no_save) { #ifdef FSCom @@ -599,7 +603,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src) if (src == RX_SRC_LOCAL) { // Local packet, fully authoritative LOG_INFO("updatePosition LOCAL pos@%x, time=%u, latI=%d, lonI=%d, alt=%d\n", p.timestamp, p.time, p.latitude_i, - p.longitude_i, p.altitude); + p.longitude_i, p.altitude); info->position = p; } else if ((p.time > 0) && !p.latitude_i && !p.longitude_i && !p.timestamp && !p.location_source) { diff --git a/src/mesh/NodeDB.h b/src/mesh/NodeDB.h index 991e577c7..651dd2207 100644 --- a/src/mesh/NodeDB.h +++ b/src/mesh/NodeDB.h @@ -58,7 +58,8 @@ class NodeDB void init(); /// write to flash - void saveToDisk(int saveWhat = SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS), saveChannelsToDisk(), saveDeviceStateToDisk(); + void saveToDisk(int saveWhat = SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS), + saveChannelsToDisk(), saveDeviceStateToDisk(); /** Reinit radio config if needed, because either: * a) sometimes a buggy android app might send us bogus settings or @@ -122,7 +123,7 @@ class NodeDB size_t getNumOnlineNodes(); void initConfigIntervals(), initModuleConfigIntervals(), resetNodes(); - + bool factoryReset(); bool loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, void *dest_struct); @@ -140,13 +141,11 @@ class NodeDB newStatus.notifyObservers(&status); } - /// read our db from flash void loadFromDisk(); /// Reinit device state from scratch (not loading from disk) - void installDefaultDeviceState(), installDefaultChannels(), installDefaultConfig(), - installDefaultModuleConfig(); + void installDefaultDeviceState(), installDefaultChannels(), installDefaultConfig(), installDefaultModuleConfig(); }; /** @@ -203,13 +202,15 @@ extern NodeDB nodeDB; inline uint32_t getConfiguredOrDefaultMs(uint32_t configuredInterval) { - if (configuredInterval > 0) return configuredInterval * 1000; + if (configuredInterval > 0) + return configuredInterval * 1000; return default_broadcast_interval_secs * 1000; } inline uint32_t getConfiguredOrDefaultMs(uint32_t configuredInterval, uint32_t defaultInterval) { - if (configuredInterval > 0) return configuredInterval * 1000; + if (configuredInterval > 0) + return configuredInterval * 1000; return defaultInterval * 1000; } @@ -218,4 +219,7 @@ inline uint32_t getConfiguredOrDefaultMs(uint32_t configuredInterval, uint32_t d */ extern uint32_t radioGeneration; -#define Module_Config_size (ModuleConfig_CannedMessageConfig_size + ModuleConfig_ExternalNotificationConfig_size + ModuleConfig_MQTTConfig_size + ModuleConfig_RangeTestConfig_size + ModuleConfig_SerialConfig_size + ModuleConfig_StoreForwardConfig_size + ModuleConfig_TelemetryConfig_size + ModuleConfig_size) +#define Module_Config_size \ + (ModuleConfig_CannedMessageConfig_size + ModuleConfig_ExternalNotificationConfig_size + ModuleConfig_MQTTConfig_size + \ + ModuleConfig_RangeTestConfig_size + ModuleConfig_SerialConfig_size + ModuleConfig_StoreForwardConfig_size + \ + ModuleConfig_TelemetryConfig_size + ModuleConfig_size) diff --git a/src/mesh/PacketHistory.cpp b/src/mesh/PacketHistory.cpp index e46adfc9e..4784ecf3b 100644 --- a/src/mesh/PacketHistory.cpp +++ b/src/mesh/PacketHistory.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "PacketHistory.h" +#include "configuration.h" #include "mesh-pb-constants.h" PacketHistory::PacketHistory() @@ -26,10 +26,10 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) r.rxTimeMsec = now; auto found = recentPackets.find(r); - bool seenRecently = (found != recentPackets.end()); // found not equal to .end() means packet was seen recently + bool seenRecently = (found != recentPackets.end()); // found not equal to .end() means packet was seen recently if (seenRecently && (now - found->rxTimeMsec) >= FLOOD_EXPIRE_TIME) { // Check whether found packet has already expired - recentPackets.erase(found); // Erase and pretend packet has not been seen recently + recentPackets.erase(found); // Erase and pretend packet has not been seen recently found = recentPackets.end(); seenRecently = false; } @@ -58,12 +58,13 @@ bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) /** * Iterate through all recent packets, and remove all older than FLOOD_EXPIRE_TIME */ -void PacketHistory::clearExpiredRecentPackets() { +void PacketHistory::clearExpiredRecentPackets() +{ uint32_t now = millis(); LOG_DEBUG("recentPackets size=%ld\n", recentPackets.size()); - for (auto it = recentPackets.begin(); it != recentPackets.end(); ) { + for (auto it = recentPackets.begin(); it != recentPackets.end();) { if ((now - it->rxTimeMsec) >= FLOOD_EXPIRE_TIME) { it = recentPackets.erase(it); // erase returns iterator pointing to element immediately following the one erased } else { diff --git a/src/mesh/ProtobufModule.cpp b/src/mesh/ProtobufModule.cpp index cea2ecbf6..ef18c0e88 100644 --- a/src/mesh/ProtobufModule.cpp +++ b/src/mesh/ProtobufModule.cpp @@ -1,4 +1,2 @@ -#include "configuration.h" #include "ProtobufModule.h" - - +#include "configuration.h" diff --git a/src/mesh/ProtobufModule.h b/src/mesh/ProtobufModule.h index 61fc95b7a..f1b0bd3d1 100644 --- a/src/mesh/ProtobufModule.h +++ b/src/mesh/ProtobufModule.h @@ -22,8 +22,6 @@ template class ProtobufModule : protected SinglePortModule } protected: - - /** * Handle a received message, the data field in the message is already decoded and is provided * @@ -62,7 +60,8 @@ template class ProtobufModule : protected SinglePortModule private: /** Called to handle a particular incoming message - @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it + @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for + it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override { @@ -70,8 +69,7 @@ template class ProtobufModule : protected SinglePortModule // it would be better to update even if the message was destined to others. auto &p = mp.decoded; - LOG_INFO("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum, - p.payload.size); + LOG_INFO("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum, p.payload.size); T scratch; T *decoded = NULL; diff --git a/src/mesh/RF95Interface.cpp b/src/mesh/RF95Interface.cpp index 4502d0810..523c37746 100644 --- a/src/mesh/RF95Interface.cpp +++ b/src/mesh/RF95Interface.cpp @@ -1,7 +1,7 @@ -#include "configuration.h" #include "RF95Interface.h" #include "MeshRadio.h" // kinda yucky, but we need to know which region we are in #include "RadioLibRF95.h" +#include "configuration.h" #include "error.h" #define MAX_POWER 20 @@ -70,9 +70,9 @@ bool RF95Interface::init() int res = lora->begin(getFreq(), bw, sf, cr, syncWord, power, currentLimit, preambleLength); LOG_INFO("RF95 init result %d\n", res); - LOG_INFO("Frequency set to %f\n", getFreq()); - LOG_INFO("Bandwidth set to %f\n", bw); - LOG_INFO("Power output set to %d\n", power); + LOG_INFO("Frequency set to %f\n", getFreq()); + LOG_INFO("Bandwidth set to %f\n", bw); + LOG_INFO("Power output set to %d\n", power); // current limit was removed from module' ctor // override default value (60 mA) @@ -129,7 +129,7 @@ bool RF95Interface::reconfigure() if (power > MAX_POWER) // This chip has lower power limits than some power = MAX_POWER; - + err = lora->setOutputPower(power); if (err != RADIOLIB_ERR_NONE) RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); @@ -146,7 +146,6 @@ void RF95Interface::addReceiveMetadata(MeshPacket *mp) { mp->rx_snr = lora->getSNR(); mp->rx_rssi = lround(lora->getRSSI()); - } void RF95Interface::setStandby() @@ -186,15 +185,15 @@ bool RF95Interface::isChannelActive() // check if we can detect a LoRa preamble on the current channel int16_t result; setTransmitEnable(false); - setStandby(); // needed for smooth transition + setStandby(); // needed for smooth transition result = lora->scanChannel(); - + if (result == RADIOLIB_PREAMBLE_DETECTED) { // LOG_DEBUG("Channel is busy!\n"); return true; } assert(result != RADIOLIB_ERR_WRONG_MODEM); - + // LOG_DEBUG("Channel is free!\n"); return false; } diff --git a/src/mesh/RF95Interface.h b/src/mesh/RF95Interface.h index 575786a77..641f3fc2d 100644 --- a/src/mesh/RF95Interface.h +++ b/src/mesh/RF95Interface.h @@ -13,8 +13,8 @@ class RF95Interface : public RadioLibInterface public: RF95Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, SPIClass &spi); - - //TODO: Verify that this irq flag works with RFM95 / SX1276 radios the way it used to + + // TODO: Verify that this irq flag works with RFM95 / SX1276 radios the way it used to bool isIRQPending() override { return lora->getIRQFlags() & RADIOLIB_SX127X_MASK_IRQ_FLAG_VALID_HEADER; } /// Initialise the Driver transport hardware and software. diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 212255c80..76532fb69 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -11,10 +11,10 @@ #include #include -#define RDEF(name, freq_start, freq_end, duty_cycle, spacing, power_limit, audio_permitted, frequency_switching, wide_lora) \ +#define RDEF(name, freq_start, freq_end, duty_cycle, spacing, power_limit, audio_permitted, frequency_switching, wide_lora) \ { \ Config_LoRaConfig_RegionCode_##name, freq_start, freq_end, duty_cycle, spacing, power_limit, audio_permitted, \ - frequency_switching, wide_lora, #name \ + frequency_switching, wide_lora, #name \ } const RegionInfo regions[] = { @@ -38,9 +38,9 @@ const RegionInfo regions[] = { Special Note: The link above describes LoRaWAN's band plan, stating a power limit of 16 dBm. This is their own suggested specification, - we do not need to follow it. The European Union regulations clearly state that the power limit for this frequency range is 500 mW, or 27 dBm. - It also states that we can use interference avoidance and spectrum access techniques to avoid a duty cycle. - (Please refer to section 4.21 in the following document) + we do not need to follow it. The European Union regulations clearly state that the power limit for this frequency range is + 500 mW, or 27 dBm. It also states that we can use interference avoidance and spectrum access techniques to avoid a duty + cycle. (Please refer to section 4.21 in the following document) https://ec.europa.eu/growth/tools-databases/tris/index.cfm/ro/search/?trisaction=search.detail&year=2021&num=528&dLang=EN */ RDEF(EU_868, 869.4f, 869.65f, 10, 0, 27, false, false, false), @@ -94,7 +94,7 @@ const RegionInfo regions[] = { https://lora-alliance.org/wp-content/uploads/2020/11/lorawan_regional_parameters_v1.0.3reva_0.pdf */ RDEF(TH, 920.0f, 925.0f, 100, 0, 16, true, false, false), - + /* 433,05-434,7 Mhz 10 mW https://nkrzi.gov.ua/images/upload/256/5810/PDF_UUZ_19_01_2016.pdf @@ -178,7 +178,7 @@ uint32_t RadioInterface::getPacketTime(uint32_t pl) uint32_t RadioInterface::getPacketTime(MeshPacket *p) { uint32_t pl = 0; - if(p->which_payload_variant == MeshPacket_encrypted_tag) { + if (p->which_payload_variant == MeshPacket_encrypted_tag) { pl = p->encrypted.size + sizeof(PacketHeader); } else { size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded); @@ -197,7 +197,7 @@ uint32_t RadioInterface::getRetransmissionMsec(const MeshPacket *p) float channelUtil = airTime->channelUtilizationPercent(); uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); // Assuming we pick max. of CWsize and there will be a receiver with SNR at half the range - return 2*packetAirtime + (pow(2, CWsize) + pow(2, int((CWmax+CWmin)/2))) * slotTimeMsec + PROCESSING_TIME_MSEC; + return 2 * packetAirtime + (pow(2, CWsize) + pow(2, int((CWmax + CWmin) / 2))) * slotTimeMsec + PROCESSING_TIME_MSEC; } /** The delay to use when we want to send something */ @@ -226,9 +226,8 @@ uint32_t RadioInterface::getTxDelayMsecWeighted(float snr) uint32_t delay = 0; uint8_t CWsize = map(snr, SNR_MIN, SNR_MAX, CWmin, CWmax); // LOG_DEBUG("rx_snr of %f so setting CWsize to:%d\n", snr, CWsize); - if (config.device.role == Config_DeviceConfig_Role_ROUTER || - config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT) { - delay = random(0, 2*CWsize) * slotTimeMsec; + if (config.device.role == Config_DeviceConfig_Role_ROUTER || config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT) { + delay = random(0, 2 * CWsize) * slotTimeMsec; LOG_DEBUG("rx_snr found in packet. As a router, setting tx delay:%d\n", delay); } else { delay = random(0, pow(2, CWsize)) * slotTimeMsec; @@ -453,14 +452,16 @@ void RadioInterface::applyModemConfig() // float freq = myRegion->freqStart + ((((myRegion->freqEnd - myRegion->freqStart) / numChannels) / 2) * channel_num); // New frequency selection formula - float freq = myRegion->freqStart + (bw / 2000) + ( channel_num * (bw / 1000)); + float freq = myRegion->freqStart + (bw / 2000) + (channel_num * (bw / 1000)); saveChannelNum(channel_num); saveFreq(freq + config.lora.frequency_offset); LOG_INFO("Radio freq=%.3f, config.lora.frequency_offset=%.3f\n", freq, config.lora.frequency_offset); - LOG_INFO("Set radio: region=%s, name=%s, config=%u, ch=%d, power=%d\n", myRegion->name, channelName, loraConfig.modem_preset, channel_num, power); - LOG_INFO("Radio myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f mhz)\n", myRegion->freqStart, myRegion->freqEnd, myRegion->freqEnd - myRegion->freqStart); + LOG_INFO("Set radio: region=%s, name=%s, config=%u, ch=%d, power=%d\n", myRegion->name, channelName, loraConfig.modem_preset, + channel_num, power); + LOG_INFO("Radio myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f mhz)\n", myRegion->freqStart, myRegion->freqEnd, + myRegion->freqEnd - myRegion->freqStart); LOG_INFO("Radio myRegion->numChannels: %d x %.3fkHz\n", numChannels, bw); LOG_INFO("Radio channel_num: %d\n", channel_num); LOG_INFO("Radio frequency: %f\n", getFreq()); @@ -486,7 +487,6 @@ void RadioInterface::limitPower() LOG_INFO("Set radio: final power level=%d\n", power); } - void RadioInterface::deliverToReceiver(MeshPacket *p) { if (router) diff --git a/src/mesh/RadioInterface.h b/src/mesh/RadioInterface.h index 59c63add2..852ad5f38 100644 --- a/src/mesh/RadioInterface.h +++ b/src/mesh/RadioInterface.h @@ -51,23 +51,23 @@ class RadioInterface CallbackObserver notifyDeepSleepObserver = CallbackObserver(this, &RadioInterface::notifyDeepSleepCb); - protected: bool disabled = false; float bw = 125; uint8_t sf = 9; uint8_t cr = 7; - /** Slottime is the minimum time to wait, consisting of: - - CAD duration (maximum of SX126x and SX127x); - - roundtrip air propagation time (assuming max. 30km between nodes); + /** Slottime is the minimum time to wait, consisting of: + - CAD duration (maximum of SX126x and SX127x); + - roundtrip air propagation time (assuming max. 30km between nodes); - Tx/Rx turnaround time (maximum of SX126x and SX127x); - MAC processing time (measured on T-beam) */ - uint32_t slotTimeMsec = 8.5 * pow(2, sf)/bw + 0.2 + 0.4 + 7; + uint32_t slotTimeMsec = 8.5 * pow(2, sf) / bw + 0.2 + 0.4 + 7; uint16_t preambleLength = 32; // 8 is default, but we use longer to increase the amount of sleep time when receiving - const uint32_t PROCESSING_TIME_MSEC = 4500; // time to construct, process and construct a packet again (empirically determined) - const uint8_t CWmin = 2; // minimum CWsize - const uint8_t CWmax = 8; // maximum CWsize + const uint32_t PROCESSING_TIME_MSEC = + 4500; // time to construct, process and construct a packet again (empirically determined) + const uint8_t CWmin = 2; // minimum CWsize + const uint8_t CWmax = 8; // maximum CWsize MeshPacket *sendingPacket = NULL; // The packet we are currently sending uint32_t lastTxStart = 0L; @@ -116,7 +116,8 @@ class RadioInterface virtual ErrorCode send(MeshPacket *p) = 0; /** Return TX queue status */ - virtual QueueStatus getQueueStatus() { + virtual QueueStatus getQueueStatus() + { QueueStatus qs; qs.res = qs.mesh_packet_id = qs.free = qs.maxlen = 0; return qs; @@ -146,7 +147,6 @@ class RadioInterface /** The delay to use when we want to flood a message. Use a weighted scale based on SNR */ uint32_t getTxDelayMsecWeighted(float snr); - /** * Calculate airtime per * https://www.rs-online.com/designspark/rel-assets/ds-assets/uploads/knowledge-items/application-notes-for-the-internet-of-things/LoRa%20Design%20Guide.pdf @@ -220,6 +220,5 @@ class RadioInterface } }; - /// Debug printing for packets void printPacket(const char *prefix, const MeshPacket *p); diff --git a/src/mesh/RadioLibInterface.h b/src/mesh/RadioLibInterface.h index 628ea863f..031a330ff 100644 --- a/src/mesh/RadioLibInterface.h +++ b/src/mesh/RadioLibInterface.h @@ -1,8 +1,8 @@ #pragma once -#include "concurrency/NotifiedWorkerThread.h" -#include "RadioInterface.h" #include "MeshPacketQueue.h" +#include "RadioInterface.h" +#include "concurrency/NotifiedWorkerThread.h" #include @@ -39,7 +39,7 @@ class LockingModule : public Module : Module(cs, irq, rst, gpio, spi, spiSettings) { } - + void SPIbeginTransaction() override; void SPIendTransaction() override; }; @@ -62,17 +62,16 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified MeshPacketQueue txQueue = MeshPacketQueue(MAX_TX_QUEUE); protected: - /** - * We use a meshtastic sync word, but hashed with the Channel name. For releases before 1.2 we used 0x12 (or for very old loads 0x14) - * Note: do not use 0x34 - that is reserved for lorawan - * - * We now use 0x2b (so that someday we can possibly use NOT 2b - because that would be funny pun). We will be staying with this code - * for a long time. + * We use a meshtastic sync word, but hashed with the Channel name. For releases before 1.2 we used 0x12 (or for very old + * loads 0x14) Note: do not use 0x34 - that is reserved for lorawan + * + * We now use 0x2b (so that someday we can possibly use NOT 2b - because that would be funny pun). We will be staying with + * this code for a long time. */ const uint8_t syncWord = 0x2b; - - float currentLimit = 100; // 100mA OCP - Should be acceptable for RFM95/SX127x chipset. + + float currentLimit = 100; // 100mA OCP - Should be acceptable for RFM95/SX127x chipset. LockingModule module; // The HW interface to the radio @@ -131,8 +130,8 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified virtual bool cancelSending(NodeNum from, PacketId id) override; private: - /** if we have something waiting to send, start a short (random) timer so we can come check for collision before actually doing - * the transmit */ + /** if we have something waiting to send, start a short (random) timer so we can come check for collision before actually + * doing the transmit */ void setTransmitDelay(); /** random timer with certain min. and max. settings */ @@ -156,7 +155,6 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified QueueStatus getQueueStatus(); protected: - /** Do any hardware setup needed on entry into send configuration for the radio. Subclasses can customize */ virtual void configHardwareForSend() {} diff --git a/src/mesh/RadioLibRF95.cpp b/src/mesh/RadioLibRF95.cpp index 6067f59b6..ad4b75a1f 100644 --- a/src/mesh/RadioLibRF95.cpp +++ b/src/mesh/RadioLibRF95.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "RadioLibRF95.h" +#include "configuration.h" #define RF95_CHIP_VERSION 0x12 #define RF95_ALT_VERSION 0x11 // Supposedly some versions of the chip have id 0x11 @@ -7,11 +7,10 @@ // From datasheet but radiolib doesn't know anything about this #define SX127X_REG_TCXO 0x4B - RadioLibRF95::RadioLibRF95(Module *mod) : SX1278(mod) {} -int16_t RadioLibRF95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, - uint16_t preambleLength, uint8_t gain) +int16_t RadioLibRF95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, + uint8_t gain) { // execute common part int16_t state = SX127x::begin(RF95_CHIP_VERSION, syncWord, preambleLength); diff --git a/src/mesh/RadioLibRF95.h b/src/mesh/RadioLibRF95.h index 7fbaff780..3bdb794f2 100644 --- a/src/mesh/RadioLibRF95.h +++ b/src/mesh/RadioLibRF95.h @@ -6,9 +6,9 @@ \brief Derived class for %RFM95 modules. Overrides some methods from SX1278 due to different parameter ranges. */ -class RadioLibRF95: public SX1278 { +class RadioLibRF95 : public SX1278 +{ public: - // constructor /*! @@ -16,7 +16,7 @@ class RadioLibRF95: public SX1278 { \param mod Instance of Module that will be used to communicate with the %LoRa chip. */ - explicit RadioLibRF95(Module* mod); + explicit RadioLibRF95(Module *mod); // basic methods @@ -31,19 +31,21 @@ class RadioLibRF95: public SX1278 { \param cr %LoRa link coding rate denominator. Allowed values range from 5 to 8. - \param syncWord %LoRa sync word. Can be used to distinguish different networks. Note that value 0x34 is reserved for LoRaWAN networks. + \param syncWord %LoRa sync word. Can be used to distinguish different networks. Note that value 0x34 is reserved for LoRaWAN + networks. \param power Transmission output power in dBm. Allowed values range from 2 to 17 dBm. - \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer than the set number. - Allowed values range from 6 to 65535. + \param preambleLength Length of %LoRa transmission preamble in symbols. The actual preamble length is 4.25 symbols longer + than the set number. Allowed values range from 6 to 65535. - \param gain Gain of receiver LNA (low-noise amplifier). Can be set to any integer in range 1 to 6 where 1 is the highest gain. - Set to 0 to enable automatic gain control (recommended). + \param gain Gain of receiver LNA (low-noise amplifier). Can be set to any integer in range 1 to 6 where 1 is the highest + gain. Set to 0 to enable automatic gain control (recommended). \returns \ref status_codes */ - int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = RADIOLIB_SX127X_SYNC_WORD, int8_t power = 17, uint16_t preambleLength = 8, uint8_t gain = 0); + int16_t begin(float freq = 915.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, + uint8_t syncWord = RADIOLIB_SX127X_SYNC_WORD, int8_t power = 17, uint16_t preambleLength = 8, uint8_t gain = 0); // configuration methods @@ -60,11 +62,10 @@ class RadioLibRF95: public SX1278 { bool isReceiving(); /// For debugging - uint8_t readReg(uint8_t addr); + uint8_t readReg(uint8_t addr); protected: // since default current limit for SX126x/127x in updated RadioLib is 60mA // use the previous value float currentLimit = 100; }; - diff --git a/src/mesh/ReliableRouter.cpp b/src/mesh/ReliableRouter.cpp index a7e80e8a1..95b46f9c4 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -38,7 +38,7 @@ bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) // the original sending process. // This "optimization", does save lots of airtime. For DMs, you also get a real ACK back - // from the intended recipient. + // from the intended recipient. auto key = GlobalPacketId(getFrom(p), p->id); auto old = findPendingPacket(key); if (old) { @@ -54,9 +54,9 @@ bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) } /* Resend implicit ACKs for repeated packets (assuming the original packet was sent with HOP_RELIABLE) - * this way if an implicit ACK is dropped and a packet is resent we'll rebroadcast again. - * Resending real ACKs is omitted, as you might receive a packet multiple times due to flooding and - * flooding this ACK back to the original sender already adds redundancy. */ + * this way if an implicit ACK is dropped and a packet is resent we'll rebroadcast again. + * Resending real ACKs is omitted, as you might receive a packet multiple times due to flooding and + * flooding this ACK back to the original sender already adds redundancy. */ if (wasSeenRecently(p, false) && p->hop_limit == HOP_RELIABLE && !MeshModule::currentReply && p->to != nodeDB.getNodeNum()) { // retransmission on broadcast has hop_limit still equal to HOP_RELIABLE LOG_DEBUG("Resending implicit ack for a repeated floodmsg\n"); @@ -88,12 +88,11 @@ void ReliableRouter::sniffReceived(const MeshPacket *p, const Routing *c) if (p->want_ack) { if (MeshModule::currentReply) LOG_DEBUG("Some other module has replied to this message, no need for a 2nd ack\n"); + else if (p->which_payload_variant == MeshPacket_decoded_tag) + sendAckNak(Routing_Error_NONE, getFrom(p), p->id, p->channel); else - if (p->which_payload_variant == MeshPacket_decoded_tag) - sendAckNak(Routing_Error_NONE, getFrom(p), p->id, p->channel); - else - // Send a 'NO_CHANNEL' error on the primary channel if want_ack packet destined for us cannot be decoded - sendAckNak(Routing_Error_NO_CHANNEL, getFrom(p), p->id, channels.getPrimaryIndex()); + // Send a 'NO_CHANNEL' error on the primary channel if want_ack packet destined for us cannot be decoded + sendAckNak(Routing_Error_NO_CHANNEL, getFrom(p), p->id, channels.getPrimaryIndex()); } // We consider an ack to be either a !routing packet with a request ID or a routing packet with !error diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 74487588b..e1643e206 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -1,8 +1,8 @@ #include "Router.h" #include "Channels.h" #include "CryptoEngine.h" -#include "NodeDB.h" #include "MeshRadio.h" +#include "NodeDB.h" #include "RTC.h" #include "configuration.h" #include "main.h" @@ -202,10 +202,10 @@ ErrorCode Router::send(MeshPacket *p) if (!config.lora.override_duty_cycle && myRegion->dutyCycle < 100) { float hourlyTxPercent = airTime->utilizationTXPercent(); if (hourlyTxPercent > myRegion->dutyCycle) { - uint8_t silentMinutes = airTime->getSilentMinutes(hourlyTxPercent, myRegion->dutyCycle); + uint8_t silentMinutes = airTime->getSilentMinutes(hourlyTxPercent, myRegion->dutyCycle); LOG_WARN("Duty cycle limit exceeded. Aborting send for now, you can send again in %d minutes.\n", silentMinutes); Routing_Error err = Routing_Error_DUTY_CYCLE_LIMIT; - if (getFrom(p) == nodeDB.getNodeNum()) { // only send NAK to API, not to the mesh + if (getFrom(p) == nodeDB.getNodeNum()) { // only send NAK to API, not to the mesh abortSendAndNak(err, p); } else { packetPool.release(p); @@ -235,21 +235,21 @@ ErrorCode Router::send(MeshPacket *p) if (p->which_payload_variant == MeshPacket_decoded_tag) { ChannelIndex chIndex = p->channel; // keep as a local because we are about to change it - bool shouldActuallyEncrypt = true; + bool shouldActuallyEncrypt = true; #if HAS_WIFI || HAS_ETHERNET - if(moduleConfig.mqtt.enabled) { + if (moduleConfig.mqtt.enabled) { // check if we should send decrypted packets to mqtt // truth table: /* mqtt_server mqtt_encryption_enabled should_encrypt - * not set 0 1 - * not set 1 1 - * set 0 0 - * set 1 1 - * - * => so we only decrypt mqtt if they have a custom mqtt server AND mqtt_encryption_enabled is FALSE - */ + * not set 0 1 + * not set 1 1 + * set 0 0 + * set 1 1 + * + * => so we only decrypt mqtt if they have a custom mqtt server AND mqtt_encryption_enabled is FALSE + */ if (*moduleConfig.mqtt.address && !moduleConfig.mqtt.encryption_enabled) { shouldActuallyEncrypt = false; @@ -330,7 +330,7 @@ bool perhapsDecode(MeshPacket *p) } else { // parsing was successful p->which_payload_variant = MeshPacket_decoded_tag; // change type to decoded - p->channel = chIndex; // change to store the index instead of the hash + p->channel = chIndex; // change to store the index instead of the hash // Decompress if needed. jm if (p->decoded.portnum == PortNum_TEXT_MESSAGE_COMPRESSED_APP) { diff --git a/src/mesh/SX1262Interface.cpp b/src/mesh/SX1262Interface.cpp index d01372802..3bd402ed1 100644 --- a/src/mesh/SX1262Interface.cpp +++ b/src/mesh/SX1262Interface.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "SX1262Interface.h" +#include "configuration.h" #include "error.h" SX1262Interface::SX1262Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, diff --git a/src/mesh/SX1268Interface.cpp b/src/mesh/SX1268Interface.cpp index 668943124..cae4bac41 100644 --- a/src/mesh/SX1268Interface.cpp +++ b/src/mesh/SX1268Interface.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "SX1268Interface.h" +#include "configuration.h" #include "error.h" SX1268Interface::SX1268Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, diff --git a/src/mesh/SX126xInterface.cpp b/src/mesh/SX126xInterface.cpp index 0e033eeb6..2fc4084f7 100644 --- a/src/mesh/SX126xInterface.cpp +++ b/src/mesh/SX126xInterface.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "SX126xInterface.h" +#include "configuration.h" #include "error.h" // Particular boards might define a different max power based on what their hardware can do @@ -7,9 +7,9 @@ #define SX126X_MAX_POWER 22 #endif -template +template SX126xInterface::SX126xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, - SPIClass &spi) + SPIClass &spi) : RadioLibInterface(cs, irq, rst, busy, spi, &lora), lora(&module) { LOG_WARN("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); @@ -18,8 +18,7 @@ SX126xInterface::SX126xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, /// Initialise the Driver transport hardware and software. /// Make sure the Driver is properly configured before calling init(). /// \return true if initialisation succeeded. -template -bool SX126xInterface::init() +template bool SX126xInterface::init() { #ifdef SX126X_POWER_EN digitalWrite(SX126X_POWER_EN, HIGH); @@ -27,7 +26,7 @@ bool SX126xInterface::init() #endif #if defined(SX126X_RXEN) && (SX126X_RXEN != RADIOLIB_NC) // set not rx or tx mode - digitalWrite(SX126X_RXEN, LOW); // Set low before becoming an output + digitalWrite(SX126X_RXEN, LOW); // Set low before becoming an output pinMode(SX126X_RXEN, OUTPUT); #endif #if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) @@ -106,8 +105,7 @@ bool SX126xInterface::init() return res == RADIOLIB_ERR_NONE; } -template -bool SX126xInterface::reconfigure() +template bool SX126xInterface::reconfigure() { RadioLibInterface::reconfigure(); @@ -156,14 +154,12 @@ bool SX126xInterface::reconfigure() return RADIOLIB_ERR_NONE; } -template -void INTERRUPT_ATTR SX126xInterface::disableInterrupt() +template void INTERRUPT_ATTR SX126xInterface::disableInterrupt() { lora.clearDio1Action(); } -template -void SX126xInterface::setStandby() +template void SX126xInterface::setStandby() { checkNotification(); // handle any pending interrupts before we force standby @@ -189,8 +185,7 @@ void SX126xInterface::setStandby() /** * Add SNR data to received messages */ -template -void SX126xInterface::addReceiveMetadata(MeshPacket *mp) +template void SX126xInterface::addReceiveMetadata(MeshPacket *mp) { // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); @@ -199,8 +194,7 @@ void SX126xInterface::addReceiveMetadata(MeshPacket *mp) /** We override to turn on transmitter power as needed. */ -template -void SX126xInterface::configHardwareForSend() +template void SX126xInterface::configHardwareForSend() { #if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) // we have RXEN/TXEN control - turn on TX power / off RX power digitalWrite(SX126X_TXEN, HIGH); @@ -215,8 +209,7 @@ void SX126xInterface::configHardwareForSend() // For power draw measurements, helpful to force radio to stay sleeping // #define SLEEP_ONLY -template -void SX126xInterface::startReceive() +template void SX126xInterface::startReceive() { #ifdef SLEEP_ONLY sleep(); @@ -244,8 +237,7 @@ void SX126xInterface::startReceive() } /** Could we send right now (i.e. either not actively receving or transmitting)? */ -template -bool SX126xInterface::isChannelActive() +template bool SX126xInterface::isChannelActive() { // check if we can detect a LoRa preamble on the current channel int16_t result; @@ -261,8 +253,7 @@ bool SX126xInterface::isChannelActive() } /** Could we send right now (i.e. either not actively receving or transmitting)? */ -template -bool SX126xInterface::isActivelyReceiving() +template bool SX126xInterface::isActivelyReceiving() { // The IRQ status will be cleared when we start our read operation. Check if we've started a header, but haven't yet // received and handled the interrupt for reading the packet/handling errors. @@ -279,8 +270,7 @@ bool SX126xInterface::isActivelyReceiving() return hasPreamble; } -template -bool SX126xInterface::sleep() +template bool SX126xInterface::sleep() { // Not keeping config is busted - next time nrf52 board boots lora sending fails tcxo related? - see datasheet // \todo Display actual typename of the adapter, not just `SX126x` diff --git a/src/mesh/SX126xInterface.h b/src/mesh/SX126xInterface.h index b0e5d9a32..9a77ab70f 100644 --- a/src/mesh/SX126xInterface.h +++ b/src/mesh/SX126xInterface.h @@ -6,8 +6,7 @@ * \brief Adapter for SX126x radio family. Implements common logic for child classes. * \tparam T RadioLib module type for SX126x: SX1262, SX1268. */ -template -class SX126xInterface : public RadioLibInterface +template class SX126xInterface : public RadioLibInterface { public: SX126xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, SPIClass &spi); @@ -28,11 +27,10 @@ class SX126xInterface : public RadioLibInterface bool isIRQPending() override { return lora.getIrqStatus() != 0; } protected: - float currentLimit = 140; // Higher OCP limit for SX126x PA /** - * Specific module instance + * Specific module instance */ T lora; diff --git a/src/mesh/SX1280Interface.cpp b/src/mesh/SX1280Interface.cpp index 7fc6b45e1..e19e3e573 100644 --- a/src/mesh/SX1280Interface.cpp +++ b/src/mesh/SX1280Interface.cpp @@ -1,5 +1,5 @@ -#include "configuration.h" #include "SX1280Interface.h" +#include "configuration.h" #include "error.h" SX1280Interface::SX1280Interface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, diff --git a/src/mesh/SX1280Interface.h b/src/mesh/SX1280Interface.h index 190ca3cf4..0c905cd12 100644 --- a/src/mesh/SX1280Interface.h +++ b/src/mesh/SX1280Interface.h @@ -6,7 +6,6 @@ * Our adapter for SX1280 radios */ - class SX1280Interface : public SX128xInterface { public: diff --git a/src/mesh/SX128xInterface.cpp b/src/mesh/SX128xInterface.cpp index 0fa77575f..a8a1b7240 100644 --- a/src/mesh/SX128xInterface.cpp +++ b/src/mesh/SX128xInterface.cpp @@ -1,16 +1,16 @@ -#include "configuration.h" #include "SX128xInterface.h" -#include "mesh/NodeDB.h" +#include "configuration.h" #include "error.h" +#include "mesh/NodeDB.h" // Particular boards might define a different max power based on what their hardware can do #ifndef SX128X_MAX_POWER #define SX128X_MAX_POWER 13 #endif -template +template SX128xInterface::SX128xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, - SPIClass &spi) + SPIClass &spi) : RadioLibInterface(cs, irq, rst, busy, spi, &lora), lora(&module) { } @@ -18,21 +18,20 @@ SX128xInterface::SX128xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, /// Initialise the Driver transport hardware and software. /// Make sure the Driver is properly configured before calling init(). /// \return true if initialisation succeeded. -template -bool SX128xInterface::init() +template bool SX128xInterface::init() { #ifdef SX128X_POWER_EN digitalWrite(SX128X_POWER_EN, HIGH); pinMode(SX128X_POWER_EN, OUTPUT); #endif - + #ifdef RF95_FAN_EN pinMode(RF95_FAN_EN, OUTPUT); digitalWrite(RF95_FAN_EN, 1); #endif - + #if defined(SX128X_RXEN) && (SX128X_RXEN != RADIOLIB_NC) // set not rx or tx mode - digitalWrite(SX128X_RXEN, LOW); // Set low before becoming an output + digitalWrite(SX128X_RXEN, LOW); // Set low before becoming an output pinMode(SX128X_RXEN, OUTPUT); #endif #if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) @@ -56,7 +55,7 @@ bool SX128xInterface::init() // \todo Display actual typename of the adapter, not just `SX128x` LOG_INFO("SX128x init result %d\n", res); - if((config.lora.region != Config_LoRaConfig_RegionCode_LORA_24) && (res == RADIOLIB_ERR_INVALID_FREQUENCY)) { + if ((config.lora.region != Config_LoRaConfig_RegionCode_LORA_24) && (res == RADIOLIB_ERR_INVALID_FREQUENCY)) { LOG_WARN("Radio chip only supports 2.4GHz LoRa. Adjusting Region and rebooting.\n"); config.lora.region = Config_LoRaConfig_RegionCode_LORA_24; nodeDB.saveToDisk(SEGMENT_CONFIG); @@ -70,9 +69,9 @@ bool SX128xInterface::init() #endif } - LOG_INFO("Frequency set to %f\n", getFreq()); - LOG_INFO("Bandwidth set to %f\n", bw); - LOG_INFO("Power output set to %d\n", power); + LOG_INFO("Frequency set to %f\n", getFreq()); + LOG_INFO("Bandwidth set to %f\n", bw); + LOG_INFO("Power output set to %d\n", power); if (res == RADIOLIB_ERR_NONE) res = lora.setCRC(2); @@ -83,8 +82,7 @@ bool SX128xInterface::init() return res == RADIOLIB_ERR_NONE; } -template -bool SX128xInterface::reconfigure() +template bool SX128xInterface::reconfigure() { RadioLibInterface::reconfigure(); @@ -130,23 +128,20 @@ bool SX128xInterface::reconfigure() return RADIOLIB_ERR_NONE; } -template -void INTERRUPT_ATTR SX128xInterface::disableInterrupt() +template void INTERRUPT_ATTR SX128xInterface::disableInterrupt() { lora.clearDio1Action(); } -template -bool SX128xInterface::wideLora() +template bool SX128xInterface::wideLora() { return true; } -template -void SX128xInterface::setStandby() +template void SX128xInterface::setStandby() { checkNotification(); // handle any pending interrupts before we force standby - + int err = lora.standby(); if (err != RADIOLIB_ERR_NONE) @@ -169,8 +164,7 @@ void SX128xInterface::setStandby() /** * Add SNR data to received messages */ -template -void SX128xInterface::addReceiveMetadata(MeshPacket *mp) +template void SX128xInterface::addReceiveMetadata(MeshPacket *mp) { // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); @@ -179,8 +173,7 @@ void SX128xInterface::addReceiveMetadata(MeshPacket *mp) /** We override to turn on transmitter power as needed. */ -template -void SX128xInterface::configHardwareForSend() +template void SX128xInterface::configHardwareForSend() { #if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) // we have RXEN/TXEN control - turn on TX power / off RX power digitalWrite(SX128X_TXEN, HIGH); @@ -195,8 +188,7 @@ void SX128xInterface::configHardwareForSend() // For power draw measurements, helpful to force radio to stay sleeping // #define SLEEP_ONLY -template -void SX128xInterface::startReceive() +template void SX128xInterface::startReceive() { #ifdef SLEEP_ONLY sleep(); @@ -210,7 +202,7 @@ void SX128xInterface::startReceive() #if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) digitalWrite(SX128X_TXEN, LOW); #endif - + int err = lora.startReceive(); assert(err == RADIOLIB_ERR_NONE); @@ -223,33 +215,30 @@ void SX128xInterface::startReceive() } /** Could we send right now (i.e. either not actively receving or transmitting)? */ -template -bool SX128xInterface::isChannelActive() +template bool SX128xInterface::isChannelActive() { // check if we can detect a LoRa preamble on the current channel int16_t result; - setStandby(); + setStandby(); result = lora.scanChannel(); - if (result == RADIOLIB_PREAMBLE_DETECTED) + if (result == RADIOLIB_PREAMBLE_DETECTED) return true; - + assert(result != RADIOLIB_ERR_WRONG_MODEM); - + return false; } /** Could we send right now (i.e. either not actively receving or transmitting)? */ -template -bool SX128xInterface::isActivelyReceiving() +template bool SX128xInterface::isActivelyReceiving() { uint16_t irq = lora.getIrqStatus(); bool hasPreamble = (irq & RADIOLIB_SX128X_IRQ_HEADER_VALID); return hasPreamble; } -template -bool SX128xInterface::sleep() +template bool SX128xInterface::sleep() { // Not keeping config is busted - next time nrf52 board boots lora sending fails tcxo related? - see datasheet // \todo Display actual typename of the adapter, not just `SX128x` diff --git a/src/mesh/SX128xInterface.h b/src/mesh/SX128xInterface.h index 2010a65c4..6028ed992 100644 --- a/src/mesh/SX128xInterface.h +++ b/src/mesh/SX128xInterface.h @@ -6,8 +6,7 @@ * \brief Adapter for SX128x radio family. Implements common logic for child classes. * \tparam T RadioLib module type for SX128x: SX1280. */ -template -class SX128xInterface : public RadioLibInterface +template class SX128xInterface : public RadioLibInterface { public: SX128xInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, SPIClass &spi); @@ -30,9 +29,8 @@ class SX128xInterface : public RadioLibInterface bool isIRQPending() override { return lora.getIrqStatus() != 0; } protected: - /** - * Specific module instance + * Specific module instance */ T lora; diff --git a/src/mesh/StreamAPI.cpp b/src/mesh/StreamAPI.cpp index 9be24cac9..b3ffa1682 100644 --- a/src/mesh/StreamAPI.cpp +++ b/src/mesh/StreamAPI.cpp @@ -27,15 +27,16 @@ int32_t StreamAPI::readStream() } else { while (stream->available()) { // Currently we never want to block int cInt = stream->read(); - if(cInt < 0) - break; // We ran out of characters (even though available said otherwise) - this can happen on rf52 adafruit arduino + if (cInt < 0) + break; // We ran out of characters (even though available said otherwise) - this can happen on rf52 adafruit + // arduino - uint8_t c = (uint8_t) cInt; + uint8_t c = (uint8_t)cInt; // Use the read pointer for a little state machine, first look for framing, then length bytes, then payload size_t ptr = rxPtr; - rxPtr++; // assume we will probably advance the rxPtr + rxPtr++; // assume we will probably advance the rxPtr rxBuf[ptr] = c; // store all bytes (including framing) // console->printf("rxPtr %d ptr=%d c=0x%x\n", rxPtr, ptr, c); @@ -58,9 +59,9 @@ int32_t StreamAPI::readStream() rxPtr = 0; // length is bogus, restart search for framing } - if (rxPtr != 0) // Is packet still considered 'good'? + if (rxPtr != 0) // Is packet still considered 'good'? if (ptr + 1 >= len + HEADER_LEN) { // have we received all of the payload? - rxPtr = 0; // start over again on the next packet + rxPtr = 0; // start over again on the next packet // If we didn't just fail the packet and we now have the right # of bytes, parse it handleToRadio(rxBuf + HEADER_LEN, len); diff --git a/src/mesh/TypedQueue.h b/src/mesh/TypedQueue.h index d923a40b0..721eec2c0 100644 --- a/src/mesh/TypedQueue.h +++ b/src/mesh/TypedQueue.h @@ -19,10 +19,7 @@ template class TypedQueue concurrency::OSThread *reader = NULL; public: - explicit TypedQueue(int maxElements) : h(xQueueCreate(maxElements, sizeof(T))) - { - assert(h); - } + explicit TypedQueue(int maxElements) : h(xQueueCreate(maxElements, sizeof(T))) { assert(h); } ~TypedQueue() { vQueueDelete(h); } diff --git a/src/mesh/api/ServerAPI.cpp b/src/mesh/api/ServerAPI.cpp index e35455063..140567ad2 100644 --- a/src/mesh/api/ServerAPI.cpp +++ b/src/mesh/api/ServerAPI.cpp @@ -2,34 +2,30 @@ #include "configuration.h" #include -template +template ServerAPI::ServerAPI(T &_client) : StreamAPI(&client), concurrency::OSThread("ServerAPI"), client(_client) { LOG_INFO("Incoming wifi connection\n"); } -template -ServerAPI::~ServerAPI() +template ServerAPI::~ServerAPI() { client.stop(); } -template -void ServerAPI::close() +template void ServerAPI::close() { client.stop(); // drop tcp connection StreamAPI::close(); } /// Check the current underlying physical link to see if the client is currently connected -template -bool ServerAPI::checkIsConnected() +template bool ServerAPI::checkIsConnected() { return client.connected(); } -template -int32_t ServerAPI::runOnce() +template int32_t ServerAPI::runOnce() { if (client.connected()) { return StreamAPI::runOncePart(); @@ -40,17 +36,14 @@ int32_t ServerAPI::runOnce() } } -template -APIServerPort::APIServerPort(int port) : U(port), concurrency::OSThread("ApiServer") {} +template APIServerPort::APIServerPort(int port) : U(port), concurrency::OSThread("ApiServer") {} -template -void APIServerPort::init() +template void APIServerPort::init() { U::begin(); } -template -int32_t APIServerPort::runOnce() +template int32_t APIServerPort::runOnce() { auto client = U::available(); if (client) { diff --git a/src/mesh/api/ServerAPI.h b/src/mesh/api/ServerAPI.h index 174aa774f..dd2a767c9 100644 --- a/src/mesh/api/ServerAPI.h +++ b/src/mesh/api/ServerAPI.h @@ -6,8 +6,7 @@ * Provides both debug printing and, if the client starts sending protobufs to us, switches to send/receive protobufs * (and starts dropping debug printing - FIXME, eventually those prints should be encapsulated in protobufs). */ -template -class ServerAPI : public StreamAPI, private concurrency::OSThread +template class ServerAPI : public StreamAPI, private concurrency::OSThread { private: T client; @@ -34,8 +33,7 @@ class ServerAPI : public StreamAPI, private concurrency::OSThread /** * Listens for incoming connections and does accepts and creates instances of WiFiServerAPI as needed */ -template -class APIServerPort : public U, private concurrency::OSThread +template class APIServerPort : public U, private concurrency::OSThread { /** The currently open port * diff --git a/src/mesh/api/WiFiServerAPI.h b/src/mesh/api/WiFiServerAPI.h index 279ee0f3f..11b494d23 100644 --- a/src/mesh/api/WiFiServerAPI.h +++ b/src/mesh/api/WiFiServerAPI.h @@ -9,8 +9,8 @@ */ class WiFiServerAPI : public ServerAPI { - public: - explicit WiFiServerAPI(WiFiClient &_client); + public: + explicit WiFiServerAPI(WiFiClient &_client); }; /** @@ -18,8 +18,8 @@ class WiFiServerAPI : public ServerAPI */ class WiFiServerPort : public APIServerPort { - public: - explicit WiFiServerPort(int port); + public: + explicit WiFiServerPort(int port); }; -void initApiServer(int port=4403); +void initApiServer(int port = 4403); diff --git a/src/mesh/api/ethServerAPI.h b/src/mesh/api/ethServerAPI.h index 36f363f70..59673a684 100644 --- a/src/mesh/api/ethServerAPI.h +++ b/src/mesh/api/ethServerAPI.h @@ -9,8 +9,8 @@ */ class ethServerAPI : public ServerAPI { - public: - explicit ethServerAPI(EthernetClient &_client); + public: + explicit ethServerAPI(EthernetClient &_client); }; /** @@ -18,8 +18,8 @@ class ethServerAPI : public ServerAPI */ class ethServerPort : public APIServerPort { - public: - explicit ethServerPort(int port); + public: + explicit ethServerPort(int port); }; -void initApiServer(int port=4403); +void initApiServer(int port = 4403); diff --git a/src/mesh/compression/unishox2.c b/src/mesh/compression/unishox2.c index 2d6c60d75..1632f970a 100644 --- a/src/mesh/compression/unishox2.c +++ b/src/mesh/compression/unishox2.c @@ -25,11 +25,11 @@ * defined in unishox2.h */ +#include +#include +#include #include #include -#include -#include -#include #include "unishox2.h" @@ -37,18 +37,16 @@ typedef unsigned char uint8_t; /// possible horizontal sets and states -enum {USX_ALPHA = 0, USX_SYM, USX_NUM, USX_DICT, USX_DELTA, USX_NUM_TEMP}; +enum { USX_ALPHA = 0, USX_SYM, USX_NUM, USX_DICT, USX_DELTA, USX_NUM_TEMP }; -/// This 2D array has the characters for the sets USX_ALPHA, USX_SYM and USX_NUM. Where a character cannot fit into a uint8_t, 0 is used and handled in code. -uint8_t usx_sets[][28] = {{ 0, ' ', 'e', 't', 'a', 'o', 'i', 'n', - 's', 'r', 'l', 'c', 'd', 'h', 'u', 'p', 'm', 'b', - 'g', 'w', 'f', 'y', 'v', 'k', 'q', 'j', 'x', 'z'}, - {'"', '{', '}', '_', '<', '>', ':', '\n', - 0, '[', ']', '\\', ';', '\'', '\t', '@', '*', '&', - '?', '!', '^', '|', '\r', '~', '`', 0, 0, 0}, - { 0, ',', '.', '0', '1', '9', '2', '5', '-', - '/', '3', '4', '6', '7', '8', '(', ')', ' ', - '=', '+', '$', '%', '#', 0, 0, 0, 0, 0}}; +/// This 2D array has the characters for the sets USX_ALPHA, USX_SYM and USX_NUM. Where a character cannot fit into a uint8_t, 0 +/// is used and handled in code. +uint8_t usx_sets[][28] = {{0, ' ', 'e', 't', 'a', 'o', 'i', 'n', 's', 'r', 'l', 'c', 'd', 'h', + 'u', 'p', 'm', 'b', 'g', 'w', 'f', 'y', 'v', 'k', 'q', 'j', 'x', 'z'}, + {'"', '{', '}', '_', '<', '>', ':', '\n', 0, '[', ']', '\\', ';', '\'', + '\t', '@', '*', '&', '?', '!', '^', '|', '\r', '~', '`', 0, 0, 0}, + {0, ',', '.', '0', '1', '9', '2', '5', '-', '/', '3', '4', '6', '7', + '8', '(', ')', ' ', '=', '+', '$', '%', '#', 0, 0, 0, 0, 0}}; /// Stores position of letter in usx_sets. /// First 3 bits - position in usx_hcodes @@ -56,18 +54,14 @@ uint8_t usx_sets[][28] = {{ 0, ' ', 'e', 't', 'a', 'o', 'i', 'n', uint8_t usx_code_94[94]; /// Vertical codes starting from the MSB -uint8_t usx_vcodes[] = { 0x00, 0x40, 0x60, 0x80, 0x90, 0xA0, 0xB0, - 0xC0, 0xD0, 0xD8, 0xE0, 0xE4, 0xE8, 0xEC, - 0xEE, 0xF0, 0xF2, 0xF4, 0xF6, 0xF7, 0xF8, - 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF }; +uint8_t usx_vcodes[] = {0x00, 0x40, 0x60, 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xD8, 0xE0, 0xE4, 0xE8, 0xEC, + 0xEE, 0xF0, 0xF2, 0xF4, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF}; /// Length of each veritical code -uint8_t usx_vcode_lens[] = { 2, 3, 3, 4, 4, 4, 4, - 4, 5, 5, 6, 6, 6, 7, - 7, 7, 7, 7, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8 }; +uint8_t usx_vcode_lens[] = {2, 3, 3, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; -/// Vertical Codes and Set number for frequent sequences in sets USX_SYM and USX_NUM. First 3 bits indicate set (USX_SYM/USX_NUM) and rest are vcode positions +/// Vertical Codes and Set number for frequent sequences in sets USX_SYM and USX_NUM. First 3 bits indicate set (USX_SYM/USX_NUM) +/// and rest are vcode positions uint8_t usx_freq_codes[] = {(1 << 5) + 25, (1 << 5) + 26, (1 << 5) + 27, (2 << 5) + 23, (2 << 5) + 24, (2 << 5) + 25}; /// Not used @@ -89,7 +83,7 @@ const int UTF8_PREFIX[] = {0xC0, 0xE0, 0xF0}; /// Set (USX_NUM - 1) and vertical code (22) for encoding \\r #define CR_CODE ((1 << 5) + 22) /// Set (USX_NUM - 1) and vertical code (14) for encoding \\t -#define TAB_CODE ((1 << 5) + 14) +#define TAB_CODE ((1 << 5) + 14) /// Set (USX_NUM - 2) and vertical code (17) for space character when it appears in USX_NUM state \\r #define NUM_SPC_CODE ((2 << 5) + 17) @@ -122,21 +116,22 @@ uint8_t is_inited = 0; /// Fills the usx_code_94 94 letter array based on sets of characters at usx_sets \n /// For each element in usx_code_94, first 3 msb bits is set (USX_ALPHA / USX_SYM / USX_NUM) \n /// and the rest 5 bits indicate the vertical position in the corresponding set -void init_coder() { - if (is_inited) - return; - memset(usx_code_94, '\0', sizeof(usx_code_94)); - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 28; j++) { - uint8_t c = usx_sets[i][j]; - if (c > 32) { - usx_code_94[c - USX_OFFSET_94] = (i << 5) + j; - if (c >= 'a' && c <= 'z') - usx_code_94[c - USX_OFFSET_94 - ('a' - 'A')] = (i << 5) + j; - } +void init_coder() +{ + if (is_inited) + return; + memset(usx_code_94, '\0', sizeof(usx_code_94)); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 28; j++) { + uint8_t c = usx_sets[i][j]; + if (c > 32) { + usx_code_94[c - USX_OFFSET_94] = (i << 5) + j; + if (c >= 'a' && c <= 'z') + usx_code_94[c - USX_OFFSET_94 - ('a' - 'A')] = (i << 5) + j; + } + } } - } - is_inited = 1; + is_inited = 1; } /// Mask for retrieving each code to be encoded according to its length @@ -145,79 +140,84 @@ unsigned int usx_mask[] = {0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF}; /// Appends specified number of bits to the output (out) \n /// If maximum limit (olen) is reached, -1 is returned \n /// Otherwise clen bits in code are appended to out starting with MSB -int append_bits(char *out, int olen, int ol, uint8_t code, int clen) { +int append_bits(char *out, int olen, int ol, uint8_t code, int clen) +{ + // printf("%d,%x,%d,%d\n", ol, code, clen, state); - //printf("%d,%x,%d,%d\n", ol, code, clen, state); + while (clen > 0) { + int oidx; + unsigned char a_byte; - while (clen > 0) { - int oidx; - unsigned char a_byte; - - uint8_t cur_bit = ol % 8; - uint8_t blen = clen; - a_byte = code & usx_mask[blen - 1]; - a_byte >>= cur_bit; - if (blen + cur_bit > 8) - blen = (8 - cur_bit); - oidx = ol / 8; - if (oidx < 0 || olen <= oidx) - return -1; - if (cur_bit == 0) - out[oidx] = a_byte; - else - out[oidx] |= a_byte; - code <<= blen; - ol += blen; - clen -= blen; - } - return ol; + uint8_t cur_bit = ol % 8; + uint8_t blen = clen; + a_byte = code & usx_mask[blen - 1]; + a_byte >>= cur_bit; + if (blen + cur_bit > 8) + blen = (8 - cur_bit); + oidx = ol / 8; + if (oidx < 0 || olen <= oidx) + return -1; + if (cur_bit == 0) + out[oidx] = a_byte; + else + out[oidx] |= a_byte; + code <<= blen; + ol += blen; + clen -= blen; + } + return ol; } /// This is a safe call to append_bits() making sure it does not write past olen -#define SAFE_APPEND_BITS(exp) do { \ - const int newidx = (exp); \ - if (newidx < 0) return newidx; \ -} while (0) +#define SAFE_APPEND_BITS(exp) \ + do { \ + const int newidx = (exp); \ + if (newidx < 0) \ + return newidx; \ + } while (0) /// Appends switch code to out depending on the state (USX_DELTA or other) -int append_switch_code(char *out, int olen, int ol, uint8_t state) { - if (state == USX_DELTA) { - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, UNI_STATE_SPL_CODE, UNI_STATE_SPL_CODE_LEN)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, UNI_STATE_SW_CODE, UNI_STATE_SW_CODE_LEN)); - } else - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, SW_CODE, SW_CODE_LEN)); - return ol; +int append_switch_code(char *out, int olen, int ol, uint8_t state) +{ + if (state == USX_DELTA) { + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, UNI_STATE_SPL_CODE, UNI_STATE_SPL_CODE_LEN)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, UNI_STATE_SW_CODE, UNI_STATE_SW_CODE_LEN)); + } else + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, SW_CODE, SW_CODE_LEN)); + return ol; } /// Appends given horizontal and veritical code bits to out -int append_code(char *out, int olen, int ol, uint8_t code, uint8_t *state, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) { - uint8_t hcode = code >> 5; - uint8_t vcode = code & 0x1F; - if (!usx_hcode_lens[hcode] && hcode != USX_ALPHA) - return ol; - switch (hcode) { +int append_code(char *out, int olen, int ol, uint8_t code, uint8_t *state, const uint8_t usx_hcodes[], + const uint8_t usx_hcode_lens[]) +{ + uint8_t hcode = code >> 5; + uint8_t vcode = code & 0x1F; + if (!usx_hcode_lens[hcode] && hcode != USX_ALPHA) + return ol; + switch (hcode) { case USX_ALPHA: - if (*state != USX_ALPHA) { - SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, *state)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); - *state = USX_ALPHA; - } - break; + if (*state != USX_ALPHA) { + SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, *state)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + *state = USX_ALPHA; + } + break; case USX_SYM: - SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, *state)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_SYM], usx_hcode_lens[USX_SYM])); - break; - case USX_NUM: - if (*state != USX_NUM) { SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, *state)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_NUM], usx_hcode_lens[USX_NUM])); - if (usx_sets[hcode][vcode] >= '0' && usx_sets[hcode][vcode] <= '9') - *state = USX_NUM; - } - } - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_vcodes[vcode], usx_vcode_lens[vcode])); - return ol; + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_SYM], usx_hcode_lens[USX_SYM])); + break; + case USX_NUM: + if (*state != USX_NUM) { + SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, *state)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_NUM], usx_hcode_lens[USX_NUM])); + if (usx_sets[hcode][vcode] >= '0' && usx_sets[hcode][vcode] <= '9') + *state = USX_NUM; + } + } + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_vcodes[vcode], usx_vcode_lens[vcode])); + return ol; } /// Length of bits used to represent count for each level @@ -227,21 +227,22 @@ const int32_t count_adder[5] = {4, 20, 148, 2196, 67732}; /// Codes used to specify the level that the count belongs to const uint8_t count_codes[] = {0x01, 0x82, 0xC3, 0xE4, 0xF4}; /// Encodes given count to out -int encodeCount(char *out, int olen, int ol, int count) { - // First five bits are code and Last three bits of codes represent length - for (int i = 0; i < 5; i++) { - if (count < count_adder[i]) { - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, (count_codes[i] & 0xF8), count_codes[i] & 0x07)); - uint16_t count16 = (count - (i ? count_adder[i - 1] : 0)) << (16 - count_bit_lens[i]); - if (count_bit_lens[i] > 8) { - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, count16 >> 8, 8)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, count16 & 0xFF, count_bit_lens[i] - 8)); - } else - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, count16 >> 8, count_bit_lens[i])); - return ol; +int encodeCount(char *out, int olen, int ol, int count) +{ + // First five bits are code and Last three bits of codes represent length + for (int i = 0; i < 5; i++) { + if (count < count_adder[i]) { + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, (count_codes[i] & 0xF8), count_codes[i] & 0x07)); + uint16_t count16 = (count - (i ? count_adder[i - 1] : 0)) << (16 - count_bit_lens[i]); + if (count_bit_lens[i] > 8) { + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, count16 >> 8, 8)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, count16 & 0xFF, count_bit_lens[i] - 8)); + } else + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, count16 >> 8, count_bit_lens[i])); + return ol; + } } - } - return ol; + return ol; } /// Length of bits used to represent delta code for each level @@ -250,80 +251,78 @@ const uint8_t uni_bit_len[5] = {6, 12, 14, 16, 21}; const int32_t uni_adder[5] = {0, 64, 4160, 20544, 86080}; /// Encodes the unicode code point given by code to out. prev_code is used to calculate the delta -int encodeUnicode(char *out, int olen, int ol, int32_t code, int32_t prev_code) { - // First five bits are code and Last three bits of codes represent length - //const uint8_t codes[8] = {0x00, 0x42, 0x83, 0xA3, 0xC3, 0xE4, 0xF5, 0xFD}; - const uint8_t codes[6] = {0x01, 0x82, 0xC3, 0xE4, 0xF5, 0xFD}; - int32_t till = 0; - int32_t diff = code - prev_code; - if (diff < 0) - diff = -diff; - //printf("%ld, ", code); - //printf("Diff: %d\n", diff); - for (int i = 0; i < 5; i++) { - till += (1 << uni_bit_len[i]); - if (diff < till) { - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, (codes[i] & 0xF8), codes[i] & 0x07)); - //if (diff) { - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, prev_code > code ? 0x80 : 0, 1)); - int32_t val = diff - uni_adder[i]; - //printf("Val: %d\n", val); - if (uni_bit_len[i] > 16) { - val <<= (24 - uni_bit_len[i]); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val >> 16, 8)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, (val >> 8) & 0xFF, 8)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val & 0xFF, uni_bit_len[i] - 16)); - } else - if (uni_bit_len[i] > 8) { - val <<= (16 - uni_bit_len[i]); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val >> 8, 8)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val & 0xFF, uni_bit_len[i] - 8)); - } else { - val <<= (8 - uni_bit_len[i]); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val & 0xFF, uni_bit_len[i])); +int encodeUnicode(char *out, int olen, int ol, int32_t code, int32_t prev_code) +{ + // First five bits are code and Last three bits of codes represent length + // const uint8_t codes[8] = {0x00, 0x42, 0x83, 0xA3, 0xC3, 0xE4, 0xF5, 0xFD}; + const uint8_t codes[6] = {0x01, 0x82, 0xC3, 0xE4, 0xF5, 0xFD}; + int32_t till = 0; + int32_t diff = code - prev_code; + if (diff < 0) + diff = -diff; + // printf("%ld, ", code); + // printf("Diff: %d\n", diff); + for (int i = 0; i < 5; i++) { + till += (1 << uni_bit_len[i]); + if (diff < till) { + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, (codes[i] & 0xF8), codes[i] & 0x07)); + // if (diff) { + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, prev_code > code ? 0x80 : 0, 1)); + int32_t val = diff - uni_adder[i]; + // printf("Val: %d\n", val); + if (uni_bit_len[i] > 16) { + val <<= (24 - uni_bit_len[i]); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val >> 16, 8)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, (val >> 8) & 0xFF, 8)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val & 0xFF, uni_bit_len[i] - 16)); + } else if (uni_bit_len[i] > 8) { + val <<= (16 - uni_bit_len[i]); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val >> 8, 8)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val & 0xFF, uni_bit_len[i] - 8)); + } else { + val <<= (8 - uni_bit_len[i]); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, val & 0xFF, uni_bit_len[i])); + } + return ol; } - return ol; } - } - return ol; + return ol; } /// Reads UTF-8 character from in. Also returns the number of bytes occupied by the UTF-8 character in utf8len -int32_t readUTF8(const char *in, int len, int l, int *utf8len) { - int32_t ret = 0; - if (l < (len - 1) && (in[l] & 0xE0) == 0xC0 && (in[l + 1] & 0xC0) == 0x80) { - *utf8len = 2; - ret = (in[l] & 0x1F); - ret <<= 6; - ret += (in[l + 1] & 0x3F); - if (ret < 0x80) - ret = 0; - } else - if (l < (len - 2) && (in[l] & 0xF0) == 0xE0 && (in[l + 1] & 0xC0) == 0x80 - && (in[l + 2] & 0xC0) == 0x80) { - *utf8len = 3; - ret = (in[l] & 0x0F); - ret <<= 6; - ret += (in[l + 1] & 0x3F); - ret <<= 6; - ret += (in[l + 2] & 0x3F); - if (ret < 0x0800) - ret = 0; - } else - if (l < (len - 3) && (in[l] & 0xF8) == 0xF0 && (in[l + 1] & 0xC0) == 0x80 - && (in[l + 2] & 0xC0) == 0x80 && (in[l + 3] & 0xC0) == 0x80) { - *utf8len = 4; - ret = (in[l] & 0x07); - ret <<= 6; - ret += (in[l + 1] & 0x3F); - ret <<= 6; - ret += (in[l + 2] & 0x3F); - ret <<= 6; - ret += (in[l + 3] & 0x3F); - if (ret < 0x10000) - ret = 0; - } - return ret; +int32_t readUTF8(const char *in, int len, int l, int *utf8len) +{ + int32_t ret = 0; + if (l < (len - 1) && (in[l] & 0xE0) == 0xC0 && (in[l + 1] & 0xC0) == 0x80) { + *utf8len = 2; + ret = (in[l] & 0x1F); + ret <<= 6; + ret += (in[l + 1] & 0x3F); + if (ret < 0x80) + ret = 0; + } else if (l < (len - 2) && (in[l] & 0xF0) == 0xE0 && (in[l + 1] & 0xC0) == 0x80 && (in[l + 2] & 0xC0) == 0x80) { + *utf8len = 3; + ret = (in[l] & 0x0F); + ret <<= 6; + ret += (in[l + 1] & 0x3F); + ret <<= 6; + ret += (in[l + 2] & 0x3F); + if (ret < 0x0800) + ret = 0; + } else if (l < (len - 3) && (in[l] & 0xF8) == 0xF0 && (in[l + 1] & 0xC0) == 0x80 && (in[l + 2] & 0xC0) == 0x80 && + (in[l + 3] & 0xC0) == 0x80) { + *utf8len = 4; + ret = (in[l] & 0x07); + ret <<= 6; + ret += (in[l + 1] & 0x3F); + ret <<= 6; + ret += (in[l + 2] & 0x3F); + ret <<= 6; + ret += (in[l + 3] & 0x3F); + if (ret < 0x10000) + ret = 0; + } + return ret; } /// Finds the longest matching sequence from the beginning of the string. \n @@ -331,39 +330,42 @@ int32_t readUTF8(const char *in, int len, int l, int *utf8len) { /// This is also used for Unicode strings \n /// This is a crude implementation that is not optimized. Assuming only short strings \n /// are encoded, this is not much of an issue. -int matchOccurance(const char *in, int len, int l, char *out, int olen, int *ol, uint8_t *state, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) { - int j, k; - int longest_dist = 0; - int longest_len = 0; - for (j = l - NICE_LEN; j >= 0; j--) { - for (k = l; k < len && j + k - l < l; k++) { - if (in[k] != in[j + k - l]) - break; +int matchOccurance(const char *in, int len, int l, char *out, int olen, int *ol, uint8_t *state, const uint8_t usx_hcodes[], + const uint8_t usx_hcode_lens[]) +{ + int j, k; + int longest_dist = 0; + int longest_len = 0; + for (j = l - NICE_LEN; j >= 0; j--) { + for (k = l; k < len && j + k - l < l; k++) { + if (in[k] != in[j + k - l]) + break; + } + while ((((unsigned char)in[k]) >> 6) == 2) + k--; // Skip partial UTF-8 matches + // if ((in[k - 1] >> 3) == 0x1E || (in[k - 1] >> 4) == 0x0E || (in[k - 1] >> 5) == 0x06) + // k--; + if ((k - l) > (NICE_LEN - 1)) { + int match_len = k - l - NICE_LEN; + int match_dist = l - j - NICE_LEN + 1; + if (match_len > longest_len) { + longest_len = match_len; + longest_dist = match_dist; + } + } } - while ((((unsigned char) in[k]) >> 6) == 2) - k--; // Skip partial UTF-8 matches - //if ((in[k - 1] >> 3) == 0x1E || (in[k - 1] >> 4) == 0x0E || (in[k - 1] >> 5) == 0x06) - // k--; - if ((k - l) > (NICE_LEN - 1)) { - int match_len = k - l - NICE_LEN; - int match_dist = l - j - NICE_LEN + 1; - if (match_len > longest_len) { - longest_len = match_len; - longest_dist = match_dist; - } + if (longest_len) { + SAFE_APPEND_BITS(*ol = append_switch_code(out, olen, *ol, *state)); + SAFE_APPEND_BITS(*ol = append_bits(out, olen, *ol, usx_hcodes[USX_DICT], usx_hcode_lens[USX_DICT])); + // printf("Len:%d / Dist:%d/%.*s\n", longest_len, longest_dist, longest_len + NICE_LEN, in + l - longest_dist - NICE_LEN + + // 1); + SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, longest_len)); + SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, longest_dist)); + l += (longest_len + NICE_LEN); + l--; + return l; } - } - if (longest_len) { - SAFE_APPEND_BITS(*ol = append_switch_code(out, olen, *ol, *state)); - SAFE_APPEND_BITS(*ol = append_bits(out, olen, *ol, usx_hcodes[USX_DICT], usx_hcode_lens[USX_DICT])); - //printf("Len:%d / Dist:%d/%.*s\n", longest_len, longest_dist, longest_len + NICE_LEN, in + l - longest_dist - NICE_LEN + 1); - SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, longest_len)); - SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, longest_dist)); - l += (longest_len + NICE_LEN); - l--; - return l; - } - return -l; + return -l; } /// This is used only when encoding a string array @@ -372,493 +374,518 @@ int matchOccurance(const char *in, int len, int l, char *out, int olen, int *ol, /// This is also used for Unicode strings \n /// This is a crude implementation that is not optimized. Assuming only short strings \n /// are encoded, this is not much of an issue. -int matchLine(const char *in, int len, int l, char *out, int olen, int *ol, struct us_lnk_lst *prev_lines, uint8_t *state, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) { - int last_ol = *ol; - int last_len = 0; - int last_dist = 0; - int last_ctx = 0; - int line_ctr = 0; - int j = 0; - do { - int i, k; - int line_len = (int)strlen(prev_lines->data); - int limit = (line_ctr == 0 ? l : line_len); - for (; j < limit; j++) { - for (i = l, k = j; k < line_len && i < len; k++, i++) { - if (prev_lines->data[k] != in[i]) - break; - } - while ((((unsigned char) prev_lines->data[k]) >> 6) == 2) - k--; // Skip partial UTF-8 matches - if ((k - j) >= NICE_LEN) { - if (last_len) { - if (j > last_dist) - continue; - //int saving = ((k - j) - last_len) + (last_dist - j) + (last_ctx - line_ctr); - //if (saving < 0) { - // //printf("No savng: %d\n", saving); - // continue; - //} - *ol = last_ol; +int matchLine(const char *in, int len, int l, char *out, int olen, int *ol, struct us_lnk_lst *prev_lines, uint8_t *state, + const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) +{ + int last_ol = *ol; + int last_len = 0; + int last_dist = 0; + int last_ctx = 0; + int line_ctr = 0; + int j = 0; + do { + int i, k; + int line_len = (int)strlen(prev_lines->data); + int limit = (line_ctr == 0 ? l : line_len); + for (; j < limit; j++) { + for (i = l, k = j; k < line_len && i < len; k++, i++) { + if (prev_lines->data[k] != in[i]) + break; + } + while ((((unsigned char)prev_lines->data[k]) >> 6) == 2) + k--; // Skip partial UTF-8 matches + if ((k - j) >= NICE_LEN) { + if (last_len) { + if (j > last_dist) + continue; + // int saving = ((k - j) - last_len) + (last_dist - j) + (last_ctx - line_ctr); + // if (saving < 0) { + // //printf("No savng: %d\n", saving); + // continue; + // } + *ol = last_ol; + } + last_len = (k - j); + last_dist = j; + last_ctx = line_ctr; + SAFE_APPEND_BITS(*ol = append_switch_code(out, olen, *ol, *state)); + SAFE_APPEND_BITS(*ol = append_bits(out, olen, *ol, usx_hcodes[USX_DICT], usx_hcode_lens[USX_DICT])); + SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, last_len - NICE_LEN)); + SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, last_dist)); + SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, last_ctx)); + /* + if ((*ol - last_ol) > (last_len * 4)) { + last_len = 0; + *ol = last_ol; + }*/ + // printf("Len: %d, Dist: %d, Line: %d\n", last_len, last_dist, last_ctx); + j += last_len; + } } - last_len = (k - j); - last_dist = j; - last_ctx = line_ctr; - SAFE_APPEND_BITS(*ol = append_switch_code(out, olen, *ol, *state)); - SAFE_APPEND_BITS(*ol = append_bits(out, olen, *ol, usx_hcodes[USX_DICT], usx_hcode_lens[USX_DICT])); - SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, last_len - NICE_LEN)); - SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, last_dist)); - SAFE_APPEND_BITS(*ol = encodeCount(out, olen, *ol, last_ctx)); - /* - if ((*ol - last_ol) > (last_len * 4)) { - last_len = 0; - *ol = last_ol; - }*/ - //printf("Len: %d, Dist: %d, Line: %d\n", last_len, last_dist, last_ctx); - j += last_len; - } + line_ctr++; + prev_lines = prev_lines->previous; + } while (prev_lines && prev_lines->data != NULL); + if (last_len) { + l += last_len; + l--; + return l; } - line_ctr++; - prev_lines = prev_lines->previous; - } while (prev_lines && prev_lines->data != NULL); - if (last_len) { - l += last_len; - l--; - return l; - } - return -l; + return -l; } /// Returns 4 bit code assuming ch falls between '0' to '9', \n /// 'A' to 'F' or 'a' to 'f' -uint8_t getBaseCode(char ch) { - if (ch >= '0' && ch <= '9') - return (ch - '0') << 4; - else if (ch >= 'A' && ch <= 'F') - return (ch - 'A' + 10) << 4; - else if (ch >= 'a' && ch <= 'f') - return (ch - 'a' + 10) << 4; - return 0; +uint8_t getBaseCode(char ch) +{ + if (ch >= '0' && ch <= '9') + return (ch - '0') << 4; + else if (ch >= 'A' && ch <= 'F') + return (ch - 'A' + 10) << 4; + else if (ch >= 'a' && ch <= 'f') + return (ch - 'a' + 10) << 4; + return 0; } /// Enum indicating nibble type - USX_NIB_NUM means ch is a number '0' to '9', \n /// USX_NIB_HEX_LOWER means ch is between 'a' to 'f', \n /// USX_NIB_HEX_UPPER means ch is between 'A' to 'F' -enum {USX_NIB_NUM = 0, USX_NIB_HEX_LOWER, USX_NIB_HEX_UPPER, USX_NIB_NOT}; +enum { USX_NIB_NUM = 0, USX_NIB_HEX_LOWER, USX_NIB_HEX_UPPER, USX_NIB_NOT }; /// Gets 4 bit code assuming ch falls between '0' to '9', \n /// 'A' to 'F' or 'a' to 'f' -char getNibbleType(char ch) { - if (ch >= '0' && ch <= '9') - return USX_NIB_NUM; - else if (ch >= 'a' && ch <= 'f') - return USX_NIB_HEX_LOWER; - else if (ch >= 'A' && ch <= 'F') - return USX_NIB_HEX_UPPER; - return USX_NIB_NOT; +char getNibbleType(char ch) +{ + if (ch >= '0' && ch <= '9') + return USX_NIB_NUM; + else if (ch >= 'a' && ch <= 'f') + return USX_NIB_HEX_LOWER; + else if (ch >= 'A' && ch <= 'F') + return USX_NIB_HEX_UPPER; + return USX_NIB_NOT; } /// Starts coding of nibble sets -int append_nibble_escape(char *out, int olen, int ol, uint8_t state, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) { - SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_NUM], usx_hcode_lens[USX_NUM])); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, 0, 2)); - return ol; +int append_nibble_escape(char *out, int olen, int ol, uint8_t state, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) +{ + SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_NUM], usx_hcode_lens[USX_NUM])); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, 0, 2)); + return ol; } /// Returns minimum value of two longs -long min_of(long c, long i) { - return c > i ? i : c; +long min_of(long c, long i) +{ + return c > i ? i : c; } /// Appends the terminator code depending on the state, preset and whether full terminator needs to be encoded to out or not \n -int append_final_bits(char *const out, const int olen, int ol, const uint8_t state, const uint8_t is_all_upper, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) { - if (usx_hcode_lens[USX_ALPHA]) { - if (USX_NUM != state) { - // for num state, append TERM_CODE directly - // for other state, switch to Num Set first - SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_NUM], usx_hcode_lens[USX_NUM])); +int append_final_bits(char *const out, const int olen, int ol, const uint8_t state, const uint8_t is_all_upper, + const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) +{ + if (usx_hcode_lens[USX_ALPHA]) { + if (USX_NUM != state) { + // for num state, append TERM_CODE directly + // for other state, switch to Num Set first + SAFE_APPEND_BITS(ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_hcodes[USX_NUM], usx_hcode_lens[USX_NUM])); + } + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_vcodes[TERM_CODE & 0x1F], usx_vcode_lens[TERM_CODE & 0x1F])); + } else { + // preset 1, terminate at 2 or 3 SW_CODE, i.e., 4 or 6 continuous 0 bits + // see discussion: https://github.com/siara-cc/Unishox/issues/19#issuecomment-922435580 + SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, TERM_BYTE_PRESET_1, + is_all_upper ? TERM_BYTE_PRESET_1_LEN_UPPER : TERM_BYTE_PRESET_1_LEN_LOWER)); } - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, usx_vcodes[TERM_CODE & 0x1F], usx_vcode_lens[TERM_CODE & 0x1F])); - } else { - // preset 1, terminate at 2 or 3 SW_CODE, i.e., 4 or 6 continuous 0 bits - // see discussion: https://github.com/siara-cc/Unishox/issues/19#issuecomment-922435580 - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, TERM_BYTE_PRESET_1, is_all_upper ? TERM_BYTE_PRESET_1_LEN_UPPER : TERM_BYTE_PRESET_1_LEN_LOWER)); - } - // fill uint8_t with the last bit - SAFE_APPEND_BITS(ol = append_bits(out, olen, ol, (ol == 0 || out[(ol-1)/8] << ((ol-1)&7) >= 0) ? 0 : 0xFF, (8 - ol % 8) & 7)); + // fill uint8_t with the last bit + SAFE_APPEND_BITS( + ol = append_bits(out, olen, ol, (ol == 0 || out[(ol - 1) / 8] << ((ol - 1) & 7) >= 0) ? 0 : 0xFF, (8 - ol % 8) & 7)); - return ol; + return ol; } /// Macro used in the main compress function so that if the output len exceeds given maximum length (olen) it can exit -#define SAFE_APPEND_BITS2(olen, exp) do { \ - const int newidx = (exp); \ - const int __olen = (olen); \ - if (newidx < 0) return __olen >= 0 ? __olen + 1 : (1 - __olen) * 4; \ -} while (0) +#define SAFE_APPEND_BITS2(olen, exp) \ + do { \ + const int newidx = (exp); \ + const int __olen = (olen); \ + if (newidx < 0) \ + return __olen >= 0 ? __olen + 1 : (1 - __olen) * 4; \ + } while (0) // Main API function. See unishox2.h for documentation -int unishox2_compress_lines(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[], struct us_lnk_lst *prev_lines) { +int unishox2_compress_lines(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], + const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[], + struct us_lnk_lst *prev_lines) +{ - uint8_t state; + uint8_t state; - int l, ll, ol; - char c_in, c_next; - int prev_uni; - uint8_t is_upper, is_all_upper; -#if (UNISHOX_API_OUT_AND_LEN(0,1)) == 0 - const int olen = INT_MAX - 1; - const int rawolen = olen; - const uint8_t need_full_term_codes = 0; + int l, ll, ol; + char c_in, c_next; + int prev_uni; + uint8_t is_upper, is_all_upper; +#if (UNISHOX_API_OUT_AND_LEN(0, 1)) == 0 + const int olen = INT_MAX - 1; + const int rawolen = olen; + const uint8_t need_full_term_codes = 0; #else - const int rawolen = olen; - uint8_t need_full_term_codes = 0; - if (olen < 0) { - need_full_term_codes = 1; - olen *= -1; - } + const int rawolen = olen; + uint8_t need_full_term_codes = 0; + if (olen < 0) { + need_full_term_codes = 1; + olen *= -1; + } #endif - init_coder(); - ol = 0; - prev_uni = 0; - state = USX_ALPHA; - is_all_upper = 0; - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, UNISHOX_MAGIC_BITS, UNISHOX_MAGIC_BIT_LEN)); // magic bit(s) - for (l=0; l 0) { - continue; - } else if (l < 0 && ol < 0) { - return olen + 1; - } - l = -l; - } else { - l = matchOccurance(in, len, l, out, olen, &ol, &state, usx_hcodes, usx_hcode_lens); - if (l > 0) { - continue; - } else if (l < 0 && ol < 0) { - return olen + 1; - } - l = -l; - } - } - - c_in = in[l]; - if (l && len > 4 && l < (len - 4) && usx_hcode_lens[USX_NUM]) { - if (c_in == in[l - 1] && c_in == in[l + 1] && c_in == in[l + 2] && c_in == in[l + 3]) { - int rpt_count = l + 4; - while (rpt_count < len && in[rpt_count] == c_in) - rpt_count++; - rpt_count -= l; - SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, RPT_CODE, &state, usx_hcodes, usx_hcode_lens)); - SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, rpt_count - 4)); - l += rpt_count; - l--; - continue; - } - } - - if (l <= (len - 36) && usx_hcode_lens[USX_NUM]) { - if (in[l + 8] == '-' && in[l + 13] == '-' && in[l + 18] == '-' && in[l + 23] == '-') { - char hex_type = USX_NIB_NUM; - int uid_pos = l; - for (; uid_pos < l + 36; uid_pos++) { - char c_uid = in[uid_pos]; - if (c_uid == '-' && (uid_pos == 8 || uid_pos == 13 || uid_pos == 18 || uid_pos == 23)) - continue; - char nib_type = getNibbleType(c_uid); - if (nib_type == USX_NIB_NOT) - break; - if (nib_type != USX_NIB_NUM) { - if (hex_type != USX_NIB_NUM && hex_type != nib_type) - break; - hex_type = nib_type; - } - } - if (uid_pos == l + 36) { - SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, (hex_type == USX_NIB_HEX_LOWER ? 0xC0 : 0xF0), - (hex_type == USX_NIB_HEX_LOWER ? 3 : 5))); - for (uid_pos = l; uid_pos < l + 36; uid_pos++) { - char c_uid = in[uid_pos]; - if (c_uid != '-') - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, getBaseCode(c_uid), 4)); - } - //printf("GUID:\n"); - l += 35; - continue; - } - } - } - - if (l < (len - 5) && usx_hcode_lens[USX_NUM]) { - char hex_type = USX_NIB_NUM; - int hex_len = 0; - do { - char nib_type = getNibbleType(in[l + hex_len]); - if (nib_type == USX_NIB_NOT) - break; - if (nib_type != USX_NIB_NUM) { - if (hex_type != USX_NIB_NUM && hex_type != nib_type) - break; - hex_type = nib_type; - } - hex_len++; - } while (l + hex_len < len); - if (hex_len > 10 && hex_type == USX_NIB_NUM) - hex_type = USX_NIB_HEX_LOWER; - if ((hex_type == USX_NIB_HEX_LOWER || hex_type == USX_NIB_HEX_UPPER) && hex_len > 3) { - SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, (hex_type == USX_NIB_HEX_LOWER ? 0x80 : 0xE0), (hex_type == USX_NIB_HEX_LOWER ? 2 : 4))); - SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, hex_len)); - do { - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, getBaseCode(in[l++]), 4)); - } while (--hex_len); - l--; - continue; - } - } - - if (usx_templates != NULL) { - int i; - for (i = 0; i < 5; i++) { - if (usx_templates[i]) { - int rem = (int)strlen(usx_templates[i]); - int j = 0; - for (; j < rem && l + j < len; j++) { - char c_t = usx_templates[i][j]; - c_in = in[l + j]; - if (c_t == 'f' || c_t == 'F') { - if (getNibbleType(c_in) != (c_t == 'f' ? USX_NIB_HEX_LOWER : USX_NIB_HEX_UPPER) - && getNibbleType(c_in) != USX_NIB_NUM) { - break; - } - } else - if (c_t == 'r' || c_t == 't' || c_t == 'o') { - if (c_in < '0' || c_in > (c_t == 'r' ? '7' : (c_t == 't' ? '3' : '1'))) - break; - } else - if (c_t != c_in) - break; - } - if (((float)j / rem) > 0.66) { - //printf("%s\n", usx_templates[i]); - rem = rem - j; - SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, 0, 1)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, (count_codes[i] & 0xF8), count_codes[i] & 0x07)); - SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, rem)); - for (int k = 0; k < j; k++) { - char c_t = usx_templates[i][k]; - if (c_t == 'f' || c_t == 'F') - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, getBaseCode(in[l + k]), 4)); - else if (c_t == 'r' || c_t == 't' || c_t == 'o') { - c_t = (c_t == 'r' ? 3 : (c_t == 't' ? 2 : 1)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, (in[l + k] - '0') << (8 - c_t), c_t)); - } + if (usx_hcode_lens[USX_DICT] && l < (len - NICE_LEN + 1)) { + if (prev_lines) { + l = matchLine(in, len, l, out, olen, &ol, prev_lines, &state, usx_hcodes, usx_hcode_lens); + if (l > 0) { + continue; + } else if (l < 0 && ol < 0) { + return olen + 1; + } + l = -l; + } else { + l = matchOccurance(in, len, l, out, olen, &ol, &state, usx_hcodes, usx_hcode_lens); + if (l > 0) { + continue; + } else if (l < 0 && ol < 0) { + return olen + 1; + } + l = -l; } - l += j; - l--; - break; - } } - } - if (i < 5) - continue; - } - if (usx_freq_seq != NULL) { - int i; - for (i = 0; i < 6; i++) { - int seq_len = (int)strlen(usx_freq_seq[i]); - if (len - seq_len >= 0 && l <= len - seq_len) { - if (memcmp(usx_freq_seq[i], in + l, seq_len) == 0 && usx_hcode_lens[usx_freq_codes[i] >> 5]) { - SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, usx_freq_codes[i], &state, usx_hcodes, usx_hcode_lens)); - l += seq_len; - l--; - break; - } + c_in = in[l]; + if (l && len > 4 && l < (len - 4) && usx_hcode_lens[USX_NUM]) { + if (c_in == in[l - 1] && c_in == in[l + 1] && c_in == in[l + 2] && c_in == in[l + 3]) { + int rpt_count = l + 4; + while (rpt_count < len && in[rpt_count] == c_in) + rpt_count++; + rpt_count -= l; + SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, RPT_CODE, &state, usx_hcodes, usx_hcode_lens)); + SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, rpt_count - 4)); + l += rpt_count; + l--; + continue; + } } - } - if (i < 6) - continue; - } - c_in = in[l]; + if (l <= (len - 36) && usx_hcode_lens[USX_NUM]) { + if (in[l + 8] == '-' && in[l + 13] == '-' && in[l + 18] == '-' && in[l + 23] == '-') { + char hex_type = USX_NIB_NUM; + int uid_pos = l; + for (; uid_pos < l + 36; uid_pos++) { + char c_uid = in[uid_pos]; + if (c_uid == '-' && (uid_pos == 8 || uid_pos == 13 || uid_pos == 18 || uid_pos == 23)) + continue; + char nib_type = getNibbleType(c_uid); + if (nib_type == USX_NIB_NOT) + break; + if (nib_type != USX_NIB_NUM) { + if (hex_type != USX_NIB_NUM && hex_type != nib_type) + break; + hex_type = nib_type; + } + } + if (uid_pos == l + 36) { + SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, (hex_type == USX_NIB_HEX_LOWER ? 0xC0 : 0xF0), + (hex_type == USX_NIB_HEX_LOWER ? 3 : 5))); + for (uid_pos = l; uid_pos < l + 36; uid_pos++) { + char c_uid = in[uid_pos]; + if (c_uid != '-') + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, getBaseCode(c_uid), 4)); + } + // printf("GUID:\n"); + l += 35; + continue; + } + } + } - is_upper = 0; - if (c_in >= 'A' && c_in <= 'Z') - is_upper = 1; - else { - if (is_all_upper) { - is_all_upper = 0; - SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); - state = USX_ALPHA; - } - } - if (is_upper && !is_all_upper) { - if (state == USX_NUM) { - SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); - state = USX_ALPHA; - } - SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); - if (state == USX_DELTA) { - state = USX_ALPHA; - SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); - } - } - c_next = 0; - if (l+1 < len) - c_next = in[l+1]; + if (l < (len - 5) && usx_hcode_lens[USX_NUM]) { + char hex_type = USX_NIB_NUM; + int hex_len = 0; + do { + char nib_type = getNibbleType(in[l + hex_len]); + if (nib_type == USX_NIB_NOT) + break; + if (nib_type != USX_NIB_NUM) { + if (hex_type != USX_NIB_NUM && hex_type != nib_type) + break; + hex_type = nib_type; + } + hex_len++; + } while (l + hex_len < len); + if (hex_len > 10 && hex_type == USX_NIB_NUM) + hex_type = USX_NIB_HEX_LOWER; + if ((hex_type == USX_NIB_HEX_LOWER || hex_type == USX_NIB_HEX_UPPER) && hex_len > 3) { + SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, (hex_type == USX_NIB_HEX_LOWER ? 0x80 : 0xE0), + (hex_type == USX_NIB_HEX_LOWER ? 2 : 4))); + SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, hex_len)); + do { + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, getBaseCode(in[l++]), 4)); + } while (--hex_len); + l--; + continue; + } + } - if (c_in >= 32 && c_in <= 126) { - if (is_upper && !is_all_upper) { - for (ll=l+4; ll>=l && ll 'Z') - break; + if (usx_templates != NULL) { + int i; + for (i = 0; i < 5; i++) { + if (usx_templates[i]) { + int rem = (int)strlen(usx_templates[i]); + int j = 0; + for (; j < rem && l + j < len; j++) { + char c_t = usx_templates[i][j]; + c_in = in[l + j]; + if (c_t == 'f' || c_t == 'F') { + if (getNibbleType(c_in) != (c_t == 'f' ? USX_NIB_HEX_LOWER : USX_NIB_HEX_UPPER) && + getNibbleType(c_in) != USX_NIB_NUM) { + break; + } + } else if (c_t == 'r' || c_t == 't' || c_t == 'o') { + if (c_in < '0' || c_in > (c_t == 'r' ? '7' : (c_t == 't' ? '3' : '1'))) + break; + } else if (c_t != c_in) + break; + } + if (((float)j / rem) > 0.66) { + // printf("%s\n", usx_templates[i]); + rem = rem - j; + SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, 0, 1)); + SAFE_APPEND_BITS2(rawolen, + ol = append_bits(out, olen, ol, (count_codes[i] & 0xF8), count_codes[i] & 0x07)); + SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, rem)); + for (int k = 0; k < j; k++) { + char c_t = usx_templates[i][k]; + if (c_t == 'f' || c_t == 'F') + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, getBaseCode(in[l + k]), 4)); + else if (c_t == 'r' || c_t == 't' || c_t == 'o') { + c_t = (c_t == 'r' ? 3 : (c_t == 't' ? 2 : 1)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, (in[l + k] - '0') << (8 - c_t), c_t)); + } + } + l += j; + l--; + break; + } + } + } + if (i < 5) + continue; } - if (ll == l-1) { - SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); - state = USX_ALPHA; - is_all_upper = 1; + + if (usx_freq_seq != NULL) { + int i; + for (i = 0; i < 6; i++) { + int seq_len = (int)strlen(usx_freq_seq[i]); + if (len - seq_len >= 0 && l <= len - seq_len) { + if (memcmp(usx_freq_seq[i], in + l, seq_len) == 0 && usx_hcode_lens[usx_freq_codes[i] >> 5]) { + SAFE_APPEND_BITS2(rawolen, + ol = append_code(out, olen, ol, usx_freq_codes[i], &state, usx_hcodes, usx_hcode_lens)); + l += seq_len; + l--; + break; + } + } + } + if (i < 6) + continue; } - } - if (state == USX_DELTA && (c_in == ' ' || c_in == '.' || c_in == ',')) { - uint8_t spl_code = (c_in == ',' ? 0xC0 : (c_in == '.' ? 0xE0 : (c_in == ' ' ? 0 : 0xFF))); - if (spl_code != 0xFF) { - uint8_t spl_code_len = (c_in == ',' ? 3 : (c_in == '.' ? 4 : (c_in == ' ' ? 1 : 4))); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, UNI_STATE_SPL_CODE, UNI_STATE_SPL_CODE_LEN)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, spl_code, spl_code_len)); - continue; + + c_in = in[l]; + + is_upper = 0; + if (c_in >= 'A' && c_in <= 'Z') + is_upper = 1; + else { + if (is_all_upper) { + is_all_upper = 0; + SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + state = USX_ALPHA; + } } - } - c_in -= 32; - if (is_all_upper && is_upper) - c_in += 32; - if (c_in == 0) { - if (state == USX_NUM) - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_vcodes[NUM_SPC_CODE & 0x1F], usx_vcode_lens[NUM_SPC_CODE & 0x1F])); - else - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_vcodes[1], usx_vcode_lens[1])); - } else { - c_in--; - SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, usx_code_94[(int)c_in], &state, usx_hcodes, usx_hcode_lens)); - } - } else - if (c_in == 13 && c_next == 10) { - SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, CRLF_CODE, &state, usx_hcodes, usx_hcode_lens)); - l++; - } else - if (c_in == 10) { - if (state == USX_DELTA) { - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, UNI_STATE_SPL_CODE, UNI_STATE_SPL_CODE_LEN)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, 0xF0, 4)); - } else - SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, LF_CODE, &state, usx_hcodes, usx_hcode_lens)); - } else - if (c_in == 13) { - SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, CR_CODE, &state, usx_hcodes, usx_hcode_lens)); - } else - if (c_in == '\t') { - SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, TAB_CODE, &state, usx_hcodes, usx_hcode_lens)); - } else { - int utf8len; - int32_t uni = readUTF8(in, len, l, &utf8len); - if (uni) { - l += utf8len; - if (state != USX_DELTA) { - int32_t uni2 = readUTF8(in, len, l, &utf8len); - if (uni2) { - if (state != USX_ALPHA) { - SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + if (is_upper && !is_all_upper) { + if (state == USX_NUM) { + SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + state = USX_ALPHA; } SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_vcodes[1], usx_vcode_lens[1])); // code for space (' ') - state = USX_DELTA; - } else { - SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_DELTA], usx_hcode_lens[USX_DELTA])); - } + if (state == USX_DELTA) { + state = USX_ALPHA; + SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + } } - SAFE_APPEND_BITS2(rawolen, ol = encodeUnicode(out, olen, ol, uni, prev_uni)); - //printf("%d:%d:%d\n", l, utf8len, uni); - prev_uni = uni; - l--; - } else { - int bin_count = 1; - for (int bi = l + 1; bi < len; bi++) { - char c_bi = in[bi]; - //if (c_bi > 0x1F && c_bi != 0x7F) - // break; - if (readUTF8(in, len, bi, &utf8len)) - break; - if (bi < (len - 4) && c_bi == in[bi - 1] && c_bi == in[bi + 1] && c_bi == in[bi + 2] && c_bi == in[bi + 3]) - break; - bin_count++; + c_next = 0; + if (l + 1 < len) + c_next = in[l + 1]; + + if (c_in >= 32 && c_in <= 126) { + if (is_upper && !is_all_upper) { + for (ll = l + 4; ll >= l && ll < len; ll--) { + if (in[ll] < 'A' || in[ll] > 'Z') + break; + } + if (ll == l - 1) { + SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + state = USX_ALPHA; + is_all_upper = 1; + } + } + if (state == USX_DELTA && (c_in == ' ' || c_in == '.' || c_in == ',')) { + uint8_t spl_code = (c_in == ',' ? 0xC0 : (c_in == '.' ? 0xE0 : (c_in == ' ' ? 0 : 0xFF))); + if (spl_code != 0xFF) { + uint8_t spl_code_len = (c_in == ',' ? 3 : (c_in == '.' ? 4 : (c_in == ' ' ? 1 : 4))); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, UNI_STATE_SPL_CODE, UNI_STATE_SPL_CODE_LEN)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, spl_code, spl_code_len)); + continue; + } + } + c_in -= 32; + if (is_all_upper && is_upper) + c_in += 32; + if (c_in == 0) { + if (state == USX_NUM) + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_vcodes[NUM_SPC_CODE & 0x1F], + usx_vcode_lens[NUM_SPC_CODE & 0x1F])); + else + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, usx_vcodes[1], usx_vcode_lens[1])); + } else { + c_in--; + SAFE_APPEND_BITS2(rawolen, + ol = append_code(out, olen, ol, usx_code_94[(int)c_in], &state, usx_hcodes, usx_hcode_lens)); + } + } else if (c_in == 13 && c_next == 10) { + SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, CRLF_CODE, &state, usx_hcodes, usx_hcode_lens)); + l++; + } else if (c_in == 10) { + if (state == USX_DELTA) { + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, UNI_STATE_SPL_CODE, UNI_STATE_SPL_CODE_LEN)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, 0xF0, 4)); + } else + SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, LF_CODE, &state, usx_hcodes, usx_hcode_lens)); + } else if (c_in == 13) { + SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, CR_CODE, &state, usx_hcodes, usx_hcode_lens)); + } else if (c_in == '\t') { + SAFE_APPEND_BITS2(rawolen, ol = append_code(out, olen, ol, TAB_CODE, &state, usx_hcodes, usx_hcode_lens)); + } else { + int utf8len; + int32_t uni = readUTF8(in, len, l, &utf8len); + if (uni) { + l += utf8len; + if (state != USX_DELTA) { + int32_t uni2 = readUTF8(in, len, l, &utf8len); + if (uni2) { + if (state != USX_ALPHA) { + SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS2(rawolen, + ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + } + SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS2(rawolen, + ol = append_bits(out, olen, ol, usx_hcodes[USX_ALPHA], usx_hcode_lens[USX_ALPHA])); + SAFE_APPEND_BITS2( + rawolen, ol = append_bits(out, olen, ol, usx_vcodes[1], usx_vcode_lens[1])); // code for space (' ') + state = USX_DELTA; + } else { + SAFE_APPEND_BITS2(rawolen, ol = append_switch_code(out, olen, ol, state)); + SAFE_APPEND_BITS2(rawolen, + ol = append_bits(out, olen, ol, usx_hcodes[USX_DELTA], usx_hcode_lens[USX_DELTA])); + } + } + SAFE_APPEND_BITS2(rawolen, ol = encodeUnicode(out, olen, ol, uni, prev_uni)); + // printf("%d:%d:%d\n", l, utf8len, uni); + prev_uni = uni; + l--; + } else { + int bin_count = 1; + for (int bi = l + 1; bi < len; bi++) { + char c_bi = in[bi]; + // if (c_bi > 0x1F && c_bi != 0x7F) + // break; + if (readUTF8(in, len, bi, &utf8len)) + break; + if (bi < (len - 4) && c_bi == in[bi - 1] && c_bi == in[bi + 1] && c_bi == in[bi + 2] && c_bi == in[bi + 3]) + break; + bin_count++; + } + // printf("Bin:%d:%d:%x:%d\n", l, (unsigned char) c_in, (unsigned char) c_in, bin_count); + SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, 0xF8, 5)); + SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, bin_count)); + do { + SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, in[l++], 8)); + } while (--bin_count); + l--; + } } - //printf("Bin:%d:%d:%x:%d\n", l, (unsigned char) c_in, (unsigned char) c_in, bin_count); - SAFE_APPEND_BITS2(rawolen, ol = append_nibble_escape(out, olen, ol, state, usx_hcodes, usx_hcode_lens)); - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, 0xF8, 5)); - SAFE_APPEND_BITS2(rawolen, ol = encodeCount(out, olen, ol, bin_count)); - do { - SAFE_APPEND_BITS2(rawolen, ol = append_bits(out, olen, ol, in[l++], 8)); - } while (--bin_count); - l--; - } } - } - if (need_full_term_codes) { - const int orig_ol = ol; - SAFE_APPEND_BITS2(rawolen, ol = append_final_bits(out, olen, ol, state, is_all_upper, usx_hcodes, usx_hcode_lens)); - return (ol / 8) * 4 + (((ol-orig_ol)/8) & 3); - } else { - const int rst = (ol + 7) / 8; - append_final_bits(out, rst, ol, state, is_all_upper, usx_hcodes, usx_hcode_lens); - return rst; - } + if (need_full_term_codes) { + const int orig_ol = ol; + SAFE_APPEND_BITS2(rawolen, ol = append_final_bits(out, olen, ol, state, is_all_upper, usx_hcodes, usx_hcode_lens)); + return (ol / 8) * 4 + (((ol - orig_ol) / 8) & 3); + } else { + const int rst = (ol + 7) / 8; + append_final_bits(out, rst, ol, state, is_all_upper, usx_hcodes, usx_hcode_lens); + return rst; + } } // Main API function. See unishox2.h for documentation -int unishox2_compress(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[]) { - return unishox2_compress_lines(in, len, UNISHOX_API_OUT_AND_LEN(out, olen), usx_hcodes, usx_hcode_lens, usx_freq_seq, usx_templates, NULL); +int unishox2_compress(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], + const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[]) +{ + return unishox2_compress_lines(in, len, UNISHOX_API_OUT_AND_LEN(out, olen), usx_hcodes, usx_hcode_lens, usx_freq_seq, + usx_templates, NULL); } // Main API function. See unishox2.h for documentation -int unishox2_compress_simple(const char *in, int len, char *out) { - return unishox2_compress_lines(in, len, UNISHOX_API_OUT_AND_LEN(out, INT_MAX - 1), USX_HCODES_DFLT, USX_HCODE_LENS_DFLT, USX_FREQ_SEQ_DFLT, USX_TEMPLATES, NULL); +int unishox2_compress_simple(const char *in, int len, char *out) +{ + return unishox2_compress_lines(in, len, UNISHOX_API_OUT_AND_LEN(out, INT_MAX - 1), USX_HCODES_DFLT, USX_HCODE_LENS_DFLT, + USX_FREQ_SEQ_DFLT, USX_TEMPLATES, NULL); } // Reads one bit from in -int readBit(const char *in, int bit_no) { - return in[bit_no >> 3] & (0x80 >> (bit_no % 8)); +int readBit(const char *in, int bit_no) +{ + return in[bit_no >> 3] & (0x80 >> (bit_no % 8)); } // Reads next 8 bits, if available -int read8bitCode(const char *in, int len, int bit_no) { - int bit_pos = bit_no & 0x07; - int char_pos = bit_no >> 3; - len >>= 3; - uint8_t code = (((uint8_t)in[char_pos]) << bit_pos); - char_pos++; - if (char_pos < len) { - code |= ((uint8_t)in[char_pos]) >> (8 - bit_pos); - } else - code |= (0xFF >> (8 - bit_pos)); - return code; +int read8bitCode(const char *in, int len, int bit_no) +{ + int bit_pos = bit_no & 0x07; + int char_pos = bit_no >> 3; + len >>= 3; + uint8_t code = (((uint8_t)in[char_pos]) << bit_pos); + char_pos++; + if (char_pos < len) { + code |= ((uint8_t)in[char_pos]) >> (8 - bit_pos); + } else + code |= (0xFF >> (8 - bit_pos)); + return code; } /// The list of veritical codes is split into 5 sections. Used by readVCodeIdx() @@ -874,17 +901,14 @@ uint8_t usx_vsection_shift[] = {5, 4, 3, 1, 0}; /// Vertical decoder lookup table - 3 bits code len, 5 bytes vertical pos /// code len is one less as 8 cannot be accommodated in 3 bits -uint8_t usx_vcode_lookup[36] = { - (1 << 5) + 0, (1 << 5) + 0, (2 << 5) + 1, (2 << 5) + 2, // Section 1 - (3 << 5) + 3, (3 << 5) + 4, (3 << 5) + 5, (3 << 5) + 6, // Section 2 - (3 << 5) + 7, (3 << 5) + 7, (4 << 5) + 8, (4 << 5) + 9, // Section 3 - (5 << 5) + 10, (5 << 5) + 10, (5 << 5) + 11, (5 << 5) + 11, // Section 4 - (5 << 5) + 12, (5 << 5) + 12, (6 << 5) + 13, (6 << 5) + 14, - (6 << 5) + 15, (6 << 5) + 15, (6 << 5) + 16, (6 << 5) + 16, // Section 5 - (6 << 5) + 17, (6 << 5) + 17, (7 << 5) + 18, (7 << 5) + 19, - (7 << 5) + 20, (7 << 5) + 21, (7 << 5) + 22, (7 << 5) + 23, - (7 << 5) + 24, (7 << 5) + 25, (7 << 5) + 26, (7 << 5) + 27 -}; +uint8_t usx_vcode_lookup[36] = {(1 << 5) + 0, (1 << 5) + 0, (2 << 5) + 1, (2 << 5) + 2, // Section 1 + (3 << 5) + 3, (3 << 5) + 4, (3 << 5) + 5, (3 << 5) + 6, // Section 2 + (3 << 5) + 7, (3 << 5) + 7, (4 << 5) + 8, (4 << 5) + 9, // Section 3 + (5 << 5) + 10, (5 << 5) + 10, (5 << 5) + 11, (5 << 5) + 11, // Section 4 + (5 << 5) + 12, (5 << 5) + 12, (6 << 5) + 13, (6 << 5) + 14, (6 << 5) + 15, (6 << 5) + 15, + (6 << 5) + 16, (6 << 5) + 16, // Section 5 + (6 << 5) + 17, (6 << 5) + 17, (7 << 5) + 18, (7 << 5) + 19, (7 << 5) + 20, (7 << 5) + 21, + (7 << 5) + 22, (7 << 5) + 23, (7 << 5) + 24, (7 << 5) + 25, (7 << 5) + 26, (7 << 5) + 27}; /// Decodes the vertical code from the given bitstream at in \n /// This is designed to use less memory using a 36 uint8_t buffer \n @@ -893,21 +917,22 @@ uint8_t usx_vcode_lookup[36] = { /// Decoder is designed for using less memory, not speed. \n /// Returns the veritical code index or 99 if match could not be found. \n /// Also updates bit_no_p with how many ever bits used by the vertical code. -int readVCodeIdx(const char *in, int len, int *bit_no_p) { - if (*bit_no_p < len) { - uint8_t code = read8bitCode(in, len, *bit_no_p); - int i = 0; - do { - if (code <= usx_vsections[i]) { - uint8_t vcode = usx_vcode_lookup[usx_vsection_pos[i] + ((code & usx_vsection_mask[i]) >> usx_vsection_shift[i])]; - (*bit_no_p) += ((vcode >> 5) + 1); - if (*bit_no_p > len) - return 99; - return vcode & 0x1F; - } - } while (++i < SECTION_COUNT); - } - return 99; +int readVCodeIdx(const char *in, int len, int *bit_no_p) +{ + if (*bit_no_p < len) { + uint8_t code = read8bitCode(in, len, *bit_no_p); + int i = 0; + do { + if (code <= usx_vsections[i]) { + uint8_t vcode = usx_vcode_lookup[usx_vsection_pos[i] + ((code & usx_vsection_mask[i]) >> usx_vsection_shift[i])]; + (*bit_no_p) += ((vcode >> 5) + 1); + if (*bit_no_p > len) + return 99; + return vcode & 0x1F; + } + } while (++i < SECTION_COUNT); + } + return 99; } /// Mask for retrieving each code to be decoded according to its length \n @@ -917,451 +942,482 @@ uint8_t len_masks[] = {0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF}; /// depending on the hcodes defined using usx_hcodes and usx_hcode_lens \n /// Returns the horizontal code index or 99 if match could not be found. \n /// Also updates bit_no_p with how many ever bits used by the horizontal code. -int readHCodeIdx(const char *in, int len, int *bit_no_p, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) { - if (!usx_hcode_lens[USX_ALPHA]) - return USX_ALPHA; - if (*bit_no_p < len) { - uint8_t code = read8bitCode(in, len, *bit_no_p); - for (int code_pos = 0; code_pos < 5; code_pos++) { - if (usx_hcode_lens[code_pos] && (code & len_masks[usx_hcode_lens[code_pos] - 1]) == usx_hcodes[code_pos]) { - *bit_no_p += usx_hcode_lens[code_pos]; - return code_pos; - } +int readHCodeIdx(const char *in, int len, int *bit_no_p, const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[]) +{ + if (!usx_hcode_lens[USX_ALPHA]) + return USX_ALPHA; + if (*bit_no_p < len) { + uint8_t code = read8bitCode(in, len, *bit_no_p); + for (int code_pos = 0; code_pos < 5; code_pos++) { + if (usx_hcode_lens[code_pos] && (code & len_masks[usx_hcode_lens[code_pos] - 1]) == usx_hcodes[code_pos]) { + *bit_no_p += usx_hcode_lens[code_pos]; + return code_pos; + } + } } - } - return 99; + return 99; } // TODO: Last value check.. Also len check in readBit /// Returns the position of step code (0, 10, 110, etc.) encountered in the stream -int getStepCodeIdx(const char *in, int len, int *bit_no_p, int limit) { - int idx = 0; - while (*bit_no_p < len && readBit(in, *bit_no_p)) { - idx++; +int getStepCodeIdx(const char *in, int len, int *bit_no_p, int limit) +{ + int idx = 0; + while (*bit_no_p < len && readBit(in, *bit_no_p)) { + idx++; + (*bit_no_p)++; + if (idx == limit) + return idx; + } + if (*bit_no_p >= len) + return 99; (*bit_no_p)++; - if (idx == limit) - return idx; - } - if (*bit_no_p >= len) - return 99; - (*bit_no_p)++; - return idx; + return idx; } /// Reads specified number of bits and builds the corresponding integer -int32_t getNumFromBits(const char *in, int len, int bit_no, int count) { - int32_t ret = 0; - while (count-- && bit_no < len) { - ret += (readBit(in, bit_no) ? 1 << count : 0); - bit_no++; - } - return count < 0 ? ret : -1; +int32_t getNumFromBits(const char *in, int len, int bit_no, int count) +{ + int32_t ret = 0; + while (count-- && bit_no < len) { + ret += (readBit(in, bit_no) ? 1 << count : 0); + bit_no++; + } + return count < 0 ? ret : -1; } /// Decodes the count from the given bit stream at in. Also updates bit_no_p -int32_t readCount(const char *in, int *bit_no_p, int len) { - int idx = getStepCodeIdx(in, len, bit_no_p, 4); - if (idx == 99) - return -1; - if (*bit_no_p + count_bit_lens[idx] - 1 >= len) - return -1; - int32_t count = getNumFromBits(in, len, *bit_no_p, count_bit_lens[idx]) + (idx ? count_adder[idx - 1] : 0); - (*bit_no_p) += count_bit_lens[idx]; - return count; +int32_t readCount(const char *in, int *bit_no_p, int len) +{ + int idx = getStepCodeIdx(in, len, bit_no_p, 4); + if (idx == 99) + return -1; + if (*bit_no_p + count_bit_lens[idx] - 1 >= len) + return -1; + int32_t count = getNumFromBits(in, len, *bit_no_p, count_bit_lens[idx]) + (idx ? count_adder[idx - 1] : 0); + (*bit_no_p) += count_bit_lens[idx]; + return count; } /// Decodes the Unicode codepoint from the given bit stream at in. Also updates bit_no_p \n /// When the step code is 5, reads the next step code to find out the special code. -int32_t readUnicode(const char *in, int *bit_no_p, int len) { - int idx = getStepCodeIdx(in, len, bit_no_p, 5); - if (idx == 99) - return 0x7FFFFF00 + 99; - if (idx == 5) { - idx = getStepCodeIdx(in, len, bit_no_p, 4); - return 0x7FFFFF00 + idx; - } - if (idx >= 0) { - int sign = (*bit_no_p < len ? readBit(in, *bit_no_p) : 0); - (*bit_no_p)++; - if (*bit_no_p + uni_bit_len[idx] - 1 >= len) - return 0x7FFFFF00 + 99; - int32_t count = getNumFromBits(in, len, *bit_no_p, uni_bit_len[idx]); - count += uni_adder[idx]; - (*bit_no_p) += uni_bit_len[idx]; - //printf("Sign: %d, Val:%d", sign, count); - return sign ? -count : count; - } - return 0; +int32_t readUnicode(const char *in, int *bit_no_p, int len) +{ + int idx = getStepCodeIdx(in, len, bit_no_p, 5); + if (idx == 99) + return 0x7FFFFF00 + 99; + if (idx == 5) { + idx = getStepCodeIdx(in, len, bit_no_p, 4); + return 0x7FFFFF00 + idx; + } + if (idx >= 0) { + int sign = (*bit_no_p < len ? readBit(in, *bit_no_p) : 0); + (*bit_no_p)++; + if (*bit_no_p + uni_bit_len[idx] - 1 >= len) + return 0x7FFFFF00 + 99; + int32_t count = getNumFromBits(in, len, *bit_no_p, uni_bit_len[idx]); + count += uni_adder[idx]; + (*bit_no_p) += uni_bit_len[idx]; + // printf("Sign: %d, Val:%d", sign, count); + return sign ? -count : count; + } + return 0; } /// Macro to ensure that the decoder does not append more than olen bytes to out -#define DEC_OUTPUT_CHAR(out, olen, ol, c) do { \ - char *const obuf = (out); \ - const int oidx = (ol); \ - const int limit = (olen); \ - if (limit <= oidx) return limit + 1; \ - else if (oidx < 0) return 0; \ - else obuf[oidx] = (c); \ -} while (0) +#define DEC_OUTPUT_CHAR(out, olen, ol, c) \ + do { \ + char *const obuf = (out); \ + const int oidx = (ol); \ + const int limit = (olen); \ + if (limit <= oidx) \ + return limit + 1; \ + else if (oidx < 0) \ + return 0; \ + else \ + obuf[oidx] = (c); \ + } while (0) /// Macro to ensure that the decoder does not append more than olen bytes to out -#define DEC_OUTPUT_CHARS(olen, exp) do { \ - const int newidx = (exp); \ - const int limit = (olen); \ - if (newidx > limit) return limit + 1; \ -} while (0) +#define DEC_OUTPUT_CHARS(olen, exp) \ + do { \ + const int newidx = (exp); \ + const int limit = (olen); \ + if (newidx > limit) \ + return limit + 1; \ + } while (0) /// Write given unicode code point to out as a UTF-8 sequence -int writeUTF8(char *out, int olen, int ol, int uni) { - if (uni < (1 << 11)) { - DEC_OUTPUT_CHAR(out, olen, ol++, 0xC0 + (uni >> 6)); - DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + (uni & 0x3F)); - } else - if (uni < (1 << 16)) { - DEC_OUTPUT_CHAR(out, olen, ol++, 0xE0 + (uni >> 12)); - DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + ((uni >> 6) & 0x3F)); - DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + (uni & 0x3F)); - } else { - DEC_OUTPUT_CHAR(out, olen, ol++, 0xF0 + (uni >> 18)); - DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + ((uni >> 12) & 0x3F)); - DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + ((uni >> 6) & 0x3F)); - DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + (uni & 0x3F)); - } - return ol; +int writeUTF8(char *out, int olen, int ol, int uni) +{ + if (uni < (1 << 11)) { + DEC_OUTPUT_CHAR(out, olen, ol++, 0xC0 + (uni >> 6)); + DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + (uni & 0x3F)); + } else if (uni < (1 << 16)) { + DEC_OUTPUT_CHAR(out, olen, ol++, 0xE0 + (uni >> 12)); + DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + ((uni >> 6) & 0x3F)); + DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + (uni & 0x3F)); + } else { + DEC_OUTPUT_CHAR(out, olen, ol++, 0xF0 + (uni >> 18)); + DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + ((uni >> 12) & 0x3F)); + DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + ((uni >> 6) & 0x3F)); + DEC_OUTPUT_CHAR(out, olen, ol++, 0x80 + (uni & 0x3F)); + } + return ol; } /// Decode repeating sequence and appends to out -int decodeRepeat(const char *in, int len, char *out, int olen, int ol, int *bit_no, struct us_lnk_lst *prev_lines) { - if (prev_lines) { - int32_t dict_len = readCount(in, bit_no, len) + NICE_LEN; - if (dict_len < NICE_LEN) - return -1; - int32_t dist = readCount(in, bit_no, len); - if (dist < 0) - return -1; - int32_t ctx = readCount(in, bit_no, len); - if (ctx < 0) - return -1; - struct us_lnk_lst *cur_line = prev_lines; - const int left = olen - ol; - while (ctx-- && cur_line) - cur_line = cur_line->previous; - if (cur_line == NULL) - return -1; - if (left <= 0) return olen + 1; - if (dist >= strlen(cur_line->data)) - return -1; - memmove(out + ol, cur_line->data + dist, min_of(left, dict_len)); - if (left < dict_len) return olen + 1; - ol += dict_len; - } else { - int32_t dict_len = readCount(in, bit_no, len) + NICE_LEN; - if (dict_len < NICE_LEN) - return -1; - int32_t dist = readCount(in, bit_no, len) + NICE_LEN - 1; - if (dist < NICE_LEN - 1) - return -1; - const int32_t left = olen - ol; - //printf("Decode len: %d, dist: %d\n", dict_len - NICE_LEN, dist - NICE_LEN + 1); - if (left <= 0) return olen + 1; - if (ol - dist < 0) - return -1; - memmove(out + ol, out + ol - dist, min_of(left, dict_len)); - if (left < dict_len) return olen + 1; - ol += dict_len; - } - return ol; +int decodeRepeat(const char *in, int len, char *out, int olen, int ol, int *bit_no, struct us_lnk_lst *prev_lines) +{ + if (prev_lines) { + int32_t dict_len = readCount(in, bit_no, len) + NICE_LEN; + if (dict_len < NICE_LEN) + return -1; + int32_t dist = readCount(in, bit_no, len); + if (dist < 0) + return -1; + int32_t ctx = readCount(in, bit_no, len); + if (ctx < 0) + return -1; + struct us_lnk_lst *cur_line = prev_lines; + const int left = olen - ol; + while (ctx-- && cur_line) + cur_line = cur_line->previous; + if (cur_line == NULL) + return -1; + if (left <= 0) + return olen + 1; + if (dist >= strlen(cur_line->data)) + return -1; + memmove(out + ol, cur_line->data + dist, min_of(left, dict_len)); + if (left < dict_len) + return olen + 1; + ol += dict_len; + } else { + int32_t dict_len = readCount(in, bit_no, len) + NICE_LEN; + if (dict_len < NICE_LEN) + return -1; + int32_t dist = readCount(in, bit_no, len) + NICE_LEN - 1; + if (dist < NICE_LEN - 1) + return -1; + const int32_t left = olen - ol; + // printf("Decode len: %d, dist: %d\n", dict_len - NICE_LEN, dist - NICE_LEN + 1); + if (left <= 0) + return olen + 1; + if (ol - dist < 0) + return -1; + memmove(out + ol, out + ol - dist, min_of(left, dict_len)); + if (left < dict_len) + return olen + 1; + ol += dict_len; + } + return ol; } /// Returns hex character corresponding to the 4 bit nibble -char getHexChar(int32_t nibble, int hex_type) { - if (nibble >= 0 && nibble <= 9) - return '0' + nibble; - else if (hex_type < USX_NIB_HEX_UPPER) - return 'a' + nibble - 10; - return 'A' + nibble - 10; +char getHexChar(int32_t nibble, int hex_type) +{ + if (nibble >= 0 && nibble <= 9) + return '0' + nibble; + else if (hex_type < USX_NIB_HEX_UPPER) + return 'a' + nibble - 10; + return 'A' + nibble - 10; } // Main API function. See unishox2.h for documentation -int unishox2_decompress_lines(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[], struct us_lnk_lst *prev_lines) { +int unishox2_decompress_lines(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], + const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[], + struct us_lnk_lst *prev_lines) +{ - int dstate; - int bit_no; - int h, v; - uint8_t is_all_upper; -#if (UNISHOX_API_OUT_AND_LEN(0,1)) == 0 - const int olen = INT_MAX - 1; + int dstate; + int bit_no; + int h, v; + uint8_t is_all_upper; +#if (UNISHOX_API_OUT_AND_LEN(0, 1)) == 0 + const int olen = INT_MAX - 1; #endif - init_coder(); - int ol = 0; - bit_no = UNISHOX_MAGIC_BIT_LEN; // ignore the magic bit - dstate = h = USX_ALPHA; - is_all_upper = 0; + init_coder(); + int ol = 0; + bit_no = UNISHOX_MAGIC_BIT_LEN; // ignore the magic bit + dstate = h = USX_ALPHA; + is_all_upper = 0; - int prev_uni = 0; + int prev_uni = 0; - len <<= 3; - while (bit_no < len) { - int orig_bit_no = bit_no; - if (dstate == USX_DELTA || h == USX_DELTA) { - if (dstate != USX_DELTA) - h = dstate; - int32_t delta = readUnicode(in, &bit_no, len); - if ((delta >> 8) == 0x7FFFFF) { - int spl_code_idx = delta & 0x000000FF; - if (spl_code_idx == 99) - break; - switch (spl_code_idx) { - case 0: - DEC_OUTPUT_CHAR(out, olen, ol++, ' '); - continue; - case 1: - h = readHCodeIdx(in, len, &bit_no, usx_hcodes, usx_hcode_lens); - if (h == 99) { - bit_no = len; - continue; + len <<= 3; + while (bit_no < len) { + int orig_bit_no = bit_no; + if (dstate == USX_DELTA || h == USX_DELTA) { + if (dstate != USX_DELTA) + h = dstate; + int32_t delta = readUnicode(in, &bit_no, len); + if ((delta >> 8) == 0x7FFFFF) { + int spl_code_idx = delta & 0x000000FF; + if (spl_code_idx == 99) + break; + switch (spl_code_idx) { + case 0: + DEC_OUTPUT_CHAR(out, olen, ol++, ' '); + continue; + case 1: + h = readHCodeIdx(in, len, &bit_no, usx_hcodes, usx_hcode_lens); + if (h == 99) { + bit_no = len; + continue; + } + if (h == USX_DELTA || h == USX_ALPHA) { + dstate = h; + continue; + } + if (h == USX_DICT) { + int rpt_ret = decodeRepeat(in, len, out, olen, ol, &bit_no, prev_lines); + if (rpt_ret < 0) + return ol; // if we break here it will only break out of switch + DEC_OUTPUT_CHARS(olen, ol = rpt_ret); + h = dstate; + continue; + } + break; + case 2: + DEC_OUTPUT_CHAR(out, olen, ol++, ','); + continue; + case 3: + DEC_OUTPUT_CHAR(out, olen, ol++, '.'); + continue; + case 4: + DEC_OUTPUT_CHAR(out, olen, ol++, 10); + continue; + } + } else { + prev_uni += delta; + DEC_OUTPUT_CHARS(olen, ol = writeUTF8(out, olen, ol, prev_uni)); + // printf("%ld, ", prev_uni); } - if (h == USX_DELTA || h == USX_ALPHA) { - dstate = h; - continue; - } - if (h == USX_DICT) { - int rpt_ret = decodeRepeat(in, len, out, olen, ol, &bit_no, prev_lines); - if (rpt_ret < 0) - return ol; // if we break here it will only break out of switch - DEC_OUTPUT_CHARS(olen, ol = rpt_ret); - h = dstate; - continue; - } - break; - case 2: - DEC_OUTPUT_CHAR(out, olen, ol++, ','); - continue; - case 3: - DEC_OUTPUT_CHAR(out, olen, ol++, '.'); - continue; - case 4: - DEC_OUTPUT_CHAR(out, olen, ol++, 10); - continue; - } - } else { - prev_uni += delta; - DEC_OUTPUT_CHARS(olen, ol = writeUTF8(out, olen, ol, prev_uni)); - //printf("%ld, ", prev_uni); - } - if (dstate == USX_DELTA && h == USX_DELTA) - continue; - } else - h = dstate; - char c = 0; - uint8_t is_upper = is_all_upper; - v = readVCodeIdx(in, len, &bit_no); - if (v == 99 || h == 99) { - bit_no = orig_bit_no; - break; - } - if (v == 0 && h != USX_SYM) { - if (bit_no >= len) - break; - if (h != USX_NUM || dstate != USX_DELTA) { - h = readHCodeIdx(in, len, &bit_no, usx_hcodes, usx_hcode_lens); - if (h == 99 || bit_no >= len) { - bit_no = orig_bit_no; - break; - } - } - if (h == USX_ALPHA) { - if (dstate == USX_ALPHA) { - if (!usx_hcode_lens[USX_ALPHA] && TERM_BYTE_PRESET_1 == (read8bitCode(in, len, bit_no - SW_CODE_LEN) & (0xFF << (8 - (is_all_upper ? TERM_BYTE_PRESET_1_LEN_UPPER : TERM_BYTE_PRESET_1_LEN_LOWER))))) - break; // Terminator for preset 1 - if (is_all_upper) { - is_upper = is_all_upper = 0; - continue; - } - v = readVCodeIdx(in, len, &bit_no); - if (v == 99) { - bit_no = orig_bit_no; - break; - } - if (v == 0) { - h = readHCodeIdx(in, len, &bit_no, usx_hcodes, usx_hcode_lens); - if (h == 99) { - bit_no = orig_bit_no; - break; - } - if (h == USX_ALPHA) { - is_all_upper = 1; - continue; - } - } - is_upper = 1; - } else { - dstate = USX_ALPHA; - continue; - } - } else - if (h == USX_DICT) { - int rpt_ret = decodeRepeat(in, len, out, olen, ol, &bit_no, prev_lines); - if (rpt_ret < 0) - break; - DEC_OUTPUT_CHARS(olen, ol = rpt_ret); - continue; - } else - if (h == USX_DELTA) { - //printf("Sign: %d, bitno: %d\n", sign, bit_no); - //printf("Code: %d\n", prev_uni); - //printf("BitNo: %d\n", bit_no); - continue; - } else { - if (h != USX_NUM || dstate != USX_DELTA) - v = readVCodeIdx(in, len, &bit_no); - if (v == 99) { - bit_no = orig_bit_no; - break; - } - if (h == USX_NUM && v == 0) { - int idx = getStepCodeIdx(in, len, &bit_no, 5); - if (idx == 99) - break; - if (idx == 0) { - idx = getStepCodeIdx(in, len, &bit_no, 4); - if (idx >= 5) - break; - int32_t rem = readCount(in, &bit_no, len); - if (rem < 0) - break; - if (usx_templates[idx] == NULL) - break; - size_t tlen = strlen(usx_templates[idx]); - if (rem > tlen) - break; - rem = tlen - rem; - int eof = 0; - for (int j = 0; j < rem; j++) { - char c_t = usx_templates[idx][j]; - if (c_t == 'f' || c_t == 'r' || c_t == 't' || c_t == 'o' || c_t == 'F') { - char nibble_len = (c_t == 'f' || c_t == 'F' ? 4 : (c_t == 'r' ? 3 : (c_t == 't' ? 2 : 1))); - const int32_t raw_char = getNumFromBits(in, len, bit_no, nibble_len); - if (raw_char < 0) { - eof = 1; - break; - } - DEC_OUTPUT_CHAR(out, olen, ol++, getHexChar((char)raw_char, - c_t == 'f' ? USX_NIB_HEX_LOWER : USX_NIB_HEX_UPPER)); - bit_no += nibble_len; - } else - DEC_OUTPUT_CHAR(out, olen, ol++, c_t); - } - if (eof) break; // reach input eof - } else - if (idx == 5) { - int32_t bin_count = readCount(in, &bit_no, len); - if (bin_count < 0) - break; - if (bin_count == 0) // invalid encoding - break; - do { - const int32_t raw_char = getNumFromBits(in, len, bit_no, 8); - if (raw_char < 0) - break; - DEC_OUTPUT_CHAR(out, olen, ol++, (char)raw_char); - bit_no += 8; - } while (--bin_count); - if (bin_count > 0) break; // reach input eof - } else { - int32_t nibble_count = 0; - if (idx == 2 || idx == 4) - nibble_count = 32; - else { - nibble_count = readCount(in, &bit_no, len); - if (nibble_count < 0) - break; - if (nibble_count == 0) // invalid encoding - break; - } - do { - int32_t nibble = getNumFromBits(in, len, bit_no, 4); - if (nibble < 0) - break; - DEC_OUTPUT_CHAR(out, olen, ol++, getHexChar(nibble, idx < 3 ? USX_NIB_HEX_LOWER : USX_NIB_HEX_UPPER)); - if ((idx == 2 || idx == 4) && (nibble_count == 25 || nibble_count == 21 || nibble_count == 17 || nibble_count == 13)) - DEC_OUTPUT_CHAR(out, olen, ol++, '-'); - bit_no += 4; - } while (--nibble_count); - if (nibble_count > 0) break; // reach input eof - } - if (dstate == USX_DELTA) - h = USX_DELTA; - continue; - } - } - } - if (is_upper && v == 1) { - h = dstate = USX_DELTA; // continuous delta coding - continue; - } - if (h < 3 && v < 28) - c = usx_sets[h][v]; - if (c >= 'a' && c <= 'z') { - dstate = USX_ALPHA; - if (is_upper) - c -= 32; - } else { - if (c >= '0' && c <= '9') { - dstate = USX_NUM; - } else if (c == 0) { - if (v == 8) { - DEC_OUTPUT_CHAR(out, olen, ol++, '\r'); - DEC_OUTPUT_CHAR(out, olen, ol++, '\n'); - } else if (h == USX_NUM && v == 26) { - int32_t count = readCount(in, &bit_no, len); - if (count < 0) - break; - count += 4; - if (ol <= 0) - return 0; // invalid encoding - char rpt_c = out[ol - 1]; - while (count--) - DEC_OUTPUT_CHAR(out, olen, ol++, rpt_c); - } else if (h == USX_SYM && v > 24) { - v -= 25; - const int freqlen = (int)strlen(usx_freq_seq[v]); - const int left = olen - ol; - if (left <= 0) return olen + 1; - memcpy(out + ol, usx_freq_seq[v], min_of(left, freqlen)); - if (left < freqlen) return olen + 1; - ol += freqlen; - } else if (h == USX_NUM && v > 22 && v < 26) { - v -= (23 - 3); - const int freqlen = (int)strlen(usx_freq_seq[v]); - const int left = olen - ol; - if (left <= 0) return olen + 1; - memcpy(out + ol, usx_freq_seq[v], min_of(left, freqlen)); - if (left < freqlen) return olen + 1; - ol += freqlen; + if (dstate == USX_DELTA && h == USX_DELTA) + continue; } else - break; // Terminator + h = dstate; + char c = 0; + uint8_t is_upper = is_all_upper; + v = readVCodeIdx(in, len, &bit_no); + if (v == 99 || h == 99) { + bit_no = orig_bit_no; + break; + } + if (v == 0 && h != USX_SYM) { + if (bit_no >= len) + break; + if (h != USX_NUM || dstate != USX_DELTA) { + h = readHCodeIdx(in, len, &bit_no, usx_hcodes, usx_hcode_lens); + if (h == 99 || bit_no >= len) { + bit_no = orig_bit_no; + break; + } + } + if (h == USX_ALPHA) { + if (dstate == USX_ALPHA) { + if (!usx_hcode_lens[USX_ALPHA] && + TERM_BYTE_PRESET_1 == + (read8bitCode(in, len, bit_no - SW_CODE_LEN) & + (0xFF << (8 - (is_all_upper ? TERM_BYTE_PRESET_1_LEN_UPPER : TERM_BYTE_PRESET_1_LEN_LOWER))))) + break; // Terminator for preset 1 + if (is_all_upper) { + is_upper = is_all_upper = 0; + continue; + } + v = readVCodeIdx(in, len, &bit_no); + if (v == 99) { + bit_no = orig_bit_no; + break; + } + if (v == 0) { + h = readHCodeIdx(in, len, &bit_no, usx_hcodes, usx_hcode_lens); + if (h == 99) { + bit_no = orig_bit_no; + break; + } + if (h == USX_ALPHA) { + is_all_upper = 1; + continue; + } + } + is_upper = 1; + } else { + dstate = USX_ALPHA; + continue; + } + } else if (h == USX_DICT) { + int rpt_ret = decodeRepeat(in, len, out, olen, ol, &bit_no, prev_lines); + if (rpt_ret < 0) + break; + DEC_OUTPUT_CHARS(olen, ol = rpt_ret); + continue; + } else if (h == USX_DELTA) { + // printf("Sign: %d, bitno: %d\n", sign, bit_no); + // printf("Code: %d\n", prev_uni); + // printf("BitNo: %d\n", bit_no); + continue; + } else { + if (h != USX_NUM || dstate != USX_DELTA) + v = readVCodeIdx(in, len, &bit_no); + if (v == 99) { + bit_no = orig_bit_no; + break; + } + if (h == USX_NUM && v == 0) { + int idx = getStepCodeIdx(in, len, &bit_no, 5); + if (idx == 99) + break; + if (idx == 0) { + idx = getStepCodeIdx(in, len, &bit_no, 4); + if (idx >= 5) + break; + int32_t rem = readCount(in, &bit_no, len); + if (rem < 0) + break; + if (usx_templates[idx] == NULL) + break; + size_t tlen = strlen(usx_templates[idx]); + if (rem > tlen) + break; + rem = tlen - rem; + int eof = 0; + for (int j = 0; j < rem; j++) { + char c_t = usx_templates[idx][j]; + if (c_t == 'f' || c_t == 'r' || c_t == 't' || c_t == 'o' || c_t == 'F') { + char nibble_len = (c_t == 'f' || c_t == 'F' ? 4 : (c_t == 'r' ? 3 : (c_t == 't' ? 2 : 1))); + const int32_t raw_char = getNumFromBits(in, len, bit_no, nibble_len); + if (raw_char < 0) { + eof = 1; + break; + } + DEC_OUTPUT_CHAR(out, olen, ol++, + getHexChar((char)raw_char, c_t == 'f' ? USX_NIB_HEX_LOWER : USX_NIB_HEX_UPPER)); + bit_no += nibble_len; + } else + DEC_OUTPUT_CHAR(out, olen, ol++, c_t); + } + if (eof) + break; // reach input eof + } else if (idx == 5) { + int32_t bin_count = readCount(in, &bit_no, len); + if (bin_count < 0) + break; + if (bin_count == 0) // invalid encoding + break; + do { + const int32_t raw_char = getNumFromBits(in, len, bit_no, 8); + if (raw_char < 0) + break; + DEC_OUTPUT_CHAR(out, olen, ol++, (char)raw_char); + bit_no += 8; + } while (--bin_count); + if (bin_count > 0) + break; // reach input eof + } else { + int32_t nibble_count = 0; + if (idx == 2 || idx == 4) + nibble_count = 32; + else { + nibble_count = readCount(in, &bit_no, len); + if (nibble_count < 0) + break; + if (nibble_count == 0) // invalid encoding + break; + } + do { + int32_t nibble = getNumFromBits(in, len, bit_no, 4); + if (nibble < 0) + break; + DEC_OUTPUT_CHAR(out, olen, ol++, getHexChar(nibble, idx < 3 ? USX_NIB_HEX_LOWER : USX_NIB_HEX_UPPER)); + if ((idx == 2 || idx == 4) && + (nibble_count == 25 || nibble_count == 21 || nibble_count == 17 || nibble_count == 13)) + DEC_OUTPUT_CHAR(out, olen, ol++, '-'); + bit_no += 4; + } while (--nibble_count); + if (nibble_count > 0) + break; // reach input eof + } + if (dstate == USX_DELTA) + h = USX_DELTA; + continue; + } + } + } + if (is_upper && v == 1) { + h = dstate = USX_DELTA; // continuous delta coding + continue; + } + if (h < 3 && v < 28) + c = usx_sets[h][v]; + if (c >= 'a' && c <= 'z') { + dstate = USX_ALPHA; + if (is_upper) + c -= 32; + } else { + if (c >= '0' && c <= '9') { + dstate = USX_NUM; + } else if (c == 0) { + if (v == 8) { + DEC_OUTPUT_CHAR(out, olen, ol++, '\r'); + DEC_OUTPUT_CHAR(out, olen, ol++, '\n'); + } else if (h == USX_NUM && v == 26) { + int32_t count = readCount(in, &bit_no, len); + if (count < 0) + break; + count += 4; + if (ol <= 0) + return 0; // invalid encoding + char rpt_c = out[ol - 1]; + while (count--) + DEC_OUTPUT_CHAR(out, olen, ol++, rpt_c); + } else if (h == USX_SYM && v > 24) { + v -= 25; + const int freqlen = (int)strlen(usx_freq_seq[v]); + const int left = olen - ol; + if (left <= 0) + return olen + 1; + memcpy(out + ol, usx_freq_seq[v], min_of(left, freqlen)); + if (left < freqlen) + return olen + 1; + ol += freqlen; + } else if (h == USX_NUM && v > 22 && v < 26) { + v -= (23 - 3); + const int freqlen = (int)strlen(usx_freq_seq[v]); + const int left = olen - ol; + if (left <= 0) + return olen + 1; + memcpy(out + ol, usx_freq_seq[v], min_of(left, freqlen)); + if (left < freqlen) + return olen + 1; + ol += freqlen; + } else + break; // Terminator + if (dstate == USX_DELTA) + h = USX_DELTA; + continue; + } + } if (dstate == USX_DELTA) - h = USX_DELTA; - continue; - } + h = USX_DELTA; + DEC_OUTPUT_CHAR(out, olen, ol++, c); } - if (dstate == USX_DELTA) - h = USX_DELTA; - DEC_OUTPUT_CHAR(out, olen, ol++, c); - } - - return ol; + return ol; } // Main API function. See unishox2.h for documentation -int unishox2_decompress(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[]) { - return unishox2_decompress_lines(in, len, UNISHOX_API_OUT_AND_LEN(out, olen), usx_hcodes, usx_hcode_lens, usx_freq_seq, usx_templates, NULL); +int unishox2_decompress(const char *in, int len, UNISHOX_API_OUT_AND_LEN(char *out, int olen), const uint8_t usx_hcodes[], + const uint8_t usx_hcode_lens[], const char *usx_freq_seq[], const char *usx_templates[]) +{ + return unishox2_decompress_lines(in, len, UNISHOX_API_OUT_AND_LEN(out, olen), usx_hcodes, usx_hcode_lens, usx_freq_seq, + usx_templates, NULL); } // Main API function. See unishox2.h for documentation -int unishox2_decompress_simple(const char *in, int len, char *out) { - return unishox2_decompress(in, len, UNISHOX_API_OUT_AND_LEN(out, INT_MAX - 1), USX_PSET_DFLT); +int unishox2_decompress_simple(const char *in, int len, char *out) +{ + return unishox2_decompress(in, len, UNISHOX_API_OUT_AND_LEN(out, INT_MAX - 1), USX_PSET_DFLT); } diff --git a/src/mesh/compression/unishox2.h b/src/mesh/compression/unishox2.h index bbbd7a759..e3674fb7c 100644 --- a/src/mesh/compression/unishox2.h +++ b/src/mesh/compression/unishox2.h @@ -30,7 +30,7 @@ #ifndef unishox2 #define unishox2 -#define UNISHOX_VERSION "2.0" ///< Unicode spec version +#define UNISHOX_VERSION "2.0" ///< Unicode spec version /** * Macro switch to enable/disable output buffer length parameter in low level api \n @@ -45,104 +45,217 @@ * The simple api, i.e. unishox2_(de)compress_simple will always omit the buffer length */ #ifndef UNISHOX_API_WITH_OUTPUT_LEN -# define UNISHOX_API_WITH_OUTPUT_LEN 0 +#define UNISHOX_API_WITH_OUTPUT_LEN 0 #endif /// Upto 8 bits of initial magic bit sequence can be included. Bit count can be specified with UNISHOX_MAGIC_BIT_LEN #ifndef UNISHOX_MAGIC_BITS -# define UNISHOX_MAGIC_BITS 0xFF +#define UNISHOX_MAGIC_BITS 0xFF #endif /// Desired length of Magic bits defined by UNISHOX_MAGIC_BITS #ifdef UNISHOX_MAGIC_BIT_LEN -# if UNISHOX_MAGIC_BIT_LEN < 0 || 9 <= UNISHOX_MAGIC_BIT_LEN -# error "UNISHOX_MAGIC_BIT_LEN need between [0, 8)" -# endif +#if UNISHOX_MAGIC_BIT_LEN < 0 || 9 <= UNISHOX_MAGIC_BIT_LEN +#error "UNISHOX_MAGIC_BIT_LEN need between [0, 8)" +#endif #else -# define UNISHOX_MAGIC_BIT_LEN 1 +#define UNISHOX_MAGIC_BIT_LEN 1 #endif -//enum {USX_ALPHA = 0, USX_SYM, USX_NUM, USX_DICT, USX_DELTA}; +// enum {USX_ALPHA = 0, USX_SYM, USX_NUM, USX_DICT, USX_DELTA}; -/// Default Horizontal codes. When composition of text is know beforehand, the other hcodes in this section can be used to achieve more compression. -#define USX_HCODES_DFLT (const unsigned char[]) {0x00, 0x40, 0x80, 0xC0, 0xE0} +/// Default Horizontal codes. When composition of text is know beforehand, the other hcodes in this section can be used to achieve +/// more compression. +#define USX_HCODES_DFLT \ + (const unsigned char[]) \ + { \ + 0x00, 0x40, 0x80, 0xC0, 0xE0 \ + } /// Length of each default hcode -#define USX_HCODE_LENS_DFLT (const unsigned char[]) {2, 2, 2, 3, 3} +#define USX_HCODE_LENS_DFLT \ + (const unsigned char[]) \ + { \ + 2, 2, 2, 3, 3 \ + } /// Horizontal codes preset for English Alphabet content only -#define USX_HCODES_ALPHA_ONLY (const unsigned char[]) {0x00, 0x00, 0x00, 0x00, 0x00} +#define USX_HCODES_ALPHA_ONLY \ + (const unsigned char[]) \ + { \ + 0x00, 0x00, 0x00, 0x00, 0x00 \ + } /// Length of each Alpha only hcode -#define USX_HCODE_LENS_ALPHA_ONLY (const unsigned char[]) {0, 0, 0, 0, 0} +#define USX_HCODE_LENS_ALPHA_ONLY \ + (const unsigned char[]) \ + { \ + 0, 0, 0, 0, 0 \ + } /// Horizontal codes preset for Alpha Numeric content only -#define USX_HCODES_ALPHA_NUM_ONLY (const unsigned char[]) {0x00, 0x00, 0x80, 0x00, 0x00} +#define USX_HCODES_ALPHA_NUM_ONLY \ + (const unsigned char[]) \ + { \ + 0x00, 0x00, 0x80, 0x00, 0x00 \ + } /// Length of each Alpha numeric hcode -#define USX_HCODE_LENS_ALPHA_NUM_ONLY (const unsigned char[]) {1, 0, 1, 0, 0} +#define USX_HCODE_LENS_ALPHA_NUM_ONLY \ + (const unsigned char[]) \ + { \ + 1, 0, 1, 0, 0 \ + } /// Horizontal codes preset for Alpha Numeric and Symbol content only -#define USX_HCODES_ALPHA_NUM_SYM_ONLY (const unsigned char[]) {0x00, 0x80, 0xC0, 0x00, 0x00} +#define USX_HCODES_ALPHA_NUM_SYM_ONLY \ + (const unsigned char[]) \ + { \ + 0x00, 0x80, 0xC0, 0x00, 0x00 \ + } /// Length of each Alpha numeric and symbol hcodes -#define USX_HCODE_LENS_ALPHA_NUM_SYM_ONLY (const unsigned char[]) {1, 2, 2, 0, 0} +#define USX_HCODE_LENS_ALPHA_NUM_SYM_ONLY \ + (const unsigned char[]) \ + { \ + 1, 2, 2, 0, 0 \ + } /// Horizontal codes preset favouring Alphabet content -#define USX_HCODES_FAVOR_ALPHA (const unsigned char[]) {0x00, 0x80, 0xA0, 0xC0, 0xE0} +#define USX_HCODES_FAVOR_ALPHA \ + (const unsigned char[]) \ + { \ + 0x00, 0x80, 0xA0, 0xC0, 0xE0 \ + } /// Length of each hcode favouring Alpha content -#define USX_HCODE_LENS_FAVOR_ALPHA (const unsigned char[]) {1, 3, 3, 3, 3} +#define USX_HCODE_LENS_FAVOR_ALPHA \ + (const unsigned char[]) \ + { \ + 1, 3, 3, 3, 3 \ + } /// Horizontal codes preset favouring repeating sequences -#define USX_HCODES_FAVOR_DICT (const unsigned char[]) {0x00, 0x40, 0xC0, 0x80, 0xE0} +#define USX_HCODES_FAVOR_DICT \ + (const unsigned char[]) \ + { \ + 0x00, 0x40, 0xC0, 0x80, 0xE0 \ + } /// Length of each hcode favouring repeating sequences -#define USX_HCODE_LENS_FAVOR_DICT (const unsigned char[]) {2, 2, 3, 2, 3} +#define USX_HCODE_LENS_FAVOR_DICT \ + (const unsigned char[]) \ + { \ + 2, 2, 3, 2, 3 \ + } /// Horizontal codes preset favouring symbols -#define USX_HCODES_FAVOR_SYM (const unsigned char[]) {0x80, 0x00, 0xA0, 0xC0, 0xE0} +#define USX_HCODES_FAVOR_SYM \ + (const unsigned char[]) \ + { \ + 0x80, 0x00, 0xA0, 0xC0, 0xE0 \ + } /// Length of each hcode favouring symbols -#define USX_HCODE_LENS_FAVOR_SYM (const unsigned char[]) {3, 1, 3, 3, 3} +#define USX_HCODE_LENS_FAVOR_SYM \ + (const unsigned char[]) \ + { \ + 3, 1, 3, 3, 3 \ + } //#define USX_HCODES_FAVOR_UMLAUT {0x00, 0x40, 0xE0, 0xC0, 0x80} //#define USX_HCODE_LENS_FAVOR_UMLAUT {2, 2, 3, 3, 2} /// Horizontal codes preset favouring umlaut letters -#define USX_HCODES_FAVOR_UMLAUT (const unsigned char[]) {0x80, 0xA0, 0xC0, 0xE0, 0x00} +#define USX_HCODES_FAVOR_UMLAUT \ + (const unsigned char[]) \ + { \ + 0x80, 0xA0, 0xC0, 0xE0, 0x00 \ + } /// Length of each hcode favouring umlaut letters -#define USX_HCODE_LENS_FAVOR_UMLAUT (const unsigned char[]) {3, 3, 3, 3, 1} +#define USX_HCODE_LENS_FAVOR_UMLAUT \ + (const unsigned char[]) \ + { \ + 3, 3, 3, 3, 1 \ + } /// Horizontal codes preset for no repeating sequences -#define USX_HCODES_NO_DICT (const unsigned char[]) {0x00, 0x40, 0x80, 0x00, 0xC0} +#define USX_HCODES_NO_DICT \ + (const unsigned char[]) \ + { \ + 0x00, 0x40, 0x80, 0x00, 0xC0 \ + } /// Length of each hcode for no repeating sequences -#define USX_HCODE_LENS_NO_DICT (const unsigned char[]) {2, 2, 2, 0, 2} +#define USX_HCODE_LENS_NO_DICT \ + (const unsigned char[]) \ + { \ + 2, 2, 2, 0, 2 \ + } /// Horizontal codes preset for no Unicode characters -#define USX_HCODES_NO_UNI (const unsigned char[]) {0x00, 0x40, 0x80, 0xC0, 0x00} +#define USX_HCODES_NO_UNI \ + (const unsigned char[]) \ + { \ + 0x00, 0x40, 0x80, 0xC0, 0x00 \ + } /// Length of each hcode for no Unicode characters -#define USX_HCODE_LENS_NO_UNI (const unsigned char[]) {2, 2, 2, 2, 0} +#define USX_HCODE_LENS_NO_UNI \ + (const unsigned char[]) \ + { \ + 2, 2, 2, 2, 0 \ + } -/// Default frequently occuring sequences. When composition of text is know beforehand, the other sequences in this section can be used to achieve more compression. -#define USX_FREQ_SEQ_DFLT (const char *[]) {"\": \"", "\": ", ""} +#define USX_FREQ_SEQ_HTML \ + (const char *[]) \ + { \ + "" \ + } /// Frequently occuring sequences in XML content -#define USX_FREQ_SEQ_XML (const char *[]) {"", "", " -#include -#include "target_specific.h" #include "mesh/api/ethServerAPI.h" #include "mqtt/MQTT.h" +#include "target_specific.h" +#include +#include #ifndef DISABLE_NTP #include @@ -35,7 +35,7 @@ static int32_t reconnectETH() LOG_INFO("Starting NTP time client\n"); timeClient.begin(); timeClient.setUpdateInterval(60 * 60); // Update once an hour -#endif +#endif // initWebServer(); initApiServer(); @@ -50,7 +50,7 @@ static int32_t reconnectETH() #ifndef DISABLE_NTP if (isEthernetAvailable() && (ntp_renew < millis())) { - + LOG_INFO("Updating NTP time from %s\n", config.network.ntp_server); if (timeClient.update()) { LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed\n"); @@ -80,12 +80,12 @@ bool initEthernet() #ifdef PIN_ETHERNET_RESET pinMode(PIN_ETHERNET_RESET, OUTPUT); - digitalWrite(PIN_ETHERNET_RESET, LOW); // Reset Time. + digitalWrite(PIN_ETHERNET_RESET, LOW); // Reset Time. delay(100); - digitalWrite(PIN_ETHERNET_RESET, HIGH); // Reset Time. + digitalWrite(PIN_ETHERNET_RESET, HIGH); // Reset Time. #endif - Ethernet.init( ETH_SPI_PORT, PIN_ETHERNET_SS ); + Ethernet.init(ETH_SPI_PORT, PIN_ETHERNET_SS); uint8_t mac[6]; @@ -94,7 +94,7 @@ bool initEthernet() // createSSLCert(); getMacAddr(mac); // FIXME use the BLE MAC for now... - mac[0] &= 0xfe; // Make sure this is not a multicast MAC + mac[0] &= 0xfe; // Make sure this is not a multicast MAC if (config.network.address_mode == Config_NetworkConfig_AddressMode_DHCP) { LOG_INFO("starting Ethernet DHCP\n"); @@ -114,15 +114,19 @@ bool initEthernet() } else if (Ethernet.linkStatus() == LinkOFF) { LOG_ERROR("Ethernet cable is not connected.\n"); return false; - } else{ + } else { LOG_ERROR("Unknown Ethernet error.\n"); return false; } } else { - LOG_INFO("Local IP %u.%u.%u.%u\n",Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]); - LOG_INFO("Subnet Mask %u.%u.%u.%u\n",Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], Ethernet.subnetMask()[3]); - LOG_INFO("Gateway IP %u.%u.%u.%u\n",Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], Ethernet.gatewayIP()[3]); - LOG_INFO("DNS Server IP %u.%u.%u.%u\n",Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], Ethernet.dnsServerIP()[2], Ethernet.dnsServerIP()[3]); + LOG_INFO("Local IP %u.%u.%u.%u\n", Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], + Ethernet.localIP()[3]); + LOG_INFO("Subnet Mask %u.%u.%u.%u\n", Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], + Ethernet.subnetMask()[3]); + LOG_INFO("Gateway IP %u.%u.%u.%u\n", Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], + Ethernet.gatewayIP()[3]); + LOG_INFO("DNS Server IP %u.%u.%u.%u\n", Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], + Ethernet.dnsServerIP()[2], Ethernet.dnsServerIP()[3]); } ethEvent = new Periodic("ethConnect", reconnectETH); @@ -135,7 +139,8 @@ bool initEthernet() } } -bool isEthernetAvailable() { +bool isEthernetAvailable() +{ if (!config.network.eth_enabled) { return false; diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index 7551a0828..8683f9cb1 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -6,13 +6,13 @@ #include "mesh/http/ContentHelper.h" #include "mesh/http/WebServer.h" #include "mesh/http/WiFiAPClient.h" +#include "mqtt/JSON.h" #include "power.h" #include "sleep.h" #include #include #include #include -#include "mqtt/JSON.h" #ifdef ARCH_ESP32 #include "esp_task_wdt.h" @@ -321,7 +321,7 @@ void handleFsBrowseStatic(HTTPRequest *req, HTTPResponse *res) res->print(value->Stringify().c_str()); - delete value; + delete value; } void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res) @@ -336,7 +336,7 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res) std::string pathDelete = "/" + paramValDelete; if (FSCom.remove(pathDelete.c_str())) { LOG_INFO("%s\n", pathDelete.c_str()); - JSONObject jsonObjOuter; + JSONObject jsonObjOuter; jsonObjOuter["status"] = new JSONValue("ok"); JSONValue *value = new JSONValue(jsonObjOuter); res->print(value->Stringify().c_str()); diff --git a/src/mesh/http/ContentHandler.h b/src/mesh/http/ContentHandler.h index 278b923ed..903d5ee08 100644 --- a/src/mesh/http/ContentHandler.h +++ b/src/mesh/http/ContentHandler.h @@ -1,6 +1,5 @@ #pragma once - void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer); // Declare some handler functions for the various URLs on the server @@ -22,7 +21,6 @@ void handleAdmin(HTTPRequest *req, HTTPResponse *res); void handleAdminSettings(HTTPRequest *req, HTTPResponse *res); void handleAdminSettingsApply(HTTPRequest *req, HTTPResponse *res); - // Interface to the PhoneAPI to access the protobufs with messages class HttpAPI : public PhoneAPI { @@ -34,7 +32,6 @@ class HttpAPI : public PhoneAPI // Nothing here yet protected: - /// Check the current underlying physical link to see if the client is currently connected virtual bool checkIsConnected() override { return true; } // FIXME, be smarter about this }; diff --git a/src/mesh/http/WebServer.cpp b/src/mesh/http/WebServer.cpp index 29cace436..289f1429b 100644 --- a/src/mesh/http/WebServer.cpp +++ b/src/mesh/http/WebServer.cpp @@ -152,7 +152,7 @@ void createSSLCert() if (millis() / 1000 >= 3) { screen->setSSLFrames(); } -#endif +#endif } runLoop = false; } else { @@ -165,7 +165,8 @@ void createSSLCert() WebServerThread *webServerThread; -WebServerThread::WebServerThread() : concurrency::OSThread("WebServerThread") { +WebServerThread::WebServerThread() : concurrency::OSThread("WebServerThread") +{ if (!config.network.wifi_enabled) { disable(); } diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index 1139c305e..e8bacc12a 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -1,17 +1,17 @@ +#include "mesh/http/WiFiAPClient.h" #include "NodeDB.h" #include "RTC.h" #include "concurrency/Periodic.h" -#include "mesh/http/WiFiAPClient.h" #include "configuration.h" #include "main.h" -#include "mesh/http/WebServer.h" #include "mesh/api/WiFiServerAPI.h" +#include "mesh/http/WebServer.h" #include "mqtt/MQTT.h" #include "target_specific.h" #include -#include #include #include +#include #ifndef DISABLE_NTP #include @@ -47,7 +47,7 @@ static int32_t reconnectWiFi() const char *wifiPsw = config.network.wifi_psk; if (config.network.wifi_enabled && needReconnect) { - + if (!*wifiPsw) // Treat empty password as no password wifiPsw = NULL; @@ -55,7 +55,7 @@ static int32_t reconnectWiFi() // Make sure we clear old connection credentials WiFi.disconnect(false, true); - LOG_INFO("Reconnecting to WiFi access point %s\n",wifiName); + LOG_INFO("Reconnecting to WiFi access point %s\n", wifiName); delay(5000); @@ -66,7 +66,7 @@ static int32_t reconnectWiFi() #ifndef DISABLE_NTP if (WiFi.isConnected() && (((millis() - lastrun_ntp) > 43200000) || (lastrun_ntp == 0))) { // every 12 hours - LOG_DEBUG("Updating NTP time from %s\n",config.network.ntp_server); + LOG_DEBUG("Updating NTP time from %s\n", config.network.ntp_server); if (timeClient.update()) { LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed\n"); @@ -172,10 +172,8 @@ bool initWifi() WiFi.setAutoReconnect(true); WiFi.setSleep(false); if (config.network.address_mode == Config_NetworkConfig_AddressMode_STATIC && config.network.ipv4_config.ip != 0) { - WiFi.config(config.network.ipv4_config.ip, - config.network.ipv4_config.gateway, - config.network.ipv4_config.subnet, - config.network.ipv4_config.dns, + WiFi.config(config.network.ipv4_config.ip, config.network.ipv4_config.gateway, config.network.ipv4_config.subnet, + config.network.ipv4_config.dns, config.network.ipv4_config.dns); // Wifi wants two DNS servers... set both to the same value } @@ -184,7 +182,6 @@ bool initWifi() WiFi.onEvent( [](WiFiEvent_t event, WiFiEventInfo_t info) { - LOG_WARN("WiFi lost connection. Reason: %d\n", info.wifi_sta_disconnected.reason); /* diff --git a/src/mesh/http/WiFiAPClient.h b/src/mesh/http/WiFiAPClient.h index a11330ad0..0c08c567b 100644 --- a/src/mesh/http/WiFiAPClient.h +++ b/src/mesh/http/WiFiAPClient.h @@ -1,7 +1,7 @@ #pragma once -#include "configuration.h" #include "concurrency/Periodic.h" +#include "configuration.h" #include #include diff --git a/src/mesh/mesh-pb-constants.cpp b/src/mesh/mesh-pb-constants.cpp index d8a981054..f9fa02251 100644 --- a/src/mesh/mesh-pb-constants.cpp +++ b/src/mesh/mesh-pb-constants.cpp @@ -13,7 +13,8 @@ size_t pb_encode_to_bytes(uint8_t *destbuf, size_t destbufsize, const pb_msgdesc pb_ostream_t stream = pb_ostream_from_buffer(destbuf, destbufsize); if (!pb_encode(&stream, fields, src_struct)) { LOG_ERROR("Panic: can't encode protobuf reason='%s'\n", PB_GET_ERROR(&stream)); - assert(0); // If this asser fails it probably means you made a field too large for the max limits specified in mesh.options + assert( + 0); // If this asser fails it probably means you made a field too large for the max limits specified in mesh.options } else { return stream.bytes_written; } diff --git a/src/modules/CannedMessageModule.h b/src/modules/CannedMessageModule.h index 2edef4655..744ec6f47 100644 --- a/src/modules/CannedMessageModule.h +++ b/src/modules/CannedMessageModule.h @@ -3,8 +3,7 @@ #include "ProtobufModule.h" #include "input/InputBroker.h" -enum cannedMessageModuleRunState -{ +enum cannedMessageModuleRunState { CANNED_MESSAGE_RUN_STATE_DISABLED, CANNED_MESSAGE_RUN_STATE_INACTIVE, CANNED_MESSAGE_RUN_STATE_ACTIVE, @@ -15,27 +14,23 @@ enum cannedMessageModuleRunState CANNED_MESSAGE_RUN_STATE_ACTION_DOWN, }; - #define CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT 50 /** * Sum of CannedMessageModuleConfig part sizes. */ #define CANNED_MESSAGE_MODULE_MESSAGES_SIZE 800 -class CannedMessageModule : - public SinglePortModule, - public Observable, - private concurrency::OSThread +class CannedMessageModule : public SinglePortModule, public Observable, private concurrency::OSThread { CallbackObserver inputObserver = - CallbackObserver( - this, &CannedMessageModule::handleInputEvent); + CallbackObserver(this, &CannedMessageModule::handleInputEvent); + public: CannedMessageModule(); - const char* getCurrentMessage(); - const char* getPrevMessage(); - const char* getNextMessage(); - const char* getNodeName(NodeNum node); + const char *getCurrentMessage(); + const char *getPrevMessage(); + const char *getNextMessage(); + const char *getNodeName(NodeNum node); bool shouldDraw(); void eventUp(); void eventDown(); @@ -47,13 +42,9 @@ class CannedMessageModule : String drawWithCursor(String text, int cursor); protected: - virtual int32_t runOnce() override; - void sendText( - NodeNum dest, - const char* message, - bool wantReplies); + void sendText(NodeNum dest, const char *message, bool wantReplies); int splitConfiguredMessages(); int getNextIndex(); @@ -61,11 +52,10 @@ class CannedMessageModule : int handleInputEvent(const InputEvent *event); virtual bool wantUIFrame() override { return this->shouldDraw(); } - virtual Observable* getUIFrameObservable() override { return this; } - virtual void drawFrame( - OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override; - virtual AdminMessageHandleResult handleAdminMessageForModule( - const MeshPacket &mp, AdminMessage *request, AdminMessage *response) override; + virtual Observable *getUIFrameObservable() override { return this; } + virtual void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override; + virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, + AdminMessage *response) override; void loadProtoForModule(); bool saveProtoForModule(); @@ -76,11 +66,11 @@ class CannedMessageModule : cannedMessageModuleRunState runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; char payload = 0x00; unsigned int cursor = 0; - String freetext = ""; // Text Buffer for Freetext Editor + String freetext = ""; // Text Buffer for Freetext Editor bool destSelect = false; // Freetext Editor Mode NodeNum dest = NODENUM_BROADCAST; - char messageStore[CANNED_MESSAGE_MODULE_MESSAGES_SIZE+1]; + char messageStore[CANNED_MESSAGE_MODULE_MESSAGES_SIZE + 1]; char *messages[CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT]; int messagesCount = 0; unsigned long lastTouchMillis = 0; diff --git a/src/modules/ExternalNotificationModule.h b/src/modules/ExternalNotificationModule.h index 097ae96b3..2adc3ad1a 100644 --- a/src/modules/ExternalNotificationModule.h +++ b/src/modules/ExternalNotificationModule.h @@ -7,13 +7,13 @@ #include #else // Noop class for portduino. -class rtttl +class rtttl { public: explicit rtttl() {} static bool isPlaying() { return false; } static void play() {} - static void begin(byte a, const char * b) {}; + static void begin(byte a, const char *b){}; static void stop() {} static bool done() { return true; } }; @@ -27,7 +27,7 @@ class rtttl */ class ExternalNotificationModule : public SinglePortModule, private concurrency::OSThread { - uint32_t output = 0; + uint32_t output = 0; public: ExternalNotificationModule(); @@ -45,7 +45,8 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency: protected: /** Called to handle a particular incoming message - @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it + @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for + it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override; @@ -53,7 +54,8 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency: bool isNagging = false; - virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, AdminMessage *response) override; + virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, + AdminMessage *response) override; }; extern ExternalNotificationModule *externalNotificationModule; diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index cd873a466..aacb77151 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -18,9 +18,9 @@ #include "modules/Telemetry/EnvironmentTelemetry.h" #endif #ifdef ARCH_ESP32 +#include "modules/esp32/AudioModule.h" #include "modules/esp32/RangeTestModule.h" #include "modules/esp32/StoreForwardModule.h" -#include "modules/esp32/AudioModule.h" #endif #if defined(ARCH_ESP32) || defined(ARCH_NRF52) #include "modules/ExternalNotificationModule.h" @@ -42,7 +42,7 @@ void setupModules() waypointModule = new WaypointModule(); textMessageModule = new TextMessageModule(); traceRouteModule = new TraceRouteModule(); - + // Note: if the rest of meshtastic doesn't need to explicitly use your module, you do not need to assign the instance // to a global variable. diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index 5dc05cd95..5fe2ef299 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -54,7 +54,8 @@ NodeInfoModule::NodeInfoModule() : ProtobufModule("nodeinfo", PortNum_NODEINFO_APP, &User_msg), concurrency::OSThread("NodeInfoModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others - setIntervalFromNow(30 * 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup) + setIntervalFromNow(30 * + 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup) } int32_t NodeInfoModule::runOnce() diff --git a/src/modules/NodeInfoModule.h b/src/modules/NodeInfoModule.h index db1b35575..d805f362b 100644 --- a/src/modules/NodeInfoModule.h +++ b/src/modules/NodeInfoModule.h @@ -8,14 +8,15 @@ class NodeInfoModule : public ProtobufModule, private concurrency::OSThrea { /// The id of the last packet we sent, to allow us to cancel it if we make something fresher PacketId prevPacketId = 0; - + uint32_t currentGeneration = 0; + public: /** Constructor * name is for debugging output */ NodeInfoModule(); - + /** * Send our NodeInfo into the mesh */ diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index 4d119043c..b3565d919 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -33,10 +33,10 @@ bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr // Log packet size and list of fields LOG_INFO("POSITION node=%08x l=%d %s%s%s%s%s%s%s%s%s%s%s%s%s\n", getFrom(&mp), mp.decoded.payload.size, - p.latitude_i ? "LAT " : "", p.longitude_i ? "LON " : "", p.altitude ? "MSL " : "", p.altitude_hae ? "HAE " : "", - p.altitude_geoidal_separation ? "GEO " : "", p.PDOP ? "PDOP " : "", p.HDOP ? "HDOP " : "", p.VDOP ? "VDOP " : "", - p.sats_in_view ? "SIV " : "", p.fix_quality ? "FXQ " : "", p.fix_type ? "FXT " : "", p.timestamp ? "PTS " : "", - p.time ? "TIME " : ""); + p.latitude_i ? "LAT " : "", p.longitude_i ? "LON " : "", p.altitude ? "MSL " : "", p.altitude_hae ? "HAE " : "", + p.altitude_geoidal_separation ? "GEO " : "", p.PDOP ? "PDOP " : "", p.HDOP ? "HDOP " : "", p.VDOP ? "VDOP " : "", + p.sats_in_view ? "SIV " : "", p.fix_quality ? "FXQ " : "", p.fix_type ? "FXT " : "", p.timestamp ? "PTS " : "", + p.time ? "TIME " : ""); if (p.time) { struct timeval tv; @@ -140,7 +140,8 @@ int32_t PositionModule::runOnce() // We limit our GPS broadcasts to a max rate uint32_t now = millis(); - uint32_t intervalMs = config.position.position_broadcast_secs > 0 ? config.position.position_broadcast_secs * 1000 : default_broadcast_interval_secs * 1000; + uint32_t intervalMs = config.position.position_broadcast_secs > 0 ? config.position.position_broadcast_secs * 1000 + : default_broadcast_interval_secs * 1000; if (lastGpsSend == 0 || (now - lastGpsSend) >= intervalMs) { // Only send packets if the channel is less than 40% utilized. @@ -193,7 +194,7 @@ int32_t PositionModule::runOnce() currentGeneration = radioGeneration; LOG_INFO("Sending smart pos@%x:6 to mesh (wantReplies=%d, d=%d, dtt=%d, tt=%d)\n", node2->position.timestamp, - requestReplies, distance, distanceTravelThreshold, timeTravel); + requestReplies, distance, distanceTravelThreshold, timeTravel); sendOurPosition(NODENUM_BROADCAST, requestReplies); // Set the current coords as our last ones, after we've compared distance with current and decided to send diff --git a/src/modules/PositionModule.h b/src/modules/PositionModule.h index 2c964dca1..d5a33a95a 100644 --- a/src/modules/PositionModule.h +++ b/src/modules/PositionModule.h @@ -25,14 +25,13 @@ class PositionModule : public ProtobufModule, private concurrency::OST * name is for debugging output */ PositionModule(); - + /** * Send our position into the mesh */ void sendOurPosition(NodeNum dest = NODENUM_BROADCAST, bool wantReplies = false); protected: - /** Called to handle a particular incoming message @return true if you've guaranteed you've handled this message and no other handlers should be considered for it diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 8e0031a57..4336d6229 100644 --- a/src/modules/RemoteHardwareModule.cpp +++ b/src/modules/RemoteHardwareModule.cpp @@ -1,9 +1,9 @@ -#include "configuration.h" #include "RemoteHardwareModule.h" #include "MeshService.h" #include "NodeDB.h" #include "RTC.h" #include "Router.h" +#include "configuration.h" #include "main.h" #define NUM_GPIOS 64 @@ -32,7 +32,7 @@ static uint64_t digitalReads(uint64_t mask) // The Arduino docs show to run pinMode(). But, when testing, found it is best not to. // If the line below is uncommented, read will flip the pin to the default of the second // argument in pinModes(), which will make the read turn the PIN "on". - //pinModes(mask, INPUT_PULLUP); + // pinModes(mask, INPUT_PULLUP); for (uint64_t i = 0; i < NUM_GPIOS; i++) { uint64_t m = 1 << i; @@ -48,7 +48,7 @@ static uint64_t digitalReads(uint64_t mask) RemoteHardwareModule::RemoteHardwareModule() : ProtobufModule("remotehardware", PortNum_REMOTE_HARDWARE_APP, &HardwareMessage_msg), concurrency::OSThread( - "RemoteHardwareModule") + "RemoteHardwareModule") { } @@ -93,9 +93,10 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar case HardwareMessage_Type_WATCH_GPIOS: { watchGpios = p.gpio_mask; - lastWatchMsec = 0; // Force a new publish soon - previousWatch = ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish) - enabled = true; // Let our thread run at least once + lastWatchMsec = 0; // Force a new publish soon + previousWatch = + ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish) + enabled = true; // Let our thread run at least once LOG_INFO("Now watching GPIOs 0x%llx\n", watchGpios); break; } diff --git a/src/modules/ReplyModule.cpp b/src/modules/ReplyModule.cpp index bf4e691fb..7b3b1e714 100644 --- a/src/modules/ReplyModule.cpp +++ b/src/modules/ReplyModule.cpp @@ -1,6 +1,6 @@ -#include "configuration.h" #include "ReplyModule.h" #include "MeshService.h" +#include "configuration.h" #include "main.h" #include @@ -16,7 +16,7 @@ MeshPacket *ReplyModule::allocReply() screen->print("Sending reply\n"); const char *replyStr = "Message Received"; - auto reply = allocDataPacket(); // Allocate a packet for sending + auto reply = allocDataPacket(); // Allocate a packet for sending reply->decoded.payload.size = strlen(replyStr); // You must specify how many bytes are in the reply memcpy(reply->decoded.payload.bytes, replyStr, reply->decoded.payload.size); diff --git a/src/modules/ReplyModule.h b/src/modules/ReplyModule.h index 28a57a4bd..1ca5b7389 100644 --- a/src/modules/ReplyModule.h +++ b/src/modules/ReplyModule.h @@ -1,7 +1,6 @@ #pragma once #include "SinglePortModule.h" - /** * A simple example module that just replies with "Message received" to any message it receives. */ @@ -14,9 +13,8 @@ class ReplyModule : public SinglePortModule ReplyModule() : SinglePortModule("reply", PortNum_REPLY_APP) {} protected: - /** For reply module we do all of our processing in the (normally optional) * want_replies handling - */ + */ virtual MeshPacket *allocReply() override; }; diff --git a/src/modules/RoutingModule.cpp b/src/modules/RoutingModule.cpp index 8c4eeb4ff..e4c6f71b2 100644 --- a/src/modules/RoutingModule.cpp +++ b/src/modules/RoutingModule.cpp @@ -1,8 +1,8 @@ -#include "configuration.h" #include "RoutingModule.h" #include "MeshService.h" #include "NodeDB.h" #include "Router.h" +#include "configuration.h" #include "main.h" RoutingModule *routingModule; diff --git a/src/modules/RoutingModule.h b/src/modules/RoutingModule.h index b2840ff58..76cb6e2bb 100644 --- a/src/modules/RoutingModule.h +++ b/src/modules/RoutingModule.h @@ -1,6 +1,6 @@ #pragma once -#include "ProtobufModule.h" #include "Channels.h" +#include "ProtobufModule.h" /** * Routing module for router control messages diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 4383ecaab..a5da9c224 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -1,8 +1,8 @@ #include "SerialModule.h" #include "MeshService.h" +#include "NMEAWPL.h" #include "NodeDB.h" #include "RTC.h" -#include "NMEAWPL.h" #include "Router.h" #include "configuration.h" #include @@ -67,19 +67,18 @@ size_t serialPayloadSize; SerialModuleRadio::SerialModuleRadio() : MeshModule("SerialModuleRadio") { - switch (moduleConfig.serial.mode) - { - case ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG: - ourPortNum = PortNum_TEXT_MESSAGE_APP; - break; - case ModuleConfig_SerialConfig_Serial_Mode_NMEA: - ourPortNum = PortNum_POSITION_APP; - break; - default: - ourPortNum = PortNum_SERIAL_APP; - // restrict to the serial channel for rx - boundChannel = Channels::serialChannel; - break; + switch (moduleConfig.serial.mode) { + case ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG: + ourPortNum = PortNum_TEXT_MESSAGE_APP; + break; + case ModuleConfig_SerialConfig_Serial_Mode_NMEA: + ourPortNum = PortNum_POSITION_APP; + break; + default: + ourPortNum = PortNum_SERIAL_APP; + // restrict to the serial channel for rx + boundChannel = Channels::serialChannel; + break; } } @@ -161,7 +160,7 @@ int32_t SerialModule::runOnce() baud = 921600; } -#ifdef ARCH_ESP32 +#ifdef ARCH_ESP32 Serial2.setRxBufferSize(RX_BUFFER); if (moduleConfig.serial.rxd && moduleConfig.serial.txd) { diff --git a/src/modules/SerialModule.h b/src/modules/SerialModule.h index c853263b6..83bfa5952 100644 --- a/src/modules/SerialModule.h +++ b/src/modules/SerialModule.h @@ -1,11 +1,11 @@ #pragma once +#include "MeshModule.h" +#include "Router.h" #include "SinglePortModule.h" #include "concurrency/OSThread.h" #include "configuration.h" #include -#include "MeshModule.h" -#include "Router.h" #include #if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) @@ -50,7 +50,8 @@ class SerialModuleRadio : public MeshModule /** Called to handle a particular incoming message - @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it + @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for + it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override; @@ -66,7 +67,6 @@ class SerialModuleRadio : public MeshModule return p; } - }; extern SerialModuleRadio *serialModuleRadio; diff --git a/src/modules/TextMessageModule.cpp b/src/modules/TextMessageModule.cpp index c5dcca95a..7ed25d1dc 100644 --- a/src/modules/TextMessageModule.cpp +++ b/src/modules/TextMessageModule.cpp @@ -1,7 +1,7 @@ -#include "configuration.h" #include "TextMessageModule.h" #include "NodeDB.h" #include "PowerFSM.h" +#include "configuration.h" TextMessageModule *textMessageModule; diff --git a/src/modules/TextMessageModule.h b/src/modules/TextMessageModule.h index 3b12dee48..11598c8c4 100644 --- a/src/modules/TextMessageModule.h +++ b/src/modules/TextMessageModule.h @@ -1,6 +1,6 @@ #pragma once -#include "SinglePortModule.h" #include "Observer.h" +#include "SinglePortModule.h" /** * Text message handling for meshtastic - draws on the OLED display the most recent received message @@ -14,10 +14,10 @@ class TextMessageModule : public SinglePortModule, public Observabledecoded; // Only append an ID for the request (one way) - if (!incoming.request_id) { + if (!incoming.request_id) { RouteDiscovery scratch; RouteDiscovery *updated = NULL; memset(&scratch, 0, sizeof(scratch)); @@ -29,37 +27,38 @@ void TraceRouteModule::updateRoute(MeshPacket* p) appendMyID(updated); printRoute(updated, p->from, NODENUM_BROADCAST); - + // Set updated route to the payload of the to be flooded packet - p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &RouteDiscovery_msg, updated); + p->decoded.payload.size = + pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &RouteDiscovery_msg, updated); } } - -void TraceRouteModule::appendMyID(RouteDiscovery* updated) +void TraceRouteModule::appendMyID(RouteDiscovery *updated) { // Length of route array can normally not be exceeded due to the max. hop_limit of 7 - if (updated->route_count < sizeof(updated->route)/sizeof(updated->route[0])) { + if (updated->route_count < sizeof(updated->route) / sizeof(updated->route[0])) { updated->route[updated->route_count] = myNodeInfo.my_node_num; - updated->route_count += 1; + updated->route_count += 1; } else { LOG_WARN("Route exceeded maximum hop limit, are you bridging networks?\n"); } } - -void TraceRouteModule::printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest) +void TraceRouteModule::printRoute(RouteDiscovery *r, uint32_t origin, uint32_t dest) { LOG_INFO("Route traced:\n"); LOG_INFO("0x%x --> ", origin); - for (uint8_t i=0; iroute_count; i++) { - LOG_INFO("0x%x --> ", r->route[i]); + for (uint8_t i = 0; i < r->route_count; i++) { + LOG_INFO("0x%x --> ", r->route[i]); } - if (dest != NODENUM_BROADCAST) LOG_INFO("0x%x\n", dest); else LOG_INFO("...\n"); + if (dest != NODENUM_BROADCAST) + LOG_INFO("0x%x\n", dest); + else + LOG_INFO("...\n"); } - -MeshPacket* TraceRouteModule::allocReply() +MeshPacket *TraceRouteModule::allocReply() { assert(currentRequest); @@ -75,12 +74,12 @@ MeshPacket* TraceRouteModule::allocReply() printRoute(updated, req.from, req.to); // Create a MeshPacket with this payload and set it as the reply - MeshPacket* reply = allocDataProtobuf(*updated); + MeshPacket *reply = allocDataProtobuf(*updated); return reply; } - -TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, &RouteDiscovery_msg) { - ourPortNum = PortNum_TRACEROUTE_APP; +TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, &RouteDiscovery_msg) +{ + ourPortNum = PortNum_TRACEROUTE_APP; } diff --git a/src/modules/TraceRouteModule.h b/src/modules/TraceRouteModule.h index 15b7a564d..7601d672d 100644 --- a/src/modules/TraceRouteModule.h +++ b/src/modules/TraceRouteModule.h @@ -1,36 +1,34 @@ #pragma once #include "ProtobufModule.h" - /** * A module that traces the route to a certain destination node */ class TraceRouteModule : public ProtobufModule { - public: - TraceRouteModule(); + public: + TraceRouteModule(); - // Let FloodingRouter call updateRoute upon rebroadcasting a TraceRoute request - friend class FloodingRouter; + // Let FloodingRouter call updateRoute upon rebroadcasting a TraceRoute request + friend class FloodingRouter; - protected: - bool handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r) override; + protected: + bool handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r) override; - virtual MeshPacket *allocReply() override; + virtual MeshPacket *allocReply() override; - /* Call before rebroadcasting a RouteDiscovery payload in order to update - the route array containing the IDs of nodes this packet went through */ - void updateRoute(MeshPacket* p); - - private: - // Call to add your ID to the route array of a RouteDiscovery message - void appendMyID(RouteDiscovery *r); + /* Call before rebroadcasting a RouteDiscovery payload in order to update + the route array containing the IDs of nodes this packet went through */ + void updateRoute(MeshPacket *p); - /* Call to print the route array of a RouteDiscovery message. - Set origin to where the request came from. - Set dest to the ID of its destination, or NODENUM_BROADCAST if it has not yet arrived there. */ - void printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest); + private: + // Call to add your ID to the route array of a RouteDiscovery message + void appendMyID(RouteDiscovery *r); + /* Call to print the route array of a RouteDiscovery message. + Set origin to where the request came from. + Set dest to the ID of its destination, or NODENUM_BROADCAST if it has not yet arrived there. */ + void printRoute(RouteDiscovery *r, uint32_t origin, uint32_t dest); }; extern TraceRouteModule *traceRouteModule; \ No newline at end of file diff --git a/src/modules/WaypointModule.cpp b/src/modules/WaypointModule.cpp index 6be2ff51a..61af5db7b 100644 --- a/src/modules/WaypointModule.cpp +++ b/src/modules/WaypointModule.cpp @@ -1,7 +1,7 @@ -#include "configuration.h" #include "WaypointModule.h" #include "NodeDB.h" #include "PowerFSM.h" +#include "configuration.h" WaypointModule *waypointModule; @@ -10,7 +10,6 @@ ProcessMessage WaypointModule::handleReceived(const MeshPacket &mp) auto &p = mp.decoded; LOG_INFO("Received waypoint msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); - notifyObservers(&mp); return ProcessMessage::CONTINUE; // Let others look at this message also if they want diff --git a/src/modules/WaypointModule.h b/src/modules/WaypointModule.h index 1c940fd35..789e0915b 100644 --- a/src/modules/WaypointModule.h +++ b/src/modules/WaypointModule.h @@ -1,6 +1,6 @@ #pragma once -#include "SinglePortModule.h" #include "Observer.h" +#include "SinglePortModule.h" /** * Waypoint message handling for meshtastic @@ -14,10 +14,10 @@ class WaypointModule : public SinglePortModule, public Observabletx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header)); + memcpy(audioModule->tx_encode_frame, &audioModule->tx_header, sizeof(audioModule->tx_header)); LOG_INFO("Starting codec2 task\n"); @@ -79,11 +80,11 @@ void run_codec2(void* parameter) for (int i = 0; i < audioModule->adc_buffer_size; i++) audioModule->speech[i] = (int16_t)hp_filter.Update((float)audioModule->speech[i]); - codec2_encode(audioModule->codec2, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, audioModule->speech); - audioModule->tx_encode_frame_index += audioModule->encode_codec_size; + codec2_encode(audioModule->codec2, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, + audioModule->speech); + audioModule->tx_encode_frame_index += audioModule->encode_codec_size; - if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header))) - { + if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header))) { LOG_INFO("Sending %d codec2 bytes\n", audioModule->encode_frame_size); audioModule->sendPayload(); audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header); @@ -92,19 +93,18 @@ void run_codec2(void* parameter) if (audioModule->radio_state == RadioState::rx) { size_t bytesOut = 0; if (memcmp(audioModule->rx_encode_frame, &audioModule->tx_header, sizeof(audioModule->tx_header)) == 0) { - for (int i = 4; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size) - { + for (int i = 4; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size) { codec2_decode(audioModule->codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); - i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); + i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, + pdMS_TO_TICKS(500)); } } else { // if the buffer header does not match our own codec, make a temp decoding setup. - CODEC2* tmp_codec2 = codec2_create(audioModule->rx_encode_frame[3]); + CODEC2 *tmp_codec2 = codec2_create(audioModule->rx_encode_frame[3]); codec2_set_lpc_post_filter(tmp_codec2, 1, 0, 0.8, 0.2); int tmp_encode_codec_size = (codec2_bits_per_frame(tmp_codec2) + 7) / 8; int tmp_adc_buffer_size = codec2_samples_per_frame(tmp_codec2); - for (int i = 4; i < audioModule->rx_encode_frame_index; i += tmp_encode_codec_size) - { + for (int i = 4; i < audioModule->rx_encode_frame_index; i += tmp_encode_codec_size) { codec2_decode(tmp_codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i); i2s_write(I2S_PORT, &audioModule->output_buffer, tmp_adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500)); } @@ -125,16 +125,18 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), // moduleConfig.audio.ptt_pin = 39; if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { - LOG_INFO("Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + LOG_INFO("Setting up codec2 in mode %u", + (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); - memcpy(tx_header.magic,c2_magic,sizeof(c2_magic)); + memcpy(tx_header.magic, c2_magic, sizeof(c2_magic)); tx_header.mode = (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1; codec2_set_lpc_post_filter(codec2, 1, 0, 0.8, 0.2); encode_codec_size = (codec2_bits_per_frame(codec2) + 7) / 8; encode_frame_num = (Constants_DATA_PAYLOAD_LEN - sizeof(tx_header)) / encode_codec_size; encode_frame_size = encode_frame_num * encode_codec_size; // max 233 bytes + 4 header bytes adc_buffer_size = codec2_samples_per_frame(codec2); - LOG_INFO(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size); + LOG_INFO(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, + encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { disable(); @@ -151,17 +153,18 @@ void AudioModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int display->setFont(FONT_SMALL); display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); - display->drawStringf(0 + x, 0 + y, buffer, "Codec2 Mode %d Audio", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); + display->drawStringf(0 + x, 0 + y, buffer, "Codec2 Mode %d Audio", + (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1); display->setColor(WHITE); display->setFont(FONT_LARGE); display->setTextAlignment(TEXT_ALIGN_CENTER); switch (radio_state) { - case RadioState::tx: - display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "PTT"); - break; - default: - display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "Receive"); - break; + case RadioState::tx: + display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "PTT"); + break; + default: + display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "Receive"); + break; } } @@ -171,38 +174,37 @@ int32_t AudioModule::runOnce() esp_err_t res; if (firstTime) { // Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC - LOG_INFO("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); - i2s_config_t i2s_config = { - .mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), - .sample_rate = 8000, - .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, - .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, - .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S), - .intr_alloc_flags = 0, - .dma_buf_count = 8, - .dma_buf_len = adc_buffer_size, // 320 * 2 bytes - .use_apll = false, - .tx_desc_auto_clear = true, - .fixed_mclk = 0 - }; + LOG_INFO("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, + moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck); + i2s_config_t i2s_config = {.mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | + (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)), + .sample_rate = 8000, + .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, + .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, + .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S), + .intr_alloc_flags = 0, + .dma_buf_count = 8, + .dma_buf_len = adc_buffer_size, // 320 * 2 bytes + .use_apll = false, + .tx_desc_auto_clear = true, + .fixed_mclk = 0}; res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); - if(res != ESP_OK) + if (res != ESP_OK) LOG_ERROR("Failed to install I2S driver: %d\n", res); const i2s_pin_config_t pin_config = { .bck_io_num = moduleConfig.audio.i2s_sck, .ws_io_num = moduleConfig.audio.i2s_ws, .data_out_num = moduleConfig.audio.i2s_din ? moduleConfig.audio.i2s_din : I2S_PIN_NO_CHANGE, - .data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE - }; + .data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE}; res = i2s_set_pin(I2S_PORT, &pin_config); - if(res != ESP_OK) + if (res != ESP_OK) LOG_ERROR("Failed to set I2S pin config: %d\n", res); res = i2s_start(I2S_PORT); - if(res != ESP_OK) + if (res != ESP_OK) LOG_ERROR("Failed to start I2S: %d\n", res); - + radio_state = RadioState::rx; // Configure PTT input @@ -237,13 +239,14 @@ int32_t AudioModule::runOnce() if (radio_state == RadioState::tx) { // Get I2S data from the microphone and place in data buffer size_t bytesIn = 0; - res = i2s_read(I2S_PORT, adc_buffer + adc_buffer_index, adc_buffer_size - adc_buffer_index, &bytesIn, pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive. + res = i2s_read(I2S_PORT, adc_buffer + adc_buffer_index, adc_buffer_size - adc_buffer_index, &bytesIn, + pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive. if (res == ESP_OK) { adc_buffer_index += bytesIn; if (adc_buffer_index == adc_buffer_size) { adc_buffer_index = 0; - memcpy((void*)speech, (void*)adc_buffer, 2 * adc_buffer_size); + memcpy((void *)speech, (void *)adc_buffer, 2 * adc_buffer_size); // Notify run_codec2 task that the buffer is ready. radio_state = RadioState::tx; BaseType_t xHigherPriorityTaskWoken = pdFALSE; @@ -258,7 +261,6 @@ int32_t AudioModule::runOnce() } else { return disable(); } - } MeshPacket *AudioModule::allocReply() @@ -281,7 +283,7 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies) p->to = dest; p->decoded.want_response = wantReplies; - p->want_ack = false; // Audio is shoot&forget. No need to wait for ACKs. + p->want_ack = false; // Audio is shoot&forget. No need to wait for ACKs. p->priority = MeshPacket_Priority_MAX; // Audio is important, because realtime p->decoded.payload.size = tx_encode_frame_index; diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index 1a41ab6c4..fbf843d4f 100644 --- a/src/modules/esp32/AudioModule.h +++ b/src/modules/esp32/AudioModule.h @@ -6,12 +6,12 @@ #if defined(ARCH_ESP32) #include "NodeDB.h" #include -#include -#include -#include #include #include #include +#include +#include +#include enum RadioState { standby, rx, tx }; @@ -47,7 +47,7 @@ class AudioModule : public SinglePortModule, public ObservableshouldDraw(); } - virtual Observable* getUIFrameObservable() override { return this; } + virtual Observable *getUIFrameObservable() override { return this; } #if !HAS_SCREEN void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y); -#else - virtual void drawFrame( - OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override; +#else + virtual void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override; #endif /** Called to handle a particular incoming message - * @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it + * @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered + * for it */ virtual ProcessMessage handleReceived(const MeshPacket &mp) override; }; diff --git a/src/modules/esp32/RangeTestModule.cpp b/src/modules/esp32/RangeTestModule.cpp index 52a18def5..4230b71a5 100644 --- a/src/modules/esp32/RangeTestModule.cpp +++ b/src/modules/esp32/RangeTestModule.cpp @@ -82,8 +82,6 @@ int32_t RangeTestModule::runOnce() return disable(); // This thread does not need to run as a receiver } - - } } else { LOG_INFO("Range Test Module - Disabled\n"); diff --git a/src/mqtt/JSON.cpp b/src/mqtt/JSON.cpp index 65bff304a..e98bf47b9 100644 --- a/src/mqtt/JSON.cpp +++ b/src/mqtt/JSON.cpp @@ -30,9 +30,7 @@ * @access private * */ -JSON::JSON() -{ -} +JSON::JSON() {} /** * Parses a complete JSON encoded string @@ -45,24 +43,23 @@ JSON::JSON() */ JSONValue *JSON::Parse(const char *data) { - // Skip any preceding whitespace, end of data = no JSON = fail - if (!SkipWhitespace(&data)) - return NULL; + // Skip any preceding whitespace, end of data = no JSON = fail + if (!SkipWhitespace(&data)) + return NULL; - // We need the start of a value here now... - JSONValue *value = JSONValue::Parse(&data); - if (value == NULL) - return NULL; - - // Can be white space now and should be at the end of the string then... - if (SkipWhitespace(&data)) - { - delete value; - return NULL; - } - - // We're now at the end of the string - return value; + // We need the start of a value here now... + JSONValue *value = JSONValue::Parse(&data); + if (value == NULL) + return NULL; + + // Can be white space now and should be at the end of the string then... + if (SkipWhitespace(&data)) { + delete value; + return NULL; + } + + // We're now at the end of the string + return value; } /** @@ -76,10 +73,10 @@ JSONValue *JSON::Parse(const char *data) */ std::string JSON::Stringify(const JSONValue *value) { - if (value != NULL) - return value->Stringify(); - else - return ""; + if (value != NULL) + return value->Stringify(); + else + return ""; } /** @@ -93,10 +90,10 @@ std::string JSON::Stringify(const JSONValue *value) */ bool JSON::SkipWhitespace(const char **data) { - while (**data != 0 && (**data == ' ' || **data == '\t' || **data == '\r' || **data == '\n')) - (*data)++; - - return **data != 0; + while (**data != 0 && (**data == ' ' || **data == '\t' || **data == '\r' || **data == '\n')) + (*data)++; + + return **data != 0; } /** @@ -112,92 +109,100 @@ bool JSON::SkipWhitespace(const char **data) */ bool JSON::ExtractString(const char **data, std::string &str) { - str = ""; - - while (**data != 0) - { - // Save the char so we can change it if need be - char next_char = **data; - - // Escaping something? - if (next_char == '\\') - { - // Move over the escape char - (*data)++; - - // Deal with the escaped char - switch (**data) - { - case '"': next_char = '"'; break; - case '\\': next_char = '\\'; break; - case '/': next_char = '/'; break; - case 'b': next_char = '\b'; break; - case 'f': next_char = '\f'; break; - case 'n': next_char = '\n'; break; - case 'r': next_char = '\r'; break; - case 't': next_char = '\t'; break; - case 'u': - { - // We need 5 chars (4 hex + the 'u') or its not valid - if (!simplejson_csnlen(*data, 5)) - return false; - - // Deal with the chars - next_char = 0; - for (int i = 0; i < 4; i++) - { - // Do it first to move off the 'u' and leave us on the - // final hex digit as we move on by one later on + str = ""; + + while (**data != 0) { + // Save the char so we can change it if need be + char next_char = **data; + + // Escaping something? + if (next_char == '\\') { + // Move over the escape char (*data)++; - - next_char <<= 4; - - // Parse the hex digit - if (**data >= '0' && **data <= '9') - next_char |= (**data - '0'); - else if (**data >= 'A' && **data <= 'F') - next_char |= (10 + (**data - 'A')); - else if (**data >= 'a' && **data <= 'f') - next_char |= (10 + (**data - 'a')); - else - { - // Invalid hex digit = invalid JSON - return false; + + // Deal with the escaped char + switch (**data) { + case '"': + next_char = '"'; + break; + case '\\': + next_char = '\\'; + break; + case '/': + next_char = '/'; + break; + case 'b': + next_char = '\b'; + break; + case 'f': + next_char = '\f'; + break; + case 'n': + next_char = '\n'; + break; + case 'r': + next_char = '\r'; + break; + case 't': + next_char = '\t'; + break; + case 'u': { + // We need 5 chars (4 hex + the 'u') or its not valid + if (!simplejson_csnlen(*data, 5)) + return false; + + // Deal with the chars + next_char = 0; + for (int i = 0; i < 4; i++) { + // Do it first to move off the 'u' and leave us on the + // final hex digit as we move on by one later on + (*data)++; + + next_char <<= 4; + + // Parse the hex digit + if (**data >= '0' && **data <= '9') + next_char |= (**data - '0'); + else if (**data >= 'A' && **data <= 'F') + next_char |= (10 + (**data - 'A')); + else if (**data >= 'a' && **data <= 'f') + next_char |= (10 + (**data - 'a')); + else { + // Invalid hex digit = invalid JSON + return false; + } + } + break; + } + + // By the spec, only the above cases are allowed + default: + return false; } - } - break; } - - // By the spec, only the above cases are allowed - default: - return false; - } + + // End of the string? + else if (next_char == '"') { + (*data)++; + str.reserve(); // Remove unused capacity + return true; + } + + // Disallowed char? + else if (next_char < ' ' && next_char != '\t') { + // SPEC Violation: Allow tabs due to real world cases + return false; + } + + // Add the next char + str += next_char; + + // Move on + (*data)++; } - - // End of the string? - else if (next_char == '"') - { - (*data)++; - str.reserve(); // Remove unused capacity - return true; - } - - // Disallowed char? - else if (next_char < ' ' && next_char != '\t') - { - // SPEC Violation: Allow tabs due to real world cases - return false; - } - - // Add the next char - str += next_char; - - // Move on - (*data)++; - } - - // If we're here, the string ended incorrectly - return false; + + // If we're here, the string ended incorrectly + return false; } /** @@ -211,11 +216,11 @@ bool JSON::ExtractString(const char **data, std::string &str) */ double JSON::ParseInt(const char **data) { - double integer = 0; - while (**data != 0 && **data >= '0' && **data <= '9') - integer = integer * 10 + (*(*data)++ - '0'); - - return integer; + double integer = 0; + while (**data != 0 && **data >= '0' && **data <= '9') + integer = integer * 10 + (*(*data)++ - '0'); + + return integer; } /** @@ -229,13 +234,12 @@ double JSON::ParseInt(const char **data) */ double JSON::ParseDecimal(const char **data) { - double decimal = 0.0; - double factor = 0.1; - while (**data != 0 && **data >= '0' && **data <= '9') - { - int digit = (*(*data)++ - '0'); - decimal = decimal + digit * factor; - factor *= 0.1; - } - return decimal; + double decimal = 0.0; + double factor = 0.1; + while (**data != 0 && **data >= '0' && **data <= '9') { + int digit = (*(*data)++ - '0'); + decimal = decimal + digit * factor; + factor *= 0.1; + } + return decimal; } diff --git a/src/mqtt/JSON.h b/src/mqtt/JSON.h index d6532d696..33f34e684 100644 --- a/src/mqtt/JSON.h +++ b/src/mqtt/JSON.h @@ -25,46 +25,49 @@ #ifndef _JSON_H_ #define _JSON_H_ -#include -#include -#include #include +#include +#include +#include // Simple function to check a string 's' has at least 'n' characters -static inline bool simplejson_csnlen(const char *s, size_t n) { - if (s == 0) - return false; +static inline bool simplejson_csnlen(const char *s, size_t n) +{ + if (s == 0) + return false; - const char *save = s; - while (n-- > 0) - { - if (*(save++) == 0) return false; - } + const char *save = s; + while (n-- > 0) { + if (*(save++) == 0) + return false; + } - return true; + return true; } // Custom types class JSONValue; -typedef std::vector JSONArray; -typedef std::map JSONObject; +typedef std::vector JSONArray; +typedef std::map JSONObject; #include "JSONValue.h" class JSON { - friend class JSONValue; - - public: - static JSONValue* Parse(const char *data); - static std::string Stringify(const JSONValue *value); - protected: - static bool SkipWhitespace(const char **data); - static bool ExtractString(const char **data, std::string &str); - static double ParseInt(const char **data); - static double ParseDecimal(const char **data); - private: - JSON(); + friend class JSONValue; + + public: + static JSONValue *Parse(const char *data); + static std::string Stringify(const JSONValue *value); + + protected: + static bool SkipWhitespace(const char **data); + static bool ExtractString(const char **data, std::string &str); + static double ParseInt(const char **data); + static double ParseDecimal(const char **data); + + private: + JSON(); }; #endif diff --git a/src/mqtt/JSONValue.cpp b/src/mqtt/JSONValue.cpp index 13a01511e..10d79a4df 100644 --- a/src/mqtt/JSONValue.cpp +++ b/src/mqtt/JSONValue.cpp @@ -22,20 +22,32 @@ * THE SOFTWARE. */ -#include -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include #include "JSONValue.h" // Macros to free an array/object -#define FREE_ARRAY(x) { JSONArray::iterator iter; for (iter = x.begin(); iter != x.end(); iter++) { delete *iter; } } -#define FREE_OBJECT(x) { JSONObject::iterator iter; for (iter = x.begin(); iter != x.end(); iter++) { delete (*iter).second; } } +#define FREE_ARRAY(x) \ + { \ + JSONArray::iterator iter; \ + for (iter = x.begin(); iter != x.end(); iter++) { \ + delete *iter; \ + } \ + } +#define FREE_OBJECT(x) \ + { \ + JSONObject::iterator iter; \ + for (iter = x.begin(); iter != x.end(); iter++) { \ + delete (*iter).second; \ + } \ + } /** * Parses a JSON encoded value to a JSONValue object @@ -48,257 +60,232 @@ */ JSONValue *JSONValue::Parse(const char **data) { - // Is it a string? - if (**data == '"') - { - std::string str; - if (!JSON::ExtractString(&(++(*data)), str)) - return NULL; - else - return new JSONValue(str); - } + // Is it a string? + if (**data == '"') { + std::string str; + if (!JSON::ExtractString(&(++(*data)), str)) + return NULL; + else + return new JSONValue(str); + } - // Is it a boolean? - else if ((simplejson_csnlen(*data, 4) && strncasecmp(*data, "true", 4) == 0) || (simplejson_csnlen(*data, 5) && strncasecmp(*data, "false", 5) == 0)) - { - bool value = strncasecmp(*data, "true", 4) == 0; - (*data) += value ? 4 : 5; - return new JSONValue(value); - } + // Is it a boolean? + else if ((simplejson_csnlen(*data, 4) && strncasecmp(*data, "true", 4) == 0) || + (simplejson_csnlen(*data, 5) && strncasecmp(*data, "false", 5) == 0)) { + bool value = strncasecmp(*data, "true", 4) == 0; + (*data) += value ? 4 : 5; + return new JSONValue(value); + } - // Is it a null? - else if (simplejson_csnlen(*data, 4) && strncasecmp(*data, "null", 4) == 0) - { - (*data) += 4; - return new JSONValue(); - } + // Is it a null? + else if (simplejson_csnlen(*data, 4) && strncasecmp(*data, "null", 4) == 0) { + (*data) += 4; + return new JSONValue(); + } - // Is it a number? - else if (**data == '-' || (**data >= '0' && **data <= '9')) - { - // Negative? - bool neg = **data == '-'; - if (neg) (*data)++; + // Is it a number? + else if (**data == '-' || (**data >= '0' && **data <= '9')) { + // Negative? + bool neg = **data == '-'; + if (neg) + (*data)++; - double number = 0.0; + double number = 0.0; - // Parse the whole part of the number - only if it wasn't 0 - if (**data == '0') - (*data)++; - else if (**data >= '1' && **data <= '9') - number = JSON::ParseInt(data); - else - return NULL; + // Parse the whole part of the number - only if it wasn't 0 + if (**data == '0') + (*data)++; + else if (**data >= '1' && **data <= '9') + number = JSON::ParseInt(data); + else + return NULL; - // Could be a decimal now... - if (**data == '.') - { - (*data)++; + // Could be a decimal now... + if (**data == '.') { + (*data)++; - // Not get any digits? - if (!(**data >= '0' && **data <= '9')) - return NULL; + // Not get any digits? + if (!(**data >= '0' && **data <= '9')) + return NULL; - // Find the decimal and sort the decimal place out - // Use ParseDecimal as ParseInt won't work with decimals less than 0.1 - // thanks to Javier Abadia for the report & fix - double decimal = JSON::ParseDecimal(data); + // Find the decimal and sort the decimal place out + // Use ParseDecimal as ParseInt won't work with decimals less than 0.1 + // thanks to Javier Abadia for the report & fix + double decimal = JSON::ParseDecimal(data); - // Save the number - number += decimal; - } + // Save the number + number += decimal; + } - // Could be an exponent now... - if (**data == 'E' || **data == 'e') - { - (*data)++; + // Could be an exponent now... + if (**data == 'E' || **data == 'e') { + (*data)++; - // Check signage of expo - bool neg_expo = false; - if (**data == '-' || **data == '+') - { - neg_expo = **data == '-'; - (*data)++; - } + // Check signage of expo + bool neg_expo = false; + if (**data == '-' || **data == '+') { + neg_expo = **data == '-'; + (*data)++; + } - // Not get any digits? - if (!(**data >= '0' && **data <= '9')) - return NULL; + // Not get any digits? + if (!(**data >= '0' && **data <= '9')) + return NULL; - // Sort the expo out - double expo = JSON::ParseInt(data); - for (double i = 0.0; i < expo; i++) - number = neg_expo ? (number / 10.0) : (number * 10.0); - } + // Sort the expo out + double expo = JSON::ParseInt(data); + for (double i = 0.0; i < expo; i++) + number = neg_expo ? (number / 10.0) : (number * 10.0); + } - // Was it neg? - if (neg) number *= -1; + // Was it neg? + if (neg) + number *= -1; - return new JSONValue(number); - } + return new JSONValue(number); + } - // An object? - else if (**data == '{') - { - JSONObject object; + // An object? + else if (**data == '{') { + JSONObject object; - (*data)++; + (*data)++; - while (**data != 0) - { - // Whitespace at the start? - if (!JSON::SkipWhitespace(data)) - { - FREE_OBJECT(object); - return NULL; - } + while (**data != 0) { + // Whitespace at the start? + if (!JSON::SkipWhitespace(data)) { + FREE_OBJECT(object); + return NULL; + } - // Special case - empty object - if (object.size() == 0 && **data == '}') - { - (*data)++; - return new JSONValue(object); - } + // Special case - empty object + if (object.size() == 0 && **data == '}') { + (*data)++; + return new JSONValue(object); + } - // We want a string now... - std::string name; - if (!JSON::ExtractString(&(++(*data)), name)) - { - FREE_OBJECT(object); - return NULL; - } + // We want a string now... + std::string name; + if (!JSON::ExtractString(&(++(*data)), name)) { + FREE_OBJECT(object); + return NULL; + } - // More whitespace? - if (!JSON::SkipWhitespace(data)) - { - FREE_OBJECT(object); - return NULL; - } + // More whitespace? + if (!JSON::SkipWhitespace(data)) { + FREE_OBJECT(object); + return NULL; + } - // Need a : now - if (*((*data)++) != ':') - { - FREE_OBJECT(object); - return NULL; - } + // Need a : now + if (*((*data)++) != ':') { + FREE_OBJECT(object); + return NULL; + } - // More whitespace? - if (!JSON::SkipWhitespace(data)) - { - FREE_OBJECT(object); - return NULL; - } + // More whitespace? + if (!JSON::SkipWhitespace(data)) { + FREE_OBJECT(object); + return NULL; + } - // The value is here - JSONValue *value = Parse(data); - if (value == NULL) - { - FREE_OBJECT(object); - return NULL; - } + // The value is here + JSONValue *value = Parse(data); + if (value == NULL) { + FREE_OBJECT(object); + return NULL; + } - // Add the name:value - if (object.find(name) != object.end()) - delete object[name]; - object[name] = value; + // Add the name:value + if (object.find(name) != object.end()) + delete object[name]; + object[name] = value; - // More whitespace? - if (!JSON::SkipWhitespace(data)) - { - FREE_OBJECT(object); - return NULL; - } + // More whitespace? + if (!JSON::SkipWhitespace(data)) { + FREE_OBJECT(object); + return NULL; + } - // End of object? - if (**data == '}') - { - (*data)++; - return new JSONValue(object); - } + // End of object? + if (**data == '}') { + (*data)++; + return new JSONValue(object); + } - // Want a , now - if (**data != ',') - { - FREE_OBJECT(object); - return NULL; - } + // Want a , now + if (**data != ',') { + FREE_OBJECT(object); + return NULL; + } - (*data)++; - } + (*data)++; + } - // Only here if we ran out of data - FREE_OBJECT(object); - return NULL; - } + // Only here if we ran out of data + FREE_OBJECT(object); + return NULL; + } - // An array? - else if (**data == '[') - { - JSONArray array; + // An array? + else if (**data == '[') { + JSONArray array; - (*data)++; + (*data)++; - while (**data != 0) - { - // Whitespace at the start? - if (!JSON::SkipWhitespace(data)) - { - FREE_ARRAY(array); - return NULL; - } + while (**data != 0) { + // Whitespace at the start? + if (!JSON::SkipWhitespace(data)) { + FREE_ARRAY(array); + return NULL; + } - // Special case - empty array - if (array.size() == 0 && **data == ']') - { - (*data)++; - return new JSONValue(array); - } + // Special case - empty array + if (array.size() == 0 && **data == ']') { + (*data)++; + return new JSONValue(array); + } - // Get the value - JSONValue *value = Parse(data); - if (value == NULL) - { - FREE_ARRAY(array); - return NULL; - } + // Get the value + JSONValue *value = Parse(data); + if (value == NULL) { + FREE_ARRAY(array); + return NULL; + } - // Add the value - array.push_back(value); + // Add the value + array.push_back(value); - // More whitespace? - if (!JSON::SkipWhitespace(data)) - { - FREE_ARRAY(array); - return NULL; - } + // More whitespace? + if (!JSON::SkipWhitespace(data)) { + FREE_ARRAY(array); + return NULL; + } - // End of array? - if (**data == ']') - { - (*data)++; - return new JSONValue(array); - } + // End of array? + if (**data == ']') { + (*data)++; + return new JSONValue(array); + } - // Want a , now - if (**data != ',') - { - FREE_ARRAY(array); - return NULL; - } + // Want a , now + if (**data != ',') { + FREE_ARRAY(array); + return NULL; + } - (*data)++; - } + (*data)++; + } - // Only here if we ran out of data - FREE_ARRAY(array); - return NULL; - } + // Only here if we ran out of data + FREE_ARRAY(array); + return NULL; + } - // Ran out of possibilites, it's bad! - else - { - return NULL; - } + // Ran out of possibilites, it's bad! + else { + return NULL; + } } /** @@ -308,7 +295,7 @@ JSONValue *JSONValue::Parse(const char **data) */ JSONValue::JSONValue(/*NULL*/) { - type = JSONType_Null; + type = JSONType_Null; } /** @@ -320,8 +307,8 @@ JSONValue::JSONValue(/*NULL*/) */ JSONValue::JSONValue(const char *m_char_value) { - type = JSONType_String; - string_value = new std::string(std::string(m_char_value)); + type = JSONType_String; + string_value = new std::string(std::string(m_char_value)); } /** @@ -333,8 +320,8 @@ JSONValue::JSONValue(const char *m_char_value) */ JSONValue::JSONValue(const std::string &m_string_value) { - type = JSONType_String; - string_value = new std::string(m_string_value); + type = JSONType_String; + string_value = new std::string(m_string_value); } /** @@ -346,8 +333,8 @@ JSONValue::JSONValue(const std::string &m_string_value) */ JSONValue::JSONValue(bool m_bool_value) { - type = JSONType_Bool; - bool_value = m_bool_value; + type = JSONType_Bool; + bool_value = m_bool_value; } /** @@ -359,8 +346,8 @@ JSONValue::JSONValue(bool m_bool_value) */ JSONValue::JSONValue(double m_number_value) { - type = JSONType_Number; - number_value = m_number_value; + type = JSONType_Number; + number_value = m_number_value; } /** @@ -372,8 +359,8 @@ JSONValue::JSONValue(double m_number_value) */ JSONValue::JSONValue(int m_integer_value) { - type = JSONType_Number; - number_value = (double) m_integer_value; + type = JSONType_Number; + number_value = (double)m_integer_value; } /** @@ -385,8 +372,8 @@ JSONValue::JSONValue(int m_integer_value) */ JSONValue::JSONValue(const JSONArray &m_array_value) { - type = JSONType_Array; - array_value = new JSONArray(m_array_value); + type = JSONType_Array; + array_value = new JSONArray(m_array_value); } /** @@ -398,8 +385,8 @@ JSONValue::JSONValue(const JSONArray &m_array_value) */ JSONValue::JSONValue(const JSONObject &m_object_value) { - type = JSONType_Object; - object_value = new JSONObject(m_object_value); + type = JSONType_Object; + object_value = new JSONObject(m_object_value); } /** @@ -411,49 +398,45 @@ JSONValue::JSONValue(const JSONObject &m_object_value) */ JSONValue::JSONValue(const JSONValue &m_source) { - type = m_source.type; + type = m_source.type; - switch (type) - { - case JSONType_String: - string_value = new std::string(*m_source.string_value); - break; + switch (type) { + case JSONType_String: + string_value = new std::string(*m_source.string_value); + break; - case JSONType_Bool: - bool_value = m_source.bool_value; - break; + case JSONType_Bool: + bool_value = m_source.bool_value; + break; - case JSONType_Number: - number_value = m_source.number_value; - break; + case JSONType_Number: + number_value = m_source.number_value; + break; - case JSONType_Array: - { - JSONArray source_array = *m_source.array_value; - JSONArray::iterator iter; - array_value = new JSONArray(); - for (iter = source_array.begin(); iter != source_array.end(); iter++) - array_value->push_back(new JSONValue(**iter)); - break; - } + case JSONType_Array: { + JSONArray source_array = *m_source.array_value; + JSONArray::iterator iter; + array_value = new JSONArray(); + for (iter = source_array.begin(); iter != source_array.end(); iter++) + array_value->push_back(new JSONValue(**iter)); + break; + } - case JSONType_Object: - { - JSONObject source_object = *m_source.object_value; - object_value = new JSONObject(); - JSONObject::iterator iter; - for (iter = source_object.begin(); iter != source_object.end(); iter++) - { - std::string name = (*iter).first; - (*object_value)[name] = new JSONValue(*((*iter).second)); - } - break; - } + case JSONType_Object: { + JSONObject source_object = *m_source.object_value; + object_value = new JSONObject(); + JSONObject::iterator iter; + for (iter = source_object.begin(); iter != source_object.end(); iter++) { + std::string name = (*iter).first; + (*object_value)[name] = new JSONValue(*((*iter).second)); + } + break; + } - case JSONType_Null: - // Nothing to do. - break; - } + case JSONType_Null: + // Nothing to do. + break; + } } /** @@ -464,26 +447,20 @@ JSONValue::JSONValue(const JSONValue &m_source) */ JSONValue::~JSONValue() { - if (type == JSONType_Array) - { - JSONArray::iterator iter; - for (iter = array_value->begin(); iter != array_value->end(); iter++) - delete *iter; - delete array_value; - } - else if (type == JSONType_Object) - { - JSONObject::iterator iter; - for (iter = object_value->begin(); iter != object_value->end(); iter++) - { - delete (*iter).second; - } - delete object_value; - } - else if (type == JSONType_String) - { - delete string_value; - } + if (type == JSONType_Array) { + JSONArray::iterator iter; + for (iter = array_value->begin(); iter != array_value->end(); iter++) + delete *iter; + delete array_value; + } else if (type == JSONType_Object) { + JSONObject::iterator iter; + for (iter = object_value->begin(); iter != object_value->end(); iter++) { + delete (*iter).second; + } + delete object_value; + } else if (type == JSONType_String) { + delete string_value; + } } /** @@ -495,7 +472,7 @@ JSONValue::~JSONValue() */ bool JSONValue::IsNull() const { - return type == JSONType_Null; + return type == JSONType_Null; } /** @@ -507,7 +484,7 @@ bool JSONValue::IsNull() const */ bool JSONValue::IsString() const { - return type == JSONType_String; + return type == JSONType_String; } /** @@ -519,7 +496,7 @@ bool JSONValue::IsString() const */ bool JSONValue::IsBool() const { - return type == JSONType_Bool; + return type == JSONType_Bool; } /** @@ -531,7 +508,7 @@ bool JSONValue::IsBool() const */ bool JSONValue::IsNumber() const { - return type == JSONType_Number; + return type == JSONType_Number; } /** @@ -543,7 +520,7 @@ bool JSONValue::IsNumber() const */ bool JSONValue::IsArray() const { - return type == JSONType_Array; + return type == JSONType_Array; } /** @@ -555,7 +532,7 @@ bool JSONValue::IsArray() const */ bool JSONValue::IsObject() const { - return type == JSONType_Object; + return type == JSONType_Object; } /** @@ -568,7 +545,7 @@ bool JSONValue::IsObject() const */ const std::string &JSONValue::AsString() const { - return (*string_value); + return (*string_value); } /** @@ -581,7 +558,7 @@ const std::string &JSONValue::AsString() const */ bool JSONValue::AsBool() const { - return bool_value; + return bool_value; } /** @@ -594,7 +571,7 @@ bool JSONValue::AsBool() const */ double JSONValue::AsNumber() const { - return number_value; + return number_value; } /** @@ -607,7 +584,7 @@ double JSONValue::AsNumber() const */ const JSONArray &JSONValue::AsArray() const { - return (*array_value); + return (*array_value); } /** @@ -620,7 +597,7 @@ const JSONArray &JSONValue::AsArray() const */ const JSONObject &JSONValue::AsObject() const { - return (*object_value); + return (*object_value); } /** @@ -634,15 +611,14 @@ const JSONObject &JSONValue::AsObject() const */ std::size_t JSONValue::CountChildren() const { - switch (type) - { - case JSONType_Array: - return array_value->size(); - case JSONType_Object: - return object_value->size(); - default: - return 0; - } + switch (type) { + case JSONType_Array: + return array_value->size(); + case JSONType_Object: + return object_value->size(); + default: + return 0; + } } /** @@ -655,14 +631,11 @@ std::size_t JSONValue::CountChildren() const */ bool JSONValue::HasChild(std::size_t index) const { - if (type == JSONType_Array) - { - return index < array_value->size(); - } - else - { - return false; - } + if (type == JSONType_Array) { + return index < array_value->size(); + } else { + return false; + } } /** @@ -676,14 +649,11 @@ bool JSONValue::HasChild(std::size_t index) const */ JSONValue *JSONValue::Child(std::size_t index) { - if (index < array_value->size()) - { - return (*array_value)[index]; - } - else - { - return NULL; - } + if (index < array_value->size()) { + return (*array_value)[index]; + } else { + return NULL; + } } /** @@ -694,16 +664,13 @@ JSONValue *JSONValue::Child(std::size_t index) * * @return bool Returns true if the object has a value at the given key. */ -bool JSONValue::HasChild(const char* name) const +bool JSONValue::HasChild(const char *name) const { - if (type == JSONType_Object) - { - return object_value->find(name) != object_value->end(); - } - else - { - return false; - } + if (type == JSONType_Object) { + return object_value->find(name) != object_value->end(); + } else { + return false; + } } /** @@ -715,17 +682,14 @@ bool JSONValue::HasChild(const char* name) const * @return JSONValue* Returns JSONValue for the given key in the object * or NULL if it doesn't exist. */ -JSONValue* JSONValue::Child(const char* name) +JSONValue *JSONValue::Child(const char *name) { - JSONObject::const_iterator it = object_value->find(name); - if (it != object_value->end()) - { - return it->second; - } - else - { - return NULL; - } + JSONObject::const_iterator it = object_value->find(name); + if (it != object_value->end()) { + return it->second; + } else { + return NULL; + } } /** @@ -738,20 +702,18 @@ JSONValue* JSONValue::Child(const char* name) */ std::vector JSONValue::ObjectKeys() const { - std::vector keys; + std::vector keys; - if (type == JSONType_Object) - { - JSONObject::const_iterator iter = object_value->begin(); - while (iter != object_value->end()) - { - keys.push_back(iter->first); + if (type == JSONType_Object) { + JSONObject::const_iterator iter = object_value->begin(); + while (iter != object_value->end()) { + keys.push_back(iter->first); - iter++; - } - } + iter++; + } + } - return keys; + return keys; } /** @@ -765,11 +727,10 @@ std::vector JSONValue::ObjectKeys() const */ std::string JSONValue::Stringify(bool const prettyprint) const { - size_t const indentDepth = prettyprint ? 1 : 0; - return StringifyImpl(indentDepth); + size_t const indentDepth = prettyprint ? 1 : 0; + return StringifyImpl(indentDepth); } - /** * Creates a JSON encoded string for the value with all necessary characters escaped * @@ -781,75 +742,68 @@ std::string JSONValue::Stringify(bool const prettyprint) const */ std::string JSONValue::StringifyImpl(size_t const indentDepth) const { - std::string ret_string; - size_t const indentDepth1 = indentDepth ? indentDepth + 1 : 0; - std::string const indentStr = Indent(indentDepth); - std::string const indentStr1 = Indent(indentDepth1); + std::string ret_string; + size_t const indentDepth1 = indentDepth ? indentDepth + 1 : 0; + std::string const indentStr = Indent(indentDepth); + std::string const indentStr1 = Indent(indentDepth1); - switch (type) - { - case JSONType_Null: - ret_string = "null"; - break; + switch (type) { + case JSONType_Null: + ret_string = "null"; + break; - case JSONType_String: - ret_string = StringifyString(*string_value); - break; + case JSONType_String: + ret_string = StringifyString(*string_value); + break; - case JSONType_Bool: - ret_string = bool_value ? "true" : "false"; - break; + case JSONType_Bool: + ret_string = bool_value ? "true" : "false"; + break; - case JSONType_Number: - { - if (isinf(number_value) || isnan(number_value)) - ret_string = "null"; - else - { - std::stringstream ss; - ss.precision(15); - ss << number_value; - ret_string = ss.str(); - } - break; - } + case JSONType_Number: { + if (isinf(number_value) || isnan(number_value)) + ret_string = "null"; + else { + std::stringstream ss; + ss.precision(15); + ss << number_value; + ret_string = ss.str(); + } + break; + } - case JSONType_Array: - { - ret_string = indentDepth ? "[\n" + indentStr1 : "["; - JSONArray::const_iterator iter = array_value->begin(); - while (iter != array_value->end()) - { - ret_string += (*iter)->StringifyImpl(indentDepth1); + case JSONType_Array: { + ret_string = indentDepth ? "[\n" + indentStr1 : "["; + JSONArray::const_iterator iter = array_value->begin(); + while (iter != array_value->end()) { + ret_string += (*iter)->StringifyImpl(indentDepth1); - // Not at the end - add a separator - if (++iter != array_value->end()) - ret_string += ","; - } - ret_string += indentDepth ? "\n" + indentStr + "]" : "]"; - break; - } + // Not at the end - add a separator + if (++iter != array_value->end()) + ret_string += ","; + } + ret_string += indentDepth ? "\n" + indentStr + "]" : "]"; + break; + } - case JSONType_Object: - { - ret_string = indentDepth ? "{\n" + indentStr1 : "{"; - JSONObject::const_iterator iter = object_value->begin(); - while (iter != object_value->end()) - { - ret_string += StringifyString((*iter).first); - ret_string += ":"; - ret_string += (*iter).second->StringifyImpl(indentDepth1); + case JSONType_Object: { + ret_string = indentDepth ? "{\n" + indentStr1 : "{"; + JSONObject::const_iterator iter = object_value->begin(); + while (iter != object_value->end()) { + ret_string += StringifyString((*iter).first); + ret_string += ":"; + ret_string += (*iter).second->StringifyImpl(indentDepth1); - // Not at the end - add a separator - if (++iter != object_value->end()) - ret_string += ","; - } - ret_string += indentDepth ? "\n" + indentStr + "}" : "}"; - break; - } - } + // Not at the end - add a separator + if (++iter != object_value->end()) + ret_string += ","; + } + ret_string += indentDepth ? "\n" + indentStr + "}" : "}"; + break; + } + } - return ret_string; + return ret_string; } /** @@ -865,61 +819,44 @@ std::string JSONValue::StringifyImpl(size_t const indentDepth) const */ std::string JSONValue::StringifyString(const std::string &str) { - std::string str_out = "\""; + std::string str_out = "\""; - std::string::const_iterator iter = str.begin(); - while (iter != str.end()) - { - char chr = *iter; + std::string::const_iterator iter = str.begin(); + while (iter != str.end()) { + char chr = *iter; - if (chr == '"' || chr == '\\' || chr == '/') - { - str_out += '\\'; - str_out += chr; - } - else if (chr == '\b') - { - str_out += "\\b"; - } - else if (chr == '\f') - { - str_out += "\\f"; - } - else if (chr == '\n') - { - str_out += "\\n"; - } - else if (chr == '\r') - { - str_out += "\\r"; - } - else if (chr == '\t') - { - str_out += "\\t"; - } - else if (chr < ' ' || chr > 126) - { - str_out += "\\u"; - for (int i = 0; i < 4; i++) - { - int value = (chr >> 12) & 0xf; - if (value >= 0 && value <= 9) - str_out += (char)('0' + value); - else if (value >= 10 && value <= 15) - str_out += (char)('A' + (value - 10)); - chr <<= 4; - } - } - else - { - str_out += chr; - } + if (chr == '"' || chr == '\\' || chr == '/') { + str_out += '\\'; + str_out += chr; + } else if (chr == '\b') { + str_out += "\\b"; + } else if (chr == '\f') { + str_out += "\\f"; + } else if (chr == '\n') { + str_out += "\\n"; + } else if (chr == '\r') { + str_out += "\\r"; + } else if (chr == '\t') { + str_out += "\\t"; + } else if (chr < ' ' || chr > 126) { + str_out += "\\u"; + for (int i = 0; i < 4; i++) { + int value = (chr >> 12) & 0xf; + if (value >= 0 && value <= 9) + str_out += (char)('0' + value); + else if (value >= 10 && value <= 15) + str_out += (char)('A' + (value - 10)); + chr <<= 4; + } + } else { + str_out += chr; + } - iter++; - } + iter++; + } - str_out += "\""; - return str_out; + str_out += "\""; + return str_out; } /** @@ -933,8 +870,8 @@ std::string JSONValue::StringifyString(const std::string &str) */ std::string JSONValue::Indent(size_t depth) { - const size_t indent_step = 2; - depth ? --depth : 0; - std::string indentStr(depth * indent_step, ' '); - return indentStr; + const size_t indent_step = 2; + depth ? --depth : 0; + std::string indentStr(depth * indent_step, ' '); + return indentStr; } diff --git a/src/mqtt/JSONValue.h b/src/mqtt/JSONValue.h index c915a10a6..9b231e93f 100644 --- a/src/mqtt/JSONValue.h +++ b/src/mqtt/JSONValue.h @@ -25,8 +25,8 @@ #ifndef _JSONVALUE_H_ #define _JSONVALUE_H_ -#include #include +#include #include "JSON.h" @@ -36,60 +36,59 @@ enum JSONType { JSONType_Null, JSONType_String, JSONType_Bool, JSONType_Number, class JSONValue { - friend class JSON; + friend class JSON; - public: - JSONValue(/*NULL*/); - JSONValue(const char *m_char_value); - JSONValue(const std::string &m_string_value); - JSONValue(bool m_bool_value); - JSONValue(double m_number_value); - JSONValue(int m_integer_value); - JSONValue(const JSONArray &m_array_value); - JSONValue(const JSONObject &m_object_value); - JSONValue(const JSONValue &m_source); - ~JSONValue(); + public: + JSONValue(/*NULL*/); + JSONValue(const char *m_char_value); + JSONValue(const std::string &m_string_value); + JSONValue(bool m_bool_value); + JSONValue(double m_number_value); + JSONValue(int m_integer_value); + JSONValue(const JSONArray &m_array_value); + JSONValue(const JSONObject &m_object_value); + JSONValue(const JSONValue &m_source); + ~JSONValue(); - bool IsNull() const; - bool IsString() const; - bool IsBool() const; - bool IsNumber() const; - bool IsArray() const; - bool IsObject() const; + bool IsNull() const; + bool IsString() const; + bool IsBool() const; + bool IsNumber() const; + bool IsArray() const; + bool IsObject() const; - const std::string &AsString() const; - bool AsBool() const; - double AsNumber() const; - const JSONArray &AsArray() const; - const JSONObject &AsObject() const; + const std::string &AsString() const; + bool AsBool() const; + double AsNumber() const; + const JSONArray &AsArray() const; + const JSONObject &AsObject() const; - std::size_t CountChildren() const; - bool HasChild(std::size_t index) const; - JSONValue *Child(std::size_t index); - bool HasChild(const char* name) const; - JSONValue *Child(const char* name); - std::vector ObjectKeys() const; + std::size_t CountChildren() const; + bool HasChild(std::size_t index) const; + JSONValue *Child(std::size_t index); + bool HasChild(const char *name) const; + JSONValue *Child(const char *name); + std::vector ObjectKeys() const; - std::string Stringify(bool const prettyprint = false) const; - protected: - static JSONValue *Parse(const char **data); + std::string Stringify(bool const prettyprint = false) const; - private: - static std::string StringifyString(const std::string &str); - std::string StringifyImpl(size_t const indentDepth) const; - static std::string Indent(size_t depth); + protected: + static JSONValue *Parse(const char **data); - JSONType type; + private: + static std::string StringifyString(const std::string &str); + std::string StringifyImpl(size_t const indentDepth) const; + static std::string Indent(size_t depth); - union - { - bool bool_value; - double number_value; - std::string *string_value; - JSONArray *array_value; - JSONObject *object_value; - }; + JSONType type; + union { + bool bool_value; + double number_value; + std::string *string_value; + JSONArray *array_value; + JSONObject *object_value; + }; }; #endif diff --git a/src/network-stubs.cpp b/src/network-stubs.cpp index 0119fa1be..1737579d5 100644 --- a/src/network-stubs.cpp +++ b/src/network-stubs.cpp @@ -2,13 +2,15 @@ #if (HAS_WIFI == 0) -bool initWifi() { +bool initWifi() +{ return false; } void deinitWifi() {} -bool isWifiAvailable() { +bool isWifiAvailable() +{ return false; } @@ -16,11 +18,13 @@ bool isWifiAvailable() { #if (HAS_ETHERNET == 0) -bool initEthernet() { +bool initEthernet() +{ return false; } -bool isEthernetAvailable() { +bool isEthernetAvailable() +{ return false; } diff --git a/src/nimble/NimbleBluetooth.cpp b/src/nimble/NimbleBluetooth.cpp index 78bf135fe..2e346f760 100644 --- a/src/nimble/NimbleBluetooth.cpp +++ b/src/nimble/NimbleBluetooth.cpp @@ -1,11 +1,11 @@ -#include "configuration.h" #include "NimbleBluetooth.h" #include "BluetoothCommon.h" #include "PowerFSM.h" -#include "sleep.h" +#include "configuration.h" #include "main.h" #include "mesh/PhoneAPI.h" #include "mesh/mesh-pb-constants.h" +#include "sleep.h" #include NimBLECharacteristic *fromNumCharacteristic; @@ -18,12 +18,12 @@ class BluetoothPhoneAPI : public PhoneAPI /** * Subclasses can use this as a hook to provide custom notifications for their transport (i.e. bluetooth notifies) */ - virtual void onNowHasData(uint32_t fromRadioNum) + virtual void onNowHasData(uint32_t fromRadioNum) { PhoneAPI::onNowHasData(fromRadioNum); LOG_INFO("BLE notify fromNum\n"); - + uint8_t val[4]; put_le32(val, fromRadioNum); @@ -32,10 +32,7 @@ class BluetoothPhoneAPI : public PhoneAPI } /// Check the current underlying physical link to see if the client is currently connected - virtual bool checkIsConnected() - { - return bleServer && bleServer->getConnectedCount() > 0; - } + virtual bool checkIsConnected() { return bleServer && bleServer->getConnectedCount() > 0; } }; static BluetoothPhoneAPI *bluetoothPhoneAPI; @@ -43,19 +40,21 @@ static BluetoothPhoneAPI *bluetoothPhoneAPI; * Subclasses can use this as a hook to provide custom notifications for their transport (i.e. bluetooth notifies) */ -class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks +class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks { - virtual void onWrite(NimBLECharacteristic *pCharacteristic) { + virtual void onWrite(NimBLECharacteristic *pCharacteristic) + { LOG_INFO("To Radio onwrite\n"); auto val = pCharacteristic->getValue(); - + bluetoothPhoneAPI->handleToRadio(val.data(), val.length()); } }; -class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks +class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks { - virtual void onRead(NimBLECharacteristic *pCharacteristic) { + virtual void onRead(NimBLECharacteristic *pCharacteristic) + { LOG_INFO("From Radio onread\n"); uint8_t fromRadioBytes[FromRadio_size]; size_t numBytes = bluetoothPhoneAPI->getFromRadio(fromRadioBytes); @@ -66,15 +65,16 @@ class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks } }; -class NimbleBluetoothServerCallback : public NimBLEServerCallbacks +class NimbleBluetoothServerCallback : public NimBLEServerCallbacks { - virtual uint32_t onPassKeyRequest() { + virtual uint32_t onPassKeyRequest() + { uint32_t passkey = config.bluetooth.fixed_pin; - + if (config.bluetooth.mode == Config_BluetoothConfig_PairingMode_RANDOM_PIN) { LOG_INFO("Using random passkey\n"); // This is the passkey to be entered on peer - we pick a number >100,000 to ensure 6 digits - passkey = random(100000, 999999); + passkey = random(100000, 999999); } LOG_INFO("*** Enter passkey %d on the peer side ***\n", passkey); @@ -85,7 +85,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks return passkey; } - virtual void onAuthenticationComplete(ble_gap_conn_desc *desc) + virtual void onAuthenticationComplete(ble_gap_conn_desc *desc) { LOG_INFO("BLE authentication complete\n"); @@ -96,10 +96,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks // bluetoothPhoneAPI->setInitialState(); } - virtual void onDisconnect(NimBLEServer* pServer, ble_gap_conn_desc *desc) - { - LOG_INFO("BLE disconnect\n"); - } + virtual void onDisconnect(NimBLEServer *pServer, ble_gap_conn_desc *desc) { LOG_INFO("BLE disconnect\n"); } }; static NimbleBluetoothToRadioCallback *toRadioCallbacks; @@ -109,7 +106,7 @@ void NimbleBluetooth::shutdown() { // Shutdown bluetooth for minimum power draw LOG_INFO("Disable bluetooth\n"); - //Bluefruit.Advertising.stop(); + // Bluefruit.Advertising.stop(); NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising(); pAdvertising->reset(); pAdvertising->stop(); @@ -135,7 +132,7 @@ void NimbleBluetooth::setup() NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_ONLY); } bleServer = NimBLEDevice::createServer(); - + NimbleBluetoothServerCallback *serverCallbacks = new NimbleBluetoothServerCallback(); bleServer->setCallbacks(serverCallbacks, true); @@ -143,7 +140,7 @@ void NimbleBluetooth::setup() startAdvertising(); } -void NimbleBluetooth::setupService() +void NimbleBluetooth::setupService() { NimBLEService *bleService = bleServer->createService(MESH_SERVICE_UUID); NimBLECharacteristic *ToRadioCharacteristic; @@ -153,11 +150,14 @@ void NimbleBluetooth::setupService() ToRadioCharacteristic = bleService->createCharacteristic(TORADIO_UUID, NIMBLE_PROPERTY::WRITE); FromRadioCharacteristic = bleService->createCharacteristic(FROMRADIO_UUID, NIMBLE_PROPERTY::READ); fromNumCharacteristic = bleService->createCharacteristic(FROMNUM_UUID, NIMBLE_PROPERTY::NOTIFY | NIMBLE_PROPERTY::READ); - } - else { - ToRadioCharacteristic = bleService->createCharacteristic(TORADIO_UUID, NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::WRITE_AUTHEN | NIMBLE_PROPERTY::WRITE_ENC); - FromRadioCharacteristic = bleService->createCharacteristic(FROMRADIO_UUID, NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::READ_AUTHEN | NIMBLE_PROPERTY::READ_ENC); - fromNumCharacteristic = bleService->createCharacteristic(FROMNUM_UUID, NIMBLE_PROPERTY::NOTIFY | NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::READ_AUTHEN | NIMBLE_PROPERTY::READ_ENC); + } else { + ToRadioCharacteristic = bleService->createCharacteristic( + TORADIO_UUID, NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::WRITE_AUTHEN | NIMBLE_PROPERTY::WRITE_ENC); + FromRadioCharacteristic = bleService->createCharacteristic( + FROMRADIO_UUID, NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::READ_AUTHEN | NIMBLE_PROPERTY::READ_ENC); + fromNumCharacteristic = + bleService->createCharacteristic(FROMNUM_UUID, NIMBLE_PROPERTY::NOTIFY | NIMBLE_PROPERTY::READ | + NIMBLE_PROPERTY::READ_AUTHEN | NIMBLE_PROPERTY::READ_ENC); } bluetoothPhoneAPI = new BluetoothPhoneAPI(); @@ -170,7 +170,7 @@ void NimbleBluetooth::setupService() bleService->start(); } -void NimbleBluetooth::startAdvertising() +void NimbleBluetooth::startAdvertising() { NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising(); pAdvertising->reset(); @@ -181,7 +181,7 @@ void NimbleBluetooth::startAdvertising() /// Given a level between 0-100, update the BLE attribute void updateBatteryLevel(uint8_t level) { - //blebas.write(level); + // blebas.write(level); } void NimbleBluetooth::clearBonds() @@ -190,7 +190,7 @@ void NimbleBluetooth::clearBonds() NimBLEDevice::deleteAllBonds(); } -void clearNVS() +void clearNVS() { NimBLEDevice::deleteAllBonds(); #ifdef ARCH_ESP32 diff --git a/src/platform/esp32/BleOta.cpp b/src/platform/esp32/BleOta.cpp index ef93a240b..698336f69 100644 --- a/src/platform/esp32/BleOta.cpp +++ b/src/platform/esp32/BleOta.cpp @@ -1,43 +1,46 @@ -#include "Arduino.h" #include "BleOta.h" +#include "Arduino.h" #include static const String MESHTASTIC_OTA_APP_PROJECT_NAME("Meshtastic-OTA"); -const esp_partition_t* BleOta::findEspOtaAppPartition() { - const esp_partition_t *part = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, nullptr); +const esp_partition_t *BleOta::findEspOtaAppPartition() +{ + const esp_partition_t *part = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, nullptr); - esp_app_desc_t app_desc; - esp_err_t ret = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_get_partition_description(part, &app_desc)); + esp_app_desc_t app_desc; + esp_err_t ret = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_get_partition_description(part, &app_desc)); - if (ret != ESP_OK || MESHTASTIC_OTA_APP_PROJECT_NAME != app_desc.project_name) { - part = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, nullptr); - ret = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_get_partition_description(part, &app_desc)); - } + if (ret != ESP_OK || MESHTASTIC_OTA_APP_PROJECT_NAME != app_desc.project_name) { + part = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, nullptr); + ret = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_get_partition_description(part, &app_desc)); + } - if (ret == ESP_OK && MESHTASTIC_OTA_APP_PROJECT_NAME == app_desc.project_name) { - return part; - } else { - return nullptr; - } + if (ret == ESP_OK && MESHTASTIC_OTA_APP_PROJECT_NAME == app_desc.project_name) { + return part; + } else { + return nullptr; + } } -String BleOta::getOtaAppVersion() { - const esp_partition_t *part = findEspOtaAppPartition(); - esp_app_desc_t app_desc; - esp_err_t ret = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_get_partition_description(part, &app_desc)); - String version; - if (ret == ESP_OK) { - version = app_desc.version; - } - return version; +String BleOta::getOtaAppVersion() +{ + const esp_partition_t *part = findEspOtaAppPartition(); + esp_app_desc_t app_desc; + esp_err_t ret = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_get_partition_description(part, &app_desc)); + String version; + if (ret == ESP_OK) { + version = app_desc.version; + } + return version; } -bool BleOta::switchToOtaApp() { - bool success = false; - const esp_partition_t *part = findEspOtaAppPartition(); - if (part) { - success = (ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_set_boot_partition(part)) == ESP_OK); - } - return success; +bool BleOta::switchToOtaApp() +{ + bool success = false; + const esp_partition_t *part = findEspOtaAppPartition(); + if (part) { + success = (ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_set_boot_partition(part)) == ESP_OK); + } + return success; } \ No newline at end of file diff --git a/src/platform/esp32/BleOta.h b/src/platform/esp32/BleOta.h index 4c598f36d..16ea45b84 100644 --- a/src/platform/esp32/BleOta.h +++ b/src/platform/esp32/BleOta.h @@ -3,9 +3,10 @@ #include -class BleOta { +class BleOta +{ public: - explicit BleOta() {}; + explicit BleOta(){}; static String getOtaAppVersion(); static bool switchToOtaApp(); @@ -15,4 +16,4 @@ class BleOta { static const esp_partition_t *findEspOtaAppPartition(); }; -#endif //BLEOTA_H \ No newline at end of file +#endif // BLEOTA_H \ No newline at end of file diff --git a/src/platform/esp32/ESP32CryptoEngine.cpp b/src/platform/esp32/ESP32CryptoEngine.cpp index f8cb04704..998419df8 100644 --- a/src/platform/esp32/ESP32CryptoEngine.cpp +++ b/src/platform/esp32/ESP32CryptoEngine.cpp @@ -3,8 +3,6 @@ #include "mbedtls/aes.h" - - class ESP32CryptoEngine : public CryptoEngine { @@ -42,7 +40,7 @@ class ESP32CryptoEngine : public CryptoEngine virtual void encrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes) override { if (key.length > 0) { - LOG_DEBUG("ESP32 crypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); + LOG_DEBUG("ESP32 crypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t)packetId, numBytes); initNonce(fromNode, packetId); if (numBytes <= MAX_BLOCKSIZE) { static uint8_t scratch[MAX_BLOCKSIZE]; @@ -50,7 +48,7 @@ class ESP32CryptoEngine : public CryptoEngine size_t nc_off = 0; memcpy(scratch, bytes, numBytes); memset(scratch + numBytes, 0, - sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it) + sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it) auto res = mbedtls_aes_crypt_ctr(&aes, numBytes, &nc_off, nonce, stream_block, scratch, bytes); assert(!res); diff --git a/src/platform/esp32/SimpleAllocator.cpp b/src/platform/esp32/SimpleAllocator.cpp index 0fb6677d2..ed44722c5 100644 --- a/src/platform/esp32/SimpleAllocator.cpp +++ b/src/platform/esp32/SimpleAllocator.cpp @@ -1,8 +1,11 @@ +#include "SimpleAllocator.h" #include "assert.h" #include "configuration.h" -#include "SimpleAllocator.h" -SimpleAllocator::SimpleAllocator() { reset(); } +SimpleAllocator::SimpleAllocator() +{ + reset(); +} void *SimpleAllocator::alloc(size_t size) { @@ -14,7 +17,10 @@ void *SimpleAllocator::alloc(size_t size) return res; } -void SimpleAllocator::reset() { nextFree = 0; } +void SimpleAllocator::reset() +{ + nextFree = 0; +} void *operator new(size_t size, SimpleAllocator &p) { diff --git a/src/platform/esp32/SimpleAllocator.h b/src/platform/esp32/SimpleAllocator.h index 5fdb6738c..eaf4ee710 100644 --- a/src/platform/esp32/SimpleAllocator.h +++ b/src/platform/esp32/SimpleAllocator.h @@ -8,7 +8,7 @@ * It will panic if that buffer fills up. * If you are _sure_ no outstanding references to blocks in this buffer still exist, you can call * reset() to start from scratch. - * + * * Currently the only usecase for this class is the ESP32 bluetooth stack, where once we've called deinit(false) * we are sure all those bluetooth objects no longer exist, and we'll need to recreate them when we restart bluetooth */ @@ -18,14 +18,14 @@ class SimpleAllocator uint32_t nextFree = 0; -public: + public: SimpleAllocator(); void *alloc(size_t size); /** If you are _sure_ no outstanding references to blocks in this buffer still exist, you can call - * reset() to start from scratch. - * */ + * reset() to start from scratch. + * */ void reset(); }; @@ -35,8 +35,9 @@ void *operator new(size_t size, SimpleAllocator &p); * Temporarily makes the specified Allocator be used for _all_ allocations. Useful when calling library routines * that don't know about pools */ -class AllocatorScope { -public: +class AllocatorScope +{ + public: explicit AllocatorScope(SimpleAllocator &a); ~AllocatorScope(); }; diff --git a/src/platform/esp32/architecture.h b/src/platform/esp32/architecture.h index 212df9f46..785847825 100644 --- a/src/platform/esp32/architecture.h +++ b/src/platform/esp32/architecture.h @@ -7,31 +7,31 @@ // #ifndef HAS_BLUETOOTH - #define HAS_BLUETOOTH 1 +#define HAS_BLUETOOTH 1 #endif #ifndef HAS_WIFI - #define HAS_WIFI 1 +#define HAS_WIFI 1 #endif #ifndef HAS_SCREEN - #define HAS_SCREEN 1 +#define HAS_SCREEN 1 #endif #ifndef HAS_WIRE - #define HAS_WIRE 1 +#define HAS_WIRE 1 #endif #ifndef HAS_GPS - #define HAS_GPS 1 +#define HAS_GPS 1 #endif #ifndef HAS_BUTTON - #define HAS_BUTTON 1 +#define HAS_BUTTON 1 #endif #ifndef HAS_TELEMETRY - #define HAS_TELEMETRY 1 +#define HAS_TELEMETRY 1 #endif #ifndef HAS_RADIO - #define HAS_RADIO 1 +#define HAS_RADIO 1 #endif #ifndef HAS_RTC - #define HAS_RTC 1 +#define HAS_RTC 1 #endif #if defined(HAS_AXP192) || defined(HAS_AXP2101) @@ -44,52 +44,52 @@ // This string must exactly match the case used in release file names or the android updater won't work #if defined(TBEAM_V10) - #define HW_VENDOR HardwareModel_TBEAM +#define HW_VENDOR HardwareModel_TBEAM #elif defined(TBEAM_V07) - #define HW_VENDOR HardwareModel_TBEAM_V0P7 +#define HW_VENDOR HardwareModel_TBEAM_V0P7 #elif defined(LILYGO_TBEAM_S3_CORE) - #define HW_VENDOR HardwareModel_LILYGO_TBEAM_S3_CORE +#define HW_VENDOR HardwareModel_LILYGO_TBEAM_S3_CORE #elif defined(DIY_V1) - #define HW_VENDOR HardwareModel_DIY_V1 +#define HW_VENDOR HardwareModel_DIY_V1 #elif defined(RAK_11200) - #define HW_VENDOR HardwareModel_RAK11200 +#define HW_VENDOR HardwareModel_RAK11200 #elif defined(ARDUINO_HELTEC_WIFI_LORA_32_V2) - #ifdef HELTEC_V2_0 - #define HW_VENDOR HardwareModel_HELTEC_V2_0 - #endif - #ifdef HELTEC_V2_1 - #define HW_VENDOR HardwareModel_HELTEC_V2_1 - #endif +#ifdef HELTEC_V2_0 +#define HW_VENDOR HardwareModel_HELTEC_V2_0 +#endif +#ifdef HELTEC_V2_1 +#define HW_VENDOR HardwareModel_HELTEC_V2_1 +#endif #elif defined(ARDUINO_HELTEC_WIFI_LORA_32) - #define HW_VENDOR HardwareModel_HELTEC_V1 +#define HW_VENDOR HardwareModel_HELTEC_V1 #elif defined(TLORA_V1) - #define HW_VENDOR HardwareModel_TLORA_V1 +#define HW_VENDOR HardwareModel_TLORA_V1 #elif defined(TLORA_V2) - #define HW_VENDOR HardwareModel_TLORA_V2 +#define HW_VENDOR HardwareModel_TLORA_V2 #elif defined(TLORA_V1_3) - #define HW_VENDOR HardwareModel_TLORA_V1_1P3 +#define HW_VENDOR HardwareModel_TLORA_V1_1P3 #elif defined(TLORA_V2_1_16) - #define HW_VENDOR HardwareModel_TLORA_V2_1_1P6 +#define HW_VENDOR HardwareModel_TLORA_V2_1_1P6 #elif defined(TLORA_V2_1_18) - #define HW_VENDOR HardwareModel_TLORA_V2_1_1P8 +#define HW_VENDOR HardwareModel_TLORA_V2_1_1P8 #elif defined(GENIEBLOCKS) - #define HW_VENDOR HardwareModel_GENIEBLOCKS +#define HW_VENDOR HardwareModel_GENIEBLOCKS #elif defined(PRIVATE_HW) - #define HW_VENDOR HardwareModel_PRIVATE_HW +#define HW_VENDOR HardwareModel_PRIVATE_HW #elif defined(NANO_G1) - #define HW_VENDOR HardwareModel_NANO_G1 +#define HW_VENDOR HardwareModel_NANO_G1 #elif defined(M5STACK) - #define HW_VENDOR HardwareModel_M5STACK +#define HW_VENDOR HardwareModel_M5STACK #elif defined(STATION_G1) - #define HW_VENDOR HardwareModel_STATION_G1 +#define HW_VENDOR HardwareModel_STATION_G1 #elif defined(DR_DEV) - #define HW_VENDOR HardwareModel_DR_DEV +#define HW_VENDOR HardwareModel_DR_DEV #elif defined(HELTEC_V3) - #define HW_VENDOR HardwareModel_HELTEC_V3 +#define HW_VENDOR HardwareModel_HELTEC_V3 #elif defined(HELTEC_WSL_V3) - #define HW_VENDOR HardwareModel_HELTEC_WSL_V3 +#define HW_VENDOR HardwareModel_HELTEC_WSL_V3 #elif defined(TLORA_T3S3_V1) - #define HW_VENDOR HardwareModel_TLORA_T3_S3 +#define HW_VENDOR HardwareModel_TLORA_T3_S3 #endif // @@ -121,4 +121,3 @@ #endif #define SERIAL0_RX_GPIO 3 // Always GPIO3 on ESP32 - diff --git a/src/platform/esp32/main-esp32.cpp b/src/platform/esp32/main-esp32.cpp index f141ff3be..ca757a6e5 100644 --- a/src/platform/esp32/main-esp32.cpp +++ b/src/platform/esp32/main-esp32.cpp @@ -10,18 +10,19 @@ #include "mesh/http/WiFiAPClient.h" #include "sleep.h" +#include "soc/rtc.h" #include "target_specific.h" #include "utils.h" #include #include #include #include -#include "soc/rtc.h" #if !defined(CONFIG_IDF_TARGET_ESP32S2) NimbleBluetooth *nimbleBluetooth; -void setBluetoothEnable(bool on) { +void setBluetoothEnable(bool on) +{ if (!isWifiAvailable() && config.bluetooth.enabled == true) { if (!nimbleBluetooth) { @@ -35,8 +36,8 @@ void setBluetoothEnable(bool on) { } } #else -void setBluetoothEnable(bool on) { } -void updateBatteryLevel(uint8_t level) { } +void setBluetoothEnable(bool on) {} +void updateBatteryLevel(uint8_t level) {} #endif void getMacAddr(uint8_t *dmac) @@ -76,12 +77,12 @@ void enableSlowCLK() CALIBRATE_ONE(RTC_CAL_RTC_MUX); CALIBRATE_ONE(RTC_CAL_32K_XTAL); if (rtc_clk_slow_freq_get() != RTC_SLOW_FREQ_32K_XTAL) { - LOG_WARN("Failed to switch 32K XTAL RTC source to 32.768Khz !!! \n"); return; + LOG_WARN("Failed to switch 32K XTAL RTC source to 32.768Khz !!! \n"); + return; } } #endif - void esp32Setup() { uint32_t seed = esp_random(); @@ -96,8 +97,8 @@ void esp32Setup() nvs_stats_t nvs_stats; auto res = nvs_get_stats(NULL, &nvs_stats); assert(res == ESP_OK); - LOG_DEBUG("NVS: UsedEntries %d, FreeEntries %d, AllEntries %d, NameSpaces %d\n", nvs_stats.used_entries, nvs_stats.free_entries, - nvs_stats.total_entries, nvs_stats.namespace_count); + LOG_DEBUG("NVS: UsedEntries %d, FreeEntries %d, AllEntries %d, NameSpaces %d\n", nvs_stats.used_entries, + nvs_stats.free_entries, nvs_stats.total_entries, nvs_stats.namespace_count); LOG_DEBUG("Setup Preferences in Flash Storage\n"); @@ -110,10 +111,10 @@ void esp32Setup() preferences.putUInt("rebootCounter", rebootCounter); preferences.end(); LOG_DEBUG("Number of Device Reboots: %d\n", rebootCounter); - String BLEOTA=BleOta::getOtaAppVersion(); + String BLEOTA = BleOta::getOtaAppVersion(); if (BLEOTA.isEmpty()) { LOG_DEBUG("No OTA firmware available\n"); - }else{ + } else { LOG_DEBUG("OTA firmware version %s\n", BLEOTA.c_str()); } @@ -155,7 +156,6 @@ uint32_t axpDebugRead() Periodic axpDebugOutput(axpDebugRead); #endif - /// loop code specific to ESP32 targets void esp32Loop() { diff --git a/src/platform/nrf52/JLINK_MONITOR.c b/src/platform/nrf52/JLINK_MONITOR.c index a79a00e9c..160264905 100644 --- a/src/platform/nrf52/JLINK_MONITOR.c +++ b/src/platform/nrf52/JLINK_MONITOR.c @@ -8,7 +8,7 @@ * www.segger.com Support: support@segger.com * * * ********************************************************************** - + ---------------------------------------------------------------------- File : JLINK_MONITOR.c Purpose : Implementation of debug monitor for J-Link monitor mode debug on Cortex-M devices. @@ -18,103 +18,107 @@ Purpose : Implementation of debug monitor for J-Link monitor mode debug on Corte #include "JLINK_MONITOR.h" /********************************************************************* -* -* Configuration -* -********************************************************************** -*/ + * + * Configuration + * + ********************************************************************** + */ /********************************************************************* -* -* Defines -* -********************************************************************** -*/ + * + * Defines + * + ********************************************************************** + */ /********************************************************************* -* -* Types -* -********************************************************************** -*/ + * + * Types + * + ********************************************************************** + */ /********************************************************************* -* -* Static data -* -********************************************************************** -*/ + * + * Static data + * + ********************************************************************** + */ -volatile int MAIN_MonCnt; // Incremented in JLINK_MONITOR_OnPoll() while CPU is in debug mode +volatile int MAIN_MonCnt; // Incremented in JLINK_MONITOR_OnPoll() while CPU is in debug mode /********************************************************************* -* -* Local functions -* -********************************************************************** -*/ + * + * Local functions + * + ********************************************************************** + */ /********************************************************************* -* -* Global functions -* -********************************************************************** -*/ + * + * Global functions + * + ********************************************************************** + */ -/********************************************************************* -* -* JLINK_MONITOR_OnExit() -* -* Function description -* Called from DebugMon_Handler(), once per debug exit. -* May perform some target specific operations to be done on debug mode exit. -* -* Notes -* (1) Must not keep the CPU busy for more than 100 ms -*/ -void JLINK_MONITOR_OnExit(void) { - // - // Add custom code here - // -// BSP_ClrLED(0); +/********************************************************************* + * + * JLINK_MONITOR_OnExit() + * + * Function description + * Called from DebugMon_Handler(), once per debug exit. + * May perform some target specific operations to be done on debug mode exit. + * + * Notes + * (1) Must not keep the CPU busy for more than 100 ms + */ +void JLINK_MONITOR_OnExit(void) +{ + // + // Add custom code here + // + // BSP_ClrLED(0); } -/********************************************************************* -* -* JLINK_MONITOR_OnEnter() -* -* Function description -* Called from DebugMon_Handler(), once per debug entry. -* May perform some target specific operations to be done on debug mode entry -* -* Notes -* (1) Must not keep the CPU busy for more than 100 ms -*/ -void JLINK_MONITOR_OnEnter(void) { - // - // Add custom code here - // -// BSP_SetLED(0); -// BSP_ClrLED(1); +/********************************************************************* + * + * JLINK_MONITOR_OnEnter() + * + * Function description + * Called from DebugMon_Handler(), once per debug entry. + * May perform some target specific operations to be done on debug mode entry + * + * Notes + * (1) Must not keep the CPU busy for more than 100 ms + */ +void JLINK_MONITOR_OnEnter(void) +{ + // + // Add custom code here + // + // BSP_SetLED(0); + // BSP_ClrLED(1); } -/********************************************************************* -* -* JLINK_MONITOR_OnPoll() -* -* Function description -* Called periodically from DebugMon_Handler(), to perform some actions that need to be performed periodically during debug mode. -* -* Notes -* (1) Must not keep the CPU busy for more than 100 ms -*/ -void JLINK_MONITOR_OnPoll(void) { - // - // Add custom code here - // - MAIN_MonCnt++; -// BSP_ToggleLED(0); -// _Delay(500000); +/********************************************************************* + * + * JLINK_MONITOR_OnPoll() + * + * Function description + * Called periodically from DebugMon_Handler(), to perform some actions that need to be performed periodically during debug + * mode. + * + * Notes + * (1) Must not keep the CPU busy for more than 100 ms + */ +void JLINK_MONITOR_OnPoll(void) +{ + // + // Add custom code here + // + MAIN_MonCnt++; + // BSP_ToggleLED(0); + // _Delay(500000); } /****** End Of File *************************************************/ diff --git a/src/platform/nrf52/JLINK_MONITOR.h b/src/platform/nrf52/JLINK_MONITOR.h index 99953d368..87cf332fe 100644 --- a/src/platform/nrf52/JLINK_MONITOR.h +++ b/src/platform/nrf52/JLINK_MONITOR.h @@ -8,7 +8,7 @@ * www.segger.com Support: support@segger.com * * * ********************************************************************** - + ---------------------------------------------------------------------- File : JLINK_MONITOR.h Purpose : Header file of debug monitor for J-Link monitor mode debug on Cortex-M devices. @@ -18,9 +18,9 @@ Purpose : Header file of debug monitor for J-Link monitor mode debug on Cortex-M #ifndef JLINK_MONITOR_H #define JLINK_MONITOR_H -void JLINK_MONITOR_OnExit (void); -void JLINK_MONITOR_OnEnter (void); -void JLINK_MONITOR_OnPoll (void); +void JLINK_MONITOR_OnExit(void); +void JLINK_MONITOR_OnEnter(void); +void JLINK_MONITOR_OnPoll(void); #endif diff --git a/src/platform/nrf52/NRF52Bluetooth.cpp b/src/platform/nrf52/NRF52Bluetooth.cpp index 7bbc1a7bb..7bdd1a982 100644 --- a/src/platform/nrf52/NRF52Bluetooth.cpp +++ b/src/platform/nrf52/NRF52Bluetooth.cpp @@ -1,6 +1,6 @@ -#include "configuration.h" #include "NRF52Bluetooth.h" #include "BluetoothCommon.h" +#include "configuration.h" #include "main.h" #include "mesh/PhoneAPI.h" #include "mesh/mesh-pb-constants.h" @@ -38,7 +38,8 @@ class BluetoothPhoneAPI : public PhoneAPI } /// Check the current underlying physical link to see if the client is currently connected - virtual bool checkIsConnected() override { + virtual bool checkIsConnected() override + { BLEConnection *connection = Bluefruit.Connection(connectionHandle); return connection->connected(); } @@ -171,7 +172,8 @@ void setupMeshService(void) fromNum.setProperties(CHR_PROPS_NOTIFY | CHR_PROPS_READ); fromNum.setPermission(secMode, SECMODE_NO_ACCESS); // FIXME, secure this!!! - fromNum.setFixedLen(0); // Variable len (either 0 or 4) FIXME consider changing protocol so it is fixed 4 byte len, where 0 means empty + fromNum.setFixedLen( + 0); // Variable len (either 0 or 4) FIXME consider changing protocol so it is fixed 4 byte len, where 0 means empty fromNum.setMaxLen(4); fromNum.setCccdWriteCallback(onCccd); // Optionally capture CCCD updates // We don't yet need to hook the fromNum auth callback @@ -180,9 +182,11 @@ void setupMeshService(void) fromNum.begin(); fromRadio.setProperties(CHR_PROPS_READ); - fromRadio.setPermission(secMode, SECMODE_NO_ACCESS); + fromRadio.setPermission(secMode, SECMODE_NO_ACCESS); fromRadio.setMaxLen(sizeof(fromRadioBytes)); - fromRadio.setReadAuthorizeCallback(onFromRadioAuthorize, false); // We don't call this callback via the adafruit queue, because we can safely run in the BLE context + fromRadio.setReadAuthorizeCallback( + onFromRadioAuthorize, + false); // We don't call this callback via the adafruit queue, because we can safely run in the BLE context fromRadio.setBuffer(fromRadioBytes, sizeof(fromRadioBytes)); // we preallocate our fromradio buffer so we won't waste space // for two copies fromRadio.begin(); @@ -193,7 +197,7 @@ void setupMeshService(void) toRadio.setMaxLen(512); toRadio.setBuffer(toRadioBytes, sizeof(toRadioBytes)); // We don't call this callback via the adafruit queue, because we can safely run in the BLE context - toRadio.setWriteCallback(onToRadioWrite, false); + toRadio.setWriteCallback(onToRadioWrite, false); toRadio.begin(); } @@ -222,8 +226,8 @@ void NRF52Bluetooth::setup() Bluefruit.ScanResponse.clearData(); if (config.bluetooth.mode != Config_BluetoothConfig_PairingMode_NO_PIN) { - configuredPasskey = config.bluetooth.mode == Config_BluetoothConfig_PairingMode_FIXED_PIN ? - config.bluetooth.fixed_pin : random(100000, 999999); + configuredPasskey = config.bluetooth.mode == Config_BluetoothConfig_PairingMode_FIXED_PIN ? config.bluetooth.fixed_pin + : random(100000, 999999); auto pinString = std::to_string(configuredPasskey); LOG_INFO("Bluetooth pin set to '%i'\n", configuredPasskey); Bluefruit.Security.setPIN(pinString.c_str()); @@ -232,8 +236,7 @@ void NRF52Bluetooth::setup() Bluefruit.Security.setPairCompleteCallback(NRF52Bluetooth::onPairingCompleted); Bluefruit.Security.setSecuredCallback(NRF52Bluetooth::onConnectionSecured); meshBleService.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM); - } - else { + } else { Bluefruit.Security.setIOCaps(false, false, false); meshBleService.setPermission(SECMODE_OPEN, SECMODE_OPEN); } @@ -246,7 +249,7 @@ void NRF52Bluetooth::setup() bledfu.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM); bledfu.begin(); // Install the DFU helper - + // Configure and Start the Device Information Service LOG_INFO("Configuring the Device Information Service\n"); bledis.setModel(optstr(HW_VERSION)); @@ -258,15 +261,13 @@ void NRF52Bluetooth::setup() blebas.begin(); blebas.write(0); // Unknown battery level for now - // Setup the Heart Rate Monitor service using // BLEService and BLECharacteristic classes LOG_INFO("Configuring the Mesh bluetooth service\n"); setupMeshService(); // Supposedly debugging works with soft device if you disable advertising - if (isSoftDeviceAllowed) - { + if (isSoftDeviceAllowed) { // Setup the advertising packet(s) LOG_INFO("Setting up the advertising payload(s)\n"); startAdv(); @@ -298,15 +299,14 @@ void NRF52Bluetooth::onConnectionSecured(uint16_t conn_handle) bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passkey[6], bool match_request) { - LOG_INFO("BLE pairing process started with passkey %.3s %.3s\n", passkey, passkey+3); + LOG_INFO("BLE pairing process started with passkey %.3s %.3s\n", passkey, passkey + 3); screen->startBluetoothPinScreen(configuredPasskey); - if (match_request) - { + if (match_request) { uint32_t start_time = millis(); - while(millis() < start_time + 30000) - { - if (!Bluefruit.connected(conn_handle)) break; + while (millis() < start_time + 30000) { + if (!Bluefruit.connected(conn_handle)) + break; } } LOG_INFO("BLE passkey pairing: match_request=%i\n", match_request); diff --git a/src/platform/nrf52/NRF52CryptoEngine.cpp b/src/platform/nrf52/NRF52CryptoEngine.cpp index 73add2c3b..a7cf3d5bf 100644 --- a/src/platform/nrf52/NRF52CryptoEngine.cpp +++ b/src/platform/nrf52/NRF52CryptoEngine.cpp @@ -1,7 +1,7 @@ -#include "configuration.h" #include "CryptoEngine.h" -#include #include "aes-256/tiny-aes.h" +#include "configuration.h" +#include class NRF52CryptoEngine : public CryptoEngine { public: @@ -17,20 +17,20 @@ class NRF52CryptoEngine : public CryptoEngine virtual void encrypt(uint32_t fromNode, uint64_t packetId, size_t numBytes, uint8_t *bytes) override { if (key.length > 16) { - LOG_DEBUG("Software encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); + LOG_DEBUG("Software encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t)packetId, numBytes); AES_ctx ctx; initNonce(fromNode, packetId); AES_init_ctx_iv(&ctx, key.bytes, nonce); AES_CTR_xcrypt_buffer(&ctx, bytes, numBytes); } else if (key.length > 0) { - LOG_DEBUG("nRF52 encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t) packetId, numBytes); + LOG_DEBUG("nRF52 encrypt fr=%x, num=%x, numBytes=%d!\n", fromNode, (uint32_t)packetId, numBytes); nRFCrypto.begin(); nRFCrypto_AES ctx; uint8_t myLen = ctx.blockLen(numBytes); char encBuf[myLen] = {0}; initNonce(fromNode, packetId); ctx.begin(); - ctx.Process((char*)bytes, numBytes, nonce, key.bytes, key.length, encBuf, ctx.encryptFlag, ctx.ctrMode); + ctx.Process((char *)bytes, numBytes, nonce, key.bytes, key.length, encBuf, ctx.encryptFlag, ctx.ctrMode); ctx.end(); nRFCrypto.end(); memcpy(bytes, encBuf, numBytes); diff --git a/src/platform/nrf52/aes-256/tiny-aes.cpp b/src/platform/nrf52/aes-256/tiny-aes.cpp index dc28a5249..20a7344e1 100644 --- a/src/platform/nrf52/aes-256/tiny-aes.cpp +++ b/src/platform/nrf52/aes-256/tiny-aes.cpp @@ -8,8 +8,8 @@ NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0) For AES192/256 the key size is proportionally larger. */ -#include #include "tiny-aes.h" +#include #define Nb 4 #define Nk 8 @@ -18,212 +18,199 @@ NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0) typedef uint8_t state_t[4][4]; static const uint8_t sbox[256] = { - //0 1 2 3 4 5 6 7 8 9 A B C D E F - 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; + // 0 1 2 3 4 5 6 7 8 9 A B C D E F + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, + 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, + 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, + 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, + 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, + 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, + 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, + 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, + 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, + 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}; -static const uint8_t Rcon[11] = { - 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; +static const uint8_t Rcon[11] = {0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36}; #define getSBoxValue(num) (sbox[(num)]) -static void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key) +static void KeyExpansion(uint8_t *RoundKey, const uint8_t *Key) { - uint8_t tempa[4]; - - for (unsigned i = 0; i < Nk; ++i) - { - RoundKey[(i * 4) + 0] = Key[(i * 4) + 0]; - RoundKey[(i * 4) + 1] = Key[(i * 4) + 1]; - RoundKey[(i * 4) + 2] = Key[(i * 4) + 2]; - RoundKey[(i * 4) + 3] = Key[(i * 4) + 3]; - } + uint8_t tempa[4]; - for (unsigned i = Nk; i < Nb * (Nr + 1); ++i) - { - unsigned k = (i - 1) * 4; - tempa[0]=RoundKey[k + 0]; - tempa[1]=RoundKey[k + 1]; - tempa[2]=RoundKey[k + 2]; - tempa[3]=RoundKey[k + 3]; - - if (i % Nk == 0) - { - const uint8_t u8tmp = tempa[0]; - tempa[0] = tempa[1]; - tempa[1] = tempa[2]; - tempa[2] = tempa[3]; - tempa[3] = u8tmp; - - tempa[0] = getSBoxValue(tempa[0]); - tempa[1] = getSBoxValue(tempa[1]); - tempa[2] = getSBoxValue(tempa[2]); - tempa[3] = getSBoxValue(tempa[3]); - - tempa[0] = tempa[0] ^ Rcon[i/Nk]; + for (unsigned i = 0; i < Nk; ++i) { + RoundKey[(i * 4) + 0] = Key[(i * 4) + 0]; + RoundKey[(i * 4) + 1] = Key[(i * 4) + 1]; + RoundKey[(i * 4) + 2] = Key[(i * 4) + 2]; + RoundKey[(i * 4) + 3] = Key[(i * 4) + 3]; } - if (i % Nk == 4) - { - tempa[0] = getSBoxValue(tempa[0]); - tempa[1] = getSBoxValue(tempa[1]); - tempa[2] = getSBoxValue(tempa[2]); - tempa[3] = getSBoxValue(tempa[3]); + for (unsigned i = Nk; i < Nb * (Nr + 1); ++i) { + unsigned k = (i - 1) * 4; + tempa[0] = RoundKey[k + 0]; + tempa[1] = RoundKey[k + 1]; + tempa[2] = RoundKey[k + 2]; + tempa[3] = RoundKey[k + 3]; + + if (i % Nk == 0) { + const uint8_t u8tmp = tempa[0]; + tempa[0] = tempa[1]; + tempa[1] = tempa[2]; + tempa[2] = tempa[3]; + tempa[3] = u8tmp; + + tempa[0] = getSBoxValue(tempa[0]); + tempa[1] = getSBoxValue(tempa[1]); + tempa[2] = getSBoxValue(tempa[2]); + tempa[3] = getSBoxValue(tempa[3]); + + tempa[0] = tempa[0] ^ Rcon[i / Nk]; + } + + if (i % Nk == 4) { + tempa[0] = getSBoxValue(tempa[0]); + tempa[1] = getSBoxValue(tempa[1]); + tempa[2] = getSBoxValue(tempa[2]); + tempa[3] = getSBoxValue(tempa[3]); + } + + unsigned j = i * 4; + k = (i - Nk) * 4; + RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0]; + RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1]; + RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2]; + RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3]; } - - unsigned j = i * 4; k=(i - Nk) * 4; - RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0]; - RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1]; - RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2]; - RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3]; - } } -void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key) +void AES_init_ctx(struct AES_ctx *ctx, const uint8_t *key) { - KeyExpansion(ctx->RoundKey, key); + KeyExpansion(ctx->RoundKey, key); } -void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv) +void AES_init_ctx_iv(struct AES_ctx *ctx, const uint8_t *key, const uint8_t *iv) { - KeyExpansion(ctx->RoundKey, key); - memcpy (ctx->Iv, iv, AES_BLOCKLEN); + KeyExpansion(ctx->RoundKey, key); + memcpy(ctx->Iv, iv, AES_BLOCKLEN); } -void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv) +void AES_ctx_set_iv(struct AES_ctx *ctx, const uint8_t *iv) { - memcpy (ctx->Iv, iv, AES_BLOCKLEN); + memcpy(ctx->Iv, iv, AES_BLOCKLEN); } -static void AddRoundKey(uint8_t round, state_t* state, const uint8_t* RoundKey) +static void AddRoundKey(uint8_t round, state_t *state, const uint8_t *RoundKey) { - for (uint8_t i = 0; i < 4; ++i) - { - for (uint8_t j = 0; j < 4; ++j) - { - (*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j]; + for (uint8_t i = 0; i < 4; ++i) { + for (uint8_t j = 0; j < 4; ++j) { + (*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j]; + } } - } } -static void SubBytes(state_t* state) +static void SubBytes(state_t *state) { - for (uint8_t i = 0; i < 4; ++i) - { - for (uint8_t j = 0; j < 4; ++j) - { - (*state)[j][i] = getSBoxValue((*state)[j][i]); + for (uint8_t i = 0; i < 4; ++i) { + for (uint8_t j = 0; j < 4; ++j) { + (*state)[j][i] = getSBoxValue((*state)[j][i]); + } } - } } -static void ShiftRows(state_t* state) +static void ShiftRows(state_t *state) { - uint8_t temp = (*state)[0][1]; - (*state)[0][1] = (*state)[1][1]; - (*state)[1][1] = (*state)[2][1]; - (*state)[2][1] = (*state)[3][1]; - (*state)[3][1] = temp; + uint8_t temp = (*state)[0][1]; + (*state)[0][1] = (*state)[1][1]; + (*state)[1][1] = (*state)[2][1]; + (*state)[2][1] = (*state)[3][1]; + (*state)[3][1] = temp; - temp = (*state)[0][2]; - (*state)[0][2] = (*state)[2][2]; - (*state)[2][2] = temp; + temp = (*state)[0][2]; + (*state)[0][2] = (*state)[2][2]; + (*state)[2][2] = temp; - temp = (*state)[1][2]; - (*state)[1][2] = (*state)[3][2]; - (*state)[3][2] = temp; + temp = (*state)[1][2]; + (*state)[1][2] = (*state)[3][2]; + (*state)[3][2] = temp; - temp = (*state)[0][3]; - (*state)[0][3] = (*state)[3][3]; - (*state)[3][3] = (*state)[2][3]; - (*state)[2][3] = (*state)[1][3]; - (*state)[1][3] = temp; + temp = (*state)[0][3]; + (*state)[0][3] = (*state)[3][3]; + (*state)[3][3] = (*state)[2][3]; + (*state)[2][3] = (*state)[1][3]; + (*state)[1][3] = temp; } static uint8_t xtime(uint8_t x) { - return ((x<<1) ^ (((x>>7) & 1) * 0x1b)); + return ((x << 1) ^ (((x >> 7) & 1) * 0x1b)); } -static void MixColumns(state_t* state) +static void MixColumns(state_t *state) { - for (uint8_t i = 0; i < 4; ++i) - { - uint8_t t = (*state)[i][0]; - uint8_t Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ; - uint8_t Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ; - Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ; - Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ; - Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ; - } -} - -#define Multiply(x, y) \ - ( ((y & 1) * x) ^ \ - ((y>>1 & 1) * xtime(x)) ^ \ - ((y>>2 & 1) * xtime(xtime(x))) ^ \ - ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \ - ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \ - - -static void Cipher(state_t* state, const uint8_t* RoundKey) -{ - uint8_t round = 0; - - AddRoundKey(0, state, RoundKey); - - for (round = 1; ; ++round) - { - SubBytes(state); - ShiftRows(state); - if (round == Nr) { - break; + for (uint8_t i = 0; i < 4; ++i) { + uint8_t t = (*state)[i][0]; + uint8_t Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3]; + uint8_t Tm = (*state)[i][0] ^ (*state)[i][1]; + Tm = xtime(Tm); + (*state)[i][0] ^= Tm ^ Tmp; + Tm = (*state)[i][1] ^ (*state)[i][2]; + Tm = xtime(Tm); + (*state)[i][1] ^= Tm ^ Tmp; + Tm = (*state)[i][2] ^ (*state)[i][3]; + Tm = xtime(Tm); + (*state)[i][2] ^= Tm ^ Tmp; + Tm = (*state)[i][3] ^ t; + Tm = xtime(Tm); + (*state)[i][3] ^= Tm ^ Tmp; } - MixColumns(state); - AddRoundKey(round, state, RoundKey); - } - AddRoundKey(Nr, state, RoundKey); } -void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length) +#define Multiply(x, y) \ + (((y & 1) * x) ^ ((y >> 1 & 1) * xtime(x)) ^ ((y >> 2 & 1) * xtime(xtime(x))) ^ ((y >> 3 & 1) * xtime(xtime(xtime(x)))) ^ \ + ((y >> 4 & 1) * xtime(xtime(xtime(xtime(x)))))) + +static void Cipher(state_t *state, const uint8_t *RoundKey) { - uint8_t buffer[AES_BLOCKLEN]; - - size_t i; - int bi; - for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi) - { - if (bi == AES_BLOCKLEN) - { - - memcpy(buffer, ctx->Iv, AES_BLOCKLEN); - Cipher((state_t*)buffer,ctx->RoundKey); + uint8_t round = 0; - for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi) - { - if (ctx->Iv[bi] == 255) - { - ctx->Iv[bi] = 0; - continue; - } - ctx->Iv[bi] += 1; - break; - } - bi = 0; + AddRoundKey(0, state, RoundKey); + + for (round = 1;; ++round) { + SubBytes(state); + ShiftRows(state); + if (round == Nr) { + break; + } + MixColumns(state); + AddRoundKey(round, state, RoundKey); + } + AddRoundKey(Nr, state, RoundKey); +} + +void AES_CTR_xcrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, size_t length) +{ + uint8_t buffer[AES_BLOCKLEN]; + + size_t i; + int bi; + for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi) { + if (bi == AES_BLOCKLEN) { + + memcpy(buffer, ctx->Iv, AES_BLOCKLEN); + Cipher((state_t *)buffer, ctx->RoundKey); + + for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi) { + if (ctx->Iv[bi] == 255) { + ctx->Iv[bi] = 0; + continue; + } + ctx->Iv[bi] += 1; + break; + } + bi = 0; + } + + buf[i] = (buf[i] ^ buffer[bi]); } - - buf[i] = (buf[i] ^ buffer[bi]); - } } diff --git a/src/platform/nrf52/aes-256/tiny-aes.h b/src/platform/nrf52/aes-256/tiny-aes.h index eded2c77f..ef78e0aeb 100644 --- a/src/platform/nrf52/aes-256/tiny-aes.h +++ b/src/platform/nrf52/aes-256/tiny-aes.h @@ -1,23 +1,22 @@ #ifndef _TINY_AES_H_ #define _TINY_AES_H_ -#include #include +#include #define AES_BLOCKLEN 16 // Block length in bytes - AES is 128b block only // #define AES_KEYLEN 32 #define AES_keyExpSize 240 -struct AES_ctx -{ - uint8_t RoundKey[AES_keyExpSize]; - uint8_t Iv[AES_BLOCKLEN]; +struct AES_ctx { + uint8_t RoundKey[AES_keyExpSize]; + uint8_t Iv[AES_BLOCKLEN]; }; -void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key); -void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv); -void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv); +void AES_init_ctx(struct AES_ctx *ctx, const uint8_t *key); +void AES_init_ctx_iv(struct AES_ctx *ctx, const uint8_t *key, const uint8_t *iv); +void AES_ctx_set_iv(struct AES_ctx *ctx, const uint8_t *iv); -void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length); +void AES_CTR_xcrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, size_t length); #endif // _TINY_AES_H_ diff --git a/src/platform/nrf52/architecture.h b/src/platform/nrf52/architecture.h index 986a864c9..9493796a0 100644 --- a/src/platform/nrf52/architecture.h +++ b/src/platform/nrf52/architecture.h @@ -6,28 +6,28 @@ // defaults for NRF52 architecture // #ifndef HAS_BLUETOOTH - #define HAS_BLUETOOTH 1 +#define HAS_BLUETOOTH 1 #endif #ifndef HAS_SCREEN - #define HAS_SCREEN 1 +#define HAS_SCREEN 1 #endif #ifndef HAS_WIRE - #define HAS_WIRE 1 +#define HAS_WIRE 1 #endif #ifndef HAS_GPS - #define HAS_GPS 1 +#define HAS_GPS 1 #endif #ifndef HAS_BUTTON - #define HAS_BUTTON 1 +#define HAS_BUTTON 1 #endif #ifndef HAS_TELEMETRY - #define HAS_TELEMETRY 1 +#define HAS_TELEMETRY 1 #endif #ifndef HAS_RADIO - #define HAS_RADIO 1 +#define HAS_RADIO 1 #endif #ifdef HAS_CPU_SHUTDOWN - #define HAS_CPU_SHUTDOWN 1 +#define HAS_CPU_SHUTDOWN 1 #endif // @@ -36,19 +36,19 @@ // This string must exactly match the case used in release file names or the android updater won't work #ifdef ARDUINO_NRF52840_PCA10056 - #define HW_VENDOR HardwareModel_NRF52840DK +#define HW_VENDOR HardwareModel_NRF52840DK #elif defined(ARDUINO_NRF52840_PPR) - #define HW_VENDOR HardwareModel_PPR +#define HW_VENDOR HardwareModel_PPR #elif defined(RAK4630) - #define HW_VENDOR HardwareModel_RAK4631 +#define HW_VENDOR HardwareModel_RAK4631 #elif defined(TTGO_T_ECHO) - #define HW_VENDOR HardwareModel_T_ECHO +#define HW_VENDOR HardwareModel_T_ECHO #elif defined(NORDIC_PCA10059) - #define HW_VENDOR HardwareModel_NRF52840_PCA10059 +#define HW_VENDOR HardwareModel_NRF52840_PCA10059 #elif defined(PRIVATE_HW) || defined(FEATHER_DIY) - #define HW_VENDOR HardwareModel_PRIVATE_HW +#define HW_VENDOR HardwareModel_PRIVATE_HW #else - #define HW_VENDOR HardwareModel_NRF52_UNKNOWN +#define HW_VENDOR HardwareModel_NRF52_UNKNOWN #endif // diff --git a/src/platform/nrf52/hardfault.cpp b/src/platform/nrf52/hardfault.cpp index fb27c3550..13a4ee046 100644 --- a/src/platform/nrf52/hardfault.cpp +++ b/src/platform/nrf52/hardfault.cpp @@ -23,7 +23,7 @@ static void printUsageErrorMsg(uint32_t cfsr) else if ((cfsr & (1 << 0)) != 0) FAULT_MSG("Invalid instruction\n"); else - FAULT_MSG("FIXME add to printUsageErrorMsg!\n"); + FAULT_MSG("FIXME add to printUsageErrorMsg!\n"); } static void printBusErrorMsg(uint32_t cfsr) @@ -94,22 +94,19 @@ extern "C" void HardFault_Handler(void) /* The prototype shows it is a naked function - in effect this is just an assembly function. */ -extern "C" void HardFault_Handler( void ) __attribute__( ( naked ) ); +extern "C" void HardFault_Handler(void) __attribute__((naked)); /* The fault handler implementation calls a function called prvGetRegistersFromStack(). */ -extern "C" void HardFault_Handler(void) +extern "C" void HardFault_Handler(void) { - __asm volatile - ( - " tst lr, #4 \n" - " ite eq \n" - " mrseq r0, msp \n" - " mrsne r0, psp \n" - " ldr r1, [r0, #24] \n" - " ldr r2, handler2_address_const \n" - " bx r2 \n" - " handler2_address_const: .word HardFault_Impl \n" - ); + __asm volatile(" tst lr, #4 \n" + " ite eq \n" + " mrseq r0, msp \n" + " mrsne r0, psp \n" + " ldr r1, [r0, #24] \n" + " ldr r2, handler2_address_const \n" + " bx r2 \n" + " handler2_address_const: .word HardFault_Impl \n"); } #endif diff --git a/src/platform/nrf52/main-bare.cpp b/src/platform/nrf52/main-bare.cpp index fb1b4a27e..0bba6d6f4 100644 --- a/src/platform/nrf52/main-bare.cpp +++ b/src/platform/nrf52/main-bare.cpp @@ -1,2 +1 @@ #include "target_specific.h" - diff --git a/src/platform/nrf52/main-nrf52.cpp b/src/platform/nrf52/main-nrf52.cpp index e3096b0ce..f08033d27 100644 --- a/src/platform/nrf52/main-nrf52.cpp +++ b/src/platform/nrf52/main-nrf52.cpp @@ -1,11 +1,11 @@ #include "configuration.h" +#include #include #include #include #include #include #include -#include // #include #include "NodeDB.h" @@ -22,7 +22,8 @@ static inline void debugger_break(void) "mov pc, lr\n\t"); } -bool loopCanSleep() { +bool loopCanSleep() +{ // turn off sleep only while connected via USB // return true; return !Serial; // the bool operator on the nrf52 serial class returns true if connected to a PC currently @@ -77,7 +78,7 @@ void setBluetoothEnable(bool on) else { nrf52Bluetooth = new NRF52Bluetooth(); nrf52Bluetooth->setup(); - + // We delay brownout init until after BLE because BLE starts soft device initBrownout(); } @@ -148,7 +149,7 @@ void nrf52Setup() // Init random seed union seedParts { uint32_t seed32; - uint8_t seed8[4]; + uint8_t seed8[4]; } seed; nRFCrypto.begin(); nRFCrypto.Random.generate(seed.seed8, sizeof(seed.seed8)); @@ -192,7 +193,8 @@ void cpuDeepSleep(uint64_t msecToWake) } } -void clearBonds() { +void clearBonds() +{ if (!nrf52Bluetooth) { nrf52Bluetooth = new NRF52Bluetooth(); nrf52Bluetooth->setup(); diff --git a/src/platform/portduino/CrossPlatformCryptoEngine.cpp b/src/platform/portduino/CrossPlatformCryptoEngine.cpp index 4c6d5f178..46ef942f0 100644 --- a/src/platform/portduino/CrossPlatformCryptoEngine.cpp +++ b/src/platform/portduino/CrossPlatformCryptoEngine.cpp @@ -55,7 +55,7 @@ class CrossPlatformCryptoEngine : public CryptoEngine static uint8_t scratch[MAX_BLOCKSIZE]; memcpy(scratch, bytes, numBytes); memset(scratch + numBytes, 0, - sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it) + sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it) ctr->setIV(nonce, sizeof(nonce)); ctr->setCounterSize(4); diff --git a/src/platform/portduino/PortduinoGlue.cpp b/src/platform/portduino/PortduinoGlue.cpp index b041391f8..fee6e05f9 100644 --- a/src/platform/portduino/PortduinoGlue.cpp +++ b/src/platform/portduino/PortduinoGlue.cpp @@ -23,7 +23,6 @@ void cpuDeepSleep(uint64_t msecs) void updateBatteryLevel(uint8_t level) NOT_IMPLEMENTED("updateBatteryLevel"); - /** a simulated pin for busted IRQ hardware * Porduino helper class to do this i2c based polling: */ @@ -51,27 +50,29 @@ class PolledIrqPin : public GPIOPin static GPIOPin *loraIrq; -int TCPPort = 4403; +int TCPPort = 4403; -static error_t parse_opt(int key, char *arg, struct argp_state *state) { - switch (key) { - case 'p': - if (sscanf(arg, "%d", &TCPPort) < 1) - return ARGP_ERR_UNKNOWN; - else - printf("Using TCP port %d\n", TCPPort); - break; - case ARGP_KEY_ARG: +static error_t parse_opt(int key, char *arg, struct argp_state *state) +{ + switch (key) { + case 'p': + if (sscanf(arg, "%d", &TCPPort) < 1) + return ARGP_ERR_UNKNOWN; + else + printf("Using TCP port %d\n", TCPPort); + break; + case ARGP_KEY_ARG: + return 0; + default: + return ARGP_ERR_UNKNOWN; + } return 0; - default: - return ARGP_ERR_UNKNOWN; - } - return 0; } -void portduinoCustomInit() { +void portduinoCustomInit() +{ static struct argp_option options[] = {{"port", 'p', "PORT", 0, "The TCP port to use."}, {0}}; - static void *childArguments; + static void *childArguments; static char doc[] = "Meshtastic native build."; static char args_doc[] = "..."; static struct argp argp = {options, parse_opt, args_doc, doc, 0, 0, 0}; @@ -79,7 +80,6 @@ void portduinoCustomInit() { portduinoAddArguments(child, childArguments); } - /** apps run under portduino can optionally define a portduinoSetup() to * use portduino specific init code (such as gpioBind) to setup portduino on their host machine, * before running 'arduino' code. @@ -89,9 +89,9 @@ void portduinoSetup() printf("Setting up Meshtastic on Portduino...\n"); #ifdef PORTDUINO_LINUX_HARDWARE - SPI.begin(); // We need to create SPI + SPI.begin(); // We need to create SPI bool usePineLora = !spiChip->isSimulated(); - if(usePineLora) { + if (usePineLora) { printf("Connecting to PineLora board...\n"); // FIXME: remove this hack once interrupts are confirmed to work on new pine64 board @@ -110,8 +110,7 @@ void portduinoSetup() auto loraCs = new LinuxGPIOPin(SX126X_CS, "ch341", "cs0", "loraCs"); loraCs->setSilent(); gpioBind(loraCs); - } - else + } else #endif { diff --git a/src/platform/portduino/SimRadio.cpp b/src/platform/portduino/SimRadio.cpp index ce96d02cc..8c6f5846e 100644 --- a/src/platform/portduino/SimRadio.cpp +++ b/src/platform/portduino/SimRadio.cpp @@ -35,9 +35,9 @@ void SimRadio::setTransmitDelay() // So we want to make sure the other side has had a chance to reconfigure its radio. /* We assume if rx_snr = 0 and rx_rssi = 0, the packet was generated locally. - * This assumption is valid because of the offset generated by the radio to account for the noise - * floor. - */ + * This assumption is valid because of the offset generated by the radio to account for the noise + * floor. + */ if (p->rx_snr == 0 && p->rx_rssi == 0) { startTransmitTimer(true); } else { @@ -96,7 +96,6 @@ void SimRadio::completeSending() } } - /** Could we send right now (i.e. either not actively receving or transmitting)? */ bool SimRadio::canSendImmediately() { @@ -116,14 +115,14 @@ bool SimRadio::canSendImmediately() return true; } -bool SimRadio::isActivelyReceiving() +bool SimRadio::isActivelyReceiving() { - return false; // TODO check how this should be simulated + return false; // TODO check how this should be simulated } bool SimRadio::isChannelActive() { - return false; // TODO ask simulator + return false; // TODO ask simulator } /** Attempt to cancel a previously sent packet. Returns true if a packet was found we could cancel */ @@ -138,14 +137,13 @@ bool SimRadio::cancelSending(NodeNum from, PacketId id) return result; } - void SimRadio::onNotify(uint32_t notification) { switch (notification) { case ISR_TX: handleTransmitInterrupt(); LOG_DEBUG("tx complete - starting timer\n"); - startTransmitTimer(); + startTransmitTimer(); break; case ISR_RX: LOG_DEBUG("rx complete - starting timer\n"); @@ -179,25 +177,25 @@ void SimRadio::onNotify(uint32_t notification) } else { // LOG_DEBUG("done with txqueue\n"); } - break; + break; default: assert(0); // We expected to receive a valid notification from the ISR } } /** start an immediate transmit */ -void SimRadio::startSend(MeshPacket * txp) +void SimRadio::startSend(MeshPacket *txp) { printPacket("Starting low level send", txp); size_t numbytes = beginSending(txp); - MeshPacket* p = packetPool.allocCopy(*txp); + MeshPacket *p = packetPool.allocCopy(*txp); perhapsDecode(p); Compressed c = Compressed_init_default; - c.portnum = p->decoded.portnum; - // LOG_DEBUG("Sending back to simulator with portNum %d\n", p->decoded.portnum); + c.portnum = p->decoded.portnum; + // LOG_DEBUG("Sending back to simulator with portNum %d\n", p->decoded.portnum); if (p->decoded.payload.size <= sizeof(c.data.bytes)) { memcpy(&c.data.bytes, p->decoded.payload.bytes, p->decoded.payload.size); - c.data.size = p->decoded.payload.size; + c.data.size = p->decoded.payload.size; } else { LOG_WARN("Payload size is larger than compressed message allows! Sending empty payload.\n"); } @@ -206,8 +204,8 @@ void SimRadio::startSend(MeshPacket * txp) service.sendToPhone(p); // Sending back to simulator } - -void SimRadio::startReceive(MeshPacket *p) { +void SimRadio::startReceive(MeshPacket *p) +{ isReceiving = true; size_t length = getPacketLength(p); uint32_t xmitMsec = getPacketTime(length); @@ -243,8 +241,8 @@ void SimRadio::handleReceiveInterrupt(MeshPacket *p) xmitMsec = getPacketTime(length); // LOG_DEBUG("Payload size %d vs length (includes header) %d\n", p->decoded.payload.size, length); - MeshPacket *mp = packetPool.allocCopy(*p); // keep a copy in packtPool - mp->which_payload_variant = MeshPacket_decoded_tag; // Mark that the payload is already decoded + MeshPacket *mp = packetPool.allocCopy(*p); // keep a copy in packtPool + mp->which_payload_variant = MeshPacket_decoded_tag; // Mark that the payload is already decoded printPacket("Lora RX", mp); @@ -253,15 +251,17 @@ void SimRadio::handleReceiveInterrupt(MeshPacket *p) deliverToReceiver(mp); } -size_t SimRadio::getPacketLength(MeshPacket *mp) { +size_t SimRadio::getPacketLength(MeshPacket *mp) +{ auto &p = mp->decoded; - return (size_t)p.payload.size+sizeof(PacketHeader); + return (size_t)p.payload.size + sizeof(PacketHeader); } -int16_t SimRadio::readData(uint8_t* data, size_t len) { +int16_t SimRadio::readData(uint8_t *data, size_t len) +{ int16_t state = RADIOLIB_ERR_NONE; - if(state == RADIOLIB_ERR_NONE) { + if (state == RADIOLIB_ERR_NONE) { // add null terminator data[len] = 0; } diff --git a/src/platform/portduino/SimRadio.h b/src/platform/portduino/SimRadio.h index c4336a22b..1bfdc5c63 100644 --- a/src/platform/portduino/SimRadio.h +++ b/src/platform/portduino/SimRadio.h @@ -1,22 +1,22 @@ #pragma once -#include "RadioInterface.h" #include "MeshPacketQueue.h" +#include "RadioInterface.h" #include "api/WiFiServerAPI.h" #include class SimRadio : public RadioInterface { - enum PendingISR { ISR_NONE = 0, ISR_RX, ISR_TX, TRANSMIT_DELAY_COMPLETED }; + enum PendingISR { ISR_NONE = 0, ISR_RX, ISR_TX, TRANSMIT_DELAY_COMPLETED }; - /** - * Debugging counts - */ - uint32_t rxBad = 0, rxGood = 0, txGood = 0; + /** + * Debugging counts + */ + uint32_t rxBad = 0, rxGood = 0, txGood = 0; + + MeshPacketQueue txQueue = MeshPacketQueue(MAX_TX_QUEUE); - MeshPacketQueue txQueue = MeshPacketQueue(MAX_TX_QUEUE); - public: SimRadio(); @@ -24,7 +24,6 @@ class SimRadio : public RadioInterface */ static SimRadio *instance; - virtual ErrorCode send(MeshPacket *p) override; /** can we detect a LoRa preamble on the current channel? */ @@ -38,7 +37,7 @@ class SimRadio : public RadioInterface /** Attempt to cancel a previously sent packet. Returns true if a packet was found we could cancel */ virtual bool cancelSending(NodeNum from, PacketId id) override; - /** + /** * Start waiting to receive a message * * External functions can call this method to wake the device from sleep. @@ -47,13 +46,11 @@ class SimRadio : public RadioInterface QueueStatus getQueueStatus() override; - - protected: + protected: /// are _trying_ to receive a packet currently (note - we might just be waiting for one) bool isReceiving = false; - private: - + private: void setTransmitDelay(); /** random timer with certain min. and max. settings */ @@ -71,19 +68,17 @@ class SimRadio : public RadioInterface virtual void startSend(MeshPacket *txp); // derive packet length - size_t getPacketLength(MeshPacket *p); + size_t getPacketLength(MeshPacket *p); - int16_t readData(uint8_t* str, size_t len); + int16_t readData(uint8_t *str, size_t len); - protected: + protected: /** Could we send right now (i.e. either not actively receiving or transmitting)? */ virtual bool canSendImmediately(); - /** * If a send was in progress finish it and return the buffer to the pool */ void completeSending(); - }; extern SimRadio *simRadio; \ No newline at end of file diff --git a/src/platform/rp2040/architecture.h b/src/platform/rp2040/architecture.h index 35d163e4a..d80d88914 100644 --- a/src/platform/rp2040/architecture.h +++ b/src/platform/rp2040/architecture.h @@ -3,5 +3,5 @@ #define ARCH_RP2040 #if defined(PRIVATE_HW) - #define HW_VENDOR HardwareModel_PRIVATE_HW +#define HW_VENDOR HardwareModel_PRIVATE_HW #endif \ No newline at end of file diff --git a/src/platform/rp2040/main-rp2040.cpp b/src/platform/rp2040/main-rp2040.cpp index 3f785d344..1de8c5b68 100644 --- a/src/platform/rp2040/main-rp2040.cpp +++ b/src/platform/rp2040/main-rp2040.cpp @@ -1,6 +1,6 @@ #include "configuration.h" -#include #include +#include void setBluetoothEnable(bool on) { diff --git a/src/platform/rp2040/rp2040CryptoEngine.cpp b/src/platform/rp2040/rp2040CryptoEngine.cpp index bb1c00779..c90126cc7 100644 --- a/src/platform/rp2040/rp2040CryptoEngine.cpp +++ b/src/platform/rp2040/rp2040CryptoEngine.cpp @@ -1,6 +1,6 @@ -#include "configuration.h" #include "CryptoEngine.h" #include "aes.hpp" +#include "configuration.h" class RP2040CryptoEngine : public CryptoEngine { diff --git a/src/platform/stm32wl/STM32WLCryptoEngine.cpp b/src/platform/stm32wl/STM32WLCryptoEngine.cpp index 535d88cfc..7367a2bc0 100644 --- a/src/platform/stm32wl/STM32WLCryptoEngine.cpp +++ b/src/platform/stm32wl/STM32WLCryptoEngine.cpp @@ -1,6 +1,6 @@ -#include "configuration.h" #include "CryptoEngine.h" #include "aes.hpp" +#include "configuration.h" class STM32WLCryptoEngine : public CryptoEngine { diff --git a/src/platform/stm32wl/architecture.h b/src/platform/stm32wl/architecture.h index 02196eaf6..dc7adc5ff 100644 --- a/src/platform/stm32wl/architecture.h +++ b/src/platform/stm32wl/architecture.h @@ -11,21 +11,20 @@ // #ifndef HW_VENDOR - #define HW_VENDOR HardwareModel_PRIVATE_HW +#define HW_VENDOR HardwareModel_PRIVATE_HW #endif #ifdef __cplusplus extern "C" { #endif - void stm32wl_emulate_digitalWrite(long unsigned int pin, long unsigned int value); - int stm32wl_emulate_digitalRead(long unsigned int pin); +void stm32wl_emulate_digitalWrite(long unsigned int pin, long unsigned int value); +int stm32wl_emulate_digitalRead(long unsigned int pin); #ifdef __cplusplus } #endif /* virtual pins for stm32wl_emulate_digitalWrite() / stm32wl_emulate_digitalRead() to recognize */ -#define SX126X_CS 1000 -#define SX126X_DIO1 1001 +#define SX126X_CS 1000 +#define SX126X_DIO1 1001 #define SX126X_RESET 1003 -#define SX126X_BUSY 1004 - +#define SX126X_BUSY 1004 diff --git a/src/platform/stm32wl/layer.c b/src/platform/stm32wl/layer.c index 1352b3910..d6f073200 100644 --- a/src/platform/stm32wl/layer.c +++ b/src/platform/stm32wl/layer.c @@ -1,7 +1,7 @@ -#include #include "architecture.h" #include "stm32wlxx.h" #include "stm32wlxx_hal.h" +#include void HardFault_Handler(void) { @@ -10,28 +10,27 @@ void HardFault_Handler(void) void stm32wl_emulate_digitalWrite(long unsigned int pin, long unsigned int value) { - switch (pin) - { - case SX126X_CS: /* active low */ - if (value) - LL_PWR_UnselectSUBGHZSPI_NSS(); - else - LL_PWR_SelectSUBGHZSPI_NSS(); - break; - case SX126X_RESET: /* active low */ - if (value) - LL_RCC_RF_DisableReset(); - else - { - LL_RCC_RF_EnableReset(); - LL_RCC_HSE_EnableTcxo(); - LL_RCC_HSE_Enable(); - while (!LL_RCC_HSE_IsReady()); - } - break; - default: - asm("bkpt"); - break; + switch (pin) { + case SX126X_CS: /* active low */ + if (value) + LL_PWR_UnselectSUBGHZSPI_NSS(); + else + LL_PWR_SelectSUBGHZSPI_NSS(); + break; + case SX126X_RESET: /* active low */ + if (value) + LL_RCC_RF_DisableReset(); + else { + LL_RCC_RF_EnableReset(); + LL_RCC_HSE_EnableTcxo(); + LL_RCC_HSE_Enable(); + while (!LL_RCC_HSE_IsReady()) + ; + } + break; + default: + asm("bkpt"); + break; } } @@ -40,28 +39,27 @@ static bool irq_happened; void SUBGHZ_Radio_IRQHandler(void) { NVIC_DisableIRQ(SUBGHZ_Radio_IRQn); - irq_happened = true; + irq_happened = true; } int stm32wl_emulate_digitalRead(long unsigned int pin) { int outcome = 0; - switch (pin) - { - case SX126X_BUSY: -// return ((LL_PWR_IsActiveFlag_RFBUSYMS() & LL_PWR_IsActiveFlag_RFBUSYS()) == 1UL); - outcome = LL_PWR_IsActiveFlag_RFBUSYS(); - break; - case SX126X_DIO1: - default: - NVIC_ClearPendingIRQ(SUBGHZ_Radio_IRQn); - irq_happened = false; - NVIC_EnableIRQ(SUBGHZ_Radio_IRQn); - for (int i = 0; i < 64; i++) asm("nop"); - outcome = irq_happened; - break; + switch (pin) { + case SX126X_BUSY: + // return ((LL_PWR_IsActiveFlag_RFBUSYMS() & LL_PWR_IsActiveFlag_RFBUSYS()) == 1UL); + outcome = LL_PWR_IsActiveFlag_RFBUSYS(); + break; + case SX126X_DIO1: + default: + NVIC_ClearPendingIRQ(SUBGHZ_Radio_IRQn); + irq_happened = false; + NVIC_EnableIRQ(SUBGHZ_Radio_IRQn); + for (int i = 0; i < 64; i++) + asm("nop"); + outcome = irq_happened; + break; } return outcome; } - diff --git a/src/platform/stm32wl/main-stm32wl.cpp b/src/platform/stm32wl/main-stm32wl.cpp index f5b83a704..147408441 100644 --- a/src/platform/stm32wl/main-stm32wl.cpp +++ b/src/platform/stm32wl/main-stm32wl.cpp @@ -1,7 +1,7 @@ +#include "RTC.h" +#include "configuration.h" #include #include -#include "configuration.h" -#include "RTC.h" void setBluetoothEnable(bool on) {} @@ -19,9 +19,8 @@ void cpuDeepSleep(uint64_t msecToWake) {} /* pacify libc_nano */ extern "C" { -int _gettimeofday( struct timeval *tv, void *tzvp ) +int _gettimeofday(struct timeval *tv, void *tzvp) { return -1; } } - diff --git a/src/power.h b/src/power.h index b370e0248..6b787d320 100644 --- a/src/power.h +++ b/src/power.h @@ -40,7 +40,7 @@ class Power : private concurrency::OSThread private: uint8_t low_voltage_counter; -#ifdef DEBUG_HEAP +#ifdef DEBUG_HEAP uint32_t lastheap; #endif }; diff --git a/src/shutdown.h b/src/shutdown.h index 7a57d789a..1b0a0509a 100644 --- a/src/shutdown.h +++ b/src/shutdown.h @@ -13,7 +13,7 @@ void powerCommandsCheck() #elif defined(ARCH_NRF52) NVIC_SystemReset(); #else - rebootAtMsec = -1; + rebootAtMsec = -1; LOG_WARN("FIXME implement reboot for this platform. Skipping for now.\n"); #endif } @@ -25,10 +25,10 @@ void powerCommandsCheck() #ifdef PIN_LED1 ledOff(PIN_LED1); #endif -#ifdef PIN_LED2 +#ifdef PIN_LED2 ledOff(PIN_LED2); #endif -#ifdef PIN_LED3 +#ifdef PIN_LED3 ledOff(PIN_LED3); #endif } diff --git a/src/sleep.cpp b/src/sleep.cpp index 5eb62a1c5..921e687bf 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -29,7 +29,8 @@ Observable preflightSleep; /// Called to tell observers we are now entering sleep and you should prepare. Must return 0 /// notifySleep will be called for light or deep sleep, notifyDeepSleep is only called for deep sleep -/// notifyGPSSleep will be called when config.position.gps_enabled is set to 0 or from buttonthread when GPS_POWER_TOGGLE is enabled. +/// notifyGPSSleep will be called when config.position.gps_enabled is set to 0 or from buttonthread when GPS_POWER_TOGGLE is +/// enabled. Observable notifySleep, notifyDeepSleep; Observable notifyGPSSleep; @@ -93,14 +94,14 @@ void setGPSPower(bool on) LOG_INFO("Setting GPS power=%d\n", on); #ifdef HAS_PMU - if (pmu_found && PMU){ + if (pmu_found && PMU) { uint8_t model = PMU->getChipModel(); - if(model == XPOWERS_AXP2101){ + if (model == XPOWERS_AXP2101) { // t-beam-s3-core GNSS power channel on ? PMU->enablePowerOutput(XPOWERS_ALDO4) : PMU->disablePowerOutput(XPOWERS_ALDO4); - }else if(model == XPOWERS_AXP192){ + } else if (model == XPOWERS_AXP192) { // t-beam GNSS power channel - on ? PMU->enablePowerOutput(XPOWERS_LDO3) : PMU->disablePowerOutput(XPOWERS_LDO3); + on ? PMU->enablePowerOutput(XPOWERS_LDO3) : PMU->disablePowerOutput(XPOWERS_LDO3); } } #endif @@ -163,7 +164,7 @@ static void waitEnterSleep() } // Code that still needs to be moved into notifyObservers - console->flush(); // send all our characters before we stop cpu clock + console->flush(); // send all our characters before we stop cpu clock setBluetoothEnable(false); // has to be off before calling light sleep notifySleep.notifyObservers(NULL); @@ -171,32 +172,26 @@ static void waitEnterSleep() void doGPSpowersave(bool on) { - #ifdef HAS_PMU - if (on) - { +#ifdef HAS_PMU + if (on) { LOG_INFO("Turning GPS back on\n"); gps->forceWake(1); setGPSPower(1); - } - else - { + } else { LOG_INFO("Turning off GPS chip\n"); notifyGPSSleep.notifyObservers(NULL); setGPSPower(0); } - #endif - #ifdef PIN_GPS_WAKE - if (on) - { +#endif +#ifdef PIN_GPS_WAKE + if (on) { LOG_INFO("Waking GPS"); gps->forceWake(1); - } - else - { + } else { LOG_INFO("GPS entering sleep"); notifyGPSSleep.notifyObservers(NULL); } - #endif +#endif } void doDeepSleep(uint64_t msecToWake) @@ -239,10 +234,10 @@ void doDeepSleep(uint64_t msecToWake) // all the time. uint8_t model = PMU->getChipModel(); - if(model == XPOWERS_AXP2101){ + if (model == XPOWERS_AXP2101) { PMU->disablePowerOutput(XPOWERS_ALDO3); // lora radio power channel - }else if(model == XPOWERS_AXP192){ - PMU->disablePowerOutput(XPOWERS_LDO2); // lora radio power channel + } else if (model == XPOWERS_AXP192) { + PMU->disablePowerOutput(XPOWERS_LDO2); // lora radio power channel } } #endif @@ -329,7 +324,6 @@ void enableModemSleep() { static esp_pm_config_esp32_t esp32_config; // filled with zeros because bss - #if CONFIG_IDF_TARGET_ESP32S3 esp32_config.max_freq_mhz = CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ; #elif CONFIG_IDF_TARGET_ESP32S2 diff --git a/src/utils.h b/src/utils.h index 36f719ca7..a725bf13c 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,7 +1,7 @@ #pragma once /// C++ v17+ clamp function, limits a given value to a range defined by lo and hi -template -constexpr const T& clamp( const T& v, const T& lo, const T& hi ) { +template constexpr const T &clamp(const T &v, const T &lo, const T &hi) +{ return (v < lo) ? lo : (hi < v) ? hi : v; } \ No newline at end of file diff --git a/variants/Dongle_nRF52840-pca10059-v1/variant.cpp b/variants/Dongle_nRF52840-pca10059-v1/variant.cpp index 5b9288319..8c6bf039c 100644 --- a/variants/Dongle_nRF52840-pca10059-v1/variant.cpp +++ b/variants/Dongle_nRF52840-pca10059-v1/variant.cpp @@ -16,28 +16,23 @@ */ #include "variant.h" +#include "nrf.h" #include "wiring_constants.h" #include "wiring_digital.h" -#include "nrf.h" -const uint32_t g_ADigitalPinMap[] = - { - // P0 - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, +const uint32_t g_ADigitalPinMap[] = { + // P0 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - // P1 - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47}; + // 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); + // LED1 & LED2 + pinMode(PIN_LED1, OUTPUT); + ledOff(PIN_LED1); - pinMode(PIN_LED2, OUTPUT); - ledOff(PIN_LED2); + pinMode(PIN_LED2, OUTPUT); + ledOff(PIN_LED2); } diff --git a/variants/Dongle_nRF52840-pca10059-v1/variant.h b/variants/Dongle_nRF52840-pca10059-v1/variant.h index c846573aa..d165d6bdc 100644 --- a/variants/Dongle_nRF52840-pca10059-v1/variant.h +++ b/variants/Dongle_nRF52840-pca10059-v1/variant.h @@ -43,13 +43,13 @@ extern "C" { #define NUM_ANALOG_OUTPUTS (0) // LEDs -#define PIN_LED1 (0 + 12) // Blue LED P1.12 -#define PIN_LED2 (0 + 6) // Built in Green P0.06 +#define PIN_LED1 (0 + 12) // Blue LED P1.12 +#define PIN_LED2 (0 + 6) // Built in Green P0.06 -//Green Built in LED1 +// Green Built in LED1 //#define PIN_LED1 (0 + 6) // LED1 P1.15 - -//RGB NeoPixel LED2 + +// RGB NeoPixel LED2 //#define PIN_LED1 (0 + 8) Red //#define PIN_LED1 (32 + 9) Green //#define PIN_LED1 (0 + 12) Blue @@ -60,25 +60,24 @@ extern "C" { #define LED_GREEN PIN_LED1 #define LED_BLUE PIN_LED2 -#define LED_STATE_ON 0 // State when LED is litted +#define LED_STATE_ON 0 // State when LED is litted /* * Buttons */ -#define PIN_BUTTON1 (32 + 6) // BTN_DN P1.06 Built in button +#define PIN_BUTTON1 (32 + 6) // BTN_DN P1.06 Built in button /* * Analog pins */ -#define PIN_A0 (-1) +#define PIN_A0 (-1) static const uint8_t A0 = PIN_A0; #define ADC_RESOLUTION 14 // Other pins -#define PIN_AREF (-1) // AREF Not yet used - +#define PIN_AREF (-1) // AREF Not yet used static const uint8_t AREF = PIN_AREF; @@ -97,31 +96,31 @@ static const uint8_t AREF = PIN_AREF; */ #define SPI_INTERFACES_COUNT 2 -#define PIN_SPI_MISO (0 + 17) // MISO P0.17 -#define PIN_SPI_MOSI (0 + 15) // MOSI P0.15 -#define PIN_SPI_SCK (0 + 13) // SCK P0.13 +#define PIN_SPI_MISO (0 + 17) // MISO P0.17 +#define PIN_SPI_MOSI (0 + 15) // MOSI P0.15 +#define PIN_SPI_SCK (0 + 13) // SCK P0.13 -#define PIN_SPI1_MISO (-1) // -#define PIN_SPI1_MOSI (10) // EPD_MOSI P0.10 -#define PIN_SPI1_SCK (9) // EPD_SCLK P0.09 +#define PIN_SPI1_MISO (-1) // +#define PIN_SPI1_MOSI (10) // EPD_MOSI P0.10 +#define PIN_SPI1_SCK (9) // EPD_SCLK P0.09 -static const uint8_t SS = (0 + 31); // LORA_CS P0.31 +static const uint8_t SS = (0 + 31); // LORA_CS P0.31 static const uint8_t MOSI = PIN_SPI_MOSI; static const uint8_t MISO = PIN_SPI_MISO; static const uint8_t SCK = PIN_SPI_SCK; - /* +/* * eink display pins */ //#define PIN_EINK_EN (-1) -#define PIN_EINK_EN (0 + 6) // Turn on the Green built in LED -#define PIN_EINK_CS (32) // EPD_CS -#define PIN_EINK_BUSY (20) // EPD_BUSY -#define PIN_EINK_DC (24) // EPD_D/C -#define PIN_EINK_RES (-1) // Not Connected P0.22 available -#define PIN_EINK_SCLK (9) // EPD_SCLK -#define PIN_EINK_MOSI (10) // EPD_MOSI +#define PIN_EINK_EN (0 + 6) // Turn on the Green built in LED +#define PIN_EINK_CS (32) // EPD_CS +#define PIN_EINK_BUSY (20) // EPD_BUSY +#define PIN_EINK_DC (24) // EPD_D/C +#define PIN_EINK_RES (-1) // Not Connected P0.22 available +#define PIN_EINK_SCLK (9) // EPD_SCLK +#define PIN_EINK_MOSI (10) // EPD_MOSI #define USE_EINK @@ -130,21 +129,21 @@ static const uint8_t SCK = PIN_SPI_SCK; */ #define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE_SDA (32 + 4) // SDA -#define PIN_WIRE_SCL (32 + 7) // SCL +#define PIN_WIRE_SDA (32 + 4) // SDA +#define PIN_WIRE_SCL (32 + 7) // SCL // NiceRF 868 LoRa module #define USE_SX1262 -#define SX126X_CS (0 + 31) // LORA_CS P0.31 -#define SX126X_DIO1 (0 + 29) // DIO1 P0.29 -#define SX126X_BUSY (0 + 2) // LORA_BUSY P0.02 -#define SX126X_RESET (32 + 15) // LORA_RESET P1.15 -#define SX126X_TXEN (32 + 13) // TXEN P1.13 NiceRF 868 dont use -#define SX126X_RXEN (32 + 10) // RXEN P1.10 NiceRF 868 dont use +#define SX126X_CS (0 + 31) // LORA_CS P0.31 +#define SX126X_DIO1 (0 + 29) // DIO1 P0.29 +#define SX126X_BUSY (0 + 2) // LORA_BUSY P0.02 +#define SX126X_RESET (32 + 15) // LORA_RESET P1.15 +#define SX126X_TXEN (32 + 13) // TXEN P1.13 NiceRF 868 dont use +#define SX126X_RXEN (32 + 10) // RXEN P1.10 NiceRF 868 dont use #define SX126X_E22 -#define PIN_GPS_EN (-1) -#define PIN_GPS_PPS (-1) // Pulse per second input from the GPS +#define PIN_GPS_EN (-1) +#define PIN_GPS_PPS (-1) // Pulse per second input from the GPS #define GPS_RX_PIN PIN_SERIAL1_RX #define GPS_TX_PIN PIN_SERIAL1_TX @@ -166,7 +165,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #undef AREF_VOLTAGE #define AREF_VOLTAGE 3.0 #define VBAT_AR_INTERNAL AR_INTERNAL_3_0 -#define ADC_MULTIPLIER VBAT_DIVIDER_COMP //REAL_VBAT_MV_PER_LSB +#define ADC_MULTIPLIER VBAT_DIVIDER_COMP // REAL_VBAT_MV_PER_LSB #define VBAT_RAW_TO_SCALED(x) (REAL_VBAT_MV_PER_LSB * x) #ifdef __cplusplus diff --git a/variants/betafpv_2400_tx_micro/variant.h b/variants/betafpv_2400_tx_micro/variant.h index d4af5dac4..2a8b2f40c 100644 --- a/variants/betafpv_2400_tx_micro/variant.h +++ b/variants/betafpv_2400_tx_micro/variant.h @@ -1,34 +1,34 @@ -//https://betafpv.com/products/elrs-micro-tx-module +// https://betafpv.com/products/elrs-micro-tx-module #include // 0.96" OLED -#define I2C_SDA 22 -#define I2C_SCL 32 +#define I2C_SDA 22 +#define I2C_SCL 32 // NO GPS #undef GPS_RX_PIN #undef GPS_TX_PIN -#define RF95_SCK 18 -#define RF95_MISO 19 -#define RF95_MOSI 23 -#define RF95_NSS 5 -#define RF95_FAN_EN 17 +#define RF95_SCK 18 +#define RF95_MISO 19 +#define RF95_MOSI 23 +#define RF95_NSS 5 +#define RF95_FAN_EN 17 -#define LED_PIN 16 // This is a LED_WS2812 not a standard LED +#define LED_PIN 16 // This is a LED_WS2812 not a standard LED -#define BUTTON_PIN 25 +#define BUTTON_PIN 25 #define BUTTON_NEED_PULLUP #undef EXT_NOTIFY_OUT // SX128X 2.4 Ghz LoRa module #define USE_SX1280 -#define LORA_RESET 14 -#define SX128X_CS 5 -#define SX128X_DIO1 4 -#define SX128X_BUSY 21 -#define SX128X_TXEN 26 -#define SX128X_RXEN 27 +#define LORA_RESET 14 +#define SX128X_CS 5 +#define SX128X_DIO1 4 +#define SX128X_BUSY 21 +#define SX128X_TXEN 26 +#define SX128X_RXEN 27 #define SX128X_RESET LORA_RESET #define SX128X_MAX_POWER 13 diff --git a/variants/diy/dr-dev/variant.h b/variants/diy/dr-dev/variant.h index 7d0625907..122a617b6 100644 --- a/variants/diy/dr-dev/variant.h +++ b/variants/diy/dr-dev/variant.h @@ -12,9 +12,9 @@ #define BUTTON_NEED_PULLUP #define EXT_NOTIFY_OUT 12 // Overridden default pin to use for Ext Notify Module (#975). -#define LORA_DIO0 NOT_A_PIN // a No connect on the SX1262/SX1268 module +#define LORA_DIO0 NOT_A_PIN // a No connect on the SX1262/SX1268 module #define LORA_RESET NOT_A_PIN // RST for SX1276, and for SX1262/SX1268 -#define LORA_DIO3 NOT_A_PIN // Not connected on PCB, but internally on the SX1262/SX1268, if DIO3 is high the TXCO is enabled +#define LORA_DIO3 NOT_A_PIN // Not connected on PCB, but internally on the SX1262/SX1268, if DIO3 is high the TXCO is enabled // In transmitting, set TXEN as high communication level,RXEN pin is low level; // In receiving, set RXEN as high communication level, TXEN is lowlevel; @@ -29,16 +29,15 @@ // PINS FOR THE 900M22S -#define LORA_DIO1 26 // IRQ for SX1262/SX1268 -#define LORA_DIO2 22 // BUSY for SX1262/SX1268 +#define LORA_DIO1 26 // IRQ for SX1262/SX1268 +#define LORA_DIO2 22 // BUSY for SX1262/SX1268 #define LORA_TXEN NOT_A_PIN // Input - RF switch TX control, connecting external MCU IO or DIO2, valid in high level -#define LORA_RXEN 17 // Input - RF switch RX control, connecting external MCU IO, valid in high level +#define LORA_RXEN 17 // Input - RF switch RX control, connecting external MCU IO, valid in high level #undef RF95_NSS #define RF95_NSS 16 #define SX126X_BUSY 22 #define SX126X_CS 16 - // PINS FOR THE 900M30S /* #define LORA_DIO1 27 // IRQ for SX1262/SX1268 diff --git a/variants/diy/v1/variant.h b/variants/diy/v1/variant.h index 456daa708..349ed8ff3 100644 --- a/variants/diy/v1/variant.h +++ b/variants/diy/v1/variant.h @@ -9,11 +9,11 @@ #define GPS_TX_PIN 15 #define GPS_UBLOX -#define BUTTON_PIN 39 // The middle button GPIO on the T-Beam -#define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage +#define BUTTON_PIN 39 // The middle button GPIO on the T-Beam +#define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage #define ADC_MULTIPLIER 1.85 // (R1 = 470k, R2 = 680k) -#define EXT_NOTIFY_OUT 12 // Overridden default pin to use for Ext Notify Module (#975). -#define LED_PIN 2 // add status LED (compatible with core-pcb and DIY targets) +#define EXT_NOTIFY_OUT 12 // Overridden default pin to use for Ext Notify Module (#975). +#define LED_PIN 2 // add status LED (compatible with core-pcb and DIY targets) #define LORA_DIO0 26 // a No connect on the SX1262/SX1268 module #define LORA_RESET 23 // RST for SX1276, and for SX1262/SX1268 diff --git a/variants/diy/v1_1/variant.h b/variants/diy/v1_1/variant.h index 3100c7029..a550b9d1c 100644 --- a/variants/diy/v1_1/variant.h +++ b/variants/diy/v1_1/variant.h @@ -19,8 +19,8 @@ // In transmitting, set TXEN as high communication level,RXEN pin is low level; // In receiving, set RXEN as high communication level, TXEN is lowlevel; // Before powering off, set TXEN、RXEN as low level. -#define LORA_RXEN 14 // Input - RF switch RX control, connecting external MCU IO, valid in high level -#define LORA_TXEN 13 // Input - RF switch TX control, connecting external MCU IO or DIO2, valid in high level +#define LORA_RXEN 14 // Input - RF switch RX control, connecting external MCU IO, valid in high level +#define LORA_TXEN 13 // Input - RF switch TX control, connecting external MCU IO or DIO2, valid in high level #undef RF95_SCK #define RF95_SCK 18 diff --git a/variants/feather_diy/variant.h b/variants/feather_diy/variant.h index 92128add2..85614d9b5 100644 --- a/variants/feather_diy/variant.h +++ b/variants/feather_diy/variant.h @@ -43,11 +43,11 @@ extern "C" { #define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE_SDA (0 + 12) //P0.12 22 -#define PIN_WIRE_SCL (0 + 11) //P0.12 23 +#define PIN_WIRE_SDA (0 + 12) // P0.12 22 +#define PIN_WIRE_SCL (0 + 11) // P0.12 23 -#define PIN_LED1 (32 + 15) //P1.15 3 -#define PIN_LED2 (32 + 10) //P1.10 4 +#define PIN_LED1 (32 + 15) // P1.15 3 +#define PIN_LED2 (32 + 10) // P1.10 4 #define LED_BUILTIN PIN_LED1 @@ -56,30 +56,30 @@ extern "C" { #define LED_STATE_ON 1 // State when LED is litted -#define BUTTON_PIN (32 + 2) //P1.02 7 +#define BUTTON_PIN (32 + 2) // P1.02 7 /* * Serial interfaces */ -#define PIN_SERIAL1_RX (0 + 24) //P0.24 1 -#define PIN_SERIAL1_TX (0 + 25) //P0.25 0 +#define PIN_SERIAL1_RX (0 + 24) // P0.24 1 +#define PIN_SERIAL1_TX (0 + 25) // P0.25 0 #define PIN_SERIAL2_RX (-1) #define PIN_SERIAL2_TX (-1) #define SPI_INTERFACES_COUNT 1 -#define PIN_SPI_MISO (0 + 15) //P0.15 24 -#define PIN_SPI_MOSI (0 + 13) //P0.13 25 -#define PIN_SPI_SCK (0 + 14) //P0.14 26 +#define PIN_SPI_MISO (0 + 15) // P0.15 24 +#define PIN_SPI_MOSI (0 + 13) // P0.13 25 +#define PIN_SPI_SCK (0 + 14) // P0.14 26 #define SS 2 -#define LORA_DIO0 -1 // a No connect on the SX1262/SX1268 module -#define LORA_RESET (32 + 9) //P1.09 13 // RST for SX1276, and for SX1262/SX1268 -#define LORA_DIO1 (0 + 6) //P0.06 11 // IRQ for SX1262/SX1268 -#define LORA_DIO2 (0 + 8) //P0.08 12 // BUSY for SX1262/SX1268 -#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262/SX1268, if DIO3 is high the TXCO is enabled +#define LORA_DIO0 -1 // a No connect on the SX1262/SX1268 module +#define LORA_RESET (32 + 9) // P1.09 13 // RST for SX1276, and for SX1262/SX1268 +#define LORA_DIO1 (0 + 6) // P0.06 11 // IRQ for SX1262/SX1268 +#define LORA_DIO2 (0 + 8) // P0.08 12 // BUSY for SX1262/SX1268 +#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262/SX1268, if DIO3 is high the TXCO is enabled #define RF95_SCK SCK #define RF95_MISO MI @@ -99,8 +99,8 @@ extern "C" { #define SX126X_DIO1 LORA_DIO1 #define SX126X_BUSY LORA_DIO2 #define SX126X_RESET LORA_RESET -#define SX126X_RXEN (0 + 27) //P0.27 10 -#define SX126X_TXEN (0 + 26) //P0.26 9 +#define SX126X_RXEN (0 + 27) // P0.27 10 +#define SX126X_TXEN (0 + 26) // P0.26 9 #ifdef EBYTE_E22 // Internally the TTGO module hooks the SX126x-DIO2 in to control the TX/RX switch diff --git a/variants/heltec_v1/variant.h b/variants/heltec_v1/variant.h index 9ea07eb0c..50a786623 100644 --- a/variants/heltec_v1/variant.h +++ b/variants/heltec_v1/variant.h @@ -12,8 +12,8 @@ #define RESET_OLED 16 // If defined, this pin will be used to reset the display controller -#define LED_PIN 25 // If defined we will blink this LED -#define BUTTON_PIN 0 // If defined, this will be used for user button presses +#define LED_PIN 25 // If defined we will blink this LED +#define BUTTON_PIN 0 // If defined, this will be used for user button presses #define USE_RF95 #define LORA_DIO0 26 // a No connect on the SX1262 module diff --git a/variants/heltec_v2.1/variant.h b/variants/heltec_v2.1/variant.h index d2c00a18c..884ad83d6 100644 --- a/variants/heltec_v2.1/variant.h +++ b/variants/heltec_v2.1/variant.h @@ -29,5 +29,5 @@ #define ADC_MULTIPLIER 3.8 -#define BATTERY_PIN 37 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage +#define BATTERY_PIN 37 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage #define EXT_NOTIFY_OUT 13 // Default pin to use for Ext Notify Module. diff --git a/variants/heltec_v2/variant.h b/variants/heltec_v2/variant.h index e5981fd63..893ee320f 100644 --- a/variants/heltec_v2/variant.h +++ b/variants/heltec_v2/variant.h @@ -27,4 +27,3 @@ // ratio of voltage divider = 3.20 (R12=100k, R10=220k) #define ADC_MULTIPLIER 3.2 #define BATTERY_PIN 13 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage - diff --git a/variants/heltec_v3/variant.h b/variants/heltec_v3/variant.h index 267ebc2ab..a2e8bde8e 100644 --- a/variants/heltec_v3/variant.h +++ b/variants/heltec_v3/variant.h @@ -12,19 +12,19 @@ #define USE_SX1262 -#define LORA_DIO0 -1 // a No connect on the SX1262 module -#define LORA_RESET 12 -#define LORA_DIO1 14 // SX1262 IRQ -#define LORA_DIO2 13 // SX1262 BUSY -#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled +#define LORA_DIO0 -1 // a No connect on the SX1262 module +#define LORA_RESET 12 +#define LORA_DIO1 14 // SX1262 IRQ +#define LORA_DIO2 13 // SX1262 BUSY +#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled -#define RF95_SCK 9 -#define RF95_MISO 11 -#define RF95_MOSI 10 -#define RF95_NSS 8 +#define RF95_SCK 9 +#define RF95_MISO 11 +#define RF95_MOSI 10 +#define RF95_NSS 8 -#define SX126X_CS RF95_NSS -#define SX126X_DIO1 LORA_DIO1 -#define SX126X_BUSY LORA_DIO2 -#define SX126X_RESET LORA_RESET +#define SX126X_CS RF95_NSS +#define SX126X_DIO1 LORA_DIO1 +#define SX126X_BUSY LORA_DIO2 +#define SX126X_RESET LORA_RESET #define SX126X_E22 diff --git a/variants/heltec_wsl_v3/variant.h b/variants/heltec_wsl_v3/variant.h index b8f911066..bd7a03a99 100644 --- a/variants/heltec_wsl_v3/variant.h +++ b/variants/heltec_wsl_v3/variant.h @@ -10,19 +10,19 @@ #define USE_SX1262 -#define LORA_DIO0 -1 // a No connect on the SX1262 module -#define LORA_RESET 12 -#define LORA_DIO1 14 // SX1262 IRQ -#define LORA_DIO2 13 // SX1262 BUSY -#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled +#define LORA_DIO0 -1 // a No connect on the SX1262 module +#define LORA_RESET 12 +#define LORA_DIO1 14 // SX1262 IRQ +#define LORA_DIO2 13 // SX1262 BUSY +#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled -#define RF95_SCK 9 -#define RF95_MISO 11 -#define RF95_MOSI 10 -#define RF95_NSS 8 +#define RF95_SCK 9 +#define RF95_MISO 11 +#define RF95_MOSI 10 +#define RF95_NSS 8 -#define SX126X_CS RF95_NSS -#define SX126X_DIO1 LORA_DIO1 -#define SX126X_BUSY LORA_DIO2 -#define SX126X_RESET LORA_RESET +#define SX126X_CS RF95_NSS +#define SX126X_DIO1 LORA_DIO1 +#define SX126X_BUSY LORA_DIO2 +#define SX126X_RESET LORA_RESET #define SX126X_E22 \ No newline at end of file diff --git a/variants/lora_isp4520/variant.cpp b/variants/lora_isp4520/variant.cpp index cf1320f4f..41b31384a 100644 --- a/variants/lora_isp4520/variant.cpp +++ b/variants/lora_isp4520/variant.cpp @@ -25,7 +25,7 @@ const uint32_t g_ADigitalPinMap[] = { 25, // D0 SPI_MISO - 24, // D1 SPI_NSS + 24, // D1 SPI_NSS 23, // D2 SPI_SCK 4, // D3 VBAT 11, // D4 DIO1 @@ -39,14 +39,14 @@ const uint32_t g_ADigitalPinMap[] = { 10, // D12 LED1 GREEN 17, // D13 LED2 RED 9, // D14 BUZZER - 7, // D15 BUTTON1 + 7, // D15 BUTTON1 }; #include void initVariant() { - for (int i : {PIN_LED1, PIN_LED2}) { - pinMode(i, OUTPUT); - ledOff(i); - } + for (int i : {PIN_LED1, PIN_LED2}) { + pinMode(i, OUTPUT); + ledOff(i); + } } diff --git a/variants/lora_isp4520/variant.h b/variants/lora_isp4520/variant.h index 1d1ad8b97..ce0c48297 100644 --- a/variants/lora_isp4520/variant.h +++ b/variants/lora_isp4520/variant.h @@ -33,7 +33,7 @@ // Number of pins defined in PinDescription array #define PINS_COUNT (16) #define NUM_DIGITAL_PINS (16) -#define NUM_ANALOG_INPUTS (1) +#define NUM_ANALOG_INPUTS (1) #define NUM_ANALOG_OUTPUTS (1) /* @@ -41,7 +41,7 @@ */ #define SPI_INTERFACES_COUNT 1 -// These are in arduino pin numbers, +// These are in arduino pin numbers, // translation in g_ADigitalPinMap in variants.cpp #define PIN_SPI_MISO (0) #define PIN_SPI_MOSI (9) @@ -54,9 +54,9 @@ // GPIOs the SX1262 is connected #define USE_SX1262 -#define SX126X_CS 1 // aka SPI_NSS +#define SX126X_CS 1 // aka SPI_NSS #define SX126X_DIO1 (4) -#define SX126X_BUSY (5) +#define SX126X_BUSY (5) #define SX126X_RESET (6) /* @@ -80,7 +80,7 @@ /* * Buttons */ -#define PIN_BUTTON1 (15) +#define PIN_BUTTON1 (15) #define PIN_BUTTON2 (7) #define PIN_BUTTON3 (8) diff --git a/variants/lora_relay_v2/variant.cpp b/variants/lora_relay_v2/variant.cpp index 147f535c9..23d648873 100644 --- a/variants/lora_relay_v2/variant.cpp +++ b/variants/lora_relay_v2/variant.cpp @@ -25,22 +25,22 @@ const uint32_t g_ADigitalPinMap[] = { // D0 .. D13 - 25, // D0 is P0.25 (UART TX) - 24, // D1 is P0.24 (UART RX - 10, // D2 is P0.10 (NFC2) - 47, // D3 is P1.15 (LED1) + 25, // D0 is P0.25 (UART TX) + 24, // D1 is P0.24 (UART RX + 10, // D2 is P0.10 (NFC2) + 47, // D3 is P1.15 (LED1) (32 + 10), // D4 is P1.10 (LED2) - 40, // D5 is P1.08 - 7, // D6 is P0.07 - 34, // D7 is P1.02 (Switch) - 16, // D8 is P0.16 (NeoPixel) - 26, // D9 is P0.26 D_RS (IPS data/command control) - 27, // D10 is P0.27 - 6, // D11 is P0.06 D_RES (IPS display reset) - 8, // D12 is P0.08 D_CS (IPS display chip select) - 41, // D13 is P0.23 BLT (IPS display backlight) - 4, // D14 is P0.04 SX1262 RXEN - 5, // D15 is P0.05 BOOST_EN (5V buck converter enable for the the radio power) + 40, // D5 is P1.08 + 7, // D6 is P0.07 + 34, // D7 is P1.02 (Switch) + 16, // D8 is P0.16 (NeoPixel) + 26, // D9 is P0.26 D_RS (IPS data/command control) + 27, // D10 is P0.27 + 6, // D11 is P0.06 D_RES (IPS display reset) + 8, // D12 is P0.08 D_CS (IPS display chip select) + 41, // D13 is P0.23 BLT (IPS display backlight) + 4, // D14 is P0.04 SX1262 RXEN + 5, // D15 is P0.05 BOOST_EN (5V buck converter enable for the the radio power) // D14 .. D21 (aka A0 .. A7) 30, // D16 is P0.30 (A0) @@ -77,7 +77,7 @@ const uint32_t g_ADigitalPinMap[] = { // 32, // P1.00 is SWO (attached to debug header) // D29-D43 - 32 + 12, // D29 P0.27 E22-SX1262 DIO1 + 32 + 12, // D29 P0.27 E22-SX1262 DIO1 28, // D30 P0.28 E22-SX1262 DIO2 30, // D31 P0.30 E22-SX1262 TXEN 35, // D32 P1.03 E22-SX1262 NSS diff --git a/variants/lora_relay_v2/variant.h b/variants/lora_relay_v2/variant.h index 0ff47745e..bc1f0714a 100644 --- a/variants/lora_relay_v2/variant.h +++ b/variants/lora_relay_v2/variant.h @@ -164,7 +164,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #define ST7735_SDA (39) // actually spi MOSI #define ST7735_SCK (37) // actually spi clk -#define PIN_GPS_WAKE 36 // Just kill GPS power when we want it to sleep? FIXME +#define PIN_GPS_WAKE 36 // Just kill GPS power when we want it to sleep? FIXME #define GPS_WAKE_ACTIVE 0 // GPS Power output is active low // #define LORA_DISABLE_SENDING // The board can brownout during lora TX if you don't have a battery connected. Disable sending diff --git a/variants/m5stack_core/pins_arduino.h b/variants/m5stack_core/pins_arduino.h index 8b86a0d6f..8f2a0041e 100644 --- a/variants/m5stack_core/pins_arduino.h +++ b/variants/m5stack_core/pins_arduino.h @@ -4,12 +4,12 @@ #include #define EXTERNAL_NUM_INTERRUPTS 16 -#define NUM_DIGITAL_PINS 20 -#define NUM_ANALOG_INPUTS 16 +#define NUM_DIGITAL_PINS 20 +#define NUM_ANALOG_INPUTS 16 -#define analogInputToDigitalPin(p) (((p)<20)?(analogChannelToDigitalPin(p)):-1) -#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) -#define digitalPinHasPWM(p) (p < 34) +#define analogInputToDigitalPin(p) (((p) < 20) ? (analogChannelToDigitalPin(p)) : -1) +#define digitalPinToInterrupt(p) (((p) < 40) ? (p) : -1) +#define digitalPinHasPWM(p) (p < 34) static const uint8_t TX = 1; static const uint8_t RX = 3; @@ -20,10 +20,10 @@ static const uint8_t RXD2 = 16; static const uint8_t SDA = 21; static const uint8_t SCL = 22; -static const uint8_t SS = 5; -static const uint8_t MOSI = 23; -static const uint8_t MISO = 19; -static const uint8_t SCK = 18; +static const uint8_t SS = 5; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 19; +static const uint8_t SCK = 18; static const uint8_t G23 = 23; static const uint8_t G19 = 19; diff --git a/variants/m5stack_core/variant.h b/variants/m5stack_core/variant.h index 186788f06..d9ef9ab28 100644 --- a/variants/m5stack_core/variant.h +++ b/variants/m5stack_core/variant.h @@ -25,8 +25,8 @@ #define USE_RF95 #define LORA_DIO0 36 // a No connect on the SX1262 module #define LORA_RESET 26 -#define LORA_DIO1 RADIOLIB_NC// Not really used -#define LORA_DIO2 RADIOLIB_NC// Not really used +#define LORA_DIO1 RADIOLIB_NC // Not really used +#define LORA_DIO2 RADIOLIB_NC // Not really used // This board has different GPS pins than all other boards #undef GPS_RX_PIN diff --git a/variants/m5stack_coreink/pins_arduino.h b/variants/m5stack_coreink/pins_arduino.h index 93329f499..7f9a14785 100644 --- a/variants/m5stack_coreink/pins_arduino.h +++ b/variants/m5stack_coreink/pins_arduino.h @@ -4,12 +4,12 @@ #include #define EXTERNAL_NUM_INTERRUPTS 16 -#define NUM_DIGITAL_PINS 40 -#define NUM_ANALOG_INPUTS 16 +#define NUM_DIGITAL_PINS 40 +#define NUM_ANALOG_INPUTS 16 -#define analogInputToDigitalPin(p) (((p)<20)?(esp32_adc2gpio[(p)]):-1) -#define digitalPinToInterrupt(p) (((p)<40)?(p):-1) -#define digitalPinHasPWM(p) (p < 34) +#define analogInputToDigitalPin(p) (((p) < 20) ? (esp32_adc2gpio[(p)]) : -1) +#define digitalPinToInterrupt(p) (((p) < 40) ? (p) : -1) +#define digitalPinHasPWM(p) (p < 34) #define TX2 -1 #define RX2 -1 @@ -20,10 +20,10 @@ static const uint8_t RX = 3; static const uint8_t SDA = 32; static const uint8_t SCL = 33; -static const uint8_t SS = 9; -static const uint8_t MOSI = 23; -static const uint8_t MISO = 34; -static const uint8_t SCK = 18; +static const uint8_t SS = 9; +static const uint8_t MOSI = 23; +static const uint8_t MISO = 34; +static const uint8_t SCK = 18; static const uint8_t G26 = 26; static const uint8_t G36 = 36; diff --git a/variants/m5stack_coreink/variant.h b/variants/m5stack_coreink/variant.h index e5f49c7a8..37131caca 100644 --- a/variants/m5stack_coreink/variant.h +++ b/variants/m5stack_coreink/variant.h @@ -10,16 +10,16 @@ #define PCF8563_RTC 0x51 #define HAS_RTC 1 -//Wheel -// Down 37 -// Push 38 -// Up 39 -// Top Physical Button 5 +// Wheel +// Down 37 +// Push 38 +// Up 39 +// Top Physical Button 5 #define BUTTON_NEED_PULLUP #define BUTTON_PIN 5 -//BUZZER +// BUZZER #define PIN_BUZZER 2 #undef RF95_SCK @@ -28,10 +28,10 @@ #undef RF95_NSS #define USE_RF95 -#define RF95_SCK 18 +#define RF95_SCK 18 #define RF95_MISO 34 -#define RF95_MOSI 23 -#define RF95_NSS 14 +#define RF95_MOSI 23 +#define RF95_NSS 14 #define LORA_DIO0 25 #define LORA_RESET 26 #define LORA_DIO1 RADIOLIB_NC @@ -42,12 +42,12 @@ #undef GPS_TX_PIN #define USE_EINK -//https://docs.m5stack.com/en/core/coreink -//https://m5stack.oss-cn-shenzhen.aliyuncs.com/resource/docs/schematic/Core/coreink/coreink_sch.pdf -#define PIN_EINK_EN -1 // N/C -#define PIN_EINK_CS 9 // EPD_CS -#define PIN_EINK_BUSY 4 // EPD_BUSY -#define PIN_EINK_DC 15 // EPD_D/C -#define PIN_EINK_RES -1 // Connected but not needed -#define PIN_EINK_SCLK 18 // EPD_SCLK -#define PIN_EINK_MOSI 23 // EPD_MOSI +// https://docs.m5stack.com/en/core/coreink +// https://m5stack.oss-cn-shenzhen.aliyuncs.com/resource/docs/schematic/Core/coreink/coreink_sch.pdf +#define PIN_EINK_EN -1 // N/C +#define PIN_EINK_CS 9 // EPD_CS +#define PIN_EINK_BUSY 4 // EPD_BUSY +#define PIN_EINK_DC 15 // EPD_D/C +#define PIN_EINK_RES -1 // Connected but not needed +#define PIN_EINK_SCLK 18 // EPD_SCLK +#define PIN_EINK_MOSI 23 // EPD_MOSI diff --git a/variants/nano-g1/variant.h b/variants/nano-g1/variant.h index ff0fb4401..eec6e8a07 100644 --- a/variants/nano-g1/variant.h +++ b/variants/nano-g1/variant.h @@ -3,8 +3,9 @@ #define I2C_SDA 21 #define I2C_SCL 22 -#define BUTTON_PIN 36 // The middle button GPIO on the Nano G1 -//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented anywhere. +#define BUTTON_PIN 36 // The middle button GPIO on the Nano G1 +//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented +// anywhere. #define EXT_NOTIFY_OUT 13 // Default pin to use for Ext Notify Module. // common pinout for their SX1262 vs RF95 modules - both can be enabled and we will probe at runtime for RF95 and if @@ -23,7 +24,7 @@ #define SX126X_DIO1 LORA_DIO1 #define SX126X_BUSY LORA_DIO2 #define SX126X_RESET LORA_RESET -#define SX126X_E22 // Not really an E22 +#define SX126X_E22 // Not really an E22 // Internally the module hooks the SX1262-DIO2 in to control the TX/RX switch (which is the default for the sx1262interface // code) #endif diff --git a/variants/pca10056-rc-clock/variant.cpp b/variants/pca10056-rc-clock/variant.cpp index bd85e9713..a1882a33f 100644 --- a/variants/pca10056-rc-clock/variant.cpp +++ b/variants/pca10056-rc-clock/variant.cpp @@ -19,31 +19,24 @@ */ #include "variant.h" +#include "nrf.h" #include "wiring_constants.h" #include "wiring_digital.h" -#include "nrf.h" -const uint32_t g_ADigitalPinMap[] = -{ - // P0 - 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , - 8 , 9 , 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - - // P1 - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47 -}; +const uint32_t g_ADigitalPinMap[] = { + // P0 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 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); + // LED1 & LED2 + pinMode(PIN_LED1, OUTPUT); + ledOff(PIN_LED1); - pinMode(PIN_LED2, OUTPUT); - ledOff(PIN_LED2);; + pinMode(PIN_LED2, OUTPUT); + ledOff(PIN_LED2); + ; } - diff --git a/variants/portduino/variant.h b/variants/portduino/variant.h index 76696b7af..e6269a38b 100644 --- a/variants/portduino/variant.h +++ b/variants/portduino/variant.h @@ -12,7 +12,7 @@ #define LORA_DIO0 26 // a No connect on the SX1262 module #define LORA_RESET 14 #define LORA_DIO1 33 // SX1262 IRQ, called DIO0 on pinelora schematic, pin 7 on ch341f "ack" - FIXME, enable hwints in linux -#define LORA_DIO2 32 // SX1262 BUSY, actually connected to "DIO5" on pinelora schematic, pin 8 on ch341f "slct" +#define LORA_DIO2 32 // SX1262 BUSY, actually connected to "DIO5" on pinelora schematic, pin 8 on ch341f "slct" #define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled #ifdef USE_SX1262 @@ -20,6 +20,5 @@ #define SX126X_DIO1 LORA_DIO1 #define SX126X_BUSY LORA_DIO2 #define SX126X_RESET LORA_RESET -// HOPE RFM90 does not have a TCXO therefore not SX126X_E22 +// HOPE RFM90 does not have a TCXO therefore not SX126X_E22 #endif - diff --git a/variants/ppr/variant.h b/variants/ppr/variant.h index 24ddc09ca..4b37970a4 100644 --- a/variants/ppr/variant.h +++ b/variants/ppr/variant.h @@ -138,7 +138,7 @@ static const uint8_t SCK = PIN_SPI_SCK; // #define SX126X_ANT_SW (32 + 10) #define SX126X_RXEN (22) #define SX126X_TXEN (24) -#define SX126X_E22 // Indicates this SX1262 is inside of an ebyte E22 module and special config should be done for that +#define SX126X_E22 // Indicates this SX1262 is inside of an ebyte E22 module and special config should be done for that // ERC12864-10 LCD #define ERC12864_CS (32 + 4) diff --git a/variants/ppr1/variant.cpp b/variants/ppr1/variant.cpp index 7c763037d..acc3e344a 100644 --- a/variants/ppr1/variant.cpp +++ b/variants/ppr1/variant.cpp @@ -25,9 +25,7 @@ const uint32_t g_ADigitalPinMap[] = { // P0 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, // P1 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}; diff --git a/variants/ppr1/variant.h b/variants/ppr1/variant.h index a7ee07701..635614da0 100644 --- a/variants/ppr1/variant.h +++ b/variants/ppr1/variant.h @@ -25,7 +25,6 @@ #define USE_LFXO // Board uses 32khz crystal for LF // #define USE_LFRC // Board uses RC for LF - /*---------------------------------------------------------------------------- * Headers *----------------------------------------------------------------------------*/ diff --git a/variants/rak11200/pins_arduino.h b/variants/rak11200/pins_arduino.h index a85faaa7f..2dfe02614 100644 --- a/variants/rak11200/pins_arduino.h +++ b/variants/rak11200/pins_arduino.h @@ -11,10 +11,10 @@ #define digitalPinToInterrupt(p) (((p) < 40) ? (p) : -1) #define digitalPinHasPWM(p) (p < 34) -#define LED_GREEN 12 -#define LED_BLUE 2 +#define LED_GREEN 12 +#define LED_BLUE 2 -#define LED_BUILTIN LED_GREEN +#define LED_BUILTIN LED_GREEN static const uint8_t TX = 1; static const uint8_t RX = 3; diff --git a/variants/rak11200/variant.h b/variants/rak11200/variant.h index 569f8f9de..7f2c24082 100644 --- a/variants/rak11200/variant.h +++ b/variants/rak11200/variant.h @@ -63,7 +63,8 @@ static const uint8_t SCK = 33; #define LORA_RESET WB_IO4 // RST for SX1276, and for SX1262/SX1268 #define LORA_DIO1 WB_IO6 // IRQ for SX1262/SX1268 #define LORA_DIO2 WB_IO5 // BUSY for SX1262/SX1268 -#define LORA_DIO3 RADIOLIB_NC // Not connected on PCB, but internally on the TTGO SX1262/SX1268, if DIO3 is high the TXCO is enabled +#define LORA_DIO3 \ + RADIOLIB_NC // Not connected on PCB, but internally on the TTGO SX1262/SX1268, if DIO3 is high the TXCO is enabled #undef RF95_SCK #define RF95_SCK SCK @@ -75,7 +76,7 @@ static const uint8_t SCK = 33; #define RF95_NSS SS #define USE_SX1262 -#define SX126X_CS SS// NSS for SX126X +#define SX126X_CS SS // NSS for SX126X #define SX126X_DIO1 LORA_DIO1 #define SX126X_BUSY LORA_DIO2 #define SX126X_RESET LORA_RESET diff --git a/variants/rak4631/variant.cpp b/variants/rak4631/variant.cpp index b96f6f1cd..75cca1dc3 100644 --- a/variants/rak4631/variant.cpp +++ b/variants/rak4631/variant.cpp @@ -19,28 +19,23 @@ */ #include "variant.h" +#include "nrf.h" #include "wiring_constants.h" #include "wiring_digital.h" -#include "nrf.h" -const uint32_t g_ADigitalPinMap[] = - { - // P0 - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, +const uint32_t g_ADigitalPinMap[] = { + // P0 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - // P1 - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47}; + // 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); + // LED1 & LED2 + pinMode(PIN_LED1, OUTPUT); + ledOff(PIN_LED1); - pinMode(PIN_LED2, OUTPUT); - ledOff(PIN_LED2); + pinMode(PIN_LED2, OUTPUT); + ledOff(PIN_LED2); } diff --git a/variants/rak4631/variant.h b/variants/rak4631/variant.h index 7b07c9aff..a37e1e7de 100644 --- a/variants/rak4631/variant.h +++ b/variants/rak4631/variant.h @@ -65,7 +65,6 @@ extern "C" { #define PIN_BUTTON3 24 #define PIN_BUTTON4 25 - /* * Analog pins */ @@ -116,14 +115,14 @@ static const uint8_t AREF = PIN_AREF; #define PIN_SPI1_MISO (29) // (0 + 29) #define PIN_SPI1_MOSI (30) // (0 + 30) -#define PIN_SPI1_SCK (3) // (0 + 3) +#define PIN_SPI1_SCK (3) // (0 + 3) static const uint8_t SS = 42; static const uint8_t MOSI = PIN_SPI_MOSI; static const uint8_t MISO = PIN_SPI_MISO; static const uint8_t SCK = PIN_SPI_SCK; - /* +/* * eink display pins */ @@ -136,7 +135,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #define PIN_EINK_MOSI (0 + 30) // also called SDI // Controls power for the eink display - Board power is enabled either by VBUS from USB or the CPU asserting PWR_ON -// FIXME - I think this is actually just the board power enable - it enables power to the CPU also +// FIXME - I think this is actually just the board power enable - it enables power to the CPU also //#define PIN_EINK_PWR_ON (-1) // #define USE_EINK @@ -173,7 +172,7 @@ static const uint8_t SCK = PIN_SPI_SCK; SW1 <-> P0.01 (Arduino GPIO number 1) A0 <-> P0.04/AIN2 (Arduino Analog A2 A1 <-> P0.31/AIN7 (Arduino Analog A7 - SPI_CS <-> P0.26 (Arduino GPIO number 26) + SPI_CS <-> P0.26 (Arduino GPIO number 26) */ // RAK4630 LoRa module @@ -203,7 +202,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #define GPS_TX_PIN PIN_SERIAL1_TX // RAK12002 RTC Module -#define RV3028_RTC (uint8_t) 0b1010010 +#define RV3028_RTC (uint8_t)0b1010010 // RAK18001 Buzzer in Slot C // #define PIN_BUZZER 21 // IO3 is PWM2 @@ -226,7 +225,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #undef AREF_VOLTAGE #define AREF_VOLTAGE 3.0 #define VBAT_AR_INTERNAL AR_INTERNAL_3_0 -#define ADC_MULTIPLIER VBAT_DIVIDER_COMP //REAL_VBAT_MV_PER_LSB +#define ADC_MULTIPLIER VBAT_DIVIDER_COMP // REAL_VBAT_MV_PER_LSB #define VBAT_RAW_TO_SCALED(x) (REAL_VBAT_MV_PER_LSB * x) #define HAS_RTC 1 diff --git a/variants/rak4631_epaper/variant.cpp b/variants/rak4631_epaper/variant.cpp index b96f6f1cd..75cca1dc3 100644 --- a/variants/rak4631_epaper/variant.cpp +++ b/variants/rak4631_epaper/variant.cpp @@ -19,28 +19,23 @@ */ #include "variant.h" +#include "nrf.h" #include "wiring_constants.h" #include "wiring_digital.h" -#include "nrf.h" -const uint32_t g_ADigitalPinMap[] = - { - // P0 - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, +const uint32_t g_ADigitalPinMap[] = { + // P0 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - // P1 - 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, 45, 46, 47}; + // 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); + // LED1 & LED2 + pinMode(PIN_LED1, OUTPUT); + ledOff(PIN_LED1); - pinMode(PIN_LED2, OUTPUT); - ledOff(PIN_LED2); + pinMode(PIN_LED2, OUTPUT); + ledOff(PIN_LED2); } diff --git a/variants/rak4631_epaper/variant.h b/variants/rak4631_epaper/variant.h index 890f00ddd..9961abfa1 100644 --- a/variants/rak4631_epaper/variant.h +++ b/variants/rak4631_epaper/variant.h @@ -65,7 +65,6 @@ extern "C" { #define PIN_BUTTON3 24 #define PIN_BUTTON4 25 - /* * Analog pins */ @@ -116,14 +115,14 @@ static const uint8_t AREF = PIN_AREF; #define PIN_SPI1_MISO (29) // (0 + 29) #define PIN_SPI1_MOSI (30) // (0 + 30) -#define PIN_SPI1_SCK (3) // (0 + 3) +#define PIN_SPI1_SCK (3) // (0 + 3) static const uint8_t SS = 42; static const uint8_t MOSI = PIN_SPI_MOSI; static const uint8_t MISO = PIN_SPI_MISO; static const uint8_t SCK = PIN_SPI_SCK; - /* +/* * eink display pins */ @@ -136,7 +135,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #define PIN_EINK_MOSI (0 + 30) // also called SDI // Controls power for the eink display - Board power is enabled either by VBUS from USB or the CPU asserting PWR_ON -// FIXME - I think this is actually just the board power enable - it enables power to the CPU also +// FIXME - I think this is actually just the board power enable - it enables power to the CPU also //#define PIN_EINK_PWR_ON (-1) #define USE_EINK @@ -173,7 +172,7 @@ static const uint8_t SCK = PIN_SPI_SCK; SW1 <-> P0.01 (Arduino GPIO number 1) A0 <-> P0.04/AIN2 (Arduino Analog A2 A1 <-> P0.31/AIN7 (Arduino Analog A7 - SPI_CS <-> P0.26 (Arduino GPIO number 26) + SPI_CS <-> P0.26 (Arduino GPIO number 26) */ // RAK4630 LoRa module @@ -203,7 +202,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #define GPS_TX_PIN PIN_SERIAL1_TX // RAK12002 RTC Module -#define RV3028_RTC (uint8_t) 0b1010010 +#define RV3028_RTC (uint8_t)0b1010010 // Battery // The battery sense is hooked to pin A0 (5) @@ -222,7 +221,7 @@ static const uint8_t SCK = PIN_SPI_SCK; #undef AREF_VOLTAGE #define AREF_VOLTAGE 3.0 #define VBAT_AR_INTERNAL AR_INTERNAL_3_0 -#define ADC_MULTIPLIER VBAT_DIVIDER_COMP //REAL_VBAT_MV_PER_LSB +#define ADC_MULTIPLIER VBAT_DIVIDER_COMP // REAL_VBAT_MV_PER_LSB #define VBAT_RAW_TO_SCALED(x) (REAL_VBAT_MV_PER_LSB * x) #define HAS_RTC 1 diff --git a/variants/station-g1/variant.h b/variants/station-g1/variant.h index 431082241..4572d47a6 100644 --- a/variants/station-g1/variant.h +++ b/variants/station-g1/variant.h @@ -3,8 +3,9 @@ #define I2C_SDA 21 #define I2C_SCL 22 -#define BUTTON_PIN 36 // The middle button GPIO on the Nano G1 -//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented anywhere. +#define BUTTON_PIN 36 // The middle button GPIO on the Nano G1 +//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented +// anywhere. #define EXT_NOTIFY_OUT 13 // Default pin to use for Ext Notify Module. // common pinout for their SX1262 vs RF95 modules - both can be enabled and we will probe at runtime for RF95 and if @@ -23,14 +24,16 @@ #define SX126X_DIO1 LORA_DIO1 #define SX126X_BUSY LORA_DIO2 #define SX126X_RESET LORA_RESET -//#define SX126X_E22 // Not really an E22 +//#define SX126X_E22 // Not really an E22 // Internally the module hooks the SX1262-DIO2 in to control the TX/RX switch (which is the default for the sx1262interface // code) -#define SX126X_MAX_POWER 16 //Ensure the PA does not exceed the saturation output power. More Info:https://uniteng.com/wiki/doku.php?id=meshtastic:station#rf_design_-_lora_station_edition_g1 +#define SX126X_MAX_POWER \ + 16 // Ensure the PA does not exceed the saturation output power. More + // Info:https://uniteng.com/wiki/doku.php?id=meshtastic:station#rf_design_-_lora_station_edition_g1 #endif -#define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage -#define BATTERY_SENSE_SAMPLES 30 //Set the number of samples, It has an effect of increasing sensitivity. +#define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage +#define BATTERY_SENSE_SAMPLES 30 // Set the number of samples, It has an effect of increasing sensitivity. #define ADC_MULTIPLIER 6.45 #define BAT_FULLVOLT 12600 #define BAT_EMPTYVOLT 8200 diff --git a/variants/t-echo/variant.h b/variants/t-echo/variant.h index bfcff0d3b..bd8dd838f 100644 --- a/variants/t-echo/variant.h +++ b/variants/t-echo/variant.h @@ -44,8 +44,8 @@ extern "C" { // LEDs #define PIN_LED1 (0 + 14) // 13 red (confirmed on 1.0 board) -#define PIN_LED2 (0 + 15) // 14 blue -#define PIN_LED3 (0 + 13) // 15 green +#define PIN_LED2 (0 + 15) // 14 blue +#define PIN_LED3 (0 + 13) // 15 green #define LED_RED PIN_LED3 #define LED_BLUE PIN_LED1 @@ -61,7 +61,7 @@ extern "C" { * Buttons */ #define PIN_BUTTON1 (32 + 10) -#define PIN_BUTTON2 (0 + 18) // 0.18 is labeled on the board as RESET but we configure it in the bootloader as a regular GPIO +#define PIN_BUTTON2 (0 + 18) // 0.18 is labeled on the board as RESET but we configure it in the bootloader as a regular GPIO #define PIN_BUTTON_TOUCH (0 + 11) // 0.11 is the soft touch button on T-Echo /* @@ -112,8 +112,8 @@ External serial flash WP25R1635FZUIL0 #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) +#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 @@ -154,7 +154,7 @@ External serial flash WP25R1635FZUIL0 #define PIN_EINK_MOSI (0 + 29) // also called SDI // Controls power for the eink display - Board power is enabled either by VBUS from USB or the CPU asserting PWR_ON -// FIXME - I think this is actually just the board power enable - it enables power to the CPU also +// FIXME - I think this is actually just the board power enable - it enables power to the CPU also #define PIN_EINK_PWR_ON (0 + 12) #define USE_EINK @@ -174,8 +174,8 @@ External serial flash WP25R1635FZUIL0 #define PIN_GPS_WAKE (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 PIN_GPS_TX (32 + 9) // This is for bits going TOWARDS the CPU -#define PIN_GPS_RX (32 + 8) // This is for bits going TOWARDS the GPS +#define PIN_GPS_TX (32 + 9) // This is for bits going TOWARDS the CPU +#define PIN_GPS_RX (32 + 8) // This is for bits going TOWARDS the GPS #define GPS_THREAD_INTERVAL 50 @@ -217,7 +217,7 @@ External serial flash WP25R1635FZUIL0 #undef AREF_VOLTAGE #define AREF_VOLTAGE 3.0 #define VBAT_AR_INTERNAL AR_INTERNAL_3_0 -#define ADC_MULTIPLIER VBAT_DIVIDER_COMP +#define ADC_MULTIPLIER VBAT_DIVIDER_COMP #define VBAT_RAW_TO_SCALED(x) (REAL_VBAT_MV_PER_LSB * x) #define HAS_RTC 1 diff --git a/variants/tbeam-s3-core/pins_arduino.h b/variants/tbeam-s3-core/pins_arduino.h index 5030d1d23..24edb7d9f 100644 --- a/variants/tbeam-s3-core/pins_arduino.h +++ b/variants/tbeam-s3-core/pins_arduino.h @@ -7,12 +7,12 @@ #define USB_PID 0x1001 #define EXTERNAL_NUM_INTERRUPTS 46 -#define NUM_DIGITAL_PINS 48 -#define NUM_ANALOG_INPUTS 20 +#define NUM_DIGITAL_PINS 48 +#define NUM_ANALOG_INPUTS 20 -#define analogInputToDigitalPin(p) (((p)<20)?(analogChannelToDigitalPin(p)):-1) -#define digitalPinToInterrupt(p) (((p)<48)?(p):-1) -#define digitalPinHasPWM(p) (p < 46) +#define analogInputToDigitalPin(p) (((p) < 20) ? (analogChannelToDigitalPin(p)) : -1) +#define digitalPinToInterrupt(p) (((p) < 48) ? (p) : -1) +#define digitalPinHasPWM(p) (p < 46) static const uint8_t TX = 43; static const uint8_t RX = 44; @@ -22,23 +22,21 @@ static const uint8_t SDA = 42; static const uint8_t SCL = 41; // Default SPI will be mapped to Radio -static const uint8_t SS = 10; -static const uint8_t MOSI = 11; -static const uint8_t MISO = 13; -static const uint8_t SCK = 12; +static const uint8_t SS = 10; +static const uint8_t MOSI = 11; +static const uint8_t MISO = 13; +static const uint8_t SCK = 12; // Another SPI bus shares SD card and QMI8653 inertial measurement sensor -#define SPI_MOSI (35) -#define SPI_SCK (36) -#define SPI_MISO (37) -#define SPI_CS (47) -#define IMU_CS (34) +#define SPI_MOSI (35) +#define SPI_SCK (36) +#define SPI_MISO (37) +#define SPI_CS (47) +#define IMU_CS (34) -#define SDCARD_CS SPI_CS -#define IMU_INT (33) +#define SDCARD_CS SPI_CS +#define IMU_INT (33) // #define PMU_IRQ (40) -#define RTC_INT (14) - - +#define RTC_INT (14) #endif /* Pins_Arduino_h */ diff --git a/variants/tbeam-s3-core/variant.h b/variants/tbeam-s3-core/variant.h index 001b50a30..69f639de8 100644 --- a/variants/tbeam-s3-core/variant.h +++ b/variants/tbeam-s3-core/variant.h @@ -1,36 +1,35 @@ // #define BUTTON_NEED_PULLUP // if set we need to turn on the internal CPU pullup during sleep -#define I2C_SDA1 42 //Used for PMU management and PCF8563 -#define I2C_SCL1 41 //Used for PMU management and PCF8563 +#define I2C_SDA1 42 // Used for PMU management and PCF8563 +#define I2C_SCL1 41 // Used for PMU management and PCF8563 -#define I2C_SDA 17 //For QMC6310 sensors and screens -#define I2C_SCL 18 //For QMC6310 sensors and screens +#define I2C_SDA 17 // For QMC6310 sensors and screens +#define I2C_SCL 18 // For QMC6310 sensors and screens -#define BUTTON_PIN 0 // The middle button GPIO on the T-Beam S3 -//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented anywhere. +#define BUTTON_PIN 0 // The middle button GPIO on the T-Beam S3 +//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented +// anywhere. // #define EXT_NOTIFY_OUT 13 // Default pin to use for Ext Notify Module. - - -#define LED_INVERTED 1 +#define LED_INVERTED 1 // TTGO uses a common pinout for their SX1262 vs RF95 modules - both can be enabled and we will probe at runtime for RF95 and if // not found then probe for SX1262 #define USE_SX1262 #define USE_SX1268 -#define LORA_DIO0 -1 // a No connect on the SX1262 module -#define LORA_RESET 5 -#define LORA_DIO1 1 // SX1262 IRQ -#define LORA_DIO2 4 // SX1262 BUSY -#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled +#define LORA_DIO0 -1 // a No connect on the SX1262 module +#define LORA_RESET 5 +#define LORA_DIO1 1 // SX1262 IRQ +#define LORA_DIO2 4 // SX1262 BUSY +#define LORA_DIO3 // Not connected on PCB, but internally on the TTGO SX1262, if DIO3 is high the TXCO is enabled #ifdef USE_SX1262 -#define SX126X_CS 10 // FIXME - we really should define LORA_CS instead -#define SX126X_DIO1 LORA_DIO1 -#define SX126X_BUSY LORA_DIO2 -#define SX126X_RESET LORA_RESET -#define SX126X_E22 // Not really an E22 but TTGO seems to be trying to clone that +#define SX126X_CS 10 // FIXME - we really should define LORA_CS instead +#define SX126X_DIO1 LORA_DIO1 +#define SX126X_BUSY LORA_DIO2 +#define SX126X_RESET LORA_RESET +#define SX126X_E22 // Not really an E22 but TTGO seems to be trying to clone that // Internally the TTGO module hooks the SX1262-DIO2 in to control the TX/RX switch (which is the default for the sx1262interface // code) #endif @@ -44,18 +43,17 @@ #define PMU_USE_WIRE1 #define RTC_USE_WIRE1 -#define RF95_SCK 12 -#define RF95_MISO 13 -#define RF95_MOSI 11 -#define RF95_NSS 10 +#define RF95_SCK 12 +#define RF95_MISO 13 +#define RF95_MOSI 11 +#define RF95_NSS 10 -#define GPS_RX_PIN 9 -#define GPS_TX_PIN 8 -#define GPS_WAKEUP_PIN 7 -#define GPS_1PPS_PIN 6 +#define GPS_RX_PIN 9 +#define GPS_TX_PIN 8 +#define GPS_WAKEUP_PIN 7 +#define GPS_1PPS_PIN 6 - -#define HAS_SDCARD //Have SPI interface SD card slot +#define HAS_SDCARD // Have SPI interface SD card slot #define SDCARD_USE_SPI1 // PCF8563 RTC Module @@ -63,7 +61,7 @@ #define HAS_RTC 1 -//has 32768 Hz crystal +// has 32768 Hz crystal #define HAS_32768HZ #define USE_SH1106 \ No newline at end of file diff --git a/variants/tbeam/variant.h b/variants/tbeam/variant.h index 268e9ef96..642e3721c 100644 --- a/variants/tbeam/variant.h +++ b/variants/tbeam/variant.h @@ -3,8 +3,9 @@ #define I2C_SDA 21 #define I2C_SCL 22 -#define BUTTON_PIN 38 // The middle button GPIO on the T-Beam -//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented anywhere. +#define BUTTON_PIN 38 // The middle button GPIO on the T-Beam +//#define BUTTON_PIN_ALT 13 // Alternate GPIO for an external button if needed. Does anyone use this? It is not documented +// anywhere. #define EXT_NOTIFY_OUT 13 // Default pin to use for Ext Notify Module. #define LED_INVERTED 1 diff --git a/variants/tbeam_v07/variant.h b/variants/tbeam_v07/variant.h index 17a6e8e87..ac7776c1a 100644 --- a/variants/tbeam_v07/variant.h +++ b/variants/tbeam_v07/variant.h @@ -4,7 +4,7 @@ #define I2C_SCL 22 #define BUTTON_PIN 39 -#define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage +#define BATTERY_PIN 35 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage #define EXT_NOTIFY_OUT 13 // Default pin to use for Ext Notify Module. #define USE_RF95 diff --git a/variants/tlora_t3s3_v1/pins_arduino.h b/variants/tlora_t3s3_v1/pins_arduino.h index 9b8eba7c1..627dad19d 100644 --- a/variants/tlora_t3s3_v1/pins_arduino.h +++ b/variants/tlora_t3s3_v1/pins_arduino.h @@ -7,28 +7,28 @@ #define USB_PID 0x1001 #define EXTERNAL_NUM_INTERRUPTS 46 -#define NUM_DIGITAL_PINS 48 -#define NUM_ANALOG_INPUTS 20 +#define NUM_DIGITAL_PINS 48 +#define NUM_ANALOG_INPUTS 20 -#define analogInputToDigitalPin(p) (((p)<20)?(analogChannelToDigitalPin(p)):-1) -#define digitalPinToInterrupt(p) (((p)<48)?(p):-1) -#define digitalPinHasPWM(p) (p < 46) +#define analogInputToDigitalPin(p) (((p) < 20) ? (analogChannelToDigitalPin(p)) : -1) +#define digitalPinToInterrupt(p) (((p) < 48) ? (p) : -1) +#define digitalPinHasPWM(p) (p < 46) // The default Wire will be mapped to PMU and RTC static const uint8_t SDA = 18; static const uint8_t SCL = 17; // Default SPI will be mapped to Radio -static const uint8_t SS = 7; -static const uint8_t MOSI = 6; -static const uint8_t MISO = 3; -static const uint8_t SCK = 5; +static const uint8_t SS = 7; +static const uint8_t MOSI = 6; +static const uint8_t MISO = 3; +static const uint8_t SCK = 5; -#define SPI_MOSI (11) -#define SPI_SCK (14) -#define SPI_MISO (2) -#define SPI_CS (13) +#define SPI_MOSI (11) +#define SPI_SCK (14) +#define SPI_MISO (2) +#define SPI_CS (13) -#define SDCARD_CS SPI_CS +#define SDCARD_CS SPI_CS #endif /* Pins_Arduino_h */ diff --git a/variants/tlora_t3s3_v1/variant.h b/variants/tlora_t3s3_v1/variant.h index 64874dac0..116911ae0 100644 --- a/variants/tlora_t3s3_v1/variant.h +++ b/variants/tlora_t3s3_v1/variant.h @@ -13,8 +13,8 @@ #define I2C_SDA 18 // I2C pins for this board #define I2C_SCL 17 -#define LED_PIN 37 // If defined we will blink this LED -#define BUTTON_PIN 0 // If defined, this will be used for user button presses, +#define LED_PIN 37 // If defined we will blink this LED +#define BUTTON_PIN 0 // If defined, this will be used for user button presses, #define BUTTON_NEED_PULLUP diff --git a/variants/tlora_v1/variant.h b/variants/tlora_v1/variant.h index 6ab8bad4c..c390a3438 100644 --- a/variants/tlora_v1/variant.h +++ b/variants/tlora_v1/variant.h @@ -7,8 +7,8 @@ #define RESET_OLED 16 // If defined, this pin will be used to reset the display controller #define VEXT_ENABLE 21 // active low, powers the oled display and the lora antenna boost -#define LED_PIN 2 // If defined we will blink this LED -#define BUTTON_PIN 0 // If defined, this will be used for user button presses +#define LED_PIN 2 // If defined we will blink this LED +#define BUTTON_PIN 0 // If defined, this will be used for user button presses #define BUTTON_NEED_PULLUP #define EXT_NOTIFY_OUT 13 // Default pin to use for Ext Notify Module. diff --git a/variants/tlora_v2_1_16/variant.h b/variants/tlora_v2_1_16/variant.h index 14175f48b..74b82d8c1 100644 --- a/variants/tlora_v2_1_16/variant.h +++ b/variants/tlora_v2_1_16/variant.h @@ -10,12 +10,11 @@ #define I2C_SDA 21 // I2C pins for this board #define I2C_SCL 22 -#define LED_PIN 25 // If defined we will blink this LED -#define BUTTON_PIN 12 // If defined, this will be used for user button presses, +#define LED_PIN 25 // If defined we will blink this LED +#define BUTTON_PIN 12 // If defined, this will be used for user button presses, #define BUTTON_NEED_PULLUP #define USE_RF95 #define LORA_DIO0 26 // a No connect on the SX1262 module #define LORA_RESET 23 - diff --git a/variants/tlora_v2_1_18/variant.h b/variants/tlora_v2_1_18/variant.h index 95d699767..0262f0122 100644 --- a/variants/tlora_v2_1_18/variant.h +++ b/variants/tlora_v2_1_18/variant.h @@ -8,8 +8,8 @@ #define I2C_SDA 21 // I2C pins for this board #define I2C_SCL 22 -#define LED_PIN 25 // If defined we will blink this LED -#define BUTTON_PIN 12 // If defined, this will be used for user button presses, +#define LED_PIN 25 // If defined we will blink this LED +#define BUTTON_PIN 12 // If defined, this will be used for user button presses, #define BUTTON_NEED_PULLUP diff --git a/variants/wio-e5/variant.h b/variants/wio-e5/variant.h index 3ef371e29..b1f7556b4 100644 --- a/variants/wio-e5/variant.h +++ b/variants/wio-e5/variant.h @@ -12,18 +12,18 @@ Do not expect a working Meshtastic device with this target. #ifndef _VARIANT_WIOE5_ #define _VARIANT_WIOE5_ -//Arduino/PlatformIO support for SUBGHZSPI is not currently available +// Arduino/PlatformIO support for SUBGHZSPI is not currently available //#define USE_SX1262 #ifdef USE_SX1262 - #define HAS_RADIO 1 +#define HAS_RADIO 1 - /* module only transmits through RFO_HP */ - #define SX126X_RXEN PA5 - #define SX126X_TXEN PA4 +/* module only transmits through RFO_HP */ +#define SX126X_RXEN PA5 +#define SX126X_TXEN PA4 - /* TCXO fed by internal LDO option behind PB0 pin */ - #define SX126X_E22 +/* TCXO fed by internal LDO option behind PB0 pin */ +#define SX126X_E22 #endif #endif \ No newline at end of file