diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..584097061 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +* text=auto eol=lf +*.{cmd,[cC][mM][dD]} text eol=crlf +*.{bat,[bB][aA][tT]} text eol=crlf +*.{sh,[sS][hH]} text eol=lf diff --git a/.github/ISSUE_TEMPLATE/New Board.yml b/.github/ISSUE_TEMPLATE/New Board.yml index ad706f3c0..c71ed4ba2 100644 --- a/.github/ISSUE_TEMPLATE/New Board.yml +++ b/.github/ISSUE_TEMPLATE/New Board.yml @@ -28,7 +28,7 @@ body: description: What LoRa IC does the board have? validations: required: true - + - type: input id: link attributes: diff --git a/.github/actions/setup-base/action.yml b/.github/actions/setup-base/action.yml index 1791f80ae..45930a94f 100644 --- a/.github/actions/setup-base/action.yml +++ b/.github/actions/setup-base/action.yml @@ -1,5 +1,5 @@ -name: 'Setup Build Base Composite Action' -description: 'Base build actions for Meshtastic Platform IO steps' +name: "Setup Build Base Composite Action" +description: "Base build actions for Meshtastic Platform IO steps" runs: using: "composite" @@ -10,7 +10,7 @@ runs: submodules: "recursive" ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} - + - name: Install cppcheck shell: bash run: | @@ -38,4 +38,4 @@ runs: - name: Upgrade platformio shell: bash run: | - pio upgrade \ No newline at end of file + pio upgrade diff --git a/.github/workflows/build_esp32.yml b/.github/workflows/build_esp32.yml index 74b71db50..7996a9b1b 100644 --- a/.github/workflows/build_esp32.yml +++ b/.github/workflows/build_esp32.yml @@ -7,7 +7,7 @@ on: required: true type: string -jobs: +jobs: build-esp32: runs-on: ubuntu-latest steps: @@ -31,7 +31,7 @@ jobs: - name: Remove debug flags for release if: ${{ github.event_name == 'workflow_dispatch' }} - run: | + run: | sed -i '/DDEBUG_HEAP/d' ./arch/esp32/esp32.ini sed -i '/DDEBUG_HEAP/d' ./arch/esp32/esp32s2.ini sed -i '/DDEBUG_HEAP/d' ./arch/esp32/esp32s3.ini @@ -46,7 +46,7 @@ jobs: file: "firmware.bin" target: "release/bleota.bin" token: ${{ secrets.GITHUB_TOKEN }} - + - name: Get release version string shell: bash run: echo "version=$(./bin/buildinfo.py long)" >> $GITHUB_OUTPUT diff --git a/.github/workflows/build_nrf52.yml b/.github/workflows/build_nrf52.yml index cdf43c22e..33ee4d00c 100644 --- a/.github/workflows/build_nrf52.yml +++ b/.github/workflows/build_nrf52.yml @@ -7,7 +7,7 @@ on: required: true type: string -jobs: +jobs: build-nrf52: runs-on: ubuntu-latest steps: @@ -30,4 +30,4 @@ jobs: path: | release/*.uf2 release/*.elf - release/*.zip \ No newline at end of file + release/*.zip diff --git a/.github/workflows/build_rpi2040.yml b/.github/workflows/build_rpi2040.yml index fb7e3db5b..76ca2c20e 100644 --- a/.github/workflows/build_rpi2040.yml +++ b/.github/workflows/build_rpi2040.yml @@ -7,7 +7,7 @@ on: required: true type: string -jobs: +jobs: build-rpi2040: runs-on: ubuntu-latest steps: @@ -29,4 +29,4 @@ jobs: name: firmware-${{ inputs.board }}-${{ steps.version.outputs.version }}.zip path: | release/*.uf2 - release/*.elf \ No newline at end of file + release/*.elf diff --git a/.github/workflows/main_matrix.yml b/.github/workflows/main_matrix.yml index dbbd0e52e..fb01f3208 100644 --- a/.github/workflows/main_matrix.yml +++ b/.github/workflows/main_matrix.yml @@ -137,19 +137,26 @@ jobs: release/device-*.bat - name: Docker login - if: ${{ github.event_name == 'workflow_dispatch' }} uses: docker/login-action@v2 with: username: meshtastic password: ${{ secrets.DOCKER_TOKEN }} - name: Docker setup - if: ${{ github.event_name == 'workflow_dispatch' }} uses: docker/setup-buildx-action@v2 - - name: Docker build and push + - name: Docker build and push tagged versions if: ${{ github.event_name == 'workflow_dispatch' }} uses: docker/build-push-action@v3 + with: + context: . + file: ./Dockerfile + push: true + tags: meshtastic/device-simulator:${{ steps.version.outputs.version }} + + - name: Docker build and push + if: github.ref == 'refs/heads/master' + uses: docker/build-push-action@v3 with: context: . file: ./Dockerfile diff --git a/.github/workflows/sec_sast_flawfinder.yml b/.github/workflows/sec_sast_flawfinder.yml index e2ba44090..2c7e751af 100644 --- a/.github/workflows/sec_sast_flawfinder.yml +++ b/.github/workflows/sec_sast_flawfinder.yml @@ -10,31 +10,31 @@ on: jobs: flawfinder: - runs-on: ubuntu-latest - name: Flawfinder + runs-on: ubuntu-latest + name: Flawfinder - steps: - # step 1 - - name: clone application source code - uses: actions/checkout@v3 + steps: + # step 1 + - name: clone application source code + uses: actions/checkout@v3 - # step 2 - - name: flawfinder_scan - uses: david-a-wheeler/flawfinder@2.0.19 - with: - arguments: '--sarif ./' - output: 'flawfinder_report.sarif' + # step 2 + - name: flawfinder_scan + uses: david-a-wheeler/flawfinder@2.0.19 + with: + arguments: "--sarif ./" + output: "flawfinder_report.sarif" - # step 3 - - name: save report as pipeline artifact - uses: actions/upload-artifact@v3 - with: - name: flawfinder_report.sarif - path: flawfinder_report.sarif + # step 3 + - name: save report as pipeline artifact + uses: actions/upload-artifact@v3 + with: + name: flawfinder_report.sarif + path: flawfinder_report.sarif - # step 4 - - name: publish code scanning alerts - uses: github/codeql-action/upload-sarif@v2 - with: - sarif_file: flawfinder_report.sarif - category: flawfinder + # step 4 + - name: publish code scanning alerts + uses: github/codeql-action/upload-sarif@v2 + with: + sarif_file: flawfinder_report.sarif + category: flawfinder diff --git a/.github/workflows/sec_sast_semgrep_cron.yml b/.github/workflows/sec_sast_semgrep_cron.yml index 426250280..cdd2c3c37 100644 --- a/.github/workflows/sec_sast_semgrep_cron.yml +++ b/.github/workflows/sec_sast_semgrep_cron.yml @@ -6,39 +6,37 @@ on: branches: - master schedule: - - cron: '0 1 * * 6' + - cron: "0 1 * * 6" jobs: - semgrep-full: - runs-on: ubuntu-latest - container: - image: returntocorp/semgrep + runs-on: ubuntu-latest + container: + image: returntocorp/semgrep - steps: + steps: + # step 1 + - name: clone application source code + uses: actions/checkout@v3 - # step 1 - - name: clone application source code - uses: actions/checkout@v3 + # step 2 + - name: full scan + run: | + semgrep \ + --sarif --output report.sarif \ + --metrics=off \ + --config="p/default" - # step 2 - - name: full scan - run: | - semgrep \ - --sarif --output report.sarif \ - --metrics=off \ - --config="p/default" + # step 3 + - name: save report as pipeline artifact + uses: actions/upload-artifact@v3 + with: + name: report.sarif + path: report.sarif - # step 3 - - name: save report as pipeline artifact - uses: actions/upload-artifact@v3 - with: - name: report.sarif - path: report.sarif - - # step 4 - - name: publish code scanning alerts - uses: github/codeql-action/upload-sarif@v2 - with: - sarif_file: report.sarif - category: semgrep + # step 4 + - name: publish code scanning alerts + uses: github/codeql-action/upload-sarif@v2 + with: + sarif_file: report.sarif + category: semgrep diff --git a/.github/workflows/sec_sast_semgrep_pull.yml b/.github/workflows/sec_sast_semgrep_pull.yml index 8fe3632b4..1697ffb1b 100644 --- a/.github/workflows/sec_sast_semgrep_pull.yml +++ b/.github/workflows/sec_sast_semgrep_pull.yml @@ -1,17 +1,14 @@ --- name: Semgrep Differential Scan -on: - pull_request +on: pull_request jobs: - semgrep-diff: runs-on: ubuntu-latest container: image: returntocorp/semgrep steps: - # step 1 - name: clone application source code uses: actions/checkout@v3 diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 3ba9cca33..70acfd11b 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -8,16 +8,17 @@ plugins: uri: https://github.com/trunk-io/plugins lint: enabled: + - git-diff-check + - gitleaks@8.15.2 + - clang-format@14.0.0 + - prettier@2.8.3 + disabled: - shellcheck@0.9.0 - shfmt@3.5.0 - oxipng@8.0.0 - actionlint@1.6.22 - - git-diff-check - - gitleaks@8.15.2 - markdownlint@0.33.0 - hadolint@2.12.0 - - clang-format@14.0.0 - - prettier@2.8.3 - svgo@3.0.2 runtimes: enabled: diff --git a/.vscode/tasks.json b/.vscode/tasks.json index b2340005e..cdb8f5114 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,17 +1,15 @@ { - "version": "2.0.0", - "tasks": [ - { - "type": "PlatformIO", - "task": "Build", - "problemMatcher": [ - "$platformio" - ], - "group": { - "kind": "build", - "isDefault": true - }, - "label": "PlatformIO: Build" - } - ] -} \ No newline at end of file + "version": "2.0.0", + "tasks": [ + { + "type": "PlatformIO", + "task": "Build", + "problemMatcher": ["$platformio"], + "group": { + "kind": "build", + "isDefault": true + }, + "label": "PlatformIO: Build" + } + ] +} diff --git a/bin/readprops.py b/bin/readprops.py index c23092e41..ffa361541 100644 --- a/bin/readprops.py +++ b/bin/readprops.py @@ -22,9 +22,9 @@ def readProps(prefsLoc): isDirty = subprocess.check_output( ['git', 'diff', 'HEAD']).decode("utf-8").strip() suffix = sha - if isDirty: - # short for 'dirty', we want to keep our verstrings source for protobuf reasons - suffix = sha + "-d" + # if isDirty: + # # short for 'dirty', we want to keep our verstrings source for protobuf reasons + # suffix = sha + "-d" verObj['long'] = "{}.{}.{}.{}".format( version["major"], version["minor"], version["build"], suffix) except: diff --git a/bin/regen-protos.bat b/bin/regen-protos.bat index 29f35d0ae..aa2a2684f 100644 --- a/bin/regen-protos.bat +++ b/bin/regen-protos.bat @@ -1 +1,5 @@ -cd protobufs && ..\nanopb-0.4.7\generator-bin\protoc.exe --nanopb_out=-v:..\src\mesh\generated\meshtastic -I=..\protobufs meshtastic\*.proto +cd protobufs && ..\nanopb-0.4.7\generator-bin\protoc.exe --nanopb_out=-v:..\src\mesh\generated -I=..\protobufs ..\protobufs\meshtastic\*.proto + +@REM cd ../src/mesh/generated/meshtastic +@REM sed -i 's/#include "meshtastic/#include "./g' * +@REM sed -i 's/meshtastic_//g' * diff --git a/bin/regen-protos.sh b/bin/regen-protos.sh index abfe7a141..5fa3ab049 100755 --- a/bin/regen-protos.sh +++ b/bin/regen-protos.sh @@ -10,10 +10,10 @@ echo "prebuilt binaries for your computer into nanopb-0.4.7" cd protobufs ../nanopb-0.4.7/generator-bin/protoc --nanopb_out=-v:../src/mesh/generated/ -I=../protobufs meshtastic/*.proto -cd ../src/mesh/generated/meshtastic -sed -i 's/#include "meshtastic/#include "./g' * +# cd ../src/mesh/generated/meshtastic +# sed -i 's/#include "meshtastic/#include "./g' -- * -sed -i 's/meshtastic_//g' * +# sed -i 's/meshtastic_//g' -- * #echo "Regenerating protobuf documentation - if you see an error message" #echo "you can ignore it unless doing a new protobuf release to github." 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/platformio.ini b/platformio.ini index e58656dd2..1d8083f70 100644 --- a/platformio.ini +++ b/platformio.ini @@ -39,7 +39,7 @@ extra_scripts = bin/platformio-custom.py ; The Radiolib stuff will speed up building considerably. Exclud all the stuff we dont need. build_flags = -Wno-missing-field-initializers -Wno-format - -Isrc -Isrc/mesh -Isrc/gps -Isrc/buzz -Wl,-Map,.pio/build/output.map + -Isrc -Isrc/mesh -Isrc/mesh/generated -Isrc/gps -Isrc/buzz -Wl,-Map,.pio/build/output.map -DUSE_THREAD_NAMES -DTINYGPS_OPTION_NO_CUSTOM_FIELDS -DPB_ENABLE_MALLOC=1 @@ -58,7 +58,7 @@ build_flags = -Wno-missing-field-initializers monitor_speed = 115200 lib_deps = - https://github.com/meshtastic/esp8266-oled-ssd1306.git#53580644255b48ebb7a737343c6b4e71c7e11cf2 ; ESP8266_SSD1306 + https://github.com/meshtastic/esp8266-oled-ssd1306.git#da1ede4dfcd91074283b029080759fd744120909 ; ESP8266_SSD1306 mathertel/OneButton@^2.0.3 ; OneButton library for non-blocking button debounce https://github.com/meshtastic/arduino-fsm.git#7db3702bf0cfe97b783d6c72595e3f38e0b19159 https://github.com/meshtastic/TinyGPSPlus.git#127ad674ef85f0201cb68a065879653ed94792c4 @@ -66,7 +66,7 @@ lib_deps = nanopb/Nanopb@^0.4.6 erriez/ErriezCRC32@^1.0.1 ; jgromes/RadioLib@^5.5.1 - https://github.com/jgromes/RadioLib.git#395844922c5d88d5db0481a9c91479931172428d + https://github.com/jgromes/RadioLib.git#1afa947030c5637f71f6563bc22aa75032e53a57 ; Used for the code analysis in PIO Home / Inspect check_tool = cppcheck diff --git a/protobufs b/protobufs index aaa6e08b2..2b391ff8a 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit aaa6e08b2e00127d4396f3a994cede4a749cff9c +Subproject commit 2b391ff8a76bfc07662faa007bb4fd6e01691ba8 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/ButtonThread.h b/src/ButtonThread.h index d94b6a769..5bb856027 100644 --- a/src/ButtonThread.h +++ b/src/ButtonThread.h @@ -115,8 +115,7 @@ class ButtonThread : public concurrency::OSThread { // LOG_DEBUG("press!\n"); #ifdef BUTTON_PIN - if ((BUTTON_PIN != moduleConfig.canned_message.inputbroker_pin_press) || - !moduleConfig.canned_message.enabled) { + if ((BUTTON_PIN != moduleConfig.canned_message.inputbroker_pin_press) || !moduleConfig.canned_message.enabled) { powerFSM.trigger(EVENT_PRESS); } #endif @@ -144,10 +143,10 @@ class ButtonThread : public concurrency::OSThread #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 shutdown_on_long_stop = true; @@ -160,28 +159,25 @@ class ButtonThread : public concurrency::OSThread static void userButtonDoublePressed() { - #if defined(USE_EINK) && defined(PIN_EINK_EN) +#if defined(USE_EINK) && defined(PIN_EINK_EN) digitalWrite(PIN_EINK_EN, digitalRead(PIN_EINK_EN) == LOW); - #endif - #if defined(GPS_POWER_TOGGLE) - if(config.position.gps_enabled) - { - LOG_DEBUG("Flag set to false for gps power\n"); - } - else - { - LOG_DEBUG("Flag set to true to restore power\n"); - } - config.position.gps_enabled = !(config.position.gps_enabled); - doGPSpowersave(config.position.gps_enabled); - #endif +#endif + screen->print("Sent ad-hoc ping\n"); + service.refreshMyNodeInfo(); + service.sendNetworkPing(NODENUM_BROADCAST, true); } static void userButtonMultiPressed() { - screen->print("Sent ad-hoc ping\n"); - service.refreshMyNodeInfo(); - service.sendNetworkPing(NODENUM_BROADCAST, true); +#if defined(GPS_POWER_TOGGLE) + if (config.position.gps_enabled) { + LOG_DEBUG("Flag set to false for gps power\n"); + } else { + LOG_DEBUG("Flag set to true to restore power\n"); + } + config.position.gps_enabled = !(config.position.gps_enabled); + doGPSpowersave(config.position.gps_enabled); +#endif } static void userButtonPressedLongStart() 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..bdfce36ff 100644 --- a/src/GPSStatus.h +++ b/src/GPSStatus.h @@ -20,15 +20,15 @@ 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; + meshtastic_Position p = meshtastic_Position_init_default; public: GPSStatus() { statusType = STATUS_TYPE_GPS; } // preferred method - GPSStatus(bool hasLock, bool isConnected, bool isPowerSaving, const Position &pos) : Status() + GPSStatus(bool hasLock, bool isConnected, bool isPowerSaving, const meshtastic_Position &pos) : Status() { this->hasLock = hasLock; this->isConnected = isConnected; @@ -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 { @@ -55,7 +55,7 @@ class GPSStatus : public Status #ifdef GPS_EXTRAVERBOSE LOG_WARN("Using fixed latitude\n"); #endif - NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); + meshtastic_NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); return node->position.latitude_i; } else { return p.latitude_i; @@ -68,7 +68,7 @@ class GPSStatus : public Status #ifdef GPS_EXTRAVERBOSE LOG_WARN("Using fixed longitude\n"); #endif - NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); + meshtastic_NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); return node->position.longitude_i; } else { return p.longitude_i; @@ -81,29 +81,38 @@ class GPSStatus : public Status #ifdef GPS_EXTRAVERBOSE LOG_WARN("Using fixed altitude\n"); #endif - NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); + meshtastic_NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); return node->position.altitude; } else { return p.altitude; } } - 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..c36c65efc 100644 --- a/src/PowerFSM.cpp +++ b/src/PowerFSM.cpp @@ -11,12 +11,12 @@ /// 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); + bool isRouter = (config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER ? 1 : 0); // If we are not a router and we already have AC power go to POWER state after init, otherwise go to ON // We assume routers might be powered all the time, but from a low current (solar) source @@ -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; @@ -237,7 +238,7 @@ Fsm powerFSM(&stateBOOT); void PowerFSM_setup() { - bool isRouter = (config.device.role == Config_DeviceConfig_Role_ROUTER ? 1 : 0); + bool isRouter = (config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER ? 1 : 0); bool hasPower = isPowered(); LOG_INFO("PowerFSM init, USB power=%d\n", hasPower ? 1 : 0); @@ -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 0c3fe81fc..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 >%d 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/detect/i2cScan.h b/src/detect/i2cScan.h index 0189677bd..87ca55957 100644 --- a/src/detect/i2cScan.h +++ b/src/detect/i2cScan.h @@ -168,13 +168,13 @@ void scanI2Cdevice() registerValue = getRegisterValue(addr, 0xD0, 1); // GET_ID if (registerValue == 0x61) { LOG_INFO("BME-680 sensor found at address 0x%x\n", (uint8_t)addr); - nodeTelemetrySensorsMap[TelemetrySensorType_BME680] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_BME680] = addr; } else if (registerValue == 0x60) { LOG_INFO("BME-280 sensor found at address 0x%x\n", (uint8_t)addr); - nodeTelemetrySensorsMap[TelemetrySensorType_BME280] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_BME280] = addr; } else { LOG_INFO("BMP-280 sensor found at address 0x%x\n", (uint8_t)addr); - nodeTelemetrySensorsMap[TelemetrySensorType_BMP280] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_BMP280] = addr; } } if (addr == INA_ADDR || addr == INA_ADDR_ALTERNATE) { @@ -182,41 +182,41 @@ void scanI2Cdevice() LOG_DEBUG("Register MFG_UID: 0x%x\n", registerValue); if (registerValue == 0x5449) { LOG_INFO("INA260 sensor found at address 0x%x\n", (uint8_t)addr); - nodeTelemetrySensorsMap[TelemetrySensorType_INA260] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_INA260] = addr; } else { // Assume INA219 if INA260 ID is not found LOG_INFO("INA219 sensor found at address 0x%x\n", (uint8_t)addr); - nodeTelemetrySensorsMap[TelemetrySensorType_INA219] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_INA219] = addr; } } if (addr == MCP9808_ADDR) { - nodeTelemetrySensorsMap[TelemetrySensorType_MCP9808] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_MCP9808] = addr; LOG_INFO("MCP9808 sensor found\n"); } if (addr == SHT31_ADDR) { LOG_INFO("SHT31 sensor found\n"); - nodeTelemetrySensorsMap[TelemetrySensorType_SHT31] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_SHT31] = addr; } if (addr == SHTC3_ADDR) { LOG_INFO("SHTC3 sensor found\n"); - nodeTelemetrySensorsMap[TelemetrySensorType_SHTC3] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_SHTC3] = addr; } if (addr == LPS22HB_ADDR || addr == LPS22HB_ADDR_ALT) { LOG_INFO("LPS22HB sensor found\n"); - nodeTelemetrySensorsMap[TelemetrySensorType_LPS22] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_LPS22] = addr; } // High rate sensors, will be processed internally if (addr == QMC6310_ADDR) { LOG_INFO("QMC6310 Highrate 3-Axis magnetic sensor found\n"); - nodeTelemetrySensorsMap[TelemetrySensorType_QMC6310] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_QMC6310] = addr; } if (addr == QMI8658_ADDR) { LOG_INFO("QMI8658 Highrate 6-Axis inertial measurement sensor found\n"); - nodeTelemetrySensorsMap[TelemetrySensorType_QMI8658] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_QMI8658] = addr; } if (addr == QMC5883L_ADDR) { LOG_INFO("QMC5883L Highrate 3-Axis magnetic sensor found\n"); - nodeTelemetrySensorsMap[TelemetrySensorType_QMC5883L] = addr; + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_QMC5883L] = addr; } } else if (err == 4) { LOG_ERROR("Unknow error at address 0x%x\n", addr); diff --git a/src/error.h b/src/error.h index 087215b1d..fc0707cd6 100644 --- a/src/error.h +++ b/src/error.h @@ -8,5 +8,5 @@ #define RECORD_CRITICALERROR(code) recordCriticalError(code, __LINE__, __FILE__) /// Record an error that should be reported via analytics -void recordCriticalError(CriticalErrorCode code = CriticalErrorCode_UNSPECIFIED, uint32_t address = 0, +void recordCriticalError(meshtastic_CriticalErrorCode code = meshtastic_CriticalErrorCode_UNSPECIFIED, uint32_t address = 0, const char *filename = NULL); diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 1814261a4..1b7c8511f 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"); @@ -190,11 +190,10 @@ if (!config.position.tx_gpio) // Switch to Vehicle Mode, since SoftRF enables Aviation < 2g _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 +203,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 +218,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 +227,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 +236,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 +245,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 +254,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 +275,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 +294,8 @@ if(config.position.gps_enabled){ notifyDeepSleepObserver.observe(¬ifyDeepSleep); notifyGPSSleepObserver.observe(¬ifyGPSSleep); } - if (config.position.gps_enabled==false) { + + if (config.position.gps_enabled == false && config.position.fixed_position == false) { setAwake(false); doGPSpowersave(false); } @@ -396,12 +402,13 @@ uint32_t GPS::getSleepTime() const uint32_t t = config.position.gps_update_interval; bool gps_enabled = config.position.gps_enabled; - if (!gps_enabled) + // We'll not need the GPS thread to wake up again after first acq. with fixed position. + if (!gps_enabled || config.position.fixed_position) t = UINT32_MAX; // Sleep forever now if (t == UINT32_MAX) return t; // already maxint - + return t * 1000; } @@ -421,16 +428,21 @@ void GPS::publishUpdate() int32_t GPS::runOnce() { + // Repeaters have no need for GPS + if (config.device.role == meshtastic_Config_DeviceConfig_Role_REPEATER) + disable(); + if (whileIdle()) { // 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(); + disable(); // Stop the GPS thread as it can do nothing useful until next reboot. } } } @@ -480,7 +492,7 @@ int32_t GPS::runOnce() if (hasValidLocation) { LOG_DEBUG("hasValidLocation FALLING EDGE (last read: %d)\n", gotLoc); } - p = Position_init_default; + p = meshtastic_Position_init_default; hasValidLocation = false; } @@ -492,6 +504,14 @@ int32_t GPS::runOnce() // If state has changed do a publish publishUpdate(); + if (!(fixeddelayCtr >= 20) && config.position.fixed_position && hasValidLocation) { + fixeddelayCtr++; + // LOG_DEBUG("Our delay counter is %d\n", fixeddelayCtr); + if (fixeddelayCtr >= 20) { + doGPSpowersave(false); + forceWake(false); + } + } // 9600bps is approx 1 byte per msec, so considering our buffer size we never need to wake more often than 200ms // if not awake we can run super infrquently (once every 5 secs?) to see if we need to wake. return isAwake ? GPS_THREAD_INTERVAL : 5000; @@ -544,10 +564,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 +581,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 +593,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 +600,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 +630,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 +681,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..a5f5f2ff4 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); @@ -55,7 +54,7 @@ class GPS : private concurrency::OSThread /** If !NULL we will use this serial port to construct our GPS */ static HardwareSerial *_serial_gps; - Position p = Position_init_default; + meshtastic_Position p = meshtastic_Position_init_default; GPS() : concurrency::OSThread("GPS") {} @@ -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,17 +163,20 @@ 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); + // delay counter to allow more sats before fixed position stops GPS thread + uint8_t fixeddelayCtr = 0; + protected: 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..0632164e9 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,19 +147,19 @@ 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; } - p.location_source = Position_LocSource_LOC_INTERNAL; + p.location_source = meshtastic_Position_LocSource_LOC_INTERNAL; // Dilution of precision (an accuracy metric) is reported in 10^2 units, so we need to scale down when we use it #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS @@ -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..6ab2c85bf 100644 --- a/src/gps/NMEAWPL.cpp +++ b/src/gps/NMEAWPL.cpp @@ -16,17 +16,13 @@ * ------------------------------------------- */ -uint32_t printWPL(char *buf, size_t bufsz, const Position &pos, const char *name) +uint32_t printWPL(char *buf, size_t bufsz, const meshtastic_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) +uint32_t printGGA(char *buf, size_t bufsz, const meshtastic_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..a9f00cb14 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); +uint32_t printWPL(char *buf, size_t bufsz, const meshtastic_Position &pos, const char *name); +uint32_t printGGA(char *buf, size_t bufsz, const meshtastic_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/EInkDisplay2.cpp b/src/graphics/EInkDisplay2.cpp index 07fcd2c46..f9d99ab7e 100644 --- a/src/graphics/EInkDisplay2.cpp +++ b/src/graphics/EInkDisplay2.cpp @@ -1,11 +1,11 @@ #include "configuration.h" #ifdef USE_EINK -#include "main.h" #include "EInkDisplay2.h" -#include "SPILock.h" -#include #include "GxEPD2_BW.h" +#include "SPILock.h" +#include "main.h" +#include #define COLORED GxEPD_BLACK #define UNCOLORED GxEPD_WHITE @@ -14,62 +14,63 @@ #define TECHO_DISPLAY_MODEL GxEPD2_154_D67 #elif defined(RAK4630) -//GxEPD2_213_BN - RAK14000 2.13 inch b/w 250x122 - changed from GxEPD2_213_B74 - which was not going to give partial update support +// GxEPD2_213_BN - RAK14000 2.13 inch b/w 250x122 - changed from GxEPD2_213_B74 - which was not going to give partial update +// support #define TECHO_DISPLAY_MODEL GxEPD2_213_BN -//4.2 inch 300x400 - GxEPD2_420_M01 +// 4.2 inch 300x400 - GxEPD2_420_M01 //#define TECHO_DISPLAY_MODEL GxEPD2_420_M01 -//2.9 inch 296x128 - GxEPD2_290_T5D +// 2.9 inch 296x128 - GxEPD2_290_T5D //#define TECHO_DISPLAY_MODEL GxEPD2_290_T5D -//1.54 inch 200x200 - GxEPD2_154_M09 +// 1.54 inch 200x200 - GxEPD2_154_M09 //#define TECHO_DISPLAY_MODEL GxEPD2_154_M09 #elif defined(PCA10059) -//4.2 inch 300x400 - GxEPD2_420_M01 +// 4.2 inch 300x400 - GxEPD2_420_M01 #define TECHO_DISPLAY_MODEL GxEPD2_420_M01 #elif defined(M5_COREINK) -//M5Stack CoreInk -//1.54 inch 200x200 - GxEPD2_154_M09 +// M5Stack CoreInk +// 1.54 inch 200x200 - GxEPD2_154_M09 #define TECHO_DISPLAY_MODEL GxEPD2_154_M09 #endif GxEPD2_BW *adafruitDisplay; -EInkDisplay::EInkDisplay(uint8_t address, int sda, int scl) +EInkDisplay::EInkDisplay(uint8_t address, int sda, int scl, uint8_t screen_model) { - #if defined(TTGO_T_ECHO) +#if defined(TTGO_T_ECHO) setGeometry(GEOMETRY_RAWMODE, TECHO_DISPLAY_MODEL::WIDTH, TECHO_DISPLAY_MODEL::HEIGHT); - #elif defined(RAK4630) - - //GxEPD2_213_BN - RAK14000 2.13 inch b/w 250x122 +#elif defined(RAK4630) + + // GxEPD2_213_BN - RAK14000 2.13 inch b/w 250x122 setGeometry(GEOMETRY_RAWMODE, 250, 122); - //GxEPD2_420_M01 - //setGeometry(GEOMETRY_RAWMODE, 300, 400); + // GxEPD2_420_M01 + // setGeometry(GEOMETRY_RAWMODE, 300, 400); - //GxEPD2_290_T5D - //setGeometry(GEOMETRY_RAWMODE, 296, 128); + // GxEPD2_290_T5D + // setGeometry(GEOMETRY_RAWMODE, 296, 128); - //GxEPD2_154_M09 - //setGeometry(GEOMETRY_RAWMODE, 200, 200); - - #elif defined(PCA10059) + // GxEPD2_154_M09 + // setGeometry(GEOMETRY_RAWMODE, 200, 200); - //GxEPD2_420_M01 +#elif defined(PCA10059) + + // GxEPD2_420_M01 setGeometry(GEOMETRY_RAWMODE, 300, 400); - - #elif defined(M5_COREINK) - - //M5Stack_CoreInk 200x200 - //1.54 inch 200x200 - GxEPD2_154_M09 + +#elif defined(M5_COREINK) + + // M5Stack_CoreInk 200x200 + // 1.54 inch 200x200 - GxEPD2_154_M09 setGeometry(GEOMETRY_RAWMODE, EPD_HEIGHT, EPD_WIDTH); - #endif +#endif // setGeometry(GEOMETRY_RAWMODE, 128, 64); // old resolution // setGeometry(GEOMETRY_128_64); // We originally used this because I wasn't sure if rawmode worked - it does } @@ -104,28 +105,28 @@ bool EInkDisplay::forceDisplay(uint32_t msecLimit) } LOG_DEBUG("Updating E-Paper... "); - - #if defined(TTGO_T_ECHO) + +#if defined(TTGO_T_ECHO) // ePaper.Reset(); // wake the screen from sleep adafruitDisplay->display(false); // FIXME, use partial update mode - #elif defined(RAK4630) - - //RAK14000 2.13 inch b/w 250x122 actually now does support partial updates - - //Full update mode (slow) - //adafruitDisplay->display(false); // FIXME, use partial update mode - - //Only enable for e-Paper with support for partial updates and comment out above adafruitDisplay->display(false); - // 1.54 inch 200x200 - GxEPD2_154_M09 - // 2.13 inch 250x122 - GxEPD2_213_BN - // 2.9 inch 296x128 - GxEPD2_290_T5D - // 4.2 inch 300x400 - GxEPD2_420_M01 +#elif defined(RAK4630) + + // RAK14000 2.13 inch b/w 250x122 actually now does support partial updates + + // Full update mode (slow) + // adafruitDisplay->display(false); // FIXME, use partial update mode + + // Only enable for e-Paper with support for partial updates and comment out above adafruitDisplay->display(false); + // 1.54 inch 200x200 - GxEPD2_154_M09 + // 2.13 inch 250x122 - GxEPD2_213_BN + // 2.9 inch 296x128 - GxEPD2_290_T5D + // 4.2 inch 300x400 - GxEPD2_420_M01 adafruitDisplay->nextPage(); - - #elif defined(PCA10059) || defined(M5_COREINK) + +#elif defined(PCA10059) || defined(M5_COREINK) adafruitDisplay->nextPage(); - #endif - +#endif + // Put screen to sleep to save power (possibly not necessary because we already did poweroff inside of display) adafruitDisplay->hibernate(); LOG_DEBUG("done\n"); @@ -175,41 +176,40 @@ bool EInkDisplay::connect() pinMode(PIN_EINK_EN, OUTPUT); #endif - #if defined(TTGO_T_ECHO) -{ - auto lowLevel = new TECHO_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY, SPI1); - - adafruitDisplay = new GxEPD2_BW(*lowLevel); - adafruitDisplay->init(); - adafruitDisplay->setRotation(3); -} -#elif defined(RAK4630) -{ - if (eink_found) { - auto lowLevel = new TECHO_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY); + { + auto lowLevel = new TECHO_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY, SPI1); adafruitDisplay = new GxEPD2_BW(*lowLevel); - - adafruitDisplay->init(115200, true, 10, false, SPI1, SPISettings(4000000, MSBFIRST, SPI_MODE0)); - - //RAK14000 2.13 inch b/w 250x122 does actually now support partial updates + adafruitDisplay->init(); adafruitDisplay->setRotation(3); - //Partial update support for 1.54, 2.13 RAK14000 b/w , 2.9 and 4.2 - //adafruitDisplay->setRotation(1); - adafruitDisplay->setPartialWindow(0, 0, displayWidth, displayHeight); - } else { - (void)adafruitDisplay; - } -} + } +#elif defined(RAK4630) + { + if (eink_found) { + auto lowLevel = new TECHO_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY); + + adafruitDisplay = new GxEPD2_BW(*lowLevel); + + adafruitDisplay->init(115200, true, 10, false, SPI1, SPISettings(4000000, MSBFIRST, SPI_MODE0)); + + // RAK14000 2.13 inch b/w 250x122 does actually now support partial updates + adafruitDisplay->setRotation(3); + // Partial update support for 1.54, 2.13 RAK14000 b/w , 2.9 and 4.2 + // adafruitDisplay->setRotation(1); + adafruitDisplay->setPartialWindow(0, 0, displayWidth, displayHeight); + } else { + (void)adafruitDisplay; + } + } #elif defined(PCA10059) -{ - auto lowLevel = new TECHO_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY); - adafruitDisplay = new GxEPD2_BW(*lowLevel); - adafruitDisplay->init(115200, true, 10, false, SPI1, SPISettings(4000000, MSBFIRST, SPI_MODE0)); - adafruitDisplay->setRotation(3); - adafruitDisplay->setPartialWindow(0, 0, displayWidth, displayHeight); -} + { + auto lowLevel = new TECHO_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY); + adafruitDisplay = new GxEPD2_BW(*lowLevel); + adafruitDisplay->init(115200, true, 10, false, SPI1, SPISettings(4000000, MSBFIRST, SPI_MODE0)); + adafruitDisplay->setRotation(3); + adafruitDisplay->setPartialWindow(0, 0, displayWidth, displayHeight); + } #elif defined(M5_COREINK) auto lowLevel = new TECHO_DISPLAY_MODEL(PIN_EINK_CS, PIN_EINK_DC, PIN_EINK_RES, PIN_EINK_BUSY); adafruitDisplay = new GxEPD2_BW(*lowLevel); @@ -217,12 +217,11 @@ bool EInkDisplay::connect() adafruitDisplay->setRotation(0); adafruitDisplay->setPartialWindow(0, 0, EPD_WIDTH, EPD_HEIGHT); #endif - - - //adafruitDisplay->setFullWindow(); - //adafruitDisplay->fillScreen(UNCOLORED); - //adafruitDisplay->drawCircle(100, 100, 20, COLORED); - //adafruitDisplay->display(false); + + // adafruitDisplay->setFullWindow(); + // adafruitDisplay->fillScreen(UNCOLORED); + // adafruitDisplay->drawCircle(100, 100, 20, COLORED); + // adafruitDisplay->display(false); return true; } diff --git a/src/graphics/EInkDisplay2.h b/src/graphics/EInkDisplay2.h index 727132d0e..7d56c8022 100644 --- a/src/graphics/EInkDisplay2.h +++ b/src/graphics/EInkDisplay2.h @@ -17,26 +17,26 @@ class EInkDisplay : public OLEDDisplay /// How often should we update the display /// thereafter we do once per 5 minutes uint32_t slowUpdateMsec = 5 * 60 * 1000; - + public: /* constructor FIXME - the parameters are not used, just a temporary hack to keep working like the old displays */ - EInkDisplay(uint8_t address, int sda, int scl); + EInkDisplay(uint8_t address, int sda, int scl, uint8_t screen_model); // Write the buffer to the display memory (for eink we only do this occasionally) virtual void display(void) override; /** * Force a display update if we haven't drawn within the specified msecLimit - * + * * @return true if we did draw the screen */ bool forceDisplay(uint32_t msecLimit = 1000); /** * shim to make the abstraction happy - * + * */ void setDetected(uint8_t detected); @@ -50,5 +50,3 @@ class EInkDisplay : public OLEDDisplay // Connect to the display virtual bool connect() override; }; - - diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index abaeec660..ed5e1c3a0 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -352,7 +352,7 @@ static void drawCriticalFaultFrame(OLEDDisplay *display, OLEDDisplayUiState *sta } // Ignore messages orginating from phone (from the current node 0x0) unless range test or store and forward module are enabled -static bool shouldDrawMessage(const MeshPacket *packet) +static bool shouldDrawMessage(const meshtastic_MeshPacket *packet) { return packet->from != 0 && !moduleConfig.range_test.enabled && !moduleConfig.store_forward.enabled; } @@ -365,8 +365,8 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state // the max length of this buffer is much longer than we can possibly print static char tempBuf[237]; - MeshPacket &mp = devicestate.rx_text_message; - NodeInfo *node = nodeDB.getNode(getFrom(&mp)); + meshtastic_MeshPacket &mp = devicestate.rx_text_message; + meshtastic_NodeInfo *node = nodeDB.getNode(getFrom(&mp)); // LOG_DEBUG("drawing text message from 0x%x: %s\n", mp.from, // mp.decoded.variant.data.decoded.bytes); @@ -375,14 +375,20 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state // be wrapped. Currently only spaces and "-" are allowed for wrapping display->setTextAlignment(TEXT_ALIGN_LEFT); display->setFont(FONT_SMALL); - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_INVERTED) { display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); } - display->drawStringf(0 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); + + tm *tm = localtime(reinterpret_cast(&mp.rx_time)); + if (config.display.heading_bold) { - display->drawStringf(1 + x, 0 + y, tempBuf, "From: %s", (node && node->has_user) ? node->user.short_name : "???"); + display->drawStringf(1 + x, 0 + y, tempBuf, "[%02d:%02d:%02d] From: %s", tm->tm_hour, tm->tm_min, tm->tm_sec, + (node && node->has_user) ? node->user.short_name : "???"); } + display->drawStringf(0 + x, 0 + y, tempBuf, "[%02d:%02d:%02d] From: %s", tm->tm_hour, tm->tm_min, tm->tm_sec, + (node && node->has_user) ? node->user.short_name : "???"); + display->setColor(WHITE); snprintf(tempBuf, sizeof(tempBuf), "%s", mp.decoded.payload.bytes); display->drawStringMaxWidth(0 + x, 0 + y + FONT_HEIGHT_SMALL, x + display->getWidth(), tempBuf); @@ -556,7 +562,7 @@ static void drawGPSAltitude(OLEDDisplay *display, int16_t x, int16_t y, const GP } else { geoCoord.updateCoords(int32_t(gps->getLatitude()), int32_t(gps->getLongitude()), int32_t(gps->getAltitude())); displayLine = "Altitude: " + String(geoCoord.getAltitude()) + "m"; - if (config.display.units == Config_DisplayConfig_DisplayUnits_IMPERIAL) + if (config.display.units == meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL) displayLine = "Altitude: " + String(geoCoord.getAltitude() * METERS_TO_FEET) + "ft"; display->drawString(x + (SCREEN_WIDTH - (display->getStringWidth(displayLine))) / 2, y, displayLine); } @@ -578,21 +584,21 @@ static void drawGPScoordinates(OLEDDisplay *display, int16_t x, int16_t y, const geoCoord.updateCoords(int32_t(gps->getLatitude()), int32_t(gps->getLongitude()), int32_t(gps->getAltitude())); - if (gpsFormat != Config_DisplayConfig_GpsCoordinateFormat_DMS) { + if (gpsFormat != meshtastic_Config_DisplayConfig_GpsCoordinateFormat_DMS) { char coordinateLine[22]; - if (gpsFormat == Config_DisplayConfig_GpsCoordinateFormat_DEC) { // Decimal Degrees + if (gpsFormat == meshtastic_Config_DisplayConfig_GpsCoordinateFormat_DEC) { // Decimal Degrees snprintf(coordinateLine, sizeof(coordinateLine), "%f %f", geoCoord.getLatitude() * 1e-7, geoCoord.getLongitude() * 1e-7); - } else if (gpsFormat == Config_DisplayConfig_GpsCoordinateFormat_UTM) { // Universal Transverse Mercator + } else if (gpsFormat == meshtastic_Config_DisplayConfig_GpsCoordinateFormat_UTM) { // Universal Transverse Mercator snprintf(coordinateLine, sizeof(coordinateLine), "%2i%1c %06u %07u", geoCoord.getUTMZone(), geoCoord.getUTMBand(), geoCoord.getUTMEasting(), geoCoord.getUTMNorthing()); - } else if (gpsFormat == Config_DisplayConfig_GpsCoordinateFormat_MGRS) { // Military Grid Reference System + } else if (gpsFormat == meshtastic_Config_DisplayConfig_GpsCoordinateFormat_MGRS) { // Military Grid Reference System snprintf(coordinateLine, sizeof(coordinateLine), "%2i%1c %1c%1c %05u %05u", geoCoord.getMGRSZone(), geoCoord.getMGRSBand(), geoCoord.getMGRSEast100k(), geoCoord.getMGRSNorth100k(), geoCoord.getMGRSEasting(), geoCoord.getMGRSNorthing()); - } else if (gpsFormat == Config_DisplayConfig_GpsCoordinateFormat_OLC) { // Open Location Code + } else if (gpsFormat == meshtastic_Config_DisplayConfig_GpsCoordinateFormat_OLC) { // Open Location Code geoCoord.getOLCCode(coordinateLine); - } else if (gpsFormat == Config_DisplayConfig_GpsCoordinateFormat_OSGR) { // Ordnance Survey Grid Reference + } else if (gpsFormat == meshtastic_Config_DisplayConfig_GpsCoordinateFormat_OSGR) { // Ordnance Survey Grid Reference if (geoCoord.getOSGRE100k() == 'I' || geoCoord.getOSGRN100k() == 'I') // OSGR is only valid around the UK region snprintf(coordinateLine, sizeof(coordinateLine), "%s", "Out of Boundary"); else @@ -610,7 +616,6 @@ static void drawGPScoordinates(OLEDDisplay *display, int16_t x, int16_t y, const } else { display->drawString(x + (SCREEN_WIDTH - (display->getStringWidth(coordinateLine))) / 2, y, coordinateLine); } - } else { char latLine[22]; char lonLine[22]; @@ -699,7 +704,7 @@ static float estimatedHeading(double lat, double lon) /// Sometimes we will have Position objects that only have a time, so check for /// valid lat/lon -static bool hasPosition(NodeInfo *n) +static bool hasPosition(meshtastic_NodeInfo *n) { return n->has_position && (n->position.latitude_i != 0 || n->position.longitude_i != 0); } @@ -709,7 +714,7 @@ static uint16_t getCompassDiam(OLEDDisplay *display) uint16_t diam = 0; uint16_t offset = 0; - if (config.display.displaymode != Config_DisplayConfig_DisplayMode_DEFAULT) + if (config.display.displaymode != meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT) offset = FONT_HEIGHT_SMALL; // get the smaller of the 2 dimensions and subtract 20 @@ -786,7 +791,7 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ prevFrame = state->currentFrame; nodeIndex = (nodeIndex + 1) % nodeDB.getNumNodes(); - NodeInfo *n = nodeDB.getNodeByIndex(nodeIndex); + meshtastic_NodeInfo *n = nodeDB.getNodeByIndex(nodeIndex); if (n->num == nodeDB.getNodeNum()) { // Don't show our node, just skip to next nodeIndex = (nodeIndex + 1) % nodeDB.getNumNodes(); @@ -795,14 +800,14 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ displayedNodeNum = n->num; } - NodeInfo *node = nodeDB.getNodeByIndex(nodeIndex); + meshtastic_NodeInfo *node = nodeDB.getNodeByIndex(nodeIndex); display->setFont(FONT_SMALL); // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_INVERTED) { display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); } @@ -832,12 +837,12 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ static char distStr[20]; strncpy(distStr, "? km", sizeof(distStr)); // might not have location data - NodeInfo *ourNode = nodeDB.getNode(nodeDB.getNodeNum()); + meshtastic_NodeInfo *ourNode = nodeDB.getNode(nodeDB.getNodeNum()); const char *fields[] = {username, distStr, signalStr, lastStr, NULL}; int16_t compassX = 0, compassY = 0; // coordinates for the center of the compass/circle - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT) { compassX = x + SCREEN_WIDTH - getCompassDiam(display) / 2 - 5; compassY = y + SCREEN_HEIGHT / 2; } else { @@ -847,18 +852,18 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ bool hasNodeHeading = false; if (ourNode && hasPosition(ourNode)) { - Position &op = ourNode->position; + meshtastic_Position &op = ourNode->position; float myHeading = estimatedHeading(DegD(op.latitude_i), DegD(op.longitude_i)); drawCompassNorth(display, compassX, compassY, myHeading); if (hasPosition(node)) { // display direction toward node hasNodeHeading = true; - Position &p = node->position; + meshtastic_Position &p = node->position; float d = GeoCoord::latLongToMeter(DegD(p.latitude_i), DegD(p.longitude_i), DegD(op.latitude_i), DegD(op.longitude_i)); - if (config.display.units == Config_DisplayConfig_DisplayUnits_IMPERIAL) { + if (config.display.units == meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL) { if (d < (2 * MILES_TO_FEET)) snprintf(distStr, sizeof(distStr), "%.0f ft", d * METERS_TO_FEET); else @@ -887,7 +892,7 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ } display->drawCircle(compassX, compassY, getCompassDiam(display) / 2); - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_INVERTED) { display->setColor(BLACK); } // Must be after distStr is populated @@ -908,7 +913,11 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ // } // } // #else -Screen::Screen(uint8_t address, int sda, int scl) : OSThread("Screen"), cmdQueue(32), dispdev(address, sda, scl), ui(&dispdev) +Screen::Screen(uint8_t address, int sda, int scl) + : OSThread("Screen"), cmdQueue(32), + dispdev(address, sda, scl, + screen_model == meshtastic_Config_DisplayConfig_OledType_OLED_SH1107 ? GEOMETRY_128_128 : GEOMETRY_128_64), + ui(&dispdev) { address_found = address; cmdQueue.setReader(this); @@ -958,6 +967,8 @@ void Screen::setup() useDisplay = true; #ifdef AutoOLEDWire_h + if (screen_model == meshtastic_Config_DisplayConfig_OledType_OLED_SH1107) + screen_model = meshtastic_Config_DisplayConfig_OledType_OLED_SH1106; dispdev.setDetected(screen_model); #endif @@ -1079,7 +1090,7 @@ int32_t Screen::runOnce() } #ifndef DISABLE_WELCOME_UNSET - if (showingNormalScreen && config.lora.region == Config_LoRaConfig_RegionCode_UNSET) { + if (showingNormalScreen && config.lora.region == meshtastic_Config_LoRaConfig_RegionCode_UNSET) { setWelcomeFrames(); } #endif @@ -1399,7 +1410,7 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_INVERTED) { display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); } @@ -1413,20 +1424,20 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 // Display power status if (powerStatus->getHasBattery()) { - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT) { drawBattery(display, x, y + 2, imgBattery, powerStatus); } else { drawBattery(display, x + 1, y + 3, imgBattery, powerStatus); } } else if (powerStatus->knowsUSB()) { - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT) { display->drawFastImage(x, y + 2, 16, 8, powerStatus->getHasUSB() ? imgUSB : imgPower); } else { display->drawFastImage(x + 1, y + 3, 16, 8, powerStatus->getHasUSB() ? imgUSB : imgPower); } } // Display nodes status - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT) { drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 2, nodeStatus); } else { drawNodes(display, x + (SCREEN_WIDTH * 0.25), y + 3, nodeStatus); @@ -1439,7 +1450,7 @@ void DebugInfo::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16 #endif drawGPSpowerstat(display, x, yPos, gpsStatus); } else { - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_DEFAULT) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT) { drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 2, gpsStatus); } else { drawGPS(display, x + (SCREEN_WIDTH * 0.63), y + 3, gpsStatus); @@ -1512,7 +1523,7 @@ void DebugInfo::drawFrameWiFi(OLEDDisplay *display, OLEDDisplayUiState *state, i // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_INVERTED) { display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); } @@ -1644,7 +1655,7 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); - if (config.display.displaymode == Config_DisplayConfig_DisplayMode_INVERTED) { + if (config.display.displaymode == meshtastic_Config_DisplayConfig_DisplayMode_INVERTED) { display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL); display->setColor(BLACK); } @@ -1671,25 +1682,28 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat auto mode = ""; switch (config.lora.modem_preset) { - case Config_LoRaConfig_ModemPreset_SHORT_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_SLOW: mode = "ShortS"; break; - case Config_LoRaConfig_ModemPreset_SHORT_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_FAST: mode = "ShortF"; break; - case Config_LoRaConfig_ModemPreset_MEDIUM_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_SLOW: mode = "MedS"; break; - case Config_LoRaConfig_ModemPreset_MEDIUM_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_FAST: mode = "MedF"; break; - case Config_LoRaConfig_ModemPreset_LONG_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_LONG_SLOW: mode = "LongS"; break; - case Config_LoRaConfig_ModemPreset_LONG_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_LONG_FAST: mode = "LongF"; break; - case Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_LONG_MODERATE: + mode = "LongM"; + break; + case meshtastic_Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW: mode = "VeryL"; break; default: @@ -1751,7 +1765,8 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat display->drawString(x + SCREEN_WIDTH - display->getStringWidth(chUtil), y + FONT_HEIGHT_SMALL * 1, chUtil); if (config.position.gps_enabled) { // Line 3 - if (config.display.gps_format != Config_DisplayConfig_GpsCoordinateFormat_DMS) // if DMS then don't draw altitude + if (config.display.gps_format != + meshtastic_Config_DisplayConfig_GpsCoordinateFormat_DMS) // if DMS then don't draw altitude drawGPSAltitude(display, x, y + FONT_HEIGHT_SMALL * 2, gpsStatus); // Line 4 @@ -1799,7 +1814,7 @@ int Screen::handleStatusUpdate(const meshtastic::Status *arg) return 0; } -int Screen::handleTextMessage(const MeshPacket *packet) +int Screen::handleTextMessage(const meshtastic_MeshPacket *packet) { if (showingNormalScreen) { setFrames(); // Regen the list of screens (will show new text message) diff --git a/src/graphics/Screen.h b/src/graphics/Screen.h index 3988fa1a8..db851e8bb 100644 --- a/src/graphics/Screen.h +++ b/src/graphics/Screen.h @@ -7,15 +7,15 @@ namespace graphics { // Noop class for boards without screen. -class Screen +class Screen { public: - explicit Screen(char){} + explicit Screen(char) {} void onPress() {} void setup() {} void setOn(bool) {} - void print(const char*){} - void adjustBrightness(){} + void print(const char *) {} + void adjustBrightness() {} void doDeepSleep() {} void forceDisplay() {} void startBluetoothPinScreen(uint32_t pin) {} @@ -23,7 +23,7 @@ class Screen void startRebootScreen() {} void startFirmwareUpdateScreen() {} }; -} +} // namespace graphics #else #include @@ -34,7 +34,7 @@ class Screen #ifdef USE_ST7567 #include -#elif defined(USE_SH1106) +#elif defined(USE_SH1106) || defined(USE_SH1107) #include #elif defined(USE_SSD1306) #include @@ -49,9 +49,9 @@ class Screen #include "commands.h" #include "concurrency/LockGuard.h" #include "concurrency/OSThread.h" +#include "mesh/MeshModule.h" #include "power.h" #include -#include "mesh/MeshModule.h" // 0 to 255, though particular variants might define different defaults #ifndef BRIGHTNESS_DEFAULT @@ -110,8 +110,8 @@ class Screen : public concurrency::OSThread CallbackObserver(this, &Screen::handleStatusUpdate); CallbackObserver nodeStatusObserver = CallbackObserver(this, &Screen::handleStatusUpdate); - CallbackObserver textMessageObserver = - CallbackObserver(this, &Screen::handleTextMessage); + CallbackObserver textMessageObserver = + CallbackObserver(this, &Screen::handleTextMessage); CallbackObserver uiFrameEventObserver = CallbackObserver(this, &Screen::handleUIFrameEvent); @@ -132,13 +132,14 @@ class Screen : public concurrency::OSThread void setOn(bool on) { if (!on) - handleSetOn(false); // We handle off commands immediately, because they might be called because the CPU is shutting down + handleSetOn( + false); // We handle off commands immediately, because they might be called because the CPU is shutting down else enqueueCmd(ScreenCmd{.cmd = on ? Cmd::SET_ON : Cmd::SET_OFF}); } /** - * Prepare the display for the unit going to the lowest power mode possible. Most screens will just + * Prepare the display for the unit going to the lowest power mode possible. Most screens will just * poweroff, but eink screens will show a "I'm sleeping" graphic, possibly with a QR code */ void doDeepSleep(); @@ -223,29 +224,33 @@ class Screen : public concurrency::OSThread LASTCHAR = ch; switch (last) { // conversion depending on first UTF8-character - case 0xC2: { - SKIPREST = false; - return (uint8_t)ch; - } - case 0xC3: { - SKIPREST = false; - return (uint8_t)(ch | 0xC0); - } - // map UTF-8 cyrillic chars to it Windows-1251 (CP-1251) ASCII codes - // note: in this case we must use compatible font - provided ArialMT_Plain_10/16/24 by 'ThingPulse/esp8266-oled-ssd1306' library - // have empty chars for non-latin ASCII symbols - case 0xD0: { - SKIPREST = false; - if (ch == 129) return (uint8_t)(168); // Ё - if (ch > 143 && ch < 192) return (uint8_t)(ch + 48); - break; - } - case 0xD1: { - SKIPREST = false; - if (ch == 145) return (uint8_t)(184); // ё - if (ch > 127 && ch < 144) return (uint8_t)(ch + 112); - break; - } + case 0xC2: { + SKIPREST = false; + return (uint8_t)ch; + } + case 0xC3: { + SKIPREST = false; + return (uint8_t)(ch | 0xC0); + } + // map UTF-8 cyrillic chars to it Windows-1251 (CP-1251) ASCII codes + // note: in this case we must use compatible font - provided ArialMT_Plain_10/16/24 by 'ThingPulse/esp8266-oled-ssd1306' + // library have empty chars for non-latin ASCII symbols + case 0xD0: { + SKIPREST = false; + if (ch == 129) + return (uint8_t)(168); // Ё + if (ch > 143 && ch < 192) + return (uint8_t)(ch + 48); + break; + } + case 0xD1: { + SKIPREST = false; + if (ch == 145) + return (uint8_t)(184); // ё + if (ch > 127 && ch < 144) + return (uint8_t)(ch + 112); + break; + } } // We want to strip out prefix chars for two-byte char formats @@ -268,7 +273,7 @@ class Screen : public concurrency::OSThread DebugInfo *debug_info() { return &debugInfo; } int handleStatusUpdate(const meshtastic::Status *arg); - int handleTextMessage(const MeshPacket *arg); + int handleTextMessage(const meshtastic_MeshPacket *arg); int handleUIFrameEvent(const UIFrameEvent *arg); /// Used to force (super slow) eink displays to draw critical frames @@ -342,10 +347,7 @@ class Screen : public concurrency::OSThread /// Display device -// #ifdef RAK4630 -// EInkDisplay dispdev; -// AutoOLEDWire dispdev_oled; -#ifdef USE_SH1106 +#if defined(USE_SH1106) || defined(USE_SH1107) SH1106Wire dispdev; #elif defined(USE_SSD1306) SSD1306Wire dispdev; diff --git a/src/graphics/TFTDisplay.cpp b/src/graphics/TFTDisplay.cpp index 670c0f162..0bd1d3a99 100644 --- a/src/graphics/TFTDisplay.cpp +++ b/src/graphics/TFTDisplay.cpp @@ -8,7 +8,7 @@ static TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in User_Setup.h -TFTDisplay::TFTDisplay(uint8_t address, int sda, int scl) +TFTDisplay::TFTDisplay(uint8_t address, int sda, int scl, uint8_t screen_model) { #ifdef SCREEN_ROTATE setGeometry(GEOMETRY_RAWMODE, TFT_HEIGHT, TFT_WIDTH); @@ -22,7 +22,7 @@ void TFTDisplay::display(void) { concurrency::LockGuard g(spiLock); - uint16_t x,y; + uint16_t x, y; for (y = 0; y < displayHeight; y++) { for (x = 0; x < displayWidth; x++) { diff --git a/src/graphics/TFTDisplay.h b/src/graphics/TFTDisplay.h index c9749d9a8..c18dc03c6 100644 --- a/src/graphics/TFTDisplay.h +++ b/src/graphics/TFTDisplay.h @@ -18,14 +18,14 @@ class TFTDisplay : public OLEDDisplay /* constructor FIXME - the parameters are not used, just a temporary hack to keep working like the old displays */ - TFTDisplay(uint8_t address, int sda, int scl); + TFTDisplay(uint8_t address, int sda, int scl, uint8_t screen_model); // Write the buffer to the display memory virtual void display(void) override; - + /** * shim to make the abstraction happy - * + * */ void setDetected(uint8_t detected); 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/RotaryEncoderInterruptBase.cpp b/src/input/RotaryEncoderInterruptBase.cpp index ad55bd1a4..19b507f6c 100644 --- a/src/input/RotaryEncoderInterruptBase.cpp +++ b/src/input/RotaryEncoderInterruptBase.cpp @@ -34,7 +34,7 @@ void RotaryEncoderInterruptBase::init( int32_t RotaryEncoderInterruptBase::runOnce() { InputEvent e; - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; e.source = this->_originName; if (this->action == ROTARY_ACTION_PRESSED) { @@ -48,7 +48,7 @@ int32_t RotaryEncoderInterruptBase::runOnce() e.inputEvent = this->_eventCcw; } - if (e.inputEvent != ModuleConfig_CannedMessageConfig_InputEventChar_NONE) { + if (e.inputEvent != meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE) { this->notifyObservers(&e); } diff --git a/src/input/RotaryEncoderInterruptBase.h b/src/input/RotaryEncoderInterruptBase.h index 88d619178..06f7a2354 100644 --- a/src/input/RotaryEncoderInterruptBase.h +++ b/src/input/RotaryEncoderInterruptBase.h @@ -33,8 +33,8 @@ class RotaryEncoderInterruptBase : public Observable, public private: uint8_t _pinA = 0; uint8_t _pinB = 0; - char _eventCw = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; - char _eventCcw = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; - char _eventPressed = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + char _eventCw = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + char _eventCcw = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + char _eventPressed = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; const char *_originName; }; 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/UpDownInterruptBase.h b/src/input/UpDownInterruptBase.h index 1ee4e4a03..ed7eee332 100644 --- a/src/input/UpDownInterruptBase.h +++ b/src/input/UpDownInterruptBase.h @@ -16,8 +16,8 @@ class UpDownInterruptBase : public Observable private: uint8_t _pinDown = 0; uint8_t _pinUp = 0; - char _eventDown = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; - char _eventUp = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; - char _eventPressed = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + char _eventDown = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + char _eventUp = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + char _eventPressed = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; const char *_originName; }; diff --git a/src/input/UpDownInterruptImpl1.cpp b/src/input/UpDownInterruptImpl1.cpp index c49409660..c22152f82 100644 --- a/src/input/UpDownInterruptImpl1.cpp +++ b/src/input/UpDownInterruptImpl1.cpp @@ -17,9 +17,9 @@ void UpDownInterruptImpl1::init() uint8_t pinDown = moduleConfig.canned_message.inputbroker_pin_b; uint8_t pinPress = moduleConfig.canned_message.inputbroker_pin_press; - char eventDown = static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_DOWN); - char eventUp = static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_UP); - char eventPressed = static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_SELECT); + char eventDown = static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_DOWN); + char eventUp = static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_UP); + char eventPressed = static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_SELECT); UpDownInterruptBase::init(pinDown, pinUp, pinPress, eventDown, eventUp, eventPressed, UpDownInterruptImpl1::handleIntDown, UpDownInterruptImpl1::handleIntUp, UpDownInterruptImpl1::handleIntPressed); 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..9212b6d4c 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; } @@ -70,35 +70,35 @@ int32_t KbI2cBase::runOnce() while (Wire.available()) { char c = Wire.read(); InputEvent e; - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; e.source = this->_originName; switch (c) { case 0x1b: // ESC - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL; break; case 0x08: // Back - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_BACK; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_BACK; e.kbchar = c; break; case 0xb5: // Up - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_UP; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_UP; break; case 0xb6: // Down - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_DOWN; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_DOWN; break; case 0xb4: // Left - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_LEFT; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_LEFT; e.kbchar = c; break; case 0xb7: // Right - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT; e.kbchar = c; break; case 0x0d: // Enter - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_SELECT; + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_SELECT; break; - case 0x00: //nopress - e.inputEvent = ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + case 0x00: // nopress + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; break; default: // all other keys e.inputEvent = ANYKEY; @@ -106,7 +106,7 @@ int32_t KbI2cBase::runOnce() break; } - if (e.inputEvent != ModuleConfig_CannedMessageConfig_InputEventChar_NONE) { + if (e.inputEvent != meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE) { this->notifyObservers(&e); } } 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/main.cpp b/src/main.cpp index 76a6a6b6f..4f65ff51b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,12 +3,12 @@ #include "MeshService.h" #include "NodeDB.h" #include "PowerFSM.h" +#include "ReliableRouter.h" #include "airtime.h" #include "buzz.h" #include "configuration.h" #include "error.h" #include "power.h" -#include "ReliableRouter.h" // #include "debug.h" #include "FSCommon.h" #include "RTC.h" @@ -27,8 +27,8 @@ #include // #include -#include "mesh/http/WiFiAPClient.h" #include "mesh/eth/ethClient.h" +#include "mesh/http/WiFiAPClient.h" #ifdef ARCH_ESP32 #include "mesh/http/WebServer.h" @@ -87,7 +87,7 @@ uint8_t rtc_found; // Keystore Chips uint8_t keystore_found; -#ifndef ARCH_PORTDUINO +#if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) ATECCX08A atecc; #endif @@ -98,7 +98,8 @@ uint32_t serialSinceMsec; bool pmu_found; // Array map of sensor types (as array index) and i2c address as value we'll find in the i2c scan -uint8_t nodeTelemetrySensorsMap[_TelemetrySensorType_MAX + 1] = { 0 }; // one is enough, missing elements will be initialized to 0 anyway. +uint8_t nodeTelemetrySensorsMap[_meshtastic_TelemetrySensorType_MAX + 1] = { + 0}; // one is enough, missing elements will be initialized to 0 anyway. Router *router = NULL; // Users of router don't care what sort of subclass implements that API @@ -127,6 +128,17 @@ static int32_t ledBlinker() setLed(ledOn); +#ifdef ARCH_ESP32 + auto newHeap = ESP.getFreeHeap(); + if (newHeap < 11000) { + LOG_DEBUG("\n\n====== heap too low [11000] -> reboot in 1s ======\n\n"); +#ifdef HAS_SCREEN + screen->startRebootScreen(); +#endif + rebootAtMsec = millis() + 900; + } +#endif + // have a very sparse duty cycle of LED being on, unless charging, then blink 0.5Hz square wave rate to indicate that return powerStatus->getIsCharging() ? 1000 : (ledOn ? 1 : 1000); } @@ -169,7 +181,7 @@ void setup() #endif #ifdef DEBUG_PORT - consoleInit(); // Set serial baud rate and init our mesh console + consoleInit(); // Set serial baud rate and init our mesh console #endif serialSinceMsec = millis(); @@ -249,12 +261,11 @@ void setup() powerStatus->observe(&power->newStatus); power->setup(); // Must be after status handler is installed, so that handler gets notified of the initial configuration - #ifdef LILYGO_TBEAM_S3_CORE // In T-Beam-S3-core, the I2C device cannot be scanned before power initialization, otherwise the device will be stuck // PCF8563 RTC in tbeam-s3 uses Wire1 to share I2C bus Wire1.beginTransmission(PCF8563_RTC); - if (Wire1.endTransmission() == 0){ + if (Wire1.endTransmission() == 0) { rtc_found = PCF8563_RTC; LOG_INFO("PCF8563 RTC found\n"); } @@ -299,12 +310,20 @@ void setup() // but we need to do this after main cpu iniot (esp32setup), because we need the random seed set nodeDB.init(); + // If we're taking on the repeater role, use flood router + if (config.device.role == meshtastic_Config_DeviceConfig_Role_REPEATER) + router = new FloodingRouter(); + playStartMelody(); // fixed screen override? - if (config.display.oled != Config_DisplayConfig_OledType_OLED_AUTO) + if (config.display.oled != meshtastic_Config_DisplayConfig_OledType_OLED_AUTO) screen_model = config.display.oled; +#if defined(USE_SH1107) + screen_model = Config_DisplayConfig_OledType_OLED_SH1107; // set dimension of 128x128 +#endif + // Init our SPI controller (must be before screen and lora) initSPI(); #ifndef ARCH_ESP32 @@ -337,7 +356,7 @@ void setup() // Do this after service.init (because that clears error_code) #ifdef HAS_PMU if (!pmu_found) - RECORD_CRITICALERROR(CriticalErrorCode_NO_AXP192); // Record a hardware fault for missing hardware + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_NO_AXP192); // Record a hardware fault for missing hardware #endif // Don't call screen setup until after nodedb is setup (because we need @@ -448,18 +467,18 @@ void setup() } #endif -// check if the radio chip matches the selected region + // check if the radio chip matches the selected region -if((config.lora.region == Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLora())){ - LOG_WARN("Radio chip does not support 2.4GHz LoRa. Reverting to unset.\n"); - config.lora.region = Config_LoRaConfig_RegionCode_UNSET; - nodeDB.saveToDisk(SEGMENT_CONFIG); - if(!rIf->reconfigure()) { - LOG_WARN("Reconfigure failed, rebooting\n"); - screen->startRebootScreen(); - rebootAtMsec = millis() + 5000; + if ((config.lora.region == meshtastic_Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLora())) { + LOG_WARN("Radio chip does not support 2.4GHz LoRa. Reverting to unset.\n"); + config.lora.region = meshtastic_Config_LoRaConfig_RegionCode_UNSET; + nodeDB.saveToDisk(SEGMENT_CONFIG); + if (!rIf->reconfigure()) { + LOG_WARN("Reconfigure failed, rebooting\n"); + screen->startRebootScreen(); + rebootAtMsec = millis() + 5000; + } } -} #if HAS_WIFI || HAS_ETHERNET mqttInit(); @@ -486,13 +505,15 @@ if((config.lora.region == Config_LoRaConfig_RegionCode_LORA_24) && (!rIf->wideLo airTime = new AirTime(); if (!rIf) - RECORD_CRITICALERROR(CriticalErrorCode_NO_RADIO); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_NO_RADIO); else { router->addInterface(rIf); // Calculate and save the bit rate to myNodeInfo // TODO: This needs to be added what ever method changes the channel from the phone. - myNodeInfo.bitrate = (float(Constants_DATA_PAYLOAD_LEN) / (float(rIf->getPacketTime(Constants_DATA_PAYLOAD_LEN)))) * 1000; + myNodeInfo.bitrate = + (float(meshtastic_Constants_DATA_PAYLOAD_LEN) / (float(rIf->getPacketTime(meshtastic_Constants_DATA_PAYLOAD_LEN)))) * + 1000; LOG_DEBUG("myNodeInfo.bitrate = %f bytes / sec\n", myNodeInfo.bitrate); } diff --git a/src/main.h b/src/main.h index 27aa06d6c..9d965b0fc 100644 --- a/src/main.h +++ b/src/main.h @@ -26,7 +26,7 @@ extern bool isUSBPowered; extern ATECCX08A atecc; #endif -extern uint8_t nodeTelemetrySensorsMap[_TelemetrySensorType_MAX + 1]; +extern uint8_t nodeTelemetrySensorsMap[_meshtastic_TelemetrySensorType_MAX + 1]; extern int TCPPort; // set by Portduino diff --git a/src/mesh/Channels.cpp b/src/mesh/Channels.cpp index f9b3eb9b8..1b090a28f 100644 --- a/src/mesh/Channels.cpp +++ b/src/mesh/Channels.cpp @@ -45,23 +45,23 @@ int16_t Channels::generateHash(ChannelIndex channelNum) /** * Validate a channel, fixing any errors as needed */ -Channel &Channels::fixupChannel(ChannelIndex chIndex) +meshtastic_Channel &Channels::fixupChannel(ChannelIndex chIndex) { - Channel &ch = getByIndex(chIndex); + meshtastic_Channel &ch = getByIndex(chIndex); ch.index = chIndex; // Preinit the index so it be ready to share with the phone (we'll never change it later) if (!ch.has_settings) { // No settings! Must disable and skip - ch.role = Channel_Role_DISABLED; + ch.role = meshtastic_Channel_Role_DISABLED; memset(&ch.settings, 0, sizeof(ch.settings)); ch.has_settings = true; } else { - ChannelSettings &channelSettings = ch.settings; + meshtastic_ChannelSettings &meshtastic_channelSettings = ch.settings; // Convert the old string "Default" to our new short representation - if (strcmp(channelSettings.name, "Default") == 0) - *channelSettings.name = '\0'; + if (strcmp(meshtastic_channelSettings.name, "Default") == 0) + *meshtastic_channelSettings.name = '\0'; } hashes[chIndex] = generateHash(chIndex); @@ -74,11 +74,11 @@ Channel &Channels::fixupChannel(ChannelIndex chIndex) */ void Channels::initDefaultChannel(ChannelIndex chIndex) { - Channel &ch = getByIndex(chIndex); - ChannelSettings &channelSettings = ch.settings; - Config_LoRaConfig &loraConfig = config.lora; + meshtastic_Channel &ch = getByIndex(chIndex); + meshtastic_ChannelSettings &channelSettings = ch.settings; + meshtastic_Config_LoRaConfig &loraConfig = config.lora; - loraConfig.modem_preset = Config_LoRaConfig_ModemPreset_LONG_FAST; // Default to Long Range & Fast + loraConfig.modem_preset = meshtastic_Config_LoRaConfig_ModemPreset_LONG_FAST; // Default to Long Range & Fast loraConfig.use_preset = true; loraConfig.tx_power = 0; // default uint8_t defaultpskIndex = 1; @@ -87,25 +87,25 @@ void Channels::initDefaultChannel(ChannelIndex chIndex) strncpy(channelSettings.name, "", sizeof(channelSettings.name)); ch.has_settings = true; - ch.role = Channel_Role_PRIMARY; + ch.role = meshtastic_Channel_Role_PRIMARY; } CryptoKey Channels::getKey(ChannelIndex chIndex) { - Channel &ch = getByIndex(chIndex); - const ChannelSettings &channelSettings = ch.settings; + meshtastic_Channel &ch = getByIndex(chIndex); + const meshtastic_ChannelSettings &channelSettings = ch.settings; assert(ch.has_settings); CryptoKey k; memset(k.bytes, 0, sizeof(k.bytes)); // In case the user provided a short key, we want to pad the rest with zeros - if (ch.role == Channel_Role_DISABLED) { + if (ch.role == meshtastic_Channel_Role_DISABLED) { k.length = -1; // invalid } else { memcpy(k.bytes, channelSettings.psk.bytes, channelSettings.psk.size); k.length = channelSettings.psk.size; if (k.length == 0) { - if (ch.role == Channel_Role_SECONDARY) { + if (ch.role == meshtastic_Channel_Role_SECONDARY) { LOG_DEBUG("Unset PSK for secondary channel %s. using primary key\n", ch.settings.name); k = getKey(primaryIndex); } else @@ -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; @@ -182,24 +182,24 @@ void Channels::onConfigChanged() { // Make sure the phone hasn't mucked anything up for (int i = 0; i < channelFile.channels_count; i++) { - Channel &ch = fixupChannel(i); + meshtastic_Channel &ch = fixupChannel(i); - if (ch.role == Channel_Role_PRIMARY) + if (ch.role == meshtastic_Channel_Role_PRIMARY) primaryIndex = i; } } -Channel &Channels::getByIndex(ChannelIndex chIndex) +meshtastic_Channel &Channels::getByIndex(ChannelIndex chIndex) { // remove this assert cause malformed packets can make our firmware reboot here. if (chIndex < channelFile.channels_count) { // This should be equal to MAX_NUM_CHANNELS - Channel *ch = channelFile.channels + chIndex; + meshtastic_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)); + static meshtastic_Channel *ch = (meshtastic_Channel *)malloc(sizeof(meshtastic_Channel)); + memset(ch, 0, sizeof(meshtastic_Channel)); // ch.index -1 means we don't know the channel locally and need to look it up by settings.name // not sure this is handled right everywhere ch->index = -1; @@ -207,7 +207,7 @@ Channel &Channels::getByIndex(ChannelIndex chIndex) } } -Channel &Channels::getByName(const char* chName) +meshtastic_Channel &Channels::getByName(const char *chName) { for (ChannelIndex i = 0; i < getNumChannels(); i++) { if (strcasecmp(getGlobalId(i), chName) == 0) { @@ -218,15 +218,15 @@ Channel &Channels::getByName(const char* chName) return getByIndex(getPrimaryIndex()); } -void Channels::setChannel(const Channel &c) +void Channels::setChannel(const meshtastic_Channel &c) { - Channel &old = getByIndex(c.index); + meshtastic_Channel &old = getByIndex(c.index); // if this is the new primary, demote any existing roles - if (c.role == Channel_Role_PRIMARY) + if (c.role == meshtastic_Channel_Role_PRIMARY) for (int i = 0; i < getNumChannels(); i++) - if (channelFile.channels[i].role == Channel_Role_PRIMARY) - channelFile.channels[i].role = Channel_Role_SECONDARY; + if (channelFile.channels[i].role == meshtastic_Channel_Role_PRIMARY) + channelFile.channels[i].role = meshtastic_Channel_Role_SECONDARY; old = c; // slam in the new settings/role } @@ -234,7 +234,7 @@ void Channels::setChannel(const Channel &c) const char *Channels::getName(size_t chIndex) { // Convert the short "" representation for Default into a usable string - const ChannelSettings &channelSettings = getByIndex(chIndex).settings; + const meshtastic_ChannelSettings &channelSettings = getByIndex(chIndex).settings; const char *channelName = channelSettings.name; if (!*channelName) { // emptystring // Per mesh.proto spec, if bandwidth is specified we must ignore modemPreset enum, we assume that in that case @@ -242,33 +242,32 @@ const char *Channels::getName(size_t chIndex) if (config.lora.use_preset) { switch (config.lora.modem_preset) { - case Config_LoRaConfig_ModemPreset_SHORT_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_SLOW: channelName = "ShortSlow"; break; - case Config_LoRaConfig_ModemPreset_SHORT_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_FAST: channelName = "ShortFast"; break; - case Config_LoRaConfig_ModemPreset_MEDIUM_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_SLOW: channelName = "MediumSlow"; break; - case Config_LoRaConfig_ModemPreset_MEDIUM_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_FAST: channelName = "MediumFast"; break; - case Config_LoRaConfig_ModemPreset_LONG_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_LONG_SLOW: channelName = "LongSlow"; break; - case Config_LoRaConfig_ModemPreset_LONG_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_LONG_FAST: channelName = "LongFast"; break; - case Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW: channelName = "VLongSlow"; break; default: channelName = "Invalid"; break; } - } - else { + } else { channelName = "Custom"; } } diff --git a/src/mesh/Channels.h b/src/mesh/Channels.h index 79e96b7f6..f3d696f90 100644 --- a/src/mesh/Channels.h +++ b/src/mesh/Channels.h @@ -29,24 +29,23 @@ class Channels int16_t hashes[MAX_NUM_CHANNELS] = {}; public: - Channels() {} /// Well known channel names static const char *adminChannel, *gpioChannel, *serialChannel; - const ChannelSettings &getPrimary() { return getByIndex(getPrimaryIndex()).settings; } + const meshtastic_ChannelSettings &getPrimary() { return getByIndex(getPrimaryIndex()).settings; } /** Return the Channel for a specified index */ - Channel &getByIndex(ChannelIndex chIndex); + meshtastic_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. */ + meshtastic_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. */ - void setChannel(const Channel &c); + void setChannel(const meshtastic_Channel &c); /** Return a human friendly name for this channel (and expand any short strings as needed) */ @@ -125,7 +124,7 @@ class Channels /** * Validate a channel, fixing any errors as needed */ - Channel &fixupChannel(ChannelIndex chIndex); + meshtastic_Channel &fixupChannel(ChannelIndex chIndex); /** * Write a default channel to the specified channel index 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..1498bbeab 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -9,7 +9,7 @@ FloodingRouter::FloodingRouter() {} * later free() the packet to pool. This routine is not allowed to stall. * If the txmit queue is full it might return an error */ -ErrorCode FloodingRouter::send(MeshPacket *p) +ErrorCode FloodingRouter::send(meshtastic_MeshPacket *p) { // Add any messages _we_ send to the seen message list (so we will ignore all retransmissions we see) wasSeenRecently(p); // FIXME, move this to a sniffSent method @@ -17,7 +17,7 @@ ErrorCode FloodingRouter::send(MeshPacket *p) return Router::send(p); } -bool FloodingRouter::shouldFilterReceived(const MeshPacket *p) +bool FloodingRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) { if (wasSeenRecently(p)) { // Note: this will also add a recent packet record printPacket("Ignoring incoming msg, because we've already seen it", p); @@ -27,40 +27,43 @@ bool FloodingRouter::shouldFilterReceived(const MeshPacket *p) return Router::shouldFilterReceived(p); } -void FloodingRouter::sniffReceived(const MeshPacket *p, const Routing *c) +void FloodingRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) { - bool isAck = ((c && c->error_reason == Routing_Error_NONE)); // consider only ROUTING_APP message without error as ACK + bool isAck = + ((c && c->error_reason == meshtastic_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) { - MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it + if (config.device.role != meshtastic_Config_DeviceConfig_Role_CLIENT_MUTE) { + meshtastic_MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it tosend->hop_limit--; // bump down the hop count // If it is a traceRoute request, update the route that it went via me - if (p->which_payload_variant == MeshPacket_decoded_tag && traceRouteModule->wantPacket(p)) { + if (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag && traceRouteModule->wantPacket(p)) { traceRouteModule->updateRoute(tosend); } - LOG_INFO("Rebroadcasting received floodmsg to neighbors", p); + LOG_INFO("Rebroadcasting received floodmsg to neighbors\n"); // Note: we are careful to resend using the original senders node id // We are careful not to call our hooked version of send() - because we don't want to check this again Router::send(tosend); - } else { LOG_DEBUG("Not rebroadcasting. Role = Role_ClientMute\n"); } - } else { LOG_DEBUG("Ignoring a simple (0 id) broadcast\n"); } } + if (config.device.rebroadcast_mode == meshtastic_Config_DeviceConfig_RebroadcastMode_LOCAL_ONLY) { + LOG_DEBUG("Cancelling rebroadcast of message from node on a foreign mesh, due to local only rebroadcast mode\n"); + Router::cancelSending(p->to, p->decoded.request_id); + } // handle the packet as normal Router::sniffReceived(p, c); } diff --git a/src/mesh/FloodingRouter.h b/src/mesh/FloodingRouter.h index 01b51c9a2..73dbd1f3f 100644 --- a/src/mesh/FloodingRouter.h +++ b/src/mesh/FloodingRouter.h @@ -42,7 +42,7 @@ class FloodingRouter : public Router, protected PacketHistory * later free() the packet to pool. This routine is not allowed to stall. * If the txmit queue is full it might return an error */ - virtual ErrorCode send(MeshPacket *p) override; + virtual ErrorCode send(meshtastic_MeshPacket *p) override; protected: /** @@ -51,10 +51,10 @@ class FloodingRouter : public Router, protected PacketHistory * Called immedately on receiption, before any further processing. * @return true to abandon the packet */ - virtual bool shouldFilterReceived(const MeshPacket *p) override; + virtual bool shouldFilterReceived(const meshtastic_MeshPacket *p) override; /** * Look for broadcasts we need to rebroadcast */ - virtual void sniffReceived(const MeshPacket *p, const Routing *c) override; + virtual void sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) override; }; 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..cc54e78c2 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -1,20 +1,20 @@ -#include "configuration.h" #include "MeshModule.h" #include "Channels.h" #include "MeshService.h" #include "NodeDB.h" +#include "configuration.h" #include "modules/RoutingModule.h" #include std::vector *MeshModule::modules; -const MeshPacket *MeshModule::currentRequest; +const meshtastic_MeshPacket *MeshModule::currentRequest; /** * If any of the current chain of modules has already sent a reply, it will be here. This is useful to allow * the RoutingPlugin to avoid sending redundant acks */ -MeshPacket *MeshModule::currentReply; +meshtastic_MeshPacket *MeshModule::currentReply; MeshModule::MeshModule(const char *_name) : name(_name) { @@ -32,21 +32,22 @@ MeshModule::~MeshModule() assert(0); // FIXME - remove from list of modules once someone needs this feature } -MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex) +meshtastic_MeshPacket *MeshModule::allocAckNak(meshtastic_Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex) { - Routing c = Routing_init_default; + meshtastic_Routing c = meshtastic_Routing_init_default; c.error_reason = err; - c.which_variant = Routing_error_reason_tag; + c.which_variant = meshtastic_Routing_error_reason_tag; // Now that we have moded sendAckNak up one level into the class heirarchy we can no longer assume we are a RoutingPlugin // So we manually call pb_encode_to_bytes and specify routing port number // auto p = allocDataProtobuf(c); - MeshPacket *p = router->allocForSending(); - p->decoded.portnum = PortNum_ROUTING_APP; - p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Routing_msg, &c); + meshtastic_MeshPacket *p = router->allocForSending(); + p->decoded.portnum = meshtastic_PortNum_ROUTING_APP; + p->decoded.payload.size = + pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &meshtastic_Routing_msg, &c); - p->priority = MeshPacket_Priority_ACK; + p->priority = meshtastic_MeshPacket_Priority_ACK; p->hop_limit = config.lora.hop_limit; // Flood ACK back to original sender p->to = to; @@ -57,7 +58,7 @@ MeshPacket *MeshModule::allocAckNak(Routing_Error err, NodeNum to, PacketId idFr return p; } -MeshPacket *MeshModule::allocErrorResponse(Routing_Error err, const MeshPacket *p) +meshtastic_MeshPacket *MeshModule::allocErrorResponse(meshtastic_Routing_Error err, const meshtastic_MeshPacket *p) { auto r = allocAckNak(err, getFrom(p), p->id, p->channel); @@ -66,13 +67,13 @@ MeshPacket *MeshModule::allocErrorResponse(Routing_Error err, const MeshPacket * return r; } -void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) +void MeshModule::callPlugins(const meshtastic_MeshPacket &mp, RxSource src) { // LOG_DEBUG("In call modules\n"); bool moduleFound = false; // We now allow **encrypted** packets to pass through the modules - bool isDecoded = mp.which_payload_variant == MeshPacket_decoded_tag; + bool isDecoded = mp.which_payload_variant == meshtastic_MeshPacket_decoded_tag; currentReply = NULL; // No reply yet @@ -101,13 +102,13 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) moduleFound = true; /// received channel (or NULL if not decoded) - Channel *ch = isDecoded ? &channels.getByIndex(mp.channel) : NULL; + meshtastic_Channel *ch = isDecoded ? &channels.getByIndex(mp.channel) : NULL; /// 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); @@ -117,7 +118,7 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) if (mp.decoded.want_response) { printPacket("packet on wrong channel, returning error", &mp); - currentReply = pi.allocErrorResponse(Routing_Error_NOT_AUTHORIZED, &mp); + currentReply = pi.allocErrorResponse(meshtastic_Routing_Error_NOT_AUTHORIZED, &mp); } else printPacket("packet on wrong channel, but can't respond", &mp); } else { @@ -161,7 +162,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 @@ -170,17 +171,16 @@ void MeshModule::callPlugins(const MeshPacket &mp, RxSource src) // SECURITY NOTE! I considered sending back a different error code if we didn't find the psk (i.e. !isDecoded) // but opted NOT TO. Because it is not a good idea to let remote nodes 'probe' to find out which PSKs were "good" vs // bad. - routingModule->sendAckNak(Routing_Error_NO_RESPONSE, getFrom(&mp), mp.id, mp.channel); + routingModule->sendAckNak(meshtastic_Routing_Error_NO_RESPONSE, getFrom(&mp), mp.id, mp.channel); } } 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() +meshtastic_MeshPacket *MeshModule::allocReply() { auto r = myReply; myReply = NULL; // Only use each reply once @@ -191,7 +191,7 @@ MeshPacket *MeshModule::allocReply() * so that subclasses can (optionally) send a response back to the original sender. Implementing this method * is optional */ -void MeshModule::sendResponse(const MeshPacket &req) +void MeshModule::sendResponse(const meshtastic_MeshPacket &req) { auto r = allocReply(); if (r) { @@ -206,16 +206,16 @@ void MeshModule::sendResponse(const MeshPacket &req) /** set the destination and packet parameters of packet p intended as a reply to a particular "to" packet * This ensures that if the request packet was sent reliably, the reply is sent that way as well. */ -void setReplyTo(MeshPacket *p, const MeshPacket &to) +void setReplyTo(meshtastic_MeshPacket *p, const meshtastic_MeshPacket &to) { - assert(p->which_payload_variant == MeshPacket_decoded_tag); // Should already be set by now + assert(p->which_payload_variant == meshtastic_MeshPacket_decoded_tag); // Should already be set by now p->to = getFrom(&to); // Make sure that if we are sending to the local node, we use our local node addr, not 0 p->channel = to.channel; // Use the same channel that the request came in on // No need for an ack if we are just delivering locally (it just generates an ignored ack) p->want_ack = (to.from != 0) ? to.want_ack : false; - if (p->priority == MeshPacket_Priority_UNSET) - p->priority = MeshPacket_Priority_RELIABLE; + if (p->priority == meshtastic_MeshPacket_Priority_UNSET) + p->priority = meshtastic_MeshPacket_Priority_RELIABLE; p->decoded.request_id = to.id; } @@ -235,14 +235,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 +249,20 @@ void MeshModule::observeUIEvents( } } -AdminMessageHandleResult MeshModule::handleAdminMessageForAllPlugins(const MeshPacket &mp, AdminMessage *request, AdminMessage *response) +AdminMessageHandleResult MeshModule::handleAdminMessageForAllPlugins(const meshtastic_MeshPacket &mp, + meshtastic_AdminMessage *request, + meshtastic_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..c6550f3d9 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, @@ -66,14 +64,18 @@ class MeshModule /** For use only by MeshService */ - static void callPlugins(const MeshPacket &mp, RxSource src = RX_SRC_RADIO); + static void callPlugins(const meshtastic_MeshPacket &mp, RxSource src = RX_SRC_RADIO); static std::vector GetMeshModulesWithUIFrames(); static void observeUIEvents(Observer *observer); - static AdminMessageHandleResult handleAdminMessageForAllPlugins( - const MeshPacket &mp, AdminMessage *request, AdminMessage *response); + static AdminMessageHandleResult handleAdminMessageForAllPlugins(const meshtastic_MeshPacket &mp, + meshtastic_AdminMessage *request, + meshtastic_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; @@ -107,12 +109,12 @@ class MeshModule * Note: this can be static because we are guaranteed to be processing only one * plumodulegin at a time. */ - static const MeshPacket *currentRequest; + static const meshtastic_MeshPacket *currentRequest; /** * If your handler wants to send a response, simply set currentReply and it will be sent at the end of response handling. */ - MeshPacket *myReply = NULL; + meshtastic_MeshPacket *myReply = NULL; /** * Initialize your module. This setup function is called once after all hardware and mesh protocol layers have @@ -123,13 +125,17 @@ class MeshModule /** * @return true if you want to receive the specified portnum */ - virtual bool wantPacket(const MeshPacket *p) = 0; + virtual bool wantPacket(const meshtastic_MeshPacket *p) = 0; /** 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 meshtastic_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. @@ -137,38 +143,48 @@ class MeshModule * Note: most implementers don't need to override this, instead: If while handling a request you have a reply, just set * the protected reply field in this instance. * */ - virtual MeshPacket *allocReply(); + virtual meshtastic_MeshPacket *allocReply(); /*** * @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); + meshtastic_MeshPacket *allocAckNak(meshtastic_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); + meshtastic_MeshPacket *allocErrorResponse(meshtastic_Routing_Error err, const meshtastic_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 meshtastic_MeshPacket &mp, + meshtastic_AdminMessage *request, + meshtastic_AdminMessage *response) + { + return AdminMessageHandleResult::NOT_HANDLED; + }; private: /** * If any of the current chain of modules has already sent a reply, it will be here. This is useful to allow * the RoutingModule to avoid sending redundant acks */ - static MeshPacket *currentReply; + static meshtastic_MeshPacket *currentReply; friend class ReliableRouter; @@ -176,10 +192,10 @@ class MeshModule * so that subclasses can (optionally) send a response back to the original sender. This method calls allocReply() * to generate the reply message, and if !NULL that message will be delivered to whoever sent req */ - void sendResponse(const MeshPacket &req); + void sendResponse(const meshtastic_MeshPacket &req); }; /** set the destination and packet parameters of packet p intended as a reply to a particular "to" packet * This ensures that if the request packet was sent reliably, the reply is sent that way as well. */ -void setReplyTo(MeshPacket *p, const MeshPacket &to); +void setReplyTo(meshtastic_MeshPacket *p, const meshtastic_MeshPacket &to); diff --git a/src/mesh/MeshPacketQueue.cpp b/src/mesh/MeshPacketQueue.cpp index 9af381a0e..24756fd2a 100644 --- a/src/mesh/MeshPacketQueue.cpp +++ b/src/mesh/MeshPacketQueue.cpp @@ -1,18 +1,18 @@ -#include "configuration.h" #include "MeshPacketQueue.h" +#include "configuration.h" #include #include /// @return the priority of the specified packet -inline uint32_t getPriority(const MeshPacket *p) +inline uint32_t getPriority(const meshtastic_MeshPacket *p) { auto pri = p->priority; return pri; } /// @return "true" if "p1" is ordered before "p2" -bool CompareMeshPacketFunc(const MeshPacket *p1, const MeshPacket *p2) +bool CompareMeshPacketFunc(const meshtastic_MeshPacket *p1, const meshtastic_MeshPacket *p2) { assert(p1 && p2); auto p1p = getPriority(p1), p2p = getPriority(p2); @@ -26,27 +26,29 @@ bool CompareMeshPacketFunc(const MeshPacket *p1, const MeshPacket *p2) MeshPacketQueue::MeshPacketQueue(size_t _maxLen) : maxLen(_maxLen) {} -bool MeshPacketQueue::empty() { +bool MeshPacketQueue::empty() +{ return queue.empty(); } /** * Some clients might not properly set priority, therefore we fix it here. */ -void fixPriority(MeshPacket *p) +void fixPriority(meshtastic_MeshPacket *p) { // We might receive acks from other nodes (and since generated remotely, they won't have priority assigned. Check for that // and fix it - if (p->priority == MeshPacket_Priority_UNSET) { + if (p->priority == meshtastic_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 == meshtastic_PortNum_ROUTING_APP) + ? meshtastic_MeshPacket_Priority_ACK + : (p->want_ack ? meshtastic_MeshPacket_Priority_RELIABLE : meshtastic_MeshPacket_Priority_DEFAULT); } } /** enqueue a packet, return false if full */ -bool MeshPacketQueue::enqueue(MeshPacket *p) +bool MeshPacketQueue::enqueue(meshtastic_MeshPacket *p) { fixPriority(p); @@ -60,7 +62,7 @@ bool MeshPacketQueue::enqueue(MeshPacket *p) return true; } -MeshPacket *MeshPacketQueue::dequeue() +meshtastic_MeshPacket *MeshPacketQueue::dequeue() { if (empty()) { return NULL; @@ -73,7 +75,7 @@ MeshPacket *MeshPacketQueue::dequeue() return p; } -MeshPacket *MeshPacketQueue::getFront() +meshtastic_MeshPacket *MeshPacketQueue::getFront() { if (empty()) { return NULL; @@ -84,7 +86,7 @@ MeshPacket *MeshPacketQueue::getFront() } /** Attempt to find and remove a packet from this queue. Returns a pointer to the removed packet, or NULL if not found */ -MeshPacket *MeshPacketQueue::remove(NodeNum from, PacketId id) +meshtastic_MeshPacket *MeshPacketQueue::remove(NodeNum from, PacketId id) { for (auto it = queue.begin(); it != queue.end(); it++) { auto p = (*it); @@ -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(meshtastic_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..3c28fc5ce 100644 --- a/src/mesh/MeshPacketQueue.h +++ b/src/mesh/MeshPacketQueue.h @@ -4,23 +4,23 @@ #include - /** * A priority queue of packets */ class MeshPacketQueue { size_t maxLen; - std::vector queue; + std::vector queue; - /** Replace a lower priority package in the queue with 'mp' (provided there are lower pri packages). Return true if replaced. */ - bool replaceLowerPriorityPacket(MeshPacket *mp); + /** Replace a lower priority package in the queue with 'mp' (provided there are lower pri packages). Return true if replaced. + */ + bool replaceLowerPriorityPacket(meshtastic_MeshPacket *mp); public: explicit MeshPacketQueue(size_t _maxLen); /** enqueue a packet, return false if full */ - bool enqueue(MeshPacket *p); + bool enqueue(meshtastic_MeshPacket *p); /** return true if the queue is empty */ bool empty(); @@ -31,10 +31,10 @@ class MeshPacketQueue /** return total size of the Queue */ size_t getMaxLen() { return maxLen; } - MeshPacket *dequeue(); + meshtastic_MeshPacket *dequeue(); - MeshPacket *getFront(); + meshtastic_MeshPacket *getFront(); /** Attempt to find and remove a packet from this queue. Returns the packet which was removed from the queue */ - MeshPacket *remove(NodeNum from, PacketId id); + meshtastic_MeshPacket *remove(NodeNum from, PacketId id); }; diff --git a/src/mesh/MeshRadio.h b/src/mesh/MeshRadio.h index 2cb7f4e6d..f2514eea1 100644 --- a/src/mesh/MeshRadio.h +++ b/src/mesh/MeshRadio.h @@ -7,7 +7,7 @@ // Map from old region names to new region enums struct RegionInfo { - Config_LoRaConfig_RegionCode code; + meshtastic_Config_LoRaConfig_RegionCode code; float freqStart; float freqEnd; float dutyCycle; diff --git a/src/mesh/MeshService.cpp b/src/mesh/MeshService.cpp index 9a6fa984c..85a6390c9 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" @@ -51,15 +51,15 @@ FIXME in the initial proof of concept we just skip the entire want/deny flow and MeshService service; -static MemoryDynamic staticQueueStatusPool; +static MemoryDynamic staticQueueStatusPool; -Allocator &queueStatusPool = staticQueueStatusPool; +Allocator &queueStatusPool = staticQueueStatusPool; #include "Router.h" MeshService::MeshService() : toPhoneQueue(MAX_RX_TOPHONE), toPhoneQueueStatusQueue(MAX_RX_TOPHONE) { - lastQueueStatus = { 0, 0, 16, 0 }; + lastQueueStatus = {0, 0, 16, 0}; } void MeshService::init() @@ -71,14 +71,14 @@ void MeshService::init() gpsObserver.observe(&gps->newStatus); } -int MeshService::handleFromRadio(const MeshPacket *mp) +int MeshService::handleFromRadio(const meshtastic_MeshPacket *mp) { powerFSM.trigger(EVENT_PACKET_FOR_PHONE); // Possibly keep the node from sleeping printPacket("Forwarding to phone", mp); nodeDB.updateFrom(*mp); // update our DB state based off sniffing every RX packet from the radio - sendToPhone((MeshPacket *)mp); + sendToPhone((meshtastic_MeshPacket *)mp); return 0; } @@ -87,7 +87,7 @@ int MeshService::handleFromRadio(const MeshPacket *mp) void MeshService::loop() { if (lastQueueStatus.free == 0) { // check if there is now free space in TX queue - QueueStatus qs = router->getQueueStatus(); + meshtastic_QueueStatus qs = router->getQueueStatus(); if (qs.free != lastQueueStatus.free) (void)sendQueueStatusToPhone(qs, 0, 0); } @@ -130,31 +130,32 @@ void MeshService::reloadOwner(bool shouldSave) * Called by PhoneAPI.handleToRadio. Note: p is a scratch buffer, this function is allowed to write to it but it can not keep a * reference */ -void MeshService::handleToRadio(MeshPacket &p) +void MeshService::handleToRadio(meshtastic_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) { + if (p.decoded.portnum == meshtastic_PortNum_SIMULATOR_APP) { // Simulator packet (=Compressed packet) is encapsulated in a MeshPacket, so need to unwrap first - Compressed scratch; - Compressed *decoded = NULL; - if (p.which_payload_variant == MeshPacket_decoded_tag) { + meshtastic_Compressed scratch; + meshtastic_Compressed *decoded = NULL; + if (p.which_payload_variant == meshtastic_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, &meshtastic_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; @@ -187,16 +188,16 @@ bool MeshService::cancelSending(PacketId id) return router->cancelSending(nodeDB.getNodeNum(), id); } -ErrorCode MeshService::sendQueueStatusToPhone(const QueueStatus &qs, ErrorCode res, uint32_t mesh_packet_id) +ErrorCode MeshService::sendQueueStatusToPhone(const meshtastic_QueueStatus &qs, ErrorCode res, uint32_t mesh_packet_id) { - QueueStatus *copied = queueStatusPool.allocCopy(qs); + meshtastic_QueueStatus *copied = queueStatusPool.allocCopy(qs); copied->res = res; copied->mesh_packet_id = mesh_packet_id; if (toPhoneQueueStatusQueue.numFree() == 0) { LOG_DEBUG("NOTE: tophone queue status queue is full, discarding oldest\n"); - QueueStatus *d = toPhoneQueueStatusQueue.dequeuePtr(0); + meshtastic_QueueStatus *d = toPhoneQueueStatusQueue.dequeuePtr(0); if (d) releaseQueueStatusToPool(d); } @@ -209,7 +210,7 @@ ErrorCode MeshService::sendQueueStatusToPhone(const QueueStatus &qs, ErrorCode r return res ? ERRNO_OK : ERRNO_UNKNOWN; } -void MeshService::sendToMesh(MeshPacket *p, RxSource src, bool ccToPhone) +void MeshService::sendToMesh(meshtastic_MeshPacket *p, RxSource src, bool ccToPhone) { uint32_t mesh_packet_id = p->id; nodeDB.updateFrom(*p); // update our local DB for this packet (because phone might have sent position packets etc...) @@ -219,7 +220,7 @@ void MeshService::sendToMesh(MeshPacket *p, RxSource src, bool ccToPhone) /* NOTE(pboldin): Prepare and send QueueStatus message to the phone as a * high-priority message. */ - QueueStatus qs = router->getQueueStatus(); + meshtastic_QueueStatus qs = router->getQueueStatus(); ErrorCode r = sendQueueStatusToPhone(qs, res, mesh_packet_id); if (r != ERRNO_OK) { LOG_DEBUG("Can't send status to phone"); @@ -232,7 +233,7 @@ void MeshService::sendToMesh(MeshPacket *p, RxSource src, bool ccToPhone) void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies) { - NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); + meshtastic_NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); assert(node); if (node->has_position && (node->position.latitude_i != 0 || node->position.longitude_i != 0)) { @@ -248,24 +249,24 @@ void MeshService::sendNetworkPing(NodeNum dest, bool wantReplies) } } -void MeshService::sendToPhone(MeshPacket *p) +void MeshService::sendToPhone(meshtastic_MeshPacket *p) { if (toPhoneQueue.numFree() == 0) { LOG_WARN("ToPhone queue is full, discarding oldest\n"); - MeshPacket *d = toPhoneQueue.dequeuePtr(0); + meshtastic_MeshPacket *d = toPhoneQueue.dequeuePtr(0); if (d) releaseToPool(d); } - MeshPacket *copied = packetPool.allocCopy(*p); + meshtastic_MeshPacket *copied = packetPool.allocCopy(*p); perhapsDecode(copied); assert(toPhoneQueue.enqueue(copied, 0)); fromNum++; } -NodeInfo *MeshService::refreshMyNodeInfo() +meshtastic_NodeInfo *MeshService::refreshMyNodeInfo() { - NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); + meshtastic_NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); assert(node); // We might not have a position yet for our local node, in that case, at least try to send the time @@ -274,7 +275,7 @@ NodeInfo *MeshService::refreshMyNodeInfo() node->has_position = true; } - Position &position = node->position; + meshtastic_Position &position = node->position; // Update our local node info with our time (even if we don't decide to update anyone else) node->last_heard = @@ -290,8 +291,8 @@ NodeInfo *MeshService::refreshMyNodeInfo() int MeshService::onGPSChanged(const meshtastic::GPSStatus *newStatus) { // Update our local node info with our position (even if we don't decide to update anyone else) - NodeInfo *node = refreshMyNodeInfo(); - Position pos = Position_init_default; + meshtastic_NodeInfo *node = refreshMyNodeInfo(); + meshtastic_Position pos = meshtastic_Position_init_default; if (newStatus->getHasLock()) { // load data from GPS object, will add timestamp + battery further down @@ -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..b8abac80d 100644 --- a/src/mesh/MeshService.h +++ b/src/mesh/MeshService.h @@ -14,7 +14,7 @@ #include "../platform/portduino/SimRadio.h" #endif -extern Allocator &queueStatusPool; +extern Allocator &queueStatusPool; /** * Top level app for this service. keeps the mesh, the radio config and the queue of received packets. @@ -29,13 +29,13 @@ class MeshService /// FIXME, change to a DropOldestQueue and keep a count of the number of dropped packets to ensure /// we never hang because android hasn't been there in a while /// FIXME - save this to flash on deep sleep - PointerQueue toPhoneQueue; + PointerQueue toPhoneQueue; // keep list of QueueStatus packets to be send to the phone - PointerQueue toPhoneQueueStatusQueue; + PointerQueue toPhoneQueueStatusQueue; // This holds the last QueueStatus send - QueueStatus lastQueueStatus; + meshtastic_QueueStatus lastQueueStatus; /// The current nonce for the newest packet which has been queued for the phone uint32_t fromNum = 0; @@ -59,28 +59,28 @@ class MeshService /// Return the next packet destined to the phone. FIXME, somehow use fromNum to allow the phone to retry the /// last few packets if needs to. - MeshPacket *getForPhone() { return toPhoneQueue.dequeuePtr(0); } + meshtastic_MeshPacket *getForPhone() { return toPhoneQueue.dequeuePtr(0); } /// Allows the bluetooth handler to free packets after they have been sent - void releaseToPool(MeshPacket *p) { packetPool.release(p); } + void releaseToPool(meshtastic_MeshPacket *p) { packetPool.release(p); } /// Return the next QueueStatus packet destined to the phone. - QueueStatus *getQueueStatusForPhone() { return toPhoneQueueStatusQueue.dequeuePtr(0); } + meshtastic_QueueStatus *getQueueStatusForPhone() { return toPhoneQueueStatusQueue.dequeuePtr(0); } // Release QueueStatus packet to pool - void releaseQueueStatusToPool(QueueStatus *p) { queueStatusPool.release(p); } + void releaseQueueStatusToPool(meshtastic_QueueStatus *p) { queueStatusPool.release(p); } /** * Given a ToRadio buffer parse it and properly handle it (setup radio, owner or send packet into the mesh) * Called by PhoneAPI.handleToRadio. Note: p is a scratch buffer, this function is allowed to write to it but it can not keep * a reference */ - void handleToRadio(MeshPacket &p); + void handleToRadio(meshtastic_MeshPacket &p); /** 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); @@ -92,16 +92,16 @@ class MeshService /// Send a packet into the mesh - note p must have been allocated from packetPool. We will return it to that pool after /// sending. This is the ONLY function you should use for sending messages into the mesh, because it also updates the nodedb /// cache - void sendToMesh(MeshPacket *p, RxSource src = RX_SRC_LOCAL, bool ccToPhone = false); + void sendToMesh(meshtastic_MeshPacket *p, RxSource src = RX_SRC_LOCAL, bool ccToPhone = false); /** Attempt to cancel a previously sent packet from this _local_ node. Returns true if a packet was found we could cancel */ bool cancelSending(PacketId id); /// Pull the latest power and time info into my nodeinfo - NodeInfo *refreshMyNodeInfo(); + meshtastic_NodeInfo *refreshMyNodeInfo(); - /// Send a packet to the phone - void sendToPhone(MeshPacket *p); + /// Send a packet to the phone + void sendToPhone(meshtastic_MeshPacket *p); bool isToPhoneQueueEmpty(); @@ -112,10 +112,10 @@ class MeshService /// Handle a packet that just arrived from the radio. This method does _ReliableRouternot_ free the provided packet. If it /// needs to keep the packet around it makes a copy - int handleFromRadio(const MeshPacket *p); + int handleFromRadio(const meshtastic_MeshPacket *p); friend class RoutingModule; - ErrorCode sendQueueStatusToPhone(const QueueStatus &qs, ErrorCode res, uint32_t mesh_packet_id); + ErrorCode sendQueueStatusToPhone(const meshtastic_QueueStatus &qs, ErrorCode res, uint32_t mesh_packet_id); }; extern MeshService service; diff --git a/src/mesh/MeshTypes.h b/src/mesh/MeshTypes.h index c08637385..ee23b9158 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 }; /** @@ -39,10 +39,10 @@ enum RxSource { typedef int ErrorCode; /// Alloc and free packets to our global, ISR safe pool -extern Allocator &packetPool; +extern Allocator &packetPool; /** * Most (but not always) of the time we want to treat packets 'from' the local phone (where from == 0), as if they originated on * the local node. If from is zero this function returns our node number instead */ -NodeNum getFrom(const MeshPacket *p); \ No newline at end of file +NodeNum getFrom(const meshtastic_MeshPacket *p); \ No newline at end of file diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index 076f56af6..37697bc18 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" @@ -32,12 +32,12 @@ NodeDB nodeDB; // we have plenty of ram so statically alloc this tempbuf (for now) -EXT_RAM_ATTR DeviceState devicestate; -MyNodeInfo &myNodeInfo = devicestate.my_node; -LocalConfig config; -LocalModuleConfig moduleConfig; -ChannelFile channelFile; -OEMStore oemStore; +EXT_RAM_ATTR meshtastic_DeviceState devicestate; +meshtastic_MyNodeInfo &myNodeInfo = devicestate.my_node; +meshtastic_LocalConfig config; +meshtastic_LocalModuleConfig moduleConfig; +meshtastic_ChannelFile channelFile; +meshtastic_OEMStore oemStore; /** The current change # for radio settings. Starts at 0 on boot and any time the radio settings * might have changed is incremented. Allows others to detect they might now be on a new channel. @@ -53,7 +53,7 @@ extern void getMacAddr(uint8_t *dmac); * But there are some special ids used when we haven't yet been configured by a user. In that case * we use !macaddr (no colons). */ -User &owner = devicestate.owner; +meshtastic_User &owner = devicestate.owner; static uint8_t ourMacAddr[6]; @@ -69,7 +69,7 @@ NodeDB::NodeDB() : nodes(devicestate.node_db), numNodes(&devicestate.node_db_cou * Most (but not always) of the time we want to treat packets 'from' the local phone (where from == 0), as if they originated on * the local node. If from is zero this function returns our node number instead */ -NodeNum getFrom(const MeshPacket *p) +NodeNum getFrom(const meshtastic_MeshPacket *p) { return (p->from == 0) ? nodeDB.getNodeNum() : p->from; } @@ -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) { @@ -102,7 +102,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) config.power.wait_bluetooth_secs = 10; config.position.position_broadcast_secs = 6 * 60; config.power.ls_secs = 60; - config.lora.region = Config_LoRaConfig_RegionCode_TW; + config.lora.region = meshtastic_Config_LoRaConfig_RegionCode_TW; // Enter super deep sleep soon and stay there not very long // radioConfig.preferences.mesh_sds_timeout_secs = 10; @@ -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) @@ -151,7 +151,7 @@ bool NodeDB::factoryReset() void NodeDB::installDefaultConfig() { LOG_INFO("Installing default LocalConfig\n"); - memset(&config, 0, sizeof(LocalConfig)); + memset(&config, 0, sizeof(meshtastic_LocalConfig)); config.version = DEVICESTATE_CUR_VER; config.has_device = true; config.has_display = true; @@ -160,10 +160,13 @@ 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.region = Config_LoRaConfig_RegionCode_UNSET; - config.lora.modem_preset = Config_LoRaConfig_ModemPreset_LONG_FAST; + config.device.rebroadcast_mode = meshtastic_Config_DeviceConfig_RebroadcastMode_ALL; + config.lora.sx126x_rx_boosted_gain = 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 = meshtastic_Config_LoRaConfig_RegionCode_UNSET; + config.lora.modem_preset = meshtastic_Config_LoRaConfig_ModemPreset_LONG_FAST; config.lora.hop_limit = HOP_RELIABLE; config.position.gps_enabled = true; config.position.position_broadcast_smart_enabled = true; @@ -178,14 +181,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 ? meshtastic_Config_BluetoothConfig_PairingMode_RANDOM_PIN + : meshtastic_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 = + (meshtastic_Config_PositionConfig_PositionFlags_ALTITUDE | meshtastic_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,15 +201,15 @@ 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; } void NodeDB::installDefaultModuleConfig() { LOG_INFO("Installing default ModuleConfig\n"); - memset(&moduleConfig, 0, sizeof(ModuleConfig)); - + memset(&moduleConfig, 0, sizeof(meshtastic_ModuleConfig)); + moduleConfig.version = DEVICESTATE_CUR_VER; moduleConfig.has_mqtt = true; moduleConfig.has_range_test = true; @@ -221,7 +226,26 @@ void NodeDB::installDefaultModuleConfig() initModuleConfigIntervals(); } -void NodeDB::initModuleConfigIntervals() +void NodeDB::installRoleDefaults(meshtastic_Config_DeviceConfig_Role role) +{ + if (role == meshtastic_Config_DeviceConfig_Role_ROUTER) { + initConfigIntervals(); + initModuleConfigIntervals(); + } else if (role == meshtastic_Config_DeviceConfig_Role_REPEATER) { + config.display.screen_on_secs = 1; + meshtastic_Channel &ch = channels.getByIndex(channels.getPrimaryIndex()); + meshtastic_ChannelSettings &channelSettings = ch.settings; + uint8_t defaultpskIndex = 1; + channelSettings.psk.bytes[0] = defaultpskIndex; + channelSettings.psk.size = 1; + } else if (role == meshtastic_Config_DeviceConfig_Role_TRACKER) { + config.position.position_broadcast_smart_enabled = false; + config.position.position_broadcast_secs = 120; + config.position.gps_update_interval = 60; + } +} + +void NodeDB::initModuleConfigIntervals() { moduleConfig.telemetry.device_update_interval = default_broadcast_interval_secs; moduleConfig.telemetry.environment_update_interval = default_broadcast_interval_secs; @@ -230,7 +254,7 @@ void NodeDB::initModuleConfigIntervals() void NodeDB::installDefaultChannels() { LOG_INFO("Installing default ChannelFile\n"); - memset(&channelFile, 0, sizeof(ChannelFile)); + memset(&channelFile, 0, sizeof(meshtastic_ChannelFile)); channelFile.version = DEVICESTATE_CUR_VER; } @@ -244,10 +268,10 @@ void NodeDB::resetNodes() void NodeDB::installDefaultDeviceState() { LOG_INFO("Installing default DeviceState\n"); - memset(&devicestate, 0, sizeof(DeviceState)); + memset(&devicestate, 0, sizeof(meshtastic_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 +309,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 = + meshtastic_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 @@ -299,7 +324,7 @@ void NodeDB::init() owner.hw_model = HW_VENDOR; // Include our owner in the node db under our nodenum - NodeInfo *info = getOrCreateNode(getNodeNum()); + meshtastic_NodeInfo *info = getOrCreateNode(getNodeNum()); info->user = owner; info->has_user = true; @@ -348,7 +373,7 @@ void NodeDB::pickNewNodeNum() if (r == NODENUM_BROADCAST || r < NUM_RESERVED) r = NUM_RESERVED; // don't pick a reserved node number - NodeInfo *found; + meshtastic_NodeInfo *found; while ((found = getNode(r)) && memcmp(found->user.macaddr, owner.macaddr, sizeof(owner.macaddr))) { NodeNum n = random(NUM_RESERVED, NODENUM_BROADCAST); // try a new random choice LOG_DEBUG("NOTE! Our desired nodenum 0x%x is in use, so trying for 0x%x\n", r, n); @@ -364,7 +389,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) { @@ -400,7 +424,8 @@ bool NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, c void NodeDB::loadFromDisk() { // static DeviceState scratch; We no longer read into a tempbuf because this structure is 15KB of valuable RAM - if (!loadProto(prefFileName, DeviceState_size, sizeof(DeviceState), &DeviceState_msg, &devicestate)) { + if (!loadProto(prefFileName, meshtastic_DeviceState_size, sizeof(meshtastic_DeviceState), &meshtastic_DeviceState_msg, + &devicestate)) { installDefaultDeviceState(); // Our in RAM copy might now be corrupt } else { if (devicestate.version < DEVICESTATE_MIN_VER) { @@ -411,7 +436,8 @@ void NodeDB::loadFromDisk() } } - if (!loadProto(configFileName, LocalConfig_size, sizeof(LocalConfig), &LocalConfig_msg, &config)) { + if (!loadProto(configFileName, meshtastic_LocalConfig_size, sizeof(meshtastic_LocalConfig), &meshtastic_LocalConfig_msg, + &config)) { installDefaultConfig(); // Our in RAM copy might now be corrupt } else { if (config.version < DEVICESTATE_MIN_VER) { @@ -422,7 +448,8 @@ void NodeDB::loadFromDisk() } } - if (!loadProto(moduleConfigFileName, LocalModuleConfig_size, sizeof(LocalModuleConfig), &LocalModuleConfig_msg, &moduleConfig)) { + if (!loadProto(moduleConfigFileName, meshtastic_LocalModuleConfig_size, sizeof(meshtastic_LocalModuleConfig), + &meshtastic_LocalModuleConfig_msg, &moduleConfig)) { installDefaultModuleConfig(); // Our in RAM copy might now be corrupt } else { if (moduleConfig.version < DEVICESTATE_MIN_VER) { @@ -433,7 +460,8 @@ void NodeDB::loadFromDisk() } } - if (!loadProto(channelFileName, ChannelFile_size, sizeof(ChannelFile), &ChannelFile_msg, &channelFile)) { + if (!loadProto(channelFileName, meshtastic_ChannelFile_size, sizeof(meshtastic_ChannelFile), &meshtastic_ChannelFile_msg, + &channelFile)) { installDefaultChannels(); // Our in RAM copy might now be corrupt } else { if (channelFile.version < DEVICESTATE_MIN_VER) { @@ -444,7 +472,7 @@ void NodeDB::loadFromDisk() } } - if (loadProto(oemConfigFile, OEMStore_size, sizeof(OEMStore), &OEMStore_msg, &oemStore)) + if (loadProto(oemConfigFile, meshtastic_OEMStore_size, sizeof(meshtastic_OEMStore), &meshtastic_OEMStore_msg, &oemStore)) LOG_INFO("Loaded OEMStore\n"); } @@ -478,9 +506,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 @@ -497,17 +525,17 @@ void NodeDB::saveChannelsToDisk() #ifdef FSCom FSCom.mkdir("/prefs"); #endif - saveProto(channelFileName, ChannelFile_size, &ChannelFile_msg, &channelFile); + saveProto(channelFileName, meshtastic_ChannelFile_size, &meshtastic_ChannelFile_msg, &channelFile); } } -void NodeDB::saveDeviceStateToDisk() +void NodeDB::saveDeviceStateToDisk() { if (!devicestate.no_save) { #ifdef FSCom FSCom.mkdir("/prefs"); #endif - saveProto(prefFileName, DeviceState_size, &DeviceState_msg, &devicestate); + saveProto(prefFileName, meshtastic_DeviceState_size, &meshtastic_DeviceState_msg, &devicestate); } } @@ -529,7 +557,7 @@ void NodeDB::saveToDisk(int saveWhat) config.has_power = true; config.has_network = true; config.has_bluetooth = true; - saveProto(configFileName, LocalConfig_size, &LocalConfig_msg, &config); + saveProto(configFileName, meshtastic_LocalConfig_size, &meshtastic_LocalConfig_msg, &config); } if (saveWhat & SEGMENT_MODULECONFIG) { @@ -540,7 +568,7 @@ void NodeDB::saveToDisk(int saveWhat) moduleConfig.has_serial = true; moduleConfig.has_store_forward = true; moduleConfig.has_telemetry = true; - saveProto(moduleConfigFileName, LocalModuleConfig_size, &LocalModuleConfig_msg, &moduleConfig); + saveProto(moduleConfigFileName, meshtastic_LocalModuleConfig_size, &meshtastic_LocalModuleConfig_msg, &moduleConfig); } if (saveWhat & SEGMENT_CHANNELS) { @@ -551,7 +579,7 @@ void NodeDB::saveToDisk(int saveWhat) } } -const NodeInfo *NodeDB::readNextInfo() +const meshtastic_NodeInfo *NodeDB::readNextInfo() { if (readPointer < *numNodes) return &nodes[readPointer++]; @@ -560,7 +588,7 @@ const NodeInfo *NodeDB::readNextInfo() } /// Given a node, return how many seconds in the past (vs now) that we last heard from it -uint32_t sinceLastSeen(const NodeInfo *n) +uint32_t sinceLastSeen(const meshtastic_NodeInfo *n) { uint32_t now = getTime(); @@ -589,9 +617,9 @@ size_t NodeDB::getNumOnlineNodes() /** Update position info for this node based on received position data */ -void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src) +void NodeDB::updatePosition(uint32_t nodeId, const meshtastic_Position &p, RxSource src) { - NodeInfo *info = getOrCreateNode(nodeId); + meshtastic_NodeInfo *info = getOrCreateNode(nodeId); if (!info) { return; } @@ -599,15 +627,13 @@ 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) { // FIXME SPECIAL TIME SETTING PACKET FROM EUD TO RADIO // (stop-gap fix for issue #900) LOG_DEBUG("updatePosition SPECIAL time setting time=%u\n", p.time); info->position.time = p.time; - } else { // Be careful to only update fields that have been set by the REMOTE sender // A lot of position reports don't have time populated. In that case, be careful to not blow away the time we @@ -634,11 +660,11 @@ void NodeDB::updatePosition(uint32_t nodeId, const Position &p, RxSource src) /** Update telemetry info for this node based on received metrics * We only care about device telemetry here */ -void NodeDB::updateTelemetry(uint32_t nodeId, const Telemetry &t, RxSource src) +void NodeDB::updateTelemetry(uint32_t nodeId, const meshtastic_Telemetry &t, RxSource src) { - NodeInfo *info = getOrCreateNode(nodeId); + meshtastic_NodeInfo *info = getOrCreateNode(nodeId); // Environment metrics should never go to NodeDb but we'll safegaurd anyway - if (!info || t.which_variant != Telemetry_device_metrics_tag) { + if (!info || t.which_variant != meshtastic_Telemetry_device_metrics_tag) { return; } @@ -656,9 +682,9 @@ void NodeDB::updateTelemetry(uint32_t nodeId, const Telemetry &t, RxSource src) /** Update user info for this node based on received user data */ -void NodeDB::updateUser(uint32_t nodeId, const User &p) +void NodeDB::updateUser(uint32_t nodeId, const meshtastic_User &p) { - NodeInfo *info = getOrCreateNode(nodeId); + meshtastic_NodeInfo *info = getOrCreateNode(nodeId); if (!info) { return; } @@ -685,12 +711,12 @@ void NodeDB::updateUser(uint32_t nodeId, const User &p) /// given a subpacket sniffed from the network, update our DB state /// we updateGUI and updateGUIforNode if we think our this change is big enough for a redraw -void NodeDB::updateFrom(const MeshPacket &mp) +void NodeDB::updateFrom(const meshtastic_MeshPacket &mp) { - if (mp.which_payload_variant == MeshPacket_decoded_tag && mp.from) { + if (mp.which_payload_variant == meshtastic_MeshPacket_decoded_tag && mp.from) { LOG_DEBUG("Update DB node 0x%x, rx_time=%u\n", mp.from, mp.rx_time); - NodeInfo *info = getOrCreateNode(getFrom(&mp)); + meshtastic_NodeInfo *info = getOrCreateNode(getFrom(&mp)); if (!info) { return; } @@ -705,7 +731,7 @@ void NodeDB::updateFrom(const MeshPacket &mp) /// Find a node in our DB, return null for missing /// NOTE: This function might be called from an ISR -NodeInfo *NodeDB::getNode(NodeNum n) +meshtastic_NodeInfo *NodeDB::getNode(NodeNum n) { for (int i = 0; i < *numNodes; i++) if (nodes[i].num == n) @@ -715,9 +741,9 @@ NodeInfo *NodeDB::getNode(NodeNum n) } /// Find a node in our DB, create an empty NodeInfo if missing -NodeInfo *NodeDB::getOrCreateNode(NodeNum n) +meshtastic_NodeInfo *NodeDB::getOrCreateNode(NodeNum n) { - NodeInfo *info = getNode(n); + meshtastic_NodeInfo *info = getNode(n); if (!info) { if (*numNodes >= MAX_NUM_NODES) { @@ -749,7 +775,7 @@ NodeInfo *NodeDB::getOrCreateNode(NodeNum n) } /// Record an error that should be reported via analytics -void recordCriticalError(CriticalErrorCode code, uint32_t address, const char *filename) +void recordCriticalError(meshtastic_CriticalErrorCode code, uint32_t address, const char *filename) { // Print error to screen and serial port String lcd = String("Critical error ") + code + "!\n"; diff --git a/src/mesh/NodeDB.h b/src/mesh/NodeDB.h index 991e577c7..106d35402 100644 --- a/src/mesh/NodeDB.h +++ b/src/mesh/NodeDB.h @@ -21,16 +21,16 @@ DeviceState versions used to be defined in the .proto file but really only this #define DEVICESTATE_CUR_VER 20 #define DEVICESTATE_MIN_VER DEVICESTATE_CUR_VER -extern DeviceState devicestate; -extern ChannelFile channelFile; -extern MyNodeInfo &myNodeInfo; -extern LocalConfig config; -extern LocalModuleConfig moduleConfig; -extern OEMStore oemStore; -extern User &owner; +extern meshtastic_DeviceState devicestate; +extern meshtastic_ChannelFile channelFile; +extern meshtastic_MyNodeInfo &myNodeInfo; +extern meshtastic_LocalConfig config; +extern meshtastic_LocalModuleConfig moduleConfig; +extern meshtastic_OEMStore oemStore; +extern meshtastic_User &owner; /// Given a node, return how many seconds in the past (vs now) that we last heard from it -uint32_t sinceLastSeen(const NodeInfo *n); +uint32_t sinceLastSeen(const meshtastic_NodeInfo *n); class NodeDB { @@ -40,14 +40,14 @@ class NodeDB // Eventually use a smarter datastructure // HashMap nodes; // Note: these two references just point into our static array we serialize to/from disk - NodeInfo *nodes; + meshtastic_NodeInfo *nodes; pb_size_t *numNodes; uint32_t readPointer = 0; public: - bool updateGUI = false; // we think the gui should definitely be redrawn, screen will clear this once handled - NodeInfo *updateGUIforNode = NULL; // if currently showing this node, we think you should update the GUI + bool updateGUI = false; // we think the gui should definitely be redrawn, screen will clear this once handled + meshtastic_NodeInfo *updateGUIforNode = NULL; // if currently showing this node, we think you should update the GUI Observable newStatus; /// don't do mesh based algoritm for node id assignment (initially) @@ -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 @@ -70,19 +71,19 @@ class NodeDB /// given a subpacket sniffed from the network, update our DB state /// we updateGUI and updateGUIforNode if we think our this change is big enough for a redraw - void updateFrom(const MeshPacket &p); + void updateFrom(const meshtastic_MeshPacket &p); /** Update position info for this node based on received position data */ - void updatePosition(uint32_t nodeId, const Position &p, RxSource src = RX_SRC_RADIO); + void updatePosition(uint32_t nodeId, const meshtastic_Position &p, RxSource src = RX_SRC_RADIO); /** Update telemetry info for this node based on received metrics */ - void updateTelemetry(uint32_t nodeId, const Telemetry &t, RxSource src = RX_SRC_RADIO); + void updateTelemetry(uint32_t nodeId, const meshtastic_Telemetry &t, RxSource src = RX_SRC_RADIO); /** Update user info for this node based on received user data */ - void updateUser(uint32_t nodeId, const User &p); + void updateUser(uint32_t nodeId, const meshtastic_User &p); /// @return our node number NodeNum getNodeNum() { return myNodeInfo.my_node_num; } @@ -104,15 +105,15 @@ class NodeDB void resetReadPointer() { readPointer = 0; } /// Allow the bluetooth layer to read our next nodeinfo record, or NULL if done reading - const NodeInfo *readNextInfo(); + const meshtastic_NodeInfo *readNextInfo(); /// pick a provisional nodenum we hope no one is using void pickNewNodeNum(); /// Find a node in our DB, return null for missing - NodeInfo *getNode(NodeNum n); + meshtastic_NodeInfo *getNode(NodeNum n); - NodeInfo *getNodeByIndex(size_t x) + meshtastic_NodeInfo *getNodeByIndex(size_t x) { assert(x < *numNodes); return &nodes[x]; @@ -122,15 +123,17 @@ 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); bool saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct); + void installRoleDefaults(meshtastic_Config_DeviceConfig_Role role); + private: /// Find a node in our DB, create an empty NodeInfo if missing - NodeInfo *getOrCreateNode(NodeNum n); + meshtastic_NodeInfo *getOrCreateNode(NodeNum n); /// Notify observers of changes to the DB void notifyObservers(bool forceUpdate = false) @@ -140,13 +143,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(); }; /** @@ -183,7 +184,8 @@ extern NodeDB nodeDB; // Our delay functions check for this for times that should never expire #define NODE_DELAY_FOREVER 0xffffffff -#define IF_ROUTER(routerVal, normalVal) ((config.device.role == Config_DeviceConfig_Role_ROUTER) ? (routerVal) : (normalVal)) +#define IF_ROUTER(routerVal, normalVal) \ + ((config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER) ? (routerVal) : (normalVal)) #define ONE_DAY 24 * 60 * 60 @@ -203,13 +205,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 +222,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..9ecad47cd 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() @@ -11,7 +11,7 @@ PacketHistory::PacketHistory() /** * Update recentBroadcasts and return true if we have already seen this packet */ -bool PacketHistory::wasSeenRecently(const MeshPacket *p, bool withUpdate) +bool PacketHistory::wasSeenRecently(const meshtastic_MeshPacket *p, bool withUpdate) { if (p->id == 0) { LOG_DEBUG("Ignoring message with zero id\n"); @@ -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/PacketHistory.h b/src/mesh/PacketHistory.h index d44a3d369..e59acca8f 100644 --- a/src/mesh/PacketHistory.h +++ b/src/mesh/PacketHistory.h @@ -41,5 +41,5 @@ class PacketHistory * * @param withUpdate if true and not found we add an entry to recentPackets */ - bool wasSeenRecently(const MeshPacket *p, bool withUpdate = true); + bool wasSeenRecently(const meshtastic_MeshPacket *p, bool withUpdate = true); }; diff --git a/src/mesh/PhoneAPI.cpp b/src/mesh/PhoneAPI.cpp index 7c5781879..0c430ea5c 100644 --- a/src/mesh/PhoneAPI.cpp +++ b/src/mesh/PhoneAPI.cpp @@ -80,20 +80,20 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) // return (lastContactMsec != 0) && memset(&toRadioScratch, 0, sizeof(toRadioScratch)); - if (pb_decode_from_bytes(buf, bufLength, &ToRadio_msg, &toRadioScratch)) { + if (pb_decode_from_bytes(buf, bufLength, &meshtastic_ToRadio_msg, &toRadioScratch)) { switch (toRadioScratch.which_payload_variant) { - case ToRadio_packet_tag: + case meshtastic_ToRadio_packet_tag: return handleToRadioPacket(toRadioScratch.packet); - case ToRadio_want_config_id_tag: + case meshtastic_ToRadio_want_config_id_tag: config_nonce = toRadioScratch.want_config_id; LOG_INFO("Client wants config, nonce=%u\n", config_nonce); handleStartConfig(); break; - case ToRadio_disconnect_tag: + case meshtastic_ToRadio_disconnect_tag: LOG_INFO("Disconnecting from phone\n"); close(); break; - case ToRadio_xmodemPacket_tag: + case meshtastic_ToRadio_xmodemPacket_tag: LOG_INFO("Got xmodem packet\n"); xModem.handlePacket(toRadioScratch.xmodemPacket); break; @@ -143,7 +143,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // If the user has specified they don't want our node to share its location, make sure to tell the phone // app not to send locations on our behalf. myNodeInfo.has_gps = gps && gps->isConnected(); // Update with latest GPS connect info - fromRadioScratch.which_payload_variant = FromRadio_my_info_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_my_info_tag; fromRadioScratch.my_info = myNodeInfo; state = STATE_SEND_NODEINFO; @@ -152,13 +152,13 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) case STATE_SEND_NODEINFO: { LOG_INFO("getFromRadio=STATE_SEND_NODEINFO\n"); - const NodeInfo *info = nodeInfoForPhone; + const meshtastic_NodeInfo *info = nodeInfoForPhone; nodeInfoForPhone = NULL; // We just consumed a nodeinfo, will need a new one next time if (info) { LOG_INFO("Sending nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s\n", info->num, info->last_heard, info->user.id, info->user.long_name); - fromRadioScratch.which_payload_variant = FromRadio_node_info_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_node_info_tag; fromRadioScratch.node_info = *info; // Stay in current state until done sending nodeinfos } else { @@ -172,47 +172,47 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) case STATE_SEND_CHANNELS: LOG_INFO("getFromRadio=STATE_SEND_CHANNELS\n"); - fromRadioScratch.which_payload_variant = FromRadio_channel_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_channel_tag; fromRadioScratch.channel = channels.getByIndex(config_state); config_state++; // Advance when we have sent all of our Channels if (config_state >= MAX_NUM_CHANNELS) { state = STATE_SEND_CONFIG; - config_state = _AdminMessage_ConfigType_MIN + 1; + config_state = _meshtastic_AdminMessage_ConfigType_MIN + 1; } break; case STATE_SEND_CONFIG: LOG_INFO("getFromRadio=STATE_SEND_CONFIG\n"); - fromRadioScratch.which_payload_variant = FromRadio_config_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_config_tag; switch (config_state) { - case Config_device_tag: - fromRadioScratch.config.which_payload_variant = Config_device_tag; + case meshtastic_Config_device_tag: + fromRadioScratch.config.which_payload_variant = meshtastic_Config_device_tag; fromRadioScratch.config.payload_variant.device = config.device; break; - case Config_position_tag: - fromRadioScratch.config.which_payload_variant = Config_position_tag; + case meshtastic_Config_position_tag: + fromRadioScratch.config.which_payload_variant = meshtastic_Config_position_tag; fromRadioScratch.config.payload_variant.position = config.position; break; - case Config_power_tag: - fromRadioScratch.config.which_payload_variant = Config_power_tag; + case meshtastic_Config_power_tag: + fromRadioScratch.config.which_payload_variant = meshtastic_Config_power_tag; fromRadioScratch.config.payload_variant.power = config.power; fromRadioScratch.config.payload_variant.power.ls_secs = default_ls_secs; break; - case Config_network_tag: - fromRadioScratch.config.which_payload_variant = Config_network_tag; + case meshtastic_Config_network_tag: + fromRadioScratch.config.which_payload_variant = meshtastic_Config_network_tag; fromRadioScratch.config.payload_variant.network = config.network; break; - case Config_display_tag: - fromRadioScratch.config.which_payload_variant = Config_display_tag; + case meshtastic_Config_display_tag: + fromRadioScratch.config.which_payload_variant = meshtastic_Config_display_tag; fromRadioScratch.config.payload_variant.display = config.display; break; - case Config_lora_tag: - fromRadioScratch.config.which_payload_variant = Config_lora_tag; + case meshtastic_Config_lora_tag: + fromRadioScratch.config.which_payload_variant = meshtastic_Config_lora_tag; fromRadioScratch.config.payload_variant.lora = config.lora; break; - case Config_bluetooth_tag: - fromRadioScratch.config.which_payload_variant = Config_bluetooth_tag; + case meshtastic_Config_bluetooth_tag: + fromRadioScratch.config.which_payload_variant = meshtastic_Config_bluetooth_tag; fromRadioScratch.config.payload_variant.bluetooth = config.bluetooth; break; default: @@ -224,50 +224,50 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) config_state++; // Advance when we have sent all of our config objects - if (config_state > (_AdminMessage_ConfigType_MAX + 1)) { + if (config_state > (_meshtastic_AdminMessage_ConfigType_MAX + 1)) { state = STATE_SEND_MODULECONFIG; - config_state = _AdminMessage_ModuleConfigType_MIN + 1; + config_state = _meshtastic_AdminMessage_ModuleConfigType_MIN + 1; } break; case STATE_SEND_MODULECONFIG: LOG_INFO("getFromRadio=STATE_SEND_MODULECONFIG\n"); - fromRadioScratch.which_payload_variant = FromRadio_moduleConfig_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_moduleConfig_tag; switch (config_state) { - case ModuleConfig_mqtt_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_mqtt_tag; + case meshtastic_ModuleConfig_mqtt_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_mqtt_tag; fromRadioScratch.moduleConfig.payload_variant.mqtt = moduleConfig.mqtt; break; - case ModuleConfig_serial_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_serial_tag; + case meshtastic_ModuleConfig_serial_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_serial_tag; fromRadioScratch.moduleConfig.payload_variant.serial = moduleConfig.serial; break; - case ModuleConfig_external_notification_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_external_notification_tag; + case meshtastic_ModuleConfig_external_notification_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_external_notification_tag; fromRadioScratch.moduleConfig.payload_variant.external_notification = moduleConfig.external_notification; break; - case ModuleConfig_store_forward_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_store_forward_tag; + case meshtastic_ModuleConfig_store_forward_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_store_forward_tag; fromRadioScratch.moduleConfig.payload_variant.store_forward = moduleConfig.store_forward; break; - case ModuleConfig_range_test_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_range_test_tag; + case meshtastic_ModuleConfig_range_test_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_range_test_tag; fromRadioScratch.moduleConfig.payload_variant.range_test = moduleConfig.range_test; break; - case ModuleConfig_telemetry_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_telemetry_tag; + case meshtastic_ModuleConfig_telemetry_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_telemetry_tag; fromRadioScratch.moduleConfig.payload_variant.telemetry = moduleConfig.telemetry; break; - case ModuleConfig_canned_message_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_canned_message_tag; + case meshtastic_ModuleConfig_canned_message_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_canned_message_tag; fromRadioScratch.moduleConfig.payload_variant.canned_message = moduleConfig.canned_message; break; - case ModuleConfig_audio_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_audio_tag; + case meshtastic_ModuleConfig_audio_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_audio_tag; fromRadioScratch.moduleConfig.payload_variant.audio = moduleConfig.audio; break; - case ModuleConfig_remote_hardware_tag: - fromRadioScratch.moduleConfig.which_payload_variant = ModuleConfig_remote_hardware_tag; + case meshtastic_ModuleConfig_remote_hardware_tag: + fromRadioScratch.moduleConfig.which_payload_variant = meshtastic_ModuleConfig_remote_hardware_tag; fromRadioScratch.moduleConfig.payload_variant.remote_hardware = moduleConfig.remote_hardware; break; default: @@ -276,7 +276,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) config_state++; // Advance when we have sent all of our ModuleConfig objects - if (config_state > (_AdminMessage_ModuleConfigType_MAX + 1)) { + if (config_state > (_meshtastic_AdminMessage_ModuleConfigType_MAX + 1)) { state = STATE_SEND_COMPLETE_ID; config_state = 0; } @@ -284,7 +284,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) case STATE_SEND_COMPLETE_ID: LOG_INFO("getFromRadio=STATE_SEND_COMPLETE_ID\n"); - fromRadioScratch.which_payload_variant = FromRadio_config_complete_id_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_config_complete_id_tag; fromRadioScratch.config_complete_id = config_nonce; config_nonce = 0; state = STATE_SEND_PACKETS; @@ -294,19 +294,18 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Do we have a message from the mesh? LOG_INFO("getFromRadio=STATE_SEND_PACKETS\n"); if (queueStatusPacketForPhone) { - fromRadioScratch.which_payload_variant = FromRadio_queueStatus_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_queueStatus_tag; fromRadioScratch.queueStatus = *queueStatusPacketForPhone; releaseQueueStatusPhonePacket(); - } else if (xmodemPacketForPhone) { - fromRadioScratch.which_payload_variant = FromRadio_xmodemPacket_tag; - fromRadioScratch.xmodemPacket = *xmodemPacketForPhone; - free(xmodemPacketForPhone); - xmodemPacketForPhone = NULL; + } else if (xmodemPacketForPhone.control != meshtastic_XModem_Control_NUL) { + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_xmodemPacket_tag; + fromRadioScratch.xmodemPacket = xmodemPacketForPhone; + xmodemPacketForPhone = meshtastic_XModem_init_zero; } else if (packetForPhone) { printPacket("phone downloaded packet", packetForPhone); // Encapsulate as a FromRadio packet - fromRadioScratch.which_payload_variant = FromRadio_packet_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_packet_tag; fromRadioScratch.packet = *packetForPhone; releasePhonePacket(); } @@ -319,7 +318,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Do we have a message from the mesh? if (fromRadioScratch.which_payload_variant != 0) { // Encapsulate as a FromRadio packet - size_t numbytes = pb_encode_to_bytes(buf, FromRadio_size, &FromRadio_msg, &fromRadioScratch); + size_t numbytes = pb_encode_to_bytes(buf, meshtastic_FromRadio_size, &meshtastic_FromRadio_msg, &fromRadioScratch); LOG_DEBUG("encoding toPhone packet to phone variant=%d, %d bytes\n", fromRadioScratch.which_payload_variant, numbytes); return numbytes; @@ -377,11 +376,12 @@ bool PhoneAPI::available() if (hasPacket) return true; - if (!xmodemPacketForPhone) + if (xmodemPacketForPhone.control == meshtastic_XModem_Control_NUL) xmodemPacketForPhone = xModem.getForPhone(); - hasPacket = !!packetForPhone; - if (hasPacket) + if (xmodemPacketForPhone.control != meshtastic_XModem_Control_NUL) { + xModem.resetForPhone(); return true; + } if (!packetForPhone) packetForPhone = service.getForPhone(); @@ -399,7 +399,7 @@ bool PhoneAPI::available() /** * Handle a packet that the phone wants us to send. It is our responsibility to free the packet to the pool */ -bool PhoneAPI::handleToRadioPacket(MeshPacket &p) +bool PhoneAPI::handleToRadioPacket(meshtastic_MeshPacket &p) { printPacket("PACKET FROM PHONE", &p); service.handleToRadio(p); diff --git a/src/mesh/PhoneAPI.h b/src/mesh/PhoneAPI.h index bed917af2..5a73f5874 100644 --- a/src/mesh/PhoneAPI.h +++ b/src/mesh/PhoneAPI.h @@ -41,18 +41,19 @@ class PhoneAPI /// We temporarily keep the packet here between the call to available and getFromRadio. We will free it after the phone /// downloads it - MeshPacket *packetForPhone = NULL; + meshtastic_MeshPacket *packetForPhone = NULL; // file transfer packets destined for phone. Push it to the queue then free it. - XModem *xmodemPacketForPhone = NULL; + meshtastic_XModem xmodemPacketForPhone = meshtastic_XModem_init_zero; // Keep QueueStatus packet just as packetForPhone - QueueStatus *queueStatusPacketForPhone = NULL; + meshtastic_QueueStatus *queueStatusPacketForPhone = NULL; /// We temporarily keep the nodeInfo here between the call to available and getFromRadio - const NodeInfo *nodeInfoForPhone = NULL; + const meshtastic_NodeInfo *nodeInfoForPhone = NULL; - ToRadio toRadioScratch = {0}; // this is a static scratch object, any data must be copied elsewhere before returning + meshtastic_ToRadio toRadioScratch = { + 0}; // this is a static scratch object, any data must be copied elsewhere before returning /// Use to ensure that clients don't get confused about old messages from the radio uint32_t config_nonce = 0; @@ -92,7 +93,7 @@ class PhoneAPI protected: /// Our fromradio packet while it is being assembled - FromRadio fromRadioScratch = {}; + meshtastic_FromRadio fromRadioScratch = {}; /** the last msec we heard from the client on the other side of this link */ uint32_t lastContactMsec = 0; @@ -128,7 +129,7 @@ class PhoneAPI * Handle a packet that the phone wants us to send. We can write to it but can not keep a reference to it * @return true true if a packet was queued for sending */ - bool handleToRadioPacket(MeshPacket &p); + bool handleToRadioPacket(meshtastic_MeshPacket &p); /// If the mesh service tells us fromNum has changed, tell the phone virtual int onNotify(uint32_t newValue) override; 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..bdfdea9ad 100644 --- a/src/mesh/ProtobufModule.h +++ b/src/mesh/ProtobufModule.h @@ -16,31 +16,29 @@ template class ProtobufModule : protected SinglePortModule /** Constructor * name is for debugging output */ - ProtobufModule(const char *_name, PortNum _ourPortNum, const pb_msgdesc_t *_fields) + ProtobufModule(const char *_name, meshtastic_PortNum _ourPortNum, const pb_msgdesc_t *_fields) : SinglePortModule(_name, _ourPortNum), fields(_fields) { } protected: - - /** * Handle a received message, the data field in the message is already decoded and is provided * * In general decoded will always be !NULL. But in some special applications (where you have handling packets * for multiple port numbers, decoding will ONLY be attempted for packets where the portnum matches our expected ourPortNum. */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, T *decoded) = 0; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, T *decoded) = 0; /** * Return a mesh packet which has been preinited with a particular protobuf data payload and port number. * You can then send this packet (after customizing any of the payload fields you might need) with * service.sendToMesh() */ - MeshPacket *allocDataProtobuf(const T &payload) + meshtastic_MeshPacket *allocDataProtobuf(const T &payload) { // Update our local node info with our position (even if we don't decide to update anyone else) - MeshPacket *p = allocDataPacket(); + meshtastic_MeshPacket *p = allocDataPacket(); p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), fields, &payload); @@ -52,7 +50,7 @@ template class ProtobufModule : protected SinglePortModule * Gets the short name from the sender of the mesh packet * Returns "???" if unknown sender */ - const char *getSenderShortName(const MeshPacket &mp) + const char *getSenderShortName(const meshtastic_MeshPacket &mp) { auto node = nodeDB.getNode(getFrom(&mp)); const char *sender = (node) ? node->user.short_name : "???"; @@ -62,20 +60,20 @@ 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 + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override { // FIXME - we currently update position data in the DB only if the message was a broadcast or destined to us // 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; - if (mp.which_payload_variant == MeshPacket_decoded_tag && mp.decoded.portnum == ourPortNum) { + if (mp.which_payload_variant == meshtastic_MeshPacket_decoded_tag && mp.decoded.portnum == ourPortNum) { memset(&scratch, 0, sizeof(scratch)); if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, fields, &scratch)) { decoded = &scratch; diff --git a/src/mesh/RF95Interface.cpp b/src/mesh/RF95Interface.cpp index 4502d0810..f4344941d 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) @@ -104,15 +104,15 @@ bool RF95Interface::reconfigure() // configure publicly accessible settings int err = lora->setSpreadingFactor(sf); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); err = lora->setBandwidth(bw); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); err = lora->setCodingRate(cr); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); err = lora->setSyncWord(syncWord); assert(err == RADIOLIB_ERR_NONE); @@ -125,14 +125,14 @@ bool RF95Interface::reconfigure() err = lora->setFrequency(getFreq()); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); 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); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); startReceive(); // restart receiving @@ -142,11 +142,10 @@ bool RF95Interface::reconfigure() /** * Add SNR data to received messages */ -void RF95Interface::addReceiveMetadata(MeshPacket *mp) +void RF95Interface::addReceiveMetadata(meshtastic_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..9851020d9 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. @@ -55,7 +55,7 @@ class RF95Interface : public RadioLibInterface /** * Add SNR data to received messages */ - virtual void addReceiveMetadata(MeshPacket *mp) override; + virtual void addReceiveMetadata(meshtastic_MeshPacket *mp) override; virtual void setStandby() override; diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 37b929249..61c864394 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 \ + meshtastic_Config_LoRaConfig_RegionCode_##name, freq_start, freq_end, duty_cycle, spacing, power_limit, audio_permitted, \ + 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 @@ -127,7 +127,7 @@ static uint8_t bytes[MAX_RHPACKETLEN]; void initRegion() { const RegionInfo *r = regions; - for (; r->code != Config_LoRaConfig_RegionCode_UNSET && r->code != config.lora.region; r++) + for (; r->code != meshtastic_Config_LoRaConfig_RegionCode_UNSET && r->code != config.lora.region; r++) ; myRegion = r; LOG_INFO("Wanted region %d, using %s\n", config.lora.region, r->name); @@ -175,29 +175,29 @@ uint32_t RadioInterface::getPacketTime(uint32_t pl) return msecs; } -uint32_t RadioInterface::getPacketTime(MeshPacket *p) +uint32_t RadioInterface::getPacketTime(meshtastic_MeshPacket *p) { uint32_t pl = 0; - if(p->which_payload_variant == MeshPacket_encrypted_tag) { + if (p->which_payload_variant == meshtastic_MeshPacket_encrypted_tag) { pl = p->encrypted.size + sizeof(PacketHeader); } else { - size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded); + size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_Data_msg, &p->decoded); pl = numbytes + sizeof(PacketHeader); } return getPacketTime(pl); } /** The delay to use for retransmitting dropped packets */ -uint32_t RadioInterface::getRetransmissionMsec(const MeshPacket *p) +uint32_t RadioInterface::getRetransmissionMsec(const meshtastic_MeshPacket *p) { - size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded); + size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_Data_msg, &p->decoded); uint32_t packetAirtime = getPacketTime(numbytes + sizeof(PacketHeader)); // Make sure enough time has elapsed for this packet to be sent and an ACK is received. // LOG_DEBUG("Waiting for flooding message with airtime %d and slotTime is %d\n", packetAirtime, slotTimeMsec); 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,10 @@ 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 == meshtastic_Config_DeviceConfig_Role_ROUTER || + config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER_CLIENT || + config.device.role == meshtastic_Config_DeviceConfig_Role_REPEATER) { + 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; @@ -238,11 +239,11 @@ uint32_t RadioInterface::getTxDelayMsecWeighted(float snr) return delay; } -void printPacket(const char *prefix, const MeshPacket *p) +void printPacket(const char *prefix, const meshtastic_MeshPacket *p) { LOG_DEBUG("%s (id=0x%08x fr=0x%02x to=0x%02x, WantAck=%d, HopLim=%d Ch=0x%x", prefix, p->id, p->from & 0xff, p->to & 0xff, p->want_ack, p->hop_limit, p->channel); - if (p->which_payload_variant == MeshPacket_decoded_tag) { + if (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { auto &s = p->decoded; LOG_DEBUG(" Portnum=%d", s.portnum); @@ -275,7 +276,7 @@ void printPacket(const char *prefix, const MeshPacket *p) LOG_DEBUG(" rxSNR=%g", p->rx_snr); } if (p->rx_rssi != 0) { - LOG_DEBUG(" rxRSSI=%g", p->rx_rssi); + LOG_DEBUG(" rxRSSI=%i", p->rx_rssi); } if (p->priority != 0) LOG_DEBUG(" priority=%d", p->priority); @@ -372,26 +373,26 @@ void RadioInterface::applyModemConfig() { // Set up default configuration // No Sync Words in LORA mode - Config_LoRaConfig &loraConfig = config.lora; + meshtastic_Config_LoRaConfig &loraConfig = config.lora; if (loraConfig.use_preset) { switch (loraConfig.modem_preset) { - case Config_LoRaConfig_ModemPreset_SHORT_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_FAST: bw = (myRegion->wideLora) ? 812.5 : 250; cr = 8; sf = 7; break; - case Config_LoRaConfig_ModemPreset_SHORT_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_SHORT_SLOW: bw = (myRegion->wideLora) ? 812.5 : 250; cr = 8; sf = 8; break; - case Config_LoRaConfig_ModemPreset_MEDIUM_FAST: + case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_FAST: bw = (myRegion->wideLora) ? 812.5 : 250; cr = 8; sf = 9; break; - case Config_LoRaConfig_ModemPreset_MEDIUM_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_SLOW: bw = (myRegion->wideLora) ? 812.5 : 250; cr = 8; sf = 10; @@ -401,13 +402,18 @@ void RadioInterface::applyModemConfig() cr = 8; sf = 11; break; - case Config_LoRaConfig_ModemPreset_LONG_SLOW: + case meshtastic_Config_LoRaConfig_ModemPreset_LONG_MODERATE: + bw = (myRegion->wideLora) ? 406.25 : 125; + cr = 8; + sf = 11; + break; + case meshtastic_Config_LoRaConfig_ModemPreset_LONG_SLOW: bw = (myRegion->wideLora) ? 406.25 : 125; cr = 8; sf = 12; break; - case Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW: - bw = (myRegion->wideLora) ? 203.125 : 31.25; + case meshtastic_Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW: + bw = (myRegion->wideLora) ? 203.125 : 62.5; cr = 8; sf = 12; break; @@ -453,14 +459,22 @@ 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)); + + // override if we have a verbatim frequency + if (loraConfig.override_frequency) { + freq = loraConfig.override_frequency; + channel_num = -1; + } saveChannelNum(channel_num); - saveFreq(freq + config.lora.frequency_offset); + saveFreq(freq + loraConfig.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("Radio freq=%.3f, config.lora.frequency_offset=%.3f\n", freq, loraConfig.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("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,8 +500,7 @@ void RadioInterface::limitPower() LOG_INFO("Set radio: final power level=%d\n", power); } - -void RadioInterface::deliverToReceiver(MeshPacket *p) +void RadioInterface::deliverToReceiver(meshtastic_MeshPacket *p) { if (router) router->enqueueReceivedMessage(p); @@ -496,12 +509,12 @@ void RadioInterface::deliverToReceiver(MeshPacket *p) /*** * given a packet set sendingPacket and decode the protobufs into radiobuf. Returns # of payload bytes to send */ -size_t RadioInterface::beginSending(MeshPacket *p) +size_t RadioInterface::beginSending(meshtastic_MeshPacket *p) { assert(!sendingPacket); // LOG_DEBUG("sending queued packet on mesh (txGood=%d,rxGood=%d,rxBad=%d)\n", rf95.txGood(), rf95.rxGood(), rf95.rxBad()); - assert(p->which_payload_variant == MeshPacket_encrypted_tag); // It should have already been encoded by now + assert(p->which_payload_variant == meshtastic_MeshPacket_encrypted_tag); // It should have already been encoded by now lastTxStart = millis(); diff --git a/src/mesh/RadioInterface.h b/src/mesh/RadioInterface.h index 59c63add2..1a84c87f9 100644 --- a/src/mesh/RadioInterface.h +++ b/src/mesh/RadioInterface.h @@ -51,25 +51,25 @@ 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 + meshtastic_MeshPacket *sendingPacket = NULL; // The packet we are currently sending uint32_t lastTxStart = 0L; /** @@ -80,7 +80,7 @@ class RadioInterface /** * Enqueue a received packet for the registered receiver */ - void deliverToReceiver(MeshPacket *p); + void deliverToReceiver(meshtastic_MeshPacket *p); public: /** pool is the pool we will alloc our rx packets from @@ -113,11 +113,12 @@ class RadioInterface * later free() the packet to pool. This routine is not allowed to stall. * If the txmit queue is full it might return an error */ - virtual ErrorCode send(MeshPacket *p) = 0; + virtual ErrorCode send(meshtastic_MeshPacket *p) = 0; /** Return TX queue status */ - virtual QueueStatus getQueueStatus() { - QueueStatus qs; + virtual meshtastic_QueueStatus getQueueStatus() + { + meshtastic_QueueStatus qs; qs.res = qs.mesh_packet_id = qs.free = qs.maxlen = 0; return qs; } @@ -138,7 +139,7 @@ class RadioInterface virtual bool reconfigure(); /** The delay to use for retransmitting dropped packets */ - uint32_t getRetransmissionMsec(const MeshPacket *p); + uint32_t getRetransmissionMsec(const meshtastic_MeshPacket *p); /** The delay to use when we want to send something */ uint32_t getTxDelayMsec(); @@ -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 @@ -154,7 +154,7 @@ class RadioInterface * * @return num msecs for the packet */ - uint32_t getPacketTime(MeshPacket *p); + uint32_t getPacketTime(meshtastic_MeshPacket *p); uint32_t getPacketTime(uint32_t totalPacketLen); /** @@ -182,7 +182,7 @@ class RadioInterface * * Used as the first step of */ - size_t beginSending(MeshPacket *p); + size_t beginSending(meshtastic_MeshPacket *p); /** * Some regulatory regions limit xmit power. @@ -220,6 +220,5 @@ class RadioInterface } }; - /// Debug printing for packets -void printPacket(const char *prefix, const MeshPacket *p); +void printPacket(const char *prefix, const meshtastic_MeshPacket *p); diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index eb17dbe37..ef69f722c 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -3,8 +3,8 @@ #include "NodeDB.h" #include "SPILock.h" #include "configuration.h" -#include "main.h" #include "error.h" +#include "main.h" #include "mesh-pb-constants.h" #include #include @@ -87,7 +87,7 @@ bool RadioLibInterface::canSendImmediately() // TX IRQ from the radio, the radio is probably broken. if (busyTx && (millis() - lastTxStart > 60000)) { LOG_ERROR("Hardware Failure! busyTx for more than 60s\n"); - RECORD_CRITICALERROR(CriticalErrorCode_TRANSMIT_FAILED); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_TRANSMIT_FAILED); // reboot in 5 seconds when this condition occurs. rebootAtMsec = lastTxStart + 65000; } @@ -101,27 +101,22 @@ bool RadioLibInterface::canSendImmediately() /// Send a packet (possibly by enquing in a private fifo). This routine will /// later free() the packet to pool. This routine is not allowed to stall because it is called from /// bluetooth comms code. If the txmit queue is empty it might return an error -ErrorCode RadioLibInterface::send(MeshPacket *p) +ErrorCode RadioLibInterface::send(meshtastic_MeshPacket *p) { #ifndef DISABLE_WELCOME_UNSET - if (config.lora.region != Config_LoRaConfig_RegionCode_UNSET) { + if (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_UNSET) { if (disabled || !config.lora.tx_enabled) { - - if (config.lora.region != Config_LoRaConfig_RegionCode_UNSET) { - if (disabled || !config.lora.tx_enabled) { - LOG_WARN("send - !config.lora.tx_enabled\n"); - packetPool.release(p); - return ERRNO_DISABLED; - } - - } else { - LOG_WARN("send - lora tx disable because RegionCode_Unset\n"); - packetPool.release(p); - return ERRNO_DISABLED; - } + LOG_WARN("send - !config.lora.tx_enabled\n"); + packetPool.release(p); + return ERRNO_DISABLED; } + + } else { + LOG_WARN("send - lora tx disable because RegionCode_Unset\n"); + packetPool.release(p); + return ERRNO_DISABLED; } #else @@ -134,33 +129,33 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) #endif - // Sometimes when testing it is useful to be able to never turn on the xmitter + // Sometimes when testing it is useful to be able to never turn on the xmitter #ifndef LORA_DISABLE_SENDING - printPacket("enqueuing for send", p); + printPacket("enqueuing for send", p); - LOG_DEBUG("txGood=%d,rxGood=%d,rxBad=%d\n", txGood, rxGood, rxBad); - ErrorCode res = txQueue.enqueue(p) ? ERRNO_OK : ERRNO_UNKNOWN; - - if (res != ERRNO_OK) { // we weren't able to queue it, so we must drop it to prevent leaks - packetPool.release(p); - return res; - } - - // set (random) transmit delay to let others reconfigure their radio, - // to avoid collisions and implement timing-based flooding - // LOG_DEBUG("Set random delay before transmitting.\n"); - setTransmitDelay(); + LOG_DEBUG("txGood=%d,rxGood=%d,rxBad=%d\n", txGood, rxGood, rxBad); + ErrorCode res = txQueue.enqueue(p) ? ERRNO_OK : ERRNO_UNKNOWN; + if (res != ERRNO_OK) { // we weren't able to queue it, so we must drop it to prevent leaks + packetPool.release(p); return res; + } + + // set (random) transmit delay to let others reconfigure their radio, + // to avoid collisions and implement timing-based flooding + // LOG_DEBUG("Set random delay before transmitting.\n"); + setTransmitDelay(); + + return res; #else packetPool.release(p); return ERRNO_DISABLED; #endif - } +} -QueueStatus RadioLibInterface::getQueueStatus() +meshtastic_QueueStatus RadioLibInterface::getQueueStatus() { - QueueStatus qs; + meshtastic_QueueStatus qs; qs.res = qs.mesh_packet_id = 0; qs.free = txQueue.getFree(); @@ -169,242 +164,248 @@ QueueStatus RadioLibInterface::getQueueStatus() return qs; } - bool RadioLibInterface::canSleep() - { - bool res = txQueue.empty(); - if (!res) // only print debug messages if we are vetoing sleep - LOG_DEBUG("radio wait to sleep, txEmpty=%d\n", res); +bool RadioLibInterface::canSleep() +{ + bool res = txQueue.empty(); + if (!res) // only print debug messages if we are vetoing sleep + LOG_DEBUG("radio wait to sleep, txEmpty=%d\n", res); - return res; - } + return res; +} - /** Attempt to cancel a previously sent packet. Returns true if a packet was found we could cancel */ - bool RadioLibInterface::cancelSending(NodeNum from, PacketId id) - { - auto p = txQueue.remove(from, id); - if (p) - packetPool.release(p); // free the packet we just removed +/** Attempt to cancel a previously sent packet. Returns true if a packet was found we could cancel */ +bool RadioLibInterface::cancelSending(NodeNum from, PacketId id) +{ + auto p = txQueue.remove(from, id); + if (p) + packetPool.release(p); // free the packet we just removed - bool result = (p != NULL); - LOG_DEBUG("cancelSending id=0x%x, removed=%d\n", id, result); - return result; - } + bool result = (p != NULL); + LOG_DEBUG("cancelSending id=0x%x, removed=%d\n", id, result); + return result; +} - /** radio helper thread callback. - We never immediately transmit after any operation (either Rx or Tx). Instead we should wait a random multiple of - 'slotTimes' (see definition in RadioInterface.h) taken from a contention window (CW) to lower the chance of collision. - The CW size is determined by setTransmitDelay() and depends either on the current channel utilization or SNR in case - of a flooding message. After this, we perform channel activity detection (CAD) and reset the transmit delay if it is - currently active. - */ - void RadioLibInterface::onNotify(uint32_t notification) - { - switch (notification) { - case ISR_TX: - handleTransmitInterrupt(); - startReceive(); - // LOG_DEBUG("tx complete - starting timer\n"); - startTransmitTimer(); - break; - case ISR_RX: - handleReceiveInterrupt(); - startReceive(); - // LOG_DEBUG("rx complete - starting timer\n"); - startTransmitTimer(); - break; - case TRANSMIT_DELAY_COMPLETED: - // LOG_DEBUG("delay done\n"); +/** radio helper thread callback. +We never immediately transmit after any operation (either Rx or Tx). Instead we should wait a random multiple of +'slotTimes' (see definition in RadioInterface.h) taken from a contention window (CW) to lower the chance of collision. +The CW size is determined by setTransmitDelay() and depends either on the current channel utilization or SNR in case +of a flooding message. After this, we perform channel activity detection (CAD) and reset the transmit delay if it is +currently active. +*/ +void RadioLibInterface::onNotify(uint32_t notification) +{ + switch (notification) { + case ISR_TX: + handleTransmitInterrupt(); + startReceive(); + // LOG_DEBUG("tx complete - starting timer\n"); + startTransmitTimer(); + break; + case ISR_RX: + handleReceiveInterrupt(); + startReceive(); + // LOG_DEBUG("rx complete - starting timer\n"); + startTransmitTimer(); + break; + case TRANSMIT_DELAY_COMPLETED: + // LOG_DEBUG("delay done\n"); - // If we are not currently in receive mode, then restart the random delay (this can happen if the main thread - // has placed the unit into standby) FIXME, how will this work if the chipset is in sleep mode? - if (!txQueue.empty()) { - if (!canSendImmediately()) { - // LOG_DEBUG("Currently Rx/Tx-ing: set random delay\n"); - setTransmitDelay(); // currently Rx/Tx-ing: reset random delay + // If we are not currently in receive mode, then restart the random delay (this can happen if the main thread + // has placed the unit into standby) FIXME, how will this work if the chipset is in sleep mode? + if (!txQueue.empty()) { + if (!canSendImmediately()) { + // LOG_DEBUG("Currently Rx/Tx-ing: set random delay\n"); + setTransmitDelay(); // currently Rx/Tx-ing: reset random delay + } else { + if (isChannelActive()) { // check if there is currently a LoRa packet on the channel + // LOG_DEBUG("Channel is active: set random delay\n"); + setTransmitDelay(); // reset random delay } else { - if (isChannelActive()) { // check if there is currently a LoRa packet on the channel - // LOG_DEBUG("Channel is active: set random delay\n"); - setTransmitDelay(); // reset random delay - } else { - // Send any outgoing packets we have ready - MeshPacket *txp = txQueue.dequeue(); - assert(txp); - startSend(txp); + // Send any outgoing packets we have ready + meshtastic_MeshPacket *txp = txQueue.dequeue(); + assert(txp); + startSend(txp); - // Packet has been sent, count it toward our TX airtime utilization. - uint32_t xmitMsec = getPacketTime(txp); - airTime->logAirtime(TX_LOG, xmitMsec); - } + // Packet has been sent, count it toward our TX airtime utilization. + uint32_t xmitMsec = getPacketTime(txp); + airTime->logAirtime(TX_LOG, xmitMsec); } - } else { - // LOG_DEBUG("done with txqueue\n"); } - break; - default: - assert(0); // We expected to receive a valid notification from the ISR - } - } - - void RadioLibInterface::setTransmitDelay() - { - MeshPacket *p = txQueue.getFront(); - // We want all sending/receiving to be done by our daemon thread. - // We use a delay here because this packet might have been sent in response to a packet we just received. - // 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. - */ - if (p->rx_snr == 0 && p->rx_rssi == 0) { - startTransmitTimer(true); } else { - // If there is a SNR, start a timer scaled based on that SNR. - LOG_DEBUG("rx_snr found. hop_limit:%d rx_snr:%f\n", p->hop_limit, p->rx_snr); - startTransmitTimerSNR(p->rx_snr); + // LOG_DEBUG("done with txqueue\n"); } + break; + default: + assert(0); // We expected to receive a valid notification from the ISR + } +} + +void RadioLibInterface::setTransmitDelay() +{ + meshtastic_MeshPacket *p = txQueue.getFront(); + // We want all sending/receiving to be done by our daemon thread. + // We use a delay here because this packet might have been sent in response to a packet we just received. + // 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. + */ + if (p->rx_snr == 0 && p->rx_rssi == 0) { + startTransmitTimer(true); + } else { + // If there is a SNR, start a timer scaled based on that SNR. + LOG_DEBUG("rx_snr found. hop_limit:%d rx_snr:%f\n", p->hop_limit, p->rx_snr); + startTransmitTimerSNR(p->rx_snr); + } +} + +void RadioLibInterface::startTransmitTimer(bool withDelay) +{ + // If we have work to do and the timer wasn't already scheduled, schedule it now + if (!txQueue.empty()) { + uint32_t delay = !withDelay ? 1 : getTxDelayMsec(); + // LOG_DEBUG("xmit timer %d\n", delay); + notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable + } +} + +void RadioLibInterface::startTransmitTimerSNR(float snr) +{ + // If we have work to do and the timer wasn't already scheduled, schedule it now + if (!txQueue.empty()) { + uint32_t delay = getTxDelayMsecWeighted(snr); + // LOG_DEBUG("xmit timer %d\n", delay); + notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable + } +} + +void RadioLibInterface::handleTransmitInterrupt() +{ + // LOG_DEBUG("handling lora TX interrupt\n"); + // This can be null if we forced the device to enter standby mode. In that case + // ignore the transmit interrupt + if (sendingPacket) + completeSending(); +} + +void RadioLibInterface::completeSending() +{ + // We are careful to clear sending packet before calling printPacket because + // that can take a long time + auto p = sendingPacket; + sendingPacket = NULL; + + if (p) { + txGood++; + printPacket("Completed sending", p); + + // We are done sending that packet, release it + packetPool.release(p); + // LOG_DEBUG("Done with send\n"); + } +} + +void RadioLibInterface::handleReceiveInterrupt() +{ + uint32_t xmitMsec; + + // when this is called, we should be in receive mode - if we are not, just jump out instead of bombing. Possible Race + // Condition? + if (!isReceiving) { + LOG_DEBUG("*** WAS_ASSERT *** handleReceiveInterrupt called when not in receive mode\n"); + return; } - void RadioLibInterface::startTransmitTimer(bool withDelay) - { - // If we have work to do and the timer wasn't already scheduled, schedule it now - if (!txQueue.empty()) { - uint32_t delay = !withDelay ? 1 : getTxDelayMsec(); - // LOG_DEBUG("xmit timer %d\n", delay); - notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable - } - } + isReceiving = false; - void RadioLibInterface::startTransmitTimerSNR(float snr) - { - // If we have work to do and the timer wasn't already scheduled, schedule it now - if (!txQueue.empty()) { - uint32_t delay = getTxDelayMsecWeighted(snr); - // LOG_DEBUG("xmit timer %d\n", delay); - notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable - } - } + // read the number of actually received bytes + size_t length = iface->getPacketLength(); - void RadioLibInterface::handleTransmitInterrupt() - { - // LOG_DEBUG("handling lora TX interrupt\n"); - // This can be null if we forced the device to enter standby mode. In that case - // ignore the transmit interrupt - if (sendingPacket) - completeSending(); - } + xmitMsec = getPacketTime(length); - void RadioLibInterface::completeSending() - { - // We are careful to clear sending packet before calling printPacket because - // that can take a long time - auto p = sendingPacket; - sendingPacket = NULL; + int state = iface->readData(radiobuf, length); + if (state != RADIOLIB_ERR_NONE) { + LOG_ERROR("ignoring received packet due to error=%d\n", state); + rxBad++; - if (p) { - txGood++; - printPacket("Completed sending", p); + airTime->logAirtime(RX_ALL_LOG, xmitMsec); - // We are done sending that packet, release it - packetPool.release(p); - // LOG_DEBUG("Done with send\n"); - } - } + } else { + // Skip the 4 headers that are at the beginning of the rxBuf + int32_t payloadLen = length - sizeof(PacketHeader); + const uint8_t *payload = radiobuf + sizeof(PacketHeader); - void RadioLibInterface::handleReceiveInterrupt() - { - uint32_t xmitMsec; - - // when this is called, we should be in receive mode - if we are not, just jump out instead of bombing. Possible Race Condition? - if (!isReceiving) { - LOG_DEBUG("*** WAS_ASSERT *** handleReceiveInterrupt called when not in receive mode\n"); - return; - } - - isReceiving = false; - - // read the number of actually received bytes - size_t length = iface->getPacketLength(); - - xmitMsec = getPacketTime(length); - - int state = iface->readData(radiobuf, length); - if (state != RADIOLIB_ERR_NONE) { - LOG_ERROR("ignoring received packet due to error=%d\n", state); + // check for short packets + if (payloadLen < 0) { + LOG_WARN("ignoring received packet too short\n"); rxBad++; - airTime->logAirtime(RX_ALL_LOG, xmitMsec); - } else { - // Skip the 4 headers that are at the beginning of the rxBuf - int32_t payloadLen = length - sizeof(PacketHeader); - const uint8_t *payload = radiobuf + sizeof(PacketHeader); - - // check for short packets - if (payloadLen < 0) { - LOG_WARN("ignoring received packet too short\n"); - rxBad++; - airTime->logAirtime(RX_ALL_LOG, xmitMsec); - } else { - const PacketHeader *h = (PacketHeader *)radiobuf; - - rxGood++; - - // Note: we deliver _all_ packets to our router (i.e. our interface is intentionally promiscuous). - // This allows the router and other apps on our node to sniff packets (usually routing) between other - // nodes. - MeshPacket *mp = packetPool.allocZeroed(); - - mp->from = h->from; - mp->to = h->to; - mp->id = h->id; - mp->channel = h->channel; - assert(HOP_MAX <= PACKET_FLAGS_HOP_MASK); // If hopmax changes, carefully check this code - mp->hop_limit = h->flags & PACKET_FLAGS_HOP_MASK; - mp->want_ack = !!(h->flags & PACKET_FLAGS_WANT_ACK_MASK); - - addReceiveMetadata(mp); - - mp->which_payload_variant = MeshPacket_encrypted_tag; // Mark that the payload is still encrypted at this point - assert(((uint32_t)payloadLen) <= sizeof(mp->encrypted.bytes)); - memcpy(mp->encrypted.bytes, payload, payloadLen); - mp->encrypted.size = payloadLen; - - printPacket("Lora RX", mp); - - airTime->logAirtime(RX_LOG, xmitMsec); - - deliverToReceiver(mp); - } - } - } - - /** start an immediate transmit */ - void RadioLibInterface::startSend(MeshPacket * txp) - { - printPacket("Starting low level send", txp); - if (disabled || !config.lora.tx_enabled) { - LOG_WARN("startSend is dropping tx packet because we are disabled\n"); - packetPool.release(txp); - } else { - setStandby(); // Cancel any already in process receives - - configHardwareForSend(); // must be after setStandby - - size_t numbytes = beginSending(txp); - - int res = iface->startTransmit(radiobuf, numbytes); - if (res != RADIOLIB_ERR_NONE) { - LOG_ERROR("startTransmit failed, error=%d\n", res); - RECORD_CRITICALERROR(CriticalErrorCode_RADIO_SPI_BUG); - - // This send failed, but make sure to 'complete' it properly - completeSending(); - startReceive(); // Restart receive mode (because startTransmit failed to put us in xmit mode) + const PacketHeader *h = (PacketHeader *)radiobuf; + rxGood++; + // altered packet with "from == 0" can do Remote Node Administration without permission + if (h->from == 0) { + LOG_WARN("ignoring received packet without sender\n"); + return; } - // Must be done AFTER, starting transmit, because startTransmit clears (possibly stale) interrupt pending register - // bits - enableInterrupt(isrTxLevel0); + // Note: we deliver _all_ packets to our router (i.e. our interface is intentionally promiscuous). + // This allows the router and other apps on our node to sniff packets (usually routing) between other + // nodes. + meshtastic_MeshPacket *mp = packetPool.allocZeroed(); + + mp->from = h->from; + mp->to = h->to; + mp->id = h->id; + mp->channel = h->channel; + assert(HOP_MAX <= PACKET_FLAGS_HOP_MASK); // If hopmax changes, carefully check this code + mp->hop_limit = h->flags & PACKET_FLAGS_HOP_MASK; + mp->want_ack = !!(h->flags & PACKET_FLAGS_WANT_ACK_MASK); + + addReceiveMetadata(mp); + + mp->which_payload_variant = + meshtastic_MeshPacket_encrypted_tag; // Mark that the payload is still encrypted at this point + assert(((uint32_t)payloadLen) <= sizeof(mp->encrypted.bytes)); + memcpy(mp->encrypted.bytes, payload, payloadLen); + mp->encrypted.size = payloadLen; + + printPacket("Lora RX", mp); + + airTime->logAirtime(RX_LOG, xmitMsec); + + deliverToReceiver(mp); } } +} + +/** start an immediate transmit */ +void RadioLibInterface::startSend(meshtastic_MeshPacket *txp) +{ + printPacket("Starting low level send", txp); + if (disabled || !config.lora.tx_enabled) { + LOG_WARN("startSend is dropping tx packet because we are disabled\n"); + packetPool.release(txp); + } else { + setStandby(); // Cancel any already in process receives + + configHardwareForSend(); // must be after setStandby + + size_t numbytes = beginSending(txp); + + int res = iface->startTransmit(radiobuf, numbytes); + if (res != RADIOLIB_ERR_NONE) { + LOG_ERROR("startTransmit failed, error=%d\n", res); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_RADIO_SPI_BUG); + + // This send failed, but make sure to 'complete' it properly + completeSending(); + startReceive(); // Restart receive mode (because startTransmit failed to put us in xmit mode) + } + + // Must be done AFTER, starting transmit, because startTransmit clears (possibly stale) interrupt pending register + // bits + enableInterrupt(isrTxLevel0); + } +} diff --git a/src/mesh/RadioLibInterface.h b/src/mesh/RadioLibInterface.h index 628ea863f..c5cc85df7 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 @@ -103,7 +102,7 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified RadioLibInterface(RADIOLIB_PIN_TYPE cs, RADIOLIB_PIN_TYPE irq, RADIOLIB_PIN_TYPE rst, RADIOLIB_PIN_TYPE busy, SPIClass &spi, PhysicalLayer *iface = NULL); - virtual ErrorCode send(MeshPacket *p) override; + virtual ErrorCode send(meshtastic_MeshPacket *p) override; /** * Return true if we think the board can go to sleep (i.e. our tx queue is empty, we are not sending or receiving) @@ -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 */ @@ -151,12 +150,11 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified /** start an immediate transmit * This method is virtual so subclasses can hook as needed, subclasses should not call directly */ - virtual void startSend(MeshPacket *txp); + virtual void startSend(meshtastic_MeshPacket *txp); - QueueStatus getQueueStatus(); + meshtastic_QueueStatus getQueueStatus(); protected: - /** Do any hardware setup needed on entry into send configuration for the radio. Subclasses can customize */ virtual void configHardwareForSend() {} @@ -175,7 +173,7 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified /** * Add SNR data to received messages */ - virtual void addReceiveMetadata(MeshPacket *mp) = 0; + virtual void addReceiveMetadata(meshtastic_MeshPacket *mp) = 0; virtual void setStandby() = 0; }; 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..8000926f3 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -10,7 +10,7 @@ * If the message is want_ack, then add it to a list of packets to retransmit. * If we run out of retransmissions, send a nak packet towards the original client to indicate failure. */ -ErrorCode ReliableRouter::send(MeshPacket *p) +ErrorCode ReliableRouter::send(meshtastic_MeshPacket *p) { if (p->want_ack) { // If someone asks for acks on broadcast, we need the hop limit to be at least one, so that first node that receives our @@ -27,7 +27,7 @@ ErrorCode ReliableRouter::send(MeshPacket *p) return FloodingRouter::send(p); } -bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) +bool ReliableRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) { // Note: do not use getFrom() here, because we want to ignore messages sent from phone if (p->from == getNodeNum()) { @@ -38,14 +38,14 @@ 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) { LOG_DEBUG("generating implicit ack\n"); // NOTE: we do NOT check p->wantAck here because p is the INCOMING rebroadcast and that packet is not expected to be // marked as wantAck - sendAckNak(Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); + sendAckNak(meshtastic_Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); stopRetransmission(key); } else { @@ -54,13 +54,13 @@ 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"); - MeshPacket *tosend = packetPool.allocCopy(*p); + meshtastic_MeshPacket *tosend = packetPool.allocCopy(*p); tosend->hop_limit--; // bump down the hop count Router::send(tosend); } @@ -80,7 +80,7 @@ bool ReliableRouter::shouldFilterReceived(const MeshPacket *p) * * Otherwise, let superclass handle it. */ -void ReliableRouter::sniffReceived(const MeshPacket *p, const Routing *c) +void ReliableRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) { NodeNum ourNode = getNodeNum(); @@ -88,19 +88,18 @@ 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 == meshtastic_MeshPacket_decoded_tag) + sendAckNak(meshtastic_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(meshtastic_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 - PacketId ackId = ((c && c->error_reason == Routing_Error_NONE) || !c) ? p->decoded.request_id : 0; + PacketId ackId = ((c && c->error_reason == meshtastic_Routing_Error_NONE) || !c) ? p->decoded.request_id : 0; // A nak is a routing packt that has an error code - PacketId nakId = (c && c->error_reason != Routing_Error_NONE) ? p->decoded.request_id : 0; + PacketId nakId = (c && c->error_reason != meshtastic_Routing_Error_NONE) ? p->decoded.request_id : 0; // We intentionally don't check wasSeenRecently, because it is harmless to delete non existent retransmission records if (ackId || nakId) { @@ -120,7 +119,7 @@ void ReliableRouter::sniffReceived(const MeshPacket *p, const Routing *c) #define NUM_RETRANSMISSIONS 3 -PendingPacket::PendingPacket(MeshPacket *p) +PendingPacket::PendingPacket(meshtastic_MeshPacket *p) { packet = p; numRetransmissions = NUM_RETRANSMISSIONS - 1; // We subtract one, because we assume the user just did the first send @@ -158,7 +157,7 @@ bool ReliableRouter::stopRetransmission(GlobalPacketId key) /** * Add p to the list of packets to retransmit occasionally. We will free it once we stop retransmitting. */ -PendingPacket *ReliableRouter::startRetransmission(MeshPacket *p) +PendingPacket *ReliableRouter::startRetransmission(meshtastic_MeshPacket *p) { auto id = GlobalPacketId(p); auto rec = PendingPacket(p); @@ -192,7 +191,7 @@ int32_t ReliableRouter::doRetransmissions() if (p.numRetransmissions == 0) { LOG_DEBUG("Reliable send failed, returning a nak for fr=0x%x,to=0x%x,id=0x%x\n", p.packet->from, p.packet->to, p.packet->id); - sendAckNak(Routing_Error_MAX_RETRANSMIT, getFrom(p.packet), p.packet->id, p.packet->channel); + sendAckNak(meshtastic_Routing_Error_MAX_RETRANSMIT, getFrom(p.packet), p.packet->id, p.packet->channel); // Note: we don't stop retransmission here, instead the Nak packet gets processed in sniffReceived stopRetransmission(it->first); stillValid = false; // just deleted it diff --git a/src/mesh/ReliableRouter.h b/src/mesh/ReliableRouter.h index 65f486e5b..259da7249 100644 --- a/src/mesh/ReliableRouter.h +++ b/src/mesh/ReliableRouter.h @@ -13,7 +13,7 @@ struct GlobalPacketId { bool operator==(const GlobalPacketId &p) const { return node == p.node && id == p.id; } - explicit GlobalPacketId(const MeshPacket *p) + explicit GlobalPacketId(const meshtastic_MeshPacket *p) { node = getFrom(p); id = p->id; @@ -30,7 +30,7 @@ struct GlobalPacketId { * A packet queued for retransmission */ struct PendingPacket { - MeshPacket *packet; + meshtastic_MeshPacket *packet; /** The next time we should try to retransmit this packet */ uint32_t nextTxMsec = 0; @@ -39,7 +39,7 @@ struct PendingPacket { uint8_t numRetransmissions = 0; PendingPacket() {} - explicit PendingPacket(MeshPacket *p); + explicit PendingPacket(meshtastic_MeshPacket *p); }; class GlobalPacketIdHashFunction @@ -68,7 +68,7 @@ class ReliableRouter : public FloodingRouter * later free() the packet to pool. This routine is not allowed to stall. * If the txmit queue is full it might return an error */ - virtual ErrorCode send(MeshPacket *p) override; + virtual ErrorCode send(meshtastic_MeshPacket *p) override; /** Do our retransmission handling */ virtual int32_t runOnce() override @@ -85,7 +85,7 @@ class ReliableRouter : public FloodingRouter /** * Look for acks/naks or someone retransmitting us */ - virtual void sniffReceived(const MeshPacket *p, const Routing *c) override; + virtual void sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) override; /** * Try to find the pending packet record for this ID (or NULL if not found) @@ -96,12 +96,12 @@ class ReliableRouter : public FloodingRouter /** * We hook this method so we can see packets before FloodingRouter says they should be discarded */ - virtual bool shouldFilterReceived(const MeshPacket *p) override; + virtual bool shouldFilterReceived(const meshtastic_MeshPacket *p) override; /** * Add p to the list of packets to retransmit occasionally. We will free it once we stop retransmitting. */ - PendingPacket *startRetransmission(MeshPacket *p); + PendingPacket *startRetransmission(meshtastic_MeshPacket *p); private: /** diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 74487588b..fc38f9f5e 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" @@ -35,9 +35,9 @@ extern "C" { 2) // max number of packets which can be in flight (either queued from reception or queued for sending) // static MemoryPool staticPool(MAX_PACKETS); -static MemoryDynamic staticPool; +static MemoryDynamic staticPool; -Allocator &packetPool = staticPool; +Allocator &packetPool = staticPool; static uint8_t bytes[MAX_RHPACKETLEN]; @@ -63,7 +63,7 @@ Router::Router() : concurrency::OSThread("Router"), fromRadioQueue(MAX_RX_FROMRA */ int32_t Router::runOnce() { - MeshPacket *mp; + meshtastic_MeshPacket *mp; while ((mp = fromRadioQueue.dequeuePtr(0)) != NULL) { // printPacket("handle fromRadioQ", mp); perhapsHandleReceived(mp); @@ -77,7 +77,7 @@ int32_t Router::runOnce() * RadioInterface calls this to queue up packets that have been received from the radio. The router is now responsible for * freeing the packet */ -void Router::enqueueReceivedMessage(MeshPacket *p) +void Router::enqueueReceivedMessage(meshtastic_MeshPacket *p) { if (fromRadioQueue.enqueue(p, 0)) { // NOWAIT - fixme, if queue is full, delete older messages @@ -112,11 +112,11 @@ PacketId generatePacketId() return id; } -MeshPacket *Router::allocForSending() +meshtastic_MeshPacket *Router::allocForSending() { - MeshPacket *p = packetPool.allocZeroed(); + meshtastic_MeshPacket *p = packetPool.allocZeroed(); - p->which_payload_variant = MeshPacket_decoded_tag; // Assume payload is decoded at start. + p->which_payload_variant = meshtastic_MeshPacket_decoded_tag; // Assume payload is decoded at start. p->from = nodeDB.getNodeNum(); p->to = NODENUM_BROADCAST; p->hop_limit = (config.lora.hop_limit >= HOP_MAX) ? HOP_MAX : config.lora.hop_limit; @@ -130,12 +130,12 @@ MeshPacket *Router::allocForSending() /** * Send an ack or a nak packet back towards whoever sent idFrom */ -void Router::sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex) +void Router::sendAckNak(meshtastic_Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex) { routingModule->sendAckNak(err, to, idFrom, chIndex); } -void Router::abortSendAndNak(Routing_Error err, MeshPacket *p) +void Router::abortSendAndNak(meshtastic_Routing_Error err, meshtastic_MeshPacket *p) { LOG_ERROR("Error=%d, returning NAK and dropping packet.\n", err); sendAckNak(err, getFrom(p), p->id, p->channel); @@ -149,12 +149,12 @@ void Router::setReceivedMessage() runASAP = true; } -QueueStatus Router::getQueueStatus() +meshtastic_QueueStatus Router::getQueueStatus() { return iface->getQueueStatus(); } -ErrorCode Router::sendLocal(MeshPacket *p, RxSource src) +ErrorCode Router::sendLocal(meshtastic_MeshPacket *p, RxSource src) { // No need to deliver externally if the destination is the local node if (p->to == nodeDB.getNodeNum()) { @@ -163,7 +163,7 @@ ErrorCode Router::sendLocal(MeshPacket *p, RxSource src) return ERRNO_OK; } else if (!iface) { // We must be sending to remote nodes also, fail if no interface found - abortSendAndNak(Routing_Error_NO_INTERFACE, p); + abortSendAndNak(meshtastic_Routing_Error_NO_INTERFACE, p); return ERRNO_NO_INTERFACES; } else { @@ -190,22 +190,22 @@ void printBytes(const char *label, const uint8_t *p, size_t numbytes) * later free() the packet to pool. This routine is not allowed to stall. * If the txmit queue is full it might return an error. */ -ErrorCode Router::send(MeshPacket *p) +ErrorCode Router::send(meshtastic_MeshPacket *p) { if (p->to == nodeDB.getNodeNum()) { LOG_ERROR("BUG! send() called with packet destined for local node!\n"); packetPool.release(p); - return Routing_Error_BAD_REQUEST; + return meshtastic_Routing_Error_BAD_REQUEST; } // should have already been handled by sendLocal // Abort sending if we are violating the duty cycle 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 + meshtastic_Routing_Error err = meshtastic_Routing_Error_DUTY_CYCLE_LIMIT; + if (getFrom(p) == nodeDB.getNodeNum()) { // only send NAK to API, not to the mesh abortSendAndNak(err, p); } else { packetPool.release(p); @@ -228,28 +228,28 @@ ErrorCode Router::send(MeshPacket *p) // If the packet hasn't yet been encrypted, do so now (it might already be encrypted if we are just forwarding it) - assert(p->which_payload_variant == MeshPacket_encrypted_tag || - p->which_payload_variant == MeshPacket_decoded_tag); // I _think_ all packets should have a payload by now + assert(p->which_payload_variant == meshtastic_MeshPacket_encrypted_tag || + p->which_payload_variant == meshtastic_MeshPacket_decoded_tag); // I _think_ all packets should have a payload by now // If the packet is not yet encrypted, do so now - if (p->which_payload_variant == MeshPacket_decoded_tag) { + if (p->which_payload_variant == meshtastic_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; @@ -264,7 +264,7 @@ ErrorCode Router::send(MeshPacket *p) #endif auto encodeResult = perhapsEncode(p); - if (encodeResult != Routing_Error_NONE) { + if (encodeResult != meshtastic_Routing_Error_NONE) { abortSendAndNak(encodeResult, p); return encodeResult; // FIXME - this isn't a valid ErrorCode } @@ -293,17 +293,18 @@ bool Router::cancelSending(NodeNum from, PacketId id) * Every (non duplicate) packet this node receives will be passed through this method. This allows subclasses to * update routing tables etc... based on what we overhear (even for messages not destined to our node) */ -void Router::sniffReceived(const MeshPacket *p, const Routing *c) +void Router::sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) { // FIXME, update nodedb here for any packet that passes through us } -bool perhapsDecode(MeshPacket *p) +bool perhapsDecode(meshtastic_MeshPacket *p) { + if (config.device.role == meshtastic_Config_DeviceConfig_Role_REPEATER && + config.device.rebroadcast_mode == meshtastic_Config_DeviceConfig_RebroadcastMode_ALL_SKIP_DECODING) + return false; - // LOG_DEBUG("\n\n** perhapsDecode payloadVariant - %d\n\n", p->which_payloadVariant); - - if (p->which_payload_variant == MeshPacket_decoded_tag) + if (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) return true; // If packet was already decoded just return // assert(p->which_payloadVariant == MeshPacket_encrypted_tag); @@ -323,20 +324,20 @@ bool perhapsDecode(MeshPacket *p) // Take those raw bytes and convert them back into a well structured protobuf we can understand memset(&p->decoded, 0, sizeof(p->decoded)); - if (!pb_decode_from_bytes(bytes, rawSize, &Data_msg, &p->decoded)) { + if (!pb_decode_from_bytes(bytes, rawSize, &meshtastic_Data_msg, &p->decoded)) { LOG_ERROR("Invalid protobufs in received mesh packet (bad psk?)!\n"); - } else if (p->decoded.portnum == PortNum_UNKNOWN_APP) { + } else if (p->decoded.portnum == meshtastic_PortNum_UNKNOWN_APP) { LOG_ERROR("Invalid portnum (bad psk?)!\n"); } 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->which_payload_variant = meshtastic_MeshPacket_decoded_tag; // change type to decoded + 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) { + if (p->decoded.portnum == meshtastic_PortNum_TEXT_MESSAGE_COMPRESSED_APP) { // Decompress the payload - char compressed_in[Constants_DATA_PAYLOAD_LEN] = {}; - char decompressed_out[Constants_DATA_PAYLOAD_LEN] = {}; + char compressed_in[meshtastic_Constants_DATA_PAYLOAD_LEN] = {}; + char decompressed_out[meshtastic_Constants_DATA_PAYLOAD_LEN] = {}; int decompressed_len; memcpy(compressed_in, p->decoded.payload.bytes, p->decoded.payload.size); @@ -348,7 +349,7 @@ bool perhapsDecode(MeshPacket *p) memcpy(p->decoded.payload.bytes, decompressed_out, decompressed_len); // Switch the port from PortNum_TEXT_MESSAGE_COMPRESSED_APP to PortNum_TEXT_MESSAGE_APP - p->decoded.portnum = PortNum_TEXT_MESSAGE_APP; + p->decoded.portnum = meshtastic_PortNum_TEXT_MESSAGE_APP; } printPacket("decoded message", p); @@ -363,21 +364,20 @@ bool perhapsDecode(MeshPacket *p) /** Return 0 for success or a Routing_Errror code for failure */ -Routing_Error perhapsEncode(MeshPacket *p) +meshtastic_Routing_Error perhapsEncode(meshtastic_MeshPacket *p) { // If the packet is not yet encrypted, do so now - if (p->which_payload_variant == MeshPacket_decoded_tag) { - - size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &Data_msg, &p->decoded); + if (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { + size_t numbytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_Data_msg, &p->decoded); // Only allow encryption on the text message app. // TODO: Allow modules to opt into compression. - if (p->decoded.portnum == PortNum_TEXT_MESSAGE_APP) { + if (p->decoded.portnum == meshtastic_PortNum_TEXT_MESSAGE_APP) { - char original_payload[Constants_DATA_PAYLOAD_LEN]; + char original_payload[meshtastic_Constants_DATA_PAYLOAD_LEN]; memcpy(original_payload, p->decoded.payload.bytes, p->decoded.payload.size); - char compressed_out[Constants_DATA_PAYLOAD_LEN] = {0}; + char compressed_out[meshtastic_Constants_DATA_PAYLOAD_LEN] = {0}; int compressed_len; compressed_len = unishox2_compress_simple(original_payload, p->decoded.payload.size, compressed_out); @@ -401,12 +401,12 @@ Routing_Error perhapsEncode(MeshPacket *p) p->decoded.payload.size = compressed_len; memcpy(p->decoded.payload.bytes, compressed_out, compressed_len); - p->decoded.portnum = PortNum_TEXT_MESSAGE_COMPRESSED_APP; + p->decoded.portnum = meshtastic_PortNum_TEXT_MESSAGE_COMPRESSED_APP; } } if (numbytes > MAX_RHPACKETLEN) - return Routing_Error_TOO_LARGE; + return meshtastic_Routing_Error_TOO_LARGE; // printBytes("plaintext", bytes, numbytes); @@ -414,7 +414,7 @@ Routing_Error perhapsEncode(MeshPacket *p) auto hash = channels.setActiveByIndex(chIndex); if (hash < 0) // No suitable channel could be found for sending - return Routing_Error_NO_CHANNEL; + return meshtastic_Routing_Error_NO_CHANNEL; // Now that we are encrypting the packet channel should be the hash (no longer the index) p->channel = hash; @@ -423,10 +423,10 @@ Routing_Error perhapsEncode(MeshPacket *p) // Copy back into the packet and set the variant type memcpy(p->encrypted.bytes, bytes, numbytes); p->encrypted.size = numbytes; - p->which_payload_variant = MeshPacket_encrypted_tag; + p->which_payload_variant = meshtastic_MeshPacket_encrypted_tag; } - return Routing_Error_NONE; + return meshtastic_Routing_Error_NONE; } NodeNum Router::getNodeNum() @@ -438,7 +438,7 @@ NodeNum Router::getNodeNum() * Handle any packet that is received by an interface on this node. * Note: some packets may merely being passed through this node and will be forwarded elsewhere. */ -void Router::handleReceived(MeshPacket *p, RxSource src) +void Router::handleReceived(meshtastic_MeshPacket *p, RxSource src) { // Also, we should set the time from the ISR and it should have msec level resolution p->rx_time = getValidTime(RTCQualityFromNet); // store the arrival timestamp for the phone @@ -454,14 +454,14 @@ void Router::handleReceived(MeshPacket *p, RxSource src) else printPacket("handleReceived(REMOTE)", p); } else { - printPacket("packet decoding failed (no PSK?)", p); + printPacket("packet decoding failed or skipped (no PSK?)", p); } // call modules here MeshModule::callPlugins(*p, src); } -void Router::perhapsHandleReceived(MeshPacket *p) +void Router::perhapsHandleReceived(meshtastic_MeshPacket *p) { // assert(radioConfig.has_preferences); bool ignore = is_in_repeated(config.lora.ignore_incoming, p->from); diff --git a/src/mesh/Router.h b/src/mesh/Router.h index 5a9cc0702..f43f92158 100644 --- a/src/mesh/Router.h +++ b/src/mesh/Router.h @@ -16,7 +16,7 @@ class Router : protected concurrency::OSThread private: /// Packets which have just arrived from the radio, ready to be processed by this service and possibly /// forwarded to the phone. - PointerQueue fromRadioQueue; + PointerQueue fromRadioQueue; protected: RadioInterface *iface = NULL; @@ -45,7 +45,7 @@ class Router : protected concurrency::OSThread * * NOTE: This method will free the provided packet (even if we return an error code) */ - ErrorCode sendLocal(MeshPacket *p, RxSource src = RX_SRC_RADIO); + ErrorCode sendLocal(meshtastic_MeshPacket *p, RxSource src = RX_SRC_RADIO); /** Attempt to cancel a previously sent packet. Returns true if a packet was found we could cancel */ bool cancelSending(NodeNum from, PacketId id); @@ -53,10 +53,10 @@ class Router : protected concurrency::OSThread /** Allocate and return a meshpacket which defaults as send to broadcast from the current node. * The returned packet is guaranteed to have a unique packet ID already assigned */ - MeshPacket *allocForSending(); + meshtastic_MeshPacket *allocForSending(); /** Return Underlying interface's TX queue status */ - QueueStatus getQueueStatus(); + meshtastic_QueueStatus getQueueStatus(); /** * @return our local nodenum */ @@ -71,10 +71,7 @@ class Router : protected concurrency::OSThread * RadioInterface calls this to queue up packets that have been received from the radio. The router is now responsible for * freeing the packet */ - void enqueueReceivedMessage(MeshPacket *p); - - protected: - friend class RoutingModule; + void enqueueReceivedMessage(meshtastic_MeshPacket *p); /** * Send a packet on a suitable interface. This routine will @@ -83,7 +80,10 @@ class Router : protected concurrency::OSThread * * NOTE: This method will free the provided packet (even if we return an error code) */ - virtual ErrorCode send(MeshPacket *p); + virtual ErrorCode send(meshtastic_MeshPacket *p); + + protected: + friend class RoutingModule; /** * Should this incoming filter be dropped? @@ -93,18 +93,18 @@ class Router : protected concurrency::OSThread * Called immedately on receiption, before any further processing. * @return true to abandon the packet */ - virtual bool shouldFilterReceived(const MeshPacket *p) { return false; } + virtual bool shouldFilterReceived(const meshtastic_MeshPacket *p) { return false; } /** * Every (non duplicate) packet this node receives will be passed through this method. This allows subclasses to * update routing tables etc... based on what we overhear (even for messages not destined to our node) */ - virtual void sniffReceived(const MeshPacket *p, const Routing *c); + virtual void sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c); /** * Send an ack or a nak packet back towards whoever sent idFrom */ - void sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex); + void sendAckNak(meshtastic_Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex); private: /** @@ -115,7 +115,7 @@ class Router : protected concurrency::OSThread * Note: this packet will never be called for messages sent/generated by this node. * Note: this method will free the provided packet. */ - void perhapsHandleReceived(MeshPacket *p); + void perhapsHandleReceived(meshtastic_MeshPacket *p); /** * Called from perhapsHandleReceived() - allows subclass message delivery behavior. @@ -125,10 +125,10 @@ class Router : protected concurrency::OSThread * Note: this packet will never be called for messages sent/generated by this node. * Note: this method will free the provided packet. */ - void handleReceived(MeshPacket *p, RxSource src = RX_SRC_RADIO); + void handleReceived(meshtastic_MeshPacket *p, RxSource src = RX_SRC_RADIO); /** Frees the provided packet, and generates a NAK indicating the speicifed error while sending */ - void abortSendAndNak(Routing_Error err, MeshPacket *p); + void abortSendAndNak(meshtastic_Routing_Error err, meshtastic_MeshPacket *p); }; /** FIXME - move this into a mesh packet class @@ -136,11 +136,11 @@ class Router : protected concurrency::OSThread * * @return true for success, false for corrupt packet. */ -bool perhapsDecode(MeshPacket *p); +bool perhapsDecode(meshtastic_MeshPacket *p); /** Return 0 for success or a Routing_Errror code for failure */ -Routing_Error perhapsEncode(MeshPacket *p); +meshtastic_Routing_Error perhapsEncode(meshtastic_MeshPacket *p); extern Router *router; 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..8cd735da5 100644 --- a/src/mesh/SX126xInterface.cpp +++ b/src/mesh/SX126xInterface.cpp @@ -1,15 +1,16 @@ -#include "configuration.h" #include "SX126xInterface.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 SX126X_MAX_POWER #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,23 +19,13 @@ 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); pinMode(SX126X_POWER_EN, OUTPUT); #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 - pinMode(SX126X_RXEN, OUTPUT); -#endif -#if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) - digitalWrite(SX126X_TXEN, LOW); - pinMode(SX126X_TXEN, OUTPUT); -#endif - #ifndef SX126X_E22 float tcxoVoltage = 0; // None - we use an XTAL #else @@ -67,12 +58,29 @@ bool SX126xInterface::init() LOG_DEBUG("Current limit set to %f\n", currentLimit); LOG_DEBUG("Current limit set result %d\n", res); -#if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) - // lora.begin sets Dio2 as RF switch control, which is not true if we are manually controlling RX and TX +#ifdef SX126X_E22 + // E22 Emulation explicitly requires DIO2 as RF switch, so set it to TRUE again for good measure. In case somebody defines + // SX126X_TX for an E22 Module if (res == RADIOLIB_ERR_NONE) res = lora.setDio2AsRfSwitch(true); #endif +#if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) + // lora.begin sets Dio2 as RF switch control, which is not true if we are manually controlling RX and TX + if (res == RADIOLIB_ERR_NONE) { + res = lora.setDio2AsRfSwitch(false); + lora.setRfSwitchPins(SX126X_RXEN, SX126X_TXEN); + } +#endif + + if (config.lora.sx126x_rx_boosted_gain) { + uint16_t result = lora.setRxBoostedGainMode(true); + LOG_INFO("Set Rx Boosted Gain mode; result: %d\n", result); + } else { + uint16_t result = lora.setRxBoostedGainMode(false); + LOG_INFO("Set Rx Power Saving Gain mode; result: %d\n", result); + } + #if 0 // Read/write a register we are not using (only used for FSK mode) to test SPI comms uint8_t crcLSB = 0; @@ -106,8 +114,7 @@ bool SX126xInterface::init() return res == RADIOLIB_ERR_NONE; } -template -bool SX126xInterface::reconfigure() +template bool SX126xInterface::reconfigure() { RadioLibInterface::reconfigure(); @@ -117,15 +124,15 @@ bool SX126xInterface::reconfigure() // configure publicly accessible settings int err = lora.setSpreadingFactor(sf); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); err = lora.setBandwidth(bw); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); err = lora.setCodingRate(cr); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); // Hmm - seems to lower SNR when the signal levels are high. Leaving off for now... // TODO: Confirm gain registers are okay now @@ -143,7 +150,7 @@ bool SX126xInterface::reconfigure() err = lora.setFrequency(getFreq()); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); if (power > SX126X_MAX_POWER) // This chip has lower power limits than some power = SX126X_MAX_POWER; @@ -156,14 +163,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 @@ -174,13 +179,6 @@ void SX126xInterface::setStandby() assert(err == RADIOLIB_ERR_NONE); -#if defined(SX126X_RXEN) && (SX126X_RXEN != RADIOLIB_NC) // we have RXEN/TXEN control - turn off RX and TX power - digitalWrite(SX126X_RXEN, LOW); -#endif -#if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) - digitalWrite(SX126X_TXEN, LOW); -#endif - isReceiving = false; // If we were receiving, not any more disableInterrupt(); completeSending(); // If we were sending, not anymore @@ -189,8 +187,7 @@ void SX126xInterface::setStandby() /** * Add SNR data to received messages */ -template -void SX126xInterface::addReceiveMetadata(MeshPacket *mp) +template void SX126xInterface::addReceiveMetadata(meshtastic_MeshPacket *mp) { // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); @@ -199,24 +196,15 @@ 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); -#endif -#if defined(SX126X_RXEN) && (SX126X_RXEN != RADIOLIB_NC) - digitalWrite(SX126X_RXEN, LOW); -#endif - RadioLibInterface::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(); @@ -224,13 +212,6 @@ void SX126xInterface::startReceive() setStandby(); -#if defined(SX126X_RXEN) && (SX126X_RXEN != RADIOLIB_NC) // we have RXEN/TXEN control - turn on RX power / off TX power - digitalWrite(SX126X_RXEN, HIGH); -#endif -#if defined(SX126X_TXEN) && (SX126X_TXEN != RADIOLIB_NC) - digitalWrite(SX126X_TXEN, LOW); -#endif - // int err = lora.startReceive(); int err = lora.startReceiveDutyCycleAuto(); // We use a 32 bit preamble so this should save some power by letting radio sit in // standby mostly. @@ -244,8 +225,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 +241,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 +258,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..a773fd71f 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; @@ -65,7 +63,7 @@ class SX126xInterface : public RadioLibInterface /** * Add SNR data to received messages */ - virtual void addReceiveMetadata(MeshPacket *mp) override; + virtual void addReceiveMetadata(meshtastic_MeshPacket *mp) override; virtual void setStandby() override; 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..c984d9f05 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,9 +55,9 @@ 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 != meshtastic_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; + config.lora.region = meshtastic_Config_LoRaConfig_RegionCode_LORA_24; nodeDB.saveToDisk(SEGMENT_CONFIG); delay(2000); #if defined(ARCH_ESP32) @@ -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(); @@ -94,15 +92,15 @@ bool SX128xInterface::reconfigure() // configure publicly accessible settings int err = lora.setSpreadingFactor(sf); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); err = lora.setBandwidth(bw); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); err = lora.setCodingRate(cr); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); // Hmm - seems to lower SNR when the signal levels are high. Leaving off for now... // TODO: Confirm gain registers are okay now @@ -117,7 +115,7 @@ bool SX128xInterface::reconfigure() err = lora.setFrequency(getFreq()); if (err != RADIOLIB_ERR_NONE) - RECORD_CRITICALERROR(CriticalErrorCode_INVALID_RADIO_SETTING); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); if (power > SX128X_MAX_POWER) // This chip has lower power limits than some power = SX128X_MAX_POWER; @@ -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(meshtastic_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..235d39ee0 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; @@ -65,7 +63,7 @@ class SX128xInterface : public RadioLibInterface /** * Add SNR data to received messages */ - virtual void addReceiveMetadata(MeshPacket *mp) override; + virtual void addReceiveMetadata(meshtastic_MeshPacket *mp) override; virtual void setStandby() override; diff --git a/src/mesh/SinglePortModule.h b/src/mesh/SinglePortModule.h index 2e587cb89..6fa69d964 100644 --- a/src/mesh/SinglePortModule.h +++ b/src/mesh/SinglePortModule.h @@ -9,29 +9,29 @@ class SinglePortModule : public MeshModule { protected: - PortNum ourPortNum; + meshtastic_PortNum ourPortNum; public: /** Constructor * name is for debugging output */ - SinglePortModule(const char *_name, PortNum _ourPortNum) : MeshModule(_name), ourPortNum(_ourPortNum) {} + SinglePortModule(const char *_name, meshtastic_PortNum _ourPortNum) : MeshModule(_name), ourPortNum(_ourPortNum) {} protected: /** * @return true if you want to receive the specified portnum */ - virtual bool wantPacket(const MeshPacket *p) override { return p->decoded.portnum == ourPortNum; } + virtual bool wantPacket(const meshtastic_MeshPacket *p) override { return p->decoded.portnum == ourPortNum; } /** * Return a mesh packet which has been preinited as a data packet with a particular port number. * You can then send this packet (after customizing any of the payload fields you might need) with * service.sendToMesh() */ - MeshPacket *allocDataPacket() + meshtastic_MeshPacket *allocDataPacket() { // Update our local node info with our position (even if we don't decide to update anyone else) - MeshPacket *p = router->allocForSending(); + meshtastic_MeshPacket *p = router->allocForSending(); p->decoded.portnum = ourPortNum; return p; diff --git a/src/mesh/StreamAPI.cpp b/src/mesh/StreamAPI.cpp index 9be24cac9..4d04dffe4 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); @@ -111,11 +112,11 @@ void StreamAPI::emitRebooted() { // In case we send a FromRadio packet memset(&fromRadioScratch, 0, sizeof(fromRadioScratch)); - fromRadioScratch.which_payload_variant = FromRadio_rebooted_tag; + fromRadioScratch.which_payload_variant = meshtastic_FromRadio_rebooted_tag; fromRadioScratch.rebooted = true; // LOG_DEBUG("Emitting reboot packet for serial shell\n"); - emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, FromRadio_size, &FromRadio_msg, &fromRadioScratch)); + emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, meshtastic_FromRadio_size, &meshtastic_FromRadio_msg, &fromRadioScratch)); } /// Hookable to find out when connection changes 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 "./channel.pb.h" -#include "./config.pb.h" -#include "./device_metadata.pb.h" -#include "./mesh.pb.h" -#include "./module_config.pb.h" +#include "meshtastic/channel.pb.h" +#include "meshtastic/config.pb.h" +#include "meshtastic/device_metadata.pb.h" +#include "meshtastic/mesh.pb.h" +#include "meshtastic/module_config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -16,69 +16,69 @@ /* Enum definitions */ /* TODO: REPLACE */ -typedef enum _AdminMessage_ConfigType { +typedef enum _meshtastic_AdminMessage_ConfigType { /* TODO: REPLACE */ - AdminMessage_ConfigType_DEVICE_CONFIG = 0, + meshtastic_AdminMessage_ConfigType_DEVICE_CONFIG = 0, /* TODO: REPLACE */ - AdminMessage_ConfigType_POSITION_CONFIG = 1, + meshtastic_AdminMessage_ConfigType_POSITION_CONFIG = 1, /* TODO: REPLACE */ - AdminMessage_ConfigType_POWER_CONFIG = 2, + meshtastic_AdminMessage_ConfigType_POWER_CONFIG = 2, /* TODO: REPLACE */ - AdminMessage_ConfigType_NETWORK_CONFIG = 3, + meshtastic_AdminMessage_ConfigType_NETWORK_CONFIG = 3, /* TODO: REPLACE */ - AdminMessage_ConfigType_DISPLAY_CONFIG = 4, + meshtastic_AdminMessage_ConfigType_DISPLAY_CONFIG = 4, /* TODO: REPLACE */ - AdminMessage_ConfigType_LORA_CONFIG = 5, + meshtastic_AdminMessage_ConfigType_LORA_CONFIG = 5, /* TODO: REPLACE */ - AdminMessage_ConfigType_BLUETOOTH_CONFIG = 6 -} AdminMessage_ConfigType; + meshtastic_AdminMessage_ConfigType_BLUETOOTH_CONFIG = 6 +} meshtastic_AdminMessage_ConfigType; /* TODO: REPLACE */ -typedef enum _AdminMessage_ModuleConfigType { +typedef enum _meshtastic_AdminMessage_ModuleConfigType { /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_MQTT_CONFIG = 0, + meshtastic_AdminMessage_ModuleConfigType_MQTT_CONFIG = 0, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_SERIAL_CONFIG = 1, + meshtastic_AdminMessage_ModuleConfigType_SERIAL_CONFIG = 1, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG = 2, + meshtastic_AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG = 2, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG = 3, + meshtastic_AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG = 3, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_RANGETEST_CONFIG = 4, + meshtastic_AdminMessage_ModuleConfigType_RANGETEST_CONFIG = 4, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_TELEMETRY_CONFIG = 5, + meshtastic_AdminMessage_ModuleConfigType_TELEMETRY_CONFIG = 5, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG = 6, + meshtastic_AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG = 6, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_AUDIO_CONFIG = 7, + meshtastic_AdminMessage_ModuleConfigType_AUDIO_CONFIG = 7, /* TODO: REPLACE */ - AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG = 8 -} AdminMessage_ModuleConfigType; + meshtastic_AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG = 8 +} meshtastic_AdminMessage_ModuleConfigType; /* Struct definitions */ /* This message is handled by the Admin module and is responsible for all settings/channel read/write operations. This message is used to do settings operations to both remote AND local nodes. (Prior to 1.2 these operations were done via special ToRadio operations) */ -typedef struct _AdminMessage { +typedef struct _meshtastic_AdminMessage { pb_size_t which_payload_variant; union { /* Send the specified channel in the response to this message NOTE: This field is sent with the channel index + 1 (to ensure we never try to send 'zero' - which protobufs treats as not present) */ uint32_t get_channel_request; /* TODO: REPLACE */ - Channel get_channel_response; + meshtastic_Channel get_channel_response; /* Send the current owner data in the response to this message. */ bool get_owner_request; /* TODO: REPLACE */ - User get_owner_response; + meshtastic_User get_owner_response; /* Ask for the following config data to be sent */ - AdminMessage_ConfigType get_config_request; + meshtastic_AdminMessage_ConfigType get_config_request; /* Send the current Config in the response to this message. */ - Config get_config_response; + meshtastic_Config get_config_response; /* Ask for the following config data to be sent */ - AdminMessage_ModuleConfigType get_module_config_request; + meshtastic_AdminMessage_ModuleConfigType get_module_config_request; /* Send the current Config in the response to this message. */ - ModuleConfig get_module_config_response; + meshtastic_ModuleConfig get_module_config_response; /* Get the Canned Message Module messages in the response to this message. */ bool get_canned_message_module_messages_request; /* Get the Canned Message Module messages in the response to this message. */ @@ -86,23 +86,23 @@ typedef struct _AdminMessage { /* Request the node to send device metadata (firmware, protobuf version, etc) */ bool get_device_metadata_request; /* Device metadata response */ - DeviceMetadata get_device_metadata_response; + meshtastic_DeviceMetadata get_device_metadata_response; /* Get the Ringtone in the response to this message. */ bool get_ringtone_request; /* Get the Ringtone in the response to this message. */ char get_ringtone_response[231]; /* Set the owner for this node */ - User set_owner; + meshtastic_User set_owner; /* Set channels (using the new API). A special channel is the "primary channel". The other records are secondary channels. Note: only one channel can be marked as primary. If the client sets a particular channel to be primary, the previous channel will be set to SECONDARY automatically. */ - Channel set_channel; + meshtastic_Channel set_channel; /* Set the current Config */ - Config set_config; + meshtastic_Config set_config; /* Set the current Config */ - ModuleConfig set_module_config; + meshtastic_ModuleConfig set_module_config; /* Set the Canned Message Module messages text. */ char set_canned_message_module_messages[201]; /* Set the ringtone for ExternalNotification. */ @@ -112,13 +112,6 @@ typedef struct _AdminMessage { bool begin_edit_settings; /* Commits an open transaction for any edits made to config, module config, owner, and channel settings */ bool commit_edit_settings; - /* Setting channels/radio config remotely carries the risk that you might send an invalid config and the radio never talks to your mesh again. - Therefore if setting either of these properties remotely, you must send a confirm_xxx message within 10 minutes. - If you fail to do so, the radio will assume loss of comms and revert your changes. - These messages are optional when changing the local node. */ - bool confirm_set_channel; - /* TODO: REPLACE */ - bool confirm_set_radio; /* Tell the node to reboot into the OTA Firmware in this many seconds (or <0 to cancel reboot) Only Implemented for ESP32 Devices. This needs to be issued to send a new main firmware via bluetooth. */ int32_t reboot_ota_seconds; @@ -134,7 +127,7 @@ typedef struct _AdminMessage { /* Tell the node to reset the nodedb. */ int32_t nodedb_reset; }; -} AdminMessage; +} meshtastic_AdminMessage; #ifdef __cplusplus @@ -142,56 +135,54 @@ extern "C" { #endif /* Helper constants for enums */ -#define _AdminMessage_ConfigType_MIN AdminMessage_ConfigType_DEVICE_CONFIG -#define _AdminMessage_ConfigType_MAX AdminMessage_ConfigType_BLUETOOTH_CONFIG -#define _AdminMessage_ConfigType_ARRAYSIZE ((AdminMessage_ConfigType)(AdminMessage_ConfigType_BLUETOOTH_CONFIG+1)) +#define _meshtastic_AdminMessage_ConfigType_MIN meshtastic_AdminMessage_ConfigType_DEVICE_CONFIG +#define _meshtastic_AdminMessage_ConfigType_MAX meshtastic_AdminMessage_ConfigType_BLUETOOTH_CONFIG +#define _meshtastic_AdminMessage_ConfigType_ARRAYSIZE ((meshtastic_AdminMessage_ConfigType)(meshtastic_AdminMessage_ConfigType_BLUETOOTH_CONFIG+1)) -#define _AdminMessage_ModuleConfigType_MIN AdminMessage_ModuleConfigType_MQTT_CONFIG -#define _AdminMessage_ModuleConfigType_MAX AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG -#define _AdminMessage_ModuleConfigType_ARRAYSIZE ((AdminMessage_ModuleConfigType)(AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG+1)) +#define _meshtastic_AdminMessage_ModuleConfigType_MIN meshtastic_AdminMessage_ModuleConfigType_MQTT_CONFIG +#define _meshtastic_AdminMessage_ModuleConfigType_MAX meshtastic_AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG +#define _meshtastic_AdminMessage_ModuleConfigType_ARRAYSIZE ((meshtastic_AdminMessage_ModuleConfigType)(meshtastic_AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG+1)) -#define AdminMessage_payload_variant_get_config_request_ENUMTYPE AdminMessage_ConfigType -#define AdminMessage_payload_variant_get_module_config_request_ENUMTYPE AdminMessage_ModuleConfigType +#define meshtastic_AdminMessage_payload_variant_get_config_request_ENUMTYPE meshtastic_AdminMessage_ConfigType +#define meshtastic_AdminMessage_payload_variant_get_module_config_request_ENUMTYPE meshtastic_AdminMessage_ModuleConfigType /* Initializer values for message structs */ -#define AdminMessage_init_default {0, {0}} -#define AdminMessage_init_zero {0, {0}} +#define meshtastic_AdminMessage_init_default {0, {0}} +#define meshtastic_AdminMessage_init_zero {0, {0}} /* Field tags (for use in manual encoding/decoding) */ -#define AdminMessage_get_channel_request_tag 1 -#define AdminMessage_get_channel_response_tag 2 -#define AdminMessage_get_owner_request_tag 3 -#define AdminMessage_get_owner_response_tag 4 -#define AdminMessage_get_config_request_tag 5 -#define AdminMessage_get_config_response_tag 6 -#define AdminMessage_get_module_config_request_tag 7 -#define AdminMessage_get_module_config_response_tag 8 -#define AdminMessage_get_canned_message_module_messages_request_tag 10 -#define AdminMessage_get_canned_message_module_messages_response_tag 11 -#define AdminMessage_get_device_metadata_request_tag 12 -#define AdminMessage_get_device_metadata_response_tag 13 -#define AdminMessage_get_ringtone_request_tag 14 -#define AdminMessage_get_ringtone_response_tag 15 -#define AdminMessage_set_owner_tag 32 -#define AdminMessage_set_channel_tag 33 -#define AdminMessage_set_config_tag 34 -#define AdminMessage_set_module_config_tag 35 -#define AdminMessage_set_canned_message_module_messages_tag 36 -#define AdminMessage_set_ringtone_message_tag 37 -#define AdminMessage_begin_edit_settings_tag 64 -#define AdminMessage_commit_edit_settings_tag 65 -#define AdminMessage_confirm_set_channel_tag 66 -#define AdminMessage_confirm_set_radio_tag 67 -#define AdminMessage_reboot_ota_seconds_tag 95 -#define AdminMessage_exit_simulator_tag 96 -#define AdminMessage_reboot_seconds_tag 97 -#define AdminMessage_shutdown_seconds_tag 98 -#define AdminMessage_factory_reset_tag 99 -#define AdminMessage_nodedb_reset_tag 100 +#define meshtastic_AdminMessage_get_channel_request_tag 1 +#define meshtastic_AdminMessage_get_channel_response_tag 2 +#define meshtastic_AdminMessage_get_owner_request_tag 3 +#define meshtastic_AdminMessage_get_owner_response_tag 4 +#define meshtastic_AdminMessage_get_config_request_tag 5 +#define meshtastic_AdminMessage_get_config_response_tag 6 +#define meshtastic_AdminMessage_get_module_config_request_tag 7 +#define meshtastic_AdminMessage_get_module_config_response_tag 8 +#define meshtastic_AdminMessage_get_canned_message_module_messages_request_tag 10 +#define meshtastic_AdminMessage_get_canned_message_module_messages_response_tag 11 +#define meshtastic_AdminMessage_get_device_metadata_request_tag 12 +#define meshtastic_AdminMessage_get_device_metadata_response_tag 13 +#define meshtastic_AdminMessage_get_ringtone_request_tag 14 +#define meshtastic_AdminMessage_get_ringtone_response_tag 15 +#define meshtastic_AdminMessage_set_owner_tag 32 +#define meshtastic_AdminMessage_set_channel_tag 33 +#define meshtastic_AdminMessage_set_config_tag 34 +#define meshtastic_AdminMessage_set_module_config_tag 35 +#define meshtastic_AdminMessage_set_canned_message_module_messages_tag 36 +#define meshtastic_AdminMessage_set_ringtone_message_tag 37 +#define meshtastic_AdminMessage_begin_edit_settings_tag 64 +#define meshtastic_AdminMessage_commit_edit_settings_tag 65 +#define meshtastic_AdminMessage_reboot_ota_seconds_tag 95 +#define meshtastic_AdminMessage_exit_simulator_tag 96 +#define meshtastic_AdminMessage_reboot_seconds_tag 97 +#define meshtastic_AdminMessage_shutdown_seconds_tag 98 +#define meshtastic_AdminMessage_factory_reset_tag 99 +#define meshtastic_AdminMessage_nodedb_reset_tag 100 /* Struct field encoding specification for nanopb */ -#define AdminMessage_FIELDLIST(X, a) \ +#define meshtastic_AdminMessage_FIELDLIST(X, a) \ X(a, STATIC, ONEOF, UINT32, (payload_variant,get_channel_request,get_channel_request), 1) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,get_channel_response,get_channel_response), 2) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,get_owner_request,get_owner_request), 3) \ @@ -214,33 +205,31 @@ X(a, STATIC, ONEOF, STRING, (payload_variant,set_canned_message_module_me X(a, STATIC, ONEOF, STRING, (payload_variant,set_ringtone_message,set_ringtone_message), 37) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,begin_edit_settings,begin_edit_settings), 64) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,commit_edit_settings,commit_edit_settings), 65) \ -X(a, STATIC, ONEOF, BOOL, (payload_variant,confirm_set_channel,confirm_set_channel), 66) \ -X(a, STATIC, ONEOF, BOOL, (payload_variant,confirm_set_radio,confirm_set_radio), 67) \ X(a, STATIC, ONEOF, INT32, (payload_variant,reboot_ota_seconds,reboot_ota_seconds), 95) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,exit_simulator,exit_simulator), 96) \ X(a, STATIC, ONEOF, INT32, (payload_variant,reboot_seconds,reboot_seconds), 97) \ X(a, STATIC, ONEOF, INT32, (payload_variant,shutdown_seconds,shutdown_seconds), 98) \ X(a, STATIC, ONEOF, INT32, (payload_variant,factory_reset,factory_reset), 99) \ X(a, STATIC, ONEOF, INT32, (payload_variant,nodedb_reset,nodedb_reset), 100) -#define AdminMessage_CALLBACK NULL -#define AdminMessage_DEFAULT NULL -#define AdminMessage_payload_variant_get_channel_response_MSGTYPE Channel -#define AdminMessage_payload_variant_get_owner_response_MSGTYPE User -#define AdminMessage_payload_variant_get_config_response_MSGTYPE Config -#define AdminMessage_payload_variant_get_module_config_response_MSGTYPE ModuleConfig -#define AdminMessage_payload_variant_get_device_metadata_response_MSGTYPE DeviceMetadata -#define AdminMessage_payload_variant_set_owner_MSGTYPE User -#define AdminMessage_payload_variant_set_channel_MSGTYPE Channel -#define AdminMessage_payload_variant_set_config_MSGTYPE Config -#define AdminMessage_payload_variant_set_module_config_MSGTYPE ModuleConfig +#define meshtastic_AdminMessage_CALLBACK NULL +#define meshtastic_AdminMessage_DEFAULT NULL +#define meshtastic_AdminMessage_payload_variant_get_channel_response_MSGTYPE meshtastic_Channel +#define meshtastic_AdminMessage_payload_variant_get_owner_response_MSGTYPE meshtastic_User +#define meshtastic_AdminMessage_payload_variant_get_config_response_MSGTYPE meshtastic_Config +#define meshtastic_AdminMessage_payload_variant_get_module_config_response_MSGTYPE meshtastic_ModuleConfig +#define meshtastic_AdminMessage_payload_variant_get_device_metadata_response_MSGTYPE meshtastic_DeviceMetadata +#define meshtastic_AdminMessage_payload_variant_set_owner_MSGTYPE meshtastic_User +#define meshtastic_AdminMessage_payload_variant_set_channel_MSGTYPE meshtastic_Channel +#define meshtastic_AdminMessage_payload_variant_set_config_MSGTYPE meshtastic_Config +#define meshtastic_AdminMessage_payload_variant_set_module_config_MSGTYPE meshtastic_ModuleConfig -extern const pb_msgdesc_t AdminMessage_msg; +extern const pb_msgdesc_t meshtastic_AdminMessage_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define AdminMessage_fields &AdminMessage_msg +#define meshtastic_AdminMessage_fields &meshtastic_AdminMessage_msg /* Maximum encoded size of messages (where known) */ -#define AdminMessage_size 234 +#define meshtastic_AdminMessage_size 234 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/apponly.pb.c b/src/mesh/generated/meshtastic/apponly.pb.c index 8360eaa34..8c3801ed7 100644 --- a/src/mesh/generated/meshtastic/apponly.pb.c +++ b/src/mesh/generated/meshtastic/apponly.pb.c @@ -1,12 +1,12 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./apponly.pb.h" +#include "meshtastic/apponly.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(ChannelSet, ChannelSet, 2) +PB_BIND(meshtastic_ChannelSet, meshtastic_ChannelSet, 2) diff --git a/src/mesh/generated/meshtastic/apponly.pb.h b/src/mesh/generated/meshtastic/apponly.pb.h index a37ba8ab5..b66af0ebd 100644 --- a/src/mesh/generated/meshtastic/apponly.pb.h +++ b/src/mesh/generated/meshtastic/apponly.pb.h @@ -4,8 +4,8 @@ #ifndef PB_MESHTASTIC_MESHTASTIC_APPONLY_PB_H_INCLUDED #define PB_MESHTASTIC_MESHTASTIC_APPONLY_PB_H_INCLUDED #include -#include "./channel.pb.h" -#include "./config.pb.h" +#include "meshtastic/channel.pb.h" +#include "meshtastic/config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -17,14 +17,14 @@ any SECONDARY channels. No DISABLED channels are included. This abstraction is used only on the the 'app side' of the world (ie python, javascript and android etc) to show a group of Channels as a (long) URL */ -typedef struct _ChannelSet { +typedef struct _meshtastic_ChannelSet { /* Channel list with settings */ pb_size_t settings_count; - ChannelSettings settings[8]; + meshtastic_ChannelSettings settings[8]; /* LoRa config */ bool has_lora_config; - Config_LoRaConfig lora_config; -} ChannelSet; + meshtastic_Config_LoRaConfig lora_config; +} meshtastic_ChannelSet; #ifdef __cplusplus @@ -32,29 +32,29 @@ extern "C" { #endif /* Initializer values for message structs */ -#define ChannelSet_init_default {0, {ChannelSettings_init_default, ChannelSettings_init_default, ChannelSettings_init_default, ChannelSettings_init_default, ChannelSettings_init_default, ChannelSettings_init_default, ChannelSettings_init_default, ChannelSettings_init_default}, false, Config_LoRaConfig_init_default} -#define ChannelSet_init_zero {0, {ChannelSettings_init_zero, ChannelSettings_init_zero, ChannelSettings_init_zero, ChannelSettings_init_zero, ChannelSettings_init_zero, ChannelSettings_init_zero, ChannelSettings_init_zero, ChannelSettings_init_zero}, false, Config_LoRaConfig_init_zero} +#define meshtastic_ChannelSet_init_default {0, {meshtastic_ChannelSettings_init_default, meshtastic_ChannelSettings_init_default, meshtastic_ChannelSettings_init_default, meshtastic_ChannelSettings_init_default, meshtastic_ChannelSettings_init_default, meshtastic_ChannelSettings_init_default, meshtastic_ChannelSettings_init_default, meshtastic_ChannelSettings_init_default}, false, meshtastic_Config_LoRaConfig_init_default} +#define meshtastic_ChannelSet_init_zero {0, {meshtastic_ChannelSettings_init_zero, meshtastic_ChannelSettings_init_zero, meshtastic_ChannelSettings_init_zero, meshtastic_ChannelSettings_init_zero, meshtastic_ChannelSettings_init_zero, meshtastic_ChannelSettings_init_zero, meshtastic_ChannelSettings_init_zero, meshtastic_ChannelSettings_init_zero}, false, meshtastic_Config_LoRaConfig_init_zero} /* Field tags (for use in manual encoding/decoding) */ -#define ChannelSet_settings_tag 1 -#define ChannelSet_lora_config_tag 2 +#define meshtastic_ChannelSet_settings_tag 1 +#define meshtastic_ChannelSet_lora_config_tag 2 /* Struct field encoding specification for nanopb */ -#define ChannelSet_FIELDLIST(X, a) \ +#define meshtastic_ChannelSet_FIELDLIST(X, a) \ X(a, STATIC, REPEATED, MESSAGE, settings, 1) \ X(a, STATIC, OPTIONAL, MESSAGE, lora_config, 2) -#define ChannelSet_CALLBACK NULL -#define ChannelSet_DEFAULT NULL -#define ChannelSet_settings_MSGTYPE ChannelSettings -#define ChannelSet_lora_config_MSGTYPE Config_LoRaConfig +#define meshtastic_ChannelSet_CALLBACK NULL +#define meshtastic_ChannelSet_DEFAULT NULL +#define meshtastic_ChannelSet_settings_MSGTYPE meshtastic_ChannelSettings +#define meshtastic_ChannelSet_lora_config_MSGTYPE meshtastic_Config_LoRaConfig -extern const pb_msgdesc_t ChannelSet_msg; +extern const pb_msgdesc_t meshtastic_ChannelSet_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define ChannelSet_fields &ChannelSet_msg +#define meshtastic_ChannelSet_fields &meshtastic_ChannelSet_msg /* Maximum encoded size of messages (where known) */ -#define ChannelSet_size 584 +#define meshtastic_ChannelSet_size 591 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/cannedmessages.pb.c b/src/mesh/generated/meshtastic/cannedmessages.pb.c index 5fb8adfd0..fffa3fdf9 100644 --- a/src/mesh/generated/meshtastic/cannedmessages.pb.c +++ b/src/mesh/generated/meshtastic/cannedmessages.pb.c @@ -1,12 +1,12 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./cannedmessages.pb.h" +#include "meshtastic/cannedmessages.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(CannedMessageModuleConfig, CannedMessageModuleConfig, AUTO) +PB_BIND(meshtastic_CannedMessageModuleConfig, meshtastic_CannedMessageModuleConfig, AUTO) diff --git a/src/mesh/generated/meshtastic/cannedmessages.pb.h b/src/mesh/generated/meshtastic/cannedmessages.pb.h index e2f0426f2..b81f65d0d 100644 --- a/src/mesh/generated/meshtastic/cannedmessages.pb.h +++ b/src/mesh/generated/meshtastic/cannedmessages.pb.h @@ -11,10 +11,10 @@ /* Struct definitions */ /* Canned message module configuration. */ -typedef struct _CannedMessageModuleConfig { +typedef struct _meshtastic_CannedMessageModuleConfig { /* Predefined messages for canned message module separated by '|' characters. */ char messages[201]; -} CannedMessageModuleConfig; +} meshtastic_CannedMessageModuleConfig; #ifdef __cplusplus @@ -22,25 +22,25 @@ extern "C" { #endif /* Initializer values for message structs */ -#define CannedMessageModuleConfig_init_default {""} -#define CannedMessageModuleConfig_init_zero {""} +#define meshtastic_CannedMessageModuleConfig_init_default {""} +#define meshtastic_CannedMessageModuleConfig_init_zero {""} /* Field tags (for use in manual encoding/decoding) */ -#define CannedMessageModuleConfig_messages_tag 1 +#define meshtastic_CannedMessageModuleConfig_messages_tag 1 /* Struct field encoding specification for nanopb */ -#define CannedMessageModuleConfig_FIELDLIST(X, a) \ +#define meshtastic_CannedMessageModuleConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, STRING, messages, 1) -#define CannedMessageModuleConfig_CALLBACK NULL -#define CannedMessageModuleConfig_DEFAULT NULL +#define meshtastic_CannedMessageModuleConfig_CALLBACK NULL +#define meshtastic_CannedMessageModuleConfig_DEFAULT NULL -extern const pb_msgdesc_t CannedMessageModuleConfig_msg; +extern const pb_msgdesc_t meshtastic_CannedMessageModuleConfig_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define CannedMessageModuleConfig_fields &CannedMessageModuleConfig_msg +#define meshtastic_CannedMessageModuleConfig_fields &meshtastic_CannedMessageModuleConfig_msg /* Maximum encoded size of messages (where known) */ -#define CannedMessageModuleConfig_size 203 +#define meshtastic_CannedMessageModuleConfig_size 203 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/channel.pb.c b/src/mesh/generated/meshtastic/channel.pb.c index b22ec0b36..62585fd17 100644 --- a/src/mesh/generated/meshtastic/channel.pb.c +++ b/src/mesh/generated/meshtastic/channel.pb.c @@ -1,15 +1,15 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./channel.pb.h" +#include "meshtastic/channel.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(ChannelSettings, ChannelSettings, AUTO) +PB_BIND(meshtastic_ChannelSettings, meshtastic_ChannelSettings, AUTO) -PB_BIND(Channel, Channel, AUTO) +PB_BIND(meshtastic_Channel, meshtastic_Channel, AUTO) diff --git a/src/mesh/generated/meshtastic/channel.pb.h b/src/mesh/generated/meshtastic/channel.pb.h index 8c287eca8..83ef7b5fc 100644 --- a/src/mesh/generated/meshtastic/channel.pb.h +++ b/src/mesh/generated/meshtastic/channel.pb.h @@ -19,18 +19,18 @@ cross band routing as needed. If a device has only a single radio (the common case) only one channel can be PRIMARY at a time (but any number of SECONDARY channels can't be sent received on that common frequency) */ -typedef enum _Channel_Role { +typedef enum _meshtastic_Channel_Role { /* This channel is not in use right now */ - Channel_Role_DISABLED = 0, + meshtastic_Channel_Role_DISABLED = 0, /* This channel is used to set the frequency for the radio - all other enabled channels must be SECONDARY */ - Channel_Role_PRIMARY = 1, + meshtastic_Channel_Role_PRIMARY = 1, /* Secondary channels are only used for encryption/decryption/authentication purposes. Their radio settings (freq etc) are ignored, only psk is used. */ - Channel_Role_SECONDARY = 2 -} Channel_Role; + meshtastic_Channel_Role_SECONDARY = 2 +} meshtastic_Channel_Role; /* Struct definitions */ -typedef PB_BYTES_ARRAY_T(32) ChannelSettings_psk_t; +typedef PB_BYTES_ARRAY_T(32) meshtastic_ChannelSettings_psk_t; /* Full settings (center freq, spread factor, pre-shared secret key etc...) needed to configure a radio for speaking on a particular channel This information can be encoded as a QRcode/url so that other users can configure @@ -50,7 +50,7 @@ typedef PB_BYTES_ARRAY_T(32) ChannelSettings_psk_t; FIXME: Add description of multi-channel support and how primary vs secondary channels are used. FIXME: explain how apps use channels for security. explain how remote settings and remote gpio are managed as an example */ -typedef struct _ChannelSettings { +typedef struct _meshtastic_ChannelSettings { /* Deprecated in favor of LoraConfig.channel_num */ uint32_t channel_num; /* A simple pre-shared key for now for crypto. @@ -63,7 +63,7 @@ typedef struct _ChannelSettings { `1` = The special "default" channel key: {0xd4, 0xf1, 0xbb, 0x3a, 0x20, 0x29, 0x07, 0x59, 0xf0, 0xbc, 0xff, 0xab, 0xcf, 0x4e, 0x69, 0xbf} `2` through 10 = The default channel key, except with 1 through 9 added to the last byte. Shown to user as simple1 through 10 */ - ChannelSettings_psk_t psk; + meshtastic_ChannelSettings_psk_t psk; /* A SHORT name that will be packed into the URL. Less than 12 bytes. Something for end users to call the channel @@ -89,20 +89,20 @@ typedef struct _ChannelSettings { bool uplink_enabled; /* If true, messages seen on the internet will be forwarded to the local mesh. */ bool downlink_enabled; -} ChannelSettings; +} meshtastic_ChannelSettings; /* A pair of a channel number, mode and the (sharable) settings for that channel */ -typedef struct _Channel { +typedef struct _meshtastic_Channel { /* The index of this channel in the channel table (from 0 to MAX_NUM_CHANNELS-1) (Someday - not currently implemented) An index of -1 could be used to mean "set by name", in which case the target node will find and set the channel by settings.name. */ int8_t index; /* The new settings, or NULL to disable that channel */ bool has_settings; - ChannelSettings settings; + meshtastic_ChannelSettings settings; /* TODO: REPLACE */ - Channel_Role role; -} Channel; + meshtastic_Channel_Role role; +} meshtastic_Channel; #ifdef __cplusplus @@ -110,60 +110,60 @@ extern "C" { #endif /* Helper constants for enums */ -#define _Channel_Role_MIN Channel_Role_DISABLED -#define _Channel_Role_MAX Channel_Role_SECONDARY -#define _Channel_Role_ARRAYSIZE ((Channel_Role)(Channel_Role_SECONDARY+1)) +#define _meshtastic_Channel_Role_MIN meshtastic_Channel_Role_DISABLED +#define _meshtastic_Channel_Role_MAX meshtastic_Channel_Role_SECONDARY +#define _meshtastic_Channel_Role_ARRAYSIZE ((meshtastic_Channel_Role)(meshtastic_Channel_Role_SECONDARY+1)) -#define Channel_role_ENUMTYPE Channel_Role +#define meshtastic_Channel_role_ENUMTYPE meshtastic_Channel_Role /* Initializer values for message structs */ -#define ChannelSettings_init_default {0, {0, {0}}, "", 0, 0, 0} -#define Channel_init_default {0, false, ChannelSettings_init_default, _Channel_Role_MIN} -#define ChannelSettings_init_zero {0, {0, {0}}, "", 0, 0, 0} -#define Channel_init_zero {0, false, ChannelSettings_init_zero, _Channel_Role_MIN} +#define meshtastic_ChannelSettings_init_default {0, {0, {0}}, "", 0, 0, 0} +#define meshtastic_Channel_init_default {0, false, meshtastic_ChannelSettings_init_default, _meshtastic_Channel_Role_MIN} +#define meshtastic_ChannelSettings_init_zero {0, {0, {0}}, "", 0, 0, 0} +#define meshtastic_Channel_init_zero {0, false, meshtastic_ChannelSettings_init_zero, _meshtastic_Channel_Role_MIN} /* Field tags (for use in manual encoding/decoding) */ -#define ChannelSettings_channel_num_tag 1 -#define ChannelSettings_psk_tag 2 -#define ChannelSettings_name_tag 3 -#define ChannelSettings_id_tag 4 -#define ChannelSettings_uplink_enabled_tag 5 -#define ChannelSettings_downlink_enabled_tag 6 -#define Channel_index_tag 1 -#define Channel_settings_tag 2 -#define Channel_role_tag 3 +#define meshtastic_ChannelSettings_channel_num_tag 1 +#define meshtastic_ChannelSettings_psk_tag 2 +#define meshtastic_ChannelSettings_name_tag 3 +#define meshtastic_ChannelSettings_id_tag 4 +#define meshtastic_ChannelSettings_uplink_enabled_tag 5 +#define meshtastic_ChannelSettings_downlink_enabled_tag 6 +#define meshtastic_Channel_index_tag 1 +#define meshtastic_Channel_settings_tag 2 +#define meshtastic_Channel_role_tag 3 /* Struct field encoding specification for nanopb */ -#define ChannelSettings_FIELDLIST(X, a) \ +#define meshtastic_ChannelSettings_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, channel_num, 1) \ X(a, STATIC, SINGULAR, BYTES, psk, 2) \ X(a, STATIC, SINGULAR, STRING, name, 3) \ X(a, STATIC, SINGULAR, FIXED32, id, 4) \ X(a, STATIC, SINGULAR, BOOL, uplink_enabled, 5) \ X(a, STATIC, SINGULAR, BOOL, downlink_enabled, 6) -#define ChannelSettings_CALLBACK NULL -#define ChannelSettings_DEFAULT NULL +#define meshtastic_ChannelSettings_CALLBACK NULL +#define meshtastic_ChannelSettings_DEFAULT NULL -#define Channel_FIELDLIST(X, a) \ +#define meshtastic_Channel_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, INT32, index, 1) \ X(a, STATIC, OPTIONAL, MESSAGE, settings, 2) \ X(a, STATIC, SINGULAR, UENUM, role, 3) -#define Channel_CALLBACK NULL -#define Channel_DEFAULT NULL -#define Channel_settings_MSGTYPE ChannelSettings +#define meshtastic_Channel_CALLBACK NULL +#define meshtastic_Channel_DEFAULT NULL +#define meshtastic_Channel_settings_MSGTYPE meshtastic_ChannelSettings -extern const pb_msgdesc_t ChannelSettings_msg; -extern const pb_msgdesc_t Channel_msg; +extern const pb_msgdesc_t meshtastic_ChannelSettings_msg; +extern const pb_msgdesc_t meshtastic_Channel_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define ChannelSettings_fields &ChannelSettings_msg -#define Channel_fields &Channel_msg +#define meshtastic_ChannelSettings_fields &meshtastic_ChannelSettings_msg +#define meshtastic_Channel_fields &meshtastic_Channel_msg /* Maximum encoded size of messages (where known) */ -#define ChannelSettings_size 62 -#define Channel_size 77 +#define meshtastic_ChannelSettings_size 62 +#define meshtastic_Channel_size 77 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/config.pb.c b/src/mesh/generated/meshtastic/config.pb.c index bd65fee30..361e28d7c 100644 --- a/src/mesh/generated/meshtastic/config.pb.c +++ b/src/mesh/generated/meshtastic/config.pb.c @@ -1,36 +1,37 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./config.pb.h" +#include "meshtastic/config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(Config, Config, AUTO) +PB_BIND(meshtastic_Config, meshtastic_Config, AUTO) -PB_BIND(Config_DeviceConfig, Config_DeviceConfig, AUTO) +PB_BIND(meshtastic_Config_DeviceConfig, meshtastic_Config_DeviceConfig, AUTO) -PB_BIND(Config_PositionConfig, Config_PositionConfig, AUTO) +PB_BIND(meshtastic_Config_PositionConfig, meshtastic_Config_PositionConfig, AUTO) -PB_BIND(Config_PowerConfig, Config_PowerConfig, AUTO) +PB_BIND(meshtastic_Config_PowerConfig, meshtastic_Config_PowerConfig, AUTO) -PB_BIND(Config_NetworkConfig, Config_NetworkConfig, AUTO) +PB_BIND(meshtastic_Config_NetworkConfig, meshtastic_Config_NetworkConfig, AUTO) -PB_BIND(Config_NetworkConfig_IpV4Config, Config_NetworkConfig_IpV4Config, AUTO) +PB_BIND(meshtastic_Config_NetworkConfig_IpV4Config, meshtastic_Config_NetworkConfig_IpV4Config, AUTO) -PB_BIND(Config_DisplayConfig, Config_DisplayConfig, AUTO) +PB_BIND(meshtastic_Config_DisplayConfig, meshtastic_Config_DisplayConfig, AUTO) -PB_BIND(Config_LoRaConfig, Config_LoRaConfig, 2) +PB_BIND(meshtastic_Config_LoRaConfig, meshtastic_Config_LoRaConfig, 2) -PB_BIND(Config_BluetoothConfig, Config_BluetoothConfig, AUTO) +PB_BIND(meshtastic_Config_BluetoothConfig, meshtastic_Config_BluetoothConfig, AUTO) + diff --git a/src/mesh/generated/meshtastic/config.pb.h b/src/mesh/generated/meshtastic/config.pb.h index f49c330d9..3d9fe24d4 100644 --- a/src/mesh/generated/meshtastic/config.pb.h +++ b/src/mesh/generated/meshtastic/config.pb.h @@ -11,182 +11,207 @@ /* Enum definitions */ /* Defines the device's role on the Mesh network */ -typedef enum _Config_DeviceConfig_Role { +typedef enum _meshtastic_Config_DeviceConfig_Role { /* Client device role */ - Config_DeviceConfig_Role_CLIENT = 0, + meshtastic_Config_DeviceConfig_Role_CLIENT = 0, /* Client Mute device role Same as a client except packets will not hop over this node, does not contribute to routing packets for mesh. */ - Config_DeviceConfig_Role_CLIENT_MUTE = 1, + meshtastic_Config_DeviceConfig_Role_CLIENT_MUTE = 1, /* Router device role. Mesh packets will prefer to be routed over this node. This node will not be used by client apps. - The wifi/ble radios and the oled screen will be put to sleep. */ - Config_DeviceConfig_Role_ROUTER = 2, + The wifi/ble radios and the oled screen will be put to sleep. + This mode may still potentially have higher power usage due to it's preference in message rebroadcasting on the mesh. */ + meshtastic_Config_DeviceConfig_Role_ROUTER = 2, /* Router Client device role Mesh packets will prefer to be routed over this node. The Router Client can be used as both a Router and an app connected Client. */ - Config_DeviceConfig_Role_ROUTER_CLIENT = 3 -} Config_DeviceConfig_Role; + meshtastic_Config_DeviceConfig_Role_ROUTER_CLIENT = 3, + /* Repeater device role + Mesh packets will simply be rebroadcasted over this node. Nodes configured with this role will not originate NodeInfo, Position, Telemetry + or any other packet type. They will simply rebroadcast any mesh packets on the same frequency, channel num, spread factor, and coding rate. */ + meshtastic_Config_DeviceConfig_Role_REPEATER = 4, + /* Tracker device role + Position Mesh packets will be prioritized higher and sent more frequently by default. */ + meshtastic_Config_DeviceConfig_Role_TRACKER = 5 +} meshtastic_Config_DeviceConfig_Role; + +/* Defines the device's behavior for how messages are rebroadcast */ +typedef enum _meshtastic_Config_DeviceConfig_RebroadcastMode { + /* Default behavior. + Rebroadcast any observed message, if it was on our private channel or from another mesh with the same lora params. */ + meshtastic_Config_DeviceConfig_RebroadcastMode_ALL = 0, + /* Same as behavior as ALL but skips packet decoding and simply rebroadcasts them. + Only available in Repeater role. Setting this on any other roles will result in ALL behavior. */ + meshtastic_Config_DeviceConfig_RebroadcastMode_ALL_SKIP_DECODING = 1, + /* Ignores observed messages from foreign meshes that are open or those which it cannot decrypt. + Only rebroadcasts message on the nodes local primary / secondary channels. */ + meshtastic_Config_DeviceConfig_RebroadcastMode_LOCAL_ONLY = 2 +} meshtastic_Config_DeviceConfig_RebroadcastMode; /* Bit field of boolean configuration options, indicating which optional fields to include when assembling POSITION messages Longitude and latitude are always included (also time if GPS-synced) NOTE: the more fields are included, the larger the message will be - leading to longer airtime and a higher risk of packet loss */ -typedef enum _Config_PositionConfig_PositionFlags { +typedef enum _meshtastic_Config_PositionConfig_PositionFlags { /* Required for compilation */ - Config_PositionConfig_PositionFlags_UNSET = 0, + meshtastic_Config_PositionConfig_PositionFlags_UNSET = 0, /* Include an altitude value (if available) */ - Config_PositionConfig_PositionFlags_ALTITUDE = 1, + meshtastic_Config_PositionConfig_PositionFlags_ALTITUDE = 1, /* Altitude value is MSL */ - Config_PositionConfig_PositionFlags_ALTITUDE_MSL = 2, + meshtastic_Config_PositionConfig_PositionFlags_ALTITUDE_MSL = 2, /* Include geoidal separation */ - Config_PositionConfig_PositionFlags_GEOIDAL_SEPARATION = 4, + meshtastic_Config_PositionConfig_PositionFlags_GEOIDAL_SEPARATION = 4, /* Include the DOP value ; PDOP used by default, see below */ - Config_PositionConfig_PositionFlags_DOP = 8, + meshtastic_Config_PositionConfig_PositionFlags_DOP = 8, /* If POS_DOP set, send separate HDOP / VDOP values instead of PDOP */ - Config_PositionConfig_PositionFlags_HVDOP = 16, + meshtastic_Config_PositionConfig_PositionFlags_HVDOP = 16, /* Include number of "satellites in view" */ - Config_PositionConfig_PositionFlags_SATINVIEW = 32, + meshtastic_Config_PositionConfig_PositionFlags_SATINVIEW = 32, /* Include a sequence number incremented per packet */ - Config_PositionConfig_PositionFlags_SEQ_NO = 64, + meshtastic_Config_PositionConfig_PositionFlags_SEQ_NO = 64, /* Include positional timestamp (from GPS solution) */ - Config_PositionConfig_PositionFlags_TIMESTAMP = 128, + meshtastic_Config_PositionConfig_PositionFlags_TIMESTAMP = 128, /* Include positional heading Intended for use with vehicle not walking speeds walking speeds are likely to be error prone like the compass */ - Config_PositionConfig_PositionFlags_HEADING = 256, + meshtastic_Config_PositionConfig_PositionFlags_HEADING = 256, /* Include positional speed Intended for use with vehicle not walking speeds walking speeds are likely to be error prone like the compass */ - Config_PositionConfig_PositionFlags_SPEED = 512 -} Config_PositionConfig_PositionFlags; + meshtastic_Config_PositionConfig_PositionFlags_SPEED = 512 +} meshtastic_Config_PositionConfig_PositionFlags; -typedef enum _Config_NetworkConfig_AddressMode { +typedef enum _meshtastic_Config_NetworkConfig_AddressMode { /* obtain ip address via DHCP */ - Config_NetworkConfig_AddressMode_DHCP = 0, + meshtastic_Config_NetworkConfig_AddressMode_DHCP = 0, /* use static ip address */ - Config_NetworkConfig_AddressMode_STATIC = 1 -} Config_NetworkConfig_AddressMode; + meshtastic_Config_NetworkConfig_AddressMode_STATIC = 1 +} meshtastic_Config_NetworkConfig_AddressMode; /* How the GPS coordinates are displayed on the OLED screen. */ -typedef enum _Config_DisplayConfig_GpsCoordinateFormat { +typedef enum _meshtastic_Config_DisplayConfig_GpsCoordinateFormat { /* GPS coordinates are displayed in the normal decimal degrees format: DD.DDDDDD DDD.DDDDDD */ - Config_DisplayConfig_GpsCoordinateFormat_DEC = 0, + meshtastic_Config_DisplayConfig_GpsCoordinateFormat_DEC = 0, /* GPS coordinates are displayed in the degrees minutes seconds format: DD°MM'SS"C DDD°MM'SS"C, where C is the compass point representing the locations quadrant */ - Config_DisplayConfig_GpsCoordinateFormat_DMS = 1, + meshtastic_Config_DisplayConfig_GpsCoordinateFormat_DMS = 1, /* Universal Transverse Mercator format: ZZB EEEEEE NNNNNNN, where Z is zone, B is band, E is easting, N is northing */ - Config_DisplayConfig_GpsCoordinateFormat_UTM = 2, + meshtastic_Config_DisplayConfig_GpsCoordinateFormat_UTM = 2, /* Military Grid Reference System format: ZZB CD EEEEE NNNNN, where Z is zone, B is band, C is the east 100k square, D is the north 100k square, E is easting, N is northing */ - Config_DisplayConfig_GpsCoordinateFormat_MGRS = 3, + meshtastic_Config_DisplayConfig_GpsCoordinateFormat_MGRS = 3, /* Open Location Code (aka Plus Codes). */ - Config_DisplayConfig_GpsCoordinateFormat_OLC = 4, + meshtastic_Config_DisplayConfig_GpsCoordinateFormat_OLC = 4, /* Ordnance Survey Grid Reference (the National Grid System of the UK). Format: AB EEEEE NNNNN, where A is the east 100k square, B is the north 100k square, E is the easting, N is the northing */ - Config_DisplayConfig_GpsCoordinateFormat_OSGR = 5 -} Config_DisplayConfig_GpsCoordinateFormat; + meshtastic_Config_DisplayConfig_GpsCoordinateFormat_OSGR = 5 +} meshtastic_Config_DisplayConfig_GpsCoordinateFormat; /* Unit display preference */ -typedef enum _Config_DisplayConfig_DisplayUnits { +typedef enum _meshtastic_Config_DisplayConfig_DisplayUnits { /* Metric (Default) */ - Config_DisplayConfig_DisplayUnits_METRIC = 0, + meshtastic_Config_DisplayConfig_DisplayUnits_METRIC = 0, /* Imperial */ - Config_DisplayConfig_DisplayUnits_IMPERIAL = 1 -} Config_DisplayConfig_DisplayUnits; + meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL = 1 +} meshtastic_Config_DisplayConfig_DisplayUnits; /* Override OLED outo detect with this if it fails. */ -typedef enum _Config_DisplayConfig_OledType { +typedef enum _meshtastic_Config_DisplayConfig_OledType { /* Default / Auto */ - Config_DisplayConfig_OledType_OLED_AUTO = 0, + meshtastic_Config_DisplayConfig_OledType_OLED_AUTO = 0, /* Default / Auto */ - Config_DisplayConfig_OledType_OLED_SSD1306 = 1, + meshtastic_Config_DisplayConfig_OledType_OLED_SSD1306 = 1, /* Default / Auto */ - Config_DisplayConfig_OledType_OLED_SH1106 = 2 -} Config_DisplayConfig_OledType; + meshtastic_Config_DisplayConfig_OledType_OLED_SH1106 = 2, + /* Can not be auto detected but set by proto. Used for 128x128 screens */ + meshtastic_Config_DisplayConfig_OledType_OLED_SH1107 = 3 +} meshtastic_Config_DisplayConfig_OledType; -typedef enum _Config_DisplayConfig_DisplayMode { +typedef enum _meshtastic_Config_DisplayConfig_DisplayMode { /* Default. The old style for the 128x64 OLED screen */ - Config_DisplayConfig_DisplayMode_DEFAULT = 0, + meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT = 0, /* Rearrange display elements to cater for bicolor OLED displays */ - Config_DisplayConfig_DisplayMode_TWOCOLOR = 1, + meshtastic_Config_DisplayConfig_DisplayMode_TWOCOLOR = 1, /* Same as TwoColor, but with inverted top bar. Not so good for Epaper displays */ - Config_DisplayConfig_DisplayMode_INVERTED = 2, + meshtastic_Config_DisplayConfig_DisplayMode_INVERTED = 2, /* TFT Full Color Displays (not implemented yet) */ - Config_DisplayConfig_DisplayMode_COLOR = 3 -} Config_DisplayConfig_DisplayMode; + meshtastic_Config_DisplayConfig_DisplayMode_COLOR = 3 +} meshtastic_Config_DisplayConfig_DisplayMode; -typedef enum _Config_LoRaConfig_RegionCode { +typedef enum _meshtastic_Config_LoRaConfig_RegionCode { /* Region is not set */ - Config_LoRaConfig_RegionCode_UNSET = 0, + meshtastic_Config_LoRaConfig_RegionCode_UNSET = 0, /* United States */ - Config_LoRaConfig_RegionCode_US = 1, + meshtastic_Config_LoRaConfig_RegionCode_US = 1, /* European Union 433mhz */ - Config_LoRaConfig_RegionCode_EU_433 = 2, + meshtastic_Config_LoRaConfig_RegionCode_EU_433 = 2, /* European Union 433mhz */ - Config_LoRaConfig_RegionCode_EU_868 = 3, + meshtastic_Config_LoRaConfig_RegionCode_EU_868 = 3, /* China */ - Config_LoRaConfig_RegionCode_CN = 4, + meshtastic_Config_LoRaConfig_RegionCode_CN = 4, /* Japan */ - Config_LoRaConfig_RegionCode_JP = 5, + meshtastic_Config_LoRaConfig_RegionCode_JP = 5, /* Australia / New Zealand */ - Config_LoRaConfig_RegionCode_ANZ = 6, + meshtastic_Config_LoRaConfig_RegionCode_ANZ = 6, /* Korea */ - Config_LoRaConfig_RegionCode_KR = 7, + meshtastic_Config_LoRaConfig_RegionCode_KR = 7, /* Taiwan */ - Config_LoRaConfig_RegionCode_TW = 8, + meshtastic_Config_LoRaConfig_RegionCode_TW = 8, /* Russia */ - Config_LoRaConfig_RegionCode_RU = 9, + meshtastic_Config_LoRaConfig_RegionCode_RU = 9, /* India */ - Config_LoRaConfig_RegionCode_IN = 10, + meshtastic_Config_LoRaConfig_RegionCode_IN = 10, /* New Zealand 865mhz */ - Config_LoRaConfig_RegionCode_NZ_865 = 11, + meshtastic_Config_LoRaConfig_RegionCode_NZ_865 = 11, /* Thailand */ - Config_LoRaConfig_RegionCode_TH = 12, + meshtastic_Config_LoRaConfig_RegionCode_TH = 12, /* WLAN Band */ - Config_LoRaConfig_RegionCode_LORA_24 = 13, + meshtastic_Config_LoRaConfig_RegionCode_LORA_24 = 13, /* Ukraine 433mhz */ - Config_LoRaConfig_RegionCode_UA_433 = 14, + meshtastic_Config_LoRaConfig_RegionCode_UA_433 = 14, /* Ukraine 868mhz */ - Config_LoRaConfig_RegionCode_UA_868 = 15 -} Config_LoRaConfig_RegionCode; + meshtastic_Config_LoRaConfig_RegionCode_UA_868 = 15 +} meshtastic_Config_LoRaConfig_RegionCode; /* Standard predefined channel settings Note: these mappings must match ModemPreset Choice in the device code. */ -typedef enum _Config_LoRaConfig_ModemPreset { +typedef enum _meshtastic_Config_LoRaConfig_ModemPreset { /* Long Range - Fast */ - Config_LoRaConfig_ModemPreset_LONG_FAST = 0, + meshtastic_Config_LoRaConfig_ModemPreset_LONG_FAST = 0, /* Long Range - Slow */ - Config_LoRaConfig_ModemPreset_LONG_SLOW = 1, + meshtastic_Config_LoRaConfig_ModemPreset_LONG_SLOW = 1, /* Very Long Range - Slow */ - Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW = 2, + meshtastic_Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW = 2, /* Medium Range - Slow */ - Config_LoRaConfig_ModemPreset_MEDIUM_SLOW = 3, + meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_SLOW = 3, /* Medium Range - Fast */ - Config_LoRaConfig_ModemPreset_MEDIUM_FAST = 4, + meshtastic_Config_LoRaConfig_ModemPreset_MEDIUM_FAST = 4, /* Short Range - Slow */ - Config_LoRaConfig_ModemPreset_SHORT_SLOW = 5, + meshtastic_Config_LoRaConfig_ModemPreset_SHORT_SLOW = 5, /* Short Range - Fast */ - Config_LoRaConfig_ModemPreset_SHORT_FAST = 6 -} Config_LoRaConfig_ModemPreset; + meshtastic_Config_LoRaConfig_ModemPreset_SHORT_FAST = 6, + /* Long Range - Moderately Fast */ + meshtastic_Config_LoRaConfig_ModemPreset_LONG_MODERATE = 7 +} meshtastic_Config_LoRaConfig_ModemPreset; -typedef enum _Config_BluetoothConfig_PairingMode { +typedef enum _meshtastic_Config_BluetoothConfig_PairingMode { /* Device generates a random pin that will be shown on the screen of the device for pairing */ - Config_BluetoothConfig_PairingMode_RANDOM_PIN = 0, + meshtastic_Config_BluetoothConfig_PairingMode_RANDOM_PIN = 0, /* Device requires a specified fixed pin for pairing */ - Config_BluetoothConfig_PairingMode_FIXED_PIN = 1, + meshtastic_Config_BluetoothConfig_PairingMode_FIXED_PIN = 1, /* Device requires no pin for pairing */ - Config_BluetoothConfig_PairingMode_NO_PIN = 2 -} Config_BluetoothConfig_PairingMode; + meshtastic_Config_BluetoothConfig_PairingMode_NO_PIN = 2 +} meshtastic_Config_BluetoothConfig_PairingMode; /* Struct definitions */ /* Configuration */ -typedef struct _Config_DeviceConfig { +typedef struct _meshtastic_Config_DeviceConfig { /* Sets the role of node */ - Config_DeviceConfig_Role role; + meshtastic_Config_DeviceConfig_Role role; /* Disabling this will disable the SerialConsole by not initilizing the StreamAPI */ bool serial_enabled; /* By default we turn off logging as soon as an API client connects (to keep shared serial link quiet). @@ -198,10 +223,12 @@ typedef struct _Config_DeviceConfig { /* For boards without a PWM buzzer, this is the pin number that will be used Defaults to PIN_BUZZER if defined. */ uint32_t buzzer_gpio; -} Config_DeviceConfig; + /* Sets the role of node */ + meshtastic_Config_DeviceConfig_RebroadcastMode rebroadcast_mode; +} meshtastic_Config_DeviceConfig; /* Position Config */ -typedef struct _Config_PositionConfig { +typedef struct _meshtastic_Config_PositionConfig { /* We should send our position this often (but only if it has changed significantly) Defaults to 15 minutes */ uint32_t position_broadcast_secs; @@ -229,11 +256,11 @@ typedef struct _Config_PositionConfig { uint32_t rx_gpio; /* (Re)define GPS_TX_PIN for your board. */ uint32_t tx_gpio; -} Config_PositionConfig; +} meshtastic_Config_PositionConfig; /* Power Config\ See [Power Config](/docs/settings/config/power) for additional power config details. */ -typedef struct _Config_PowerConfig { +typedef struct _meshtastic_Config_PowerConfig { /* If set, we are powered from a low-current source (i.e. solar), so even if it looks like we have power flowing in we should try to minimize power consumption as much as possible. YOU DO NOT NEED TO SET THIS IF YOU'VE set is_router (it is implied in that case). @@ -269,9 +296,9 @@ typedef struct _Config_PowerConfig { While in light sleep when we receive packets on the LoRa radio we will wake and handle them and stay awake in no BLE mode for this value 0 for default of 10 seconds */ uint32_t min_wake_secs; -} Config_PowerConfig; +} meshtastic_Config_PowerConfig; -typedef struct _Config_NetworkConfig_IpV4Config { +typedef struct _meshtastic_Config_NetworkConfig_IpV4Config { /* Static IP address */ uint32_t ip; /* Static gateway address */ @@ -280,10 +307,10 @@ typedef struct _Config_NetworkConfig_IpV4Config { uint32_t subnet; /* Static DNS server address */ uint32_t dns; -} Config_NetworkConfig_IpV4Config; +} meshtastic_Config_NetworkConfig_IpV4Config; /* Network Config */ -typedef struct _Config_NetworkConfig { +typedef struct _meshtastic_Config_NetworkConfig { /* Enable WiFi (disables Bluetooth) */ bool wifi_enabled; /* If set, this node will try to join the specified wifi network and @@ -296,21 +323,21 @@ typedef struct _Config_NetworkConfig { /* Enable Ethernet */ bool eth_enabled; /* acquire an address via DHCP or assign static */ - Config_NetworkConfig_AddressMode address_mode; + meshtastic_Config_NetworkConfig_AddressMode address_mode; /* struct to keep static address */ bool has_ipv4_config; - Config_NetworkConfig_IpV4Config ipv4_config; + meshtastic_Config_NetworkConfig_IpV4Config ipv4_config; /* rsyslog Server and Port */ char rsyslog_server[33]; -} Config_NetworkConfig; +} meshtastic_Config_NetworkConfig; /* Display Config */ -typedef struct _Config_DisplayConfig { +typedef struct _meshtastic_Config_DisplayConfig { /* Number of seconds the screen stays on after pressing the user button or receiving a message 0 for default of one minute MAXUINT for always on */ uint32_t screen_on_secs; /* How the GPS coordinates are formatted on the OLED screen. */ - Config_DisplayConfig_GpsCoordinateFormat gps_format; + meshtastic_Config_DisplayConfig_GpsCoordinateFormat gps_format; /* Automatically toggles to the next page on the screen like a carousel, based the specified interval in seconds. Potentially useful for devices without user buttons. */ uint32_t auto_screen_carousel_secs; @@ -320,17 +347,17 @@ typedef struct _Config_DisplayConfig { /* Flip screen vertically, for cases that mount the screen upside down */ bool flip_screen; /* Perferred display units */ - Config_DisplayConfig_DisplayUnits units; + meshtastic_Config_DisplayConfig_DisplayUnits units; /* Override auto-detect in screen */ - Config_DisplayConfig_OledType oled; + meshtastic_Config_DisplayConfig_OledType oled; /* Display Mode */ - Config_DisplayConfig_DisplayMode displaymode; + meshtastic_Config_DisplayConfig_DisplayMode displaymode; /* Print first line in pseudo-bold? FALSE is original style, TRUE is bold */ bool heading_bold; -} Config_DisplayConfig; +} meshtastic_Config_DisplayConfig; /* Lora Config */ -typedef struct _Config_LoRaConfig { +typedef struct _meshtastic_Config_LoRaConfig { /* When enabled, the `modem_preset` fields will be adheared to, else the `bandwidth`/`spread_factor`/`coding_rate` will be taked from their respective manually defined fields */ bool use_preset; @@ -339,7 +366,7 @@ typedef struct _Config_LoRaConfig { Because protobufs take ZERO space when the value is zero this works out nicely. This value is replaced by bandwidth/spread_factor/coding_rate. If you'd like to experiment with other options add them to MeshRadio.cpp in the device code. */ - Config_LoRaConfig_ModemPreset modem_preset; + meshtastic_Config_LoRaConfig_ModemPreset modem_preset; /* Bandwidth in MHz Certain bandwidth numbers are 'special' and will be converted to the appropriate floating point value: 31 -> 31.25MHz */ @@ -355,7 +382,7 @@ typedef struct _Config_LoRaConfig { Used to correct for crystal calibration errors. */ float frequency_offset; /* The region code for the radio (US, CN, EU433, etc...) */ - Config_LoRaConfig_RegionCode region; + meshtastic_Config_LoRaConfig_RegionCode region; /* Maximum number of hops. This can't be greater than 7. Default of 3 */ uint32_t hop_limit; @@ -379,34 +406,42 @@ typedef struct _Config_LoRaConfig { the local regulations if you're not a HAM. Has no effect if the duty cycle of the used region is 100%. */ bool override_duty_cycle; + /* If true, sets RX boosted gain mode on SX126X based radios */ + bool sx126x_rx_boosted_gain; + /* This parameter is for advanced users and licensed HAM radio operators. + Ignore Channel Calculation and use this frequency instead. The frequency_offset + will still be applied. This will allow you to use out-of-band frequencies. + Please respect your local laws and regulations. If you are a HAM, make sure you + enable HAM mode and turn off encryption. */ + float override_frequency; /* For testing it is useful sometimes to force a node to never listen to particular other nodes (simulating radio out of range). All nodenums listed in ignore_incoming will have packets they send droped on receive (by router.cpp) */ pb_size_t ignore_incoming_count; uint32_t ignore_incoming[3]; -} Config_LoRaConfig; +} meshtastic_Config_LoRaConfig; -typedef struct _Config_BluetoothConfig { +typedef struct _meshtastic_Config_BluetoothConfig { /* Enable Bluetooth on the device */ bool enabled; /* Determines the pairing strategy for the device */ - Config_BluetoothConfig_PairingMode mode; + meshtastic_Config_BluetoothConfig_PairingMode mode; /* Specified pin for PairingMode.FixedPin */ uint32_t fixed_pin; -} Config_BluetoothConfig; +} meshtastic_Config_BluetoothConfig; -typedef struct _Config { +typedef struct _meshtastic_Config { pb_size_t which_payload_variant; union { - Config_DeviceConfig device; - Config_PositionConfig position; - Config_PowerConfig power; - Config_NetworkConfig network; - Config_DisplayConfig display; - Config_LoRaConfig lora; - Config_BluetoothConfig bluetooth; + meshtastic_Config_DeviceConfig device; + meshtastic_Config_PositionConfig position; + meshtastic_Config_PowerConfig power; + meshtastic_Config_NetworkConfig network; + meshtastic_Config_DisplayConfig display; + meshtastic_Config_LoRaConfig lora; + meshtastic_Config_BluetoothConfig bluetooth; } payload_variant; -} Config; +} meshtastic_Config; #ifdef __cplusplus @@ -414,155 +449,163 @@ extern "C" { #endif /* Helper constants for enums */ -#define _Config_DeviceConfig_Role_MIN Config_DeviceConfig_Role_CLIENT -#define _Config_DeviceConfig_Role_MAX Config_DeviceConfig_Role_ROUTER_CLIENT -#define _Config_DeviceConfig_Role_ARRAYSIZE ((Config_DeviceConfig_Role)(Config_DeviceConfig_Role_ROUTER_CLIENT+1)) +#define _meshtastic_Config_DeviceConfig_Role_MIN meshtastic_Config_DeviceConfig_Role_CLIENT +#define _meshtastic_Config_DeviceConfig_Role_MAX meshtastic_Config_DeviceConfig_Role_TRACKER +#define _meshtastic_Config_DeviceConfig_Role_ARRAYSIZE ((meshtastic_Config_DeviceConfig_Role)(meshtastic_Config_DeviceConfig_Role_TRACKER+1)) -#define _Config_PositionConfig_PositionFlags_MIN Config_PositionConfig_PositionFlags_UNSET -#define _Config_PositionConfig_PositionFlags_MAX Config_PositionConfig_PositionFlags_SPEED -#define _Config_PositionConfig_PositionFlags_ARRAYSIZE ((Config_PositionConfig_PositionFlags)(Config_PositionConfig_PositionFlags_SPEED+1)) +#define _meshtastic_Config_DeviceConfig_RebroadcastMode_MIN meshtastic_Config_DeviceConfig_RebroadcastMode_ALL +#define _meshtastic_Config_DeviceConfig_RebroadcastMode_MAX meshtastic_Config_DeviceConfig_RebroadcastMode_LOCAL_ONLY +#define _meshtastic_Config_DeviceConfig_RebroadcastMode_ARRAYSIZE ((meshtastic_Config_DeviceConfig_RebroadcastMode)(meshtastic_Config_DeviceConfig_RebroadcastMode_LOCAL_ONLY+1)) -#define _Config_NetworkConfig_AddressMode_MIN Config_NetworkConfig_AddressMode_DHCP -#define _Config_NetworkConfig_AddressMode_MAX Config_NetworkConfig_AddressMode_STATIC -#define _Config_NetworkConfig_AddressMode_ARRAYSIZE ((Config_NetworkConfig_AddressMode)(Config_NetworkConfig_AddressMode_STATIC+1)) +#define _meshtastic_Config_PositionConfig_PositionFlags_MIN meshtastic_Config_PositionConfig_PositionFlags_UNSET +#define _meshtastic_Config_PositionConfig_PositionFlags_MAX meshtastic_Config_PositionConfig_PositionFlags_SPEED +#define _meshtastic_Config_PositionConfig_PositionFlags_ARRAYSIZE ((meshtastic_Config_PositionConfig_PositionFlags)(meshtastic_Config_PositionConfig_PositionFlags_SPEED+1)) -#define _Config_DisplayConfig_GpsCoordinateFormat_MIN Config_DisplayConfig_GpsCoordinateFormat_DEC -#define _Config_DisplayConfig_GpsCoordinateFormat_MAX Config_DisplayConfig_GpsCoordinateFormat_OSGR -#define _Config_DisplayConfig_GpsCoordinateFormat_ARRAYSIZE ((Config_DisplayConfig_GpsCoordinateFormat)(Config_DisplayConfig_GpsCoordinateFormat_OSGR+1)) +#define _meshtastic_Config_NetworkConfig_AddressMode_MIN meshtastic_Config_NetworkConfig_AddressMode_DHCP +#define _meshtastic_Config_NetworkConfig_AddressMode_MAX meshtastic_Config_NetworkConfig_AddressMode_STATIC +#define _meshtastic_Config_NetworkConfig_AddressMode_ARRAYSIZE ((meshtastic_Config_NetworkConfig_AddressMode)(meshtastic_Config_NetworkConfig_AddressMode_STATIC+1)) -#define _Config_DisplayConfig_DisplayUnits_MIN Config_DisplayConfig_DisplayUnits_METRIC -#define _Config_DisplayConfig_DisplayUnits_MAX Config_DisplayConfig_DisplayUnits_IMPERIAL -#define _Config_DisplayConfig_DisplayUnits_ARRAYSIZE ((Config_DisplayConfig_DisplayUnits)(Config_DisplayConfig_DisplayUnits_IMPERIAL+1)) +#define _meshtastic_Config_DisplayConfig_GpsCoordinateFormat_MIN meshtastic_Config_DisplayConfig_GpsCoordinateFormat_DEC +#define _meshtastic_Config_DisplayConfig_GpsCoordinateFormat_MAX meshtastic_Config_DisplayConfig_GpsCoordinateFormat_OSGR +#define _meshtastic_Config_DisplayConfig_GpsCoordinateFormat_ARRAYSIZE ((meshtastic_Config_DisplayConfig_GpsCoordinateFormat)(meshtastic_Config_DisplayConfig_GpsCoordinateFormat_OSGR+1)) -#define _Config_DisplayConfig_OledType_MIN Config_DisplayConfig_OledType_OLED_AUTO -#define _Config_DisplayConfig_OledType_MAX Config_DisplayConfig_OledType_OLED_SH1106 -#define _Config_DisplayConfig_OledType_ARRAYSIZE ((Config_DisplayConfig_OledType)(Config_DisplayConfig_OledType_OLED_SH1106+1)) +#define _meshtastic_Config_DisplayConfig_DisplayUnits_MIN meshtastic_Config_DisplayConfig_DisplayUnits_METRIC +#define _meshtastic_Config_DisplayConfig_DisplayUnits_MAX meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL +#define _meshtastic_Config_DisplayConfig_DisplayUnits_ARRAYSIZE ((meshtastic_Config_DisplayConfig_DisplayUnits)(meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL+1)) -#define _Config_DisplayConfig_DisplayMode_MIN Config_DisplayConfig_DisplayMode_DEFAULT -#define _Config_DisplayConfig_DisplayMode_MAX Config_DisplayConfig_DisplayMode_COLOR -#define _Config_DisplayConfig_DisplayMode_ARRAYSIZE ((Config_DisplayConfig_DisplayMode)(Config_DisplayConfig_DisplayMode_COLOR+1)) +#define _meshtastic_Config_DisplayConfig_OledType_MIN meshtastic_Config_DisplayConfig_OledType_OLED_AUTO +#define _meshtastic_Config_DisplayConfig_OledType_MAX meshtastic_Config_DisplayConfig_OledType_OLED_SH1107 +#define _meshtastic_Config_DisplayConfig_OledType_ARRAYSIZE ((meshtastic_Config_DisplayConfig_OledType)(meshtastic_Config_DisplayConfig_OledType_OLED_SH1107+1)) -#define _Config_LoRaConfig_RegionCode_MIN Config_LoRaConfig_RegionCode_UNSET -#define _Config_LoRaConfig_RegionCode_MAX Config_LoRaConfig_RegionCode_UA_868 -#define _Config_LoRaConfig_RegionCode_ARRAYSIZE ((Config_LoRaConfig_RegionCode)(Config_LoRaConfig_RegionCode_UA_868+1)) +#define _meshtastic_Config_DisplayConfig_DisplayMode_MIN meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT +#define _meshtastic_Config_DisplayConfig_DisplayMode_MAX meshtastic_Config_DisplayConfig_DisplayMode_COLOR +#define _meshtastic_Config_DisplayConfig_DisplayMode_ARRAYSIZE ((meshtastic_Config_DisplayConfig_DisplayMode)(meshtastic_Config_DisplayConfig_DisplayMode_COLOR+1)) -#define _Config_LoRaConfig_ModemPreset_MIN Config_LoRaConfig_ModemPreset_LONG_FAST -#define _Config_LoRaConfig_ModemPreset_MAX Config_LoRaConfig_ModemPreset_SHORT_FAST -#define _Config_LoRaConfig_ModemPreset_ARRAYSIZE ((Config_LoRaConfig_ModemPreset)(Config_LoRaConfig_ModemPreset_SHORT_FAST+1)) +#define _meshtastic_Config_LoRaConfig_RegionCode_MIN meshtastic_Config_LoRaConfig_RegionCode_UNSET +#define _meshtastic_Config_LoRaConfig_RegionCode_MAX meshtastic_Config_LoRaConfig_RegionCode_UA_868 +#define _meshtastic_Config_LoRaConfig_RegionCode_ARRAYSIZE ((meshtastic_Config_LoRaConfig_RegionCode)(meshtastic_Config_LoRaConfig_RegionCode_UA_868+1)) -#define _Config_BluetoothConfig_PairingMode_MIN Config_BluetoothConfig_PairingMode_RANDOM_PIN -#define _Config_BluetoothConfig_PairingMode_MAX Config_BluetoothConfig_PairingMode_NO_PIN -#define _Config_BluetoothConfig_PairingMode_ARRAYSIZE ((Config_BluetoothConfig_PairingMode)(Config_BluetoothConfig_PairingMode_NO_PIN+1)) +#define _meshtastic_Config_LoRaConfig_ModemPreset_MIN meshtastic_Config_LoRaConfig_ModemPreset_LONG_FAST +#define _meshtastic_Config_LoRaConfig_ModemPreset_MAX meshtastic_Config_LoRaConfig_ModemPreset_LONG_MODERATE +#define _meshtastic_Config_LoRaConfig_ModemPreset_ARRAYSIZE ((meshtastic_Config_LoRaConfig_ModemPreset)(meshtastic_Config_LoRaConfig_ModemPreset_LONG_MODERATE+1)) + +#define _meshtastic_Config_BluetoothConfig_PairingMode_MIN meshtastic_Config_BluetoothConfig_PairingMode_RANDOM_PIN +#define _meshtastic_Config_BluetoothConfig_PairingMode_MAX meshtastic_Config_BluetoothConfig_PairingMode_NO_PIN +#define _meshtastic_Config_BluetoothConfig_PairingMode_ARRAYSIZE ((meshtastic_Config_BluetoothConfig_PairingMode)(meshtastic_Config_BluetoothConfig_PairingMode_NO_PIN+1)) -#define Config_DeviceConfig_role_ENUMTYPE Config_DeviceConfig_Role +#define meshtastic_Config_DeviceConfig_role_ENUMTYPE meshtastic_Config_DeviceConfig_Role +#define meshtastic_Config_DeviceConfig_rebroadcast_mode_ENUMTYPE meshtastic_Config_DeviceConfig_RebroadcastMode -#define Config_NetworkConfig_address_mode_ENUMTYPE Config_NetworkConfig_AddressMode +#define meshtastic_Config_NetworkConfig_address_mode_ENUMTYPE meshtastic_Config_NetworkConfig_AddressMode -#define Config_DisplayConfig_gps_format_ENUMTYPE Config_DisplayConfig_GpsCoordinateFormat -#define Config_DisplayConfig_units_ENUMTYPE Config_DisplayConfig_DisplayUnits -#define Config_DisplayConfig_oled_ENUMTYPE Config_DisplayConfig_OledType -#define Config_DisplayConfig_displaymode_ENUMTYPE Config_DisplayConfig_DisplayMode +#define meshtastic_Config_DisplayConfig_gps_format_ENUMTYPE meshtastic_Config_DisplayConfig_GpsCoordinateFormat +#define meshtastic_Config_DisplayConfig_units_ENUMTYPE meshtastic_Config_DisplayConfig_DisplayUnits +#define meshtastic_Config_DisplayConfig_oled_ENUMTYPE meshtastic_Config_DisplayConfig_OledType +#define meshtastic_Config_DisplayConfig_displaymode_ENUMTYPE meshtastic_Config_DisplayConfig_DisplayMode -#define Config_LoRaConfig_modem_preset_ENUMTYPE Config_LoRaConfig_ModemPreset -#define Config_LoRaConfig_region_ENUMTYPE Config_LoRaConfig_RegionCode +#define meshtastic_Config_LoRaConfig_modem_preset_ENUMTYPE meshtastic_Config_LoRaConfig_ModemPreset +#define meshtastic_Config_LoRaConfig_region_ENUMTYPE meshtastic_Config_LoRaConfig_RegionCode -#define Config_BluetoothConfig_mode_ENUMTYPE Config_BluetoothConfig_PairingMode +#define meshtastic_Config_BluetoothConfig_mode_ENUMTYPE meshtastic_Config_BluetoothConfig_PairingMode /* Initializer values for message structs */ -#define Config_init_default {0, {Config_DeviceConfig_init_default}} -#define Config_DeviceConfig_init_default {_Config_DeviceConfig_Role_MIN, 0, 0, 0, 0} -#define Config_PositionConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} -#define Config_PowerConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0} -#define Config_NetworkConfig_init_default {0, "", "", "", 0, _Config_NetworkConfig_AddressMode_MIN, false, Config_NetworkConfig_IpV4Config_init_default, ""} -#define Config_NetworkConfig_IpV4Config_init_default {0, 0, 0, 0} -#define Config_DisplayConfig_init_default {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN, _Config_DisplayConfig_DisplayMode_MIN, 0} -#define Config_LoRaConfig_init_default {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} -#define Config_BluetoothConfig_init_default {0, _Config_BluetoothConfig_PairingMode_MIN, 0} -#define Config_init_zero {0, {Config_DeviceConfig_init_zero}} -#define Config_DeviceConfig_init_zero {_Config_DeviceConfig_Role_MIN, 0, 0, 0, 0} -#define Config_PositionConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} -#define Config_PowerConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0} -#define Config_NetworkConfig_init_zero {0, "", "", "", 0, _Config_NetworkConfig_AddressMode_MIN, false, Config_NetworkConfig_IpV4Config_init_zero, ""} -#define Config_NetworkConfig_IpV4Config_init_zero {0, 0, 0, 0} -#define Config_DisplayConfig_init_zero {0, _Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _Config_DisplayConfig_DisplayUnits_MIN, _Config_DisplayConfig_OledType_MIN, _Config_DisplayConfig_DisplayMode_MIN, 0} -#define Config_LoRaConfig_init_zero {0, _Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, {0, 0, 0}} -#define Config_BluetoothConfig_init_zero {0, _Config_BluetoothConfig_PairingMode_MIN, 0} +#define meshtastic_Config_init_default {0, {meshtastic_Config_DeviceConfig_init_default}} +#define meshtastic_Config_DeviceConfig_init_default {_meshtastic_Config_DeviceConfig_Role_MIN, 0, 0, 0, 0, _meshtastic_Config_DeviceConfig_RebroadcastMode_MIN} +#define meshtastic_Config_PositionConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_Config_PowerConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_Config_NetworkConfig_init_default {0, "", "", "", 0, _meshtastic_Config_NetworkConfig_AddressMode_MIN, false, meshtastic_Config_NetworkConfig_IpV4Config_init_default, ""} +#define meshtastic_Config_NetworkConfig_IpV4Config_init_default {0, 0, 0, 0} +#define meshtastic_Config_DisplayConfig_init_default {0, _meshtastic_Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _meshtastic_Config_DisplayConfig_DisplayUnits_MIN, _meshtastic_Config_DisplayConfig_OledType_MIN, _meshtastic_Config_DisplayConfig_DisplayMode_MIN, 0} +#define meshtastic_Config_LoRaConfig_init_default {0, _meshtastic_Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _meshtastic_Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0}} +#define meshtastic_Config_BluetoothConfig_init_default {0, _meshtastic_Config_BluetoothConfig_PairingMode_MIN, 0} +#define meshtastic_Config_init_zero {0, {meshtastic_Config_DeviceConfig_init_zero}} +#define meshtastic_Config_DeviceConfig_init_zero {_meshtastic_Config_DeviceConfig_Role_MIN, 0, 0, 0, 0, _meshtastic_Config_DeviceConfig_RebroadcastMode_MIN} +#define meshtastic_Config_PositionConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_Config_PowerConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_Config_NetworkConfig_init_zero {0, "", "", "", 0, _meshtastic_Config_NetworkConfig_AddressMode_MIN, false, meshtastic_Config_NetworkConfig_IpV4Config_init_zero, ""} +#define meshtastic_Config_NetworkConfig_IpV4Config_init_zero {0, 0, 0, 0} +#define meshtastic_Config_DisplayConfig_init_zero {0, _meshtastic_Config_DisplayConfig_GpsCoordinateFormat_MIN, 0, 0, 0, _meshtastic_Config_DisplayConfig_DisplayUnits_MIN, _meshtastic_Config_DisplayConfig_OledType_MIN, _meshtastic_Config_DisplayConfig_DisplayMode_MIN, 0} +#define meshtastic_Config_LoRaConfig_init_zero {0, _meshtastic_Config_LoRaConfig_ModemPreset_MIN, 0, 0, 0, 0, _meshtastic_Config_LoRaConfig_RegionCode_MIN, 0, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0}} +#define meshtastic_Config_BluetoothConfig_init_zero {0, _meshtastic_Config_BluetoothConfig_PairingMode_MIN, 0} /* Field tags (for use in manual encoding/decoding) */ -#define Config_DeviceConfig_role_tag 1 -#define Config_DeviceConfig_serial_enabled_tag 2 -#define Config_DeviceConfig_debug_log_enabled_tag 3 -#define Config_DeviceConfig_button_gpio_tag 4 -#define Config_DeviceConfig_buzzer_gpio_tag 5 -#define Config_PositionConfig_position_broadcast_secs_tag 1 -#define Config_PositionConfig_position_broadcast_smart_enabled_tag 2 -#define Config_PositionConfig_fixed_position_tag 3 -#define Config_PositionConfig_gps_enabled_tag 4 -#define Config_PositionConfig_gps_update_interval_tag 5 -#define Config_PositionConfig_gps_attempt_time_tag 6 -#define Config_PositionConfig_position_flags_tag 7 -#define Config_PositionConfig_rx_gpio_tag 8 -#define Config_PositionConfig_tx_gpio_tag 9 -#define Config_PowerConfig_is_power_saving_tag 1 -#define Config_PowerConfig_on_battery_shutdown_after_secs_tag 2 -#define Config_PowerConfig_adc_multiplier_override_tag 3 -#define Config_PowerConfig_wait_bluetooth_secs_tag 4 -#define Config_PowerConfig_mesh_sds_timeout_secs_tag 5 -#define Config_PowerConfig_sds_secs_tag 6 -#define Config_PowerConfig_ls_secs_tag 7 -#define Config_PowerConfig_min_wake_secs_tag 8 -#define Config_NetworkConfig_IpV4Config_ip_tag 1 -#define Config_NetworkConfig_IpV4Config_gateway_tag 2 -#define Config_NetworkConfig_IpV4Config_subnet_tag 3 -#define Config_NetworkConfig_IpV4Config_dns_tag 4 -#define Config_NetworkConfig_wifi_enabled_tag 1 -#define Config_NetworkConfig_wifi_ssid_tag 3 -#define Config_NetworkConfig_wifi_psk_tag 4 -#define Config_NetworkConfig_ntp_server_tag 5 -#define Config_NetworkConfig_eth_enabled_tag 6 -#define Config_NetworkConfig_address_mode_tag 7 -#define Config_NetworkConfig_ipv4_config_tag 8 -#define Config_NetworkConfig_rsyslog_server_tag 9 -#define Config_DisplayConfig_screen_on_secs_tag 1 -#define Config_DisplayConfig_gps_format_tag 2 -#define Config_DisplayConfig_auto_screen_carousel_secs_tag 3 -#define Config_DisplayConfig_compass_north_top_tag 4 -#define Config_DisplayConfig_flip_screen_tag 5 -#define Config_DisplayConfig_units_tag 6 -#define Config_DisplayConfig_oled_tag 7 -#define Config_DisplayConfig_displaymode_tag 8 -#define Config_DisplayConfig_heading_bold_tag 9 -#define Config_LoRaConfig_use_preset_tag 1 -#define Config_LoRaConfig_modem_preset_tag 2 -#define Config_LoRaConfig_bandwidth_tag 3 -#define Config_LoRaConfig_spread_factor_tag 4 -#define Config_LoRaConfig_coding_rate_tag 5 -#define Config_LoRaConfig_frequency_offset_tag 6 -#define Config_LoRaConfig_region_tag 7 -#define Config_LoRaConfig_hop_limit_tag 8 -#define Config_LoRaConfig_tx_enabled_tag 9 -#define Config_LoRaConfig_tx_power_tag 10 -#define Config_LoRaConfig_channel_num_tag 11 -#define Config_LoRaConfig_override_duty_cycle_tag 12 -#define Config_LoRaConfig_ignore_incoming_tag 103 -#define Config_BluetoothConfig_enabled_tag 1 -#define Config_BluetoothConfig_mode_tag 2 -#define Config_BluetoothConfig_fixed_pin_tag 3 -#define Config_device_tag 1 -#define Config_position_tag 2 -#define Config_power_tag 3 -#define Config_network_tag 4 -#define Config_display_tag 5 -#define Config_lora_tag 6 -#define Config_bluetooth_tag 7 +#define meshtastic_Config_DeviceConfig_role_tag 1 +#define meshtastic_Config_DeviceConfig_serial_enabled_tag 2 +#define meshtastic_Config_DeviceConfig_debug_log_enabled_tag 3 +#define meshtastic_Config_DeviceConfig_button_gpio_tag 4 +#define meshtastic_Config_DeviceConfig_buzzer_gpio_tag 5 +#define meshtastic_Config_DeviceConfig_rebroadcast_mode_tag 6 +#define meshtastic_Config_PositionConfig_position_broadcast_secs_tag 1 +#define meshtastic_Config_PositionConfig_position_broadcast_smart_enabled_tag 2 +#define meshtastic_Config_PositionConfig_fixed_position_tag 3 +#define meshtastic_Config_PositionConfig_gps_enabled_tag 4 +#define meshtastic_Config_PositionConfig_gps_update_interval_tag 5 +#define meshtastic_Config_PositionConfig_gps_attempt_time_tag 6 +#define meshtastic_Config_PositionConfig_position_flags_tag 7 +#define meshtastic_Config_PositionConfig_rx_gpio_tag 8 +#define meshtastic_Config_PositionConfig_tx_gpio_tag 9 +#define meshtastic_Config_PowerConfig_is_power_saving_tag 1 +#define meshtastic_Config_PowerConfig_on_battery_shutdown_after_secs_tag 2 +#define meshtastic_Config_PowerConfig_adc_multiplier_override_tag 3 +#define meshtastic_Config_PowerConfig_wait_bluetooth_secs_tag 4 +#define meshtastic_Config_PowerConfig_mesh_sds_timeout_secs_tag 5 +#define meshtastic_Config_PowerConfig_sds_secs_tag 6 +#define meshtastic_Config_PowerConfig_ls_secs_tag 7 +#define meshtastic_Config_PowerConfig_min_wake_secs_tag 8 +#define meshtastic_Config_NetworkConfig_IpV4Config_ip_tag 1 +#define meshtastic_Config_NetworkConfig_IpV4Config_gateway_tag 2 +#define meshtastic_Config_NetworkConfig_IpV4Config_subnet_tag 3 +#define meshtastic_Config_NetworkConfig_IpV4Config_dns_tag 4 +#define meshtastic_Config_NetworkConfig_wifi_enabled_tag 1 +#define meshtastic_Config_NetworkConfig_wifi_ssid_tag 3 +#define meshtastic_Config_NetworkConfig_wifi_psk_tag 4 +#define meshtastic_Config_NetworkConfig_ntp_server_tag 5 +#define meshtastic_Config_NetworkConfig_eth_enabled_tag 6 +#define meshtastic_Config_NetworkConfig_address_mode_tag 7 +#define meshtastic_Config_NetworkConfig_ipv4_config_tag 8 +#define meshtastic_Config_NetworkConfig_rsyslog_server_tag 9 +#define meshtastic_Config_DisplayConfig_screen_on_secs_tag 1 +#define meshtastic_Config_DisplayConfig_gps_format_tag 2 +#define meshtastic_Config_DisplayConfig_auto_screen_carousel_secs_tag 3 +#define meshtastic_Config_DisplayConfig_compass_north_top_tag 4 +#define meshtastic_Config_DisplayConfig_flip_screen_tag 5 +#define meshtastic_Config_DisplayConfig_units_tag 6 +#define meshtastic_Config_DisplayConfig_oled_tag 7 +#define meshtastic_Config_DisplayConfig_displaymode_tag 8 +#define meshtastic_Config_DisplayConfig_heading_bold_tag 9 +#define meshtastic_Config_LoRaConfig_use_preset_tag 1 +#define meshtastic_Config_LoRaConfig_modem_preset_tag 2 +#define meshtastic_Config_LoRaConfig_bandwidth_tag 3 +#define meshtastic_Config_LoRaConfig_spread_factor_tag 4 +#define meshtastic_Config_LoRaConfig_coding_rate_tag 5 +#define meshtastic_Config_LoRaConfig_frequency_offset_tag 6 +#define meshtastic_Config_LoRaConfig_region_tag 7 +#define meshtastic_Config_LoRaConfig_hop_limit_tag 8 +#define meshtastic_Config_LoRaConfig_tx_enabled_tag 9 +#define meshtastic_Config_LoRaConfig_tx_power_tag 10 +#define meshtastic_Config_LoRaConfig_channel_num_tag 11 +#define meshtastic_Config_LoRaConfig_override_duty_cycle_tag 12 +#define meshtastic_Config_LoRaConfig_sx126x_rx_boosted_gain_tag 13 +#define meshtastic_Config_LoRaConfig_override_frequency_tag 14 +#define meshtastic_Config_LoRaConfig_ignore_incoming_tag 103 +#define meshtastic_Config_BluetoothConfig_enabled_tag 1 +#define meshtastic_Config_BluetoothConfig_mode_tag 2 +#define meshtastic_Config_BluetoothConfig_fixed_pin_tag 3 +#define meshtastic_Config_device_tag 1 +#define meshtastic_Config_position_tag 2 +#define meshtastic_Config_power_tag 3 +#define meshtastic_Config_network_tag 4 +#define meshtastic_Config_display_tag 5 +#define meshtastic_Config_lora_tag 6 +#define meshtastic_Config_bluetooth_tag 7 /* Struct field encoding specification for nanopb */ -#define Config_FIELDLIST(X, a) \ +#define meshtastic_Config_FIELDLIST(X, a) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,device,payload_variant.device), 1) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,position,payload_variant.position), 2) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,power,payload_variant.power), 3) \ @@ -570,26 +613,27 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,network,payload_variant.netw X(a, STATIC, ONEOF, MESSAGE, (payload_variant,display,payload_variant.display), 5) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,lora,payload_variant.lora), 6) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,bluetooth,payload_variant.bluetooth), 7) -#define Config_CALLBACK NULL -#define Config_DEFAULT NULL -#define Config_payload_variant_device_MSGTYPE Config_DeviceConfig -#define Config_payload_variant_position_MSGTYPE Config_PositionConfig -#define Config_payload_variant_power_MSGTYPE Config_PowerConfig -#define Config_payload_variant_network_MSGTYPE Config_NetworkConfig -#define Config_payload_variant_display_MSGTYPE Config_DisplayConfig -#define Config_payload_variant_lora_MSGTYPE Config_LoRaConfig -#define Config_payload_variant_bluetooth_MSGTYPE Config_BluetoothConfig +#define meshtastic_Config_CALLBACK NULL +#define meshtastic_Config_DEFAULT NULL +#define meshtastic_Config_payload_variant_device_MSGTYPE meshtastic_Config_DeviceConfig +#define meshtastic_Config_payload_variant_position_MSGTYPE meshtastic_Config_PositionConfig +#define meshtastic_Config_payload_variant_power_MSGTYPE meshtastic_Config_PowerConfig +#define meshtastic_Config_payload_variant_network_MSGTYPE meshtastic_Config_NetworkConfig +#define meshtastic_Config_payload_variant_display_MSGTYPE meshtastic_Config_DisplayConfig +#define meshtastic_Config_payload_variant_lora_MSGTYPE meshtastic_Config_LoRaConfig +#define meshtastic_Config_payload_variant_bluetooth_MSGTYPE meshtastic_Config_BluetoothConfig -#define Config_DeviceConfig_FIELDLIST(X, a) \ +#define meshtastic_Config_DeviceConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, role, 1) \ X(a, STATIC, SINGULAR, BOOL, serial_enabled, 2) \ X(a, STATIC, SINGULAR, BOOL, debug_log_enabled, 3) \ X(a, STATIC, SINGULAR, UINT32, button_gpio, 4) \ -X(a, STATIC, SINGULAR, UINT32, buzzer_gpio, 5) -#define Config_DeviceConfig_CALLBACK NULL -#define Config_DeviceConfig_DEFAULT NULL +X(a, STATIC, SINGULAR, UINT32, buzzer_gpio, 5) \ +X(a, STATIC, SINGULAR, UENUM, rebroadcast_mode, 6) +#define meshtastic_Config_DeviceConfig_CALLBACK NULL +#define meshtastic_Config_DeviceConfig_DEFAULT NULL -#define Config_PositionConfig_FIELDLIST(X, a) \ +#define meshtastic_Config_PositionConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, position_broadcast_secs, 1) \ X(a, STATIC, SINGULAR, BOOL, position_broadcast_smart_enabled, 2) \ X(a, STATIC, SINGULAR, BOOL, fixed_position, 3) \ @@ -599,10 +643,10 @@ X(a, STATIC, SINGULAR, UINT32, gps_attempt_time, 6) \ X(a, STATIC, SINGULAR, UINT32, position_flags, 7) \ X(a, STATIC, SINGULAR, UINT32, rx_gpio, 8) \ X(a, STATIC, SINGULAR, UINT32, tx_gpio, 9) -#define Config_PositionConfig_CALLBACK NULL -#define Config_PositionConfig_DEFAULT NULL +#define meshtastic_Config_PositionConfig_CALLBACK NULL +#define meshtastic_Config_PositionConfig_DEFAULT NULL -#define Config_PowerConfig_FIELDLIST(X, a) \ +#define meshtastic_Config_PowerConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, is_power_saving, 1) \ X(a, STATIC, SINGULAR, UINT32, on_battery_shutdown_after_secs, 2) \ X(a, STATIC, SINGULAR, FLOAT, adc_multiplier_override, 3) \ @@ -611,10 +655,10 @@ X(a, STATIC, SINGULAR, UINT32, mesh_sds_timeout_secs, 5) \ X(a, STATIC, SINGULAR, UINT32, sds_secs, 6) \ X(a, STATIC, SINGULAR, UINT32, ls_secs, 7) \ X(a, STATIC, SINGULAR, UINT32, min_wake_secs, 8) -#define Config_PowerConfig_CALLBACK NULL -#define Config_PowerConfig_DEFAULT NULL +#define meshtastic_Config_PowerConfig_CALLBACK NULL +#define meshtastic_Config_PowerConfig_DEFAULT NULL -#define Config_NetworkConfig_FIELDLIST(X, a) \ +#define meshtastic_Config_NetworkConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, wifi_enabled, 1) \ X(a, STATIC, SINGULAR, STRING, wifi_ssid, 3) \ X(a, STATIC, SINGULAR, STRING, wifi_psk, 4) \ @@ -623,19 +667,19 @@ X(a, STATIC, SINGULAR, BOOL, eth_enabled, 6) \ X(a, STATIC, SINGULAR, UENUM, address_mode, 7) \ X(a, STATIC, OPTIONAL, MESSAGE, ipv4_config, 8) \ X(a, STATIC, SINGULAR, STRING, rsyslog_server, 9) -#define Config_NetworkConfig_CALLBACK NULL -#define Config_NetworkConfig_DEFAULT NULL -#define Config_NetworkConfig_ipv4_config_MSGTYPE Config_NetworkConfig_IpV4Config +#define meshtastic_Config_NetworkConfig_CALLBACK NULL +#define meshtastic_Config_NetworkConfig_DEFAULT NULL +#define meshtastic_Config_NetworkConfig_ipv4_config_MSGTYPE meshtastic_Config_NetworkConfig_IpV4Config -#define Config_NetworkConfig_IpV4Config_FIELDLIST(X, a) \ +#define meshtastic_Config_NetworkConfig_IpV4Config_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, FIXED32, ip, 1) \ X(a, STATIC, SINGULAR, FIXED32, gateway, 2) \ X(a, STATIC, SINGULAR, FIXED32, subnet, 3) \ X(a, STATIC, SINGULAR, FIXED32, dns, 4) -#define Config_NetworkConfig_IpV4Config_CALLBACK NULL -#define Config_NetworkConfig_IpV4Config_DEFAULT NULL +#define meshtastic_Config_NetworkConfig_IpV4Config_CALLBACK NULL +#define meshtastic_Config_NetworkConfig_IpV4Config_DEFAULT NULL -#define Config_DisplayConfig_FIELDLIST(X, a) \ +#define meshtastic_Config_DisplayConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, screen_on_secs, 1) \ X(a, STATIC, SINGULAR, UENUM, gps_format, 2) \ X(a, STATIC, SINGULAR, UINT32, auto_screen_carousel_secs, 3) \ @@ -645,10 +689,10 @@ X(a, STATIC, SINGULAR, UENUM, units, 6) \ X(a, STATIC, SINGULAR, UENUM, oled, 7) \ X(a, STATIC, SINGULAR, UENUM, displaymode, 8) \ X(a, STATIC, SINGULAR, BOOL, heading_bold, 9) -#define Config_DisplayConfig_CALLBACK NULL -#define Config_DisplayConfig_DEFAULT NULL +#define meshtastic_Config_DisplayConfig_CALLBACK NULL +#define meshtastic_Config_DisplayConfig_DEFAULT NULL -#define Config_LoRaConfig_FIELDLIST(X, a) \ +#define meshtastic_Config_LoRaConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, use_preset, 1) \ X(a, STATIC, SINGULAR, UENUM, modem_preset, 2) \ X(a, STATIC, SINGULAR, UINT32, bandwidth, 3) \ @@ -661,48 +705,50 @@ X(a, STATIC, SINGULAR, BOOL, tx_enabled, 9) \ X(a, STATIC, SINGULAR, INT32, tx_power, 10) \ X(a, STATIC, SINGULAR, UINT32, channel_num, 11) \ X(a, STATIC, SINGULAR, BOOL, override_duty_cycle, 12) \ +X(a, STATIC, SINGULAR, BOOL, sx126x_rx_boosted_gain, 13) \ +X(a, STATIC, SINGULAR, FLOAT, override_frequency, 14) \ X(a, STATIC, REPEATED, UINT32, ignore_incoming, 103) -#define Config_LoRaConfig_CALLBACK NULL -#define Config_LoRaConfig_DEFAULT NULL +#define meshtastic_Config_LoRaConfig_CALLBACK NULL +#define meshtastic_Config_LoRaConfig_DEFAULT NULL -#define Config_BluetoothConfig_FIELDLIST(X, a) \ +#define meshtastic_Config_BluetoothConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) \ X(a, STATIC, SINGULAR, UENUM, mode, 2) \ X(a, STATIC, SINGULAR, UINT32, fixed_pin, 3) -#define Config_BluetoothConfig_CALLBACK NULL -#define Config_BluetoothConfig_DEFAULT NULL +#define meshtastic_Config_BluetoothConfig_CALLBACK NULL +#define meshtastic_Config_BluetoothConfig_DEFAULT NULL -extern const pb_msgdesc_t Config_msg; -extern const pb_msgdesc_t Config_DeviceConfig_msg; -extern const pb_msgdesc_t Config_PositionConfig_msg; -extern const pb_msgdesc_t Config_PowerConfig_msg; -extern const pb_msgdesc_t Config_NetworkConfig_msg; -extern const pb_msgdesc_t Config_NetworkConfig_IpV4Config_msg; -extern const pb_msgdesc_t Config_DisplayConfig_msg; -extern const pb_msgdesc_t Config_LoRaConfig_msg; -extern const pb_msgdesc_t Config_BluetoothConfig_msg; +extern const pb_msgdesc_t meshtastic_Config_msg; +extern const pb_msgdesc_t meshtastic_Config_DeviceConfig_msg; +extern const pb_msgdesc_t meshtastic_Config_PositionConfig_msg; +extern const pb_msgdesc_t meshtastic_Config_PowerConfig_msg; +extern const pb_msgdesc_t meshtastic_Config_NetworkConfig_msg; +extern const pb_msgdesc_t meshtastic_Config_NetworkConfig_IpV4Config_msg; +extern const pb_msgdesc_t meshtastic_Config_DisplayConfig_msg; +extern const pb_msgdesc_t meshtastic_Config_LoRaConfig_msg; +extern const pb_msgdesc_t meshtastic_Config_BluetoothConfig_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define Config_fields &Config_msg -#define Config_DeviceConfig_fields &Config_DeviceConfig_msg -#define Config_PositionConfig_fields &Config_PositionConfig_msg -#define Config_PowerConfig_fields &Config_PowerConfig_msg -#define Config_NetworkConfig_fields &Config_NetworkConfig_msg -#define Config_NetworkConfig_IpV4Config_fields &Config_NetworkConfig_IpV4Config_msg -#define Config_DisplayConfig_fields &Config_DisplayConfig_msg -#define Config_LoRaConfig_fields &Config_LoRaConfig_msg -#define Config_BluetoothConfig_fields &Config_BluetoothConfig_msg +#define meshtastic_Config_fields &meshtastic_Config_msg +#define meshtastic_Config_DeviceConfig_fields &meshtastic_Config_DeviceConfig_msg +#define meshtastic_Config_PositionConfig_fields &meshtastic_Config_PositionConfig_msg +#define meshtastic_Config_PowerConfig_fields &meshtastic_Config_PowerConfig_msg +#define meshtastic_Config_NetworkConfig_fields &meshtastic_Config_NetworkConfig_msg +#define meshtastic_Config_NetworkConfig_IpV4Config_fields &meshtastic_Config_NetworkConfig_IpV4Config_msg +#define meshtastic_Config_DisplayConfig_fields &meshtastic_Config_DisplayConfig_msg +#define meshtastic_Config_LoRaConfig_fields &meshtastic_Config_LoRaConfig_msg +#define meshtastic_Config_BluetoothConfig_fields &meshtastic_Config_BluetoothConfig_msg /* Maximum encoded size of messages (where known) */ -#define Config_BluetoothConfig_size 10 -#define Config_DeviceConfig_size 18 -#define Config_DisplayConfig_size 26 -#define Config_LoRaConfig_size 70 -#define Config_NetworkConfig_IpV4Config_size 20 -#define Config_NetworkConfig_size 195 -#define Config_PositionConfig_size 42 -#define Config_PowerConfig_size 43 -#define Config_size 198 +#define meshtastic_Config_BluetoothConfig_size 10 +#define meshtastic_Config_DeviceConfig_size 20 +#define meshtastic_Config_DisplayConfig_size 26 +#define meshtastic_Config_LoRaConfig_size 77 +#define meshtastic_Config_NetworkConfig_IpV4Config_size 20 +#define meshtastic_Config_NetworkConfig_size 195 +#define meshtastic_Config_PositionConfig_size 42 +#define meshtastic_Config_PowerConfig_size 43 +#define meshtastic_Config_size 198 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/device_metadata.pb.c b/src/mesh/generated/meshtastic/device_metadata.pb.c index 725ac4c9f..627ce3244 100644 --- a/src/mesh/generated/meshtastic/device_metadata.pb.c +++ b/src/mesh/generated/meshtastic/device_metadata.pb.c @@ -1,12 +1,12 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./device_metadata.pb.h" +#include "meshtastic/device_metadata.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(DeviceMetadata, DeviceMetadata, AUTO) +PB_BIND(meshtastic_DeviceMetadata, meshtastic_DeviceMetadata, AUTO) diff --git a/src/mesh/generated/meshtastic/device_metadata.pb.h b/src/mesh/generated/meshtastic/device_metadata.pb.h index cf6314e19..384863601 100644 --- a/src/mesh/generated/meshtastic/device_metadata.pb.h +++ b/src/mesh/generated/meshtastic/device_metadata.pb.h @@ -4,7 +4,7 @@ #ifndef PB_MESHTASTIC_MESHTASTIC_DEVICE_METADATA_PB_H_INCLUDED #define PB_MESHTASTIC_MESHTASTIC_DEVICE_METADATA_PB_H_INCLUDED #include -#include "./config.pb.h" +#include "meshtastic/config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -12,7 +12,7 @@ /* Struct definitions */ /* Device metadata response */ -typedef struct _DeviceMetadata { +typedef struct _meshtastic_DeviceMetadata { /* Device firmware version string */ char firmware_version[18]; /* Device state version */ @@ -26,10 +26,10 @@ typedef struct _DeviceMetadata { /* Indicates that the device has an ethernet peripheral */ bool hasEthernet; /* Indicates that the device's role in the mesh */ - Config_DeviceConfig_Role role; + meshtastic_Config_DeviceConfig_Role role; /* Indicates the device's current enabled position flags */ uint32_t position_flags; -} DeviceMetadata; +} meshtastic_DeviceMetadata; #ifdef __cplusplus @@ -37,21 +37,21 @@ extern "C" { #endif /* Initializer values for message structs */ -#define DeviceMetadata_init_default {"", 0, 0, 0, 0, 0, _Config_DeviceConfig_Role_MIN, 0} -#define DeviceMetadata_init_zero {"", 0, 0, 0, 0, 0, _Config_DeviceConfig_Role_MIN, 0} +#define meshtastic_DeviceMetadata_init_default {"", 0, 0, 0, 0, 0, _meshtastic_Config_DeviceConfig_Role_MIN, 0} +#define meshtastic_DeviceMetadata_init_zero {"", 0, 0, 0, 0, 0, _meshtastic_Config_DeviceConfig_Role_MIN, 0} /* Field tags (for use in manual encoding/decoding) */ -#define DeviceMetadata_firmware_version_tag 1 -#define DeviceMetadata_device_state_version_tag 2 -#define DeviceMetadata_canShutdown_tag 3 -#define DeviceMetadata_hasWifi_tag 4 -#define DeviceMetadata_hasBluetooth_tag 5 -#define DeviceMetadata_hasEthernet_tag 6 -#define DeviceMetadata_role_tag 7 -#define DeviceMetadata_position_flags_tag 8 +#define meshtastic_DeviceMetadata_firmware_version_tag 1 +#define meshtastic_DeviceMetadata_device_state_version_tag 2 +#define meshtastic_DeviceMetadata_canShutdown_tag 3 +#define meshtastic_DeviceMetadata_hasWifi_tag 4 +#define meshtastic_DeviceMetadata_hasBluetooth_tag 5 +#define meshtastic_DeviceMetadata_hasEthernet_tag 6 +#define meshtastic_DeviceMetadata_role_tag 7 +#define meshtastic_DeviceMetadata_position_flags_tag 8 /* Struct field encoding specification for nanopb */ -#define DeviceMetadata_FIELDLIST(X, a) \ +#define meshtastic_DeviceMetadata_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, STRING, firmware_version, 1) \ X(a, STATIC, SINGULAR, UINT32, device_state_version, 2) \ X(a, STATIC, SINGULAR, BOOL, canShutdown, 3) \ @@ -60,16 +60,16 @@ X(a, STATIC, SINGULAR, BOOL, hasBluetooth, 5) \ X(a, STATIC, SINGULAR, BOOL, hasEthernet, 6) \ X(a, STATIC, SINGULAR, UENUM, role, 7) \ X(a, STATIC, SINGULAR, UINT32, position_flags, 8) -#define DeviceMetadata_CALLBACK NULL -#define DeviceMetadata_DEFAULT NULL +#define meshtastic_DeviceMetadata_CALLBACK NULL +#define meshtastic_DeviceMetadata_DEFAULT NULL -extern const pb_msgdesc_t DeviceMetadata_msg; +extern const pb_msgdesc_t meshtastic_DeviceMetadata_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define DeviceMetadata_fields &DeviceMetadata_msg +#define meshtastic_DeviceMetadata_fields &meshtastic_DeviceMetadata_msg /* Maximum encoded size of messages (where known) */ -#define DeviceMetadata_size 41 +#define meshtastic_DeviceMetadata_size 41 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/deviceonly.pb.c b/src/mesh/generated/meshtastic/deviceonly.pb.c index 0b26e68d1..f3d27d086 100644 --- a/src/mesh/generated/meshtastic/deviceonly.pb.c +++ b/src/mesh/generated/meshtastic/deviceonly.pb.c @@ -1,18 +1,18 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./deviceonly.pb.h" +#include "meshtastic/deviceonly.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(DeviceState, DeviceState, 4) +PB_BIND(meshtastic_DeviceState, meshtastic_DeviceState, 4) -PB_BIND(ChannelFile, ChannelFile, 2) +PB_BIND(meshtastic_ChannelFile, meshtastic_ChannelFile, 2) -PB_BIND(OEMStore, OEMStore, 2) +PB_BIND(meshtastic_OEMStore, meshtastic_OEMStore, 2) diff --git a/src/mesh/generated/meshtastic/deviceonly.pb.h b/src/mesh/generated/meshtastic/deviceonly.pb.h index 234b65d00..842431b28 100644 --- a/src/mesh/generated/meshtastic/deviceonly.pb.h +++ b/src/mesh/generated/meshtastic/deviceonly.pb.h @@ -4,8 +4,8 @@ #ifndef PB_MESHTASTIC_MESHTASTIC_DEVICEONLY_PB_H_INCLUDED #define PB_MESHTASTIC_MESHTASTIC_DEVICEONLY_PB_H_INCLUDED #include -#include "./channel.pb.h" -#include "./mesh.pb.h" +#include "meshtastic/channel.pb.h" +#include "meshtastic/mesh.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -13,14 +13,14 @@ /* Enum definitions */ /* TODO: REPLACE */ -typedef enum _ScreenFonts { +typedef enum _meshtastic_ScreenFonts { /* TODO: REPLACE */ - ScreenFonts_FONT_SMALL = 0, + meshtastic_ScreenFonts_FONT_SMALL = 0, /* TODO: REPLACE */ - ScreenFonts_FONT_MEDIUM = 1, + meshtastic_ScreenFonts_FONT_MEDIUM = 1, /* TODO: REPLACE */ - ScreenFonts_FONT_LARGE = 2 -} ScreenFonts; + meshtastic_ScreenFonts_FONT_LARGE = 2 +} meshtastic_ScreenFonts; /* Struct definitions */ /* This message is never sent over the wire, but it is used for serializing DB @@ -28,24 +28,24 @@ typedef enum _ScreenFonts { FIXME, since we write this each time we enter deep sleep (and have infinite flash) it would be better to use some sort of append only data structure for the receive queue and use the preferences store for the other stuff */ -typedef struct _DeviceState { +typedef struct _meshtastic_DeviceState { /* Read only settings/info about this node */ bool has_my_node; - MyNodeInfo my_node; + meshtastic_MyNodeInfo my_node; /* My owner info */ bool has_owner; - User owner; + meshtastic_User owner; /* TODO: REPLACE */ pb_size_t node_db_count; - NodeInfo node_db[80]; + meshtastic_NodeInfo node_db[80]; /* Received packets saved for delivery to the phone */ pb_size_t receive_queue_count; - MeshPacket receive_queue[1]; + meshtastic_MeshPacket receive_queue[1]; /* We keep the last received text message (only) stored in the device flash, so we can show it on the screen. Might be null */ bool has_rx_text_message; - MeshPacket rx_text_message; + meshtastic_MeshPacket rx_text_message; /* A version integer used to invalidate old save files when we make incompatible changes This integer is set at build time and is private to NodeDB.cpp in the device code. */ @@ -55,37 +55,37 @@ typedef struct _DeviceState { bool no_save; /* Some GPSes seem to have bogus settings from the factory, so we always do one factory reset. */ bool did_gps_reset; -} DeviceState; +} meshtastic_DeviceState; /* The on-disk saved channels */ -typedef struct _ChannelFile { +typedef struct _meshtastic_ChannelFile { /* The channels our node knows about */ pb_size_t channels_count; - Channel channels[8]; + meshtastic_Channel channels[8]; /* A version integer used to invalidate old save files when we make incompatible changes This integer is set at build time and is private to NodeDB.cpp in the device code. */ uint32_t version; -} ChannelFile; +} meshtastic_ChannelFile; -typedef PB_BYTES_ARRAY_T(2048) OEMStore_oem_icon_bits_t; -typedef PB_BYTES_ARRAY_T(32) OEMStore_oem_aes_key_t; +typedef PB_BYTES_ARRAY_T(2048) meshtastic_OEMStore_oem_icon_bits_t; +typedef PB_BYTES_ARRAY_T(32) meshtastic_OEMStore_oem_aes_key_t; /* This can be used for customizing the firmware distribution. If populated, show a secondary bootup screen with cuatom logo and text for 2.5 seconds. */ -typedef struct _OEMStore { +typedef struct _meshtastic_OEMStore { /* The Logo width in Px */ uint32_t oem_icon_width; /* The Logo height in Px */ uint32_t oem_icon_height; /* The Logo in xbm bytechar format */ - OEMStore_oem_icon_bits_t oem_icon_bits; + meshtastic_OEMStore_oem_icon_bits_t oem_icon_bits; /* Use this font for the OEM text. */ - ScreenFonts oem_font; + meshtastic_ScreenFonts oem_font; /* Use this font for the OEM text. */ char oem_text[40]; /* The default device encryption key, 16 or 32 byte */ - OEMStore_oem_aes_key_t oem_aes_key; -} OEMStore; + meshtastic_OEMStore_oem_aes_key_t oem_aes_key; +} meshtastic_OEMStore; #ifdef __cplusplus @@ -93,43 +93,43 @@ extern "C" { #endif /* Helper constants for enums */ -#define _ScreenFonts_MIN ScreenFonts_FONT_SMALL -#define _ScreenFonts_MAX ScreenFonts_FONT_LARGE -#define _ScreenFonts_ARRAYSIZE ((ScreenFonts)(ScreenFonts_FONT_LARGE+1)) +#define _meshtastic_ScreenFonts_MIN meshtastic_ScreenFonts_FONT_SMALL +#define _meshtastic_ScreenFonts_MAX meshtastic_ScreenFonts_FONT_LARGE +#define _meshtastic_ScreenFonts_ARRAYSIZE ((meshtastic_ScreenFonts)(meshtastic_ScreenFonts_FONT_LARGE+1)) -#define OEMStore_oem_font_ENUMTYPE ScreenFonts +#define meshtastic_OEMStore_oem_font_ENUMTYPE meshtastic_ScreenFonts /* Initializer values for message structs */ -#define DeviceState_init_default {false, MyNodeInfo_init_default, false, User_init_default, 0, {NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default, NodeInfo_init_default}, 0, {MeshPacket_init_default}, false, MeshPacket_init_default, 0, 0, 0} -#define ChannelFile_init_default {0, {Channel_init_default, Channel_init_default, Channel_init_default, Channel_init_default, Channel_init_default, Channel_init_default, Channel_init_default, Channel_init_default}, 0} -#define OEMStore_init_default {0, 0, {0, {0}}, _ScreenFonts_MIN, "", {0, {0}}} -#define DeviceState_init_zero {false, MyNodeInfo_init_zero, false, User_init_zero, 0, {NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero, NodeInfo_init_zero}, 0, {MeshPacket_init_zero}, false, MeshPacket_init_zero, 0, 0, 0} -#define ChannelFile_init_zero {0, {Channel_init_zero, Channel_init_zero, Channel_init_zero, Channel_init_zero, Channel_init_zero, Channel_init_zero, Channel_init_zero, Channel_init_zero}, 0} -#define OEMStore_init_zero {0, 0, {0, {0}}, _ScreenFonts_MIN, "", {0, {0}}} +#define meshtastic_DeviceState_init_default {false, meshtastic_MyNodeInfo_init_default, false, meshtastic_User_init_default, 0, {meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default, meshtastic_NodeInfo_init_default}, 0, {meshtastic_MeshPacket_init_default}, false, meshtastic_MeshPacket_init_default, 0, 0, 0} +#define meshtastic_ChannelFile_init_default {0, {meshtastic_Channel_init_default, meshtastic_Channel_init_default, meshtastic_Channel_init_default, meshtastic_Channel_init_default, meshtastic_Channel_init_default, meshtastic_Channel_init_default, meshtastic_Channel_init_default, meshtastic_Channel_init_default}, 0} +#define meshtastic_OEMStore_init_default {0, 0, {0, {0}}, _meshtastic_ScreenFonts_MIN, "", {0, {0}}} +#define meshtastic_DeviceState_init_zero {false, meshtastic_MyNodeInfo_init_zero, false, meshtastic_User_init_zero, 0, {meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero, meshtastic_NodeInfo_init_zero}, 0, {meshtastic_MeshPacket_init_zero}, false, meshtastic_MeshPacket_init_zero, 0, 0, 0} +#define meshtastic_ChannelFile_init_zero {0, {meshtastic_Channel_init_zero, meshtastic_Channel_init_zero, meshtastic_Channel_init_zero, meshtastic_Channel_init_zero, meshtastic_Channel_init_zero, meshtastic_Channel_init_zero, meshtastic_Channel_init_zero, meshtastic_Channel_init_zero}, 0} +#define meshtastic_OEMStore_init_zero {0, 0, {0, {0}}, _meshtastic_ScreenFonts_MIN, "", {0, {0}}} /* Field tags (for use in manual encoding/decoding) */ -#define DeviceState_my_node_tag 2 -#define DeviceState_owner_tag 3 -#define DeviceState_node_db_tag 4 -#define DeviceState_receive_queue_tag 5 -#define DeviceState_rx_text_message_tag 7 -#define DeviceState_version_tag 8 -#define DeviceState_no_save_tag 9 -#define DeviceState_did_gps_reset_tag 11 -#define ChannelFile_channels_tag 1 -#define ChannelFile_version_tag 2 -#define OEMStore_oem_icon_width_tag 1 -#define OEMStore_oem_icon_height_tag 2 -#define OEMStore_oem_icon_bits_tag 3 -#define OEMStore_oem_font_tag 4 -#define OEMStore_oem_text_tag 5 -#define OEMStore_oem_aes_key_tag 6 +#define meshtastic_DeviceState_my_node_tag 2 +#define meshtastic_DeviceState_owner_tag 3 +#define meshtastic_DeviceState_node_db_tag 4 +#define meshtastic_DeviceState_receive_queue_tag 5 +#define meshtastic_DeviceState_rx_text_message_tag 7 +#define meshtastic_DeviceState_version_tag 8 +#define meshtastic_DeviceState_no_save_tag 9 +#define meshtastic_DeviceState_did_gps_reset_tag 11 +#define meshtastic_ChannelFile_channels_tag 1 +#define meshtastic_ChannelFile_version_tag 2 +#define meshtastic_OEMStore_oem_icon_width_tag 1 +#define meshtastic_OEMStore_oem_icon_height_tag 2 +#define meshtastic_OEMStore_oem_icon_bits_tag 3 +#define meshtastic_OEMStore_oem_font_tag 4 +#define meshtastic_OEMStore_oem_text_tag 5 +#define meshtastic_OEMStore_oem_aes_key_tag 6 /* Struct field encoding specification for nanopb */ -#define DeviceState_FIELDLIST(X, a) \ +#define meshtastic_DeviceState_FIELDLIST(X, a) \ X(a, STATIC, OPTIONAL, MESSAGE, my_node, 2) \ X(a, STATIC, OPTIONAL, MESSAGE, owner, 3) \ X(a, STATIC, REPEATED, MESSAGE, node_db, 4) \ @@ -138,44 +138,44 @@ X(a, STATIC, OPTIONAL, MESSAGE, rx_text_message, 7) \ X(a, STATIC, SINGULAR, UINT32, version, 8) \ X(a, STATIC, SINGULAR, BOOL, no_save, 9) \ X(a, STATIC, SINGULAR, BOOL, did_gps_reset, 11) -#define DeviceState_CALLBACK NULL -#define DeviceState_DEFAULT NULL -#define DeviceState_my_node_MSGTYPE MyNodeInfo -#define DeviceState_owner_MSGTYPE User -#define DeviceState_node_db_MSGTYPE NodeInfo -#define DeviceState_receive_queue_MSGTYPE MeshPacket -#define DeviceState_rx_text_message_MSGTYPE MeshPacket +#define meshtastic_DeviceState_CALLBACK NULL +#define meshtastic_DeviceState_DEFAULT NULL +#define meshtastic_DeviceState_my_node_MSGTYPE meshtastic_MyNodeInfo +#define meshtastic_DeviceState_owner_MSGTYPE meshtastic_User +#define meshtastic_DeviceState_node_db_MSGTYPE meshtastic_NodeInfo +#define meshtastic_DeviceState_receive_queue_MSGTYPE meshtastic_MeshPacket +#define meshtastic_DeviceState_rx_text_message_MSGTYPE meshtastic_MeshPacket -#define ChannelFile_FIELDLIST(X, a) \ +#define meshtastic_ChannelFile_FIELDLIST(X, a) \ X(a, STATIC, REPEATED, MESSAGE, channels, 1) \ X(a, STATIC, SINGULAR, UINT32, version, 2) -#define ChannelFile_CALLBACK NULL -#define ChannelFile_DEFAULT NULL -#define ChannelFile_channels_MSGTYPE Channel +#define meshtastic_ChannelFile_CALLBACK NULL +#define meshtastic_ChannelFile_DEFAULT NULL +#define meshtastic_ChannelFile_channels_MSGTYPE meshtastic_Channel -#define OEMStore_FIELDLIST(X, a) \ +#define meshtastic_OEMStore_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, oem_icon_width, 1) \ X(a, STATIC, SINGULAR, UINT32, oem_icon_height, 2) \ X(a, STATIC, SINGULAR, BYTES, oem_icon_bits, 3) \ X(a, STATIC, SINGULAR, UENUM, oem_font, 4) \ X(a, STATIC, SINGULAR, STRING, oem_text, 5) \ X(a, STATIC, SINGULAR, BYTES, oem_aes_key, 6) -#define OEMStore_CALLBACK NULL -#define OEMStore_DEFAULT NULL +#define meshtastic_OEMStore_CALLBACK NULL +#define meshtastic_OEMStore_DEFAULT NULL -extern const pb_msgdesc_t DeviceState_msg; -extern const pb_msgdesc_t ChannelFile_msg; -extern const pb_msgdesc_t OEMStore_msg; +extern const pb_msgdesc_t meshtastic_DeviceState_msg; +extern const pb_msgdesc_t meshtastic_ChannelFile_msg; +extern const pb_msgdesc_t meshtastic_OEMStore_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define DeviceState_fields &DeviceState_msg -#define ChannelFile_fields &ChannelFile_msg -#define OEMStore_fields &OEMStore_msg +#define meshtastic_DeviceState_fields &meshtastic_DeviceState_msg +#define meshtastic_ChannelFile_fields &meshtastic_ChannelFile_msg +#define meshtastic_OEMStore_fields &meshtastic_OEMStore_msg /* Maximum encoded size of messages (where known) */ -#define ChannelFile_size 638 -#define DeviceState_size 21800 -#define OEMStore_size 2140 +#define meshtastic_ChannelFile_size 638 +#define meshtastic_DeviceState_size 21800 +#define meshtastic_OEMStore_size 2140 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/localonly.pb.c b/src/mesh/generated/meshtastic/localonly.pb.c index b6be65c46..8fc3f1139 100644 --- a/src/mesh/generated/meshtastic/localonly.pb.c +++ b/src/mesh/generated/meshtastic/localonly.pb.c @@ -1,15 +1,15 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./localonly.pb.h" +#include "meshtastic/localonly.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(LocalConfig, LocalConfig, 2) +PB_BIND(meshtastic_LocalConfig, meshtastic_LocalConfig, 2) -PB_BIND(LocalModuleConfig, LocalModuleConfig, 2) +PB_BIND(meshtastic_LocalModuleConfig, meshtastic_LocalModuleConfig, 2) diff --git a/src/mesh/generated/meshtastic/localonly.pb.h b/src/mesh/generated/meshtastic/localonly.pb.h index fbaa06666..29448b3ee 100644 --- a/src/mesh/generated/meshtastic/localonly.pb.h +++ b/src/mesh/generated/meshtastic/localonly.pb.h @@ -4,75 +4,75 @@ #ifndef PB_MESHTASTIC_MESHTASTIC_LOCALONLY_PB_H_INCLUDED #define PB_MESHTASTIC_MESHTASTIC_LOCALONLY_PB_H_INCLUDED #include -#include "./config.pb.h" -#include "./module_config.pb.h" +#include "meshtastic/config.pb.h" +#include "meshtastic/module_config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif /* Struct definitions */ -typedef struct _LocalConfig { +typedef struct _meshtastic_LocalConfig { /* The part of the config that is specific to the Device */ bool has_device; - Config_DeviceConfig device; + meshtastic_Config_DeviceConfig device; /* The part of the config that is specific to the GPS Position */ bool has_position; - Config_PositionConfig position; + meshtastic_Config_PositionConfig position; /* The part of the config that is specific to the Power settings */ bool has_power; - Config_PowerConfig power; + meshtastic_Config_PowerConfig power; /* The part of the config that is specific to the Wifi Settings */ bool has_network; - Config_NetworkConfig network; + meshtastic_Config_NetworkConfig network; /* The part of the config that is specific to the Display */ bool has_display; - Config_DisplayConfig display; + meshtastic_Config_DisplayConfig display; /* The part of the config that is specific to the Lora Radio */ bool has_lora; - Config_LoRaConfig lora; + meshtastic_Config_LoRaConfig lora; /* The part of the config that is specific to the Bluetooth settings */ bool has_bluetooth; - Config_BluetoothConfig bluetooth; + meshtastic_Config_BluetoothConfig bluetooth; /* A version integer used to invalidate old save files when we make incompatible changes This integer is set at build time and is private to NodeDB.cpp in the device code. */ uint32_t version; -} LocalConfig; +} meshtastic_LocalConfig; -typedef struct _LocalModuleConfig { +typedef struct _meshtastic_LocalModuleConfig { /* The part of the config that is specific to the MQTT module */ bool has_mqtt; - ModuleConfig_MQTTConfig mqtt; + meshtastic_ModuleConfig_MQTTConfig mqtt; /* The part of the config that is specific to the Serial module */ bool has_serial; - ModuleConfig_SerialConfig serial; + meshtastic_ModuleConfig_SerialConfig serial; /* The part of the config that is specific to the ExternalNotification module */ bool has_external_notification; - ModuleConfig_ExternalNotificationConfig external_notification; + meshtastic_ModuleConfig_ExternalNotificationConfig external_notification; /* The part of the config that is specific to the Store & Forward module */ bool has_store_forward; - ModuleConfig_StoreForwardConfig store_forward; + meshtastic_ModuleConfig_StoreForwardConfig store_forward; /* The part of the config that is specific to the RangeTest module */ bool has_range_test; - ModuleConfig_RangeTestConfig range_test; + meshtastic_ModuleConfig_RangeTestConfig range_test; /* The part of the config that is specific to the Telemetry module */ bool has_telemetry; - ModuleConfig_TelemetryConfig telemetry; + meshtastic_ModuleConfig_TelemetryConfig telemetry; /* The part of the config that is specific to the Canned Message module */ bool has_canned_message; - ModuleConfig_CannedMessageConfig canned_message; + meshtastic_ModuleConfig_CannedMessageConfig canned_message; /* A version integer used to invalidate old save files when we make incompatible changes This integer is set at build time and is private to NodeDB.cpp in the device code. */ uint32_t version; /* The part of the config that is specific to the Audio module */ bool has_audio; - ModuleConfig_AudioConfig audio; + meshtastic_ModuleConfig_AudioConfig audio; /* The part of the config that is specific to the Remote Hardware module */ bool has_remote_hardware; - ModuleConfig_RemoteHardwareConfig remote_hardware; -} LocalModuleConfig; + meshtastic_ModuleConfig_RemoteHardwareConfig remote_hardware; +} meshtastic_LocalModuleConfig; #ifdef __cplusplus @@ -80,33 +80,33 @@ extern "C" { #endif /* Initializer values for message structs */ -#define LocalConfig_init_default {false, Config_DeviceConfig_init_default, false, Config_PositionConfig_init_default, false, Config_PowerConfig_init_default, false, Config_NetworkConfig_init_default, false, Config_DisplayConfig_init_default, false, Config_LoRaConfig_init_default, false, Config_BluetoothConfig_init_default, 0} -#define LocalModuleConfig_init_default {false, ModuleConfig_MQTTConfig_init_default, false, ModuleConfig_SerialConfig_init_default, false, ModuleConfig_ExternalNotificationConfig_init_default, false, ModuleConfig_StoreForwardConfig_init_default, false, ModuleConfig_RangeTestConfig_init_default, false, ModuleConfig_TelemetryConfig_init_default, false, ModuleConfig_CannedMessageConfig_init_default, 0, false, ModuleConfig_AudioConfig_init_default, false, ModuleConfig_RemoteHardwareConfig_init_default} -#define LocalConfig_init_zero {false, Config_DeviceConfig_init_zero, false, Config_PositionConfig_init_zero, false, Config_PowerConfig_init_zero, false, Config_NetworkConfig_init_zero, false, Config_DisplayConfig_init_zero, false, Config_LoRaConfig_init_zero, false, Config_BluetoothConfig_init_zero, 0} -#define LocalModuleConfig_init_zero {false, ModuleConfig_MQTTConfig_init_zero, false, ModuleConfig_SerialConfig_init_zero, false, ModuleConfig_ExternalNotificationConfig_init_zero, false, ModuleConfig_StoreForwardConfig_init_zero, false, ModuleConfig_RangeTestConfig_init_zero, false, ModuleConfig_TelemetryConfig_init_zero, false, ModuleConfig_CannedMessageConfig_init_zero, 0, false, ModuleConfig_AudioConfig_init_zero, false, ModuleConfig_RemoteHardwareConfig_init_zero} +#define meshtastic_LocalConfig_init_default {false, meshtastic_Config_DeviceConfig_init_default, false, meshtastic_Config_PositionConfig_init_default, false, meshtastic_Config_PowerConfig_init_default, false, meshtastic_Config_NetworkConfig_init_default, false, meshtastic_Config_DisplayConfig_init_default, false, meshtastic_Config_LoRaConfig_init_default, false, meshtastic_Config_BluetoothConfig_init_default, 0} +#define meshtastic_LocalModuleConfig_init_default {false, meshtastic_ModuleConfig_MQTTConfig_init_default, false, meshtastic_ModuleConfig_SerialConfig_init_default, false, meshtastic_ModuleConfig_ExternalNotificationConfig_init_default, false, meshtastic_ModuleConfig_StoreForwardConfig_init_default, false, meshtastic_ModuleConfig_RangeTestConfig_init_default, false, meshtastic_ModuleConfig_TelemetryConfig_init_default, false, meshtastic_ModuleConfig_CannedMessageConfig_init_default, 0, false, meshtastic_ModuleConfig_AudioConfig_init_default, false, meshtastic_ModuleConfig_RemoteHardwareConfig_init_default} +#define meshtastic_LocalConfig_init_zero {false, meshtastic_Config_DeviceConfig_init_zero, false, meshtastic_Config_PositionConfig_init_zero, false, meshtastic_Config_PowerConfig_init_zero, false, meshtastic_Config_NetworkConfig_init_zero, false, meshtastic_Config_DisplayConfig_init_zero, false, meshtastic_Config_LoRaConfig_init_zero, false, meshtastic_Config_BluetoothConfig_init_zero, 0} +#define meshtastic_LocalModuleConfig_init_zero {false, meshtastic_ModuleConfig_MQTTConfig_init_zero, false, meshtastic_ModuleConfig_SerialConfig_init_zero, false, meshtastic_ModuleConfig_ExternalNotificationConfig_init_zero, false, meshtastic_ModuleConfig_StoreForwardConfig_init_zero, false, meshtastic_ModuleConfig_RangeTestConfig_init_zero, false, meshtastic_ModuleConfig_TelemetryConfig_init_zero, false, meshtastic_ModuleConfig_CannedMessageConfig_init_zero, 0, false, meshtastic_ModuleConfig_AudioConfig_init_zero, false, meshtastic_ModuleConfig_RemoteHardwareConfig_init_zero} /* Field tags (for use in manual encoding/decoding) */ -#define LocalConfig_device_tag 1 -#define LocalConfig_position_tag 2 -#define LocalConfig_power_tag 3 -#define LocalConfig_network_tag 4 -#define LocalConfig_display_tag 5 -#define LocalConfig_lora_tag 6 -#define LocalConfig_bluetooth_tag 7 -#define LocalConfig_version_tag 8 -#define LocalModuleConfig_mqtt_tag 1 -#define LocalModuleConfig_serial_tag 2 -#define LocalModuleConfig_external_notification_tag 3 -#define LocalModuleConfig_store_forward_tag 4 -#define LocalModuleConfig_range_test_tag 5 -#define LocalModuleConfig_telemetry_tag 6 -#define LocalModuleConfig_canned_message_tag 7 -#define LocalModuleConfig_version_tag 8 -#define LocalModuleConfig_audio_tag 9 -#define LocalModuleConfig_remote_hardware_tag 10 +#define meshtastic_LocalConfig_device_tag 1 +#define meshtastic_LocalConfig_position_tag 2 +#define meshtastic_LocalConfig_power_tag 3 +#define meshtastic_LocalConfig_network_tag 4 +#define meshtastic_LocalConfig_display_tag 5 +#define meshtastic_LocalConfig_lora_tag 6 +#define meshtastic_LocalConfig_bluetooth_tag 7 +#define meshtastic_LocalConfig_version_tag 8 +#define meshtastic_LocalModuleConfig_mqtt_tag 1 +#define meshtastic_LocalModuleConfig_serial_tag 2 +#define meshtastic_LocalModuleConfig_external_notification_tag 3 +#define meshtastic_LocalModuleConfig_store_forward_tag 4 +#define meshtastic_LocalModuleConfig_range_test_tag 5 +#define meshtastic_LocalModuleConfig_telemetry_tag 6 +#define meshtastic_LocalModuleConfig_canned_message_tag 7 +#define meshtastic_LocalModuleConfig_version_tag 8 +#define meshtastic_LocalModuleConfig_audio_tag 9 +#define meshtastic_LocalModuleConfig_remote_hardware_tag 10 /* Struct field encoding specification for nanopb */ -#define LocalConfig_FIELDLIST(X, a) \ +#define meshtastic_LocalConfig_FIELDLIST(X, a) \ X(a, STATIC, OPTIONAL, MESSAGE, device, 1) \ X(a, STATIC, OPTIONAL, MESSAGE, position, 2) \ X(a, STATIC, OPTIONAL, MESSAGE, power, 3) \ @@ -115,17 +115,17 @@ X(a, STATIC, OPTIONAL, MESSAGE, display, 5) \ X(a, STATIC, OPTIONAL, MESSAGE, lora, 6) \ X(a, STATIC, OPTIONAL, MESSAGE, bluetooth, 7) \ X(a, STATIC, SINGULAR, UINT32, version, 8) -#define LocalConfig_CALLBACK NULL -#define LocalConfig_DEFAULT NULL -#define LocalConfig_device_MSGTYPE Config_DeviceConfig -#define LocalConfig_position_MSGTYPE Config_PositionConfig -#define LocalConfig_power_MSGTYPE Config_PowerConfig -#define LocalConfig_network_MSGTYPE Config_NetworkConfig -#define LocalConfig_display_MSGTYPE Config_DisplayConfig -#define LocalConfig_lora_MSGTYPE Config_LoRaConfig -#define LocalConfig_bluetooth_MSGTYPE Config_BluetoothConfig +#define meshtastic_LocalConfig_CALLBACK NULL +#define meshtastic_LocalConfig_DEFAULT NULL +#define meshtastic_LocalConfig_device_MSGTYPE meshtastic_Config_DeviceConfig +#define meshtastic_LocalConfig_position_MSGTYPE meshtastic_Config_PositionConfig +#define meshtastic_LocalConfig_power_MSGTYPE meshtastic_Config_PowerConfig +#define meshtastic_LocalConfig_network_MSGTYPE meshtastic_Config_NetworkConfig +#define meshtastic_LocalConfig_display_MSGTYPE meshtastic_Config_DisplayConfig +#define meshtastic_LocalConfig_lora_MSGTYPE meshtastic_Config_LoRaConfig +#define meshtastic_LocalConfig_bluetooth_MSGTYPE meshtastic_Config_BluetoothConfig -#define LocalModuleConfig_FIELDLIST(X, a) \ +#define meshtastic_LocalModuleConfig_FIELDLIST(X, a) \ X(a, STATIC, OPTIONAL, MESSAGE, mqtt, 1) \ X(a, STATIC, OPTIONAL, MESSAGE, serial, 2) \ X(a, STATIC, OPTIONAL, MESSAGE, external_notification, 3) \ @@ -136,28 +136,28 @@ X(a, STATIC, OPTIONAL, MESSAGE, canned_message, 7) \ X(a, STATIC, SINGULAR, UINT32, version, 8) \ X(a, STATIC, OPTIONAL, MESSAGE, audio, 9) \ X(a, STATIC, OPTIONAL, MESSAGE, remote_hardware, 10) -#define LocalModuleConfig_CALLBACK NULL -#define LocalModuleConfig_DEFAULT NULL -#define LocalModuleConfig_mqtt_MSGTYPE ModuleConfig_MQTTConfig -#define LocalModuleConfig_serial_MSGTYPE ModuleConfig_SerialConfig -#define LocalModuleConfig_external_notification_MSGTYPE ModuleConfig_ExternalNotificationConfig -#define LocalModuleConfig_store_forward_MSGTYPE ModuleConfig_StoreForwardConfig -#define LocalModuleConfig_range_test_MSGTYPE ModuleConfig_RangeTestConfig -#define LocalModuleConfig_telemetry_MSGTYPE ModuleConfig_TelemetryConfig -#define LocalModuleConfig_canned_message_MSGTYPE ModuleConfig_CannedMessageConfig -#define LocalModuleConfig_audio_MSGTYPE ModuleConfig_AudioConfig -#define LocalModuleConfig_remote_hardware_MSGTYPE ModuleConfig_RemoteHardwareConfig +#define meshtastic_LocalModuleConfig_CALLBACK NULL +#define meshtastic_LocalModuleConfig_DEFAULT NULL +#define meshtastic_LocalModuleConfig_mqtt_MSGTYPE meshtastic_ModuleConfig_MQTTConfig +#define meshtastic_LocalModuleConfig_serial_MSGTYPE meshtastic_ModuleConfig_SerialConfig +#define meshtastic_LocalModuleConfig_external_notification_MSGTYPE meshtastic_ModuleConfig_ExternalNotificationConfig +#define meshtastic_LocalModuleConfig_store_forward_MSGTYPE meshtastic_ModuleConfig_StoreForwardConfig +#define meshtastic_LocalModuleConfig_range_test_MSGTYPE meshtastic_ModuleConfig_RangeTestConfig +#define meshtastic_LocalModuleConfig_telemetry_MSGTYPE meshtastic_ModuleConfig_TelemetryConfig +#define meshtastic_LocalModuleConfig_canned_message_MSGTYPE meshtastic_ModuleConfig_CannedMessageConfig +#define meshtastic_LocalModuleConfig_audio_MSGTYPE meshtastic_ModuleConfig_AudioConfig +#define meshtastic_LocalModuleConfig_remote_hardware_MSGTYPE meshtastic_ModuleConfig_RemoteHardwareConfig -extern const pb_msgdesc_t LocalConfig_msg; -extern const pb_msgdesc_t LocalModuleConfig_msg; +extern const pb_msgdesc_t meshtastic_LocalConfig_msg; +extern const pb_msgdesc_t meshtastic_LocalModuleConfig_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define LocalConfig_fields &LocalConfig_msg -#define LocalModuleConfig_fields &LocalModuleConfig_msg +#define meshtastic_LocalConfig_fields &meshtastic_LocalConfig_msg +#define meshtastic_LocalModuleConfig_fields &meshtastic_LocalModuleConfig_msg /* Maximum encoded size of messages (where known) */ -#define LocalConfig_size 425 -#define LocalModuleConfig_size 412 +#define meshtastic_LocalConfig_size 434 +#define meshtastic_LocalModuleConfig_size 412 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/mesh.pb.c b/src/mesh/generated/meshtastic/mesh.pb.c index bc9af848f..977e3916f 100644 --- a/src/mesh/generated/meshtastic/mesh.pb.c +++ b/src/mesh/generated/meshtastic/mesh.pb.c @@ -1,51 +1,51 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./mesh.pb.h" +#include "meshtastic/mesh.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(Position, Position, AUTO) +PB_BIND(meshtastic_Position, meshtastic_Position, AUTO) -PB_BIND(User, User, AUTO) +PB_BIND(meshtastic_User, meshtastic_User, AUTO) -PB_BIND(RouteDiscovery, RouteDiscovery, AUTO) +PB_BIND(meshtastic_RouteDiscovery, meshtastic_RouteDiscovery, AUTO) -PB_BIND(Routing, Routing, AUTO) +PB_BIND(meshtastic_Routing, meshtastic_Routing, AUTO) -PB_BIND(Data, Data, 2) +PB_BIND(meshtastic_Data, meshtastic_Data, 2) -PB_BIND(Waypoint, Waypoint, AUTO) +PB_BIND(meshtastic_Waypoint, meshtastic_Waypoint, AUTO) -PB_BIND(MeshPacket, MeshPacket, 2) +PB_BIND(meshtastic_MeshPacket, meshtastic_MeshPacket, 2) -PB_BIND(NodeInfo, NodeInfo, AUTO) +PB_BIND(meshtastic_NodeInfo, meshtastic_NodeInfo, AUTO) -PB_BIND(MyNodeInfo, MyNodeInfo, AUTO) +PB_BIND(meshtastic_MyNodeInfo, meshtastic_MyNodeInfo, AUTO) -PB_BIND(LogRecord, LogRecord, AUTO) +PB_BIND(meshtastic_LogRecord, meshtastic_LogRecord, AUTO) -PB_BIND(QueueStatus, QueueStatus, AUTO) +PB_BIND(meshtastic_QueueStatus, meshtastic_QueueStatus, AUTO) -PB_BIND(FromRadio, FromRadio, 2) +PB_BIND(meshtastic_FromRadio, meshtastic_FromRadio, 2) -PB_BIND(ToRadio, ToRadio, 2) +PB_BIND(meshtastic_ToRadio, meshtastic_ToRadio, 2) -PB_BIND(Compressed, Compressed, AUTO) +PB_BIND(meshtastic_Compressed, meshtastic_Compressed, AUTO) diff --git a/src/mesh/generated/meshtastic/mesh.pb.h b/src/mesh/generated/meshtastic/mesh.pb.h index 98cf8238b..0a8cf5cfe 100644 --- a/src/mesh/generated/meshtastic/mesh.pb.h +++ b/src/mesh/generated/meshtastic/mesh.pb.h @@ -4,12 +4,12 @@ #ifndef PB_MESHTASTIC_MESHTASTIC_MESH_PB_H_INCLUDED #define PB_MESHTASTIC_MESHTASTIC_MESH_PB_H_INCLUDED #include -#include "./channel.pb.h" -#include "./config.pb.h" -#include "./module_config.pb.h" -#include "./portnums.pb.h" -#include "./telemetry.pb.h" -#include "./xmodem.pb.h" +#include "meshtastic/channel.pb.h" +#include "meshtastic/config.pb.h" +#include "meshtastic/module_config.pb.h" +#include "meshtastic/portnums.pb.h" +#include "meshtastic/telemetry.pb.h" +#include "meshtastic/xmodem.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -20,179 +20,179 @@ bin/build-all.sh script. Because they will be used to find firmware filenames in the android app for OTA updates. To match the old style filenames, _ is converted to -, p is converted to . */ -typedef enum _HardwareModel { +typedef enum _meshtastic_HardwareModel { /* TODO: REPLACE */ - HardwareModel_UNSET = 0, + meshtastic_HardwareModel_UNSET = 0, /* TODO: REPLACE */ - HardwareModel_TLORA_V2 = 1, + meshtastic_HardwareModel_TLORA_V2 = 1, /* TODO: REPLACE */ - HardwareModel_TLORA_V1 = 2, + meshtastic_HardwareModel_TLORA_V1 = 2, /* TODO: REPLACE */ - HardwareModel_TLORA_V2_1_1P6 = 3, + meshtastic_HardwareModel_TLORA_V2_1_1P6 = 3, /* TODO: REPLACE */ - HardwareModel_TBEAM = 4, + meshtastic_HardwareModel_TBEAM = 4, /* The original heltec WiFi_Lora_32_V2, which had battery voltage sensing hooked to GPIO 13 (see HELTEC_V2 for the new version). */ - HardwareModel_HELTEC_V2_0 = 5, + meshtastic_HardwareModel_HELTEC_V2_0 = 5, /* TODO: REPLACE */ - HardwareModel_TBEAM_V0P7 = 6, + meshtastic_HardwareModel_TBEAM_V0P7 = 6, /* TODO: REPLACE */ - HardwareModel_T_ECHO = 7, + meshtastic_HardwareModel_T_ECHO = 7, /* TODO: REPLACE */ - HardwareModel_TLORA_V1_1P3 = 8, + meshtastic_HardwareModel_TLORA_V1_1P3 = 8, /* TODO: REPLACE */ - HardwareModel_RAK4631 = 9, + meshtastic_HardwareModel_RAK4631 = 9, /* The new version of the heltec WiFi_Lora_32_V2 board that has battery sensing hooked to GPIO 37. Sadly they did not update anything on the silkscreen to identify this board */ - HardwareModel_HELTEC_V2_1 = 10, + meshtastic_HardwareModel_HELTEC_V2_1 = 10, /* Ancient heltec WiFi_Lora_32 board */ - HardwareModel_HELTEC_V1 = 11, + meshtastic_HardwareModel_HELTEC_V1 = 11, /* New T-BEAM with ESP32-S3 CPU */ - HardwareModel_LILYGO_TBEAM_S3_CORE = 12, + meshtastic_HardwareModel_LILYGO_TBEAM_S3_CORE = 12, /* RAK WisBlock ESP32 core: https://docs.rakwireless.com/Product-Categories/WisBlock/RAK11200/Overview/ */ - HardwareModel_RAK11200 = 13, + meshtastic_HardwareModel_RAK11200 = 13, /* B&Q Consulting Nano Edition G1: https://uniteng.com/wiki/doku.php?id=meshtastic:nano */ - HardwareModel_NANO_G1 = 14, + meshtastic_HardwareModel_NANO_G1 = 14, /* TODO: REPLACE */ - HardwareModel_TLORA_V2_1_1P8 = 15, + meshtastic_HardwareModel_TLORA_V2_1_1P8 = 15, /* TODO: REPLACE */ - HardwareModel_TLORA_T3_S3 = 16, + meshtastic_HardwareModel_TLORA_T3_S3 = 16, /* B&Q Consulting Station Edition G1: https://uniteng.com/wiki/doku.php?id=meshtastic:station */ - HardwareModel_STATION_G1 = 25, + meshtastic_HardwareModel_STATION_G1 = 25, /* Less common/prototype boards listed here (needs one more byte over the air) */ - HardwareModel_LORA_RELAY_V1 = 32, + meshtastic_HardwareModel_LORA_RELAY_V1 = 32, /* TODO: REPLACE */ - HardwareModel_NRF52840DK = 33, + meshtastic_HardwareModel_NRF52840DK = 33, /* TODO: REPLACE */ - HardwareModel_PPR = 34, + meshtastic_HardwareModel_PPR = 34, /* TODO: REPLACE */ - HardwareModel_GENIEBLOCKS = 35, + meshtastic_HardwareModel_GENIEBLOCKS = 35, /* TODO: REPLACE */ - HardwareModel_NRF52_UNKNOWN = 36, + meshtastic_HardwareModel_NRF52_UNKNOWN = 36, /* TODO: REPLACE */ - HardwareModel_PORTDUINO = 37, + meshtastic_HardwareModel_PORTDUINO = 37, /* The simulator built into the android app */ - HardwareModel_ANDROID_SIM = 38, + meshtastic_HardwareModel_ANDROID_SIM = 38, /* Custom DIY device based on @NanoVHF schematics: https://github.com/NanoVHF/Meshtastic-DIY/tree/main/Schematics */ - HardwareModel_DIY_V1 = 39, + meshtastic_HardwareModel_DIY_V1 = 39, /* nRF52840 Dongle : https://www.nordicsemi.com/Products/Development-hardware/nrf52840-dongle/ */ - HardwareModel_NRF52840_PCA10059 = 40, + meshtastic_HardwareModel_NRF52840_PCA10059 = 40, /* Custom Disaster Radio esp32 v3 device https://github.com/sudomesh/disaster-radio/tree/master/hardware/board_esp32_v3 */ - HardwareModel_DR_DEV = 41, + meshtastic_HardwareModel_DR_DEV = 41, /* M5 esp32 based MCU modules with enclosure, TFT and LORA Shields. All Variants (Basic, Core, Fire, Core2, Paper) https://m5stack.com/ */ - HardwareModel_M5STACK = 42, + meshtastic_HardwareModel_M5STACK = 42, /* New Heltec LoRA32 with ESP32-S3 CPU */ - HardwareModel_HELTEC_V3 = 43, + meshtastic_HardwareModel_HELTEC_V3 = 43, /* New Heltec Wireless Stick Lite with ESP32-S3 CPU */ - HardwareModel_HELTEC_WSL_V3 = 44, + meshtastic_HardwareModel_HELTEC_WSL_V3 = 44, /* New BETAFPV ELRS Micro TX Module 2.4G with ESP32 CPU */ - HardwareModel_BETAFPV_2400_TX = 45, + meshtastic_HardwareModel_BETAFPV_2400_TX = 45, /* Reserved ID For developing private Ports. These will show up in live traffic sparsely, so we can use a high number. Keep it within 8 bits. */ - HardwareModel_PRIVATE_HW = 255 -} HardwareModel; + meshtastic_HardwareModel_PRIVATE_HW = 255 +} meshtastic_HardwareModel; /* Shared constants between device and phone */ -typedef enum _Constants { +typedef enum _meshtastic_Constants { /* First enum must be zero, and we are just using this enum to pass int constants between two very different environments */ - Constants_ZERO = 0, + meshtastic_Constants_ZERO = 0, /* From mesh.options note: this payload length is ONLY the bytes that are sent inside of the Data protobuf (excluding protobuf overhead). The 16 byte header is outside of this envelope */ - Constants_DATA_PAYLOAD_LEN = 237 -} Constants; + meshtastic_Constants_DATA_PAYLOAD_LEN = 237 +} meshtastic_Constants; /* Error codes for critical errors The device might report these fault codes on the screen. If you encounter a fault code, please post on the meshtastic.discourse.group and we'll try to help. */ -typedef enum _CriticalErrorCode { +typedef enum _meshtastic_CriticalErrorCode { /* TODO: REPLACE */ - CriticalErrorCode_NONE = 0, + meshtastic_CriticalErrorCode_NONE = 0, /* A software bug was detected while trying to send lora */ - CriticalErrorCode_TX_WATCHDOG = 1, + meshtastic_CriticalErrorCode_TX_WATCHDOG = 1, /* A software bug was detected on entry to sleep */ - CriticalErrorCode_SLEEP_ENTER_WAIT = 2, + meshtastic_CriticalErrorCode_SLEEP_ENTER_WAIT = 2, /* No Lora radio hardware could be found */ - CriticalErrorCode_NO_RADIO = 3, + meshtastic_CriticalErrorCode_NO_RADIO = 3, /* Not normally used */ - CriticalErrorCode_UNSPECIFIED = 4, + meshtastic_CriticalErrorCode_UNSPECIFIED = 4, /* We failed while configuring a UBlox GPS */ - CriticalErrorCode_UBLOX_UNIT_FAILED = 5, + meshtastic_CriticalErrorCode_UBLOX_UNIT_FAILED = 5, /* This board was expected to have a power management chip and it is missing or broken */ - CriticalErrorCode_NO_AXP192 = 6, + meshtastic_CriticalErrorCode_NO_AXP192 = 6, /* The channel tried to set a radio setting which is not supported by this chipset, radio comms settings are now undefined. */ - CriticalErrorCode_INVALID_RADIO_SETTING = 7, + meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING = 7, /* Radio transmit hardware failure. We sent data to the radio chip, but it didn't reply with an interrupt. */ - CriticalErrorCode_TRANSMIT_FAILED = 8, + meshtastic_CriticalErrorCode_TRANSMIT_FAILED = 8, /* We detected that the main CPU voltage dropped below the minumum acceptable value */ - CriticalErrorCode_BROWNOUT = 9, + meshtastic_CriticalErrorCode_BROWNOUT = 9, /* Selftest of SX1262 radio chip failed */ - CriticalErrorCode_SX1262_FAILURE = 10, + meshtastic_CriticalErrorCode_SX1262_FAILURE = 10, /* A (likely software but possibly hardware) failure was detected while trying to send packets. If this occurs on your board, please post in the forum so that we can ask you to collect some information to allow fixing this bug */ - CriticalErrorCode_RADIO_SPI_BUG = 11 -} CriticalErrorCode; + meshtastic_CriticalErrorCode_RADIO_SPI_BUG = 11 +} meshtastic_CriticalErrorCode; /* How the location was acquired: manual, onboard GPS, external (EUD) GPS */ -typedef enum _Position_LocSource { +typedef enum _meshtastic_Position_LocSource { /* TODO: REPLACE */ - Position_LocSource_LOC_UNSET = 0, + meshtastic_Position_LocSource_LOC_UNSET = 0, /* TODO: REPLACE */ - Position_LocSource_LOC_MANUAL = 1, + meshtastic_Position_LocSource_LOC_MANUAL = 1, /* TODO: REPLACE */ - Position_LocSource_LOC_INTERNAL = 2, + meshtastic_Position_LocSource_LOC_INTERNAL = 2, /* TODO: REPLACE */ - Position_LocSource_LOC_EXTERNAL = 3 -} Position_LocSource; + meshtastic_Position_LocSource_LOC_EXTERNAL = 3 +} meshtastic_Position_LocSource; /* How the altitude was acquired: manual, GPS int/ext, etc Default: same as location_source if present */ -typedef enum _Position_AltSource { +typedef enum _meshtastic_Position_AltSource { /* TODO: REPLACE */ - Position_AltSource_ALT_UNSET = 0, + meshtastic_Position_AltSource_ALT_UNSET = 0, /* TODO: REPLACE */ - Position_AltSource_ALT_MANUAL = 1, + meshtastic_Position_AltSource_ALT_MANUAL = 1, /* TODO: REPLACE */ - Position_AltSource_ALT_INTERNAL = 2, + meshtastic_Position_AltSource_ALT_INTERNAL = 2, /* TODO: REPLACE */ - Position_AltSource_ALT_EXTERNAL = 3, + meshtastic_Position_AltSource_ALT_EXTERNAL = 3, /* TODO: REPLACE */ - Position_AltSource_ALT_BAROMETRIC = 4 -} Position_AltSource; + meshtastic_Position_AltSource_ALT_BAROMETRIC = 4 +} meshtastic_Position_AltSource; /* A failure in delivering a message (usually used for routing control messages, but might be provided in addition to ack.fail_id to provide details on the type of failure). */ -typedef enum _Routing_Error { +typedef enum _meshtastic_Routing_Error { /* This message is not a failure */ - Routing_Error_NONE = 0, + meshtastic_Routing_Error_NONE = 0, /* Our node doesn't have a route to the requested destination anymore. */ - Routing_Error_NO_ROUTE = 1, + meshtastic_Routing_Error_NO_ROUTE = 1, /* We received a nak while trying to forward on your behalf */ - Routing_Error_GOT_NAK = 2, + meshtastic_Routing_Error_GOT_NAK = 2, /* TODO: REPLACE */ - Routing_Error_TIMEOUT = 3, + meshtastic_Routing_Error_TIMEOUT = 3, /* No suitable interface could be found for delivering this packet */ - Routing_Error_NO_INTERFACE = 4, + meshtastic_Routing_Error_NO_INTERFACE = 4, /* We reached the max retransmission count (typically for naive flood routing) */ - Routing_Error_MAX_RETRANSMIT = 5, + meshtastic_Routing_Error_MAX_RETRANSMIT = 5, /* No suitable channel was found for sending this packet (i.e. was requested channel index disabled?) */ - Routing_Error_NO_CHANNEL = 6, + meshtastic_Routing_Error_NO_CHANNEL = 6, /* The packet was too big for sending (exceeds interface MTU after encoding) */ - Routing_Error_TOO_LARGE = 7, + meshtastic_Routing_Error_TOO_LARGE = 7, /* The request had want_response set, the request reached the destination node, but no service on that node wants to send a response (possibly due to bad channel permissions) */ - Routing_Error_NO_RESPONSE = 8, + meshtastic_Routing_Error_NO_RESPONSE = 8, /* Cannot send currently because duty cycle regulations will be violated. */ - Routing_Error_DUTY_CYCLE_LIMIT = 9, + meshtastic_Routing_Error_DUTY_CYCLE_LIMIT = 9, /* The application layer service on the remote node received your request, but considered your request somehow invalid */ - Routing_Error_BAD_REQUEST = 32, + meshtastic_Routing_Error_BAD_REQUEST = 32, /* The application layer service on the remote node received your request, but considered your request not authorized (i.e you did not send the request on the required bound channel) */ - Routing_Error_NOT_AUTHORIZED = 33 -} Routing_Error; + meshtastic_Routing_Error_NOT_AUTHORIZED = 33 +} meshtastic_Routing_Error; /* The priority of this message for sending. Higher priorities are sent first (when managing the transmit queue). @@ -212,57 +212,57 @@ typedef enum _Routing_Error { So I bit the bullet and implemented a new (internal - not sent over the air) field in MeshPacket called ‘priority’. And the transmission queue in the router object is now a priority queue. */ -typedef enum _MeshPacket_Priority { +typedef enum _meshtastic_MeshPacket_Priority { /* Treated as Priority.DEFAULT */ - MeshPacket_Priority_UNSET = 0, + meshtastic_MeshPacket_Priority_UNSET = 0, /* TODO: REPLACE */ - MeshPacket_Priority_MIN = 1, + meshtastic_MeshPacket_Priority_MIN = 1, /* Background position updates are sent with very low priority - if the link is super congested they might not go out at all */ - MeshPacket_Priority_BACKGROUND = 10, + meshtastic_MeshPacket_Priority_BACKGROUND = 10, /* This priority is used for most messages that don't have a priority set */ - MeshPacket_Priority_DEFAULT = 64, + meshtastic_MeshPacket_Priority_DEFAULT = 64, /* If priority is unset but the message is marked as want_ack, assume it is important and use a slightly higher priority */ - MeshPacket_Priority_RELIABLE = 70, + meshtastic_MeshPacket_Priority_RELIABLE = 70, /* Ack/naks are sent with very high priority to ensure that retransmission stops as soon as possible */ - MeshPacket_Priority_ACK = 120, + meshtastic_MeshPacket_Priority_ACK = 120, /* TODO: REPLACE */ - MeshPacket_Priority_MAX = 127 -} MeshPacket_Priority; + meshtastic_MeshPacket_Priority_MAX = 127 +} meshtastic_MeshPacket_Priority; /* Identify if this is a delayed packet */ -typedef enum _MeshPacket_Delayed { +typedef enum _meshtastic_MeshPacket_Delayed { /* If unset, the message is being sent in real time. */ - MeshPacket_Delayed_NO_DELAY = 0, + meshtastic_MeshPacket_Delayed_NO_DELAY = 0, /* The message is delayed and was originally a broadcast */ - MeshPacket_Delayed_DELAYED_BROADCAST = 1, + meshtastic_MeshPacket_Delayed_DELAYED_BROADCAST = 1, /* The message is delayed and was originally a direct message */ - MeshPacket_Delayed_DELAYED_DIRECT = 2 -} MeshPacket_Delayed; + meshtastic_MeshPacket_Delayed_DELAYED_DIRECT = 2 +} meshtastic_MeshPacket_Delayed; /* Log levels, chosen to match python logging conventions. */ -typedef enum _LogRecord_Level { +typedef enum _meshtastic_LogRecord_Level { /* Log levels, chosen to match python logging conventions. */ - LogRecord_Level_UNSET = 0, + meshtastic_LogRecord_Level_UNSET = 0, /* Log levels, chosen to match python logging conventions. */ - LogRecord_Level_CRITICAL = 50, + meshtastic_LogRecord_Level_CRITICAL = 50, /* Log levels, chosen to match python logging conventions. */ - LogRecord_Level_ERROR = 40, + meshtastic_LogRecord_Level_ERROR = 40, /* Log levels, chosen to match python logging conventions. */ - LogRecord_Level_WARNING = 30, + meshtastic_LogRecord_Level_WARNING = 30, /* Log levels, chosen to match python logging conventions. */ - LogRecord_Level_INFO = 20, + meshtastic_LogRecord_Level_INFO = 20, /* Log levels, chosen to match python logging conventions. */ - LogRecord_Level_DEBUG = 10, + meshtastic_LogRecord_Level_DEBUG = 10, /* Log levels, chosen to match python logging conventions. */ - LogRecord_Level_TRACE = 5 -} LogRecord_Level; + meshtastic_LogRecord_Level_TRACE = 5 +} meshtastic_LogRecord_Level; /* Struct definitions */ /* a gps position */ -typedef struct _Position { +typedef struct _meshtastic_Position { /* The new preferred location encoding, multiply by 1e-7 to get degrees in floating point */ int32_t latitude_i; @@ -277,9 +277,9 @@ typedef struct _Position { seconds since 1970 */ uint32_t time; /* TODO: REPLACE */ - Position_LocSource location_source; + meshtastic_Position_LocSource location_source; /* TODO: REPLACE */ - Position_AltSource altitude_source; + meshtastic_Position_AltSource altitude_source; /* Positional timestamp (actual timestamp of GPS solution) in integer epoch seconds */ uint32_t timestamp; /* Pos. timestamp milliseconds adjustment (rarely available or required) */ @@ -327,7 +327,7 @@ typedef struct _Position { /* A sequence number, incremented with each Position message to help detect lost updates if needed */ uint32_t seq_number; -} Position; +} meshtastic_Position; /* Broadcast when a newly powered mesh node wants to find a node num it can use Sent from the phone over bluetooth to set the user id for the owner of this node. @@ -349,7 +349,7 @@ typedef struct _Position { A few nodenums are reserved and will never be requested: 0xff - broadcast 0 through 3 - for future use */ -typedef struct _User { +typedef struct _meshtastic_User { /* A globally unique ID string for this user. In the case of Signal that would mean +16504442323, for the default macaddr derived id it would be !<8 hexidecimal bytes>. Note: app developers are encouraged to also use the following standard @@ -367,43 +367,43 @@ typedef struct _User { Starting in 1.2.11 moved to hw_model enum in the NodeInfo object. Apps will still need the string here for older builds (so OTA update can find the right image), but if the enum is available it will be used instead. */ - HardwareModel hw_model; + meshtastic_HardwareModel hw_model; /* In some regions Ham radio operators have different bandwidth limitations than others. If this user is a licensed operator, set this flag. Also, "long_name" should be their licence number. */ bool is_licensed; -} User; +} meshtastic_User; /* A message used in our Dynamic Source Routing protocol (RFC 4728 based) */ -typedef struct _RouteDiscovery { +typedef struct _meshtastic_RouteDiscovery { /* The list of nodenums this packet has visited so far */ pb_size_t route_count; uint32_t route[8]; -} RouteDiscovery; +} meshtastic_RouteDiscovery; /* A Routing control Data packet handled by the routing module */ -typedef struct _Routing { +typedef struct _meshtastic_Routing { pb_size_t which_variant; union { /* A route request going from the requester */ - RouteDiscovery route_request; + meshtastic_RouteDiscovery route_request; /* A route reply */ - RouteDiscovery route_reply; + meshtastic_RouteDiscovery route_reply; /* A failure in delivering a message (usually used for routing control messages, but might be provided in addition to ack.fail_id to provide details on the type of failure). */ - Routing_Error error_reason; + meshtastic_Routing_Error error_reason; }; -} Routing; +} meshtastic_Routing; -typedef PB_BYTES_ARRAY_T(237) Data_payload_t; +typedef PB_BYTES_ARRAY_T(237) meshtastic_Data_payload_t; /* (Formerly called SubPacket) The payload portion fo a packet, this is the actual bytes that are sent inside a radio packet (because from/to are broken out by the comms library) */ -typedef struct _Data { +typedef struct _meshtastic_Data { /* Formerly named typ and of type Type */ - PortNum portnum; + meshtastic_PortNum portnum; /* TODO: REPLACE */ - Data_payload_t payload; + meshtastic_Data_payload_t payload; /* Not normally used, but for testing a sender can request that recipient responds in kind (i.e. if it received a position, it should unicast back it's position). Note: that if you set this on a broadcast you will receive many replies. */ @@ -426,10 +426,10 @@ typedef struct _Data { /* Defaults to false. If true, then what is in the payload should be treated as an emoji like giving a message a heart or poop emoji. */ uint32_t emoji; -} Data; +} meshtastic_Data; /* Waypoint message, used to share arbitrary locations across the mesh */ -typedef struct _Waypoint { +typedef struct _meshtastic_Waypoint { /* Id of the waypoint */ uint32_t id; /* latitude_i */ @@ -447,13 +447,13 @@ typedef struct _Waypoint { char description[100]; /* Designator icon for the waypoint in the form of a unicode emoji */ uint32_t icon; -} Waypoint; +} meshtastic_Waypoint; -typedef PB_BYTES_ARRAY_T(256) MeshPacket_encrypted_t; +typedef PB_BYTES_ARRAY_T(256) meshtastic_MeshPacket_encrypted_t; /* A packet envelope sent/received over the mesh only payload_variant is sent in the payload portion of the LORA packet. The other fields are either not sent at all, or sent in the special 16 byte LORA header. */ -typedef struct _MeshPacket { +typedef struct _meshtastic_MeshPacket { /* The sending node number. Note: Our crypto implementation uses this field as well. See [crypto](/docs/overview/encryption) for details. @@ -473,9 +473,9 @@ typedef struct _MeshPacket { pb_size_t which_payload_variant; union { /* TODO: REPLACE */ - Data decoded; + meshtastic_Data decoded; /* TODO: REPLACE */ - MeshPacket_encrypted_t encrypted; + meshtastic_MeshPacket_encrypted_t encrypted; }; /* A unique ID for this packet. Always 0 for no-ack packets or non broadcast packets (and therefore take zero bytes of space). @@ -514,12 +514,12 @@ typedef struct _MeshPacket { bool want_ack; /* The priority of this message for sending. See MeshPacket.Priority description for more details. */ - MeshPacket_Priority priority; + meshtastic_MeshPacket_Priority priority; /* rssi of received packet. Only sent to phone for dispay purposes. */ int32_t rx_rssi; /* Describe if this message is delayed */ - MeshPacket_Delayed delayed; -} MeshPacket; + meshtastic_MeshPacket_Delayed delayed; +} meshtastic_MeshPacket; /* The bluetooth to device link: Old BTLE protocol docs from TODO, merge in above and make real docs... @@ -537,16 +537,16 @@ typedef struct _MeshPacket { level etc) SET_CONFIG (switches device to a new set of radio params and preshared key, drops all existing nodes, force our node to rejoin this new group) Full information about a node on the mesh */ -typedef struct _NodeInfo { +typedef struct _meshtastic_NodeInfo { /* The node number */ uint32_t num; /* The user info for this node */ bool has_user; - User user; + meshtastic_User user; /* This position data. Note: before 1.2.14 we would also store the last time we've heard from this node in position.time, that is no longer true. Position.time now indicates the last time we received a POSITION from that node. */ bool has_position; - Position position; + meshtastic_Position position; /* Returns the Signal-to-noise ratio (SNR) of the last received message, as measured by the receiver. Return SNR of the last received message in dB */ float snr; @@ -554,13 +554,13 @@ typedef struct _NodeInfo { uint32_t last_heard; /* The latest device metrics for the node. */ bool has_device_metrics; - DeviceMetrics device_metrics; -} NodeInfo; + meshtastic_DeviceMetrics device_metrics; +} meshtastic_NodeInfo; /* Unique local debugging info for this node Note: we don't include position or the user info, because that will come in the Sent to the phone in response to WantNodes. */ -typedef struct _MyNodeInfo { +typedef struct _meshtastic_MyNodeInfo { /* Tells the phone what our node number is, default starting value is lowbyte of macaddr, but it will be fixed if that is already in use */ uint32_t my_node_num; @@ -577,7 +577,7 @@ typedef struct _MyNodeInfo { This field will be cleared after the phone reads MyNodeInfo (i.e. it will only be reported once) a numeric error code to go with error message, zero means no error */ - CriticalErrorCode error_code; + meshtastic_CriticalErrorCode error_code; /* A numeric error address (nonzero if available) */ uint32_t error_address; /* The total number of errors this node has ever encountered @@ -608,14 +608,14 @@ typedef struct _MyNodeInfo { float channel_utilization; /* Percent of airtime for transmission used within the last hour. */ float air_util_tx; -} MyNodeInfo; +} meshtastic_MyNodeInfo; /* Debug output from the device. To minimize the size of records inside the device code, if a time/source/level is not set on the message it is assumed to be a continuation of the previously sent message. This allows the device code to use fixed maxlen 64 byte strings for messages, and then extend as needed by emitting multiple records. */ -typedef struct _LogRecord { +typedef struct _meshtastic_LogRecord { /* Log levels, chosen to match python logging conventions. */ char message[64]; /* Seconds since 1970 - or 0 for unknown/unset */ @@ -623,10 +623,10 @@ typedef struct _LogRecord { /* Usually based on thread name - if known */ char source[8]; /* Not yet set */ - LogRecord_Level level; -} LogRecord; + meshtastic_LogRecord_Level level; +} meshtastic_LogRecord; -typedef struct _QueueStatus { +typedef struct _meshtastic_QueueStatus { /* Last attempt to queue status, ErrorCode */ int8_t res; /* Free entries in the outgoing queue */ @@ -635,30 +635,30 @@ typedef struct _QueueStatus { uint8_t maxlen; /* What was mesh packet id that generated this response? */ uint32_t mesh_packet_id; -} QueueStatus; +} meshtastic_QueueStatus; /* Packets from the radio to the phone will appear on the fromRadio characteristic. It will support READ and NOTIFY. When a new packet arrives the device will BLE notify? It will sit in that descriptor until consumed by the phone, at which point the next item in the FIFO will be populated. */ -typedef struct _FromRadio { +typedef struct _meshtastic_FromRadio { /* The packet id, used to allow the phone to request missing read packets from the FIFO, see our bluetooth docs */ uint32_t id; pb_size_t which_payload_variant; union { /* Log levels, chosen to match python logging conventions. */ - MeshPacket packet; + meshtastic_MeshPacket packet; /* Tells the phone what our node number is, can be -1 if we've not yet joined a mesh. NOTE: This ID must not change - to keep (minimal) compatibility with <1.2 version of android apps. */ - MyNodeInfo my_info; + meshtastic_MyNodeInfo my_info; /* One packet is sent for each node in the on radio DB starts over with the first node in our DB */ - NodeInfo node_info; + meshtastic_NodeInfo node_info; /* Include a part of the config (was: RadioConfig radio) */ - Config config; + meshtastic_Config config; /* Set to send debug console output over our protobuf stream */ - LogRecord log_record; + meshtastic_LogRecord log_record; /* Sent as true once the device has finished sending all of the responses to want_config recipient should check if this ID matches our original request nonce, if not, it means your config responses haven't started yet. @@ -670,23 +670,23 @@ typedef struct _FromRadio { NOTE: This ID must not change - to keep (minimal) compatibility with <1.2 version of android apps. */ bool rebooted; /* Include module config */ - ModuleConfig moduleConfig; + meshtastic_ModuleConfig moduleConfig; /* One packet is sent for each channel */ - Channel channel; + meshtastic_Channel channel; /* Queue status info */ - QueueStatus queueStatus; + meshtastic_QueueStatus queueStatus; /* File Transfer Chunk */ - XModem xmodemPacket; + meshtastic_XModem xmodemPacket; }; -} FromRadio; +} meshtastic_FromRadio; /* Packets/commands to the radio will be written (reliably) to the toRadio characteristic. Once the write completes the phone can assume it is handled. */ -typedef struct _ToRadio { +typedef struct _meshtastic_ToRadio { pb_size_t which_payload_variant; union { /* Send this packet on the mesh */ - MeshPacket packet; + meshtastic_MeshPacket packet; /* Phone wants radio to send full node db to the phone, This is typically the first packet sent to the radio when the phone gets a bluetooth connection. The radio will respond by sending back a @@ -700,18 +700,18 @@ typedef struct _ToRadio { This is useful for serial links where there is no hardware/protocol based notification that the client has dropped the link. (Sending this message is optional for clients) */ bool disconnect; - XModem xmodemPacket; + meshtastic_XModem xmodemPacket; }; -} ToRadio; +} meshtastic_ToRadio; -typedef PB_BYTES_ARRAY_T(237) Compressed_data_t; +typedef PB_BYTES_ARRAY_T(237) meshtastic_Compressed_data_t; /* Compressed message payload */ -typedef struct _Compressed { +typedef struct _meshtastic_Compressed { /* PortNum to determine the how to handle the compressed payload. */ - PortNum portnum; + meshtastic_PortNum portnum; /* Compressed data. */ - Compressed_data_t data; -} Compressed; + meshtastic_Compressed_data_t data; +} meshtastic_Compressed; #ifdef __cplusplus @@ -719,210 +719,210 @@ extern "C" { #endif /* Helper constants for enums */ -#define _HardwareModel_MIN HardwareModel_UNSET -#define _HardwareModel_MAX HardwareModel_PRIVATE_HW -#define _HardwareModel_ARRAYSIZE ((HardwareModel)(HardwareModel_PRIVATE_HW+1)) +#define _meshtastic_HardwareModel_MIN meshtastic_HardwareModel_UNSET +#define _meshtastic_HardwareModel_MAX meshtastic_HardwareModel_PRIVATE_HW +#define _meshtastic_HardwareModel_ARRAYSIZE ((meshtastic_HardwareModel)(meshtastic_HardwareModel_PRIVATE_HW+1)) -#define _Constants_MIN Constants_ZERO -#define _Constants_MAX Constants_DATA_PAYLOAD_LEN -#define _Constants_ARRAYSIZE ((Constants)(Constants_DATA_PAYLOAD_LEN+1)) +#define _meshtastic_Constants_MIN meshtastic_Constants_ZERO +#define _meshtastic_Constants_MAX meshtastic_Constants_DATA_PAYLOAD_LEN +#define _meshtastic_Constants_ARRAYSIZE ((meshtastic_Constants)(meshtastic_Constants_DATA_PAYLOAD_LEN+1)) -#define _CriticalErrorCode_MIN CriticalErrorCode_NONE -#define _CriticalErrorCode_MAX CriticalErrorCode_RADIO_SPI_BUG -#define _CriticalErrorCode_ARRAYSIZE ((CriticalErrorCode)(CriticalErrorCode_RADIO_SPI_BUG+1)) +#define _meshtastic_CriticalErrorCode_MIN meshtastic_CriticalErrorCode_NONE +#define _meshtastic_CriticalErrorCode_MAX meshtastic_CriticalErrorCode_RADIO_SPI_BUG +#define _meshtastic_CriticalErrorCode_ARRAYSIZE ((meshtastic_CriticalErrorCode)(meshtastic_CriticalErrorCode_RADIO_SPI_BUG+1)) -#define _Position_LocSource_MIN Position_LocSource_LOC_UNSET -#define _Position_LocSource_MAX Position_LocSource_LOC_EXTERNAL -#define _Position_LocSource_ARRAYSIZE ((Position_LocSource)(Position_LocSource_LOC_EXTERNAL+1)) +#define _meshtastic_Position_LocSource_MIN meshtastic_Position_LocSource_LOC_UNSET +#define _meshtastic_Position_LocSource_MAX meshtastic_Position_LocSource_LOC_EXTERNAL +#define _meshtastic_Position_LocSource_ARRAYSIZE ((meshtastic_Position_LocSource)(meshtastic_Position_LocSource_LOC_EXTERNAL+1)) -#define _Position_AltSource_MIN Position_AltSource_ALT_UNSET -#define _Position_AltSource_MAX Position_AltSource_ALT_BAROMETRIC -#define _Position_AltSource_ARRAYSIZE ((Position_AltSource)(Position_AltSource_ALT_BAROMETRIC+1)) +#define _meshtastic_Position_AltSource_MIN meshtastic_Position_AltSource_ALT_UNSET +#define _meshtastic_Position_AltSource_MAX meshtastic_Position_AltSource_ALT_BAROMETRIC +#define _meshtastic_Position_AltSource_ARRAYSIZE ((meshtastic_Position_AltSource)(meshtastic_Position_AltSource_ALT_BAROMETRIC+1)) -#define _Routing_Error_MIN Routing_Error_NONE -#define _Routing_Error_MAX Routing_Error_NOT_AUTHORIZED -#define _Routing_Error_ARRAYSIZE ((Routing_Error)(Routing_Error_NOT_AUTHORIZED+1)) +#define _meshtastic_Routing_Error_MIN meshtastic_Routing_Error_NONE +#define _meshtastic_Routing_Error_MAX meshtastic_Routing_Error_NOT_AUTHORIZED +#define _meshtastic_Routing_Error_ARRAYSIZE ((meshtastic_Routing_Error)(meshtastic_Routing_Error_NOT_AUTHORIZED+1)) -#define _MeshPacket_Priority_MIN MeshPacket_Priority_UNSET -#define _MeshPacket_Priority_MAX MeshPacket_Priority_MAX -#define _MeshPacket_Priority_ARRAYSIZE ((MeshPacket_Priority)(MeshPacket_Priority_MAX+1)) +#define _meshtastic_MeshPacket_Priority_MIN meshtastic_MeshPacket_Priority_UNSET +#define _meshtastic_MeshPacket_Priority_MAX meshtastic_MeshPacket_Priority_MAX +#define _meshtastic_MeshPacket_Priority_ARRAYSIZE ((meshtastic_MeshPacket_Priority)(meshtastic_MeshPacket_Priority_MAX+1)) -#define _MeshPacket_Delayed_MIN MeshPacket_Delayed_NO_DELAY -#define _MeshPacket_Delayed_MAX MeshPacket_Delayed_DELAYED_DIRECT -#define _MeshPacket_Delayed_ARRAYSIZE ((MeshPacket_Delayed)(MeshPacket_Delayed_DELAYED_DIRECT+1)) +#define _meshtastic_MeshPacket_Delayed_MIN meshtastic_MeshPacket_Delayed_NO_DELAY +#define _meshtastic_MeshPacket_Delayed_MAX meshtastic_MeshPacket_Delayed_DELAYED_DIRECT +#define _meshtastic_MeshPacket_Delayed_ARRAYSIZE ((meshtastic_MeshPacket_Delayed)(meshtastic_MeshPacket_Delayed_DELAYED_DIRECT+1)) -#define _LogRecord_Level_MIN LogRecord_Level_UNSET -#define _LogRecord_Level_MAX LogRecord_Level_CRITICAL -#define _LogRecord_Level_ARRAYSIZE ((LogRecord_Level)(LogRecord_Level_CRITICAL+1)) +#define _meshtastic_LogRecord_Level_MIN meshtastic_LogRecord_Level_UNSET +#define _meshtastic_LogRecord_Level_MAX meshtastic_LogRecord_Level_CRITICAL +#define _meshtastic_LogRecord_Level_ARRAYSIZE ((meshtastic_LogRecord_Level)(meshtastic_LogRecord_Level_CRITICAL+1)) -#define Position_location_source_ENUMTYPE Position_LocSource -#define Position_altitude_source_ENUMTYPE Position_AltSource +#define meshtastic_Position_location_source_ENUMTYPE meshtastic_Position_LocSource +#define meshtastic_Position_altitude_source_ENUMTYPE meshtastic_Position_AltSource -#define User_hw_model_ENUMTYPE HardwareModel +#define meshtastic_User_hw_model_ENUMTYPE meshtastic_HardwareModel -#define Routing_variant_error_reason_ENUMTYPE Routing_Error +#define meshtastic_Routing_variant_error_reason_ENUMTYPE meshtastic_Routing_Error -#define Data_portnum_ENUMTYPE PortNum +#define meshtastic_Data_portnum_ENUMTYPE meshtastic_PortNum -#define MeshPacket_priority_ENUMTYPE MeshPacket_Priority -#define MeshPacket_delayed_ENUMTYPE MeshPacket_Delayed +#define meshtastic_MeshPacket_priority_ENUMTYPE meshtastic_MeshPacket_Priority +#define meshtastic_MeshPacket_delayed_ENUMTYPE meshtastic_MeshPacket_Delayed -#define MyNodeInfo_error_code_ENUMTYPE CriticalErrorCode +#define meshtastic_MyNodeInfo_error_code_ENUMTYPE meshtastic_CriticalErrorCode -#define LogRecord_level_ENUMTYPE LogRecord_Level +#define meshtastic_LogRecord_level_ENUMTYPE meshtastic_LogRecord_Level -#define Compressed_portnum_ENUMTYPE PortNum +#define meshtastic_Compressed_portnum_ENUMTYPE meshtastic_PortNum /* Initializer values for message structs */ -#define Position_init_default {0, 0, 0, 0, _Position_LocSource_MIN, _Position_AltSource_MIN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} -#define User_init_default {"", "", "", {0}, _HardwareModel_MIN, 0} -#define RouteDiscovery_init_default {0, {0, 0, 0, 0, 0, 0, 0, 0}} -#define Routing_init_default {0, {RouteDiscovery_init_default}} -#define Data_init_default {_PortNum_MIN, {0, {0}}, 0, 0, 0, 0, 0, 0} -#define Waypoint_init_default {0, 0, 0, 0, 0, "", "", 0} -#define MeshPacket_init_default {0, 0, 0, 0, {Data_init_default}, 0, 0, 0, 0, 0, _MeshPacket_Priority_MIN, 0, _MeshPacket_Delayed_MIN} -#define NodeInfo_init_default {0, false, User_init_default, false, Position_init_default, 0, 0, false, DeviceMetrics_init_default} -#define MyNodeInfo_init_default {0, 0, 0, "", _CriticalErrorCode_MIN, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, 0, 0} -#define LogRecord_init_default {"", 0, "", _LogRecord_Level_MIN} -#define QueueStatus_init_default {0, 0, 0, 0} -#define FromRadio_init_default {0, 0, {MeshPacket_init_default}} -#define ToRadio_init_default {0, {MeshPacket_init_default}} -#define Compressed_init_default {_PortNum_MIN, {0, {0}}} -#define Position_init_zero {0, 0, 0, 0, _Position_LocSource_MIN, _Position_AltSource_MIN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} -#define User_init_zero {"", "", "", {0}, _HardwareModel_MIN, 0} -#define RouteDiscovery_init_zero {0, {0, 0, 0, 0, 0, 0, 0, 0}} -#define Routing_init_zero {0, {RouteDiscovery_init_zero}} -#define Data_init_zero {_PortNum_MIN, {0, {0}}, 0, 0, 0, 0, 0, 0} -#define Waypoint_init_zero {0, 0, 0, 0, 0, "", "", 0} -#define MeshPacket_init_zero {0, 0, 0, 0, {Data_init_zero}, 0, 0, 0, 0, 0, _MeshPacket_Priority_MIN, 0, _MeshPacket_Delayed_MIN} -#define NodeInfo_init_zero {0, false, User_init_zero, false, Position_init_zero, 0, 0, false, DeviceMetrics_init_zero} -#define MyNodeInfo_init_zero {0, 0, 0, "", _CriticalErrorCode_MIN, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, 0, 0} -#define LogRecord_init_zero {"", 0, "", _LogRecord_Level_MIN} -#define QueueStatus_init_zero {0, 0, 0, 0} -#define FromRadio_init_zero {0, 0, {MeshPacket_init_zero}} -#define ToRadio_init_zero {0, {MeshPacket_init_zero}} -#define Compressed_init_zero {_PortNum_MIN, {0, {0}}} +#define meshtastic_Position_init_default {0, 0, 0, 0, _meshtastic_Position_LocSource_MIN, _meshtastic_Position_AltSource_MIN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_User_init_default {"", "", "", {0}, _meshtastic_HardwareModel_MIN, 0} +#define meshtastic_RouteDiscovery_init_default {0, {0, 0, 0, 0, 0, 0, 0, 0}} +#define meshtastic_Routing_init_default {0, {meshtastic_RouteDiscovery_init_default}} +#define meshtastic_Data_init_default {_meshtastic_PortNum_MIN, {0, {0}}, 0, 0, 0, 0, 0, 0} +#define meshtastic_Waypoint_init_default {0, 0, 0, 0, 0, "", "", 0} +#define meshtastic_MeshPacket_init_default {0, 0, 0, 0, {meshtastic_Data_init_default}, 0, 0, 0, 0, 0, _meshtastic_MeshPacket_Priority_MIN, 0, _meshtastic_MeshPacket_Delayed_MIN} +#define meshtastic_NodeInfo_init_default {0, false, meshtastic_User_init_default, false, meshtastic_Position_init_default, 0, 0, false, meshtastic_DeviceMetrics_init_default} +#define meshtastic_MyNodeInfo_init_default {0, 0, 0, "", _meshtastic_CriticalErrorCode_MIN, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, 0, 0} +#define meshtastic_LogRecord_init_default {"", 0, "", _meshtastic_LogRecord_Level_MIN} +#define meshtastic_QueueStatus_init_default {0, 0, 0, 0} +#define meshtastic_FromRadio_init_default {0, 0, {meshtastic_MeshPacket_init_default}} +#define meshtastic_ToRadio_init_default {0, {meshtastic_MeshPacket_init_default}} +#define meshtastic_Compressed_init_default {_meshtastic_PortNum_MIN, {0, {0}}} +#define meshtastic_Position_init_zero {0, 0, 0, 0, _meshtastic_Position_LocSource_MIN, _meshtastic_Position_AltSource_MIN, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_User_init_zero {"", "", "", {0}, _meshtastic_HardwareModel_MIN, 0} +#define meshtastic_RouteDiscovery_init_zero {0, {0, 0, 0, 0, 0, 0, 0, 0}} +#define meshtastic_Routing_init_zero {0, {meshtastic_RouteDiscovery_init_zero}} +#define meshtastic_Data_init_zero {_meshtastic_PortNum_MIN, {0, {0}}, 0, 0, 0, 0, 0, 0} +#define meshtastic_Waypoint_init_zero {0, 0, 0, 0, 0, "", "", 0} +#define meshtastic_MeshPacket_init_zero {0, 0, 0, 0, {meshtastic_Data_init_zero}, 0, 0, 0, 0, 0, _meshtastic_MeshPacket_Priority_MIN, 0, _meshtastic_MeshPacket_Delayed_MIN} +#define meshtastic_NodeInfo_init_zero {0, false, meshtastic_User_init_zero, false, meshtastic_Position_init_zero, 0, 0, false, meshtastic_DeviceMetrics_init_zero} +#define meshtastic_MyNodeInfo_init_zero {0, 0, 0, "", _meshtastic_CriticalErrorCode_MIN, 0, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0, 0, 0, 0}, 0, 0, 0} +#define meshtastic_LogRecord_init_zero {"", 0, "", _meshtastic_LogRecord_Level_MIN} +#define meshtastic_QueueStatus_init_zero {0, 0, 0, 0} +#define meshtastic_FromRadio_init_zero {0, 0, {meshtastic_MeshPacket_init_zero}} +#define meshtastic_ToRadio_init_zero {0, {meshtastic_MeshPacket_init_zero}} +#define meshtastic_Compressed_init_zero {_meshtastic_PortNum_MIN, {0, {0}}} /* Field tags (for use in manual encoding/decoding) */ -#define Position_latitude_i_tag 1 -#define Position_longitude_i_tag 2 -#define Position_altitude_tag 3 -#define Position_time_tag 4 -#define Position_location_source_tag 5 -#define Position_altitude_source_tag 6 -#define Position_timestamp_tag 7 -#define Position_timestamp_millis_adjust_tag 8 -#define Position_altitude_hae_tag 9 -#define Position_altitude_geoidal_separation_tag 10 -#define Position_PDOP_tag 11 -#define Position_HDOP_tag 12 -#define Position_VDOP_tag 13 -#define Position_gps_accuracy_tag 14 -#define Position_ground_speed_tag 15 -#define Position_ground_track_tag 16 -#define Position_fix_quality_tag 17 -#define Position_fix_type_tag 18 -#define Position_sats_in_view_tag 19 -#define Position_sensor_id_tag 20 -#define Position_next_update_tag 21 -#define Position_seq_number_tag 22 -#define User_id_tag 1 -#define User_long_name_tag 2 -#define User_short_name_tag 3 -#define User_macaddr_tag 4 -#define User_hw_model_tag 5 -#define User_is_licensed_tag 6 -#define RouteDiscovery_route_tag 1 -#define Routing_route_request_tag 1 -#define Routing_route_reply_tag 2 -#define Routing_error_reason_tag 3 -#define Data_portnum_tag 1 -#define Data_payload_tag 2 -#define Data_want_response_tag 3 -#define Data_dest_tag 4 -#define Data_source_tag 5 -#define Data_request_id_tag 6 -#define Data_reply_id_tag 7 -#define Data_emoji_tag 8 -#define Waypoint_id_tag 1 -#define Waypoint_latitude_i_tag 2 -#define Waypoint_longitude_i_tag 3 -#define Waypoint_expire_tag 4 -#define Waypoint_locked_to_tag 5 -#define Waypoint_name_tag 6 -#define Waypoint_description_tag 7 -#define Waypoint_icon_tag 8 -#define MeshPacket_from_tag 1 -#define MeshPacket_to_tag 2 -#define MeshPacket_channel_tag 3 -#define MeshPacket_decoded_tag 4 -#define MeshPacket_encrypted_tag 5 -#define MeshPacket_id_tag 6 -#define MeshPacket_rx_time_tag 7 -#define MeshPacket_rx_snr_tag 8 -#define MeshPacket_hop_limit_tag 9 -#define MeshPacket_want_ack_tag 10 -#define MeshPacket_priority_tag 11 -#define MeshPacket_rx_rssi_tag 12 -#define MeshPacket_delayed_tag 13 -#define NodeInfo_num_tag 1 -#define NodeInfo_user_tag 2 -#define NodeInfo_position_tag 3 -#define NodeInfo_snr_tag 4 -#define NodeInfo_last_heard_tag 5 -#define NodeInfo_device_metrics_tag 6 -#define MyNodeInfo_my_node_num_tag 1 -#define MyNodeInfo_has_gps_tag 2 -#define MyNodeInfo_max_channels_tag 3 -#define MyNodeInfo_firmware_version_tag 4 -#define MyNodeInfo_error_code_tag 5 -#define MyNodeInfo_error_address_tag 6 -#define MyNodeInfo_error_count_tag 7 -#define MyNodeInfo_reboot_count_tag 8 -#define MyNodeInfo_bitrate_tag 9 -#define MyNodeInfo_message_timeout_msec_tag 10 -#define MyNodeInfo_min_app_version_tag 11 -#define MyNodeInfo_air_period_tx_tag 12 -#define MyNodeInfo_air_period_rx_tag 13 -#define MyNodeInfo_has_wifi_tag 14 -#define MyNodeInfo_channel_utilization_tag 15 -#define MyNodeInfo_air_util_tx_tag 16 -#define LogRecord_message_tag 1 -#define LogRecord_time_tag 2 -#define LogRecord_source_tag 3 -#define LogRecord_level_tag 4 -#define QueueStatus_res_tag 1 -#define QueueStatus_free_tag 2 -#define QueueStatus_maxlen_tag 3 -#define QueueStatus_mesh_packet_id_tag 4 -#define FromRadio_id_tag 1 -#define FromRadio_packet_tag 2 -#define FromRadio_my_info_tag 3 -#define FromRadio_node_info_tag 4 -#define FromRadio_config_tag 5 -#define FromRadio_log_record_tag 6 -#define FromRadio_config_complete_id_tag 7 -#define FromRadio_rebooted_tag 8 -#define FromRadio_moduleConfig_tag 9 -#define FromRadio_channel_tag 10 -#define FromRadio_queueStatus_tag 11 -#define FromRadio_xmodemPacket_tag 12 -#define ToRadio_packet_tag 1 -#define ToRadio_want_config_id_tag 3 -#define ToRadio_disconnect_tag 4 -#define ToRadio_xmodemPacket_tag 5 -#define Compressed_portnum_tag 1 -#define Compressed_data_tag 2 +#define meshtastic_Position_latitude_i_tag 1 +#define meshtastic_Position_longitude_i_tag 2 +#define meshtastic_Position_altitude_tag 3 +#define meshtastic_Position_time_tag 4 +#define meshtastic_Position_location_source_tag 5 +#define meshtastic_Position_altitude_source_tag 6 +#define meshtastic_Position_timestamp_tag 7 +#define meshtastic_Position_timestamp_millis_adjust_tag 8 +#define meshtastic_Position_altitude_hae_tag 9 +#define meshtastic_Position_altitude_geoidal_separation_tag 10 +#define meshtastic_Position_PDOP_tag 11 +#define meshtastic_Position_HDOP_tag 12 +#define meshtastic_Position_VDOP_tag 13 +#define meshtastic_Position_gps_accuracy_tag 14 +#define meshtastic_Position_ground_speed_tag 15 +#define meshtastic_Position_ground_track_tag 16 +#define meshtastic_Position_fix_quality_tag 17 +#define meshtastic_Position_fix_type_tag 18 +#define meshtastic_Position_sats_in_view_tag 19 +#define meshtastic_Position_sensor_id_tag 20 +#define meshtastic_Position_next_update_tag 21 +#define meshtastic_Position_seq_number_tag 22 +#define meshtastic_User_id_tag 1 +#define meshtastic_User_long_name_tag 2 +#define meshtastic_User_short_name_tag 3 +#define meshtastic_User_macaddr_tag 4 +#define meshtastic_User_hw_model_tag 5 +#define meshtastic_User_is_licensed_tag 6 +#define meshtastic_RouteDiscovery_route_tag 1 +#define meshtastic_Routing_route_request_tag 1 +#define meshtastic_Routing_route_reply_tag 2 +#define meshtastic_Routing_error_reason_tag 3 +#define meshtastic_Data_portnum_tag 1 +#define meshtastic_Data_payload_tag 2 +#define meshtastic_Data_want_response_tag 3 +#define meshtastic_Data_dest_tag 4 +#define meshtastic_Data_source_tag 5 +#define meshtastic_Data_request_id_tag 6 +#define meshtastic_Data_reply_id_tag 7 +#define meshtastic_Data_emoji_tag 8 +#define meshtastic_Waypoint_id_tag 1 +#define meshtastic_Waypoint_latitude_i_tag 2 +#define meshtastic_Waypoint_longitude_i_tag 3 +#define meshtastic_Waypoint_expire_tag 4 +#define meshtastic_Waypoint_locked_to_tag 5 +#define meshtastic_Waypoint_name_tag 6 +#define meshtastic_Waypoint_description_tag 7 +#define meshtastic_Waypoint_icon_tag 8 +#define meshtastic_MeshPacket_from_tag 1 +#define meshtastic_MeshPacket_to_tag 2 +#define meshtastic_MeshPacket_channel_tag 3 +#define meshtastic_MeshPacket_decoded_tag 4 +#define meshtastic_MeshPacket_encrypted_tag 5 +#define meshtastic_MeshPacket_id_tag 6 +#define meshtastic_MeshPacket_rx_time_tag 7 +#define meshtastic_MeshPacket_rx_snr_tag 8 +#define meshtastic_MeshPacket_hop_limit_tag 9 +#define meshtastic_MeshPacket_want_ack_tag 10 +#define meshtastic_MeshPacket_priority_tag 11 +#define meshtastic_MeshPacket_rx_rssi_tag 12 +#define meshtastic_MeshPacket_delayed_tag 13 +#define meshtastic_NodeInfo_num_tag 1 +#define meshtastic_NodeInfo_user_tag 2 +#define meshtastic_NodeInfo_position_tag 3 +#define meshtastic_NodeInfo_snr_tag 4 +#define meshtastic_NodeInfo_last_heard_tag 5 +#define meshtastic_NodeInfo_device_metrics_tag 6 +#define meshtastic_MyNodeInfo_my_node_num_tag 1 +#define meshtastic_MyNodeInfo_has_gps_tag 2 +#define meshtastic_MyNodeInfo_max_channels_tag 3 +#define meshtastic_MyNodeInfo_firmware_version_tag 4 +#define meshtastic_MyNodeInfo_error_code_tag 5 +#define meshtastic_MyNodeInfo_error_address_tag 6 +#define meshtastic_MyNodeInfo_error_count_tag 7 +#define meshtastic_MyNodeInfo_reboot_count_tag 8 +#define meshtastic_MyNodeInfo_bitrate_tag 9 +#define meshtastic_MyNodeInfo_message_timeout_msec_tag 10 +#define meshtastic_MyNodeInfo_min_app_version_tag 11 +#define meshtastic_MyNodeInfo_air_period_tx_tag 12 +#define meshtastic_MyNodeInfo_air_period_rx_tag 13 +#define meshtastic_MyNodeInfo_has_wifi_tag 14 +#define meshtastic_MyNodeInfo_channel_utilization_tag 15 +#define meshtastic_MyNodeInfo_air_util_tx_tag 16 +#define meshtastic_LogRecord_message_tag 1 +#define meshtastic_LogRecord_time_tag 2 +#define meshtastic_LogRecord_source_tag 3 +#define meshtastic_LogRecord_level_tag 4 +#define meshtastic_QueueStatus_res_tag 1 +#define meshtastic_QueueStatus_free_tag 2 +#define meshtastic_QueueStatus_maxlen_tag 3 +#define meshtastic_QueueStatus_mesh_packet_id_tag 4 +#define meshtastic_FromRadio_id_tag 1 +#define meshtastic_FromRadio_packet_tag 2 +#define meshtastic_FromRadio_my_info_tag 3 +#define meshtastic_FromRadio_node_info_tag 4 +#define meshtastic_FromRadio_config_tag 5 +#define meshtastic_FromRadio_log_record_tag 6 +#define meshtastic_FromRadio_config_complete_id_tag 7 +#define meshtastic_FromRadio_rebooted_tag 8 +#define meshtastic_FromRadio_moduleConfig_tag 9 +#define meshtastic_FromRadio_channel_tag 10 +#define meshtastic_FromRadio_queueStatus_tag 11 +#define meshtastic_FromRadio_xmodemPacket_tag 12 +#define meshtastic_ToRadio_packet_tag 1 +#define meshtastic_ToRadio_want_config_id_tag 3 +#define meshtastic_ToRadio_disconnect_tag 4 +#define meshtastic_ToRadio_xmodemPacket_tag 5 +#define meshtastic_Compressed_portnum_tag 1 +#define meshtastic_Compressed_data_tag 2 /* Struct field encoding specification for nanopb */ -#define Position_FIELDLIST(X, a) \ +#define meshtastic_Position_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, SFIXED32, latitude_i, 1) \ X(a, STATIC, SINGULAR, SFIXED32, longitude_i, 2) \ X(a, STATIC, SINGULAR, INT32, altitude, 3) \ @@ -945,34 +945,34 @@ X(a, STATIC, SINGULAR, UINT32, sats_in_view, 19) \ X(a, STATIC, SINGULAR, UINT32, sensor_id, 20) \ X(a, STATIC, SINGULAR, UINT32, next_update, 21) \ X(a, STATIC, SINGULAR, UINT32, seq_number, 22) -#define Position_CALLBACK NULL -#define Position_DEFAULT NULL +#define meshtastic_Position_CALLBACK NULL +#define meshtastic_Position_DEFAULT NULL -#define User_FIELDLIST(X, a) \ +#define meshtastic_User_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, STRING, id, 1) \ X(a, STATIC, SINGULAR, STRING, long_name, 2) \ X(a, STATIC, SINGULAR, STRING, short_name, 3) \ X(a, STATIC, SINGULAR, FIXED_LENGTH_BYTES, macaddr, 4) \ X(a, STATIC, SINGULAR, UENUM, hw_model, 5) \ X(a, STATIC, SINGULAR, BOOL, is_licensed, 6) -#define User_CALLBACK NULL -#define User_DEFAULT NULL +#define meshtastic_User_CALLBACK NULL +#define meshtastic_User_DEFAULT NULL -#define RouteDiscovery_FIELDLIST(X, a) \ +#define meshtastic_RouteDiscovery_FIELDLIST(X, a) \ X(a, STATIC, REPEATED, FIXED32, route, 1) -#define RouteDiscovery_CALLBACK NULL -#define RouteDiscovery_DEFAULT NULL +#define meshtastic_RouteDiscovery_CALLBACK NULL +#define meshtastic_RouteDiscovery_DEFAULT NULL -#define Routing_FIELDLIST(X, a) \ +#define meshtastic_Routing_FIELDLIST(X, a) \ X(a, STATIC, ONEOF, MESSAGE, (variant,route_request,route_request), 1) \ X(a, STATIC, ONEOF, MESSAGE, (variant,route_reply,route_reply), 2) \ X(a, STATIC, ONEOF, UENUM, (variant,error_reason,error_reason), 3) -#define Routing_CALLBACK NULL -#define Routing_DEFAULT NULL -#define Routing_variant_route_request_MSGTYPE RouteDiscovery -#define Routing_variant_route_reply_MSGTYPE RouteDiscovery +#define meshtastic_Routing_CALLBACK NULL +#define meshtastic_Routing_DEFAULT NULL +#define meshtastic_Routing_variant_route_request_MSGTYPE meshtastic_RouteDiscovery +#define meshtastic_Routing_variant_route_reply_MSGTYPE meshtastic_RouteDiscovery -#define Data_FIELDLIST(X, a) \ +#define meshtastic_Data_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, portnum, 1) \ X(a, STATIC, SINGULAR, BYTES, payload, 2) \ X(a, STATIC, SINGULAR, BOOL, want_response, 3) \ @@ -981,10 +981,10 @@ X(a, STATIC, SINGULAR, FIXED32, source, 5) \ X(a, STATIC, SINGULAR, FIXED32, request_id, 6) \ X(a, STATIC, SINGULAR, FIXED32, reply_id, 7) \ X(a, STATIC, SINGULAR, FIXED32, emoji, 8) -#define Data_CALLBACK NULL -#define Data_DEFAULT NULL +#define meshtastic_Data_CALLBACK NULL +#define meshtastic_Data_DEFAULT NULL -#define Waypoint_FIELDLIST(X, a) \ +#define meshtastic_Waypoint_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, id, 1) \ X(a, STATIC, SINGULAR, SFIXED32, latitude_i, 2) \ X(a, STATIC, SINGULAR, SFIXED32, longitude_i, 3) \ @@ -993,10 +993,10 @@ X(a, STATIC, SINGULAR, UINT32, locked_to, 5) \ X(a, STATIC, SINGULAR, STRING, name, 6) \ X(a, STATIC, SINGULAR, STRING, description, 7) \ X(a, STATIC, SINGULAR, FIXED32, icon, 8) -#define Waypoint_CALLBACK NULL -#define Waypoint_DEFAULT NULL +#define meshtastic_Waypoint_CALLBACK NULL +#define meshtastic_Waypoint_DEFAULT NULL -#define MeshPacket_FIELDLIST(X, a) \ +#define meshtastic_MeshPacket_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, FIXED32, from, 1) \ X(a, STATIC, SINGULAR, FIXED32, to, 2) \ X(a, STATIC, SINGULAR, UINT32, channel, 3) \ @@ -1010,24 +1010,24 @@ X(a, STATIC, SINGULAR, BOOL, want_ack, 10) \ X(a, STATIC, SINGULAR, UENUM, priority, 11) \ X(a, STATIC, SINGULAR, INT32, rx_rssi, 12) \ X(a, STATIC, SINGULAR, UENUM, delayed, 13) -#define MeshPacket_CALLBACK NULL -#define MeshPacket_DEFAULT NULL -#define MeshPacket_payload_variant_decoded_MSGTYPE Data +#define meshtastic_MeshPacket_CALLBACK NULL +#define meshtastic_MeshPacket_DEFAULT NULL +#define meshtastic_MeshPacket_payload_variant_decoded_MSGTYPE meshtastic_Data -#define NodeInfo_FIELDLIST(X, a) \ +#define meshtastic_NodeInfo_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, num, 1) \ X(a, STATIC, OPTIONAL, MESSAGE, user, 2) \ X(a, STATIC, OPTIONAL, MESSAGE, position, 3) \ X(a, STATIC, SINGULAR, FLOAT, snr, 4) \ X(a, STATIC, SINGULAR, FIXED32, last_heard, 5) \ X(a, STATIC, OPTIONAL, MESSAGE, device_metrics, 6) -#define NodeInfo_CALLBACK NULL -#define NodeInfo_DEFAULT NULL -#define NodeInfo_user_MSGTYPE User -#define NodeInfo_position_MSGTYPE Position -#define NodeInfo_device_metrics_MSGTYPE DeviceMetrics +#define meshtastic_NodeInfo_CALLBACK NULL +#define meshtastic_NodeInfo_DEFAULT NULL +#define meshtastic_NodeInfo_user_MSGTYPE meshtastic_User +#define meshtastic_NodeInfo_position_MSGTYPE meshtastic_Position +#define meshtastic_NodeInfo_device_metrics_MSGTYPE meshtastic_DeviceMetrics -#define MyNodeInfo_FIELDLIST(X, a) \ +#define meshtastic_MyNodeInfo_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, my_node_num, 1) \ X(a, STATIC, SINGULAR, BOOL, has_gps, 2) \ X(a, STATIC, SINGULAR, UINT32, max_channels, 3) \ @@ -1044,26 +1044,26 @@ X(a, STATIC, REPEATED, UINT32, air_period_rx, 13) \ X(a, STATIC, SINGULAR, BOOL, has_wifi, 14) \ X(a, STATIC, SINGULAR, FLOAT, channel_utilization, 15) \ X(a, STATIC, SINGULAR, FLOAT, air_util_tx, 16) -#define MyNodeInfo_CALLBACK NULL -#define MyNodeInfo_DEFAULT NULL +#define meshtastic_MyNodeInfo_CALLBACK NULL +#define meshtastic_MyNodeInfo_DEFAULT NULL -#define LogRecord_FIELDLIST(X, a) \ +#define meshtastic_LogRecord_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, STRING, message, 1) \ X(a, STATIC, SINGULAR, FIXED32, time, 2) \ X(a, STATIC, SINGULAR, STRING, source, 3) \ X(a, STATIC, SINGULAR, UENUM, level, 4) -#define LogRecord_CALLBACK NULL -#define LogRecord_DEFAULT NULL +#define meshtastic_LogRecord_CALLBACK NULL +#define meshtastic_LogRecord_DEFAULT NULL -#define QueueStatus_FIELDLIST(X, a) \ +#define meshtastic_QueueStatus_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, INT32, res, 1) \ X(a, STATIC, SINGULAR, UINT32, free, 2) \ X(a, STATIC, SINGULAR, UINT32, maxlen, 3) \ X(a, STATIC, SINGULAR, UINT32, mesh_packet_id, 4) -#define QueueStatus_CALLBACK NULL -#define QueueStatus_DEFAULT NULL +#define meshtastic_QueueStatus_CALLBACK NULL +#define meshtastic_QueueStatus_DEFAULT NULL -#define FromRadio_FIELDLIST(X, a) \ +#define meshtastic_FromRadio_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, id, 1) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,packet,packet), 2) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,my_info,my_info), 3) \ @@ -1076,80 +1076,80 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,moduleConfig,moduleConfig), X(a, STATIC, ONEOF, MESSAGE, (payload_variant,channel,channel), 10) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,queueStatus,queueStatus), 11) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,xmodemPacket,xmodemPacket), 12) -#define FromRadio_CALLBACK NULL -#define FromRadio_DEFAULT NULL -#define FromRadio_payload_variant_packet_MSGTYPE MeshPacket -#define FromRadio_payload_variant_my_info_MSGTYPE MyNodeInfo -#define FromRadio_payload_variant_node_info_MSGTYPE NodeInfo -#define FromRadio_payload_variant_config_MSGTYPE Config -#define FromRadio_payload_variant_log_record_MSGTYPE LogRecord -#define FromRadio_payload_variant_moduleConfig_MSGTYPE ModuleConfig -#define FromRadio_payload_variant_channel_MSGTYPE Channel -#define FromRadio_payload_variant_queueStatus_MSGTYPE QueueStatus -#define FromRadio_payload_variant_xmodemPacket_MSGTYPE XModem +#define meshtastic_FromRadio_CALLBACK NULL +#define meshtastic_FromRadio_DEFAULT NULL +#define meshtastic_FromRadio_payload_variant_packet_MSGTYPE meshtastic_MeshPacket +#define meshtastic_FromRadio_payload_variant_my_info_MSGTYPE meshtastic_MyNodeInfo +#define meshtastic_FromRadio_payload_variant_node_info_MSGTYPE meshtastic_NodeInfo +#define meshtastic_FromRadio_payload_variant_config_MSGTYPE meshtastic_Config +#define meshtastic_FromRadio_payload_variant_log_record_MSGTYPE meshtastic_LogRecord +#define meshtastic_FromRadio_payload_variant_moduleConfig_MSGTYPE meshtastic_ModuleConfig +#define meshtastic_FromRadio_payload_variant_channel_MSGTYPE meshtastic_Channel +#define meshtastic_FromRadio_payload_variant_queueStatus_MSGTYPE meshtastic_QueueStatus +#define meshtastic_FromRadio_payload_variant_xmodemPacket_MSGTYPE meshtastic_XModem -#define ToRadio_FIELDLIST(X, a) \ +#define meshtastic_ToRadio_FIELDLIST(X, a) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,packet,packet), 1) \ X(a, STATIC, ONEOF, UINT32, (payload_variant,want_config_id,want_config_id), 3) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,disconnect,disconnect), 4) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,xmodemPacket,xmodemPacket), 5) -#define ToRadio_CALLBACK NULL -#define ToRadio_DEFAULT NULL -#define ToRadio_payload_variant_packet_MSGTYPE MeshPacket -#define ToRadio_payload_variant_xmodemPacket_MSGTYPE XModem +#define meshtastic_ToRadio_CALLBACK NULL +#define meshtastic_ToRadio_DEFAULT NULL +#define meshtastic_ToRadio_payload_variant_packet_MSGTYPE meshtastic_MeshPacket +#define meshtastic_ToRadio_payload_variant_xmodemPacket_MSGTYPE meshtastic_XModem -#define Compressed_FIELDLIST(X, a) \ +#define meshtastic_Compressed_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, portnum, 1) \ X(a, STATIC, SINGULAR, BYTES, data, 2) -#define Compressed_CALLBACK NULL -#define Compressed_DEFAULT NULL +#define meshtastic_Compressed_CALLBACK NULL +#define meshtastic_Compressed_DEFAULT NULL -extern const pb_msgdesc_t Position_msg; -extern const pb_msgdesc_t User_msg; -extern const pb_msgdesc_t RouteDiscovery_msg; -extern const pb_msgdesc_t Routing_msg; -extern const pb_msgdesc_t Data_msg; -extern const pb_msgdesc_t Waypoint_msg; -extern const pb_msgdesc_t MeshPacket_msg; -extern const pb_msgdesc_t NodeInfo_msg; -extern const pb_msgdesc_t MyNodeInfo_msg; -extern const pb_msgdesc_t LogRecord_msg; -extern const pb_msgdesc_t QueueStatus_msg; -extern const pb_msgdesc_t FromRadio_msg; -extern const pb_msgdesc_t ToRadio_msg; -extern const pb_msgdesc_t Compressed_msg; +extern const pb_msgdesc_t meshtastic_Position_msg; +extern const pb_msgdesc_t meshtastic_User_msg; +extern const pb_msgdesc_t meshtastic_RouteDiscovery_msg; +extern const pb_msgdesc_t meshtastic_Routing_msg; +extern const pb_msgdesc_t meshtastic_Data_msg; +extern const pb_msgdesc_t meshtastic_Waypoint_msg; +extern const pb_msgdesc_t meshtastic_MeshPacket_msg; +extern const pb_msgdesc_t meshtastic_NodeInfo_msg; +extern const pb_msgdesc_t meshtastic_MyNodeInfo_msg; +extern const pb_msgdesc_t meshtastic_LogRecord_msg; +extern const pb_msgdesc_t meshtastic_QueueStatus_msg; +extern const pb_msgdesc_t meshtastic_FromRadio_msg; +extern const pb_msgdesc_t meshtastic_ToRadio_msg; +extern const pb_msgdesc_t meshtastic_Compressed_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define Position_fields &Position_msg -#define User_fields &User_msg -#define RouteDiscovery_fields &RouteDiscovery_msg -#define Routing_fields &Routing_msg -#define Data_fields &Data_msg -#define Waypoint_fields &Waypoint_msg -#define MeshPacket_fields &MeshPacket_msg -#define NodeInfo_fields &NodeInfo_msg -#define MyNodeInfo_fields &MyNodeInfo_msg -#define LogRecord_fields &LogRecord_msg -#define QueueStatus_fields &QueueStatus_msg -#define FromRadio_fields &FromRadio_msg -#define ToRadio_fields &ToRadio_msg -#define Compressed_fields &Compressed_msg +#define meshtastic_Position_fields &meshtastic_Position_msg +#define meshtastic_User_fields &meshtastic_User_msg +#define meshtastic_RouteDiscovery_fields &meshtastic_RouteDiscovery_msg +#define meshtastic_Routing_fields &meshtastic_Routing_msg +#define meshtastic_Data_fields &meshtastic_Data_msg +#define meshtastic_Waypoint_fields &meshtastic_Waypoint_msg +#define meshtastic_MeshPacket_fields &meshtastic_MeshPacket_msg +#define meshtastic_NodeInfo_fields &meshtastic_NodeInfo_msg +#define meshtastic_MyNodeInfo_fields &meshtastic_MyNodeInfo_msg +#define meshtastic_LogRecord_fields &meshtastic_LogRecord_msg +#define meshtastic_QueueStatus_fields &meshtastic_QueueStatus_msg +#define meshtastic_FromRadio_fields &meshtastic_FromRadio_msg +#define meshtastic_ToRadio_fields &meshtastic_ToRadio_msg +#define meshtastic_Compressed_fields &meshtastic_Compressed_msg /* Maximum encoded size of messages (where known) */ -#define Compressed_size 243 -#define Data_size 270 -#define FromRadio_size 330 -#define LogRecord_size 81 -#define MeshPacket_size 321 -#define MyNodeInfo_size 179 -#define NodeInfo_size 258 -#define Position_size 137 -#define QueueStatus_size 23 -#define RouteDiscovery_size 40 -#define Routing_size 42 -#define ToRadio_size 324 -#define User_size 77 -#define Waypoint_size 165 +#define meshtastic_Compressed_size 243 +#define meshtastic_Data_size 270 +#define meshtastic_FromRadio_size 330 +#define meshtastic_LogRecord_size 81 +#define meshtastic_MeshPacket_size 321 +#define meshtastic_MyNodeInfo_size 179 +#define meshtastic_NodeInfo_size 258 +#define meshtastic_Position_size 137 +#define meshtastic_QueueStatus_size 23 +#define meshtastic_RouteDiscovery_size 40 +#define meshtastic_Routing_size 42 +#define meshtastic_ToRadio_size 324 +#define meshtastic_User_size 77 +#define meshtastic_Waypoint_size 165 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/module_config.pb.c b/src/mesh/generated/meshtastic/module_config.pb.c index a67bcfcc9..0878be909 100644 --- a/src/mesh/generated/meshtastic/module_config.pb.c +++ b/src/mesh/generated/meshtastic/module_config.pb.c @@ -1,39 +1,39 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./module_config.pb.h" +#include "meshtastic/module_config.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(ModuleConfig, ModuleConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig, meshtastic_ModuleConfig, AUTO) -PB_BIND(ModuleConfig_MQTTConfig, ModuleConfig_MQTTConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_MQTTConfig, meshtastic_ModuleConfig_MQTTConfig, AUTO) -PB_BIND(ModuleConfig_RemoteHardwareConfig, ModuleConfig_RemoteHardwareConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_RemoteHardwareConfig, meshtastic_ModuleConfig_RemoteHardwareConfig, AUTO) -PB_BIND(ModuleConfig_AudioConfig, ModuleConfig_AudioConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_AudioConfig, meshtastic_ModuleConfig_AudioConfig, AUTO) -PB_BIND(ModuleConfig_SerialConfig, ModuleConfig_SerialConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_SerialConfig, meshtastic_ModuleConfig_SerialConfig, AUTO) -PB_BIND(ModuleConfig_ExternalNotificationConfig, ModuleConfig_ExternalNotificationConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_ExternalNotificationConfig, meshtastic_ModuleConfig_ExternalNotificationConfig, AUTO) -PB_BIND(ModuleConfig_StoreForwardConfig, ModuleConfig_StoreForwardConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_StoreForwardConfig, meshtastic_ModuleConfig_StoreForwardConfig, AUTO) -PB_BIND(ModuleConfig_RangeTestConfig, ModuleConfig_RangeTestConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_RangeTestConfig, meshtastic_ModuleConfig_RangeTestConfig, AUTO) -PB_BIND(ModuleConfig_TelemetryConfig, ModuleConfig_TelemetryConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_TelemetryConfig, meshtastic_ModuleConfig_TelemetryConfig, AUTO) -PB_BIND(ModuleConfig_CannedMessageConfig, ModuleConfig_CannedMessageConfig, AUTO) +PB_BIND(meshtastic_ModuleConfig_CannedMessageConfig, meshtastic_ModuleConfig_CannedMessageConfig, AUTO) diff --git a/src/mesh/generated/meshtastic/module_config.pb.h b/src/mesh/generated/meshtastic/module_config.pb.h index 84914285f..50fed5197 100644 --- a/src/mesh/generated/meshtastic/module_config.pb.h +++ b/src/mesh/generated/meshtastic/module_config.pb.h @@ -11,70 +11,70 @@ /* Enum definitions */ /* Baudrate for codec2 voice */ -typedef enum _ModuleConfig_AudioConfig_Audio_Baud { - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_DEFAULT = 0, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_3200 = 1, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_2400 = 2, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1600 = 3, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1400 = 4, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1300 = 5, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1200 = 6, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 = 7, - ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B = 8 -} ModuleConfig_AudioConfig_Audio_Baud; +typedef enum _meshtastic_ModuleConfig_AudioConfig_Audio_Baud { + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_DEFAULT = 0, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_3200 = 1, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_2400 = 2, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1600 = 3, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1400 = 4, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1300 = 5, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_1200 = 6, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 = 7, + meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B = 8 +} meshtastic_ModuleConfig_AudioConfig_Audio_Baud; /* TODO: REPLACE */ -typedef enum _ModuleConfig_SerialConfig_Serial_Baud { - ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT = 0, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_110 = 1, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_300 = 2, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_600 = 3, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_1200 = 4, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_2400 = 5, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_4800 = 6, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_9600 = 7, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_19200 = 8, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_38400 = 9, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_57600 = 10, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_115200 = 11, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_230400 = 12, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_460800 = 13, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_576000 = 14, - ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600 = 15 -} ModuleConfig_SerialConfig_Serial_Baud; +typedef enum _meshtastic_ModuleConfig_SerialConfig_Serial_Baud { + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT = 0, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_110 = 1, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_300 = 2, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_600 = 3, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_1200 = 4, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_2400 = 5, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_4800 = 6, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_9600 = 7, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_19200 = 8, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_38400 = 9, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_57600 = 10, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_115200 = 11, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_230400 = 12, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_460800 = 13, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_576000 = 14, + meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600 = 15 +} meshtastic_ModuleConfig_SerialConfig_Serial_Baud; /* TODO: REPLACE */ -typedef enum _ModuleConfig_SerialConfig_Serial_Mode { - ModuleConfig_SerialConfig_Serial_Mode_DEFAULT = 0, - ModuleConfig_SerialConfig_Serial_Mode_SIMPLE = 1, - ModuleConfig_SerialConfig_Serial_Mode_PROTO = 2, - ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG = 3, - ModuleConfig_SerialConfig_Serial_Mode_NMEA = 4 -} ModuleConfig_SerialConfig_Serial_Mode; +typedef enum _meshtastic_ModuleConfig_SerialConfig_Serial_Mode { + meshtastic_ModuleConfig_SerialConfig_Serial_Mode_DEFAULT = 0, + meshtastic_ModuleConfig_SerialConfig_Serial_Mode_SIMPLE = 1, + meshtastic_ModuleConfig_SerialConfig_Serial_Mode_PROTO = 2, + meshtastic_ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG = 3, + meshtastic_ModuleConfig_SerialConfig_Serial_Mode_NMEA = 4 +} meshtastic_ModuleConfig_SerialConfig_Serial_Mode; /* TODO: REPLACE */ -typedef enum _ModuleConfig_CannedMessageConfig_InputEventChar { +typedef enum _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar { /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig_InputEventChar_NONE = 0, + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE = 0, /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig_InputEventChar_UP = 17, + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_UP = 17, /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig_InputEventChar_DOWN = 18, + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_DOWN = 18, /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig_InputEventChar_LEFT = 19, + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_LEFT = 19, /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT = 20, + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT = 20, /* '\n' */ - ModuleConfig_CannedMessageConfig_InputEventChar_SELECT = 10, + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_SELECT = 10, /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig_InputEventChar_BACK = 27, + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_BACK = 27, /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL = 24 -} ModuleConfig_CannedMessageConfig_InputEventChar; + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL = 24 +} meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar; /* Struct definitions */ /* MQTT Client Config */ -typedef struct _ModuleConfig_MQTTConfig { +typedef struct _meshtastic_ModuleConfig_MQTTConfig { /* If a meshtastic node is able to reach the internet it will normally attempt to gateway any channels that are marked as is_uplink_enabled or is_downlink_enabled. */ bool enabled; @@ -96,22 +96,22 @@ typedef struct _ModuleConfig_MQTTConfig { bool encryption_enabled; /* Whether to send / consume json packets on MQTT */ bool json_enabled; -} ModuleConfig_MQTTConfig; +} meshtastic_ModuleConfig_MQTTConfig; /* RemoteHardwareModule Config */ -typedef struct _ModuleConfig_RemoteHardwareConfig { +typedef struct _meshtastic_ModuleConfig_RemoteHardwareConfig { /* Whether the Module is enabled */ bool enabled; -} ModuleConfig_RemoteHardwareConfig; +} meshtastic_ModuleConfig_RemoteHardwareConfig; /* Audio Config for codec2 voice */ -typedef struct _ModuleConfig_AudioConfig { +typedef struct _meshtastic_ModuleConfig_AudioConfig { /* Whether Audio is enabled */ bool codec2_enabled; /* PTT Pin */ uint8_t ptt_pin; /* The audio sample rate to use for codec2 */ - ModuleConfig_AudioConfig_Audio_Baud bitrate; + meshtastic_ModuleConfig_AudioConfig_Audio_Baud bitrate; /* I2S Word Select */ uint8_t i2s_ws; /* I2S Data IN */ @@ -120,10 +120,10 @@ typedef struct _ModuleConfig_AudioConfig { uint8_t i2s_din; /* I2S Clock */ uint8_t i2s_sck; -} ModuleConfig_AudioConfig; +} meshtastic_ModuleConfig_AudioConfig; /* Serial Config */ -typedef struct _ModuleConfig_SerialConfig { +typedef struct _meshtastic_ModuleConfig_SerialConfig { /* Preferences for the SerialModule FIXME - Move this out of UserPreferences and into a section for module configuration. */ bool enabled; @@ -134,15 +134,15 @@ typedef struct _ModuleConfig_SerialConfig { /* TODO: REPLACE */ uint32_t txd; /* TODO: REPLACE */ - ModuleConfig_SerialConfig_Serial_Baud baud; + meshtastic_ModuleConfig_SerialConfig_Serial_Baud baud; /* TODO: REPLACE */ uint32_t timeout; /* TODO: REPLACE */ - ModuleConfig_SerialConfig_Serial_Mode mode; -} ModuleConfig_SerialConfig; + meshtastic_ModuleConfig_SerialConfig_Serial_Mode mode; +} meshtastic_ModuleConfig_SerialConfig; /* External Notifications Config */ -typedef struct _ModuleConfig_ExternalNotificationConfig { +typedef struct _meshtastic_ModuleConfig_ExternalNotificationConfig { /* Enable the ExternalNotificationModule */ bool enabled; /* When using in On/Off mode, keep the output on for this many @@ -181,10 +181,10 @@ typedef struct _ModuleConfig_ExternalNotificationConfig { Default is 0 which means don't repeat at all. 60 would mean blink and/or beep for 60 seconds */ uint16_t nag_timeout; -} ModuleConfig_ExternalNotificationConfig; +} meshtastic_ModuleConfig_ExternalNotificationConfig; /* Store and Forward Module Config */ -typedef struct _ModuleConfig_StoreForwardConfig { +typedef struct _meshtastic_ModuleConfig_StoreForwardConfig { /* Enable the Store and Forward Module */ bool enabled; /* TODO: REPLACE */ @@ -195,10 +195,10 @@ typedef struct _ModuleConfig_StoreForwardConfig { uint32_t history_return_max; /* TODO: REPLACE */ uint32_t history_return_window; -} ModuleConfig_StoreForwardConfig; +} meshtastic_ModuleConfig_StoreForwardConfig; /* Preferences for the RangeTestModule */ -typedef struct _ModuleConfig_RangeTestConfig { +typedef struct _meshtastic_ModuleConfig_RangeTestConfig { /* Enable the Range Test Module */ bool enabled; /* Send out range test messages from this node */ @@ -206,10 +206,10 @@ typedef struct _ModuleConfig_RangeTestConfig { /* Bool value indicating that this node should save a RangeTest.csv file. ESP32 Only */ bool save; -} ModuleConfig_RangeTestConfig; +} meshtastic_ModuleConfig_RangeTestConfig; /* Configuration for both device and environment metrics */ -typedef struct _ModuleConfig_TelemetryConfig { +typedef struct _meshtastic_ModuleConfig_TelemetryConfig { /* Interval in seconds of how often we should try to send our device metrics to the mesh */ uint32_t device_update_interval; @@ -222,10 +222,10 @@ typedef struct _ModuleConfig_TelemetryConfig { /* We'll always read the sensor in Celsius, but sometimes we might want to display the results in Fahrenheit as a "user preference". */ bool environment_display_fahrenheit; -} ModuleConfig_TelemetryConfig; +} meshtastic_ModuleConfig_TelemetryConfig; /* TODO: REPLACE */ -typedef struct _ModuleConfig_CannedMessageConfig { +typedef struct _meshtastic_ModuleConfig_CannedMessageConfig { /* Enable the rotary encoder #1. This is a 'dumb' encoder sending pulses on both A and B pins while rotating. */ bool rotary1_enabled; /* GPIO pin for rotary encoder A port. */ @@ -235,11 +235,11 @@ typedef struct _ModuleConfig_CannedMessageConfig { /* GPIO pin for rotary encoder Press port. */ uint32_t inputbroker_pin_press; /* Generate input event on CW of this kind. */ - ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_cw; + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_cw; /* Generate input event on CCW of this kind. */ - ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_ccw; + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_ccw; /* Generate input event on Press of this kind. */ - ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_press; + meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar inputbroker_event_press; /* Enable the Up/Down/Select input device. Can be RAK rotary encoder or 3 buttons. Uses the a/b/press definitions from inputbroker. */ bool updown1_enabled; /* Enable/disable CannedMessageModule. */ @@ -250,32 +250,32 @@ typedef struct _ModuleConfig_CannedMessageConfig { /* CannedMessageModule also sends a bell character with the messages. ExternalNotificationModule can benefit from this feature. */ bool send_bell; -} ModuleConfig_CannedMessageConfig; +} meshtastic_ModuleConfig_CannedMessageConfig; /* Module Config */ -typedef struct _ModuleConfig { +typedef struct _meshtastic_ModuleConfig { pb_size_t which_payload_variant; union { /* TODO: REPLACE */ - ModuleConfig_MQTTConfig mqtt; + meshtastic_ModuleConfig_MQTTConfig mqtt; /* TODO: REPLACE */ - ModuleConfig_SerialConfig serial; + meshtastic_ModuleConfig_SerialConfig serial; /* TODO: REPLACE */ - ModuleConfig_ExternalNotificationConfig external_notification; + meshtastic_ModuleConfig_ExternalNotificationConfig external_notification; /* TODO: REPLACE */ - ModuleConfig_StoreForwardConfig store_forward; + meshtastic_ModuleConfig_StoreForwardConfig store_forward; /* TODO: REPLACE */ - ModuleConfig_RangeTestConfig range_test; + meshtastic_ModuleConfig_RangeTestConfig range_test; /* TODO: REPLACE */ - ModuleConfig_TelemetryConfig telemetry; + meshtastic_ModuleConfig_TelemetryConfig telemetry; /* TODO: REPLACE */ - ModuleConfig_CannedMessageConfig canned_message; + meshtastic_ModuleConfig_CannedMessageConfig canned_message; /* TODO: REPLACE */ - ModuleConfig_AudioConfig audio; + meshtastic_ModuleConfig_AudioConfig audio; /* TODO: REPLACE */ - ModuleConfig_RemoteHardwareConfig remote_hardware; + meshtastic_ModuleConfig_RemoteHardwareConfig remote_hardware; } payload_variant; -} ModuleConfig; +} meshtastic_ModuleConfig; #ifdef __cplusplus @@ -283,133 +283,133 @@ extern "C" { #endif /* Helper constants for enums */ -#define _ModuleConfig_AudioConfig_Audio_Baud_MIN ModuleConfig_AudioConfig_Audio_Baud_CODEC2_DEFAULT -#define _ModuleConfig_AudioConfig_Audio_Baud_MAX ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B -#define _ModuleConfig_AudioConfig_Audio_Baud_ARRAYSIZE ((ModuleConfig_AudioConfig_Audio_Baud)(ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B+1)) +#define _meshtastic_ModuleConfig_AudioConfig_Audio_Baud_MIN meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_DEFAULT +#define _meshtastic_ModuleConfig_AudioConfig_Audio_Baud_MAX meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B +#define _meshtastic_ModuleConfig_AudioConfig_Audio_Baud_ARRAYSIZE ((meshtastic_ModuleConfig_AudioConfig_Audio_Baud)(meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700B+1)) -#define _ModuleConfig_SerialConfig_Serial_Baud_MIN ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT -#define _ModuleConfig_SerialConfig_Serial_Baud_MAX ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600 -#define _ModuleConfig_SerialConfig_Serial_Baud_ARRAYSIZE ((ModuleConfig_SerialConfig_Serial_Baud)(ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600+1)) +#define _meshtastic_ModuleConfig_SerialConfig_Serial_Baud_MIN meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT +#define _meshtastic_ModuleConfig_SerialConfig_Serial_Baud_MAX meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600 +#define _meshtastic_ModuleConfig_SerialConfig_Serial_Baud_ARRAYSIZE ((meshtastic_ModuleConfig_SerialConfig_Serial_Baud)(meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600+1)) -#define _ModuleConfig_SerialConfig_Serial_Mode_MIN ModuleConfig_SerialConfig_Serial_Mode_DEFAULT -#define _ModuleConfig_SerialConfig_Serial_Mode_MAX ModuleConfig_SerialConfig_Serial_Mode_NMEA -#define _ModuleConfig_SerialConfig_Serial_Mode_ARRAYSIZE ((ModuleConfig_SerialConfig_Serial_Mode)(ModuleConfig_SerialConfig_Serial_Mode_NMEA+1)) +#define _meshtastic_ModuleConfig_SerialConfig_Serial_Mode_MIN meshtastic_ModuleConfig_SerialConfig_Serial_Mode_DEFAULT +#define _meshtastic_ModuleConfig_SerialConfig_Serial_Mode_MAX meshtastic_ModuleConfig_SerialConfig_Serial_Mode_NMEA +#define _meshtastic_ModuleConfig_SerialConfig_Serial_Mode_ARRAYSIZE ((meshtastic_ModuleConfig_SerialConfig_Serial_Mode)(meshtastic_ModuleConfig_SerialConfig_Serial_Mode_NMEA+1)) -#define _ModuleConfig_CannedMessageConfig_InputEventChar_MIN ModuleConfig_CannedMessageConfig_InputEventChar_NONE -#define _ModuleConfig_CannedMessageConfig_InputEventChar_MAX ModuleConfig_CannedMessageConfig_InputEventChar_BACK -#define _ModuleConfig_CannedMessageConfig_InputEventChar_ARRAYSIZE ((ModuleConfig_CannedMessageConfig_InputEventChar)(ModuleConfig_CannedMessageConfig_InputEventChar_BACK+1)) +#define _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE +#define _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MAX meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_BACK +#define _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_ARRAYSIZE ((meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar)(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_BACK+1)) -#define ModuleConfig_AudioConfig_bitrate_ENUMTYPE ModuleConfig_AudioConfig_Audio_Baud +#define meshtastic_ModuleConfig_AudioConfig_bitrate_ENUMTYPE meshtastic_ModuleConfig_AudioConfig_Audio_Baud -#define ModuleConfig_SerialConfig_baud_ENUMTYPE ModuleConfig_SerialConfig_Serial_Baud -#define ModuleConfig_SerialConfig_mode_ENUMTYPE ModuleConfig_SerialConfig_Serial_Mode +#define meshtastic_ModuleConfig_SerialConfig_baud_ENUMTYPE meshtastic_ModuleConfig_SerialConfig_Serial_Baud +#define meshtastic_ModuleConfig_SerialConfig_mode_ENUMTYPE meshtastic_ModuleConfig_SerialConfig_Serial_Mode -#define ModuleConfig_CannedMessageConfig_inputbroker_event_cw_ENUMTYPE ModuleConfig_CannedMessageConfig_InputEventChar -#define ModuleConfig_CannedMessageConfig_inputbroker_event_ccw_ENUMTYPE ModuleConfig_CannedMessageConfig_InputEventChar -#define ModuleConfig_CannedMessageConfig_inputbroker_event_press_ENUMTYPE ModuleConfig_CannedMessageConfig_InputEventChar +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_event_cw_ENUMTYPE meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_event_ccw_ENUMTYPE meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_event_press_ENUMTYPE meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar /* Initializer values for message structs */ -#define ModuleConfig_init_default {0, {ModuleConfig_MQTTConfig_init_default}} -#define ModuleConfig_MQTTConfig_init_default {0, "", "", "", 0, 0} -#define ModuleConfig_RemoteHardwareConfig_init_default {0} -#define ModuleConfig_AudioConfig_init_default {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} -#define ModuleConfig_SerialConfig_init_default {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} -#define ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} -#define ModuleConfig_StoreForwardConfig_init_default {0, 0, 0, 0, 0} -#define ModuleConfig_RangeTestConfig_init_default {0, 0, 0} -#define ModuleConfig_TelemetryConfig_init_default {0, 0, 0, 0, 0} -#define ModuleConfig_CannedMessageConfig_init_default {0, 0, 0, 0, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} -#define ModuleConfig_init_zero {0, {ModuleConfig_MQTTConfig_init_zero}} -#define ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0} -#define ModuleConfig_RemoteHardwareConfig_init_zero {0} -#define ModuleConfig_AudioConfig_init_zero {0, 0, _ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} -#define ModuleConfig_SerialConfig_init_zero {0, 0, 0, 0, _ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _ModuleConfig_SerialConfig_Serial_Mode_MIN} -#define ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} -#define ModuleConfig_StoreForwardConfig_init_zero {0, 0, 0, 0, 0} -#define ModuleConfig_RangeTestConfig_init_zero {0, 0, 0} -#define ModuleConfig_TelemetryConfig_init_zero {0, 0, 0, 0, 0} -#define ModuleConfig_CannedMessageConfig_init_zero {0, 0, 0, 0, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} +#define meshtastic_ModuleConfig_init_default {0, {meshtastic_ModuleConfig_MQTTConfig_init_default}} +#define meshtastic_ModuleConfig_MQTTConfig_init_default {0, "", "", "", 0, 0} +#define meshtastic_ModuleConfig_RemoteHardwareConfig_init_default {0} +#define meshtastic_ModuleConfig_AudioConfig_init_default {0, 0, _meshtastic_ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_SerialConfig_init_default {0, 0, 0, 0, _meshtastic_ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _meshtastic_ModuleConfig_SerialConfig_Serial_Mode_MIN} +#define meshtastic_ModuleConfig_ExternalNotificationConfig_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_StoreForwardConfig_init_default {0, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_RangeTestConfig_init_default {0, 0, 0} +#define meshtastic_ModuleConfig_TelemetryConfig_init_default {0, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_CannedMessageConfig_init_default {0, 0, 0, 0, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} +#define meshtastic_ModuleConfig_init_zero {0, {meshtastic_ModuleConfig_MQTTConfig_init_zero}} +#define meshtastic_ModuleConfig_MQTTConfig_init_zero {0, "", "", "", 0, 0} +#define meshtastic_ModuleConfig_RemoteHardwareConfig_init_zero {0} +#define meshtastic_ModuleConfig_AudioConfig_init_zero {0, 0, _meshtastic_ModuleConfig_AudioConfig_Audio_Baud_MIN, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_SerialConfig_init_zero {0, 0, 0, 0, _meshtastic_ModuleConfig_SerialConfig_Serial_Baud_MIN, 0, _meshtastic_ModuleConfig_SerialConfig_Serial_Mode_MIN} +#define meshtastic_ModuleConfig_ExternalNotificationConfig_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_StoreForwardConfig_init_zero {0, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_RangeTestConfig_init_zero {0, 0, 0} +#define meshtastic_ModuleConfig_TelemetryConfig_init_zero {0, 0, 0, 0, 0} +#define meshtastic_ModuleConfig_CannedMessageConfig_init_zero {0, 0, 0, 0, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, _meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_MIN, 0, 0, "", 0} /* Field tags (for use in manual encoding/decoding) */ -#define ModuleConfig_MQTTConfig_enabled_tag 1 -#define ModuleConfig_MQTTConfig_address_tag 2 -#define ModuleConfig_MQTTConfig_username_tag 3 -#define ModuleConfig_MQTTConfig_password_tag 4 -#define ModuleConfig_MQTTConfig_encryption_enabled_tag 5 -#define ModuleConfig_MQTTConfig_json_enabled_tag 6 -#define ModuleConfig_RemoteHardwareConfig_enabled_tag 1 -#define ModuleConfig_AudioConfig_codec2_enabled_tag 1 -#define ModuleConfig_AudioConfig_ptt_pin_tag 2 -#define ModuleConfig_AudioConfig_bitrate_tag 3 -#define ModuleConfig_AudioConfig_i2s_ws_tag 4 -#define ModuleConfig_AudioConfig_i2s_sd_tag 5 -#define ModuleConfig_AudioConfig_i2s_din_tag 6 -#define ModuleConfig_AudioConfig_i2s_sck_tag 7 -#define ModuleConfig_SerialConfig_enabled_tag 1 -#define ModuleConfig_SerialConfig_echo_tag 2 -#define ModuleConfig_SerialConfig_rxd_tag 3 -#define ModuleConfig_SerialConfig_txd_tag 4 -#define ModuleConfig_SerialConfig_baud_tag 5 -#define ModuleConfig_SerialConfig_timeout_tag 6 -#define ModuleConfig_SerialConfig_mode_tag 7 -#define ModuleConfig_ExternalNotificationConfig_enabled_tag 1 -#define ModuleConfig_ExternalNotificationConfig_output_ms_tag 2 -#define ModuleConfig_ExternalNotificationConfig_output_tag 3 -#define ModuleConfig_ExternalNotificationConfig_active_tag 4 -#define ModuleConfig_ExternalNotificationConfig_alert_message_tag 5 -#define ModuleConfig_ExternalNotificationConfig_alert_bell_tag 6 -#define ModuleConfig_ExternalNotificationConfig_use_pwm_tag 7 -#define ModuleConfig_ExternalNotificationConfig_output_vibra_tag 8 -#define ModuleConfig_ExternalNotificationConfig_output_buzzer_tag 9 -#define ModuleConfig_ExternalNotificationConfig_alert_message_vibra_tag 10 -#define ModuleConfig_ExternalNotificationConfig_alert_message_buzzer_tag 11 -#define ModuleConfig_ExternalNotificationConfig_alert_bell_vibra_tag 12 -#define ModuleConfig_ExternalNotificationConfig_alert_bell_buzzer_tag 13 -#define ModuleConfig_ExternalNotificationConfig_nag_timeout_tag 14 -#define ModuleConfig_StoreForwardConfig_enabled_tag 1 -#define ModuleConfig_StoreForwardConfig_heartbeat_tag 2 -#define ModuleConfig_StoreForwardConfig_records_tag 3 -#define ModuleConfig_StoreForwardConfig_history_return_max_tag 4 -#define ModuleConfig_StoreForwardConfig_history_return_window_tag 5 -#define ModuleConfig_RangeTestConfig_enabled_tag 1 -#define ModuleConfig_RangeTestConfig_sender_tag 2 -#define ModuleConfig_RangeTestConfig_save_tag 3 -#define ModuleConfig_TelemetryConfig_device_update_interval_tag 1 -#define ModuleConfig_TelemetryConfig_environment_update_interval_tag 2 -#define ModuleConfig_TelemetryConfig_environment_measurement_enabled_tag 3 -#define ModuleConfig_TelemetryConfig_environment_screen_enabled_tag 4 -#define ModuleConfig_TelemetryConfig_environment_display_fahrenheit_tag 5 -#define ModuleConfig_CannedMessageConfig_rotary1_enabled_tag 1 -#define ModuleConfig_CannedMessageConfig_inputbroker_pin_a_tag 2 -#define ModuleConfig_CannedMessageConfig_inputbroker_pin_b_tag 3 -#define ModuleConfig_CannedMessageConfig_inputbroker_pin_press_tag 4 -#define ModuleConfig_CannedMessageConfig_inputbroker_event_cw_tag 5 -#define ModuleConfig_CannedMessageConfig_inputbroker_event_ccw_tag 6 -#define ModuleConfig_CannedMessageConfig_inputbroker_event_press_tag 7 -#define ModuleConfig_CannedMessageConfig_updown1_enabled_tag 8 -#define ModuleConfig_CannedMessageConfig_enabled_tag 9 -#define ModuleConfig_CannedMessageConfig_allow_input_source_tag 10 -#define ModuleConfig_CannedMessageConfig_send_bell_tag 11 -#define ModuleConfig_mqtt_tag 1 -#define ModuleConfig_serial_tag 2 -#define ModuleConfig_external_notification_tag 3 -#define ModuleConfig_store_forward_tag 4 -#define ModuleConfig_range_test_tag 5 -#define ModuleConfig_telemetry_tag 6 -#define ModuleConfig_canned_message_tag 7 -#define ModuleConfig_audio_tag 8 -#define ModuleConfig_remote_hardware_tag 9 +#define meshtastic_ModuleConfig_MQTTConfig_enabled_tag 1 +#define meshtastic_ModuleConfig_MQTTConfig_address_tag 2 +#define meshtastic_ModuleConfig_MQTTConfig_username_tag 3 +#define meshtastic_ModuleConfig_MQTTConfig_password_tag 4 +#define meshtastic_ModuleConfig_MQTTConfig_encryption_enabled_tag 5 +#define meshtastic_ModuleConfig_MQTTConfig_json_enabled_tag 6 +#define meshtastic_ModuleConfig_RemoteHardwareConfig_enabled_tag 1 +#define meshtastic_ModuleConfig_AudioConfig_codec2_enabled_tag 1 +#define meshtastic_ModuleConfig_AudioConfig_ptt_pin_tag 2 +#define meshtastic_ModuleConfig_AudioConfig_bitrate_tag 3 +#define meshtastic_ModuleConfig_AudioConfig_i2s_ws_tag 4 +#define meshtastic_ModuleConfig_AudioConfig_i2s_sd_tag 5 +#define meshtastic_ModuleConfig_AudioConfig_i2s_din_tag 6 +#define meshtastic_ModuleConfig_AudioConfig_i2s_sck_tag 7 +#define meshtastic_ModuleConfig_SerialConfig_enabled_tag 1 +#define meshtastic_ModuleConfig_SerialConfig_echo_tag 2 +#define meshtastic_ModuleConfig_SerialConfig_rxd_tag 3 +#define meshtastic_ModuleConfig_SerialConfig_txd_tag 4 +#define meshtastic_ModuleConfig_SerialConfig_baud_tag 5 +#define meshtastic_ModuleConfig_SerialConfig_timeout_tag 6 +#define meshtastic_ModuleConfig_SerialConfig_mode_tag 7 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_enabled_tag 1 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_output_ms_tag 2 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_output_tag 3 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_active_tag 4 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_alert_message_tag 5 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_alert_bell_tag 6 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_use_pwm_tag 7 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_output_vibra_tag 8 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_output_buzzer_tag 9 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_alert_message_vibra_tag 10 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_alert_message_buzzer_tag 11 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_alert_bell_vibra_tag 12 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_alert_bell_buzzer_tag 13 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_nag_timeout_tag 14 +#define meshtastic_ModuleConfig_StoreForwardConfig_enabled_tag 1 +#define meshtastic_ModuleConfig_StoreForwardConfig_heartbeat_tag 2 +#define meshtastic_ModuleConfig_StoreForwardConfig_records_tag 3 +#define meshtastic_ModuleConfig_StoreForwardConfig_history_return_max_tag 4 +#define meshtastic_ModuleConfig_StoreForwardConfig_history_return_window_tag 5 +#define meshtastic_ModuleConfig_RangeTestConfig_enabled_tag 1 +#define meshtastic_ModuleConfig_RangeTestConfig_sender_tag 2 +#define meshtastic_ModuleConfig_RangeTestConfig_save_tag 3 +#define meshtastic_ModuleConfig_TelemetryConfig_device_update_interval_tag 1 +#define meshtastic_ModuleConfig_TelemetryConfig_environment_update_interval_tag 2 +#define meshtastic_ModuleConfig_TelemetryConfig_environment_measurement_enabled_tag 3 +#define meshtastic_ModuleConfig_TelemetryConfig_environment_screen_enabled_tag 4 +#define meshtastic_ModuleConfig_TelemetryConfig_environment_display_fahrenheit_tag 5 +#define meshtastic_ModuleConfig_CannedMessageConfig_rotary1_enabled_tag 1 +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_pin_a_tag 2 +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_pin_b_tag 3 +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_pin_press_tag 4 +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_event_cw_tag 5 +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_event_ccw_tag 6 +#define meshtastic_ModuleConfig_CannedMessageConfig_inputbroker_event_press_tag 7 +#define meshtastic_ModuleConfig_CannedMessageConfig_updown1_enabled_tag 8 +#define meshtastic_ModuleConfig_CannedMessageConfig_enabled_tag 9 +#define meshtastic_ModuleConfig_CannedMessageConfig_allow_input_source_tag 10 +#define meshtastic_ModuleConfig_CannedMessageConfig_send_bell_tag 11 +#define meshtastic_ModuleConfig_mqtt_tag 1 +#define meshtastic_ModuleConfig_serial_tag 2 +#define meshtastic_ModuleConfig_external_notification_tag 3 +#define meshtastic_ModuleConfig_store_forward_tag 4 +#define meshtastic_ModuleConfig_range_test_tag 5 +#define meshtastic_ModuleConfig_telemetry_tag 6 +#define meshtastic_ModuleConfig_canned_message_tag 7 +#define meshtastic_ModuleConfig_audio_tag 8 +#define meshtastic_ModuleConfig_remote_hardware_tag 9 /* Struct field encoding specification for nanopb */ -#define ModuleConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_FIELDLIST(X, a) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,mqtt,payload_variant.mqtt), 1) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,serial,payload_variant.serial), 2) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,external_notification,payload_variant.external_notification), 3) \ @@ -419,34 +419,34 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,telemetry,payload_variant.te X(a, STATIC, ONEOF, MESSAGE, (payload_variant,canned_message,payload_variant.canned_message), 7) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,audio,payload_variant.audio), 8) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,remote_hardware,payload_variant.remote_hardware), 9) -#define ModuleConfig_CALLBACK NULL -#define ModuleConfig_DEFAULT NULL -#define ModuleConfig_payload_variant_mqtt_MSGTYPE ModuleConfig_MQTTConfig -#define ModuleConfig_payload_variant_serial_MSGTYPE ModuleConfig_SerialConfig -#define ModuleConfig_payload_variant_external_notification_MSGTYPE ModuleConfig_ExternalNotificationConfig -#define ModuleConfig_payload_variant_store_forward_MSGTYPE ModuleConfig_StoreForwardConfig -#define ModuleConfig_payload_variant_range_test_MSGTYPE ModuleConfig_RangeTestConfig -#define ModuleConfig_payload_variant_telemetry_MSGTYPE ModuleConfig_TelemetryConfig -#define ModuleConfig_payload_variant_canned_message_MSGTYPE ModuleConfig_CannedMessageConfig -#define ModuleConfig_payload_variant_audio_MSGTYPE ModuleConfig_AudioConfig -#define ModuleConfig_payload_variant_remote_hardware_MSGTYPE ModuleConfig_RemoteHardwareConfig +#define meshtastic_ModuleConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_payload_variant_mqtt_MSGTYPE meshtastic_ModuleConfig_MQTTConfig +#define meshtastic_ModuleConfig_payload_variant_serial_MSGTYPE meshtastic_ModuleConfig_SerialConfig +#define meshtastic_ModuleConfig_payload_variant_external_notification_MSGTYPE meshtastic_ModuleConfig_ExternalNotificationConfig +#define meshtastic_ModuleConfig_payload_variant_store_forward_MSGTYPE meshtastic_ModuleConfig_StoreForwardConfig +#define meshtastic_ModuleConfig_payload_variant_range_test_MSGTYPE meshtastic_ModuleConfig_RangeTestConfig +#define meshtastic_ModuleConfig_payload_variant_telemetry_MSGTYPE meshtastic_ModuleConfig_TelemetryConfig +#define meshtastic_ModuleConfig_payload_variant_canned_message_MSGTYPE meshtastic_ModuleConfig_CannedMessageConfig +#define meshtastic_ModuleConfig_payload_variant_audio_MSGTYPE meshtastic_ModuleConfig_AudioConfig +#define meshtastic_ModuleConfig_payload_variant_remote_hardware_MSGTYPE meshtastic_ModuleConfig_RemoteHardwareConfig -#define ModuleConfig_MQTTConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_MQTTConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) \ X(a, STATIC, SINGULAR, STRING, address, 2) \ X(a, STATIC, SINGULAR, STRING, username, 3) \ X(a, STATIC, SINGULAR, STRING, password, 4) \ X(a, STATIC, SINGULAR, BOOL, encryption_enabled, 5) \ X(a, STATIC, SINGULAR, BOOL, json_enabled, 6) -#define ModuleConfig_MQTTConfig_CALLBACK NULL -#define ModuleConfig_MQTTConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_MQTTConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_MQTTConfig_DEFAULT NULL -#define ModuleConfig_RemoteHardwareConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_RemoteHardwareConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) -#define ModuleConfig_RemoteHardwareConfig_CALLBACK NULL -#define ModuleConfig_RemoteHardwareConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_RemoteHardwareConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_RemoteHardwareConfig_DEFAULT NULL -#define ModuleConfig_AudioConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_AudioConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, codec2_enabled, 1) \ X(a, STATIC, SINGULAR, UINT32, ptt_pin, 2) \ X(a, STATIC, SINGULAR, UENUM, bitrate, 3) \ @@ -454,10 +454,10 @@ X(a, STATIC, SINGULAR, UINT32, i2s_ws, 4) \ X(a, STATIC, SINGULAR, UINT32, i2s_sd, 5) \ X(a, STATIC, SINGULAR, UINT32, i2s_din, 6) \ X(a, STATIC, SINGULAR, UINT32, i2s_sck, 7) -#define ModuleConfig_AudioConfig_CALLBACK NULL -#define ModuleConfig_AudioConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_AudioConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_AudioConfig_DEFAULT NULL -#define ModuleConfig_SerialConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_SerialConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) \ X(a, STATIC, SINGULAR, BOOL, echo, 2) \ X(a, STATIC, SINGULAR, UINT32, rxd, 3) \ @@ -465,10 +465,10 @@ X(a, STATIC, SINGULAR, UINT32, txd, 4) \ X(a, STATIC, SINGULAR, UENUM, baud, 5) \ X(a, STATIC, SINGULAR, UINT32, timeout, 6) \ X(a, STATIC, SINGULAR, UENUM, mode, 7) -#define ModuleConfig_SerialConfig_CALLBACK NULL -#define ModuleConfig_SerialConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_SerialConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_SerialConfig_DEFAULT NULL -#define ModuleConfig_ExternalNotificationConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_ExternalNotificationConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) \ X(a, STATIC, SINGULAR, UINT32, output_ms, 2) \ X(a, STATIC, SINGULAR, UINT32, output, 3) \ @@ -483,35 +483,35 @@ X(a, STATIC, SINGULAR, BOOL, alert_message_buzzer, 11) \ X(a, STATIC, SINGULAR, BOOL, alert_bell_vibra, 12) \ X(a, STATIC, SINGULAR, BOOL, alert_bell_buzzer, 13) \ X(a, STATIC, SINGULAR, UINT32, nag_timeout, 14) -#define ModuleConfig_ExternalNotificationConfig_CALLBACK NULL -#define ModuleConfig_ExternalNotificationConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_ExternalNotificationConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_ExternalNotificationConfig_DEFAULT NULL -#define ModuleConfig_StoreForwardConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_StoreForwardConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) \ X(a, STATIC, SINGULAR, BOOL, heartbeat, 2) \ X(a, STATIC, SINGULAR, UINT32, records, 3) \ X(a, STATIC, SINGULAR, UINT32, history_return_max, 4) \ X(a, STATIC, SINGULAR, UINT32, history_return_window, 5) -#define ModuleConfig_StoreForwardConfig_CALLBACK NULL -#define ModuleConfig_StoreForwardConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_StoreForwardConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_StoreForwardConfig_DEFAULT NULL -#define ModuleConfig_RangeTestConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_RangeTestConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, enabled, 1) \ X(a, STATIC, SINGULAR, UINT32, sender, 2) \ X(a, STATIC, SINGULAR, BOOL, save, 3) -#define ModuleConfig_RangeTestConfig_CALLBACK NULL -#define ModuleConfig_RangeTestConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_RangeTestConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_RangeTestConfig_DEFAULT NULL -#define ModuleConfig_TelemetryConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_TelemetryConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, device_update_interval, 1) \ X(a, STATIC, SINGULAR, UINT32, environment_update_interval, 2) \ X(a, STATIC, SINGULAR, BOOL, environment_measurement_enabled, 3) \ X(a, STATIC, SINGULAR, BOOL, environment_screen_enabled, 4) \ X(a, STATIC, SINGULAR, BOOL, environment_display_fahrenheit, 5) -#define ModuleConfig_TelemetryConfig_CALLBACK NULL -#define ModuleConfig_TelemetryConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_TelemetryConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_TelemetryConfig_DEFAULT NULL -#define ModuleConfig_CannedMessageConfig_FIELDLIST(X, a) \ +#define meshtastic_ModuleConfig_CannedMessageConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, BOOL, rotary1_enabled, 1) \ X(a, STATIC, SINGULAR, UINT32, inputbroker_pin_a, 2) \ X(a, STATIC, SINGULAR, UINT32, inputbroker_pin_b, 3) \ @@ -523,43 +523,43 @@ X(a, STATIC, SINGULAR, BOOL, updown1_enabled, 8) \ X(a, STATIC, SINGULAR, BOOL, enabled, 9) \ X(a, STATIC, SINGULAR, STRING, allow_input_source, 10) \ X(a, STATIC, SINGULAR, BOOL, send_bell, 11) -#define ModuleConfig_CannedMessageConfig_CALLBACK NULL -#define ModuleConfig_CannedMessageConfig_DEFAULT NULL +#define meshtastic_ModuleConfig_CannedMessageConfig_CALLBACK NULL +#define meshtastic_ModuleConfig_CannedMessageConfig_DEFAULT NULL -extern const pb_msgdesc_t ModuleConfig_msg; -extern const pb_msgdesc_t ModuleConfig_MQTTConfig_msg; -extern const pb_msgdesc_t ModuleConfig_RemoteHardwareConfig_msg; -extern const pb_msgdesc_t ModuleConfig_AudioConfig_msg; -extern const pb_msgdesc_t ModuleConfig_SerialConfig_msg; -extern const pb_msgdesc_t ModuleConfig_ExternalNotificationConfig_msg; -extern const pb_msgdesc_t ModuleConfig_StoreForwardConfig_msg; -extern const pb_msgdesc_t ModuleConfig_RangeTestConfig_msg; -extern const pb_msgdesc_t ModuleConfig_TelemetryConfig_msg; -extern const pb_msgdesc_t ModuleConfig_CannedMessageConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_MQTTConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_RemoteHardwareConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_AudioConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_SerialConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_ExternalNotificationConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_StoreForwardConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_RangeTestConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_TelemetryConfig_msg; +extern const pb_msgdesc_t meshtastic_ModuleConfig_CannedMessageConfig_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define ModuleConfig_fields &ModuleConfig_msg -#define ModuleConfig_MQTTConfig_fields &ModuleConfig_MQTTConfig_msg -#define ModuleConfig_RemoteHardwareConfig_fields &ModuleConfig_RemoteHardwareConfig_msg -#define ModuleConfig_AudioConfig_fields &ModuleConfig_AudioConfig_msg -#define ModuleConfig_SerialConfig_fields &ModuleConfig_SerialConfig_msg -#define ModuleConfig_ExternalNotificationConfig_fields &ModuleConfig_ExternalNotificationConfig_msg -#define ModuleConfig_StoreForwardConfig_fields &ModuleConfig_StoreForwardConfig_msg -#define ModuleConfig_RangeTestConfig_fields &ModuleConfig_RangeTestConfig_msg -#define ModuleConfig_TelemetryConfig_fields &ModuleConfig_TelemetryConfig_msg -#define ModuleConfig_CannedMessageConfig_fields &ModuleConfig_CannedMessageConfig_msg +#define meshtastic_ModuleConfig_fields &meshtastic_ModuleConfig_msg +#define meshtastic_ModuleConfig_MQTTConfig_fields &meshtastic_ModuleConfig_MQTTConfig_msg +#define meshtastic_ModuleConfig_RemoteHardwareConfig_fields &meshtastic_ModuleConfig_RemoteHardwareConfig_msg +#define meshtastic_ModuleConfig_AudioConfig_fields &meshtastic_ModuleConfig_AudioConfig_msg +#define meshtastic_ModuleConfig_SerialConfig_fields &meshtastic_ModuleConfig_SerialConfig_msg +#define meshtastic_ModuleConfig_ExternalNotificationConfig_fields &meshtastic_ModuleConfig_ExternalNotificationConfig_msg +#define meshtastic_ModuleConfig_StoreForwardConfig_fields &meshtastic_ModuleConfig_StoreForwardConfig_msg +#define meshtastic_ModuleConfig_RangeTestConfig_fields &meshtastic_ModuleConfig_RangeTestConfig_msg +#define meshtastic_ModuleConfig_TelemetryConfig_fields &meshtastic_ModuleConfig_TelemetryConfig_msg +#define meshtastic_ModuleConfig_CannedMessageConfig_fields &meshtastic_ModuleConfig_CannedMessageConfig_msg /* Maximum encoded size of messages (where known) */ -#define ModuleConfig_AudioConfig_size 19 -#define ModuleConfig_CannedMessageConfig_size 49 -#define ModuleConfig_ExternalNotificationConfig_size 40 -#define ModuleConfig_MQTTConfig_size 201 -#define ModuleConfig_RangeTestConfig_size 10 -#define ModuleConfig_RemoteHardwareConfig_size 2 -#define ModuleConfig_SerialConfig_size 26 -#define ModuleConfig_StoreForwardConfig_size 22 -#define ModuleConfig_TelemetryConfig_size 18 -#define ModuleConfig_size 204 +#define meshtastic_ModuleConfig_AudioConfig_size 19 +#define meshtastic_ModuleConfig_CannedMessageConfig_size 49 +#define meshtastic_ModuleConfig_ExternalNotificationConfig_size 40 +#define meshtastic_ModuleConfig_MQTTConfig_size 201 +#define meshtastic_ModuleConfig_RangeTestConfig_size 10 +#define meshtastic_ModuleConfig_RemoteHardwareConfig_size 2 +#define meshtastic_ModuleConfig_SerialConfig_size 26 +#define meshtastic_ModuleConfig_StoreForwardConfig_size 22 +#define meshtastic_ModuleConfig_TelemetryConfig_size 18 +#define meshtastic_ModuleConfig_size 204 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/mqtt.pb.c b/src/mesh/generated/meshtastic/mqtt.pb.c index 86a1e0075..3046e6109 100644 --- a/src/mesh/generated/meshtastic/mqtt.pb.c +++ b/src/mesh/generated/meshtastic/mqtt.pb.c @@ -1,12 +1,12 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./mqtt.pb.h" +#include "meshtastic/mqtt.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(ServiceEnvelope, ServiceEnvelope, AUTO) +PB_BIND(meshtastic_ServiceEnvelope, meshtastic_ServiceEnvelope, AUTO) diff --git a/src/mesh/generated/meshtastic/mqtt.pb.h b/src/mesh/generated/meshtastic/mqtt.pb.h index 644a771bb..12e83c724 100644 --- a/src/mesh/generated/meshtastic/mqtt.pb.h +++ b/src/mesh/generated/meshtastic/mqtt.pb.h @@ -4,7 +4,7 @@ #ifndef PB_MESHTASTIC_MESHTASTIC_MQTT_PB_H_INCLUDED #define PB_MESHTASTIC_MESHTASTIC_MQTT_PB_H_INCLUDED #include -#include "./mesh.pb.h" +#include "meshtastic/mesh.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -12,16 +12,16 @@ /* Struct definitions */ /* This message wraps a MeshPacket with extra metadata about the sender and how it arrived. */ -typedef struct _ServiceEnvelope { +typedef struct _meshtastic_ServiceEnvelope { /* The (probably encrypted) packet */ - struct _MeshPacket *packet; + struct _meshtastic_MeshPacket *packet; /* The global channel ID it was sent on */ char *channel_id; /* The sending gateway node ID. Can we use this to authenticate/prevent fake nodeid impersonation for senders? - i.e. use gateway/mesh id (which is authenticated) + local node id as the globally trusted nodenum */ char *gateway_id; -} ServiceEnvelope; +} meshtastic_ServiceEnvelope; #ifdef __cplusplus @@ -29,30 +29,30 @@ extern "C" { #endif /* Initializer values for message structs */ -#define ServiceEnvelope_init_default {NULL, NULL, NULL} -#define ServiceEnvelope_init_zero {NULL, NULL, NULL} +#define meshtastic_ServiceEnvelope_init_default {NULL, NULL, NULL} +#define meshtastic_ServiceEnvelope_init_zero {NULL, NULL, NULL} /* Field tags (for use in manual encoding/decoding) */ -#define ServiceEnvelope_packet_tag 1 -#define ServiceEnvelope_channel_id_tag 2 -#define ServiceEnvelope_gateway_id_tag 3 +#define meshtastic_ServiceEnvelope_packet_tag 1 +#define meshtastic_ServiceEnvelope_channel_id_tag 2 +#define meshtastic_ServiceEnvelope_gateway_id_tag 3 /* Struct field encoding specification for nanopb */ -#define ServiceEnvelope_FIELDLIST(X, a) \ +#define meshtastic_ServiceEnvelope_FIELDLIST(X, a) \ X(a, POINTER, OPTIONAL, MESSAGE, packet, 1) \ X(a, POINTER, SINGULAR, STRING, channel_id, 2) \ X(a, POINTER, SINGULAR, STRING, gateway_id, 3) -#define ServiceEnvelope_CALLBACK NULL -#define ServiceEnvelope_DEFAULT NULL -#define ServiceEnvelope_packet_MSGTYPE MeshPacket +#define meshtastic_ServiceEnvelope_CALLBACK NULL +#define meshtastic_ServiceEnvelope_DEFAULT NULL +#define meshtastic_ServiceEnvelope_packet_MSGTYPE meshtastic_MeshPacket -extern const pb_msgdesc_t ServiceEnvelope_msg; +extern const pb_msgdesc_t meshtastic_ServiceEnvelope_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define ServiceEnvelope_fields &ServiceEnvelope_msg +#define meshtastic_ServiceEnvelope_fields &meshtastic_ServiceEnvelope_msg /* Maximum encoded size of messages (where known) */ -/* ServiceEnvelope_size depends on runtime parameters */ +/* meshtastic_ServiceEnvelope_size depends on runtime parameters */ #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/portnums.pb.c b/src/mesh/generated/meshtastic/portnums.pb.c index 663247bf8..dd0d00e20 100644 --- a/src/mesh/generated/meshtastic/portnums.pb.c +++ b/src/mesh/generated/meshtastic/portnums.pb.c @@ -1,7 +1,7 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./portnums.pb.h" +#include "meshtastic/portnums.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif diff --git a/src/mesh/generated/meshtastic/portnums.pb.h b/src/mesh/generated/meshtastic/portnums.pb.h index 27d2ab498..59cf0ebe5 100644 --- a/src/mesh/generated/meshtastic/portnums.pb.h +++ b/src/mesh/generated/meshtastic/portnums.pb.h @@ -22,87 +22,87 @@ Note: This was formerly a Type enum named 'typ' with the same id # We have change to this 'portnum' based scheme for specifying app handlers for particular payloads. This change is backwards compatible by treating the legacy OPAQUE/CLEAR_TEXT values identically. */ -typedef enum _PortNum { +typedef enum _meshtastic_PortNum { /* Deprecated: do not use in new code (formerly called OPAQUE) A message sent from a device outside of the mesh, in a form the mesh does not understand NOTE: This must be 0, because it is documented in IMeshService.aidl to be so */ - PortNum_UNKNOWN_APP = 0, + meshtastic_PortNum_UNKNOWN_APP = 0, /* A simple UTF-8 text message, which even the little micros in the mesh can understand and show on their screen eventually in some circumstances even signal might send messages in this form (see below) */ - PortNum_TEXT_MESSAGE_APP = 1, + meshtastic_PortNum_TEXT_MESSAGE_APP = 1, /* Reserved for built-in GPIO/example app. See remote_hardware.proto/HardwareMessage for details on the message sent/received to this port number */ - PortNum_REMOTE_HARDWARE_APP = 2, + meshtastic_PortNum_REMOTE_HARDWARE_APP = 2, /* The built-in position messaging app. Payload is a [Position](/docs/developers/protobufs/api#position) message */ - PortNum_POSITION_APP = 3, + meshtastic_PortNum_POSITION_APP = 3, /* The built-in user info app. Payload is a [User](/docs/developers/protobufs/api#user) message */ - PortNum_NODEINFO_APP = 4, + meshtastic_PortNum_NODEINFO_APP = 4, /* Protocol control packets for mesh protocol use. Payload is a [Routing](/docs/developers/protobufs/api#routing) message */ - PortNum_ROUTING_APP = 5, + meshtastic_PortNum_ROUTING_APP = 5, /* Admin control packets. Payload is a [AdminMessage](/docs/developers/protobufs/api#adminmessage) message */ - PortNum_ADMIN_APP = 6, + meshtastic_PortNum_ADMIN_APP = 6, /* Compressed TEXT_MESSAGE payloads. */ - PortNum_TEXT_MESSAGE_COMPRESSED_APP = 7, + meshtastic_PortNum_TEXT_MESSAGE_COMPRESSED_APP = 7, /* Waypoint payloads. Payload is a [Waypoint](/docs/developers/protobufs/api#waypoint) message */ - PortNum_WAYPOINT_APP = 8, + meshtastic_PortNum_WAYPOINT_APP = 8, /* Audio Payloads. Encapsulated codec2 packets. On 2.4 GHZ Bandwidths only for now */ - PortNum_AUDIO_APP = 9, + meshtastic_PortNum_AUDIO_APP = 9, /* Provides a 'ping' service that replies to any packet it receives. Also serves as a small example module. */ - PortNum_REPLY_APP = 32, + meshtastic_PortNum_REPLY_APP = 32, /* Used for the python IP tunnel feature */ - PortNum_IP_TUNNEL_APP = 33, + meshtastic_PortNum_IP_TUNNEL_APP = 33, /* Provides a hardware serial interface to send and receive from the Meshtastic network. Connect to the RX/TX pins of a device with 38400 8N1. Packets received from the Meshtastic network is forwarded to the RX pin while sending a packet to TX will go out to the Mesh network. Maximum packet size of 240 bytes. Module is disabled by default can be turned on by setting SERIAL_MODULE_ENABLED = 1 in SerialPlugh.cpp. */ - PortNum_SERIAL_APP = 64, + meshtastic_PortNum_SERIAL_APP = 64, /* STORE_FORWARD_APP (Work in Progress) Maintained by Jm Casler (MC Hamster) : jm@casler.org */ - PortNum_STORE_FORWARD_APP = 65, + meshtastic_PortNum_STORE_FORWARD_APP = 65, /* Optional port for messages for the range test module. */ - PortNum_RANGE_TEST_APP = 66, + meshtastic_PortNum_RANGE_TEST_APP = 66, /* Provides a format to send and receive telemetry data from the Meshtastic network. Maintained by Charles Crossan (crossan007) : crossan007@gmail.com */ - PortNum_TELEMETRY_APP = 67, + meshtastic_PortNum_TELEMETRY_APP = 67, /* Experimental tools for estimating node position without a GPS Maintained by Github user a-f-G-U-C (a Meshtastic contributor) Project files at https://github.com/a-f-G-U-C/Meshtastic-ZPS */ - PortNum_ZPS_APP = 68, + meshtastic_PortNum_ZPS_APP = 68, /* Used to let multiple instances of Linux native applications communicate as if they did using their LoRa chip. Maintained by GitHub user GUVWAF. Project files at https://github.com/GUVWAF/Meshtasticator */ - PortNum_SIMULATOR_APP = 69, + meshtastic_PortNum_SIMULATOR_APP = 69, /* Provides a traceroute functionality to show the route a packet towards a certain destination would take on the mesh. */ - PortNum_TRACEROUTE_APP = 70, + meshtastic_PortNum_TRACEROUTE_APP = 70, /* Private applications should use portnums >= 256. To simplify initial development and testing you can use "PRIVATE_APP" in your code without needing to rebuild protobuf files (via [regen-protos.sh](https://github.com/meshtastic/firmware/blob/master/bin/regen-protos.sh)) */ - PortNum_PRIVATE_APP = 256, + meshtastic_PortNum_PRIVATE_APP = 256, /* ATAK Forwarder Module https://github.com/paulmandal/atak-forwarder */ - PortNum_ATAK_FORWARDER = 257, + meshtastic_PortNum_ATAK_FORWARDER = 257, /* Currently we limit port nums to no higher than this value */ - PortNum_MAX = 511 -} PortNum; + meshtastic_PortNum_MAX = 511 +} meshtastic_PortNum; #ifdef __cplusplus extern "C" { #endif /* Helper constants for enums */ -#define _PortNum_MIN PortNum_UNKNOWN_APP -#define _PortNum_MAX PortNum_MAX -#define _PortNum_ARRAYSIZE ((PortNum)(PortNum_MAX+1)) +#define _meshtastic_PortNum_MIN meshtastic_PortNum_UNKNOWN_APP +#define _meshtastic_PortNum_MAX meshtastic_PortNum_MAX +#define _meshtastic_PortNum_ARRAYSIZE ((meshtastic_PortNum)(meshtastic_PortNum_MAX+1)) #ifdef __cplusplus diff --git a/src/mesh/generated/meshtastic/remote_hardware.pb.c b/src/mesh/generated/meshtastic/remote_hardware.pb.c index e33884659..f368ec1ef 100644 --- a/src/mesh/generated/meshtastic/remote_hardware.pb.c +++ b/src/mesh/generated/meshtastic/remote_hardware.pb.c @@ -1,12 +1,12 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./remote_hardware.pb.h" +#include "meshtastic/remote_hardware.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(HardwareMessage, HardwareMessage, AUTO) +PB_BIND(meshtastic_HardwareMessage, meshtastic_HardwareMessage, AUTO) diff --git a/src/mesh/generated/meshtastic/remote_hardware.pb.h b/src/mesh/generated/meshtastic/remote_hardware.pb.h index b76dbe0bc..26df97616 100644 --- a/src/mesh/generated/meshtastic/remote_hardware.pb.h +++ b/src/mesh/generated/meshtastic/remote_hardware.pb.h @@ -11,22 +11,22 @@ /* Enum definitions */ /* TODO: REPLACE */ -typedef enum _HardwareMessage_Type { +typedef enum _meshtastic_HardwareMessage_Type { /* Unset/unused */ - HardwareMessage_Type_UNSET = 0, + meshtastic_HardwareMessage_Type_UNSET = 0, /* Set gpio gpios based on gpio_mask/gpio_value */ - HardwareMessage_Type_WRITE_GPIOS = 1, + meshtastic_HardwareMessage_Type_WRITE_GPIOS = 1, /* We are now interested in watching the gpio_mask gpios. If the selected gpios change, please broadcast GPIOS_CHANGED. Will implicitly change the gpios requested to be INPUT gpios. */ - HardwareMessage_Type_WATCH_GPIOS = 2, + meshtastic_HardwareMessage_Type_WATCH_GPIOS = 2, /* The gpios listed in gpio_mask have changed, the new values are listed in gpio_value */ - HardwareMessage_Type_GPIOS_CHANGED = 3, + meshtastic_HardwareMessage_Type_GPIOS_CHANGED = 3, /* Read the gpios specified in gpio_mask, send back a READ_GPIOS_REPLY reply with gpio_value populated */ - HardwareMessage_Type_READ_GPIOS = 4, + meshtastic_HardwareMessage_Type_READ_GPIOS = 4, /* A reply to READ_GPIOS. gpio_mask and gpio_value will be populated */ - HardwareMessage_Type_READ_GPIOS_REPLY = 5 -} HardwareMessage_Type; + meshtastic_HardwareMessage_Type_READ_GPIOS_REPLY = 5 +} meshtastic_HardwareMessage_Type; /* Struct definitions */ /* An example app to show off the module system. This message is used for @@ -38,15 +38,15 @@ typedef enum _HardwareMessage_Type { because no security yet (beyond the channel mechanism). It should be off by default and then protected based on some TBD mechanism (a special channel once multichannel support is included?) */ -typedef struct _HardwareMessage { +typedef struct _meshtastic_HardwareMessage { /* What type of HardwareMessage is this? */ - HardwareMessage_Type type; + meshtastic_HardwareMessage_Type type; /* What gpios are we changing. Not used for all MessageTypes, see MessageType for details */ uint64_t gpio_mask; /* For gpios that were listed in gpio_mask as valid, what are the signal levels for those gpios. Not used for all MessageTypes, see MessageType for details */ uint64_t gpio_value; -} HardwareMessage; +} meshtastic_HardwareMessage; #ifdef __cplusplus @@ -54,37 +54,37 @@ extern "C" { #endif /* Helper constants for enums */ -#define _HardwareMessage_Type_MIN HardwareMessage_Type_UNSET -#define _HardwareMessage_Type_MAX HardwareMessage_Type_READ_GPIOS_REPLY -#define _HardwareMessage_Type_ARRAYSIZE ((HardwareMessage_Type)(HardwareMessage_Type_READ_GPIOS_REPLY+1)) +#define _meshtastic_HardwareMessage_Type_MIN meshtastic_HardwareMessage_Type_UNSET +#define _meshtastic_HardwareMessage_Type_MAX meshtastic_HardwareMessage_Type_READ_GPIOS_REPLY +#define _meshtastic_HardwareMessage_Type_ARRAYSIZE ((meshtastic_HardwareMessage_Type)(meshtastic_HardwareMessage_Type_READ_GPIOS_REPLY+1)) -#define HardwareMessage_type_ENUMTYPE HardwareMessage_Type +#define meshtastic_HardwareMessage_type_ENUMTYPE meshtastic_HardwareMessage_Type /* Initializer values for message structs */ -#define HardwareMessage_init_default {_HardwareMessage_Type_MIN, 0, 0} -#define HardwareMessage_init_zero {_HardwareMessage_Type_MIN, 0, 0} +#define meshtastic_HardwareMessage_init_default {_meshtastic_HardwareMessage_Type_MIN, 0, 0} +#define meshtastic_HardwareMessage_init_zero {_meshtastic_HardwareMessage_Type_MIN, 0, 0} /* Field tags (for use in manual encoding/decoding) */ -#define HardwareMessage_type_tag 1 -#define HardwareMessage_gpio_mask_tag 2 -#define HardwareMessage_gpio_value_tag 3 +#define meshtastic_HardwareMessage_type_tag 1 +#define meshtastic_HardwareMessage_gpio_mask_tag 2 +#define meshtastic_HardwareMessage_gpio_value_tag 3 /* Struct field encoding specification for nanopb */ -#define HardwareMessage_FIELDLIST(X, a) \ +#define meshtastic_HardwareMessage_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, type, 1) \ X(a, STATIC, SINGULAR, UINT64, gpio_mask, 2) \ X(a, STATIC, SINGULAR, UINT64, gpio_value, 3) -#define HardwareMessage_CALLBACK NULL -#define HardwareMessage_DEFAULT NULL +#define meshtastic_HardwareMessage_CALLBACK NULL +#define meshtastic_HardwareMessage_DEFAULT NULL -extern const pb_msgdesc_t HardwareMessage_msg; +extern const pb_msgdesc_t meshtastic_HardwareMessage_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define HardwareMessage_fields &HardwareMessage_msg +#define meshtastic_HardwareMessage_fields &meshtastic_HardwareMessage_msg /* Maximum encoded size of messages (where known) */ -#define HardwareMessage_size 24 +#define meshtastic_HardwareMessage_size 24 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/rtttl.pb.c b/src/mesh/generated/meshtastic/rtttl.pb.c index 5980cacf2..685bbde45 100644 --- a/src/mesh/generated/meshtastic/rtttl.pb.c +++ b/src/mesh/generated/meshtastic/rtttl.pb.c @@ -1,12 +1,12 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./rtttl.pb.h" +#include "meshtastic/rtttl.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(RTTTLConfig, RTTTLConfig, AUTO) +PB_BIND(meshtastic_RTTTLConfig, meshtastic_RTTTLConfig, AUTO) diff --git a/src/mesh/generated/meshtastic/rtttl.pb.h b/src/mesh/generated/meshtastic/rtttl.pb.h index 8cca21f59..aa55d0b7d 100644 --- a/src/mesh/generated/meshtastic/rtttl.pb.h +++ b/src/mesh/generated/meshtastic/rtttl.pb.h @@ -11,10 +11,10 @@ /* Struct definitions */ /* Canned message module configuration. */ -typedef struct _RTTTLConfig { +typedef struct _meshtastic_RTTTLConfig { /* Ringtone for PWM Buzzer in RTTTL Format. */ char ringtone[230]; -} RTTTLConfig; +} meshtastic_RTTTLConfig; #ifdef __cplusplus @@ -22,25 +22,25 @@ extern "C" { #endif /* Initializer values for message structs */ -#define RTTTLConfig_init_default {""} -#define RTTTLConfig_init_zero {""} +#define meshtastic_RTTTLConfig_init_default {""} +#define meshtastic_RTTTLConfig_init_zero {""} /* Field tags (for use in manual encoding/decoding) */ -#define RTTTLConfig_ringtone_tag 1 +#define meshtastic_RTTTLConfig_ringtone_tag 1 /* Struct field encoding specification for nanopb */ -#define RTTTLConfig_FIELDLIST(X, a) \ +#define meshtastic_RTTTLConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, STRING, ringtone, 1) -#define RTTTLConfig_CALLBACK NULL -#define RTTTLConfig_DEFAULT NULL +#define meshtastic_RTTTLConfig_CALLBACK NULL +#define meshtastic_RTTTLConfig_DEFAULT NULL -extern const pb_msgdesc_t RTTTLConfig_msg; +extern const pb_msgdesc_t meshtastic_RTTTLConfig_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define RTTTLConfig_fields &RTTTLConfig_msg +#define meshtastic_RTTTLConfig_fields &meshtastic_RTTTLConfig_msg /* Maximum encoded size of messages (where known) */ -#define RTTTLConfig_size 232 +#define meshtastic_RTTTLConfig_size 232 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/storeforward.pb.c b/src/mesh/generated/meshtastic/storeforward.pb.c index 154e01db5..44a1c70c1 100644 --- a/src/mesh/generated/meshtastic/storeforward.pb.c +++ b/src/mesh/generated/meshtastic/storeforward.pb.c @@ -1,21 +1,21 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./storeforward.pb.h" +#include "meshtastic/storeforward.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(StoreAndForward, StoreAndForward, AUTO) +PB_BIND(meshtastic_StoreAndForward, meshtastic_StoreAndForward, AUTO) -PB_BIND(StoreAndForward_Statistics, StoreAndForward_Statistics, AUTO) +PB_BIND(meshtastic_StoreAndForward_Statistics, meshtastic_StoreAndForward_Statistics, AUTO) -PB_BIND(StoreAndForward_History, StoreAndForward_History, AUTO) +PB_BIND(meshtastic_StoreAndForward_History, meshtastic_StoreAndForward_History, AUTO) -PB_BIND(StoreAndForward_Heartbeat, StoreAndForward_Heartbeat, AUTO) +PB_BIND(meshtastic_StoreAndForward_Heartbeat, meshtastic_StoreAndForward_Heartbeat, AUTO) diff --git a/src/mesh/generated/meshtastic/storeforward.pb.h b/src/mesh/generated/meshtastic/storeforward.pb.h index 75b06fc4a..e6cb51f61 100644 --- a/src/mesh/generated/meshtastic/storeforward.pb.h +++ b/src/mesh/generated/meshtastic/storeforward.pb.h @@ -12,42 +12,42 @@ /* Enum definitions */ /* 001 - 063 = From Router 064 - 127 = From Client */ -typedef enum _StoreAndForward_RequestResponse { +typedef enum _meshtastic_StoreAndForward_RequestResponse { /* Unset/unused */ - StoreAndForward_RequestResponse_UNSET = 0, + meshtastic_StoreAndForward_RequestResponse_UNSET = 0, /* Router is an in error state. */ - StoreAndForward_RequestResponse_ROUTER_ERROR = 1, + meshtastic_StoreAndForward_RequestResponse_ROUTER_ERROR = 1, /* Router heartbeat */ - StoreAndForward_RequestResponse_ROUTER_HEARTBEAT = 2, + meshtastic_StoreAndForward_RequestResponse_ROUTER_HEARTBEAT = 2, /* Router has requested the client respond. This can work as a "are you there" message. */ - StoreAndForward_RequestResponse_ROUTER_PING = 3, + meshtastic_StoreAndForward_RequestResponse_ROUTER_PING = 3, /* The response to a "Ping" */ - StoreAndForward_RequestResponse_ROUTER_PONG = 4, + meshtastic_StoreAndForward_RequestResponse_ROUTER_PONG = 4, /* Router is currently busy. Please try again later. */ - StoreAndForward_RequestResponse_ROUTER_BUSY = 5, + meshtastic_StoreAndForward_RequestResponse_ROUTER_BUSY = 5, /* Router is responding to a request for history. */ - StoreAndForward_RequestResponse_ROUTER_HISTORY = 6, + meshtastic_StoreAndForward_RequestResponse_ROUTER_HISTORY = 6, /* Router is responding to a request for stats. */ - StoreAndForward_RequestResponse_ROUTER_STATS = 7, + meshtastic_StoreAndForward_RequestResponse_ROUTER_STATS = 7, /* Client is an in error state. */ - StoreAndForward_RequestResponse_CLIENT_ERROR = 64, + meshtastic_StoreAndForward_RequestResponse_CLIENT_ERROR = 64, /* Client has requested a replay from the router. */ - StoreAndForward_RequestResponse_CLIENT_HISTORY = 65, + meshtastic_StoreAndForward_RequestResponse_CLIENT_HISTORY = 65, /* Client has requested stats from the router. */ - StoreAndForward_RequestResponse_CLIENT_STATS = 66, + meshtastic_StoreAndForward_RequestResponse_CLIENT_STATS = 66, /* Client has requested the router respond. This can work as a "are you there" message. */ - StoreAndForward_RequestResponse_CLIENT_PING = 67, + meshtastic_StoreAndForward_RequestResponse_CLIENT_PING = 67, /* The response to a "Ping" */ - StoreAndForward_RequestResponse_CLIENT_PONG = 68, + meshtastic_StoreAndForward_RequestResponse_CLIENT_PONG = 68, /* Client has requested that the router abort processing the client's request */ - StoreAndForward_RequestResponse_CLIENT_ABORT = 106 -} StoreAndForward_RequestResponse; + meshtastic_StoreAndForward_RequestResponse_CLIENT_ABORT = 106 +} meshtastic_StoreAndForward_RequestResponse; /* Struct definitions */ /* TODO: REPLACE */ -typedef struct _StoreAndForward_Statistics { +typedef struct _meshtastic_StoreAndForward_Statistics { /* Number of messages we have ever seen */ uint32_t messages_total; /* Number of messages we have currently saved our history. */ @@ -66,42 +66,42 @@ typedef struct _StoreAndForward_Statistics { uint32_t return_max; /* Is the heartbeat enabled on the server? */ uint32_t return_window; -} StoreAndForward_Statistics; +} meshtastic_StoreAndForward_Statistics; /* TODO: REPLACE */ -typedef struct _StoreAndForward_History { +typedef struct _meshtastic_StoreAndForward_History { /* Number of that will be sent to the client */ uint32_t history_messages; /* The window of messages that was used to filter the history client requested */ uint32_t window; /* The window of messages that was used to filter the history client requested */ uint32_t last_request; -} StoreAndForward_History; +} meshtastic_StoreAndForward_History; /* TODO: REPLACE */ -typedef struct _StoreAndForward_Heartbeat { +typedef struct _meshtastic_StoreAndForward_Heartbeat { /* Number of that will be sent to the client */ uint32_t period; /* If set, this is not the primary Store & Forward router on the mesh */ uint32_t secondary; -} StoreAndForward_Heartbeat; +} meshtastic_StoreAndForward_Heartbeat; /* TODO: REPLACE */ -typedef struct _StoreAndForward { +typedef struct _meshtastic_StoreAndForward { /* TODO: REPLACE */ - StoreAndForward_RequestResponse rr; + meshtastic_StoreAndForward_RequestResponse rr; pb_size_t which_variant; union { /* TODO: REPLACE */ - StoreAndForward_Statistics stats; + meshtastic_StoreAndForward_Statistics stats; /* TODO: REPLACE */ - StoreAndForward_History history; + meshtastic_StoreAndForward_History history; /* TODO: REPLACE */ - StoreAndForward_Heartbeat heartbeat; + meshtastic_StoreAndForward_Heartbeat heartbeat; /* Empty Payload */ bool empty; } variant; -} StoreAndForward; +} meshtastic_StoreAndForward; #ifdef __cplusplus @@ -109,61 +109,61 @@ extern "C" { #endif /* Helper constants for enums */ -#define _StoreAndForward_RequestResponse_MIN StoreAndForward_RequestResponse_UNSET -#define _StoreAndForward_RequestResponse_MAX StoreAndForward_RequestResponse_CLIENT_ABORT -#define _StoreAndForward_RequestResponse_ARRAYSIZE ((StoreAndForward_RequestResponse)(StoreAndForward_RequestResponse_CLIENT_ABORT+1)) +#define _meshtastic_StoreAndForward_RequestResponse_MIN meshtastic_StoreAndForward_RequestResponse_UNSET +#define _meshtastic_StoreAndForward_RequestResponse_MAX meshtastic_StoreAndForward_RequestResponse_CLIENT_ABORT +#define _meshtastic_StoreAndForward_RequestResponse_ARRAYSIZE ((meshtastic_StoreAndForward_RequestResponse)(meshtastic_StoreAndForward_RequestResponse_CLIENT_ABORT+1)) -#define StoreAndForward_rr_ENUMTYPE StoreAndForward_RequestResponse +#define meshtastic_StoreAndForward_rr_ENUMTYPE meshtastic_StoreAndForward_RequestResponse /* Initializer values for message structs */ -#define StoreAndForward_init_default {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_default}} -#define StoreAndForward_Statistics_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} -#define StoreAndForward_History_init_default {0, 0, 0} -#define StoreAndForward_Heartbeat_init_default {0, 0} -#define StoreAndForward_init_zero {_StoreAndForward_RequestResponse_MIN, 0, {StoreAndForward_Statistics_init_zero}} -#define StoreAndForward_Statistics_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} -#define StoreAndForward_History_init_zero {0, 0, 0} -#define StoreAndForward_Heartbeat_init_zero {0, 0} +#define meshtastic_StoreAndForward_init_default {_meshtastic_StoreAndForward_RequestResponse_MIN, 0, {meshtastic_StoreAndForward_Statistics_init_default}} +#define meshtastic_StoreAndForward_Statistics_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_StoreAndForward_History_init_default {0, 0, 0} +#define meshtastic_StoreAndForward_Heartbeat_init_default {0, 0} +#define meshtastic_StoreAndForward_init_zero {_meshtastic_StoreAndForward_RequestResponse_MIN, 0, {meshtastic_StoreAndForward_Statistics_init_zero}} +#define meshtastic_StoreAndForward_Statistics_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0} +#define meshtastic_StoreAndForward_History_init_zero {0, 0, 0} +#define meshtastic_StoreAndForward_Heartbeat_init_zero {0, 0} /* Field tags (for use in manual encoding/decoding) */ -#define StoreAndForward_Statistics_messages_total_tag 1 -#define StoreAndForward_Statistics_messages_saved_tag 2 -#define StoreAndForward_Statistics_messages_max_tag 3 -#define StoreAndForward_Statistics_up_time_tag 4 -#define StoreAndForward_Statistics_requests_tag 5 -#define StoreAndForward_Statistics_requests_history_tag 6 -#define StoreAndForward_Statistics_heartbeat_tag 7 -#define StoreAndForward_Statistics_return_max_tag 8 -#define StoreAndForward_Statistics_return_window_tag 9 -#define StoreAndForward_History_history_messages_tag 1 -#define StoreAndForward_History_window_tag 2 -#define StoreAndForward_History_last_request_tag 3 -#define StoreAndForward_Heartbeat_period_tag 1 -#define StoreAndForward_Heartbeat_secondary_tag 2 -#define StoreAndForward_rr_tag 1 -#define StoreAndForward_stats_tag 2 -#define StoreAndForward_history_tag 3 -#define StoreAndForward_heartbeat_tag 4 -#define StoreAndForward_empty_tag 5 +#define meshtastic_StoreAndForward_Statistics_messages_total_tag 1 +#define meshtastic_StoreAndForward_Statistics_messages_saved_tag 2 +#define meshtastic_StoreAndForward_Statistics_messages_max_tag 3 +#define meshtastic_StoreAndForward_Statistics_up_time_tag 4 +#define meshtastic_StoreAndForward_Statistics_requests_tag 5 +#define meshtastic_StoreAndForward_Statistics_requests_history_tag 6 +#define meshtastic_StoreAndForward_Statistics_heartbeat_tag 7 +#define meshtastic_StoreAndForward_Statistics_return_max_tag 8 +#define meshtastic_StoreAndForward_Statistics_return_window_tag 9 +#define meshtastic_StoreAndForward_History_history_messages_tag 1 +#define meshtastic_StoreAndForward_History_window_tag 2 +#define meshtastic_StoreAndForward_History_last_request_tag 3 +#define meshtastic_StoreAndForward_Heartbeat_period_tag 1 +#define meshtastic_StoreAndForward_Heartbeat_secondary_tag 2 +#define meshtastic_StoreAndForward_rr_tag 1 +#define meshtastic_StoreAndForward_stats_tag 2 +#define meshtastic_StoreAndForward_history_tag 3 +#define meshtastic_StoreAndForward_heartbeat_tag 4 +#define meshtastic_StoreAndForward_empty_tag 5 /* Struct field encoding specification for nanopb */ -#define StoreAndForward_FIELDLIST(X, a) \ +#define meshtastic_StoreAndForward_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, rr, 1) \ X(a, STATIC, ONEOF, MESSAGE, (variant,stats,variant.stats), 2) \ X(a, STATIC, ONEOF, MESSAGE, (variant,history,variant.history), 3) \ X(a, STATIC, ONEOF, MESSAGE, (variant,heartbeat,variant.heartbeat), 4) \ X(a, STATIC, ONEOF, BOOL, (variant,empty,variant.empty), 5) -#define StoreAndForward_CALLBACK NULL -#define StoreAndForward_DEFAULT NULL -#define StoreAndForward_variant_stats_MSGTYPE StoreAndForward_Statistics -#define StoreAndForward_variant_history_MSGTYPE StoreAndForward_History -#define StoreAndForward_variant_heartbeat_MSGTYPE StoreAndForward_Heartbeat +#define meshtastic_StoreAndForward_CALLBACK NULL +#define meshtastic_StoreAndForward_DEFAULT NULL +#define meshtastic_StoreAndForward_variant_stats_MSGTYPE meshtastic_StoreAndForward_Statistics +#define meshtastic_StoreAndForward_variant_history_MSGTYPE meshtastic_StoreAndForward_History +#define meshtastic_StoreAndForward_variant_heartbeat_MSGTYPE meshtastic_StoreAndForward_Heartbeat -#define StoreAndForward_Statistics_FIELDLIST(X, a) \ +#define meshtastic_StoreAndForward_Statistics_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, messages_total, 1) \ X(a, STATIC, SINGULAR, UINT32, messages_saved, 2) \ X(a, STATIC, SINGULAR, UINT32, messages_max, 3) \ @@ -173,38 +173,38 @@ X(a, STATIC, SINGULAR, UINT32, requests_history, 6) \ X(a, STATIC, SINGULAR, BOOL, heartbeat, 7) \ X(a, STATIC, SINGULAR, UINT32, return_max, 8) \ X(a, STATIC, SINGULAR, UINT32, return_window, 9) -#define StoreAndForward_Statistics_CALLBACK NULL -#define StoreAndForward_Statistics_DEFAULT NULL +#define meshtastic_StoreAndForward_Statistics_CALLBACK NULL +#define meshtastic_StoreAndForward_Statistics_DEFAULT NULL -#define StoreAndForward_History_FIELDLIST(X, a) \ +#define meshtastic_StoreAndForward_History_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, history_messages, 1) \ X(a, STATIC, SINGULAR, UINT32, window, 2) \ X(a, STATIC, SINGULAR, UINT32, last_request, 3) -#define StoreAndForward_History_CALLBACK NULL -#define StoreAndForward_History_DEFAULT NULL +#define meshtastic_StoreAndForward_History_CALLBACK NULL +#define meshtastic_StoreAndForward_History_DEFAULT NULL -#define StoreAndForward_Heartbeat_FIELDLIST(X, a) \ +#define meshtastic_StoreAndForward_Heartbeat_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, period, 1) \ X(a, STATIC, SINGULAR, UINT32, secondary, 2) -#define StoreAndForward_Heartbeat_CALLBACK NULL -#define StoreAndForward_Heartbeat_DEFAULT NULL +#define meshtastic_StoreAndForward_Heartbeat_CALLBACK NULL +#define meshtastic_StoreAndForward_Heartbeat_DEFAULT NULL -extern const pb_msgdesc_t StoreAndForward_msg; -extern const pb_msgdesc_t StoreAndForward_Statistics_msg; -extern const pb_msgdesc_t StoreAndForward_History_msg; -extern const pb_msgdesc_t StoreAndForward_Heartbeat_msg; +extern const pb_msgdesc_t meshtastic_StoreAndForward_msg; +extern const pb_msgdesc_t meshtastic_StoreAndForward_Statistics_msg; +extern const pb_msgdesc_t meshtastic_StoreAndForward_History_msg; +extern const pb_msgdesc_t meshtastic_StoreAndForward_Heartbeat_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define StoreAndForward_fields &StoreAndForward_msg -#define StoreAndForward_Statistics_fields &StoreAndForward_Statistics_msg -#define StoreAndForward_History_fields &StoreAndForward_History_msg -#define StoreAndForward_Heartbeat_fields &StoreAndForward_Heartbeat_msg +#define meshtastic_StoreAndForward_fields &meshtastic_StoreAndForward_msg +#define meshtastic_StoreAndForward_Statistics_fields &meshtastic_StoreAndForward_Statistics_msg +#define meshtastic_StoreAndForward_History_fields &meshtastic_StoreAndForward_History_msg +#define meshtastic_StoreAndForward_Heartbeat_fields &meshtastic_StoreAndForward_Heartbeat_msg /* Maximum encoded size of messages (where known) */ -#define StoreAndForward_Heartbeat_size 12 -#define StoreAndForward_History_size 18 -#define StoreAndForward_Statistics_size 50 -#define StoreAndForward_size 54 +#define meshtastic_StoreAndForward_Heartbeat_size 12 +#define meshtastic_StoreAndForward_History_size 18 +#define meshtastic_StoreAndForward_Statistics_size 50 +#define meshtastic_StoreAndForward_size 54 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/telemetry.pb.c b/src/mesh/generated/meshtastic/telemetry.pb.c index 1446be188..cdc01710a 100644 --- a/src/mesh/generated/meshtastic/telemetry.pb.c +++ b/src/mesh/generated/meshtastic/telemetry.pb.c @@ -1,18 +1,18 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./telemetry.pb.h" +#include "meshtastic/telemetry.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(DeviceMetrics, DeviceMetrics, AUTO) +PB_BIND(meshtastic_DeviceMetrics, meshtastic_DeviceMetrics, AUTO) -PB_BIND(EnvironmentMetrics, EnvironmentMetrics, AUTO) +PB_BIND(meshtastic_EnvironmentMetrics, meshtastic_EnvironmentMetrics, AUTO) -PB_BIND(Telemetry, Telemetry, AUTO) +PB_BIND(meshtastic_Telemetry, meshtastic_Telemetry, AUTO) diff --git a/src/mesh/generated/meshtastic/telemetry.pb.h b/src/mesh/generated/meshtastic/telemetry.pb.h index 7d4bb02eb..188b27d77 100644 --- a/src/mesh/generated/meshtastic/telemetry.pb.h +++ b/src/mesh/generated/meshtastic/telemetry.pb.h @@ -11,38 +11,38 @@ /* Enum definitions */ /* TODO: REPLACE */ -typedef enum _TelemetrySensorType { +typedef enum _meshtastic_TelemetrySensorType { /* No external telemetry sensor explicitly set */ - TelemetrySensorType_SENSOR_UNSET = 0, + meshtastic_TelemetrySensorType_SENSOR_UNSET = 0, /* High accuracy temperature, pressure, humidity */ - TelemetrySensorType_BME280 = 1, + meshtastic_TelemetrySensorType_BME280 = 1, /* High accuracy temperature, pressure, humidity, and air resistance */ - TelemetrySensorType_BME680 = 2, + meshtastic_TelemetrySensorType_BME680 = 2, /* Very high accuracy temperature */ - TelemetrySensorType_MCP9808 = 3, + meshtastic_TelemetrySensorType_MCP9808 = 3, /* Moderate accuracy current and voltage */ - TelemetrySensorType_INA260 = 4, + meshtastic_TelemetrySensorType_INA260 = 4, /* Moderate accuracy current and voltage */ - TelemetrySensorType_INA219 = 5, + meshtastic_TelemetrySensorType_INA219 = 5, /* High accuracy temperature and pressure */ - TelemetrySensorType_BMP280 = 6, + meshtastic_TelemetrySensorType_BMP280 = 6, /* High accuracy temperature and humidity */ - TelemetrySensorType_SHTC3 = 7, + meshtastic_TelemetrySensorType_SHTC3 = 7, /* High accuracy pressure */ - TelemetrySensorType_LPS22 = 8, + meshtastic_TelemetrySensorType_LPS22 = 8, /* 3-Axis magnetic sensor */ - TelemetrySensorType_QMC6310 = 9, + meshtastic_TelemetrySensorType_QMC6310 = 9, /* 6-Axis inertial measurement sensor */ - TelemetrySensorType_QMI8658 = 10, + meshtastic_TelemetrySensorType_QMI8658 = 10, /* 3-Axis magnetic sensor */ - TelemetrySensorType_QMC5883L = 11, + meshtastic_TelemetrySensorType_QMC5883L = 11, /* High accuracy temperature and humidity */ - TelemetrySensorType_SHT31 = 12 -} TelemetrySensorType; + meshtastic_TelemetrySensorType_SHT31 = 12 +} meshtastic_TelemetrySensorType; /* Struct definitions */ /* Key native device metrics such as battery level */ -typedef struct _DeviceMetrics { +typedef struct _meshtastic_DeviceMetrics { /* 1-100 (0 means powered) */ uint32_t battery_level; /* Voltage measured */ @@ -51,10 +51,10 @@ typedef struct _DeviceMetrics { float channel_utilization; /* Percent of airtime for transmission used within the last hour. */ float air_util_tx; -} DeviceMetrics; +} meshtastic_DeviceMetrics; /* Weather station or other environmental metrics */ -typedef struct _EnvironmentMetrics { +typedef struct _meshtastic_EnvironmentMetrics { /* Temperature measured */ float temperature; /* Relative humidity percent measured */ @@ -67,24 +67,24 @@ typedef struct _EnvironmentMetrics { float voltage; /* Current measured */ float current; -} EnvironmentMetrics; +} meshtastic_EnvironmentMetrics; /* Types of Measurements the telemetry module is equipped to handle */ -typedef struct _Telemetry { - /* This is usually not sent over the mesh (to save space), but it is sent - from the phone so that the local device can set its RTC If it is sent over - the mesh (because there are devices on the mesh without GPS), it will only - be sent by devices which has a hardware GPS clock (IE Mobile Phone). +typedef struct _meshtastic_Telemetry { + /* This is usually not sent over the mesh (to save space), but it is sent + from the phone so that the local device can set its RTC If it is sent over + the mesh (because there are devices on the mesh without GPS), it will only + be sent by devices which has a hardware GPS clock (IE Mobile Phone). seconds since 1970 */ uint32_t time; pb_size_t which_variant; union { /* Key native device metrics such as battery level */ - DeviceMetrics device_metrics; + meshtastic_DeviceMetrics device_metrics; /* Weather station or other environmental metrics */ - EnvironmentMetrics environment_metrics; + meshtastic_EnvironmentMetrics environment_metrics; } variant; -} Telemetry; +} meshtastic_Telemetry; #ifdef __cplusplus @@ -92,78 +92,78 @@ extern "C" { #endif /* Helper constants for enums */ -#define _TelemetrySensorType_MIN TelemetrySensorType_SENSOR_UNSET -#define _TelemetrySensorType_MAX TelemetrySensorType_SHT31 -#define _TelemetrySensorType_ARRAYSIZE ((TelemetrySensorType)(TelemetrySensorType_SHT31+1)) +#define _meshtastic_TelemetrySensorType_MIN meshtastic_TelemetrySensorType_SENSOR_UNSET +#define _meshtastic_TelemetrySensorType_MAX meshtastic_TelemetrySensorType_SHT31 +#define _meshtastic_TelemetrySensorType_ARRAYSIZE ((meshtastic_TelemetrySensorType)(meshtastic_TelemetrySensorType_SHT31+1)) /* Initializer values for message structs */ -#define DeviceMetrics_init_default {0, 0, 0, 0} -#define EnvironmentMetrics_init_default {0, 0, 0, 0, 0, 0} -#define Telemetry_init_default {0, 0, {DeviceMetrics_init_default}} -#define DeviceMetrics_init_zero {0, 0, 0, 0} -#define EnvironmentMetrics_init_zero {0, 0, 0, 0, 0, 0} -#define Telemetry_init_zero {0, 0, {DeviceMetrics_init_zero}} +#define meshtastic_DeviceMetrics_init_default {0, 0, 0, 0} +#define meshtastic_EnvironmentMetrics_init_default {0, 0, 0, 0, 0, 0} +#define meshtastic_Telemetry_init_default {0, 0, {meshtastic_DeviceMetrics_init_default}} +#define meshtastic_DeviceMetrics_init_zero {0, 0, 0, 0} +#define meshtastic_EnvironmentMetrics_init_zero {0, 0, 0, 0, 0, 0} +#define meshtastic_Telemetry_init_zero {0, 0, {meshtastic_DeviceMetrics_init_zero}} /* Field tags (for use in manual encoding/decoding) */ -#define DeviceMetrics_battery_level_tag 1 -#define DeviceMetrics_voltage_tag 2 -#define DeviceMetrics_channel_utilization_tag 3 -#define DeviceMetrics_air_util_tx_tag 4 -#define EnvironmentMetrics_temperature_tag 1 -#define EnvironmentMetrics_relative_humidity_tag 2 -#define EnvironmentMetrics_barometric_pressure_tag 3 -#define EnvironmentMetrics_gas_resistance_tag 4 -#define EnvironmentMetrics_voltage_tag 5 -#define EnvironmentMetrics_current_tag 6 -#define Telemetry_time_tag 1 -#define Telemetry_device_metrics_tag 2 -#define Telemetry_environment_metrics_tag 3 +#define meshtastic_DeviceMetrics_battery_level_tag 1 +#define meshtastic_DeviceMetrics_voltage_tag 2 +#define meshtastic_DeviceMetrics_channel_utilization_tag 3 +#define meshtastic_DeviceMetrics_air_util_tx_tag 4 +#define meshtastic_EnvironmentMetrics_temperature_tag 1 +#define meshtastic_EnvironmentMetrics_relative_humidity_tag 2 +#define meshtastic_EnvironmentMetrics_barometric_pressure_tag 3 +#define meshtastic_EnvironmentMetrics_gas_resistance_tag 4 +#define meshtastic_EnvironmentMetrics_voltage_tag 5 +#define meshtastic_EnvironmentMetrics_current_tag 6 +#define meshtastic_Telemetry_time_tag 1 +#define meshtastic_Telemetry_device_metrics_tag 2 +#define meshtastic_Telemetry_environment_metrics_tag 3 /* Struct field encoding specification for nanopb */ -#define DeviceMetrics_FIELDLIST(X, a) \ +#define meshtastic_DeviceMetrics_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, battery_level, 1) \ X(a, STATIC, SINGULAR, FLOAT, voltage, 2) \ X(a, STATIC, SINGULAR, FLOAT, channel_utilization, 3) \ X(a, STATIC, SINGULAR, FLOAT, air_util_tx, 4) -#define DeviceMetrics_CALLBACK NULL -#define DeviceMetrics_DEFAULT NULL +#define meshtastic_DeviceMetrics_CALLBACK NULL +#define meshtastic_DeviceMetrics_DEFAULT NULL -#define EnvironmentMetrics_FIELDLIST(X, a) \ +#define meshtastic_EnvironmentMetrics_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, FLOAT, temperature, 1) \ X(a, STATIC, SINGULAR, FLOAT, relative_humidity, 2) \ X(a, STATIC, SINGULAR, FLOAT, barometric_pressure, 3) \ X(a, STATIC, SINGULAR, FLOAT, gas_resistance, 4) \ X(a, STATIC, SINGULAR, FLOAT, voltage, 5) \ X(a, STATIC, SINGULAR, FLOAT, current, 6) -#define EnvironmentMetrics_CALLBACK NULL -#define EnvironmentMetrics_DEFAULT NULL +#define meshtastic_EnvironmentMetrics_CALLBACK NULL +#define meshtastic_EnvironmentMetrics_DEFAULT NULL -#define Telemetry_FIELDLIST(X, a) \ +#define meshtastic_Telemetry_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, FIXED32, time, 1) \ X(a, STATIC, ONEOF, MESSAGE, (variant,device_metrics,variant.device_metrics), 2) \ X(a, STATIC, ONEOF, MESSAGE, (variant,environment_metrics,variant.environment_metrics), 3) -#define Telemetry_CALLBACK NULL -#define Telemetry_DEFAULT NULL -#define Telemetry_variant_device_metrics_MSGTYPE DeviceMetrics -#define Telemetry_variant_environment_metrics_MSGTYPE EnvironmentMetrics +#define meshtastic_Telemetry_CALLBACK NULL +#define meshtastic_Telemetry_DEFAULT NULL +#define meshtastic_Telemetry_variant_device_metrics_MSGTYPE meshtastic_DeviceMetrics +#define meshtastic_Telemetry_variant_environment_metrics_MSGTYPE meshtastic_EnvironmentMetrics -extern const pb_msgdesc_t DeviceMetrics_msg; -extern const pb_msgdesc_t EnvironmentMetrics_msg; -extern const pb_msgdesc_t Telemetry_msg; +extern const pb_msgdesc_t meshtastic_DeviceMetrics_msg; +extern const pb_msgdesc_t meshtastic_EnvironmentMetrics_msg; +extern const pb_msgdesc_t meshtastic_Telemetry_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define DeviceMetrics_fields &DeviceMetrics_msg -#define EnvironmentMetrics_fields &EnvironmentMetrics_msg -#define Telemetry_fields &Telemetry_msg +#define meshtastic_DeviceMetrics_fields &meshtastic_DeviceMetrics_msg +#define meshtastic_EnvironmentMetrics_fields &meshtastic_EnvironmentMetrics_msg +#define meshtastic_Telemetry_fields &meshtastic_Telemetry_msg /* Maximum encoded size of messages (where known) */ -#define DeviceMetrics_size 21 -#define EnvironmentMetrics_size 30 -#define Telemetry_size 37 +#define meshtastic_DeviceMetrics_size 21 +#define meshtastic_EnvironmentMetrics_size 30 +#define meshtastic_Telemetry_size 37 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/xmodem.pb.c b/src/mesh/generated/meshtastic/xmodem.pb.c index f2b00401d..9692a5eb4 100644 --- a/src/mesh/generated/meshtastic/xmodem.pb.c +++ b/src/mesh/generated/meshtastic/xmodem.pb.c @@ -1,12 +1,12 @@ /* Automatically generated nanopb constant definitions */ /* Generated by nanopb-0.4.7 */ -#include "./xmodem.pb.h" +#include "meshtastic/xmodem.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. #endif -PB_BIND(XModem, XModem, AUTO) +PB_BIND(meshtastic_XModem, meshtastic_XModem, AUTO) diff --git a/src/mesh/generated/meshtastic/xmodem.pb.h b/src/mesh/generated/meshtastic/xmodem.pb.h index 4994fa97b..48d5aa5cd 100644 --- a/src/mesh/generated/meshtastic/xmodem.pb.h +++ b/src/mesh/generated/meshtastic/xmodem.pb.h @@ -10,25 +10,25 @@ #endif /* Enum definitions */ -typedef enum _XModem_Control { - XModem_Control_NUL = 0, - XModem_Control_SOH = 1, - XModem_Control_STX = 2, - XModem_Control_EOT = 4, - XModem_Control_ACK = 6, - XModem_Control_NAK = 21, - XModem_Control_CAN = 24, - XModem_Control_CTRLZ = 26 -} XModem_Control; +typedef enum _meshtastic_XModem_Control { + meshtastic_XModem_Control_NUL = 0, + meshtastic_XModem_Control_SOH = 1, + meshtastic_XModem_Control_STX = 2, + meshtastic_XModem_Control_EOT = 4, + meshtastic_XModem_Control_ACK = 6, + meshtastic_XModem_Control_NAK = 21, + meshtastic_XModem_Control_CAN = 24, + meshtastic_XModem_Control_CTRLZ = 26 +} meshtastic_XModem_Control; /* Struct definitions */ -typedef PB_BYTES_ARRAY_T(128) XModem_buffer_t; -typedef struct _XModem { - XModem_Control control; +typedef PB_BYTES_ARRAY_T(128) meshtastic_XModem_buffer_t; +typedef struct _meshtastic_XModem { + meshtastic_XModem_Control control; uint16_t seq; uint16_t crc16; - XModem_buffer_t buffer; -} XModem; + meshtastic_XModem_buffer_t buffer; +} meshtastic_XModem; #ifdef __cplusplus @@ -36,39 +36,39 @@ extern "C" { #endif /* Helper constants for enums */ -#define _XModem_Control_MIN XModem_Control_NUL -#define _XModem_Control_MAX XModem_Control_CTRLZ -#define _XModem_Control_ARRAYSIZE ((XModem_Control)(XModem_Control_CTRLZ+1)) +#define _meshtastic_XModem_Control_MIN meshtastic_XModem_Control_NUL +#define _meshtastic_XModem_Control_MAX meshtastic_XModem_Control_CTRLZ +#define _meshtastic_XModem_Control_ARRAYSIZE ((meshtastic_XModem_Control)(meshtastic_XModem_Control_CTRLZ+1)) -#define XModem_control_ENUMTYPE XModem_Control +#define meshtastic_XModem_control_ENUMTYPE meshtastic_XModem_Control /* Initializer values for message structs */ -#define XModem_init_default {_XModem_Control_MIN, 0, 0, {0, {0}}} -#define XModem_init_zero {_XModem_Control_MIN, 0, 0, {0, {0}}} +#define meshtastic_XModem_init_default {_meshtastic_XModem_Control_MIN, 0, 0, {0, {0}}} +#define meshtastic_XModem_init_zero {_meshtastic_XModem_Control_MIN, 0, 0, {0, {0}}} /* Field tags (for use in manual encoding/decoding) */ -#define XModem_control_tag 1 -#define XModem_seq_tag 2 -#define XModem_crc16_tag 3 -#define XModem_buffer_tag 4 +#define meshtastic_XModem_control_tag 1 +#define meshtastic_XModem_seq_tag 2 +#define meshtastic_XModem_crc16_tag 3 +#define meshtastic_XModem_buffer_tag 4 /* Struct field encoding specification for nanopb */ -#define XModem_FIELDLIST(X, a) \ +#define meshtastic_XModem_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, control, 1) \ X(a, STATIC, SINGULAR, UINT32, seq, 2) \ X(a, STATIC, SINGULAR, UINT32, crc16, 3) \ X(a, STATIC, SINGULAR, BYTES, buffer, 4) -#define XModem_CALLBACK NULL -#define XModem_DEFAULT NULL +#define meshtastic_XModem_CALLBACK NULL +#define meshtastic_XModem_DEFAULT NULL -extern const pb_msgdesc_t XModem_msg; +extern const pb_msgdesc_t meshtastic_XModem_msg; /* Defines for backwards compatibility with code written before nanopb-0.4.0 */ -#define XModem_fields &XModem_msg +#define meshtastic_XModem_fields &meshtastic_XModem_msg /* Maximum encoded size of messages (where known) */ -#define XModem_size 141 +#define meshtastic_XModem_size 141 #ifdef __cplusplus } /* extern "C" */ 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 148c8efcf..11f05f583 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -194,7 +194,8 @@ bool initWifi() WiFi.onEvent(WiFiEvent); WiFi.setAutoReconnect(true); WiFi.setSleep(false); - if (config.network.address_mode == Config_NetworkConfig_AddressMode_STATIC && config.network.ipv4_config.ip != 0) { + if (config.network.address_mode == meshtastic_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, config.network.ipv4_config.dns); // Wifi wants two DNS servers... set both to the same value 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/mesh/mesh-pb-constants.h b/src/mesh/mesh-pb-constants.h index aadfe1f54..8e22aa82b 100644 --- a/src/mesh/mesh-pb-constants.h +++ b/src/mesh/mesh-pb-constants.h @@ -16,10 +16,10 @@ #define MAX_RX_TOPHONE 32 /// max number of nodes allowed in the mesh -#define MAX_NUM_NODES (member_size(DeviceState, node_db) / member_size(DeviceState, node_db[0])) +#define MAX_NUM_NODES (member_size(meshtastic_DeviceState, node_db) / member_size(meshtastic_DeviceState, node_db[0])) /// Max number of channels allowed -#define MAX_NUM_CHANNELS (member_size(ChannelFile, channels) / member_size(ChannelFile, channels[0])) +#define MAX_NUM_CHANNELS (member_size(meshtastic_ChannelFile, channels) / member_size(meshtastic_ChannelFile, channels[0])) /// helper function for encoding a record as a protobuf, any failures to encode are fatal and we will panic /// returns the encoded packet size diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index ac13f273a..18557f0b3 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -38,7 +38,7 @@ static void writeSecret(char *buf, size_t bufsz, const char *currentVal) * @param r Decoded AdminMessage * @return bool */ -bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) +bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_AdminMessage *r) { // if handled == false, then let others look at this message also if they want bool handled = false; @@ -49,26 +49,26 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) /** * Getters */ - case AdminMessage_get_owner_request_tag: + case meshtastic_AdminMessage_get_owner_request_tag: LOG_INFO("Client is getting owner\n"); handleGetOwner(mp); break; - case AdminMessage_get_config_request_tag: + case meshtastic_AdminMessage_get_config_request_tag: LOG_INFO("Client is getting config\n"); handleGetConfig(mp, r->get_config_request); break; - case AdminMessage_get_module_config_request_tag: + case meshtastic_AdminMessage_get_module_config_request_tag: LOG_INFO("Client is getting module config\n"); handleGetModuleConfig(mp, r->get_module_config_request); break; - case AdminMessage_get_channel_request_tag: { + case meshtastic_AdminMessage_get_channel_request_tag: { uint32_t i = r->get_channel_request - 1; LOG_INFO("Client is getting channel %u\n", i); if (i >= MAX_NUM_CHANNELS) - myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); + myReply = allocErrorResponse(meshtastic_Routing_Error_BAD_REQUEST, &mp); else handleGetChannel(mp, i); break; @@ -77,25 +77,25 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) /** * Setters */ - case AdminMessage_set_owner_tag: + case meshtastic_AdminMessage_set_owner_tag: LOG_INFO("Client is setting owner\n"); handleSetOwner(r->set_owner); break; - case AdminMessage_set_config_tag: + case meshtastic_AdminMessage_set_config_tag: LOG_INFO("Client is setting the config\n"); handleSetConfig(r->set_config); break; - case AdminMessage_set_module_config_tag: + case meshtastic_AdminMessage_set_module_config_tag: LOG_INFO("Client is setting the module config\n"); handleSetModuleConfig(r->set_module_config); break; - case AdminMessage_set_channel_tag: + case meshtastic_AdminMessage_set_channel_tag: LOG_INFO("Client is setting channel %d\n", r->set_channel.index); if (r->set_channel.index < 0 || r->set_channel.index >= (int)MAX_NUM_CHANNELS) - myReply = allocErrorResponse(Routing_Error_BAD_REQUEST, &mp); + myReply = allocErrorResponse(meshtastic_Routing_Error_BAD_REQUEST, &mp); else handleSetChannel(r->set_channel); break; @@ -103,11 +103,11 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) /** * Other */ - case AdminMessage_reboot_seconds_tag: { + case meshtastic_AdminMessage_reboot_seconds_tag: { reboot(r->reboot_seconds); break; } - case AdminMessage_reboot_ota_seconds_tag: { + case meshtastic_AdminMessage_reboot_ota_seconds_tag: { int32_t s = r->reboot_ota_seconds; #ifdef ARCH_ESP32 if (BleOta::getOtaAppVersion().isEmpty()) { @@ -125,49 +125,49 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000); break; } - case AdminMessage_shutdown_seconds_tag: { + case meshtastic_AdminMessage_shutdown_seconds_tag: { int32_t s = r->shutdown_seconds; LOG_INFO("Shutdown in %d seconds\n", s); shutdownAtMsec = (s < 0) ? 0 : (millis() + s * 1000); break; } - case AdminMessage_get_device_metadata_request_tag: { + case meshtastic_AdminMessage_get_device_metadata_request_tag: { LOG_INFO("Client is getting device metadata\n"); handleGetDeviceMetadata(mp); break; } - case AdminMessage_factory_reset_tag: { + case meshtastic_AdminMessage_factory_reset_tag: { LOG_INFO("Initiating factory reset\n"); nodeDB.factoryReset(); reboot(DEFAULT_REBOOT_SECONDS); break; } - case AdminMessage_nodedb_reset_tag: { + case meshtastic_AdminMessage_nodedb_reset_tag: { LOG_INFO("Initiating node-db reset\n"); nodeDB.resetNodes(); reboot(DEFAULT_REBOOT_SECONDS); break; } - case AdminMessage_begin_edit_settings_tag: { + case meshtastic_AdminMessage_begin_edit_settings_tag: { LOG_INFO("Beginning transaction for editing settings\n"); hasOpenEditTransaction = true; break; } - case AdminMessage_commit_edit_settings_tag: { + case meshtastic_AdminMessage_commit_edit_settings_tag: { LOG_INFO("Committing transaction for edited settings\n"); hasOpenEditTransaction = false; saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); break; } #ifdef ARCH_PORTDUINO - case AdminMessage_exit_simulator_tag: + case meshtastic_AdminMessage_exit_simulator_tag: LOG_INFO("Exiting simulator\n"); _exit(0); break; #endif default: - AdminMessage res = AdminMessage_init_default; + meshtastic_AdminMessage res = meshtastic_AdminMessage_init_default; AdminMessageHandleResult handleResult = MeshModule::handleAdminMessageForAllPlugins(mp, r, &res); if (handleResult == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) { @@ -183,7 +183,7 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) // If asked for a response and it is not yet set, generate an 'ACK' response if (mp.decoded.want_response && !myReply) { - myReply = allocErrorResponse(Routing_Error_NONE, &mp); + myReply = allocErrorResponse(meshtastic_Routing_Error_NONE, &mp); } return handled; @@ -193,7 +193,7 @@ bool AdminModule::handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *r) * Setter methods */ -void AdminModule::handleSetOwner(const User &o) +void AdminModule::handleSetOwner(const meshtastic_User &o) { int changed = 0; bool licensed_changed = false; @@ -223,53 +223,51 @@ void AdminModule::handleSetOwner(const User &o) } } -void AdminModule::handleSetConfig(const Config &c) +void AdminModule::handleSetConfig(const meshtastic_Config &c) { - bool isRouter = (config.device.role == Config_DeviceConfig_Role_ROUTER); - bool isRegionUnset = (config.lora.region == Config_LoRaConfig_RegionCode_UNSET); + auto existingRole = config.device.role; + bool isRegionUnset = (config.lora.region == meshtastic_Config_LoRaConfig_RegionCode_UNSET); switch (c.which_payload_variant) { - case Config_device_tag: + case meshtastic_Config_device_tag: LOG_INFO("Setting config: Device\n"); config.has_device = true; config.device = c.payload_variant.device; // If we're setting router role for the first time, install its intervals - if (!isRouter && c.payload_variant.device.role == Config_DeviceConfig_Role_ROUTER) { - nodeDB.initConfigIntervals(); - nodeDB.initModuleConfigIntervals(); - } + if (existingRole != c.payload_variant.device.role) + nodeDB.installRoleDefaults(c.payload_variant.device.role); break; - case Config_position_tag: + case meshtastic_Config_position_tag: LOG_INFO("Setting config: Position\n"); config.has_position = true; config.position = c.payload_variant.position; // Save nodedb as well in case we got a fixed position packet saveChanges(SEGMENT_DEVICESTATE, false); break; - case Config_power_tag: + case meshtastic_Config_power_tag: LOG_INFO("Setting config: Power\n"); config.has_power = true; config.power = c.payload_variant.power; break; - case Config_network_tag: + case meshtastic_Config_network_tag: LOG_INFO("Setting config: WiFi\n"); config.has_network = true; config.network = c.payload_variant.network; break; - case Config_display_tag: + case meshtastic_Config_display_tag: LOG_INFO("Setting config: Display\n"); config.has_display = true; config.display = c.payload_variant.display; break; - case Config_lora_tag: + case meshtastic_Config_lora_tag: LOG_INFO("Setting config: LoRa\n"); config.has_lora = true; config.lora = c.payload_variant.lora; - if (isRegionUnset && config.lora.region > Config_LoRaConfig_RegionCode_UNSET) { + if (isRegionUnset && config.lora.region > meshtastic_Config_LoRaConfig_RegionCode_UNSET) { config.lora.tx_enabled = true; } break; - case Config_bluetooth_tag: + case meshtastic_Config_bluetooth_tag: LOG_INFO("Setting config: Bluetooth\n"); config.has_bluetooth = true; config.bluetooth = c.payload_variant.bluetooth; @@ -279,50 +277,50 @@ void AdminModule::handleSetConfig(const Config &c) saveChanges(SEGMENT_CONFIG); } -void AdminModule::handleSetModuleConfig(const ModuleConfig &c) +void AdminModule::handleSetModuleConfig(const meshtastic_ModuleConfig &c) { switch (c.which_payload_variant) { - case ModuleConfig_mqtt_tag: + case meshtastic_ModuleConfig_mqtt_tag: LOG_INFO("Setting module config: MQTT\n"); moduleConfig.has_mqtt = true; moduleConfig.mqtt = c.payload_variant.mqtt; break; - case ModuleConfig_serial_tag: + case meshtastic_ModuleConfig_serial_tag: LOG_INFO("Setting module config: Serial\n"); moduleConfig.has_serial = true; moduleConfig.serial = c.payload_variant.serial; break; - case ModuleConfig_external_notification_tag: + case meshtastic_ModuleConfig_external_notification_tag: LOG_INFO("Setting module config: External Notification\n"); moduleConfig.has_external_notification = true; moduleConfig.external_notification = c.payload_variant.external_notification; break; - case ModuleConfig_store_forward_tag: + case meshtastic_ModuleConfig_store_forward_tag: LOG_INFO("Setting module config: Store & Forward\n"); moduleConfig.has_store_forward = true; moduleConfig.store_forward = c.payload_variant.store_forward; break; - case ModuleConfig_range_test_tag: + case meshtastic_ModuleConfig_range_test_tag: LOG_INFO("Setting module config: Range Test\n"); moduleConfig.has_range_test = true; moduleConfig.range_test = c.payload_variant.range_test; break; - case ModuleConfig_telemetry_tag: + case meshtastic_ModuleConfig_telemetry_tag: LOG_INFO("Setting module config: Telemetry\n"); moduleConfig.has_telemetry = true; moduleConfig.telemetry = c.payload_variant.telemetry; break; - case ModuleConfig_canned_message_tag: + case meshtastic_ModuleConfig_canned_message_tag: LOG_INFO("Setting module config: Canned Message\n"); moduleConfig.has_canned_message = true; moduleConfig.canned_message = c.payload_variant.canned_message; break; - case ModuleConfig_audio_tag: + case meshtastic_ModuleConfig_audio_tag: LOG_INFO("Setting module config: Audio\n"); moduleConfig.has_audio = true; moduleConfig.audio = c.payload_variant.audio; break; - case ModuleConfig_remote_hardware_tag: + case meshtastic_ModuleConfig_remote_hardware_tag: LOG_INFO("Setting module config: Remote Hardware\n"); moduleConfig.has_remote_hardware = true; moduleConfig.remote_hardware = c.payload_variant.remote_hardware; @@ -332,7 +330,7 @@ void AdminModule::handleSetModuleConfig(const ModuleConfig &c) saveChanges(SEGMENT_MODULECONFIG); } -void AdminModule::handleSetChannel(const Channel &cc) +void AdminModule::handleSetChannel(const meshtastic_Channel &cc) { channels.setChannel(cc); channels.onConfigChanged(); // tell the radios about this change @@ -343,59 +341,59 @@ void AdminModule::handleSetChannel(const Channel &cc) * Getters */ -void AdminModule::handleGetOwner(const MeshPacket &req) +void AdminModule::handleGetOwner(const meshtastic_MeshPacket &req) { if (req.decoded.want_response) { // We create the reply here - AdminMessage res = AdminMessage_init_default; + meshtastic_AdminMessage res = meshtastic_AdminMessage_init_default; res.get_owner_response = owner; - res.which_payload_variant = AdminMessage_get_owner_response_tag; + res.which_payload_variant = meshtastic_AdminMessage_get_owner_response_tag; myReply = allocDataProtobuf(res); } } -void AdminModule::handleGetConfig(const MeshPacket &req, const uint32_t configType) +void AdminModule::handleGetConfig(const meshtastic_MeshPacket &req, const uint32_t configType) { - AdminMessage res = AdminMessage_init_default; + meshtastic_AdminMessage res = meshtastic_AdminMessage_init_default; if (req.decoded.want_response) { switch (configType) { - case AdminMessage_ConfigType_DEVICE_CONFIG: + case meshtastic_AdminMessage_ConfigType_DEVICE_CONFIG: LOG_INFO("Getting config: Device\n"); - res.get_config_response.which_payload_variant = Config_device_tag; + res.get_config_response.which_payload_variant = meshtastic_Config_device_tag; res.get_config_response.payload_variant.device = config.device; break; - case AdminMessage_ConfigType_POSITION_CONFIG: + case meshtastic_AdminMessage_ConfigType_POSITION_CONFIG: LOG_INFO("Getting config: Position\n"); - res.get_config_response.which_payload_variant = Config_position_tag; + res.get_config_response.which_payload_variant = meshtastic_Config_position_tag; res.get_config_response.payload_variant.position = config.position; break; - case AdminMessage_ConfigType_POWER_CONFIG: + case meshtastic_AdminMessage_ConfigType_POWER_CONFIG: LOG_INFO("Getting config: Power\n"); - res.get_config_response.which_payload_variant = Config_power_tag; + res.get_config_response.which_payload_variant = meshtastic_Config_power_tag; res.get_config_response.payload_variant.power = config.power; break; - case AdminMessage_ConfigType_NETWORK_CONFIG: + case meshtastic_AdminMessage_ConfigType_NETWORK_CONFIG: LOG_INFO("Getting config: Network\n"); - res.get_config_response.which_payload_variant = Config_network_tag; + res.get_config_response.which_payload_variant = meshtastic_Config_network_tag; res.get_config_response.payload_variant.network = config.network; writeSecret(res.get_config_response.payload_variant.network.wifi_psk, sizeof(res.get_config_response.payload_variant.network.wifi_psk), config.network.wifi_psk); break; - case AdminMessage_ConfigType_DISPLAY_CONFIG: + case meshtastic_AdminMessage_ConfigType_DISPLAY_CONFIG: LOG_INFO("Getting config: Display\n"); - res.get_config_response.which_payload_variant = Config_display_tag; + res.get_config_response.which_payload_variant = meshtastic_Config_display_tag; res.get_config_response.payload_variant.display = config.display; break; - case AdminMessage_ConfigType_LORA_CONFIG: + case meshtastic_AdminMessage_ConfigType_LORA_CONFIG: LOG_INFO("Getting config: LoRa\n"); - res.get_config_response.which_payload_variant = Config_lora_tag; + res.get_config_response.which_payload_variant = meshtastic_Config_lora_tag; res.get_config_response.payload_variant.lora = config.lora; break; - case AdminMessage_ConfigType_BLUETOOTH_CONFIG: + case meshtastic_AdminMessage_ConfigType_BLUETOOTH_CONFIG: LOG_INFO("Getting config: Bluetooth\n"); - res.get_config_response.which_payload_variant = Config_bluetooth_tag; + res.get_config_response.which_payload_variant = meshtastic_Config_bluetooth_tag; res.get_config_response.payload_variant.bluetooth = config.bluetooth; break; } @@ -406,60 +404,60 @@ void AdminModule::handleGetConfig(const MeshPacket &req, const uint32_t configTy // hideSecret(r.get_radio_response.preferences.wifi_ssid); // hmm - leave public for now, because only minimally private // and useful for users to know current provisioning) hideSecret(r.get_radio_response.preferences.wifi_password); // r.get_config_response.which_payloadVariant = Config_ModuleConfig_telemetry_tag; - res.which_payload_variant = AdminMessage_get_config_response_tag; + res.which_payload_variant = meshtastic_AdminMessage_get_config_response_tag; myReply = allocDataProtobuf(res); } } -void AdminModule::handleGetModuleConfig(const MeshPacket &req, const uint32_t configType) +void AdminModule::handleGetModuleConfig(const meshtastic_MeshPacket &req, const uint32_t configType) { - AdminMessage res = AdminMessage_init_default; + meshtastic_AdminMessage res = meshtastic_AdminMessage_init_default; if (req.decoded.want_response) { switch (configType) { - case AdminMessage_ModuleConfigType_MQTT_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_MQTT_CONFIG: LOG_INFO("Getting module config: MQTT\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_mqtt_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_mqtt_tag; res.get_module_config_response.payload_variant.mqtt = moduleConfig.mqtt; break; - case AdminMessage_ModuleConfigType_SERIAL_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_SERIAL_CONFIG: LOG_INFO("Getting module config: Serial\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_serial_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_serial_tag; res.get_module_config_response.payload_variant.serial = moduleConfig.serial; break; - case AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG: LOG_INFO("Getting module config: External Notification\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_external_notification_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_external_notification_tag; res.get_module_config_response.payload_variant.external_notification = moduleConfig.external_notification; break; - case AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG: LOG_INFO("Getting module config: Store & Forward\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_store_forward_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_store_forward_tag; res.get_module_config_response.payload_variant.store_forward = moduleConfig.store_forward; break; - case AdminMessage_ModuleConfigType_RANGETEST_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_RANGETEST_CONFIG: LOG_INFO("Getting module config: Range Test\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_range_test_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_range_test_tag; res.get_module_config_response.payload_variant.range_test = moduleConfig.range_test; break; - case AdminMessage_ModuleConfigType_TELEMETRY_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_TELEMETRY_CONFIG: LOG_INFO("Getting module config: Telemetry\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_telemetry_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_telemetry_tag; res.get_module_config_response.payload_variant.telemetry = moduleConfig.telemetry; break; - case AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG: LOG_INFO("Getting module config: Canned Message\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_canned_message_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_canned_message_tag; res.get_module_config_response.payload_variant.canned_message = moduleConfig.canned_message; break; - case AdminMessage_ModuleConfigType_AUDIO_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_AUDIO_CONFIG: LOG_INFO("Getting module config: Audio\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_audio_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_audio_tag; res.get_module_config_response.payload_variant.audio = moduleConfig.audio; break; - case AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG: + case meshtastic_AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG: LOG_INFO("Getting module config: Remote Hardware\n"); - res.get_module_config_response.which_payload_variant = ModuleConfig_remote_hardware_tag; + res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_remote_hardware_tag; res.get_module_config_response.payload_variant.remote_hardware = moduleConfig.remote_hardware; break; } @@ -471,16 +469,16 @@ void AdminModule::handleGetModuleConfig(const MeshPacket &req, const uint32_t co // hideSecret(r.get_radio_response.preferences.wifi_ssid); // hmm - leave public for now, because only minimally private // and useful for users to know current provisioning) hideSecret(r.get_radio_response.preferences.wifi_password); // r.get_config_response.which_payloadVariant = Config_ModuleConfig_telemetry_tag; - res.which_payload_variant = AdminMessage_get_module_config_response_tag; + res.which_payload_variant = meshtastic_AdminMessage_get_module_config_response_tag; myReply = allocDataProtobuf(res); } } -void AdminModule::handleGetDeviceMetadata(const MeshPacket &req) +void AdminModule::handleGetDeviceMetadata(const meshtastic_MeshPacket &req) { - AdminMessage r = AdminMessage_init_default; + meshtastic_AdminMessage r = meshtastic_AdminMessage_init_default; - DeviceMetadata deviceMetadata; + meshtastic_DeviceMetadata deviceMetadata; strncpy(deviceMetadata.firmware_version, myNodeInfo.firmware_version, 18); deviceMetadata.device_state_version = DEVICESTATE_CUR_VER; deviceMetadata.canShutdown = pmu_found || HAS_CPU_SHUTDOWN; @@ -491,17 +489,17 @@ void AdminModule::handleGetDeviceMetadata(const MeshPacket &req) deviceMetadata.position_flags = config.position.position_flags; r.get_device_metadata_response = deviceMetadata; - r.which_payload_variant = AdminMessage_get_device_metadata_response_tag; + r.which_payload_variant = meshtastic_AdminMessage_get_device_metadata_response_tag; myReply = allocDataProtobuf(r); } -void AdminModule::handleGetChannel(const MeshPacket &req, uint32_t channelIndex) +void AdminModule::handleGetChannel(const meshtastic_MeshPacket &req, uint32_t channelIndex) { if (req.decoded.want_response) { // We create the reply here - AdminMessage r = AdminMessage_init_default; + meshtastic_AdminMessage r = meshtastic_AdminMessage_init_default; r.get_channel_response = channels.getByIndex(channelIndex); - r.which_payload_variant = AdminMessage_get_channel_response_tag; + r.which_payload_variant = meshtastic_AdminMessage_get_channel_response_tag; myReply = allocDataProtobuf(r); } } @@ -526,7 +524,7 @@ void AdminModule::saveChanges(int saveWhat, bool shouldReboot) } } -AdminModule::AdminModule() : ProtobufModule("Admin", PortNum_ADMIN_APP, &AdminMessage_msg) +AdminModule::AdminModule() : ProtobufModule("Admin", meshtastic_PortNum_ADMIN_APP, &meshtastic_AdminMessage_msg) { // restrict to the admin channel for rx boundChannel = Channels::adminChannel; diff --git a/src/modules/AdminModule.h b/src/modules/AdminModule.h index 369bcc60b..a0602b140 100644 --- a/src/modules/AdminModule.h +++ b/src/modules/AdminModule.h @@ -4,7 +4,7 @@ /** * Admin module for admin messages */ -class AdminModule : public ProtobufModule +class AdminModule : public ProtobufModule { public: /** Constructor @@ -17,7 +17,7 @@ class AdminModule : public ProtobufModule @return true if you've guaranteed you've handled this message and no other handlers should be considered for it */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, AdminMessage *p) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_AdminMessage *p) override; private: bool hasOpenEditTransaction = false; @@ -26,19 +26,19 @@ class AdminModule : public ProtobufModule /** * Getters */ - void handleGetOwner(const MeshPacket &req); - void handleGetConfig(const MeshPacket &req, uint32_t configType); - void handleGetModuleConfig(const MeshPacket &req, uint32_t configType); - void handleGetChannel(const MeshPacket &req, uint32_t channelIndex); - void handleGetDeviceMetadata(const MeshPacket &req); + void handleGetOwner(const meshtastic_MeshPacket &req); + void handleGetConfig(const meshtastic_MeshPacket &req, uint32_t configType); + void handleGetModuleConfig(const meshtastic_MeshPacket &req, uint32_t configType); + void handleGetChannel(const meshtastic_MeshPacket &req, uint32_t channelIndex); + void handleGetDeviceMetadata(const meshtastic_MeshPacket &req); /** * Setters */ - void handleSetOwner(const User &o); - void handleSetChannel(const Channel &cc); - void handleSetConfig(const Config &c); - void handleSetModuleConfig(const ModuleConfig &c); + void handleSetOwner(const meshtastic_User &o); + void handleSetChannel(const meshtastic_Channel &cc); + void handleSetConfig(const meshtastic_Config &c); + void handleSetModuleConfig(const meshtastic_ModuleConfig &c); void handleSetChannel(); void reboot(int32_t seconds); }; diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index 5e1550893..9e5b63c51 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -39,12 +39,12 @@ extern uint8_t cardkb_found; static const char *cannedMessagesConfigFile = "/prefs/cannedConf.proto"; -CannedMessageModuleConfig cannedMessageModuleConfig; +meshtastic_CannedMessageModuleConfig cannedMessageModuleConfig; CannedMessageModule *cannedMessageModule; CannedMessageModule::CannedMessageModule() - : SinglePortModule("canned", PortNum_TEXT_MESSAGE_APP), concurrency::OSThread("CannedMessageModule") + : SinglePortModule("canned", meshtastic_PortNum_TEXT_MESSAGE_APP), concurrency::OSThread("CannedMessageModule") { if (moduleConfig.canned_message.enabled) { this->loadProtoForModule(); @@ -122,17 +122,17 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) } bool validEvent = false; - if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_UP)) { + if (event->inputEvent == static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_UP)) { LOG_DEBUG("Canned message event UP\n"); this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_UP; validEvent = true; } - if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_DOWN)) { + if (event->inputEvent == static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_DOWN)) { LOG_DEBUG("Canned message event DOWN\n"); this->runState = CANNED_MESSAGE_RUN_STATE_ACTION_DOWN; validEvent = true; } - if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_SELECT)) { + if (event->inputEvent == static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_SELECT)) { LOG_DEBUG("Canned message event Select\n"); // when inactive, call the onebutton shortpress instead. Activate Module only on up/down if ((this->runState == CANNED_MESSAGE_RUN_STATE_INACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_DISABLED)) { @@ -143,15 +143,15 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) validEvent = true; } } - if (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL)) { + if (event->inputEvent == static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL)) { LOG_DEBUG("Canned message event Cancel\n"); // emulate a timeout. Same result this->lastTouchMillis = 0; validEvent = true; } - if ((event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_BACK)) || - (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_LEFT)) || - (event->inputEvent == static_cast(ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT))) { + if ((event->inputEvent == static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_BACK)) || + (event->inputEvent == static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_LEFT)) || + (event->inputEvent == static_cast(meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT))) { LOG_DEBUG("Canned message event (%x)\n", event->kbchar); if (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT) { // pass the pressed key @@ -192,7 +192,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) void CannedMessageModule::sendText(NodeNum dest, const char *message, bool wantReplies) { - MeshPacket *p = allocDataPacket(); + meshtastic_MeshPacket *p = allocDataPacket(); p->to = dest; p->want_ack = true; p->decoded.payload.size = strlen(message); @@ -360,9 +360,9 @@ int32_t CannedMessageModule::runOnce() this->freetext.substring(0, this->cursor) + this->payload + this->freetext.substring(this->cursor); } this->cursor += 1; - if (this->freetext.length() > Constants_DATA_PAYLOAD_LEN) { - this->cursor = Constants_DATA_PAYLOAD_LEN; - this->freetext = this->freetext.substring(0, Constants_DATA_PAYLOAD_LEN); + if (this->freetext.length() > meshtastic_Constants_DATA_PAYLOAD_LEN) { + this->cursor = meshtastic_Constants_DATA_PAYLOAD_LEN; + this->freetext = this->freetext.substring(0, meshtastic_Constants_DATA_PAYLOAD_LEN); } break; } @@ -398,7 +398,7 @@ const char *CannedMessageModule::getNodeName(NodeNum node) if (node == NODENUM_BROADCAST) { return "Broadcast"; } else { - NodeInfo *info = nodeDB.getNode(node); + meshtastic_NodeInfo *info = nodeDB.getNode(node); if (info != NULL) { return info->user.long_name; } else { @@ -457,7 +457,7 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st } display->drawStringf(0 + x, 0 + y, buffer, "To: %s", cannedMessageModule->getNodeName(this->dest)); // used chars right aligned - snprintf(buffer, sizeof(buffer), "%d left", Constants_DATA_PAYLOAD_LEN - this->freetext.length()); + snprintf(buffer, sizeof(buffer), "%d left", meshtastic_Constants_DATA_PAYLOAD_LEN - this->freetext.length()); display->drawString(x + display->getWidth() - display->getStringWidth(buffer), y + 0, buffer); if (this->destSelect) { display->drawString(x + display->getWidth() - display->getStringWidth(buffer) - 1, y + 0, buffer); @@ -483,8 +483,9 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st void CannedMessageModule::loadProtoForModule() { - if (!nodeDB.loadProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, sizeof(CannedMessageModuleConfig), - &CannedMessageModuleConfig_msg, &cannedMessageModuleConfig)) { + if (!nodeDB.loadProto(cannedMessagesConfigFile, meshtastic_CannedMessageModuleConfig_size, + sizeof(meshtastic_CannedMessageModuleConfig), &meshtastic_CannedMessageModuleConfig_msg, + &cannedMessageModuleConfig)) { installDefaultCannedMessageModuleConfig(); } } @@ -503,8 +504,8 @@ bool CannedMessageModule::saveProtoForModule() FS.mkdir("/prefs"); #endif - okay &= nodeDB.saveProto(cannedMessagesConfigFile, CannedMessageModuleConfig_size, &CannedMessageModuleConfig_msg, - &cannedMessageModuleConfig); + okay &= nodeDB.saveProto(cannedMessagesConfigFile, meshtastic_CannedMessageModuleConfig_size, + &meshtastic_CannedMessageModuleConfig_msg, &cannedMessageModuleConfig); return okay; } @@ -526,19 +527,20 @@ void CannedMessageModule::installDefaultCannedMessageModuleConfig() * @return AdminMessageHandleResult HANDLED if message was handled * HANDLED_WITH_RESULT if a result is also prepared. */ -AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, - AdminMessage *response) +AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const meshtastic_MeshPacket &mp, + meshtastic_AdminMessage *request, + meshtastic_AdminMessage *response) { AdminMessageHandleResult result; switch (request->which_payload_variant) { - case AdminMessage_get_canned_message_module_messages_request_tag: + case meshtastic_AdminMessage_get_canned_message_module_messages_request_tag: LOG_DEBUG("Client is getting radio canned messages\n"); this->handleGetCannedMessageModuleMessages(mp, response); result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; break; - case AdminMessage_set_canned_message_module_messages_tag: + case meshtastic_AdminMessage_set_canned_message_module_messages_tag: LOG_DEBUG("Client is setting radio canned messages\n"); this->handleSetCannedMessageModuleMessages(request->set_canned_message_module_messages); result = AdminMessageHandleResult::HANDLED; @@ -551,11 +553,12 @@ AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const return result; } -void CannedMessageModule::handleGetCannedMessageModuleMessages(const MeshPacket &req, AdminMessage *response) +void CannedMessageModule::handleGetCannedMessageModuleMessages(const meshtastic_MeshPacket &req, + meshtastic_AdminMessage *response) { LOG_DEBUG("*** handleGetCannedMessageModuleMessages\n"); if (req.decoded.want_response) { - response->which_payload_variant = AdminMessage_get_canned_message_module_messages_response_tag; + response->which_payload_variant = meshtastic_AdminMessage_get_canned_message_module_messages_response_tag; strncpy(response->get_canned_message_module_messages_response, cannedMessageModuleConfig.messages, sizeof(response->get_canned_message_module_messages_response)); } // Don't send anything if not instructed to. Better than asserting. diff --git a/src/modules/CannedMessageModule.h b/src/modules/CannedMessageModule.h index 2edef4655..5858a473c 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,45 +14,37 @@ 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(); void eventSelect(); - void handleGetCannedMessageModuleMessages(const MeshPacket &req, AdminMessage *response); + void handleGetCannedMessageModuleMessages(const meshtastic_MeshPacket &req, meshtastic_AdminMessage *response); void handleSetCannedMessageModuleMessages(const char *from_msg); 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,11 @@ 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 meshtastic_MeshPacket &mp, + meshtastic_AdminMessage *request, + meshtastic_AdminMessage *response) override; void loadProtoForModule(); bool saveProtoForModule(); @@ -76,11 +67,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.cpp b/src/modules/ExternalNotificationModule.cpp index 1e379b65c..3c931f3e2 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -27,7 +27,7 @@ #define ASCII_BELL 0x07 -RTTTLConfig rtttlConfig; +meshtastic_RTTTLConfig rtttlConfig; ExternalNotificationModule *externalNotificationModule; @@ -142,8 +142,8 @@ void ExternalNotificationModule::stopNow() } ExternalNotificationModule::ExternalNotificationModule() - : SinglePortModule("ExternalNotificationModule", PortNum_TEXT_MESSAGE_APP), concurrency::OSThread( - "ExternalNotificationModule") + : SinglePortModule("ExternalNotificationModule", meshtastic_PortNum_TEXT_MESSAGE_APP), concurrency::OSThread( + "ExternalNotificationModule") { /* Uncomment the preferences below if you want to use the module @@ -164,7 +164,8 @@ ExternalNotificationModule::ExternalNotificationModule() // moduleConfig.external_notification.nag_timeout = 300; if (moduleConfig.external_notification.enabled) { - if (!nodeDB.loadProto(rtttlConfigFile, RTTTLConfig_size, sizeof(RTTTLConfig), &RTTTLConfig_msg, &rtttlConfig)) { + if (!nodeDB.loadProto(rtttlConfigFile, meshtastic_RTTTLConfig_size, sizeof(meshtastic_RTTTLConfig), + &meshtastic_RTTTLConfig_msg, &rtttlConfig)) { memset(rtttlConfig.ringtone, 0, sizeof(rtttlConfig.ringtone)); strncpy(rtttlConfig.ringtone, "a:d=8,o=5,b=125:4d#6,a#,2d#6,16p,g#,4a#,4d#.,p,16g,16a#,d#6,a#,f6,2d#6,16p,c#.6,16c6,16a#,g#.,2a#", @@ -205,7 +206,7 @@ ExternalNotificationModule::ExternalNotificationModule() } } -ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) +ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshPacket &mp) { if (moduleConfig.external_notification.enabled) { @@ -319,19 +320,20 @@ ProcessMessage ExternalNotificationModule::handleReceived(const MeshPacket &mp) * @return AdminMessageHandleResult HANDLED if message was handled * HANDLED_WITH_RESULT if a result is also prepared. */ -AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, - AdminMessage *response) +AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule(const meshtastic_MeshPacket &mp, + meshtastic_AdminMessage *request, + meshtastic_AdminMessage *response) { AdminMessageHandleResult result; switch (request->which_payload_variant) { - case AdminMessage_get_ringtone_request_tag: + case meshtastic_AdminMessage_get_ringtone_request_tag: LOG_INFO("Client is getting ringtone\n"); this->handleGetRingtone(mp, response); result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; break; - case AdminMessage_set_ringtone_message_tag: + case meshtastic_AdminMessage_set_ringtone_message_tag: LOG_INFO("Client is setting ringtone\n"); this->handleSetRingtone(request->set_canned_message_module_messages); result = AdminMessageHandleResult::HANDLED; @@ -344,11 +346,11 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule return result; } -void ExternalNotificationModule::handleGetRingtone(const MeshPacket &req, AdminMessage *response) +void ExternalNotificationModule::handleGetRingtone(const meshtastic_MeshPacket &req, meshtastic_AdminMessage *response) { LOG_INFO("*** handleGetRingtone\n"); if (req.decoded.want_response) { - response->which_payload_variant = AdminMessage_get_ringtone_response_tag; + response->which_payload_variant = meshtastic_AdminMessage_get_ringtone_response_tag; strncpy(response->get_ringtone_response, rtttlConfig.ringtone, sizeof(response->get_ringtone_response)); } // Don't send anything if not instructed to. Better than asserting. } @@ -364,6 +366,6 @@ void ExternalNotificationModule::handleSetRingtone(const char *from_msg) } if (changed) { - nodeDB.saveProto(rtttlConfigFile, RTTTLConfig_size, &RTTTLConfig_msg, &rtttlConfig); + nodeDB.saveProto(rtttlConfigFile, meshtastic_RTTTLConfig_size, &meshtastic_RTTTLConfig_msg, &rtttlConfig); } } \ No newline at end of file diff --git a/src/modules/ExternalNotificationModule.h b/src/modules/ExternalNotificationModule.h index 097ae96b3..7d4f54c2f 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(); @@ -40,20 +40,23 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency: void stopNow(); - void handleGetRingtone(const MeshPacket &req, AdminMessage *response); + void handleGetRingtone(const meshtastic_MeshPacket &req, meshtastic_AdminMessage *response); void handleSetRingtone(const char *from_msg); 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; + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override; virtual int32_t runOnce() override; bool isNagging = false; - virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, AdminMessage *response) override; + virtual AdminMessageHandleResult handleAdminMessageForModule(const meshtastic_MeshPacket &mp, + meshtastic_AdminMessage *request, + meshtastic_AdminMessage *response) override; }; extern ExternalNotificationModule *externalNotificationModule; diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index cd873a466..e8481356b 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" @@ -33,51 +33,56 @@ */ void setupModules() { + if (config.device.role != meshtastic_Config_DeviceConfig_Role_REPEATER) { #if HAS_BUTTON - inputBroker = new InputBroker(); + inputBroker = new InputBroker(); #endif - adminModule = new AdminModule(); - nodeInfoModule = new NodeInfoModule(); - positionModule = new PositionModule(); - 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. + adminModule = new AdminModule(); + nodeInfoModule = new NodeInfoModule(); + positionModule = new PositionModule(); + waypointModule = new WaypointModule(); + textMessageModule = new TextMessageModule(); + traceRouteModule = new TraceRouteModule(); - new RemoteHardwareModule(); - new ReplyModule(); + // 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. + + new RemoteHardwareModule(); + new ReplyModule(); #if HAS_BUTTON - rotaryEncoderInterruptImpl1 = new RotaryEncoderInterruptImpl1(); - rotaryEncoderInterruptImpl1->init(); - upDownInterruptImpl1 = new UpDownInterruptImpl1(); - upDownInterruptImpl1->init(); - cardKbI2cImpl = new CardKbI2cImpl(); - cardKbI2cImpl->init(); + rotaryEncoderInterruptImpl1 = new RotaryEncoderInterruptImpl1(); + rotaryEncoderInterruptImpl1->init(); + upDownInterruptImpl1 = new UpDownInterruptImpl1(); + upDownInterruptImpl1->init(); + cardKbI2cImpl = new CardKbI2cImpl(); + cardKbI2cImpl->init(); #endif #if HAS_SCREEN - cannedMessageModule = new CannedMessageModule(); + cannedMessageModule = new CannedMessageModule(); #endif #if HAS_TELEMETRY - new DeviceTelemetryModule(); - new EnvironmentTelemetryModule(); + new DeviceTelemetryModule(); + new EnvironmentTelemetryModule(); #endif #if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) - new SerialModule(); + new SerialModule(); #endif #ifdef ARCH_ESP32 - // Only run on an esp32 based device. - audioModule = new AudioModule(); - externalNotificationModule = new ExternalNotificationModule(); + // Only run on an esp32 based device. + audioModule = new AudioModule(); + externalNotificationModule = new ExternalNotificationModule(); - storeForwardModule = new StoreForwardModule(); + storeForwardModule = new StoreForwardModule(); - new RangeTestModule(); + new RangeTestModule(); #elif defined(ARCH_NRF52) - externalNotificationModule = new ExternalNotificationModule(); + externalNotificationModule = new ExternalNotificationModule(); #endif - - // NOTE! This module must be added LAST because it likes to check for replies from other modules and avoid sending extra acks + } else { + adminModule = new AdminModule(); + traceRouteModule = new TraceRouteModule(); + } + // NOTE! This module must be added LAST because it likes to check for replies from other modules and avoid sending extra + // acks routingModule = new RoutingModule(); } diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index 5dc05cd95..e7ac3133f 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -8,7 +8,7 @@ NodeInfoModule *nodeInfoModule; -bool NodeInfoModule::handleReceivedProtobuf(const MeshPacket &mp, User *pptr) +bool NodeInfoModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_User *pptr) { auto p = *pptr; @@ -33,28 +33,29 @@ void NodeInfoModule::sendOurNodeInfo(NodeNum dest, bool wantReplies) if (prevPacketId) // if we wrap around to zero, we'll simply fail to cancel in that rare case (no big deal) service.cancelSending(prevPacketId); - MeshPacket *p = allocReply(); + meshtastic_MeshPacket *p = allocReply(); p->to = dest; p->decoded.want_response = wantReplies; - p->priority = MeshPacket_Priority_BACKGROUND; + p->priority = meshtastic_MeshPacket_Priority_BACKGROUND; prevPacketId = p->id; service.sendToMesh(p); } -MeshPacket *NodeInfoModule::allocReply() +meshtastic_MeshPacket *NodeInfoModule::allocReply() { - User &u = owner; + meshtastic_User &u = owner; LOG_INFO("sending owner %s/%s/%s\n", u.id, u.long_name, u.short_name); return allocDataProtobuf(u); } NodeInfoModule::NodeInfoModule() - : ProtobufModule("nodeinfo", PortNum_NODEINFO_APP, &User_msg), concurrency::OSThread("NodeInfoModule") + : ProtobufModule("nodeinfo", meshtastic_PortNum_NODEINFO_APP, &meshtastic_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..4645b06b4 100644 --- a/src/modules/NodeInfoModule.h +++ b/src/modules/NodeInfoModule.h @@ -4,18 +4,19 @@ /** * NodeInfo module for sending/receiving NodeInfos into the mesh */ -class NodeInfoModule : public ProtobufModule, private concurrency::OSThread +class NodeInfoModule : public ProtobufModule, private concurrency::OSThread { /// 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 */ @@ -26,11 +27,11 @@ class NodeInfoModule : public ProtobufModule, private concurrency::OSThrea @return true if you've guaranteed you've handled this message and no other handlers should be considered for it */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, User *p) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_User *p) override; /** 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. */ - virtual MeshPacket *allocReply() override; + virtual meshtastic_MeshPacket *allocReply() override; /** Does our periodic broadcast */ virtual int32_t runOnce() override; diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index 4d119043c..d923dad8a 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -10,13 +10,14 @@ PositionModule *positionModule; PositionModule::PositionModule() - : ProtobufModule("position", PortNum_POSITION_APP, &Position_msg), concurrency::OSThread("PositionModule") + : ProtobufModule("position", meshtastic_PortNum_POSITION_APP, &meshtastic_Position_msg), concurrency::OSThread( + "PositionModule") { isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others setIntervalFromNow(60 * 1000); // Send our initial position 60 seconds after we start (to give GPS time to setup) } -bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr) +bool PositionModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Position *pptr) { auto p = *pptr; @@ -33,10 +34,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; @@ -53,9 +54,9 @@ bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr return false; // Let others look at this message also if they want } -MeshPacket *PositionModule::allocReply() +meshtastic_MeshPacket *PositionModule::allocReply() { - NodeInfo *node = service.refreshMyNodeInfo(); // should guarantee there is now a position + meshtastic_NodeInfo *node = service.refreshMyNodeInfo(); // should guarantee there is now a position assert(node->has_position); node->position.seq_number++; @@ -65,44 +66,44 @@ MeshPacket *PositionModule::allocReply() uint32_t pos_flags = config.position.position_flags; // Populate a Position struct with ONLY the requested fields - Position p = Position_init_default; // Start with an empty structure + meshtastic_Position p = meshtastic_Position_init_default; // Start with an empty structure // lat/lon are unconditionally included - IF AVAILABLE! p.latitude_i = node->position.latitude_i; p.longitude_i = node->position.longitude_i; p.time = node->position.time; - if (pos_flags & Config_PositionConfig_PositionFlags_ALTITUDE) { - if (pos_flags & Config_PositionConfig_PositionFlags_ALTITUDE_MSL) + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_ALTITUDE) { + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_ALTITUDE_MSL) p.altitude = node->position.altitude; else p.altitude_hae = node->position.altitude_hae; - if (pos_flags & Config_PositionConfig_PositionFlags_GEOIDAL_SEPARATION) + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_GEOIDAL_SEPARATION) p.altitude_geoidal_separation = node->position.altitude_geoidal_separation; } - if (pos_flags & Config_PositionConfig_PositionFlags_DOP) { - if (pos_flags & Config_PositionConfig_PositionFlags_HVDOP) { + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_DOP) { + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_HVDOP) { p.HDOP = node->position.HDOP; p.VDOP = node->position.VDOP; } else p.PDOP = node->position.PDOP; } - if (pos_flags & Config_PositionConfig_PositionFlags_SATINVIEW) + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_SATINVIEW) p.sats_in_view = node->position.sats_in_view; - if (pos_flags & Config_PositionConfig_PositionFlags_TIMESTAMP) + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_TIMESTAMP) p.timestamp = node->position.timestamp; - if (pos_flags & Config_PositionConfig_PositionFlags_SEQ_NO) + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_SEQ_NO) p.seq_number = node->position.seq_number; - if (pos_flags & Config_PositionConfig_PositionFlags_HEADING) + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_HEADING) p.ground_track = node->position.ground_track; - if (pos_flags & Config_PositionConfig_PositionFlags_SPEED) + if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_SPEED) p.ground_speed = node->position.ground_speed; // Strip out any time information before sending packets to other nodes - to keep the wire size small (and because other @@ -125,10 +126,13 @@ void PositionModule::sendOurPosition(NodeNum dest, bool wantReplies) if (prevPacketId) // if we wrap around to zero, we'll simply fail to cancel in that rare case (no big deal) service.cancelSending(prevPacketId); - MeshPacket *p = allocReply(); + meshtastic_MeshPacket *p = allocReply(); p->to = dest; p->decoded.want_response = wantReplies; - p->priority = MeshPacket_Priority_BACKGROUND; + if (config.device.role == meshtastic_Config_DeviceConfig_Role_TRACKER) + p->priority = meshtastic_MeshPacket_Priority_RELIABLE; + else + p->priority = meshtastic_MeshPacket_Priority_BACKGROUND; prevPacketId = p->id; service.sendToMesh(p, RX_SRC_LOCAL, true); @@ -136,11 +140,12 @@ void PositionModule::sendOurPosition(NodeNum dest, bool wantReplies) int32_t PositionModule::runOnce() { - NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); + meshtastic_NodeInfo *node = nodeDB.getNode(nodeDB.getNodeNum()); // 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. @@ -159,13 +164,12 @@ int32_t PositionModule::runOnce() sendOurPosition(NODENUM_BROADCAST, requestReplies); } } - } else if (config.position.position_broadcast_smart_enabled) { // Only send packets if the channel is less than 25% utilized. if (airTime->isTxAllowedChannelUtil(true)) { - NodeInfo *node2 = service.refreshMyNodeInfo(); // should guarantee there is now a position + meshtastic_NodeInfo *node2 = service.refreshMyNodeInfo(); // should guarantee there is now a position if (node2->has_position && (node2->position.latitude_i != 0 || node2->position.longitude_i != 0)) { // The minimum distance to travel before we are able to send a new position packet. @@ -193,7 +197,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..8e9c37087 100644 --- a/src/modules/PositionModule.h +++ b/src/modules/PositionModule.h @@ -5,7 +5,7 @@ /** * Position module for sending/receiving positions into the mesh */ -class PositionModule : public ProtobufModule, private concurrency::OSThread +class PositionModule : public ProtobufModule, private concurrency::OSThread { /// The id of the last packet we sent, to allow us to cancel it if we make something fresher PacketId prevPacketId = 0; @@ -25,23 +25,22 @@ 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 */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, Position *p) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Position *p) override; /** 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. */ - virtual MeshPacket *allocReply() override; + virtual meshtastic_MeshPacket *allocReply() override; /** Does our periodic broadcast */ virtual int32_t runOnce() override; diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 8e0031a57..fb455af44 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; @@ -47,19 +47,19 @@ static uint64_t digitalReads(uint64_t mask) } RemoteHardwareModule::RemoteHardwareModule() - : ProtobufModule("remotehardware", PortNum_REMOTE_HARDWARE_APP, &HardwareMessage_msg), concurrency::OSThread( - "RemoteHardwareModule") + : ProtobufModule("remotehardware", meshtastic_PortNum_REMOTE_HARDWARE_APP, &meshtastic_HardwareMessage_msg), + concurrency::OSThread("RemoteHardwareModule") { } -bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, HardwareMessage *pptr) +bool RemoteHardwareModule::handleReceivedProtobuf(const meshtastic_MeshPacket &req, meshtastic_HardwareMessage *pptr) { if (moduleConfig.remote_hardware.enabled) { auto p = *pptr; LOG_INFO("Received RemoteHardware typ=%d\n", p.type); switch (p.type) { - case HardwareMessage_Type_WRITE_GPIOS: + case meshtastic_HardwareMessage_Type_WRITE_GPIOS: // Print notification to LCD screen screen->print("Write GPIOs\n"); @@ -73,7 +73,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar break; - case HardwareMessage_Type_READ_GPIOS: { + case meshtastic_HardwareMessage_Type_READ_GPIOS: { // Print notification to LCD screen if (screen) screen->print("Read GPIOs\n"); @@ -81,27 +81,28 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar uint64_t res = digitalReads(p.gpio_mask); // Send the reply - HardwareMessage r = HardwareMessage_init_default; - r.type = HardwareMessage_Type_READ_GPIOS_REPLY; + meshtastic_HardwareMessage r = meshtastic_HardwareMessage_init_default; + r.type = meshtastic_HardwareMessage_Type_READ_GPIOS_REPLY; r.gpio_value = res; r.gpio_mask = p.gpio_mask; - MeshPacket *p2 = allocDataProtobuf(r); + meshtastic_MeshPacket *p2 = allocDataProtobuf(r); setReplyTo(p2, req); myReply = p2; break; } - case HardwareMessage_Type_WATCH_GPIOS: { + case meshtastic_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; } - case HardwareMessage_Type_READ_GPIOS_REPLY: - case HardwareMessage_Type_GPIOS_CHANGED: + case meshtastic_HardwareMessage_Type_READ_GPIOS_REPLY: + case meshtastic_HardwareMessage_Type_GPIOS_CHANGED: break; // Ignore - we might see our own replies default: @@ -126,10 +127,10 @@ int32_t RemoteHardwareModule::runOnce() LOG_INFO("Broadcasting GPIOS 0x%llx changed!\n", curVal); // Something changed! Tell the world with a broadcast message - HardwareMessage r = HardwareMessage_init_default; - r.type = HardwareMessage_Type_GPIOS_CHANGED; + meshtastic_HardwareMessage r = meshtastic_HardwareMessage_init_default; + r.type = meshtastic_HardwareMessage_Type_GPIOS_CHANGED; r.gpio_value = curVal; - MeshPacket *p = allocDataProtobuf(r); + meshtastic_MeshPacket *p = allocDataProtobuf(r); service.sendToMesh(p); } } diff --git a/src/modules/RemoteHardwareModule.h b/src/modules/RemoteHardwareModule.h index 69733a87d..dd39f5b69 100644 --- a/src/modules/RemoteHardwareModule.h +++ b/src/modules/RemoteHardwareModule.h @@ -6,7 +6,7 @@ /** * A module that provides easy low-level remote access to device hardware. */ -class RemoteHardwareModule : public ProtobufModule, private concurrency::OSThread +class RemoteHardwareModule : public ProtobufModule, private concurrency::OSThread { /// The current set of GPIOs we've been asked to watch for changes uint64_t watchGpios = 0; @@ -28,7 +28,7 @@ class RemoteHardwareModule : public ProtobufModule, private con @return true if you've guaranteed you've handled this message and no other handlers should be considered for it */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, HardwareMessage *p) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_HardwareMessage *p) override; /** * Periodically read the gpios we have been asked to WATCH, if they have changed, diff --git a/src/modules/ReplyModule.cpp b/src/modules/ReplyModule.cpp index bf4e691fb..3bfad28ad 100644 --- a/src/modules/ReplyModule.cpp +++ b/src/modules/ReplyModule.cpp @@ -1,11 +1,11 @@ -#include "configuration.h" #include "ReplyModule.h" #include "MeshService.h" +#include "configuration.h" #include "main.h" #include -MeshPacket *ReplyModule::allocReply() +meshtastic_MeshPacket *ReplyModule::allocReply() { assert(currentRequest); // should always be !NULL auto req = *currentRequest; @@ -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..86d4172ed 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. */ @@ -11,12 +10,11 @@ class ReplyModule : public SinglePortModule /** Constructor * name is for debugging output */ - ReplyModule() : SinglePortModule("reply", PortNum_REPLY_APP) {} + ReplyModule() : SinglePortModule("reply", meshtastic_PortNum_REPLY_APP) {} protected: - /** For reply module we do all of our processing in the (normally optional) * want_replies handling - */ - virtual MeshPacket *allocReply() override; + */ + virtual meshtastic_MeshPacket *allocReply() override; }; diff --git a/src/modules/RoutingModule.cpp b/src/modules/RoutingModule.cpp index 8c4eeb4ff..f91d32a20 100644 --- a/src/modules/RoutingModule.cpp +++ b/src/modules/RoutingModule.cpp @@ -1,13 +1,13 @@ -#include "configuration.h" #include "RoutingModule.h" #include "MeshService.h" #include "NodeDB.h" #include "Router.h" +#include "configuration.h" #include "main.h" RoutingModule *routingModule; -bool RoutingModule::handleReceivedProtobuf(const MeshPacket &mp, Routing *r) +bool RoutingModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Routing *r) { printPacket("Routing sniffing", &mp); router->sniffReceived(&mp, r); @@ -22,26 +22,28 @@ bool RoutingModule::handleReceivedProtobuf(const MeshPacket &mp, Routing *r) return false; // Let others look at this message also if they want } -MeshPacket *RoutingModule::allocReply() +meshtastic_MeshPacket *RoutingModule::allocReply() { + if (config.device.role == meshtastic_Config_DeviceConfig_Role_REPEATER) + return NULL; assert(currentRequest); // We only consider making replies if the request was a legit routing packet (not just something we were sniffing) - if (currentRequest->decoded.portnum == PortNum_ROUTING_APP) { + if (currentRequest->decoded.portnum == meshtastic_PortNum_ROUTING_APP) { assert(0); // 1.2 refactoring fixme, Not sure if anything needs this yet? // return allocDataProtobuf(u); } return NULL; } -void RoutingModule::sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex) +void RoutingModule::sendAckNak(meshtastic_Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex) { auto p = allocAckNak(err, to, idFrom, chIndex); router->sendLocal(p); // we sometimes send directly to the local node } -RoutingModule::RoutingModule() : ProtobufModule("routing", PortNum_ROUTING_APP, &Routing_msg) +RoutingModule::RoutingModule() : ProtobufModule("routing", meshtastic_PortNum_ROUTING_APP, &meshtastic_Routing_msg) { isPromiscuous = true; encryptedOk = true; diff --git a/src/modules/RoutingModule.h b/src/modules/RoutingModule.h index b2840ff58..06e76cfb4 100644 --- a/src/modules/RoutingModule.h +++ b/src/modules/RoutingModule.h @@ -1,11 +1,11 @@ #pragma once -#include "ProtobufModule.h" #include "Channels.h" +#include "ProtobufModule.h" /** * Routing module for router control messages */ -class RoutingModule : public ProtobufModule +class RoutingModule : public ProtobufModule { public: /** Constructor @@ -13,7 +13,7 @@ class RoutingModule : public ProtobufModule */ RoutingModule(); - void sendAckNak(Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex); + void sendAckNak(meshtastic_Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex); protected: friend class Router; @@ -22,14 +22,14 @@ class RoutingModule : public ProtobufModule @return true if you've guaranteed you've handled this message and no other handlers should be considered for it */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, Routing *p) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Routing *p) override; /** 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. */ - virtual MeshPacket *allocReply() override; + virtual meshtastic_MeshPacket *allocReply() override; /// Override wantPacket to say we want to see all packets, not just those for our port number - virtual bool wantPacket(const MeshPacket *p) override { return true; } + virtual bool wantPacket(const meshtastic_MeshPacket *p) override { return true; } }; extern RoutingModule *routingModule; diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index 4383ecaab..5637f7eb1 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 @@ -12,7 +12,7 @@ A simple interface to send messages over the mesh network by sending strings over a serial port. - Default is to use RX GPIO 16 and TX GPIO 17. + There are no PIN defaults, you have to enable the second serial port yourself. Need help with this module? Post your question on the Meshtastic Discourse: https://meshtastic.discourse.group @@ -46,8 +46,6 @@ #if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2) -#define RXD2 16 -#define TXD2 17 #define RX_BUFFER 128 #define TIMEOUT 250 #define BAUD 38400 @@ -61,25 +59,24 @@ SerialModuleRadio *serialModuleRadio; SerialModule::SerialModule() : StreamAPI(&Serial2), concurrency::OSThread("SerialModule") {} -char serialBytes[Constants_DATA_PAYLOAD_LEN]; +char serialBytes[meshtastic_Constants_DATA_PAYLOAD_LEN]; 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 meshtastic_ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG: + ourPortNum = meshtastic_PortNum_TEXT_MESSAGE_APP; + break; + case meshtastic_ModuleConfig_SerialConfig_Serial_Mode_NMEA: + ourPortNum = meshtastic_PortNum_POSITION_APP; + break; + default: + ourPortNum = meshtastic_PortNum_SERIAL_APP; + // restrict to the serial channel for rx + boundChannel = Channels::serialChannel; + break; } } @@ -103,7 +100,7 @@ int32_t SerialModule::runOnce() // moduleConfig.serial.timeout = 1000; // moduleConfig.serial.echo = 1; - if (moduleConfig.serial.enabled) { + if (moduleConfig.serial.enabled && moduleConfig.serial.rxd && moduleConfig.serial.txd) { if (firstTime) { @@ -112,63 +109,60 @@ int32_t SerialModule::runOnce() uint32_t baud = 0; - if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT) { + if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_DEFAULT) { baud = 38400; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_110) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_110) { baud = 110; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_300) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_300) { baud = 300; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_600) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_600) { baud = 600; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_1200) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_1200) { baud = 1200; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_2400) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_2400) { baud = 2400; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_4800) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_4800) { baud = 4800; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_9600) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_9600) { baud = 9600; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_19200) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_19200) { baud = 19200; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_38400) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_38400) { baud = 38400; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_57600) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_57600) { baud = 57600; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_115200) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_115200) { baud = 115200; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_230400) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_230400) { baud = 230400; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_460800) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_460800) { baud = 460800; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_576000) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_576000) { baud = 576000; - } else if (moduleConfig.serial.baud == ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600) { + } else if (moduleConfig.serial.baud == meshtastic_ModuleConfig_SerialConfig_Serial_Baud_BAUD_921600) { baud = 921600; } -#ifdef ARCH_ESP32 +#ifdef ARCH_ESP32 Serial2.setRxBufferSize(RX_BUFFER); if (moduleConfig.serial.rxd && moduleConfig.serial.txd) { Serial2.begin(baud, SERIAL_8N1, moduleConfig.serial.rxd, moduleConfig.serial.txd); - - } else { - Serial2.begin(baud, SERIAL_8N1, RXD2, TXD2); } #else if (moduleConfig.serial.rxd && moduleConfig.serial.txd) @@ -188,15 +182,15 @@ int32_t SerialModule::runOnce() firstTime = 0; // in API mode send rebooted sequence - if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { + if (moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_PROTO) { emitRebooted(); } } else { - if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { + if (moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_PROTO) { return runOncePart(); - } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_NMEA) { + } else if (moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_NMEA) { // in NMEA mode send out GGA every 2 seconds, Don't read from Port if (millis() - lastNmeaTime > 2000) { lastNmeaTime = millis(); @@ -205,7 +199,7 @@ int32_t SerialModule::runOnce() } } else { while (Serial2.available()) { - serialPayloadSize = Serial2.readBytes(serialBytes, Constants_DATA_PAYLOAD_LEN); + serialPayloadSize = Serial2.readBytes(serialBytes, meshtastic_Constants_DATA_PAYLOAD_LEN); serialModuleRadio->sendPayload(); } } @@ -217,7 +211,7 @@ int32_t SerialModule::runOnce() } } -MeshPacket *SerialModuleRadio::allocReply() +meshtastic_MeshPacket *SerialModuleRadio::allocReply() { auto reply = allocDataPacket(); // Allocate a packet for sending @@ -226,8 +220,8 @@ MeshPacket *SerialModuleRadio::allocReply() void SerialModuleRadio::sendPayload(NodeNum dest, bool wantReplies) { - Channel *ch = (boundChannel != NULL) ? &channels.getByName(boundChannel) : NULL; - MeshPacket *p = allocReply(); + meshtastic_Channel *ch = (boundChannel != NULL) ? &channels.getByName(boundChannel) : NULL; + meshtastic_MeshPacket *p = allocReply(); p->to = dest; if (ch != NULL) { p->channel = ch->index; @@ -242,10 +236,10 @@ void SerialModuleRadio::sendPayload(NodeNum dest, bool wantReplies) service.sendToMesh(p); } -ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) +ProcessMessage SerialModuleRadio::handleReceived(const meshtastic_MeshPacket &mp) { if (moduleConfig.serial.enabled) { - if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_PROTO) { + if (moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_PROTO) { // in API mode we don't care about stuff from radio. return ProcessMessage::CONTINUE; } @@ -274,22 +268,22 @@ ProcessMessage SerialModuleRadio::handleReceived(const MeshPacket &mp) } else { - if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_DEFAULT || - moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_SIMPLE) { + if (moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_DEFAULT || + moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_SIMPLE) { Serial2.printf("%s", p.payload.bytes); - } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG) { - NodeInfo *node = nodeDB.getNode(getFrom(&mp)); + } else if (moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG) { + meshtastic_NodeInfo *node = nodeDB.getNode(getFrom(&mp)); String sender = (node && node->has_user) ? node->user.short_name : "???"; Serial2.println(); Serial2.printf("%s: %s", sender, p.payload.bytes); Serial2.println(); - } else if (moduleConfig.serial.mode == ModuleConfig_SerialConfig_Serial_Mode_NMEA) { + } else if (moduleConfig.serial.mode == meshtastic_ModuleConfig_SerialConfig_Serial_Mode_NMEA) { // Decode the Payload some more - Position scratch; - Position *decoded = NULL; - if (mp.which_payload_variant == MeshPacket_decoded_tag && mp.decoded.portnum == ourPortNum) { + meshtastic_Position scratch; + meshtastic_Position *decoded = NULL; + if (mp.which_payload_variant == meshtastic_MeshPacket_decoded_tag && mp.decoded.portnum == ourPortNum) { memset(&scratch, 0, sizeof(scratch)); - if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &Position_msg, &scratch)) { + if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Position_msg, &scratch)) { decoded = &scratch; } // send position packet as WPL to the serial port diff --git a/src/modules/SerialModule.h b/src/modules/SerialModule.h index c853263b6..8c53d2064 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) @@ -46,27 +46,27 @@ class SerialModuleRadio : public MeshModule void sendPayload(NodeNum dest = NODENUM_BROADCAST, bool wantReplies = false); protected: - virtual MeshPacket *allocReply() override; + virtual meshtastic_MeshPacket *allocReply() override; /** 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; + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override; - PortNum ourPortNum; + meshtastic_PortNum ourPortNum; - virtual bool wantPacket(const MeshPacket *p) override { return p->decoded.portnum == ourPortNum; } + virtual bool wantPacket(const meshtastic_MeshPacket *p) override { return p->decoded.portnum == ourPortNum; } - MeshPacket *allocDataPacket() + meshtastic_MeshPacket *allocDataPacket() { // Update our local node info with our position (even if we don't decide to update anyone else) - MeshPacket *p = router->allocForSending(); + meshtastic_MeshPacket *p = router->allocForSending(); p->decoded.portnum = ourPortNum; return p; } - }; extern SerialModuleRadio *serialModuleRadio; diff --git a/src/modules/Telemetry/DeviceTelemetry.cpp b/src/modules/Telemetry/DeviceTelemetry.cpp index 3821ea445..630de2933 100644 --- a/src/modules/Telemetry/DeviceTelemetry.cpp +++ b/src/modules/Telemetry/DeviceTelemetry.cpp @@ -26,9 +26,9 @@ int32_t DeviceTelemetryModule::runOnce() return sendToPhoneIntervalMs; } -bool DeviceTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Telemetry *t) +bool DeviceTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Telemetry *t) { - if (t->which_variant == Telemetry_device_metrics_tag) { + if (t->which_variant == meshtastic_Telemetry_device_metrics_tag) { const char *sender = getSenderShortName(mp); LOG_INFO("(Received from %s): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", sender, @@ -44,10 +44,10 @@ bool DeviceTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Telemet bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) { - Telemetry t; + meshtastic_Telemetry t; t.time = getTime(); - t.which_variant = Telemetry_device_metrics_tag; + t.which_variant = meshtastic_Telemetry_device_metrics_tag; t.variant.device_metrics.air_util_tx = myNodeInfo.air_util_tx; t.variant.device_metrics.battery_level = powerStatus->getBatteryChargePercent(); @@ -58,10 +58,10 @@ bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) t.variant.device_metrics.air_util_tx, t.variant.device_metrics.channel_utilization, t.variant.device_metrics.battery_level, t.variant.device_metrics.voltage); - MeshPacket *p = allocDataProtobuf(t); + meshtastic_MeshPacket *p = allocDataProtobuf(t); p->to = dest; p->decoded.want_response = false; - p->priority = MeshPacket_Priority_MIN; + p->priority = meshtastic_MeshPacket_Priority_MIN; lastMeasurementPacket = packetPool.allocCopy(*p); nodeDB.updateTelemetry(nodeDB.getNodeNum(), t, RX_SRC_LOCAL); diff --git a/src/modules/Telemetry/DeviceTelemetry.h b/src/modules/Telemetry/DeviceTelemetry.h index 11506c71f..94641f04e 100644 --- a/src/modules/Telemetry/DeviceTelemetry.h +++ b/src/modules/Telemetry/DeviceTelemetry.h @@ -5,11 +5,12 @@ #include #include -class DeviceTelemetryModule : private concurrency::OSThread, public ProtobufModule +class DeviceTelemetryModule : private concurrency::OSThread, public ProtobufModule { public: DeviceTelemetryModule() - : concurrency::OSThread("DeviceTelemetryModule"), ProtobufModule("DeviceTelemetry", PortNum_TELEMETRY_APP, &Telemetry_msg) + : concurrency::OSThread("DeviceTelemetryModule"), + ProtobufModule("DeviceTelemetry", meshtastic_PortNum_TELEMETRY_APP, &meshtastic_Telemetry_msg) { lastMeasurementPacket = nullptr; setIntervalFromNow(10 * 1000); @@ -20,7 +21,7 @@ class DeviceTelemetryModule : private concurrency::OSThread, public ProtobufModu /** 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 */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, Telemetry *p) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Telemetry *p) override; virtual int32_t runOnce() override; /** * Send our Telemetry into the mesh @@ -30,5 +31,5 @@ class DeviceTelemetryModule : private concurrency::OSThread, public ProtobufModu private: uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute uint32_t lastSentToMesh = 0; - const MeshPacket *lastMeasurementPacket; + const meshtastic_MeshPacket *lastMeasurementPacket; }; diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index dce243b83..ae4f9e648 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -118,7 +118,7 @@ int32_t EnvironmentTelemetryModule::runOnce() #endif } -uint32_t GetTimeSinceMeshPacket(const MeshPacket *mp) +uint32_t GetTimeSinceMeshPacket(const meshtastic_MeshPacket *mp) { uint32_t now = getTime(); @@ -151,13 +151,13 @@ void EnvironmentTelemetryModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiSt return; } - Telemetry lastMeasurement; + meshtastic_Telemetry lastMeasurement; uint32_t agoSecs = GetTimeSinceMeshPacket(lastMeasurementPacket); const char *lastSender = getSenderShortName(*lastMeasurementPacket); auto &p = lastMeasurementPacket->decoded; - if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, &Telemetry_msg, &lastMeasurement)) { + if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Telemetry_msg, &lastMeasurement)) { display->setFont(FONT_SMALL); display->drawString(x, y += fontHeight(FONT_MEDIUM), "Measurement Error"); LOG_ERROR("Unable to decode last packet"); @@ -182,9 +182,9 @@ void EnvironmentTelemetryModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiSt String(lastMeasurement.variant.environment_metrics.current, 0) + "mA"); } -bool EnvironmentTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Telemetry *t) +bool EnvironmentTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Telemetry *t) { - if (t->which_variant == Telemetry_environment_metrics_tag) { + if (t->which_variant == meshtastic_Telemetry_environment_metrics_tag) { const char *sender = getSenderShortName(mp); LOG_INFO("(Received from %s): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, " @@ -201,9 +201,9 @@ bool EnvironmentTelemetryModule::handleReceivedProtobuf(const MeshPacket &mp, Te bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) { - Telemetry m; + meshtastic_Telemetry m; m.time = getTime(); - m.which_variant = Telemetry_environment_metrics_tag; + m.which_variant = meshtastic_Telemetry_environment_metrics_tag; m.variant.environment_metrics.barometric_pressure = 0; m.variant.environment_metrics.current = 0; @@ -239,10 +239,10 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) sensor_read_error_count = 0; - MeshPacket *p = allocDataProtobuf(m); + meshtastic_MeshPacket *p = allocDataProtobuf(m); p->to = dest; p->decoded.want_response = false; - p->priority = MeshPacket_Priority_MIN; + p->priority = meshtastic_MeshPacket_Priority_MIN; lastMeasurementPacket = packetPool.allocCopy(*p); if (phoneOnly) { diff --git a/src/modules/Telemetry/EnvironmentTelemetry.h b/src/modules/Telemetry/EnvironmentTelemetry.h index 5dce19c57..69ef29edb 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.h +++ b/src/modules/Telemetry/EnvironmentTelemetry.h @@ -5,12 +5,12 @@ #include #include -class EnvironmentTelemetryModule : private concurrency::OSThread, public ProtobufModule +class EnvironmentTelemetryModule : private concurrency::OSThread, public ProtobufModule { public: EnvironmentTelemetryModule() : concurrency::OSThread("EnvironmentTelemetryModule"), - ProtobufModule("EnvironmentTelemetry", PortNum_TELEMETRY_APP, &Telemetry_msg) + ProtobufModule("EnvironmentTelemetry", meshtastic_PortNum_TELEMETRY_APP, &meshtastic_Telemetry_msg) { lastMeasurementPacket = nullptr; setIntervalFromNow(10 * 1000); @@ -26,7 +26,7 @@ class EnvironmentTelemetryModule : private concurrency::OSThread, public Protobu /** 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 */ - virtual bool handleReceivedProtobuf(const MeshPacket &mp, Telemetry *p) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Telemetry *p) override; virtual int32_t runOnce() override; /** * Send our Telemetry into the mesh @@ -36,7 +36,7 @@ class EnvironmentTelemetryModule : private concurrency::OSThread, public Protobu private: float CelsiusToFahrenheit(float c); bool firstTime = 1; - const MeshPacket *lastMeasurementPacket; + const meshtastic_MeshPacket *lastMeasurementPacket; uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute uint32_t lastSentToMesh = 0; uint32_t sensor_read_error_count = 0; diff --git a/src/modules/Telemetry/Sensor/BME280Sensor.cpp b/src/modules/Telemetry/Sensor/BME280Sensor.cpp index 6c173eaec..7bc65a418 100644 --- a/src/modules/Telemetry/Sensor/BME280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME280Sensor.cpp @@ -5,7 +5,7 @@ #include #include -BME280Sensor::BME280Sensor() : TelemetrySensor(TelemetrySensorType_BME280, "BME280") {} +BME280Sensor::BME280Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_BME280, "BME280") {} int32_t BME280Sensor::runOnce() { @@ -26,7 +26,7 @@ int32_t BME280Sensor::runOnce() void BME280Sensor::setup() {} -bool BME280Sensor::getMetrics(Telemetry *measurement) +bool BME280Sensor::getMetrics(meshtastic_Telemetry *measurement) { LOG_DEBUG("BME280Sensor::getMetrics\n"); bme280.takeForcedMeasurement(); diff --git a/src/modules/Telemetry/Sensor/BME280Sensor.h b/src/modules/Telemetry/Sensor/BME280Sensor.h index c75b9ef59..780dcdb61 100644 --- a/src/modules/Telemetry/Sensor/BME280Sensor.h +++ b/src/modules/Telemetry/Sensor/BME280Sensor.h @@ -13,5 +13,5 @@ class BME280Sensor : virtual public TelemetrySensor public: BME280Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/BME680Sensor.cpp b/src/modules/Telemetry/Sensor/BME680Sensor.cpp index e3266450a..f05246d52 100644 --- a/src/modules/Telemetry/Sensor/BME680Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME680Sensor.cpp @@ -4,7 +4,7 @@ #include "configuration.h" #include -BME680Sensor::BME680Sensor() : TelemetrySensor(TelemetrySensorType_BME680, "BME680") {} +BME680Sensor::BME680Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_BME680, "BME680") {} int32_t BME680Sensor::runOnce() { @@ -19,7 +19,7 @@ int32_t BME680Sensor::runOnce() void BME680Sensor::setup() {} -bool BME680Sensor::getMetrics(Telemetry *measurement) +bool BME680Sensor::getMetrics(meshtastic_Telemetry *measurement) { bme680.performReading(); measurement->variant.environment_metrics.temperature = bme680.temperature; diff --git a/src/modules/Telemetry/Sensor/BME680Sensor.h b/src/modules/Telemetry/Sensor/BME680Sensor.h index e66eba75c..d59374803 100644 --- a/src/modules/Telemetry/Sensor/BME680Sensor.h +++ b/src/modules/Telemetry/Sensor/BME680Sensor.h @@ -13,5 +13,5 @@ class BME680Sensor : virtual public TelemetrySensor public: BME680Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp index 267656c4c..c0b5625de 100644 --- a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp @@ -5,7 +5,7 @@ #include #include -BMP280Sensor::BMP280Sensor() : TelemetrySensor(TelemetrySensorType_BMP280, "BMP280") {} +BMP280Sensor::BMP280Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_BMP280, "BMP280") {} int32_t BMP280Sensor::runOnce() { @@ -25,7 +25,7 @@ int32_t BMP280Sensor::runOnce() void BMP280Sensor::setup() {} -bool BMP280Sensor::getMetrics(Telemetry *measurement) +bool BMP280Sensor::getMetrics(meshtastic_Telemetry *measurement) { LOG_DEBUG("BMP280Sensor::getMetrics\n"); bmp280.takeForcedMeasurement(); diff --git a/src/modules/Telemetry/Sensor/BMP280Sensor.h b/src/modules/Telemetry/Sensor/BMP280Sensor.h index 769f4e4ba..cc8c0b9da 100644 --- a/src/modules/Telemetry/Sensor/BMP280Sensor.h +++ b/src/modules/Telemetry/Sensor/BMP280Sensor.h @@ -13,5 +13,5 @@ class BMP280Sensor : virtual public TelemetrySensor public: BMP280Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/INA219Sensor.cpp b/src/modules/Telemetry/Sensor/INA219Sensor.cpp index 69a67ad4b..bffa1e367 100644 --- a/src/modules/Telemetry/Sensor/INA219Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA219Sensor.cpp @@ -4,7 +4,7 @@ #include "configuration.h" #include -INA219Sensor::INA219Sensor() : TelemetrySensor(TelemetrySensorType_INA219, "INA219") {} +INA219Sensor::INA219Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_INA219, "INA219") {} int32_t INA219Sensor::runOnce() { @@ -19,7 +19,7 @@ int32_t INA219Sensor::runOnce() void INA219Sensor::setup() {} -bool INA219Sensor::getMetrics(Telemetry *measurement) +bool INA219Sensor::getMetrics(meshtastic_Telemetry *measurement) { measurement->variant.environment_metrics.voltage = ina219.getBusVoltage_V(); measurement->variant.environment_metrics.current = ina219.getCurrent_mA(); diff --git a/src/modules/Telemetry/Sensor/INA219Sensor.h b/src/modules/Telemetry/Sensor/INA219Sensor.h index 7288dac8a..dc6c0a5af 100644 --- a/src/modules/Telemetry/Sensor/INA219Sensor.h +++ b/src/modules/Telemetry/Sensor/INA219Sensor.h @@ -13,5 +13,5 @@ class INA219Sensor : virtual public TelemetrySensor public: INA219Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/INA260Sensor.cpp b/src/modules/Telemetry/Sensor/INA260Sensor.cpp index d69d25a75..ee0256e62 100644 --- a/src/modules/Telemetry/Sensor/INA260Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA260Sensor.cpp @@ -4,7 +4,7 @@ #include "configuration.h" #include -INA260Sensor::INA260Sensor() : TelemetrySensor(TelemetrySensorType_INA260, "INA260") {} +INA260Sensor::INA260Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_INA260, "INA260") {} int32_t INA260Sensor::runOnce() { @@ -18,7 +18,7 @@ int32_t INA260Sensor::runOnce() void INA260Sensor::setup() {} -bool INA260Sensor::getMetrics(Telemetry *measurement) +bool INA260Sensor::getMetrics(meshtastic_Telemetry *measurement) { // mV conversion to V measurement->variant.environment_metrics.voltage = ina260.readBusVoltage() / 1000; diff --git a/src/modules/Telemetry/Sensor/INA260Sensor.h b/src/modules/Telemetry/Sensor/INA260Sensor.h index de1fe0ad7..1dcb596e6 100644 --- a/src/modules/Telemetry/Sensor/INA260Sensor.h +++ b/src/modules/Telemetry/Sensor/INA260Sensor.h @@ -13,5 +13,5 @@ class INA260Sensor : virtual public TelemetrySensor public: INA260Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp index ac77bdb40..05f940656 100644 --- a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp +++ b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp @@ -5,7 +5,7 @@ #include #include -LPS22HBSensor::LPS22HBSensor() : TelemetrySensor(TelemetrySensorType_LPS22, "LPS22HB") {} +LPS22HBSensor::LPS22HBSensor() : TelemetrySensor(meshtastic_TelemetrySensorType_LPS22, "LPS22HB") {} int32_t LPS22HBSensor::runOnce() { @@ -22,7 +22,7 @@ void LPS22HBSensor::setup() lps22hb.setDataRate(LPS22_RATE_10_HZ); } -bool LPS22HBSensor::getMetrics(Telemetry *measurement) +bool LPS22HBSensor::getMetrics(meshtastic_Telemetry *measurement) { sensors_event_t temp; sensors_event_t pressure; diff --git a/src/modules/Telemetry/Sensor/LPS22HBSensor.h b/src/modules/Telemetry/Sensor/LPS22HBSensor.h index 7472950b8..556d161c4 100644 --- a/src/modules/Telemetry/Sensor/LPS22HBSensor.h +++ b/src/modules/Telemetry/Sensor/LPS22HBSensor.h @@ -14,5 +14,5 @@ class LPS22HBSensor : virtual public TelemetrySensor public: LPS22HBSensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp index 7bac18d9a..28db3d8a9 100644 --- a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp +++ b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp @@ -4,7 +4,7 @@ #include "configuration.h" #include -MCP9808Sensor::MCP9808Sensor() : TelemetrySensor(TelemetrySensorType_MCP9808, "MCP9808") {} +MCP9808Sensor::MCP9808Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_MCP9808, "MCP9808") {} int32_t MCP9808Sensor::runOnce() { @@ -21,7 +21,7 @@ void MCP9808Sensor::setup() mcp9808.setResolution(2); } -bool MCP9808Sensor::getMetrics(Telemetry *measurement) +bool MCP9808Sensor::getMetrics(meshtastic_Telemetry *measurement) { LOG_DEBUG("MCP9808Sensor::getMetrics\n"); measurement->variant.environment_metrics.temperature = mcp9808.readTempC(); diff --git a/src/modules/Telemetry/Sensor/MCP9808Sensor.h b/src/modules/Telemetry/Sensor/MCP9808Sensor.h index 150b76237..b70707477 100644 --- a/src/modules/Telemetry/Sensor/MCP9808Sensor.h +++ b/src/modules/Telemetry/Sensor/MCP9808Sensor.h @@ -13,5 +13,5 @@ class MCP9808Sensor : virtual public TelemetrySensor public: MCP9808Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp index 940a94d46..7ffb68254 100644 --- a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp @@ -4,7 +4,7 @@ #include "configuration.h" #include -SHT31Sensor::SHT31Sensor() : TelemetrySensor(TelemetrySensorType_SHT31, "SHT31") {} +SHT31Sensor::SHT31Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_SHT31, "SHT31") {} int32_t SHT31Sensor::runOnce() { @@ -21,7 +21,7 @@ void SHT31Sensor::setup() // Set up oversampling and filter initialization } -bool SHT31Sensor::getMetrics(Telemetry *measurement) +bool SHT31Sensor::getMetrics(meshtastic_Telemetry *measurement) { measurement->variant.environment_metrics.temperature = sht31.readTemperature(); measurement->variant.environment_metrics.relative_humidity = sht31.readHumidity(); diff --git a/src/modules/Telemetry/Sensor/SHT31Sensor.h b/src/modules/Telemetry/Sensor/SHT31Sensor.h index ca574a5cd..60354aaea 100644 --- a/src/modules/Telemetry/Sensor/SHT31Sensor.h +++ b/src/modules/Telemetry/Sensor/SHT31Sensor.h @@ -13,5 +13,5 @@ class SHT31Sensor : virtual public TelemetrySensor public: SHT31Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; diff --git a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp index 1ed16cc11..b0b5d37dc 100644 --- a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp @@ -4,7 +4,7 @@ #include "configuration.h" #include -SHTC3Sensor::SHTC3Sensor() : TelemetrySensor(TelemetrySensorType_SHTC3, "SHTC3") {} +SHTC3Sensor::SHTC3Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_SHTC3, "SHTC3") {} int32_t SHTC3Sensor::runOnce() { @@ -21,7 +21,7 @@ void SHTC3Sensor::setup() // Set up oversampling and filter initialization } -bool SHTC3Sensor::getMetrics(Telemetry *measurement) +bool SHTC3Sensor::getMetrics(meshtastic_Telemetry *measurement) { sensors_event_t humidity, temp; shtc3.getEvent(&humidity, &temp); diff --git a/src/modules/Telemetry/Sensor/SHTC3Sensor.h b/src/modules/Telemetry/Sensor/SHTC3Sensor.h index f391580a6..c67047396 100644 --- a/src/modules/Telemetry/Sensor/SHTC3Sensor.h +++ b/src/modules/Telemetry/Sensor/SHTC3Sensor.h @@ -13,5 +13,5 @@ class SHTC3Sensor : virtual public TelemetrySensor public: SHTC3Sensor(); virtual int32_t runOnce() override; - virtual bool getMetrics(Telemetry *measurement) override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; }; \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/TelemetrySensor.h b/src/modules/Telemetry/Sensor/TelemetrySensor.h index 79dfbf312..7a579ef5c 100644 --- a/src/modules/Telemetry/Sensor/TelemetrySensor.h +++ b/src/modules/Telemetry/Sensor/TelemetrySensor.h @@ -8,7 +8,7 @@ class TelemetrySensor { protected: - TelemetrySensor(TelemetrySensorType sensorType, const char *sensorName) + TelemetrySensor(meshtastic_TelemetrySensorType sensorType, const char *sensorName) { this->sensorName = sensorName; this->sensorType = sensorType; @@ -16,7 +16,7 @@ class TelemetrySensor } const char *sensorName; - TelemetrySensorType sensorType; + meshtastic_TelemetrySensorType sensorType; unsigned status; int32_t initI2CSensor() @@ -36,5 +36,5 @@ class TelemetrySensor bool hasSensor() { return sensorType < sizeof(nodeTelemetrySensorsMap) && nodeTelemetrySensorsMap[sensorType] > 0; } virtual int32_t runOnce() = 0; - virtual bool getMetrics(Telemetry *measurement) = 0; + virtual bool getMetrics(meshtastic_Telemetry *measurement) = 0; }; diff --git a/src/modules/TextMessageModule.cpp b/src/modules/TextMessageModule.cpp index c5dcca95a..bab5decda 100644 --- a/src/modules/TextMessageModule.cpp +++ b/src/modules/TextMessageModule.cpp @@ -1,11 +1,11 @@ -#include "configuration.h" #include "TextMessageModule.h" #include "NodeDB.h" #include "PowerFSM.h" +#include "configuration.h" TextMessageModule *textMessageModule; -ProcessMessage TextMessageModule::handleReceived(const MeshPacket &mp) +ProcessMessage TextMessageModule::handleReceived(const meshtastic_MeshPacket &mp) { auto &p = mp.decoded; LOG_INFO("Received text msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes); diff --git a/src/modules/TextMessageModule.h b/src/modules/TextMessageModule.h index 3b12dee48..93b1bfaa2 100644 --- a/src/modules/TextMessageModule.h +++ b/src/modules/TextMessageModule.h @@ -1,25 +1,25 @@ #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 */ -class TextMessageModule : public SinglePortModule, public Observable +class TextMessageModule : public SinglePortModule, public Observable { public: /** Constructor * name is for debugging output */ - TextMessageModule() : SinglePortModule("text", PortNum_TEXT_MESSAGE_APP) {} + TextMessageModule() : SinglePortModule("text", meshtastic_PortNum_TEXT_MESSAGE_APP) {} 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; + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override; }; extern TextMessageModule *textMessageModule; diff --git a/src/modules/TraceRouteModule.cpp b/src/modules/TraceRouteModule.cpp index ba35a2f40..14396266d 100644 --- a/src/modules/TraceRouteModule.cpp +++ b/src/modules/TraceRouteModule.cpp @@ -1,86 +1,86 @@ #include "TraceRouteModule.h" -#include "MeshService.h" #include "FloodingRouter.h" +#include "MeshService.h" -TraceRouteModule *traceRouteModule; +TraceRouteModule *traceRouteModule; - -bool TraceRouteModule::handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r) -{ +bool TraceRouteModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_RouteDiscovery *r) +{ // Only handle a response if (mp.decoded.request_id) { printRoute(r, mp.to, mp.from); } - + return false; // let it be handled by RoutingModule } - -void TraceRouteModule::updateRoute(MeshPacket* p) -{ +void TraceRouteModule::updateRoute(meshtastic_MeshPacket *p) +{ auto &incoming = p->decoded; // Only append an ID for the request (one way) - if (!incoming.request_id) { - RouteDiscovery scratch; - RouteDiscovery *updated = NULL; + if (!incoming.request_id) { + meshtastic_RouteDiscovery scratch; + meshtastic_RouteDiscovery *updated = NULL; memset(&scratch, 0, sizeof(scratch)); - pb_decode_from_bytes(incoming.payload.bytes, incoming.payload.size, &RouteDiscovery_msg, &scratch); + pb_decode_from_bytes(incoming.payload.bytes, incoming.payload.size, &meshtastic_RouteDiscovery_msg, &scratch); updated = &scratch; 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), + &meshtastic_RouteDiscovery_msg, updated); } } - -void TraceRouteModule::appendMyID(RouteDiscovery* updated) +void TraceRouteModule::appendMyID(meshtastic_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(meshtastic_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() +meshtastic_MeshPacket *TraceRouteModule::allocReply() { assert(currentRequest); // Copy the payload of the current request auto req = *currentRequest; auto &p = req.decoded; - RouteDiscovery scratch; - RouteDiscovery *updated = NULL; + meshtastic_RouteDiscovery scratch; + meshtastic_RouteDiscovery *updated = NULL; memset(&scratch, 0, sizeof(scratch)); - pb_decode_from_bytes(p.payload.bytes, p.payload.size, &RouteDiscovery_msg, &scratch); + pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_RouteDiscovery_msg, &scratch); updated = &scratch; printRoute(updated, req.from, req.to); // Create a MeshPacket with this payload and set it as the reply - MeshPacket* reply = allocDataProtobuf(*updated); + meshtastic_MeshPacket *reply = allocDataProtobuf(*updated); return reply; } - -TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, &RouteDiscovery_msg) { - ourPortNum = PortNum_TRACEROUTE_APP; +TraceRouteModule::TraceRouteModule() + : ProtobufModule("traceroute", meshtastic_PortNum_TRACEROUTE_APP, &meshtastic_RouteDiscovery_msg) +{ + ourPortNum = meshtastic_PortNum_TRACEROUTE_APP; } diff --git a/src/modules/TraceRouteModule.h b/src/modules/TraceRouteModule.h index 15b7a564d..674846ef1 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 +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 meshtastic_MeshPacket &mp, meshtastic_RouteDiscovery *r) override; - virtual MeshPacket *allocReply() override; + virtual meshtastic_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(meshtastic_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(meshtastic_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(meshtastic_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..079be604e 100644 --- a/src/modules/WaypointModule.cpp +++ b/src/modules/WaypointModule.cpp @@ -1,16 +1,15 @@ -#include "configuration.h" #include "WaypointModule.h" #include "NodeDB.h" #include "PowerFSM.h" +#include "configuration.h" WaypointModule *waypointModule; -ProcessMessage WaypointModule::handleReceived(const MeshPacket &mp) +ProcessMessage WaypointModule::handleReceived(const meshtastic_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..ddbabf4de 100644 --- a/src/modules/WaypointModule.h +++ b/src/modules/WaypointModule.h @@ -1,25 +1,25 @@ #pragma once -#include "SinglePortModule.h" #include "Observer.h" +#include "SinglePortModule.h" /** * Waypoint message handling for meshtastic */ -class WaypointModule : public SinglePortModule, public Observable +class WaypointModule : public SinglePortModule, public Observable { public: /** Constructor * name is for debugging output */ - WaypointModule() : SinglePortModule("waypoint", PortNum_WAYPOINT_APP) {} + WaypointModule() : SinglePortModule("waypoint", meshtastic_PortNum_WAYPOINT_APP) {} 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; + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override; }; extern WaypointModule *waypointModule; diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index bdef12e08..072ee75e4 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -2,11 +2,11 @@ #include "configuration.h" #if defined(ARCH_ESP32) #include "AudioModule.h" +#include "FSCommon.h" #include "MeshService.h" #include "NodeDB.h" #include "RTC.h" #include "Router.h" -#include "FSCommon.h" #ifdef OLED_RU #include "graphics/fonts/OLEDDisplayFontsRU.h" @@ -17,14 +17,15 @@ A interface to send raw codec2 audio data over the mesh network. Based on the example code from the ESP32_codec2 project. https://github.com/deulis/ESP32_Codec2 - Codec 2 is a low-bitrate speech audio codec (speech coding) + Codec 2 is a low-bitrate speech audio codec (speech coding) that is patent free and open source develop by David Grant Rowe. http://www.rowetel.com/ and https://github.com/drowe67/codec2 Basic Usage: 1) Enable the module by setting audio.codec2_enabled to 1. 2) Set the pins for the I2S interface. Recommended on TLora is I2S_WS 13/I2S_SD 15/I2S_SIN 2/I2S_SCK 14 - 3) Set audio.bitrate to the desired codec2 rate (CODEC2_3200, CODEC2_2400, CODEC2_1600, CODEC2_1400, CODEC2_1300, CODEC2_1200, CODEC2_700, CODEC2_700B) + 3) Set audio.bitrate to the desired codec2 rate (CODEC2_3200, CODEC2_2400, CODEC2_1600, CODEC2_1400, CODEC2_1300, + CODEC2_1200, CODEC2_700, CODEC2_700B) KNOWN PROBLEMS * Half Duplex @@ -64,10 +65,10 @@ AudioModule *audioModule; #define FONT_HEIGHT_MEDIUM fontHeight(FONT_MEDIUM) #define FONT_HEIGHT_LARGE fontHeight(FONT_LARGE) -void run_codec2(void* parameter) +void run_codec2(void *parameter) { // 4 bytes of header in each frame hex c0 de c2 plus the bitrate - memcpy(audioModule->tx_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)); } @@ -115,7 +115,7 @@ void run_codec2(void* parameter) } } -AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") +AudioModule::AudioModule() : SinglePortModule("AudioModule", meshtastic_PortNum_AUDIO_APP), concurrency::OSThread("AudioModule") { // moduleConfig.audio.codec2_enabled = true; // moduleConfig.audio.i2s_ws = 13; @@ -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_num = (meshtastic_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,10 +261,9 @@ int32_t AudioModule::runOnce() } else { return disable(); } - } -MeshPacket *AudioModule::allocReply() +meshtastic_MeshPacket *AudioModule::allocReply() { auto reply = allocDataPacket(); return reply; @@ -277,12 +279,12 @@ bool AudioModule::shouldDraw() void AudioModule::sendPayload(NodeNum dest, bool wantReplies) { - MeshPacket *p = allocReply(); + meshtastic_MeshPacket *p = allocReply(); p->to = dest; p->decoded.want_response = wantReplies; - 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->want_ack = false; // Audio is shoot&forget. No need to wait for ACKs. + p->priority = meshtastic_MeshPacket_Priority_MAX; // Audio is important, because realtime p->decoded.payload.size = tx_encode_frame_index; memcpy(p->decoded.payload.bytes, tx_encode_frame, p->decoded.payload.size); @@ -290,7 +292,7 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies) service.sendToMesh(p); } -ProcessMessage AudioModule::handleReceived(const MeshPacket &mp) +ProcessMessage AudioModule::handleReceived(const meshtastic_MeshPacket &mp) { if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) { auto &p = mp.decoded; diff --git a/src/modules/esp32/AudioModule.h b/src/modules/esp32/AudioModule.h index 1a41ab6c4..8bf8c3f55 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 }; @@ -28,13 +28,13 @@ struct c2_header { #define I2S_PORT I2S_NUM_0 #define AUDIO_MODULE_RX_BUFFER 128 -#define AUDIO_MODULE_MODE ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 +#define AUDIO_MODULE_MODE meshtastic_ModuleConfig_AudioConfig_Audio_Baud_CODEC2_700 class AudioModule : public SinglePortModule, public Observable, private concurrency::OSThread { public: - unsigned char rx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; - unsigned char tx_encode_frame[Constants_DATA_PAYLOAD_LEN] = {}; + unsigned char rx_encode_frame[meshtastic_Constants_DATA_PAYLOAD_LEN] = {}; + unsigned char tx_encode_frame[meshtastic_Constants_DATA_PAYLOAD_LEN] = {}; c2_header tx_header = {}; int16_t speech[ADC_BUFFER_SIZE_MAX] = {}; int16_t output_buffer[ADC_BUFFER_SIZE_MAX] = {}; @@ -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; + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override; }; extern AudioModule *audioModule; diff --git a/src/modules/esp32/RangeTestModule.cpp b/src/modules/esp32/RangeTestModule.cpp index 52a18def5..dbbb47ea7 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"); @@ -93,7 +91,7 @@ int32_t RangeTestModule::runOnce() return disable(); } -MeshPacket *RangeTestModuleRadio::allocReply() +meshtastic_MeshPacket *RangeTestModuleRadio::allocReply() { auto reply = allocDataPacket(); // Allocate a packet for sending @@ -103,7 +101,7 @@ MeshPacket *RangeTestModuleRadio::allocReply() void RangeTestModuleRadio::sendPayload(NodeNum dest, bool wantReplies) { - MeshPacket *p = allocReply(); + meshtastic_MeshPacket *p = allocReply(); p->to = dest; p->decoded.want_response = wantReplies; @@ -123,7 +121,7 @@ void RangeTestModuleRadio::sendPayload(NodeNum dest, bool wantReplies) powerFSM.trigger(EVENT_CONTACT_FROM_PHONE); } -ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp) +ProcessMessage RangeTestModuleRadio::handleReceived(const meshtastic_MeshPacket &mp) { #ifdef ARCH_ESP32 @@ -178,11 +176,11 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const MeshPacket &mp) return ProcessMessage::CONTINUE; // Let others look at this message also if they want } -bool RangeTestModuleRadio::appendFile(const MeshPacket &mp) +bool RangeTestModuleRadio::appendFile(const meshtastic_MeshPacket &mp) { auto &p = mp.decoded; - NodeInfo *n = nodeDB.getNode(getFrom(&mp)); + meshtastic_NodeInfo *n = nodeDB.getNode(getFrom(&mp)); /* LOG_DEBUG("-----------------------------------------\n"); LOG_DEBUG("p.payload.bytes \"%s\"\n", p.payload.bytes); diff --git a/src/modules/esp32/RangeTestModule.h b/src/modules/esp32/RangeTestModule.h index db49a586e..e404bd8b6 100644 --- a/src/modules/esp32/RangeTestModule.h +++ b/src/modules/esp32/RangeTestModule.h @@ -28,7 +28,7 @@ class RangeTestModuleRadio : public SinglePortModule uint32_t lastRxID = 0; public: - RangeTestModuleRadio() : SinglePortModule("RangeTestModuleRadio", PortNum_TEXT_MESSAGE_APP) + RangeTestModuleRadio() : SinglePortModule("RangeTestModuleRadio", meshtastic_PortNum_TEXT_MESSAGE_APP) { loopbackOk = true; // Allow locally generated messages to loop back to the client } @@ -41,7 +41,7 @@ class RangeTestModuleRadio : public SinglePortModule /** * Append range test data to the file on the Filesystem */ - bool appendFile(const MeshPacket &mp); + bool appendFile(const meshtastic_MeshPacket &mp); /** * Kevin's magical calculation of two points to meters. @@ -49,14 +49,14 @@ class RangeTestModuleRadio : public SinglePortModule float latLongToMeter(double lat_a, double lng_a, double lat_b, double lng_b); protected: - virtual MeshPacket *allocReply() override; + virtual meshtastic_MeshPacket *allocReply() override; /** 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 */ - virtual ProcessMessage handleReceived(const MeshPacket &mp) override; + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override; }; extern RangeTestModuleRadio *rangeTestModuleRadio; diff --git a/src/modules/esp32/StoreForwardModule.cpp b/src/modules/esp32/StoreForwardModule.cpp index 36d023162..fbebc77e8 100644 --- a/src/modules/esp32/StoreForwardModule.cpp +++ b/src/modules/esp32/StoreForwardModule.cpp @@ -25,8 +25,8 @@ int32_t StoreForwardModule::runOnce() storeForwardModule->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { // Tell the client we're done sending - StoreAndForward sf = StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_ROUTER_PING; + meshtastic_StoreAndForward sf = meshtastic_StoreAndForward_init_zero; + sf.rr = meshtastic_StoreAndForward_RequestResponse_ROUTER_PING; storeForwardModule->sendMessage(this->busyTo, sf); LOG_INFO("*** S&F - Done. (ROUTER_PING)\n"); this->packetHistoryTXQueue_index = 0; @@ -40,9 +40,9 @@ int32_t StoreForwardModule::runOnce() } else if ((millis() - lastHeartbeat > (heartbeatInterval * 1000)) && airTime->isTxAllowedChannelUtil(true)) { lastHeartbeat = millis(); LOG_INFO("*** Sending heartbeat\n"); - StoreAndForward sf = StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; - sf.which_variant = StoreAndForward_heartbeat_tag; + meshtastic_StoreAndForward sf = meshtastic_StoreAndForward_init_zero; + sf.rr = meshtastic_StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; + sf.which_variant = meshtastic_StoreAndForward_heartbeat_tag; sf.variant.heartbeat.period = 300; sf.variant.heartbeat.secondary = 0; // TODO we always have one primary router for now storeForwardModule->sendMessage(NODENUM_BROADCAST, sf); @@ -93,9 +93,9 @@ void StoreForwardModule::historySend(uint32_t msAgo, uint32_t to) } else { LOG_INFO("*** S&F - No history to send\n"); } - StoreAndForward sf = StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_ROUTER_HISTORY; - sf.which_variant = StoreAndForward_history_tag; + meshtastic_StoreAndForward sf = meshtastic_StoreAndForward_init_zero; + sf.rr = meshtastic_StoreAndForward_RequestResponse_ROUTER_HISTORY; + sf.which_variant = meshtastic_StoreAndForward_history_tag; sf.variant.history.history_messages = queueSize; sf.variant.history.window = msAgo; storeForwardModule->sendMessage(to, sf); @@ -130,7 +130,7 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].channel = this->packetHistory[i].channel; this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].payload_size = this->packetHistory[i].payload_size; memcpy(this->packetHistoryTXQueue[this->packetHistoryTXQueue_size].payload, this->packetHistory[i].payload, - Constants_DATA_PAYLOAD_LEN); + meshtastic_Constants_DATA_PAYLOAD_LEN); this->packetHistoryTXQueue_size++; LOG_DEBUG("*** PacketHistoryStruct time=%d\n", this->packetHistory[i].time); @@ -141,7 +141,7 @@ uint32_t StoreForwardModule::historyQueueCreate(uint32_t msAgo, uint32_t to) return this->packetHistoryTXQueue_size; } -void StoreForwardModule::historyAdd(const MeshPacket &mp) +void StoreForwardModule::historyAdd(const meshtastic_MeshPacket &mp) { const auto &p = mp.decoded; @@ -150,13 +150,13 @@ void StoreForwardModule::historyAdd(const MeshPacket &mp) this->packetHistory[this->packetHistoryCurrent].channel = mp.channel; this->packetHistory[this->packetHistoryCurrent].from = mp.from; this->packetHistory[this->packetHistoryCurrent].payload_size = p.payload.size; - memcpy(this->packetHistory[this->packetHistoryCurrent].payload, p.payload.bytes, Constants_DATA_PAYLOAD_LEN); + memcpy(this->packetHistory[this->packetHistoryCurrent].payload, p.payload.bytes, meshtastic_Constants_DATA_PAYLOAD_LEN); this->packetHistoryCurrent++; this->packetHistoryMax++; } -MeshPacket *StoreForwardModule::allocReply() +meshtastic_MeshPacket *StoreForwardModule::allocReply() { auto reply = allocDataPacket(); // Allocate a packet for sending return reply; @@ -165,7 +165,7 @@ MeshPacket *StoreForwardModule::allocReply() void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index) { LOG_INFO("*** Sending S&F Payload\n"); - MeshPacket *p = allocReply(); + meshtastic_MeshPacket *p = allocReply(); p->to = dest; p->from = this->packetHistoryTXQueue[packetHistory_index].from; @@ -183,17 +183,17 @@ void StoreForwardModule::sendPayload(NodeNum dest, uint32_t packetHistory_index) service.sendToMesh(p); } -void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward &payload) +void StoreForwardModule::sendMessage(NodeNum dest, meshtastic_StoreAndForward &payload) { - MeshPacket *p = allocDataProtobuf(payload); + meshtastic_MeshPacket *p = allocDataProtobuf(payload); p->to = dest; - p->priority = MeshPacket_Priority_MIN; + p->priority = meshtastic_MeshPacket_Priority_MIN; // FIXME - Determine if the delayed packet is broadcast or delayed. For now, assume // everything is broadcast. - p->delayed = MeshPacket_Delayed_DELAYED_BROADCAST; + p->delayed = meshtastic_MeshPacket_Delayed_DELAYED_BROADCAST; // Let's assume that if the router received the S&F request that the client is in range. // TODO: Make this configurable. @@ -203,20 +203,20 @@ void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward &payload) service.sendToMesh(p); } -void StoreForwardModule::sendMessage(NodeNum dest, StoreAndForward_RequestResponse rr) +void StoreForwardModule::sendMessage(NodeNum dest, meshtastic_StoreAndForward_RequestResponse rr) { // Craft an empty response, save some bytes in flash - StoreAndForward sf = StoreAndForward_init_zero; + meshtastic_StoreAndForward sf = meshtastic_StoreAndForward_init_zero; sf.rr = rr; storeForwardModule->sendMessage(dest, sf); } void StoreForwardModule::statsSend(uint32_t to) { - StoreAndForward sf = StoreAndForward_init_zero; + meshtastic_StoreAndForward sf = meshtastic_StoreAndForward_init_zero; - sf.rr = StoreAndForward_RequestResponse_ROUTER_STATS; - sf.which_variant = StoreAndForward_stats_tag; + sf.rr = meshtastic_StoreAndForward_RequestResponse_ROUTER_STATS; + sf.which_variant = meshtastic_StoreAndForward_stats_tag; sf.variant.stats.messages_total = this->packetHistoryMax; sf.variant.stats.messages_saved = this->packetHistoryCurrent; sf.variant.stats.messages_max = this->records; @@ -231,29 +231,29 @@ void StoreForwardModule::statsSend(uint32_t to) storeForwardModule->sendMessage(to, sf); } -ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) +ProcessMessage StoreForwardModule::handleReceived(const meshtastic_MeshPacket &mp) { #ifdef ARCH_ESP32 if (moduleConfig.store_forward.enabled) { // The router node should not be sending messages as a client. Unless he is a ROUTER_CLIENT - if ((getFrom(&mp) != nodeDB.getNodeNum()) || (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { + if ((getFrom(&mp) != nodeDB.getNodeNum()) || (config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER_CLIENT)) { - if ((mp.decoded.portnum == PortNum_TEXT_MESSAGE_APP) && is_server) { + if ((mp.decoded.portnum == meshtastic_PortNum_TEXT_MESSAGE_APP) && is_server) { auto &p = mp.decoded; if ((p.payload.bytes[0] == 'S') && (p.payload.bytes[1] == 'F') && (p.payload.bytes[2] == 0x00)) { LOG_DEBUG("*** Legacy Request to send\n"); // Send the last 60 minutes of messages. if (this->busy) { - storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); + storeForwardModule->sendMessage(getFrom(&mp), meshtastic_StoreAndForward_RequestResponse_ROUTER_BUSY); LOG_INFO("*** S&F - Busy. Try again shortly.\n"); - MeshPacket *pr = allocReply(); + meshtastic_MeshPacket *pr = allocReply(); pr->to = getFrom(&mp); - pr->priority = MeshPacket_Priority_MIN; + pr->priority = meshtastic_MeshPacket_Priority_MIN; pr->want_ack = false; pr->decoded.want_response = false; - pr->decoded.portnum = PortNum_TEXT_MESSAGE_APP; + pr->decoded.portnum = meshtastic_PortNum_TEXT_MESSAGE_APP; memcpy(pr->decoded.payload.bytes, "** S&F - Busy. Try again shortly.", 34); pr->decoded.payload.size = 34; service.sendToMesh(pr); @@ -265,12 +265,12 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) LOG_INFO("*** S&F stored. Message history contains %u records now.\n", this->packetHistoryCurrent); } - } else if (mp.decoded.portnum == PortNum_STORE_FORWARD_APP) { + } else if (mp.decoded.portnum == meshtastic_PortNum_STORE_FORWARD_APP) { auto &p = mp.decoded; - StoreAndForward scratch; - StoreAndForward *decoded = NULL; - if (mp.which_payload_variant == MeshPacket_decoded_tag) { - if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &StoreAndForward_msg, &scratch)) { + meshtastic_StoreAndForward scratch; + meshtastic_StoreAndForward *decoded = NULL; + if (mp.which_payload_variant == meshtastic_MeshPacket_decoded_tag) { + if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_StoreAndForward_msg, &scratch)) { decoded = &scratch; } else { LOG_ERROR("Error decoding protobuf module!\n"); @@ -288,7 +288,7 @@ ProcessMessage StoreForwardModule::handleReceived(const MeshPacket &mp) return ProcessMessage::CONTINUE; // Let others look at this message also if they want } -bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p) +bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_StoreAndForward *p) { if (!moduleConfig.store_forward.enabled) { // If this module is not enabled in any capacity, don't handle the packet, and allow other modules to consume @@ -298,8 +298,8 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo requests++; switch (p->rr) { - case StoreAndForward_RequestResponse_CLIENT_ERROR: - case StoreAndForward_RequestResponse_CLIENT_ABORT: + case meshtastic_StoreAndForward_RequestResponse_CLIENT_ERROR: + case meshtastic_StoreAndForward_RequestResponse_CLIENT_ABORT: if (is_server) { // stop sending stuff, the client wants to abort or has another error if ((this->busy) && (this->busyTo == getFrom(&mp))) { @@ -310,16 +310,16 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; - case StoreAndForward_RequestResponse_CLIENT_HISTORY: + case meshtastic_StoreAndForward_RequestResponse_CLIENT_HISTORY: if (is_server) { requests_history++; LOG_INFO("*** Client Request to send HISTORY\n"); // Send the last 60 minutes of messages. if (this->busy) { - storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); + storeForwardModule->sendMessage(getFrom(&mp), meshtastic_StoreAndForward_RequestResponse_ROUTER_BUSY); LOG_INFO("*** S&F - Busy. Try again shortly.\n"); } else { - if ((p->which_variant == StoreAndForward_history_tag) && (p->variant.history.window > 0)) { + if ((p->which_variant == meshtastic_StoreAndForward_history_tag) && (p->variant.history.window > 0)) { storeForwardModule->historySend(p->variant.history.window * 60000, getFrom(&mp)); // window is in minutes } else { storeForwardModule->historySend(historyReturnWindow * 60000, getFrom(&mp)); // defaults to 4 hours @@ -328,15 +328,15 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; - case StoreAndForward_RequestResponse_CLIENT_PING: + case meshtastic_StoreAndForward_RequestResponse_CLIENT_PING: if (is_server) { LOG_INFO("*** StoreAndForward_RequestResponse_CLIENT_PING\n"); // respond with a ROUTER PONG - storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_PONG); + storeForwardModule->sendMessage(getFrom(&mp), meshtastic_StoreAndForward_RequestResponse_ROUTER_PONG); } break; - case StoreAndForward_RequestResponse_CLIENT_PONG: + case meshtastic_StoreAndForward_RequestResponse_CLIENT_PONG: if (is_server) { LOG_INFO("*** StoreAndForward_RequestResponse_CLIENT_PONG\n"); // The Client is alive, update NodeDB @@ -344,11 +344,11 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; - case StoreAndForward_RequestResponse_CLIENT_STATS: + case meshtastic_StoreAndForward_RequestResponse_CLIENT_STATS: if (is_server) { LOG_INFO("*** Client Request to send STATS\n"); if (this->busy) { - storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_ROUTER_BUSY); + storeForwardModule->sendMessage(getFrom(&mp), meshtastic_StoreAndForward_RequestResponse_ROUTER_BUSY); LOG_INFO("*** S&F - Busy. Try again shortly.\n"); } else { storeForwardModule->statsSend(getFrom(&mp)); @@ -356,22 +356,22 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; - case StoreAndForward_RequestResponse_ROUTER_ERROR: - case StoreAndForward_RequestResponse_ROUTER_BUSY: + case meshtastic_StoreAndForward_RequestResponse_ROUTER_ERROR: + case meshtastic_StoreAndForward_RequestResponse_ROUTER_BUSY: if (is_client) { LOG_DEBUG("*** StoreAndForward_RequestResponse_ROUTER_BUSY\n"); // retry in messages_saved * packetTimeMax ms - retry_delay = - millis() + packetHistoryCurrent * packetTimeMax * (StoreAndForward_RequestResponse_ROUTER_ERROR ? 2 : 1); + retry_delay = millis() + packetHistoryCurrent * packetTimeMax * + (meshtastic_StoreAndForward_RequestResponse_ROUTER_ERROR ? 2 : 1); } break; - case StoreAndForward_RequestResponse_ROUTER_PONG: + case meshtastic_StoreAndForward_RequestResponse_ROUTER_PONG: // A router responded, this is equal to receiving a heartbeat - case StoreAndForward_RequestResponse_ROUTER_HEARTBEAT: + case meshtastic_StoreAndForward_RequestResponse_ROUTER_HEARTBEAT: if (is_client) { // register heartbeat and interval - if (p->which_variant == StoreAndForward_heartbeat_tag) { + if (p->which_variant == meshtastic_StoreAndForward_heartbeat_tag) { heartbeatInterval = p->variant.heartbeat.period; } lastHeartbeat = millis(); @@ -379,19 +379,19 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; - case StoreAndForward_RequestResponse_ROUTER_PING: + case meshtastic_StoreAndForward_RequestResponse_ROUTER_PING: if (is_client) { LOG_DEBUG("*** StoreAndForward_RequestResponse_ROUTER_PING\n"); // respond with a CLIENT PONG - storeForwardModule->sendMessage(getFrom(&mp), StoreAndForward_RequestResponse_CLIENT_PONG); + storeForwardModule->sendMessage(getFrom(&mp), meshtastic_StoreAndForward_RequestResponse_CLIENT_PONG); } break; - case StoreAndForward_RequestResponse_ROUTER_STATS: + case meshtastic_StoreAndForward_RequestResponse_ROUTER_STATS: if (is_client) { LOG_DEBUG("*** Router Response STATS\n"); // These fields only have informational purpose on a client. Fill them to consume later. - if (p->which_variant == StoreAndForward_stats_tag) { + if (p->which_variant == meshtastic_StoreAndForward_stats_tag) { this->packetHistoryMax = p->variant.stats.messages_total; this->packetHistoryCurrent = p->variant.stats.messages_saved; this->records = p->variant.stats.messages_max; @@ -404,10 +404,10 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } break; - case StoreAndForward_RequestResponse_ROUTER_HISTORY: + case meshtastic_StoreAndForward_RequestResponse_ROUTER_HISTORY: if (is_client) { // These fields only have informational purpose on a client. Fill them to consume later. - if (p->which_variant == StoreAndForward_history_tag) { + if (p->which_variant == meshtastic_StoreAndForward_history_tag) { this->historyReturnWindow = p->variant.history.window / 60000; LOG_INFO("*** Router Response HISTORY - Sending %d messages from last %d minutes\n", p->variant.history.history_messages, this->historyReturnWindow); @@ -422,7 +422,8 @@ bool StoreForwardModule::handleReceivedProtobuf(const MeshPacket &mp, StoreAndFo } StoreForwardModule::StoreForwardModule() - : concurrency::OSThread("StoreForwardModule"), ProtobufModule("StoreForward", PortNum_STORE_FORWARD_APP, &StoreAndForward_msg) + : concurrency::OSThread("StoreForwardModule"), + ProtobufModule("StoreForward", meshtastic_PortNum_STORE_FORWARD_APP, &meshtastic_StoreAndForward_msg) { #ifdef ARCH_ESP32 @@ -441,8 +442,8 @@ StoreForwardModule::StoreForwardModule() if (moduleConfig.store_forward.enabled) { // Router - if ((config.device.role == Config_DeviceConfig_Role_ROUTER) || - (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { + if ((config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER) || + (config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER_CLIENT)) { LOG_INFO("*** Initializing Store & Forward Module in Router mode\n"); if (ESP.getPsramSize() > 0) { if (ESP.getFreePsram() >= 1024 * 1024) { @@ -479,8 +480,8 @@ StoreForwardModule::StoreForwardModule() // Client } - if ((config.device.role == Config_DeviceConfig_Role_CLIENT) || - (config.device.role == Config_DeviceConfig_Role_ROUTER_CLIENT)) { + if ((config.device.role == meshtastic_Config_DeviceConfig_Role_CLIENT) || + (config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER_CLIENT)) { is_client = true; LOG_INFO("*** Initializing Store & Forward Module in Client mode\n"); } diff --git a/src/modules/esp32/StoreForwardModule.h b/src/modules/esp32/StoreForwardModule.h index b1c4084f3..23f42e4ae 100644 --- a/src/modules/esp32/StoreForwardModule.h +++ b/src/modules/esp32/StoreForwardModule.h @@ -14,15 +14,15 @@ struct PacketHistoryStruct { uint32_t from; uint8_t channel; bool ack; - uint8_t payload[Constants_DATA_PAYLOAD_LEN]; + uint8_t payload[meshtastic_Constants_DATA_PAYLOAD_LEN]; pb_size_t payload_size; }; -class StoreForwardModule : private concurrency::OSThread, public ProtobufModule +class StoreForwardModule : private concurrency::OSThread, public ProtobufModule { bool busy = 0; uint32_t busyTo = 0; - char routerMessage[Constants_DATA_PAYLOAD_LEN] = {0}; + char routerMessage[meshtastic_Constants_DATA_PAYLOAD_LEN] = {0}; PacketHistoryStruct *packetHistory = 0; uint32_t packetHistoryCurrent = 0; @@ -47,7 +47,7 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< Update our local reference of when we last saw that node. @return 0 if we have never seen that node before otherwise return the last time we saw the node. */ - void historyAdd(const MeshPacket &mp); + void historyAdd(const meshtastic_MeshPacket &mp); void statsSend(uint32_t to); void historySend(uint32_t msAgo, uint32_t to); @@ -57,18 +57,18 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< * Send our payload into the mesh */ void sendPayload(NodeNum dest = NODENUM_BROADCAST, uint32_t packetHistory_index = 0); - void sendMessage(NodeNum dest, StoreAndForward &payload); - void sendMessage(NodeNum dest, StoreAndForward_RequestResponse rr); + void sendMessage(NodeNum dest, meshtastic_StoreAndForward &payload); + void sendMessage(NodeNum dest, meshtastic_StoreAndForward_RequestResponse rr); - virtual MeshPacket *allocReply() override; + virtual meshtastic_MeshPacket *allocReply() override; /* -Override the wantPacket method. */ - virtual bool wantPacket(const MeshPacket *p) override + virtual bool wantPacket(const meshtastic_MeshPacket *p) override { switch (p->decoded.portnum) { - case PortNum_TEXT_MESSAGE_APP: - case PortNum_STORE_FORWARD_APP: + case meshtastic_PortNum_TEXT_MESSAGE_APP: + case meshtastic_PortNum_STORE_FORWARD_APP: return true; default: return false; @@ -98,8 +98,8 @@ class StoreForwardModule : private concurrency::OSThread, public ProtobufModule< @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; - virtual bool handleReceivedProtobuf(const MeshPacket &mp, StoreAndForward *p); + virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp) override; + virtual bool handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_StoreAndForward *p); }; extern StoreForwardModule *storeForwardModule; 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/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index a6073af3b..5e32050ad 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -21,9 +21,9 @@ String statusTopic = "msh/2/stat/"; String cryptTopic = "msh/2/c/"; // msh/2/c/CHANNELID/NODEID String jsonTopic = "msh/2/json/"; // msh/2/json/CHANNELID/NODEID -static MemoryDynamic staticMqttPool; +static MemoryDynamic staticMqttPool; -Allocator &mqttPool = staticMqttPool; +Allocator &mqttPool = staticMqttPool; void MQTT::mqttCallback(char *topic, byte *payload, unsigned int length) { @@ -33,7 +33,7 @@ void MQTT::mqttCallback(char *topic, byte *payload, unsigned int length) void MQTT::onPublish(char *topic, byte *payload, unsigned int length) { // parsing ServiceEnvelope - ServiceEnvelope e = ServiceEnvelope_init_default; + meshtastic_ServiceEnvelope e = meshtastic_ServiceEnvelope_init_default; if (moduleConfig.mqtt.json_enabled && (strncmp(topic, jsonTopic.c_str(), jsonTopic.length()) == 0)) { // check if this is a json payload message by comparing the topic start @@ -53,10 +53,8 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) for (int i = 0; i < 3; i++) { ptr = strtok(NULL, "/"); } - LOG_DEBUG("Looking for Channel name: %s\n", ptr); - Channel sendChannel = channels.getByName(ptr); - LOG_DEBUG("Found Channel name: %s (Index %d)\n", channels.getGlobalId(sendChannel.settings.channel_num), - sendChannel.settings.channel_num); + meshtastic_Channel sendChannel = channels.getByName(ptr); + LOG_DEBUG("Found Channel name: %s (Index %d)\n", channels.getGlobalId(sendChannel.index), sendChannel.index); if ((json.find("sender") != json.end()) && (json.find("payload") != json.end()) && (json.find("type") != json.end()) && json["type"]->IsString() && @@ -68,14 +66,14 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) LOG_INFO("JSON payload %s, length %u\n", jsonPayloadStr.c_str(), jsonPayloadStr.length()); // construct protobuf data packet using TEXT_MESSAGE, send it to the mesh - MeshPacket *p = router->allocForSending(); - p->decoded.portnum = PortNum_TEXT_MESSAGE_APP; - p->channel = sendChannel.settings.channel_num; + meshtastic_MeshPacket *p = router->allocForSending(); + p->decoded.portnum = meshtastic_PortNum_TEXT_MESSAGE_APP; + p->channel = sendChannel.index; if (sendChannel.settings.downlink_enabled) { if (jsonPayloadStr.length() <= sizeof(p->decoded.payload.bytes)) { memcpy(p->decoded.payload.bytes, jsonPayloadStr.c_str(), jsonPayloadStr.length()); p->decoded.payload.size = jsonPayloadStr.length(); - MeshPacket *packet = packetPool.allocCopy(*p); + meshtastic_MeshPacket *packet = packetPool.allocCopy(*p); service.sendToMesh(packet, RX_SRC_LOCAL); } else { LOG_WARN("Received MQTT json payload too long, dropping\n"); @@ -95,19 +93,20 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) (json["sender"]->AsString().compare(owner.id) != 0)) { JSONObject posit; posit = json["payload"]->AsObject(); // get nested JSON Position - Position pos = Position_init_default; + meshtastic_Position pos = meshtastic_Position_init_default; pos.latitude_i = posit["latitude_i"]->AsNumber(); pos.longitude_i = posit["longitude_i"]->AsNumber(); pos.altitude = posit["altitude"]->AsNumber(); pos.time = posit["time"]->AsNumber(); // construct protobuf data packet using POSITION, send it to the mesh - MeshPacket *p = router->allocForSending(); - p->decoded.portnum = PortNum_POSITION_APP; - p->channel = sendChannel.settings.channel_num; + meshtastic_MeshPacket *p = router->allocForSending(); + p->decoded.portnum = meshtastic_PortNum_POSITION_APP; + p->channel = sendChannel.index; if (sendChannel.settings.downlink_enabled) { - p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), - &Position_msg, &pos); // make the Data protobuf from position + p->decoded.payload.size = + pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), + &meshtastic_Position_msg, &pos); // make the Data protobuf from position service.sendToMesh(p, RX_SRC_LOCAL); } else { LOG_WARN("Received MQTT json payload on channel %s, but downlink is disabled, dropping\n", @@ -125,7 +124,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) } delete json_value; } else { - if (!pb_decode_from_bytes(payload, length, &ServiceEnvelope_msg, &e)) { + if (!pb_decode_from_bytes(payload, length, &meshtastic_ServiceEnvelope_msg, &e)) { LOG_ERROR("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); return; } else { @@ -134,7 +133,7 @@ void MQTT::onPublish(char *topic, byte *payload, unsigned int length) else { if (e.packet) { LOG_INFO("Received MQTT topic %s, len=%u\n", topic, length); - MeshPacket *p = packetPool.allocCopy(*e.packet); + meshtastic_MeshPacket *p = packetPool.allocCopy(*e.packet); // ignore messages sent by us or if we don't have the channel key if (router && p->from != nodeDB.getNodeNum() && perhapsDecode(p)) @@ -293,9 +292,9 @@ int32_t MQTT::runOnce() if (pubSub.connected()) { if (!mqttQueue.isEmpty()) { // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets - ServiceEnvelope *env = mqttQueue.dequeuePtr(0); - static uint8_t bytes[MeshPacket_size + 64]; - size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env); + meshtastic_ServiceEnvelope *env = mqttQueue.dequeuePtr(0); + static uint8_t bytes[meshtastic_MeshPacket_size + 64]; + size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_ServiceEnvelope_msg, env); String topic = cryptTopic + env->channel_id + "/" + owner.id; LOG_INFO("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); @@ -332,24 +331,24 @@ int32_t MQTT::runOnce() } } -void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) +void MQTT::onSend(const meshtastic_MeshPacket &mp, ChannelIndex chIndex) { auto &ch = channels.getByIndex(chIndex); if (ch.settings.uplink_enabled) { const char *channelId = channels.getGlobalId(chIndex); // FIXME, for now we just use the human name for the channel - ServiceEnvelope *env = mqttPool.allocZeroed(); + meshtastic_ServiceEnvelope *env = mqttPool.allocZeroed(); env->channel_id = (char *)channelId; env->gateway_id = owner.id; - env->packet = (MeshPacket *)∓ + env->packet = (meshtastic_MeshPacket *)∓ // don't bother sending if not connected... if (pubSub.connected()) { // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets - static uint8_t bytes[MeshPacket_size + 64]; - size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &ServiceEnvelope_msg, env); + static uint8_t bytes[meshtastic_MeshPacket_size + 64]; + size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_ServiceEnvelope_msg, env); String topic = cryptTopic + channelId + "/" + owner.id; LOG_DEBUG("publish %s, %u bytes\n", topic.c_str(), numBytes); @@ -358,7 +357,7 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) if (moduleConfig.mqtt.json_enabled) { // handle json topic - auto jsonString = this->downstreamPacketToJson((MeshPacket *)&mp); + auto jsonString = this->downstreamPacketToJson((meshtastic_MeshPacket *)&mp); if (jsonString.length() != 0) { String topicJson = jsonTopic + channelId + "/" + owner.id; LOG_INFO("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), @@ -370,12 +369,12 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) LOG_INFO("MQTT not connected, queueing packet\n"); if (mqttQueue.numFree() == 0) { LOG_WARN("NOTE: MQTT queue is full, discarding oldest\n"); - ServiceEnvelope *d = mqttQueue.dequeuePtr(0); + meshtastic_ServiceEnvelope *d = mqttQueue.dequeuePtr(0); if (d) mqttPool.release(d); } // make a copy of serviceEnvelope and queue it - ServiceEnvelope *copied = mqttPool.allocCopy(*env); + meshtastic_ServiceEnvelope *copied = mqttPool.allocCopy(*env); assert(mqttQueue.enqueue(copied, 0)); } mqttPool.release(env); @@ -383,7 +382,7 @@ void MQTT::onSend(const MeshPacket &mp, ChannelIndex chIndex) } // converts a downstream packet into a json message -std::string MQTT::downstreamPacketToJson(MeshPacket *mp) +std::string MQTT::downstreamPacketToJson(meshtastic_MeshPacket *mp) { // the created jsonObj is immutable after creation, so // we need to do the heavy lifting before assembling it. @@ -392,7 +391,7 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) JSONObject jsonObj; switch (mp->decoded.portnum) { - case PortNum_TEXT_MESSAGE_APP: { + case meshtastic_PortNum_TEXT_MESSAGE_APP: { msgType = "text"; // convert bytes to string LOG_DEBUG("got text message of size %u\n", mp->decoded.payload.size); @@ -414,20 +413,20 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) } break; } - case PortNum_TELEMETRY_APP: { + case meshtastic_PortNum_TELEMETRY_APP: { msgType = "telemetry"; - Telemetry scratch; - Telemetry *decoded = NULL; - if (mp->which_payload_variant == MeshPacket_decoded_tag) { + meshtastic_Telemetry scratch; + meshtastic_Telemetry *decoded = NULL; + if (mp->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { memset(&scratch, 0, sizeof(scratch)); - if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &Telemetry_msg, &scratch)) { + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_Telemetry_msg, &scratch)) { decoded = &scratch; - if (decoded->which_variant == Telemetry_device_metrics_tag) { + if (decoded->which_variant == meshtastic_Telemetry_device_metrics_tag) { msgPayload["battery_level"] = new JSONValue((int)decoded->variant.device_metrics.battery_level); msgPayload["voltage"] = new JSONValue(decoded->variant.device_metrics.voltage); msgPayload["channel_utilization"] = new JSONValue(decoded->variant.device_metrics.channel_utilization); msgPayload["air_util_tx"] = new JSONValue(decoded->variant.device_metrics.air_util_tx); - } else if (decoded->which_variant == Telemetry_environment_metrics_tag) { + } else if (decoded->which_variant == meshtastic_Telemetry_environment_metrics_tag) { msgPayload["temperature"] = new JSONValue(decoded->variant.environment_metrics.temperature); msgPayload["relative_humidity"] = new JSONValue(decoded->variant.environment_metrics.relative_humidity); msgPayload["barometric_pressure"] = new JSONValue(decoded->variant.environment_metrics.barometric_pressure); @@ -441,13 +440,13 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) }; break; } - case PortNum_NODEINFO_APP: { + case meshtastic_PortNum_NODEINFO_APP: { msgType = "nodeinfo"; - User scratch; - User *decoded = NULL; - if (mp->which_payload_variant == MeshPacket_decoded_tag) { + meshtastic_User scratch; + meshtastic_User *decoded = NULL; + if (mp->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { memset(&scratch, 0, sizeof(scratch)); - if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &User_msg, &scratch)) { + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_User_msg, &scratch)) { decoded = &scratch; msgPayload["id"] = new JSONValue(decoded->id); msgPayload["longname"] = new JSONValue(decoded->long_name); @@ -459,13 +458,13 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) }; break; } - case PortNum_POSITION_APP: { + case meshtastic_PortNum_POSITION_APP: { msgType = "position"; - Position scratch; - Position *decoded = NULL; - if (mp->which_payload_variant == MeshPacket_decoded_tag) { + meshtastic_Position scratch; + meshtastic_Position *decoded = NULL; + if (mp->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { memset(&scratch, 0, sizeof(scratch)); - if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &Position_msg, &scratch)) { + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_Position_msg, &scratch)) { decoded = &scratch; if ((int)decoded->time) { msgPayload["time"] = new JSONValue((int)decoded->time); @@ -486,13 +485,13 @@ std::string MQTT::downstreamPacketToJson(MeshPacket *mp) break; } - case PortNum_WAYPOINT_APP: { + case meshtastic_PortNum_WAYPOINT_APP: { msgType = "position"; - Waypoint scratch; - Waypoint *decoded = NULL; - if (mp->which_payload_variant == MeshPacket_decoded_tag) { + meshtastic_Waypoint scratch; + meshtastic_Waypoint *decoded = NULL; + if (mp->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { memset(&scratch, 0, sizeof(scratch)); - if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &Waypoint_msg, &scratch)) { + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_Waypoint_msg, &scratch)) { decoded = &scratch; msgPayload["id"] = new JSONValue((int)decoded->id); msgPayload["name"] = new JSONValue(decoded->name); diff --git a/src/mqtt/MQTT.h b/src/mqtt/MQTT.h index 3f2cf2de6..8b12e2f88 100644 --- a/src/mqtt/MQTT.h +++ b/src/mqtt/MQTT.h @@ -46,7 +46,7 @@ class MQTT : private concurrency::OSThread * Note: for messages we are forwarding on the mesh that we can't find the channel for (because we don't have the keys), we * can not forward those messages to the cloud - becuase no way to find a global channel ID. */ - void onSend(const MeshPacket &mp, ChannelIndex chIndex); + void onSend(const meshtastic_MeshPacket &mp, ChannelIndex chIndex); /** Attempt to connect to server if necessary */ @@ -55,7 +55,7 @@ class MQTT : private concurrency::OSThread bool connected(); protected: - PointerQueue mqttQueue; + PointerQueue mqttQueue; int reconnectCount = 0; @@ -77,7 +77,7 @@ class MQTT : private concurrency::OSThread void onPublish(char *topic, byte *payload, unsigned int length); /// Called when a new publish arrives from the MQTT server - std::string downstreamPacketToJson(MeshPacket *mp); + std::string downstreamPacketToJson(meshtastic_MeshPacket *mp); /// Return 0 if sleep is okay, veto sleep if we are connected to pubsub server // int preflightSleepCb(void *unused = NULL) { return pubSub.connected() ? 1 : 0; } 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..79be9a35b 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,21 +40,23 @@ 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]; + uint8_t fromRadioBytes[meshtastic_FromRadio_size]; size_t numBytes = bluetoothPhoneAPI->getFromRadio(fromRadioBytes); std::string fromRadioByteString(fromRadioBytes, fromRadioBytes + numBytes); @@ -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) { + + if (config.bluetooth.mode == meshtastic_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(); @@ -130,12 +127,12 @@ void NimbleBluetooth::setup() NimBLEDevice::init(getDeviceName()); NimBLEDevice::setPower(ESP_PWR_LVL_P9); - if (config.bluetooth.mode != Config_BluetoothConfig_PairingMode_NO_PIN) { + if (config.bluetooth.mode != meshtastic_Config_BluetoothConfig_PairingMode_NO_PIN) { NimBLEDevice::setSecurityAuth(true, true, true); NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_ONLY); } bleServer = NimBLEDevice::createServer(); - + NimbleBluetoothServerCallback *serverCallbacks = new NimbleBluetoothServerCallback(); bleServer->setCallbacks(serverCallbacks, true); @@ -143,21 +140,24 @@ void NimbleBluetooth::setup() startAdvertising(); } -void NimbleBluetooth::setupService() +void NimbleBluetooth::setupService() { NimBLEService *bleService = bleServer->createService(MESH_SERVICE_UUID); NimBLECharacteristic *ToRadioCharacteristic; NimBLECharacteristic *FromRadioCharacteristic; // Define the characteristics that the app is looking for - if (config.bluetooth.mode == Config_BluetoothConfig_PairingMode_NO_PIN) { + if (config.bluetooth.mode == meshtastic_Config_BluetoothConfig_PairingMode_NO_PIN) { 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..f4c510920 100644 --- a/src/platform/esp32/BleOta.h +++ b/src/platform/esp32/BleOta.h @@ -1,11 +1,13 @@ #ifndef BLEOTA_H #define BLEOTA_H +#include #include -class BleOta { +class BleOta +{ public: - explicit BleOta() {}; + explicit BleOta(){}; static String getOtaAppVersion(); static bool switchToOtaApp(); @@ -15,4 +17,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..7936e7f75 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 meshtastic_HardwareModel_TBEAM #elif defined(TBEAM_V07) - #define HW_VENDOR HardwareModel_TBEAM_V0P7 +#define HW_VENDOR meshtastic_HardwareModel_TBEAM_V0P7 #elif defined(LILYGO_TBEAM_S3_CORE) - #define HW_VENDOR HardwareModel_LILYGO_TBEAM_S3_CORE +#define HW_VENDOR meshtastic_HardwareModel_LILYGO_TBEAM_S3_CORE #elif defined(DIY_V1) - #define HW_VENDOR HardwareModel_DIY_V1 +#define HW_VENDOR meshtastic_HardwareModel_DIY_V1 #elif defined(RAK_11200) - #define HW_VENDOR HardwareModel_RAK11200 +#define HW_VENDOR meshtastic_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 meshtastic_HardwareModel_HELTEC_V2_0 +#endif +#ifdef HELTEC_V2_1 +#define HW_VENDOR meshtastic_HardwareModel_HELTEC_V2_1 +#endif #elif defined(ARDUINO_HELTEC_WIFI_LORA_32) - #define HW_VENDOR HardwareModel_HELTEC_V1 +#define HW_VENDOR meshtastic_HardwareModel_HELTEC_V1 #elif defined(TLORA_V1) - #define HW_VENDOR HardwareModel_TLORA_V1 +#define HW_VENDOR meshtastic_HardwareModel_TLORA_V1 #elif defined(TLORA_V2) - #define HW_VENDOR HardwareModel_TLORA_V2 +#define HW_VENDOR meshtastic_HardwareModel_TLORA_V2 #elif defined(TLORA_V1_3) - #define HW_VENDOR HardwareModel_TLORA_V1_1P3 +#define HW_VENDOR meshtastic_HardwareModel_TLORA_V1_1P3 #elif defined(TLORA_V2_1_16) - #define HW_VENDOR HardwareModel_TLORA_V2_1_1P6 +#define HW_VENDOR meshtastic_HardwareModel_TLORA_V2_1_1P6 #elif defined(TLORA_V2_1_18) - #define HW_VENDOR HardwareModel_TLORA_V2_1_1P8 +#define HW_VENDOR meshtastic_HardwareModel_TLORA_V2_1_1P8 #elif defined(GENIEBLOCKS) - #define HW_VENDOR HardwareModel_GENIEBLOCKS +#define HW_VENDOR meshtastic_HardwareModel_GENIEBLOCKS #elif defined(PRIVATE_HW) - #define HW_VENDOR HardwareModel_PRIVATE_HW +#define HW_VENDOR meshtastic_HardwareModel_PRIVATE_HW #elif defined(NANO_G1) - #define HW_VENDOR HardwareModel_NANO_G1 +#define HW_VENDOR meshtastic_HardwareModel_NANO_G1 #elif defined(M5STACK) - #define HW_VENDOR HardwareModel_M5STACK +#define HW_VENDOR meshtastic_HardwareModel_M5STACK #elif defined(STATION_G1) - #define HW_VENDOR HardwareModel_STATION_G1 +#define HW_VENDOR meshtastic_HardwareModel_STATION_G1 #elif defined(DR_DEV) - #define HW_VENDOR HardwareModel_DR_DEV +#define HW_VENDOR meshtastic_HardwareModel_DR_DEV #elif defined(HELTEC_V3) - #define HW_VENDOR HardwareModel_HELTEC_V3 +#define HW_VENDOR meshtastic_HardwareModel_HELTEC_V3 #elif defined(HELTEC_WSL_V3) - #define HW_VENDOR HardwareModel_HELTEC_WSL_V3 +#define HW_VENDOR meshtastic_HardwareModel_HELTEC_WSL_V3 #elif defined(TLORA_T3S3_V1) - #define HW_VENDOR HardwareModel_TLORA_T3_S3 +#define HW_VENDOR meshtastic_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..06b07f593 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" @@ -19,8 +19,8 @@ static BLEDfu bledfu; // DFU software update helper service // This scratch buffer is used for various bluetooth reads/writes - but it is safe because only one bt operation can be in // proccess at once // static uint8_t trBytes[_max(_max(_max(_max(ToRadio_size, RadioConfig_size), User_size), MyNodeInfo_size), FromRadio_size)]; -static uint8_t fromRadioBytes[FromRadio_size]; -static uint8_t toRadioBytes[ToRadio_size]; +static uint8_t fromRadioBytes[meshtastic_FromRadio_size]; +static uint8_t toRadioBytes[meshtastic_ToRadio_size]; static uint16_t connectionHandle; @@ -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(); } @@ -167,11 +168,13 @@ void setupMeshService(void) // any characteristic(s) within that service definition.. Calling .begin() on // a BLECharacteristic will cause it to be added to the last BLEService that // was 'begin()'ed! - auto secMode = config.bluetooth.mode == Config_BluetoothConfig_PairingMode_NO_PIN ? SECMODE_OPEN : SECMODE_ENC_NO_MITM; + auto secMode = + config.bluetooth.mode == meshtastic_Config_BluetoothConfig_PairingMode_NO_PIN ? SECMODE_OPEN : SECMODE_ENC_NO_MITM; 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 +183,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 +198,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(); } @@ -221,9 +226,10 @@ void NRF52Bluetooth::setup() Bluefruit.Advertising.clearData(); 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); + if (config.bluetooth.mode != meshtastic_Config_BluetoothConfig_PairingMode_NO_PIN) { + configuredPasskey = config.bluetooth.mode == meshtastic_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 +238,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 +251,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 +263,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 +301,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/NRF52Bluetooth.h b/src/platform/nrf52/NRF52Bluetooth.h index 025e9e4c8..b4438ff39 100644 --- a/src/platform/nrf52/NRF52Bluetooth.h +++ b/src/platform/nrf52/NRF52Bluetooth.h @@ -1,5 +1,7 @@ #pragma once +#include + class NRF52Bluetooth { public: 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..383a0da4e 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 meshtastic_HardwareModel_NRF52840DK #elif defined(ARDUINO_NRF52840_PPR) - #define HW_VENDOR HardwareModel_PPR +#define HW_VENDOR meshtastic_HardwareModel_PPR #elif defined(RAK4630) - #define HW_VENDOR HardwareModel_RAK4631 +#define HW_VENDOR meshtastic_HardwareModel_RAK4631 #elif defined(TTGO_T_ECHO) - #define HW_VENDOR HardwareModel_T_ECHO +#define HW_VENDOR meshtastic_HardwareModel_T_ECHO #elif defined(NORDIC_PCA10059) - #define HW_VENDOR HardwareModel_NRF52840_PCA10059 +#define HW_VENDOR meshtastic_HardwareModel_NRF52840_PCA10059 #elif defined(PRIVATE_HW) || defined(FEATHER_DIY) - #define HW_VENDOR HardwareModel_PRIVATE_HW +#define HW_VENDOR meshtastic_HardwareModel_PRIVATE_HW #else - #define HW_VENDOR HardwareModel_NRF52_UNKNOWN +#define HW_VENDOR meshtastic_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..0384073a4 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(); } @@ -108,7 +109,7 @@ void checkSDEvents() while (NRF_SUCCESS == sd_evt_get(&evt)) { switch (evt) { case NRF_EVT_POWER_FAILURE_WARNING: - RECORD_CRITICALERROR(CriticalErrorCode_BROWNOUT); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_BROWNOUT); break; default: @@ -118,7 +119,7 @@ void checkSDEvents() } } else { if (NRF_POWER->EVENTS_POFWARN) - RECORD_CRITICALERROR(CriticalErrorCode_BROWNOUT); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_BROWNOUT); } } @@ -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..fa4212669 100644 --- a/src/platform/portduino/SimRadio.cpp +++ b/src/platform/portduino/SimRadio.cpp @@ -9,7 +9,7 @@ SimRadio::SimRadio() SimRadio *SimRadio::instance; -ErrorCode SimRadio::send(MeshPacket *p) +ErrorCode SimRadio::send(meshtastic_MeshPacket *p) { printPacket("enqueuing for send", p); @@ -29,15 +29,15 @@ ErrorCode SimRadio::send(MeshPacket *p) void SimRadio::setTransmitDelay() { - MeshPacket *p = txQueue.getFront(); + meshtastic_MeshPacket *p = txQueue.getFront(); // We want all sending/receiving to be done by our daemon thread. // We use a delay here because this packet might have been sent in response to a packet we just received. // 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"); @@ -165,7 +163,7 @@ void SimRadio::onNotify(uint32_t notification) setTransmitDelay(); // reset random delay } else { // Send any outgoing packets we have ready - MeshPacket *txp = txQueue.dequeue(); + meshtastic_MeshPacket *txp = txQueue.dequeue(); assert(txp); startSend(txp); // Packet has been sent, count it toward our TX airtime utilization. @@ -179,35 +177,36 @@ 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(meshtastic_MeshPacket *txp) { printPacket("Starting low level send", txp); size_t numbytes = beginSending(txp); - MeshPacket* p = packetPool.allocCopy(*txp); + meshtastic_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); + meshtastic_Compressed c = meshtastic_Compressed_init_default; + 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"); } - p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &Compressed_msg, &c); - p->decoded.portnum = PortNum_SIMULATOR_APP; + p->decoded.payload.size = + pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &meshtastic_Compressed_msg, &c); + p->decoded.portnum = meshtastic_PortNum_SIMULATOR_APP; service.sendToPhone(p); // Sending back to simulator } - -void SimRadio::startReceive(MeshPacket *p) { +void SimRadio::startReceive(meshtastic_MeshPacket *p) +{ isReceiving = true; size_t length = getPacketLength(p); uint32_t xmitMsec = getPacketTime(length); @@ -215,9 +214,9 @@ void SimRadio::startReceive(MeshPacket *p) { handleReceiveInterrupt(p); } -QueueStatus SimRadio::getQueueStatus() +meshtastic_QueueStatus SimRadio::getQueueStatus() { - QueueStatus qs; + meshtastic_QueueStatus qs; qs.res = qs.mesh_packet_id = 0; qs.free = txQueue.getFree(); @@ -226,7 +225,7 @@ QueueStatus SimRadio::getQueueStatus() return qs; } -void SimRadio::handleReceiveInterrupt(MeshPacket *p) +void SimRadio::handleReceiveInterrupt(meshtastic_MeshPacket *p) { LOG_DEBUG("HANDLE RECEIVE INTERRUPT\n"); uint32_t xmitMsec; @@ -243,8 +242,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 + meshtastic_MeshPacket *mp = packetPool.allocCopy(*p); // keep a copy in packtPool + mp->which_payload_variant = meshtastic_MeshPacket_decoded_tag; // Mark that the payload is already decoded printPacket("Lora RX", mp); @@ -253,15 +252,17 @@ void SimRadio::handleReceiveInterrupt(MeshPacket *p) deliverToReceiver(mp); } -size_t SimRadio::getPacketLength(MeshPacket *mp) { +size_t SimRadio::getPacketLength(meshtastic_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..b78beb70a 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,8 +24,7 @@ class SimRadio : public RadioInterface */ static SimRadio *instance; - - virtual ErrorCode send(MeshPacket *p) override; + virtual ErrorCode send(meshtastic_MeshPacket *p) override; /** can we detect a LoRa preamble on the current channel? */ virtual bool isChannelActive(); @@ -38,22 +37,20 @@ 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. */ - virtual void startReceive(MeshPacket *p); + virtual void startReceive(meshtastic_MeshPacket *p); - QueueStatus getQueueStatus() override; + meshtastic_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 */ @@ -63,27 +60,25 @@ class SimRadio : public RadioInterface void startTransmitTimerSNR(float snr); void handleTransmitInterrupt(); - void handleReceiveInterrupt(MeshPacket *p); + void handleReceiveInterrupt(meshtastic_MeshPacket *p); void onNotify(uint32_t notification); // start an immediate transmit - virtual void startSend(MeshPacket *txp); + virtual void startSend(meshtastic_MeshPacket *txp); // derive packet length - size_t getPacketLength(MeshPacket *p); + size_t getPacketLength(meshtastic_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/portduino/architecture.h b/src/platform/portduino/architecture.h index 1b77afaa6..54df672d8 100644 --- a/src/platform/portduino/architecture.h +++ b/src/platform/portduino/architecture.h @@ -10,7 +10,7 @@ // set HW_VENDOR // -#define HW_VENDOR HardwareModel_PORTDUINO +#define HW_VENDOR meshtastic_HardwareModel_PORTDUINO #define HAS_RTC 1 #define HAS_WIFI 1 diff --git a/src/platform/rp2040/architecture.h b/src/platform/rp2040/architecture.h index 35d163e4a..c5a2ecdec 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 meshtastic_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..54502a5bd 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 @@ -156,14 +157,14 @@ static void waitEnterSleep() delay(100); // Kinda yucky - wait until radio says say we can shutdown (finished in process sends/receives) if (millis() - now > 30 * 1000) { // If we wait too long just report an error and go to sleep - RECORD_CRITICALERROR(CriticalErrorCode_SLEEP_ENTER_WAIT); + RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_SLEEP_ENTER_WAIT); assert(0); // FIXME - for now we just restart, need to fix bug #167 break; } } // 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/src/xmodem.cpp b/src/xmodem.cpp index aed551795..f8b5084dc 100644 --- a/src/xmodem.cpp +++ b/src/xmodem.cpp @@ -34,10 +34,7 @@ XModemAdapter xModem; -XModemAdapter::XModemAdapter() -{ - xmodemStore = (XModem *)malloc(XModem_size); -} +XModemAdapter::XModemAdapter() {} unsigned short XModemAdapter::crc16_ccitt(const pb_byte_t *buffer, int length) { @@ -57,47 +54,44 @@ unsigned short XModemAdapter::crc16_ccitt(const pb_byte_t *buffer, int length) int XModemAdapter::check(const pb_byte_t *buf, int sz, unsigned short tcrc) { - unsigned short crc = crc16_ccitt(buf, sz); - if (crc == tcrc) - return 1; - else - return 0; + return crc16_ccitt(buf, sz) == tcrc; } -void XModemAdapter::sendControl(XModem_Control c) +void XModemAdapter::sendControl(meshtastic_XModem_Control c) { - memset(xmodemStore, 0, XModem_size); - xmodemStore->control = c; + xmodemStore = meshtastic_XModem_init_zero; + xmodemStore.control = c; LOG_DEBUG("XModem: Notify Sending control %d.\n", c); packetReady.notifyObservers(packetno); } -XModem *XModemAdapter::getForPhone() +meshtastic_XModem XModemAdapter::getForPhone() { - if (xmodemStore) { - return xmodemStore; - } else { - return NULL; - } + return xmodemStore; } -void XModemAdapter::handlePacket(XModem xmodemPacket) +void XModemAdapter::resetForPhone() +{ + xmodemStore = meshtastic_XModem_init_zero; +} + +void XModemAdapter::handlePacket(meshtastic_XModem xmodemPacket) { switch (xmodemPacket.control) { - case XModem_Control_SOH: - case XModem_Control_STX: + case meshtastic_XModem_Control_SOH: + case meshtastic_XModem_Control_STX: if ((xmodemPacket.seq == 0) && !isReceiving && !isTransmitting) { // NULL packet has the destination filename memcpy(filename, &xmodemPacket.buffer.bytes, xmodemPacket.buffer.size); - if (xmodemPacket.control == XModem_Control_SOH) { // Receive this file and put to Flash + if (xmodemPacket.control == meshtastic_XModem_Control_SOH) { // Receive this file and put to Flash file = FSCom.open(filename, FILE_O_WRITE); if (file) { - sendControl(XModem_Control_ACK); + sendControl(meshtastic_XModem_Control_ACK); isReceiving = true; packetno = 1; break; } - sendControl(XModem_Control_NAK); + sendControl(meshtastic_XModem_Control_NAK); isReceiving = false; break; } else { // Transmit this file from Flash @@ -106,20 +100,20 @@ void XModemAdapter::handlePacket(XModem xmodemPacket) if (file) { packetno = 1; isTransmitting = true; - memset(xmodemStore, 0, XModem_size); - xmodemStore->control = XModem_Control_SOH; - xmodemStore->seq = packetno; - xmodemStore->buffer.size = file.read(xmodemStore->buffer.bytes, sizeof(XModem_buffer_t::bytes)); - xmodemStore->crc16 = crc16_ccitt(xmodemStore->buffer.bytes, xmodemStore->buffer.size); - LOG_DEBUG("XModem: STX Notify Sending packet %d, %d Bytes.\n", packetno, xmodemStore->buffer.size); - if (xmodemStore->buffer.size < sizeof(XModem_buffer_t::bytes)) { + xmodemStore = meshtastic_XModem_init_zero; + xmodemStore.control = meshtastic_XModem_Control_SOH; + xmodemStore.seq = packetno; + xmodemStore.buffer.size = file.read(xmodemStore.buffer.bytes, sizeof(meshtastic_XModem_buffer_t::bytes)); + xmodemStore.crc16 = crc16_ccitt(xmodemStore.buffer.bytes, xmodemStore.buffer.size); + LOG_DEBUG("XModem: STX Notify Sending packet %d, %d Bytes.\n", packetno, xmodemStore.buffer.size); + if (xmodemStore.buffer.size < sizeof(meshtastic_XModem_buffer_t::bytes)) { isEOT = true; // send EOT on next Ack } packetReady.notifyObservers(packetno); break; } - sendControl(XModem_Control_NAK); + sendControl(meshtastic_XModem_Control_NAK); isTransmitting = false; break; } @@ -130,39 +124,39 @@ void XModemAdapter::handlePacket(XModem xmodemPacket) check(xmodemPacket.buffer.bytes, xmodemPacket.buffer.size, xmodemPacket.crc16)) { // valid packet file.write(xmodemPacket.buffer.bytes, xmodemPacket.buffer.size); - sendControl(XModem_Control_ACK); + sendControl(meshtastic_XModem_Control_ACK); packetno++; break; } // invalid packet - sendControl(XModem_Control_NAK); + sendControl(meshtastic_XModem_Control_NAK); break; } else if (isTransmitting) { // just received something weird. - sendControl(XModem_Control_CAN); + sendControl(meshtastic_XModem_Control_CAN); isTransmitting = false; break; } } break; - case XModem_Control_EOT: + case meshtastic_XModem_Control_EOT: // End of transmission - sendControl(XModem_Control_ACK); + sendControl(meshtastic_XModem_Control_ACK); file.close(); isReceiving = false; break; - case XModem_Control_CAN: + case meshtastic_XModem_Control_CAN: // Cancel transmission and remove file - sendControl(XModem_Control_ACK); + sendControl(meshtastic_XModem_Control_ACK); file.close(); FSCom.remove(filename); isReceiving = false; break; - case XModem_Control_ACK: + case meshtastic_XModem_Control_ACK: // Acknowledge Send the next packet if (isTransmitting) { if (isEOT) { - sendControl(XModem_Control_EOT); + sendControl(meshtastic_XModem_Control_EOT); file.close(); LOG_INFO("XModem: Finished sending file %s\n", filename); isTransmitting = false; @@ -171,47 +165,47 @@ void XModemAdapter::handlePacket(XModem xmodemPacket) } retrans = MAXRETRANS; // reset retransmit counter packetno++; - memset(xmodemStore, 0, XModem_size); - xmodemStore->control = XModem_Control_SOH; - xmodemStore->seq = packetno; - xmodemStore->buffer.size = file.read(xmodemStore->buffer.bytes, sizeof(XModem_buffer_t::bytes)); - xmodemStore->crc16 = crc16_ccitt(xmodemStore->buffer.bytes, xmodemStore->buffer.size); - LOG_DEBUG("XModem: ACK Notify Sending packet %d, %d Bytes.\n", packetno, xmodemStore->buffer.size); - if (xmodemStore->buffer.size < sizeof(XModem_buffer_t::bytes)) { + xmodemStore = meshtastic_XModem_init_zero; + xmodemStore.control = meshtastic_XModem_Control_SOH; + xmodemStore.seq = packetno; + xmodemStore.buffer.size = file.read(xmodemStore.buffer.bytes, sizeof(meshtastic_XModem_buffer_t::bytes)); + xmodemStore.crc16 = crc16_ccitt(xmodemStore.buffer.bytes, xmodemStore.buffer.size); + LOG_DEBUG("XModem: ACK Notify Sending packet %d, %d Bytes.\n", packetno, xmodemStore.buffer.size); + if (xmodemStore.buffer.size < sizeof(meshtastic_XModem_buffer_t::bytes)) { isEOT = true; // send EOT on next Ack } packetReady.notifyObservers(packetno); } else { // just received something weird. - sendControl(XModem_Control_CAN); + sendControl(meshtastic_XModem_Control_CAN); } break; - case XModem_Control_NAK: + case meshtastic_XModem_Control_NAK: // Negative acknowledge. Send the same buffer again if (isTransmitting) { if (--retrans <= 0) { - sendControl(XModem_Control_CAN); + sendControl(meshtastic_XModem_Control_CAN); file.close(); LOG_INFO("XModem: Retransmit timeout, cancelling file %s\n", filename); isTransmitting = false; break; } - memset(xmodemStore, 0, XModem_size); - xmodemStore->control = XModem_Control_SOH; - xmodemStore->seq = packetno; - file.seek((packetno - 1) * sizeof(XModem_buffer_t::bytes)); - xmodemStore->buffer.size = file.read(xmodemStore->buffer.bytes, sizeof(XModem_buffer_t::bytes)); - xmodemStore->crc16 = crc16_ccitt(xmodemStore->buffer.bytes, xmodemStore->buffer.size); - LOG_DEBUG("XModem: NAK Notify Sending packet %d, %d Bytes.\n", packetno, xmodemStore->buffer.size); - if (xmodemStore->buffer.size < sizeof(XModem_buffer_t::bytes)) { + xmodemStore = meshtastic_XModem_init_zero; + xmodemStore.control = meshtastic_XModem_Control_SOH; + xmodemStore.seq = packetno; + file.seek((packetno - 1) * sizeof(meshtastic_XModem_buffer_t::bytes)); + xmodemStore.buffer.size = file.read(xmodemStore.buffer.bytes, sizeof(meshtastic_XModem_buffer_t::bytes)); + xmodemStore.crc16 = crc16_ccitt(xmodemStore.buffer.bytes, xmodemStore.buffer.size); + LOG_DEBUG("XModem: NAK Notify Sending packet %d, %d Bytes.\n", packetno, xmodemStore.buffer.size); + if (xmodemStore.buffer.size < sizeof(meshtastic_XModem_buffer_t::bytes)) { isEOT = true; // send EOT on next Ack } packetReady.notifyObservers(packetno); } else { // just received something weird. - sendControl(XModem_Control_CAN); + sendControl(meshtastic_XModem_Control_CAN); } break; default: diff --git a/src/xmodem.h b/src/xmodem.h index 8a9c08db6..848e926bd 100644 --- a/src/xmodem.h +++ b/src/xmodem.h @@ -46,8 +46,9 @@ class XModemAdapter XModemAdapter(); - void handlePacket(XModem xmodemPacket); - XModem *getForPhone(); + void handlePacket(meshtastic_XModem xmodemPacket); + meshtastic_XModem getForPhone(); + void resetForPhone(); private: bool isReceiving = false; @@ -58,19 +59,19 @@ class XModemAdapter uint16_t packetno = 0; -#ifdef ARCH_NRF52 +#if defined(ARCH_NRF52) File file = File(FSCom); #else File file; #endif - char filename[sizeof(XModem_buffer_t::bytes)] = {0}; + char filename[sizeof(meshtastic_XModem_buffer_t::bytes)] = {0}; protected: - XModem *xmodemStore = NULL; + meshtastic_XModem xmodemStore = meshtastic_XModem_init_zero; unsigned short crc16_ccitt(const pb_byte_t *buffer, int length); int check(const pb_byte_t *buf, int sz, unsigned short tcrc); - void sendControl(XModem_Control c); + void sendControl(meshtastic_XModem_Control c); }; extern XModemAdapter xModem; 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..712a88091 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 @@ -44,6 +44,9 @@ #define RF95_RXEN 14 #define RF95_TXEN 13 +// Set lora.tx_power to 13 for Hydra or other E22 900M30S target due to PA +#define SX126X_MAX_POWER 22 + #ifdef EBYTE_E22 // Internally the TTGO module hooks the SX126x-DIO2 in to control the TX/RX switch // (which is the default for the sx1262interface code) 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..68b2b1172 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,8 +135,8 @@ 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 -//#define PIN_EINK_PWR_ON (-1) +// 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,17 +172,41 @@ 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 + +/* Setup of the SX1262 LoRa module ( https://docs.rakwireless.com/Product-Categories/WisBlock/RAK4631/Datasheet/ ) + +P1.10 NSS SPI NSS (Arduino GPIO number 42) +P1.11 SCK SPI CLK (Arduino GPIO number 43) +P1.12 MOSI SPI MOSI (Arduino GPIO number 44) +P1.13 MISO SPI MISO (Arduino GPIO number 45) +P1.14 BUSY BUSY signal (Arduino GPIO number 46) +P1.15 DIO1 DIO1 event interrupt (Arduino GPIO number 47) +P1.06 NRESET NRESET manual reset of the SX1262 (Arduino GPIO number 38) + +Important for successful SX1262 initialization: + +* Setup DIO2 to control the antenna switch +* Setup DIO3 to control the TCXO power supply +* Setup the SX1262 to use it's DCDC regulator and not the LDO +* RAK4630 schematics show GPIO P1.07 connected to the antenna switch, but it should not be initialized, as DIO2 will do the +control of the antenna switch + +SO GPIO 39/TXEN MAY NOT BE DEFINED FOR SUCCESSFUL OPERATION OF THE SX1262 - TG + +*/ + #define USE_SX1262 #define SX126X_CS (42) #define SX126X_DIO1 (47) #define SX126X_BUSY (46) #define SX126X_RESET (38) -#define SX126X_TXEN (39) -#define SX126X_RXEN (37) +// #define SX126X_TXEN (39) +// #define SX126X_RXEN (37) +#define SX126X_POWER_EN (37) #define SX126X_E22 // DIO2 controlls an antenna switch and the TCXO voltage is controlled by DIO3 // enables 3.3V periphery like GPS or IO Module @@ -203,7 +226,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 +249,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..3d597d3d1 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,8 +135,8 @@ 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 -//#define PIN_EINK_PWR_ON (-1) +// 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 @@ -182,8 +181,9 @@ static const uint8_t SCK = PIN_SPI_SCK; #define SX126X_DIO1 (47) #define SX126X_BUSY (46) #define SX126X_RESET (38) -#define SX126X_TXEN (39) -#define SX126X_RXEN (37) +// #define SX126X_TXEN (39) +// #define SX126X_RXEN (37) +#define SX126X_POWER_EN (37) #define SX126X_E22 // DIO2 controlls an antenna switch and the TCXO voltage is controlled by DIO3 // enables 3.3V periphery like GPS or IO Module @@ -203,7 +203,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 +222,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 diff --git a/version.properties b/version.properties index 7cf773466..26a503776 100644 --- a/version.properties +++ b/version.properties @@ -1,4 +1,4 @@ [VERSION] major = 2 minor = 0 -build = 14 +build = 17