diff --git a/.github/workflows/main_matrix.yml b/.github/workflows/main_matrix.yml index 555d4d0927..0853df19f8 100644 --- a/.github/workflows/main_matrix.yml +++ b/.github/workflows/main_matrix.yml @@ -134,8 +134,8 @@ jobs: package-raspbian-armv7l: uses: ./.github/workflows/package_raspbian_armv7l.yml - # package-native: - # uses: ./.github/workflows/package_amd64.yml + package-native: + uses: ./.github/workflows/package_amd64.yml after-checks: runs-on: ubuntu-latest @@ -249,7 +249,7 @@ jobs: gather-artifacts, package-raspbian, package-raspbian-armv7l, - # package-native, + package-native, ] steps: - name: Checkout @@ -308,15 +308,15 @@ jobs: asset_name: meshtasticd_${{ steps.version.outputs.version }}_armhf.deb asset_content_type: application/vnd.debian.binary-package - # - name: Add raspbian amd64 .deb - # uses: actions/upload-release-asset@v1 - # env: - # GITHUB_TOKEN: ${{ github.token }} - # with: - # upload_url: ${{ steps.create_release.outputs.upload_url }} - # asset_path: ./output/meshtasticd_${{ steps.version.outputs.version }}_amd64.deb - # asset_name: meshtasticd_${{ steps.version.outputs.version }}_amd64.deb - # asset_content_type: application/vnd.debian.binary-package + - name: Add raspbian amd64 .deb + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ github.token }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./output/meshtasticd_${{ steps.version.outputs.version }}_amd64.deb + asset_name: meshtasticd_${{ steps.version.outputs.version }}_amd64.deb + asset_content_type: application/vnd.debian.binary-package - name: Bump version.properties run: >- diff --git a/arch/rp2xx0/rp2040.ini b/arch/rp2xx0/rp2040.ini index 5b4ec74d2d..c004a3becb 100644 --- a/arch/rp2xx0/rp2040.ini +++ b/arch/rp2xx0/rp2040.ini @@ -1,14 +1,16 @@ ; Common settings for rp2040 Processor based targets [rp2040_base] -platform = https://github.com/maxgerhardt/platform-raspberrypi.git#60d6ae81fcc73c34b1493ca9e261695e471bc0c2 +platform = https://github.com/maxgerhardt/platform-raspberrypi.git#v1.2.0-gcc12 extends = arduino_base -platform_packages = framework-arduinopico@https://github.com/earlephilhower/arduino-pico.git#3.7.2 +platform_packages = framework-arduinopico@https://github.com/earlephilhower/arduino-pico.git#4.0.3 board_build.core = earlephilhower board_build.filesystem_size = 0.5m build_flags = ${arduino_base.build_flags} -Wno-unused-variable -Wcast-align -Isrc/platform/rp2xx0 + -Isrc/platform/rp2xx0/hardware_rosc/include + -Isrc/platform/rp2xx0/pico_sleep/include -D__PLAT_RP2040__ # -D _POSIX_THREADS build_src_filter = diff --git a/bin/config-dist.yaml b/bin/config-dist.yaml index 3a470b7bbe..a755954b1f 100644 --- a/bin/config-dist.yaml +++ b/bin/config-dist.yaml @@ -20,6 +20,7 @@ Lora: # CS: 0 # IRQ: 10 # Busy: 11 +# DIO2_AS_RF_SWITCH: true # spidev: spidev0.1 # Module: RF95 # Adafruit RFM9x @@ -154,4 +155,4 @@ Webserver: General: MaxNodes: 200 - MaxMessageQueue: 100 \ No newline at end of file + MaxMessageQueue: 100 diff --git a/bin/meshtasticd.service b/bin/meshtasticd.service index f15fdc8714..1e8ee98b8a 100644 --- a/bin/meshtasticd.service +++ b/bin/meshtasticd.service @@ -1,12 +1,16 @@ [Unit] Description=Meshtastic Native Daemon After=network-online.target +StartLimitInterval=200 +StartLimitBurst=5 [Service] User=root Group=root Type=simple ExecStart=/usr/sbin/meshtasticd +Restart=always +RestartSec=3 [Install] -WantedBy=multi-user.target \ No newline at end of file +WantedBy=multi-user.target diff --git a/bin/native-install.sh b/bin/native-install.sh index ba71c4f46b..a8fcc29a6a 100755 --- a/bin/native-install.sh +++ b/bin/native-install.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash cp "release/meshtasticd_linux_$(uname -m)" /usr/sbin/meshtasticd -mkdir /etc/meshtasticd +mkdir -p /etc/meshtasticd if [[ -f "/etc/meshtasticd/config.yaml" ]]; then cp bin/config-dist.yaml /etc/meshtasticd/config-upgrade.yaml else diff --git a/images/compass.png b/images/compass.png index 8639dde524..c4e5b589bc 100644 Binary files a/images/compass.png and b/images/compass.png differ diff --git a/images/face-24px.svg b/images/face-24px.svg index 293468664d..08e8f5ffcc 100644 --- a/images/face-24px.svg +++ b/images/face-24px.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/images/face.png b/images/face.png index 036e29f734..eb6b91e13b 100644 Binary files a/images/face.png and b/images/face.png differ diff --git a/images/location_searching-24px.svg b/images/location_searching-24px.svg index 7f72a31bc7..abef0ef788 100644 --- a/images/location_searching-24px.svg +++ b/images/location_searching-24px.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/images/pin.png b/images/pin.png index 112a7ce8ed..3c91a726c3 100644 Binary files a/images/pin.png and b/images/pin.png differ diff --git a/images/room-24px.svg b/images/room-24px.svg index 79a4807e7c..48e55ab80e 100644 --- a/images/room-24px.svg +++ b/images/room-24px.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/images/textsms-24px.svg b/images/textsms-24px.svg index 4455f047e3..84c4fdcc1d 100644 --- a/images/textsms-24px.svg +++ b/images/textsms-24px.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/platformio.ini b/platformio.ini index 5dcf61afdf..2e3ee56f95 100644 --- a/platformio.ini +++ b/platformio.ini @@ -27,6 +27,7 @@ default_envs = tbeam ;default_envs = meshtastic-dr-dev ;default_envs = m5stack-coreink ;default_envs = rak4631 +;default_envs = rak4631_eth_gw ;default_envs = rak2560 ;default_envs = rak10701 ;default_envs = wio-e5 @@ -95,7 +96,7 @@ lib_deps = https://github.com/meshtastic/ArduinoThread.git#1ae8778c85d0a2a729f989e0b1e7d7c4dc84eef0 nanopb/Nanopb@^0.4.9 erriez/ErriezCRC32@^1.0.1 - + ; Used for the code analysis in PIO Home / Inspect check_tool = cppcheck check_skip_packages = yes @@ -152,6 +153,8 @@ lib_deps = ClosedCube OPT3001@^1.1.2 emotibit/EmotiBit MLX90632@^1.0.8 dfrobot/DFRobot_RTU@^1.0.3 + sparkfun/SparkFun MAX3010x Pulse and Proximity Sensor Library@^1.1.2 + adafruit/Adafruit MLX90614 Library@^2.1.5 https://github.com/boschsensortec/Bosch-BSEC2-Library#v1.7.2502 boschsensortec/BME68x Sensor Library@^1.1.40407 diff --git a/protobufs b/protobufs index c9ae7fd478..7dc7a6d219 160000 --- a/protobufs +++ b/protobufs @@ -1 +1 @@ -Subproject commit c9ae7fd478bffe5f954b30de6cb140821fe9ff52 +Subproject commit 7dc7a6d21991efe362c7cbb556573f6bb285e407 diff --git a/src/AmbientLightingThread.h b/src/AmbientLightingThread.h index fdd4b53fac..07764e66e2 100644 --- a/src/AmbientLightingThread.h +++ b/src/AmbientLightingThread.h @@ -42,18 +42,18 @@ class AmbientLightingThread : public concurrency::OSThread #ifdef HAS_NCP5623 _type = type; if (_type == ScanI2C::DeviceType::NONE) { - LOG_DEBUG("AmbientLightingThread disabling due to no RGB leds found on I2C bus\n"); + LOG_DEBUG("AmbientLightingThread disabling due to no RGB leds found on I2C bus"); disable(); return; } #endif #if defined(HAS_NCP5623) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE) if (!moduleConfig.ambient_lighting.led_state) { - LOG_DEBUG("AmbientLightingThread disabling due to moduleConfig.ambient_lighting.led_state OFF\n"); + LOG_DEBUG("AmbientLightingThread disabling due to moduleConfig.ambient_lighting.led_state OFF"); disable(); return; } - LOG_DEBUG("AmbientLightingThread initializing\n"); + LOG_DEBUG("AmbientLightingThread initializing"); #ifdef HAS_NCP5623 if (_type == ScanI2C::NCP5623) { rgb.begin(); @@ -106,27 +106,27 @@ class AmbientLightingThread : public concurrency::OSThread rgb.setRed(0); rgb.setGreen(0); rgb.setBlue(0); - LOG_INFO("Turn Off NCP5623 Ambient lighting.\n"); + LOG_INFO("Turn Off NCP5623 Ambient lighting."); #endif #ifdef HAS_NEOPIXEL pixels.clear(); pixels.show(); - LOG_INFO("Turn Off NeoPixel Ambient lighting.\n"); + LOG_INFO("Turn Off NeoPixel Ambient lighting."); #endif #ifdef RGBLED_CA analogWrite(RGBLED_RED, 255 - 0); analogWrite(RGBLED_GREEN, 255 - 0); analogWrite(RGBLED_BLUE, 255 - 0); - LOG_INFO("Turn Off Ambient lighting RGB Common Anode.\n"); + LOG_INFO("Turn Off Ambient lighting RGB Common Anode."); #elif defined(RGBLED_RED) analogWrite(RGBLED_RED, 0); analogWrite(RGBLED_GREEN, 0); analogWrite(RGBLED_BLUE, 0); - LOG_INFO("Turn Off Ambient lighting RGB Common Cathode.\n"); + LOG_INFO("Turn Off Ambient lighting RGB Common Cathode."); #endif #ifdef UNPHONE unphone.rgb(0, 0, 0); - LOG_INFO("Turn Off unPhone Ambient lighting.\n"); + LOG_INFO("Turn Off unPhone Ambient lighting."); #endif return 0; } @@ -138,7 +138,7 @@ class AmbientLightingThread : public concurrency::OSThread rgb.setRed(moduleConfig.ambient_lighting.red); rgb.setGreen(moduleConfig.ambient_lighting.green); rgb.setBlue(moduleConfig.ambient_lighting.blue); - LOG_DEBUG("Initializing NCP5623 Ambient lighting w/ current=%d, red=%d, green=%d, blue=%d\n", + LOG_DEBUG("Initializing NCP5623 Ambient lighting w/ current=%d, red=%d, green=%d, blue=%d", moduleConfig.ambient_lighting.current, moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue); #endif @@ -158,7 +158,7 @@ class AmbientLightingThread : public concurrency::OSThread #endif #endif pixels.show(); - LOG_DEBUG("Initializing NeoPixel Ambient lighting w/ brightness(current)=%d, red=%d, green=%d, blue=%d\n", + LOG_DEBUG("Initializing NeoPixel Ambient lighting w/ brightness(current)=%d, red=%d, green=%d, blue=%d", moduleConfig.ambient_lighting.current, moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue); #endif @@ -166,18 +166,18 @@ class AmbientLightingThread : public concurrency::OSThread analogWrite(RGBLED_RED, 255 - moduleConfig.ambient_lighting.red); analogWrite(RGBLED_GREEN, 255 - moduleConfig.ambient_lighting.green); analogWrite(RGBLED_BLUE, 255 - moduleConfig.ambient_lighting.blue); - LOG_DEBUG("Initializing Ambient lighting RGB Common Anode w/ red=%d, green=%d, blue=%d\n", + LOG_DEBUG("Initializing Ambient lighting RGB Common Anode w/ red=%d, green=%d, blue=%d", moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue); #elif defined(RGBLED_RED) analogWrite(RGBLED_RED, moduleConfig.ambient_lighting.red); analogWrite(RGBLED_GREEN, moduleConfig.ambient_lighting.green); analogWrite(RGBLED_BLUE, moduleConfig.ambient_lighting.blue); - LOG_DEBUG("Initializing Ambient lighting RGB Common Cathode w/ red=%d, green=%d, blue=%d\n", + LOG_DEBUG("Initializing Ambient lighting RGB Common Cathode w/ red=%d, green=%d, blue=%d", moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue); #endif #ifdef UNPHONE unphone.rgb(moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue); - LOG_DEBUG("Initializing unPhone Ambient lighting w/ red=%d, green=%d, blue=%d\n", moduleConfig.ambient_lighting.red, + LOG_DEBUG("Initializing unPhone Ambient lighting w/ red=%d, green=%d, blue=%d", moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue); #endif } diff --git a/src/ButtonThread.cpp b/src/ButtonThread.cpp index 9e6ef55f51..ca4d40e158 100644 --- a/src/ButtonThread.cpp +++ b/src/ButtonThread.cpp @@ -36,7 +36,7 @@ ButtonThread::ButtonThread() : OSThread("Button") #if defined(ARCH_PORTDUINO) if (settingsMap.count(user) != 0 && settingsMap[user] != RADIOLIB_NC) { this->userButton = OneButton(settingsMap[user], true, true); - LOG_DEBUG("Using GPIO%02d for button\n", settingsMap[user]); + LOG_DEBUG("Using GPIO%02d for button", settingsMap[user]); } #elif defined(BUTTON_PIN) int pin = config.device.button_gpio ? config.device.button_gpio : BUTTON_PIN; // Resolved button pin @@ -47,7 +47,7 @@ ButtonThread::ButtonThread() : OSThread("Button") #else this->userButton = OneButton(pin, true, true); #endif - LOG_DEBUG("Using GPIO%02d for button\n", pin); + LOG_DEBUG("Using GPIO%02d for button", pin); #endif #ifdef INPUT_PULLUP_SENSE @@ -123,7 +123,7 @@ int32_t ButtonThread::runOnce() if (btnEvent != BUTTON_EVENT_NONE) { switch (btnEvent) { case BUTTON_EVENT_PRESSED: { - LOG_BUTTON("press!\n"); + LOG_BUTTON("press!"); // If a nag notification is running, stop it and prevent other actions if (moduleConfig.external_notification.enabled && (externalNotificationModule->nagCycleCutoff != UINT32_MAX)) { externalNotificationModule->stopNow(); @@ -148,7 +148,7 @@ int32_t ButtonThread::runOnce() } case BUTTON_EVENT_DOUBLE_PRESSED: { - LOG_BUTTON("Double press!\n"); + LOG_BUTTON("Double press!"); service->refreshLocalMeshNode(); auto sentPosition = service->trySendPosition(NODENUM_BROADCAST, true); if (screen) { @@ -162,7 +162,7 @@ int32_t ButtonThread::runOnce() } case BUTTON_EVENT_MULTI_PRESSED: { - LOG_BUTTON("Mulitipress! %hux\n", multipressClickCount); + LOG_BUTTON("Mulitipress! %hux", multipressClickCount); switch (multipressClickCount) { #if HAS_GPS // 3 clicks: toggle GPS @@ -189,7 +189,7 @@ int32_t ButtonThread::runOnce() } // end multipress event case BUTTON_EVENT_LONG_PRESSED: { - LOG_BUTTON("Long press!\n"); + LOG_BUTTON("Long press!"); powerFSM.trigger(EVENT_PRESS); if (screen) { screen->startAlert("Shutting down..."); @@ -201,7 +201,7 @@ int32_t ButtonThread::runOnce() // Do actual shutdown when button released, otherwise the button release // may wake the board immediatedly. case BUTTON_EVENT_LONG_RELEASED: { - LOG_INFO("Shutdown from long press\n"); + LOG_INFO("Shutdown from long press"); playShutdownMelody(); delay(3000); power->shutdown(); @@ -210,7 +210,7 @@ int32_t ButtonThread::runOnce() #ifdef BUTTON_PIN_TOUCH case BUTTON_EVENT_TOUCH_LONG_PRESSED: { - LOG_BUTTON("Touch press!\n"); + LOG_BUTTON("Touch press!"); if (screen) { // Wake if asleep if (powerFSM.getState() == &stateDARK) diff --git a/src/FSCommon.cpp b/src/FSCommon.cpp index 24d3f477e6..cea1130aaa 100644 --- a/src/FSCommon.cpp +++ b/src/FSCommon.cpp @@ -53,7 +53,7 @@ bool lfs_assert_failed = extern "C" void lfs_assert(const char *reason) { - LOG_ERROR("LFS assert: %s\n", reason); + LOG_ERROR("LFS assert: %s", reason); lfs_assert_failed = true; } @@ -75,19 +75,19 @@ bool copyFile(const char *from, const char *to) r = OSFS::getFile(from, cbuffer); if (r == notfound) { - LOG_ERROR("Failed to open source file %s\n", from); + LOG_ERROR("Failed to open source file %s", from); return false; } else if (r == noerr) { r = OSFS::newFile(to, cbuffer, true); if (r == noerr) { return true; } else { - LOG_ERROR("OSFS Error %d\n", r); + LOG_ERROR("OSFS Error %d", r); return false; } } else { - LOG_ERROR("OSFS Error %d\n", r); + LOG_ERROR("OSFS Error %d", r); return false; } return true; @@ -97,13 +97,13 @@ bool copyFile(const char *from, const char *to) File f1 = FSCom.open(from, FILE_O_READ); if (!f1) { - LOG_ERROR("Failed to open source file %s\n", from); + LOG_ERROR("Failed to open source file %s", from); return false; } File f2 = FSCom.open(to, FILE_O_WRITE); if (!f2) { - LOG_ERROR("Failed to open destination file %s\n", to); + LOG_ERROR("Failed to open destination file %s", to); return false; } @@ -231,7 +231,7 @@ void listDir(const char *dirname, uint8_t levels, bool del) #ifdef ARCH_ESP32 listDir(file.path(), levels - 1, del); if (del) { - LOG_DEBUG("Removing %s\n", file.path()); + LOG_DEBUG("Removing %s", file.path()); strncpy(buffer, file.path(), sizeof(buffer)); file.close(); FSCom.rmdir(buffer); @@ -241,7 +241,7 @@ void listDir(const char *dirname, uint8_t levels, bool del) #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) listDir(file.name(), levels - 1, del); if (del) { - LOG_DEBUG("Removing %s\n", file.name()); + LOG_DEBUG("Removing %s", file.name()); strncpy(buffer, file.name(), sizeof(buffer)); file.close(); FSCom.rmdir(buffer); @@ -249,7 +249,7 @@ void listDir(const char *dirname, uint8_t levels, bool del) file.close(); } #else - LOG_DEBUG(" %s (directory)\n", file.name()); + LOG_DEBUG(" %s (directory)", file.name()); listDir(file.name(), levels - 1, del); file.close(); #endif @@ -257,26 +257,26 @@ void listDir(const char *dirname, uint8_t levels, bool del) } else { #ifdef ARCH_ESP32 if (del) { - LOG_DEBUG("Deleting %s\n", file.path()); + LOG_DEBUG("Deleting %s", 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)", file.path(), file.size()); file.close(); } #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) if (del) { - LOG_DEBUG("Deleting %s\n", file.name()); + LOG_DEBUG("Deleting %s", file.name()); strncpy(buffer, file.name(), sizeof(buffer)); file.close(); FSCom.remove(buffer); } else { - LOG_DEBUG(" %s (%i Bytes)\n", file.name(), file.size()); + LOG_DEBUG(" %s (%i Bytes)", file.name(), file.size()); file.close(); } #else - LOG_DEBUG(" %s (%i Bytes)\n", file.name(), file.size()); + LOG_DEBUG(" %s (%i Bytes)", file.name(), file.size()); file.close(); #endif } @@ -284,7 +284,7 @@ void listDir(const char *dirname, uint8_t levels, bool del) } #ifdef ARCH_ESP32 if (del) { - LOG_DEBUG("Removing %s\n", root.path()); + LOG_DEBUG("Removing %s", root.path()); strncpy(buffer, root.path(), sizeof(buffer)); root.close(); FSCom.rmdir(buffer); @@ -293,7 +293,7 @@ void listDir(const char *dirname, uint8_t levels, bool del) } #elif (defined(ARCH_RP2040) || defined(ARCH_PORTDUINO)) if (del) { - LOG_DEBUG("Removing %s\n", root.name()); + LOG_DEBUG("Removing %s", root.name()); strncpy(buffer, root.name(), sizeof(buffer)); root.close(); FSCom.rmdir(buffer); @@ -329,13 +329,13 @@ void fsInit() { #ifdef FSCom if (!FSBegin()) { - LOG_ERROR("Filesystem mount Failed.\n"); + LOG_ERROR("Filesystem mount Failed."); // assert(0); This auto-formats the partition, so no need to fail here. } #if defined(ARCH_ESP32) - LOG_DEBUG("Filesystem files (%d/%d Bytes):\n", FSCom.usedBytes(), FSCom.totalBytes()); + LOG_DEBUG("Filesystem files (%d/%d Bytes):", FSCom.usedBytes(), FSCom.totalBytes()); #else - LOG_DEBUG("Filesystem files:\n"); + LOG_DEBUG("Filesystem files:"); #endif listDir("/", 10); #endif @@ -350,28 +350,28 @@ void setupSDCard() SDHandler.begin(SPI_SCK, SPI_MISO, SPI_MOSI); if (!SD.begin(SDCARD_CS, SDHandler)) { - LOG_DEBUG("No SD_MMC card detected\n"); + LOG_DEBUG("No SD_MMC card detected"); return; } uint8_t cardType = SD.cardType(); if (cardType == CARD_NONE) { - LOG_DEBUG("No SD_MMC card attached\n"); + LOG_DEBUG("No SD_MMC card attached"); return; } LOG_DEBUG("SD_MMC Card Type: "); if (cardType == CARD_MMC) { - LOG_DEBUG("MMC\n"); + LOG_DEBUG("MMC"); } else if (cardType == CARD_SD) { - LOG_DEBUG("SDSC\n"); + LOG_DEBUG("SDSC"); } else if (cardType == CARD_SDHC) { - LOG_DEBUG("SDHC\n"); + LOG_DEBUG("SDHC"); } else { - LOG_DEBUG("UNKNOWN\n"); + LOG_DEBUG("UNKNOWN"); } uint64_t cardSize = SD.cardSize() / (1024 * 1024); - LOG_DEBUG("SD Card Size: %lu MB\n", (uint32_t)cardSize); - LOG_DEBUG("Total space: %lu MB\n", (uint32_t)(SD.totalBytes() / (1024 * 1024))); - LOG_DEBUG("Used space: %lu MB\n", (uint32_t)(SD.usedBytes() / (1024 * 1024))); + LOG_DEBUG("SD Card Size: %lu MB", (uint32_t)cardSize); + LOG_DEBUG("Total space: %lu MB", (uint32_t)(SD.totalBytes() / (1024 * 1024))); + LOG_DEBUG("Used space: %lu MB", (uint32_t)(SD.usedBytes() / (1024 * 1024))); #endif } \ No newline at end of file diff --git a/src/GPSStatus.h b/src/GPSStatus.h index c2ab16c86f..12f302baa8 100644 --- a/src/GPSStatus.h +++ b/src/GPSStatus.h @@ -51,7 +51,7 @@ class GPSStatus : public Status { if (config.position.fixed_position) { #ifdef GPS_EXTRAVERBOSE - LOG_WARN("Using fixed latitude\n"); + LOG_WARN("Using fixed latitude"); #endif meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeDB->getNodeNum()); return node->position.latitude_i; @@ -64,7 +64,7 @@ class GPSStatus : public Status { if (config.position.fixed_position) { #ifdef GPS_EXTRAVERBOSE - LOG_WARN("Using fixed longitude\n"); + LOG_WARN("Using fixed longitude"); #endif meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeDB->getNodeNum()); return node->position.longitude_i; @@ -77,7 +77,7 @@ class GPSStatus : public Status { if (config.position.fixed_position) { #ifdef GPS_EXTRAVERBOSE - LOG_WARN("Using fixed altitude\n"); + LOG_WARN("Using fixed altitude"); #endif meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeDB->getNodeNum()); return node->position.altitude; @@ -95,7 +95,7 @@ class GPSStatus : public Status bool matches(const GPSStatus *newStatus) const { #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("GPSStatus.match() new pos@%x to old pos@%x\n", newStatus->p.timestamp, p.timestamp); + LOG_DEBUG("GPSStatus.match() new pos@%x to old pos@%x", newStatus->p.timestamp, p.timestamp); #endif return (newStatus->hasLock != hasLock || newStatus->isConnected != isConnected || newStatus->isPowerSaving != isPowerSaving || newStatus->p.latitude_i != p.latitude_i || @@ -112,7 +112,7 @@ class GPSStatus : public Status if (isDirty && p.timestamp && (newStatus->p.timestamp == p.timestamp)) { // We can NEVER be in two locations at the same time! (also PR #886) - LOG_ERROR("BUG: Positional timestamp unchanged from prev solution\n"); + LOG_ERROR("BUG: Positional timestamp unchanged from prev solution"); } initialized = true; @@ -124,11 +124,11 @@ class GPSStatus : public Status if (isDirty) { if (hasLock) { // In debug logs, identify position by @timestamp:stage (stage 3 = notify) - LOG_DEBUG("New GPS pos@%x:3 lat=%f lon=%f alt=%d pdop=%.2f track=%.2f speed=%.2f sats=%d\n", p.timestamp, + LOG_DEBUG("New GPS pos@%x:3 lat=%f lon=%f alt=%d pdop=%.2f track=%.2f speed=%.2f sats=%d", p.timestamp, p.latitude_i * 1e-7, p.longitude_i * 1e-7, p.altitude, p.PDOP * 1e-2, p.ground_track * 1e-5, p.ground_speed * 1e-2, p.sats_in_view); } else { - LOG_DEBUG("No GPS lock\n"); + LOG_DEBUG("No GPS lock"); } onNewStatus.notifyObservers(this); } diff --git a/src/GpioLogic.cpp b/src/GpioLogic.cpp index cbe26fc600..ba01d482da 100644 --- a/src/GpioLogic.cpp +++ b/src/GpioLogic.cpp @@ -12,7 +12,7 @@ void GpioVirtPin::set(bool value) void GpioHwPin::set(bool value) { - // if (num == 3) LOG_DEBUG("Setting pin %d to %d\n", num, value); + // if (num == 3) LOG_DEBUG("Setting pin %d to %d", num, value); pinMode(num, OUTPUT); digitalWrite(num, value); } @@ -88,7 +88,7 @@ void GpioBinaryTransformer::update() newValue = (GpioVirtPin::PinState)(p1 && p2); break; case Or: - // LOG_DEBUG("Doing GPIO OR\n"); + // LOG_DEBUG("Doing GPIO OR"); newValue = (GpioVirtPin::PinState)(p1 || p2); break; case Xor: diff --git a/src/NodeStatus.h b/src/NodeStatus.h index e6bf31aed1..60d1bdd982 100644 --- a/src/NodeStatus.h +++ b/src/NodeStatus.h @@ -56,7 +56,7 @@ class NodeStatus : public Status numTotal = newStatus->getNumTotal(); } if (isDirty || newStatus->forceUpdate) { - LOG_DEBUG("Node status update: %d online, %d total\n", numOnline, numTotal); + LOG_DEBUG("Node status update: %d online, %d total", numOnline, numTotal); onNewStatus.notifyObservers(this); } return 0; diff --git a/src/Power.cpp b/src/Power.cpp index 2f5f441ae3..02a07e620c 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -240,7 +240,7 @@ class AnalogBatteryLevel : public HasBatteryLevel #if HAS_TELEMETRY && !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) && !defined(HAS_PMU) && \ !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR if (hasINA()) { - LOG_DEBUG("Using INA on I2C addr 0x%x for device battery voltage\n", config.power.device_battery_ina_address); + LOG_DEBUG("Using INA on I2C addr 0x%x for device battery voltage", config.power.device_battery_ina_address); return getINAVoltage(); } #endif @@ -290,7 +290,7 @@ class AnalogBatteryLevel : public HasBatteryLevel last_read_value += (scaled - last_read_value) * 0.5; // Virtual LPF } - // LOG_DEBUG("battery gpio %d raw val=%u scaled=%u filtered=%u\n", BATTERY_PIN, raw, (uint32_t)(scaled), (uint32_t) + // LOG_DEBUG("battery gpio %d raw val=%u scaled=%u filtered=%u", BATTERY_PIN, raw, (uint32_t)(scaled), (uint32_t) // (last_read_value)); } return last_read_value; @@ -335,7 +335,7 @@ class AnalogBatteryLevel : public HasBatteryLevel raw += adc_buf; raw_c++; // Count valid samples } else { - LOG_DEBUG("An attempt to sample ADC2 failed\n"); + LOG_DEBUG("An attempt to sample ADC2 failed"); } } @@ -360,7 +360,12 @@ class AnalogBatteryLevel : public HasBatteryLevel /** * return true if there is a battery installed in this unit */ + // if we have a integrated device with a battery, we can assume that the battery is always connected +#ifdef BATTERY_IMMUTABLE + virtual bool isBatteryConnect() override { return true; } +#else virtual bool isBatteryConnect() override { return getBatteryPercent() != -1; } +#endif /// If we see a battery voltage higher than physics allows - assume charger is pumping /// in power @@ -495,7 +500,7 @@ bool Power::analogInit() #endif #ifdef BATTERY_PIN - LOG_DEBUG("Using analog input %d for battery level\n", BATTERY_PIN); + LOG_DEBUG("Using analog input %d for battery level", BATTERY_PIN); // disable any internal pullups pinMode(BATTERY_PIN, INPUT); @@ -526,18 +531,18 @@ bool Power::analogInit() esp_adc_cal_value_t val_type = esp_adc_cal_characterize(unit, atten, width, DEFAULT_VREF, adc_characs); // show ADC characterization base if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP) { - LOG_INFO("ADCmod: ADC characterization based on Two Point values stored in eFuse\n"); + LOG_INFO("ADCmod: ADC characterization based on Two Point values stored in eFuse"); } else if (val_type == ESP_ADC_CAL_VAL_EFUSE_VREF) { - LOG_INFO("ADCmod: ADC characterization based on reference voltage stored in eFuse\n"); + LOG_INFO("ADCmod: ADC characterization based on reference voltage stored in eFuse"); } #ifdef CONFIG_IDF_TARGET_ESP32S3 // ESP32S3 else if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP_FIT) { - LOG_INFO("ADCmod: ADC Characterization based on Two Point values and fitting curve coefficients stored in eFuse\n"); + LOG_INFO("ADCmod: ADC Characterization based on Two Point values and fitting curve coefficients stored in eFuse"); } #endif else { - LOG_INFO("ADCmod: ADC characterization based on default reference voltage\n"); + LOG_INFO("ADCmod: ADC characterization based on default reference voltage"); } #endif // ARCH_ESP32 @@ -586,9 +591,9 @@ bool Power::setup() void Power::shutdown() { - LOG_INFO("Shutting down\n"); + LOG_INFO("Shutting down"); -#if defined(ARCH_NRF52) || defined(ARCH_ESP32) +#if defined(ARCH_NRF52) || defined(ARCH_ESP32) || defined(ARCH_RP2040) #ifdef PIN_LED1 ledOff(PIN_LED1); #endif @@ -641,7 +646,7 @@ void Power::readPowerStatus() // changes. nrfx_power_usb_state_t nrf_usb_state = nrfx_power_usbstatus_get(); - // LOG_DEBUG("NRF Power %d\n", nrf_usb_state); + // LOG_DEBUG("NRF Power %d", nrf_usb_state); // If changed to DISCONNECTED if (nrf_usb_state == NRFX_POWER_USB_STATE_DISCONNECTED) @@ -654,22 +659,22 @@ void Power::readPowerStatus() // Notify any status instances that are observing us const PowerStatus powerStatus2 = PowerStatus(hasBattery, usbPowered, isCharging, batteryVoltageMv, batteryChargePercent); - LOG_DEBUG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d\n", powerStatus2.getHasUSB(), - powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); + LOG_DEBUG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d", powerStatus2.getHasUSB(), powerStatus2.getIsCharging(), + powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); newStatus.notifyObservers(&powerStatus2); #ifdef DEBUG_HEAP if (lastheap != memGet.getFreeHeap()) { - LOG_DEBUG("Threads running:"); + std::string threadlist = "Threads running:"; int running = 0; for (int i = 0; i < MAX_THREADS; i++) { auto thread = concurrency::mainController.get(i); if ((thread != nullptr) && (thread->enabled)) { - LOG_DEBUG(" %s", thread->ThreadName.c_str()); + threadlist += vformat(" %s", thread->ThreadName.c_str()); running++; } } - LOG_DEBUG("\n"); - LOG_DEBUG("Heap status: %d/%d bytes free (%d), running %d/%d threads\n", memGet.getFreeHeap(), memGet.getHeapSize(), + LOG_DEBUG(threadlist.c_str()); + LOG_DEBUG("Heap status: %d/%d bytes free (%d), running %d/%d threads", memGet.getFreeHeap(), memGet.getHeapSize(), memGet.getFreeHeap() - lastheap, running, concurrency::mainController.size(false)); lastheap = memGet.getFreeHeap(); } @@ -702,13 +707,13 @@ void Power::readPowerStatus() if (batteryLevel && powerStatus2.getHasBattery() && !powerStatus2.getHasUSB()) { if (batteryLevel->getBattVoltage() < OCV[NUM_OCV_POINTS - 1]) { low_voltage_counter++; - LOG_DEBUG("Low voltage counter: %d/10\n", low_voltage_counter); + LOG_DEBUG("Low voltage counter: %d/10", low_voltage_counter); if (low_voltage_counter > 10) { #ifdef ARCH_NRF52 // We can't trigger deep sleep on NRF52, it's freezing the board - LOG_DEBUG("Low voltage detected, but not triggering deep sleep\n"); + LOG_DEBUG("Low voltage detected, but not triggering deep sleep"); #else - LOG_INFO("Low voltage detected, triggering deep sleep\n"); + LOG_INFO("Low voltage detected, triggering deep sleep"); powerFSM.trigger(EVENT_LOW_BATTERY); #endif } @@ -730,12 +735,12 @@ int32_t Power::runOnce() PMU->getIrqStatus(); if (PMU->isVbusRemoveIrq()) { - LOG_INFO("USB unplugged\n"); + LOG_INFO("USB unplugged"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } if (PMU->isVbusInsertIrq()) { - LOG_INFO("USB plugged In\n"); + LOG_INFO("USB plugged In"); powerFSM.trigger(EVENT_POWER_CONNECTED); } @@ -743,21 +748,21 @@ int32_t Power::runOnce() Other things we could check if we cared... if (PMU->isBatChagerStartIrq()) { - LOG_DEBUG("Battery start charging\n"); + LOG_DEBUG("Battery start charging"); } if (PMU->isBatChagerDoneIrq()) { - LOG_DEBUG("Battery fully charged\n"); + LOG_DEBUG("Battery fully charged"); } if (PMU->isBatInsertIrq()) { - LOG_DEBUG("Battery inserted\n"); + LOG_DEBUG("Battery inserted"); } if (PMU->isBatRemoveIrq()) { - LOG_DEBUG("Battery removed\n"); + LOG_DEBUG("Battery removed"); } */ #ifndef T_WATCH_S3 // FIXME - why is this triggering on the T-Watch S3? if (PMU->isPekeyLongPressIrq()) { - LOG_DEBUG("PEK long button press\n"); + LOG_DEBUG("PEK long button press"); screen->setOn(false); } #endif @@ -800,22 +805,22 @@ bool Power::axpChipInit() if (!PMU) { PMU = new XPowersAXP2101(*w); if (!PMU->init()) { - LOG_WARN("Failed to find AXP2101 power management\n"); + LOG_WARN("Failed to find AXP2101 power management"); delete PMU; PMU = NULL; } else { - LOG_INFO("AXP2101 PMU init succeeded, using AXP2101 PMU\n"); + LOG_INFO("AXP2101 PMU init succeeded, using AXP2101 PMU"); } } if (!PMU) { PMU = new XPowersAXP192(*w); if (!PMU->init()) { - LOG_WARN("Failed to find AXP192 power management\n"); + LOG_WARN("Failed to find AXP192 power management"); delete PMU; PMU = NULL; } else { - LOG_INFO("AXP192 PMU init succeeded, using AXP192 PMU\n"); + LOG_INFO("AXP192 PMU init succeeded, using AXP192 PMU"); } } @@ -972,51 +977,51 @@ bool Power::axpChipInit() PMU->enableBattVoltageMeasure(); if (PMU->isChannelAvailable(XPOWERS_DCDC1)) { - LOG_DEBUG("DC1 : %s Voltage:%u mV \n", PMU->isPowerChannelEnable(XPOWERS_DCDC1) ? "+" : "-", + LOG_DEBUG("DC1 : %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("DC2 : %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("DC3 : %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("DC4 : %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("LDO2 : %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("LDO3 : %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("ALDO1: %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("ALDO2: %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("ALDO3: %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("ALDO4: %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("BLDO1: %s Voltage:%u mV ", 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) ? "+" : "-", + LOG_DEBUG("BLDO2: %s Voltage:%u mV ", PMU->isPowerChannelEnable(XPOWERS_BLDO2) ? "+" : "-", PMU->getPowerChannelVoltage(XPOWERS_BLDO2)); } @@ -1124,7 +1129,7 @@ LipoBatteryLevel lipoLevel; bool Power::lipoInit() { bool result = lipoLevel.runOnce(); - LOG_DEBUG("Power::lipoInit lipo sensor is %s\n", result ? "ready" : "not ready yet"); + LOG_DEBUG("Power::lipoInit lipo sensor is %s", result ? "ready" : "not ready yet"); if (!result) return false; batteryLevel = &lipoLevel; diff --git a/src/PowerFSM.cpp b/src/PowerFSM.cpp index 8bf7d32183..35ef2624a7 100644 --- a/src/PowerFSM.cpp +++ b/src/PowerFSM.cpp @@ -53,7 +53,7 @@ static bool isPowered() static void sdsEnter() { - LOG_DEBUG("Enter state: SDS\n"); + LOG_DEBUG("Enter state: SDS"); // FIXME - make sure GPS and LORA radio are off first - because we want close to zero current draw doDeepSleep(Default::getConfiguredOrDefaultMs(config.power.sds_secs), false); } @@ -62,7 +62,7 @@ extern Power *power; static void shutdownEnter() { - LOG_DEBUG("Enter state: SHUTDOWN\n"); + LOG_DEBUG("Enter state: SHUTDOWN"); power->shutdown(); } @@ -72,16 +72,16 @@ static uint32_t secsSlept; static void lsEnter() { - LOG_INFO("lsEnter begin, ls_secs=%u\n", config.power.ls_secs); + LOG_INFO("lsEnter begin, ls_secs=%u", config.power.ls_secs); screen->setOn(false); secsSlept = 0; // How long have we been sleeping this time - // LOG_INFO("lsEnter end\n"); + // LOG_INFO("lsEnter end"); } static void lsIdle() { - // LOG_INFO("lsIdle begin ls_secs=%u\n", getPref_ls_secs()); + // LOG_INFO("lsIdle begin ls_secs=%u", getPref_ls_secs()); #ifdef ARCH_ESP32 @@ -105,7 +105,7 @@ static void lsIdle() wakeCause2 = doLightSleep(100); // leave led on for 1ms secsSlept += sleepTime; - // LOG_INFO("sleeping, flash led!\n"); + // LOG_INFO("sleeping, flash led!"); break; case ESP_SLEEP_WAKEUP_UART: @@ -137,7 +137,7 @@ static void lsIdle() } else { // Time to stop sleeping! ledBlink.set(false); - LOG_INFO("Reached ls_secs, servicing loop()\n"); + LOG_INFO("Reached ls_secs, servicing loop()"); powerFSM.trigger(EVENT_WAKE_TIMER); } #endif @@ -145,12 +145,12 @@ static void lsIdle() static void lsExit() { - LOG_INFO("Exit state: LS\n"); + LOG_INFO("Exit state: LS"); } static void nbEnter() { - LOG_DEBUG("Enter state: NB\n"); + LOG_DEBUG("Enter state: NB"); screen->setOn(false); #ifdef ARCH_ESP32 // Only ESP32 should turn off bluetooth @@ -168,7 +168,7 @@ static void darkEnter() static void serialEnter() { - LOG_DEBUG("Enter state: SERIAL\n"); + LOG_DEBUG("Enter state: SERIAL"); setBluetoothEnable(false); screen->setOn(true); screen->print("Serial connected\n"); @@ -183,10 +183,10 @@ static void serialExit() static void powerEnter() { - // LOG_DEBUG("Enter state: POWER\n"); + // LOG_DEBUG("Enter state: POWER"); if (!isPowered()) { // If we got here, we are in the wrong state - we should be in powered, let that state ahndle things - LOG_INFO("Loss of power in Powered\n"); + LOG_INFO("Loss of power in Powered"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } else { screen->setOn(true); @@ -205,7 +205,7 @@ static void powerIdle() { if (!isPowered()) { // If we got here, we are in the wrong state - LOG_INFO("Loss of power in Powered\n"); + LOG_INFO("Loss of power in Powered"); powerFSM.trigger(EVENT_POWER_DISCONNECTED); } } @@ -222,7 +222,7 @@ static void powerExit() static void onEnter() { - LOG_DEBUG("Enter state: ON\n"); + LOG_DEBUG("Enter state: ON"); screen->setOn(true); setBluetoothEnable(true); } @@ -242,7 +242,7 @@ static void screenPress() static void bootEnter() { - LOG_DEBUG("Enter state: BOOT\n"); + LOG_DEBUG("Enter state: BOOT"); } State stateSHUTDOWN(shutdownEnter, NULL, NULL, "SHUTDOWN"); @@ -264,7 +264,7 @@ void PowerFSM_setup() config.device.role == meshtastic_Config_DeviceConfig_Role_SENSOR; bool hasPower = isPowered(); - LOG_INFO("PowerFSM init, USB power=%d\n", hasPower ? 1 : 0); + LOG_INFO("PowerFSM init, USB power=%d", hasPower ? 1 : 0); powerFSM.add_timed_transition(&stateBOOT, hasPower ? &statePOWER : &stateON, 3 * 1000, NULL, "boot timeout"); // wake timer expired or a packet arrived diff --git a/src/PowerMon.cpp b/src/PowerMon.cpp index 16909262df..38740b6ae9 100644 --- a/src/PowerMon.cpp +++ b/src/PowerMon.cpp @@ -35,7 +35,7 @@ void PowerMon::emitLog(const char *reason) { #ifdef USE_POWERMON // The nrf52 printf doesn't understand 64 bit ints, so if we ever reach that point this function will need to change. - LOG_INFO("S:PM:0x%08lx,%s\n", (uint32_t)states, reason); + LOG_INFO("S:PM:0x%08lx,%s", (uint32_t)states, reason); #endif } diff --git a/src/PowerStatus.h b/src/PowerStatus.h index 592a033280..fe4543e08d 100644 --- a/src/PowerStatus.h +++ b/src/PowerStatus.h @@ -91,7 +91,7 @@ class PowerStatus : public Status isCharging = newStatus->isCharging; } if (isDirty) { - // LOG_DEBUG("Battery %dmV %d%%\n", batteryVoltageMv, batteryChargePercent); + // LOG_DEBUG("Battery %dmV %d%%", batteryVoltageMv, batteryChargePercent); onNewStatus.notifyObservers(this); } return 0; diff --git a/src/RedirectablePrint.cpp b/src/RedirectablePrint.cpp index 6eb6f8319a..57f53019db 100644 --- a/src/RedirectablePrint.cpp +++ b/src/RedirectablePrint.cpp @@ -98,81 +98,75 @@ void RedirectablePrint::log_to_serial(const char *logLevel, const char *format, { size_t r = 0; - // Cope with 0 len format strings, but look for new line terminator - bool hasNewline = *format && format[strlen(format) - 1] == '\n'; #ifdef ARCH_PORTDUINO bool color = !settingsMap[ascii_logs]; #else bool color = true; #endif - // If we are the first message on a report, include the header - if (!isContinuationMessage) { - if (color) { - if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_DEBUG) == 0) - Print::write("\u001b[34m", 6); - if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_INFO) == 0) - Print::write("\u001b[32m", 6); - if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_WARN) == 0) - Print::write("\u001b[33m", 6); - if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_ERROR) == 0) - Print::write("\u001b[31m", 6); - if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_TRACE) == 0) - Print::write("\u001b[35m", 6); - } + // include the header + if (color) { + if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_DEBUG) == 0) + Print::write("\u001b[34m", 6); + if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_INFO) == 0) + Print::write("\u001b[32m", 6); + if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_WARN) == 0) + Print::write("\u001b[33m", 6); + if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_ERROR) == 0) + Print::write("\u001b[31m", 6); + if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_TRACE) == 0) + Print::write("\u001b[35m", 6); + } - uint32_t rtc_sec = getValidTime(RTCQuality::RTCQualityDevice, true); // display local time on logfile - if (rtc_sec > 0) { - long hms = rtc_sec % SEC_PER_DAY; - // hms += tz.tz_dsttime * SEC_PER_HOUR; - // hms -= tz.tz_minuteswest * SEC_PER_MIN; - // mod `hms` to ensure in positive range of [0...SEC_PER_DAY) - hms = (hms + SEC_PER_DAY) % SEC_PER_DAY; + uint32_t rtc_sec = getValidTime(RTCQuality::RTCQualityDevice, true); // display local time on logfile + if (rtc_sec > 0) { + long hms = rtc_sec % SEC_PER_DAY; + // hms += tz.tz_dsttime * SEC_PER_HOUR; + // hms -= tz.tz_minuteswest * SEC_PER_MIN; + // mod `hms` to ensure in positive range of [0...SEC_PER_DAY) + hms = (hms + SEC_PER_DAY) % SEC_PER_DAY; - // Tear apart hms into h:m:s - int hour = hms / SEC_PER_HOUR; - int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN; - int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN + // Tear apart hms into h:m:s + int hour = hms / SEC_PER_HOUR; + int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN; + int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN #ifdef ARCH_PORTDUINO - ::printf("%s ", logLevel); - if (color) { - ::printf("\u001b[0m"); - } - ::printf("| %02d:%02d:%02d %u ", hour, min, sec, millis() / 1000); + ::printf("%s ", logLevel); + if (color) { + ::printf("\u001b[0m"); + } + ::printf("| %02d:%02d:%02d %u ", hour, min, sec, millis() / 1000); #else - printf("%s ", logLevel); - if (color) { - printf("\u001b[0m"); - } - printf("| %02d:%02d:%02d %u ", hour, min, sec, millis() / 1000); + printf("%s ", logLevel); + if (color) { + printf("\u001b[0m"); + } + printf("| %02d:%02d:%02d %u ", hour, min, sec, millis() / 1000); #endif - } else { + } else { #ifdef ARCH_PORTDUINO - ::printf("%s ", logLevel); - if (color) { - ::printf("\u001b[0m"); - } - ::printf("| ??:??:?? %u ", millis() / 1000); -#else - printf("%s ", logLevel); - if (color) { - printf("\u001b[0m"); - } - printf("| ??:??:?? %u ", millis() / 1000); -#endif + ::printf("%s ", logLevel); + if (color) { + ::printf("\u001b[0m"); } - auto thread = concurrency::OSThread::currentThread; - if (thread) { - print("["); - // printf("%p ", thread); - // assert(thread->ThreadName.length()); - print(thread->ThreadName); - print("] "); + ::printf("| ??:??:?? %u ", millis() / 1000); +#else + printf("%s ", logLevel); + if (color) { + printf("\u001b[0m"); } + printf("| ??:??:?? %u ", millis() / 1000); +#endif + } + auto thread = concurrency::OSThread::currentThread; + if (thread) { + print("["); + // printf("%p ", thread); + // assert(thread->ThreadName.length()); + print(thread->ThreadName); + print("] "); } r += vprintf(logLevel, format, arg); - - isContinuationMessage = !hasNewline; } void RedirectablePrint::log_to_syslog(const char *logLevel, const char *format, va_list arg) @@ -283,6 +277,14 @@ meshtastic_LogRecord_Level RedirectablePrint::getLogLevel(const char *logLevel) void RedirectablePrint::log(const char *logLevel, const char *format, ...) { + + // append \n to format + size_t len = strlen(format); + char *newFormat = new char[len + 2]; + strcpy(newFormat, format); + newFormat[len] = '\n'; + newFormat[len + 1] = '\0'; + #if ARCH_PORTDUINO // level trace is special, two possible ways to handle it. if (strcmp(logLevel, MESHTASTIC_LOG_LEVEL_TRACE) == 0) { @@ -295,17 +297,24 @@ void RedirectablePrint::log(const char *logLevel, const char *format, ...) } va_end(arg); } - if (settingsMap[logoutputlevel] < level_trace && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_TRACE) == 0) + if (settingsMap[logoutputlevel] < level_trace && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_TRACE) == 0) { + delete[] newFormat; return; + } } - if (settingsMap[logoutputlevel] < level_debug && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_DEBUG) == 0) + if (settingsMap[logoutputlevel] < level_debug && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_DEBUG) == 0) { + delete[] newFormat; return; - else if (settingsMap[logoutputlevel] < level_info && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_INFO) == 0) + } else if (settingsMap[logoutputlevel] < level_info && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_INFO) == 0) { + delete[] newFormat; return; - else if (settingsMap[logoutputlevel] < level_warn && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_WARN) == 0) + } else if (settingsMap[logoutputlevel] < level_warn && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_WARN) == 0) { + delete[] newFormat; return; + } #endif if (moduleConfig.serial.override_console_serial_port && strcmp(logLevel, MESHTASTIC_LOG_LEVEL_DEBUG) == 0) { + delete[] newFormat; return; } @@ -319,9 +328,9 @@ void RedirectablePrint::log(const char *logLevel, const char *format, ...) va_list arg; va_start(arg, format); - log_to_serial(logLevel, format, arg); - log_to_syslog(logLevel, format, arg); - log_to_ble(logLevel, format, arg); + log_to_serial(logLevel, newFormat, arg); + log_to_syslog(logLevel, newFormat, arg); + log_to_ble(logLevel, newFormat, arg); va_end(arg); #ifdef HAS_FREE_RTOS @@ -331,17 +340,18 @@ void RedirectablePrint::log(const char *logLevel, const char *format, ...) #endif } + delete[] newFormat; return; } 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"); + log(logLevel, " +------------------------------------------------+ +----------------+"); + log(logLevel, " |.0 .1 .2 .3 .4 .5 .6 .7 .8 .9 .a .b .c .d .e .f | | ASCII |"); for (uint16_t i = 0; i < len; i += 16) { if (i % 128 == 0) - log(logLevel, " +------------------------------------------------+ +----------------+\n"); + log(logLevel, " +------------------------------------------------+ +----------------+"); char s[] = "| | | |\n"; uint8_t ix = 1, iy = 52; for (uint8_t j = 0; j < 16; j++) { @@ -363,7 +373,7 @@ void RedirectablePrint::hexDump(const char *logLevel, unsigned char *buf, uint16 log(logLevel, "."); log(logLevel, s); } - log(logLevel, " +------------------------------------------------+ +----------------+\n"); + log(logLevel, " +------------------------------------------------+ +----------------+"); } std::string RedirectablePrint::mt_sprintf(const std::string fmt_str, ...) diff --git a/src/RedirectablePrint.h b/src/RedirectablePrint.h index 23ae3c44de..45b62b7af2 100644 --- a/src/RedirectablePrint.h +++ b/src/RedirectablePrint.h @@ -15,9 +15,6 @@ class RedirectablePrint : public Print { Print *dest; - /// Used to allow multiple logDebug messages to appear on a single log line - bool isContinuationMessage = false; - #ifdef HAS_FREE_RTOS SemaphoreHandle_t inDebugPrint = nullptr; StaticSemaphore_t _MutexStorageSpace; @@ -54,9 +51,9 @@ class RedirectablePrint : public Print protected: /// Subclasses can override if they need to change how we format over the serial port virtual void log_to_serial(const char *logLevel, const char *format, va_list arg); + meshtastic_LogRecord_Level getLogLevel(const char *logLevel); private: void log_to_syslog(const char *logLevel, const char *format, va_list arg); void log_to_ble(const char *logLevel, const char *format, va_list arg); - meshtastic_LogRecord_Level getLogLevel(const char *logLevel); }; \ No newline at end of file diff --git a/src/SafeFile.cpp b/src/SafeFile.cpp index c17d422bd3..c76ff8054a 100644 --- a/src/SafeFile.cpp +++ b/src/SafeFile.cpp @@ -59,14 +59,14 @@ bool SafeFile::close() // brief window of risk here ;-) if (fullAtomic && FSCom.exists(filename.c_str()) && !FSCom.remove(filename.c_str())) { - LOG_ERROR("Can't remove old pref file\n"); + LOG_ERROR("Can't remove old pref file"); return false; } String filenameTmp = filename; filenameTmp += ".tmp"; if (!renameFile(filenameTmp.c_str(), filename.c_str())) { - LOG_ERROR("Error: can't rename new pref file\n"); + LOG_ERROR("Error: can't rename new pref file"); return false; } @@ -83,7 +83,7 @@ bool SafeFile::testReadback() filenameTmp += ".tmp"; auto f2 = FSCom.open(filenameTmp.c_str(), FILE_O_READ); if (!f2) { - LOG_ERROR("Can't open tmp file for readback\n"); + LOG_ERROR("Can't open tmp file for readback"); return false; } @@ -95,7 +95,7 @@ bool SafeFile::testReadback() f2.close(); if (test_hash != hash) { - LOG_ERROR("Readback failed hash mismatch\n"); + LOG_ERROR("Readback failed hash mismatch"); return false; } diff --git a/src/SerialConsole.cpp b/src/SerialConsole.cpp index fe6ccdefe1..68c41980d0 100644 --- a/src/SerialConsole.cpp +++ b/src/SerialConsole.cpp @@ -99,25 +99,7 @@ bool SerialConsole::handleToRadio(const uint8_t *buf, size_t len) void SerialConsole::log_to_serial(const char *logLevel, const char *format, va_list arg) { if (usingProtobufs && config.security.debug_log_api_enabled) { - meshtastic_LogRecord_Level ll = meshtastic_LogRecord_Level_UNSET; // default to unset - switch (logLevel[0]) { - case 'D': - ll = meshtastic_LogRecord_Level_DEBUG; - break; - case 'I': - ll = meshtastic_LogRecord_Level_INFO; - break; - case 'W': - ll = meshtastic_LogRecord_Level_WARNING; - break; - case 'E': - ll = meshtastic_LogRecord_Level_ERROR; - break; - case 'C': - ll = meshtastic_LogRecord_Level_CRITICAL; - break; - } - + meshtastic_LogRecord_Level ll = RedirectablePrint::getLogLevel(logLevel); auto thread = concurrency::OSThread::currentThread; emitLogRecord(ll, thread ? thread->ThreadName.c_str() : "", format, arg); } else diff --git a/src/airtime.cpp b/src/airtime.cpp index fcda054682..7478debb94 100644 --- a/src/airtime.cpp +++ b/src/airtime.cpp @@ -13,17 +13,17 @@ void AirTime::logAirtime(reportTypes reportType, uint32_t airtime_ms) { if (reportType == TX_LOG) { - LOG_DEBUG("Packet transmitted : %ums\n", airtime_ms); + LOG_DEBUG("Packet transmitted : %ums", airtime_ms); this->airtimes.periodTX[0] = this->airtimes.periodTX[0] + airtime_ms; air_period_tx[0] = air_period_tx[0] + airtime_ms; this->utilizationTX[this->getPeriodUtilHour()] = this->utilizationTX[this->getPeriodUtilHour()] + airtime_ms; } else if (reportType == RX_LOG) { - LOG_DEBUG("Packet received : %ums\n", airtime_ms); + LOG_DEBUG("Packet received : %ums", airtime_ms); this->airtimes.periodRX[0] = this->airtimes.periodRX[0] + airtime_ms; air_period_rx[0] = air_period_rx[0] + airtime_ms; } else if (reportType == RX_ALL_LOG) { - LOG_DEBUG("Packet received (noise?) : %ums\n", airtime_ms); + LOG_DEBUG("Packet received (noise?) : %ums", airtime_ms); this->airtimes.periodRX_ALL[0] = this->airtimes.periodRX_ALL[0] + airtime_ms; } @@ -50,7 +50,7 @@ void AirTime::airtimeRotatePeriod() { if (this->airtimes.lastPeriodIndex != this->currentPeriodIndex()) { - LOG_DEBUG("Rotating airtimes to a new period = %u\n", this->currentPeriodIndex()); + LOG_DEBUG("Rotating airtimes to a new period = %u", this->currentPeriodIndex()); for (int i = PERIODS_TO_LOG - 2; i >= 0; --i) { this->airtimes.periodTX[i + 1] = this->airtimes.periodTX[i]; @@ -105,7 +105,7 @@ float AirTime::channelUtilizationPercent() uint32_t sum = 0; for (uint32_t i = 0; i < CHANNEL_UTILIZATION_PERIODS; i++) { sum += this->channelUtilization[i]; - // LOG_DEBUG("ChanUtilArray %u %u\n", i, this->channelUtilization[i]); + // LOG_DEBUG("ChanUtilArray %u %u", i, this->channelUtilization[i]); } return (float(sum) / float(CHANNEL_UTILIZATION_PERIODS * 10 * 1000)) * 100; @@ -127,7 +127,7 @@ bool AirTime::isTxAllowedChannelUtil(bool polite) if (channelUtilizationPercent() < percentage) { return true; } else { - LOG_WARN("Channel utilization is >%d percent. Skipping this opportunity to send.\n", percentage); + LOG_WARN("Channel utilization is >%d percent. Skipping this opportunity to send.", percentage); return false; } } @@ -138,7 +138,7 @@ bool AirTime::isTxAllowedAirUtil() if (utilizationTXPercent() < myRegion->dutyCycle * polite_duty_cycle_percent / 100) { return true; } else { - LOG_WARN("Tx air utilization is >%f percent. Skipping this opportunity to send.\n", + LOG_WARN("Tx air utilization is >%f percent. Skipping this opportunity to send.", myRegion->dutyCycle * polite_duty_cycle_percent / 100); return false; } @@ -209,13 +209,13 @@ int32_t AirTime::runOnce() } } /* - LOG_DEBUG("utilPeriodTX %d TX Airtime %3.2f%\n", utilPeriodTX, airTime->utilizationTXPercent()); + LOG_DEBUG("utilPeriodTX %d TX Airtime %3.2f%", utilPeriodTX, airTime->utilizationTXPercent()); for (uint32_t i = 0; i < MINUTES_IN_HOUR; i++) { LOG_DEBUG( "%d,", this->utilizationTX[i] ); } - LOG_DEBUG("\n"); + LOG_DEBUG(""); */ return (1000 * 1); } \ No newline at end of file diff --git a/src/buzz/buzz.cpp b/src/buzz/buzz.cpp index e42a9c203f..8db9602bc3 100644 --- a/src/buzz/buzz.cpp +++ b/src/buzz/buzz.cpp @@ -55,6 +55,18 @@ void playBeep() playTones(melody, sizeof(melody) / sizeof(ToneDuration)); } +void playGPSEnableBeep() +{ + ToneDuration melody[] = {{NOTE_C3, DURATION_1_8}, {NOTE_FS3, DURATION_1_4}, {NOTE_CS4, DURATION_1_4}}; + playTones(melody, sizeof(melody) / sizeof(ToneDuration)); +} + +void playGPSDisableBeep() +{ + ToneDuration melody[] = {{NOTE_CS4, DURATION_1_8}, {NOTE_FS3, DURATION_1_4}, {NOTE_C3, 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}}; diff --git a/src/buzz/buzz.h b/src/buzz/buzz.h index 3883bd057c..c52c3020cd 100644 --- a/src/buzz/buzz.h +++ b/src/buzz/buzz.h @@ -3,3 +3,5 @@ void playBeep(); void playStartMelody(); void playShutdownMelody(); +void playGPSEnableBeep(); +void playGPSDisableBeep(); \ No newline at end of file diff --git a/src/concurrency/InterruptableDelay.cpp b/src/concurrency/InterruptableDelay.cpp index b9606e23a4..8bc85436ba 100644 --- a/src/concurrency/InterruptableDelay.cpp +++ b/src/concurrency/InterruptableDelay.cpp @@ -18,7 +18,7 @@ bool InterruptableDelay::delay(uint32_t msec) // sem take will return false if we timed out (i.e. were not interrupted) bool r = semaphore.take(msec); - // LOG_DEBUG("interrupt=%d\n", r); + // LOG_DEBUG("interrupt=%d", r); return !r; } diff --git a/src/concurrency/NotifiedWorkerThread.cpp b/src/concurrency/NotifiedWorkerThread.cpp index 271e3e60d5..d84ff0903c 100644 --- a/src/concurrency/NotifiedWorkerThread.cpp +++ b/src/concurrency/NotifiedWorkerThread.cpp @@ -32,12 +32,12 @@ IRAM_ATTR bool NotifiedWorkerThread::notifyCommon(uint32_t v, bool overwrite) notification = v; if (debugNotification) { - LOG_DEBUG("setting notification %d\n", v); + LOG_DEBUG("setting notification %d", v); } return true; } else { if (debugNotification) { - LOG_DEBUG("dropping notification %d\n", v); + LOG_DEBUG("dropping notification %d", v); } return false; } @@ -67,7 +67,7 @@ bool NotifiedWorkerThread::notifyLater(uint32_t delay, uint32_t v, bool overwrit if (didIt) { // If we didn't already have something queued, override the delay to be larger setIntervalFromNow(delay); // a new version of setInterval relative to the current time if (debugNotification) { - LOG_DEBUG("delaying notification %u\n", delay); + LOG_DEBUG("delaying notification %u", delay); } } diff --git a/src/concurrency/OSThread.cpp b/src/concurrency/OSThread.cpp index f23cbe1dce..d9bb901b2f 100644 --- a/src/concurrency/OSThread.cpp +++ b/src/concurrency/OSThread.cpp @@ -62,15 +62,15 @@ bool OSThread::shouldRun(unsigned long time) bool r = Thread::shouldRun(time); if (showRun && r) { - LOG_DEBUG("Thread %s: run\n", ThreadName.c_str()); + LOG_DEBUG("Thread %s: run", ThreadName.c_str()); } if (showWaiting && enabled && !r) { - LOG_DEBUG("Thread %s: wait %lu\n", ThreadName.c_str(), interval); + LOG_DEBUG("Thread %s: wait %lu", ThreadName.c_str(), interval); } if (showDisabled && !enabled) { - LOG_DEBUG("Thread %s: disabled\n", ThreadName.c_str()); + LOG_DEBUG("Thread %s: disabled", ThreadName.c_str()); } return r; @@ -86,9 +86,9 @@ void OSThread::run() #ifdef DEBUG_HEAP auto newHeap = memGet.getFreeHeap(); if (newHeap < heap) - LOG_DEBUG("------ Thread %s leaked heap %d -> %d (%d) ------\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); + LOG_DEBUG("------ Thread %s leaked heap %d -> %d (%d) ------", ThreadName.c_str(), heap, newHeap, newHeap - heap); if (heap < newHeap) - LOG_DEBUG("++++++ Thread %s freed heap %d -> %d (%d) ++++++\n", ThreadName.c_str(), heap, newHeap, newHeap - heap); + LOG_DEBUG("++++++ Thread %s freed heap %d -> %d (%d) ++++++", ThreadName.c_str(), heap, newHeap, newHeap - heap); #endif runned(); diff --git a/src/configuration.h b/src/configuration.h index 3cd93ec83d..cb2326470c 100644 --- a/src/configuration.h +++ b/src/configuration.h @@ -114,6 +114,7 @@ along with this program. If not, see . #define CARDKB_ADDR 0x5F #define TDECK_KB_ADDR 0x55 #define BBQ10_KB_ADDR 0x1F +#define MPR121_KB_ADDR 0x5A // ----------------------------------------------------------------------------- // SENSOR @@ -135,6 +136,7 @@ along with this program. If not, see . #define LPS22HB_ADDR_ALT 0x5D #define SHT31_4x_ADDR 0x44 #define PMSA0031_ADDR 0x12 +#define QMA6100P_ADDR 0x12 #define AHT10_ADDR 0x38 #define RCWL9620_ADDR 0x57 #define VEML7700_ADDR 0x10 @@ -144,6 +146,8 @@ along with this program. If not, see . #define MLX90632_ADDR 0x3A #define DFROBOT_LARK_ADDR 0x42 #define NAU7802_ADDR 0x2A +#define MAX30102_ADDR 0x57 +#define MLX90614_ADDR_DEF 0x5A // ----------------------------------------------------------------------------- // ACCELEROMETER @@ -185,6 +189,11 @@ along with this program. If not, see . // ----------------------------------------------------------------------------- #define FT6336U_ADDR 0x48 +// ----------------------------------------------------------------------------- +// BIAS-T Generator +// ----------------------------------------------------------------------------- +#define TPS65233_ADDR 0x60 + // convert 24-bit color to 16-bit (56K) #define COLOR565(r, g, b) (((r & 0xF8) << 8) | ((g & 0xFC) << 3) | ((b & 0xF8) >> 3)) diff --git a/src/detect/ScanI2C.cpp b/src/detect/ScanI2C.cpp index a9d70edaa9..4caa0f730b 100644 --- a/src/detect/ScanI2C.cpp +++ b/src/detect/ScanI2C.cpp @@ -31,14 +31,14 @@ ScanI2C::FoundDevice ScanI2C::firstRTC() const ScanI2C::FoundDevice ScanI2C::firstKeyboard() const { - ScanI2C::DeviceType types[] = {CARDKB, TDECKKB, BBQ10KB, RAK14004}; - return firstOfOrNONE(4, types); + ScanI2C::DeviceType types[] = {CARDKB, TDECKKB, BBQ10KB, RAK14004, MPR121KB}; + return firstOfOrNONE(5, types); } ScanI2C::FoundDevice ScanI2C::firstAccelerometer() const { - ScanI2C::DeviceType types[] = {MPU6050, LIS3DH, BMA423, LSM6DS3, BMX160, STK8BAXX, ICM20948}; - return firstOfOrNONE(7, types); + ScanI2C::DeviceType types[] = {MPU6050, LIS3DH, BMA423, LSM6DS3, BMX160, STK8BAXX, ICM20948, QMA6100P}; + return firstOfOrNONE(8, types); } ScanI2C::FoundDevice ScanI2C::find(ScanI2C::DeviceType) const diff --git a/src/detect/ScanI2C.h b/src/detect/ScanI2C.h index 3b49026ced..8591b8433c 100644 --- a/src/detect/ScanI2C.h +++ b/src/detect/ScanI2C.h @@ -39,6 +39,7 @@ class ScanI2C QMC5883L, HMC5883L, PMSA0031, + QMA6100P, MPU6050, LIS3DH, BMA423, @@ -52,13 +53,17 @@ class ScanI2C TSL2591, OPT3001, MLX90632, + MLX90614, AHT10, BMX160, DFROBOT_LARK, NAU7802, FT6336U, STK8BAXX, - ICM20948 + ICM20948, + MAX30102, + TPS65233, + MPR121KB } DeviceType; // typedef uint8_t DeviceAddress; diff --git a/src/detect/ScanI2CTwoWire.cpp b/src/detect/ScanI2CTwoWire.cpp index 43340765aa..d39c9899c5 100644 --- a/src/detect/ScanI2CTwoWire.cpp +++ b/src/detect/ScanI2CTwoWire.cpp @@ -7,7 +7,8 @@ #include "linux/LinuxHardwareI2C.h" #endif #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) -#include "main.h" // atecc +#include "main.h" // atecc +#include "meshUtils.h" // vformat #endif // AXP192 and AXP2101 have the same device address, we just need to identify it in Power.cpp @@ -71,15 +72,15 @@ ScanI2C::DeviceType ScanI2CTwoWire::probeOLED(ScanI2C::DeviceAddress addr) const r &= 0x0f; if (r == 0x08 || r == 0x00) { - LOG_INFO("sh1106 display found\n"); + LOG_INFO("sh1106 display found"); o_probe = SCREEN_SH1106; // SH1106 } else if (r == 0x03 || r == 0x04 || r == 0x06 || r == 0x07) { - LOG_INFO("ssd1306 display found\n"); + LOG_INFO("ssd1306 display found"); o_probe = SCREEN_SSD1306; // SSD1306 } c++; } while ((r != r_prev) && (c < 4)); - LOG_DEBUG("0x%x subtype probed in %i tries \n", r, c); + LOG_DEBUG("0x%x subtype probed in %i tries ", r, c); return o_probe; } @@ -88,31 +89,31 @@ void ScanI2CTwoWire::printATECCInfo() const #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) atecc.readConfigZone(false); - LOG_DEBUG("ATECC608B Serial Number: "); + std::string atecc_numbers = "ATECC608B Serial Number: "; for (int i = 0; i < 9; i++) { - LOG_DEBUG("%02x", atecc.serialNumber[i]); + atecc_numbers += vformat("%02x", atecc.serialNumber[i]); } - LOG_DEBUG(", Rev Number: "); + atecc_numbers += ", Rev Number: "; for (int i = 0; i < 4; i++) { - LOG_DEBUG("%02x", atecc.revisionNumber[i]); + atecc_numbers += vformat("%02x", atecc.revisionNumber[i]); } - LOG_DEBUG("\n"); + LOG_DEBUG(atecc_numbers.c_str()); - LOG_DEBUG("ATECC608B Config %s", atecc.configLockStatus ? "Locked" : "Unlocked"); - LOG_DEBUG(", Data %s", atecc.dataOTPLockStatus ? "Locked" : "Unlocked"); - LOG_DEBUG(", Slot 0 %s\n", atecc.slot0LockStatus ? "Locked" : "Unlocked"); + LOG_DEBUG("ATECC608B Config %s, Data %s, Slot 0 %s", atecc.configLockStatus ? "Locked" : "Unlocked", + atecc.dataOTPLockStatus ? "Locked" : "Unlocked", atecc.slot0LockStatus ? "Locked" : "Unlocked"); + std::string atecc_publickey = ""; if (atecc.configLockStatus && atecc.dataOTPLockStatus && atecc.slot0LockStatus) { if (atecc.generatePublicKey() == false) { - LOG_DEBUG("ATECC608B Error generating public key\n"); + atecc_publickey += "ATECC608B Error generating public key"; } else { - LOG_DEBUG("ATECC608B Public Key: "); + atecc_publickey += "ATECC608B Public Key: "; for (int i = 0; i < 64; i++) { - LOG_DEBUG("%02x", atecc.publicKey64Bytes[i]); + atecc_publickey += vformat("%02x", atecc.publicKey64Bytes[i]); } - LOG_DEBUG("\n"); } + LOG_DEBUG(atecc_publickey.c_str()); } #endif } @@ -128,7 +129,7 @@ uint16_t ScanI2CTwoWire::getRegisterValue(const ScanI2CTwoWire::RegisterLocation i2cBus->endTransmission(); delay(20); i2cBus->requestFrom(registerLocation.i2cAddress.address, responseWidth); - LOG_DEBUG("Wire.available() = %d\n", i2cBus->available()); + LOG_DEBUG("Wire.available() = %d", i2cBus->available()); if (i2cBus->available() == 2) { // Read MSB, then LSB value = (uint16_t)i2cBus->read() << 8; @@ -149,7 +150,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) { concurrency::LockGuard guard((concurrency::Lock *)&lock); - LOG_DEBUG("Scanning for I2C devices on port %d\n", port); + LOG_DEBUG("Scanning for I2C devices on port %d", port); uint8_t err; @@ -172,11 +173,20 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) } #endif - for (addr.address = 1; addr.address < 127; addr.address++) { + // We only need to scan 112 addresses, the rest is reserved for special purposes + // 0x00 General Call + // 0x01 CBUS addresses + // 0x02 Reserved for different bus formats + // 0x03 Reserved for future purposes + // 0x04-0x07 High Speed Master Code + // 0x78-0x7B 10-bit slave addressing + // 0x7C-0x7F Reserved for future purposes + + for (addr.address = 8; addr.address < 120; addr.address++) { if (asize != 0) { if (!in_array(address, asize, addr.address)) continue; - LOG_DEBUG("Scanning address 0x%x\n", addr.address); + LOG_DEBUG("Scanning address 0x%x", addr.address); } i2cBus->beginTransmission(addr.address); #ifdef ARCH_PORTDUINO @@ -189,7 +199,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) #endif type = NONE; if (err == 0) { - LOG_DEBUG("I2C device found at address 0x%x\n", addr.address); + LOG_DEBUG("I2C device found at address 0x%x", addr.address); switch (addr.address) { case SSD1306_ADDRESS: @@ -205,9 +215,9 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) #endif { - LOG_INFO("ATECC608B initialized\n"); + LOG_INFO("ATECC608B initialized"); } else { - LOG_WARN("ATECC608B initialization failed\n"); + LOG_WARN("ATECC608B initialization failed"); } printATECCInfo(); break; @@ -217,7 +227,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) case RV3028_RTC: // foundDevices[addr] = RTC_RV3028; type = RTC_RV3028; - LOG_INFO("RV3028 RTC found\n"); + LOG_INFO("RV3028 RTC found"); rtc.initI2C(*i2cBus); rtc.writeToRegister(0x35, 0x07); // no Clkout rtc.writeToRegister(0x37, 0xB4); @@ -225,7 +235,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) #endif #ifdef PCF8563_RTC - SCAN_SIMPLE_CASE(PCF8563_RTC, RTC_PCF8563, "PCF8563 RTC found\n") + SCAN_SIMPLE_CASE(PCF8563_RTC, RTC_PCF8563, "PCF8563 RTC found") #endif case CARDKB_ADDR: @@ -233,49 +243,50 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x04), 1); if (registerValue == 0x02) { // KEYPAD_VERSION - LOG_INFO("RAK14004 found\n"); + LOG_INFO("RAK14004 found"); type = RAK14004; } else { - LOG_INFO("m5 cardKB found\n"); + LOG_INFO("m5 cardKB found"); type = CARDKB; } break; - SCAN_SIMPLE_CASE(TDECK_KB_ADDR, TDECKKB, "T-Deck keyboard found\n"); - SCAN_SIMPLE_CASE(BBQ10_KB_ADDR, BBQ10KB, "BB Q10 keyboard found\n"); - SCAN_SIMPLE_CASE(ST7567_ADDRESS, SCREEN_ST7567, "st7567 display found\n"); + SCAN_SIMPLE_CASE(TDECK_KB_ADDR, TDECKKB, "T-Deck keyboard found"); + SCAN_SIMPLE_CASE(BBQ10_KB_ADDR, BBQ10KB, "BB Q10 keyboard found"); + + SCAN_SIMPLE_CASE(ST7567_ADDRESS, SCREEN_ST7567, "st7567 display found"); #ifdef HAS_NCP5623 - SCAN_SIMPLE_CASE(NCP5623_ADDR, NCP5623, "NCP5623 RGB LED found\n"); + SCAN_SIMPLE_CASE(NCP5623_ADDR, NCP5623, "NCP5623 RGB LED found"); #endif #ifdef HAS_PMU - SCAN_SIMPLE_CASE(XPOWERS_AXP192_AXP2101_ADDRESS, PMU_AXP192_AXP2101, "axp192/axp2101 PMU found\n") + SCAN_SIMPLE_CASE(XPOWERS_AXP192_AXP2101_ADDRESS, PMU_AXP192_AXP2101, "axp192/axp2101 PMU found") #endif case BME_ADDR: case BME_ADDR_ALTERNATE: registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0xD0), 1); // GET_ID switch (registerValue) { case 0x61: - LOG_INFO("BME-680 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("BME-680 sensor found at address 0x%x", (uint8_t)addr.address); type = BME_680; break; case 0x60: - LOG_INFO("BME-280 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("BME-280 sensor found at address 0x%x", (uint8_t)addr.address); type = BME_280; break; case 0x55: - LOG_INFO("BMP-085 or BMP-180 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("BMP-085 or BMP-180 sensor found at address 0x%x", (uint8_t)addr.address); type = BMP_085; break; default: registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x00), 1); // GET_ID switch (registerValue) { case 0x50: // BMP-388 should be 0x50 - LOG_INFO("BMP-388 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("BMP-388 sensor found at address 0x%x", (uint8_t)addr.address); type = BMP_3XX; break; case 0x58: // BMP-280 should be 0x58 default: - LOG_INFO("BMP-280 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("BMP-280 sensor found at address 0x%x", (uint8_t)addr.address); type = BMP_280; break; } @@ -284,7 +295,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) break; #ifndef HAS_NCP5623 case AHT10_ADDR: - LOG_INFO("AHT10 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("AHT10 sensor found at address 0x%x", (uint8_t)addr.address); type = AHT10; break; #endif @@ -292,23 +303,23 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) case INA_ADDR_ALTERNATE: case INA_ADDR_WAVESHARE_UPS: registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0xFE), 2); - LOG_DEBUG("Register MFG_UID: 0x%x\n", registerValue); + LOG_DEBUG("Register MFG_UID: 0x%x", registerValue); if (registerValue == 0x5449) { - LOG_INFO("INA260 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("INA260 sensor found at address 0x%x", (uint8_t)addr.address); type = INA260; } else { // Assume INA219 if INA260 ID is not found - LOG_INFO("INA219 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("INA219 sensor found at address 0x%x", (uint8_t)addr.address); type = INA219; } break; case INA3221_ADDR: registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0xFE), 2); - LOG_DEBUG("Register MFG_UID: 0x%x\n", registerValue); + LOG_DEBUG("Register MFG_UID: 0x%x", registerValue); if (registerValue == 0x5449) { - LOG_INFO("INA3221 sensor found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("INA3221 sensor found at address 0x%x", (uint8_t)addr.address); type = INA3221; } else { - LOG_INFO("DFRobot Lark weather station found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("DFRobot Lark weather station found at address 0x%x", (uint8_t)addr.address); type = DFROBOT_LARK; } break; @@ -320,7 +331,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x00), 2); if (registerValue == 0x8700) { type = STK8BAXX; - LOG_INFO("STK8BAXX accelerometer found\n"); + LOG_INFO("STK8BAXX accelerometer found"); break; } @@ -328,7 +339,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x07), 2); if (registerValue == 0x0400) { type = MCP9808; - LOG_INFO("MCP9808 sensor found\n"); + LOG_INFO("MCP9808 sensor found"); break; } @@ -336,7 +347,7 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x0F), 2); if (registerValue == 0x3300 || registerValue == 0x3333) { // RAK4631 WisBlock has LIS3DH register at 0x3333 type = LIS3DH; - LOG_INFO("LIS3DH accelerometer found\n"); + LOG_INFO("LIS3DH accelerometer found"); } break; } @@ -344,80 +355,109 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize) registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x89), 2); if (registerValue == 0x11a2 || registerValue == 0x11da || registerValue == 0xe9c) { type = SHT4X; - LOG_INFO("SHT4X sensor found\n"); + LOG_INFO("SHT4X sensor found"); } else if (getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x7E), 2) == 0x5449) { type = OPT3001; - LOG_INFO("OPT3001 light sensor found\n"); + LOG_INFO("OPT3001 light sensor found"); } else { type = SHT31; - LOG_INFO("SHT31 sensor found\n"); + LOG_INFO("SHT31 sensor found"); } break; - SCAN_SIMPLE_CASE(SHTC3_ADDR, SHTC3, "SHTC3 sensor found\n") - SCAN_SIMPLE_CASE(RCWL9620_ADDR, RCWL9620, "RCWL9620 sensor found\n") + SCAN_SIMPLE_CASE(SHTC3_ADDR, SHTC3, "SHTC3 sensor found") + case RCWL9620_ADDR: + // get MAX30102 PARTID + registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0xFF), 1); + if (registerValue == 0x15) { + type = MAX30102; + LOG_INFO("MAX30102 Health sensor found"); + break; + } else { + type = RCWL9620; + LOG_INFO("RCWL9620 sensor found"); + } + break; case LPS22HB_ADDR_ALT: - SCAN_SIMPLE_CASE(LPS22HB_ADDR, LPS22HB, "LPS22HB sensor found\n") + SCAN_SIMPLE_CASE(LPS22HB_ADDR, LPS22HB, "LPS22HB sensor found") - SCAN_SIMPLE_CASE(QMC6310_ADDR, QMC6310, "QMC6310 Highrate 3-Axis magnetic sensor found\n") + SCAN_SIMPLE_CASE(QMC6310_ADDR, QMC6310, "QMC6310 Highrate 3-Axis magnetic sensor found") case QMI8658_ADDR: registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x0A), 1); // get ID if (registerValue == 0xC0) { type = BQ24295; - LOG_INFO("BQ24295 PMU found\n"); + LOG_INFO("BQ24295 PMU found"); break; } registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x0F), 1); // get ID if (registerValue == 0x6A) { type = LSM6DS3; - LOG_INFO("LSM6DS3 accelerometer found at address 0x%x\n", (uint8_t)addr.address); + LOG_INFO("LSM6DS3 accelerometer found at address 0x%x", (uint8_t)addr.address); } else { type = QMI8658; - LOG_INFO("QMI8658 Highrate 6-Axis inertial measurement sensor found\n"); + LOG_INFO("QMI8658 Highrate 6-Axis inertial measurement sensor found"); } break; - SCAN_SIMPLE_CASE(QMC5883L_ADDR, QMC5883L, "QMC5883L Highrate 3-Axis magnetic sensor found\n") - SCAN_SIMPLE_CASE(HMC5883L_ADDR, HMC5883L, "HMC5883L 3-Axis digital compass found\n") - SCAN_SIMPLE_CASE(PMSA0031_ADDR, PMSA0031, "PMSA0031 air quality sensor found\n") - SCAN_SIMPLE_CASE(BMA423_ADDR, BMA423, "BMA423 accelerometer found\n"); - SCAN_SIMPLE_CASE(LSM6DS3_ADDR, LSM6DS3, "LSM6DS3 accelerometer found at address 0x%x\n", (uint8_t)addr.address); - SCAN_SIMPLE_CASE(TCA9535_ADDR, TCA9535, "TCA9535 I2C expander found\n"); - SCAN_SIMPLE_CASE(TCA9555_ADDR, TCA9555, "TCA9555 I2C expander found\n"); - SCAN_SIMPLE_CASE(VEML7700_ADDR, VEML7700, "VEML7700 light sensor found\n"); - SCAN_SIMPLE_CASE(TSL25911_ADDR, TSL2591, "TSL2591 light sensor found\n"); - SCAN_SIMPLE_CASE(OPT3001_ADDR, OPT3001, "OPT3001 light sensor found\n"); - SCAN_SIMPLE_CASE(MLX90632_ADDR, MLX90632, "MLX90632 IR temp sensor found\n"); - SCAN_SIMPLE_CASE(NAU7802_ADDR, NAU7802, "NAU7802 based scale found\n"); - SCAN_SIMPLE_CASE(FT6336U_ADDR, FT6336U, "FT6336U touchscreen found\n"); - SCAN_SIMPLE_CASE(MAX1704X_ADDR, MAX17048, "MAX17048 lipo fuel gauge found\n"); + SCAN_SIMPLE_CASE(QMC5883L_ADDR, QMC5883L, "QMC5883L Highrate 3-Axis magnetic sensor found") + SCAN_SIMPLE_CASE(HMC5883L_ADDR, HMC5883L, "HMC5883L 3-Axis digital compass found") +#ifdef HAS_QMA6100P + SCAN_SIMPLE_CASE(QMA6100P_ADDR, QMA6100P, "QMA6100P accelerometer found") +#else + SCAN_SIMPLE_CASE(PMSA0031_ADDR, PMSA0031, "PMSA0031 air quality sensor found") +#endif + SCAN_SIMPLE_CASE(BMA423_ADDR, BMA423, "BMA423 accelerometer found"); + SCAN_SIMPLE_CASE(LSM6DS3_ADDR, LSM6DS3, "LSM6DS3 accelerometer found at address 0x%x", (uint8_t)addr.address); + SCAN_SIMPLE_CASE(TCA9535_ADDR, TCA9535, "TCA9535 I2C expander found"); + SCAN_SIMPLE_CASE(TCA9555_ADDR, TCA9555, "TCA9555 I2C expander found"); + SCAN_SIMPLE_CASE(VEML7700_ADDR, VEML7700, "VEML7700 light sensor found"); + SCAN_SIMPLE_CASE(TSL25911_ADDR, TSL2591, "TSL2591 light sensor found"); + SCAN_SIMPLE_CASE(OPT3001_ADDR, OPT3001, "OPT3001 light sensor found"); + SCAN_SIMPLE_CASE(MLX90632_ADDR, MLX90632, "MLX90632 IR temp sensor found"); + SCAN_SIMPLE_CASE(NAU7802_ADDR, NAU7802, "NAU7802 based scale found"); + SCAN_SIMPLE_CASE(FT6336U_ADDR, FT6336U, "FT6336U touchscreen found"); + SCAN_SIMPLE_CASE(MAX1704X_ADDR, MAX17048, "MAX17048 lipo fuel gauge found"); +#ifdef HAS_TPS65233 + SCAN_SIMPLE_CASE(TPS65233_ADDR, TPS65233, "TPS65233 BIAS-T found"); +#endif + + case MLX90614_ADDR_DEF: + registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x0e), 1); + if (registerValue == 0x5a) { + type = MLX90614; + LOG_INFO("MLX90614 IR temp sensor found"); + } else { + type = MPR121KB; + LOG_INFO("MPR121KB keyboard found"); + } + break; case ICM20948_ADDR: // same as BMX160_ADDR case ICM20948_ADDR_ALT: // same as MPU6050_ADDR registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x00), 1); if (registerValue == 0xEA) { type = ICM20948; - LOG_INFO("ICM20948 9-dof motion processor found\n"); + LOG_INFO("ICM20948 9-dof motion processor found"); break; } else if (addr.address == BMX160_ADDR) { type = BMX160; - LOG_INFO("BMX160 accelerometer found\n"); + LOG_INFO("BMX160 accelerometer found"); break; } else { type = MPU6050; - LOG_INFO("MPU6050 accelerometer found\n"); + LOG_INFO("MPU6050 accelerometer found"); break; } break; default: - LOG_INFO("Device found at address 0x%x was not able to be enumerated\n", addr.address); + LOG_INFO("Device found at address 0x%x was not able to be enumerated", addr.address); } } else if (err == 4) { - LOG_ERROR("Unknown error at address 0x%x\n", addr.address); + LOG_ERROR("Unknown error at address 0x%x", addr.address); } // Check if a type was found for the enumerated device - save, if so diff --git a/src/detect/axpDebug.h b/src/detect/axpDebug.h deleted file mode 100644 index fc95447aa5..0000000000 --- a/src/detect/axpDebug.h +++ /dev/null @@ -1,19 +0,0 @@ -#if 0 -// Turn off for now -uint32_t axpDebugRead() -{ - axp.debugCharging(); - LOG_DEBUG("vbus current %f\n", axp.getVbusCurrent()); - LOG_DEBUG("charge current %f\n", axp.getBattChargeCurrent()); - LOG_DEBUG("bat voltage %f\n", axp.getBattVoltage()); - LOG_DEBUG("batt pct %d\n", axp.getBattPercentage()); - LOG_DEBUG("is battery connected %d\n", axp.isBatteryConnect()); - LOG_DEBUG("is USB connected %d\n", axp.isVBUSPlug()); - LOG_DEBUG("is charging %d\n", axp.isChargeing()); - - return 30 * 1000; -} - -Periodic axpDebugOutput(axpDebugRead); -axpDebugOutput.setup(); -#endif \ No newline at end of file diff --git a/src/detect/einkScan.h b/src/detect/einkScan.h index 6915709de2..d20c7b6e59 100644 --- a/src/detect/einkScan.h +++ b/src/detect/einkScan.h @@ -59,9 +59,9 @@ void scanEInkDevice(void) d_writeCommand(0x20); eink_found = (d_waitWhileBusy(150) > 0) ? true : false; if (eink_found) - LOG_DEBUG("EInk display found\n"); + LOG_DEBUG("EInk display found"); else - LOG_DEBUG("EInk display not found\n"); + LOG_DEBUG("EInk display not found"); SPI1.end(); } #endif \ No newline at end of file diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 33c21c5bbe..3a9516c842 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -7,6 +7,7 @@ #include "PowerMon.h" #include "RTC.h" #include "Throttle.h" +#include "buzz.h" #include "meshUtils.h" #include "main.h" // pmu_found @@ -154,7 +155,7 @@ uint8_t GPS::makeCASPacket(uint8_t class_id, uint8_t msg_id, uint8_t payload_siz CASChecksum(UBXscratch, (payload_size + 10)); #if defined(GPS_DEBUG) && defined(DEBUG_PORT) - LOG_DEBUG("Constructed CAS packet: \n"); + LOG_DEBUG("Constructed CAS packet: "); DEBUG_PORT.hexDump(MESHTASTIC_LOG_LEVEL_DEBUG, UBXscratch, payload_size + 10); #endif return (payload_size + 10); @@ -166,33 +167,33 @@ GPS_RESPONSE GPS::getACK(const char *message, uint32_t waitMillis) uint8_t b; int bytesRead = 0; uint32_t startTimeout = millis() + waitMillis; +#ifdef GPS_DEBUG + std::string debugmsg = ""; +#endif while (millis() < startTimeout) { if (_serial_gps->available()) { b = _serial_gps->read(); #ifdef GPS_DEBUG - LOG_DEBUG("%c", (b >= 32 && b <= 126) ? b : '.'); + debugmsg += vformat("%c", (b >= 32 && b <= 126) ? b : '.'); #endif buffer[bytesRead] = b; bytesRead++; if ((bytesRead == 767) || (b == '\r')) { if (strnstr((char *)buffer, message, bytesRead) != nullptr) { #ifdef GPS_DEBUG - LOG_DEBUG("\r\nFound: %s\r\n", message); // Log the found message + LOG_DEBUG("Found: %s", message); // Log the found message #endif return GNSS_RESPONSE_OK; } else { bytesRead = 0; #ifdef GPS_DEBUG - LOG_DEBUG("\r\n"); + LOG_DEBUG(debugmsg.c_str()); #endif } } } } -#ifdef GPS_DEBUG - LOG_DEBUG("\n"); -#endif return GNSS_RESPONSE_NONE; } @@ -235,7 +236,7 @@ GPS_RESPONSE GPS::getACKCas(uint8_t class_id, uint8_t msg_id, uint32_t waitMilli // Check for an ACK-ACK for the specified class and message id if ((msg_cls == 0x05) && (msg_msg_id == 0x01) && payload_cls == class_id && payload_msg == msg_id) { #ifdef GPS_DEBUG - LOG_INFO("Got ACK for class %02X message %02X in %d millis.\n", class_id, msg_id, millis() - startTime); + LOG_INFO("Got ACK for class %02X message %02X in %d millis.", class_id, msg_id, millis() - startTime); #endif return GNSS_RESPONSE_OK; } @@ -243,7 +244,7 @@ GPS_RESPONSE GPS::getACKCas(uint8_t class_id, uint8_t msg_id, uint32_t waitMilli // Check for an ACK-NACK for the specified class and message id if ((msg_cls == 0x05) && (msg_msg_id == 0x00) && payload_cls == class_id && payload_msg == msg_id) { #ifdef GPS_DEBUG - LOG_WARN("Got NACK for class %02X message %02X in %d millis.\n", class_id, msg_id, millis() - startTime); + LOG_WARN("Got NACK for class %02X message %02X in %d millis.", class_id, msg_id, millis() - startTime); #endif return GNSS_RESPONSE_NAK; } @@ -266,6 +267,9 @@ GPS_RESPONSE GPS::getACK(uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) uint32_t startTime = millis(); const char frame_errors[] = "More than 100 frame errors"; int sCounter = 0; +#ifdef GPS_DEBUG + std::string debugmsg = ""; +#endif for (int j = 2; j < 6; j++) { buf[8] += buf[j]; @@ -281,8 +285,8 @@ GPS_RESPONSE GPS::getACK(uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) while (Throttle::isWithinTimespanMs(startTime, waitMillis)) { if (ack > 9) { #ifdef GPS_DEBUG - LOG_DEBUG("\n"); - LOG_INFO("Got ACK for class %02X message %02X in %d millis.\n", class_id, msg_id, millis() - startTime); + LOG_DEBUG(""); + LOG_INFO("Got ACK for class %02X message %02X in %d millis.", class_id, msg_id, millis() - startTime); #endif return GNSS_RESPONSE_OK; // ACK received } @@ -291,22 +295,26 @@ GPS_RESPONSE GPS::getACK(uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) if (b == frame_errors[sCounter]) { sCounter++; if (sCounter == 26) { +#ifdef GPS_DEBUG + + LOG_DEBUG(debugmsg.c_str()); +#endif return GNSS_RESPONSE_FRAME_ERRORS; } } else { sCounter = 0; } #ifdef GPS_DEBUG - LOG_DEBUG("%02X", b); + debugmsg += vformat("%02X", b); #endif if (b == buf[ack]) { ack++; } else { if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message #ifdef GPS_DEBUG - LOG_DEBUG("\n"); + LOG_DEBUG(debugmsg.c_str()); #endif - LOG_WARN("Got NAK for class %02X message %02X\n", class_id, msg_id); + LOG_WARN("Got NAK for class %02X message %02X", class_id, msg_id); return GNSS_RESPONSE_NAK; // NAK received } ack = 0; // Reset the acknowledgement counter @@ -314,8 +322,8 @@ GPS_RESPONSE GPS::getACK(uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) } } #ifdef GPS_DEBUG - LOG_DEBUG("\n"); - LOG_WARN("No response for class %02X message %02X\n", class_id, msg_id); + LOG_DEBUG(debugmsg.c_str()); + LOG_WARN("No response for class %02X message %02X", class_id, msg_id); #endif return GNSS_RESPONSE_NONE; // No response received within timeout } @@ -388,7 +396,7 @@ int GPS::getACK(uint8_t *buffer, uint16_t size, uint8_t requestedClass, uint8_t } else { // return payload length #ifdef GPS_DEBUG - LOG_INFO("Got ACK for class %02X message %02X in %d millis.\n", requestedClass, requestedID, + LOG_INFO("Got ACK for class %02X message %02X in %d millis.", requestedClass, requestedID, millis() - startTime); #endif return needRead; @@ -400,7 +408,7 @@ int GPS::getACK(uint8_t *buffer, uint16_t size, uint8_t requestedClass, uint8_t } } } - // LOG_WARN("No response for class %02X message %02X\n", requestedClass, requestedID); + // LOG_WARN("No response for class %02X message %02X", requestedClass, requestedID); return 0; } @@ -416,13 +424,13 @@ bool GPS::setup() speedSelect = std::find(serialSpeeds, std::end(serialSpeeds), GPS_BAUDRATE) - serialSpeeds; } - LOG_DEBUG("Probing for GPS at %d \n", serialSpeeds[speedSelect]); + LOG_DEBUG("Probing for GPS at %d", serialSpeeds[speedSelect]); gnssModel = probe(serialSpeeds[speedSelect]); if (gnssModel == GNSS_MODEL_UNKNOWN) { if (++speedSelect == sizeof(serialSpeeds) / sizeof(int)) { speedSelect = 0; if (--probeTries == 0) { - LOG_WARN("Giving up on GPS probe and setting to 9600.\n"); + LOG_WARN("Giving up on GPS probe and setting to 9600."); return true; } } @@ -491,15 +499,15 @@ bool GPS::setup() msglen = makeCASPacket(0x06, 0x01, sizeof(cas_cfg_msg_packet), cas_cfg_msg_packet); _serial_gps->write(UBXscratch, msglen); if (getACKCas(0x06, 0x01, 250) != GNSS_RESPONSE_OK) { - LOG_WARN("ATGM336H - Could not enable NMEA MSG: %d\n", fields[i]); + LOG_WARN("ATGM336H - Could not enable NMEA MSG: %d", fields[i]); } } } else if (gnssModel == GNSS_MODEL_UC6580) { // The Unicore UC6580 can use a lot of sat systems, enable it to - // use GPS L1 & L5 + BDS B1I & B2a + GLONASS L1 + GALILEO E1 & E5a + SBAS + // use GPS L1 & L5 + BDS B1I & B2a + GLONASS L1 + GALILEO E1 & E5a + SBAS + QZSS // This will reset the receiver, so wait a bit afterwards // The paranoid will wait for the OK*04 confirmation response after each command. - _serial_gps->write("$CFGSYS,h25155\r\n"); + _serial_gps->write("$CFGSYS,h35155\r\n"); delay(750); // Must be done after the CFGSYS command // Turn off GSV messages, we don't really care about which and where the sats are, maybe someday. @@ -551,13 +559,13 @@ bool GPS::setup() msglen = makeUBXPacket(0x06, 0x09, sizeof(_message_SAVE), _message_SAVE); _serial_gps->write(UBXscratch, msglen); if (getACK(0x06, 0x09, 2000) != GNSS_RESPONSE_OK) { - LOG_WARN("Unable to save GNSS module configuration.\n"); + LOG_WARN("Unable to save GNSS module configuration."); } else { - LOG_INFO("GNSS module configuration saved!\n"); + LOG_INFO("GNSS module configuration saved!"); } } else if (IS_ONE_OF(gnssModel, GNSS_MODEL_UBLOX7, GNSS_MODEL_UBLOX8, GNSS_MODEL_UBLOX9)) { if (gnssModel == GNSS_MODEL_UBLOX7) { - LOG_DEBUG("Setting GPS+SBAS\n"); + LOG_DEBUG("Setting GPS+SBAS"); msglen = makeUBXPacket(0x06, 0x3e, sizeof(_message_GNSS_7), _message_GNSS_7); _serial_gps->write(UBXscratch, msglen); } else { // 8,9 @@ -567,12 +575,12 @@ bool GPS::setup() if (getACK(0x06, 0x3e, 800) == GNSS_RESPONSE_NAK) { // It's not critical if the module doesn't acknowledge this configuration. - LOG_INFO("reconfigure GNSS - defaults maintained. Is this module GPS-only?\n"); + LOG_INFO("reconfigure GNSS - defaults maintained. Is this module GPS-only?"); } else { if (gnssModel == GNSS_MODEL_UBLOX7) { - LOG_INFO("GNSS configured for GPS+SBAS.\n"); + LOG_INFO("GNSS configured for GPS+SBAS."); } else { // 8,9 - LOG_INFO("GNSS configured for GPS+SBAS+GLONASS+Galileo.\n"); + LOG_INFO("GNSS configured for GPS+SBAS+GLONASS+Galileo."); } // Documentation say, we need wait atleast 0.5s after reconfiguration of GNSS module, before sending next // commands for the M8 it tends to be more... 1 sec should be enough ;>) @@ -620,9 +628,9 @@ bool GPS::setup() msglen = makeUBXPacket(0x06, 0x09, sizeof(_message_SAVE), _message_SAVE); _serial_gps->write(UBXscratch, msglen); if (getACK(0x06, 0x09, 2000) != GNSS_RESPONSE_OK) { - LOG_WARN("Unable to save GNSS module configuration.\n"); + LOG_WARN("Unable to save GNSS module configuration."); } else { - LOG_INFO("GNSS module configuration saved!\n"); + LOG_INFO("GNSS module configuration saved!"); } } else if (gnssModel == GNSS_MODEL_UBLOX10) { delay(1000); @@ -667,9 +675,9 @@ bool GPS::setup() msglen = makeUBXPacket(0x06, 0x09, sizeof(_message_SAVE_10), _message_SAVE_10); _serial_gps->write(UBXscratch, msglen); if (getACK(0x06, 0x09, 2000) != GNSS_RESPONSE_OK) { - LOG_WARN("Unable to save GNSS module configuration.\n"); + LOG_WARN("Unable to save GNSS module configuration."); } else { - LOG_INFO("GNSS module configuration saved!\n"); + LOG_INFO("GNSS module configuration saved!"); } } didSerialInit = true; @@ -691,7 +699,7 @@ void GPS::setPowerState(GPSPowerState newState, uint32_t sleepTime) // Update the stored GPSPowerstate, and create local copies GPSPowerState oldState = powerState; powerState = newState; - LOG_INFO("GPS power state moving from %s to %s\n", getGPSPowerStateString(oldState), getGPSPowerStateString(newState)); + LOG_INFO("GPS power state moving from %s to %s", getGPSPowerStateString(oldState), getGPSPowerStateString(newState)); #ifdef HELTEC_MESH_NODE_T114 if ((oldState == GPS_OFF || oldState == GPS_HARDSLEEP) && (newState != GPS_OFF && newState != GPS_HARDSLEEP)) { @@ -761,7 +769,7 @@ void GPS::writePinEN(bool on) // Write and log enablePin->set(on); #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("Pin EN %s\n", val == HIGH ? "HIGH" : "LOW"); + LOG_DEBUG("Pin EN %s", val == HIGH ? "HIGH" : "LOW"); #endif } @@ -783,7 +791,7 @@ void GPS::writePinStandby(bool standby) pinMode(PIN_GPS_STANDBY, OUTPUT); digitalWrite(PIN_GPS_STANDBY, val); #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("Pin STANDBY %s\n", val == HIGH ? "HIGH" : "LOW"); + LOG_DEBUG("Pin STANDBY %s", val == HIGH ? "HIGH" : "LOW"); #endif #endif } @@ -817,7 +825,7 @@ void GPS::setPowerPMU(bool on) } #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("PMU %s\n", on ? "on" : "off"); + LOG_DEBUG("PMU %s", on ? "on" : "off"); #endif #endif } @@ -834,7 +842,7 @@ void GPS::setPowerUBLOX(bool on, uint32_t sleepMs) gps->_serial_gps->write(0xFF); clearBuffer(); // This often returns old data, so drop it #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("UBLOX: wake\n"); + LOG_DEBUG("UBLOX: wake"); #endif } @@ -849,7 +857,7 @@ void GPS::setPowerUBLOX(bool on, uint32_t sleepMs) } // Determine hardware version - if (gnssModel == GNSS_MODEL_UBLOX10) { + if (gnssModel != GNSS_MODEL_UBLOX10) { // Encode the sleep time in millis into the packet for (int i = 0; i < 4; i++) gps->_message_PMREQ[0 + i] = sleepMs >> (i * 8); @@ -869,7 +877,7 @@ void GPS::setPowerUBLOX(bool on, uint32_t sleepMs) gps->_serial_gps->write(gps->UBXscratch, msglen); #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("UBLOX: sleep for %dmS\n", sleepMs); + LOG_DEBUG("UBLOX: sleep for %dmS", sleepMs); #endif } } @@ -898,7 +906,7 @@ void GPS::down() uint32_t sleepTime = scheduling.msUntilNextSearch(); uint32_t updateInterval = Default::getConfiguredOrDefaultMs(config.position.gps_update_interval); - LOG_DEBUG("%us until next search\n", sleepTime / 1000); + LOG_DEBUG("%us until next search", sleepTime / 1000); // If update interval less than 10 seconds, no attempt to sleep if (updateInterval <= 10 * 1000UL || sleepTime == 0) @@ -921,7 +929,7 @@ void GPS::down() // https://www.desmos.com/calculator/6gvjghoumr // This is not particularly accurate, but probably an impromevement over a single, fixed threshold uint32_t hardsleepThreshold = (2750 * pow(predictedSearchDuration / 1000, 1.22)); - LOG_DEBUG("gps_update_interval >= %us needed to justify hardsleep\n", hardsleepThreshold / 1000); + LOG_DEBUG("gps_update_interval >= %us needed to justify hardsleep", hardsleepThreshold / 1000); // If update interval too short: softsleep (if supported by hardware) if (updateInterval < hardsleepThreshold) { @@ -940,7 +948,7 @@ void GPS::publishUpdate() shouldPublish = false; // In debug logs, identify position by @timestamp:stage (stage 2 = publish) - LOG_DEBUG("publishing pos@%x:2, hasVal=%d, Sats=%d, GPSlock=%d\n", p.timestamp, hasValidLocation, p.sats_in_view, + LOG_DEBUG("publishing pos@%x:2, hasVal=%d, Sats=%d, GPSlock=%d", p.timestamp, hasValidLocation, p.sats_in_view, hasLock()); // Notify any status instances that are observing us @@ -956,7 +964,7 @@ int32_t GPS::runOnce() { if (!GPSInitFinished) { if (!_serial_gps || config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_NOT_PRESENT) { - LOG_INFO("GPS set to not-present. Skipping probe.\n"); + LOG_INFO("GPS set to not-present. Skipping probe."); return disable(); } if (!setup()) @@ -968,7 +976,7 @@ int32_t GPS::runOnce() } // ONCE we will factory reset the GPS for bug #327 if (!devicestate.did_gps_reset) { - LOG_WARN("GPS FactoryReset requested\n"); + LOG_WARN("GPS FactoryReset requested"); if (gps->factoryReset()) { // If we don't succeed try again next time devicestate.did_gps_reset = true; nodeDB->saveToDisk(SEGMENT_DEVICESTATE); @@ -991,7 +999,7 @@ int32_t GPS::runOnce() GNSS_MODEL_UBLOX10)) { // reset the GPS on next bootup if (devicestate.did_gps_reset && scheduling.elapsedSearchMs() > 60 * 1000UL && !hasFlow()) { - LOG_DEBUG("GPS is not communicating, trying factory reset on next bootup.\n"); + LOG_DEBUG("GPS is not communicating, trying factory reset on next bootup."); devicestate.did_gps_reset = false; nodeDB->saveToDisk(SEGMENT_DEVICESTATE); return disable(); // Stop the GPS thread as it can do nothing useful until next reboot. @@ -1001,7 +1009,7 @@ int32_t GPS::runOnce() // At least one GPS has a bad habit of losing its mind from time to time if (rebootsSeen > 2) { rebootsSeen = 0; - LOG_DEBUG("Would normally factoryReset()\n"); + LOG_DEBUG("Would normally factoryReset()"); // gps->factoryReset(); } @@ -1018,23 +1026,23 @@ int32_t GPS::runOnce() bool gotLoc = lookForLocation(); if (gotLoc && !hasValidLocation) { // declare that we have location ASAP - LOG_DEBUG("hasValidLocation RISING EDGE\n"); + LOG_DEBUG("hasValidLocation RISING EDGE"); hasValidLocation = true; shouldPublish = true; } bool tooLong = scheduling.searchedTooLong(); if (tooLong) - LOG_WARN("Couldn't publish a valid location: didn't get a GPS lock in time.\n"); + LOG_WARN("Couldn't publish a valid location: didn't get a GPS lock in time."); // Once we get a location we no longer desperately want an update - // LOG_DEBUG("gotLoc %d, tooLong %d, gotTime %d\n", gotLoc, tooLong, gotTime); + // LOG_DEBUG("gotLoc %d, tooLong %d, gotTime %d", gotLoc, tooLong, gotTime); if ((gotLoc && gotTime) || tooLong) { if (tooLong) { // we didn't get a location during this ack window, therefore declare loss of lock if (hasValidLocation) { - LOG_DEBUG("hasValidLocation FALLING EDGE\n"); + LOG_DEBUG("hasValidLocation FALLING EDGE"); } p = meshtastic_Position_init_default; hasValidLocation = false; @@ -1066,13 +1074,13 @@ void GPS::clearBuffer() /// Prepare the GPS for the cpu entering deep or light sleep, expect to be gone for at least 100s of msecs int GPS::prepareDeepSleep(void *unused) { - LOG_INFO("GPS deep sleep!\n"); + LOG_INFO("GPS deep sleep!"); disable(); return 0; } -const char *PROBE_MESSAGE = "Trying %s (%s)...\n"; -const char *DETECTED_MESSAGE = "%s detected, using %s Module\n"; +const char *PROBE_MESSAGE = "Trying %s (%s)..."; +const char *DETECTED_MESSAGE = "%s detected, using %s Module"; #define PROBE_SIMPLE(CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \ LOG_DEBUG(PROBE_MESSAGE, TOWRITE, CHIP); \ @@ -1094,7 +1102,7 @@ GnssModel_t GPS::probe(int serialSpeed) _serial_gps->begin(serialSpeed); #else if (_serial_gps->baudRate() != serialSpeed) { - LOG_DEBUG("Setting Baud to %i\n", serialSpeed); + LOG_DEBUG("Setting Baud to %i", serialSpeed); _serial_gps->updateBaudRate(serialSpeed); } #endif @@ -1106,6 +1114,11 @@ GnssModel_t GPS::probe(int serialSpeed) // Close all NMEA sentences, valid for L76K, ATGM336H (and likely other AT6558 devices) _serial_gps->write("$PCAS03,0,0,0,0,0,0,0,0,0,0,,,0,0*02\r\n"); delay(20); + // Close NMEA sequences on Ublox + _serial_gps->write("$PUBX,40,GLL,0,0,0,0,0,0*5C\r\n"); + _serial_gps->write("$PUBX,40,GSV,0,0,0,0,0,0*59\r\n"); + _serial_gps->write("$PUBX,40,VTG,0,0,0,0,0,0*5E\r\n"); + delay(20); // Unicore UFirebirdII Series: UC6580, UM620, UM621, UM670A, UM680A, or UM681A PROBE_SIMPLE("UC6580", "$PDTINFO", "UC6580", GNSS_MODEL_UC6580, 500); @@ -1138,35 +1151,10 @@ GnssModel_t GPS::probe(int serialSpeed) // Check that the returned response class and message ID are correct GPS_RESPONSE response = getACK(0x06, 0x08, 750); if (response == GNSS_RESPONSE_NONE) { - LOG_WARN("Failed to find UBlox & MTK GNSS Module using baudrate %d\n", serialSpeed); + LOG_WARN("Failed to find GNSS Module (baudrate %d)", serialSpeed); return GNSS_MODEL_UNKNOWN; } else if (response == GNSS_RESPONSE_FRAME_ERRORS) { - LOG_INFO("UBlox Frame Errors using baudrate %d\n", serialSpeed); - } else if (response == GNSS_RESPONSE_OK) { - LOG_INFO("Found a UBlox Module using baudrate %d\n", serialSpeed); - } - - // 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 - if (serialSpeed != 9600) { - // Set the UART port to 9600 - uint8_t _message_prt[] = {0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, - 0x80, 0x25, 0x00, 0x00, 0x07, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - UBXChecksum(_message_prt, sizeof(_message_prt)); - _serial_gps->write(_message_prt, sizeof(_message_prt)); - delay(500); - serialSpeed = 9600; -#if defined(ARCH_NRF52) || defined(ARCH_PORTDUINO) || defined(ARCH_STM32WL) - _serial_gps->end(); - _serial_gps->begin(serialSpeed); -#elif defined(ARCH_RP2040) - _serial_gps->end(); - _serial_gps->setFIFOSize(256); - _serial_gps->begin(serialSpeed); -#else - _serial_gps->updateBaudRate(serialSpeed); -#endif - delay(200); + LOG_INFO("UBlox Frame Errors (baudrate %d)", serialSpeed); } memset(buffer, 0, sizeof(buffer)); @@ -1183,7 +1171,7 @@ GnssModel_t GPS::probe(int serialSpeed) uint16_t len = getACK(buffer, sizeof(buffer), 0x0A, 0x04, 1200); if (len) { - // LOG_DEBUG("monver reply size = %d\n", len); + // LOG_DEBUG("monver reply size = %d", len); uint16_t position = 0; for (int i = 0; i < 30; i++) { info.swVersion[i] = buffer[position]; @@ -1204,12 +1192,12 @@ GnssModel_t GPS::probe(int serialSpeed) break; } - 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("Module Info : "); + LOG_DEBUG("Soft version: %s", info.swVersion); + LOG_DEBUG("Hard version: %s", info.hwVersion); + LOG_DEBUG("Extensions:%d", info.extensionNo); for (int i = 0; i < info.extensionNo; i++) { - LOG_DEBUG(" %s\n", info.extension[i]); + LOG_DEBUG(" %s", info.extension[i]); } memset(buffer, 0, sizeof(buffer)); @@ -1218,38 +1206,37 @@ GnssModel_t GPS::probe(int serialSpeed) for (int i = 0; i < info.extensionNo; ++i) { if (!strncmp(info.extension[i], "MOD=", 4)) { strncpy((char *)buffer, &(info.extension[i][4]), sizeof(buffer)); - // LOG_DEBUG("GetModel:%s\n", (char *)buffer); - if (strlen((char *)buffer)) { - LOG_INFO("%s detected, using GNSS_MODEL_UBLOX\n", (char *)buffer); - } else { - LOG_INFO("Generic Ublox detected, using GNSS_MODEL_UBLOX\n"); - } } else if (!strncmp(info.extension[i], "PROTVER", 7)) { char *ptr = nullptr; memset(buffer, 0, sizeof(buffer)); strncpy((char *)buffer, &(info.extension[i][8]), sizeof(buffer)); - LOG_DEBUG("Protocol Version:%s\n", (char *)buffer); + LOG_DEBUG("Protocol Version:%s", (char *)buffer); if (strlen((char *)buffer)) { uBloxProtocolVersion = strtoul((char *)buffer, &ptr, 10); - LOG_DEBUG("ProtVer=%d\n", uBloxProtocolVersion); + LOG_DEBUG("ProtVer=%d", uBloxProtocolVersion); } else { uBloxProtocolVersion = 0; } } } if (strncmp(info.hwVersion, "00040007", 8) == 0) { + LOG_INFO(DETECTED_MESSAGE, "U-blox 6", "6"); return GNSS_MODEL_UBLOX6; } else if (strncmp(info.hwVersion, "00070000", 8) == 0) { + LOG_INFO(DETECTED_MESSAGE, "U-blox 7", "7"); return GNSS_MODEL_UBLOX7; } else if (strncmp(info.hwVersion, "00080000", 8) == 0) { + LOG_INFO(DETECTED_MESSAGE, "U-blox 8", "8"); return GNSS_MODEL_UBLOX8; } else if (strncmp(info.hwVersion, "00190000", 8) == 0) { + LOG_INFO(DETECTED_MESSAGE, "U-blox 9", "9"); return GNSS_MODEL_UBLOX9; } else if (strncmp(info.hwVersion, "000A0000", 8) == 0) { + LOG_INFO(DETECTED_MESSAGE, "U-blox 10", "10"); return GNSS_MODEL_UBLOX10; } } - + LOG_WARN("Failed to find GNSS Module (baudrate %d)", serialSpeed); return GNSS_MODEL_UNKNOWN; } @@ -1310,7 +1297,7 @@ GPS *GPS::createGps() // see NMEAGPS.h gsafixtype.begin(reader, NMEA_MSG_GXGSA, 2); gsapdop.begin(reader, NMEA_MSG_GXGSA, 15); - LOG_DEBUG("Using " NMEA_MSG_GXGSA " for 3DFIX and PDOP\n"); + LOG_DEBUG("Using " NMEA_MSG_GXGSA " for 3DFIX and PDOP"); #endif // Make sure the GPS is awake before performing any init. @@ -1331,8 +1318,8 @@ GPS *GPS::createGps() // ESP32 has a special set of parameters vs other arduino ports #if defined(ARCH_ESP32) - LOG_DEBUG("Using GPIO%d for GPS RX\n", new_gps->rx_gpio); - LOG_DEBUG("Using GPIO%d for GPS TX\n", new_gps->tx_gpio); + LOG_DEBUG("Using GPIO%d for GPS RX", new_gps->rx_gpio); + LOG_DEBUG("Using GPIO%d for GPS TX", new_gps->tx_gpio); _serial_gps->begin(GPS_BAUDRATE, SERIAL_8N1, new_gps->rx_gpio, new_gps->tx_gpio); #elif defined(ARCH_RP2040) _serial_gps->setFIFOSize(256); @@ -1390,11 +1377,11 @@ bool GPS::factoryReset() // delay(1000); } else if (gnssModel == GNSS_MODEL_MTK) { // send the CAS10 to perform a factory restart of the device (and other device that support PCAS statements) - LOG_INFO("GNSS Factory Reset via PCAS10,3\n"); + LOG_INFO("GNSS Factory Reset via PCAS10,3"); _serial_gps->write("$PCAS10,3*1F\r\n"); delay(100); } else if (gnssModel == GNSS_MODEL_ATGM336H) { - LOG_INFO("Factory Reset via CAS-CFG-RST\n"); + LOG_INFO("Factory Reset via CAS-CFG-RST"); uint8_t msglen = makeCASPacket(0x06, 0x02, sizeof(_message_CAS_CFG_RST_FACTORY), _message_CAS_CFG_RST_FACTORY); _serial_gps->write(UBXscratch, msglen); delay(100); @@ -1455,7 +1442,7 @@ The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of s 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 age %d\n", d.year(), d.month(), t.tm_mday, t.tm_hour, t.tm_min, + LOG_DEBUG("NMEA GPS time %02d-%02d-%02d %02d:%02d:%02d age %d", d.year(), d.month(), t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, ti.age()); perhapsSetRTC(RTCQualityGPS, t); return true; @@ -1499,7 +1486,7 @@ bool GPS::lookForLocation() #ifndef TINYGPS_OPTION_NO_STATISTICS if (reader.failedChecksum() > lastChecksumFailCount) { - LOG_WARN("%u new GPS checksum failures, for a total of %u.\n", reader.failedChecksum() - lastChecksumFailCount, + LOG_WARN("%u new GPS checksum failures, for a total of %u.", reader.failedChecksum() - lastChecksumFailCount, reader.failedChecksum()); lastChecksumFailCount = reader.failedChecksum(); } @@ -1507,7 +1494,7 @@ bool GPS::lookForLocation() #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS fixType = atoi(gsafixtype.value()); // will set to zero if no data - // LOG_DEBUG("FIX QUAL=%d, TYPE=%d\n", fixQual, fixType); + // LOG_DEBUG("FIX QUAL=%d, TYPE=%d", fixQual, fixType); #endif // check if GPS has an acceptable lock @@ -1515,7 +1502,7 @@ bool GPS::lookForLocation() 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", reader.location.age(), #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS gsafixtype.age(), #else @@ -1536,7 +1523,7 @@ bool GPS::lookForLocation() (gsafixtype.age() < GPS_SOL_EXPIRY_MS) && #endif (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()); + LOG_WARN("SOME data is TOO OLD: LOC %u, TIME %u, DATE %u", reader.location.age(), reader.time.age(), reader.date.age()); return false; } @@ -1546,13 +1533,13 @@ bool GPS::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)); + LOG_DEBUG("Bail out EARLY on LAT %i", 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)); + LOG_DEBUG("Bail out EARLY on LNG %i", toDegInt(loc.lng)); #endif return false; } @@ -1563,7 +1550,7 @@ bool GPS::lookForLocation() #ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS p.HDOP = reader.hdop.value(); p.PDOP = TinyGPSPlus::parseDecimal(gsapdop.value()); - // LOG_DEBUG("PDOP=%d, HDOP=%d\n", p.PDOP, p.HDOP); + // LOG_DEBUG("PDOP=%d, HDOP=%d", p.PDOP, p.HDOP); #else // FIXME! naive PDOP emulation (assumes VDOP==HDOP) // correct formula is PDOP = SQRT(HDOP^2 + VDOP^2) @@ -1573,7 +1560,7 @@ bool GPS::lookForLocation() // Discard incomplete or erroneous readings if (reader.hdop.value() == 0) { - LOG_WARN("BOGUS hdop.value() REJECTED: %d\n", reader.hdop.value()); + LOG_WARN("BOGUS hdop.value() REJECTED: %d", reader.hdop.value()); return false; } @@ -1610,7 +1597,7 @@ bool GPS::lookForLocation() 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", reader.course.value()); } } @@ -1644,24 +1631,27 @@ bool GPS::whileActive() { unsigned int charsInBuf = 0; bool isValid = false; +#ifdef GPS_DEBUG + std::string debugmsg = ""; +#endif if (powerState != GPS_ACTIVE) { clearBuffer(); return false; } #ifdef SERIAL_BUFFER_SIZE if (_serial_gps->available() >= SERIAL_BUFFER_SIZE - 1) { - LOG_WARN("GPS Buffer full with %u bytes waiting. Flushing to avoid corruption.\n", _serial_gps->available()); + LOG_WARN("GPS Buffer full with %u bytes waiting. Flushing to avoid corruption.", _serial_gps->available()); clearBuffer(); } #endif // if (_serial_gps->available() > 0) - // LOG_DEBUG("GPS Bytes Waiting: %u\n", _serial_gps->available()); + // LOG_DEBUG("GPS Bytes Waiting: %u", _serial_gps->available()); // First consume any chars that have piled up at the receiver while (_serial_gps->available() > 0) { int c = _serial_gps->read(); UBXscratch[charsInBuf] = c; #ifdef GPS_DEBUG - LOG_DEBUG("%c", c); + debugmsg += vformat("%c", (c >= 32 && c <= 126) ? c : '.'); #endif isValid |= reader.encode(c); if (charsInBuf > sizeof(UBXscratch) - 10 || c == '\r') { @@ -1673,6 +1663,9 @@ bool GPS::whileActive() charsInBuf++; } } +#ifdef GPS_DEBUG + LOG_DEBUG(debugmsg.c_str()); +#endif return isValid; } void GPS::enable() @@ -1700,17 +1693,19 @@ void GPS::toggleGpsMode() { if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_ENABLED) { config.position.gps_mode = meshtastic_Config_PositionConfig_GpsMode_DISABLED; - LOG_INFO("User toggled GpsMode. Now DISABLED.\n"); + LOG_INFO("User toggled GpsMode. Now DISABLED."); + playGPSDisableBeep(); #ifdef GNSS_AIROHA if (powerState == GPS_ACTIVE) { - LOG_DEBUG("User power Off GPS\n"); + LOG_DEBUG("User power Off GPS"); digitalWrite(PIN_GPS_EN, LOW); } #endif disable(); } else if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_DISABLED) { config.position.gps_mode = meshtastic_Config_PositionConfig_GpsMode_ENABLED; - LOG_INFO("User toggled GpsMode. Now ENABLED\n"); + LOG_INFO("User toggled GpsMode. Now ENABLED"); + playGPSEnableBeep(); enable(); } } diff --git a/src/gps/GPS.h b/src/gps/GPS.h index 6222881bc6..8b1982cf74 100644 --- a/src/gps/GPS.h +++ b/src/gps/GPS.h @@ -75,7 +75,7 @@ class GPS : private concurrency::OSThread uint8_t fixType = 0; // fix type from GPGSA #endif private: - const int serialSpeeds[6] = {9600, 4800, 38400, 57600, 115200, 9600}; + const int serialSpeeds[6] = {9600, 115200, 38400, 4800, 57600, 9600}; uint32_t lastWakeStartMsec = 0, lastSleepStartMsec = 0, lastFixStartMsec = 0; uint32_t rx_gpio = 0; uint32_t tx_gpio = 0; @@ -156,7 +156,7 @@ class GPS : private concurrency::OSThread static const uint8_t _message_CAS_CFG_NAVX_CONF[]; static const uint8_t _message_CAS_CFG_RATE_1HZ[]; - const char *ACK_SUCCESS_MESSAGE = "Get ack success!\n"; + const char *ACK_SUCCESS_MESSAGE = "Get ack success!"; meshtastic_Position p = meshtastic_Position_init_default; diff --git a/src/gps/GPSUpdateScheduling.cpp b/src/gps/GPSUpdateScheduling.cpp index 949ef60397..9c2626e848 100644 --- a/src/gps/GPSUpdateScheduling.cpp +++ b/src/gps/GPSUpdateScheduling.cpp @@ -13,7 +13,7 @@ void GPSUpdateScheduling::informSearching() void GPSUpdateScheduling::informGotLock() { searchEndedMs = millis(); - LOG_DEBUG("Took %us to get lock\n", (searchEndedMs - searchStartedMs) / 1000); + LOG_DEBUG("Took %us to get lock", (searchEndedMs - searchStartedMs) / 1000); updateLockTimePrediction(); } @@ -108,7 +108,7 @@ void GPSUpdateScheduling::updateLockTimePrediction() searchCount++; // Only tracked so we can diregard initial lock-times - LOG_DEBUG("Predicting %us to get next lock\n", predictedMsToGetLock / 1000); + LOG_DEBUG("Predicting %us to get next lock", predictedMsToGetLock / 1000); } // How long do we expect to spend searching for a lock? diff --git a/src/gps/RTC.cpp b/src/gps/RTC.cpp index d9ac56b743..8130d76681 100644 --- a/src/gps/RTC.cpp +++ b/src/gps/RTC.cpp @@ -46,7 +46,7 @@ void readFromRTC() tv.tv_usec = 0; uint32_t printableEpoch = tv.tv_sec; // Print lib only supports 32 bit but time_t can be 64 bit on some platforms - LOG_DEBUG("Read RTC time from RV3028 getTime as %02d-%02d-%02d %02d:%02d:%02d (%ld)\n", t.tm_year + 1900, t.tm_mon + 1, + LOG_DEBUG("Read RTC time from RV3028 getTime as %02d-%02d-%02d %02d:%02d:%02d (%ld)", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, printableEpoch); timeStartMsec = now; zeroOffsetSecs = tv.tv_sec; @@ -77,8 +77,8 @@ void readFromRTC() tv.tv_usec = 0; uint32_t printableEpoch = tv.tv_sec; // Print lib only supports 32 bit but time_t can be 64 bit on some platforms - LOG_DEBUG("Read RTC time from PCF8563 getDateTime as %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, printableEpoch); + LOG_DEBUG("Read RTC time from PCF8563 getDateTime as %02d-%02d-%02d %02d:%02d:%02d (%ld)", t.tm_year + 1900, t.tm_mon + 1, + t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, printableEpoch); timeStartMsec = now; zeroOffsetSecs = tv.tv_sec; if (currentQuality == RTCQualityNone) { @@ -89,7 +89,7 @@ void readFromRTC() if (!gettimeofday(&tv, NULL)) { uint32_t now = millis(); uint32_t printableEpoch = tv.tv_sec; // Print lib only supports 32 bit but time_t can be 64 bit on some platforms - LOG_DEBUG("Read RTC time as %ld\n", printableEpoch); + LOG_DEBUG("Read RTC time as %ld", printableEpoch); timeStartMsec = now; zeroOffsetSecs = tv.tv_sec; } @@ -112,7 +112,7 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv, bool forceUpdate) uint32_t printableEpoch = tv->tv_sec; // Print lib only supports 32 bit but time_t can be 64 bit on some platforms #ifdef BUILD_EPOCH if (tv->tv_sec < BUILD_EPOCH) { - LOG_WARN("Ignoring time (%ld) before build epoch (%ld)!\n", printableEpoch, BUILD_EPOCH); + LOG_WARN("Ignoring time (%ld) before build epoch (%ld)!", printableEpoch, BUILD_EPOCH); return false; } #endif @@ -120,21 +120,21 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv, bool forceUpdate) bool shouldSet; if (forceUpdate) { shouldSet = true; - LOG_DEBUG("Overriding current RTC quality (%s) with incoming time of RTC quality of %s\n", RtcName(currentQuality), + LOG_DEBUG("Overriding current RTC quality (%s) with incoming time of RTC quality of %s", RtcName(currentQuality), RtcName(q)); } else if (q > currentQuality) { shouldSet = true; - LOG_DEBUG("Upgrading time to quality %s\n", RtcName(q)); + LOG_DEBUG("Upgrading time to quality %s", RtcName(q)); } else if (q == RTCQualityGPS) { shouldSet = true; - LOG_DEBUG("Reapplying GPS time: %ld secs\n", printableEpoch); + LOG_DEBUG("Reapplying GPS time: %ld secs", printableEpoch); } else if (q == RTCQualityNTP && !Throttle::isWithinTimespanMs(lastSetMsec, (12 * 60 * 60 * 1000UL))) { // Every 12 hrs we will slam in a new NTP or Phone GPS / NTP time, to correct for local RTC clock drift shouldSet = true; - LOG_DEBUG("Reapplying external time to correct clock drift %ld secs\n", printableEpoch); + LOG_DEBUG("Reapplying external time to correct clock drift %ld secs", printableEpoch); } else { shouldSet = false; - LOG_DEBUG("Current RTC quality: %s. Ignoring time of RTC quality of %s\n", RtcName(currentQuality), RtcName(q)); + LOG_DEBUG("Current RTC quality: %s. Ignoring time of RTC quality of %s", RtcName(currentQuality), RtcName(q)); } if (shouldSet) { @@ -158,7 +158,7 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv, bool forceUpdate) #endif tm *t = gmtime(&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, + LOG_DEBUG("RV3028_RTC setTime %02d-%02d-%02d %02d:%02d:%02d (%ld)", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, printableEpoch); } #elif defined(PCF8563_RTC) @@ -172,8 +172,8 @@ bool perhapsSetRTC(RTCQuality q, const struct timeval *tv, bool forceUpdate) #endif tm *t = gmtime(&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, printableEpoch); + LOG_DEBUG("PCF8563_RTC setDateTime %02d-%02d-%02d %02d:%02d:%02d (%ld)", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, + t->tm_hour, t->tm_min, t->tm_sec, printableEpoch); } #elif defined(ARCH_ESP32) settimeofday(tv, NULL); @@ -228,9 +228,9 @@ bool perhapsSetRTC(RTCQuality q, struct tm &t) tv.tv_sec = res; tv.tv_usec = 0; // time.centisecond() * (10 / 1000); - // LOG_DEBUG("Got time from GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec); + // LOG_DEBUG("Got time from GPS month=%d, year=%d, unixtime=%ld", t.tm_mon, t.tm_year, tv.tv_sec); if (t.tm_year < 0 || t.tm_year >= 300) { - // LOG_DEBUG("Ignoring invalid GPS month=%d, year=%d, unixtime=%ld\n", t.tm_mon, t.tm_year, tv.tv_sec); + // LOG_DEBUG("Ignoring invalid GPS month=%d, year=%d, unixtime=%ld", t.tm_mon, t.tm_year, tv.tv_sec); return false; } else { return perhapsSetRTC(q, &tv); diff --git a/src/gps/ubx.h b/src/gps/ubx.h index b137d3349b..68cca00a3c 100644 --- a/src/gps/ubx.h +++ b/src/gps/ubx.h @@ -1,4 +1,4 @@ -const char *failMessage = "Unable to %s\n"; +const char *failMessage = "Unable to %s"; #define SEND_UBX_PACKET(TYPE, ID, DATA, ERRMSG, TIMEOUT) \ msglen = makeUBXPacket(TYPE, ID, sizeof(DATA), DATA); \ diff --git a/src/graphics/EInkDisplay2.cpp b/src/graphics/EInkDisplay2.cpp index c4cb10f827..1d3b2f6055 100644 --- a/src/graphics/EInkDisplay2.cpp +++ b/src/graphics/EInkDisplay2.cpp @@ -79,13 +79,13 @@ bool EInkDisplay::forceDisplay(uint32_t msecLimit) } // Trigger the refresh in GxEPD2 - LOG_DEBUG("Updating E-Paper... "); + LOG_DEBUG("Updating E-Paper"); adafruitDisplay->nextPage(); // End the update process endUpdate(); - LOG_DEBUG("done\n"); + LOG_DEBUG("done"); return true; } @@ -123,7 +123,7 @@ void EInkDisplay::setDetected(uint8_t detected) // Connect to the display - variant specific bool EInkDisplay::connect() { - LOG_INFO("Doing EInk init\n"); + LOG_INFO("Doing EInk init"); #ifdef PIN_EINK_EN // backlight power, HIGH is backlight on, LOW is off diff --git a/src/graphics/EInkDynamicDisplay.cpp b/src/graphics/EInkDynamicDisplay.cpp index ca994b2c90..ac5755bc14 100644 --- a/src/graphics/EInkDynamicDisplay.cpp +++ b/src/graphics/EInkDynamicDisplay.cpp @@ -119,7 +119,7 @@ void EInkDynamicDisplay::endOrDetach() awaitRefresh(); else { // Async begins - LOG_DEBUG("Async full-refresh begins (dropping frames)\n"); + LOG_DEBUG("Async full-refresh begins (dropping frames)"); notifyLater(intervalPollAsyncRefresh, DUE_POLL_ASYNCREFRESH, true); // Hand-off to NotifiedWorkerThread } } @@ -133,7 +133,7 @@ void EInkDynamicDisplay::endOrDetach() if (previousRefresh == FULL || previousRefresh == FAST) { // If refresh wasn't skipped (on unspecified..) LOG_WARN( "GxEPD2 version has not been modified to support async refresh; using fallback behavior. Please update lib_deps in " - "variant's platformio.ini file\n"); + "variant's platformio.ini file"); EInkDisplay::endUpdate(); } #endif @@ -170,7 +170,7 @@ bool EInkDynamicDisplay::determineMode() checkFastRequested(); if (refresh == UNSPECIFIED) - LOG_WARN("There was a flaw in the determineMode() logic.\n"); + LOG_WARN("There was a flaw in the determineMode() logic."); // -- Decision has been reached -- applyRefreshMode(); @@ -254,7 +254,7 @@ void EInkDynamicDisplay::checkRateLimiting() if (Throttle::isWithinTimespanMs(previousRunMs, EINK_LIMIT_RATE_RESPONSIVE_SEC * 1000)) { refresh = SKIPPED; reason = EXCEEDED_RATELIMIT_FAST; - LOG_DEBUG("refresh=SKIPPED, reason=EXCEEDED_RATELIMIT_FAST, frameFlags=0x%x\n", frameFlags); + LOG_DEBUG("refresh=SKIPPED, reason=EXCEEDED_RATELIMIT_FAST, frameFlags=0x%x", frameFlags); return; } } @@ -271,7 +271,7 @@ void EInkDynamicDisplay::checkCosmetic() if (frameFlags & COSMETIC) { refresh = FULL; reason = FLAGGED_COSMETIC; - LOG_DEBUG("refresh=FULL, reason=FLAGGED_COSMETIC, frameFlags=0x%x\n", frameFlags); + LOG_DEBUG("refresh=FULL, reason=FLAGGED_COSMETIC, frameFlags=0x%x", frameFlags); } } @@ -286,7 +286,7 @@ void EInkDynamicDisplay::checkDemandingFast() if (frameFlags & DEMAND_FAST) { refresh = FAST; reason = FLAGGED_DEMAND_FAST; - LOG_DEBUG("refresh=FAST, reason=FLAGGED_DEMAND_FAST, frameFlags=0x%x\n", frameFlags); + LOG_DEBUG("refresh=FAST, reason=FLAGGED_DEMAND_FAST, frameFlags=0x%x", frameFlags); } } @@ -306,7 +306,7 @@ void EInkDynamicDisplay::checkFrameMatchesPrevious() if (frameFlags == BACKGROUND && fastRefreshCount > 0) { refresh = FULL; reason = REDRAW_WITH_FULL; - LOG_DEBUG("refresh=FULL, reason=REDRAW_WITH_FULL, frameFlags=0x%x\n", frameFlags); + LOG_DEBUG("refresh=FULL, reason=REDRAW_WITH_FULL, frameFlags=0x%x", frameFlags); return; } #endif @@ -314,7 +314,7 @@ void EInkDynamicDisplay::checkFrameMatchesPrevious() // Not redrawn, not COSMETIC, not DEMAND_FAST refresh = SKIPPED; reason = FRAME_MATCHED_PREVIOUS; - LOG_DEBUG("refresh=SKIPPED, reason=FRAME_MATCHED_PREVIOUS, frameFlags=0x%x\n", frameFlags); + LOG_DEBUG("refresh=SKIPPED, reason=FRAME_MATCHED_PREVIOUS, frameFlags=0x%x", frameFlags); } // Have too many fast-refreshes occured consecutively, since last full refresh? @@ -328,7 +328,7 @@ void EInkDynamicDisplay::checkConsecutiveFastRefreshes() if (fastRefreshCount >= EINK_LIMIT_FASTREFRESH) { refresh = FULL; reason = EXCEEDED_LIMIT_FASTREFRESH; - LOG_DEBUG("refresh=FULL, reason=EXCEEDED_LIMIT_FASTREFRESH, frameFlags=0x%x\n", frameFlags); + LOG_DEBUG("refresh=FULL, reason=EXCEEDED_LIMIT_FASTREFRESH, frameFlags=0x%x", frameFlags); } } @@ -343,13 +343,13 @@ void EInkDynamicDisplay::checkFastRequested() // If we want BACKGROUND to use fast. (FULL only when a limit is hit) refresh = FAST; reason = BACKGROUND_USES_FAST; - LOG_DEBUG("refresh=FAST, reason=BACKGROUND_USES_FAST, fastRefreshCount=%lu, frameFlags=0x%x\n", fastRefreshCount, + LOG_DEBUG("refresh=FAST, reason=BACKGROUND_USES_FAST, fastRefreshCount=%lu, frameFlags=0x%x", fastRefreshCount, frameFlags); #else // If we do want to use FULL for BACKGROUND updates refresh = FULL; reason = FLAGGED_BACKGROUND; - LOG_DEBUG("refresh=FULL, reason=FLAGGED_BACKGROUND\n"); + LOG_DEBUG("refresh=FULL, reason=FLAGGED_BACKGROUND"); #endif } @@ -357,7 +357,7 @@ void EInkDynamicDisplay::checkFastRequested() if (frameFlags & RESPONSIVE) { refresh = FAST; reason = NO_OBJECTIONS; - LOG_DEBUG("refresh=FAST, reason=NO_OBJECTIONS, fastRefreshCount=%lu, frameFlags=0x%x\n", fastRefreshCount, frameFlags); + LOG_DEBUG("refresh=FAST, reason=NO_OBJECTIONS, fastRefreshCount=%lu, frameFlags=0x%x", fastRefreshCount, frameFlags); } } @@ -438,7 +438,7 @@ void EInkDynamicDisplay::checkExcessiveGhosting() if (ghostPixelCount > EINK_LIMIT_GHOSTING_PX) { refresh = FULL; reason = EXCEEDED_GHOSTINGLIMIT; - LOG_DEBUG("refresh=FULL, reason=EXCEEDED_GHOSTINGLIMIT, frameFlags=0x%x\n", frameFlags); + LOG_DEBUG("refresh=FULL, reason=EXCEEDED_GHOSTINGLIMIT, frameFlags=0x%x", frameFlags); } } @@ -469,7 +469,7 @@ void EInkDynamicDisplay::joinAsyncRefresh() if (!asyncRefreshRunning) return; - LOG_DEBUG("Joining an async refresh in progress\n"); + LOG_DEBUG("Joining an async refresh in progress"); // Continually poll the BUSY pin while (adafruitDisplay->epd2.isBusy()) @@ -479,7 +479,7 @@ void EInkDynamicDisplay::joinAsyncRefresh() adafruitDisplay->endAsyncFull(); // Run the end of nextPage() code EInkDisplay::endUpdate(); // Run base-class code to finish off update (NOT our derived class override) asyncRefreshRunning = false; // Unset the flag - LOG_DEBUG("Refresh complete\n"); + LOG_DEBUG("Refresh complete"); // Note: this code only works because of a modification to meshtastic/GxEPD2. // It is only equipped to intercept calls to nextPage() @@ -503,7 +503,7 @@ void EInkDynamicDisplay::pollAsyncRefresh() adafruitDisplay->endAsyncFull(); // Run the end of nextPage() code EInkDisplay::endUpdate(); // Run base-class code to finish off update (NOT our derived class override) asyncRefreshRunning = false; // Unset the flag - LOG_DEBUG("Async full-refresh complete\n"); + LOG_DEBUG("Async full-refresh complete"); // Note: this code only works because of a modification to meshtastic/GxEPD2. // It is only equipped to intercept calls to nextPage() diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp index ad42fa9798..efa3ec78fe 100644 --- a/src/graphics/Screen.cpp +++ b/src/graphics/Screen.cpp @@ -144,7 +144,7 @@ static bool haveGlyphs(const char *str) } } - LOG_DEBUG("haveGlyphs=%d\n", have); + LOG_DEBUG("haveGlyphs=%d", have); return have; } @@ -186,56 +186,6 @@ static void drawIconScreen(const char *upperMsg, OLEDDisplay *display, OLEDDispl display->setTextAlignment(TEXT_ALIGN_LEFT); // Restore left align, just to be kind to any other unsuspecting code } -static void drawOEMIconScreen(const char *upperMsg, OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) -{ - // draw an xbm image. - // Please note that everything that should be transitioned - // needs to be drawn relative to x and y - - // draw centered icon left to right and centered above the one line of app text - display->drawXbm(x + (SCREEN_WIDTH - oemStore.oem_icon_width) / 2, - y + (SCREEN_HEIGHT - FONT_HEIGHT_MEDIUM - oemStore.oem_icon_height) / 2 + 2, oemStore.oem_icon_width, - oemStore.oem_icon_height, (const uint8_t *)oemStore.oem_icon_bits.bytes); - - switch (oemStore.oem_font) { - case 0: - display->setFont(FONT_SMALL); - break; - case 2: - display->setFont(FONT_LARGE); - break; - default: - display->setFont(FONT_MEDIUM); - break; - } - - display->setTextAlignment(TEXT_ALIGN_LEFT); - const char *title = oemStore.oem_text; - display->drawString(x + getStringCenteredX(title), y + SCREEN_HEIGHT - FONT_HEIGHT_MEDIUM, title); - display->setFont(FONT_SMALL); - - // Draw region in upper left - if (upperMsg) - display->drawString(x + 0, y + 0, upperMsg); - - // Draw version and shortname in upper right - char buf[25]; - snprintf(buf, sizeof(buf), "%s\n%s", xstr(APP_VERSION_SHORT), haveGlyphs(owner.short_name) ? owner.short_name : ""); - - display->setTextAlignment(TEXT_ALIGN_RIGHT); - display->drawString(x + SCREEN_WIDTH, y + 0, buf); - screen->forceDisplay(); - - display->setTextAlignment(TEXT_ALIGN_LEFT); // Restore left align, just to be kind to any other unsuspecting code -} - -static void drawOEMBootScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) -{ - // Draw region in upper left - const char *region = myRegion ? myRegion->name : NULL; - drawOEMIconScreen(region, display, state, x, y); -} - void Screen::drawFrameText(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y, const char *message) { uint16_t x_offset = display->width() / 2; @@ -292,7 +242,7 @@ static void drawWelcomeScreen(OLEDDisplay *display, OLEDDisplayUiState *state, i // draw overlay in bottom right corner of screen to show when notifications are muted or modifier key is active static void drawFunctionOverlay(OLEDDisplay *display, OLEDDisplayUiState *state) { - // LOG_DEBUG("Drawing function overlay\n"); + // LOG_DEBUG("Drawing function overlay"); if (functionSymbals.begin() != functionSymbals.end()) { char buf[64]; display->setFont(FONT_SMALL); @@ -310,7 +260,7 @@ static void drawDeepSleepScreen(OLEDDisplay *display, OLEDDisplayUiState *state, EINK_ADD_FRAMEFLAG(display, COSMETIC); EINK_ADD_FRAMEFLAG(display, BLOCKING); - LOG_DEBUG("Drawing deep sleep screen\n"); + LOG_DEBUG("Drawing deep sleep screen"); // Display displayStr on the screen drawIconScreen("Sleeping", display, state, x, y); @@ -319,7 +269,7 @@ static void drawDeepSleepScreen(OLEDDisplay *display, OLEDDisplayUiState *state, /// Used on eink displays when screen updates are paused static void drawScreensaverOverlay(OLEDDisplay *display, OLEDDisplayUiState *state) { - LOG_DEBUG("Drawing screensaver overlay\n"); + LOG_DEBUG("Drawing screensaver overlay"); EINK_ADD_FRAMEFLAG(display, COSMETIC); // Take the opportunity for a full-refresh @@ -385,9 +335,9 @@ static void drawModuleFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int } else { // otherwise, just display the module frame that's aligned with the current frame module_frame = state->currentFrame; - // LOG_DEBUG("Screen is not in transition. Frame: %d\n\n", module_frame); + // LOG_DEBUG("Screen is not in transition. Frame: %d", module_frame); } - // LOG_DEBUG("Drawing Module Frame %d\n\n", module_frame); + // LOG_DEBUG("Drawing Module Frame %d", module_frame); MeshModule &pi = *moduleFrames.at(module_frame); pi.drawFrame(display, state, x, y); } @@ -497,7 +447,7 @@ void Screen::drawDigitalClockFrame(OLEDDisplay *display, OLEDDisplayUiState *sta display->drawString(x + 20, y + 2, batteryPercent); } - if (nimbleBluetooth->isConnected()) { + if (nimbleBluetooth && nimbleBluetooth->isConnected()) { drawBluetoothConnectedIcon(display, display->getWidth() - 18, y + 2); } @@ -729,7 +679,7 @@ void Screen::drawAnalogClockFrame(OLEDDisplay *display, OLEDDisplayUiState *stat display->drawString(x + 20, y + 2, batteryPercent); } - if (nimbleBluetooth->isConnected()) { + if (nimbleBluetooth && nimbleBluetooth->isConnected()) { drawBluetoothConnectedIcon(display, display->getWidth() - 18, y + 2); } @@ -962,7 +912,7 @@ static void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state const meshtastic_MeshPacket &mp = devicestate.rx_text_message; meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(getFrom(&mp)); - // LOG_DEBUG("drawing text message from 0x%x: %s\n", mp.from, + // LOG_DEBUG("drawing text message from 0x%x: %s", mp.from, // mp.decoded.variant.data.decoded.bytes); // Demo for drawStringMaxWidth: @@ -1500,7 +1450,7 @@ static void drawNodeInfo(OLEDDisplay *display, OLEDDisplayUiState *state, int16_ if (!hasNodeHeading) { // direction to node is unknown so display question mark // Debug info for gps lock errors - // LOG_DEBUG("ourNode %d, ourPos %d, theirPos %d\n", !!ourNode, ourNode && hasValidPosition(ourNode), + // LOG_DEBUG("ourNode %d, ourPos %d, theirPos %d", !!ourNode, ourNode && hasValidPosition(ourNode), // hasValidPosition(node)); display->drawString(compassX - FONT_HEIGHT_SMALL / 4, compassY - FONT_HEIGHT_SMALL / 2, "?"); } @@ -1549,7 +1499,7 @@ Screen::Screen(ScanI2C::DeviceAddress address, meshtastic_Config_DisplayConfig_O (address.port == ScanI2C::I2CPort::WIRE1) ? HW_I2C::I2C_TWO : HW_I2C::I2C_ONE); #elif ARCH_PORTDUINO if (settingsMap[displayPanel] != no_screen) { - LOG_DEBUG("Making TFTDisplay!\n"); + LOG_DEBUG("Making TFTDisplay!"); dispdev = new TFTDisplay(address.address, -1, -1, geometry, (address.port == ScanI2C::I2CPort::WIRE1) ? HW_I2C::I2C_TWO : HW_I2C::I2C_ONE); } else { @@ -1596,7 +1546,7 @@ void Screen::handleSetOn(bool on, FrameCallback einkScreensaver) if (on != screenOn) { if (on) { - LOG_INFO("Turning on screen\n"); + LOG_INFO("Turning on screen"); powerMon->setState(meshtastic_PowerMon_State_Screen_On); #ifdef T_WATCH_S3 PMU->enablePowerOutput(XPOWERS_ALDO2); @@ -1631,7 +1581,7 @@ void Screen::handleSetOn(bool on, FrameCallback einkScreensaver) // eInkScreensaver parameter is usually NULL (default argument), default frame used instead setScreensaverFrames(einkScreensaver); #endif - LOG_INFO("Turning off screen\n"); + LOG_INFO("Turning off screen"); dispdev->displayOff(); #ifdef USE_ST7789 SPI1.end(); @@ -1699,9 +1649,6 @@ void Screen::setup() // Set the utf8 conversion function dispdev->setFontTableLookupFunction(customFontTableLookup); - if (strlen(oemStore.oem_text) > 0) - logo_timeout *= 2; - // Add frames. EINK_ADD_FRAMEFLAG(dispdev, DEMAND_FAST); alertFrames[0] = [this](OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) -> void { @@ -1842,28 +1789,11 @@ int32_t Screen::runOnce() // serialSinceMsec adjusts for additional serial wait time during nRF52 bootup static bool showingBootScreen = true; if (showingBootScreen && (millis() > (logo_timeout + serialSinceMsec))) { - LOG_INFO("Done with boot screen...\n"); + LOG_INFO("Done with boot screen..."); stopBootScreen(); showingBootScreen = false; } - // If we have an OEM Boot screen, toggle after logo_timeout seconds - if (strlen(oemStore.oem_text) > 0) { - static bool showingOEMBootScreen = true; - if (showingOEMBootScreen && (millis() > ((logo_timeout / 2) + serialSinceMsec))) { - LOG_INFO("Switch to OEM screen...\n"); - // Change frames. - static FrameCallback bootOEMFrames[] = {drawOEMBootScreen}; - static const int bootOEMFrameCount = sizeof(bootOEMFrames) / sizeof(bootOEMFrames[0]); - ui->setFrames(bootOEMFrames, bootOEMFrameCount); - ui->update(); -#ifndef USE_EINK - ui->update(); -#endif - showingOEMBootScreen = false; - } - } - #ifndef DISABLE_WELCOME_UNSET if (showingNormalScreen && config.lora.region == meshtastic_Config_LoRaConfig_RegionCode_UNSET) { setWelcomeFrames(); @@ -1917,7 +1847,7 @@ int32_t Screen::runOnce() free(cmd.print_text); break; default: - LOG_ERROR("Invalid screen cmd\n"); + LOG_ERROR("Invalid screen cmd"); } } @@ -1955,12 +1885,12 @@ int32_t Screen::runOnce() EINK_ADD_FRAMEFLAG(dispdev, COSMETIC); #endif - LOG_DEBUG("LastScreenTransition exceeded %ums transitioning to next frame\n", (millis() - lastScreenTransition)); + LOG_DEBUG("LastScreenTransition exceeded %ums transitioning to next frame", (millis() - lastScreenTransition)); handleOnPress(); } } - // LOG_DEBUG("want fps %d, fixed=%d\n", targetFramerate, + // LOG_DEBUG("want fps %d, fixed=%d", targetFramerate, // ui->getUiState()->frameState); If we are scrolling we need to be called // soon, otherwise just 1 fps (to save CPU) We also ask to be called twice // as fast as we really need so that any rounding errors still result with @@ -1991,7 +1921,7 @@ void Screen::drawDebugInfoWiFiTrampoline(OLEDDisplay *display, OLEDDisplayUiStat void Screen::setSSLFrames() { if (address_found.address) { - // LOG_DEBUG("showing SSL frames\n"); + // LOG_DEBUG("showing SSL frames"); static FrameCallback sslFrames[] = {drawSSLScreen}; ui->setFrames(sslFrames, 1); ui->update(); @@ -2003,7 +1933,7 @@ void Screen::setSSLFrames() void Screen::setWelcomeFrames() { if (address_found.address) { - // LOG_DEBUG("showing Welcome frames\n"); + // LOG_DEBUG("showing Welcome frames"); static FrameCallback frames[] = {drawWelcomeScreen}; setFrameImmediateDraw(frames); } @@ -2069,7 +1999,7 @@ void Screen::setFrames(FrameFocus focus) uint8_t originalPosition = ui->getUiState()->currentFrame; FramesetInfo fsi; // Location of specific frames, for applying focus parameter - LOG_DEBUG("showing standard frames\n"); + LOG_DEBUG("showing standard frames"); showingNormalScreen = true; #ifdef USE_EINK @@ -2082,10 +2012,10 @@ void Screen::setFrames(FrameFocus focus) #endif moduleFrames = MeshModule::GetMeshModulesWithUIFrames(); - LOG_DEBUG("Showing %d module frames\n", moduleFrames.size()); + LOG_DEBUG("Showing %d module frames", moduleFrames.size()); #ifdef DEBUG_PORT int totalFrameCount = MAX_NUM_NODES + NUM_EXTRA_FRAMES + moduleFrames.size(); - LOG_DEBUG("Total frame count: %d\n", totalFrameCount); + LOG_DEBUG("Total frame count: %d", totalFrameCount); #endif // We don't show the node info of our node (if we have it yet - we should) @@ -2119,7 +2049,7 @@ void Screen::setFrames(FrameFocus focus) numframes++; } - LOG_DEBUG("Added modules. numframes: %d\n", numframes); + LOG_DEBUG("Added modules. numframes: %d", numframes); // If we have a critical fault, show it first fsi.positions.fault = numframes; @@ -2164,7 +2094,7 @@ void Screen::setFrames(FrameFocus focus) #endif fsi.frameCount = numframes; // Total framecount is used to apply FOCUS_PRESERVE - LOG_DEBUG("Finished building frames. numframes: %d\n", numframes); + LOG_DEBUG("Finished building frames. numframes: %d", numframes); ui->setFrames(normalFrames, numframes); ui->enableAllIndicators(); @@ -2245,13 +2175,13 @@ void Screen::dismissCurrentFrame() bool dismissed = false; if (currentFrame == framesetInfo.positions.textMessage && devicestate.has_rx_text_message) { - LOG_INFO("Dismissing Text Message\n"); + LOG_INFO("Dismissing Text Message"); devicestate.has_rx_text_message = false; dismissed = true; } else if (currentFrame == framesetInfo.positions.waypoint && devicestate.has_rx_waypoint) { - LOG_DEBUG("Dismissing Waypoint\n"); + LOG_DEBUG("Dismissing Waypoint"); devicestate.has_rx_waypoint = false; dismissed = true; } @@ -2263,7 +2193,7 @@ void Screen::dismissCurrentFrame() void Screen::handleStartFirmwareUpdateScreen() { - LOG_DEBUG("showing firmware screen\n"); + LOG_DEBUG("showing firmware screen"); showingNormalScreen = false; EINK_ADD_FRAMEFLAG(dispdev, DEMAND_FAST); // E-Ink: Explicitly use fast-refresh for next frame @@ -2355,7 +2285,7 @@ void Screen::handlePrint(const char *text) { // the string passed into us probably has a newline, but that would confuse the logging system // so strip it - LOG_DEBUG("Screen: %.*s\n", strlen(text) - 1, text); + LOG_DEBUG("Screen: %.*s", strlen(text) - 1, text); if (!useDisplay || !showingNormalScreen) return; @@ -2708,7 +2638,7 @@ void DebugInfo::drawFrameSettings(OLEDDisplay *display, OLEDDisplayUiState *stat int Screen::handleStatusUpdate(const meshtastic::Status *arg) { - // LOG_DEBUG("Screen got status update %d\n", arg->getStatusType()); + // LOG_DEBUG("Screen got status update %d", arg->getStatusType()); switch (arg->getStatusType()) { case STATUS_TYPE_NODE: if (showingNormalScreen && nodeStatus->getLastNumTotal() != nodeStatus->getNumTotal()) { diff --git a/src/graphics/TFTDisplay.cpp b/src/graphics/TFTDisplay.cpp index 0c32a7c32e..3ba847c236 100644 --- a/src/graphics/TFTDisplay.cpp +++ b/src/graphics/TFTDisplay.cpp @@ -380,7 +380,7 @@ class LGFX : public lgfx::LGFX_Device _panel_instance->setBus(&_bus_instance); // set the bus on the panel. auto cfg = _panel_instance->config(); // Gets a structure for display panel settings. - LOG_DEBUG("Height: %d, Width: %d \n", settingsMap[displayHeight], settingsMap[displayWidth]); + LOG_DEBUG("Height: %d, Width: %d ", settingsMap[displayHeight], settingsMap[displayWidth]); cfg.pin_cs = settingsMap[displayCS]; // Pin number where CS is connected (-1 = disable) cfg.pin_rst = settingsMap[displayReset]; cfg.panel_width = settingsMap[displayWidth]; // actual displayable width @@ -643,7 +643,7 @@ GpioPin *TFTDisplay::backlightEnable = NULL; TFTDisplay::TFTDisplay(uint8_t address, int sda, int scl, OLEDDISPLAY_GEOMETRY geometry, HW_I2C i2cBus) { - LOG_DEBUG("TFTDisplay!\n"); + LOG_DEBUG("TFTDisplay!"); #ifdef TFT_BL GpioPin *p = new GpioHwPin(TFT_BL); @@ -712,7 +712,7 @@ void TFTDisplay::sendCommand(uint8_t com) // handle display on/off directly switch (com) { case DISPLAYON: { - // LOG_DEBUG("Display on\n"); + // LOG_DEBUG("Display on"); backlightEnable->set(true); #if ARCH_PORTDUINO display(true); @@ -736,7 +736,7 @@ void TFTDisplay::sendCommand(uint8_t com) break; } case DISPLAYOFF: { - // LOG_DEBUG("Display off\n"); + // LOG_DEBUG("Display off"); backlightEnable->set(false); #if ARCH_PORTDUINO tft->clear(); @@ -772,14 +772,14 @@ void TFTDisplay::setDisplayBrightness(uint8_t _brightness) // todo #else tft->setBrightness(_brightness); - LOG_DEBUG("Brightness is set to value: %i \n", _brightness); + LOG_DEBUG("Brightness is set to value: %i ", _brightness); #endif } void TFTDisplay::flipScreenVertically() { #if defined(T_WATCH_S3) - LOG_DEBUG("Flip TFT vertically\n"); // T-Watch S3 right-handed orientation + LOG_DEBUG("Flip TFT vertically"); // T-Watch S3 right-handed orientation tft->setRotation(0); #endif } @@ -823,7 +823,7 @@ void TFTDisplay::setDetected(uint8_t detected) bool TFTDisplay::connect() { concurrency::LockGuard g(spiLock); - LOG_INFO("Doing TFT init\n"); + LOG_INFO("Doing TFT init"); #ifdef RAK14014 tft = new TFT_eSPI; #else @@ -831,7 +831,7 @@ bool TFTDisplay::connect() #endif backlightEnable->set(true); - LOG_INFO("Power to TFT Backlight\n"); + LOG_INFO("Power to TFT Backlight"); #ifdef UNPHONE unphone.backlight(true); // using unPhone library diff --git a/src/input/ExpressLRSFiveWay.cpp b/src/input/ExpressLRSFiveWay.cpp index af4433daea..56413bd55d 100644 --- a/src/input/ExpressLRSFiveWay.cpp +++ b/src/input/ExpressLRSFiveWay.cpp @@ -233,7 +233,7 @@ void ExpressLRSFiveWay::sendAdhocPing() // Contained as one method for easier remapping of buttons by user void ExpressLRSFiveWay::shutdown() { - LOG_INFO("Shutdown from long press\n"); + LOG_INFO("Shutdown from long press"); powerFSM.trigger(EVENT_PRESS); screen->startAlert("Shutting down..."); // Don't set alerting = true. We don't want to auto-dismiss this alert. diff --git a/src/input/InputBroker.h b/src/input/InputBroker.h index 17c621c8a6..db7524bb08 100644 --- a/src/input/InputBroker.h +++ b/src/input/InputBroker.h @@ -18,6 +18,7 @@ #define INPUT_BROKER_MSG_RIGHT 0xb7 #define INPUT_BROKER_MSG_FN_SYMBOL_ON 0xf1 #define INPUT_BROKER_MSG_FN_SYMBOL_OFF 0xf2 +#define INPUT_BROKER_MSG_BLUETOOTH_TOGGLE 0xAA typedef struct _InputEvent { const char *source; diff --git a/src/input/MPR121Keyboard.cpp b/src/input/MPR121Keyboard.cpp new file mode 100644 index 0000000000..e1b32aa542 --- /dev/null +++ b/src/input/MPR121Keyboard.cpp @@ -0,0 +1,430 @@ +// Based on the BBQ10 Keyboard + +#include "MPR121Keyboard.h" +#include "configuration.h" +#include + +#define _MPR121_REG_KEY 0x5a + +#define _MPR121_REG_TOUCH_STATUS 0x00 +#define _MPR121_REG_ELECTRODE_FILTERED_DATA +#define _MPR121_REG_BASELINE_VALUE 0x1E + +// Baseline filters +#define _MPR121_REG_MAX_HALF_DELTA_RISING 0x2B +#define _MPR121_REG_NOISE_HALF_DELTA_RISING 0x2C +#define _MPR121_REG_NOISE_COUNT_LIMIT_RISING 0x2D +#define _MPR121_REG_FILTER_DELAY_COUNT_RISING 0x2E +#define _MPR121_REG_MAX_HALF_DELTA_FALLING 0x2F +#define _MPR121_REG_NOISE_HALF_DELTA_FALLING 0x30 +#define _MPR121_REG_NOISE_COUNT_LIMIT_FALLING 0x31 +#define _MPR121_REG_FILTER_DELAY_COUNT_FALLING 0x32 +#define _MPR121_REG_NOISE_HALF_DELTA_TOUCHED 0x33 +#define _MPR121_REG_NOISE_COUNT_LIMIT_TOUCHED 0x34 +#define _MPR121_REG_FILTER_DELAY_COUNT_TOUCHED 0x35 + +#define _MPR121_REG_TOUCH_THRESHOLD 0x41 // First input, +2 for subsequent +#define _MPR121_REG_RELEASE_THRESHOLD 0x42 // First input, +2 for subsequent +#define _MPR121_REG_DEBOUNCE 0x5B +#define _MPR121_REG_CONFIG1 0x5C +#define _MPR121_REG_CONFIG2 0x5D +#define _MPR121_REG_ELECTRODE_CONFIG 0x5E +#define _MPR121_REG_SOFT_RESET 0x80 + +#define _KEY_MASK 0x0FFF // Key mask for the first 12 bits +#define _NUM_KEYS 12 + +#define ECR_CALIBRATION_TRACK_FROM_ZERO (0 << 6) +#define ECR_CALIBRATION_LOCK (1 << 6) +#define ECR_CALIBRATION_TRACK_FROM_PARTIAL_FILTER (2 << 6) // Recommended Typical Mode +#define ECR_CALIBRATION_TRACK_FROM_FULL_FILTER (3 << 6) +#define ECR_PROXIMITY_DETECTION_OFF (0 << 0) // Not using proximity detection +#define ECR_TOUCH_DETECTION_12CH (12 << 0) // Using all 12 channels + +#define MPR121_NONE 0x00 +#define MPR121_REBOOT 0x90 +#define MPR121_LEFT 0xb4 +#define MPR121_UP 0xb5 +#define MPR121_DOWN 0xb6 +#define MPR121_RIGHT 0xb7 +#define MPR121_ESC 0x1b +#define MPR121_BSP 0x08 +#define MPR121_SELECT 0x0d + +#define MPR121_FN_ON 0xf1 +#define MPR121_FN_OFF 0xf2 + +#define LONG_PRESS_THRESHOLD 2000 +#define MULTI_TAP_THRESHOLD 2000 + +uint8_t TapMod[12] = {1, 2, 1, 13, 7, 7, 7, 7, 7, 9, 7, 9}; // Num chars per key, Modulus for rotating through characters + +unsigned char MPR121_TapMap[12][13] = {{MPR121_BSP}, + {'0', ' '}, + {MPR121_SELECT}, + {'1', '.', ',', '?', '!', ':', ';', '-', '_', '\\', '/', '(', ')'}, + {'2', 'a', 'b', 'c', 'A', 'B', 'C'}, + {'3', 'd', 'e', 'f', 'D', 'E', 'F'}, + {'4', 'g', 'h', 'i', 'G', 'H', 'I'}, + {'5', 'j', 'k', 'l', 'J', 'K', 'L'}, + {'6', 'm', 'n', 'o', 'M', 'N', 'O'}, + {'7', 'p', 'q', 'r', 's', 'P', 'Q', 'R', 'S'}, + {'8', 't', 'u', 'v', 'T', 'U', 'V'}, + {'9', 'w', 'x', 'y', 'z', 'W', 'X', 'Y', 'Z'}}; + +unsigned char MPR121_LongPressMap[12] = {MPR121_ESC, ' ', MPR121_NONE, MPR121_NONE, MPR121_UP, MPR121_NONE, + MPR121_LEFT, MPR121_NONE, MPR121_RIGHT, MPR121_NONE, MPR121_DOWN, MPR121_NONE}; + +// Translation map from left to right, top to bottom layout to a more convenient layout to manufacture, matching the +// https://www.amazon.com.au/Capacitive-Sensitive-Sensitivity-Replacement-Traditional/dp/B0CTJD5KW9/ref=pd_ci_mcx_mh_mcx_views_0_title?th=1 +/*uint8_t MPR121_KeyMap[12] = { + 9, 6, 3, 0, + 10, 7, 4, 1, + 11, 8, 5, 2 +};*/ +// Rotated Layout +uint8_t MPR121_KeyMap[12] = {2, 5, 8, 11, 1, 4, 7, 10, 0, 3, 6, 9}; + +MPR121Keyboard::MPR121Keyboard() : m_wire(nullptr), m_addr(0), readCallback(nullptr), writeCallback(nullptr) +{ + // LOG_DEBUG("MPR121 @ %02x\n", m_addr); + state = Init; + last_key = -1; + last_tap = 0L; + char_idx = 0; + queue = ""; +} + +void MPR121Keyboard::begin(uint8_t addr, TwoWire *wire) +{ + m_addr = addr; + m_wire = wire; + + m_wire->begin(); + + reset(); +} + +void MPR121Keyboard::begin(i2c_com_fptr_t r, i2c_com_fptr_t w, uint8_t addr) +{ + m_addr = addr; + m_wire = nullptr; + writeCallback = w; + readCallback = r; + reset(); +} + +void MPR121Keyboard::reset() +{ + LOG_DEBUG("MPR121 Resetting..."); + // Trigger a MPR121 Soft Reset + if (m_wire) { + m_wire->beginTransmission(m_addr); + m_wire->write(_MPR121_REG_SOFT_RESET); + m_wire->endTransmission(); + } + if (writeCallback) { + uint8_t data = 0; + writeCallback(m_addr, _MPR121_REG_SOFT_RESET, &data, 0); + } + delay(100); + // Reset Electrode Configuration to 0x00, Stop Mode + writeRegister(_MPR121_REG_ELECTRODE_CONFIG, 0x00); + delay(100); + + LOG_DEBUG("MPR121 Configuring"); + // Set touch release thresholds + for (uint8_t i = 0; i < 12; i++) { + // Set touch threshold + writeRegister(_MPR121_REG_TOUCH_THRESHOLD + (i * 2), 15); + delay(20); + // Set release threshold + writeRegister(_MPR121_REG_RELEASE_THRESHOLD + (i * 2), 7); + delay(20); + } + // Configure filtering and baseline registers + writeRegister(_MPR121_REG_MAX_HALF_DELTA_RISING, 0x01); + delay(20); + writeRegister(_MPR121_REG_MAX_HALF_DELTA_FALLING, 0x01); + delay(20); + writeRegister(_MPR121_REG_NOISE_HALF_DELTA_RISING, 0x01); + delay(20); + writeRegister(_MPR121_REG_NOISE_HALF_DELTA_FALLING, 0x05); + delay(20); + writeRegister(_MPR121_REG_NOISE_HALF_DELTA_TOUCHED, 0x00); + delay(20); + writeRegister(_MPR121_REG_NOISE_COUNT_LIMIT_RISING, 0x0e); + delay(20); + writeRegister(_MPR121_REG_NOISE_COUNT_LIMIT_FALLING, 0x01); + delay(20); + writeRegister(_MPR121_REG_NOISE_COUNT_LIMIT_TOUCHED, 0x00); + delay(20); + writeRegister(_MPR121_REG_FILTER_DELAY_COUNT_RISING, 0x00); + delay(20); + writeRegister(_MPR121_REG_FILTER_DELAY_COUNT_FALLING, 0x00); + delay(20); + writeRegister(_MPR121_REG_FILTER_DELAY_COUNT_TOUCHED, 0x00); + delay(20); + // Set Debounce to 0x02 + writeRegister(_MPR121_REG_DEBOUNCE, 0x00); + delay(20); + // Set Filter1 itterations and discharge current 6x and 16uA respectively (0x10) + writeRegister(_MPR121_REG_CONFIG1, 0x10); + delay(20); + // Set CDT to 0.5us, Filter2 itterations to 4x, and Sample interval = 0 (0x20) + writeRegister(_MPR121_REG_CONFIG2, 0x20); + delay(20); + // Enter run mode by Seting partial filter calibration tracking, disable proximity detection, enable 12 channels + writeRegister(_MPR121_REG_ELECTRODE_CONFIG, + ECR_CALIBRATION_TRACK_FROM_PARTIAL_FILTER | ECR_PROXIMITY_DETECTION_OFF | ECR_TOUCH_DETECTION_12CH); + delay(100); + LOG_DEBUG("MPR121 Running"); + state = Idle; +} + +void MPR121Keyboard::attachInterrupt(uint8_t pin, void (*func)(void)) const +{ + pinMode(pin, INPUT_PULLUP); + ::attachInterrupt(digitalPinToInterrupt(pin), func, RISING); +} + +void MPR121Keyboard::detachInterrupt(uint8_t pin) const +{ + ::detachInterrupt(pin); +} + +uint8_t MPR121Keyboard::status() const +{ + return readRegister16(_MPR121_REG_KEY); +} + +uint8_t MPR121Keyboard::keyCount() const +{ + // Read the key register + uint16_t keyRegister = readRegister16(_MPR121_REG_KEY); + return keyCount(keyRegister); +} + +uint8_t MPR121Keyboard::keyCount(uint16_t value) const +{ + // Mask the first 12 bits + uint16_t buttonState = value & _KEY_MASK; + + // Count how many bits are set to 1 (i.e., how many buttons are pressed) + uint8_t numButtonsPressed = 0; + for (uint8_t i = 0; i < 12; ++i) { + if (buttonState & (1 << i)) { + numButtonsPressed++; + } + } + + return numButtonsPressed; +} + +bool MPR121Keyboard::hasEvent() +{ + return queue.length() > 0; +} + +void MPR121Keyboard::queueEvent(char next) +{ + if (next == MPR121_NONE) { + return; + } + queue.concat(next); +} + +char MPR121Keyboard::dequeueEvent() +{ + if (queue.length() < 1) { + return MPR121_NONE; + } + char next = queue.charAt(0); + queue.remove(0, 1); + return next; +} + +void MPR121Keyboard::trigger() +{ + // Intended to fire in response to an interrupt from the MPR121 or a longpress callback + // Only functional if not in Init state + if (state != Init) { + // Read the key register + uint16_t keyRegister = readRegister16(_MPR121_REG_KEY); + uint8_t keysPressed = keyCount(keyRegister); + if (keysPressed == 0) { + // No buttons pressed + if (state == Held) + released(); + state = Idle; + return; + } + if (keysPressed == 1) { + // No buttons pressed + if (state == Held || state == HeldLong) + held(keyRegister); + if (state == Idle) + pressed(keyRegister); + return; + } + if (keysPressed > 1) { + // Multipress + state = Busy; + return; + } + } else { + reset(); + } +} + +void MPR121Keyboard::pressed(uint16_t keyRegister) +{ + if (state == Init || state == Busy) { + return; + } + if (keyCount(keyRegister) != 1) { + LOG_DEBUG("Multipress"); + return; + } else { + LOG_DEBUG("Pressed"); + } + uint16_t buttonState = keyRegister & _KEY_MASK; + uint8_t next_pin = 0; + for (uint8_t i = 0; i < 12; ++i) { + if (buttonState & (1 << i)) { + next_pin = i; + } + } + uint8_t next_key = MPR121_KeyMap[next_pin]; + LOG_DEBUG("MPR121 Pin: %i Key: %i", next_pin, next_key); + uint32_t now = millis(); + int32_t tap_interval = now - last_tap; + if (tap_interval < 0) { + // long running, millis has overflowed. + last_tap = 0; + state = Busy; + return; + } + if (next_key != last_key || tap_interval > MULTI_TAP_THRESHOLD) { + char_idx = 0; + } else { + char_idx += 1; + } + last_key = next_key; + last_tap = now; + state = Held; + return; +} + +void MPR121Keyboard::held(uint16_t keyRegister) +{ + if (state == Init || state == Busy) { + return; + } + if (keyCount(keyRegister) != 1) { + return; + } + LOG_DEBUG("Held"); + uint16_t buttonState = keyRegister & _KEY_MASK; + uint8_t next_key = 0; + for (uint8_t i = 0; i < 12; ++i) { + if (buttonState & (1 << i)) { + next_key = MPR121_KeyMap[i]; + } + } + uint32_t now = millis(); + int32_t held_interval = now - last_tap; + if (held_interval < 0 || next_key != last_key) { + // long running, millis has overflowed, or a key has been switched quickly... + last_tap = 0; + state = Busy; + return; + } + if (held_interval > LONG_PRESS_THRESHOLD) { + // Set state to heldlong, send a longpress, and reset the timer... + state = HeldLong; // heldlong will allow this function to still fire, but prevent a "release" + queueEvent(MPR121_LongPressMap[last_key]); + last_tap = now; + LOG_DEBUG("Long Press Key: %i Map: %i", last_key, MPR121_LongPressMap[last_key]); + } + return; +} + +void MPR121Keyboard::released() +{ + if (state != Held) { + return; + } + // would clear longpress callback... later. + if (last_key < 0 || last_key > _NUM_KEYS) { // reset to idle if last_key out of bounds + last_key = -1; + state = Idle; + return; + } + LOG_DEBUG("Released"); + if (char_idx > 0 && TapMod[last_key] > 1) { + queueEvent(MPR121_BSP); + LOG_DEBUG("Multi Press, Backspace"); + } + queueEvent(MPR121_TapMap[last_key][(char_idx % TapMod[last_key])]); + LOG_DEBUG("Key Press: %i Index:%i if %i Map: %i", last_key, char_idx, TapMod[last_key], + MPR121_TapMap[last_key][(char_idx % TapMod[last_key])]); +} + +uint8_t MPR121Keyboard::readRegister8(uint8_t reg) const +{ + if (m_wire) { + m_wire->beginTransmission(m_addr); + m_wire->write(reg); + m_wire->endTransmission(); + + m_wire->requestFrom(m_addr, (uint8_t)1); + if (m_wire->available() < 1) + return 0; + + return m_wire->read(); + } + if (readCallback) { + uint8_t data; + readCallback(m_addr, reg, &data, 1); + return data; + } + return 0; +} + +uint16_t MPR121Keyboard::readRegister16(uint8_t reg) const +{ + uint8_t data[2] = {0}; + // uint8_t low = 0, high = 0; + if (m_wire) { + m_wire->beginTransmission(m_addr); + m_wire->write(reg); + m_wire->endTransmission(); + + m_wire->requestFrom(m_addr, (uint8_t)2); + if (m_wire->available() < 2) + return 0; + data[0] = m_wire->read(); + data[1] = m_wire->read(); + } + if (readCallback) { + readCallback(m_addr, reg, data, 2); + } + return (data[1] << 8) | data[0]; +} + +void MPR121Keyboard::writeRegister(uint8_t reg, uint8_t value) +{ + uint8_t data[2]; + data[0] = reg; + data[1] = value; + + if (m_wire) { + m_wire->beginTransmission(m_addr); + m_wire->write(data, sizeof(uint8_t) * 2); + m_wire->endTransmission(); + } + if (writeCallback) { + writeCallback(m_addr, data[0], &(data[1]), 1); + } +} diff --git a/src/input/MPR121Keyboard.h b/src/input/MPR121Keyboard.h new file mode 100644 index 0000000000..6349750cef --- /dev/null +++ b/src/input/MPR121Keyboard.h @@ -0,0 +1,56 @@ +// Based on the BBQ10 Keyboard + +#include "concurrency/NotifiedWorkerThread.h" +#include "configuration.h" +#include +#include + +class MPR121Keyboard +{ + public: + typedef uint8_t (*i2c_com_fptr_t)(uint8_t dev_addr, uint8_t reg_addr, uint8_t *data, uint8_t len); + + enum MPR121States { Init = 0, Idle, Held, HeldLong, Busy }; + + MPR121States state; + + int8_t last_key; + uint32_t last_tap; + uint8_t char_idx; + + String queue; + + MPR121Keyboard(); + + void begin(uint8_t addr = MPR121_KB_ADDR, TwoWire *wire = &Wire); + + void begin(i2c_com_fptr_t r, i2c_com_fptr_t w, uint8_t addr = MPR121_KB_ADDR); + + void reset(void); + + void attachInterrupt(uint8_t pin, void (*func)(void)) const; + void detachInterrupt(uint8_t pin) const; + + void trigger(void); + void pressed(uint16_t value); + void held(uint16_t value); + void released(void); + + uint8_t status(void) const; + uint8_t keyCount(void) const; + uint8_t keyCount(uint16_t value) const; + + bool hasEvent(void); + char dequeueEvent(void); + void queueEvent(char); + + uint8_t readRegister8(uint8_t reg) const; + uint16_t readRegister16(uint8_t reg) const; + void writeRegister(uint8_t reg, uint8_t value); + + private: + TwoWire *m_wire; + uint8_t m_addr; + i2c_com_fptr_t readCallback; + i2c_com_fptr_t writeCallback; +}; \ No newline at end of file diff --git a/src/input/RotaryEncoderInterruptBase.cpp b/src/input/RotaryEncoderInterruptBase.cpp index 0b8e8325d5..785d98ebe0 100644 --- a/src/input/RotaryEncoderInterruptBase.cpp +++ b/src/input/RotaryEncoderInterruptBase.cpp @@ -28,7 +28,7 @@ void RotaryEncoderInterruptBase::init( this->rotaryLevelA = digitalRead(this->_pinA); this->rotaryLevelB = digitalRead(this->_pinB); - LOG_INFO("Rotary initialized (%d, %d, %d)\n", this->_pinA, this->_pinB, pinPress); + LOG_INFO("Rotary initialized (%d, %d, %d)", this->_pinA, this->_pinB, pinPress); } int32_t RotaryEncoderInterruptBase::runOnce() @@ -38,13 +38,13 @@ int32_t RotaryEncoderInterruptBase::runOnce() e.source = this->_originName; if (this->action == ROTARY_ACTION_PRESSED) { - LOG_DEBUG("Rotary event Press\n"); + LOG_DEBUG("Rotary event Press"); e.inputEvent = this->_eventPressed; } else if (this->action == ROTARY_ACTION_CW) { - LOG_DEBUG("Rotary event CW\n"); + LOG_DEBUG("Rotary event CW"); e.inputEvent = this->_eventCw; } else if (this->action == ROTARY_ACTION_CCW) { - LOG_DEBUG("Rotary event CCW\n"); + LOG_DEBUG("Rotary event CCW"); e.inputEvent = this->_eventCcw; } diff --git a/src/input/ScanAndSelect.cpp b/src/input/ScanAndSelect.cpp index 65ca7e332b..e1b39edf58 100644 --- a/src/input/ScanAndSelect.cpp +++ b/src/input/ScanAndSelect.cpp @@ -47,7 +47,7 @@ bool ScanAndSelectInput::init() // Connect our class to the canned message module inputBroker->registerSource(this); - LOG_INFO("Initialized 'Scan and Select' input for Canned Messages, using pin %d\n", pin); + LOG_INFO("Initialized 'Scan and Select' input for Canned Messages, using pin %d", pin); return true; // Init succeded } diff --git a/src/input/SerialKeyboard.cpp b/src/input/SerialKeyboard.cpp index 4827e89951..8d0730418b 100644 --- a/src/input/SerialKeyboard.cpp +++ b/src/input/SerialKeyboard.cpp @@ -52,7 +52,7 @@ int32_t SerialKeyboard::runOnce() digitalWrite(KB_LOAD, HIGH); digitalWrite(KB_CLK, LOW); prevKeys = 0b1111111111111111; - LOG_DEBUG("Serial Keyboard setup\n"); + LOG_DEBUG("Serial Keyboard setup"); } if (INPUTBROKER_SERIAL_TYPE == 1) { // Chatter V1.0 & V2.0 keypads diff --git a/src/input/TouchScreenBase.cpp b/src/input/TouchScreenBase.cpp index 2f361ac4c6..03618b3383 100644 --- a/src/input/TouchScreenBase.cpp +++ b/src/input/TouchScreenBase.cpp @@ -23,7 +23,7 @@ TouchScreenBase::TouchScreenBase(const char *name, uint16_t width, uint16_t heig void TouchScreenBase::init(bool hasTouch) { if (hasTouch) { - LOG_INFO("TouchScreen initialized %d %d\n", TOUCH_THRESHOLD_X, TOUCH_THRESHOLD_Y); + LOG_INFO("TouchScreen initialized %d %d", TOUCH_THRESHOLD_X, TOUCH_THRESHOLD_Y); this->setInterval(100); } else { disable(); @@ -68,20 +68,20 @@ int32_t TouchScreenBase::runOnce() if (adx > ady && adx > TOUCH_THRESHOLD_X) { if (0 > dx) { // swipe right to left e.touchEvent = static_cast(TOUCH_ACTION_LEFT); - LOG_DEBUG("action SWIPE: right to left\n"); + LOG_DEBUG("action SWIPE: right to left"); } else { // swipe left to right e.touchEvent = static_cast(TOUCH_ACTION_RIGHT); - LOG_DEBUG("action SWIPE: left to right\n"); + LOG_DEBUG("action SWIPE: left to right"); } } // swipe vertical else if (ady > adx && ady > TOUCH_THRESHOLD_Y) { if (0 > dy) { // swipe bottom to top e.touchEvent = static_cast(TOUCH_ACTION_UP); - LOG_DEBUG("action SWIPE: bottom to top\n"); + LOG_DEBUG("action SWIPE: bottom to top"); } else { // swipe top to bottom e.touchEvent = static_cast(TOUCH_ACTION_DOWN); - LOG_DEBUG("action SWIPE: top to bottom\n"); + LOG_DEBUG("action SWIPE: top to bottom"); } } // tap @@ -90,7 +90,7 @@ int32_t TouchScreenBase::runOnce() if (_tapped) { _tapped = false; e.touchEvent = static_cast(TOUCH_ACTION_DOUBLE_TAP); - LOG_DEBUG("action DOUBLE TAP(%d/%d)\n", x, y); + LOG_DEBUG("action DOUBLE TAP(%d/%d)", x, y); } else { _tapped = true; } @@ -106,7 +106,7 @@ int32_t TouchScreenBase::runOnce() if (_tapped && (time_t(millis()) - _start) > TIME_LONG_PRESS - 50) { _tapped = false; e.touchEvent = static_cast(TOUCH_ACTION_TAP); - LOG_DEBUG("action TAP(%d/%d)\n", _last_x, _last_y); + LOG_DEBUG("action TAP(%d/%d)", _last_x, _last_y); } // fire LONG_PRESS event without the need for release @@ -114,7 +114,7 @@ int32_t TouchScreenBase::runOnce() // tricky: prevent reoccurring events and another touch event when releasing _start = millis() + 30000; e.touchEvent = static_cast(TOUCH_ACTION_LONG_PRESS); - LOG_DEBUG("action LONG PRESS(%d/%d)\n", _last_x, _last_y); + LOG_DEBUG("action LONG PRESS(%d/%d)", _last_x, _last_y); } if (e.touchEvent != TOUCH_ACTION_NONE) { diff --git a/src/input/TrackballInterruptBase.cpp b/src/input/TrackballInterruptBase.cpp index 71cd130cc2..e35da36229 100644 --- a/src/input/TrackballInterruptBase.cpp +++ b/src/input/TrackballInterruptBase.cpp @@ -30,7 +30,7 @@ void TrackballInterruptBase::init(uint8_t pinDown, uint8_t pinUp, uint8_t pinLef attachInterrupt(this->_pinLeft, onIntLeft, RISING); attachInterrupt(this->_pinRight, onIntRight, RISING); - LOG_DEBUG("Trackball GPIO initialized (%d, %d, %d, %d, %d)\n", this->_pinUp, this->_pinDown, this->_pinLeft, this->_pinRight, + LOG_DEBUG("Trackball GPIO initialized (%d, %d, %d, %d, %d)", this->_pinUp, this->_pinDown, this->_pinLeft, this->_pinRight, pinPress); this->setInterval(100); @@ -42,19 +42,19 @@ int32_t TrackballInterruptBase::runOnce() e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; if (this->action == TB_ACTION_PRESSED) { - // LOG_DEBUG("Trackball event Press\n"); + // LOG_DEBUG("Trackball event Press"); e.inputEvent = this->_eventPressed; } else if (this->action == TB_ACTION_UP) { - // LOG_DEBUG("Trackball event UP\n"); + // LOG_DEBUG("Trackball event UP"); e.inputEvent = this->_eventUp; } else if (this->action == TB_ACTION_DOWN) { - // LOG_DEBUG("Trackball event DOWN\n"); + // LOG_DEBUG("Trackball event DOWN"); e.inputEvent = this->_eventDown; } else if (this->action == TB_ACTION_LEFT) { - // LOG_DEBUG("Trackball event LEFT\n"); + // LOG_DEBUG("Trackball event LEFT"); e.inputEvent = this->_eventLeft; } else if (this->action == TB_ACTION_RIGHT) { - // LOG_DEBUG("Trackball event RIGHT\n"); + // LOG_DEBUG("Trackball event RIGHT"); e.inputEvent = this->_eventRight; } diff --git a/src/input/UpDownInterruptBase.cpp b/src/input/UpDownInterruptBase.cpp index b1f83c56b0..979489c57a 100644 --- a/src/input/UpDownInterruptBase.cpp +++ b/src/input/UpDownInterruptBase.cpp @@ -23,7 +23,7 @@ void UpDownInterruptBase::init(uint8_t pinDown, uint8_t pinUp, uint8_t pinPress, attachInterrupt(this->_pinDown, onIntDown, RISING); attachInterrupt(this->_pinUp, onIntUp, RISING); - LOG_DEBUG("Up/down/press GPIO initialized (%d, %d, %d)\n", this->_pinUp, this->_pinDown, pinPress); + LOG_DEBUG("Up/down/press GPIO initialized (%d, %d, %d)", this->_pinUp, this->_pinDown, pinPress); this->setInterval(100); } @@ -34,13 +34,13 @@ int32_t UpDownInterruptBase::runOnce() e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; if (this->action == UPDOWN_ACTION_PRESSED) { - LOG_DEBUG("GPIO event Press\n"); + LOG_DEBUG("GPIO event Press"); e.inputEvent = this->_eventPressed; } else if (this->action == UPDOWN_ACTION_UP) { - LOG_DEBUG("GPIO event Up\n"); + LOG_DEBUG("GPIO event Up"); e.inputEvent = this->_eventUp; } else if (this->action == UPDOWN_ACTION_DOWN) { - LOG_DEBUG("GPIO event Down\n"); + LOG_DEBUG("GPIO event Down"); e.inputEvent = this->_eventDown; } diff --git a/src/input/cardKbI2cImpl.cpp b/src/input/cardKbI2cImpl.cpp index f1df6b1377..c1f35ba3c3 100644 --- a/src/input/cardKbI2cImpl.cpp +++ b/src/input/cardKbI2cImpl.cpp @@ -9,11 +9,11 @@ CardKbI2cImpl::CardKbI2cImpl() : KbI2cBase("cardKB") {} void CardKbI2cImpl::init() { -#if !MESHTASTIC_EXCLUDE_I2C && !defined(ARCH_PORTDUINO) +#if !MESHTASTIC_EXCLUDE_I2C && !defined(ARCH_PORTDUINO) && !defined(I2C_NO_RESCAN) if (cardkb_found.address == 0x00) { - LOG_DEBUG("Rescanning for I2C keyboard\n"); - uint8_t i2caddr_scan[] = {CARDKB_ADDR, TDECK_KB_ADDR, BBQ10_KB_ADDR}; - uint8_t i2caddr_asize = 3; + LOG_DEBUG("Rescanning for I2C keyboard"); + uint8_t i2caddr_scan[] = {CARDKB_ADDR, TDECK_KB_ADDR, BBQ10_KB_ADDR, MPR121_KB_ADDR}; + uint8_t i2caddr_asize = 4; auto i2cScanner = std::unique_ptr(new ScanI2CTwoWire()); #if WIRE_INTERFACES_COUNT == 2 @@ -39,12 +39,17 @@ void CardKbI2cImpl::init() // assign an arbitrary value to distinguish from other models kb_model = 0x11; break; + case ScanI2C::DeviceType::MPR121KB: + // assign an arbitrary value to distinguish from other models + kb_model = 0x37; + break; default: // use this as default since it's also just zero - LOG_WARN("kb_info.type is unknown(0x%02x), setting kb_model=0x00\n", kb_info.type); + LOG_WARN("kb_info.type is unknown(0x%02x), setting kb_model=0x00", kb_info.type); kb_model = 0x00; } } + LOG_DEBUG("Keyboard Type: 0x%02x Model: 0x%02x Address: 0x%02x", kb_info.type, kb_model, cardkb_found.address); if (cardkb_found.address == 0x00) { disable(); return; diff --git a/src/input/kbI2cBase.cpp b/src/input/kbI2cBase.cpp index 4fbca76e59..d0f36c3868 100644 --- a/src/input/kbI2cBase.cpp +++ b/src/input/kbI2cBase.cpp @@ -34,21 +34,27 @@ int32_t KbI2cBase::runOnce() switch (cardkb_found.port) { case ScanI2C::WIRE1: #if WIRE_INTERFACES_COUNT == 2 - LOG_DEBUG("Using I2C Bus 1 (the second one)\n"); + LOG_DEBUG("Using I2C Bus 1 (the second one)"); i2cBus = &Wire1; if (cardkb_found.address == BBQ10_KB_ADDR) { Q10keyboard.begin(BBQ10_KB_ADDR, &Wire1); Q10keyboard.setBacklight(0); } + if (cardkb_found.address == MPR121_KB_ADDR) { + MPRkeyboard.begin(MPR121_KB_ADDR, &Wire1); + } break; #endif case ScanI2C::WIRE: - LOG_DEBUG("Using I2C Bus 0 (the first one)\n"); + LOG_DEBUG("Using I2C Bus 0 (the first one)"); i2cBus = &Wire; if (cardkb_found.address == BBQ10_KB_ADDR) { Q10keyboard.begin(BBQ10_KB_ADDR, &Wire); Q10keyboard.setBacklight(0); } + if (cardkb_found.address == MPR121_KB_ADDR) { + MPRkeyboard.begin(MPR121_KB_ADDR, &Wire); + } break; case ScanI2C::NO_I2C: default: @@ -157,6 +163,69 @@ int32_t KbI2cBase::runOnce() } break; } + case 0x37: { // MPR121 + MPRkeyboard.trigger(); + InputEvent e; + + while (MPRkeyboard.hasEvent()) { + char nextEvent = MPRkeyboard.dequeueEvent(); + e.inputEvent = ANYKEY; + e.kbchar = 0x00; + e.source = this->_originName; + switch (nextEvent) { + case 0x00: // MPR121_NONE + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + e.kbchar = 0x00; + break; + case 0x90: // MPR121_REBOOT + e.inputEvent = ANYKEY; + e.kbchar = INPUT_BROKER_MSG_REBOOT; + break; + case 0xb4: // MPR121_LEFT + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_LEFT; + e.kbchar = 0x00; + break; + case 0xb5: // MPR121_UP + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_UP; + e.kbchar = 0x00; + break; + case 0xb6: // MPR121_DOWN + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_DOWN; + e.kbchar = 0x00; + break; + case 0xb7: // MPR121_RIGHT + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT; + e.kbchar = 0x00; + break; + case 0x1b: // MPR121_ESC + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL; + e.kbchar = 0x1b; + break; + case 0x08: // MPR121_BSP + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_BACK; + e.kbchar = 0x08; + break; + case 0x0d: // MPR121_SELECT + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_SELECT; + e.kbchar = 0x0d; + break; + default: + if (nextEvent > 127) { + e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; + e.kbchar = 0x00; + break; + } + e.inputEvent = ANYKEY; + e.kbchar = nextEvent; + break; + } + if (e.inputEvent != meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE) { + LOG_DEBUG("MP121 Notifying: %i Char: %i", e.inputEvent, e.kbchar); + this->notifyObservers(&e); + } + } + break; + } case 0x02: { // RAK14004 uint8_t rDataBuf[8] = {0}; @@ -171,7 +240,7 @@ int32_t KbI2cBase::runOnce() } } if (PrintDataBuf != 0) { - LOG_DEBUG("RAK14004 key 0x%x pressed\n", PrintDataBuf); + LOG_DEBUG("RAK14004 key 0x%x pressed", PrintDataBuf); InputEvent e; e.inputEvent = MATRIXKEY; e.source = this->_originName; @@ -297,6 +366,7 @@ int32_t KbI2cBase::runOnce() case 0x9e: // fn+g INPUT_BROKER_MSG_GPS_TOGGLE case 0xaf: // fn+space INPUT_BROKER_MSG_SEND_PING case 0x8b: // fn+del INPUT_BROKEN_MSG_DISMISS_FRAME + case 0xAA: // fn+b INPUT_BROKER_MSG_BLUETOOTH_TOGGLE // just pass those unmodified e.inputEvent = ANYKEY; e.kbchar = c; @@ -325,7 +395,7 @@ int32_t KbI2cBase::runOnce() break; } default: - LOG_WARN("Unknown kb_model 0x%02x\n", kb_model); + LOG_WARN("Unknown kb_model 0x%02x", kb_model); } return 300; } \ No newline at end of file diff --git a/src/input/kbI2cBase.h b/src/input/kbI2cBase.h index 35b9b09016..dc2414fc05 100644 --- a/src/input/kbI2cBase.h +++ b/src/input/kbI2cBase.h @@ -2,6 +2,7 @@ #include "BBQ10Keyboard.h" #include "InputBroker.h" +#include "MPR121Keyboard.h" #include "Wire.h" #include "concurrency/OSThread.h" @@ -19,5 +20,6 @@ class KbI2cBase : public Observable, public concurrency::OST TwoWire *i2cBus = 0; BBQ10Keyboard Q10keyboard; + MPR121Keyboard MPRkeyboard; bool is_sym = false; -}; +}; \ No newline at end of file diff --git a/src/input/kbMatrixBase.cpp b/src/input/kbMatrixBase.cpp index 823bfb6291..51815b5259 100644 --- a/src/input/kbMatrixBase.cpp +++ b/src/input/kbMatrixBase.cpp @@ -70,7 +70,7 @@ int32_t KbMatrixBase::runOnce() // debounce if (key != prevkey) { if (key != 0) { - LOG_DEBUG("Key 0x%x pressed\n", key); + LOG_DEBUG("Key 0x%x pressed", key); // reset shift now that we have a keypress InputEvent e; e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE; @@ -122,7 +122,7 @@ int32_t KbMatrixBase::runOnce() } } else { - LOG_WARN("Unknown kb_model 0x%02x\n", INPUTBROKER_MATRIX_TYPE); + LOG_WARN("Unknown kb_model 0x%02x", INPUTBROKER_MATRIX_TYPE); return disable(); } return 50; // Keyscan every 50msec to avoid key bounce diff --git a/src/main.cpp b/src/main.cpp index 25059f3c7f..6bf38b5244 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -27,7 +27,6 @@ #include "detect/ScanI2CTwoWire.h" #include #endif -#include "detect/axpDebug.h" #include "detect/einkScan.h" #include "graphics/RAKled.h" #include "graphics/Screen.h" @@ -238,7 +237,7 @@ void lateInitVariant() {} */ void printInfo() { - LOG_INFO("S:B:%d,%s\n", HW_VENDOR, optstr(APP_VERSION)); + LOG_INFO("S:B:%d,%s", HW_VENDOR, optstr(APP_VERSION)); } #ifndef PIO_UNIT_TESTING void setup() @@ -277,7 +276,7 @@ void setup() serialSinceMsec = millis(); - LOG_INFO("\n\n//\\ E S H T /\\ S T / C\n\n"); + LOG_INFO("\n\n//\\ E S H T /\\ S T / C\n"); initDeepSleep(); @@ -298,6 +297,11 @@ void setup() digitalWrite(VEXT_ENABLE, VEXT_ON_VALUE); // turn on the display power #endif +#if defined(BIAS_T_ENABLE) + pinMode(BIAS_T_ENABLE, OUTPUT); + digitalWrite(BIAS_T_ENABLE, BIAS_T_VALUE); // turn on 5V for GPS Antenna +#endif + #if defined(VTFT_CTRL) pinMode(VTFT_CTRL, OUTPUT); digitalWrite(VTFT_CTRL, LOW); @@ -319,7 +323,7 @@ void setup() #ifdef PERIPHERAL_WARMUP_MS // Some peripherals may require additional time to stabilize after power is connected // e.g. I2C on Heltec Vision Master - LOG_INFO("Waiting for peripherals to stabilize\n"); + LOG_INFO("Waiting for peripherals to stabilize"); delay(PERIPHERAL_WARMUP_MS); #endif @@ -380,10 +384,10 @@ void setup() Wire.begin(I2C_SDA, I2C_SCL); #elif defined(ARCH_PORTDUINO) if (settingsStrings[i2cdev] != "") { - LOG_INFO("Using %s as I2C device.\n", settingsStrings[i2cdev].c_str()); + LOG_INFO("Using %s as I2C device.", settingsStrings[i2cdev].c_str()); Wire.begin(settingsStrings[i2cdev].c_str()); } else { - LOG_INFO("No I2C device configured, skipping.\n"); + LOG_INFO("No I2C device configured, skipping."); } #elif HAS_WIRE Wire.begin(); @@ -426,7 +430,7 @@ void setup() // accessories auto i2cScanner = std::unique_ptr(new ScanI2CTwoWire()); #if HAS_WIRE - LOG_INFO("Scanning for i2c devices...\n"); + LOG_INFO("Scanning for i2c devices..."); #endif #if defined(I2C_SDA1) && defined(ARCH_RP2040) @@ -451,7 +455,7 @@ void setup() i2cScanner->scanPort(ScanI2C::I2CPort::WIRE); #elif defined(ARCH_PORTDUINO) if (settingsStrings[i2cdev] != "") { - LOG_INFO("Scanning for i2c devices...\n"); + LOG_INFO("Scanning for i2c devices..."); i2cScanner->scanPort(ScanI2C::I2CPort::WIRE); } #elif HAS_WIRE @@ -460,9 +464,9 @@ void setup() auto i2cCount = i2cScanner->countDevices(); if (i2cCount == 0) { - LOG_INFO("No I2C devices found\n"); + LOG_INFO("No I2C devices found"); } else { - LOG_INFO("%i I2C devices found\n", i2cCount); + LOG_INFO("%i I2C devices found", i2cCount); #ifdef SENSOR_GPS_CONFLICT sensor_detected = true; #endif @@ -518,9 +522,13 @@ void setup() // assign an arbitrary value to distinguish from other models kb_model = 0x11; break; + case ScanI2C::DeviceType::MPR121KB: + // assign an arbitrary value to distinguish from other models + kb_model = 0x37; + break; default: // use this as default since it's also just zero - LOG_WARN("kb_info.type is unknown(0x%02x), setting kb_model=0x00\n", kb_info.type); + LOG_WARN("kb_info.type is unknown(0x%02x), setting kb_model=0x00", kb_info.type); kb_model = 0x00; } } @@ -538,10 +546,25 @@ void setup() rgb_found = i2cScanner->find(ScanI2C::DeviceType::NCP5623); #endif +#ifdef HAS_TPS65233 + // TPS65233 is a power management IC for satellite modems, used in the Dreamcatcher + // We are switching it off here since we don't use an LNB. + if (i2cScanner->exists(ScanI2C::DeviceType::TPS65233)) { + Wire.beginTransmission(TPS65233_ADDR); + Wire.write(0); // Register 0 + Wire.write(128); // Turn off the LNB power, keep I2C Control enabled + Wire.endTransmission(); + Wire.beginTransmission(TPS65233_ADDR); + Wire.write(1); // Register 1 + Wire.write(0); // Turn off Tone Generator 22kHz + Wire.endTransmission(); + } +#endif + #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) auto acc_info = i2cScanner->firstAccelerometer(); accelerometer_found = acc_info.type != ScanI2C::DeviceType::NONE ? acc_info.address : accelerometer_found; - LOG_DEBUG("acc_info = %i\n", acc_info.type); + LOG_DEBUG("acc_info = %i", acc_info.type); #endif #define STRING(S) #S @@ -552,7 +575,7 @@ void setup() if (found.type != ScanI2C::DeviceType::NONE) { \ nodeTelemetrySensorsMap[PB_T].first = found.address.address; \ nodeTelemetrySensorsMap[PB_T].second = i2cScanner->fetchI2CBus(found.address); \ - LOG_DEBUG("found i2c sensor %s\n", STRING(PB_T)); \ + LOG_DEBUG("found i2c sensor %s", STRING(PB_T)); \ } \ } @@ -580,10 +603,12 @@ void setup() SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::TSL2591, meshtastic_TelemetrySensorType_TSL25911FN) SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::OPT3001, meshtastic_TelemetrySensorType_OPT3001) SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::MLX90632, meshtastic_TelemetrySensorType_MLX90632) + SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::MLX90614, meshtastic_TelemetrySensorType_MLX90614) SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::SHT4X, meshtastic_TelemetrySensorType_SHT4X) SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::AHT10, meshtastic_TelemetrySensorType_AHT10) SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::DFROBOT_LARK, meshtastic_TelemetrySensorType_DFROBOT_LARK) SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::ICM20948, meshtastic_TelemetrySensorType_ICM20948) + SCANNER_TO_SENSORS_MAP(ScanI2C::DeviceType::MAX30102, meshtastic_TelemetrySensorType_MAX30102) i2cScanner.reset(); #endif @@ -602,7 +627,7 @@ void setup() // Hello printInfo(); #ifdef BUILD_EPOCH - LOG_INFO("Build timestamp: %ld\n", BUILD_EPOCH); + LOG_INFO("Build timestamp: %ld", BUILD_EPOCH); #endif #ifdef ARCH_ESP32 @@ -617,6 +642,8 @@ void setup() rp2040Setup(); #endif + initSPI(); // needed here before reading from littleFS + // We do this as early as possible because this loads preferences from flash // but we need to do this after main cpu init (esp32setup), because we need the random seed set nodeDB = new NodeDB; @@ -639,7 +666,7 @@ void setup() if (config.power.is_power_saving == true && IS_ONE_OF(config.device.role, meshtastic_Config_DeviceConfig_Role_TRACKER, meshtastic_Config_DeviceConfig_Role_TAK_TRACKER, meshtastic_Config_DeviceConfig_Role_SENSOR)) - LOG_DEBUG("Tracker/Sensor: Skipping start melody\n"); + LOG_DEBUG("Tracker/Sensor: Skipping start melody"); else playStartMelody(); @@ -649,7 +676,7 @@ void setup() #if defined(USE_SH1107) screen_model = meshtastic_Config_DisplayConfig_OledType_OLED_SH1107; // set dimension of 128x128 - display_geometry = GEOMETRY_128_128; + screen_geometry = GEOMETRY_128_128; #endif #if defined(USE_SH1107_128_64) @@ -680,7 +707,6 @@ void setup() #endif // Init our SPI controller (must be before screen and lora) - initSPI(); #ifdef ARCH_RP2040 #ifdef HW_SPI1_DEVICE SPI1.setSCK(LORA_SCK); @@ -700,7 +726,7 @@ void setup() #else // ESP32 SPI.begin(LORA_SCK, LORA_MISO, LORA_MOSI, LORA_CS); - LOG_DEBUG("SPI.begin(SCK=%d, MISO=%d, MOSI=%d, NSS=%d)\n", LORA_SCK, LORA_MISO, LORA_MOSI, LORA_CS); + LOG_DEBUG("SPI.begin(SCK=%d, MISO=%d, MOSI=%d, NSS=%d)", LORA_SCK, LORA_MISO, LORA_MOSI, LORA_CS); SPI.setFrequency(4000000); #endif @@ -709,9 +735,9 @@ void setup() // setup TZ prior to time actions. #if !MESHTASTIC_EXCLUDE_TZ - LOG_DEBUG("Using compiled/slipstreamed %s\n", slipstreamTZString); // important, removing this clobbers our magic string + LOG_DEBUG("Using compiled/slipstreamed %s", slipstreamTZString); // important, removing this clobbers our magic string if (*config.device.tzdef && config.device.tzdef[0] != 0) { - LOG_DEBUG("Saved TZ: %s \n", config.device.tzdef); + LOG_DEBUG("Saved TZ: %s ", config.device.tzdef); setenv("TZ", config.device.tzdef, 1); } else { if (strncmp((const char *)slipstreamTZString, "tzpl", 4) == 0) { @@ -722,7 +748,7 @@ void setup() } } tzset(); - LOG_DEBUG("Set Timezone to %s\n", getenv("TZ")); + LOG_DEBUG("Set Timezone to %s", getenv("TZ")); #endif readFromRTC(); // read the main CPU RTC at first (in case we can't get GPS time) @@ -739,7 +765,7 @@ void setup() if (gps) { gpsStatus->observe(&gps->newStatus); } else { - LOG_DEBUG("Running without GPS.\n"); + LOG_DEBUG("Running without GPS."); } } } @@ -752,7 +778,7 @@ void setup() nodeStatus->observe(&nodeDB->newStatus); #ifdef HAS_I2S - LOG_DEBUG("Starting audio thread\n"); + LOG_DEBUG("Starting audio thread"); audioThread = new AudioThread(); #endif service = new MeshService(); @@ -799,63 +825,63 @@ void setup() #ifdef ARCH_PORTDUINO if (settingsMap[use_sx1262]) { if (!rIf) { - LOG_DEBUG("Attempting to activate sx1262 radio on SPI port %s\n", settingsStrings[spidev].c_str()); + LOG_DEBUG("Attempting to activate sx1262 radio on SPI port %s", settingsStrings[spidev].c_str()); LockingArduinoHal *RadioLibHAL = new LockingArduinoHal(SPI, spiSettings, (settingsMap[ch341Quirk] ? settingsMap[busy] : RADIOLIB_NC)); rIf = new SX1262Interface((LockingArduinoHal *)RadioLibHAL, settingsMap[cs], settingsMap[irq], settingsMap[reset], settingsMap[busy]); if (!rIf->init()) { - LOG_ERROR("Failed to find SX1262 radio\n"); + LOG_ERROR("Failed to find SX1262 radio"); delete rIf; exit(EXIT_FAILURE); } else { - LOG_INFO("SX1262 Radio init succeeded, using SX1262 radio\n"); + LOG_INFO("SX1262 Radio init succeeded, using SX1262 radio"); } } } else if (settingsMap[use_rf95]) { if (!rIf) { - LOG_DEBUG("Attempting to activate rf95 radio on SPI port %s\n", settingsStrings[spidev].c_str()); + LOG_DEBUG("Attempting to activate rf95 radio on SPI port %s", settingsStrings[spidev].c_str()); LockingArduinoHal *RadioLibHAL = new LockingArduinoHal(SPI, spiSettings, (settingsMap[ch341Quirk] ? settingsMap[busy] : RADIOLIB_NC)); rIf = new RF95Interface((LockingArduinoHal *)RadioLibHAL, settingsMap[cs], settingsMap[irq], settingsMap[reset], settingsMap[busy]); if (!rIf->init()) { - LOG_ERROR("Failed to find RF95 radio\n"); + LOG_ERROR("Failed to find RF95 radio"); delete rIf; rIf = NULL; exit(EXIT_FAILURE); } else { - LOG_INFO("RF95 Radio init succeeded, using RF95 radio\n"); + LOG_INFO("RF95 Radio init succeeded, using RF95 radio"); } } } else if (settingsMap[use_sx1280]) { if (!rIf) { - LOG_DEBUG("Attempting to activate sx1280 radio on SPI port %s\n", settingsStrings[spidev].c_str()); + LOG_DEBUG("Attempting to activate sx1280 radio on SPI port %s", settingsStrings[spidev].c_str()); LockingArduinoHal *RadioLibHAL = new LockingArduinoHal(SPI, spiSettings); rIf = new SX1280Interface((LockingArduinoHal *)RadioLibHAL, settingsMap[cs], settingsMap[irq], settingsMap[reset], settingsMap[busy]); if (!rIf->init()) { - LOG_ERROR("Failed to find SX1280 radio\n"); + LOG_ERROR("Failed to find SX1280 radio"); delete rIf; rIf = NULL; exit(EXIT_FAILURE); } else { - LOG_INFO("SX1280 Radio init succeeded, using SX1280 radio\n"); + LOG_INFO("SX1280 Radio init succeeded, using SX1280 radio"); } } } else if (settingsMap[use_sx1268]) { if (!rIf) { - LOG_DEBUG("Attempting to activate sx1268 radio on SPI port %s\n", settingsStrings[spidev].c_str()); + LOG_DEBUG("Attempting to activate sx1268 radio on SPI port %s", settingsStrings[spidev].c_str()); LockingArduinoHal *RadioLibHAL = new LockingArduinoHal(SPI, spiSettings); rIf = new SX1268Interface((LockingArduinoHal *)RadioLibHAL, settingsMap[cs], settingsMap[irq], settingsMap[reset], settingsMap[busy]); if (!rIf->init()) { - LOG_ERROR("Failed to find SX1268 radio\n"); + LOG_ERROR("Failed to find SX1268 radio"); delete rIf; rIf = NULL; exit(EXIT_FAILURE); } else { - LOG_INFO("SX1268 Radio init succeeded, using SX1268 radio\n"); + LOG_INFO("SX1268 Radio init succeeded, using SX1268 radio"); } } } @@ -871,11 +897,11 @@ void setup() if (!rIf) { rIf = new STM32WLE5JCInterface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY); if (!rIf->init()) { - LOG_WARN("Failed to find STM32WL radio\n"); + LOG_WARN("Failed to find STM32WL radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("STM32WL Radio init succeeded, using STM32WL radio\n"); + LOG_INFO("STM32WL Radio init succeeded, using STM32WL radio"); radioType = STM32WLx_RADIO; } } @@ -885,11 +911,11 @@ void setup() if (!rIf) { rIf = new SimRadio; if (!rIf->init()) { - LOG_WARN("Failed to find simulated radio\n"); + LOG_WARN("Failed to find simulated radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("Using SIMULATED radio!\n"); + LOG_INFO("Using SIMULATED radio!"); radioType = SIM_RADIO; } } @@ -899,11 +925,11 @@ void setup() if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { rIf = new RF95Interface(RadioLibHAL, LORA_CS, RF95_IRQ, RF95_RESET, RF95_DIO1); if (!rIf->init()) { - LOG_WARN("Failed to find RF95 radio\n"); + LOG_WARN("Failed to find RF95 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("RF95 Radio init succeeded, using RF95 radio\n"); + LOG_INFO("RF95 Radio init succeeded, using RF95 radio"); radioType = RF95_RADIO; } } @@ -913,11 +939,11 @@ void setup() if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { rIf = new SX1262Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY); if (!rIf->init()) { - LOG_WARN("Failed to find SX1262 radio\n"); + LOG_WARN("Failed to find SX1262 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("SX1262 Radio init succeeded, using SX1262 radio\n"); + LOG_INFO("SX1262 Radio init succeeded, using SX1262 radio"); radioType = SX1262_RADIO; } } @@ -928,14 +954,12 @@ void setup() // Try using the specified TCXO voltage rIf = new SX1262Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY); if (!rIf->init()) { - LOG_WARN("Failed to find SX1262 radio with TCXO using DIO3 reference voltage at %f V\n", tcxoVoltage); + LOG_WARN("Failed to find SX1262 radio with TCXO, Vref %f V", tcxoVoltage); delete rIf; rIf = NULL; tcxoVoltage = 0; // if it fails, set the TCXO voltage to zero for the next attempt } else { - LOG_INFO("SX1262 Radio init succeeded, using "); - LOG_WARN("SX1262 Radio with TCXO"); - LOG_INFO(", reference voltage at %f V\n", tcxoVoltage); + LOG_WARN("SX1262 Radio init succeeded, TCXO, Vref %f V", tcxoVoltage); radioType = SX1262_RADIO; } } @@ -944,14 +968,12 @@ void setup() // If specified TCXO voltage fails, attempt to use DIO3 as a reference instea rIf = new SX1262Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY); if (!rIf->init()) { - LOG_WARN("Failed to find SX1262 radio with XTAL using DIO3 reference voltage at %f V\n", tcxoVoltage); + LOG_WARN("Failed to find SX1262 radio with XTAL, Vref %f V", tcxoVoltage); delete rIf; rIf = NULL; tcxoVoltage = SX126X_DIO3_TCXO_VOLTAGE; // if it fails, set the TCXO voltage back for the next radio search } else { - LOG_INFO("SX1262 Radio init succeeded, using "); - LOG_WARN("SX1262 Radio with XTAL"); - LOG_INFO(", reference voltage at %f V\n", tcxoVoltage); + LOG_INFO("SX1262 Radio init succeeded, XTAL, Vref %f V", tcxoVoltage); radioType = SX1262_RADIO; } } @@ -961,11 +983,11 @@ void setup() if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { rIf = new SX1268Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY); if (!rIf->init()) { - LOG_WARN("Failed to find SX1268 radio\n"); + LOG_WARN("Failed to find SX1268 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("SX1268 Radio init succeeded, using SX1268 radio\n"); + LOG_INFO("SX1268 Radio init succeeded, using SX1268 radio"); radioType = SX1268_RADIO; } } @@ -975,11 +997,11 @@ void setup() if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { rIf = new LLCC68Interface(RadioLibHAL, SX126X_CS, SX126X_DIO1, SX126X_RESET, SX126X_BUSY); if (!rIf->init()) { - LOG_WARN("Failed to find LLCC68 radio\n"); + LOG_WARN("Failed to find LLCC68 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("LLCC68 Radio init succeeded, using LLCC68 radio\n"); + LOG_INFO("LLCC68 Radio init succeeded, using LLCC68 radio"); radioType = LLCC68_RADIO; } } @@ -989,11 +1011,11 @@ void setup() if ((!rIf) && (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { rIf = new LR1110Interface(RadioLibHAL, LR1110_SPI_NSS_PIN, LR1110_IRQ_PIN, LR1110_NRESET_PIN, LR1110_BUSY_PIN); if (!rIf->init()) { - LOG_WARN("Failed to find LR1110 radio\n"); + LOG_WARN("Failed to find LR1110 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("LR1110 Radio init succeeded, using LR1110 radio\n"); + LOG_INFO("LR1110 Radio init succeeded, using LR1110 radio"); radioType = LR1110_RADIO; } } @@ -1003,11 +1025,11 @@ void setup() if (!rIf) { rIf = new LR1120Interface(RadioLibHAL, LR1120_SPI_NSS_PIN, LR1120_IRQ_PIN, LR1120_NRESET_PIN, LR1120_BUSY_PIN); if (!rIf->init()) { - LOG_WARN("Failed to find LR1120 radio\n"); + LOG_WARN("Failed to find LR1120 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("LR1120 Radio init succeeded, using LR1120 radio\n"); + LOG_INFO("LR1120 Radio init succeeded, using LR1120 radio"); radioType = LR1120_RADIO; } } @@ -1017,11 +1039,11 @@ void setup() if (!rIf) { rIf = new LR1121Interface(RadioLibHAL, LR1121_SPI_NSS_PIN, LR1121_IRQ_PIN, LR1121_NRESET_PIN, LR1121_BUSY_PIN); if (!rIf->init()) { - LOG_WARN("Failed to find LR1121 radio\n"); + LOG_WARN("Failed to find LR1121 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("LR1121 Radio init succeeded, using LR1121 radio\n"); + LOG_INFO("LR1121 Radio init succeeded, using LR1121 radio"); radioType = LR1121_RADIO; } } @@ -1031,11 +1053,11 @@ void setup() if (!rIf) { rIf = new SX1280Interface(RadioLibHAL, SX128X_CS, SX128X_DIO1, SX128X_RESET, SX128X_BUSY); if (!rIf->init()) { - LOG_WARN("Failed to find SX1280 radio\n"); + LOG_WARN("Failed to find SX1280 radio"); delete rIf; rIf = NULL; } else { - LOG_INFO("SX1280 Radio init succeeded, using SX1280 radio\n"); + LOG_INFO("SX1280 Radio init succeeded, using SX1280 radio"); radioType = SX1280_RADIO; } } @@ -1043,11 +1065,11 @@ void setup() // check if the radio chip matches the selected region 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"); + LOG_WARN("Radio chip does not support 2.4GHz LoRa. Reverting to unset."); config.lora.region = meshtastic_Config_LoRaConfig_RegionCode_UNSET; nodeDB->saveToDisk(SEGMENT_CONFIG); if (!rIf->reconfigure()) { - LOG_WARN("Reconfigure failed, rebooting\n"); + LOG_WARN("Reconfigure failed, rebooting"); screen->startAlert("Rebooting..."); rebootAtMsec = millis() + 5000; } @@ -1102,9 +1124,9 @@ void setup() router->addInterface(rIf); // Log bit rate to debug output - LOG_DEBUG("LoRA bitrate = %f bytes / sec\n", (float(meshtastic_Constants_DATA_PAYLOAD_LEN) / - (float(rIf->getPacketTime(meshtastic_Constants_DATA_PAYLOAD_LEN)))) * - 1000); + LOG_DEBUG("LoRA bitrate = %f bytes / sec", (float(meshtastic_Constants_DATA_PAYLOAD_LEN) / + (float(rIf->getPacketTime(meshtastic_Constants_DATA_PAYLOAD_LEN)))) * + 1000); } // This must be _after_ service.init because we need our preferences loaded from flash to have proper timeout values @@ -1168,4 +1190,4 @@ void loop() mainDelay.delay(delayMsec); } } -#endif +#endif \ No newline at end of file diff --git a/src/mesh/Channels.cpp b/src/mesh/Channels.cpp index bb30e501d4..b9fe956789 100644 --- a/src/mesh/Channels.cpp +++ b/src/mesh/Channels.cpp @@ -117,13 +117,18 @@ void Channels::initDefaultChannel(ChannelIndex chIndex) static const uint8_t defaultpsk0[] = USERPREFS_CHANNEL_0_PSK; memcpy(channelSettings.psk.bytes, defaultpsk0, sizeof(defaultpsk0)); channelSettings.psk.size = sizeof(defaultpsk0); - #endif #ifdef USERPREFS_CHANNEL_0_NAME strcpy(channelSettings.name, USERPREFS_CHANNEL_0_NAME); #endif #ifdef USERPREFS_CHANNEL_0_PRECISION channelSettings.module_settings.position_precision = USERPREFS_CHANNEL_0_PRECISION; +#endif +#ifdef USERPREFS_CHANNEL_0_UPLINK_ENABLED + channelSettings.uplink_enabled = USERPREFS_CHANNEL_0_UPLINK_ENABLED; +#endif +#ifdef USERPREFS_CHANNEL_0_DOWNLINK_ENABLED + channelSettings.downlink_enabled = USERPREFS_CHANNEL_0_DOWNLINK_ENABLED; #endif break; case 1: @@ -131,13 +136,18 @@ void Channels::initDefaultChannel(ChannelIndex chIndex) static const uint8_t defaultpsk1[] = USERPREFS_CHANNEL_1_PSK; memcpy(channelSettings.psk.bytes, defaultpsk1, sizeof(defaultpsk1)); channelSettings.psk.size = sizeof(defaultpsk1); - #endif #ifdef USERPREFS_CHANNEL_1_NAME strcpy(channelSettings.name, USERPREFS_CHANNEL_1_NAME); #endif #ifdef USERPREFS_CHANNEL_1_PRECISION channelSettings.module_settings.position_precision = USERPREFS_CHANNEL_1_PRECISION; +#endif +#ifdef USERPREFS_CHANNEL_1_UPLINK_ENABLED + channelSettings.uplink_enabled = USERPREFS_CHANNEL_1_UPLINK_ENABLED; +#endif +#ifdef USERPREFS_CHANNEL_1_DOWNLINK_ENABLED + channelSettings.downlink_enabled = USERPREFS_CHANNEL_1_DOWNLINK_ENABLED; #endif break; case 2: @@ -145,13 +155,18 @@ void Channels::initDefaultChannel(ChannelIndex chIndex) static const uint8_t defaultpsk2[] = USERPREFS_CHANNEL_2_PSK; memcpy(channelSettings.psk.bytes, defaultpsk2, sizeof(defaultpsk2)); channelSettings.psk.size = sizeof(defaultpsk2); - #endif #ifdef USERPREFS_CHANNEL_2_NAME strcpy(channelSettings.name, USERPREFS_CHANNEL_2_NAME); #endif #ifdef USERPREFS_CHANNEL_2_PRECISION channelSettings.module_settings.position_precision = USERPREFS_CHANNEL_2_PRECISION; +#endif +#ifdef USERPREFS_CHANNEL_2_UPLINK_ENABLED + channelSettings.uplink_enabled = USERPREFS_CHANNEL_2_UPLINK_ENABLED; +#endif +#ifdef USERPREFS_CHANNEL_2_DOWNLINK_ENABLED + channelSettings.downlink_enabled = USERPREFS_CHANNEL_2_DOWNLINK_ENABLED; #endif break; default: @@ -175,34 +190,19 @@ CryptoKey Channels::getKey(ChannelIndex chIndex) k.length = channelSettings.psk.size; if (k.length == 0) { if (ch.role == meshtastic_Channel_Role_SECONDARY) { - LOG_DEBUG("Unset PSK for secondary channel %s. using primary key\n", ch.settings.name); + LOG_DEBUG("Unset PSK for secondary channel %s. using primary key", ch.settings.name); k = getKey(primaryIndex); } else { - LOG_WARN("User disabled encryption\n"); + LOG_WARN("User disabled encryption"); } } else if (k.length == 1) { // Convert the short single byte variants of psk into variant that can be used more generally uint8_t pskIndex = k.bytes[0]; - LOG_DEBUG("Expanding short PSK #%d\n", pskIndex); + LOG_DEBUG("Expanding short PSK #%d", pskIndex); if (pskIndex == 0) k.length = 0; // Turn off encryption - 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); - 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; - *last = *last + pskIndex - 1; // index of 1 means no change vs defaultPSK - if (k.length < 16) { - LOG_WARN("OEM provided a too short AES128 key - padding\n"); - k.length = 16; - } else if (k.length < 32 && k.length != 16) { - LOG_WARN("OEM provided a too short AES256 key - padding\n"); - k.length = 32; - } - } else { + else { memcpy(k.bytes, defaultpsk, sizeof(defaultpsk)); k.length = sizeof(defaultpsk); // Bump up the last byte of PSK as needed @@ -212,12 +212,12 @@ CryptoKey Channels::getKey(ChannelIndex chIndex) } else if (k.length < 16) { // Error! The user specified only the first few bits of an AES128 key. So by convention we just pad the rest of the // key with zeros - LOG_WARN("User provided a too short AES128 key - padding\n"); + LOG_WARN("User provided a too short AES128 key - padding"); k.length = 16; } else if (k.length < 32 && k.length != 16) { // Error! The user specified only the first few bits of an AES256 key. So by convention we just pad the rest of the // key with zeros - LOG_WARN("User provided a too short AES256 key - padding\n"); + LOG_WARN("User provided a too short AES256 key - padding"); k.length = 32; } } @@ -267,7 +267,7 @@ void Channels::onConfigChanged() } #if !MESHTASTIC_EXCLUDE_MQTT if (channels.anyMqttEnabled() && mqtt && !mqtt->isEnabled()) { - LOG_DEBUG("MQTT is enabled on at least one channel, so set MQTT thread to run immediately\n"); + LOG_DEBUG("MQTT is enabled on at least one channel, so set MQTT thread to run immediately"); mqtt->start(); } #endif @@ -280,7 +280,7 @@ meshtastic_Channel &Channels::getByIndex(ChannelIndex 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?", chIndex, channelFile.channels_count); static meshtastic_Channel *ch = (meshtastic_Channel *)malloc(sizeof(meshtastic_Channel)); memset(ch, 0, sizeof(meshtastic_Channel)); @@ -384,11 +384,11 @@ bool Channels::hasDefaultChannel() bool Channels::decryptForHash(ChannelIndex chIndex, ChannelHash channelHash) { if (chIndex > getNumChannels() || getHash(chIndex) != channelHash) { - // LOG_DEBUG("Skipping channel %d (hash %x) due to invalid hash/index, want=%x\n", chIndex, getHash(chIndex), + // LOG_DEBUG("Skipping channel %d (hash %x) due to invalid hash/index, want=%x", chIndex, getHash(chIndex), // channelHash); return false; } else { - LOG_DEBUG("Using channel %d (hash 0x%x)\n", chIndex, channelHash); + LOG_DEBUG("Using channel %d (hash 0x%x)", chIndex, channelHash); setCrypto(chIndex); return true; } diff --git a/src/mesh/CryptoEngine.cpp b/src/mesh/CryptoEngine.cpp index a875eb8b28..282013ea01 100644 --- a/src/mesh/CryptoEngine.cpp +++ b/src/mesh/CryptoEngine.cpp @@ -1,8 +1,6 @@ #include "CryptoEngine.h" -#include "NodeDB.h" -#include "RadioInterface.h" +// #include "NodeDB.h" #include "architecture.h" -#include "configuration.h" #if !(MESHTASTIC_EXCLUDE_PKI) #include "aes-ccm.h" @@ -20,7 +18,7 @@ */ void CryptoEngine::generateKeyPair(uint8_t *pubKey, uint8_t *privKey) { - LOG_DEBUG("Generating Curve25519 key pair...\n"); + LOG_DEBUG("Generating Curve25519 key pair..."); Curve25519::dh1(public_key, private_key); memcpy(pubKey, public_key, sizeof(public_key)); memcpy(privKey, private_key, sizeof(private_key)); @@ -37,14 +35,14 @@ bool CryptoEngine::regeneratePublicKey(uint8_t *pubKey, uint8_t *privKey) if (!memfll(privKey, 0, sizeof(private_key))) { Curve25519::eval(pubKey, privKey, 0); if (Curve25519::isWeakPoint(pubKey)) { - LOG_ERROR("PKI key generation failed. Specified private key results in a weak\n"); + LOG_ERROR("PKI key generation failed. Specified private key results in a weak"); memset(pubKey, 0, 32); return false; } memcpy(private_key, privKey, sizeof(private_key)); memcpy(public_key, pubKey, sizeof(public_key)); } else { - LOG_WARN("X25519 key generation failed due to blank private key\n"); + LOG_WARN("X25519 key generation failed due to blank private key"); return false; } return true; @@ -62,23 +60,23 @@ void CryptoEngine::clearKeys() * * @param bytes is updated in place */ -bool CryptoEngine::encryptCurve25519(uint32_t toNode, uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes, - uint8_t *bytesOut) +bool CryptoEngine::encryptCurve25519(uint32_t toNode, uint32_t fromNode, meshtastic_UserLite_public_key_t remotePublic, + uint64_t packetNum, size_t numBytes, uint8_t *bytes, uint8_t *bytesOut) { uint8_t *auth; long extraNonceTmp = random(); auth = bytesOut + numBytes; memcpy((uint8_t *)(auth + 8), &extraNonceTmp, sizeof(uint32_t)); // do not use dereference on potential non aligned pointers : *extraNonce = extraNonceTmp; - LOG_INFO("Random nonce value: %d\n", extraNonceTmp); - meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(toNode); - if (node->num < 1 || node->user.public_key.size == 0) { - LOG_DEBUG("Node %d or their public_key not found\n", toNode); + LOG_INFO("Random nonce value: %d", extraNonceTmp); + if (remotePublic.size == 0) { + LOG_DEBUG("Node %d or their public_key not found", toNode); return false; } - if (!crypto->setDHKey(toNode)) { + if (!crypto->setDHPublicKey(remotePublic.bytes)) { return false; } + crypto->hash(shared_key, 32); initNonce(fromNode, packetNum, extraNonceTmp); // Calculate the shared secret with the destination node and encrypt @@ -97,27 +95,27 @@ bool CryptoEngine::encryptCurve25519(uint32_t toNode, uint32_t fromNode, uint64_ * * @param bytes is updated in place */ -bool CryptoEngine::decryptCurve25519(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes, uint8_t *bytesOut) +bool CryptoEngine::decryptCurve25519(uint32_t fromNode, meshtastic_UserLite_public_key_t remotePublic, uint64_t packetNum, + size_t numBytes, uint8_t *bytes, uint8_t *bytesOut) { uint8_t *auth; // set to last 8 bytes of text? uint32_t extraNonce; // pointer was not really used auth = bytes + numBytes - 12; memcpy(&extraNonce, auth + 8, sizeof(uint32_t)); // do not use dereference on potential non aligned pointers : (uint32_t *)(auth + 8); -#ifndef PIO_UNIT_TESTING - LOG_INFO("Random nonce value: %d\n", extraNonce); - meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(fromNode); + LOG_INFO("Random nonce value: %d", extraNonce); - if (node == nullptr || node->num < 1 || node->user.public_key.size == 0) { - LOG_DEBUG("Node or its public key not found in database\n"); + if (remotePublic.size == 0) { + LOG_DEBUG("Node or its public key not found in database"); return false; } // Calculate the shared secret with the sending node and decrypt - if (!crypto->setDHKey(fromNode)) { + if (!crypto->setDHPublicKey(remotePublic.bytes)) { return false; } -#endif + crypto->hash(shared_key, 32); + initNonce(fromNode, packetNum, extraNonce); printBytes("Attempting decrypt using nonce: ", nonce, 13); printBytes("Attempting decrypt using shared_key starting with: ", shared_key, 8); @@ -128,38 +126,6 @@ void CryptoEngine::setDHPrivateKey(uint8_t *_private_key) { memcpy(private_key, _private_key, 32); } -/** - * Set the PKI key used for encrypt, decrypt. - * - * @param nodeNum the node number of the node who's public key we want to use - */ -bool CryptoEngine::setDHKey(uint32_t nodeNum) -{ - meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeNum); - if (node->num < 1 || node->user.public_key.size == 0) { - LOG_DEBUG("Node %d or their public_key not found\n", nodeNum); - return false; - } - printBytes("Generating DH with remote pubkey: ", node->user.public_key.bytes, 32); - printBytes("And local pubkey: ", config.security.public_key.bytes, 32); - if (!setDHPublicKey(node->user.public_key.bytes)) - return false; - - // printBytes("DH Output: ", shared_key, 32); - - /** - * D.J. Bernstein reccomends hashing the shared key. We want to do this because there are - * at least 128 bits of entropy in the 256-bit output of the DH key exchange, but we don't - * really know where. If you extract, for instance, the first 128 bits with basic truncation, - * then you don't know if you got all of your 128 entropy bits, or less, possibly much less. - * - * No exploitable bias is really known at that point, but we know enough to be wary. - * Hashing the DH output is a simple and safe way to gather all the entropy and spread - * it around as needed. - */ - crypto->hash(shared_key, 32); - return true; -} /** * Hash arbitrary data using SHA256. @@ -208,7 +174,7 @@ bool CryptoEngine::setDHPublicKey(uint8_t *pubKey) // Calculate the shared secret with the specified node's public key and our private key // This includes an internal weak key check, which among other things looks for an all 0 public key and shared key. if (!Curve25519::dh2(shared_key, local_priv)) { - LOG_WARN("Curve25519DH step 2 failed!\n"); + LOG_WARN("Curve25519DH step 2 failed!"); return false; } return true; @@ -219,7 +185,7 @@ concurrency::Lock *cryptLock; void CryptoEngine::setKey(const CryptoKey &k) { - LOG_DEBUG("Using AES%d key!\n", k.length * 8); + LOG_DEBUG("Using AES%d key!", k.length * 8); key = k; } @@ -235,7 +201,7 @@ void CryptoEngine::encryptPacket(uint32_t fromNode, uint64_t packetId, size_t nu if (numBytes <= MAX_BLOCKSIZE) { encryptAESCtr(key, nonce, numBytes, bytes); } else { - LOG_ERROR("Packet too large for crypto engine: %d. noop encryption!\n", numBytes); + LOG_ERROR("Packet too large for crypto engine: %d. noop encryption!", numBytes); } } } diff --git a/src/mesh/CryptoEngine.h b/src/mesh/CryptoEngine.h index 4c2fc19d93..32862d95c4 100644 --- a/src/mesh/CryptoEngine.h +++ b/src/mesh/CryptoEngine.h @@ -39,10 +39,10 @@ class CryptoEngine #endif void clearKeys(); void setDHPrivateKey(uint8_t *_private_key); - virtual bool encryptCurve25519(uint32_t toNode, uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes, - uint8_t *bytesOut); - virtual bool decryptCurve25519(uint32_t fromNode, uint64_t packetNum, size_t numBytes, uint8_t *bytes, uint8_t *bytesOut); - bool setDHKey(uint32_t nodeNum); + virtual bool encryptCurve25519(uint32_t toNode, uint32_t fromNode, meshtastic_UserLite_public_key_t remotePublic, + uint64_t packetNum, size_t numBytes, uint8_t *bytes, uint8_t *bytesOut); + virtual bool decryptCurve25519(uint32_t fromNode, meshtastic_UserLite_public_key_t remotePublic, uint64_t packetNum, + size_t numBytes, uint8_t *bytes, uint8_t *bytesOut); virtual bool setDHPublicKey(uint8_t *publicKey); virtual void hash(uint8_t *bytes, size_t numBytes); diff --git a/src/mesh/Default.cpp b/src/mesh/Default.cpp index 0bedcfc918..653528b607 100644 --- a/src/mesh/Default.cpp +++ b/src/mesh/Default.cpp @@ -43,6 +43,15 @@ uint32_t Default::getConfiguredOrDefaultMsScaled(uint32_t configured, uint32_t d return getConfiguredOrDefaultMs(configured, defaultValue) * congestionScalingCoefficient(numOnlineNodes); } +uint32_t Default::getConfiguredOrMinimumValue(uint32_t configured, uint32_t minValue) +{ + // If zero, intervals should be coalesced later by getConfiguredOrDefault... methods + if (configured == 0) + return configured; + + return configured < minValue ? minValue : configured; +} + uint8_t Default::getConfiguredOrDefaultHopLimit(uint8_t configured) { #if USERPREFS_EVENT_MODE diff --git a/src/mesh/Default.h b/src/mesh/Default.h index 5641b5d25f..2406dafc52 100644 --- a/src/mesh/Default.h +++ b/src/mesh/Default.h @@ -6,8 +6,9 @@ #define THIRTY_SECONDS_MS 30 * 1000 #define FIVE_SECONDS_MS 5 * 1000 +#define min_default_telemetry_interval_secs 30 * 60 #define default_gps_update_interval IF_ROUTER(ONE_DAY, 2 * 60) -#define default_telemetry_broadcast_interval_secs IF_ROUTER(ONE_DAY / 2, 30 * 60) +#define default_telemetry_broadcast_interval_secs IF_ROUTER(ONE_DAY / 2, 60 * 60) #define default_broadcast_interval_secs IF_ROUTER(ONE_DAY / 2, 15 * 60) #define default_wait_bluetooth_secs IF_ROUTER(1, 60) #define default_sds_secs IF_ROUTER(ONE_DAY, UINT32_MAX) // Default to forever super deep sleep @@ -35,6 +36,7 @@ class Default static uint32_t getConfiguredOrDefault(uint32_t configured, uint32_t defaultValue); static uint32_t getConfiguredOrDefaultMsScaled(uint32_t configured, uint32_t defaultValue, uint32_t numOnlineNodes); static uint8_t getConfiguredOrDefaultHopLimit(uint8_t configured); + static uint32_t getConfiguredOrMinimumValue(uint32_t configured, uint32_t minValue); private: static float congestionScalingCoefficient(int numOnlineNodes) diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index 23f6b6f92d..6760d70ebf 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -35,17 +35,23 @@ bool FloodingRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) return Router::shouldFilterReceived(p); } +bool FloodingRouter::isRebroadcaster() +{ + return config.device.role != meshtastic_Config_DeviceConfig_Role_CLIENT_MUTE && + config.device.rebroadcast_mode != meshtastic_Config_DeviceConfig_RebroadcastMode_NONE; +} + void FloodingRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) { bool isAckorReply = (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) && (p->decoded.request_id != 0); - if (isAckorReply && !isToUs(p) && p->to != NODENUM_BROADCAST) { + if (isAckorReply && !isToUs(p) && !isBroadcast(p->to)) { // do not flood direct message that is ACKed or replied to - LOG_DEBUG("Rxd an ACK/reply not for me, cancel rebroadcast.\n"); + LOG_DEBUG("Rxd an ACK/reply not for me, cancel rebroadcast."); Router::cancelSending(p->to, p->decoded.request_id); // cancel rebroadcast for this DM } if (!isToUs(p) && (p->hop_limit > 0) && !isFromUs(p)) { if (p->id != 0) { - if (config.device.role != meshtastic_Config_DeviceConfig_Role_CLIENT_MUTE) { + if (isRebroadcaster()) { meshtastic_MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it tosend->hop_limit--; // bump down the hop count @@ -57,15 +63,15 @@ void FloodingRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtas } #endif - LOG_INFO("Rebroadcasting received floodmsg\n"); + LOG_INFO("Rebroadcasting received floodmsg"); // 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"); + LOG_DEBUG("Not rebroadcasting: Role = CLIENT_MUTE or Rebroadcast Mode = NONE"); } } else { - LOG_DEBUG("Ignoring 0 id broadcast\n"); + LOG_DEBUG("Ignoring 0 id broadcast"); } } // handle the packet as normal diff --git a/src/mesh/FloodingRouter.h b/src/mesh/FloodingRouter.h index a3adfe70c9..0ed2b55823 100644 --- a/src/mesh/FloodingRouter.h +++ b/src/mesh/FloodingRouter.h @@ -29,6 +29,8 @@ class FloodingRouter : public Router, protected PacketHistory { private: + bool isRebroadcaster(); + public: /** * Constructor diff --git a/src/mesh/LR11x0Interface.cpp b/src/mesh/LR11x0Interface.cpp index 6641634c4c..d0c1a1fbcd 100644 --- a/src/mesh/LR11x0Interface.cpp +++ b/src/mesh/LR11x0Interface.cpp @@ -35,7 +35,7 @@ LR11x0Interface::LR11x0Interface(LockingArduinoHal *hal, RADIOLIB_PIN_TYPE cs RADIOLIB_PIN_TYPE busy) : RadioLibInterface(hal, cs, irq, rst, busy, &lora), lora(&module) { - LOG_WARN("LR11x0Interface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); + LOG_WARN("LR11x0Interface(cs=%d, irq=%d, rst=%d, busy=%d)", cs, irq, rst, busy); } /// Initialise the Driver transport hardware and software. @@ -54,10 +54,10 @@ template bool LR11x0Interface::init() 0; // "TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip." per // https://github.com/jgromes/RadioLib/blob/690a050ebb46e6097c5d00c371e961c1caa3b52e/src/modules/LR11x0/LR11x0.h#L471C26-L471C104 // (DIO3 is free to be used as an IRQ) - LOG_DEBUG("LR11X0_DIO3_TCXO_VOLTAGE not defined, not using DIO3 as TCXO reference voltage\n"); + LOG_DEBUG("LR11X0_DIO3_TCXO_VOLTAGE not defined, not using DIO3 as TCXO reference voltage"); #else float tcxoVoltage = LR11X0_DIO3_TCXO_VOLTAGE; - LOG_DEBUG("LR11X0_DIO3_TCXO_VOLTAGE defined, using DIO3 as TCXO reference voltage at %f V\n", LR11X0_DIO3_TCXO_VOLTAGE); + LOG_DEBUG("LR11X0_DIO3_TCXO_VOLTAGE defined, using DIO3 as TCXO reference voltage at %f V", LR11X0_DIO3_TCXO_VOLTAGE); // (DIO3 is not free to be used as an IRQ) #endif @@ -67,27 +67,40 @@ template bool LR11x0Interface::init() power = LR1110_MAX_POWER; if ((power > LR1120_MAX_POWER) && - (config.lora.region == meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) // clamp again if wide freq range + (config.lora.region == meshtastic_Config_LoRaConfig_RegionCode_LORA_24)) { // clamp again if wide freq range power = LR1120_MAX_POWER; + preambleLength = 12; // 12 is the default for operation above 2GHz + } limitPower(); +#ifdef LR11X0_RF_SWITCH_SUBGHZ + pinMode(LR11X0_RF_SWITCH_SUBGHZ, OUTPUT); + digitalWrite(LR11X0_RF_SWITCH_SUBGHZ, getFreq() < 1e9 ? HIGH : LOW); + LOG_DEBUG("Setting RF0 switch to %s", getFreq() < 1e9 ? "SubGHz" : "2.4GHz"); +#endif + +#ifdef LR11X0_RF_SWITCH_2_4GHZ + pinMode(LR11X0_RF_SWITCH_2_4GHZ, OUTPUT); + digitalWrite(LR11X0_RF_SWITCH_2_4GHZ, getFreq() < 1e9 ? LOW : HIGH); + LOG_DEBUG("Setting RF1 switch to %s", getFreq() < 1e9 ? "SubGHz" : "2.4GHz"); +#endif + int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength, tcxoVoltage); // \todo Display actual typename of the adapter, not just `LR11x0` - LOG_INFO("LR11x0 init result %d\n", res); + LOG_INFO("LR11x0 init result %d", res); if (res == RADIOLIB_ERR_CHIP_NOT_FOUND) return false; LR11x0VersionInfo_t version; res = lora.getVersionInfo(&version); if (res == RADIOLIB_ERR_NONE) - LOG_DEBUG("LR11x0 Device %d, HW %d, FW %d.%d, WiFi %d.%d, GNSS %d.%d\n", version.device, version.hardware, - version.fwMajor, version.fwMinor, version.fwMajorWiFi, version.fwMinorWiFi, version.fwGNSS, - version.almanacGNSS); + LOG_DEBUG("LR11x0 Device %d, HW %d, FW %d.%d, WiFi %d.%d, GNSS %d.%d", version.device, version.hardware, version.fwMajor, + version.fwMinor, version.fwMajorWiFi, version.fwMinorWiFi, version.fwGNSS, version.almanacGNSS); - 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", getFreq()); + LOG_INFO("Bandwidth set to %f", bw); + LOG_INFO("Power output set to %d", power); if (res == RADIOLIB_ERR_NONE) res = lora.setCRC(2); @@ -109,16 +122,16 @@ template bool LR11x0Interface::init() if (dioAsRfSwitch) { lora.setRfSwitchTable(rfswitch_dio_pins, rfswitch_table); - LOG_DEBUG("Setting DIO RF switch\n", res); + LOG_DEBUG("Setting DIO RF switch", res); } if (res == RADIOLIB_ERR_NONE) { if (config.lora.sx126x_rx_boosted_gain) { // the name is unfortunate but historically accurate res = lora.setRxBoostedGainMode(true); - LOG_INFO("Set RX gain to boosted mode; result: %d\n", res); + LOG_INFO("Set RX gain to boosted mode; result: %d", res); } else { res = lora.setRxBoostedGainMode(false); - LOG_INFO("Set RX gain to power saving mode (boosted mode off); result: %d\n", res); + LOG_INFO("Set RX gain to power saving mode (boosted mode off); result: %d", res); } } @@ -188,7 +201,7 @@ template void LR11x0Interface::setStandby() int err = lora.standby(); if (err != RADIOLIB_ERR_NONE) { - LOG_DEBUG("LR11x0 standby failed with error %d\n", err); + LOG_DEBUG("LR11x0 standby failed with error %d", err); } assert(err == RADIOLIB_ERR_NONE); @@ -205,7 +218,7 @@ template void LR11x0Interface::setStandby() */ template void LR11x0Interface::addReceiveMetadata(meshtastic_MeshPacket *mp) { - // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); + // LOG_DEBUG("PacketStatus %x", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); mp->rx_rssi = lround(lora.getRSSI()); } @@ -270,7 +283,7 @@ template bool LR11x0Interface::isActivelyReceiving() template bool LR11x0Interface::sleep() { // \todo Display actual typename of the adapter, not just `LR11x0` - LOG_DEBUG("LR11x0 entering sleep mode\n"); + LOG_DEBUG("LR11x0 entering sleep mode"); setStandby(); // Stop any pending operations // turn off TCXO if it was powered diff --git a/src/mesh/MeshModule.cpp b/src/mesh/MeshModule.cpp index c60404c983..a8de540eb3 100644 --- a/src/mesh/MeshModule.cpp +++ b/src/mesh/MeshModule.cpp @@ -55,7 +55,7 @@ meshtastic_MeshPacket *MeshModule::allocAckNak(meshtastic_Routing_Error err, Nod p->decoded.request_id = idFrom; p->channel = chIndex; if (err != meshtastic_Routing_Error_NONE) - LOG_WARN("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x\n", err, to, idFrom, p->id); + LOG_WARN("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x", err, to, idFrom, p->id); return p; } @@ -74,7 +74,7 @@ meshtastic_MeshPacket *MeshModule::allocErrorResponse(meshtastic_Routing_Error e void MeshModule::callModules(meshtastic_MeshPacket &mp, RxSource src) { - // LOG_DEBUG("In call modules\n"); + // LOG_DEBUG("In call modules"); bool moduleFound = false; // We now allow **encrypted** packets to pass through the modules @@ -86,7 +86,7 @@ void MeshModule::callModules(meshtastic_MeshPacket &mp, RxSource src) // Was this message directed to us specifically? Will be false if we are sniffing someone elses packets auto ourNodeNum = nodeDB->getNodeNum(); - bool toUs = mp.to == NODENUM_BROADCAST || isToUs(&mp); + bool toUs = isBroadcast(mp.to) || isToUs(&mp); for (auto i = modules->begin(); i != modules->end(); ++i) { auto &pi = **i; @@ -104,7 +104,7 @@ void MeshModule::callModules(meshtastic_MeshPacket &mp, RxSource src) assert(!pi.myReply); // If it is !null it means we have a bug, because it should have been sent the previous time if (wantsPacket) { - LOG_DEBUG("Module '%s' wantsPacket=%d\n", pi.name, wantsPacket); + LOG_DEBUG("Module '%s' wantsPacket=%d", pi.name, wantsPacket); moduleFound = true; @@ -144,20 +144,20 @@ void MeshModule::callModules(meshtastic_MeshPacket &mp, RxSource src) if (isDecoded && mp.decoded.want_response && toUs && (!isFromUs(&mp) || isToUs(&mp)) && !currentReply) { pi.sendResponse(mp); ignoreRequest = ignoreRequest || pi.ignoreRequest; // If at least one module asks it, we may ignore a request - LOG_INFO("Asked module '%s' to send a response\n", pi.name); + LOG_INFO("Asked module '%s' to send a response", pi.name); } else { - LOG_DEBUG("Module '%s' considered\n", pi.name); + LOG_DEBUG("Module '%s' considered", pi.name); } // If the requester didn't ask for a response we might need to discard unused replies to prevent memory leaks if (pi.myReply) { - LOG_DEBUG("Discarding an unneeded response\n"); + LOG_DEBUG("Discarding an unneeded response"); packetPool.release(pi.myReply); pi.myReply = NULL; } if (handled == ProcessMessage::STOP) { - LOG_DEBUG("Module '%s' handled and skipped other processing\n", pi.name); + LOG_DEBUG("Module '%s' handled and skipped other processing", pi.name); break; } } @@ -176,7 +176,7 @@ void MeshModule::callModules(meshtastic_MeshPacket &mp, RxSource src) // no response reply // No one wanted to reply to this request, tell the requster that happened - LOG_DEBUG("No one responded, send a nak\n"); + LOG_DEBUG("No one responded, send a nak"); // 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 @@ -187,8 +187,7 @@ void MeshModule::callModules(meshtastic_MeshPacket &mp, RxSource src) } if (!moduleFound && isDecoded) { - 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", mp.decoded.portnum, (src == RX_SRC_LOCAL) ? "LOCAL" : "REMOTE"); } } @@ -211,7 +210,7 @@ void MeshModule::sendResponse(const meshtastic_MeshPacket &req) currentReply = r; } else { // Ignore - this is now expected behavior for routing module (because it ignores some replies) - // LOG_WARN("Client requested response but this module did not provide\n"); + // LOG_WARN("Client requested response but this module did not provide"); } } @@ -240,7 +239,7 @@ std::vector MeshModule::GetMeshModulesWithUIFrames() for (auto i = modules->begin(); i != modules->end(); ++i) { auto &pi = **i; if (pi.wantUIFrame()) { - LOG_DEBUG("%s wants a UI Frame\n", pi.name); + LOG_DEBUG("%s wants a UI Frame", pi.name); modulesWithUIFrames.push_back(&pi); } } @@ -255,7 +254,7 @@ void MeshModule::observeUIEvents(Observer *observer) auto &pi = **i; Observable *observable = pi.getUIFrameObservable(); if (observable != NULL) { - LOG_DEBUG("%s wants a UI Frame\n", pi.name); + LOG_DEBUG("%s wants a UI Frame", pi.name); observer->observe(observable); } } @@ -273,7 +272,7 @@ AdminMessageHandleResult MeshModule::handleAdminMessageForAllModules(const mesht AdminMessageHandleResult h = pi.handleAdminMessageForModule(mp, request, 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", pi.name, response->which_payload_variant); handled = h; } else if ((handled != AdminMessageHandleResult::HANDLED_WITH_RESPONSE) && (h == AdminMessageHandleResult::HANDLED)) { // In case the message is handled it should be populated, but will not overwrite diff --git a/src/mesh/MeshService.cpp b/src/mesh/MeshService.cpp index 655348bd57..d224c05dca 100644 --- a/src/mesh/MeshService.cpp +++ b/src/mesh/MeshService.cpp @@ -80,15 +80,15 @@ int MeshService::handleFromRadio(const meshtastic_MeshPacket *mp) nodeDB->updateFrom(*mp); // update our DB state based off sniffing every RX packet from the radio if (mp->which_payload_variant == meshtastic_MeshPacket_decoded_tag && mp->decoded.portnum == meshtastic_PortNum_TELEMETRY_APP && mp->decoded.request_id > 0) { - LOG_DEBUG("Received telemetry response. Skip sending our NodeInfo.\n"); // because this potentially a Repeater which will - // ignore our request for its NodeInfo + LOG_DEBUG("Received telemetry response. Skip sending our NodeInfo."); // because this potentially a Repeater which will + // ignore our request for its NodeInfo } else if (mp->which_payload_variant == meshtastic_MeshPacket_decoded_tag && !nodeDB->getMeshNode(mp->from)->has_user && nodeInfoModule) { - LOG_INFO("Heard new node on channel %d, sending NodeInfo and asking for a response.\n", mp->channel); + LOG_INFO("Heard new node on channel %d, sending NodeInfo and asking for a response.", mp->channel); if (airTime->isTxAllowedChannelUtil(true)) { nodeInfoModule->sendOurNodeInfo(mp->from, true, mp->channel); } else { - LOG_DEBUG("Skip sending NodeInfo due to > 25 percent channel util.\n"); + LOG_DEBUG("Skip sending NodeInfo due to > 25 percent channel util."); } } @@ -130,7 +130,7 @@ bool MeshService::reloadConfig(int saveWhat) /// The owner User record just got updated, update our node DB and broadcast the info into the mesh void MeshService::reloadOwner(bool shouldSave) { - // LOG_DEBUG("reloadOwner()\n"); + // LOG_DEBUG("reloadOwner()"); // update our local data directly nodeDB->updateUser(nodeDB->getNodeNum(), owner); assert(nodeInfoModule); @@ -180,7 +180,7 @@ void MeshService::handleToRadio(meshtastic_MeshPacket &p) // 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"); + LOG_ERROR("Error decoding protobuf for simulator message!"); } // Let SimRadio receive as if it did via its LoRa chip SimRadio::instance->startReceive(&p); @@ -222,7 +222,7 @@ ErrorCode MeshService::sendQueueStatusToPhone(const meshtastic_QueueStatus &qs, copied->mesh_packet_id = mesh_packet_id; if (toPhoneQueueStatusQueue.numFree() == 0) { - LOG_INFO("tophone queue status queue is full, discarding oldest\n"); + LOG_INFO("tophone queue status queue is full, discarding oldest"); meshtastic_QueueStatus *d = toPhoneQueueStatusQueue.dequeuePtr(0); if (d) releaseQueueStatusToPool(d); @@ -266,14 +266,14 @@ bool MeshService::trySendPosition(NodeNum dest, bool wantReplies) if (hasValidPosition(node)) { #if HAS_GPS && !MESHTASTIC_EXCLUDE_GPS if (positionModule) { - LOG_INFO("Sending position ping to 0x%x, wantReplies=%d, channel=%d\n", dest, wantReplies, node->channel); + LOG_INFO("Sending position ping to 0x%x, wantReplies=%d, channel=%d", dest, wantReplies, node->channel); positionModule->sendOurPosition(dest, wantReplies, node->channel); return true; } } else { #endif if (nodeInfoModule) { - LOG_INFO("Sending nodeinfo ping to 0x%x, wantReplies=%d, channel=%d\n", dest, wantReplies, node->channel); + LOG_INFO("Sending nodeinfo ping to 0x%x, wantReplies=%d, channel=%d", dest, wantReplies, node->channel); nodeInfoModule->sendOurNodeInfo(dest, wantReplies, node->channel); } } @@ -298,12 +298,12 @@ void MeshService::sendToPhone(meshtastic_MeshPacket *p) if (toPhoneQueue.numFree() == 0) { if (p->decoded.portnum == meshtastic_PortNum_TEXT_MESSAGE_APP || p->decoded.portnum == meshtastic_PortNum_RANGE_TEST_APP) { - LOG_WARN("ToPhone queue is full, discarding oldest\n"); + LOG_WARN("ToPhone queue is full, discarding oldest"); meshtastic_MeshPacket *d = toPhoneQueue.dequeuePtr(0); if (d) releaseToPool(d); } else { - LOG_WARN("ToPhone queue is full, dropping packet.\n"); + LOG_WARN("ToPhone queue is full, dropping packet."); releaseToPool(p); fromNum++; // Make sure to notify observers in case they are reconnected so they can get the packets return; @@ -316,9 +316,9 @@ void MeshService::sendToPhone(meshtastic_MeshPacket *p) void MeshService::sendMqttMessageToClientProxy(meshtastic_MqttClientProxyMessage *m) { - LOG_DEBUG("Sending mqtt message on topic '%s' to client for proxy\n", m->topic); + LOG_DEBUG("Sending mqtt message on topic '%s' to client for proxy", m->topic); if (toPhoneMqttProxyQueue.numFree() == 0) { - LOG_WARN("MqttClientProxyMessagePool queue is full, discarding oldest\n"); + LOG_WARN("MqttClientProxyMessagePool queue is full, discarding oldest"); meshtastic_MqttClientProxyMessage *d = toPhoneMqttProxyQueue.dequeuePtr(0); if (d) releaseMqttClientProxyMessageToPool(d); @@ -330,9 +330,9 @@ void MeshService::sendMqttMessageToClientProxy(meshtastic_MqttClientProxyMessage void MeshService::sendClientNotification(meshtastic_ClientNotification *n) { - LOG_DEBUG("Sending client notification to phone\n"); + LOG_DEBUG("Sending client notification to phone"); if (toPhoneClientNotificationQueue.numFree() == 0) { - LOG_WARN("ClientNotification queue is full, discarding oldest\n"); + LOG_WARN("ClientNotification queue is full, discarding oldest"); meshtastic_ClientNotification *d = toPhoneClientNotificationQueue.dequeuePtr(0); if (d) releaseClientNotificationToPool(d); @@ -381,12 +381,12 @@ int MeshService::onGPSChanged(const meshtastic::GPSStatus *newStatus) } else { // The GPS has lost lock #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("onGPSchanged() - lost validLocation\n"); + LOG_DEBUG("onGPSchanged() - lost validLocation"); #endif } // Used fixed position if configured regardless of GPS lock if (config.position.fixed_position) { - LOG_WARN("Using fixed position\n"); + LOG_WARN("Using fixed position"); pos = TypeConversions::ConvertToPosition(node->position); } @@ -394,7 +394,7 @@ int MeshService::onGPSChanged(const meshtastic::GPSStatus *newStatus) pos.time = getValidTime(RTCQualityFromNet); // In debug logs, identify position by @timestamp:stage (stage 4 = nodeDB) - LOG_DEBUG("onGPSChanged() pos@%x time=%u lat=%d lon=%d alt=%d\n", pos.timestamp, pos.time, pos.latitude_i, pos.longitude_i, + LOG_DEBUG("onGPSChanged() pos@%x time=%u lat=%d lon=%d alt=%d", pos.timestamp, pos.time, pos.latitude_i, pos.longitude_i, pos.altitude); // Update our current position in the local DB diff --git a/src/mesh/MeshTypes.h b/src/mesh/MeshTypes.h index 27d100fbef..7a3d785dd5 100644 --- a/src/mesh/MeshTypes.h +++ b/src/mesh/MeshTypes.h @@ -57,4 +57,6 @@ bool isFromUs(const meshtastic_MeshPacket *p); bool isToUs(const meshtastic_MeshPacket *p); /* Some clients might not properly set priority, therefore we fix it here. */ -void fixPriority(meshtastic_MeshPacket *p); \ No newline at end of file +void fixPriority(meshtastic_MeshPacket *p); + +bool isBroadcast(uint32_t dest); \ No newline at end of file diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp index 97ded5a50f..69cd631c0f 100644 --- a/src/mesh/NodeDB.cpp +++ b/src/mesh/NodeDB.cpp @@ -32,9 +32,14 @@ #if HAS_WIFI #include "mesh/wifi/WiFiAPClient.h" #endif +#include "SPILock.h" #include "modules/StoreForwardModule.h" #include +#include +#include #include +#include +#include #endif #ifdef ARCH_PORTDUINO @@ -55,8 +60,6 @@ meshtastic_MyNodeInfo &myNodeInfo = devicestate.my_node; meshtastic_LocalConfig config; meshtastic_LocalModuleConfig moduleConfig; meshtastic_ChannelFile channelFile; -meshtastic_OEMStore oemStore; -static bool hasOemStore = false; bool meshtastic_DeviceState_callback(pb_istream_t *istream, pb_ostream_t *ostream, const pb_field_iter_t *field) { @@ -102,7 +105,7 @@ static uint8_t ourMacAddr[6]; NodeDB::NodeDB() { - LOG_INFO("Initializing NodeDB\n"); + LOG_INFO("Initializing NodeDB"); loadFromDisk(); cleanupMeshDB(); @@ -111,6 +114,43 @@ NodeDB::NodeDB() uint32_t channelFileCRC = crc32Buffer(&channelFile, sizeof(channelFile)); int saveWhat = 0; + bool hasUniqueId = false; + // Get device unique id +#if defined(ARCH_ESP32) && defined(ESP_EFUSE_OPTIONAL_UNIQUE_ID) + uint32_t unique_id[4]; + // ESP32 factory burns a unique id in efuse for S2+ series and evidently C3+ series + // This is used for HMACs in the esp-rainmaker AIOT platform and seems to be a good choice for us + esp_err_t err = esp_efuse_read_field_blob(ESP_EFUSE_OPTIONAL_UNIQUE_ID, unique_id, sizeof(unique_id) * 8); + if (err == ESP_OK) { + memcpy(myNodeInfo.device_id.bytes, unique_id, sizeof(unique_id)); + myNodeInfo.device_id.size = 16; + hasUniqueId = true; + } else { + LOG_WARN("Failed to read unique id from efuse"); + } +#elif defined(ARCH_NRF52) + // Nordic applies a FIPS compliant Random ID to each chip at the factory + // We concatenate the device address to the Random ID to create a unique ID for now + // This will likely utilize a crypto module in the future + uint64_t device_id_start = ((uint64_t)NRF_FICR->DEVICEID[1] << 32) | NRF_FICR->DEVICEID[0]; + uint64_t device_id_end = ((uint64_t)NRF_FICR->DEVICEADDR[1] << 32) | NRF_FICR->DEVICEADDR[0]; + memcpy(myNodeInfo.device_id.bytes, &device_id_start, sizeof(device_id_start)); + memcpy(myNodeInfo.device_id.bytes + sizeof(device_id_start), &device_id_end, sizeof(device_id_end)); + myNodeInfo.device_id.size = 16; + hasUniqueId = true; +#else + // FIXME - implement for other platforms +#endif + // Uncomment below to print the device id + // if (hasUniqueId) { + // std::string deviceIdHex; + // for (size_t i = 0; i < myNodeInfo.device_id.size; ++i) { + // char buf[3]; + // snprintf(buf, sizeof(buf), "%02X", myNodeInfo.device_id.bytes[i]); + // deviceIdHex += buf; + // } + // LOG_DEBUG("Device ID (HEX): %s", deviceIdHex.c_str()); + // } // likewise - we always want the app requirements to come from the running appload myNodeInfo.min_app_version = 30200; // format is Mmmss (where M is 1+the numeric major number. i.e. 30200 means 2.2.00 @@ -140,7 +180,7 @@ NodeDB::NodeDB() keygenSuccess = true; } } else { - LOG_INFO("Generating new PKI keys\n"); + LOG_INFO("Generating new PKI keys"); crypto->generateKeyPair(config.security.public_key.bytes, config.security.private_key.bytes); keygenSuccess = true; } @@ -167,11 +207,27 @@ NodeDB::NodeDB() preferences.begin("meshtastic", false); myNodeInfo.reboot_count = preferences.getUInt("rebootCounter", 0); preferences.end(); - LOG_DEBUG("Number of Device Reboots: %d\n", myNodeInfo.reboot_count); + LOG_DEBUG("Number of Device Reboots: %d", myNodeInfo.reboot_count); #endif resetRadioConfig(); // If bogus settings got saved, then fix them - // nodeDB->LOG_DEBUG("region=%d, NODENUM=0x%x, dbsize=%d\n", config.lora.region, myNodeInfo.my_node_num, numMeshNodes); + // nodeDB->LOG_DEBUG("region=%d, NODENUM=0x%x, dbsize=%d", config.lora.region, myNodeInfo.my_node_num, numMeshNodes); + + // If we are setup to broadcast on the default channel, ensure that the telemetry intervals are coerced to the minimum value + // of 30 minutes or more + if (channels.isDefaultChannel(channels.getPrimaryIndex())) { + LOG_DEBUG("Coercing telemetry to min of 30 minutes on defaults"); + moduleConfig.telemetry.device_update_interval = Default::getConfiguredOrMinimumValue( + moduleConfig.telemetry.device_update_interval, min_default_telemetry_interval_secs); + moduleConfig.telemetry.environment_update_interval = Default::getConfiguredOrMinimumValue( + moduleConfig.telemetry.environment_update_interval, min_default_telemetry_interval_secs); + moduleConfig.telemetry.air_quality_interval = Default::getConfiguredOrMinimumValue( + moduleConfig.telemetry.air_quality_interval, min_default_telemetry_interval_secs); + moduleConfig.telemetry.power_update_interval = Default::getConfiguredOrMinimumValue( + moduleConfig.telemetry.power_update_interval, min_default_telemetry_interval_secs); + moduleConfig.telemetry.health_update_interval = Default::getConfiguredOrMinimumValue( + moduleConfig.telemetry.health_update_interval, min_default_telemetry_interval_secs); + } if (devicestateCRC != crc32Buffer(&devicestate, sizeof(devicestate))) saveWhat |= SEGMENT_DEVICESTATE; @@ -208,6 +264,11 @@ bool isToUs(const meshtastic_MeshPacket *p) return p->to == nodeDB->getNodeNum(); } +bool isBroadcast(uint32_t dest) +{ + return dest == NODENUM_BROADCAST || dest == NODENUM_BROADCAST_NO_LORA; +} + bool NodeDB::resetRadioConfig(bool factory_reset) { bool didFactoryReset = false; @@ -219,7 +280,7 @@ bool NodeDB::resetRadioConfig(bool factory_reset) } if (channelFile.channels_count != MAX_NUM_CHANNELS) { - LOG_INFO("Setting default channel and radio preferences!\n"); + LOG_INFO("Setting default channel and radio preferences!"); channels.initDefaults(); } @@ -240,12 +301,12 @@ bool NodeDB::resetRadioConfig(bool factory_reset) bool NodeDB::factoryReset(bool eraseBleBonds) { - LOG_INFO("Performing factory reset!\n"); + LOG_INFO("Performing factory reset!"); // first, remove the "/prefs" (this removes most prefs) rmDir("/prefs"); #ifdef FSCom if (FSCom.exists("/static/rangetest.csv") && !FSCom.remove("/static/rangetest.csv")) { - LOG_ERROR("Could not remove rangetest.csv file\n"); + LOG_ERROR("Could not remove rangetest.csv file"); } #endif // second, install default state (this will deal with the duplicate mac address issue) @@ -256,14 +317,14 @@ bool NodeDB::factoryReset(bool eraseBleBonds) // third, write everything to disk saveToDisk(); if (eraseBleBonds) { - LOG_INFO("Erasing BLE bonds\n"); + LOG_INFO("Erasing BLE bonds"); #ifdef ARCH_ESP32 // This will erase what's in NVS including ssl keys, persistent variables and ble pairing nvs_flash_erase(); #endif #ifdef ARCH_NRF52 Bluefruit.begin(); - LOG_INFO("Clearing bluetooth bonds!\n"); + LOG_INFO("Clearing bluetooth bonds!"); bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_CENTRAL); Bluefruit.Periph.clearBonds(); @@ -280,7 +341,7 @@ void NodeDB::installDefaultConfig(bool preserveKey = false) if (shouldPreserveKey) { memcpy(private_key_temp, config.security.private_key.bytes, config.security.private_key.size); } - LOG_INFO("Installing default LocalConfig\n"); + LOG_INFO("Installing default LocalConfig"); memset(&config, 0, sizeof(meshtastic_LocalConfig)); config.version = DEVICESTATE_CUR_VER; config.has_device = true; @@ -418,7 +479,7 @@ void NodeDB::initConfigIntervals() void NodeDB::installDefaultModuleConfig() { - LOG_INFO("Installing default ModuleConfig\n"); + LOG_INFO("Installing default ModuleConfig"); memset(&moduleConfig, 0, sizeof(meshtastic_ModuleConfig)); moduleConfig.version = DEVICESTATE_CUR_VER; @@ -533,6 +594,7 @@ void NodeDB::installRoleDefaults(meshtastic_Config_DeviceConfig_Role role) moduleConfig.telemetry.device_update_interval = UINT32_MAX; moduleConfig.telemetry.environment_update_interval = UINT32_MAX; moduleConfig.telemetry.air_quality_interval = UINT32_MAX; + moduleConfig.telemetry.health_update_interval = UINT32_MAX; } } @@ -543,22 +605,26 @@ void NodeDB::initModuleConfigIntervals() moduleConfig.telemetry.environment_update_interval = 0; moduleConfig.telemetry.air_quality_interval = 0; moduleConfig.telemetry.power_update_interval = 0; + moduleConfig.telemetry.health_update_interval = 0; moduleConfig.neighbor_info.update_interval = 0; moduleConfig.paxcounter.paxcounter_update_interval = 0; } void NodeDB::installDefaultChannels() { - LOG_INFO("Installing default ChannelFile\n"); + LOG_INFO("Installing default ChannelFile"); memset(&channelFile, 0, sizeof(meshtastic_ChannelFile)); channelFile.version = DEVICESTATE_CUR_VER; } void NodeDB::resetNodes() { - clearLocalPosition(); + if (!config.position.fixed_position) + clearLocalPosition(); numMeshNodes = 1; std::fill(devicestate.node_db_lite.begin() + 1, devicestate.node_db_lite.end(), meshtastic_NodeInfoLite()); + devicestate.has_rx_text_message = false; + devicestate.has_rx_waypoint = false; saveDeviceStateToDisk(); if (neighborInfoModule && moduleConfig.neighbor_info.enabled) neighborInfoModule->resetNeighbors(); @@ -576,7 +642,7 @@ void NodeDB::removeNodeByNum(NodeNum nodeNum) numMeshNodes -= removed; std::fill(devicestate.node_db_lite.begin() + numMeshNodes, devicestate.node_db_lite.begin() + numMeshNodes + 1, meshtastic_NodeInfoLite()); - LOG_DEBUG("NodeDB::removeNodeByNum purged %d entries. Saving changes...\n", removed); + LOG_DEBUG("NodeDB::removeNodeByNum purged %d entries. Saving changes...", removed); saveDeviceStateToDisk(); } @@ -608,12 +674,12 @@ void NodeDB::cleanupMeshDB() numMeshNodes -= removed; std::fill(devicestate.node_db_lite.begin() + numMeshNodes, devicestate.node_db_lite.begin() + numMeshNodes + removed, meshtastic_NodeInfoLite()); - LOG_DEBUG("cleanupMeshDB purged %d entries\n", removed); + LOG_DEBUG("cleanupMeshDB purged %d entries", removed); } void NodeDB::installDefaultDeviceState() { - LOG_INFO("Installing default DeviceState\n"); + LOG_INFO("Installing default DeviceState"); // memset(&devicestate, 0, sizeof(meshtastic_DeviceState)); numMeshNodes = 0; @@ -667,11 +733,11 @@ void NodeDB::pickNewNodeNum() NodeNum candidate = random(NUM_RESERVED, LONG_MAX); // try a new random choice if (found) LOG_WARN("NOTE! Our desired nodenum 0x%x is invalid or in use, by MAC ending in 0x%02x%02x vs our 0x%02x%02x, so " - "trying for 0x%x\n", + "trying for 0x%x", nodeNum, found->user.macaddr[4], found->user.macaddr[5], ourMacAddr[4], ourMacAddr[5], candidate); nodeNum = candidate; } - LOG_DEBUG("Using nodenum 0x%x \n", nodeNum); + LOG_DEBUG("Using nodenum 0x%x ", nodeNum); myNodeInfo.my_node_num = nodeNum; } @@ -680,7 +746,6 @@ static const char *prefFileName = "/prefs/db.proto"; static const char *configFileName = "/prefs/config.proto"; 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 LoadFileResult */ LoadFileResult NodeDB::loadProto(const char *filename, size_t protoSize, size_t objSize, const pb_msgdesc_t *fields, @@ -692,23 +757,23 @@ LoadFileResult NodeDB::loadProto(const char *filename, size_t protoSize, size_t auto f = FSCom.open(filename, FILE_O_READ); if (f) { - LOG_INFO("Loading %s\n", filename); + LOG_INFO("Loading %s", filename); pb_istream_t stream = {&readcb, &f, protoSize}; memset(dest_struct, 0, objSize); if (!pb_decode(&stream, fields, dest_struct)) { - LOG_ERROR("Error: can't decode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_ERROR("Error: can't decode protobuf %s", PB_GET_ERROR(&stream)); state = LoadFileResult::DECODE_FAILED; } else { - LOG_INFO("Loaded %s successfully\n", filename); + LOG_INFO("Loaded %s successfully", filename); state = LoadFileResult::LOAD_SUCCESS; } f.close(); } else { - LOG_ERROR("Could not open / read %s\n", filename); + LOG_ERROR("Could not open / read %s", filename); } #else - LOG_ERROR("ERROR: Filesystem not implemented\n"); + LOG_ERROR("ERROR: Filesystem not implemented"); state = LoadFileResult::NO_FILESYSTEM; #endif return state; @@ -733,11 +798,10 @@ void NodeDB::loadFromDisk() // installDefaultDeviceState(); // Our in RAM copy might now be corrupt //} else { if (devicestate.version < DEVICESTATE_MIN_VER) { - LOG_WARN("Devicestate %d is old, discarding\n", devicestate.version); + LOG_WARN("Devicestate %d is old, discarding", devicestate.version); installDefaultDeviceState(); } else { - LOG_INFO("Loaded saved devicestate version %d, with nodecount: %d\n", devicestate.version, - devicestate.node_db_lite.size()); + LOG_INFO("Loaded saved devicestate version %d, with nodecount: %d", devicestate.version, devicestate.node_db_lite.size()); meshNodes = &devicestate.node_db_lite; numMeshNodes = devicestate.node_db_lite.size(); } @@ -749,10 +813,10 @@ void NodeDB::loadFromDisk() installDefaultConfig(); // Our in RAM copy might now be corrupt } else { if (config.version < DEVICESTATE_MIN_VER) { - LOG_WARN("config %d is old, discarding\n", config.version); + LOG_WARN("config %d is old, discarding", config.version); installDefaultConfig(true); } else { - LOG_INFO("Loaded saved config version %d\n", config.version); + LOG_INFO("Loaded saved config version %d", config.version); } } @@ -762,10 +826,10 @@ void NodeDB::loadFromDisk() installDefaultModuleConfig(); // Our in RAM copy might now be corrupt } else { if (moduleConfig.version < DEVICESTATE_MIN_VER) { - LOG_WARN("moduleConfig %d is old, discarding\n", moduleConfig.version); + LOG_WARN("moduleConfig %d is old, discarding", moduleConfig.version); installDefaultModuleConfig(); } else { - LOG_INFO("Loaded saved moduleConfig version %d\n", moduleConfig.version); + LOG_INFO("Loaded saved moduleConfig version %d", moduleConfig.version); } } @@ -775,22 +839,16 @@ void NodeDB::loadFromDisk() installDefaultChannels(); // Our in RAM copy might now be corrupt } else { if (channelFile.version < DEVICESTATE_MIN_VER) { - LOG_WARN("channelFile %d is old, discarding\n", channelFile.version); + LOG_WARN("channelFile %d is old, discarding", channelFile.version); installDefaultChannels(); } else { - LOG_INFO("Loaded saved channelFile version %d\n", channelFile.version); + LOG_INFO("Loaded saved channelFile version %d", channelFile.version); } } - state = loadProto(oemConfigFile, meshtastic_OEMStore_size, sizeof(meshtastic_OEMStore), &meshtastic_OEMStore_msg, &oemStore); - if (state == LoadFileResult::LOAD_SUCCESS) { - LOG_INFO("Loaded OEMStore\n"); - hasOemStore = true; - } - // 2.4.X - configuration migration to update new default intervals if (moduleConfig.version < 23) { - LOG_DEBUG("ModuleConfig version %d is stale, upgrading to new default intervals\n", moduleConfig.version); + LOG_DEBUG("ModuleConfig version %d is stale, upgrading to new default intervals", moduleConfig.version); moduleConfig.version = DEVICESTATE_CUR_VER; if (moduleConfig.telemetry.device_update_interval == 900) moduleConfig.telemetry.device_update_interval = 0; @@ -813,15 +871,18 @@ void NodeDB::loadFromDisk() bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_t *fields, const void *dest_struct, bool fullAtomic) { +#ifdef ARCH_ESP32 + concurrency::LockGuard g(spiLock); +#endif bool okay = false; #ifdef FSCom auto f = SafeFile(filename, fullAtomic); - LOG_INFO("Saving %s\n", filename); + LOG_INFO("Saving %s", filename); pb_ostream_t stream = {&writecb, static_cast(&f), protoSize}; if (!pb_encode(&stream, fields, dest_struct)) { - LOG_ERROR("Error: can't encode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_ERROR("Error: can't encode protobuf %s", PB_GET_ERROR(&stream)); } else { okay = true; } @@ -829,10 +890,10 @@ bool NodeDB::saveProto(const char *filename, size_t protoSize, const pb_msgdesc_ bool writeSucceeded = f.close(); if (!okay || !writeSucceeded) { - LOG_ERROR("Can't write prefs!\n"); + LOG_ERROR("Can't write prefs!"); } #else - LOG_ERROR("ERROR: Filesystem not implemented\n"); + LOG_ERROR("ERROR: Filesystem not implemented"); #endif return okay; } @@ -894,11 +955,6 @@ bool NodeDB::saveToDiskNoRetry(int saveWhat) saveProto(moduleConfigFileName, meshtastic_LocalModuleConfig_size, &meshtastic_LocalModuleConfig_msg, &moduleConfig); } - // We might need to rewrite the OEM data if we are reformatting the FS - if ((saveWhat & SEGMENT_OEM) && hasOemStore) { - success &= saveProto(oemConfigFile, meshtastic_OEMStore_size, &meshtastic_OEMStore_msg, &oemStore); - } - if (saveWhat & SEGMENT_CHANNELS) { success &= saveChannelsToDisk(); } @@ -915,12 +971,10 @@ bool NodeDB::saveToDisk(int saveWhat) bool success = saveToDiskNoRetry(saveWhat); if (!success) { - LOG_ERROR("Failed to save to disk, retrying...\n"); + LOG_ERROR("Failed to save to disk, retrying..."); #ifdef ARCH_NRF52 // @geeksville is not ready yet to say we should do this on other platforms. See bug #4184 discussion FSCom.format(); - // We need to rewrite the OEM data if we are reformatting the FS - saveWhat |= SEGMENT_OEM; #endif success = saveToDiskNoRetry(saveWhat); @@ -993,7 +1047,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const meshtastic_Position &p, RxSou if (src == RX_SRC_LOCAL) { // Local packet, fully authoritative - LOG_INFO("updatePosition LOCAL pos@%x time=%u lat=%d lon=%d alt=%d\n", p.timestamp, p.time, p.latitude_i, p.longitude_i, + LOG_INFO("updatePosition LOCAL pos@%x time=%u lat=%d lon=%d alt=%d", p.timestamp, p.time, p.latitude_i, p.longitude_i, p.altitude); setLocalPosition(p); @@ -1001,7 +1055,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const meshtastic_Position &p, RxSou } 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); + LOG_DEBUG("updatePosition SPECIAL time setting time=%u", p.time); info->position.time = p.time; } else { // Be careful to only update fields that have been set by the REMOTE sender @@ -1009,7 +1063,7 @@ void NodeDB::updatePosition(uint32_t nodeId, const meshtastic_Position &p, RxSou // recorded based on the packet rxTime // // FIXME perhaps handle RX_SRC_USER separately? - LOG_INFO("updatePosition REMOTE node=0x%x time=%u lat=%d lon=%d\n", nodeId, p.time, p.latitude_i, p.longitude_i); + LOG_INFO("updatePosition REMOTE node=0x%x time=%u lat=%d lon=%d", nodeId, p.time, p.latitude_i, p.longitude_i); // First, back up fields that we want to protect from overwrite uint32_t tmp_time = info->position.time; @@ -1039,9 +1093,9 @@ void NodeDB::updateTelemetry(uint32_t nodeId, const meshtastic_Telemetry &t, RxS if (src == RX_SRC_LOCAL) { // Local packet, fully authoritative - LOG_DEBUG("updateTelemetry LOCAL\n"); + LOG_DEBUG("updateTelemetry LOCAL"); } else { - LOG_DEBUG("updateTelemetry REMOTE node=0x%x \n", nodeId); + LOG_DEBUG("updateTelemetry REMOTE node=0x%x ", nodeId); } info->device_metrics = t.variant.device_metrics; info->has_device_metrics = true; @@ -1058,16 +1112,16 @@ bool NodeDB::updateUser(uint32_t nodeId, meshtastic_User &p, uint8_t channelInde return false; } - LOG_DEBUG("old user %s/%s, channel=%d\n", info->user.long_name, info->user.short_name, info->channel); + LOG_DEBUG("old user %s/%s, channel=%d", info->user.long_name, info->user.short_name, info->channel); #if !(MESHTASTIC_EXCLUDE_PKI) if (p.public_key.size > 0) { printBytes("Incoming Pubkey: ", p.public_key.bytes, 32); if (info->user.public_key.size > 0) { // if we have a key for this user already, don't overwrite with a new one - LOG_INFO("Public Key set for node, not updating!\n"); + LOG_INFO("Public Key set for node, not updating!"); // we copy the key into the incoming packet, to prevent overwrite memcpy(p.public_key.bytes, info->user.public_key.bytes, 32); } else { - LOG_INFO("Updating Node Pubkey!\n"); + LOG_INFO("Updating Node Pubkey!"); } } #endif @@ -1082,8 +1136,7 @@ bool NodeDB::updateUser(uint32_t nodeId, meshtastic_User &p, uint8_t channelInde } if (nodeId != getNodeNum()) info->channel = channelIndex; // Set channel we need to use to reach this node (but don't set our own channel) - LOG_DEBUG("updating changed=%d user %s/%s, channel=%d\n", changed, info->user.long_name, info->user.short_name, - info->channel); + LOG_DEBUG("updating changed=%d user %s/%s, channel=%d", changed, info->user.long_name, info->user.short_name, info->channel); info->has_user = true; if (changed) { @@ -1094,7 +1147,7 @@ bool NodeDB::updateUser(uint32_t nodeId, meshtastic_User &p, uint8_t channelInde // We just changed something about the user, store our DB Throttle::execute( &lastNodeDbSave, ONE_MINUTE_MS, []() { nodeDB->saveToDisk(SEGMENT_DEVICESTATE); }, - []() { LOG_DEBUG("Deferring NodeDB saveToDisk for now\n"); }); // since we saved less than a minute ago + []() { LOG_DEBUG("Deferring NodeDB saveToDisk for now"); }); // since we saved less than a minute ago } return changed; @@ -1105,7 +1158,7 @@ bool NodeDB::updateUser(uint32_t nodeId, meshtastic_User &p, uint8_t channelInde void NodeDB::updateFrom(const meshtastic_MeshPacket &mp) { 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); + LOG_DEBUG("Update DB node 0x%x, rx_time=%u", mp.from, mp.rx_time); meshtastic_NodeInfoLite *info = getOrCreateMeshNode(getFrom(&mp)); if (!info) { @@ -1157,7 +1210,7 @@ meshtastic_NodeInfoLite *NodeDB::getOrCreateMeshNode(NodeNum n) if ((numMeshNodes >= MAX_NUM_NODES) || (memGet.getFreeHeap() < MINIMUM_SAFE_FREE_HEAP)) { if (screen) screen->print("Warn: node database full!\nErasing oldest entry\n"); - LOG_WARN("Node database full with %i nodes and %i bytes free! Erasing oldest entry\n", numMeshNodes, + LOG_WARN("Node database full with %i nodes and %i bytes free! Erasing oldest entry", numMeshNodes, memGet.getFreeHeap()); // look for oldest node and erase it uint32_t oldest = UINT32_MAX; @@ -1193,7 +1246,7 @@ meshtastic_NodeInfoLite *NodeDB::getOrCreateMeshNode(NodeNum n) // everything is missing except the nodenum memset(lite, 0, sizeof(*lite)); lite->num = n; - LOG_INFO("Adding node to database with %i nodes and %i bytes free!\n", numMeshNodes, memGet.getFreeHeap()); + LOG_INFO("Adding node to database with %i nodes and %i bytes free!", numMeshNodes, memGet.getFreeHeap()); } return lite; @@ -1204,11 +1257,12 @@ void recordCriticalError(meshtastic_CriticalErrorCode code, uint32_t address, co { // Print error to screen and serial port String lcd = String("Critical error ") + code + "!\n"; - screen->print(lcd.c_str()); + if (screen) + screen->print(lcd.c_str()); if (filename) { - LOG_ERROR("NOTE! Recording critical error %d at %s:%lu\n", code, filename, address); + LOG_ERROR("NOTE! Recording critical error %d at %s:%lu", code, filename, address); } else { - LOG_ERROR("NOTE! Recording critical error %d, address=0x%lx\n", code, address); + LOG_ERROR("NOTE! Recording critical error %d, address=0x%lx", code, address); } // Record error to DB diff --git a/src/mesh/NodeDB.h b/src/mesh/NodeDB.h index 1be61759a1..eb33a2f6d4 100644 --- a/src/mesh/NodeDB.h +++ b/src/mesh/NodeDB.h @@ -21,7 +21,6 @@ DeviceState versions used to be defined in the .proto file but really only this #define SEGMENT_MODULECONFIG 2 #define SEGMENT_DEVICESTATE 4 #define SEGMENT_CHANNELS 8 -#define SEGMENT_OEM 16 #define DEVICESTATE_CUR_VER 23 #define DEVICESTATE_MIN_VER 22 @@ -31,7 +30,6 @@ extern meshtastic_ChannelFile channelFile; extern meshtastic_MyNodeInfo &myNodeInfo; extern meshtastic_LocalConfig config; extern meshtastic_LocalModuleConfig moduleConfig; -extern meshtastic_OEMStore oemStore; extern meshtastic_User &owner; extern meshtastic_Position localPosition; @@ -154,12 +152,12 @@ class NodeDB void setLocalPosition(meshtastic_Position position, bool timeOnly = false) { if (timeOnly) { - LOG_DEBUG("Setting local position time only: time=%u timestamp=%u\n", position.time, position.timestamp); + LOG_DEBUG("Setting local position time only: time=%u timestamp=%u", position.time, position.timestamp); localPosition.time = position.time; localPosition.timestamp = position.timestamp > 0 ? position.timestamp : position.time; return; } - LOG_DEBUG("Setting local position: lat=%i lon=%i time=%u timestamp=%u\n", position.latitude_i, position.longitude_i, + LOG_DEBUG("Setting local position: lat=%i lon=%i time=%u timestamp=%u", position.latitude_i, position.longitude_i, position.time, position.timestamp); localPosition = position; } diff --git a/src/mesh/PacketHistory.cpp b/src/mesh/PacketHistory.cpp index ed1c3c59c8..8d49bce43f 100644 --- a/src/mesh/PacketHistory.cpp +++ b/src/mesh/PacketHistory.cpp @@ -19,7 +19,7 @@ PacketHistory::PacketHistory() bool PacketHistory::wasSeenRecently(const meshtastic_MeshPacket *p, bool withUpdate) { if (p->id == 0) { - LOG_DEBUG("Ignoring message with zero id\n"); + LOG_DEBUG("Ignoring message with zero id"); return false; // Not a floodable message ID, so we don't care } @@ -39,7 +39,7 @@ bool PacketHistory::wasSeenRecently(const meshtastic_MeshPacket *p, bool withUpd } if (seenRecently) { - LOG_DEBUG("Found existing packet record for fr=0x%x,to=0x%x,id=0x%x\n", p->from, p->to, p->id); + LOG_DEBUG("Found existing packet record for fr=0x%x,to=0x%x,id=0x%x", p->from, p->to, p->id); } if (withUpdate) { @@ -64,7 +64,7 @@ bool PacketHistory::wasSeenRecently(const meshtastic_MeshPacket *p, bool withUpd */ void PacketHistory::clearExpiredRecentPackets() { - LOG_DEBUG("recentPackets size=%ld\n", recentPackets.size()); + LOG_DEBUG("recentPackets size=%ld", recentPackets.size()); for (auto it = recentPackets.begin(); it != recentPackets.end();) { if (!Throttle::isWithinTimespanMs(it->rxTimeMsec, FLOOD_EXPIRE_TIME)) { @@ -74,5 +74,5 @@ void PacketHistory::clearExpiredRecentPackets() } } - LOG_DEBUG("recentPackets size=%ld (after clearing expired packets)\n", recentPackets.size()); + LOG_DEBUG("recentPackets size=%ld (after clearing expired packets)", recentPackets.size()); } \ No newline at end of file diff --git a/src/mesh/PhoneAPI.cpp b/src/mesh/PhoneAPI.cpp index ad4a1f33db..98db38c47b 100644 --- a/src/mesh/PhoneAPI.cpp +++ b/src/mesh/PhoneAPI.cpp @@ -55,16 +55,16 @@ void PhoneAPI::handleStartConfig() state = STATE_SEND_MY_INFO; pauseBluetoothLogging = true; filesManifest = getFiles("/", 10); - LOG_DEBUG("Got %d files in manifest\n", filesManifest.size()); + LOG_DEBUG("Got %d files in manifest", filesManifest.size()); - LOG_INFO("Starting API client config\n"); + LOG_INFO("Starting API client config"); nodeInfoForPhone.num = 0; // Don't keep returning old nodeinfos resetReadIndex(); } void PhoneAPI::close() { - LOG_INFO("PhoneAPI::close()\n"); + LOG_INFO("PhoneAPI::close()"); if (state != STATE_SEND_NOTHING) { state = STATE_SEND_NOTHING; @@ -95,7 +95,7 @@ bool PhoneAPI::checkConnectionTimeout() if (isConnected()) { bool newContact = checkIsConnected(); if (!newContact) { - LOG_INFO("Lost phone connection\n"); + LOG_INFO("Lost phone connection"); close(); return true; } @@ -118,41 +118,41 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) return handleToRadioPacket(toRadioScratch.packet); case meshtastic_ToRadio_want_config_id_tag: config_nonce = toRadioScratch.want_config_id; - LOG_INFO("Client wants config, nonce=%u\n", config_nonce); + LOG_INFO("Client wants config, nonce=%u", config_nonce); handleStartConfig(); break; case meshtastic_ToRadio_disconnect_tag: - LOG_INFO("Disconnecting from phone\n"); + LOG_INFO("Disconnecting from phone"); close(); break; case meshtastic_ToRadio_xmodemPacket_tag: - LOG_INFO("Got xmodem packet\n"); + LOG_INFO("Got xmodem packet"); #ifdef FSCom xModem.handlePacket(toRadioScratch.xmodemPacket); #endif break; #if !MESHTASTIC_EXCLUDE_MQTT case meshtastic_ToRadio_mqttClientProxyMessage_tag: - LOG_INFO("Got MqttClientProxy message\n"); + LOG_INFO("Got MqttClientProxy message"); if (mqtt && moduleConfig.mqtt.proxy_to_client_enabled && moduleConfig.mqtt.enabled && (channels.anyMqttEnabled() || moduleConfig.mqtt.map_reporting_enabled)) { mqtt->onClientProxyReceive(toRadioScratch.mqttClientProxyMessage); } else { LOG_WARN("MqttClientProxy received but proxy is not enabled, no channels have up/downlink, or map reporting " - "not enabled\n"); + "not enabled"); } break; #endif case meshtastic_ToRadio_heartbeat_tag: - LOG_DEBUG("Got client heartbeat\n"); + LOG_DEBUG("Got client heartbeat"); break; default: // Ignore nop messages - // LOG_DEBUG("Error: unexpected ToRadio variant\n"); + // LOG_DEBUG("Error: unexpected ToRadio variant"); break; } } else { - LOG_ERROR("Error: ignoring malformed toradio\n"); + LOG_ERROR("Error: ignoring malformed toradio"); } return false; @@ -179,7 +179,7 @@ bool PhoneAPI::handleToRadio(const uint8_t *buf, size_t bufLength) size_t PhoneAPI::getFromRadio(uint8_t *buf) { if (!available()) { - // LOG_DEBUG("getFromRadio=not available\n"); + // LOG_DEBUG("getFromRadio=not available"); return 0; } // In case we send a FromRadio packet @@ -188,11 +188,11 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // Advance states as needed switch (state) { case STATE_SEND_NOTHING: - LOG_INFO("getFromRadio=STATE_SEND_NOTHING\n"); + LOG_INFO("getFromRadio=STATE_SEND_NOTHING"); break; case STATE_SEND_MY_INFO: - LOG_INFO("getFromRadio=STATE_SEND_MY_INFO\n"); + LOG_INFO("getFromRadio=STATE_SEND_MY_INFO"); // 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. fromRadioScratch.which_payload_variant = meshtastic_FromRadio_my_info_tag; @@ -203,7 +203,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_OWN_NODEINFO: { - LOG_INFO("getFromRadio=STATE_SEND_OWN_NODEINFO\n"); + LOG_INFO("getFromRadio=STATE_SEND_OWN_NODEINFO"); auto us = nodeDB->readNextMeshNode(readIndex); if (us) { nodeInfoForPhone = TypeConversions::ConvertToNodeInfo(us); @@ -219,14 +219,14 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) } case STATE_SEND_METADATA: - LOG_INFO("getFromRadio=STATE_SEND_METADATA\n"); + LOG_INFO("getFromRadio=STATE_SEND_METADATA"); fromRadioScratch.which_payload_variant = meshtastic_FromRadio_metadata_tag; fromRadioScratch.metadata = getDeviceMetadata(); state = STATE_SEND_CHANNELS; break; case STATE_SEND_CHANNELS: - LOG_INFO("getFromRadio=STATE_SEND_CHANNELS\n"); + LOG_INFO("getFromRadio=STATE_SEND_CHANNELS"); fromRadioScratch.which_payload_variant = meshtastic_FromRadio_channel_tag; fromRadioScratch.channel = channels.getByIndex(config_state); config_state++; @@ -238,7 +238,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_CONFIG: - LOG_INFO("getFromRadio=STATE_SEND_CONFIG\n"); + LOG_INFO("getFromRadio=STATE_SEND_CONFIG"); fromRadioScratch.which_payload_variant = meshtastic_FromRadio_config_tag; switch (config_state) { case meshtastic_Config_device_tag: @@ -278,7 +278,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) fromRadioScratch.config.which_payload_variant = meshtastic_Config_sessionkey_tag; break; default: - LOG_ERROR("Unknown config type %d\n", config_state); + LOG_ERROR("Unknown config type %d", config_state); } // NOTE: The phone app needs to know the ls_secs value so it can properly expect sleep behavior. // So even if we internally use 0 to represent 'use default' we still need to send the value we are @@ -293,7 +293,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_MODULECONFIG: - LOG_INFO("getFromRadio=STATE_SEND_MODULECONFIG\n"); + LOG_INFO("getFromRadio=STATE_SEND_MODULECONFIG"); fromRadioScratch.which_payload_variant = meshtastic_FromRadio_moduleConfig_tag; switch (config_state) { case meshtastic_ModuleConfig_mqtt_tag: @@ -349,7 +349,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) fromRadioScratch.moduleConfig.payload_variant.paxcounter = moduleConfig.paxcounter; break; default: - LOG_ERROR("Unknown module config type %d\n", config_state); + LOG_ERROR("Unknown module config type %d", config_state); } config_state++; @@ -362,16 +362,16 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; case STATE_SEND_OTHER_NODEINFOS: { - LOG_INFO("getFromRadio=STATE_SEND_OTHER_NODEINFOS\n"); + LOG_INFO("getFromRadio=STATE_SEND_OTHER_NODEINFOS"); if (nodeInfoForPhone.num != 0) { - LOG_INFO("nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s\n", nodeInfoForPhone.num, nodeInfoForPhone.last_heard, + LOG_INFO("nodeinfo: num=0x%x, lastseen=%u, id=%s, name=%s", nodeInfoForPhone.num, nodeInfoForPhone.last_heard, nodeInfoForPhone.user.id, nodeInfoForPhone.user.long_name); fromRadioScratch.which_payload_variant = meshtastic_FromRadio_node_info_tag; fromRadioScratch.node_info = nodeInfoForPhone; // Stay in current state until done sending nodeinfos nodeInfoForPhone.num = 0; // We just consumed a nodeinfo, will need a new one next time } else { - LOG_INFO("Done sending nodeinfos\n"); + LOG_INFO("Done sending nodeinfos"); state = STATE_SEND_FILEMANIFEST; // Go ahead and send that ID right now return getFromRadio(buf); @@ -380,7 +380,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) } case STATE_SEND_FILEMANIFEST: { - LOG_INFO("getFromRadio=STATE_SEND_FILEMANIFEST\n"); + LOG_INFO("getFromRadio=STATE_SEND_FILEMANIFEST"); // last element if (config_state == filesManifest.size()) { // also handles an empty filesManifest config_state = 0; @@ -390,7 +390,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) } else { fromRadioScratch.which_payload_variant = meshtastic_FromRadio_fileInfo_tag; fromRadioScratch.fileInfo = filesManifest.at(config_state); - LOG_DEBUG("File: %s (%d) bytes\n", fromRadioScratch.fileInfo.file_name, fromRadioScratch.fileInfo.size_bytes); + LOG_DEBUG("File: %s (%d) bytes", fromRadioScratch.fileInfo.file_name, fromRadioScratch.fileInfo.size_bytes); config_state++; } break; @@ -403,7 +403,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) case STATE_SEND_PACKETS: pauseBluetoothLogging = false; // Do we have a message from the mesh or packet from the local device? - LOG_INFO("getFromRadio=STATE_SEND_PACKETS\n"); + LOG_INFO("getFromRadio=STATE_SEND_PACKETS"); if (queueStatusPacketForPhone) { fromRadioScratch.which_payload_variant = meshtastic_FromRadio_queueStatus_tag; fromRadioScratch.queueStatus = *queueStatusPacketForPhone; @@ -431,7 +431,7 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) break; default: - LOG_ERROR("getFromRadio unexpected state %d\n", state); + LOG_ERROR("getFromRadio unexpected state %d", state); } // Do we have a message from the mesh? @@ -441,17 +441,17 @@ size_t PhoneAPI::getFromRadio(uint8_t *buf) // VERY IMPORTANT to not print debug messages while writing to fromRadioScratch - because we use that same buffer // for logging (when we are encapsulating with protobufs) - // LOG_DEBUG("encoding toPhone packet to phone variant=%d, %d bytes\n", fromRadioScratch.which_payload_variant, numbytes); + // LOG_DEBUG("encoding toPhone packet to phone variant=%d, %d bytes", fromRadioScratch.which_payload_variant, numbytes); return numbytes; } - LOG_DEBUG("no FromRadio packet available\n"); + LOG_DEBUG("no FromRadio packet available"); return 0; } void PhoneAPI::sendConfigComplete() { - LOG_INFO("getFromRadio=STATE_SEND_COMPLETE_ID\n"); + LOG_INFO("getFromRadio=STATE_SEND_COMPLETE_ID"); fromRadioScratch.which_payload_variant = meshtastic_FromRadio_config_complete_id_tag; fromRadioScratch.config_complete_id = config_nonce; config_nonce = 0; @@ -551,11 +551,11 @@ bool PhoneAPI::available() if (!packetForPhone) packetForPhone = service->getForPhone(); hasPacket = !!packetForPhone; - // LOG_DEBUG("available hasPacket=%d\n", hasPacket); + // LOG_DEBUG("available hasPacket=%d", hasPacket); return hasPacket; } default: - LOG_ERROR("PhoneAPI::available unexpected state %d\n", state); + LOG_ERROR("PhoneAPI::available unexpected state %d", state); } return false; @@ -597,20 +597,20 @@ bool PhoneAPI::handleToRadioPacket(meshtastic_MeshPacket &p) printPacket("PACKET FROM PHONE", &p); if (p.id > 0 && wasSeenRecently(p.id)) { - LOG_DEBUG("Ignoring packet from phone, already seen recently\n"); + LOG_DEBUG("Ignoring packet from phone, already seen recently"); return false; } if (p.decoded.portnum == meshtastic_PortNum_TRACEROUTE_APP && lastPortNumToRadio[p.decoded.portnum] && Throttle::isWithinTimespanMs(lastPortNumToRadio[p.decoded.portnum], THIRTY_SECONDS_MS)) { - LOG_WARN("Rate limiting portnum %d\n", p.decoded.portnum); + LOG_WARN("Rate limiting portnum %d", p.decoded.portnum); sendNotification(meshtastic_LogRecord_Level_WARNING, p.id, "TraceRoute can only be sent once every 30 seconds"); meshtastic_QueueStatus qs = router->getQueueStatus(); service->sendQueueStatusToPhone(qs, 0, p.id); return false; } else if (p.decoded.portnum == meshtastic_PortNum_POSITION_APP && lastPortNumToRadio[p.decoded.portnum] && Throttle::isWithinTimespanMs(lastPortNumToRadio[p.decoded.portnum], FIVE_SECONDS_MS)) { - LOG_WARN("Rate limiting portnum %d\n", p.decoded.portnum); + LOG_WARN("Rate limiting portnum %d", p.decoded.portnum); meshtastic_QueueStatus qs = router->getQueueStatus(); service->sendQueueStatusToPhone(qs, 0, p.id); // FIXME: Figure out why this continues to happen @@ -629,10 +629,10 @@ int PhoneAPI::onNotify(uint32_t newValue) // doesn't call this from idle) if (state == STATE_SEND_PACKETS) { - LOG_INFO("Telling client we have new packets %u\n", newValue); + LOG_INFO("Telling client we have new packets %u", newValue); onNowHasData(newValue); } else { - LOG_DEBUG("(Client not yet interested in packets)\n"); + LOG_DEBUG("(Client not yet interested in packets)"); } return timeout ? -1 : 0; // If we timed out, MeshService should stop iterating through observers as we just removed one diff --git a/src/mesh/ProtobufModule.h b/src/mesh/ProtobufModule.h index e4d4e5c098..4ddac9a0d7 100644 --- a/src/mesh/ProtobufModule.h +++ b/src/mesh/ProtobufModule.h @@ -47,7 +47,7 @@ template class ProtobufModule : protected SinglePortModule p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), fields, &payload); - // LOG_DEBUG("did encode\n"); + // LOG_DEBUG("did encode"); return p; } @@ -82,7 +82,7 @@ template class ProtobufModule : protected SinglePortModule // it would be better to update even if the message was destined to others. auto &p = mp.decoded; - LOG_INFO("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d\n", name, mp.from, mp.id, p.portnum, p.payload.size); + LOG_INFO("Received %s from=0x%0x, id=0x%x, portnum=%d, payloadlen=%d", name, mp.from, mp.id, p.portnum, p.payload.size); T scratch; T *decoded = NULL; @@ -91,7 +91,7 @@ template class ProtobufModule : protected SinglePortModule if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, fields, &scratch)) { decoded = &scratch; } else { - LOG_ERROR("Error decoding protobuf module!\n"); + LOG_ERROR("Error decoding protobuf module!"); // if we can't decode it, nobody can process it! return ProcessMessage::STOP; } @@ -112,7 +112,7 @@ template class ProtobufModule : protected SinglePortModule if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, fields, &scratch)) { decoded = &scratch; } else { - LOG_ERROR("Error decoding protobuf module!\n"); + LOG_ERROR("Error decoding protobuf module!"); // if we can't decode it, nobody can process it! return; } diff --git a/src/mesh/RF95Interface.cpp b/src/mesh/RF95Interface.cpp index 581fd90342..db56659bd6 100644 --- a/src/mesh/RF95Interface.cpp +++ b/src/mesh/RF95Interface.cpp @@ -82,7 +82,7 @@ RF95Interface::RF95Interface(LockingArduinoHal *hal, RADIOLIB_PIN_TYPE cs, RADIO RADIOLIB_PIN_TYPE busy) : RadioLibInterface(hal, cs, irq, rst, busy) { - LOG_DEBUG("RF95Interface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); + LOG_DEBUG("RF95Interface(cs=%d, irq=%d, rst=%d, busy=%d)", cs, irq, rst, busy); } /** Some boards require GPIO control of tx vs rx paths */ @@ -176,12 +176,12 @@ bool RF95Interface::init() setTransmitEnable(false); int res = lora->begin(getFreq(), bw, sf, cr, syncWord, power, 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("RF95 init result %d", res); + LOG_INFO("Frequency set to %f", getFreq()); + LOG_INFO("Bandwidth set to %f", bw); + LOG_INFO("Power output set to %d", power); #if defined(RADIOMASTER_900_BANDIT_NANO) || defined(RADIOMASTER_900_BANDIT) - LOG_INFO("DAC output set to %d\n", powerDAC); + LOG_INFO("DAC output set to %d", powerDAC); #endif if (res == RADIOLIB_ERR_NONE) @@ -220,17 +220,17 @@ bool RF95Interface::reconfigure() err = lora->setSyncWord(syncWord); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("RF95 setSyncWord %s%d\n", radioLibErr, err); + LOG_ERROR("RF95 setSyncWord %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora->setCurrentLimit(currentLimit); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("RF95 setCurrentLimit %s%d\n", radioLibErr, err); + LOG_ERROR("RF95 setCurrentLimit %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora->setPreambleLength(preambleLength); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR(" RF95 setPreambleLength %s%d\n", radioLibErr, err); + LOG_ERROR(" RF95 setPreambleLength %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora->setFrequency(getFreq()); @@ -266,7 +266,7 @@ void RF95Interface::setStandby() { int err = lora->standby(); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("RF95 standby %s%d\n", radioLibErr, err); + LOG_ERROR("RF95 standby %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); isReceiving = false; // If we were receiving, not any more @@ -290,7 +290,7 @@ void RF95Interface::startReceive() setStandby(); int err = lora->startReceive(); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("RF95 startReceive %s%d\n", radioLibErr, err); + LOG_ERROR("RF95 startReceive %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); isReceiving = true; @@ -308,14 +308,14 @@ bool RF95Interface::isChannelActive() result = lora->scanChannel(); if (result == RADIOLIB_PREAMBLE_DETECTED) { - // LOG_DEBUG("Channel is busy!\n"); + // LOG_DEBUG("Channel is busy!"); return true; } if (result != RADIOLIB_CHANNEL_FREE) - LOG_ERROR("RF95 isChannelActive %s%d\n", radioLibErr, result); + LOG_ERROR("RF95 isChannelActive %s%d", radioLibErr, result); assert(result != RADIOLIB_ERR_WRONG_MODEM); - // LOG_DEBUG("Channel is free!\n"); + // LOG_DEBUG("Channel is free!"); return false; } diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 7501852f29..f51c9bcb95 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -170,11 +170,11 @@ void initRegion() #ifdef REGULATORY_LORA_REGIONCODE for (; r->code != meshtastic_Config_LoRaConfig_RegionCode_UNSET && r->code != REGULATORY_LORA_REGIONCODE; r++) ; - LOG_INFO("Wanted region %d, regulatory override to %s\n", config.lora.region, r->name); + LOG_INFO("Wanted region %d, regulatory override to %s", config.lora.region, r->name); #else for (; r->code != meshtastic_Config_LoRaConfig_RegionCode_UNSET && r->code != config.lora.region; r++) ; - LOG_INFO("Wanted region %d, using %s\n", config.lora.region, r->name); + LOG_INFO("Wanted region %d, using %s", config.lora.region, r->name); #endif myRegion = r; } @@ -234,7 +234,7 @@ uint32_t RadioInterface::getRetransmissionMsec(const meshtastic_MeshPacket *p) 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); + // LOG_DEBUG("Waiting for flooding message with airtime %d and slotTime is %d", 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 client with SNR at half the range @@ -250,7 +250,7 @@ uint32_t RadioInterface::getTxDelayMsec() current channel utilization. */ float channelUtil = airTime->channelUtilizationPercent(); uint8_t CWsize = map(channelUtil, 0, 100, CWmin, CWmax); - // LOG_DEBUG("Current channel utilization is %f so setting CWsize to %d\n", channelUtil, CWsize); + // LOG_DEBUG("Current channel utilization is %f so setting CWsize to %d", channelUtil, CWsize); return random(0, pow(2, CWsize)) * slotTimeMsec; } @@ -267,15 +267,15 @@ uint32_t RadioInterface::getTxDelayMsecWeighted(float snr) // low SNR = small CW size (Short Delay) 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); + // LOG_DEBUG("rx_snr of %f so setting CWsize to:%d", snr, CWsize); if (config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER || 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); + LOG_DEBUG("rx_snr found in packet. As a router, setting tx delay:%d", delay); } else { // offset the maximum delay for routers: (2 * CWmax * slotTimeMsec) delay = (2 * CWmax * slotTimeMsec) + random(0, pow(2, CWsize)) * slotTimeMsec; - LOG_DEBUG("rx_snr found in packet. Setting tx delay:%d\n", delay); + LOG_DEBUG("rx_snr found in packet. Setting tx delay:%d", delay); } return delay; @@ -329,7 +329,7 @@ void printPacket(const char *prefix, const meshtastic_MeshPacket *p) out += DEBUG_PORT.mt_sprintf(" priority=%d", p->priority); out += ")"; - LOG_DEBUG("%s\n", out.c_str()); + LOG_DEBUG("%s", out.c_str()); #endif } @@ -346,7 +346,7 @@ bool RadioInterface::reconfigure() bool RadioInterface::init() { - LOG_INFO("Starting meshradio init...\n"); + LOG_INFO("Starting meshradio init..."); configChangedObserver.observe(&service->configChanged); preflightSleepObserver.observe(&preflightSleep); @@ -494,8 +494,7 @@ void RadioInterface::applyModemConfig() } if ((myRegion->freqEnd - myRegion->freqStart) < bw / 1000) { - static const char *err_string = - "Regional frequency range is smaller than bandwidth. Falling back to default preset.\n"; + static const char *err_string = "Regional frequency range is smaller than bandwidth. Falling back to default preset."; LOG_ERROR(err_string); RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_INVALID_RADIO_SETTING); @@ -556,15 +555,15 @@ void RadioInterface::applyModemConfig() preambleTimeMsec = getPacketTime((uint32_t)0); maxPacketTimeMsec = getPacketTime(meshtastic_Constants_DATA_PAYLOAD_LEN + sizeof(PacketHeader)); - 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, + LOG_INFO("Radio freq=%.3f, config.lora.frequency_offset=%.3f", freq, loraConfig.frequency_offset); + LOG_INFO("Set radio: region=%s, name=%s, config=%u, ch=%d, power=%d", myRegion->name, channelName, loraConfig.modem_preset, channel_num, power); - LOG_INFO("myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f MHz)\n", myRegion->freqStart, myRegion->freqEnd, + LOG_INFO("myRegion->freqStart -> myRegion->freqEnd: %f -> %f (%f MHz)", myRegion->freqStart, myRegion->freqEnd, myRegion->freqEnd - myRegion->freqStart); - LOG_INFO("numChannels: %d x %.3fkHz\n", numChannels, bw); - LOG_INFO("channel_num: %d\n", channel_num + 1); - LOG_INFO("frequency: %f\n", getFreq()); - LOG_INFO("Slot time: %u msec\n", slotTimeMsec); + LOG_INFO("numChannels: %d x %.3fkHz", numChannels, bw); + LOG_INFO("channel_num: %d", channel_num + 1); + LOG_INFO("frequency: %f", getFreq()); + LOG_INFO("Slot time: %u msec", slotTimeMsec); } /** @@ -579,11 +578,11 @@ void RadioInterface::limitPower() maxPower = myRegion->powerLimit; if ((power > maxPower) && !devicestate.owner.is_licensed) { - LOG_INFO("Lowering transmit power because of regulatory limits\n"); + LOG_INFO("Lowering transmit power because of regulatory limits"); power = maxPower; } - LOG_INFO("Set radio: final power level=%d\n", power); + LOG_INFO("Set radio: final power level=%d", power); } void RadioInterface::deliverToReceiver(meshtastic_MeshPacket *p) @@ -599,7 +598,7 @@ 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()); + // LOG_DEBUG("sending queued packet on mesh (txGood=%d,rxGood=%d,rxBad=%d)", rf95.txGood(), rf95.rxGood(), rf95.rxBad()); assert(p->which_payload_variant == meshtastic_MeshPacket_encrypted_tag); // It should have already been encoded by now lastTxStart = millis(); @@ -611,7 +610,7 @@ size_t RadioInterface::beginSending(meshtastic_MeshPacket *p) radioBuffer.header.next_hop = 0; // *** For future use *** radioBuffer.header.relay_node = 0; // *** For future use *** if (p->hop_limit > HOP_MAX) { - LOG_WARN("hop limit %d is too high, setting to %d\n", p->hop_limit, HOP_RELIABLE); + LOG_WARN("hop limit %d is too high, setting to %d", p->hop_limit, HOP_RELIABLE); p->hop_limit = HOP_RELIABLE; } radioBuffer.header.flags = diff --git a/src/mesh/RadioInterface.h b/src/mesh/RadioInterface.h index 6df51ce1a9..89a4c70879 100644 --- a/src/mesh/RadioInterface.h +++ b/src/mesh/RadioInterface.h @@ -55,7 +55,7 @@ typedef struct { PacketHeader header; /** The payload, of maximum length minus the header, aligned just to be sure */ - uint8_t payload[MAX_LORA_PAYLOAD_LEN + 1 - sizeof(PacketHeader)] __attribute__ ((__aligned__)); + uint8_t payload[MAX_LORA_PAYLOAD_LEN + 1 - sizeof(PacketHeader)] __attribute__((__aligned__)); } RadioBuffer; @@ -105,7 +105,7 @@ class RadioInterface /** * A temporary buffer used for sending/receiving packets, sized to hold the biggest buffer we might need * */ - RadioBuffer radioBuffer __attribute__ ((__aligned__)); + RadioBuffer radioBuffer __attribute__((__aligned__)); /** * Enqueue a received packet for the registered receiver */ diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index 8188260180..f44d50d363 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -111,18 +111,18 @@ bool RadioLibInterface::canSendImmediately() if (busyTx || busyRx) { if (busyTx) { - LOG_WARN("Can not send yet, busyTx\n"); + LOG_WARN("Can not send yet, busyTx"); } // If we've been trying to send the same packet more than one minute and we haven't gotten a // TX IRQ from the radio, the radio is probably broken. if (busyTx && !Throttle::isWithinTimespanMs(lastTxStart, 60000)) { - LOG_ERROR("Hardware Failure! busyTx for more than 60s\n"); + LOG_ERROR("Hardware Failure! busyTx for more than 60s"); RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_TRANSMIT_FAILED); // reboot in 5 seconds when this condition occurs. rebootAtMsec = lastTxStart + 65000; } if (busyRx) { - LOG_WARN("Can not send yet, busyRx\n"); + LOG_WARN("Can not send yet, busyRx"); } return false; } else @@ -139,12 +139,12 @@ bool RadioLibInterface::receiveDetected(uint16_t irq, ulong syncWordHeaderValidF } else if (!Throttle::isWithinTimespanMs(activeReceiveStart, 2 * preambleTimeMsec) && !(irq & syncWordHeaderValidFlag)) { // The HEADER_VALID flag should be set by now if it was really a packet, so ignore PREAMBLE_DETECTED flag activeReceiveStart = 0; - LOG_DEBUG("Ignore false preamble detection.\n"); + LOG_DEBUG("Ignore false preamble detection."); return false; } else if (!Throttle::isWithinTimespanMs(activeReceiveStart, maxPacketTimeMsec)) { // We should have gotten an RX_DONE IRQ by now if it was really a packet, so ignore HEADER_VALID flag activeReceiveStart = 0; - LOG_DEBUG("Ignore false header detection.\n"); + LOG_DEBUG("Ignore false header detection."); return false; } } @@ -161,13 +161,13 @@ ErrorCode RadioLibInterface::send(meshtastic_MeshPacket *p) if (config.lora.region != meshtastic_Config_LoRaConfig_RegionCode_UNSET) { if (disabled || !config.lora.tx_enabled) { - LOG_WARN("send - !config.lora.tx_enabled\n"); + LOG_WARN("send - !config.lora.tx_enabled"); packetPool.release(p); return ERRNO_DISABLED; } } else { - LOG_WARN("send - lora tx disabled because RegionCode_Unset\n"); + LOG_WARN("send - lora tx disabled because RegionCode_Unset"); packetPool.release(p); return ERRNO_DISABLED; } @@ -175,7 +175,7 @@ ErrorCode RadioLibInterface::send(meshtastic_MeshPacket *p) #else if (disabled || !config.lora.tx_enabled) { - LOG_WARN("send - !config.lora.tx_enabled\n"); + LOG_WARN("send - !config.lora.tx_enabled"); packetPool.release(p); return ERRNO_DISABLED; } @@ -186,7 +186,7 @@ ErrorCode RadioLibInterface::send(meshtastic_MeshPacket *p) #ifndef LORA_DISABLE_SENDING printPacket("enqueuing for send", p); - LOG_DEBUG("txGood=%d,txRelay=%d,rxGood=%d,rxBad=%d\n", txGood, txRelay, rxGood, rxBad); + LOG_DEBUG("txGood=%d,txRelay=%d,rxGood=%d,rxBad=%d", txGood, txRelay, 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 @@ -196,7 +196,7 @@ ErrorCode RadioLibInterface::send(meshtastic_MeshPacket *p) // 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"); + // LOG_DEBUG("Set random delay before transmitting."); setTransmitDelay(); return res; @@ -221,7 +221,7 @@ 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); + LOG_DEBUG("radio wait to sleep, txEmpty=%d", res); } return res; } @@ -234,7 +234,7 @@ bool RadioLibInterface::cancelSending(NodeNum from, PacketId id) packetPool.release(p); // free the packet we just removed bool result = (p != NULL); - LOG_DEBUG("cancelSending id=0x%x, removed=%d\n", id, result); + LOG_DEBUG("cancelSending id=0x%x, removed=%d", id, result); return result; } @@ -251,27 +251,27 @@ void RadioLibInterface::onNotify(uint32_t notification) case ISR_TX: handleTransmitInterrupt(); startReceive(); - // LOG_DEBUG("tx complete - starting timer\n"); + // LOG_DEBUG("tx complete - starting timer"); startTransmitTimer(); break; case ISR_RX: handleReceiveInterrupt(); startReceive(); - // LOG_DEBUG("rx complete - starting timer\n"); + // LOG_DEBUG("rx complete - starting timer"); startTransmitTimer(); break; case TRANSMIT_DELAY_COMPLETED: - // LOG_DEBUG("delay done\n"); + // LOG_DEBUG("delay done"); // 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"); + // LOG_DEBUG("Currently Rx/Tx-ing: set random delay"); 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, try receiving first.\n"); + // LOG_DEBUG("Channel is active, try receiving first."); startReceive(); // try receiving this packet, afterwards we'll be trying to transmit again setTransmitDelay(); } else { @@ -286,7 +286,7 @@ void RadioLibInterface::onNotify(uint32_t notification) } } } else { - // LOG_DEBUG("done with txqueue\n"); + // LOG_DEBUG("done with txqueue"); } break; default: @@ -309,7 +309,7 @@ void RadioLibInterface::setTransmitDelay() 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); + LOG_DEBUG("rx_snr found. hop_limit:%d rx_snr:%f", p->hop_limit, p->rx_snr); startTransmitTimerSNR(p->rx_snr); } } @@ -319,7 +319,7 @@ 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); + // LOG_DEBUG("xmit timer %d", delay); notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable } } @@ -329,14 +329,14 @@ 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); + // LOG_DEBUG("xmit timer %d", delay); notifyLater(delay, TRANSMIT_DELAY_COMPLETED, false); // This will implicitly enable } } void RadioLibInterface::handleTransmitInterrupt() { - // LOG_DEBUG("handling lora TX interrupt\n"); + // LOG_DEBUG("handling lora TX interrupt"); // This can be null if we forced the device to enter standby mode. In that case // ignore the transmit interrupt if (sendingPacket) @@ -359,7 +359,7 @@ void RadioLibInterface::completeSending() // We are done sending that packet, release it packetPool.release(p); - // LOG_DEBUG("Done with send\n"); + // LOG_DEBUG("Done with send"); } } @@ -370,7 +370,7 @@ void RadioLibInterface::handleReceiveInterrupt() // 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_ERROR("handleReceiveInterrupt called when not in receive mode, which shouldn't happen.\n"); + LOG_ERROR("handleReceiveInterrupt called when not in receive mode, which shouldn't happen."); return; } @@ -383,7 +383,7 @@ void RadioLibInterface::handleReceiveInterrupt() #ifndef DISABLE_WELCOME_UNSET if (config.lora.region == meshtastic_Config_LoRaConfig_RegionCode_UNSET) { - LOG_WARN("recv - lora rx disabled because RegionCode_Unset\n"); + LOG_WARN("recv - lora rx disabled because RegionCode_Unset"); airTime->logAirtime(RX_ALL_LOG, xmitMsec); return; } @@ -391,7 +391,7 @@ void RadioLibInterface::handleReceiveInterrupt() int state = iface->readData((uint8_t *)&radioBuffer, length); if (state != RADIOLIB_ERR_NONE) { - LOG_ERROR("ignoring received packet due to error=%d\n", state); + LOG_ERROR("ignoring received packet due to error=%d", state); rxBad++; airTime->logAirtime(RX_ALL_LOG, xmitMsec); @@ -402,14 +402,14 @@ void RadioLibInterface::handleReceiveInterrupt() // check for short packets if (payloadLen < 0) { - LOG_WARN("ignoring received packet too short\n"); + LOG_WARN("ignoring received packet too short"); rxBad++; airTime->logAirtime(RX_ALL_LOG, xmitMsec); } else { rxGood++; // altered packet with "from == 0" can do Remote Node Administration without permission if (radioBuffer.header.from == 0) { - LOG_WARN("ignoring received packet without sender\n"); + LOG_WARN("ignoring received packet without sender"); return; } @@ -467,8 +467,11 @@ void RadioLibInterface::setStandby() void RadioLibInterface::startSend(meshtastic_MeshPacket *txp) { printPacket("Starting low level send", txp); - if (disabled || !config.lora.tx_enabled) { - LOG_WARN("Drop Tx packet because LoRa Tx disabled\n"); + if (txp->to == NODENUM_BROADCAST_NO_LORA) { + LOG_DEBUG("Drop Tx packet because dest is broadcast no-lora"); + packetPool.release(txp); + } else if (disabled || !config.lora.tx_enabled) { + LOG_WARN("Drop Tx packet because LoRa Tx disabled"); packetPool.release(txp); } else { configHardwareForSend(); // must be after setStandby @@ -477,7 +480,7 @@ void RadioLibInterface::startSend(meshtastic_MeshPacket *txp) int res = iface->startTransmit((uint8_t *)&radioBuffer, numbytes); if (res != RADIOLIB_ERR_NONE) { - LOG_ERROR("startTransmit failed, error=%d\n", res); + LOG_ERROR("startTransmit failed, error=%d", res); RECORD_CRITICALERROR(meshtastic_CriticalErrorCode_RADIO_SPI_BUG); // This send failed, but make sure to 'complete' it properly diff --git a/src/mesh/RadioLibInterface.h b/src/mesh/RadioLibInterface.h index 673f53a322..353176a5ba 100644 --- a/src/mesh/RadioLibInterface.h +++ b/src/mesh/RadioLibInterface.h @@ -197,5 +197,5 @@ class RadioLibInterface : public RadioInterface, protected concurrency::Notified */ virtual void setStandby(); - const char *radioLibErr = "RadioLib err=\n"; + const char *radioLibErr = "RadioLib err="; }; \ No newline at end of file diff --git a/src/mesh/RadioLibRF95.cpp b/src/mesh/RadioLibRF95.cpp index fe9bbdc93f..a34c0605f9 100644 --- a/src/mesh/RadioLibRF95.cpp +++ b/src/mesh/RadioLibRF95.cpp @@ -18,8 +18,8 @@ int16_t RadioLibRF95::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_ // current limit was removed from module' ctor // override default value (60 mA) state = setCurrentLimit(currentLimit); - LOG_DEBUG("Current limit set to %f\n", currentLimit); - LOG_DEBUG("Current limit set result %d\n", state); + LOG_DEBUG("Current limit set to %f", currentLimit); + LOG_DEBUG("Current limit set result %d", state); // configure settings not accessible by API // state = config(); @@ -73,7 +73,7 @@ bool RadioLibRF95::isReceiving() { // 0x0b == Look for header info valid, signal synchronized or signal detected uint8_t reg = readReg(RADIOLIB_SX127X_REG_MODEM_STAT); - // Serial.printf("reg %x\n", reg); + // Serial.printf("reg %x", reg); return (reg & (RH_RF95_MODEM_STATUS_SIGNAL_DETECTED | RH_RF95_MODEM_STATUS_SIGNAL_SYNCHRONIZED | RH_RF95_MODEM_STATUS_HEADER_INFO_VALID)) != 0; } diff --git a/src/mesh/ReliableRouter.cpp b/src/mesh/ReliableRouter.cpp index fa05e79731..a2e09362dd 100644 --- a/src/mesh/ReliableRouter.cpp +++ b/src/mesh/ReliableRouter.cpp @@ -53,14 +53,14 @@ bool ReliableRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) auto key = GlobalPacketId(getFrom(p), p->id); auto old = findPendingPacket(key); if (old) { - LOG_DEBUG("generating implicit ack\n"); + LOG_DEBUG("generating implicit ack"); // 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(meshtastic_Routing_Error_NONE, getFrom(p), p->id, old->packet->channel); stopRetransmission(key); } else { - LOG_DEBUG("didn't find pending packet\n"); + LOG_DEBUG("didn't find pending packet"); } } @@ -79,7 +79,7 @@ bool ReliableRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) * flooding this ACK back to the original sender already adds redundancy. */ bool isRepeated = p->hop_start == 0 ? (p->hop_limit == HOP_RELIABLE) : (p->hop_start == p->hop_limit); if (wasSeenRecently(p, false) && isRepeated && !MeshModule::currentReply && !isToUs(p)) { - LOG_DEBUG("Resending implicit ack for a repeated floodmsg\n"); + LOG_DEBUG("Resending implicit ack for a repeated floodmsg"); meshtastic_MeshPacket *tosend = packetPool.allocCopy(*p); tosend->hop_limit--; // bump down the hop count Router::send(tosend); @@ -105,12 +105,12 @@ void ReliableRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtas if (isToUs(p)) { // ignore ack/nak/want_ack packets that are not address to us (we only handle 0 hop reliability) if (p->want_ack) { if (MeshModule::currentReply) { - LOG_DEBUG("Another module replied to this message, no need for 2nd ack\n"); + LOG_DEBUG("Another module replied to this message, no need for 2nd ack"); } else if (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { sendAckNak(meshtastic_Routing_Error_NONE, getFrom(p), p->id, p->channel, p->hop_start, p->hop_limit); } else if (p->which_payload_variant == meshtastic_MeshPacket_encrypted_tag && p->channel == 0 && (nodeDB->getMeshNode(p->from) == nullptr || nodeDB->getMeshNode(p->from)->user.public_key.size == 0)) { - LOG_INFO("PKI packet from unknown node, send PKI_UNKNOWN_PUBKEY\n"); + LOG_INFO("PKI packet from unknown node, send PKI_UNKNOWN_PUBKEY"); sendAckNak(meshtastic_Routing_Error_PKI_UNKNOWN_PUBKEY, getFrom(p), p->id, channels.getPrimaryIndex(), p->hop_start, p->hop_limit); } else { @@ -134,7 +134,7 @@ void ReliableRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtas // We intentionally don't check wasSeenRecently, because it is harmless to delete non existent retransmission records if (ackId || nakId) { - LOG_DEBUG("Received a %s for 0x%x, stopping retransmissions\n", ackId ? "ACK" : "NAK", ackId); + LOG_DEBUG("Received a %s for 0x%x, stopping retransmissions", ackId ? "ACK" : "NAK", ackId); if (ackId) { stopRetransmission(p->to, ackId); } else { @@ -227,15 +227,15 @@ int32_t ReliableRouter::doRetransmissions() // FIXME, handle 51 day rolloever here!!! if (p.nextTxMsec <= now) { 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, + LOG_DEBUG("Reliable send failed, returning a nak for fr=0x%x,to=0x%x,id=0x%x", p.packet->from, p.packet->to, p.packet->id); 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 } else { - LOG_DEBUG("Sending reliable retransmission fr=0x%x,to=0x%x,id=0x%x, tries left=%d\n", p.packet->from, - p.packet->to, p.packet->id, p.numRetransmissions); + LOG_DEBUG("Sending reliable retransmission fr=0x%x,to=0x%x,id=0x%x, tries left=%d", p.packet->from, p.packet->to, + p.packet->id, p.numRetransmissions); // Note: we call the superclass version because we don't want to have our version of send() add a new // retransmission record diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index b5732dee9a..84ae7bbb02 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -48,9 +48,9 @@ Router::Router() : concurrency::OSThread("Router"), fromRadioQueue(MAX_RX_FROMRA { // This is called pre main(), don't touch anything here, the following code is not safe - /* LOG_DEBUG("Size of NodeInfo %d\n", sizeof(NodeInfo)); - LOG_DEBUG("Size of SubPacket %d\n", sizeof(SubPacket)); - LOG_DEBUG("Size of MeshPacket %d\n", sizeof(MeshPacket)); */ + /* LOG_DEBUG("Size of NodeInfo %d", sizeof(NodeInfo)); + LOG_DEBUG("Size of SubPacket %d", sizeof(SubPacket)); + LOG_DEBUG("Size of MeshPacket %d", sizeof(MeshPacket)); */ fromRadioQueue.setReader(this); @@ -71,7 +71,7 @@ int32_t Router::runOnce() perhapsHandleReceived(mp); } - // LOG_DEBUG("sleeping forever!\n"); + // LOG_DEBUG("sleeping forever!"); return INT32_MAX; // Wait a long time - until we get woken for the message queue } @@ -104,14 +104,14 @@ PacketId generatePacketId() // pick a random initial sequence number at boot (to prevent repeated reboots always starting at 0) // Note: we mask the high order bit to ensure that we never pass a 'negative' number to random rollingPacketId = random(UINT32_MAX & 0x7fffffff); - LOG_DEBUG("Initial packet id %u\n", rollingPacketId); + LOG_DEBUG("Initial packet id %u", rollingPacketId); } rollingPacketId++; rollingPacketId &= ID_COUNTER_MASK; // Mask out the top 22 bits PacketId id = rollingPacketId | random(UINT32_MAX & 0x7fffffff) << 10; // top 22 bits - LOG_DEBUG("Partially randomized packet id %u\n", id); + LOG_DEBUG("Partially randomized packet id %u", id); return id; } @@ -141,14 +141,14 @@ void Router::sendAckNak(meshtastic_Routing_Error err, NodeNum to, PacketId idFro void Router::abortSendAndNak(meshtastic_Routing_Error err, meshtastic_MeshPacket *p) { - LOG_ERROR("Error=%d, returning NAK and dropping packet.\n", err); + LOG_ERROR("Error=%d, returning NAK and dropping packet.", err); sendAckNak(err, getFrom(p), p->id, p->channel); packetPool.release(p); } void Router::setReceivedMessage() { - // LOG_DEBUG("set interval to ASAP\n"); + // LOG_DEBUG("set interval to ASAP"); setInterval(0); // Run ASAP, so we can figure out our correct sleep time runASAP = true; } @@ -166,7 +166,7 @@ meshtastic_QueueStatus Router::getQueueStatus() ErrorCode Router::sendLocal(meshtastic_MeshPacket *p, RxSource src) { if (p->to == 0) { - LOG_ERROR("Packet received with to: of 0!\n"); + LOG_ERROR("Packet received with to: of 0!"); } // No need to deliver externally if the destination is the local node if (isToUs(p)) { @@ -181,7 +181,7 @@ ErrorCode Router::sendLocal(meshtastic_MeshPacket *p, RxSource src) } else { // If we are sending a broadcast, we also treat it as if we just received it ourself // this allows local apps (and PCs) to see broadcasts sourced locally - if (p->to == NODENUM_BROADCAST) { + if (isBroadcast(p->to)) { handleReceived(p, src); } @@ -189,7 +189,7 @@ ErrorCode Router::sendLocal(meshtastic_MeshPacket *p, RxSource src) meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(p->to); if (node && node->user.public_key.size == 0) { p->channel = node->channel; - LOG_DEBUG("localSend to channel %d\n", p->channel); + LOG_DEBUG("localSend to channel %d", p->channel); } } @@ -205,7 +205,7 @@ ErrorCode Router::sendLocal(meshtastic_MeshPacket *p, RxSource src) ErrorCode Router::send(meshtastic_MeshPacket *p) { if (isToUs(p)) { - LOG_ERROR("BUG! send() called with packet destined for local node!\n"); + LOG_ERROR("BUG! send() called with packet destined for local node!"); packetPool.release(p); return meshtastic_Routing_Error_BAD_REQUEST; } // should have already been handled by sendLocal @@ -216,7 +216,7 @@ ErrorCode Router::send(meshtastic_MeshPacket *p) if (hourlyTxPercent > myRegion->dutyCycle) { #ifdef DEBUG_PORT 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); + LOG_WARN("Duty cycle limit exceeded. Aborting send for now, you can send again in %d minutes.", silentMinutes); meshtastic_ClientNotification *cn = clientNotificationPool.allocZeroed(); cn->has_reply_id = true; cn->reply_id = p->id; @@ -240,7 +240,7 @@ ErrorCode Router::send(meshtastic_MeshPacket *p) // assert // Never set the want_ack flag on broadcast packets sent over the air. - if (p->to == NODENUM_BROADCAST) + if (isBroadcast(p->to)) p->want_ack = false; // Up until this point we might have been using 0 for the from address (if it started with the phone), but when we send over @@ -309,7 +309,7 @@ bool perhapsDecode(meshtastic_MeshPacket *p) if (config.device.rebroadcast_mode == meshtastic_Config_DeviceConfig_RebroadcastMode_KNOWN_ONLY && (nodeDB->getMeshNode(p->from) == NULL || !nodeDB->getMeshNode(p->from)->has_user)) { - LOG_DEBUG("Node 0x%x not in nodeDB-> Rebroadcast mode KNOWN_ONLY will ignore packet\n", p->from); + LOG_DEBUG("Node 0x%x not in nodeDB-> Rebroadcast mode KNOWN_ONLY will ignore packet", p->from); return false; } @@ -318,7 +318,7 @@ bool perhapsDecode(meshtastic_MeshPacket *p) size_t rawSize = p->encrypted.size; if (rawSize > sizeof(bytes)) { - LOG_ERROR("Packet too large to attempt decryption! (rawSize=%d > 256)\n", rawSize); + LOG_ERROR("Packet too large to attempt decryption! (rawSize=%d > 256)", rawSize); return false; } bool decrypted = false; @@ -328,30 +328,31 @@ bool perhapsDecode(meshtastic_MeshPacket *p) memcpy(ScratchEncrypted, p->encrypted.bytes, rawSize); #if !(MESHTASTIC_EXCLUDE_PKI) // Attempt PKI decryption first - if (p->channel == 0 && isToUs(p) && p->to > 0 && p->to != NODENUM_BROADCAST && nodeDB->getMeshNode(p->from) != nullptr && + if (p->channel == 0 && isToUs(p) && p->to > 0 && !isBroadcast(p->to) && nodeDB->getMeshNode(p->from) != nullptr && nodeDB->getMeshNode(p->from)->user.public_key.size > 0 && nodeDB->getMeshNode(p->to)->user.public_key.size > 0 && rawSize > MESHTASTIC_PKC_OVERHEAD) { - LOG_DEBUG("Attempting PKI decryption\n"); + LOG_DEBUG("Attempting PKI decryption"); - if (crypto->decryptCurve25519(p->from, p->id, rawSize, ScratchEncrypted, bytes)) { - LOG_INFO("PKI Decryption worked!\n"); + if (crypto->decryptCurve25519(p->from, nodeDB->getMeshNode(p->from)->user.public_key, p->id, rawSize, ScratchEncrypted, + bytes)) { + LOG_INFO("PKI Decryption worked!"); memset(&p->decoded, 0, sizeof(p->decoded)); rawSize -= MESHTASTIC_PKC_OVERHEAD; if (pb_decode_from_bytes(bytes, rawSize, &meshtastic_Data_msg, &p->decoded) && p->decoded.portnum != meshtastic_PortNum_UNKNOWN_APP) { decrypted = true; - LOG_INFO("Packet decrypted using PKI!\n"); + LOG_INFO("Packet decrypted using PKI!"); p->pki_encrypted = true; memcpy(&p->public_key.bytes, nodeDB->getMeshNode(p->from)->user.public_key.bytes, 32); p->public_key.size = 32; // memcpy(bytes, ScratchEncrypted, rawSize); // TODO: Rename the bytes buffers // chIndex = 8; } else { - LOG_ERROR("PKC Decrypted, but pb_decode failed!\n"); + LOG_ERROR("PKC Decrypted, but pb_decode failed!"); return false; } } else { - LOG_WARN("PKC decrypt attempted but failed!\n"); + LOG_WARN("PKC decrypt attempted but failed!"); } } #endif @@ -370,9 +371,9 @@ bool perhapsDecode(meshtastic_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, &meshtastic_Data_msg, &p->decoded)) { - LOG_ERROR("Invalid protobufs in received mesh packet id=0x%08x (bad psk?)!\n", p->id); + LOG_ERROR("Invalid protobufs in received mesh packet id=0x%08x (bad psk?)!", p->id); } else if (p->decoded.portnum == meshtastic_PortNum_UNKNOWN_APP) { - LOG_ERROR("Invalid portnum (bad psk?)!\n"); + LOG_ERROR("Invalid portnum (bad psk?)!"); } else { decrypted = true; break; @@ -399,7 +400,7 @@ bool perhapsDecode(meshtastic_MeshPacket *p) decompressed_len = unishox2_decompress_simple(compressed_in, p->decoded.payload.size, decompressed_out); - // LOG_DEBUG("\n\n**\n\nDecompressed length - %d \n", decompressed_len); + // LOG_DEBUG("**Decompressed length - %d ", decompressed_len); memcpy(p->decoded.payload.bytes, decompressed_out, decompressed_len); @@ -409,15 +410,15 @@ bool perhapsDecode(meshtastic_MeshPacket *p) printPacket("decoded message", p); #if ENABLE_JSON_LOGGING - LOG_TRACE("%s\n", MeshPacketSerializer::JsonSerialize(p, false).c_str()); + LOG_TRACE("%s", MeshPacketSerializer::JsonSerialize(p, false).c_str()); #elif ARCH_PORTDUINO if (settingsStrings[traceFilename] != "" || settingsMap[logoutputlevel] == level_trace) { - LOG_TRACE("%s\n", MeshPacketSerializer::JsonSerialize(p, false).c_str()); + LOG_TRACE("%s", MeshPacketSerializer::JsonSerialize(p, false).c_str()); } #endif return true; } else { - LOG_WARN("No suitable channel found for decoding, hash was 0x%x!\n", p->channel); + LOG_WARN("No suitable channel found for decoding, hash was 0x%x!", p->channel); return false; } } @@ -452,20 +453,20 @@ meshtastic_Routing_Error perhapsEncode(meshtastic_MeshPacket *p) int compressed_len; compressed_len = unishox2_compress_simple(original_payload, p->decoded.payload.size, compressed_out); - LOG_DEBUG("Original length - %d \n", p->decoded.payload.size); - LOG_DEBUG("Compressed length - %d \n", compressed_len); - LOG_DEBUG("Original message - %s \n", p->decoded.payload.bytes); + LOG_DEBUG("Original length - %d ", p->decoded.payload.size); + LOG_DEBUG("Compressed length - %d ", compressed_len); + LOG_DEBUG("Original message - %s ", p->decoded.payload.bytes); // If the compressed length is greater than or equal to the original size, don't use the compressed form if (compressed_len >= p->decoded.payload.size) { - LOG_DEBUG("Not using compressing message.\n"); + LOG_DEBUG("Not using compressing message."); // Set the uncompressed payload variant anyway. Shouldn't hurt? // p->decoded.which_payloadVariant = Data_payload_tag; // Otherwise we use the compressor } else { - LOG_DEBUG("Using compressed message.\n"); + LOG_DEBUG("Using compressed message."); // Copy the compressed data into the meshpacket p->decoded.payload.size = compressed_len; @@ -492,22 +493,22 @@ meshtastic_Routing_Error perhapsEncode(meshtastic_MeshPacket *p) // Don't use PKC if it's not explicitly requested and a non-primary channel is requested !(p->pki_encrypted != true && p->channel > 0) && // Check for valid keys and single node destination - config.security.private_key.size == 32 && p->to != NODENUM_BROADCAST && node != nullptr && + config.security.private_key.size == 32 && !isBroadcast(p->to) && node != nullptr && // Check for a known public key for the destination (node->user.public_key.size == 32) && // Some portnums either make no sense to send with PKC p->decoded.portnum != meshtastic_PortNum_TRACEROUTE_APP && p->decoded.portnum != meshtastic_PortNum_NODEINFO_APP && p->decoded.portnum != meshtastic_PortNum_ROUTING_APP && p->decoded.portnum != meshtastic_PortNum_POSITION_APP) { - LOG_DEBUG("Using PKI!\n"); + LOG_DEBUG("Using PKI!"); if (numbytes + MESHTASTIC_HEADER_LENGTH + MESHTASTIC_PKC_OVERHEAD > MAX_LORA_PAYLOAD_LEN) return meshtastic_Routing_Error_TOO_LARGE; if (p->pki_encrypted && !memfll(p->public_key.bytes, 0, 32) && memcmp(p->public_key.bytes, node->user.public_key.bytes, 32) != 0) { - LOG_WARN("Client public key differs from requested: 0x%02x, stored key begins 0x%02x\n", *p->public_key.bytes, + LOG_WARN("Client public key differs from requested: 0x%02x, stored key begins 0x%02x", *p->public_key.bytes, *node->user.public_key.bytes); return meshtastic_Routing_Error_PKI_FAILED; } - crypto->encryptCurve25519(p->to, getFrom(p), p->id, numbytes, bytes, ScratchEncrypted); + crypto->encryptCurve25519(p->to, getFrom(p), node->user.public_key, p->id, numbytes, bytes, ScratchEncrypted); numbytes += MESHTASTIC_PKC_OVERHEAD; memcpy(p->encrypted.bytes, ScratchEncrypted, numbytes); p->channel = 0; @@ -585,7 +586,7 @@ void Router::handleReceived(meshtastic_MeshPacket *p, RxSource src) if (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag && p->decoded.portnum == meshtastic_PortNum_NEIGHBORINFO_APP && (!moduleConfig.has_neighbor_info || !moduleConfig.neighbor_info.enabled)) { - LOG_DEBUG("Neighbor info module is disabled, ignoring neighbor packet\n"); + LOG_DEBUG("Neighbor info module is disabled, ignoring neighbor packet"); cancelSending(p->from, p->id); skipHandle = true; } @@ -598,7 +599,7 @@ void Router::handleReceived(meshtastic_MeshPacket *p, RxSource src) p->decoded.portnum == meshtastic_PortNum_DETECTION_SENSOR_APP || p->decoded.portnum == meshtastic_PortNum_RANGE_TEST_APP || p->decoded.portnum == meshtastic_PortNum_REMOTE_HARDWARE_APP)) { - LOG_DEBUG("Ignoring packet on blacklisted portnum during event\n"); + LOG_DEBUG("Ignoring packet on blacklisted portnum during event"); cancelSending(p->from, p->id); skipHandle = true; } @@ -612,8 +613,12 @@ void Router::handleReceived(meshtastic_MeshPacket *p, RxSource src) MeshModule::callModules(*p, src); #if !MESHTASTIC_EXCLUDE_MQTT + // Mark as pki_encrypted if it is not yet decoded and MQTT encryption is also enabled, hash matches and it's a DM not to + // us (because we would be able to decrypt it) + if (!decoded && moduleConfig.mqtt.encryption_enabled && p->channel == 0x00 && !isBroadcast(p->to) && !isToUs(p)) + p_encrypted->pki_encrypted = true; // After potentially altering it, publish received message to MQTT if we're not the original transmitter of the packet - if (decoded && moduleConfig.mqtt.enabled && !isFromUs(p) && mqtt) + if ((decoded || p_encrypted->pki_encrypted) && moduleConfig.mqtt.enabled && !isFromUs(p) && mqtt) mqtt->onSend(*p_encrypted, *p, p->channel); #endif } @@ -626,29 +631,35 @@ void Router::perhapsHandleReceived(meshtastic_MeshPacket *p) #if ENABLE_JSON_LOGGING // Even ignored packets get logged in the trace p->rx_time = getValidTime(RTCQualityFromNet); // store the arrival timestamp for the phone - LOG_TRACE("%s\n", MeshPacketSerializer::JsonSerializeEncrypted(p).c_str()); + LOG_TRACE("%s", MeshPacketSerializer::JsonSerializeEncrypted(p).c_str()); #elif ARCH_PORTDUINO // Even ignored packets get logged in the trace if (settingsStrings[traceFilename] != "" || settingsMap[logoutputlevel] == level_trace) { p->rx_time = getValidTime(RTCQualityFromNet); // store the arrival timestamp for the phone - LOG_TRACE("%s\n", MeshPacketSerializer::JsonSerializeEncrypted(p).c_str()); + LOG_TRACE("%s", MeshPacketSerializer::JsonSerializeEncrypted(p).c_str()); } #endif // assert(radioConfig.has_preferences); if (is_in_repeated(config.lora.ignore_incoming, p->from)) { - LOG_DEBUG("Ignoring incoming message, 0x%x is in our ignore list\n", p->from); + LOG_DEBUG("Ignoring msg, 0x%x is in our ignore list", p->from); + packetPool.release(p); + return; + } + + if (p->from == NODENUM_BROADCAST) { + LOG_DEBUG("Ignoring msg from broadcast address"); packetPool.release(p); return; } if (config.lora.ignore_mqtt && p->via_mqtt) { - LOG_DEBUG("Message came in via MQTT from 0x%x\n", p->from); + LOG_DEBUG("Msg came in via MQTT from 0x%x", p->from); packetPool.release(p); return; } if (shouldFilterReceived(p)) { - LOG_DEBUG("Incoming message was filtered from 0x%x\n", p->from); + LOG_DEBUG("Incoming msg was filtered from 0x%x", p->from); packetPool.release(p); return; } diff --git a/src/mesh/STM32WLE5JCInterface.cpp b/src/mesh/STM32WLE5JCInterface.cpp index 3c1870d3bb..499db91766 100644 --- a/src/mesh/STM32WLE5JCInterface.cpp +++ b/src/mesh/STM32WLE5JCInterface.cpp @@ -27,11 +27,11 @@ bool STM32WLE5JCInterface::init() int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength, tcxoVoltage); - LOG_INFO("STM32WLx init result %d\n", res); + LOG_INFO("STM32WLx init result %d", 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", getFreq()); + LOG_INFO("Bandwidth set to %f", bw); + LOG_INFO("Power output set to %d", power); if (res == RADIOLIB_ERR_NONE) startReceive(); // start receiving diff --git a/src/mesh/SX126xInterface.cpp b/src/mesh/SX126xInterface.cpp index 924cdfa9f4..c88ed39d93 100644 --- a/src/mesh/SX126xInterface.cpp +++ b/src/mesh/SX126xInterface.cpp @@ -20,7 +20,7 @@ SX126xInterface::SX126xInterface(LockingArduinoHal *hal, RADIOLIB_PIN_TYPE cs RADIOLIB_PIN_TYPE busy) : RadioLibInterface(hal, cs, irq, rst, busy, &lora), lora(&module) { - LOG_DEBUG("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); + LOG_DEBUG("SX126xInterface(cs=%d, irq=%d, rst=%d, busy=%d)", cs, irq, rst, busy); } /// Initialise the Driver transport hardware and software. @@ -68,9 +68,9 @@ template bool SX126xInterface::init() // (DIO3 is not free to be used as an IRQ) #endif if (tcxoVoltage == 0) - LOG_DEBUG("SX126X_DIO3_TCXO_VOLTAGE not defined, not using DIO3 as TCXO reference voltage\n"); + LOG_DEBUG("SX126X_DIO3_TCXO_VOLTAGE not defined, not using DIO3 as TCXO reference voltage"); else - LOG_DEBUG("SX126X_DIO3_TCXO_VOLTAGE defined, using DIO3 as TCXO reference voltage at %f V\n", tcxoVoltage); + LOG_DEBUG("SX126X_DIO3_TCXO_VOLTAGE defined, using DIO3 as TCXO reference voltage at %f V", tcxoVoltage); // FIXME: May want to set depending on a definition, currently all SX126x variant files use the DC-DC regulator option bool useRegulatorLDO = false; // Seems to depend on the connection to pin 9/DCC_SW - if an inductor DCDC? @@ -84,13 +84,13 @@ template bool SX126xInterface::init() int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength, tcxoVoltage, useRegulatorLDO); // \todo Display actual typename of the adapter, not just `SX126x` - LOG_INFO("SX126x init result %d\n", res); + LOG_INFO("SX126x init result %d", res); if (res == RADIOLIB_ERR_CHIP_NOT_FOUND) return false; - 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", getFreq()); + LOG_INFO("Bandwidth set to %f", bw); + LOG_INFO("Power output set to %d", power); // Overriding current limit // (https://github.com/jgromes/RadioLib/blob/690a050ebb46e6097c5d00c371e961c1caa3b52e/src/modules/SX126x/SX126x.cpp#L85) using @@ -101,8 +101,8 @@ template bool SX126xInterface::init() // FIXME: Not ideal to increase SX1261 current limit above 60mA as it can only transmit max 15dBm, should probably only do it // if using SX1262 or SX1268 res = lora.setCurrentLimit(currentLimit); - LOG_DEBUG("Current limit set to %f\n", currentLimit); - LOG_DEBUG("Current limit set result %d\n", res); + LOG_DEBUG("Current limit set to %f", currentLimit); + LOG_DEBUG("Current limit set result %d", res); if (res == RADIOLIB_ERR_NONE) { #ifdef SX126X_DIO2_AS_RF_SWITCH @@ -116,36 +116,36 @@ template bool SX126xInterface::init() bool dio2AsRfSwitch = false; #endif res = lora.setDio2AsRfSwitch(dio2AsRfSwitch); - LOG_DEBUG("Set DIO2 as %sRF switch, result: %d\n", dio2AsRfSwitch ? "" : "not ", res); + LOG_DEBUG("Set DIO2 as %sRF switch, result: %d", dio2AsRfSwitch ? "" : "not ", res); } // If a pin isn't defined, we set it to RADIOLIB_NC, it is safe to always do external RF switching with RADIOLIB_NC as it has // no effect #if ARCH_PORTDUINO if (res == RADIOLIB_ERR_NONE) { - LOG_DEBUG("Using MCU pin %i as RXEN and pin %i as TXEN to control RF switching\n", settingsMap[rxen], settingsMap[txen]); + LOG_DEBUG("Using MCU pin %i as RXEN and pin %i as TXEN to control RF switching", settingsMap[rxen], settingsMap[txen]); lora.setRfSwitchPins(settingsMap[rxen], settingsMap[txen]); } #else #ifndef SX126X_RXEN #define SX126X_RXEN RADIOLIB_NC - LOG_DEBUG("SX126X_RXEN not defined, defaulting to RADIOLIB_NC\n"); + LOG_DEBUG("SX126X_RXEN not defined, defaulting to RADIOLIB_NC"); #endif #ifndef SX126X_TXEN #define SX126X_TXEN RADIOLIB_NC - LOG_DEBUG("SX126X_TXEN not defined, defaulting to RADIOLIB_NC\n"); + LOG_DEBUG("SX126X_TXEN not defined, defaulting to RADIOLIB_NC"); #endif if (res == RADIOLIB_ERR_NONE) { - LOG_DEBUG("Using MCU pin %i as RXEN and pin %i as TXEN to control RF switching\n", SX126X_RXEN, SX126X_TXEN); + LOG_DEBUG("Using MCU pin %i as RXEN and pin %i as TXEN to control RF switching", SX126X_RXEN, SX126X_TXEN); lora.setRfSwitchPins(SX126X_RXEN, SX126X_TXEN); } #endif if (config.lora.sx126x_rx_boosted_gain) { uint16_t result = lora.setRxBoostedGainMode(true); - LOG_INFO("Set RX gain to boosted mode; result: %d\n", result); + LOG_INFO("Set RX gain to boosted mode; result: %d", result); } else { uint16_t result = lora.setRxBoostedGainMode(false); - LOG_INFO("Set RX gain to power saving mode (boosted mode off); result: %d\n", result); + LOG_INFO("Set RX gain to power saving mode (boosted mode off); result: %d", result); } #if 0 @@ -203,17 +203,17 @@ template bool SX126xInterface::reconfigure() err = lora.setSyncWord(syncWord); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX126X setSyncWord %s%d\n", radioLibErr, err); + LOG_ERROR("SX126X setSyncWord %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora.setCurrentLimit(currentLimit); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX126X setCurrentLimit %s%d\n", radioLibErr, err); + LOG_ERROR("SX126X setCurrentLimit %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora.setPreambleLength(preambleLength); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX126X setPreambleLength %s%d\n", radioLibErr, err); + LOG_ERROR("SX126X setPreambleLength %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora.setFrequency(getFreq()); @@ -225,7 +225,7 @@ template bool SX126xInterface::reconfigure() err = lora.setOutputPower(power); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX126X setOutputPower %s%d\n", radioLibErr, err); + LOG_ERROR("SX126X setOutputPower %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); startReceive(); // restart receiving @@ -245,7 +245,7 @@ template void SX126xInterface::setStandby() int err = lora.standby(); if (err != RADIOLIB_ERR_NONE) - LOG_DEBUG("SX126x standby %s%d\n", radioLibErr, err); + LOG_DEBUG("SX126x standby %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); isReceiving = false; // If we were receiving, not any more @@ -260,7 +260,7 @@ template void SX126xInterface::setStandby() */ template void SX126xInterface::addReceiveMetadata(meshtastic_MeshPacket *mp) { - // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); + // LOG_DEBUG("PacketStatus %x", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); mp->rx_rssi = lround(lora.getRSSI()); } @@ -287,7 +287,7 @@ template void SX126xInterface::startReceive() // Furthermore, we need the PREAMBLE_DETECTED and HEADER_VALID IRQ flag to detect whether we are actively receiving int err = lora.startReceiveDutyCycleAuto(preambleLength, 8, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | RADIOLIB_IRQ_PREAMBLE_DETECTED); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX126X startReceiveDutyCycleAuto %s%d\n", radioLibErr, err); + LOG_ERROR("SX126X startReceiveDutyCycleAuto %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); RadioLibInterface::startReceive(); @@ -308,7 +308,7 @@ template bool SX126xInterface::isChannelActive() if (result == RADIOLIB_LORA_DETECTED) return true; if (result != RADIOLIB_CHANNEL_FREE) - LOG_ERROR("SX126X scanChannel %s%d\n", radioLibErr, result); + LOG_ERROR("SX126X scanChannel %s%d", radioLibErr, result); assert(result != RADIOLIB_ERR_WRONG_MODEM); return false; @@ -326,8 +326,8 @@ 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` - LOG_DEBUG("SX126x entering sleep mode\n"); // (FIXME, don't keep config) - setStandby(); // Stop any pending operations + LOG_DEBUG("SX126x entering sleep mode"); // (FIXME, don't keep config) + setStandby(); // Stop any pending operations // turn off TCXO if it was powered // FIXME - this isn't correct diff --git a/src/mesh/SX128xInterface.cpp b/src/mesh/SX128xInterface.cpp index d379f26e6a..9fe86cc6e0 100644 --- a/src/mesh/SX128xInterface.cpp +++ b/src/mesh/SX128xInterface.cpp @@ -19,7 +19,7 @@ SX128xInterface::SX128xInterface(LockingArduinoHal *hal, RADIOLIB_PIN_TYPE cs RADIOLIB_PIN_TYPE busy) : RadioLibInterface(hal, cs, irq, rst, busy, &lora), lora(&module) { - LOG_DEBUG("SX128xInterface(cs=%d, irq=%d, rst=%d, busy=%d)\n", cs, irq, rst, busy); + LOG_DEBUG("SX128xInterface(cs=%d, irq=%d, rst=%d, busy=%d)", cs, irq, rst, busy); } /// Initialise the Driver transport hardware and software. @@ -68,10 +68,10 @@ template bool SX128xInterface::init() int res = lora.begin(getFreq(), bw, sf, cr, syncWord, power, preambleLength); // \todo Display actual typename of the adapter, not just `SX128x` - LOG_INFO("SX128x init result %d\n", res); + LOG_INFO("SX128x init result %d", res); 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"); + LOG_WARN("Radio chip only supports 2.4GHz LoRa. Adjusting Region and rebooting."); config.lora.region = meshtastic_Config_LoRaConfig_RegionCode_LORA_24; nodeDB->saveToDisk(SEGMENT_CONFIG); delay(2000); @@ -80,13 +80,13 @@ template bool SX128xInterface::init() #elif defined(ARCH_NRF52) NVIC_SystemReset(); #else - LOG_ERROR("FIXME implement reboot for this platform. Skipping for now.\n"); + LOG_ERROR("FIXME implement reboot for this platform. Skipping for now."); #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", getFreq()); + LOG_INFO("Bandwidth set to %f", bw); + LOG_INFO("Power output set to %d", power); #if defined(SX128X_TXEN) && (SX128X_TXEN != RADIOLIB_NC) && defined(SX128X_RXEN) && (SX128X_RXEN != RADIOLIB_NC) if (res == RADIOLIB_ERR_NONE) { @@ -129,12 +129,12 @@ template bool SX128xInterface::reconfigure() err = lora.setSyncWord(syncWord); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX128X setSyncWord %s%d\n", radioLibErr, err); + LOG_ERROR("SX128X setSyncWord %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora.setPreambleLength(preambleLength); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX128X setPreambleLength %s%d\n", radioLibErr, err); + LOG_ERROR("SX128X setPreambleLength %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); err = lora.setFrequency(getFreq()); @@ -146,7 +146,7 @@ template bool SX128xInterface::reconfigure() err = lora.setOutputPower(power); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX128X setOutputPower %s%d\n", radioLibErr, err); + LOG_ERROR("SX128X setOutputPower %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); startReceive(); // restart receiving @@ -171,7 +171,7 @@ template void SX128xInterface::setStandby() int err = lora.standby(); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX128x standby %s%d\n", radioLibErr, err); + LOG_ERROR("SX128x standby %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); #if ARCH_PORTDUINO if (settingsMap[rxen] != RADIOLIB_NC) { @@ -200,7 +200,7 @@ template void SX128xInterface::setStandby() */ template void SX128xInterface::addReceiveMetadata(meshtastic_MeshPacket *mp) { - // LOG_DEBUG("PacketStatus %x\n", lora.getPacketStatus()); + // LOG_DEBUG("PacketStatus %x", lora.getPacketStatus()); mp->rx_snr = lora.getSNR(); mp->rx_rssi = lround(lora.getRSSI()); } @@ -261,7 +261,7 @@ template void SX128xInterface::startReceive() int err = lora.startReceive(RADIOLIB_SX128X_RX_TIMEOUT_INF, RADIOLIB_IRQ_RX_DEFAULT_FLAGS | RADIOLIB_IRQ_PREAMBLE_DETECTED); if (err != RADIOLIB_ERR_NONE) - LOG_ERROR("SX128X startReceive %s%d\n", radioLibErr, err); + LOG_ERROR("SX128X startReceive %s%d", radioLibErr, err); assert(err == RADIOLIB_ERR_NONE); RadioLibInterface::startReceive(); @@ -282,7 +282,7 @@ template bool SX128xInterface::isChannelActive() if (result == RADIOLIB_LORA_DETECTED) return true; if (result != RADIOLIB_CHANNEL_FREE) - LOG_ERROR("SX128X scanChannel %s%d\n", radioLibErr, result); + LOG_ERROR("SX128X scanChannel %s%d", radioLibErr, result); assert(result != RADIOLIB_ERR_WRONG_MODEM); return false; @@ -298,8 +298,8 @@ 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` - LOG_DEBUG("SX128x entering sleep mode\n"); // (FIXME, don't keep config) - setStandby(); // Stop any pending operations + LOG_DEBUG("SX128x entering sleep mode"); // (FIXME, don't keep config) + setStandby(); // Stop any pending operations // turn off TCXO if it was powered // FIXME - this isn't correct diff --git a/src/mesh/StreamAPI.cpp b/src/mesh/StreamAPI.cpp index c3d85ed338..4a42e5197a 100644 --- a/src/mesh/StreamAPI.cpp +++ b/src/mesh/StreamAPI.cpp @@ -115,7 +115,7 @@ void StreamAPI::emitRebooted() fromRadioScratch.which_payload_variant = meshtastic_FromRadio_rebooted_tag; fromRadioScratch.rebooted = true; - // LOG_DEBUG("Emitting reboot packet for serial shell\n"); + // LOG_DEBUG("Emitting reboot packet for serial shell"); emitTxBuffer(pb_encode_to_bytes(txBuf + HEADER_LEN, meshtastic_FromRadio_size, &meshtastic_FromRadio_msg, &fromRadioScratch)); } diff --git a/src/mesh/api/ServerAPI.cpp b/src/mesh/api/ServerAPI.cpp index 42217428df..7705858b5e 100644 --- a/src/mesh/api/ServerAPI.cpp +++ b/src/mesh/api/ServerAPI.cpp @@ -5,7 +5,7 @@ template ServerAPI::ServerAPI(T &_client) : StreamAPI(&client), concurrency::OSThread("ServerAPI"), client(_client) { - LOG_INFO("Incoming API connection\n"); + LOG_INFO("Incoming API connection"); } template ServerAPI::~ServerAPI() @@ -30,7 +30,7 @@ template int32_t ServerAPI::runOnce() if (client.connected()) { return StreamAPI::runOncePart(); } else { - LOG_INFO("Client dropped connection, suspending API service\n"); + LOG_INFO("Client dropped connection, suspending API service"); enabled = false; // we no longer need to run return 0; } @@ -63,11 +63,11 @@ template int32_t APIServerPort::runOnce() // Reconnections are delayed by full wait time if (waitTime < 400) { waitTime *= 2; - LOG_INFO("Previous TCP connection still open, trying again in %dms\n", waitTime); + LOG_INFO("Previous TCP connection still open, trying again in %dms", waitTime); return waitTime; } #endif - LOG_INFO("Force closing previous TCP connection\n"); + LOG_INFO("Force closing previous TCP connection"); delete openAPI; } diff --git a/src/mesh/api/WiFiServerAPI.cpp b/src/mesh/api/WiFiServerAPI.cpp index ba31f76e5f..89ab2c626b 100644 --- a/src/mesh/api/WiFiServerAPI.cpp +++ b/src/mesh/api/WiFiServerAPI.cpp @@ -11,7 +11,7 @@ void initApiServer(int port) // Start API server on port 4403 if (!apiPort) { apiPort = new WiFiServerPort(port); - LOG_INFO("API server listening on TCP port %d\n", port); + LOG_INFO("API server listening on TCP port %d", port); apiPort->init(); } } @@ -22,7 +22,7 @@ void deInitApiServer() WiFiServerAPI::WiFiServerAPI(WiFiClient &_client) : ServerAPI(_client) { - LOG_INFO("Incoming wifi connection\n"); + LOG_INFO("Incoming wifi connection"); } WiFiServerPort::WiFiServerPort(int port) : APIServerPort(port) {} diff --git a/src/mesh/api/ethServerAPI.cpp b/src/mesh/api/ethServerAPI.cpp index 3badcdfdec..a8701848a6 100644 --- a/src/mesh/api/ethServerAPI.cpp +++ b/src/mesh/api/ethServerAPI.cpp @@ -12,14 +12,14 @@ void initApiServer(int port) // Start API server on port 4403 if (!apiPort) { apiPort = new ethServerPort(port); - LOG_INFO("API server listening on TCP port %d\n", port); + LOG_INFO("API server listening on TCP port %d", port); apiPort->init(); } } ethServerAPI::ethServerAPI(EthernetClient &_client) : ServerAPI(_client) { - LOG_INFO("Incoming ethernet connection\n"); + LOG_INFO("Incoming ethernet connection"); } ethServerPort::ethServerPort(int port) : APIServerPort(port) {} diff --git a/src/mesh/eth/ethClient.cpp b/src/mesh/eth/ethClient.cpp index 1c97f3bed7..67da224c6a 100644 --- a/src/mesh/eth/ethClient.cpp +++ b/src/mesh/eth/ethClient.cpp @@ -38,16 +38,16 @@ static int32_t reconnectETH() Ethernet.maintain(); if (!ethStartupComplete) { // Start web server - LOG_INFO("Starting Ethernet network services\n"); + LOG_INFO("Starting Ethernet network services"); #ifndef DISABLE_NTP - LOG_INFO("Starting NTP time client\n"); + LOG_INFO("Starting NTP time client"); timeClient.begin(); timeClient.setUpdateInterval(60 * 60); // Update once an hour #endif if (config.network.rsyslog_server[0]) { - LOG_INFO("Starting Syslog client\n"); + LOG_INFO("Starting Syslog client"); // Defaults int serverPort = 514; const char *serverAddr = config.network.rsyslog_server; @@ -82,9 +82,9 @@ static int32_t reconnectETH() #ifndef DISABLE_NTP if (isEthernetAvailable() && (ntp_renew < millis())) { - LOG_INFO("Updating NTP time from %s\n", config.network.ntp_server); + LOG_INFO("Updating NTP time from %s", config.network.ntp_server); if (timeClient.update()) { - LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed\n"); + LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed"); struct timeval tv; tv.tv_sec = timeClient.getEpochTime(); @@ -94,7 +94,7 @@ static int32_t reconnectETH() ntp_renew = millis() + 43200 * 1000; // success, refresh every 12 hours } else { - LOG_ERROR("NTP Update failed\n"); + LOG_ERROR("NTP Update failed"); ntp_renew = millis() + 300 * 1000; // failure, retry every 5 minutes } } @@ -127,45 +127,45 @@ bool initEthernet() mac[0] &= 0xfe; // Make sure this is not a multicast MAC if (config.network.address_mode == meshtastic_Config_NetworkConfig_AddressMode_DHCP) { - LOG_INFO("starting Ethernet DHCP\n"); + LOG_INFO("starting Ethernet DHCP"); status = Ethernet.begin(mac); } else if (config.network.address_mode == meshtastic_Config_NetworkConfig_AddressMode_STATIC) { - LOG_INFO("starting Ethernet Static\n"); + LOG_INFO("starting Ethernet Static"); Ethernet.begin(mac, config.network.ipv4_config.ip, config.network.ipv4_config.dns, config.network.ipv4_config.gateway, config.network.ipv4_config.subnet); status = 1; } else { - LOG_INFO("Ethernet Disabled\n"); + LOG_INFO("Ethernet Disabled"); return false; } if (status == 0) { if (Ethernet.hardwareStatus() == EthernetNoHardware) { - LOG_ERROR("Ethernet shield was not found.\n"); + LOG_ERROR("Ethernet shield was not found."); return false; } else if (Ethernet.linkStatus() == LinkOFF) { - LOG_ERROR("Ethernet cable is not connected.\n"); + LOG_ERROR("Ethernet cable is not connected."); return false; } else { - LOG_ERROR("Unknown Ethernet error.\n"); + LOG_ERROR("Unknown Ethernet error."); return false; } } else { - LOG_INFO("Local IP %u.%u.%u.%u\n", Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], + LOG_INFO("Local IP %u.%u.%u.%u", Ethernet.localIP()[0], Ethernet.localIP()[1], Ethernet.localIP()[2], Ethernet.localIP()[3]); - LOG_INFO("Subnet Mask %u.%u.%u.%u\n", Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], + LOG_INFO("Subnet Mask %u.%u.%u.%u", Ethernet.subnetMask()[0], Ethernet.subnetMask()[1], Ethernet.subnetMask()[2], Ethernet.subnetMask()[3]); - LOG_INFO("Gateway IP %u.%u.%u.%u\n", Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], + LOG_INFO("Gateway IP %u.%u.%u.%u", Ethernet.gatewayIP()[0], Ethernet.gatewayIP()[1], Ethernet.gatewayIP()[2], Ethernet.gatewayIP()[3]); - LOG_INFO("DNS Server IP %u.%u.%u.%u\n", Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], - Ethernet.dnsServerIP()[2], Ethernet.dnsServerIP()[3]); + LOG_INFO("DNS Server IP %u.%u.%u.%u", Ethernet.dnsServerIP()[0], Ethernet.dnsServerIP()[1], Ethernet.dnsServerIP()[2], + Ethernet.dnsServerIP()[3]); } ethEvent = new Periodic("ethConnect", reconnectETH); return true; } else { - LOG_INFO("Not using Ethernet\n"); + LOG_INFO("Not using Ethernet"); return false; } } diff --git a/src/mesh/generated/meshtastic/admin.pb.h b/src/mesh/generated/meshtastic/admin.pb.h index bf81269b40..d802eb3da2 100644 --- a/src/mesh/generated/meshtastic/admin.pb.h +++ b/src/mesh/generated/meshtastic/admin.pb.h @@ -9,6 +9,7 @@ #include "meshtastic/connection_status.pb.h" #include "meshtastic/mesh.pb.h" #include "meshtastic/module_config.pb.h" +#include "meshtastic/device_ui.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -34,7 +35,9 @@ typedef enum _meshtastic_AdminMessage_ConfigType { /* TODO: REPLACE */ meshtastic_AdminMessage_ConfigType_SECURITY_CONFIG = 7, /* */ - meshtastic_AdminMessage_ConfigType_SESSIONKEY_CONFIG = 8 + meshtastic_AdminMessage_ConfigType_SESSIONKEY_CONFIG = 8, + /* device-ui config */ + meshtastic_AdminMessage_ConfigType_DEVICEUI_CONFIG = 9 } meshtastic_AdminMessage_ConfigType; /* TODO: REPLACE */ @@ -171,6 +174,12 @@ typedef struct _meshtastic_AdminMessage { /* Set time only on the node Convenience method to set the time on the node (as Net quality) without any other position data */ uint32_t set_time_only; + /* Tell the node to send the stored ui data. */ + bool get_ui_config_request; + /* Reply stored device ui data. */ + meshtastic_DeviceUIConfig get_ui_config_response; + /* Tell the node to store UI data persistently. */ + meshtastic_DeviceUIConfig store_ui_config; /* Begins an edit transaction for config, module config, owner, and channel settings changes This will delay the standard *implicit* save to the file system and subsequent reboot behavior until committed (commit_edit_settings) */ bool begin_edit_settings; @@ -206,8 +215,8 @@ extern "C" { /* Helper constants for enums */ #define _meshtastic_AdminMessage_ConfigType_MIN meshtastic_AdminMessage_ConfigType_DEVICE_CONFIG -#define _meshtastic_AdminMessage_ConfigType_MAX meshtastic_AdminMessage_ConfigType_SESSIONKEY_CONFIG -#define _meshtastic_AdminMessage_ConfigType_ARRAYSIZE ((meshtastic_AdminMessage_ConfigType)(meshtastic_AdminMessage_ConfigType_SESSIONKEY_CONFIG+1)) +#define _meshtastic_AdminMessage_ConfigType_MAX meshtastic_AdminMessage_ConfigType_DEVICEUI_CONFIG +#define _meshtastic_AdminMessage_ConfigType_ARRAYSIZE ((meshtastic_AdminMessage_ConfigType)(meshtastic_AdminMessage_ConfigType_DEVICEUI_CONFIG+1)) #define _meshtastic_AdminMessage_ModuleConfigType_MIN meshtastic_AdminMessage_ModuleConfigType_MQTT_CONFIG #define _meshtastic_AdminMessage_ModuleConfigType_MAX meshtastic_AdminMessage_ModuleConfigType_PAXCOUNTER_CONFIG @@ -267,6 +276,9 @@ extern "C" { #define meshtastic_AdminMessage_set_fixed_position_tag 41 #define meshtastic_AdminMessage_remove_fixed_position_tag 42 #define meshtastic_AdminMessage_set_time_only_tag 43 +#define meshtastic_AdminMessage_get_ui_config_request_tag 44 +#define meshtastic_AdminMessage_get_ui_config_response_tag 45 +#define meshtastic_AdminMessage_store_ui_config_tag 46 #define meshtastic_AdminMessage_begin_edit_settings_tag 64 #define meshtastic_AdminMessage_commit_edit_settings_tag 65 #define meshtastic_AdminMessage_factory_reset_device_tag 94 @@ -314,6 +326,9 @@ X(a, STATIC, ONEOF, UINT32, (payload_variant,remove_favorite_node,remove_ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,set_fixed_position,set_fixed_position), 41) \ X(a, STATIC, ONEOF, BOOL, (payload_variant,remove_fixed_position,remove_fixed_position), 42) \ X(a, STATIC, ONEOF, FIXED32, (payload_variant,set_time_only,set_time_only), 43) \ +X(a, STATIC, ONEOF, BOOL, (payload_variant,get_ui_config_request,get_ui_config_request), 44) \ +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,get_ui_config_response,get_ui_config_response), 45) \ +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,store_ui_config,store_ui_config), 46) \ 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, INT32, (payload_variant,factory_reset_device,factory_reset_device), 94) \ @@ -339,6 +354,8 @@ X(a, STATIC, SINGULAR, BYTES, session_passkey, 101) #define meshtastic_AdminMessage_payload_variant_set_config_MSGTYPE meshtastic_Config #define meshtastic_AdminMessage_payload_variant_set_module_config_MSGTYPE meshtastic_ModuleConfig #define meshtastic_AdminMessage_payload_variant_set_fixed_position_MSGTYPE meshtastic_Position +#define meshtastic_AdminMessage_payload_variant_get_ui_config_response_MSGTYPE meshtastic_DeviceUIConfig +#define meshtastic_AdminMessage_payload_variant_store_ui_config_MSGTYPE meshtastic_DeviceUIConfig #define meshtastic_HamParameters_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, STRING, call_sign, 1) \ diff --git a/src/mesh/generated/meshtastic/config.pb.h b/src/mesh/generated/meshtastic/config.pb.h index 988f852ffb..fab23ae34f 100644 --- a/src/mesh/generated/meshtastic/config.pb.h +++ b/src/mesh/generated/meshtastic/config.pb.h @@ -4,6 +4,7 @@ #ifndef PB_MESHTASTIC_MESHTASTIC_CONFIG_PB_H_INCLUDED #define PB_MESHTASTIC_MESHTASTIC_CONFIG_PB_H_INCLUDED #include +#include "meshtastic/device_ui.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -73,7 +74,12 @@ typedef enum _meshtastic_Config_DeviceConfig_RebroadcastMode { meshtastic_Config_DeviceConfig_RebroadcastMode_LOCAL_ONLY = 2, /* Ignores observed messages from foreign meshes like LOCAL_ONLY, but takes it step further by also ignoring messages from nodenums not in the node's known list (NodeDB) */ - meshtastic_Config_DeviceConfig_RebroadcastMode_KNOWN_ONLY = 3 + meshtastic_Config_DeviceConfig_RebroadcastMode_KNOWN_ONLY = 3, + /* Only permitted for SENSOR, TRACKER and TAK_TRACKER roles, this will inhibit all rebroadcasts, not unlike CLIENT_MUTE role. */ + meshtastic_Config_DeviceConfig_RebroadcastMode_NONE = 4, + /* Ignores packets from non-standard portnums such as: TAK, RangeTest, PaxCounter, etc. + Only rebroadcasts packets with standard portnums: NodeInfo, Text, Position, Telemetry, and Routing. */ + meshtastic_Config_DeviceConfig_RebroadcastMode_CORE_PORTNUMS_ONLY = 5 } meshtastic_Config_DeviceConfig_RebroadcastMode; /* Bit field of boolean configuration options, indicating which optional @@ -571,6 +577,7 @@ typedef struct _meshtastic_Config { meshtastic_Config_BluetoothConfig bluetooth; meshtastic_Config_SecurityConfig security; meshtastic_Config_SessionkeyConfig sessionkey; + meshtastic_DeviceUIConfig device_ui; } payload_variant; } meshtastic_Config; @@ -585,8 +592,8 @@ extern "C" { #define _meshtastic_Config_DeviceConfig_Role_ARRAYSIZE ((meshtastic_Config_DeviceConfig_Role)(meshtastic_Config_DeviceConfig_Role_TAK_TRACKER+1)) #define _meshtastic_Config_DeviceConfig_RebroadcastMode_MIN meshtastic_Config_DeviceConfig_RebroadcastMode_ALL -#define _meshtastic_Config_DeviceConfig_RebroadcastMode_MAX meshtastic_Config_DeviceConfig_RebroadcastMode_KNOWN_ONLY -#define _meshtastic_Config_DeviceConfig_RebroadcastMode_ARRAYSIZE ((meshtastic_Config_DeviceConfig_RebroadcastMode)(meshtastic_Config_DeviceConfig_RebroadcastMode_KNOWN_ONLY+1)) +#define _meshtastic_Config_DeviceConfig_RebroadcastMode_MAX meshtastic_Config_DeviceConfig_RebroadcastMode_CORE_PORTNUMS_ONLY +#define _meshtastic_Config_DeviceConfig_RebroadcastMode_ARRAYSIZE ((meshtastic_Config_DeviceConfig_RebroadcastMode)(meshtastic_Config_DeviceConfig_RebroadcastMode_CORE_PORTNUMS_ONLY+1)) #define _meshtastic_Config_PositionConfig_PositionFlags_MIN meshtastic_Config_PositionConfig_PositionFlags_UNSET #define _meshtastic_Config_PositionConfig_PositionFlags_MAX meshtastic_Config_PositionConfig_PositionFlags_SPEED @@ -774,6 +781,7 @@ extern "C" { #define meshtastic_Config_bluetooth_tag 7 #define meshtastic_Config_security_tag 8 #define meshtastic_Config_sessionkey_tag 9 +#define meshtastic_Config_device_ui_tag 10 /* Struct field encoding specification for nanopb */ #define meshtastic_Config_FIELDLIST(X, a) \ @@ -785,7 +793,8 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,display,payload_variant.disp X(a, STATIC, ONEOF, MESSAGE, (payload_variant,lora,payload_variant.lora), 6) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,bluetooth,payload_variant.bluetooth), 7) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,security,payload_variant.security), 8) \ -X(a, STATIC, ONEOF, MESSAGE, (payload_variant,sessionkey,payload_variant.sessionkey), 9) +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,sessionkey,payload_variant.sessionkey), 9) \ +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,device_ui,payload_variant.device_ui), 10) #define meshtastic_Config_CALLBACK NULL #define meshtastic_Config_DEFAULT NULL #define meshtastic_Config_payload_variant_device_MSGTYPE meshtastic_Config_DeviceConfig @@ -797,6 +806,7 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,sessionkey,payload_variant.s #define meshtastic_Config_payload_variant_bluetooth_MSGTYPE meshtastic_Config_BluetoothConfig #define meshtastic_Config_payload_variant_security_MSGTYPE meshtastic_Config_SecurityConfig #define meshtastic_Config_payload_variant_sessionkey_MSGTYPE meshtastic_Config_SessionkeyConfig +#define meshtastic_Config_payload_variant_device_ui_MSGTYPE meshtastic_DeviceUIConfig #define meshtastic_Config_DeviceConfig_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UENUM, role, 1) \ diff --git a/src/mesh/generated/meshtastic/device_ui.pb.cpp b/src/mesh/generated/meshtastic/device_ui.pb.cpp new file mode 100644 index 0000000000..6e0cf0cc8b --- /dev/null +++ b/src/mesh/generated/meshtastic/device_ui.pb.cpp @@ -0,0 +1,22 @@ +/* Automatically generated nanopb constant definitions */ +/* Generated by nanopb-0.4.9 */ + +#include "meshtastic/device_ui.pb.h" +#if PB_PROTO_HEADER_VERSION != 40 +#error Regenerate this file with the current version of nanopb generator. +#endif + +PB_BIND(meshtastic_DeviceUIConfig, meshtastic_DeviceUIConfig, AUTO) + + +PB_BIND(meshtastic_NodeFilter, meshtastic_NodeFilter, AUTO) + + +PB_BIND(meshtastic_NodeHighlight, meshtastic_NodeHighlight, AUTO) + + + + + + + diff --git a/src/mesh/generated/meshtastic/device_ui.pb.h b/src/mesh/generated/meshtastic/device_ui.pb.h new file mode 100644 index 0000000000..469fe6f11f --- /dev/null +++ b/src/mesh/generated/meshtastic/device_ui.pb.h @@ -0,0 +1,198 @@ +/* Automatically generated nanopb header */ +/* Generated by nanopb-0.4.9 */ + +#ifndef PB_MESHTASTIC_MESHTASTIC_DEVICE_UI_PB_H_INCLUDED +#define PB_MESHTASTIC_MESHTASTIC_DEVICE_UI_PB_H_INCLUDED +#include + +#if PB_PROTO_HEADER_VERSION != 40 +#error Regenerate this file with the current version of nanopb generator. +#endif + +/* Enum definitions */ +typedef enum _meshtastic_Theme { + /* Dark */ + meshtastic_Theme_DARK = 0, + /* Light */ + meshtastic_Theme_LIGHT = 1, + /* Red */ + meshtastic_Theme_RED = 2 +} meshtastic_Theme; + +/* Localization */ +typedef enum _meshtastic_Language { + /* English */ + meshtastic_Language_ENGLISH = 0, + /* French */ + meshtastic_Language_FRENCH = 1, + /* German */ + meshtastic_Language_GERMAN = 2, + /* Italian */ + meshtastic_Language_ITALIAN = 3, + /* Portuguese */ + meshtastic_Language_PORTUGUESE = 4, + /* Spanish */ + meshtastic_Language_SPANISH = 5, + /* Swedish */ + meshtastic_Language_SWEDISH = 6, + /* Finnish */ + meshtastic_Language_FINNISH = 7, + /* Polish */ + meshtastic_Language_POLISH = 8, + /* Turkish */ + meshtastic_Language_TURKISH = 9 +} meshtastic_Language; + +/* Struct definitions */ +typedef struct _meshtastic_NodeFilter { + /* Filter unknown nodes */ + bool unknown_switch; + /* Filter offline nodes */ + bool offline_switch; + /* Filter nodes w/o public key */ + bool public_key_switch; + /* Filter based on hops away */ + int8_t hops_away; + /* Filter nodes w/o position */ + bool position_switch; + /* Filter nodes by matching name string */ + char node_name[16]; +} meshtastic_NodeFilter; + +typedef struct _meshtastic_NodeHighlight { + /* Hightlight nodes w/ active chat */ + bool chat_switch; + /* Highlight nodes w/ position */ + bool position_switch; + /* Highlight nodes w/ telemetry data */ + bool telemetry_switch; + /* Highlight nodes w/ iaq data */ + bool iaq_switch; + /* Highlight nodes by matching name string */ + char node_name[16]; +} meshtastic_NodeHighlight; + +typedef struct _meshtastic_DeviceUIConfig { + /* TFT display brightness 1..255 */ + uint8_t screen_brightness; + /* Screen timeout 0..900 */ + uint16_t screen_timeout; + /* Screen lock enabled */ + bool screen_lock; + /* Color theme */ + meshtastic_Theme theme; + /* Audible message alert enabled */ + bool alert_enabled; + /* Localization */ + meshtastic_Language language; + /* Node list filter */ + bool has_node_filter; + meshtastic_NodeFilter node_filter; + /* Node list highlightening */ + bool has_node_highlight; + meshtastic_NodeHighlight node_highlight; +} meshtastic_DeviceUIConfig; + + +#ifdef __cplusplus +extern "C" { +#endif + +/* Helper constants for enums */ +#define _meshtastic_Theme_MIN meshtastic_Theme_DARK +#define _meshtastic_Theme_MAX meshtastic_Theme_RED +#define _meshtastic_Theme_ARRAYSIZE ((meshtastic_Theme)(meshtastic_Theme_RED+1)) + +#define _meshtastic_Language_MIN meshtastic_Language_ENGLISH +#define _meshtastic_Language_MAX meshtastic_Language_TURKISH +#define _meshtastic_Language_ARRAYSIZE ((meshtastic_Language)(meshtastic_Language_TURKISH+1)) + +#define meshtastic_DeviceUIConfig_theme_ENUMTYPE meshtastic_Theme +#define meshtastic_DeviceUIConfig_language_ENUMTYPE meshtastic_Language + + + + +/* Initializer values for message structs */ +#define meshtastic_DeviceUIConfig_init_default {0, 0, 0, _meshtastic_Theme_MIN, 0, _meshtastic_Language_MIN, false, meshtastic_NodeFilter_init_default, false, meshtastic_NodeHighlight_init_default} +#define meshtastic_NodeFilter_init_default {0, 0, 0, 0, 0, ""} +#define meshtastic_NodeHighlight_init_default {0, 0, 0, 0, ""} +#define meshtastic_DeviceUIConfig_init_zero {0, 0, 0, _meshtastic_Theme_MIN, 0, _meshtastic_Language_MIN, false, meshtastic_NodeFilter_init_zero, false, meshtastic_NodeHighlight_init_zero} +#define meshtastic_NodeFilter_init_zero {0, 0, 0, 0, 0, ""} +#define meshtastic_NodeHighlight_init_zero {0, 0, 0, 0, ""} + +/* Field tags (for use in manual encoding/decoding) */ +#define meshtastic_NodeFilter_unknown_switch_tag 1 +#define meshtastic_NodeFilter_offline_switch_tag 2 +#define meshtastic_NodeFilter_public_key_switch_tag 3 +#define meshtastic_NodeFilter_hops_away_tag 4 +#define meshtastic_NodeFilter_position_switch_tag 5 +#define meshtastic_NodeFilter_node_name_tag 6 +#define meshtastic_NodeHighlight_chat_switch_tag 1 +#define meshtastic_NodeHighlight_position_switch_tag 2 +#define meshtastic_NodeHighlight_telemetry_switch_tag 3 +#define meshtastic_NodeHighlight_iaq_switch_tag 4 +#define meshtastic_NodeHighlight_node_name_tag 5 +#define meshtastic_DeviceUIConfig_screen_brightness_tag 1 +#define meshtastic_DeviceUIConfig_screen_timeout_tag 2 +#define meshtastic_DeviceUIConfig_screen_lock_tag 3 +#define meshtastic_DeviceUIConfig_theme_tag 4 +#define meshtastic_DeviceUIConfig_alert_enabled_tag 5 +#define meshtastic_DeviceUIConfig_language_tag 6 +#define meshtastic_DeviceUIConfig_node_filter_tag 7 +#define meshtastic_DeviceUIConfig_node_highlight_tag 8 + +/* Struct field encoding specification for nanopb */ +#define meshtastic_DeviceUIConfig_FIELDLIST(X, a) \ +X(a, STATIC, SINGULAR, UINT32, screen_brightness, 1) \ +X(a, STATIC, SINGULAR, UINT32, screen_timeout, 2) \ +X(a, STATIC, SINGULAR, BOOL, screen_lock, 3) \ +X(a, STATIC, SINGULAR, UENUM, theme, 4) \ +X(a, STATIC, SINGULAR, BOOL, alert_enabled, 5) \ +X(a, STATIC, SINGULAR, UENUM, language, 6) \ +X(a, STATIC, OPTIONAL, MESSAGE, node_filter, 7) \ +X(a, STATIC, OPTIONAL, MESSAGE, node_highlight, 8) +#define meshtastic_DeviceUIConfig_CALLBACK NULL +#define meshtastic_DeviceUIConfig_DEFAULT NULL +#define meshtastic_DeviceUIConfig_node_filter_MSGTYPE meshtastic_NodeFilter +#define meshtastic_DeviceUIConfig_node_highlight_MSGTYPE meshtastic_NodeHighlight + +#define meshtastic_NodeFilter_FIELDLIST(X, a) \ +X(a, STATIC, SINGULAR, BOOL, unknown_switch, 1) \ +X(a, STATIC, SINGULAR, BOOL, offline_switch, 2) \ +X(a, STATIC, SINGULAR, BOOL, public_key_switch, 3) \ +X(a, STATIC, SINGULAR, INT32, hops_away, 4) \ +X(a, STATIC, SINGULAR, BOOL, position_switch, 5) \ +X(a, STATIC, SINGULAR, STRING, node_name, 6) +#define meshtastic_NodeFilter_CALLBACK NULL +#define meshtastic_NodeFilter_DEFAULT NULL + +#define meshtastic_NodeHighlight_FIELDLIST(X, a) \ +X(a, STATIC, SINGULAR, BOOL, chat_switch, 1) \ +X(a, STATIC, SINGULAR, BOOL, position_switch, 2) \ +X(a, STATIC, SINGULAR, BOOL, telemetry_switch, 3) \ +X(a, STATIC, SINGULAR, BOOL, iaq_switch, 4) \ +X(a, STATIC, SINGULAR, STRING, node_name, 5) +#define meshtastic_NodeHighlight_CALLBACK NULL +#define meshtastic_NodeHighlight_DEFAULT NULL + +extern const pb_msgdesc_t meshtastic_DeviceUIConfig_msg; +extern const pb_msgdesc_t meshtastic_NodeFilter_msg; +extern const pb_msgdesc_t meshtastic_NodeHighlight_msg; + +/* Defines for backwards compatibility with code written before nanopb-0.4.0 */ +#define meshtastic_DeviceUIConfig_fields &meshtastic_DeviceUIConfig_msg +#define meshtastic_NodeFilter_fields &meshtastic_NodeFilter_msg +#define meshtastic_NodeHighlight_fields &meshtastic_NodeHighlight_msg + +/* Maximum encoded size of messages (where known) */ +#define MESHTASTIC_MESHTASTIC_DEVICE_UI_PB_H_MAX_SIZE meshtastic_DeviceUIConfig_size +#define meshtastic_DeviceUIConfig_size 80 +#define meshtastic_NodeFilter_size 36 +#define meshtastic_NodeHighlight_size 25 + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/src/mesh/generated/meshtastic/deviceonly.pb.cpp b/src/mesh/generated/meshtastic/deviceonly.pb.cpp index 135634762f..92853f00dd 100644 --- a/src/mesh/generated/meshtastic/deviceonly.pb.cpp +++ b/src/mesh/generated/meshtastic/deviceonly.pb.cpp @@ -21,9 +21,4 @@ PB_BIND(meshtastic_DeviceState, meshtastic_DeviceState, 2) PB_BIND(meshtastic_ChannelFile, meshtastic_ChannelFile, 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 2aa8fda8e4..a90e72244c 100644 --- a/src/mesh/generated/meshtastic/deviceonly.pb.h +++ b/src/mesh/generated/meshtastic/deviceonly.pb.h @@ -6,7 +6,6 @@ #include #include #include "meshtastic/channel.pb.h" -#include "meshtastic/localonly.pb.h" #include "meshtastic/mesh.pb.h" #include "meshtastic/telemetry.pb.h" #include "meshtastic/config.pb.h" @@ -15,17 +14,6 @@ #error Regenerate this file with the current version of nanopb generator. #endif -/* Enum definitions */ -/* Font sizes for the device screen */ -typedef enum _meshtastic_ScreenFonts { - /* TODO: REPLACE */ - meshtastic_ScreenFonts_FONT_SMALL = 0, - /* TODO: REPLACE */ - meshtastic_ScreenFonts_FONT_MEDIUM = 1, - /* TODO: REPLACE */ - meshtastic_ScreenFonts_FONT_LARGE = 2 -} meshtastic_ScreenFonts; - /* Struct definitions */ /* Position with static location information only for NodeDBLite */ typedef struct _meshtastic_PositionLite { @@ -154,65 +142,22 @@ typedef struct _meshtastic_ChannelFile { uint32_t version; } meshtastic_ChannelFile; -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 custom logo and text for 2.5 seconds. */ -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 */ - meshtastic_OEMStore_oem_icon_bits_t oem_icon_bits; - /* Use this font for the OEM text. */ - meshtastic_ScreenFonts oem_font; - /* Use this font for the OEM text. */ - char oem_text[40]; - /* The default device encryption key, 16 or 32 byte */ - meshtastic_OEMStore_oem_aes_key_t oem_aes_key; - /* A Preset LocalConfig to apply during factory reset */ - bool has_oem_local_config; - meshtastic_LocalConfig oem_local_config; - /* A Preset LocalModuleConfig to apply during factory reset */ - bool has_oem_local_module_config; - meshtastic_LocalModuleConfig oem_local_module_config; -} meshtastic_OEMStore; - #ifdef __cplusplus extern "C" { #endif -/* Helper constants for enums */ -#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 meshtastic_PositionLite_location_source_ENUMTYPE meshtastic_Position_LocSource - -#define meshtastic_UserLite_hw_model_ENUMTYPE meshtastic_HardwareModel -#define meshtastic_UserLite_role_ENUMTYPE meshtastic_Config_DeviceConfig_Role - - - - -#define meshtastic_OEMStore_oem_font_ENUMTYPE meshtastic_ScreenFonts - - /* Initializer values for message structs */ #define meshtastic_PositionLite_init_default {0, 0, 0, 0, _meshtastic_Position_LocSource_MIN} #define meshtastic_UserLite_init_default {{0}, "", "", _meshtastic_HardwareModel_MIN, 0, _meshtastic_Config_DeviceConfig_Role_MIN, {0, {0}}} #define meshtastic_NodeInfoLite_init_default {0, false, meshtastic_UserLite_init_default, false, meshtastic_PositionLite_init_default, 0, 0, false, meshtastic_DeviceMetrics_init_default, 0, 0, false, 0, 0} #define meshtastic_DeviceState_init_default {false, meshtastic_MyNodeInfo_init_default, false, meshtastic_User_init_default, 0, {meshtastic_MeshPacket_init_default}, false, meshtastic_MeshPacket_init_default, 0, 0, 0, false, meshtastic_MeshPacket_init_default, 0, {meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default, meshtastic_NodeRemoteHardwarePin_init_default}, {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}}, false, meshtastic_LocalConfig_init_default, false, meshtastic_LocalModuleConfig_init_default} #define meshtastic_PositionLite_init_zero {0, 0, 0, 0, _meshtastic_Position_LocSource_MIN} #define meshtastic_UserLite_init_zero {{0}, "", "", _meshtastic_HardwareModel_MIN, 0, _meshtastic_Config_DeviceConfig_Role_MIN, {0, {0}}} #define meshtastic_NodeInfoLite_init_zero {0, false, meshtastic_UserLite_init_zero, false, meshtastic_PositionLite_init_zero, 0, 0, false, meshtastic_DeviceMetrics_init_zero, 0, 0, false, 0, 0} #define meshtastic_DeviceState_init_zero {false, meshtastic_MyNodeInfo_init_zero, false, meshtastic_User_init_zero, 0, {meshtastic_MeshPacket_init_zero}, false, meshtastic_MeshPacket_init_zero, 0, 0, 0, false, meshtastic_MeshPacket_init_zero, 0, {meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero, meshtastic_NodeRemoteHardwarePin_init_zero}, {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}}, false, meshtastic_LocalConfig_init_zero, false, meshtastic_LocalModuleConfig_init_zero} /* Field tags (for use in manual encoding/decoding) */ #define meshtastic_PositionLite_latitude_i_tag 1 @@ -249,14 +194,6 @@ extern "C" { #define meshtastic_DeviceState_node_db_lite_tag 14 #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 -#define meshtastic_OEMStore_oem_local_config_tag 7 -#define meshtastic_OEMStore_oem_local_module_config_tag 8 /* Struct field encoding specification for nanopb */ #define meshtastic_PositionLite_FIELDLIST(X, a) \ @@ -325,26 +262,11 @@ X(a, STATIC, SINGULAR, UINT32, version, 2) #define meshtastic_ChannelFile_DEFAULT NULL #define meshtastic_ChannelFile_channels_MSGTYPE meshtastic_Channel -#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) \ -X(a, STATIC, OPTIONAL, MESSAGE, oem_local_config, 7) \ -X(a, STATIC, OPTIONAL, MESSAGE, oem_local_module_config, 8) -#define meshtastic_OEMStore_CALLBACK NULL -#define meshtastic_OEMStore_DEFAULT NULL -#define meshtastic_OEMStore_oem_local_config_MSGTYPE meshtastic_LocalConfig -#define meshtastic_OEMStore_oem_local_module_config_MSGTYPE meshtastic_LocalModuleConfig - extern const pb_msgdesc_t meshtastic_PositionLite_msg; extern const pb_msgdesc_t meshtastic_UserLite_msg; extern const pb_msgdesc_t meshtastic_NodeInfoLite_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 meshtastic_PositionLite_fields &meshtastic_PositionLite_msg @@ -352,14 +274,12 @@ extern const pb_msgdesc_t meshtastic_OEMStore_msg; #define meshtastic_NodeInfoLite_fields &meshtastic_NodeInfoLite_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) */ /* meshtastic_DeviceState_size depends on runtime parameters */ -#define MESHTASTIC_MESHTASTIC_DEVICEONLY_PB_H_MAX_SIZE meshtastic_OEMStore_size +#define MESHTASTIC_MESHTASTIC_DEVICEONLY_PB_H_MAX_SIZE meshtastic_ChannelFile_size #define meshtastic_ChannelFile_size 718 #define meshtastic_NodeInfoLite_size 183 -#define meshtastic_OEMStore_size 3578 #define meshtastic_PositionLite_size 28 #define meshtastic_UserLite_size 96 diff --git a/src/mesh/generated/meshtastic/mesh.pb.h b/src/mesh/generated/meshtastic/mesh.pb.h index fb154e9d55..17254354c1 100644 --- a/src/mesh/generated/meshtastic/mesh.pb.h +++ b/src/mesh/generated/meshtastic/mesh.pb.h @@ -10,6 +10,7 @@ #include "meshtastic/portnums.pb.h" #include "meshtastic/telemetry.pb.h" #include "meshtastic/xmodem.pb.h" +#include "meshtastic/device_ui.pb.h" #if PB_PROTO_HEADER_VERSION != 40 #error Regenerate this file with the current version of nanopb generator. @@ -764,6 +765,7 @@ typedef struct _meshtastic_NodeInfo { bool is_favorite; } meshtastic_NodeInfo; +typedef PB_BYTES_ARRAY_T(16) meshtastic_MyNodeInfo_device_id_t; /* 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. */ @@ -777,6 +779,8 @@ typedef struct _meshtastic_MyNodeInfo { /* The minimum app version that can talk to this device. Phone/PC apps should compare this to their build number and if too low tell the user they must update their app */ uint32_t min_app_version; + /* Unique hardware identifier for this device */ + meshtastic_MyNodeInfo_device_id_t device_id; } meshtastic_MyNodeInfo; /* Debug output from the device. @@ -940,6 +944,8 @@ typedef struct _meshtastic_FromRadio { meshtastic_FileInfo fileInfo; /* Notification message to the client */ meshtastic_ClientNotification clientNotification; + /* Persistent data for device-ui */ + meshtastic_DeviceUIConfig deviceuiConfig; }; } meshtastic_FromRadio; @@ -1109,7 +1115,7 @@ extern "C" { #define meshtastic_MqttClientProxyMessage_init_default {"", 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, 0, 0, {0, {0}}, 0} #define meshtastic_NodeInfo_init_default {0, false, meshtastic_User_init_default, false, meshtastic_Position_init_default, 0, 0, false, meshtastic_DeviceMetrics_init_default, 0, 0, false, 0, 0} -#define meshtastic_MyNodeInfo_init_default {0, 0, 0} +#define meshtastic_MyNodeInfo_init_default {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}} @@ -1134,7 +1140,7 @@ extern "C" { #define meshtastic_MqttClientProxyMessage_init_zero {"", 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, 0, 0, {0, {0}}, 0} #define meshtastic_NodeInfo_init_zero {0, false, meshtastic_User_init_zero, false, meshtastic_Position_init_zero, 0, 0, false, meshtastic_DeviceMetrics_init_zero, 0, 0, false, 0, 0} -#define meshtastic_MyNodeInfo_init_zero {0, 0, 0} +#define meshtastic_MyNodeInfo_init_zero {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}} @@ -1241,6 +1247,7 @@ extern "C" { #define meshtastic_MyNodeInfo_my_node_num_tag 1 #define meshtastic_MyNodeInfo_reboot_count_tag 8 #define meshtastic_MyNodeInfo_min_app_version_tag 11 +#define meshtastic_MyNodeInfo_device_id_tag 12 #define meshtastic_LogRecord_message_tag 1 #define meshtastic_LogRecord_time_tag 2 #define meshtastic_LogRecord_source_tag 3 @@ -1292,6 +1299,7 @@ extern "C" { #define meshtastic_FromRadio_mqttClientProxyMessage_tag 14 #define meshtastic_FromRadio_fileInfo_tag 15 #define meshtastic_FromRadio_clientNotification_tag 16 +#define meshtastic_FromRadio_deviceuiConfig_tag 17 #define meshtastic_ToRadio_packet_tag 1 #define meshtastic_ToRadio_want_config_id_tag 3 #define meshtastic_ToRadio_disconnect_tag 4 @@ -1442,7 +1450,8 @@ X(a, STATIC, SINGULAR, BOOL, is_favorite, 10) #define meshtastic_MyNodeInfo_FIELDLIST(X, a) \ X(a, STATIC, SINGULAR, UINT32, my_node_num, 1) \ X(a, STATIC, SINGULAR, UINT32, reboot_count, 8) \ -X(a, STATIC, SINGULAR, UINT32, min_app_version, 11) +X(a, STATIC, SINGULAR, UINT32, min_app_version, 11) \ +X(a, STATIC, SINGULAR, BYTES, device_id, 12) #define meshtastic_MyNodeInfo_CALLBACK NULL #define meshtastic_MyNodeInfo_DEFAULT NULL @@ -1478,7 +1487,8 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,xmodemPacket,xmodemPacket), X(a, STATIC, ONEOF, MESSAGE, (payload_variant,metadata,metadata), 13) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,mqttClientProxyMessage,mqttClientProxyMessage), 14) \ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,fileInfo,fileInfo), 15) \ -X(a, STATIC, ONEOF, MESSAGE, (payload_variant,clientNotification,clientNotification), 16) +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,clientNotification,clientNotification), 16) \ +X(a, STATIC, ONEOF, MESSAGE, (payload_variant,deviceuiConfig,deviceuiConfig), 17) #define meshtastic_FromRadio_CALLBACK NULL #define meshtastic_FromRadio_DEFAULT NULL #define meshtastic_FromRadio_payload_variant_packet_MSGTYPE meshtastic_MeshPacket @@ -1494,6 +1504,7 @@ X(a, STATIC, ONEOF, MESSAGE, (payload_variant,clientNotification,clientNot #define meshtastic_FromRadio_payload_variant_mqttClientProxyMessage_MSGTYPE meshtastic_MqttClientProxyMessage #define meshtastic_FromRadio_payload_variant_fileInfo_MSGTYPE meshtastic_FileInfo #define meshtastic_FromRadio_payload_variant_clientNotification_MSGTYPE meshtastic_ClientNotification +#define meshtastic_FromRadio_payload_variant_deviceuiConfig_MSGTYPE meshtastic_DeviceUIConfig #define meshtastic_ClientNotification_FIELDLIST(X, a) \ X(a, STATIC, OPTIONAL, UINT32, reply_id, 1) \ @@ -1663,7 +1674,7 @@ extern const pb_msgdesc_t meshtastic_ChunkedPayloadResponse_msg; #define meshtastic_LogRecord_size 426 #define meshtastic_MeshPacket_size 367 #define meshtastic_MqttClientProxyMessage_size 501 -#define meshtastic_MyNodeInfo_size 18 +#define meshtastic_MyNodeInfo_size 36 #define meshtastic_NeighborInfo_size 258 #define meshtastic_Neighbor_size 22 #define meshtastic_NodeInfo_size 317 diff --git a/src/mesh/generated/meshtastic/rtttl.pb.h b/src/mesh/generated/meshtastic/rtttl.pb.h index 2b7e35f116..0572265f7a 100644 --- a/src/mesh/generated/meshtastic/rtttl.pb.h +++ b/src/mesh/generated/meshtastic/rtttl.pb.h @@ -13,7 +13,7 @@ /* Canned message module configuration. */ typedef struct _meshtastic_RTTTLConfig { /* Ringtone for PWM Buzzer in RTTTL Format. */ - char ringtone[230]; + char ringtone[231]; } meshtastic_RTTTLConfig; @@ -41,7 +41,7 @@ extern const pb_msgdesc_t meshtastic_RTTTLConfig_msg; /* Maximum encoded size of messages (where known) */ #define MESHTASTIC_MESHTASTIC_RTTTL_PB_H_MAX_SIZE meshtastic_RTTTLConfig_size -#define meshtastic_RTTTLConfig_size 232 +#define meshtastic_RTTTLConfig_size 233 #ifdef __cplusplus } /* extern "C" */ diff --git a/src/mesh/generated/meshtastic/telemetry.pb.h b/src/mesh/generated/meshtastic/telemetry.pb.h index a33988129e..309c01dc7e 100644 --- a/src/mesh/generated/meshtastic/telemetry.pb.h +++ b/src/mesh/generated/meshtastic/telemetry.pb.h @@ -74,8 +74,10 @@ typedef enum _meshtastic_TelemetrySensorType { meshtastic_TelemetrySensorType_CUSTOM_SENSOR = 29, /* MAX30102 Pulse Oximeter and Heart-Rate Sensor */ meshtastic_TelemetrySensorType_MAX30102 = 30, - /* MLX90614 non-contact IR temperature sensor. */ - meshtastic_TelemetrySensorType_MLX90614 = 31 + /* MLX90614 non-contact IR temperature sensor */ + meshtastic_TelemetrySensorType_MLX90614 = 31, + /* SCD40/SCD41 CO2, humidity, temperature sensor */ + meshtastic_TelemetrySensorType_SCD4X = 32 } meshtastic_TelemetrySensorType; /* Struct definitions */ @@ -215,6 +217,9 @@ typedef struct _meshtastic_AirQualityMetrics { /* 10.0um Particle Count */ bool has_particles_100um; uint32_t particles_100um; + /* 10.0um Particle Count */ + bool has_co2; + uint32_t co2; } meshtastic_AirQualityMetrics; /* Local device mesh statistics */ @@ -294,8 +299,8 @@ extern "C" { /* Helper constants for enums */ #define _meshtastic_TelemetrySensorType_MIN meshtastic_TelemetrySensorType_SENSOR_UNSET -#define _meshtastic_TelemetrySensorType_MAX meshtastic_TelemetrySensorType_MLX90614 -#define _meshtastic_TelemetrySensorType_ARRAYSIZE ((meshtastic_TelemetrySensorType)(meshtastic_TelemetrySensorType_MLX90614+1)) +#define _meshtastic_TelemetrySensorType_MAX meshtastic_TelemetrySensorType_SCD4X +#define _meshtastic_TelemetrySensorType_ARRAYSIZE ((meshtastic_TelemetrySensorType)(meshtastic_TelemetrySensorType_SCD4X+1)) @@ -310,7 +315,7 @@ extern "C" { #define meshtastic_DeviceMetrics_init_default {false, 0, false, 0, false, 0, false, 0, false, 0} #define meshtastic_EnvironmentMetrics_init_default {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} #define meshtastic_PowerMetrics_init_default {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} -#define meshtastic_AirQualityMetrics_init_default {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} +#define meshtastic_AirQualityMetrics_init_default {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} #define meshtastic_LocalStats_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #define meshtastic_HealthMetrics_init_default {false, 0, false, 0, false, 0} #define meshtastic_Telemetry_init_default {0, 0, {meshtastic_DeviceMetrics_init_default}} @@ -318,7 +323,7 @@ extern "C" { #define meshtastic_DeviceMetrics_init_zero {false, 0, false, 0, false, 0, false, 0, false, 0} #define meshtastic_EnvironmentMetrics_init_zero {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} #define meshtastic_PowerMetrics_init_zero {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} -#define meshtastic_AirQualityMetrics_init_zero {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} +#define meshtastic_AirQualityMetrics_init_zero {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0} #define meshtastic_LocalStats_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} #define meshtastic_HealthMetrics_init_zero {false, 0, false, 0, false, 0} #define meshtastic_Telemetry_init_zero {0, 0, {meshtastic_DeviceMetrics_init_zero}} @@ -365,6 +370,7 @@ extern "C" { #define meshtastic_AirQualityMetrics_particles_25um_tag 10 #define meshtastic_AirQualityMetrics_particles_50um_tag 11 #define meshtastic_AirQualityMetrics_particles_100um_tag 12 +#define meshtastic_AirQualityMetrics_co2_tag 13 #define meshtastic_LocalStats_uptime_seconds_tag 1 #define meshtastic_LocalStats_channel_utilization_tag 2 #define meshtastic_LocalStats_air_util_tx_tag 3 @@ -442,7 +448,8 @@ X(a, STATIC, OPTIONAL, UINT32, particles_05um, 8) \ X(a, STATIC, OPTIONAL, UINT32, particles_10um, 9) \ X(a, STATIC, OPTIONAL, UINT32, particles_25um, 10) \ X(a, STATIC, OPTIONAL, UINT32, particles_50um, 11) \ -X(a, STATIC, OPTIONAL, UINT32, particles_100um, 12) +X(a, STATIC, OPTIONAL, UINT32, particles_100um, 12) \ +X(a, STATIC, OPTIONAL, UINT32, co2, 13) #define meshtastic_AirQualityMetrics_CALLBACK NULL #define meshtastic_AirQualityMetrics_DEFAULT NULL @@ -512,7 +519,7 @@ extern const pb_msgdesc_t meshtastic_Nau7802Config_msg; /* Maximum encoded size of messages (where known) */ #define MESHTASTIC_MESHTASTIC_TELEMETRY_PB_H_MAX_SIZE meshtastic_Telemetry_size -#define meshtastic_AirQualityMetrics_size 72 +#define meshtastic_AirQualityMetrics_size 78 #define meshtastic_DeviceMetrics_size 27 #define meshtastic_EnvironmentMetrics_size 85 #define meshtastic_HealthMetrics_size 11 diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index c5ea86429e..8535a335fc 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -143,7 +143,7 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) { - LOG_DEBUG("webAPI handleAPIv1FromRadio\n"); + LOG_DEBUG("webAPI handleAPIv1FromRadio"); /* For documentation, see: @@ -188,12 +188,12 @@ void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) res->write(txBuf, len); } - LOG_DEBUG("webAPI handleAPIv1FromRadio, len %d\n", len); + LOG_DEBUG("webAPI handleAPIv1FromRadio, len %d", len); } void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res) { - LOG_DEBUG("webAPI handleAPIv1ToRadio\n"); + LOG_DEBUG("webAPI handleAPIv1ToRadio"); /* For documentation, see: @@ -216,11 +216,11 @@ void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res) byte buffer[MAX_TO_FROM_RADIO_SIZE]; size_t s = req->readBytes(buffer, MAX_TO_FROM_RADIO_SIZE); - LOG_DEBUG("Received %d bytes from PUT request\n", s); + LOG_DEBUG("Received %d bytes from PUT request", s); webAPI.handleToRadio(buffer, s); res->write(buffer, s); - LOG_DEBUG("webAPI handleAPIv1ToRadio\n"); + LOG_DEBUG("webAPI handleAPIv1ToRadio"); } void htmlDeleteDir(const char *dirname) @@ -243,7 +243,7 @@ void htmlDeleteDir(const char *dirname) String fileName = String(file.name()); file.flush(); file.close(); - LOG_DEBUG(" %s\n", fileName.c_str()); + LOG_DEBUG(" %s", fileName.c_str()); FSCom.remove(fileName); } file = root.openNextFile(); @@ -341,7 +341,7 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res) if (params->getQueryParameter("delete", paramValDelete)) { std::string pathDelete = "/" + paramValDelete; if (FSCom.remove(pathDelete.c_str())) { - LOG_INFO("%s\n", pathDelete.c_str()); + LOG_INFO("%s", pathDelete.c_str()); JSONObject jsonObjOuter; jsonObjOuter["status"] = new JSONValue("ok"); JSONValue *value = new JSONValue(jsonObjOuter); @@ -349,7 +349,7 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res) delete value; return; } else { - LOG_INFO("%s\n", pathDelete.c_str()); + LOG_INFO("%s", pathDelete.c_str()); JSONObject jsonObjOuter; jsonObjOuter["status"] = new JSONValue("Error"); JSONValue *value = new JSONValue(jsonObjOuter); @@ -385,13 +385,13 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) if (FSCom.exists(filename.c_str())) { file = FSCom.open(filename.c_str()); if (!file.available()) { - LOG_WARN("File not available - %s\n", filename.c_str()); + LOG_WARN("File not available - %s", filename.c_str()); } } else if (FSCom.exists(filenameGzip.c_str())) { file = FSCom.open(filenameGzip.c_str()); res->setHeader("Content-Encoding", "gzip"); if (!file.available()) { - LOG_WARN("File not available - %s\n", filenameGzip.c_str()); + LOG_WARN("File not available - %s", filenameGzip.c_str()); } } else { has_set_content_type = true; @@ -399,7 +399,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) file = FSCom.open(filenameGzip.c_str()); res->setHeader("Content-Type", "text/html"); if (!file.available()) { - LOG_WARN("File not available - %s\n", filenameGzip.c_str()); + LOG_WARN("File not available - %s", filenameGzip.c_str()); res->println("Web server is running.

The content you are looking for can't be found. Please see: FAQ.

admin"); @@ -441,7 +441,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) return; } else { - LOG_ERROR("This should not have happened...\n"); + LOG_ERROR("This should not have happened..."); res->println("ERROR: This should not have happened..."); } } @@ -449,7 +449,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) void handleFormUpload(HTTPRequest *req, HTTPResponse *res) { - LOG_DEBUG("Form Upload - Disabling keep-alive\n"); + LOG_DEBUG("Form Upload - Disabling keep-alive"); res->setHeader("Connection", "close"); // First, we need to check the encoding of the form that we have received. @@ -457,7 +457,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) // Then we select the body parser based on the encoding. // Actually we do this only for documentary purposes, we know the form is going // to be multipart/form-data. - LOG_DEBUG("Form Upload - Creating body parser reference\n"); + LOG_DEBUG("Form Upload - Creating body parser reference"); HTTPBodyParser *parser; std::string contentType = req->getHeader("Content-Type"); @@ -473,10 +473,10 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) // Now, we can decide based on the content type: if (contentType == "multipart/form-data") { - LOG_DEBUG("Form Upload - multipart/form-data\n"); + LOG_DEBUG("Form Upload - multipart/form-data"); parser = new HTTPMultipartBodyParser(req); } else { - LOG_DEBUG("Unknown POST Content-Type: %s\n", contentType.c_str()); + LOG_DEBUG("Unknown POST Content-Type: %s", contentType.c_str()); return; } @@ -503,19 +503,19 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) std::string filename = parser->getFieldFilename(); std::string mimeType = parser->getFieldMimeType(); // We log all three values, so that you can observe the upload on the serial monitor: - LOG_DEBUG("handleFormUpload: field name='%s', filename='%s', mimetype='%s'\n", name.c_str(), filename.c_str(), + LOG_DEBUG("handleFormUpload: field name='%s', filename='%s', mimetype='%s'", name.c_str(), filename.c_str(), mimeType.c_str()); // Double check that it is what we expect if (name != "file") { - LOG_DEBUG("Skipping unexpected field\n"); + LOG_DEBUG("Skipping unexpected field"); res->println("

No file found.

"); return; } // Double check that it is what we expect if (filename == "") { - LOG_DEBUG("Skipping unexpected field\n"); + LOG_DEBUG("Skipping unexpected field"); res->println("

No file found.

"); return; } @@ -536,7 +536,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) byte buf[512]; size_t readLength = parser->read(buf, 512); - // LOG_DEBUG("\n\nreadLength - %i\n", readLength); + // LOG_DEBUG("readLength - %i", readLength); // Abort the transfer if there is less than 50k space left on the filesystem. if (FSCom.totalBytes() - FSCom.usedBytes() < 51200) { @@ -553,7 +553,7 @@ void handleFormUpload(HTTPRequest *req, HTTPResponse *res) // if (readLength) { file.write(buf, readLength); fileLength += readLength; - LOG_DEBUG("File Length %i\n", fileLength); + LOG_DEBUG("File Length %i", fileLength); //} } // enableLoopWDT(); @@ -676,7 +676,7 @@ void handleReport(HTTPRequest *req, HTTPResponse *res) */ void handleHotspot(HTTPRequest *req, HTTPResponse *res) { - LOG_INFO("Hotspot Request\n"); + LOG_INFO("Hotspot Request"); /* If we don't do a redirect, be sure to return a "Success" message @@ -690,7 +690,7 @@ void handleHotspot(HTTPRequest *req, HTTPResponse *res) res->setHeader("Access-Control-Allow-Methods", "GET"); // res->println(""); - res->println("\n"); + res->println(""); } void handleDeleteFsContent(HTTPRequest *req, HTTPResponse *res) @@ -699,14 +699,14 @@ void handleDeleteFsContent(HTTPRequest *req, HTTPResponse *res) res->setHeader("Access-Control-Allow-Origin", "*"); res->setHeader("Access-Control-Allow-Methods", "GET"); - res->println("

Meshtastic

\n"); + res->println("

Meshtastic

"); res->println("Deleting Content in /static/*"); - LOG_INFO("Deleting files from /static/* : \n"); + LOG_INFO("Deleting files from /static/* : "); htmlDeleteDir("/static"); - res->println("


Back to admin\n"); + res->println("


Back to admin"); } void handleAdmin(HTTPRequest *req, HTTPResponse *res) @@ -715,10 +715,10 @@ void handleAdmin(HTTPRequest *req, HTTPResponse *res) res->setHeader("Access-Control-Allow-Origin", "*"); res->setHeader("Access-Control-Allow-Methods", "GET"); - res->println("

Meshtastic

\n"); - // res->println("Settings
\n"); - // res->println("Manage Web Content
\n"); - res->println("Device Report
\n"); + res->println("

Meshtastic

"); + // res->println("Settings
"); + // res->println("Manage Web Content
"); + res->println("Device Report
"); } void handleAdminSettings(HTTPRequest *req, HTTPResponse *res) @@ -727,20 +727,20 @@ void handleAdminSettings(HTTPRequest *req, HTTPResponse *res) res->setHeader("Access-Control-Allow-Origin", "*"); res->setHeader("Access-Control-Allow-Methods", "GET"); - res->println("

Meshtastic

\n"); - res->println("This isn't done.\n"); - res->println("
\n"); - res->println("\n"); - res->println("\n"); - res->println("\n"); - res->println("\n"); + res->println("

Meshtastic

"); + res->println("This isn't done."); + res->println(""); + res->println("
Set?Settingcurrent valuenew value
WiFi SSIDfalse
WiFi Passwordfalse
"); + res->println(""); + res->println(""); + res->println(""); res->println( - "\n"); - res->println("
Set?Settingcurrent valuenew value
WiFi SSIDfalse
WiFi Passwordfalse
Smart Position Updatefalse
\n"); - res->println("\n"); - res->println("\n"); - res->println("\n"); - res->println("


Back to admin\n"); + "

"); + res->println("
Smart Position Updatefalse
"); + res->println(""); + res->println(""); + res->println(""); + res->println("


Back to admin"); } void handleAdminSettingsApply(HTTPRequest *req, HTTPResponse *res) @@ -748,11 +748,11 @@ void handleAdminSettingsApply(HTTPRequest *req, HTTPResponse *res) res->setHeader("Content-Type", "text/html"); res->setHeader("Access-Control-Allow-Origin", "*"); res->setHeader("Access-Control-Allow-Methods", "POST"); - res->println("

Meshtastic

\n"); + res->println("

Meshtastic

"); res->println( "Settings Applied. "); - res->println("Settings Applied. Please wait.\n"); + res->println("Settings Applied. Please wait."); } void handleFs(HTTPRequest *req, HTTPResponse *res) @@ -761,10 +761,10 @@ void handleFs(HTTPRequest *req, HTTPResponse *res) res->setHeader("Access-Control-Allow-Origin", "*"); res->setHeader("Access-Control-Allow-Methods", "GET"); - res->println("

Meshtastic

\n"); + res->println("

Meshtastic

"); res->println("Delete Web Content

Be patient!"); - res->println("


Back to admin\n"); + res->println("


Back to admin"); } void handleRestart(HTTPRequest *req, HTTPResponse *res) @@ -773,10 +773,10 @@ void handleRestart(HTTPRequest *req, HTTPResponse *res) res->setHeader("Access-Control-Allow-Origin", "*"); res->setHeader("Access-Control-Allow-Methods", "GET"); - res->println("

Meshtastic

\n"); + res->println("

Meshtastic

"); res->println("Restarting"); - LOG_DEBUG("Restarted on HTTP(s) Request\n"); + LOG_DEBUG("Restarted on HTTP(s) Request"); webServerThread->requestRestart = (millis() / 1000) + 5; } diff --git a/src/mesh/http/WebServer.cpp b/src/mesh/http/WebServer.cpp index fc8535257b..62a8431fa0 100644 --- a/src/mesh/http/WebServer.cpp +++ b/src/mesh/http/WebServer.cpp @@ -69,19 +69,19 @@ static void taskCreateCert(void *parameter) #if 0 // Delete the saved certs (used in debugging) - LOG_DEBUG("Deleting any saved SSL keys ...\n"); + LOG_DEBUG("Deleting any saved SSL keys ..."); // prefs.clear(); prefs.remove("PK"); prefs.remove("cert"); #endif - LOG_INFO("Checking if we have a previously saved SSL Certificate.\n"); + LOG_INFO("Checking if we have a previously saved SSL Certificate."); size_t pkLen = prefs.getBytesLength("PK"); size_t certLen = prefs.getBytesLength("cert"); if (pkLen && certLen) { - LOG_INFO("Existing SSL Certificate found!\n"); + LOG_INFO("Existing SSL Certificate found!"); uint8_t *pkBuffer = new uint8_t[pkLen]; prefs.getBytes("PK", pkBuffer, pkLen); @@ -91,11 +91,11 @@ static void taskCreateCert(void *parameter) cert = new SSLCert(certBuffer, certLen, pkBuffer, pkLen); - LOG_DEBUG("Retrieved Private Key: %d Bytes\n", cert->getPKLength()); - LOG_DEBUG("Retrieved Certificate: %d Bytes\n", cert->getCertLength()); + LOG_DEBUG("Retrieved Private Key: %d Bytes", cert->getPKLength()); + LOG_DEBUG("Retrieved Certificate: %d Bytes", cert->getCertLength()); } else { - LOG_INFO("Creating the certificate. This may take a while. Please wait...\n"); + LOG_INFO("Creating the certificate. This may take a while. Please wait..."); yield(); cert = new SSLCert(); yield(); @@ -104,13 +104,13 @@ static void taskCreateCert(void *parameter) yield(); if (createCertResult != 0) { - LOG_ERROR("Creating the certificate failed\n"); + LOG_ERROR("Creating the certificate failed"); } else { - LOG_INFO("Creating the certificate was successful\n"); + LOG_INFO("Creating the certificate was successful"); - LOG_DEBUG("Created Private Key: %d Bytes\n", cert->getPKLength()); + LOG_DEBUG("Created Private Key: %d Bytes", cert->getPKLength()); - LOG_DEBUG("Created Certificate: %d Bytes\n", cert->getCertLength()); + LOG_DEBUG("Created Certificate: %d Bytes", cert->getCertLength()); prefs.putBytes("PK", (uint8_t *)cert->getPKData(), cert->getPKLength()); prefs.putBytes("cert", (uint8_t *)cert->getCertData(), cert->getCertLength()); @@ -139,7 +139,7 @@ void createSSLCert() 16, /* Priority of the task. */ NULL); /* Task handle. */ - LOG_DEBUG("Waiting for SSL Cert to be generated.\n"); + LOG_DEBUG("Waiting for SSL Cert to be generated."); while (!isCertReady) { if ((millis() / 500) % 2) { if (runLoop) { @@ -158,7 +158,7 @@ void createSSLCert() runLoop = true; } } - LOG_INFO("SSL Cert Ready!\n"); + LOG_INFO("SSL Cert Ready!"); } } @@ -189,7 +189,7 @@ int32_t WebServerThread::runOnce() void initWebServer() { - LOG_DEBUG("Initializing Web Server ...\n"); + LOG_DEBUG("Initializing Web Server ..."); // We can now use the new certificate to setup our server as usual. secureServer = new HTTPSServer(cert); @@ -198,16 +198,16 @@ void initWebServer() registerHandlers(insecureServer, secureServer); if (secureServer) { - LOG_INFO("Starting Secure Web Server...\n"); + LOG_INFO("Starting Secure Web Server..."); secureServer->start(); } - LOG_INFO("Starting Insecure Web Server...\n"); + LOG_INFO("Starting Insecure Web Server..."); insecureServer->start(); if (insecureServer->isRunning()) { - LOG_INFO("Web Servers Ready! :-) \n"); + LOG_INFO("Web Servers Ready! :-) "); isWebServerReady = true; } else { - LOG_ERROR("Web Servers Failed! ;-( \n"); + LOG_ERROR("Web Servers Failed! ;-( "); } } #endif \ No newline at end of file diff --git a/src/mesh/mesh-pb-constants.cpp b/src/mesh/mesh-pb-constants.cpp index 5b5d669ccf..a279cd9911 100644 --- a/src/mesh/mesh-pb-constants.cpp +++ b/src/mesh/mesh-pb-constants.cpp @@ -13,7 +13,7 @@ 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)); + LOG_ERROR("Panic: can't encode protobuf reason='%s'", PB_GET_ERROR(&stream)); assert( 0); // If this assert fails it probably means you made a field too large for the max limits specified in mesh.options return 0; @@ -27,7 +27,7 @@ bool pb_decode_from_bytes(const uint8_t *srcbuf, size_t srcbufsize, const pb_msg { pb_istream_t stream = pb_istream_from_buffer(srcbuf, srcbufsize); if (!pb_decode(&stream, fields, dest_struct)) { - LOG_ERROR("Can't decode protobuf reason='%s', pb_msgdesc %p\n", PB_GET_ERROR(&stream), fields); + LOG_ERROR("Can't decode protobuf reason='%s', pb_msgdesc %p", PB_GET_ERROR(&stream), fields); return false; } else { return true; @@ -59,7 +59,7 @@ bool readcb(pb_istream_t *stream, uint8_t *buf, size_t count) bool writecb(pb_ostream_t *stream, const uint8_t *buf, size_t count) { auto file = (Print *)stream->state; - // LOG_DEBUG("writing %d bytes to protobuf file\n", count); + // LOG_DEBUG("writing %d bytes to protobuf file", count); return file->write(buf, count) == count; } #endif diff --git a/src/mesh/raspihttp/PiWebServer.cpp b/src/mesh/raspihttp/PiWebServer.cpp index d7e5967595..711a81024e 100644 --- a/src/mesh/raspihttp/PiWebServer.cpp +++ b/src/mesh/raspihttp/PiWebServer.cpp @@ -178,14 +178,14 @@ int callback_static_file(const struct _u_request *request, struct _u_response *r content_type = u_map_get_case(&configWeb.mime_types, get_filename_ext(file_requested)); if (content_type == NULL) { content_type = u_map_get(&configWeb.mime_types, "*"); - LOG_DEBUG("Static File Server - Unknown mime type for extension %s \n", get_filename_ext(file_requested)); + LOG_DEBUG("Static File Server - Unknown mime type for extension %s ", get_filename_ext(file_requested)); } u_map_put(response->map_header, "Content-Type", content_type); u_map_copy_into(response->map_header, &configWeb.map_header); if (ulfius_set_stream_response(response, 200, callback_static_file_stream, callback_static_file_stream_free, length, STATIC_FILE_CHUNK, f) != U_OK) { - LOG_DEBUG("callback_static_file - Error ulfius_set_stream_response\n "); + LOG_DEBUG("callback_static_file - Error ulfius_set_stream_response"); } } } else { @@ -210,7 +210,7 @@ int callback_static_file(const struct _u_request *request, struct _u_response *r free(real_path); // realpath uses malloc return U_CALLBACK_CONTINUE; } else { - LOG_DEBUG("Static File Server - Error, user_data is NULL or inconsistent\n"); + LOG_DEBUG("Static File Server - Error, user_data is NULL or inconsistent"); return U_CALLBACK_ERROR; } } @@ -223,7 +223,7 @@ static void handleWebResponse() {} */ int handleAPIv1ToRadio(const struct _u_request *req, struct _u_response *res, void *user_data) { - LOG_DEBUG("handleAPIv1ToRadio web -> radio \n"); + LOG_DEBUG("handleAPIv1ToRadio web -> radio "); ulfius_add_header_to_response(res, "Content-Type", "application/x-protobuf"); ulfius_add_header_to_response(res, "Access-Control-Allow-Headers", "Content-Type"); @@ -246,9 +246,9 @@ int handleAPIv1ToRadio(const struct _u_request *req, struct _u_response *res, vo portduinoVFS->mountpoint(configWeb.rootPath); - LOG_DEBUG("Received %d bytes from PUT request\n", s); + LOG_DEBUG("Received %d bytes from PUT request", s); webAPI.handleToRadio(buffer, s); - LOG_DEBUG("end web->radio \n"); + LOG_DEBUG("end web->radio "); return U_CALLBACK_COMPLETE; } @@ -259,7 +259,7 @@ int handleAPIv1ToRadio(const struct _u_request *req, struct _u_response *res, vo int handleAPIv1FromRadio(const struct _u_request *req, struct _u_response *res, void *user_data) { - // LOG_DEBUG("handleAPIv1FromRadio radio -> web\n"); + // LOG_DEBUG("handleAPIv1FromRadio radio -> web"); std::string valueAll; // Status code is 200 OK by default. @@ -278,21 +278,21 @@ int handleAPIv1FromRadio(const struct _u_request *req, struct _u_response *res, ulfius_set_response_properties(res, U_OPT_STATUS, 200, U_OPT_BINARY_BODY, txBuf, len); const char *tmpa = (const char *)txBuf; ulfius_set_string_body_response(res, 200, tmpa); - // LOG_DEBUG("\n----webAPI response all:----\n"); + // LOG_DEBUG("\n----webAPI response all:----"); // LOG_DEBUG(tmpa); - // LOG_DEBUG("\n"); + // LOG_DEBUG(""); } // Otherwise, just return one protobuf } else { len = webAPI.getFromRadio(txBuf); const char *tmpa = (const char *)txBuf; ulfius_set_binary_body_response(res, 200, tmpa, len); - // LOG_DEBUG("\n----webAPI response:\n"); + // LOG_DEBUG("\n----webAPI response:"); // LOG_DEBUG(tmpa); - // LOG_DEBUG("\n"); + // LOG_DEBUG(""); } - // LOG_DEBUG("end radio->web\n", len); + // LOG_DEBUG("end radio->web", len); return U_CALLBACK_COMPLETE; } @@ -346,7 +346,7 @@ char *read_file_into_string(const char *filename) { FILE *file = fopen(filename, "rb"); if (file == NULL) { - LOG_ERROR("Error reading File : %s \n", filename); + LOG_ERROR("Error reading File : %s ", filename); return NULL; } @@ -358,7 +358,7 @@ char *read_file_into_string(const char *filename) // reserve mem for file + 1 byte char *buffer = (char *)malloc(filesize + 1); if (buffer == NULL) { - LOG_ERROR("Malloc of mem failed for file : %s \n", filename); + LOG_ERROR("Malloc of mem failed for file : %s ", filename); fclose(file); return NULL; } @@ -366,7 +366,7 @@ char *read_file_into_string(const char *filename) // read content size_t readSize = fread(buffer, 1, filesize, file); if (readSize != filesize) { - LOG_ERROR("Error reading file into buffer\n"); + LOG_ERROR("Error reading file into buffer"); free(buffer); fclose(file); return NULL; @@ -383,13 +383,13 @@ int PiWebServerThread::CheckSSLandLoad() // read certificate cert_pem = read_file_into_string("certificate.pem"); if (cert_pem == NULL) { - LOG_ERROR("ERROR SSL Certificate File can't be loaded or is missing\n"); + LOG_ERROR("ERROR SSL Certificate File can't be loaded or is missing"); return 1; } // read private key key_pem = read_file_into_string("private_key.pem"); if (key_pem == NULL) { - LOG_ERROR("ERROR file private_key can't be loaded or is missing\n"); + LOG_ERROR("ERROR file private_key can't be loaded or is missing"); return 2; } @@ -403,19 +403,19 @@ int PiWebServerThread::CreateSSLCertificate() X509 *x509 = NULL; if (generate_rsa_key(&pkey) != 0) { - LOG_ERROR("Error generating RSA-Key.\n"); + LOG_ERROR("Error generating RSA-Key."); return 1; } if (generate_self_signed_x509(pkey, &x509) != 0) { - LOG_ERROR("Error generating of X509-Certificat.\n"); + LOG_ERROR("Error generating of X509-Certificat."); return 2; } // Ope file to write private key file FILE *pkey_file = fopen("private_key.pem", "wb"); if (!pkey_file) { - LOG_ERROR("Error opening private key file.\n"); + LOG_ERROR("Error opening private key file."); return 3; } // write private key file @@ -425,7 +425,7 @@ int PiWebServerThread::CreateSSLCertificate() // open Certificate file FILE *x509_file = fopen("certificate.pem", "wb"); if (!x509_file) { - LOG_ERROR("Error opening certificate.\n"); + LOG_ERROR("Error opening certificate."); return 4; } // write cirtificate @@ -434,7 +434,7 @@ int PiWebServerThread::CreateSSLCertificate() EVP_PKEY_free(pkey); X509_free(x509); - LOG_INFO("Create SSL Certifictate -certificate.pem- succesfull \n"); + LOG_INFO("Create SSL Certifictate -certificate.pem- succesfull "); return 0; } @@ -447,24 +447,24 @@ PiWebServerThread::PiWebServerThread() if (CheckSSLandLoad() != 0) { CreateSSLCertificate(); if (CheckSSLandLoad() != 0) { - LOG_ERROR("Major Error Gen & Read SSL Certificate\n"); + LOG_ERROR("Major Error Gen & Read SSL Certificate"); } } if (settingsMap[webserverport] != 0) { webservport = settingsMap[webserverport]; - LOG_INFO("Using webserver port from yaml config. %i \n", webservport); + LOG_INFO("Using webserver port from yaml config. %i ", webservport); } else { - LOG_INFO("Webserver port in yaml config set to 0, so defaulting to port 443.\n"); + LOG_INFO("Webserver port in yaml config set to 0, so defaulting to port 443."); webservport = 443; } // Web Content Service Instance if (ulfius_init_instance(&instanceWeb, webservport, NULL, DEFAULT_REALM) != U_OK) { - LOG_ERROR("Webserver couldn't be started, abort execution\n"); + LOG_ERROR("Webserver couldn't be started, abort execution"); } else { - LOG_INFO("Webserver started ....\n"); + LOG_INFO("Webserver started ...."); u_map_init(&configWeb.mime_types); u_map_put(&configWeb.mime_types, "*", "application/octet-stream"); u_map_put(&configWeb.mime_types, ".html", "text/html"); @@ -505,10 +505,10 @@ PiWebServerThread::PiWebServerThread() retssl = ulfius_start_secure_framework(&instanceWeb, key_pem, cert_pem); if (retssl == U_OK) { - LOG_INFO("Web Server framework started on port: %i \n", webservport); - LOG_INFO("Web Server root %s\n", (char *)webrootpath.c_str()); + LOG_INFO("Web Server framework started on port: %i ", webservport); + LOG_INFO("Web Server root %s", (char *)webrootpath.c_str()); } else { - LOG_ERROR("Error starting Web Server framework, error number: %d\n", retssl); + LOG_ERROR("Error starting Web Server framework, error number: %d", retssl); } } } diff --git a/src/mesh/wifi/WiFiAPClient.cpp b/src/mesh/wifi/WiFiAPClient.cpp index c835878d32..e760a82761 100644 --- a/src/mesh/wifi/WiFiAPClient.cpp +++ b/src/mesh/wifi/WiFiAPClient.cpp @@ -57,30 +57,30 @@ static void onNetworkConnected() { if (!APStartupComplete) { // Start web server - LOG_INFO("Starting WiFi network services\n"); + LOG_INFO("Starting WiFi network services"); #ifdef ARCH_ESP32 // start mdns if (!MDNS.begin("Meshtastic")) { - LOG_ERROR("Error setting up MDNS responder!\n"); + LOG_ERROR("Error setting up MDNS responder!"); } else { - LOG_INFO("mDNS responder started\n"); - LOG_INFO("mDNS Host: Meshtastic.local\n"); + LOG_INFO("mDNS responder started"); + LOG_INFO("mDNS Host: Meshtastic.local"); MDNS.addService("http", "tcp", 80); MDNS.addService("https", "tcp", 443); } #else // ESP32 handles this in WiFiEvent - LOG_INFO("Obtained IP address: %s\n", WiFi.localIP().toString().c_str()); + LOG_INFO("Obtained IP address: %s", WiFi.localIP().toString().c_str()); #endif #ifndef DISABLE_NTP - LOG_INFO("Starting NTP time client\n"); + LOG_INFO("Starting NTP time client"); timeClient.begin(); timeClient.setUpdateInterval(60 * 60); // Update once an hour #endif if (config.network.rsyslog_server[0]) { - LOG_INFO("Starting Syslog client\n"); + LOG_INFO("Starting Syslog client"); // Defaults int serverPort = 514; const char *serverAddr = config.network.rsyslog_server; @@ -132,7 +132,7 @@ static int32_t reconnectWiFi() #else WiFi.disconnect(false); #endif - LOG_INFO("Reconnecting to WiFi access point %s\n", wifiName); + LOG_INFO("Reconnecting to WiFi access point %s", wifiName); delay(5000); @@ -144,9 +144,9 @@ static int32_t reconnectWiFi() #ifndef DISABLE_NTP if (WiFi.isConnected() && (!Throttle::isWithinTimespanMs(lastrun_ntp, 43200000) || (lastrun_ntp == 0))) { // every 12 hours - LOG_DEBUG("Updating NTP time from %s\n", config.network.ntp_server); + LOG_DEBUG("Updating NTP time from %s", config.network.ntp_server); if (timeClient.update()) { - LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed\n"); + LOG_DEBUG("NTP Request Success - Setting RTCQualityNTP if needed"); struct timeval tv; tv.tv_sec = timeClient.getEpochTime(); @@ -155,7 +155,7 @@ static int32_t reconnectWiFi() perhapsSetRTC(RTCQualityNTP, &tv); lastrun_ntp = millis(); } else { - LOG_DEBUG("NTP Update failed\n"); + LOG_DEBUG("NTP Update failed"); } } #endif @@ -188,7 +188,7 @@ bool isWifiAvailable() // Disable WiFi void deinitWifi() { - LOG_INFO("WiFi deinit\n"); + LOG_INFO("WiFi deinit"); if (isWifiAvailable()) { #ifdef ARCH_ESP32 @@ -197,7 +197,7 @@ void deinitWifi() WiFi.disconnect(true); #endif WiFi.mode(WIFI_OFF); - LOG_INFO("WiFi Turned Off\n"); + LOG_INFO("WiFi Turned Off"); // WiFi.printDiag(Serial); } } @@ -247,7 +247,7 @@ bool initWifi() WiFi.onEvent( [](WiFiEvent_t event, WiFiEventInfo_t info) { - LOG_WARN("WiFi lost connection. Reason: %d\n", info.wifi_sta_disconnected.reason); + LOG_WARN("WiFi lost connection. Reason: %d", info.wifi_sta_disconnected.reason); /* If we are disconnected from the AP for some reason, @@ -260,12 +260,12 @@ bool initWifi() }, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED); #endif - LOG_DEBUG("JOINING WIFI soon: ssid=%s\n", wifiName); + LOG_DEBUG("JOINING WIFI soon: ssid=%s", wifiName); wifiReconnect = new Periodic("WifiConnect", reconnectWiFi); } return true; } else { - LOG_INFO("Not using WIFI\n"); + LOG_INFO("Not using WIFI"); return false; } } @@ -278,23 +278,23 @@ static void WiFiEvent(WiFiEvent_t event) switch (event) { case ARDUINO_EVENT_WIFI_READY: - LOG_INFO("WiFi interface ready\n"); + LOG_INFO("WiFi interface ready"); break; case ARDUINO_EVENT_WIFI_SCAN_DONE: - LOG_INFO("Completed scan for access points\n"); + LOG_INFO("Completed scan for access points"); break; case ARDUINO_EVENT_WIFI_STA_START: - LOG_INFO("WiFi station started\n"); + LOG_INFO("WiFi station started"); break; case ARDUINO_EVENT_WIFI_STA_STOP: - LOG_INFO("WiFi station stopped\n"); + LOG_INFO("WiFi station stopped"); syslog.disable(); break; case ARDUINO_EVENT_WIFI_STA_CONNECTED: - LOG_INFO("Connected to access point\n"); + LOG_INFO("Connected to access point"); break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - LOG_INFO("Disconnected from WiFi access point\n"); + LOG_INFO("Disconnected from WiFi access point"); if (!isReconnecting) { WiFi.disconnect(false, true); syslog.disable(); @@ -303,22 +303,22 @@ static void WiFiEvent(WiFiEvent_t event) } break; case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: - LOG_INFO("Authentication mode of access point has changed\n"); + LOG_INFO("Authentication mode of access point has changed"); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP: - LOG_INFO("Obtained IP address: %s\n", WiFi.localIP().toString().c_str()); + LOG_INFO("Obtained IP address: %s", WiFi.localIP().toString().c_str()); onNetworkConnected(); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP6: #if ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(3, 0, 0) - LOG_INFO("Obtained Local IP6 address: %s\n", WiFi.linkLocalIPv6().toString().c_str()); - LOG_INFO("Obtained GlobalIP6 address: %s\n", WiFi.globalIPv6().toString().c_str()); + LOG_INFO("Obtained Local IP6 address: %s", WiFi.linkLocalIPv6().toString().c_str()); + LOG_INFO("Obtained GlobalIP6 address: %s", WiFi.globalIPv6().toString().c_str()); #else - LOG_INFO("Obtained IP6 address: %s\n", WiFi.localIPv6().toString().c_str()); + LOG_INFO("Obtained IP6 address: %s", WiFi.localIPv6().toString().c_str()); #endif break; case ARDUINO_EVENT_WIFI_STA_LOST_IP: - LOG_INFO("Lost IP address and IP address is reset to 0\n"); + LOG_INFO("Lost IP address and IP address is reset to 0"); if (!isReconnecting) { WiFi.disconnect(false, true); syslog.disable(); @@ -327,94 +327,94 @@ static void WiFiEvent(WiFiEvent_t event) } break; case ARDUINO_EVENT_WPS_ER_SUCCESS: - LOG_INFO("WiFi Protected Setup (WPS): succeeded in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): succeeded in enrollee mode"); break; case ARDUINO_EVENT_WPS_ER_FAILED: - LOG_INFO("WiFi Protected Setup (WPS): failed in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): failed in enrollee mode"); break; case ARDUINO_EVENT_WPS_ER_TIMEOUT: - LOG_INFO("WiFi Protected Setup (WPS): timeout in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): timeout in enrollee mode"); break; case ARDUINO_EVENT_WPS_ER_PIN: - LOG_INFO("WiFi Protected Setup (WPS): pin code in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): pin code in enrollee mode"); break; case ARDUINO_EVENT_WPS_ER_PBC_OVERLAP: - LOG_INFO("WiFi Protected Setup (WPS): push button overlap in enrollee mode\n"); + LOG_INFO("WiFi Protected Setup (WPS): push button overlap in enrollee mode"); break; case ARDUINO_EVENT_WIFI_AP_START: - LOG_INFO("WiFi access point started\n"); + LOG_INFO("WiFi access point started"); break; case ARDUINO_EVENT_WIFI_AP_STOP: - LOG_INFO("WiFi access point stopped\n"); + LOG_INFO("WiFi access point stopped"); break; case ARDUINO_EVENT_WIFI_AP_STACONNECTED: - LOG_INFO("Client connected\n"); + LOG_INFO("Client connected"); break; case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: - LOG_INFO("Client disconnected\n"); + LOG_INFO("Client disconnected"); break; case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED: - LOG_INFO("Assigned IP address to client\n"); + LOG_INFO("Assigned IP address to client"); break; case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED: - LOG_INFO("Received probe request\n"); + LOG_INFO("Received probe request"); break; case ARDUINO_EVENT_WIFI_AP_GOT_IP6: - LOG_INFO("IPv6 is preferred\n"); + LOG_INFO("IPv6 is preferred"); break; case ARDUINO_EVENT_WIFI_FTM_REPORT: - LOG_INFO("Fast Transition Management report\n"); + LOG_INFO("Fast Transition Management report"); break; case ARDUINO_EVENT_ETH_START: - LOG_INFO("Ethernet started\n"); + LOG_INFO("Ethernet started"); break; case ARDUINO_EVENT_ETH_STOP: - LOG_INFO("Ethernet stopped\n"); + LOG_INFO("Ethernet stopped"); break; case ARDUINO_EVENT_ETH_CONNECTED: - LOG_INFO("Ethernet connected\n"); + LOG_INFO("Ethernet connected"); break; case ARDUINO_EVENT_ETH_DISCONNECTED: - LOG_INFO("Ethernet disconnected\n"); + LOG_INFO("Ethernet disconnected"); break; case ARDUINO_EVENT_ETH_GOT_IP: - LOG_INFO("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)\n"); + LOG_INFO("Obtained IP address (ARDUINO_EVENT_ETH_GOT_IP)"); break; case ARDUINO_EVENT_ETH_GOT_IP6: - LOG_INFO("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)\n"); + LOG_INFO("Obtained IP6 address (ARDUINO_EVENT_ETH_GOT_IP6)"); break; case ARDUINO_EVENT_SC_SCAN_DONE: - LOG_INFO("SmartConfig: Scan done\n"); + LOG_INFO("SmartConfig: Scan done"); break; case ARDUINO_EVENT_SC_FOUND_CHANNEL: - LOG_INFO("SmartConfig: Found channel\n"); + LOG_INFO("SmartConfig: Found channel"); break; case ARDUINO_EVENT_SC_GOT_SSID_PSWD: - LOG_INFO("SmartConfig: Got SSID and password\n"); + LOG_INFO("SmartConfig: Got SSID and password"); break; case ARDUINO_EVENT_SC_SEND_ACK_DONE: - LOG_INFO("SmartConfig: Send ACK done\n"); + LOG_INFO("SmartConfig: Send ACK done"); break; case ARDUINO_EVENT_PROV_INIT: - LOG_INFO("Provisioning: Init\n"); + LOG_INFO("Provisioning: Init"); break; case ARDUINO_EVENT_PROV_DEINIT: - LOG_INFO("Provisioning: Stopped\n"); + LOG_INFO("Provisioning: Stopped"); break; case ARDUINO_EVENT_PROV_START: - LOG_INFO("Provisioning: Started\n"); + LOG_INFO("Provisioning: Started"); break; case ARDUINO_EVENT_PROV_END: - LOG_INFO("Provisioning: End\n"); + LOG_INFO("Provisioning: End"); break; case ARDUINO_EVENT_PROV_CRED_RECV: - LOG_INFO("Provisioning: Credentials received\n"); + LOG_INFO("Provisioning: Credentials received"); break; case ARDUINO_EVENT_PROV_CRED_FAIL: - LOG_INFO("Provisioning: Credentials failed\n"); + LOG_INFO("Provisioning: Credentials failed"); break; case ARDUINO_EVENT_PROV_CRED_SUCCESS: - LOG_INFO("Provisioning: Credentials success\n"); + LOG_INFO("Provisioning: Credentials success"); break; default: break; diff --git a/src/meshUtils.cpp b/src/meshUtils.cpp index e98a6f1ce6..d211f29225 100644 --- a/src/meshUtils.cpp +++ b/src/meshUtils.cpp @@ -94,4 +94,18 @@ bool isOneOf(int item, int count, ...) } va_end(args); return found; +} + +const std::string vformat(const char *const zcFormat, ...) +{ + va_list vaArgs; + va_start(vaArgs, zcFormat); + va_list vaArgsCopy; + va_copy(vaArgsCopy, vaArgs); + const int iLen = std::vsnprintf(NULL, 0, zcFormat, vaArgsCopy); + va_end(vaArgsCopy); + std::vector zc(iLen + 1); + std::vsnprintf(zc.data(), zc.size(), zcFormat, vaArgs); + va_end(vaArgs); + return std::string(zc.data(), iLen); } \ No newline at end of file diff --git a/src/meshUtils.h b/src/meshUtils.h index aff3976f48..47d42b41b9 100644 --- a/src/meshUtils.h +++ b/src/meshUtils.h @@ -24,4 +24,6 @@ bool memfll(const uint8_t *mem, uint8_t find, size_t numbytes); bool isOneOf(int item, int count, ...); +const std::string vformat(const char *const zcFormat, ...); + #define IS_ONE_OF(item, ...) isOneOf(item, sizeof((int[]){__VA_ARGS__}) / sizeof(int), __VA_ARGS__) diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp index 01ef038e84..c0580ab335 100644 --- a/src/modules/AdminModule.cpp +++ b/src/modules/AdminModule.cpp @@ -74,15 +74,15 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta // Could tighten this up further by tracking the last public_key we went an AdminMessage request to // and only allowing responses from that remote. if (messageIsResponse(r)) { - LOG_DEBUG("Allowing admin response message\n"); + LOG_DEBUG("Allowing admin response message"); } else if (mp.from == 0) { if (config.security.is_managed) { - LOG_INFO("Ignoring local admin payload because is_managed.\n"); + LOG_INFO("Ignoring local admin payload because is_managed."); return handled; } } else if (strcasecmp(ch->settings.name, Channels::adminChannel) == 0) { if (!config.security.admin_channel_enabled) { - LOG_INFO("Ignoring admin channel, as legacy admin is disabled.\n"); + LOG_INFO("Ignoring admin channel, as legacy admin is disabled."); myReply = allocErrorResponse(meshtastic_Routing_Error_NOT_AUTHORIZED, &mp); return handled; } @@ -93,25 +93,25 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta memcmp(mp.public_key.bytes, config.security.admin_key[1].bytes, 32) == 0) || (config.security.admin_key[2].size == 32 && memcmp(mp.public_key.bytes, config.security.admin_key[2].bytes, 32) == 0)) { - LOG_INFO("PKC admin payload with authorized sender key.\n"); + LOG_INFO("PKC admin payload with authorized sender key."); } else { myReply = allocErrorResponse(meshtastic_Routing_Error_ADMIN_PUBLIC_KEY_UNAUTHORIZED, &mp); - LOG_INFO("Received PKC admin payload, but the sender public key does not match the admin authorized key!\n"); + LOG_INFO("Received PKC admin payload, but the sender public key does not match the admin authorized key!"); return handled; } } else { - LOG_INFO("Ignoring unauthorized admin payload %i\n", r->which_payload_variant); + LOG_INFO("Ignoring unauthorized admin payload %i", r->which_payload_variant); myReply = allocErrorResponse(meshtastic_Routing_Error_NOT_AUTHORIZED, &mp); return handled; } - LOG_INFO("Handling admin payload %i\n", r->which_payload_variant); + LOG_INFO("Handling admin payload %i", r->which_payload_variant); // all of the get and set messages, including those for other modules, flow through here first. // any message that changes state, we want to check the passkey for if (mp.from != 0 && !messageIsRequest(r) && !messageIsResponse(r)) { if (!checkPassKey(r)) { - LOG_WARN("Admin message without session_key!\n"); + LOG_WARN("Admin message without session_key!"); myReply = allocErrorResponse(meshtastic_Routing_Error_ADMIN_BAD_SESSION_KEY, &mp); return handled; } @@ -122,23 +122,23 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta * Getters */ case meshtastic_AdminMessage_get_owner_request_tag: - LOG_INFO("Client is getting owner\n"); + LOG_INFO("Client is getting owner"); handleGetOwner(mp); break; case meshtastic_AdminMessage_get_config_request_tag: - LOG_INFO("Client is getting config\n"); + LOG_INFO("Client is getting config"); handleGetConfig(mp, r->get_config_request); break; case meshtastic_AdminMessage_get_module_config_request_tag: - LOG_INFO("Client is getting module config\n"); + LOG_INFO("Client is getting module config"); handleGetModuleConfig(mp, r->get_module_config_request); break; case meshtastic_AdminMessage_get_channel_request_tag: { uint32_t i = r->get_channel_request - 1; - LOG_INFO("Client is getting channel %u\n", i); + LOG_INFO("Client is getting channel %u", i); if (i >= MAX_NUM_CHANNELS) myReply = allocErrorResponse(meshtastic_Routing_Error_BAD_REQUEST, &mp); else @@ -150,29 +150,29 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta * Setters */ case meshtastic_AdminMessage_set_owner_tag: - LOG_INFO("Client is setting owner\n"); + LOG_INFO("Client is setting owner"); handleSetOwner(r->set_owner); break; case meshtastic_AdminMessage_set_config_tag: - LOG_INFO("Client is setting the config\n"); + LOG_INFO("Client is setting the config"); handleSetConfig(r->set_config); break; case meshtastic_AdminMessage_set_module_config_tag: - LOG_INFO("Client is setting the module config\n"); + LOG_INFO("Client is setting the module config"); handleSetModuleConfig(r->set_module_config); break; case meshtastic_AdminMessage_set_channel_tag: - LOG_INFO("Client is setting channel %d\n", r->set_channel.index); + LOG_INFO("Client is setting channel %d", r->set_channel.index); if (r->set_channel.index < 0 || r->set_channel.index >= (int)MAX_NUM_CHANNELS) myReply = allocErrorResponse(meshtastic_Routing_Error_BAD_REQUEST, &mp); else handleSetChannel(r->set_channel); break; case meshtastic_AdminMessage_set_ham_mode_tag: - LOG_INFO("Client is setting ham mode\n"); + LOG_INFO("Client is setting ham mode"); handleSetHamMode(r->set_ham_mode); break; @@ -187,15 +187,15 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta int32_t s = r->reboot_ota_seconds; #if defined(ARCH_ESP32) && !MESHTASTIC_EXCLUDE_BLUETOOTH if (BleOta::getOtaAppVersion().isEmpty()) { - LOG_INFO("No OTA firmware available, scheduling regular reboot in %d seconds\n", s); + LOG_INFO("No OTA firmware available, scheduling regular reboot in %d seconds", s); screen->startAlert("Rebooting..."); } else { screen->startFirmwareUpdateScreen(); BleOta::switchToOtaApp(); - LOG_INFO("Rebooting to OTA in %d seconds\n", s); + LOG_INFO("Rebooting to OTA in %d seconds", s); } #else - LOG_INFO("Not on ESP32, scheduling regular reboot in %d seconds\n", s); + LOG_INFO("Not on ESP32, scheduling regular reboot in %d seconds", s); screen->startAlert("Rebooting..."); #endif rebootAtMsec = (s < 0) ? 0 : (millis() + s * 1000); @@ -203,56 +203,56 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta } case meshtastic_AdminMessage_shutdown_seconds_tag: { int32_t s = r->shutdown_seconds; - LOG_INFO("Shutdown in %d seconds\n", s); + LOG_INFO("Shutdown in %d seconds", s); shutdownAtMsec = (s < 0) ? 0 : (millis() + s * 1000); break; } case meshtastic_AdminMessage_get_device_metadata_request_tag: { - LOG_INFO("Client is getting device metadata\n"); + LOG_INFO("Client is getting device metadata"); handleGetDeviceMetadata(mp); break; } case meshtastic_AdminMessage_factory_reset_config_tag: { disableBluetooth(); - LOG_INFO("Initiating factory config reset\n"); + LOG_INFO("Initiating factory config reset"); nodeDB->factoryReset(); - LOG_INFO("Factory config reset finished, rebooting soon.\n"); + LOG_INFO("Factory config reset finished, rebooting soon."); reboot(DEFAULT_REBOOT_SECONDS); break; } case meshtastic_AdminMessage_factory_reset_device_tag: { disableBluetooth(); - LOG_INFO("Initiating full factory reset\n"); + LOG_INFO("Initiating full factory reset"); nodeDB->factoryReset(true); reboot(DEFAULT_REBOOT_SECONDS); break; } case meshtastic_AdminMessage_nodedb_reset_tag: { disableBluetooth(); - LOG_INFO("Initiating node-db reset\n"); + LOG_INFO("Initiating node-db reset"); nodeDB->resetNodes(); reboot(DEFAULT_REBOOT_SECONDS); break; } case meshtastic_AdminMessage_begin_edit_settings_tag: { - LOG_INFO("Beginning transaction for editing settings\n"); + LOG_INFO("Beginning transaction for editing settings"); hasOpenEditTransaction = true; break; } case meshtastic_AdminMessage_commit_edit_settings_tag: { disableBluetooth(); - LOG_INFO("Committing transaction for edited settings\n"); + LOG_INFO("Committing transaction for edited settings"); hasOpenEditTransaction = false; saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS); break; } case meshtastic_AdminMessage_get_device_connection_status_request_tag: { - LOG_INFO("Client is getting device connection status\n"); + LOG_INFO("Client is getting device connection status"); handleGetDeviceConnectionStatus(mp); break; } case meshtastic_AdminMessage_get_module_config_response_tag: { - LOG_INFO("Client is receiving a get_module_config response.\n"); + LOG_INFO("Client is receiving a get_module_config response."); if (fromOthers && r->get_module_config_response.which_payload_variant == meshtastic_AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG) { handleGetModuleConfigResponse(mp, r); @@ -260,13 +260,13 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta break; } case meshtastic_AdminMessage_remove_by_nodenum_tag: { - LOG_INFO("Client is receiving a remove_nodenum command.\n"); + LOG_INFO("Client is receiving a remove_nodenum command."); nodeDB->removeNodeByNum(r->remove_by_nodenum); this->notifyObservers(r); // Observed by screen break; } case meshtastic_AdminMessage_set_favorite_node_tag: { - LOG_INFO("Client is receiving a set_favorite_node command.\n"); + LOG_INFO("Client is receiving a set_favorite_node command."); meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(r->set_favorite_node); if (node != NULL) { node->is_favorite = true; @@ -275,7 +275,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta break; } case meshtastic_AdminMessage_remove_favorite_node_tag: { - LOG_INFO("Client is receiving a remove_favorite_node command.\n"); + LOG_INFO("Client is receiving a remove_favorite_node command."); meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(r->remove_favorite_node); if (node != NULL) { node->is_favorite = false; @@ -284,7 +284,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta break; } case meshtastic_AdminMessage_set_fixed_position_tag: { - LOG_INFO("Client is receiving a set_fixed_position command.\n"); + LOG_INFO("Client is receiving a set_fixed_position command."); meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeDB->getNodeNum()); node->has_position = true; node->position = TypeConversions::ConvertToPositionLite(r->set_fixed_position); @@ -300,14 +300,14 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta break; } case meshtastic_AdminMessage_remove_fixed_position_tag: { - LOG_INFO("Client is receiving a remove_fixed_position command.\n"); + LOG_INFO("Client is receiving a remove_fixed_position command."); nodeDB->clearLocalPosition(); config.position.fixed_position = false; saveChanges(SEGMENT_DEVICESTATE | SEGMENT_CONFIG, false); break; } case meshtastic_AdminMessage_set_time_only_tag: { - LOG_INFO("Client is receiving a set_time_only command.\n"); + LOG_INFO("Client is receiving a set_time_only command."); struct timeval tv; tv.tv_sec = r->set_time_only; tv.tv_usec = 0; @@ -316,26 +316,26 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta break; } case meshtastic_AdminMessage_enter_dfu_mode_request_tag: { - LOG_INFO("Client is requesting to enter DFU mode.\n"); + LOG_INFO("Client is requesting to enter DFU mode."); #if defined(ARCH_NRF52) || defined(ARCH_RP2040) enterDfuMode(); #endif break; } case meshtastic_AdminMessage_delete_file_request_tag: { - LOG_DEBUG("Client is requesting to delete file: %s\n", r->delete_file_request); + LOG_DEBUG("Client is requesting to delete file: %s", r->delete_file_request); #ifdef FSCom if (FSCom.remove(r->delete_file_request)) { - LOG_DEBUG("Successfully deleted file\n"); + LOG_DEBUG("Successfully deleted file"); } else { - LOG_DEBUG("Failed to delete file\n"); + LOG_DEBUG("Failed to delete file"); } #endif break; } #ifdef ARCH_PORTDUINO case meshtastic_AdminMessage_exit_simulator_tag: - LOG_INFO("Exiting simulator\n"); + LOG_INFO("Exiting simulator"); _exit(0); break; #endif @@ -348,10 +348,10 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta setPassKey(&res); myReply = allocDataProtobuf(res); } else if (mp.decoded.want_response) { - LOG_DEBUG("We did not responded to a request that wanted a respond. req.variant=%d\n", r->which_payload_variant); + LOG_DEBUG("We did not responded to a request that wanted a respond. req.variant=%d", r->which_payload_variant); } else if (handleResult != AdminMessageHandleResult::HANDLED) { // Probably a message sent by us or sent to our local node. FIXME, we should avoid scanning these messages - LOG_INFO("Ignoring nonrelevant admin %d\n", r->which_payload_variant); + LOG_INFO("Ignoring nonrelevant admin %d", r->which_payload_variant); } break; } @@ -369,7 +369,7 @@ void AdminModule::handleGetModuleConfigResponse(const meshtastic_MeshPacket &mp, // Skip if it's disabled or no pins are exposed if (!r->get_module_config_response.payload_variant.remote_hardware.enabled || r->get_module_config_response.payload_variant.remote_hardware.available_pins_count == 0) { - LOG_DEBUG("Remote hardware module disabled or no available_pins. Skipping...\n"); + LOG_DEBUG("Remote hardware module disabled or no available_pins. Skipping..."); return; } for (uint8_t i = 0; i < devicestate.node_remote_hardware_pins_count; i++) { @@ -427,7 +427,7 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c) switch (c.which_payload_variant) { case meshtastic_Config_device_tag: - LOG_INFO("Setting config: Device\n"); + LOG_INFO("Setting config: Device"); config.has_device = true; #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) && !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR if (config.device.double_tap_as_button_press == false && c.payload_variant.device.double_tap_as_button_press == true && @@ -451,11 +451,19 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c) requiresReboot = false; } config.device = c.payload_variant.device; + if (config.device.rebroadcast_mode == meshtastic_Config_DeviceConfig_RebroadcastMode_NONE && + IS_ONE_OF(config.device.role, meshtastic_Config_DeviceConfig_Role_ROUTER, + meshtastic_Config_DeviceConfig_Role_REPEATER)) { + config.device.rebroadcast_mode = meshtastic_Config_DeviceConfig_RebroadcastMode_ALL; + const char *warning = "Rebroadcast mode can't be set to NONE for a router or repeater\n"; + LOG_WARN(warning); + sendWarning(warning); + } // If we're setting router role for the first time, install its intervals if (existingRole != c.payload_variant.device.role) nodeDB->installRoleDefaults(c.payload_variant.device.role); if (config.device.node_info_broadcast_secs < min_node_info_broadcast_secs) { - LOG_DEBUG("Tried to set node_info_broadcast_secs too low, setting to %d\n", min_node_info_broadcast_secs); + LOG_DEBUG("Tried to set node_info_broadcast_secs too low, setting to %d", min_node_info_broadcast_secs); config.device.node_info_broadcast_secs = min_node_info_broadcast_secs; } // Router Client is deprecated; Set it to client @@ -476,14 +484,14 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c) #endif break; case meshtastic_Config_position_tag: - LOG_INFO("Setting config: Position\n"); + LOG_INFO("Setting config: Position"); config.has_position = true; config.position = c.payload_variant.position; // Save nodedb as well in case we got a fixed position packet saveChanges(SEGMENT_DEVICESTATE, false); break; case meshtastic_Config_power_tag: - LOG_INFO("Setting config: Power\n"); + LOG_INFO("Setting config: Power"); config.has_power = true; // Really just the adc override is the only thing that can change without a reboot if (config.power.device_battery_ina_address == c.payload_variant.power.device_battery_ina_address && @@ -498,12 +506,12 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c) config.power = c.payload_variant.power; break; case meshtastic_Config_network_tag: - LOG_INFO("Setting config: WiFi\n"); + LOG_INFO("Setting config: WiFi"); config.has_network = true; config.network = c.payload_variant.network; break; case meshtastic_Config_display_tag: - LOG_INFO("Setting config: Display\n"); + LOG_INFO("Setting config: Display"); config.has_display = true; if (config.display.screen_on_secs == c.payload_variant.display.screen_on_secs && config.display.flip_screen == c.payload_variant.display.flip_screen && @@ -521,7 +529,7 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c) config.display = c.payload_variant.display; break; case meshtastic_Config_lora_tag: - LOG_INFO("Setting config: LoRa\n"); + LOG_INFO("Setting config: LoRa"); config.has_lora = true; // If no lora radio parameters change, don't need to reboot if (config.lora.use_preset == c.payload_variant.lora.use_preset && config.lora.region == c.payload_variant.lora.region && @@ -560,12 +568,12 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c) } break; case meshtastic_Config_bluetooth_tag: - LOG_INFO("Setting config: Bluetooth\n"); + LOG_INFO("Setting config: Bluetooth"); config.has_bluetooth = true; config.bluetooth = c.payload_variant.bluetooth; break; case meshtastic_Config_security_tag: - LOG_INFO("Setting config: Security\n"); + LOG_INFO("Setting config: Security"); config.security = c.payload_variant.security; #if !(MESHTASTIC_EXCLUDE_PKI_KEYGEN) && !(MESHTASTIC_EXCLUDE_PKI) // We check for a potentially valid private key, and a blank public key, and regen the public key if needed. @@ -600,71 +608,71 @@ void AdminModule::handleSetModuleConfig(const meshtastic_ModuleConfig &c) disableBluetooth(); switch (c.which_payload_variant) { case meshtastic_ModuleConfig_mqtt_tag: - LOG_INFO("Setting module config: MQTT\n"); + LOG_INFO("Setting module config: MQTT"); moduleConfig.has_mqtt = true; moduleConfig.mqtt = c.payload_variant.mqtt; break; case meshtastic_ModuleConfig_serial_tag: - LOG_INFO("Setting module config: Serial\n"); + LOG_INFO("Setting module config: Serial"); moduleConfig.has_serial = true; moduleConfig.serial = c.payload_variant.serial; break; case meshtastic_ModuleConfig_external_notification_tag: - LOG_INFO("Setting module config: External Notification\n"); + LOG_INFO("Setting module config: External Notification"); moduleConfig.has_external_notification = true; moduleConfig.external_notification = c.payload_variant.external_notification; break; case meshtastic_ModuleConfig_store_forward_tag: - LOG_INFO("Setting module config: Store & Forward\n"); + LOG_INFO("Setting module config: Store & Forward"); moduleConfig.has_store_forward = true; moduleConfig.store_forward = c.payload_variant.store_forward; break; case meshtastic_ModuleConfig_range_test_tag: - LOG_INFO("Setting module config: Range Test\n"); + LOG_INFO("Setting module config: Range Test"); moduleConfig.has_range_test = true; moduleConfig.range_test = c.payload_variant.range_test; break; case meshtastic_ModuleConfig_telemetry_tag: - LOG_INFO("Setting module config: Telemetry\n"); + LOG_INFO("Setting module config: Telemetry"); moduleConfig.has_telemetry = true; moduleConfig.telemetry = c.payload_variant.telemetry; break; case meshtastic_ModuleConfig_canned_message_tag: - LOG_INFO("Setting module config: Canned Message\n"); + LOG_INFO("Setting module config: Canned Message"); moduleConfig.has_canned_message = true; moduleConfig.canned_message = c.payload_variant.canned_message; break; case meshtastic_ModuleConfig_audio_tag: - LOG_INFO("Setting module config: Audio\n"); + LOG_INFO("Setting module config: Audio"); moduleConfig.has_audio = true; moduleConfig.audio = c.payload_variant.audio; break; case meshtastic_ModuleConfig_remote_hardware_tag: - LOG_INFO("Setting module config: Remote Hardware\n"); + LOG_INFO("Setting module config: Remote Hardware"); moduleConfig.has_remote_hardware = true; moduleConfig.remote_hardware = c.payload_variant.remote_hardware; break; case meshtastic_ModuleConfig_neighbor_info_tag: - LOG_INFO("Setting module config: Neighbor Info\n"); + LOG_INFO("Setting module config: Neighbor Info"); moduleConfig.has_neighbor_info = true; if (moduleConfig.neighbor_info.update_interval < min_neighbor_info_broadcast_secs) { - LOG_DEBUG("Tried to set update_interval too low, setting to %d\n", default_neighbor_info_broadcast_secs); + LOG_DEBUG("Tried to set update_interval too low, setting to %d", default_neighbor_info_broadcast_secs); moduleConfig.neighbor_info.update_interval = default_neighbor_info_broadcast_secs; } moduleConfig.neighbor_info = c.payload_variant.neighbor_info; break; case meshtastic_ModuleConfig_detection_sensor_tag: - LOG_INFO("Setting module config: Detection Sensor\n"); + LOG_INFO("Setting module config: Detection Sensor"); moduleConfig.has_detection_sensor = true; moduleConfig.detection_sensor = c.payload_variant.detection_sensor; break; case meshtastic_ModuleConfig_ambient_lighting_tag: - LOG_INFO("Setting module config: Ambient Lighting\n"); + LOG_INFO("Setting module config: Ambient Lighting"); moduleConfig.has_ambient_lighting = true; moduleConfig.ambient_lighting = c.payload_variant.ambient_lighting; break; case meshtastic_ModuleConfig_paxcounter_tag: - LOG_INFO("Setting module config: Paxcounter\n"); + LOG_INFO("Setting module config: Paxcounter"); moduleConfig.has_paxcounter = true; moduleConfig.paxcounter = c.payload_variant.paxcounter; break; @@ -703,49 +711,49 @@ void AdminModule::handleGetConfig(const meshtastic_MeshPacket &req, const uint32 if (req.decoded.want_response) { switch (configType) { case meshtastic_AdminMessage_ConfigType_DEVICE_CONFIG: - LOG_INFO("Getting config: Device\n"); + LOG_INFO("Getting config: Device"); res.get_config_response.which_payload_variant = meshtastic_Config_device_tag; res.get_config_response.payload_variant.device = config.device; break; case meshtastic_AdminMessage_ConfigType_POSITION_CONFIG: - LOG_INFO("Getting config: Position\n"); + LOG_INFO("Getting config: Position"); res.get_config_response.which_payload_variant = meshtastic_Config_position_tag; res.get_config_response.payload_variant.position = config.position; break; case meshtastic_AdminMessage_ConfigType_POWER_CONFIG: - LOG_INFO("Getting config: Power\n"); + LOG_INFO("Getting config: Power"); res.get_config_response.which_payload_variant = meshtastic_Config_power_tag; res.get_config_response.payload_variant.power = config.power; break; case meshtastic_AdminMessage_ConfigType_NETWORK_CONFIG: - LOG_INFO("Getting config: Network\n"); + LOG_INFO("Getting config: Network"); 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 meshtastic_AdminMessage_ConfigType_DISPLAY_CONFIG: - LOG_INFO("Getting config: Display\n"); + LOG_INFO("Getting config: Display"); res.get_config_response.which_payload_variant = meshtastic_Config_display_tag; res.get_config_response.payload_variant.display = config.display; break; case meshtastic_AdminMessage_ConfigType_LORA_CONFIG: - LOG_INFO("Getting config: LoRa\n"); + LOG_INFO("Getting config: LoRa"); res.get_config_response.which_payload_variant = meshtastic_Config_lora_tag; res.get_config_response.payload_variant.lora = config.lora; break; case meshtastic_AdminMessage_ConfigType_BLUETOOTH_CONFIG: - LOG_INFO("Getting config: Bluetooth\n"); + LOG_INFO("Getting config: Bluetooth"); res.get_config_response.which_payload_variant = meshtastic_Config_bluetooth_tag; res.get_config_response.payload_variant.bluetooth = config.bluetooth; break; case meshtastic_AdminMessage_ConfigType_SECURITY_CONFIG: - LOG_INFO("Getting config: Security\n"); + LOG_INFO("Getting config: Security"); res.get_config_response.which_payload_variant = meshtastic_Config_security_tag; res.get_config_response.payload_variant.security = config.security; break; case meshtastic_AdminMessage_ConfigType_SESSIONKEY_CONFIG: - LOG_INFO("Getting config: Sessionkey\n"); + LOG_INFO("Getting config: Sessionkey"); res.get_config_response.which_payload_variant = meshtastic_Config_sessionkey_tag; break; } @@ -769,67 +777,67 @@ void AdminModule::handleGetModuleConfig(const meshtastic_MeshPacket &req, const if (req.decoded.want_response) { switch (configType) { case meshtastic_AdminMessage_ModuleConfigType_MQTT_CONFIG: - LOG_INFO("Getting module config: MQTT\n"); + LOG_INFO("Getting module config: MQTT"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_mqtt_tag; res.get_module_config_response.payload_variant.mqtt = moduleConfig.mqtt; break; case meshtastic_AdminMessage_ModuleConfigType_SERIAL_CONFIG: - LOG_INFO("Getting module config: Serial\n"); + LOG_INFO("Getting module config: Serial"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_serial_tag; res.get_module_config_response.payload_variant.serial = moduleConfig.serial; break; case meshtastic_AdminMessage_ModuleConfigType_EXTNOTIF_CONFIG: - LOG_INFO("Getting module config: External Notification\n"); + LOG_INFO("Getting module config: External Notification"); 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 meshtastic_AdminMessage_ModuleConfigType_STOREFORWARD_CONFIG: - LOG_INFO("Getting module config: Store & Forward\n"); + LOG_INFO("Getting module config: Store & Forward"); 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 meshtastic_AdminMessage_ModuleConfigType_RANGETEST_CONFIG: - LOG_INFO("Getting module config: Range Test\n"); + LOG_INFO("Getting module config: Range Test"); 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 meshtastic_AdminMessage_ModuleConfigType_TELEMETRY_CONFIG: - LOG_INFO("Getting module config: Telemetry\n"); + LOG_INFO("Getting module config: Telemetry"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_telemetry_tag; res.get_module_config_response.payload_variant.telemetry = moduleConfig.telemetry; break; case meshtastic_AdminMessage_ModuleConfigType_CANNEDMSG_CONFIG: - LOG_INFO("Getting module config: Canned Message\n"); + LOG_INFO("Getting module config: Canned Message"); 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 meshtastic_AdminMessage_ModuleConfigType_AUDIO_CONFIG: - LOG_INFO("Getting module config: Audio\n"); + LOG_INFO("Getting module config: Audio"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_audio_tag; res.get_module_config_response.payload_variant.audio = moduleConfig.audio; break; case meshtastic_AdminMessage_ModuleConfigType_REMOTEHARDWARE_CONFIG: - LOG_INFO("Getting module config: Remote Hardware\n"); + LOG_INFO("Getting module config: Remote Hardware"); 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; case meshtastic_AdminMessage_ModuleConfigType_NEIGHBORINFO_CONFIG: - LOG_INFO("Getting module config: Neighbor Info\n"); + LOG_INFO("Getting module config: Neighbor Info"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_neighbor_info_tag; res.get_module_config_response.payload_variant.neighbor_info = moduleConfig.neighbor_info; break; case meshtastic_AdminMessage_ModuleConfigType_DETECTIONSENSOR_CONFIG: - LOG_INFO("Getting module config: Detection Sensor\n"); + LOG_INFO("Getting module config: Detection Sensor"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_detection_sensor_tag; res.get_module_config_response.payload_variant.detection_sensor = moduleConfig.detection_sensor; break; case meshtastic_AdminMessage_ModuleConfigType_AMBIENTLIGHTING_CONFIG: - LOG_INFO("Getting module config: Ambient Lighting\n"); + LOG_INFO("Getting module config: Ambient Lighting"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_ambient_lighting_tag; res.get_module_config_response.payload_variant.ambient_lighting = moduleConfig.ambient_lighting; break; case meshtastic_AdminMessage_ModuleConfigType_PAXCOUNTER_CONFIG: - LOG_INFO("Getting module config: Paxcounter\n"); + LOG_INFO("Getting module config: Paxcounter"); res.get_module_config_response.which_payload_variant = meshtastic_ModuleConfig_paxcounter_tag; res.get_module_config_response.payload_variant.paxcounter = moduleConfig.paxcounter; break; @@ -958,7 +966,7 @@ void AdminModule::handleGetChannel(const meshtastic_MeshPacket &req, uint32_t ch void AdminModule::reboot(int32_t seconds) { - LOG_INFO("Rebooting in %d seconds\n", seconds); + LOG_INFO("Rebooting in %d seconds", seconds); screen->startAlert("Rebooting..."); rebootAtMsec = (seconds < 0) ? 0 : (millis() + seconds * 1000); } @@ -966,10 +974,10 @@ void AdminModule::reboot(int32_t seconds) void AdminModule::saveChanges(int saveWhat, bool shouldReboot) { if (!hasOpenEditTransaction) { - LOG_INFO("Saving changes to disk\n"); + LOG_INFO("Saving changes to disk"); service->reloadConfig(saveWhat); // Calls saveToDisk among other things } else { - LOG_INFO("Delaying save of changes to disk until the open transaction is committed\n"); + LOG_INFO("Delaying save of changes to disk until the open transaction is committed"); } if (shouldReboot && !hasOpenEditTransaction) { reboot(DEFAULT_REBOOT_SECONDS); @@ -1064,6 +1072,15 @@ bool AdminModule::messageIsRequest(const meshtastic_AdminMessage *r) return false; } +void AdminModule::sendWarning(const char *message) +{ + meshtastic_ClientNotification *cn = clientNotificationPool.allocZeroed(); + cn->level = meshtastic_LogRecord_Level_WARNING; + cn->time = getValidTime(RTCQualityFromNet); + strncpy(cn->message, message, sizeof(cn->message)); + service->sendClientNotification(cn); +} + void disableBluetooth() { #if HAS_BLUETOOTH diff --git a/src/modules/AdminModule.h b/src/modules/AdminModule.h index d6c0a7343d..e54b89af1c 100644 --- a/src/modules/AdminModule.h +++ b/src/modules/AdminModule.h @@ -57,6 +57,7 @@ class AdminModule : public ProtobufModule, public Obser bool messageIsResponse(const meshtastic_AdminMessage *r); bool messageIsRequest(const meshtastic_AdminMessage *r); + void sendWarning(const char *message); }; extern AdminModule *adminModule; diff --git a/src/modules/AtakPluginModule.cpp b/src/modules/AtakPluginModule.cpp index 72d0696190..10c8878346 100644 --- a/src/modules/AtakPluginModule.cpp +++ b/src/modules/AtakPluginModule.cpp @@ -65,7 +65,7 @@ void AtakPluginModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtast { // From Phone (EUD) if (mp.from == 0) { - LOG_DEBUG("Received uncompressed TAK payload from phone: %d bytes\n", mp.decoded.payload.size); + LOG_DEBUG("Received uncompressed TAK payload from phone: %d bytes", mp.decoded.payload.size); // Compress for LoRA transport auto compressed = cloneTAKPacketData(t); compressed.is_compressed = true; @@ -73,28 +73,28 @@ void AtakPluginModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtast auto length = unishox2_compress_lines(t->contact.callsign, strlen(t->contact.callsign), compressed.contact.callsign, sizeof(compressed.contact.callsign) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Compression overflowed contact.callsign. Reverting to uncompressed packet\n"); + LOG_WARN("Compression overflowed contact.callsign. Reverting to uncompressed packet"); return; } - LOG_DEBUG("Compressed callsign: %d bytes\n", length); + LOG_DEBUG("Compressed callsign: %d bytes", length); length = unishox2_compress_lines(t->contact.device_callsign, strlen(t->contact.device_callsign), compressed.contact.device_callsign, sizeof(compressed.contact.device_callsign) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Compression overflowed contact.device_callsign. Reverting to uncompressed packet\n"); + LOG_WARN("Compression overflowed contact.device_callsign. Reverting to uncompressed packet"); return; } - LOG_DEBUG("Compressed device_callsign: %d bytes\n", length); + LOG_DEBUG("Compressed device_callsign: %d bytes", length); } if (t->which_payload_variant == meshtastic_TAKPacket_chat_tag) { auto length = unishox2_compress_lines(t->payload_variant.chat.message, strlen(t->payload_variant.chat.message), compressed.payload_variant.chat.message, sizeof(compressed.payload_variant.chat.message) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Compression overflowed chat.message. Reverting to uncompressed packet\n"); + LOG_WARN("Compression overflowed chat.message. Reverting to uncompressed packet"); return; } - LOG_DEBUG("Compressed chat message: %d bytes\n", length); + LOG_DEBUG("Compressed chat message: %d bytes", length); if (t->payload_variant.chat.has_to) { compressed.payload_variant.chat.has_to = true; @@ -102,10 +102,10 @@ void AtakPluginModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtast compressed.payload_variant.chat.to, sizeof(compressed.payload_variant.chat.to) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Compression overflowed chat.to. Reverting to uncompressed packet\n"); + LOG_WARN("Compression overflowed chat.to. Reverting to uncompressed packet"); return; } - LOG_DEBUG("Compressed chat to: %d bytes\n", length); + LOG_DEBUG("Compressed chat to: %d bytes", length); } if (t->payload_variant.chat.has_to_callsign) { @@ -114,19 +114,19 @@ void AtakPluginModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtast compressed.payload_variant.chat.to_callsign, sizeof(compressed.payload_variant.chat.to_callsign) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Compression overflowed chat.to_callsign. Reverting to uncompressed packet\n"); + LOG_WARN("Compression overflowed chat.to_callsign. Reverting to uncompressed packet"); return; } - LOG_DEBUG("Compressed chat to_callsign: %d bytes\n", length); + LOG_DEBUG("Compressed chat to_callsign: %d bytes", length); } } mp.decoded.payload.size = pb_encode_to_bytes(mp.decoded.payload.bytes, sizeof(mp.decoded.payload.bytes), meshtastic_TAKPacket_fields, &compressed); - LOG_DEBUG("Final payload: %d bytes\n", mp.decoded.payload.size); + LOG_DEBUG("Final payload: %d bytes", mp.decoded.payload.size); } else { if (!t->is_compressed) { // Not compressed. Something is wrong - LOG_WARN("Received uncompressed TAKPacket over radio! Skipping\n"); + LOG_WARN("Received uncompressed TAKPacket over radio! Skipping"); return; } @@ -139,29 +139,29 @@ void AtakPluginModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtast unishox2_decompress_lines(t->contact.callsign, strlen(t->contact.callsign), uncompressed.contact.callsign, sizeof(uncompressed.contact.callsign) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Decompression overflowed contact.callsign. Bailing out\n"); + LOG_WARN("Decompression overflowed contact.callsign. Bailing out"); return; } - LOG_DEBUG("Decompressed callsign: %d bytes\n", length); + LOG_DEBUG("Decompressed callsign: %d bytes", length); length = unishox2_decompress_lines(t->contact.device_callsign, strlen(t->contact.device_callsign), uncompressed.contact.device_callsign, sizeof(uncompressed.contact.device_callsign) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Decompression overflowed contact.device_callsign. Bailing out\n"); + LOG_WARN("Decompression overflowed contact.device_callsign. Bailing out"); return; } - LOG_DEBUG("Decompressed device_callsign: %d bytes\n", length); + LOG_DEBUG("Decompressed device_callsign: %d bytes", length); } if (uncompressed.which_payload_variant == meshtastic_TAKPacket_chat_tag) { auto length = unishox2_decompress_lines(t->payload_variant.chat.message, strlen(t->payload_variant.chat.message), uncompressed.payload_variant.chat.message, sizeof(uncompressed.payload_variant.chat.message) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Decompression overflowed chat.message. Bailing out\n"); + LOG_WARN("Decompression overflowed chat.message. Bailing out"); return; } - LOG_DEBUG("Decompressed chat message: %d bytes\n", length); + LOG_DEBUG("Decompressed chat message: %d bytes", length); if (t->payload_variant.chat.has_to) { uncompressed.payload_variant.chat.has_to = true; @@ -169,10 +169,10 @@ void AtakPluginModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtast uncompressed.payload_variant.chat.to, sizeof(uncompressed.payload_variant.chat.to) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Decompression overflowed chat.to. Bailing out\n"); + LOG_WARN("Decompression overflowed chat.to. Bailing out"); return; } - LOG_DEBUG("Decompressed chat to: %d bytes\n", length); + LOG_DEBUG("Decompressed chat to: %d bytes", length); } if (t->payload_variant.chat.has_to_callsign) { @@ -182,10 +182,10 @@ void AtakPluginModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtast uncompressed.payload_variant.chat.to_callsign, sizeof(uncompressed.payload_variant.chat.to_callsign) - 1, USX_PSET_DFLT, NULL); if (length < 0) { - LOG_WARN("Decompression overflowed chat.to_callsign. Bailing out\n"); + LOG_WARN("Decompression overflowed chat.to_callsign. Bailing out"); return; } - LOG_DEBUG("Decompressed chat to_callsign: %d bytes\n", length); + LOG_DEBUG("Decompressed chat to_callsign: %d bytes", length); } } decompressedCopy->decoded.payload.size = diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp index 615a1ab54b..90c8c0f2cc 100644 --- a/src/modules/CannedMessageModule.cpp +++ b/src/modules/CannedMessageModule.cpp @@ -12,6 +12,7 @@ #include "detect/ScanI2C.h" #include "input/ScanAndSelect.h" #include "mesh/generated/meshtastic/cannedmessages.pb.h" +#include "modules/AdminModule.h" #include "main.h" // for cardkb_found #include "modules/ExternalNotificationModule.h" // for buzzer control @@ -47,11 +48,11 @@ CannedMessageModule::CannedMessageModule() this->loadProtoForModule(); if ((this->splitConfiguredMessages() <= 0) && (cardkb_found.address == 0x00) && !INPUTBROKER_MATRIX_TYPE && !CANNED_MESSAGE_MODULE_ENABLE) { - LOG_INFO("CannedMessageModule: No messages are configured. Module is disabled\n"); + LOG_INFO("CannedMessageModule: No messages are configured. Module is disabled"); this->runState = CANNED_MESSAGE_RUN_STATE_DISABLED; disable(); } else { - LOG_INFO("CannedMessageModule is enabled\n"); + LOG_INFO("CannedMessageModule is enabled"); // T-Watch interface currently has no way to select destination type, so default to 'node' #if defined(T_WATCH_S3) || defined(RAK14014) @@ -111,7 +112,7 @@ int CannedMessageModule::splitConfiguredMessages() } if (strlen(this->messages[messageIndex - 1]) > 0) { // We have a last message. - LOG_DEBUG("CannedMessage %d is: '%s'\n", messageIndex - 1, this->messages[messageIndex - 1]); + LOG_DEBUG("CannedMessage %d is: '%s'", messageIndex - 1, this->messages[messageIndex - 1]); this->messagesCount = messageIndex; } else { this->messagesCount = messageIndex - 1; @@ -226,12 +227,12 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) case INPUT_BROKER_MSG_BRIGHTNESS_UP: // make screen brighter if (screen) screen->increaseBrightness(); - LOG_DEBUG("increasing Screen Brightness\n"); + LOG_DEBUG("increasing Screen Brightness"); break; case INPUT_BROKER_MSG_BRIGHTNESS_DOWN: // make screen dimmer if (screen) screen->decreaseBrightness(); - LOG_DEBUG("Decreasing Screen Brightness\n"); + LOG_DEBUG("Decreasing Screen Brightness"); break; case INPUT_BROKER_MSG_FN_SYMBOL_ON: // draw modifier (function) symbal if (screen) @@ -268,6 +269,21 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) showTemporaryMessage("GPS Toggled"); #endif break; + case INPUT_BROKER_MSG_BLUETOOTH_TOGGLE: // toggle Bluetooth on/off + if (config.bluetooth.enabled == true) { + config.bluetooth.enabled = false; + LOG_INFO("User toggled Bluetooth"); + nodeDB->saveToDisk(); + disableBluetooth(); + showTemporaryMessage("Bluetooth OFF"); + } else if (config.bluetooth.enabled == false) { + config.bluetooth.enabled = true; + LOG_INFO("User toggled Bluetooth"); + nodeDB->saveToDisk(); + rebootAtMsec = millis() + 2000; + showTemporaryMessage("Bluetooth ON\nReboot"); + } + break; case INPUT_BROKER_MSG_SEND_PING: // fn+space send network ping like double press does service->refreshLocalMeshNode(); if (service->trySendPosition(NODENUM_BROADCAST, true)) { @@ -285,7 +301,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event) return 0; default: // pass the pressed key - // LOG_DEBUG("Canned message ANYKEY (%x)\n", event->kbchar); + // LOG_DEBUG("Canned message ANYKEY (%x)", event->kbchar); this->payload = event->kbchar; this->lastTouchMillis = millis(); validEvent = true; @@ -398,7 +414,7 @@ void CannedMessageModule::sendText(NodeNum dest, ChannelIndex channel, const cha // or raising a UIFrameEvent before another module has the chance this->waitingForAck = true; - LOG_INFO("Sending message id=%d, dest=%x, msg=%.*s\n", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); + LOG_INFO("Sending message id=%d, dest=%x, msg=%.*s", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); service->sendToMesh( p, RX_SRC_LOCAL, @@ -412,7 +428,7 @@ int32_t CannedMessageModule::runOnce() temporaryMessage = ""; return INT32_MAX; } - // LOG_DEBUG("Check status\n"); + // LOG_DEBUG("Check status"); UIFrameEvent e; if ((this->runState == CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_ACK_NACK_RECEIVED) || (this->runState == CANNED_MESSAGE_RUN_STATE_MESSAGE)) { @@ -465,7 +481,7 @@ int32_t CannedMessageModule::runOnce() } this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE; } else { - // LOG_DEBUG("Reset message is empty.\n"); + // LOG_DEBUG("Reset message is empty."); this->runState = CANNED_MESSAGE_RUN_STATE_INACTIVE; } } @@ -482,7 +498,7 @@ int32_t CannedMessageModule::runOnce() return 2000; } else if ((this->runState != CANNED_MESSAGE_RUN_STATE_FREETEXT) && (this->currentMessageIndex == -1)) { this->currentMessageIndex = 0; - LOG_DEBUG("First touch (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); + LOG_DEBUG("First touch (%d):%s", this->currentMessageIndex, this->getCurrentMessage()); e.action = UIFrameEvent::Action::REGENERATE_FRAMESET; // We want to change the list of frames shown on-screen this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; } else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_UP) { @@ -496,7 +512,7 @@ int32_t CannedMessageModule::runOnce() #endif this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; - LOG_DEBUG("MOVE UP (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); + LOG_DEBUG("MOVE UP (%d):%s", this->currentMessageIndex, this->getCurrentMessage()); } } else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_DOWN) { if (this->messagesCount > 0) { @@ -509,7 +525,7 @@ int32_t CannedMessageModule::runOnce() #endif this->runState = CANNED_MESSAGE_RUN_STATE_ACTIVE; - LOG_DEBUG("MOVE DOWN (%d):%s\n", this->currentMessageIndex, this->getCurrentMessage()); + LOG_DEBUG("MOVE DOWN (%d):%s", this->currentMessageIndex, this->getCurrentMessage()); } } else if (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT || this->runState == CANNED_MESSAGE_RUN_STATE_ACTIVE) { switch (this->payload) { @@ -1145,7 +1161,6 @@ void CannedMessageModule::loadProtoForModule() installDefaultCannedMessageModuleConfig(); } } - /** * @brief Save the module config to file. * @@ -1191,13 +1206,13 @@ AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const switch (request->which_payload_variant) { case meshtastic_AdminMessage_get_canned_message_module_messages_request_tag: - LOG_DEBUG("Client is getting radio canned messages\n"); + LOG_DEBUG("Client is getting radio canned messages"); this->handleGetCannedMessageModuleMessages(mp, response); result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; break; case meshtastic_AdminMessage_set_canned_message_module_messages_tag: - LOG_DEBUG("Client is setting radio canned messages\n"); + LOG_DEBUG("Client is setting radio canned messages"); this->handleSetCannedMessageModuleMessages(request->set_canned_message_module_messages); result = AdminMessageHandleResult::HANDLED; break; @@ -1212,7 +1227,7 @@ AdminMessageHandleResult CannedMessageModule::handleAdminMessageForModule(const void CannedMessageModule::handleGetCannedMessageModuleMessages(const meshtastic_MeshPacket &req, meshtastic_AdminMessage *response) { - LOG_DEBUG("*** handleGetCannedMessageModuleMessages\n"); + LOG_DEBUG("*** handleGetCannedMessageModuleMessages"); if (req.decoded.want_response) { response->which_payload_variant = meshtastic_AdminMessage_get_canned_message_module_messages_response_tag; strncpy(response->get_canned_message_module_messages_response, cannedMessageModuleConfig.messages, @@ -1227,7 +1242,7 @@ void CannedMessageModule::handleSetCannedMessageModuleMessages(const char *from_ if (*from_msg) { changed |= strcmp(cannedMessageModuleConfig.messages, from_msg); strncpy(cannedMessageModuleConfig.messages, from_msg, sizeof(cannedMessageModuleConfig.messages)); - LOG_DEBUG("*** from_msg.text:%s\n", from_msg); + LOG_DEBUG("*** from_msg.text:%s", from_msg); } if (changed) { diff --git a/src/modules/DetectionSensorModule.cpp b/src/modules/DetectionSensorModule.cpp index eb13616dee..99f9664c98 100644 --- a/src/modules/DetectionSensorModule.cpp +++ b/src/modules/DetectionSensorModule.cpp @@ -76,15 +76,15 @@ int32_t DetectionSensorModule::runOnce() if (moduleConfig.detection_sensor.monitor_pin > 0) { pinMode(moduleConfig.detection_sensor.monitor_pin, moduleConfig.detection_sensor.use_pullup ? INPUT_PULLUP : INPUT); } else { - LOG_WARN("Detection Sensor Module: Set to enabled but no monitor pin is set. Disabling module...\n"); + LOG_WARN("Detection Sensor Module: Set to enabled but no monitor pin is set. Disabling module..."); return disable(); } - LOG_INFO("Detection Sensor Module: Initializing\n"); + LOG_INFO("Detection Sensor Module: Initializing"); return DELAYED_INTERVAL; } - // LOG_DEBUG("Detection Sensor Module: Current pin state: %i\n", digitalRead(moduleConfig.detection_sensor.monitor_pin)); + // LOG_DEBUG("Detection Sensor Module: Current pin state: %i", digitalRead(moduleConfig.detection_sensor.monitor_pin)); if (!Throttle::isWithinTimespanMs(lastSentToMesh, Default::getConfiguredOrDefaultMs(moduleConfig.detection_sensor.minimum_broadcast_secs))) { @@ -118,7 +118,7 @@ int32_t DetectionSensorModule::runOnce() void DetectionSensorModule::sendDetectionMessage() { - LOG_DEBUG("Detected event observed. Sending message\n"); + LOG_DEBUG("Detected event observed. Sending message"); char *message = new char[40]; sprintf(message, "%s detected", moduleConfig.detection_sensor.name); meshtastic_MeshPacket *p = allocDataPacket(); @@ -130,7 +130,7 @@ void DetectionSensorModule::sendDetectionMessage() p->decoded.payload.bytes[p->decoded.payload.size + 1] = '\0'; // Bell character p->decoded.payload.size++; } - LOG_INFO("Sending message id=%d, dest=%x, msg=%.*s\n", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); + LOG_INFO("Sending message id=%d, dest=%x, msg=%.*s", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); lastSentToMesh = millis(); service->sendToMesh(p); delete[] message; @@ -145,7 +145,7 @@ void DetectionSensorModule::sendCurrentStateMessage(bool state) p->want_ack = false; p->decoded.payload.size = strlen(message); memcpy(p->decoded.payload.bytes, message, p->decoded.payload.size); - LOG_INFO("Sending message id=%d, dest=%x, msg=%.*s\n", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); + LOG_INFO("Sending message id=%d, dest=%x, msg=%.*s", p->id, p->to, p->decoded.payload.size, p->decoded.payload.bytes); lastSentToMesh = millis(); service->sendToMesh(p); delete[] message; @@ -154,6 +154,6 @@ void DetectionSensorModule::sendCurrentStateMessage(bool state) bool DetectionSensorModule::hasDetectionEvent() { bool currentState = digitalRead(moduleConfig.detection_sensor.monitor_pin); - // LOG_DEBUG("Detection Sensor Module: Current state: %i\n", currentState); + // LOG_DEBUG("Detection Sensor Module: Current state: %i", currentState); return (moduleConfig.detection_sensor.detection_trigger_type & 1) ? currentState : !currentState; } \ No newline at end of file diff --git a/src/modules/DropzoneModule.cpp b/src/modules/DropzoneModule.cpp index b1ca2af819..6c42af98be 100644 --- a/src/modules/DropzoneModule.cpp +++ b/src/modules/DropzoneModule.cpp @@ -34,13 +34,13 @@ ProcessMessage DropzoneModule::handleReceived(const meshtastic_MeshPacket &mp) auto incomingMessage = reinterpret_cast(p.payload.bytes); sprintf(matchCompare, "%s conditions", owner.short_name); if (strncasecmp(incomingMessage, matchCompare, strlen(matchCompare)) == 0) { - LOG_DEBUG("Received dropzone conditions request\n"); + LOG_DEBUG("Received dropzone conditions request"); startSendConditions = millis(); } sprintf(matchCompare, "%s conditions", owner.long_name); if (strncasecmp(incomingMessage, matchCompare, strlen(matchCompare)) == 0) { - LOG_DEBUG("Received dropzone conditions request\n"); + LOG_DEBUG("Received dropzone conditions request"); startSendConditions = millis(); } return ProcessMessage::CONTINUE; @@ -82,10 +82,10 @@ meshtastic_MeshPacket *DropzoneModule::sendConditions() sprintf(replyStr, "%s @ %02d:%02d:%02dz\nWind %.2f kts @ %d°\nBaro %.2f inHg %.2f°C", dropzoneStatus, hour, min, sec, windSpeed, windDirection, baro, temp); } else { - LOG_ERROR("No sensor found\n"); + LOG_ERROR("No sensor found"); sprintf(replyStr, "%s @ %02d:%02d:%02d\nNo sensor found", dropzoneStatus, hour, min, sec); } - LOG_DEBUG("Conditions reply: %s\n", replyStr); + LOG_DEBUG("Conditions reply: %s", replyStr); 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/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index 8abc386ec6..a35a742068 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -97,7 +97,14 @@ int32_t ExternalNotificationModule::runOnce() externalTurnedOn[i] = 0; LOG_INFO("%d ", i); } - LOG_INFO("\n"); + LOG_INFO(""); +#ifdef HAS_I2S + // GPIO0 is used as mclk for I2S audio and set to OUTPUT by the sound library + // T-Deck uses GPIO0 as trackball button, so restore the mode +#if defined(T_DECK) || (defined(BUTTON_PIN) && BUTTON_PIN == 0) + pinMode(0, INPUT); +#endif +#endif isNagging = false; return INT32_MAX; // save cycles till we're needed again } @@ -362,34 +369,34 @@ ExternalNotificationModule::ExternalNotificationModule() sizeof(rtttlConfig.ringtone)); } - LOG_INFO("Initializing External Notification Module\n"); + LOG_INFO("Initializing External Notification Module"); output = moduleConfig.external_notification.output ? moduleConfig.external_notification.output : EXT_NOTIFICATION_MODULE_OUTPUT; // Set the direction of a pin if (output > 0) { - LOG_INFO("Using Pin %i in digital mode\n", output); + LOG_INFO("Using Pin %i in digital mode", output); pinMode(output, OUTPUT); } setExternalOff(0); externalTurnedOn[0] = 0; if (moduleConfig.external_notification.output_vibra) { - LOG_INFO("Using Pin %i for vibra motor\n", moduleConfig.external_notification.output_vibra); + LOG_INFO("Using Pin %i for vibra motor", moduleConfig.external_notification.output_vibra); pinMode(moduleConfig.external_notification.output_vibra, OUTPUT); setExternalOff(1); externalTurnedOn[1] = 0; } if (moduleConfig.external_notification.output_buzzer) { if (!moduleConfig.external_notification.use_pwm) { - LOG_INFO("Using Pin %i for buzzer\n", moduleConfig.external_notification.output_buzzer); + LOG_INFO("Using Pin %i for buzzer", moduleConfig.external_notification.output_buzzer); pinMode(moduleConfig.external_notification.output_buzzer, OUTPUT); setExternalOff(2); externalTurnedOn[2] = 0; } else { config.device.buzzer_gpio = config.device.buzzer_gpio ? config.device.buzzer_gpio : PIN_BUZZER; // in PWM Mode we force the buzzer pin if it is set - LOG_INFO("Using Pin %i in PWM mode\n", config.device.buzzer_gpio); + LOG_INFO("Using Pin %i in PWM mode", config.device.buzzer_gpio); } } #ifdef HAS_NCP5623 @@ -414,7 +421,7 @@ ExternalNotificationModule::ExternalNotificationModule() pixels.setBrightness(moduleConfig.ambient_lighting.current); #endif } else { - LOG_INFO("External Notification Module Disabled\n"); + LOG_INFO("External Notification Module Disabled"); disable(); } } @@ -440,7 +447,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP if (moduleConfig.external_notification.alert_bell) { if (containsBell) { - LOG_INFO("externalNotificationModule - Notification Bell\n"); + LOG_INFO("externalNotificationModule - Notification Bell"); isNagging = true; setExternalOn(0); if (moduleConfig.external_notification.nag_timeout) { @@ -453,7 +460,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP if (moduleConfig.external_notification.alert_bell_vibra) { if (containsBell) { - LOG_INFO("externalNotificationModule - Notification Bell (Vibra)\n"); + LOG_INFO("externalNotificationModule - Notification Bell (Vibra)"); isNagging = true; setExternalOn(1); if (moduleConfig.external_notification.nag_timeout) { @@ -466,7 +473,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP if (moduleConfig.external_notification.alert_bell_buzzer) { if (containsBell) { - LOG_INFO("externalNotificationModule - Notification Bell (Buzzer)\n"); + LOG_INFO("externalNotificationModule - Notification Bell (Buzzer)"); isNagging = true; if (!moduleConfig.external_notification.use_pwm) { setExternalOn(2); @@ -486,7 +493,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP } if (moduleConfig.external_notification.alert_message) { - LOG_INFO("externalNotificationModule - Notification Module\n"); + LOG_INFO("externalNotificationModule - Notification Module"); isNagging = true; setExternalOn(0); if (moduleConfig.external_notification.nag_timeout) { @@ -497,7 +504,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP } if (moduleConfig.external_notification.alert_message_vibra) { - LOG_INFO("externalNotificationModule - Notification Module (Vibra)\n"); + LOG_INFO("externalNotificationModule - Notification Module (Vibra)"); isNagging = true; setExternalOn(1); if (moduleConfig.external_notification.nag_timeout) { @@ -508,7 +515,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP } if (moduleConfig.external_notification.alert_message_buzzer) { - LOG_INFO("externalNotificationModule - Notification Module (Buzzer)\n"); + LOG_INFO("externalNotificationModule - Notification Module (Buzzer)"); isNagging = true; if (!moduleConfig.external_notification.use_pwm && !moduleConfig.external_notification.use_i2s_as_buzzer) { setExternalOn(2); @@ -530,7 +537,7 @@ ProcessMessage ExternalNotificationModule::handleReceived(const meshtastic_MeshP setIntervalFromNow(0); // run once so we know if we should do something } } else { - LOG_INFO("External Notification Module Disabled or muted\n"); + LOG_INFO("External Notification Module Disabled or muted"); } return ProcessMessage::CONTINUE; // Let others look at this message also if they want @@ -553,13 +560,13 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule switch (request->which_payload_variant) { case meshtastic_AdminMessage_get_ringtone_request_tag: - LOG_INFO("Client is getting ringtone\n"); + LOG_INFO("Client is getting ringtone"); this->handleGetRingtone(mp, response); result = AdminMessageHandleResult::HANDLED_WITH_RESPONSE; break; case meshtastic_AdminMessage_set_ringtone_message_tag: - LOG_INFO("Client is setting ringtone\n"); + LOG_INFO("Client is setting ringtone"); this->handleSetRingtone(request->set_canned_message_module_messages); result = AdminMessageHandleResult::HANDLED; break; @@ -573,7 +580,7 @@ AdminMessageHandleResult ExternalNotificationModule::handleAdminMessageForModule void ExternalNotificationModule::handleGetRingtone(const meshtastic_MeshPacket &req, meshtastic_AdminMessage *response) { - LOG_INFO("*** handleGetRingtone\n"); + LOG_INFO("*** handleGetRingtone"); if (req.decoded.want_response) { response->which_payload_variant = meshtastic_AdminMessage_get_ringtone_response_tag; strncpy(response->get_ringtone_response, rtttlConfig.ringtone, sizeof(response->get_ringtone_response)); @@ -587,7 +594,7 @@ void ExternalNotificationModule::handleSetRingtone(const char *from_msg) if (*from_msg) { changed |= strcmp(rtttlConfig.ringtone, from_msg); strncpy(rtttlConfig.ringtone, from_msg, sizeof(rtttlConfig.ringtone)); - LOG_INFO("*** from_msg.text:%s\n", from_msg); + LOG_INFO("*** from_msg.text:%s", from_msg); } if (changed) { diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp index 554fad6a91..ad3f0ace45 100644 --- a/src/modules/Modules.cpp +++ b/src/modules/Modules.cpp @@ -58,6 +58,7 @@ #include "main.h" #include "modules/Telemetry/AirQualityTelemetry.h" #include "modules/Telemetry/EnvironmentTelemetry.h" +#include "modules/Telemetry/HealthTelemetry.h" #endif #if HAS_TELEMETRY && !MESHTASTIC_EXCLUDE_POWER_TELEMETRY #include "modules/Telemetry/PowerTelemetry.h" @@ -194,6 +195,10 @@ void setupModules() if (nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_PMSA003I].first > 0) { new AirQualityTelemetryModule(); } + if (nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_MAX30102].first > 0 || + nodeTelemetrySensorsMap[meshtastic_TelemetrySensorType_MLX90614].first > 0) { + new HealthTelemetryModule(); + } #endif #if HAS_TELEMETRY && !MESHTASTIC_EXCLUDE_POWER_TELEMETRY && !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR new PowerTelemetryModule(); diff --git a/src/modules/NeighborInfoModule.cpp b/src/modules/NeighborInfoModule.cpp index e4c9b44bdb..cbf63e9af9 100644 --- a/src/modules/NeighborInfoModule.cpp +++ b/src/modules/NeighborInfoModule.cpp @@ -14,11 +14,11 @@ NOTE: For debugging only */ void NeighborInfoModule::printNeighborInfo(const char *header, const meshtastic_NeighborInfo *np) { - LOG_DEBUG("%s NEIGHBORINFO PACKET from Node 0x%x to Node 0x%x (last sent by 0x%x)\n", header, np->node_id, - nodeDB->getNodeNum(), np->last_sent_by_id); - LOG_DEBUG("Packet contains %d neighbors\n", np->neighbors_count); + LOG_DEBUG("%s NEIGHBORINFO PACKET from Node 0x%x to Node 0x%x (last sent by 0x%x)", header, np->node_id, nodeDB->getNodeNum(), + np->last_sent_by_id); + LOG_DEBUG("Packet contains %d neighbors", np->neighbors_count); for (int i = 0; i < np->neighbors_count; i++) { - LOG_DEBUG("Neighbor %d: node_id=0x%x, snr=%.2f\n", i, np->neighbors[i].node_id, np->neighbors[i].snr); + LOG_DEBUG("Neighbor %d: node_id=0x%x, snr=%.2f", i, np->neighbors[i].node_id, np->neighbors[i].snr); } } @@ -28,9 +28,9 @@ NOTE: for debugging only */ void NeighborInfoModule::printNodeDBNeighbors() { - LOG_DEBUG("Our NodeDB contains %d neighbors\n", neighbors.size()); + LOG_DEBUG("Our NodeDB contains %d neighbors", neighbors.size()); for (size_t i = 0; i < neighbors.size(); i++) { - LOG_DEBUG("Node %d: node_id=0x%x, snr=%.2f\n", i, neighbors[i].node_id, neighbors[i].snr); + LOG_DEBUG("Node %d: node_id=0x%x, snr=%.2f", i, neighbors[i].node_id, neighbors[i].snr); } } @@ -47,7 +47,7 @@ NeighborInfoModule::NeighborInfoModule() setIntervalFromNow(Default::getConfiguredOrDefaultMs(moduleConfig.neighbor_info.update_interval, default_telemetry_broadcast_interval_secs)); } else { - LOG_DEBUG("NeighborInfoModule is disabled\n"); + LOG_DEBUG("NeighborInfoModule is disabled"); disable(); } } @@ -91,7 +91,7 @@ void NeighborInfoModule::cleanUpNeighbors() // We will remove a neighbor if we haven't heard from them in twice the broadcast interval // cannot use isWithinTimespanMs() as it->last_rx_time is seconds since 1970 if ((now - it->last_rx_time > it->node_broadcast_interval_secs * 2) && (it->node_id != my_node_id)) { - LOG_DEBUG("Removing neighbor with node ID 0x%x\n", it->node_id); + LOG_DEBUG("Removing neighbor with node ID 0x%x", it->node_id); it = std::vector::reverse_iterator( neighbors.erase(std::next(it).base())); // Erase the element and update the iterator } else { @@ -122,7 +122,7 @@ Will be used for broadcast. int32_t NeighborInfoModule::runOnce() { if (airTime->isTxAllowedChannelUtil(true) && airTime->isTxAllowedAirUtil()) { - sendNeighborInfo(NODENUM_BROADCAST, false); + sendNeighborInfo(NODENUM_BROADCAST_NO_LORA, false); } return Default::getConfiguredOrDefaultMs(moduleConfig.neighbor_info.update_interval, default_neighbor_info_broadcast_secs); } @@ -205,7 +205,7 @@ meshtastic_Neighbor *NeighborInfoModule::getOrCreateNeighbor(NodeNum originalSen neighbors.push_back(new_nbr); } else { // If we have too many neighbors, replace the oldest one - LOG_WARN("Neighbor DB is full, replacing oldest neighbor\n"); + LOG_WARN("Neighbor DB is full, replacing oldest neighbor"); neighbors.erase(neighbors.begin()); neighbors.push_back(new_nbr); } diff --git a/src/modules/NodeInfoModule.cpp b/src/modules/NodeInfoModule.cpp index 61ec375ccb..843711807e 100644 --- a/src/modules/NodeInfoModule.cpp +++ b/src/modules/NodeInfoModule.cpp @@ -16,7 +16,7 @@ bool NodeInfoModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, mes bool hasChanged = nodeDB->updateUser(getFrom(&mp), p, mp.channel); - bool wasBroadcast = mp.to == NODENUM_BROADCAST; + bool wasBroadcast = isBroadcast(mp.to); // Show new nodes on LCD screen if (wasBroadcast) { @@ -29,7 +29,7 @@ bool NodeInfoModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, mes if (hasChanged && !wasBroadcast && !isToUs(&mp)) service->sendToPhone(packetPool.allocCopy(mp)); - // LOG_DEBUG("did handleReceived\n"); + // LOG_DEBUG("did handleReceived"); return false; // Let others look at this message also if they want } @@ -50,7 +50,7 @@ void NodeInfoModule::sendOurNodeInfo(NodeNum dest, bool wantReplies, uint8_t cha else p->priority = meshtastic_MeshPacket_Priority_BACKGROUND; if (channel > 0) { - LOG_DEBUG("sending ourNodeInfo to channel %d\n", channel); + LOG_DEBUG("sending ourNodeInfo to channel %d", channel); p->channel = channel; } @@ -65,23 +65,23 @@ meshtastic_MeshPacket *NodeInfoModule::allocReply() { if (!airTime->isTxAllowedChannelUtil(false)) { ignoreRequest = true; // Mark it as ignored for MeshModule - LOG_DEBUG("Skip sending NodeInfo due to > 40 percent channel util.\n"); + LOG_DEBUG("Skip sending NodeInfo due to > 40 percent channel util."); return NULL; } // If we sent our NodeInfo less than 5 min. ago, don't send it again as it may be still underway. if (!shorterTimeout && lastSentToMesh && Throttle::isWithinTimespanMs(lastSentToMesh, 5 * 60 * 1000)) { - LOG_DEBUG("Skip sending NodeInfo since we just sent it less than 5 minutes ago.\n"); + LOG_DEBUG("Skip sending NodeInfo since we just sent it less than 5 minutes ago."); ignoreRequest = true; // Mark it as ignored for MeshModule return NULL; } else if (shorterTimeout && lastSentToMesh && Throttle::isWithinTimespanMs(lastSentToMesh, 60 * 1000)) { - LOG_DEBUG("Skip sending actively requested NodeInfo since we just sent it less than 60 seconds ago.\n"); + LOG_DEBUG("Skip sending actively requested NodeInfo since we just sent it less than 60 seconds ago."); ignoreRequest = true; // Mark it as ignored for MeshModule return NULL; } else { ignoreRequest = false; // Don't ignore requests anymore meshtastic_User &u = owner; - LOG_INFO("sending owner %s/%s/%s\n", u.id, u.long_name, u.short_name); + LOG_INFO("sending owner %s/%s/%s", u.id, u.long_name, u.short_name); lastSentToMesh = millis(); return allocDataProtobuf(u); } @@ -102,7 +102,7 @@ int32_t NodeInfoModule::runOnce() currentGeneration = radioGeneration; if (airTime->isTxAllowedAirUtil() && config.device.role != meshtastic_Config_DeviceConfig_Role_CLIENT_HIDDEN) { - LOG_INFO("Sending our nodeinfo to mesh (wantReplies=%d)\n", requestReplies); + LOG_INFO("Sending our nodeinfo to mesh (wantReplies=%d)", requestReplies); sendOurNodeInfo(NODENUM_BROADCAST, requestReplies); // Send our info (don't request replies) } return Default::getConfiguredOrDefaultMs(config.device.node_info_broadcast_secs, default_node_info_broadcast_secs); diff --git a/src/modules/PositionModule.cpp b/src/modules/PositionModule.cpp index 6ad30f9279..5500a559ec 100644 --- a/src/modules/PositionModule.cpp +++ b/src/modules/PositionModule.cpp @@ -39,7 +39,7 @@ PositionModule::PositionModule() if ((config.device.role == meshtastic_Config_DeviceConfig_Role_TRACKER || config.device.role == meshtastic_Config_DeviceConfig_Role_TAK_TRACKER) && config.power.is_power_saving) { - LOG_DEBUG("Clearing position on startup for sleepy tracker (ー。ー) zzz\n"); + LOG_DEBUG("Clearing position on startup for sleepy tracker (ー。ー) zzz"); nodeDB->clearLocalPosition(); } } @@ -57,7 +57,7 @@ bool PositionModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, mes if (isFromUs(&mp)) { isLocal = true; if (config.position.fixed_position) { - LOG_DEBUG("Ignore incoming position update from myself except for time, because position.fixed_position is true\n"); + LOG_DEBUG("Ignore incoming position update from myself except for time, because position.fixed_position is true"); #ifdef T_WATCH_S3 // Since we return early if position.fixed_position is true, set the T-Watch's RTC to the time received from the @@ -70,14 +70,14 @@ bool PositionModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, mes nodeDB->setLocalPosition(p, true); return false; } else { - LOG_DEBUG("Incoming update from MYSELF\n"); + LOG_DEBUG("Incoming update from MYSELF"); nodeDB->setLocalPosition(p); } } // Log packet size and data fields LOG_DEBUG("POSITION node=%08x l=%d lat=%d lon=%d msl=%d hae=%d geo=%d pdop=%d hdop=%d vdop=%d siv=%d fxq=%d fxt=%d pts=%d " - "time=%d\n", + "time=%d", getFrom(&mp), mp.decoded.payload.size, p.latitude_i, p.longitude_i, p.altitude, p.altitude_hae, p.altitude_geoidal_separation, p.PDOP, p.HDOP, p.VDOP, p.sats_in_view, p.fix_quality, p.fix_type, p.timestamp, p.time); @@ -111,7 +111,7 @@ void PositionModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtastic { // Phone position packets need to be truncated to the channel precision if (isFromUs(&mp) && (precision < 32 && precision > 0)) { - LOG_DEBUG("Truncating phone position to channel precision %i\n", precision); + LOG_DEBUG("Truncating phone position to channel precision %i", precision); p->latitude_i = p->latitude_i & (UINT32_MAX << (32 - precision)); p->longitude_i = p->longitude_i & (UINT32_MAX << (32 - precision)); @@ -127,11 +127,11 @@ void PositionModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtastic void PositionModule::trySetRtc(meshtastic_Position p, bool isLocal, bool forceUpdate) { if (hasQualityTimesource() && !isLocal) { - LOG_DEBUG("Ignoring time from mesh because we have a GPS, RTC, or Phone/NTP time source in the past day\n"); + LOG_DEBUG("Ignoring time from mesh because we have a GPS, RTC, or Phone/NTP time source in the past day"); return; } if (!isLocal && p.location_source < meshtastic_Position_LocSource_LOC_INTERNAL) { - LOG_DEBUG("Ignoring time from mesh because it has a unknown or manual source\n"); + LOG_DEBUG("Ignoring time from mesh because it has a unknown or manual source"); return; } struct timeval tv; @@ -158,7 +158,7 @@ bool PositionModule::hasQualityTimesource() meshtastic_MeshPacket *PositionModule::allocReply() { if (precision == 0) { - LOG_DEBUG("Skipping location send because precision is set to 0!\n"); + LOG_DEBUG("Skipping location send because precision is set to 0!"); return nullptr; } @@ -178,12 +178,12 @@ meshtastic_MeshPacket *PositionModule::allocReply() localPosition.seq_number++; if (localPosition.latitude_i == 0 && localPosition.longitude_i == 0) { - LOG_WARN("Skipping position send because lat/lon are zero!\n"); + LOG_WARN("Skipping position send because lat/lon are zero!"); return nullptr; } // lat/lon are unconditionally included - IF AVAILABLE! - LOG_DEBUG("Sending location with precision %i\n", precision); + LOG_DEBUG("Sending location with precision %i", precision); if (precision < 32 && precision > 0) { p.latitude_i = localPosition.latitude_i & (UINT32_MAX << (32 - precision)); p.longitude_i = localPosition.longitude_i & (UINT32_MAX << (32 - precision)); @@ -250,14 +250,14 @@ meshtastic_MeshPacket *PositionModule::allocReply() // nodes shouldn't trust it anyways) Note: we allow a device with a local GPS or NTP to include the time, so that devices // without can get time. if (getRTCQuality() < RTCQualityNTP) { - LOG_INFO("Stripping time %u from position send\n", p.time); + LOG_INFO("Stripping time %u from position send", p.time); p.time = 0; } else { p.time = getValidTime(RTCQualityNTP); - LOG_INFO("Providing time to mesh %u\n", p.time); + LOG_INFO("Providing time to mesh %u", p.time); } - LOG_INFO("Position reply: time=%i lat=%i lon=%i\n", p.time, p.latitude_i, p.longitude_i); + LOG_INFO("Position reply: time=%i lat=%i lon=%i", p.time, p.latitude_i, p.longitude_i); // TAK Tracker devices should send their position in a TAK packet over the ATAK port if (config.device.role == meshtastic_Config_DeviceConfig_Role_TAK_TRACKER) @@ -268,7 +268,7 @@ meshtastic_MeshPacket *PositionModule::allocReply() meshtastic_MeshPacket *PositionModule::allocAtakPli() { - LOG_INFO("Sending TAK PLI packet\n"); + LOG_INFO("Sending TAK PLI packet"); meshtastic_MeshPacket *mp = allocDataPacket(); mp->decoded.portnum = meshtastic_PortNum_ATAK_PLUGIN; @@ -293,8 +293,8 @@ meshtastic_MeshPacket *PositionModule::allocAtakPli() auto length = unishox2_compress_lines(owner.long_name, strlen(owner.long_name), takPacket.contact.device_callsign, sizeof(takPacket.contact.device_callsign) - 1, USX_PSET_DFLT, NULL); - LOG_DEBUG("Uncompressed device_callsign '%s' - %d bytes\n", owner.long_name, strlen(owner.long_name)); - LOG_DEBUG("Compressed device_callsign '%s' - %d bytes\n", takPacket.contact.device_callsign, length); + LOG_DEBUG("Uncompressed device_callsign '%s' - %d bytes", owner.long_name, strlen(owner.long_name)); + LOG_DEBUG("Compressed device_callsign '%s' - %d bytes", takPacket.contact.device_callsign, length); length = unishox2_compress_lines(owner.long_name, strlen(owner.long_name), takPacket.contact.callsign, sizeof(takPacket.contact.callsign) - 1, USX_PSET_DFLT, NULL); mp->decoded.payload.size = @@ -308,7 +308,7 @@ void PositionModule::sendOurPosition() currentGeneration = radioGeneration; // If we changed channels, ask everyone else for their latest info - LOG_INFO("Sending pos@%x:6 to mesh (wantReplies=%d)\n", localPosition.timestamp, requestReplies); + LOG_INFO("Sending pos@%x:6 to mesh (wantReplies=%d)", localPosition.timestamp, requestReplies); sendOurPosition(NODENUM_BROADCAST, requestReplies); } @@ -330,7 +330,7 @@ void PositionModule::sendOurPosition(NodeNum dest, bool wantReplies, uint8_t cha meshtastic_MeshPacket *p = allocReply(); if (p == nullptr) { - LOG_DEBUG("allocReply returned a nullptr\n"); + LOG_DEBUG("allocReply returned a nullptr"); return; } @@ -351,7 +351,7 @@ void PositionModule::sendOurPosition(NodeNum dest, bool wantReplies, uint8_t cha if (IS_ONE_OF(config.device.role, meshtastic_Config_DeviceConfig_Role_TRACKER, meshtastic_Config_DeviceConfig_Role_TAK_TRACKER) && config.power.is_power_saving) { - LOG_DEBUG("Starting next execution in 5 seconds and then going to sleep.\n"); + LOG_DEBUG("Starting next execution in 5 seconds and then going to sleep."); sleepOnNextExecution = true; setIntervalFromNow(5000); } @@ -364,7 +364,7 @@ int32_t PositionModule::runOnce() if (sleepOnNextExecution == true) { sleepOnNextExecution = false; uint32_t nightyNightMs = Default::getConfiguredOrDefaultMs(config.position.position_broadcast_secs); - LOG_DEBUG("Sleeping for %ims, then awaking to send position again.\n", nightyNightMs); + LOG_DEBUG("Sleeping for %ims, then awaking to send position again.", nightyNightMs); doDeepSleep(nightyNightMs, false); } @@ -407,10 +407,10 @@ int32_t PositionModule::runOnce() if (smartPosition.hasTraveledOverThreshold && Throttle::execute( &lastGpsSend, minimumTimeThreshold, []() { positionModule->sendOurPosition(); }, - []() { LOG_DEBUG("Skipping send smart broadcast due to time throttling\n"); })) { + []() { LOG_DEBUG("Skipping send smart broadcast due to time throttling"); })) { LOG_DEBUG("Sent smart pos@%x:6 to mesh (distanceTraveled=%fm, minDistanceThreshold=%im, timeElapsed=%ims, " - "minTimeInterval=%ims)\n", + "minTimeInterval=%ims)", localPosition.timestamp, smartPosition.distanceTraveled, smartPosition.distanceThreshold, msSinceLastSend, minimumTimeThreshold); @@ -450,19 +450,19 @@ struct SmartPosition PositionModule::getDistanceTraveledSinceLastSend(meshtastic lastGpsLatitude * 1e-7, lastGpsLongitude * 1e-7, currentPosition.latitude_i * 1e-7, currentPosition.longitude_i * 1e-7); #ifdef GPS_EXTRAVERBOSE - LOG_DEBUG("--------LAST POSITION------------------------------------\n"); - LOG_DEBUG("lastGpsLatitude=%i, lastGpsLatitude=%i\n", lastGpsLatitude, lastGpsLongitude); + LOG_DEBUG("--------LAST POSITION------------------------------------"); + LOG_DEBUG("lastGpsLatitude=%i, lastGpsLatitude=%i", lastGpsLatitude, lastGpsLongitude); - LOG_DEBUG("--------CURRENT POSITION---------------------------------\n"); - LOG_DEBUG("currentPosition.latitude_i=%i, currentPosition.longitude_i=%i\n", lastGpsLatitude, lastGpsLongitude); + LOG_DEBUG("--------CURRENT POSITION---------------------------------"); + LOG_DEBUG("currentPosition.latitude_i=%i, currentPosition.longitude_i=%i", lastGpsLatitude, lastGpsLongitude); - LOG_DEBUG("--------SMART POSITION-----------------------------------\n"); - LOG_DEBUG("hasTraveledOverThreshold=%i, distanceTraveled=%f, distanceThreshold=%f\n", + LOG_DEBUG("--------SMART POSITION-----------------------------------"); + LOG_DEBUG("hasTraveledOverThreshold=%i, distanceTraveled=%f, distanceThreshold=%f", abs(distanceTraveledSinceLastSend) >= distanceTravelThreshold, abs(distanceTraveledSinceLastSend), distanceTravelThreshold); if (abs(distanceTraveledSinceLastSend) >= distanceTravelThreshold) { - LOG_DEBUG("\n\n\nSMART SEEEEEEEEENDING\n\n\n"); + LOG_DEBUG("SMART SEEEEEEEEENDING"); } #endif @@ -482,9 +482,9 @@ void PositionModule::handleNewPosition() if (smartPosition.hasTraveledOverThreshold && Throttle::execute( &lastGpsSend, minimumTimeThreshold, []() { positionModule->sendOurPosition(); }, - []() { LOG_DEBUG("Skipping send smart broadcast due to time throttling\n"); })) { + []() { LOG_DEBUG("Skipping send smart broadcast due to time throttling"); })) { LOG_DEBUG("Sent smart pos@%x:6 to mesh (distanceTraveled=%fm, minDistanceThreshold=%im, timeElapsed=%ims, " - "minTimeInterval=%ims)\n", + "minTimeInterval=%ims)", localPosition.timestamp, smartPosition.distanceTraveled, smartPosition.distanceThreshold, msSinceLastSend, minimumTimeThreshold); diff --git a/src/modules/PowerStressModule.cpp b/src/modules/PowerStressModule.cpp index 48159ba549..5605d1100c 100644 --- a/src/modules/PowerStressModule.cpp +++ b/src/modules/PowerStressModule.cpp @@ -24,12 +24,12 @@ bool PowerStressModule::handleReceivedProtobuf(const meshtastic_MeshPacket &req, // We only respond to messages if powermon debugging is already on if (config.power.powermon_enables) { auto p = *pptr; - LOG_INFO("Received PowerStress cmd=%d\n", p.cmd); + LOG_INFO("Received PowerStress cmd=%d", p.cmd); // Some commands we can handle immediately, anything else gets deferred to be handled by our thread switch (p.cmd) { case meshtastic_PowerStressMessage_Opcode_UNSET: - LOG_ERROR("PowerStress operation unset\n"); + LOG_ERROR("PowerStress operation unset"); break; case meshtastic_PowerStressMessage_Opcode_PRINT_INFO: @@ -42,7 +42,7 @@ bool PowerStressModule::handleReceivedProtobuf(const meshtastic_MeshPacket &req, default: if (currentMessage.cmd != meshtastic_PowerStressMessage_Opcode_UNSET) - LOG_ERROR("PowerStress operation %d already in progress! Can't start new command\n", currentMessage.cmd); + LOG_ERROR("PowerStress operation %d already in progress! Can't start new command", currentMessage.cmd); else currentMessage = p; // copy for use by thread (the message provided to us will be getting freed) break; @@ -67,13 +67,13 @@ int32_t PowerStressModule::runOnce() p.cmd = meshtastic_PowerStressMessage_Opcode_UNSET; p.num_seconds = 0; isRunningCommand = false; - LOG_INFO("S:PS:%u\n", p.cmd); + LOG_INFO("S:PS:%u", p.cmd); } else { if (p.cmd != meshtastic_PowerStressMessage_Opcode_UNSET) { sleep_msec = (int32_t)(p.num_seconds * 1000); isRunningCommand = !!sleep_msec; // if the command wants us to sleep, make sure to mark that we have something running LOG_INFO( - "S:PS:%u\n", + "S:PS:%u", p.cmd); // Emit a structured log saying we are starting a powerstress state (to make it easier to parse later) switch (p.cmd) { @@ -124,7 +124,7 @@ int32_t PowerStressModule::runOnce() // FIXME - implement break; default: - LOG_ERROR("PowerStress operation %d not yet implemented!\n", p.cmd); + LOG_ERROR("PowerStress operation %d not yet implemented!", p.cmd); sleep_msec = 0; // Don't do whatever sleep was requested... break; } diff --git a/src/modules/RangeTestModule.cpp b/src/modules/RangeTestModule.cpp index e78b4e68da..2deb2ba921 100644 --- a/src/modules/RangeTestModule.cpp +++ b/src/modules/RangeTestModule.cpp @@ -54,11 +54,11 @@ int32_t RangeTestModule::runOnce() firstTime = 0; if (moduleConfig.range_test.sender) { - LOG_INFO("Initializing Range Test Module -- Sender\n"); + LOG_INFO("Initializing Range Test Module -- Sender"); started = millis(); // make a note of when we started return (5000); // Sending first message 5 seconds after initialization. } else { - LOG_INFO("Initializing Range Test Module -- Receiver\n"); + LOG_INFO("Initializing Range Test Module -- Receiver"); return disable(); // This thread does not need to run as a receiver } @@ -66,13 +66,13 @@ int32_t RangeTestModule::runOnce() if (moduleConfig.range_test.sender) { // If sender - LOG_INFO("Range Test Module - Sending heartbeat every %d ms\n", (senderHeartbeat)); + LOG_INFO("Range Test Module - Sending heartbeat every %d ms", (senderHeartbeat)); - LOG_INFO("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); - LOG_INFO("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); - LOG_INFO("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); - LOG_INFO("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); - LOG_INFO("fixed_position() %d\n", config.position.fixed_position); + LOG_INFO("gpsStatus->getLatitude() %d", gpsStatus->getLatitude()); + LOG_INFO("gpsStatus->getLongitude() %d", gpsStatus->getLongitude()); + LOG_INFO("gpsStatus->getHasLock() %d", gpsStatus->getHasLock()); + LOG_INFO("gpsStatus->getDOP() %d", gpsStatus->getDOP()); + LOG_INFO("fixed_position() %d", config.position.fixed_position); // Only send packets if the channel is less than 25% utilized. if (airTime->isTxAllowedChannelUtil(true)) { @@ -81,7 +81,7 @@ int32_t RangeTestModule::runOnce() // If we have been running for more than 8 hours, turn module back off if (!Throttle::isWithinTimespanMs(started, 28800000)) { - LOG_INFO("Range Test Module - Disabling after 8 hours\n"); + LOG_INFO("Range Test Module - Disabling after 8 hours"); return disable(); } else { return (senderHeartbeat); @@ -92,7 +92,7 @@ int32_t RangeTestModule::runOnce() } } } else { - LOG_INFO("Range Test Module - Disabled\n"); + LOG_INFO("Range Test Module - Disabled"); } #endif @@ -135,7 +135,7 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const meshtastic_MeshPacket /* auto &p = mp.decoded; - LOG_DEBUG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", + LOG_DEBUG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s", LOG_INFO.getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes); */ @@ -148,31 +148,31 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const meshtastic_MeshPacket /* NodeInfoLite *n = nodeDB->getMeshNode(getFrom(&mp)); - LOG_DEBUG("-----------------------------------------\n"); - LOG_DEBUG("p.payload.bytes \"%s\"\n", p.payload.bytes); - LOG_DEBUG("p.payload.size %d\n", p.payload.size); - LOG_DEBUG("---- Received Packet:\n"); - LOG_DEBUG("mp.from %d\n", mp.from); - LOG_DEBUG("mp.rx_snr %f\n", mp.rx_snr); - LOG_DEBUG("mp.hop_limit %d\n", mp.hop_limit); - // LOG_DEBUG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Deprecated - // LOG_DEBUG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Deprecated - LOG_DEBUG("---- Node Information of Received Packet (mp.from):\n"); - LOG_DEBUG("n->user.long_name %s\n", n->user.long_name); - LOG_DEBUG("n->user.short_name %s\n", n->user.short_name); - LOG_DEBUG("n->has_position %d\n", n->has_position); - LOG_DEBUG("n->position.latitude_i %d\n", n->position.latitude_i); - LOG_DEBUG("n->position.longitude_i %d\n", n->position.longitude_i); - LOG_DEBUG("---- Current device location information:\n"); - LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); - LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); - LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); - LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); - LOG_DEBUG("-----------------------------------------\n"); + LOG_DEBUG("-----------------------------------------"); + LOG_DEBUG("p.payload.bytes \"%s\"", p.payload.bytes); + LOG_DEBUG("p.payload.size %d", p.payload.size); + LOG_DEBUG("---- Received Packet:"); + LOG_DEBUG("mp.from %d", mp.from); + LOG_DEBUG("mp.rx_snr %f", mp.rx_snr); + LOG_DEBUG("mp.hop_limit %d", mp.hop_limit); + // LOG_DEBUG("mp.decoded.position.latitude_i %d", mp.decoded.position.latitude_i); // Deprecated + // LOG_DEBUG("mp.decoded.position.longitude_i %d", mp.decoded.position.longitude_i); // Deprecated + LOG_DEBUG("---- Node Information of Received Packet (mp.from):"); + LOG_DEBUG("n->user.long_name %s", n->user.long_name); + LOG_DEBUG("n->user.short_name %s", n->user.short_name); + LOG_DEBUG("n->has_position %d", n->has_position); + LOG_DEBUG("n->position.latitude_i %d", n->position.latitude_i); + LOG_DEBUG("n->position.longitude_i %d", n->position.longitude_i); + LOG_DEBUG("---- Current device location information:"); + LOG_DEBUG("gpsStatus->getLatitude() %d", gpsStatus->getLatitude()); + LOG_DEBUG("gpsStatus->getLongitude() %d", gpsStatus->getLongitude()); + LOG_DEBUG("gpsStatus->getHasLock() %d", gpsStatus->getHasLock()); + LOG_DEBUG("gpsStatus->getDOP() %d", gpsStatus->getDOP()); + LOG_DEBUG("-----------------------------------------"); */ } } else { - LOG_INFO("Range Test Module Disabled\n"); + LOG_INFO("Range Test Module Disabled"); } #endif @@ -187,35 +187,35 @@ bool RangeTestModuleRadio::appendFile(const meshtastic_MeshPacket &mp) meshtastic_NodeInfoLite *n = nodeDB->getMeshNode(getFrom(&mp)); /* - LOG_DEBUG("-----------------------------------------\n"); - LOG_DEBUG("p.payload.bytes \"%s\"\n", p.payload.bytes); - LOG_DEBUG("p.payload.size %d\n", p.payload.size); - LOG_DEBUG("---- Received Packet:\n"); - LOG_DEBUG("mp.from %d\n", mp.from); - LOG_DEBUG("mp.rx_snr %f\n", mp.rx_snr); - LOG_DEBUG("mp.hop_limit %d\n", mp.hop_limit); - // LOG_DEBUG("mp.decoded.position.latitude_i %d\n", mp.decoded.position.latitude_i); // Deprecated - // LOG_DEBUG("mp.decoded.position.longitude_i %d\n", mp.decoded.position.longitude_i); // Deprecated - LOG_DEBUG("---- Node Information of Received Packet (mp.from):\n"); - LOG_DEBUG("n->user.long_name %s\n", n->user.long_name); - LOG_DEBUG("n->user.short_name %s\n", n->user.short_name); - LOG_DEBUG("n->has_position %d\n", n->has_position); - LOG_DEBUG("n->position.latitude_i %d\n", n->position.latitude_i); - LOG_DEBUG("n->position.longitude_i %d\n", n->position.longitude_i); - LOG_DEBUG("---- Current device location information:\n"); - LOG_DEBUG("gpsStatus->getLatitude() %d\n", gpsStatus->getLatitude()); - LOG_DEBUG("gpsStatus->getLongitude() %d\n", gpsStatus->getLongitude()); - LOG_DEBUG("gpsStatus->getHasLock() %d\n", gpsStatus->getHasLock()); - LOG_DEBUG("gpsStatus->getDOP() %d\n", gpsStatus->getDOP()); - LOG_DEBUG("-----------------------------------------\n"); + LOG_DEBUG("-----------------------------------------"); + LOG_DEBUG("p.payload.bytes \"%s\"", p.payload.bytes); + LOG_DEBUG("p.payload.size %d", p.payload.size); + LOG_DEBUG("---- Received Packet:"); + LOG_DEBUG("mp.from %d", mp.from); + LOG_DEBUG("mp.rx_snr %f", mp.rx_snr); + LOG_DEBUG("mp.hop_limit %d", mp.hop_limit); + // LOG_DEBUG("mp.decoded.position.latitude_i %d", mp.decoded.position.latitude_i); // Deprecated + // LOG_DEBUG("mp.decoded.position.longitude_i %d", mp.decoded.position.longitude_i); // Deprecated + LOG_DEBUG("---- Node Information of Received Packet (mp.from):"); + LOG_DEBUG("n->user.long_name %s", n->user.long_name); + LOG_DEBUG("n->user.short_name %s", n->user.short_name); + LOG_DEBUG("n->has_position %d", n->has_position); + LOG_DEBUG("n->position.latitude_i %d", n->position.latitude_i); + LOG_DEBUG("n->position.longitude_i %d", n->position.longitude_i); + LOG_DEBUG("---- Current device location information:"); + LOG_DEBUG("gpsStatus->getLatitude() %d", gpsStatus->getLatitude()); + LOG_DEBUG("gpsStatus->getLongitude() %d", gpsStatus->getLongitude()); + LOG_DEBUG("gpsStatus->getHasLock() %d", gpsStatus->getHasLock()); + LOG_DEBUG("gpsStatus->getDOP() %d", gpsStatus->getDOP()); + LOG_DEBUG("-----------------------------------------"); */ if (!FSBegin()) { - LOG_DEBUG("An Error has occurred while mounting the filesystem\n"); + LOG_DEBUG("An Error has occurred while mounting the filesystem"); return 0; } if (FSCom.totalBytes() - FSCom.usedBytes() < 51200) { - LOG_DEBUG("Filesystem doesn't have enough free space. Aborting write.\n"); + LOG_DEBUG("Filesystem doesn't have enough free space. Aborting write."); return 0; } @@ -227,16 +227,16 @@ bool RangeTestModuleRadio::appendFile(const meshtastic_MeshPacket &mp) File fileToWrite = FSCom.open("/static/rangetest.csv", FILE_WRITE); if (!fileToWrite) { - LOG_ERROR("There was an error opening the file for writing\n"); + LOG_ERROR("There was an error opening the file for writing"); return 0; } // Print the CSV header if (fileToWrite.println( "time,from,sender name,sender lat,sender long,rx lat,rx long,rx elevation,rx snr,distance,hop limit,payload")) { - LOG_INFO("File was written\n"); + LOG_INFO("File was written"); } else { - LOG_ERROR("File write failed\n"); + LOG_ERROR("File write failed"); } fileToWrite.flush(); fileToWrite.close(); @@ -246,7 +246,7 @@ bool RangeTestModuleRadio::appendFile(const meshtastic_MeshPacket &mp) File fileToAppend = FSCom.open("/static/rangetest.csv", FILE_APPEND); if (!fileToAppend) { - LOG_ERROR("There was an error opening the file for appending\n"); + LOG_ERROR("There was an error opening the file for appending"); return 0; } diff --git a/src/modules/RemoteHardwareModule.cpp b/src/modules/RemoteHardwareModule.cpp index 43612e4507..a7d81cd2d9 100644 --- a/src/modules/RemoteHardwareModule.cpp +++ b/src/modules/RemoteHardwareModule.cpp @@ -79,7 +79,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const meshtastic_MeshPacket &r { if (moduleConfig.remote_hardware.enabled) { auto p = *pptr; - LOG_INFO("Received RemoteHardware type=%d\n", p.type); + LOG_INFO("Received RemoteHardware type=%d", p.type); switch (p.type) { case meshtastic_HardwareMessage_Type_WRITE_GPIOS: { @@ -122,7 +122,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const meshtastic_MeshPacket &r ~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 setInterval(2000); // Set a new interval so we'll run soon - LOG_INFO("Now watching GPIOs 0x%llx\n", watchGpios); + LOG_INFO("Now watching GPIOs 0x%llx", watchGpios); break; } @@ -131,7 +131,7 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const meshtastic_MeshPacket &r break; // Ignore - we might see our own replies default: - LOG_ERROR("Hardware operation %d not yet implemented! FIXME\n", p.type); + LOG_ERROR("Hardware operation %d not yet implemented! FIXME", p.type); break; } } @@ -149,7 +149,7 @@ int32_t RemoteHardwareModule::runOnce() if (curVal != previousWatch) { previousWatch = curVal; - LOG_INFO("Broadcasting GPIOS 0x%llx changed!\n", curVal); + LOG_INFO("Broadcasting GPIOS 0x%llx changed!", curVal); // Something changed! Tell the world with a broadcast message meshtastic_HardwareMessage r = meshtastic_HardwareMessage_init_default; diff --git a/src/modules/ReplyModule.cpp b/src/modules/ReplyModule.cpp index 439f6b7f7f..27a12d26b0 100644 --- a/src/modules/ReplyModule.cpp +++ b/src/modules/ReplyModule.cpp @@ -12,7 +12,7 @@ meshtastic_MeshPacket *ReplyModule::allocReply() auto req = *currentRequest; auto &p = req.decoded; // The incoming message is in p.payload - LOG_INFO("Received message from=0x%0x, id=%d, msg=%.*s\n", req.from, req.id, p.payload.size, p.payload.bytes); + LOG_INFO("Received message from=0x%0x, id=%d, msg=%.*s", req.from, req.id, p.payload.size, p.payload.bytes); #endif screen->print("Sending reply\n"); diff --git a/src/modules/RoutingModule.cpp b/src/modules/RoutingModule.cpp index 3b7be1ab7c..f11a9a542f 100644 --- a/src/modules/RoutingModule.cpp +++ b/src/modules/RoutingModule.cpp @@ -10,11 +10,7 @@ RoutingModule *routingModule; bool RoutingModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Routing *r) { - printPacket("Routing sniffing", &mp); - router->sniffReceived(&mp, r); - - bool maybePKI = - mp.which_payload_variant == meshtastic_MeshPacket_encrypted_tag && mp.channel == 0 && mp.to != NODENUM_BROADCAST; + bool maybePKI = mp.which_payload_variant == meshtastic_MeshPacket_encrypted_tag && mp.channel == 0 && !isBroadcast(mp.to); // Beginning of logic whether to drop the packet based on Rebroadcast mode if (mp.which_payload_variant == meshtastic_MeshPacket_encrypted_tag && (config.device.rebroadcast_mode == meshtastic_Config_DeviceConfig_RebroadcastMode_LOCAL_ONLY || @@ -26,9 +22,12 @@ bool RoutingModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, mesh return false; } + printPacket("Routing sniffing", &mp); + router->sniffReceived(&mp, r); + // FIXME - move this to a non promsicious PhoneAPI module? // Note: we are careful not to send back packets that started with the phone back to the phone - if ((mp.to == NODENUM_BROADCAST || isToUs(&mp)) && (mp.from != 0)) { + if ((isBroadcast(mp.to) || isToUs(&mp)) && (mp.from != 0)) { printPacket("Delivering rx packet", &mp); service->handleFromRadio(&mp); } diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp index d40b593455..dc9c8aa85c 100644 --- a/src/modules/SerialModule.cpp +++ b/src/modules/SerialModule.cpp @@ -125,7 +125,7 @@ int32_t SerialModule::runOnce() if (moduleConfig.serial.override_console_serial_port || (moduleConfig.serial.rxd && moduleConfig.serial.txd)) { if (firstTime) { // Interface with the serial peripheral from in here. - LOG_INFO("Initializing serial peripheral interface\n"); + LOG_INFO("Initializing serial peripheral interface"); uint32_t baud = getBaudRate(); @@ -252,7 +252,12 @@ void SerialModule::sendTelemetry(meshtastic_Telemetry m) pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &meshtastic_Telemetry_msg, &m); p->to = NODENUM_BROADCAST; p->decoded.want_response = false; - p->priority = meshtastic_MeshPacket_Priority_RELIABLE; + if (config.device.role == meshtastic_Config_DeviceConfig_Role_SENSOR) { + p->want_ack = true; + p->priority = meshtastic_MeshPacket_Priority_HIGH; + } else { + p->priority = meshtastic_MeshPacket_Priority_RELIABLE; + } service->sendToMesh(p, RX_SRC_LOCAL, true); } @@ -307,7 +312,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const meshtastic_MeshPacket &mp } auto &p = mp.decoded; - // LOG_DEBUG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s\n", + // LOG_DEBUG("Received text msg self=0x%0x, from=0x%0x, to=0x%0x, id=%d, msg=%.*s", // nodeDB->getNodeNum(), mp.from, mp.to, mp.id, p.payload.size, p.payload.bytes); if (!isFromUs(&mp)) { @@ -322,7 +327,7 @@ ProcessMessage SerialModuleRadio::handleReceived(const meshtastic_MeshPacket &mp // TODO: need to find out why. if (lastRxID != mp.id) { lastRxID = mp.id; - // LOG_DEBUG("* * Message came this device\n"); + // LOG_DEBUG("* * Message came this device"); // serialPrint->println("* * Message came this device"); serialPrint->printf("%s", p.payload.bytes); } @@ -424,8 +429,10 @@ void SerialModule::processWXSerial() static char windGust[5] = "xx.x"; // Assuming windGust is 4 characters long + null terminator static char batVoltage[5] = "0.0V"; static char capVoltage[5] = "0.0V"; + static char temperature[5] = "00.0"; static float batVoltageF = 0; static float capVoltageF = 0; + static float temperatureF = 0; bool gotwind = false; while (Serial2.available()) { @@ -499,6 +506,13 @@ void SerialModule::processWXSerial() strcpy(capVoltage, capVoltagePos + 17); // 18 for ws 80, 17 for ws85 capVoltageF = strtof(capVoltage, nullptr); } + // GXTS04Temp = 24.4 + } else if (strstr(line, "GXTS04Temp") != NULL) { // we have a temperature line + char *tempPos = strstr(line, "GXTS04Temp = "); + if (tempPos != NULL) { + strcpy(temperature, tempPos + 15); // 15 spaces for ws85 + temperatureF = strtof(temperature, nullptr); + } } // Update lineStart for the next line @@ -514,8 +528,8 @@ void SerialModule::processWXSerial() } if (gotwind) { - LOG_INFO("WS85 : %i %.1fg%.1f %.1fv %.1fv\n", atoi(windDir), strtof(windVel, nullptr), strtof(windGust, nullptr), - batVoltageF, capVoltageF); + LOG_INFO("WS85 : %i %.1fg%.1f %.1fv %.1fv %.1fC", atoi(windDir), strtof(windVel, nullptr), strtof(windGust, nullptr), + batVoltageF, capVoltageF, temperatureF); } if (gotwind && !Throttle::isWithinTimespanMs(lastAveraged, averageIntervalMillis)) { // calulate averages and send to the mesh @@ -535,17 +549,32 @@ void SerialModule::processWXSerial() // make a telemetry packet with the data meshtastic_Telemetry m = meshtastic_Telemetry_init_zero; m.which_variant = meshtastic_Telemetry_environment_metrics_tag; + m.variant.environment_metrics.wind_speed = velAvg; + m.variant.environment_metrics.has_wind_speed = true; + m.variant.environment_metrics.wind_direction = dirAvg; - m.variant.environment_metrics.wind_gust = gust; - m.variant.environment_metrics.wind_lull = lull; + m.variant.environment_metrics.has_wind_direction = true; + + m.variant.environment_metrics.temperature = temperatureF; + m.variant.environment_metrics.has_temperature = true; + m.variant.environment_metrics.voltage = capVoltageF > batVoltageF ? capVoltageF : batVoltageF; // send the larger of the two voltage values. + m.variant.environment_metrics.has_voltage = true; + + m.variant.environment_metrics.wind_gust = gust; + m.variant.environment_metrics.has_wind_gust = true; + + if (lull == -1) + lull = 0; + m.variant.environment_metrics.wind_lull = lull; + m.variant.environment_metrics.has_wind_lull = true; - LOG_INFO("WS85 Transmit speed=%fm/s, direction=%d , lull=%f, gust=%f, voltage=%f\n", + LOG_INFO("WS85 Transmit speed=%fm/s, direction=%d , lull=%f, gust=%f, voltage=%f temperature=%f", m.variant.environment_metrics.wind_speed, m.variant.environment_metrics.wind_direction, m.variant.environment_metrics.wind_lull, m.variant.environment_metrics.wind_gust, - m.variant.environment_metrics.voltage); + m.variant.environment_metrics.voltage, m.variant.environment_metrics.temperature); sendTelemetry(m); diff --git a/src/modules/StoreForwardModule.cpp b/src/modules/StoreForwardModule.cpp index e0092839f0..039523207f 100644 --- a/src/modules/StoreForwardModule.cpp +++ b/src/modules/StoreForwardModule.cpp @@ -46,7 +46,7 @@ int32_t StoreForwardModule::runOnce() } else if (this->heartbeat && (!Throttle::isWithinTimespanMs(lastHeartbeat, heartbeatInterval * 1000)) && airTime->isTxAllowedChannelUtil(true)) { lastHeartbeat = millis(); - LOG_INFO("Sending heartbeat\n"); + LOG_INFO("Sending heartbeat"); meshtastic_StoreAndForward sf = meshtastic_StoreAndForward_init_zero; sf.rr = meshtastic_StoreAndForward_RequestResponse_ROUTER_HEARTBEAT; sf.which_variant = meshtastic_StoreAndForward_heartbeat_tag; @@ -70,7 +70,7 @@ void StoreForwardModule::populatePSRAM() https://learn.upesy.com/en/programmation/psram.html#psram-tab */ - LOG_DEBUG("Before PSRAM init: heap %d/%d PSRAM %d/%d\n", memGet.getFreeHeap(), memGet.getHeapSize(), memGet.getFreePsram(), + LOG_DEBUG("Before PSRAM init: heap %d/%d PSRAM %d/%d", memGet.getFreeHeap(), memGet.getHeapSize(), memGet.getFreePsram(), memGet.getPsramSize()); /* Use a maximum of 2/3 the available PSRAM unless otherwise specified. @@ -86,9 +86,9 @@ void StoreForwardModule::populatePSRAM() #endif - LOG_DEBUG("After PSRAM init: heap %d/%d PSRAM %d/%d\n", memGet.getFreeHeap(), memGet.getHeapSize(), memGet.getFreePsram(), + LOG_DEBUG("After PSRAM init: heap %d/%d PSRAM %d/%d", memGet.getFreeHeap(), memGet.getHeapSize(), memGet.getFreePsram(), memGet.getPsramSize()); - LOG_DEBUG("numberOfPackets for packetHistory - %u\n", numberOfPackets); + LOG_DEBUG("numberOfPackets for packetHistory - %u", numberOfPackets); } /** @@ -105,11 +105,11 @@ void StoreForwardModule::historySend(uint32_t secAgo, uint32_t to) queueSize = this->historyReturnMax; if (queueSize) { - LOG_INFO("S&F - Sending %u message(s)\n", queueSize); + LOG_INFO("S&F - Sending %u message(s)", queueSize); this->busy = true; // runOnce() will pickup the next steps once busy = true. this->busyTo = to; } else { - LOG_INFO("S&F - No history\n"); + LOG_INFO("S&F - No history"); } meshtastic_StoreAndForward sf = meshtastic_StoreAndForward_init_zero; sf.rr = meshtastic_StoreAndForward_RequestResponse_ROUTER_HISTORY; @@ -187,7 +187,7 @@ void StoreForwardModule::historyAdd(const meshtastic_MeshPacket &mp) const auto &p = mp.decoded; if (this->packetHistoryTotalCount == this->records) { - LOG_WARN("S&F - PSRAM Full. Starting overwrite.\n"); + LOG_WARN("S&F - PSRAM Full. Starting overwrite."); this->packetHistoryTotalCount = 0; for (auto &i : lastRequest) { i.second = 0; // Clear the last request index for each client device @@ -215,7 +215,7 @@ bool StoreForwardModule::sendPayload(NodeNum dest, uint32_t last_time) { meshtastic_MeshPacket *p = preparePayload(dest, last_time); if (p) { - LOG_INFO("Sending S&F Payload\n"); + LOG_INFO("Sending S&F Payload"); service->sendToMesh(p); this->requestCount++; return true; @@ -335,7 +335,7 @@ void StoreForwardModule::sendErrorTextMessage(NodeNum dest, bool want_response) } else { str = "S&F not permitted on the public channel."; } - LOG_WARN("%s\n", str); + LOG_WARN("%s", str); memcpy(pr->decoded.payload.bytes, str, strlen(str)); pr->decoded.payload.size = strlen(str); if (want_response) { @@ -365,7 +365,7 @@ void StoreForwardModule::statsSend(uint32_t to) sf.variant.stats.return_max = this->historyReturnMax; sf.variant.stats.return_window = this->historyReturnWindow; - LOG_DEBUG("Sending S&F Stats\n"); + LOG_DEBUG("Sending S&F Stats"); storeForwardModule->sendMessage(to, sf); } @@ -383,7 +383,7 @@ ProcessMessage StoreForwardModule::handleReceived(const meshtastic_MeshPacket &m if ((mp.decoded.portnum == meshtastic_PortNum_TEXT_MESSAGE_APP) && is_server) { auto &p = mp.decoded; if (isToUs(&mp) && (p.payload.bytes[0] == 'S') && (p.payload.bytes[1] == 'F') && (p.payload.bytes[2] == 0x00)) { - LOG_DEBUG("Legacy Request to send\n"); + LOG_DEBUG("Legacy Request to send"); // Send the last 60 minutes of messages. if (this->busy || channels.isDefaultChannel(mp.channel)) { @@ -393,7 +393,7 @@ ProcessMessage StoreForwardModule::handleReceived(const meshtastic_MeshPacket &m } } else { storeForwardModule->historyAdd(mp); - LOG_INFO("S&F stored. Message history contains %u records now.\n", this->packetHistoryTotalCount); + LOG_INFO("S&F stored. Message history contains %u records now.", this->packetHistoryTotalCount); } } else if (!isFromUs(&mp) && mp.decoded.portnum == meshtastic_PortNum_STORE_FORWARD_APP) { auto &p = mp.decoded; @@ -403,7 +403,7 @@ ProcessMessage StoreForwardModule::handleReceived(const meshtastic_MeshPacket &m 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"); + LOG_ERROR("Error decoding protobuf module!"); // if we can't decode it, nobody can process it! return ProcessMessage::STOP; } @@ -439,7 +439,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, if (is_server) { // stop sending stuff, the client wants to abort or has another error if ((this->busy) && (this->busyTo == getFrom(&mp))) { - LOG_ERROR("Client in ERROR or ABORT requested\n"); + LOG_ERROR("Client in ERROR or ABORT requested"); this->requestCount = 0; this->busy = false; } @@ -449,7 +449,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, case meshtastic_StoreAndForward_RequestResponse_CLIENT_HISTORY: if (is_server) { requests_history++; - LOG_INFO("Client Request to send HISTORY\n"); + LOG_INFO("Client Request to send HISTORY"); // Send the last 60 minutes of messages. if (this->busy || channels.isDefaultChannel(mp.channel)) { sendErrorTextMessage(getFrom(&mp), mp.decoded.want_response); @@ -479,10 +479,10 @@ bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, case meshtastic_StoreAndForward_RequestResponse_CLIENT_STATS: if (is_server) { - LOG_INFO("Client Request to send STATS\n"); + LOG_INFO("Client Request to send STATS"); if (this->busy) { storeForwardModule->sendMessage(getFrom(&mp), meshtastic_StoreAndForward_RequestResponse_ROUTER_BUSY); - LOG_INFO("S&F - Busy. Try again shortly.\n"); + LOG_INFO("S&F - Busy. Try again shortly."); } else { storeForwardModule->statsSend(getFrom(&mp)); } @@ -492,7 +492,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, case meshtastic_StoreAndForward_RequestResponse_ROUTER_ERROR: case meshtastic_StoreAndForward_RequestResponse_ROUTER_BUSY: if (is_client) { - LOG_DEBUG("StoreAndForward_RequestResponse_ROUTER_BUSY\n"); + LOG_DEBUG("StoreAndForward_RequestResponse_ROUTER_BUSY"); // retry in messages_saved * packetTimeMax ms retry_delay = millis() + getNumAvailablePackets(this->busyTo, this->last_time) * packetTimeMax * (meshtastic_StoreAndForward_RequestResponse_ROUTER_ERROR ? 2 : 1); @@ -508,7 +508,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, heartbeatInterval = p->variant.heartbeat.period; } lastHeartbeat = millis(); - LOG_INFO("StoreAndForward Heartbeat received\n"); + LOG_INFO("StoreAndForward Heartbeat received"); } break; @@ -521,7 +521,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, case meshtastic_StoreAndForward_RequestResponse_ROUTER_STATS: if (is_client) { - LOG_DEBUG("Router Response STATS\n"); + LOG_DEBUG("Router Response STATS"); // These fields only have informational purpose on a client. Fill them to consume later. if (p->which_variant == meshtastic_StoreAndForward_stats_tag) { this->records = p->variant.stats.messages_max; @@ -539,7 +539,7 @@ bool StoreForwardModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, // These fields only have informational purpose on a client. Fill them to consume later. 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", + LOG_INFO("Router Response HISTORY - Sending %d messages from last %d minutes", p->variant.history.history_messages, this->historyReturnWindow); } } @@ -573,7 +573,7 @@ StoreForwardModule::StoreForwardModule() // Router if ((config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER || moduleConfig.store_forward.is_server)) { - LOG_INFO("Initializing Store & Forward Module in Server mode\n"); + LOG_INFO("Initializing Store & Forward Module in Server mode"); if (memGet.getPsramSize() > 0) { if (memGet.getFreePsram() >= 1024 * 1024) { @@ -601,17 +601,17 @@ StoreForwardModule::StoreForwardModule() this->populatePSRAM(); is_server = true; } else { - LOG_INFO(".\n"); - LOG_INFO("S&F: not enough PSRAM free, disabling.\n"); + LOG_INFO("."); + LOG_INFO("S&F: not enough PSRAM free, disabling."); } } else { - LOG_INFO("S&F: device doesn't have PSRAM, disabling.\n"); + LOG_INFO("S&F: device doesn't have PSRAM, disabling."); } // Client } else { is_client = true; - LOG_INFO("Initializing Store & Forward Module in Client mode\n"); + LOG_INFO("Initializing Store & Forward Module in Client mode"); } } else { disable(); diff --git a/src/modules/Telemetry/AirQualityTelemetry.cpp b/src/modules/Telemetry/AirQualityTelemetry.cpp index 0b6be1b7ef..5f7fe5dac5 100644 --- a/src/modules/Telemetry/AirQualityTelemetry.cpp +++ b/src/modules/Telemetry/AirQualityTelemetry.cpp @@ -33,9 +33,10 @@ int32_t AirQualityTelemetryModule::runOnce() firstTime = false; if (moduleConfig.telemetry.air_quality_enabled) { - LOG_INFO("Air quality Telemetry: Initializing\n"); + LOG_INFO("Air quality Telemetry: Initializing"); if (!aqi.begin_I2C()) { - LOG_WARN("Could not establish i2c connection to AQI sensor. Rescanning...\n"); +#ifndef I2C_NO_RESCAN + LOG_WARN("Could not establish i2c connection to AQI sensor. Rescanning..."); // rescan for late arriving sensors. AQI Module starts about 10 seconds into the boot so this is plenty. uint8_t i2caddr_scan[] = {PMSA0031_ADDR}; uint8_t i2caddr_asize = 1; @@ -51,6 +52,7 @@ int32_t AirQualityTelemetryModule::runOnce() i2cScanner->fetchI2CBus(found.address); return 1000; } +#endif return disable(); } return 1000; @@ -84,11 +86,11 @@ bool AirQualityTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPack #ifdef DEBUG_PORT const char *sender = getSenderShortName(mp); - LOG_INFO("(Received from %s): pm10_standard=%i, pm25_standard=%i, pm100_standard=%i\n", sender, + LOG_INFO("(Received from %s): pm10_standard=%i, pm25_standard=%i, pm100_standard=%i", sender, t->variant.air_quality_metrics.pm10_standard, t->variant.air_quality_metrics.pm25_standard, t->variant.air_quality_metrics.pm100_standard); - LOG_INFO(" | PM1.0(Environmental)=%i, PM2.5(Environmental)=%i, PM10.0(Environmental)=%i\n", + LOG_INFO(" | PM1.0(Environmental)=%i, PM2.5(Environmental)=%i, PM10.0(Environmental)=%i", t->variant.air_quality_metrics.pm10_environmental, t->variant.air_quality_metrics.pm25_environmental, t->variant.air_quality_metrics.pm100_environmental); #endif @@ -105,7 +107,7 @@ bool AirQualityTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPack bool AirQualityTelemetryModule::getAirQualityTelemetry(meshtastic_Telemetry *m) { if (!aqi.read(&data)) { - LOG_WARN("Skipping send measurements. Could not read AQIn\n"); + LOG_WARN("Skipping send measurements. Could not read AQIn"); return false; } @@ -119,11 +121,11 @@ bool AirQualityTelemetryModule::getAirQualityTelemetry(meshtastic_Telemetry *m) m->variant.air_quality_metrics.pm25_environmental = data.pm25_env; m->variant.air_quality_metrics.pm100_environmental = data.pm100_env; - LOG_INFO("(Sending): PM1.0(Standard)=%i, PM2.5(Standard)=%i, PM10.0(Standard)=%i\n", + LOG_INFO("(Sending): PM1.0(Standard)=%i, PM2.5(Standard)=%i, PM10.0(Standard)=%i", m->variant.air_quality_metrics.pm10_standard, m->variant.air_quality_metrics.pm25_standard, m->variant.air_quality_metrics.pm100_standard); - LOG_INFO(" | PM1.0(Environmental)=%i, PM2.5(Environmental)=%i, PM10.0(Environmental)=%i\n", + LOG_INFO(" | PM1.0(Environmental)=%i, PM2.5(Environmental)=%i, PM10.0(Environmental)=%i", m->variant.air_quality_metrics.pm10_environmental, m->variant.air_quality_metrics.pm25_environmental, m->variant.air_quality_metrics.pm100_environmental); @@ -141,14 +143,14 @@ meshtastic_MeshPacket *AirQualityTelemetryModule::allocReply() if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Telemetry_msg, &scratch)) { decoded = &scratch; } else { - LOG_ERROR("Error decoding AirQualityTelemetry module!\n"); + LOG_ERROR("Error decoding AirQualityTelemetry module!"); return NULL; } // Check for a request for air quality metrics if (decoded->which_variant == meshtastic_Telemetry_air_quality_metrics_tag) { meshtastic_Telemetry m = meshtastic_Telemetry_init_zero; if (getAirQualityTelemetry(&m)) { - LOG_INFO("Air quality telemetry replying to request\n"); + LOG_INFO("Air quality telemetry replying to request"); return allocDataProtobuf(m); } else { return NULL; @@ -176,10 +178,10 @@ bool AirQualityTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) lastMeasurementPacket = packetPool.allocCopy(*p); if (phoneOnly) { - LOG_INFO("Sending packet to phone\n"); + LOG_INFO("Sending packet to phone"); service->sendToPhone(p); } else { - LOG_INFO("Sending packet to mesh\n"); + LOG_INFO("Sending packet to mesh"); service->sendToMesh(p, RX_SRC_LOCAL, true); } return true; diff --git a/src/modules/Telemetry/DeviceTelemetry.cpp b/src/modules/Telemetry/DeviceTelemetry.cpp index eb3f67e968..45093340e0 100644 --- a/src/modules/Telemetry/DeviceTelemetry.cpp +++ b/src/modules/Telemetry/DeviceTelemetry.cpp @@ -51,7 +51,7 @@ bool DeviceTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPacket & #ifdef DEBUG_PORT const char *sender = getSenderShortName(mp); - LOG_INFO("(Received from %s): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f\n", sender, + LOG_INFO("(Received from %s): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f", sender, t->variant.device_metrics.air_util_tx, t->variant.device_metrics.channel_utilization, t->variant.device_metrics.battery_level, t->variant.device_metrics.voltage); #endif @@ -71,12 +71,12 @@ meshtastic_MeshPacket *DeviceTelemetryModule::allocReply() if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Telemetry_msg, &scratch)) { decoded = &scratch; } else { - LOG_ERROR("Error decoding DeviceTelemetry module!\n"); + LOG_ERROR("Error decoding DeviceTelemetry module!"); return NULL; } // Check for a request for device metrics if (decoded->which_variant == meshtastic_Telemetry_device_metrics_tag) { - LOG_INFO("Device telemetry replying to request\n"); + LOG_INFO("Device telemetry replying to request"); meshtastic_Telemetry telemetry = getDeviceTelemetry(); return allocDataProtobuf(telemetry); @@ -134,13 +134,12 @@ void DeviceTelemetryModule::sendLocalStatsToPhone() telemetry.variant.local_stats.num_tx_relay_canceled = router->txRelayCanceled; } - LOG_INFO( - "(Sending local stats): uptime=%i, channel_utilization=%f, air_util_tx=%f, num_online_nodes=%i, num_total_nodes=%i\n", - telemetry.variant.local_stats.uptime_seconds, telemetry.variant.local_stats.channel_utilization, - telemetry.variant.local_stats.air_util_tx, telemetry.variant.local_stats.num_online_nodes, - telemetry.variant.local_stats.num_total_nodes); + LOG_INFO("(Sending local stats): uptime=%i, channel_utilization=%f, air_util_tx=%f, num_online_nodes=%i, num_total_nodes=%i", + telemetry.variant.local_stats.uptime_seconds, telemetry.variant.local_stats.channel_utilization, + telemetry.variant.local_stats.air_util_tx, telemetry.variant.local_stats.num_online_nodes, + telemetry.variant.local_stats.num_total_nodes); - LOG_INFO("num_packets_tx=%i, num_packets_rx=%i, num_packets_rx_bad=%i\n", telemetry.variant.local_stats.num_packets_tx, + LOG_INFO("num_packets_tx=%i, num_packets_rx=%i, num_packets_rx_bad=%i", telemetry.variant.local_stats.num_packets_tx, telemetry.variant.local_stats.num_packets_rx, telemetry.variant.local_stats.num_packets_rx_bad); meshtastic_MeshPacket *p = allocDataProtobuf(telemetry); @@ -154,7 +153,7 @@ void DeviceTelemetryModule::sendLocalStatsToPhone() bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) { meshtastic_Telemetry telemetry = getDeviceTelemetry(); - LOG_INFO("(Sending): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f, uptime=%i\n", + LOG_INFO("(Sending): air_util_tx=%f, channel_utilization=%f, battery_level=%i, voltage=%f, uptime=%i", telemetry.variant.device_metrics.air_util_tx, telemetry.variant.device_metrics.channel_utilization, telemetry.variant.device_metrics.battery_level, telemetry.variant.device_metrics.voltage, telemetry.variant.device_metrics.uptime_seconds); @@ -166,10 +165,10 @@ bool DeviceTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) nodeDB->updateTelemetry(nodeDB->getNodeNum(), telemetry, RX_SRC_LOCAL); if (phoneOnly) { - LOG_INFO("Sending packet to phone\n"); + LOG_INFO("Sending packet to phone"); service->sendToPhone(p); } else { - LOG_INFO("Sending packet to mesh\n"); + LOG_INFO("Sending packet to mesh"); service->sendToMesh(p, RX_SRC_LOCAL, true); } return true; diff --git a/src/modules/Telemetry/EnvironmentTelemetry.cpp b/src/modules/Telemetry/EnvironmentTelemetry.cpp index 1ccdedeb7f..452c7747b4 100644 --- a/src/modules/Telemetry/EnvironmentTelemetry.cpp +++ b/src/modules/Telemetry/EnvironmentTelemetry.cpp @@ -73,7 +73,7 @@ int32_t EnvironmentTelemetryModule::runOnce() sleepOnNextExecution = false; uint32_t nightyNightMs = Default::getConfiguredOrDefaultMs(moduleConfig.telemetry.environment_update_interval, default_telemetry_broadcast_interval_secs); - LOG_DEBUG("Sleeping for %ims, then awaking to send metrics again.\n", nightyNightMs); + LOG_DEBUG("Sleeping for %ims, then awaking to send metrics again.", nightyNightMs); doDeepSleep(nightyNightMs, true); } @@ -97,7 +97,7 @@ int32_t EnvironmentTelemetryModule::runOnce() firstTime = 0; if (moduleConfig.telemetry.environment_measurement_enabled) { - LOG_INFO("Environment Telemetry: Initializing\n"); + LOG_INFO("Environment Telemetry: Initializing"); // it's possible to have this module enabled, only for displaying values on the screen. // therefore, we should only enable the sensor loop if measurement is also enabled #ifdef T1000X_SENSOR_EN @@ -252,14 +252,14 @@ bool EnvironmentTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPac const char *sender = getSenderShortName(mp); LOG_INFO("(Received from %s): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, " - "temperature=%f\n", + "temperature=%f", sender, t->variant.environment_metrics.barometric_pressure, t->variant.environment_metrics.current, t->variant.environment_metrics.gas_resistance, t->variant.environment_metrics.relative_humidity, t->variant.environment_metrics.temperature); - LOG_INFO("(Received from %s): voltage=%f, IAQ=%d, distance=%f, lux=%f\n", sender, t->variant.environment_metrics.voltage, + LOG_INFO("(Received from %s): voltage=%f, IAQ=%d, distance=%f, lux=%f", sender, t->variant.environment_metrics.voltage, t->variant.environment_metrics.iaq, t->variant.environment_metrics.distance, t->variant.environment_metrics.lux); - LOG_INFO("(Received from %s): wind speed=%fm/s, direction=%d degrees, weight=%fkg\n", sender, + LOG_INFO("(Received from %s): wind speed=%fm/s, direction=%d degrees, weight=%fkg", sender, t->variant.environment_metrics.wind_speed, t->variant.environment_metrics.wind_direction, t->variant.environment_metrics.weight); @@ -373,13 +373,13 @@ bool EnvironmentTelemetryModule::getEnvironmentTelemetry(meshtastic_Telemetry *m } else if (bmp280Sensor.hasSensor()) { // prefer bmp280 temp if both sensors are present, fetch only humidity meshtastic_Telemetry m_ahtx = meshtastic_Telemetry_init_zero; - LOG_INFO("AHTX0+BMP280 module detected: using temp from BMP280 and humy from AHTX0\n"); + LOG_INFO("AHTX0+BMP280 module detected: using temp from BMP280 and humy from AHTX0"); aht10Sensor.getMetrics(&m_ahtx); m->variant.environment_metrics.relative_humidity = m_ahtx.variant.environment_metrics.relative_humidity; } else { // prefer bmp3xx temp if both sensors are present, fetch only humidity meshtastic_Telemetry m_ahtx = meshtastic_Telemetry_init_zero; - LOG_INFO("AHTX0+BMP3XX module detected: using temp from BMP3XX and humy from AHTX0\n"); + LOG_INFO("AHTX0+BMP3XX module detected: using temp from BMP3XX and humy from AHTX0"); aht10Sensor.getMetrics(&m_ahtx); m->variant.environment_metrics.relative_humidity = m_ahtx.variant.environment_metrics.relative_humidity; } @@ -404,14 +404,14 @@ meshtastic_MeshPacket *EnvironmentTelemetryModule::allocReply() if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Telemetry_msg, &scratch)) { decoded = &scratch; } else { - LOG_ERROR("Error decoding EnvironmentTelemetry module!\n"); + LOG_ERROR("Error decoding EnvironmentTelemetry module!"); return NULL; } // Check for a request for environment metrics if (decoded->which_variant == meshtastic_Telemetry_environment_metrics_tag) { meshtastic_Telemetry m = meshtastic_Telemetry_init_zero; if (getEnvironmentTelemetry(&m)) { - LOG_INFO("Environment telemetry replying to request\n"); + LOG_INFO("Environment telemetry replying to request"); return allocDataProtobuf(m); } else { return NULL; @@ -431,14 +431,14 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) #else if (getEnvironmentTelemetry(&m)) { #endif - LOG_INFO("(Sending): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f\n", + LOG_INFO("(Sending): barometric_pressure=%f, current=%f, gas_resistance=%f, relative_humidity=%f, temperature=%f", m.variant.environment_metrics.barometric_pressure, m.variant.environment_metrics.current, m.variant.environment_metrics.gas_resistance, m.variant.environment_metrics.relative_humidity, m.variant.environment_metrics.temperature); - LOG_INFO("(Sending): voltage=%f, IAQ=%d, distance=%f, lux=%f\n", m.variant.environment_metrics.voltage, + LOG_INFO("(Sending): voltage=%f, IAQ=%d, distance=%f, lux=%f", m.variant.environment_metrics.voltage, m.variant.environment_metrics.iaq, m.variant.environment_metrics.distance, m.variant.environment_metrics.lux); - LOG_INFO("(Sending): wind speed=%fm/s, direction=%d degrees, weight=%fkg\n", m.variant.environment_metrics.wind_speed, + LOG_INFO("(Sending): wind speed=%fm/s, direction=%d degrees, weight=%fkg", m.variant.environment_metrics.wind_speed, m.variant.environment_metrics.wind_direction, m.variant.environment_metrics.weight); sensor_read_error_count = 0; @@ -456,14 +456,14 @@ bool EnvironmentTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) lastMeasurementPacket = packetPool.allocCopy(*p); if (phoneOnly) { - LOG_INFO("Sending packet to phone\n"); + LOG_INFO("Sending packet to phone"); service->sendToPhone(p); } else { - LOG_INFO("Sending packet to mesh\n"); + LOG_INFO("Sending packet to mesh"); service->sendToMesh(p, RX_SRC_LOCAL, true); if (config.device.role == meshtastic_Config_DeviceConfig_Role_SENSOR && config.power.is_power_saving) { - LOG_DEBUG("Starting next execution in 5 seconds and then going to sleep.\n"); + LOG_DEBUG("Starting next execution in 5 seconds and then going to sleep."); sleepOnNextExecution = true; setIntervalFromNow(5000); } diff --git a/src/modules/Telemetry/HealthTelemetry.cpp b/src/modules/Telemetry/HealthTelemetry.cpp new file mode 100644 index 0000000000..9b86ae2b81 --- /dev/null +++ b/src/modules/Telemetry/HealthTelemetry.cpp @@ -0,0 +1,249 @@ +#include "configuration.h" + +#if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR && !defined(ARCH_PORTDUINO) + +#include "../mesh/generated/meshtastic/telemetry.pb.h" +#include "Default.h" +#include "HealthTelemetry.h" +#include "MeshService.h" +#include "NodeDB.h" +#include "PowerFSM.h" +#include "RTC.h" +#include "Router.h" +#include "UnitConversions.h" +#include "main.h" +#include "power.h" +#include "sleep.h" +#include "target_specific.h" +#include +#include + +// Sensors +#include "Sensor/MAX30102Sensor.h" +#include "Sensor/MLX90614Sensor.h" + +MAX30102Sensor max30102Sensor; +MLX90614Sensor mlx90614Sensor; + +#define FAILED_STATE_SENSOR_READ_MULTIPLIER 10 +#define DISPLAY_RECEIVEID_MEASUREMENTS_ON_SCREEN true + +#if (HAS_SCREEN) +#include "graphics/ScreenFonts.h" +#endif +#include + +int32_t HealthTelemetryModule::runOnce() +{ + if (sleepOnNextExecution == true) { + sleepOnNextExecution = false; + uint32_t nightyNightMs = Default::getConfiguredOrDefaultMs(moduleConfig.telemetry.health_update_interval, + default_telemetry_broadcast_interval_secs); + LOG_DEBUG("Sleeping for %ims, then awaking to send metrics again.", nightyNightMs); + doDeepSleep(nightyNightMs, true); + } + + uint32_t result = UINT32_MAX; + + if (!(moduleConfig.telemetry.health_measurement_enabled || moduleConfig.telemetry.health_screen_enabled)) { + // If this module is not enabled, and the user doesn't want the display screen don't waste any OSThread time on it + return disable(); + } + + if (firstTime) { + // This is the first time the OSThread library has called this function, so do some setup + firstTime = false; + + if (moduleConfig.telemetry.health_measurement_enabled) { + LOG_INFO("Health Telemetry: Initializing"); + // Initialize sensors + if (mlx90614Sensor.hasSensor()) + result = mlx90614Sensor.runOnce(); + if (max30102Sensor.hasSensor()) + result = max30102Sensor.runOnce(); + } + return result; + } else { + // if we somehow got to a second run of this module with measurement disabled, then just wait forever + if (!moduleConfig.telemetry.health_measurement_enabled) { + return disable(); + } + + if (((lastSentToMesh == 0) || + !Throttle::isWithinTimespanMs(lastSentToMesh, Default::getConfiguredOrDefaultMsScaled( + moduleConfig.telemetry.health_update_interval, + default_telemetry_broadcast_interval_secs, numOnlineNodes))) && + airTime->isTxAllowedChannelUtil(config.device.role != meshtastic_Config_DeviceConfig_Role_SENSOR) && + airTime->isTxAllowedAirUtil()) { + sendTelemetry(); + lastSentToMesh = millis(); + } else if (((lastSentToPhone == 0) || !Throttle::isWithinTimespanMs(lastSentToPhone, sendToPhoneIntervalMs)) && + (service->isToPhoneQueueEmpty())) { + // Just send to phone when it's not our time to send to mesh yet + // Only send while queue is empty (phone assumed connected) + sendTelemetry(NODENUM_BROADCAST, true); + lastSentToPhone = millis(); + } + } + return min(sendToPhoneIntervalMs, result); +} + +bool HealthTelemetryModule::wantUIFrame() +{ + return moduleConfig.telemetry.health_screen_enabled; +} + +void HealthTelemetryModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) +{ + display->setTextAlignment(TEXT_ALIGN_LEFT); + display->setFont(FONT_SMALL); + + if (lastMeasurementPacket == nullptr) { + // If there's no valid packet, display "Health" + display->drawString(x, y, "Health"); + display->drawString(x, y += _fontHeight(FONT_SMALL), "No measurement"); + return; + } + + // Decode the last measurement packet + meshtastic_Telemetry lastMeasurement; + uint32_t agoSecs = service->GetTimeSinceMeshPacket(lastMeasurementPacket); + const char *lastSender = getSenderShortName(*lastMeasurementPacket); + + const meshtastic_Data &p = lastMeasurementPacket->decoded; + if (!pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Telemetry_msg, &lastMeasurement)) { + display->drawString(x, y, "Measurement Error"); + LOG_ERROR("Unable to decode last packet"); + return; + } + + // Display "Health From: ..." on its own + display->drawString(x, y, "Health From: " + String(lastSender) + "(" + String(agoSecs) + "s)"); + + String last_temp = String(lastMeasurement.variant.health_metrics.temperature, 0) + "°C"; + if (moduleConfig.telemetry.environment_display_fahrenheit) { + last_temp = String(UnitConversions::CelsiusToFahrenheit(lastMeasurement.variant.health_metrics.temperature), 0) + "°F"; + } + + // Continue with the remaining details + display->drawString(x, y += _fontHeight(FONT_SMALL), "Temp: " + last_temp); + if (lastMeasurement.variant.health_metrics.has_heart_bpm) { + display->drawString(x, y += _fontHeight(FONT_SMALL), + "Heart Rate: " + String(lastMeasurement.variant.health_metrics.heart_bpm, 0) + " bpm"); + } + if (lastMeasurement.variant.health_metrics.has_spO2) { + display->drawString(x, y += _fontHeight(FONT_SMALL), + "spO2: " + String(lastMeasurement.variant.health_metrics.spO2, 0) + " %"); + } +} + +bool HealthTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Telemetry *t) +{ + if (t->which_variant == meshtastic_Telemetry_health_metrics_tag) { +#ifdef DEBUG_PORT + const char *sender = getSenderShortName(mp); + + LOG_INFO("(Received from %s): temperature=%f, heart_bpm=%d, spO2=%d,", sender, t->variant.health_metrics.temperature, + t->variant.health_metrics.heart_bpm, t->variant.health_metrics.spO2); + +#endif + // release previous packet before occupying a new spot + if (lastMeasurementPacket != nullptr) + packetPool.release(lastMeasurementPacket); + + lastMeasurementPacket = packetPool.allocCopy(mp); + } + + return false; // Let others look at this message also if they want +} + +bool HealthTelemetryModule::getHealthTelemetry(meshtastic_Telemetry *m) +{ + bool valid = true; + bool hasSensor = false; + m->time = getTime(); + m->which_variant = meshtastic_Telemetry_health_metrics_tag; + m->variant.health_metrics = meshtastic_HealthMetrics_init_zero; + + if (max30102Sensor.hasSensor()) { + valid = valid && max30102Sensor.getMetrics(m); + hasSensor = true; + } + if (mlx90614Sensor.hasSensor()) { + valid = valid && mlx90614Sensor.getMetrics(m); + hasSensor = true; + } + + return valid && hasSensor; +} + +meshtastic_MeshPacket *HealthTelemetryModule::allocReply() +{ + if (currentRequest) { + auto req = *currentRequest; + const auto &p = req.decoded; + meshtastic_Telemetry scratch; + meshtastic_Telemetry *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Telemetry_msg, &scratch)) { + decoded = &scratch; + } else { + LOG_ERROR("Error decoding HealthTelemetry module!"); + return NULL; + } + // Check for a request for health metrics + if (decoded->which_variant == meshtastic_Telemetry_health_metrics_tag) { + meshtastic_Telemetry m = meshtastic_Telemetry_init_zero; + if (getHealthTelemetry(&m)) { + LOG_INFO("Health telemetry replying to request"); + return allocDataProtobuf(m); + } else { + return NULL; + } + } + } + return NULL; +} + +bool HealthTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) +{ + meshtastic_Telemetry m = meshtastic_Telemetry_init_zero; + m.which_variant = meshtastic_Telemetry_health_metrics_tag; + m.time = getTime(); + if (getHealthTelemetry(&m)) { + LOG_INFO("(Sending): temperature=%f, heart_bpm=%d, spO2=%d", m.variant.health_metrics.temperature, + m.variant.health_metrics.heart_bpm, m.variant.health_metrics.spO2); + + sensor_read_error_count = 0; + + meshtastic_MeshPacket *p = allocDataProtobuf(m); + p->to = dest; + p->decoded.want_response = false; + if (config.device.role == meshtastic_Config_DeviceConfig_Role_SENSOR) + p->priority = meshtastic_MeshPacket_Priority_RELIABLE; + else + p->priority = meshtastic_MeshPacket_Priority_BACKGROUND; + // release previous packet before occupying a new spot + if (lastMeasurementPacket != nullptr) + packetPool.release(lastMeasurementPacket); + + lastMeasurementPacket = packetPool.allocCopy(*p); + if (phoneOnly) { + LOG_INFO("Sending packet to phone"); + service->sendToPhone(p); + } else { + LOG_INFO("Sending packet to mesh"); + service->sendToMesh(p, RX_SRC_LOCAL, true); + + if (config.device.role == meshtastic_Config_DeviceConfig_Role_SENSOR && config.power.is_power_saving) { + LOG_DEBUG("Starting next execution in 5 seconds and then going to sleep."); + sleepOnNextExecution = true; + setIntervalFromNow(5000); + } + } + return true; + } + return false; +} + +#endif diff --git a/src/modules/Telemetry/HealthTelemetry.h b/src/modules/Telemetry/HealthTelemetry.h new file mode 100644 index 0000000000..4ad0da8388 --- /dev/null +++ b/src/modules/Telemetry/HealthTelemetry.h @@ -0,0 +1,60 @@ +#include "configuration.h" + +#if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR && !defined(ARCH_PORTDUINO) + +#pragma once +#include "../mesh/generated/meshtastic/telemetry.pb.h" +#include "NodeDB.h" +#include "ProtobufModule.h" +#include +#include + +class HealthTelemetryModule : private concurrency::OSThread, public ProtobufModule +{ + CallbackObserver nodeStatusObserver = + CallbackObserver(this, &HealthTelemetryModule::handleStatusUpdate); + + public: + HealthTelemetryModule() + : concurrency::OSThread("HealthTelemetryModule"), + ProtobufModule("HealthTelemetry", meshtastic_PortNum_TELEMETRY_APP, &meshtastic_Telemetry_msg) + { + lastMeasurementPacket = nullptr; + nodeStatusObserver.observe(&nodeStatus->onNewStatus); + setIntervalFromNow(10 * 1000); + } + +#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; +#endif + + virtual bool wantUIFrame() override; + + 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 meshtastic_MeshPacket &mp, meshtastic_Telemetry *p) override; + virtual int32_t runOnce() override; + /** Called to get current Health telemetry data + @return true if it contains valid data + */ + bool getHealthTelemetry(meshtastic_Telemetry *m); + virtual meshtastic_MeshPacket *allocReply() override; + /** + * Send our Telemetry into the mesh + */ + bool sendTelemetry(NodeNum dest = NODENUM_BROADCAST, bool wantReplies = false); + + private: + bool firstTime = 1; + meshtastic_MeshPacket *lastMeasurementPacket; + uint32_t sendToPhoneIntervalMs = SECONDS_IN_MINUTE * 1000; // Send to phone every minute + uint32_t lastSentToMesh = 0; + uint32_t lastSentToPhone = 0; + uint32_t sensor_read_error_count = 0; +}; + +#endif diff --git a/src/modules/Telemetry/PowerTelemetry.cpp b/src/modules/Telemetry/PowerTelemetry.cpp index be30489983..c5f19b295b 100644 --- a/src/modules/Telemetry/PowerTelemetry.cpp +++ b/src/modules/Telemetry/PowerTelemetry.cpp @@ -27,7 +27,7 @@ int32_t PowerTelemetryModule::runOnce() sleepOnNextExecution = false; uint32_t nightyNightMs = Default::getConfiguredOrDefaultMs(moduleConfig.telemetry.power_update_interval, default_telemetry_broadcast_interval_secs); - LOG_DEBUG("Sleeping for %ims, then awaking to send metrics again.\n", nightyNightMs); + LOG_DEBUG("Sleeping for %ims, then awaking to send metrics again.", nightyNightMs); doDeepSleep(nightyNightMs, true); } @@ -51,7 +51,7 @@ int32_t PowerTelemetryModule::runOnce() firstTime = 0; #if HAS_TELEMETRY && !defined(ARCH_PORTDUINO) if (moduleConfig.telemetry.power_measurement_enabled) { - LOG_INFO("Power Telemetry: Initializing\n"); + LOG_INFO("Power Telemetry: Initializing"); // it's possible to have this module enabled, only for displaying values on the screen. // therefore, we should only enable the sensor loop if measurement is also enabled if (ina219Sensor.hasSensor() && !ina219Sensor.isInitialized()) @@ -145,7 +145,7 @@ bool PowerTelemetryModule::handleReceivedProtobuf(const meshtastic_MeshPacket &m const char *sender = getSenderShortName(mp); LOG_INFO("(Received from %s): ch1_voltage=%.1f, ch1_current=%.1f, ch2_voltage=%.1f, ch2_current=%.1f, " - "ch3_voltage=%.1f, ch3_current=%.1f\n", + "ch3_voltage=%.1f, ch3_current=%.1f", sender, t->variant.power_metrics.ch1_voltage, t->variant.power_metrics.ch1_current, t->variant.power_metrics.ch2_voltage, t->variant.power_metrics.ch2_current, t->variant.power_metrics.ch3_voltage, t->variant.power_metrics.ch3_current); @@ -192,14 +192,14 @@ meshtastic_MeshPacket *PowerTelemetryModule::allocReply() if (pb_decode_from_bytes(p.payload.bytes, p.payload.size, &meshtastic_Telemetry_msg, &scratch)) { decoded = &scratch; } else { - LOG_ERROR("Error decoding PowerTelemetry module!\n"); + LOG_ERROR("Error decoding PowerTelemetry module!"); return NULL; } // Check for a request for power metrics if (decoded->which_variant == meshtastic_Telemetry_power_metrics_tag) { meshtastic_Telemetry m = meshtastic_Telemetry_init_zero; if (getPowerTelemetry(&m)) { - LOG_INFO("Power telemetry replying to request\n"); + LOG_INFO("Power telemetry replying to request"); return allocDataProtobuf(m); } else { return NULL; @@ -217,7 +217,7 @@ bool PowerTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) m.time = getTime(); if (getPowerTelemetry(&m)) { LOG_INFO("(Sending): ch1_voltage=%f, ch1_current=%f, ch2_voltage=%f, ch2_current=%f, " - "ch3_voltage=%f, ch3_current=%f\n", + "ch3_voltage=%f, ch3_current=%f", m.variant.power_metrics.ch1_voltage, m.variant.power_metrics.ch1_current, m.variant.power_metrics.ch2_voltage, m.variant.power_metrics.ch2_current, m.variant.power_metrics.ch3_voltage, m.variant.power_metrics.ch3_current); @@ -236,14 +236,14 @@ bool PowerTelemetryModule::sendTelemetry(NodeNum dest, bool phoneOnly) lastMeasurementPacket = packetPool.allocCopy(*p); if (phoneOnly) { - LOG_INFO("Sending packet to phone\n"); + LOG_INFO("Sending packet to phone"); service->sendToPhone(p); } else { - LOG_INFO("Sending packet to mesh\n"); + LOG_INFO("Sending packet to mesh"); service->sendToMesh(p, RX_SRC_LOCAL, true); if (config.device.role == meshtastic_Config_DeviceConfig_Role_SENSOR && config.power.is_power_saving) { - LOG_DEBUG("Starting next execution in 5s then going to sleep.\n"); + LOG_DEBUG("Starting next execution in 5s then going to sleep."); sleepOnNextExecution = true; setIntervalFromNow(5000); } diff --git a/src/modules/Telemetry/Sensor/AHT10.cpp b/src/modules/Telemetry/Sensor/AHT10.cpp index f9e8ba18af..039b7da410 100644 --- a/src/modules/Telemetry/Sensor/AHT10.cpp +++ b/src/modules/Telemetry/Sensor/AHT10.cpp @@ -13,7 +13,7 @@ AHT10Sensor::AHT10Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_AHT1 int32_t AHT10Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -27,7 +27,7 @@ void AHT10Sensor::setup() {} bool AHT10Sensor::getMetrics(meshtastic_Telemetry *measurement) { - LOG_DEBUG("AHT10Sensor::getMetrics\n"); + LOG_DEBUG("AHT10Sensor::getMetrics"); sensors_event_t humidity, temp; aht10.getEvent(&humidity, &temp); diff --git a/src/modules/Telemetry/Sensor/BME280Sensor.cpp b/src/modules/Telemetry/Sensor/BME280Sensor.cpp index 55bc167441..9f5cf6155e 100644 --- a/src/modules/Telemetry/Sensor/BME280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME280Sensor.cpp @@ -12,7 +12,7 @@ BME280Sensor::BME280Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_BM int32_t BME280Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -35,7 +35,7 @@ bool BME280Sensor::getMetrics(meshtastic_Telemetry *measurement) measurement->variant.environment_metrics.has_relative_humidity = true; measurement->variant.environment_metrics.has_barometric_pressure = true; - LOG_DEBUG("BME280Sensor::getMetrics\n"); + LOG_DEBUG("BME280Sensor::getMetrics"); bme280.takeForcedMeasurement(); measurement->variant.environment_metrics.temperature = bme280.readTemperature(); measurement->variant.environment_metrics.relative_humidity = bme280.readHumidity(); diff --git a/src/modules/Telemetry/Sensor/BME680Sensor.cpp b/src/modules/Telemetry/Sensor/BME680Sensor.cpp index 328ec827d2..21c74c52f6 100644 --- a/src/modules/Telemetry/Sensor/BME680Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BME680Sensor.cpp @@ -37,13 +37,13 @@ int32_t BME680Sensor::runOnce() checkStatus("updateSubscription"); status = 0; } - LOG_INFO("Init sensor: %s with the BSEC Library version %d.%d.%d.%d \n", sensorName, bme680.version.major, + LOG_INFO("Init sensor: %s with the BSEC Library version %d.%d.%d.%d ", sensorName, bme680.version.major, bme680.version.minor, bme680.version.major_bugfix, bme680.version.minor_bugfix); } else { status = 0; } if (status == 0) - LOG_DEBUG("BME680Sensor::runOnce: bme680.status %d\n", bme680.status); + LOG_DEBUG("BME680Sensor::runOnce: bme680.status %d", bme680.status); return initI2CSensor(); } @@ -80,12 +80,12 @@ void BME680Sensor::loadState() file.read((uint8_t *)&bsecState, BSEC_MAX_STATE_BLOB_SIZE); file.close(); bme680.setState(bsecState); - LOG_INFO("%s state read from %s.\n", sensorName, bsecConfigFileName); + LOG_INFO("%s state read from %s.", sensorName, bsecConfigFileName); } else { - LOG_INFO("No %s state found (File: %s).\n", sensorName, bsecConfigFileName); + LOG_INFO("No %s state found (File: %s).", sensorName, bsecConfigFileName); } #else - LOG_ERROR("ERROR: Filesystem not implemented\n"); + LOG_ERROR("ERROR: Filesystem not implemented"); #endif } @@ -97,16 +97,16 @@ void BME680Sensor::updateState() /* First state update when IAQ accuracy is >= 3 */ accuracy = bme680.getData(BSEC_OUTPUT_IAQ).accuracy; if (accuracy >= 2) { - LOG_DEBUG("%s state update IAQ accuracy %u >= 2\n", sensorName, accuracy); + LOG_DEBUG("%s state update IAQ accuracy %u >= 2", sensorName, accuracy); update = true; stateUpdateCounter++; } else { - LOG_DEBUG("%s not updated, IAQ accuracy is %u < 2\n", sensorName, accuracy); + LOG_DEBUG("%s not updated, IAQ accuracy is %u < 2", sensorName, accuracy); } } else { /* Update every STATE_SAVE_PERIOD minutes */ if ((stateUpdateCounter * STATE_SAVE_PERIOD) < millis()) { - LOG_DEBUG("%s state update every %d minutes\n", sensorName, STATE_SAVE_PERIOD / 60000); + LOG_DEBUG("%s state update every %d minutes", sensorName, STATE_SAVE_PERIOD / 60000); update = true; stateUpdateCounter++; } @@ -115,34 +115,34 @@ void BME680Sensor::updateState() if (update) { bme680.getState(bsecState); if (FSCom.exists(bsecConfigFileName) && !FSCom.remove(bsecConfigFileName)) { - LOG_WARN("Can't remove old state file\n"); + LOG_WARN("Can't remove old state file"); } auto file = FSCom.open(bsecConfigFileName, FILE_O_WRITE); if (file) { - LOG_INFO("%s state write to %s.\n", sensorName, bsecConfigFileName); + LOG_INFO("%s state write to %s.", sensorName, bsecConfigFileName); file.write((uint8_t *)&bsecState, BSEC_MAX_STATE_BLOB_SIZE); file.flush(); file.close(); } else { - LOG_INFO("Can't write %s state (File: %s).\n", sensorName, bsecConfigFileName); + LOG_INFO("Can't write %s state (File: %s).", sensorName, bsecConfigFileName); } } #else - LOG_ERROR("ERROR: Filesystem not implemented\n"); + LOG_ERROR("ERROR: Filesystem not implemented"); #endif } void BME680Sensor::checkStatus(String functionName) { if (bme680.status < BSEC_OK) - LOG_ERROR("%s BSEC2 code: %s\n", functionName.c_str(), String(bme680.status).c_str()); + LOG_ERROR("%s BSEC2 code: %s", functionName.c_str(), String(bme680.status).c_str()); else if (bme680.status > BSEC_OK) - LOG_WARN("%s BSEC2 code: %s\n", functionName.c_str(), String(bme680.status).c_str()); + LOG_WARN("%s BSEC2 code: %s", functionName.c_str(), String(bme680.status).c_str()); if (bme680.sensor.status < BME68X_OK) - LOG_ERROR("%s BME68X code: %s\n", functionName.c_str(), String(bme680.sensor.status).c_str()); + LOG_ERROR("%s BME68X code: %s", functionName.c_str(), String(bme680.sensor.status).c_str()); else if (bme680.sensor.status > BME68X_OK) - LOG_WARN("%s BME68X code: %s\n", functionName.c_str(), String(bme680.sensor.status).c_str()); + LOG_WARN("%s BME68X code: %s", functionName.c_str(), String(bme680.sensor.status).c_str()); } #endif \ No newline at end of file diff --git a/src/modules/Telemetry/Sensor/BMP085Sensor.cpp b/src/modules/Telemetry/Sensor/BMP085Sensor.cpp index 15951126fa..40ff996f22 100644 --- a/src/modules/Telemetry/Sensor/BMP085Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BMP085Sensor.cpp @@ -12,7 +12,7 @@ BMP085Sensor::BMP085Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_BM int32_t BMP085Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -29,7 +29,7 @@ bool BMP085Sensor::getMetrics(meshtastic_Telemetry *measurement) measurement->variant.environment_metrics.has_temperature = true; measurement->variant.environment_metrics.has_barometric_pressure = true; - LOG_DEBUG("BMP085Sensor::getMetrics\n"); + LOG_DEBUG("BMP085Sensor::getMetrics"); measurement->variant.environment_metrics.temperature = bmp085.readTemperature(); measurement->variant.environment_metrics.barometric_pressure = bmp085.readPressure() / 100.0F; diff --git a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp index 6b0743d757..185e9b8ecf 100644 --- a/src/modules/Telemetry/Sensor/BMP280Sensor.cpp +++ b/src/modules/Telemetry/Sensor/BMP280Sensor.cpp @@ -12,7 +12,7 @@ BMP280Sensor::BMP280Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_BM int32_t BMP280Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -34,7 +34,7 @@ bool BMP280Sensor::getMetrics(meshtastic_Telemetry *measurement) measurement->variant.environment_metrics.has_temperature = true; measurement->variant.environment_metrics.has_barometric_pressure = true; - LOG_DEBUG("BMP280Sensor::getMetrics\n"); + LOG_DEBUG("BMP280Sensor::getMetrics"); bmp280.takeForcedMeasurement(); measurement->variant.environment_metrics.temperature = bmp280.readTemperature(); measurement->variant.environment_metrics.barometric_pressure = bmp280.readPressure() / 100.0F; diff --git a/src/modules/Telemetry/Sensor/BMP3XXSensor.cpp b/src/modules/Telemetry/Sensor/BMP3XXSensor.cpp index 3996106139..4362396b10 100644 --- a/src/modules/Telemetry/Sensor/BMP3XXSensor.cpp +++ b/src/modules/Telemetry/Sensor/BMP3XXSensor.cpp @@ -10,7 +10,7 @@ void BMP3XXSensor::setup() {} int32_t BMP3XXSensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -50,11 +50,11 @@ bool BMP3XXSensor::getMetrics(meshtastic_Telemetry *measurement) measurement->variant.environment_metrics.barometric_pressure = static_cast(bmp3xx->pressure) / 100.0F; measurement->variant.environment_metrics.relative_humidity = 0.0f; - LOG_DEBUG("BMP3XXSensor::getMetrics id: %i temp: %.1f press %.1f\n", measurement->which_variant, + LOG_DEBUG("BMP3XXSensor::getMetrics id: %i temp: %.1f press %.1f", measurement->which_variant, measurement->variant.environment_metrics.temperature, measurement->variant.environment_metrics.barometric_pressure); } else { - LOG_DEBUG("BMP3XXSensor::getMetrics id: %i\n", measurement->which_variant); + LOG_DEBUG("BMP3XXSensor::getMetrics id: %i", measurement->which_variant); } return true; } diff --git a/src/modules/Telemetry/Sensor/DFRobotLarkSensor.cpp b/src/modules/Telemetry/Sensor/DFRobotLarkSensor.cpp index 4b01eb4442..1d143b03b5 100644 --- a/src/modules/Telemetry/Sensor/DFRobotLarkSensor.cpp +++ b/src/modules/Telemetry/Sensor/DFRobotLarkSensor.cpp @@ -13,7 +13,7 @@ DFRobotLarkSensor::DFRobotLarkSensor() : TelemetrySensor(meshtastic_TelemetrySen int32_t DFRobotLarkSensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -22,10 +22,10 @@ int32_t DFRobotLarkSensor::runOnce() if (lark.begin() == 0) // DFRobotLarkSensor init { - LOG_DEBUG("DFRobotLarkSensor Init Succeed\n"); + LOG_DEBUG("DFRobotLarkSensor Init Succeed"); status = true; } else { - LOG_ERROR("DFRobotLarkSensor Init Failed\n"); + LOG_ERROR("DFRobotLarkSensor Init Failed"); status = false; } return initI2CSensor(); @@ -47,11 +47,11 @@ bool DFRobotLarkSensor::getMetrics(meshtastic_Telemetry *measurement) measurement->variant.environment_metrics.wind_direction = GeoCoord::bearingToDegrees(lark.getValue("Dir").c_str()); measurement->variant.environment_metrics.barometric_pressure = lark.getValue("Pressure").toFloat(); - LOG_INFO("Temperature: %f\n", measurement->variant.environment_metrics.temperature); - LOG_INFO("Humidity: %f\n", measurement->variant.environment_metrics.relative_humidity); - LOG_INFO("Wind Speed: %f\n", measurement->variant.environment_metrics.wind_speed); - LOG_INFO("Wind Direction: %d\n", measurement->variant.environment_metrics.wind_direction); - LOG_INFO("Barometric Pressure: %f\n", measurement->variant.environment_metrics.barometric_pressure); + LOG_INFO("Temperature: %f", measurement->variant.environment_metrics.temperature); + LOG_INFO("Humidity: %f", measurement->variant.environment_metrics.relative_humidity); + LOG_INFO("Wind Speed: %f", measurement->variant.environment_metrics.wind_speed); + LOG_INFO("Wind Direction: %d", measurement->variant.environment_metrics.wind_direction); + LOG_INFO("Barometric Pressure: %f", measurement->variant.environment_metrics.barometric_pressure); return true; } diff --git a/src/modules/Telemetry/Sensor/INA219Sensor.cpp b/src/modules/Telemetry/Sensor/INA219Sensor.cpp index f70d3705ed..de69163b4c 100644 --- a/src/modules/Telemetry/Sensor/INA219Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA219Sensor.cpp @@ -15,7 +15,7 @@ INA219Sensor::INA219Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_IN int32_t INA219Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/INA260Sensor.cpp b/src/modules/Telemetry/Sensor/INA260Sensor.cpp index 751608c823..24182b3360 100644 --- a/src/modules/Telemetry/Sensor/INA260Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA260Sensor.cpp @@ -11,7 +11,7 @@ INA260Sensor::INA260Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_IN int32_t INA260Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/INA3221Sensor.cpp b/src/modules/Telemetry/Sensor/INA3221Sensor.cpp index 549346d729..ed09856e23 100644 --- a/src/modules/Telemetry/Sensor/INA3221Sensor.cpp +++ b/src/modules/Telemetry/Sensor/INA3221Sensor.cpp @@ -11,7 +11,7 @@ INA3221Sensor::INA3221Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_ int32_t INA3221Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp index 111d86d1a6..170fafd39e 100644 --- a/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp +++ b/src/modules/Telemetry/Sensor/LPS22HBSensor.cpp @@ -12,7 +12,7 @@ LPS22HBSensor::LPS22HBSensor() : TelemetrySensor(meshtastic_TelemetrySensorType_ int32_t LPS22HBSensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/MAX17048Sensor.cpp b/src/modules/Telemetry/Sensor/MAX17048Sensor.cpp index 96dd5ae80e..02ab9df018 100644 --- a/src/modules/Telemetry/Sensor/MAX17048Sensor.cpp +++ b/src/modules/Telemetry/Sensor/MAX17048Sensor.cpp @@ -19,7 +19,7 @@ MAX17048Singleton *MAX17048Singleton::pinstance{nullptr}; bool MAX17048Singleton::runOnce(TwoWire *theWire) { initialized = begin(theWire); - LOG_DEBUG("%s::runOnce %s\n", sensorStr, initialized ? "began ok" : "begin failed"); + LOG_DEBUG("%s::runOnce %s", sensorStr, initialized ? "began ok" : "begin failed"); return initialized; } @@ -27,7 +27,7 @@ bool MAX17048Singleton::isBatteryCharging() { float volts = cellVoltage(); if (isnan(volts)) { - LOG_DEBUG("%s::isBatteryCharging is not connected\n", sensorStr); + LOG_DEBUG("%s::isBatteryCharging is not connected", sensorStr); return 0; } @@ -53,7 +53,7 @@ bool MAX17048Singleton::isBatteryCharging() chargeState = MAX17048ChargeState::IDLE; } - LOG_DEBUG("%s::isBatteryCharging %s volts: %.3f soc: %.3f rate: %.3f\n", sensorStr, chargeLabels[chargeState], volts, + LOG_DEBUG("%s::isBatteryCharging %s volts: %.3f soc: %.3f rate: %.3f", sensorStr, chargeLabels[chargeState], volts, sample.cellPercent, sample.chargeRate); return chargeState == MAX17048ChargeState::IMPORT; } @@ -62,17 +62,17 @@ uint16_t MAX17048Singleton::getBusVoltageMv() { float volts = cellVoltage(); if (isnan(volts)) { - LOG_DEBUG("%s::getBusVoltageMv is not connected\n", sensorStr); + LOG_DEBUG("%s::getBusVoltageMv is not connected", sensorStr); return 0; } - LOG_DEBUG("%s::getBusVoltageMv %.3fmV\n", sensorStr, volts); + LOG_DEBUG("%s::getBusVoltageMv %.3fmV", sensorStr, volts); return (uint16_t)(volts * 1000.0f); } uint8_t MAX17048Singleton::getBusBatteryPercent() { float soc = cellPercent(); - LOG_DEBUG("%s::getBusBatteryPercent %.1f%%\n", sensorStr, soc); + LOG_DEBUG("%s::getBusBatteryPercent %.1f%%", sensorStr, soc); return clamp(static_cast(round(soc)), static_cast(0), static_cast(100)); } @@ -82,7 +82,7 @@ uint16_t MAX17048Singleton::getTimeToGoSecs() float soc = cellPercent(); // state of charge in percent 0 to 100 soc = clamp(soc, 0.0f, 100.0f); // clamp soc between 0 and 100% float ttg = ((100.0f - soc) / rate) * 3600.0f; // calculate seconds to charge/discharge - LOG_DEBUG("%s::getTimeToGoSecs %.0f seconds\n", sensorStr, ttg); + LOG_DEBUG("%s::getTimeToGoSecs %.0f seconds", sensorStr, ttg); return (uint16_t)ttg; } @@ -90,7 +90,7 @@ bool MAX17048Singleton::isBatteryConnected() { float volts = cellVoltage(); if (isnan(volts)) { - LOG_DEBUG("%s::isBatteryConnected is not connected\n", sensorStr); + LOG_DEBUG("%s::isBatteryConnected is not connected", sensorStr); return false; } @@ -103,12 +103,12 @@ bool MAX17048Singleton::isExternallyPowered() float volts = cellVoltage(); if (isnan(volts)) { // if the battery is not connected then there must be external power - LOG_DEBUG("%s::isExternallyPowered battery is\n", sensorStr); + LOG_DEBUG("%s::isExternallyPowered battery is", sensorStr); return true; } // if the bus voltage is over MAX17048_BUS_POWER_VOLTS, then the external power // is assumed to be connected - LOG_DEBUG("%s::isExternallyPowered %s connected\n", sensorStr, volts >= MAX17048_BUS_POWER_VOLTS ? "is" : "is not"); + LOG_DEBUG("%s::isExternallyPowered %s connected", sensorStr, volts >= MAX17048_BUS_POWER_VOLTS ? "is" : "is not"); return volts >= MAX17048_BUS_POWER_VOLTS; } @@ -119,11 +119,11 @@ MAX17048Sensor::MAX17048Sensor() : TelemetrySensor(meshtastic_TelemetrySensorTyp int32_t MAX17048Sensor::runOnce() { if (isInitialized()) { - LOG_INFO("Init sensor: %s is already initialised\n", sensorName); + LOG_INFO("Init sensor: %s is already initialised", sensorName); return true; } - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -140,11 +140,11 @@ void MAX17048Sensor::setup() {} bool MAX17048Sensor::getMetrics(meshtastic_Telemetry *measurement) { - LOG_DEBUG("MAX17048Sensor::getMetrics id: %i\n", measurement->which_variant); + LOG_DEBUG("MAX17048Sensor::getMetrics id: %i", measurement->which_variant); float volts = max17048->cellVoltage(); if (isnan(volts)) { - LOG_DEBUG("MAX17048Sensor::getMetrics battery is not connected\n"); + LOG_DEBUG("MAX17048Sensor::getMetrics battery is not connected"); return false; } @@ -153,7 +153,7 @@ bool MAX17048Sensor::getMetrics(meshtastic_Telemetry *measurement) soc = clamp(soc, 0.0f, 100.0f); // clamp soc between 0 and 100% float ttg = (100.0f - soc) / rate; // calculate hours to charge/discharge - LOG_DEBUG("MAX17048Sensor::getMetrics volts: %.3fV soc: %.1f%% ttg: %.1f hours\n", volts, soc, ttg); + LOG_DEBUG("MAX17048Sensor::getMetrics volts: %.3fV soc: %.1f%% ttg: %.1f hours", volts, soc, ttg); if ((int)measurement->which_variant == meshtastic_Telemetry_power_metrics_tag) { measurement->variant.power_metrics.has_ch1_voltage = true; measurement->variant.power_metrics.ch1_voltage = volts; diff --git a/src/modules/Telemetry/Sensor/MAX30102Sensor.cpp b/src/modules/Telemetry/Sensor/MAX30102Sensor.cpp new file mode 100644 index 0000000000..88128a6db7 --- /dev/null +++ b/src/modules/Telemetry/Sensor/MAX30102Sensor.cpp @@ -0,0 +1,83 @@ +#include "configuration.h" + +#if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR && !defined(ARCH_PORTDUINO) + +#include "../mesh/generated/meshtastic/telemetry.pb.h" +#include "MAX30102Sensor.h" +#include "TelemetrySensor.h" +#include + +MAX30102Sensor::MAX30102Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_MAX30102, "MAX30102") {} + +int32_t MAX30102Sensor::runOnce() +{ + LOG_INFO("Init sensor: %s", sensorName); + if (!hasSensor()) { + return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; + } + + if (max30102.begin(*nodeTelemetrySensorsMap[sensorType].second, _speed, nodeTelemetrySensorsMap[sensorType].first) == + true) // MAX30102 init + { + byte brightness = 60; // 0=Off to 255=50mA + byte sampleAverage = 4; // 1, 2, 4, 8, 16, 32 + byte leds = 2; // 1 = Red only, 2 = Red + IR + byte sampleRate = 100; // 50, 100, 200, 400, 800, 1000, 1600, 3200 + int pulseWidth = 411; // 69, 118, 215, 411 + int adcRange = 4096; // 2048, 4096, 8192, 16384 + + max30102.enableDIETEMPRDY(); // Enable the temperature ready interrupt + max30102.setup(brightness, sampleAverage, leds, sampleRate, pulseWidth, adcRange); + LOG_DEBUG("MAX30102 Init Succeed"); + status = true; + } else { + LOG_ERROR("MAX30102 Init Failed"); + status = false; + } + return initI2CSensor(); +} + +void MAX30102Sensor::setup() {} + +bool MAX30102Sensor::getMetrics(meshtastic_Telemetry *measurement) +{ + uint32_t ir_buff[MAX30102_BUFFER_LEN]; + uint32_t red_buff[MAX30102_BUFFER_LEN]; + int32_t spo2; + int8_t spo2_valid; + int32_t heart_rate; + int8_t heart_rate_valid; + float temp = max30102.readTemperature(); + + measurement->variant.environment_metrics.temperature = temp; + measurement->variant.environment_metrics.has_temperature = true; + measurement->variant.health_metrics.temperature = temp; + measurement->variant.health_metrics.has_temperature = true; + for (byte i = 0; i < MAX30102_BUFFER_LEN; i++) { + while (max30102.available() == false) + max30102.check(); + + red_buff[i] = max30102.getRed(); + ir_buff[i] = max30102.getIR(); + max30102.nextSample(); + } + + maxim_heart_rate_and_oxygen_saturation(ir_buff, MAX30102_BUFFER_LEN, red_buff, &spo2, &spo2_valid, &heart_rate, + &heart_rate_valid); + LOG_DEBUG("heart_rate=%d(%d), sp02=%d(%d)", heart_rate, heart_rate_valid, spo2, spo2_valid); + if (heart_rate_valid) { + measurement->variant.health_metrics.has_heart_bpm = true; + measurement->variant.health_metrics.heart_bpm = heart_rate; + } else { + measurement->variant.health_metrics.has_heart_bpm = false; + } + if (spo2_valid) { + measurement->variant.health_metrics.has_spO2 = true; + measurement->variant.health_metrics.spO2 = spo2; + } else { + measurement->variant.health_metrics.has_spO2 = true; + } + return true; +} + +#endif diff --git a/src/modules/Telemetry/Sensor/MAX30102Sensor.h b/src/modules/Telemetry/Sensor/MAX30102Sensor.h new file mode 100644 index 0000000000..426d9d3650 --- /dev/null +++ b/src/modules/Telemetry/Sensor/MAX30102Sensor.h @@ -0,0 +1,26 @@ +#include "configuration.h" + +#if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR && !defined(ARCH_PORTDUINO) + +#include "../mesh/generated/meshtastic/telemetry.pb.h" +#include "TelemetrySensor.h" +#include + +#define MAX30102_BUFFER_LEN 100 + +class MAX30102Sensor : public TelemetrySensor +{ + private: + MAX30105 max30102 = MAX30105(); + uint32_t _speed = 200000UL; + + protected: + virtual void setup() override; + + public: + MAX30102Sensor(); + virtual int32_t runOnce() override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; +}; + +#endif diff --git a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp index c1cda72275..6271076255 100644 --- a/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp +++ b/src/modules/Telemetry/Sensor/MCP9808Sensor.cpp @@ -11,7 +11,7 @@ MCP9808Sensor::MCP9808Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_ int32_t MCP9808Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -28,7 +28,7 @@ bool MCP9808Sensor::getMetrics(meshtastic_Telemetry *measurement) { measurement->variant.environment_metrics.has_temperature = true; - LOG_DEBUG("MCP9808Sensor::getMetrics\n"); + LOG_DEBUG("MCP9808Sensor::getMetrics"); measurement->variant.environment_metrics.temperature = mcp9808.readTempC(); return true; } diff --git a/src/modules/Telemetry/Sensor/MLX90614Sensor.cpp b/src/modules/Telemetry/Sensor/MLX90614Sensor.cpp new file mode 100644 index 0000000000..3a13eeba40 --- /dev/null +++ b/src/modules/Telemetry/Sensor/MLX90614Sensor.cpp @@ -0,0 +1,44 @@ +#include "configuration.h" + +#if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR && !defined(ARCH_PORTDUINO) + +#include "../mesh/generated/meshtastic/telemetry.pb.h" +#include "MLX90614Sensor.h" +#include "TelemetrySensor.h" +MLX90614Sensor::MLX90614Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_MLX90614, "MLX90614") {} + +int32_t MLX90614Sensor::runOnce() +{ + LOG_INFO("Init sensor: %s", sensorName); + if (!hasSensor()) { + return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; + } + + if (mlx.begin(nodeTelemetrySensorsMap[sensorType].first, nodeTelemetrySensorsMap[sensorType].second) == true) // MLX90614 init + { + LOG_DEBUG("MLX90614 emissivity: %f", mlx.readEmissivity()); + if (fabs(MLX90614_EMISSIVITY - mlx.readEmissivity()) > 0.001) { + mlx.writeEmissivity(MLX90614_EMISSIVITY); + LOG_INFO("MLX90614 emissivity updated. In case of weird data, power cycle."); + } + LOG_DEBUG("MLX90614 Init Succeed"); + status = true; + } else { + LOG_ERROR("MLX90614 Init Failed"); + status = false; + } + return initI2CSensor(); +} + +void MLX90614Sensor::setup() {} + +bool MLX90614Sensor::getMetrics(meshtastic_Telemetry *measurement) +{ + measurement->variant.environment_metrics.temperature = mlx.readAmbientTempC(); + measurement->variant.environment_metrics.has_temperature = true; + measurement->variant.health_metrics.temperature = mlx.readObjectTempC(); + measurement->variant.health_metrics.has_temperature = true; + return true; +} + +#endif diff --git a/src/modules/Telemetry/Sensor/MLX90614Sensor.h b/src/modules/Telemetry/Sensor/MLX90614Sensor.h new file mode 100644 index 0000000000..00f63449e5 --- /dev/null +++ b/src/modules/Telemetry/Sensor/MLX90614Sensor.h @@ -0,0 +1,24 @@ +#include "configuration.h" + +#if !MESHTASTIC_EXCLUDE_ENVIRONMENTAL_SENSOR && !defined(ARCH_PORTDUINO) +#include "../mesh/generated/meshtastic/telemetry.pb.h" +#include "TelemetrySensor.h" +#include + +#define MLX90614_EMISSIVITY 0.98 // human skin + +class MLX90614Sensor : public TelemetrySensor +{ + private: + Adafruit_MLX90614 mlx = Adafruit_MLX90614(); + + protected: + virtual void setup() override; + + public: + MLX90614Sensor(); + virtual int32_t runOnce() override; + virtual bool getMetrics(meshtastic_Telemetry *measurement) override; +}; + +#endif diff --git a/src/modules/Telemetry/Sensor/MLX90632Sensor.cpp b/src/modules/Telemetry/Sensor/MLX90632Sensor.cpp index 0568a46522..b7bd6ae61f 100644 --- a/src/modules/Telemetry/Sensor/MLX90632Sensor.cpp +++ b/src/modules/Telemetry/Sensor/MLX90632Sensor.cpp @@ -10,7 +10,7 @@ MLX90632Sensor::MLX90632Sensor() : TelemetrySensor(meshtastic_TelemetrySensorTyp int32_t MLX90632Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -19,10 +19,10 @@ int32_t MLX90632Sensor::runOnce() if (mlx.begin(nodeTelemetrySensorsMap[sensorType].first, *nodeTelemetrySensorsMap[sensorType].second, returnError) == true) // MLX90632 init { - LOG_DEBUG("MLX90632 Init Succeed\n"); + LOG_DEBUG("MLX90632 Init Succeed"); status = true; } else { - LOG_ERROR("MLX90632 Init Failed\n"); + LOG_ERROR("MLX90632 Init Failed"); status = false; } return initI2CSensor(); diff --git a/src/modules/Telemetry/Sensor/NAU7802Sensor.cpp b/src/modules/Telemetry/Sensor/NAU7802Sensor.cpp index 59f310a245..856a1aeecb 100644 --- a/src/modules/Telemetry/Sensor/NAU7802Sensor.cpp +++ b/src/modules/Telemetry/Sensor/NAU7802Sensor.cpp @@ -17,17 +17,17 @@ NAU7802Sensor::NAU7802Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_ int32_t NAU7802Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } status = nau7802.begin(*nodeTelemetrySensorsMap[sensorType].second); nau7802.setSampleRate(NAU7802_SPS_320); if (!loadCalibrationData()) { - LOG_ERROR("Failed to load calibration data\n"); + LOG_ERROR("Failed to load calibration data"); } nau7802.calibrateAFE(); - LOG_INFO("Offset: %d, Calibration factor: %.2f\n", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); + LOG_INFO("Offset: %d, Calibration factor: %.2f", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); return initI2CSensor(); } @@ -35,7 +35,7 @@ void NAU7802Sensor::setup() {} bool NAU7802Sensor::getMetrics(meshtastic_Telemetry *measurement) { - LOG_DEBUG("NAU7802Sensor::getMetrics\n"); + LOG_DEBUG("NAU7802Sensor::getMetrics"); nau7802.powerUp(); // Wait for the sensor to become ready for one second max uint32_t start = millis(); @@ -48,7 +48,7 @@ bool NAU7802Sensor::getMetrics(meshtastic_Telemetry *measurement) } measurement->variant.environment_metrics.has_weight = true; // Check if we have correct calibration values after powerup - LOG_DEBUG("Offset: %d, Calibration factor: %.2f\n", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); + LOG_DEBUG("Offset: %d, Calibration factor: %.2f", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); measurement->variant.environment_metrics.weight = nau7802.getWeight() / 1000; // sample is in kg nau7802.powerDown(); return true; @@ -58,9 +58,9 @@ void NAU7802Sensor::calibrate(float weight) { nau7802.calculateCalibrationFactor(weight * 1000, 64); // internal sample is in grams if (!saveCalibrationData()) { - LOG_WARN("Failed to save calibration data\n"); + LOG_WARN("Failed to save calibration data"); } - LOG_INFO("Offset: %d, Calibration factor: %.2f\n", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); + LOG_INFO("Offset: %d, Calibration factor: %.2f", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); } AdminMessageHandleResult NAU7802Sensor::handleAdminMessage(const meshtastic_MeshPacket &mp, meshtastic_AdminMessage *request, @@ -72,10 +72,10 @@ AdminMessageHandleResult NAU7802Sensor::handleAdminMessage(const meshtastic_Mesh case meshtastic_AdminMessage_set_scale_tag: if (request->set_scale == 0) { this->tare(); - LOG_DEBUG("Client requested to tare scale\n"); + LOG_DEBUG("Client requested to tare scale"); } else { this->calibrate(request->set_scale); - LOG_DEBUG("Client requested to calibrate to %d kg\n", request->set_scale); + LOG_DEBUG("Client requested to calibrate to %d kg", request->set_scale); } result = AdminMessageHandleResult::HANDLED; break; @@ -91,9 +91,9 @@ void NAU7802Sensor::tare() { nau7802.calculateZeroOffset(64); if (!saveCalibrationData()) { - LOG_WARN("Failed to save calibration data\n"); + LOG_WARN("Failed to save calibration data"); } - LOG_INFO("Offset: %d, Calibration factor: %.2f\n", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); + LOG_INFO("Offset: %d, Calibration factor: %.2f", nau7802.getZeroOffset(), nau7802.getCalibrationFactor()); } bool NAU7802Sensor::saveCalibrationData() @@ -103,11 +103,11 @@ bool NAU7802Sensor::saveCalibrationData() nau7802config.calibrationFactor = nau7802.getCalibrationFactor(); bool okay = false; - LOG_INFO("%s state write to %s.\n", sensorName, nau7802ConfigFileName); + LOG_INFO("%s state write to %s.", sensorName, nau7802ConfigFileName); pb_ostream_t stream = {&writecb, static_cast(&file), meshtastic_Nau7802Config_size}; if (!pb_encode(&stream, &meshtastic_Nau7802Config_msg, &nau7802config)) { - LOG_ERROR("Error: can't encode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_ERROR("Error: can't encode protobuf %s", PB_GET_ERROR(&stream)); } else { okay = true; } @@ -121,10 +121,10 @@ bool NAU7802Sensor::loadCalibrationData() auto file = FSCom.open(nau7802ConfigFileName, FILE_O_READ); bool okay = false; if (file) { - LOG_INFO("%s state read from %s.\n", sensorName, nau7802ConfigFileName); + LOG_INFO("%s state read from %s.", sensorName, nau7802ConfigFileName); pb_istream_t stream = {&readcb, &file, meshtastic_Nau7802Config_size}; if (!pb_decode(&stream, &meshtastic_Nau7802Config_msg, &nau7802config)) { - LOG_ERROR("Error: can't decode protobuf %s\n", PB_GET_ERROR(&stream)); + LOG_ERROR("Error: can't decode protobuf %s", PB_GET_ERROR(&stream)); } else { nau7802.setZeroOffset(nau7802config.zeroOffset); nau7802.setCalibrationFactor(nau7802config.calibrationFactor); @@ -132,7 +132,7 @@ bool NAU7802Sensor::loadCalibrationData() } file.close(); } else { - LOG_INFO("No %s state found (File: %s).\n", sensorName, nau7802ConfigFileName); + LOG_INFO("No %s state found (File: %s).", sensorName, nau7802ConfigFileName); } return okay; } diff --git a/src/modules/Telemetry/Sensor/OPT3001Sensor.cpp b/src/modules/Telemetry/Sensor/OPT3001Sensor.cpp index 3e4376d55b..75c6cd41a7 100644 --- a/src/modules/Telemetry/Sensor/OPT3001Sensor.cpp +++ b/src/modules/Telemetry/Sensor/OPT3001Sensor.cpp @@ -11,7 +11,7 @@ OPT3001Sensor::OPT3001Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_ int32_t OPT3001Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -42,7 +42,7 @@ bool OPT3001Sensor::getMetrics(meshtastic_Telemetry *measurement) OPT3001 result = opt3001.readResult(); measurement->variant.environment_metrics.lux = result.lux; - LOG_INFO("Lux: %f\n", measurement->variant.environment_metrics.lux); + LOG_INFO("Lux: %f", measurement->variant.environment_metrics.lux); return true; } diff --git a/src/modules/Telemetry/Sensor/RCWL9620Sensor.cpp b/src/modules/Telemetry/Sensor/RCWL9620Sensor.cpp index b9a29ab7d2..c7421d2792 100644 --- a/src/modules/Telemetry/Sensor/RCWL9620Sensor.cpp +++ b/src/modules/Telemetry/Sensor/RCWL9620Sensor.cpp @@ -10,7 +10,7 @@ RCWL9620Sensor::RCWL9620Sensor() : TelemetrySensor(meshtastic_TelemetrySensorTyp int32_t RCWL9620Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -24,7 +24,7 @@ void RCWL9620Sensor::setup() {} bool RCWL9620Sensor::getMetrics(meshtastic_Telemetry *measurement) { measurement->variant.environment_metrics.has_distance = true; - LOG_DEBUG("RCWL9620Sensor::getMetrics\n"); + LOG_DEBUG("RCWL9620Sensor::getMetrics"); measurement->variant.environment_metrics.distance = getDistance(); return true; } diff --git a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp index c372f79861..b96b94fa87 100644 --- a/src/modules/Telemetry/Sensor/SHT31Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHT31Sensor.cpp @@ -11,7 +11,7 @@ SHT31Sensor::SHT31Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_SHT3 int32_t SHT31Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/SHT4XSensor.cpp b/src/modules/Telemetry/Sensor/SHT4XSensor.cpp index 94367cba41..0fa6021dc2 100644 --- a/src/modules/Telemetry/Sensor/SHT4XSensor.cpp +++ b/src/modules/Telemetry/Sensor/SHT4XSensor.cpp @@ -11,7 +11,7 @@ SHT4XSensor::SHT4XSensor() : TelemetrySensor(meshtastic_TelemetrySensorType_SHT4 int32_t SHT4XSensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -22,7 +22,7 @@ int32_t SHT4XSensor::runOnce() serialNumber = sht4x.readSerial(); if (serialNumber != 0) { - LOG_DEBUG("serialNumber : %x\n", serialNumber); + LOG_DEBUG("serialNumber : %x", serialNumber); status = 1; } else { LOG_DEBUG("Error trying to execute readSerial(): "); diff --git a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp index 64ebfb472b..3a7cc48d25 100644 --- a/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp +++ b/src/modules/Telemetry/Sensor/SHTC3Sensor.cpp @@ -11,7 +11,7 @@ SHTC3Sensor::SHTC3Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_SHTC int32_t SHTC3Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/T1000xSensor.cpp b/src/modules/Telemetry/Sensor/T1000xSensor.cpp index 4772aeb9ed..068969e8e5 100644 --- a/src/modules/Telemetry/Sensor/T1000xSensor.cpp +++ b/src/modules/Telemetry/Sensor/T1000xSensor.cpp @@ -40,7 +40,7 @@ T1000xSensor::T1000xSensor() : TelemetrySensor(meshtastic_TelemetrySensorType_SE int32_t T1000xSensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } diff --git a/src/modules/Telemetry/Sensor/TSL2591Sensor.cpp b/src/modules/Telemetry/Sensor/TSL2591Sensor.cpp index 9002874b3d..add475d5b4 100644 --- a/src/modules/Telemetry/Sensor/TSL2591Sensor.cpp +++ b/src/modules/Telemetry/Sensor/TSL2591Sensor.cpp @@ -12,7 +12,7 @@ TSL2591Sensor::TSL2591Sensor() : TelemetrySensor(meshtastic_TelemetrySensorType_ int32_t TSL2591Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -36,7 +36,7 @@ bool TSL2591Sensor::getMetrics(meshtastic_Telemetry *measurement) full = lum & 0xFFFF; measurement->variant.environment_metrics.lux = tsl.calculateLux(full, ir); - LOG_INFO("Lux: %f\n", measurement->variant.environment_metrics.lux); + LOG_INFO("Lux: %f", measurement->variant.environment_metrics.lux); return true; } diff --git a/src/modules/Telemetry/Sensor/TelemetrySensor.h b/src/modules/Telemetry/Sensor/TelemetrySensor.h index da376ad31a..7910568c9b 100644 --- a/src/modules/Telemetry/Sensor/TelemetrySensor.h +++ b/src/modules/Telemetry/Sensor/TelemetrySensor.h @@ -31,10 +31,10 @@ class TelemetrySensor int32_t initI2CSensor() { if (!status) { - LOG_WARN("Could not connect to detected %s sensor.\n Removing from nodeTelemetrySensorsMap.\n", sensorName); + LOG_WARN("Could not connect to detected %s sensor. Removing from nodeTelemetrySensorsMap.", sensorName); nodeTelemetrySensorsMap[sensorType].first = 0; } else { - LOG_INFO("Opened %s sensor on i2c bus\n", sensorName); + LOG_INFO("Opened %s sensor on i2c bus", sensorName); setup(); } initialized = true; diff --git a/src/modules/Telemetry/Sensor/VEML7700Sensor.cpp b/src/modules/Telemetry/Sensor/VEML7700Sensor.cpp index c176ed21ba..496b49aeb8 100644 --- a/src/modules/Telemetry/Sensor/VEML7700Sensor.cpp +++ b/src/modules/Telemetry/Sensor/VEML7700Sensor.cpp @@ -13,7 +13,7 @@ VEML7700Sensor::VEML7700Sensor() : TelemetrySensor(meshtastic_TelemetrySensorTyp int32_t VEML7700Sensor::runOnce() { - LOG_INFO("Init sensor: %s\n", sensorName); + LOG_INFO("Init sensor: %s", sensorName); if (!hasSensor()) { return DEFAULT_SENSOR_MINIMUM_WAIT_TIME_BETWEEN_READS; } @@ -60,7 +60,7 @@ bool VEML7700Sensor::getMetrics(meshtastic_Telemetry *measurement) measurement->variant.environment_metrics.lux = veml7700.readLux(VEML_LUX_AUTO); white = veml7700.readWhite(true); measurement->variant.environment_metrics.white_lux = computeLux(white, white > 100); - LOG_INFO("white lux %f, als lux %f\n", measurement->variant.environment_metrics.white_lux, + LOG_INFO("white lux %f, als lux %f", measurement->variant.environment_metrics.white_lux, measurement->variant.environment_metrics.lux); return true; diff --git a/src/modules/TextMessageModule.cpp b/src/modules/TextMessageModule.cpp index 2933718af7..f1d01ad160 100644 --- a/src/modules/TextMessageModule.cpp +++ b/src/modules/TextMessageModule.cpp @@ -10,7 +10,7 @@ ProcessMessage TextMessageModule::handleReceived(const meshtastic_MeshPacket &mp { #ifdef DEBUG_PORT 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); + LOG_INFO("Received text msg from=0x%0x, id=0x%x, msg=%.*s", mp.from, mp.id, p.payload.size, p.payload.bytes); #endif // We only store/display messages destined for us. // Keep a copy of the most recent text message. diff --git a/src/modules/TraceRouteModule.cpp b/src/modules/TraceRouteModule.cpp index 955098c284..79b14de0a2 100644 --- a/src/modules/TraceRouteModule.cpp +++ b/src/modules/TraceRouteModule.cpp @@ -1,5 +1,6 @@ #include "TraceRouteModule.h" #include "MeshService.h" +#include "meshUtils.h" TraceRouteModule *traceRouteModule; @@ -101,45 +102,47 @@ void TraceRouteModule::appendMyIDandSNR(meshtastic_RouteDiscovery *updated, floa route[*route_count] = myNodeInfo.my_node_num; *route_count += 1; } else { - LOG_WARN("Route exceeded maximum hop limit!\n"); // Are you bridging networks? + LOG_WARN("Route exceeded maximum hop limit!"); // Are you bridging networks? } } void TraceRouteModule::printRoute(meshtastic_RouteDiscovery *r, uint32_t origin, uint32_t dest, bool isTowardsDestination) { #ifdef DEBUG_PORT - LOG_INFO("Route traced:\n"); - LOG_INFO("0x%x --> ", origin); + std::string route = "Route traced:"; + route += vformat("0x%x --> ", origin); for (uint8_t i = 0; i < r->route_count; i++) { if (i < r->snr_towards_count && r->snr_towards[i] != INT8_MIN) - LOG_INFO("0x%x (%.2fdB) --> ", r->route[i], (float)r->snr_towards[i] / 4); + route += vformat("0x%x (%.2fdB) --> ", r->route[i], (float)r->snr_towards[i] / 4); else - LOG_INFO("0x%x (?dB) --> ", r->route[i]); + route += vformat("0x%x (?dB) --> ", r->route[i]); } // If we are the destination, or it has already reached the destination, print it if (dest == nodeDB->getNodeNum() || !isTowardsDestination) { if (r->snr_towards_count > 0 && r->snr_towards[r->snr_towards_count - 1] != INT8_MIN) - LOG_INFO("0x%x (%.2fdB)\n", dest, (float)r->snr_towards[r->snr_towards_count - 1] / 4); + route += vformat("0x%x (%.2fdB)", dest, (float)r->snr_towards[r->snr_towards_count - 1] / 4); + else - LOG_INFO("0x%x (?dB)\n", dest); + route += vformat("0x%x (?dB)", dest); } else - LOG_INFO("...\n"); + route += "..."; // If there's a route back (or we are the destination as then the route is complete), print it if (r->route_back_count > 0 || origin == nodeDB->getNodeNum()) { if (r->snr_towards_count > 0 && origin == nodeDB->getNodeNum()) - LOG_INFO("(%.2fdB) 0x%x <-- ", (float)r->snr_back[r->snr_back_count - 1] / 4, origin); + route += vformat("(%.2fdB) 0x%x <-- ", (float)r->snr_back[r->snr_back_count - 1] / 4, origin); else - LOG_INFO("..."); + route += "..."; for (int8_t i = r->route_back_count - 1; i >= 0; i--) { if (i < r->snr_back_count && r->snr_back[i] != INT8_MIN) - LOG_INFO("(%.2fdB) 0x%x <-- ", (float)r->snr_back[i] / 4, r->route_back[i]); + route += vformat("(%.2fdB) 0x%x <-- ", (float)r->snr_back[i] / 4, r->route_back[i]); else - LOG_INFO("(?dB) 0x%x <-- ", r->route_back[i]); + route += vformat("(?dB) 0x%x <-- ", r->route_back[i]); } - LOG_INFO("0x%x\n", dest); + route += vformat("0x%x", dest); } + LOG_INFO(route.c_str()); #endif } diff --git a/src/modules/WaypointModule.cpp b/src/modules/WaypointModule.cpp index a4611e7809..48e0c4242d 100644 --- a/src/modules/WaypointModule.cpp +++ b/src/modules/WaypointModule.cpp @@ -14,7 +14,7 @@ ProcessMessage WaypointModule::handleReceived(const meshtastic_MeshPacket &mp) { #ifdef DEBUG_PORT 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); + LOG_INFO("Received waypoint msg from=0x%0x, id=0x%x, msg=%.*s", mp.from, mp.id, p.payload.size, p.payload.bytes); #endif // We only store/display messages destined for us. // Keep a copy of the most recent text message. @@ -68,7 +68,7 @@ bool WaypointModule::shouldDraw() } // If decoding failed - LOG_ERROR("Failed to decode waypoint\n"); + LOG_ERROR("Failed to decode waypoint"); devicestate.has_rx_waypoint = false; return false; #else diff --git a/src/modules/esp32/AudioModule.cpp b/src/modules/esp32/AudioModule.cpp index 89e4b4e256..ec0ddabfb3 100644 --- a/src/modules/esp32/AudioModule.cpp +++ b/src/modules/esp32/AudioModule.cpp @@ -46,7 +46,7 @@ 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)); - LOG_INFO("Starting codec2 task\n"); + LOG_INFO("Starting codec2 task"); while (true) { uint32_t tcount = ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(10000)); @@ -61,7 +61,7 @@ void run_codec2(void *parameter) audioModule->tx_encode_frame_index += audioModule->encode_codec_size; 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); + LOG_INFO("Sending %d codec2 bytes", audioModule->encode_frame_size); audioModule->sendPayload(); audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header); } @@ -111,7 +111,7 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", meshtastic_PortNum_ 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, + LOG_INFO("using %d frames of %d bytes for a total payload length of %d bytes", encode_frame_num, encode_codec_size, encode_frame_size); xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask); } else { @@ -148,7 +148,7 @@ 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, + LOG_INFO("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d", 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)), @@ -164,7 +164,7 @@ int32_t AudioModule::runOnce() .fixed_mclk = 0}; res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL); if (res != ESP_OK) { - LOG_ERROR("Failed to install I2S driver: %d\n", res); + LOG_ERROR("Failed to install I2S driver: %d", res); } const i2s_pin_config_t pin_config = { @@ -174,18 +174,18 @@ int32_t AudioModule::runOnce() .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) { - LOG_ERROR("Failed to set I2S pin config: %d\n", res); + LOG_ERROR("Failed to set I2S pin config: %d", res); } res = i2s_start(I2S_PORT); if (res != ESP_OK) { - LOG_ERROR("Failed to start I2S: %d\n", res); + LOG_ERROR("Failed to start I2S: %d", res); } radio_state = RadioState::rx; // Configure PTT input - LOG_INFO("Initializing PTT on Pin %u\n", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); + LOG_INFO("Initializing PTT on Pin %u", moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN); pinMode(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN, INPUT); firstTime = false; @@ -194,17 +194,17 @@ int32_t AudioModule::runOnce() // Check if PTT is pressed. TODO hook that into Onebutton/Interrupt drive. if (digitalRead(moduleConfig.audio.ptt_pin ? moduleConfig.audio.ptt_pin : PTT_PIN) == HIGH) { if (radio_state == RadioState::rx) { - LOG_INFO("PTT pressed, switching to TX\n"); + LOG_INFO("PTT pressed, switching to TX"); radio_state = RadioState::tx; e.action = UIFrameEvent::Action::REGENERATE_FRAMESET; // We want to change the list of frames shown on-screen this->notifyObservers(&e); } } else { if (radio_state == RadioState::tx) { - LOG_INFO("PTT released, switching to RX\n"); + LOG_INFO("PTT released, switching to RX"); if (tx_encode_frame_index > sizeof(tx_header)) { // Send the incomplete frame - LOG_INFO("Sending %d codec2 bytes (incomplete)\n", tx_encode_frame_index); + LOG_INFO("Sending %d codec2 bytes (incomplete)", tx_encode_frame_index); sendPayload(); } tx_encode_frame_index = sizeof(tx_header); diff --git a/src/modules/esp32/PaxcounterModule.cpp b/src/modules/esp32/PaxcounterModule.cpp index 71810df076..3a0f14ce97 100644 --- a/src/modules/esp32/PaxcounterModule.cpp +++ b/src/modules/esp32/PaxcounterModule.cpp @@ -15,7 +15,7 @@ PaxcounterModule *paxcounterModule; void PaxcounterModule::handlePaxCounterReportRequest() { // The libpax library already updated our data structure, just before invoking this callback. - LOG_INFO("PaxcounterModule: libpax reported new data: wifi=%d; ble=%d; uptime=%lu\n", + LOG_INFO("PaxcounterModule: libpax reported new data: wifi=%d; ble=%d; uptime=%lu", paxcounterModule->count_from_libpax.wifi_count, paxcounterModule->count_from_libpax.ble_count, millis() / 1000); paxcounterModule->reportedDataSent = false; paxcounterModule->setIntervalFromNow(0); @@ -39,7 +39,7 @@ bool PaxcounterModule::sendInfo(NodeNum dest) if (paxcounterModule->reportedDataSent) return false; - LOG_INFO("PaxcounterModule: sending pax info wifi=%d; ble=%d; uptime=%lu\n", count_from_libpax.wifi_count, + LOG_INFO("PaxcounterModule: sending pax info wifi=%d; ble=%d; uptime=%lu", count_from_libpax.wifi_count, count_from_libpax.ble_count, millis() / 1000); meshtastic_Paxcount pl = meshtastic_Paxcount_init_default; @@ -78,7 +78,7 @@ int32_t PaxcounterModule::runOnce() if (isActive()) { if (firstTime) { firstTime = false; - LOG_DEBUG("Paxcounter starting up with interval of %d seconds\n", + LOG_DEBUG("Paxcounter starting up with interval of %d seconds", Default::getConfiguredOrDefault(moduleConfig.paxcounter.paxcounter_update_interval, default_telemetry_broadcast_interval_secs)); struct libpax_config_t configuration; diff --git a/src/motion/AccelerometerThread.h b/src/motion/AccelerometerThread.h index f9cbb49a19..e548b20c60 100755 --- a/src/motion/AccelerometerThread.h +++ b/src/motion/AccelerometerThread.h @@ -14,6 +14,9 @@ #include "LSM6DS3Sensor.h" #include "MPU6050Sensor.h" #include "MotionSensor.h" +#ifdef HAS_QMA6100P +#include "QMA6100PSensor.h" +#endif #include "STK8XXXSensor.h" extern ScanI2C::DeviceAddress accelerometer_found; @@ -62,14 +65,14 @@ class AccelerometerThread : public concurrency::OSThread return; if (device.address.port == ScanI2C::I2CPort::NO_I2C || device.address.address == 0 || device.type == ScanI2C::NONE) { - LOG_DEBUG("AccelerometerThread disabling due to no sensors found\n"); + LOG_DEBUG("AccelerometerThread disabling due to no sensors found"); disable(); return; } #ifndef RAK_4631 if (!config.display.wake_on_tap_or_motion && !config.device.double_tap_as_button_press) { - LOG_DEBUG("AccelerometerThread disabling due to no interested configurations\n"); + LOG_DEBUG("AccelerometerThread disabling due to no interested configurations"); disable(); return; } @@ -97,6 +100,11 @@ class AccelerometerThread : public concurrency::OSThread case ScanI2C::DeviceType::ICM20948: sensor = new ICM20948Sensor(device); break; +#ifdef HAS_QMA6100P + case ScanI2C::DeviceType::QMA6100P: + sensor = new QMA6100PSensor(device); + break; +#endif default: disable(); return; @@ -106,7 +114,7 @@ class AccelerometerThread : public concurrency::OSThread if (!isInitialised) { clean(); } - LOG_DEBUG("AccelerometerThread::init %s\n", isInitialised ? "ok" : "failed"); + LOG_DEBUG("AccelerometerThread::init %s", isInitialised ? "ok" : "failed"); } // Copy constructor (not implemented / included to avoid cppcheck warnings) diff --git a/src/motion/BMA423Sensor.cpp b/src/motion/BMA423Sensor.cpp index ec07b7c40c..ec88a94308 100755 --- a/src/motion/BMA423Sensor.cpp +++ b/src/motion/BMA423Sensor.cpp @@ -41,10 +41,10 @@ bool BMA423Sensor::init() // It corresponds to isDoubleClick interrupt sensor.enableWakeupIRQ(); - LOG_DEBUG("BMA423Sensor::init ok\n"); + LOG_DEBUG("BMA423Sensor::init ok"); return true; } - LOG_DEBUG("BMA423Sensor::init failed\n"); + LOG_DEBUG("BMA423Sensor::init failed"); return false; } diff --git a/src/motion/BMX160Sensor.cpp b/src/motion/BMX160Sensor.cpp index f18c4b586f..f9e82e87d5 100755 --- a/src/motion/BMX160Sensor.cpp +++ b/src/motion/BMX160Sensor.cpp @@ -5,19 +5,21 @@ BMX160Sensor::BMX160Sensor(ScanI2C::FoundDevice foundDevice) : MotionSensor::MotionSensor(foundDevice) {} #ifdef RAK_4631 +#if !defined(MESHTASTIC_EXCLUDE_SCREEN) // screen is defined in main.cpp extern graphics::Screen *screen; +#endif bool BMX160Sensor::init() { if (sensor.begin()) { // set output data rate sensor.ODR_Config(BMX160_ACCEL_ODR_100HZ, BMX160_GYRO_ODR_100HZ); - LOG_DEBUG("BMX160Sensor::init ok\n"); + LOG_DEBUG("BMX160Sensor::init ok"); return true; } - LOG_DEBUG("BMX160Sensor::init failed\n"); + LOG_DEBUG("BMX160Sensor::init failed"); return false; } @@ -29,6 +31,7 @@ int32_t BMX160Sensor::runOnce() /* Get a new sensor event */ sensor.getAllData(&magAccel, NULL, &gAccel); +#if !defined(MESHTASTIC_EXCLUDE_SCREEN) // experimental calibrate routine. Limited to between 10 and 30 seconds after boot if (millis() > 12 * 1000 && millis() < 30 * 1000) { if (!showingScreen) { @@ -91,6 +94,7 @@ int32_t BMX160Sensor::runOnce() break; } screen->setHeading(heading); +#endif return MOTION_SENSOR_CHECK_INTERVAL_MS; } diff --git a/src/motion/ICM20948Sensor.cpp b/src/motion/ICM20948Sensor.cpp index d16968e06d..d1272e8e57 100755 --- a/src/motion/ICM20948Sensor.cpp +++ b/src/motion/ICM20948Sensor.cpp @@ -44,14 +44,14 @@ int32_t ICM20948Sensor::runOnce() // Wake on motion using polling - this is not as efficient as using hardware interrupt pin (see above) auto status = sensor->setBank(0); if (sensor->status != ICM_20948_Stat_Ok) { - LOG_DEBUG("ICM20948Sensor::isWakeOnMotion failed to set bank - %s\n", sensor->statusString()); + LOG_DEBUG("ICM20948Sensor::isWakeOnMotion failed to set bank - %s", sensor->statusString()); return MOTION_SENSOR_CHECK_INTERVAL_MS; } ICM_20948_INT_STATUS_t int_stat; status = sensor->read(AGB0_REG_INT_STATUS, (uint8_t *)&int_stat, sizeof(ICM_20948_INT_STATUS_t)); if (status != ICM_20948_Stat_Ok) { - LOG_DEBUG("ICM20948Sensor::isWakeOnMotion failed to read interrupts - %s\n", sensor->statusString()); + LOG_DEBUG("ICM20948Sensor::isWakeOnMotion failed to read interrupts - %s", sensor->statusString()); return MOTION_SENSOR_CHECK_INTERVAL_MS; } @@ -99,25 +99,25 @@ bool ICM20948Singleton::init(ScanI2C::FoundDevice device) ICM_20948_Status_e status = begin(Wire, device.address.address == ICM20948_ADDR ? 1 : 0); #endif if (status != ICM_20948_Stat_Ok) { - LOG_DEBUG("ICM20948Sensor::init begin - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init begin - %s", statusString()); return false; } // SW reset to make sure the device starts in a known state if (swReset() != ICM_20948_Stat_Ok) { - LOG_DEBUG("ICM20948Sensor::init reset - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init reset - %s", statusString()); return false; } delay(200); // Now wake the sensor up if (sleep(false) != ICM_20948_Stat_Ok) { - LOG_DEBUG("ICM20948Sensor::init wake - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init wake - %s", statusString()); return false; } if (lowPower(false) != ICM_20948_Stat_Ok) { - LOG_DEBUG("ICM20948Sensor::init high power - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init high power - %s", statusString()); return false; } @@ -125,19 +125,19 @@ bool ICM20948Singleton::init(ScanI2C::FoundDevice device) // Active low cfgIntActiveLow(true); - LOG_DEBUG("ICM20948Sensor::init set cfgIntActiveLow - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init set cfgIntActiveLow - %s", statusString()); // Push-pull cfgIntOpenDrain(false); - LOG_DEBUG("ICM20948Sensor::init set cfgIntOpenDrain - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init set cfgIntOpenDrain - %s", statusString()); // If enabled, *ANY* read will clear the INT_STATUS register. cfgIntAnyReadToClear(true); - LOG_DEBUG("ICM20948Sensor::init set cfgIntAnyReadToClear - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init set cfgIntAnyReadToClear - %s", statusString()); // Latch the interrupt until cleared cfgIntLatch(true); - LOG_DEBUG("ICM20948Sensor::init set cfgIntLatch - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init set cfgIntLatch - %s", statusString()); // Set up an interrupt pin with an internal pullup for active low pinMode(ICM_20948_INT_PIN, INPUT_PULLUP); @@ -168,13 +168,13 @@ bool ICM20948Singleton::setWakeOnMotion() // Enable WoM Logic mode 1 = Compare the current sample with the previous sample status = WOMLogic(true, 1); - LOG_DEBUG("ICM20948Sensor::init set WOMLogic - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init set WOMLogic - %s", statusString()); if (status != ICM_20948_Stat_Ok) return false; // Enable interrupts on WakeOnMotion status = intEnableWOM(true); - LOG_DEBUG("ICM20948Sensor::init set intEnableWOM - %s\n", statusString()); + LOG_DEBUG("ICM20948Sensor::init set intEnableWOM - %s", statusString()); return status == ICM_20948_Stat_Ok; // Clear any current interrupts diff --git a/src/motion/LIS3DHSensor.cpp b/src/motion/LIS3DHSensor.cpp index e2df60b1ce..d06b46b50a 100755 --- a/src/motion/LIS3DHSensor.cpp +++ b/src/motion/LIS3DHSensor.cpp @@ -1,4 +1,5 @@ #include "LIS3DHSensor.h" +#include "NodeDB.h" #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) && !MESHTASTIC_EXCLUDE_I2C @@ -10,10 +11,10 @@ bool LIS3DHSensor::init() sensor.setRange(LIS3DH_RANGE_2_G); // Adjust threshold, higher numbers are less sensitive sensor.setClick(config.device.double_tap_as_button_press ? 2 : 1, MOTION_SENSOR_CHECK_INTERVAL_MS); - LOG_DEBUG("LIS3DHSensor::init ok\n"); + LOG_DEBUG("LIS3DHSensor::init ok"); return true; } - LOG_DEBUG("LIS3DHSensor::init failed\n"); + LOG_DEBUG("LIS3DHSensor::init failed"); return false; } diff --git a/src/motion/LSM6DS3Sensor.cpp b/src/motion/LSM6DS3Sensor.cpp index 64ef9a23b1..3b25c3872b 100755 --- a/src/motion/LSM6DS3Sensor.cpp +++ b/src/motion/LSM6DS3Sensor.cpp @@ -1,4 +1,5 @@ #include "LSM6DS3Sensor.h" +#include "NodeDB.h" #if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) && !MESHTASTIC_EXCLUDE_I2C @@ -14,10 +15,10 @@ bool LSM6DS3Sensor::init() // Duration is number of occurances needed to trigger, higher threshold is less sensitive sensor.enableWakeup(config.display.wake_on_tap_or_motion, 1, LSM6DS3_WAKE_THRESH); - LOG_DEBUG("LSM6DS3Sensor::init ok\n"); + LOG_DEBUG("LSM6DS3Sensor::init ok"); return true; } - LOG_DEBUG("LSM6DS3Sensor::init failed\n"); + LOG_DEBUG("LSM6DS3Sensor::init failed"); return false; } diff --git a/src/motion/MPU6050Sensor.cpp b/src/motion/MPU6050Sensor.cpp index 77aaca46d6..b5048090af 100755 --- a/src/motion/MPU6050Sensor.cpp +++ b/src/motion/MPU6050Sensor.cpp @@ -13,10 +13,10 @@ bool MPU6050Sensor::init() sensor.setMotionDetectionDuration(20); sensor.setInterruptPinLatch(true); // Keep it latched. Will turn off when reinitialized. sensor.setInterruptPinPolarity(true); - LOG_DEBUG("MPU6050Sensor::init ok\n"); + LOG_DEBUG("MPU6050Sensor::init ok"); return true; } - LOG_DEBUG("MPU6050Sensor::init failed\n"); + LOG_DEBUG("MPU6050Sensor::init failed"); return false; } diff --git a/src/motion/MotionSensor.cpp b/src/motion/MotionSensor.cpp index 20e396bba5..95bf646400 100755 --- a/src/motion/MotionSensor.cpp +++ b/src/motion/MotionSensor.cpp @@ -10,7 +10,7 @@ MotionSensor::MotionSensor(ScanI2C::FoundDevice foundDevice) device.address.address = foundDevice.address.address; device.address.port = foundDevice.address.port; device.type = foundDevice.type; - LOG_DEBUG("MotionSensor::MotionSensor port: %s address: 0x%x type: %d\n", + LOG_DEBUG("MotionSensor::MotionSensor port: %s address: 0x%x type: %d", devicePort() == ScanI2C::I2CPort::WIRE1 ? "Wire1" : "Wire", (uint8_t)deviceAddress(), deviceType()); } @@ -29,7 +29,7 @@ ScanI2C::I2CPort MotionSensor::devicePort() return device.address.port; } -#ifdef RAK_4631 +#if defined(RAK_4631) & !MESHTASTIC_EXCLUDE_SCREEN void MotionSensor::drawFrameCalibration(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) { // int x_offset = display->width() / 2; @@ -57,14 +57,14 @@ void MotionSensor::drawFrameCalibration(OLEDDisplay *display, OLEDDisplayUiState void MotionSensor::wakeScreen() { if (powerFSM.getState() == &stateDARK) { - LOG_DEBUG("MotionSensor::wakeScreen detected\n"); + LOG_DEBUG("MotionSensor::wakeScreen detected"); powerFSM.trigger(EVENT_INPUT); } } void MotionSensor::buttonPress() { - LOG_DEBUG("MotionSensor::buttonPress detected\n"); + LOG_DEBUG("MotionSensor::buttonPress detected"); powerFSM.trigger(EVENT_PRESS); } diff --git a/src/motion/MotionSensor.h b/src/motion/MotionSensor.h index 0f7f3479b2..78eec54cec 100755 --- a/src/motion/MotionSensor.h +++ b/src/motion/MotionSensor.h @@ -14,6 +14,7 @@ #include "../graphics/Screen.h" #include "../graphics/ScreenFonts.h" #include "../power.h" +#include "Wire.h" // Base class for motion processing class MotionSensor @@ -46,7 +47,7 @@ class MotionSensor // Register a button press when a double-tap is detected virtual void buttonPress(); -#ifdef RAK_4631 +#if defined(RAK_4631) & !MESHTASTIC_EXCLUDE_SCREEN // draw an OLED frame (currently only used by the RAK4631 BMX160 sensor) static void drawFrameCalibration(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y); #endif diff --git a/src/motion/QMA6100PSensor.cpp b/src/motion/QMA6100PSensor.cpp new file mode 100644 index 0000000000..989188fe67 --- /dev/null +++ b/src/motion/QMA6100PSensor.cpp @@ -0,0 +1,183 @@ +#include "QMA6100PSensor.h" + +#if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) && !MESHTASTIC_EXCLUDE_I2C && defined(HAS_QMA6100P) + +// Flag when an interrupt has been detected +volatile static bool QMA6100P_IRQ = false; + +// Interrupt service routine +void QMA6100PSetInterrupt() +{ + QMA6100P_IRQ = true; +} + +QMA6100PSensor::QMA6100PSensor(ScanI2C::FoundDevice foundDevice) : MotionSensor::MotionSensor(foundDevice) {} + +bool QMA6100PSensor::init() +{ + // Initialise the sensor + sensor = QMA6100PSingleton::GetInstance(); + if (!sensor->init(device)) + return false; + + // Enable simple Wake on Motion + return sensor->setWakeOnMotion(); +} + +#ifdef QMA_6100P_INT_PIN + +int32_t QMA6100PSensor::runOnce() +{ + // Wake on motion using hardware interrupts - this is the most efficient way to check for motion + if (QMA6100P_IRQ) { + QMA6100P_IRQ = false; + wakeScreen(); + } + return MOTION_SENSOR_CHECK_INTERVAL_MS; +} + +#else + +int32_t QMA6100PSensor::runOnce() +{ + // Wake on motion using polling - this is not as efficient as using hardware interrupt pin (see above) + + uint8_t tempVal; + if (!sensor->readRegisterRegion(SFE_QMA6100P_INT_ST0, &tempVal, 1)) { + LOG_DEBUG("QMA6100PSensor::isWakeOnMotion failed to read interrupts"); + return MOTION_SENSOR_CHECK_INTERVAL_MS; + } + + if ((tempVal & 7) != 0) { + // Wake up! + wakeScreen(); + } + return MOTION_SENSOR_CHECK_INTERVAL_MS; +} + +#endif + +// ---------------------------------------------------------------------- +// QMA6100PSingleton +// ---------------------------------------------------------------------- + +// Get a singleton wrapper for an Sparkfun QMA_6100P_I2C +QMA6100PSingleton *QMA6100PSingleton::GetInstance() +{ + if (pinstance == nullptr) { + pinstance = new QMA6100PSingleton(); + } + return pinstance; +} + +QMA6100PSingleton::QMA6100PSingleton() {} + +QMA6100PSingleton::~QMA6100PSingleton() {} + +QMA6100PSingleton *QMA6100PSingleton::pinstance{nullptr}; + +// Initialise the QMA6100P Sensor +bool QMA6100PSingleton::init(ScanI2C::FoundDevice device) +{ + +// startup +#ifdef Wire1 + bool status = begin(device.address.address, device.address.port == ScanI2C::I2CPort::WIRE1 ? &Wire1 : &Wire); +#else + // check chip id + bool status = begin(device.address.address, &Wire); +#endif + if (status != true) { + LOG_WARN("QMA6100PSensor::init begin failed\n"); + return false; + } + delay(20); + // SW reset to make sure the device starts in a known state + if (softwareReset() != true) { + LOG_WARN("QMA6100PSensor::init reset failed\n"); + return false; + } + delay(20); + // Set range + if (!setRange(QMA_6100P_MPU_ACCEL_SCALE)) { + LOG_WARN("QMA6100PSensor::init range failed"); + return false; + } + // set active mode + if (!enableAccel()) { + LOG_WARN("ERROR :QMA6100PSensor::active mode set failed"); + } + // set calibrateoffsets + if (!calibrateOffsets()) { + LOG_WARN("ERROR :QMA6100PSensor:: calibration failed"); + } +#ifdef QMA_6100P_INT_PIN + + // Active low & Open Drain + uint8_t tempVal; + if (!readRegisterRegion(SFE_QMA6100P_INTPINT_CONF, &tempVal, 1)) { + LOG_WARN("QMA6100PSensor::init failed to read interrupt pin config"); + return false; + } + + tempVal |= 0b00000010; // Active low & Open Drain + + if (!writeRegisterByte(SFE_QMA6100P_INTPINT_CONF, tempVal)) { + LOG_WARN("QMA6100PSensor::init failed to write interrupt pin config"); + return false; + } + + // Latch until cleared, all reads clear the latch + if (!readRegisterRegion(SFE_QMA6100P_INT_CFG, &tempVal, 1)) { + LOG_WARN("QMA6100PSensor::init failed to read interrupt config"); + return false; + } + + tempVal |= 0b10000001; // Latch until cleared, INT_RD_CLR1 + + if (!writeRegisterByte(SFE_QMA6100P_INT_CFG, tempVal)) { + LOG_WARN("QMA6100PSensor::init failed to write interrupt config"); + return false; + } + // Set up an interrupt pin with an internal pullup for active low + pinMode(QMA_6100P_INT_PIN, INPUT_PULLUP); + + // Set up an interrupt service routine + attachInterrupt(QMA_6100P_INT_PIN, QMA6100PSetInterrupt, FALLING); + +#endif + return true; +} + +bool QMA6100PSingleton::setWakeOnMotion() +{ + // Enable 'Any Motion' interrupt + if (!writeRegisterByte(SFE_QMA6100P_INT_EN2, 0b00000111)) { + LOG_WARN("QMA6100PSingleton::setWakeOnMotion failed to write interrupt enable"); + return false; + } + + // Set 'Significant Motion' interrupt map to INT1 + uint8_t tempVal; + + if (!readRegisterRegion(SFE_QMA6100P_INT_MAP1, &tempVal, 1)) { + LOG_WARN("QMA6100PSingleton::setWakeOnMotion failed to read interrupt map"); + return false; + } + + sfe_qma6100p_int_map1_bitfield_t int_map1; + int_map1.all = tempVal; + int_map1.bits.int1_any_mot = 1; // any motion interrupt to INT1 + tempVal = int_map1.all; + + if (!writeRegisterByte(SFE_QMA6100P_INT_MAP1, tempVal)) { + LOG_WARN("QMA6100PSingleton::setWakeOnMotion failed to write interrupt map"); + return false; + } + + // Clear any current interrupts + QMA6100P_IRQ = false; + return true; +} + +#endif \ No newline at end of file diff --git a/src/motion/QMA6100PSensor.h b/src/motion/QMA6100PSensor.h new file mode 100644 index 0000000000..7ba00149c5 --- /dev/null +++ b/src/motion/QMA6100PSensor.h @@ -0,0 +1,63 @@ +#pragma once +#ifndef _QMA_6100P_SENSOR_H_ +#define _QMA_6100P_SENSOR_H_ + +#include "MotionSensor.h" + +#if !defined(ARCH_PORTDUINO) && !defined(ARCH_STM32WL) && !MESHTASTIC_EXCLUDE_I2C && defined(HAS_QMA6100P) + +#include + +// Set the default accelerometer scale - gpm2, gpm4, gpm8, gpm16 +#ifndef QMA_6100P_MPU_ACCEL_SCALE +#define QMA_6100P_MPU_ACCEL_SCALE SFE_QMA6100P_RANGE32G +#endif + +// The I2C address of the Accelerometer (if found) from main.cpp +extern ScanI2C::DeviceAddress accelerometer_found; + +// Singleton wrapper for the Sparkfun QMA_6100P_I2C class +class QMA6100PSingleton : public QMA6100P +{ + private: + static QMA6100PSingleton *pinstance; + + protected: + QMA6100PSingleton(); + ~QMA6100PSingleton(); + + public: + // Create a singleton instance (not thread safe) + static QMA6100PSingleton *GetInstance(); + + // Singletons should not be cloneable. + QMA6100PSingleton(QMA6100PSingleton &other) = delete; + + // Singletons should not be assignable. + void operator=(const QMA6100PSingleton &) = delete; + + // Initialise the motion sensor singleton for normal operation + bool init(ScanI2C::FoundDevice device); + + // Enable Wake on Motion interrupts (sensor must be initialised first) + bool setWakeOnMotion(); +}; + +class QMA6100PSensor : public MotionSensor +{ + private: + QMA6100PSingleton *sensor = nullptr; + + public: + explicit QMA6100PSensor(ScanI2C::FoundDevice foundDevice); + + // Initialise the motion sensor + virtual bool init() override; + + // Called each time our sensor gets a chance to run + virtual int32_t runOnce() override; +}; + +#endif + +#endif \ No newline at end of file diff --git a/src/motion/STK8XXXSensor.cpp b/src/motion/STK8XXXSensor.cpp index d4d69ef992..72b4bc3a84 100755 --- a/src/motion/STK8XXXSensor.cpp +++ b/src/motion/STK8XXXSensor.cpp @@ -17,10 +17,10 @@ bool STK8XXXSensor::init() attachInterrupt( digitalPinToInterrupt(STK8XXX_INT), [] { STK_IRQ = true; }, RISING); - LOG_DEBUG("STK8XXXSensor::init ok\n"); + LOG_DEBUG("STK8XXXSensor::init ok"); return true; } - LOG_DEBUG("STK8XXXSensor::init failed\n"); + LOG_DEBUG("STK8XXXSensor::init failed"); return false; } diff --git a/src/mqtt/MQTT.cpp b/src/mqtt/MQTT.cpp index 0c1ce0c7c2..39d554100b 100644 --- a/src/mqtt/MQTT.cpp +++ b/src/mqtt/MQTT.cpp @@ -35,6 +35,8 @@ Allocator &mqttPool = staticMqttPool; // FIXME - this size calculation is super sloppy, but it will go away once we dynamically alloc meshpackets static uint8_t bytes[meshtastic_MqttClientProxyMessage_size + 30]; // 12 for channel name and 16 for nodeid +static bool isMqttServerAddressPrivate = false; + void MQTT::mqttCallback(char *topic, byte *payload, unsigned int length) { mqtt->onReceive(topic, payload, length); @@ -72,7 +74,7 @@ void MQTT::onReceive(char *topic, byte *payload, size_t length) // this is a valid envelope if (json["type"]->AsString().compare("sendtext") == 0 && json["payload"]->IsString()) { std::string jsonPayloadStr = json["payload"]->AsString(); - LOG_INFO("JSON payload %s, length %u\n", jsonPayloadStr.c_str(), jsonPayloadStr.length()); + LOG_INFO("JSON payload %s, length %u", jsonPayloadStr.c_str(), jsonPayloadStr.length()); // construct protobuf data packet using TEXT_MESSAGE, send it to the mesh meshtastic_MeshPacket *p = router->allocForSending(); @@ -89,7 +91,7 @@ void MQTT::onReceive(char *topic, byte *payload, size_t length) p->decoded.payload.size = jsonPayloadStr.length(); service->sendToMesh(p, RX_SRC_LOCAL); } else { - LOG_WARN("Received MQTT json payload too long, dropping\n"); + LOG_WARN("Received MQTT json payload too long, dropping"); } } else if (json["type"]->AsString().compare("sendposition") == 0 && json["payload"]->IsObject()) { // invent the "sendposition" type for a valid envelope @@ -120,29 +122,29 @@ void MQTT::onReceive(char *topic, byte *payload, size_t length) &meshtastic_Position_msg, &pos); // make the Data protobuf from position service->sendToMesh(p, RX_SRC_LOCAL); } else { - LOG_DEBUG("JSON Ignoring downlink message with unsupported type.\n"); + LOG_DEBUG("JSON Ignoring downlink message with unsupported type."); } } else { - LOG_ERROR("JSON Received payload on MQTT but not a valid envelope.\n"); + LOG_ERROR("JSON Received payload on MQTT but not a valid envelope."); } } else { - LOG_WARN("JSON downlink received on channel not called 'mqtt' or without downlink enabled.\n"); + LOG_WARN("JSON downlink received on channel not called 'mqtt' or without downlink enabled."); } } else { // no json, this is an invalid payload - LOG_ERROR("JSON Received payload on MQTT but not a valid JSON\n"); + LOG_ERROR("JSON Received payload on MQTT but not a valid JSON"); } delete json_value; } else { if (length == 0) { - LOG_WARN("Empty MQTT payload received, topic %s!\n", topic); + LOG_WARN("Empty MQTT payload received, topic %s!", topic); return; } else if (!pb_decode_from_bytes(payload, length, &meshtastic_ServiceEnvelope_msg, &e)) { - LOG_ERROR("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); + LOG_ERROR("Invalid MQTT service envelope, topic %s, len %u!", topic, length); return; } else { if (e.channel_id == NULL || e.gateway_id == NULL) { - LOG_ERROR("Invalid MQTT service envelope, topic %s, len %u!\n", topic, length); + LOG_ERROR("Invalid MQTT service envelope, topic %s, len %u!", topic, length); return; } meshtastic_Channel ch = channels.getByName(e.channel_id); @@ -153,28 +155,28 @@ void MQTT::onReceive(char *topic, byte *payload, size_t length) if (e.packet && isFromUs(e.packet)) routingModule->sendAckNak(meshtastic_Routing_Error_NONE, getFrom(e.packet), e.packet->id, ch.index); else - LOG_INFO("Ignoring downlink message we originally sent.\n"); + LOG_INFO("Ignoring downlink message we originally sent."); } else { // Find channel by channel_id and check downlink_enabled if ((strcmp(e.channel_id, "PKI") == 0 && e.packet) || (strcmp(e.channel_id, channels.getGlobalId(ch.index)) == 0 && e.packet && ch.settings.downlink_enabled)) { - LOG_INFO("Received MQTT topic %s, len=%u\n", topic, length); + LOG_INFO("Received MQTT topic %s, len=%u", topic, length); meshtastic_MeshPacket *p = packetPool.allocCopy(*e.packet); p->via_mqtt = true; // Mark that the packet was received via MQTT if (isFromUs(p)) { - LOG_INFO("Ignoring downlink message we originally sent.\n"); + LOG_INFO("Ignoring downlink message we originally sent."); packetPool.release(p); return; } if (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { if (moduleConfig.mqtt.encryption_enabled) { - LOG_INFO("Ignoring decoded message on MQTT, encryption is enabled.\n"); + LOG_INFO("Ignoring decoded message on MQTT, encryption is enabled."); packetPool.release(p); return; } if (p->decoded.portnum == meshtastic_PortNum_ADMIN_APP) { - LOG_INFO("Ignoring decoded admin packet.\n"); + LOG_INFO("Ignoring decoded admin packet."); packetPool.release(p); return; } @@ -216,7 +218,7 @@ MQTT::MQTT() : concurrency::OSThread("mqtt"), mqttQueue(MAX_MQTT_QUEUE) #endif { if (moduleConfig.mqtt.enabled) { - LOG_DEBUG("Initializing MQTT\n"); + LOG_DEBUG("Initializing MQTT"); assert(!mqtt); mqtt = this; @@ -238,13 +240,18 @@ MQTT::MQTT() : concurrency::OSThread("mqtt"), mqttQueue(MAX_MQTT_QUEUE) moduleConfig.mqtt.map_report_settings.publish_interval_secs, default_map_publish_interval_secs); } + isMqttServerAddressPrivate = isPrivateIpAddress(moduleConfig.mqtt.address); + if (isMqttServerAddressPrivate) { + LOG_INFO("MQTT server is a private IP address."); + } + #if HAS_NETWORKING if (!moduleConfig.mqtt.proxy_to_client_enabled) pubSub.setCallback(mqttCallback); #endif if (moduleConfig.mqtt.proxy_to_client_enabled) { - LOG_INFO("MQTT configured to use client proxy...\n"); + LOG_INFO("MQTT configured to use client proxy..."); enabled = true; runASAP = true; reconnectCount = 0; @@ -308,7 +315,7 @@ void MQTT::reconnect() { if (wantsLink()) { if (moduleConfig.mqtt.proxy_to_client_enabled) { - LOG_INFO("MQTT connecting via client proxy instead...\n"); + LOG_INFO("MQTT connecting via client proxy instead..."); enabled = true; runASAP = true; reconnectCount = 0; @@ -337,12 +344,12 @@ void MQTT::reconnect() wifiSecureClient.setInsecure(); pubSub.setClient(wifiSecureClient); - LOG_INFO("Using TLS-encrypted session\n"); + LOG_INFO("Using TLS-encrypted session"); } catch (const std::exception &e) { - LOG_ERROR("MQTT ERROR: %s\n", e.what()); + LOG_ERROR("MQTT ERROR: %s", e.what()); } } else { - LOG_INFO("Using non-TLS-encrypted session\n"); + LOG_INFO("Using non-TLS-encrypted session"); pubSub.setClient(mqttClient); } #else @@ -363,12 +370,12 @@ void MQTT::reconnect() pubSub.setServer(serverAddr, serverPort); pubSub.setBufferSize(512); - LOG_INFO("Attempting to connect directly to MQTT server %s, port: %d, username: %s, password: %s\n", serverAddr, - serverPort, mqttUsername, mqttPassword); + LOG_INFO("Attempting to connect directly to MQTT server %s, port: %d, username: %s, password: %s", serverAddr, serverPort, + mqttUsername, mqttPassword); bool connected = pubSub.connect(owner.id, mqttUsername, mqttPassword); if (connected) { - LOG_INFO("MQTT connected\n"); + LOG_INFO("MQTT connected"); enabled = true; // Start running background process again runASAP = true; reconnectCount = 0; @@ -378,7 +385,7 @@ void MQTT::reconnect() } else { #if HAS_WIFI && !defined(ARCH_PORTDUINO) reconnectCount++; - LOG_ERROR("Failed to contact MQTT server directly (%d/%d)...\n", reconnectCount, reconnectMax); + LOG_ERROR("Failed to contact MQTT server directly (%d/%d)...", reconnectCount, reconnectMax); if (reconnectCount >= reconnectMax) { needReconnect = true; wifiReconnect->setIntervalFromNow(0); @@ -400,21 +407,22 @@ void MQTT::sendSubscriptions() if (ch.settings.downlink_enabled) { hasDownlink = true; std::string topic = cryptTopic + channels.getGlobalId(i) + "/+"; - LOG_INFO("Subscribing to %s\n", topic.c_str()); + LOG_INFO("Subscribing to %s", topic.c_str()); pubSub.subscribe(topic.c_str(), 1); // FIXME, is QOS 1 right? -#ifndef ARCH_NRF52 // JSON is not supported on nRF52, see issue #2804 +#if !defined(ARCH_NRF52) || \ + defined(NRF52_USE_JSON) // JSON is not supported on nRF52, see issue #2804 ### Fixed by using ArduinoJSON ### if (moduleConfig.mqtt.json_enabled == true) { std::string topicDecoded = jsonTopic + channels.getGlobalId(i) + "/+"; - LOG_INFO("Subscribing to %s\n", topicDecoded.c_str()); + LOG_INFO("Subscribing to %s", topicDecoded.c_str()); pubSub.subscribe(topicDecoded.c_str(), 1); // FIXME, is QOS 1 right? } -#endif // ARCH_NRF52 +#endif // ARCH_NRF52 NRF52_USE_JSON } } #if !MESHTASTIC_EXCLUDE_PKI if (hasDownlink) { std::string topic = cryptTopic + "PKI/+"; - LOG_INFO("Subscribing to %s\n", topic.c_str()); + LOG_INFO("Subscribing to %s", topic.c_str()); pubSub.subscribe(topic.c_str(), 1); } #endif @@ -470,7 +478,7 @@ int32_t MQTT::runOnce() } else { // we are connected to server, check often for new requests on the TCP port if (!wantConnection) { - LOG_INFO("MQTT link not needed, dropping\n"); + LOG_INFO("MQTT link not needed, dropping"); pubSub.disconnect(); } @@ -488,7 +496,7 @@ void MQTT::publishNodeInfo() void MQTT::publishQueuedMessages() { if (!mqttQueue.isEmpty()) { - LOG_DEBUG("Publishing enqueued MQTT message\n"); + LOG_DEBUG("Publishing enqueued MQTT message"); meshtastic_ServiceEnvelope *env = mqttQueue.dequeuePtr(0); size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_ServiceEnvelope_msg, env); std::string topic; @@ -497,11 +505,12 @@ void MQTT::publishQueuedMessages() } else { topic = cryptTopic + env->channel_id + "/" + owner.id; } - LOG_INFO("publish %s, %u bytes from queue\n", topic.c_str(), numBytes); + LOG_INFO("publish %s, %u bytes from queue", topic.c_str(), numBytes); publish(topic.c_str(), bytes, numBytes, false); -#ifndef ARCH_NRF52 // JSON is not supported on nRF52, see issue #2804 +#if !defined(ARCH_NRF52) || \ + defined(NRF52_USE_JSON) // JSON is not supported on nRF52, see issue #2804 ### Fixed by using ArduinoJson ### if (moduleConfig.mqtt.json_enabled) { // handle json topic auto jsonString = MeshPacketSerializer::JsonSerialize(env->packet); @@ -512,19 +521,18 @@ void MQTT::publishQueuedMessages() } else { topicJson = jsonTopic + env->channel_id + "/" + owner.id; } - LOG_INFO("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), - jsonString.c_str()); + LOG_INFO("JSON publish message to %s, %u bytes: %s", topicJson.c_str(), jsonString.length(), jsonString.c_str()); publish(topicJson.c_str(), jsonString.c_str(), false); } } -#endif // ARCH_NRF52 +#endif // ARCH_NRF52 NRF52_USE_JSON mqttPool.release(env); } } -void MQTT::onSend(const meshtastic_MeshPacket &mp, const meshtastic_MeshPacket &mp_decoded, ChannelIndex chIndex) +void MQTT::onSend(const meshtastic_MeshPacket &mp_encrypted, const meshtastic_MeshPacket &mp_decoded, ChannelIndex chIndex) { - if (mp.via_mqtt) + if (mp_encrypted.via_mqtt) return; // Don't send messages that came from MQTT back into MQTT bool uplinkEnabled = false; for (int i = 0; i <= 7; i++) { @@ -535,30 +543,29 @@ void MQTT::onSend(const meshtastic_MeshPacket &mp, const meshtastic_MeshPacket & return; // no channels have an uplink enabled auto &ch = channels.getByIndex(chIndex); - if (!mp.pki_encrypted) { - if (mp_decoded.which_payload_variant != meshtastic_MeshPacket_decoded_tag) { - LOG_CRIT("MQTT::onSend(): mp_decoded isn't actually decoded\n"); - return; - } - + // mp_decoded will not be decoded when it's PKI encrypted and not directed to us + if (mp_decoded.which_payload_variant == meshtastic_MeshPacket_decoded_tag) { // check for the lowest bit of the data bitfield set false, and the use of one of the default keys. - if (!isFromUs(&mp_decoded) && mp_decoded.decoded.has_bitfield && + if (!isFromUs(&mp_decoded) && !isMqttServerAddressPrivate && mp_decoded.decoded.has_bitfield && !(mp_decoded.decoded.bitfield & BITFIELD_OK_TO_MQTT_MASK) && (ch.settings.psk.size < 2 || (ch.settings.psk.size == 16 && memcmp(ch.settings.psk.bytes, defaultpsk, 16)) || (ch.settings.psk.size == 32 && memcmp(ch.settings.psk.bytes, eventpsk, 32)))) { - LOG_INFO("MQTT onSend - Not forwarding packet due to DontMqttMeBro flag\n"); + LOG_INFO("MQTT onSend - Not forwarding packet due to DontMqttMeBro flag"); return; } if (strcmp(moduleConfig.mqtt.address, default_mqtt_address) == 0 && (mp_decoded.decoded.portnum == meshtastic_PortNum_RANGE_TEST_APP || mp_decoded.decoded.portnum == meshtastic_PortNum_DETECTION_SENSOR_APP)) { - LOG_DEBUG("MQTT onSend - Ignoring range test or detection sensor message on public mqtt\n"); + LOG_DEBUG("MQTT onSend - Ignoring range test or detection sensor message on public mqtt"); return; } } - if (mp.pki_encrypted || ch.settings.uplink_enabled) { - const char *channelId = mp.pki_encrypted ? "PKI" : channels.getGlobalId(chIndex); + // Either encrypted packet (we couldn't decrypt) is marked as pki_encrypted, or we could decode the PKI encrypted packet + bool isPKIEncrypted = mp_encrypted.pki_encrypted || mp_decoded.pki_encrypted; + // If it was to a channel, check uplink enabled, else must be pki_encrypted + if ((ch.settings.uplink_enabled && !isPKIEncrypted) || isPKIEncrypted) { + const char *channelId = isPKIEncrypted ? "PKI" : channels.getGlobalId(chIndex); meshtastic_ServiceEnvelope *env = mqttPool.allocZeroed(); env->channel_id = (char *)channelId; @@ -566,37 +573,40 @@ void MQTT::onSend(const meshtastic_MeshPacket &mp, const meshtastic_MeshPacket & LOG_DEBUG("MQTT onSend - Publishing "); if (moduleConfig.mqtt.encryption_enabled) { - env->packet = (meshtastic_MeshPacket *)∓ - LOG_DEBUG("encrypted message\n"); - } else if (mp_decoded.which_payload_variant == - meshtastic_MeshPacket_decoded_tag) { // Don't upload a still-encrypted PKI packet + env->packet = (meshtastic_MeshPacket *)&mp_encrypted; + LOG_DEBUG("encrypted message"); + } else if (mp_decoded.which_payload_variant == meshtastic_MeshPacket_decoded_tag) { env->packet = (meshtastic_MeshPacket *)&mp_decoded; - LOG_DEBUG("portnum %i message\n", env->packet->decoded.portnum); + LOG_DEBUG("portnum %i message", env->packet->decoded.portnum); + } else { + LOG_DEBUG("nothing, pkt not decrypted"); + return; // Don't upload a still-encrypted PKI packet if not encryption_enabled } if (moduleConfig.mqtt.proxy_to_client_enabled || this->isConnectedDirectly()) { size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_ServiceEnvelope_msg, env); std::string topic = cryptTopic + channelId + "/" + owner.id; - LOG_DEBUG("MQTT Publish %s, %u bytes\n", topic.c_str(), numBytes); + LOG_DEBUG("MQTT Publish %s, %u bytes", topic.c_str(), numBytes); publish(topic.c_str(), bytes, numBytes, false); -#ifndef ARCH_NRF52 // JSON is not supported on nRF52, see issue #2804 +#if !defined(ARCH_NRF52) || \ + defined(NRF52_USE_JSON) // JSON is not supported on nRF52, see issue #2804 ### Fixed by using ArduinoJson ### if (moduleConfig.mqtt.json_enabled) { // handle json topic auto jsonString = MeshPacketSerializer::JsonSerialize((meshtastic_MeshPacket *)&mp_decoded); if (jsonString.length() != 0) { std::string topicJson = jsonTopic + channelId + "/" + owner.id; - LOG_INFO("JSON publish message to %s, %u bytes: %s\n", topicJson.c_str(), jsonString.length(), + LOG_INFO("JSON publish message to %s, %u bytes: %s", topicJson.c_str(), jsonString.length(), jsonString.c_str()); publish(topicJson.c_str(), jsonString.c_str(), false); } } -#endif // ARCH_NRF52 +#endif // ARCH_NRF52 NRF52_USE_JSON } else { - LOG_INFO("MQTT not connected, queueing packet\n"); + LOG_INFO("MQTT not connected, queueing packet"); if (mqttQueue.numFree() == 0) { - LOG_WARN("NOTE: MQTT queue is full, discarding oldest\n"); + LOG_WARN("NOTE: MQTT queue is full, discarding oldest"); meshtastic_ServiceEnvelope *d = mqttQueue.dequeuePtr(0); if (d) mqttPool.release(d); @@ -620,9 +630,9 @@ void MQTT::perhapsReportToMap() if (map_position_precision == 0 || (localPosition.latitude_i == 0 && localPosition.longitude_i == 0)) { last_report_to_map = millis(); if (map_position_precision == 0) - LOG_WARN("MQTT Map reporting is enabled, but precision is 0\n"); + LOG_WARN("MQTT Map reporting is enabled, but precision is 0"); if (localPosition.latitude_i == 0 && localPosition.longitude_i == 0) - LOG_WARN("MQTT Map reporting is enabled, but no position available.\n"); + LOG_WARN("MQTT Map reporting is enabled, but no position available."); return; } @@ -671,7 +681,7 @@ void MQTT::perhapsReportToMap() size_t numBytes = pb_encode_to_bytes(bytes, sizeof(bytes), &meshtastic_ServiceEnvelope_msg, se); - LOG_INFO("MQTT Publish map report to %s\n", mapTopic.c_str()); + LOG_INFO("MQTT Publish map report to %s", mapTopic.c_str()); publish(mapTopic.c_str(), bytes, numBytes, false); // Release the allocated memory for ServiceEnvelope and MeshPacket @@ -692,4 +702,70 @@ bool MQTT::isValidJsonEnvelope(JSONObject &json) (json["from"]->AsNumber() == nodeDB->getNodeNum()) && // only accept message if the "from" is us (json.find("type") != json.end()) && json["type"]->IsString() && // should specify a type (json.find("payload") != json.end()); // should have a payload +} + +bool MQTT::isPrivateIpAddress(const char address[]) +{ + // Min. length like 10.0.0.0 (8), max like 192.168.255.255:65535 (21) + size_t length = strlen(address); + if (length < 8 || length > 21) { + return false; + } + + // Ensure the address contains only digits and dots and maybe a colon. + // Some limited validation is done. + // Even if it's not a valid IP address, we will know it's not a domain. + bool hasColon = false; + int numDots = 0; + for (size_t i = 0; i < length; i++) { + if (!isdigit(address[i]) && address[i] != '.' && address[i] != ':') { + return false; + } + + // Dots can't be the first character, immediately follow another dot, + // occur more than 3 times, or occur after a colon. + if (address[i] == '.') { + if (++numDots > 3 || i == 0 || address[i - 1] == '.' || hasColon) { + return false; + } + } + // There can only be a single colon, and it can only occur after 3 dots + else if (address[i] == ':') { + if (hasColon || numDots < 3) { + return false; + } + + hasColon = true; + } + } + + // Final validation for IPv4 address and port format. + // Note that the values of octets haven't been tested, only the address format. + if (numDots != 3) { + return false; + } + + // Check the easy ones first. + if (strcmp(address, "127.0.0.1") == 0 || strncmp(address, "10.", 3) == 0 || strncmp(address, "192.168", 7) == 0 || + strncmp(address, "169.254", 7) == 0) { + return true; + } + + // See if it's definitely not a 172 address. + if (strncmp(address, "172", 3) != 0) { + return false; + } + + // We know it's a 172 address, now see if the second octet is 2 digits. + if (address[6] != '.') { + return false; + } + + // Copy the second octet into a secondary buffer we can null-terminate and parse. + char octet2[3]; + strncpy(octet2, address + 4, 2); + octet2[2] = 0; + + int octet2Num = atoi(octet2); + return octet2Num >= 16 && octet2Num <= 31; } \ No newline at end of file diff --git a/src/mqtt/MQTT.h b/src/mqtt/MQTT.h index c827e12ca6..fcefb94a2c 100644 --- a/src/mqtt/MQTT.h +++ b/src/mqtt/MQTT.h @@ -52,14 +52,14 @@ class MQTT : private concurrency::OSThread /** * Publish a packet on the global MQTT server. - * @param mp the encrypted packet to publish + * @param mp_encrypted the encrypted packet to publish * @param mp_decoded the decrypted packet to publish * @param chIndex the index of the channel for this message * * 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 - because no way to find a global channel ID. */ - void onSend(const meshtastic_MeshPacket &mp, const meshtastic_MeshPacket &mp_decoded, ChannelIndex chIndex); + void onSend(const meshtastic_MeshPacket &mp_encrypted, const meshtastic_MeshPacket &mp_decoded, ChannelIndex chIndex); /** Attempt to connect to server if necessary */ @@ -120,6 +120,10 @@ class MQTT : private concurrency::OSThread // returns true if this is a valid JSON envelope which we accept on downlink bool isValidJsonEnvelope(JSONObject &json); + /// Determines if the given address is a private IPv4 address, i.e. not routable on the public internet. + /// These are the ranges: 127.0.0.1, 10.0.0.0-10.255.255.255, 172.16.0.0-172.31.255.255, 192.168.0.0-192.168.255.255. + bool isPrivateIpAddress(const char address[]); + /// 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/nimble/NimbleBluetooth.cpp b/src/nimble/NimbleBluetooth.cpp index eedfe1a719..933d05dd1b 100644 --- a/src/nimble/NimbleBluetooth.cpp +++ b/src/nimble/NimbleBluetooth.cpp @@ -26,7 +26,7 @@ class BluetoothPhoneAPI : public PhoneAPI { PhoneAPI::onNowHasData(fromRadioNum); - LOG_INFO("BLE notify fromNum\n"); + LOG_INFO("BLE notify fromNum"); uint8_t val[4]; put_le32(val, fromRadioNum); @@ -51,15 +51,15 @@ class NimbleBluetoothToRadioCallback : public NimBLECharacteristicCallbacks { virtual void onWrite(NimBLECharacteristic *pCharacteristic) { - LOG_INFO("To Radio onwrite\n"); + LOG_INFO("To Radio onwrite"); auto val = pCharacteristic->getValue(); if (memcmp(lastToRadio, val.data(), val.length()) != 0) { - LOG_DEBUG("New ToRadio packet\n"); + LOG_DEBUG("New ToRadio packet"); memcpy(lastToRadio, val.data(), val.length()); bluetoothPhoneAPI->handleToRadio(val.data(), val.length()); } else { - LOG_DEBUG("Dropping duplicate ToRadio packet we just saw\n"); + LOG_DEBUG("Dropping duplicate ToRadio packet we just saw"); } } }; @@ -84,11 +84,11 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks uint32_t passkey = config.bluetooth.fixed_pin; if (config.bluetooth.mode == meshtastic_Config_BluetoothConfig_PairingMode_RANDOM_PIN) { - LOG_INFO("Using random passkey\n"); + LOG_INFO("Using random passkey"); // This is the passkey to be entered on peer - we pick a number >100,000 to ensure 6 digits passkey = random(100000, 999999); } - LOG_INFO("*** Enter passkey %d on the peer side ***\n", passkey); + LOG_INFO("*** Enter passkey %d on the peer side ***", passkey); powerFSM.trigger(EVENT_BLUETOOTH_PAIR); #if HAS_SCREEN @@ -125,7 +125,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks virtual void onAuthenticationComplete(ble_gap_conn_desc *desc) { - LOG_INFO("BLE authentication complete\n"); + LOG_INFO("BLE authentication complete"); if (passkeyShowing) { passkeyShowing = false; @@ -135,7 +135,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks virtual void onDisconnect(NimBLEServer *pServer, ble_gap_conn_desc *desc) { - LOG_INFO("BLE disconnect\n"); + LOG_INFO("BLE disconnect"); if (bluetoothPhoneAPI) { bluetoothPhoneAPI->close(); @@ -151,7 +151,7 @@ void NimbleBluetooth::shutdown() // No measurable power saving for ESP32 during light-sleep(?) #ifndef ARCH_ESP32 // Shutdown bluetooth for minimum power draw - LOG_INFO("Disable bluetooth\n"); + LOG_INFO("Disable bluetooth"); NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising(); pAdvertising->reset(); pAdvertising->stop(); @@ -162,7 +162,7 @@ void NimbleBluetooth::shutdown() void NimbleBluetooth::deinit() { #ifdef ARCH_ESP32 - LOG_INFO("Disable bluetooth until reboot\n"); + LOG_INFO("Disable bluetooth until reboot"); NimBLEDevice::deinit(); #endif } @@ -193,7 +193,7 @@ void NimbleBluetooth::setup() // Uncomment for testing // NimbleBluetooth::clearBonds(); - LOG_INFO("Initialise the NimBLE bluetooth module\n"); + LOG_INFO("Initialise the NimBLE bluetooth module"); NimBLEDevice::init(getDeviceName()); NimBLEDevice::setPower(ESP_PWR_LVL_P9); @@ -279,7 +279,7 @@ void updateBatteryLevel(uint8_t level) void NimbleBluetooth::clearBonds() { - LOG_INFO("Clearing bluetooth bonds!\n"); + LOG_INFO("Clearing bluetooth bonds!"); NimBLEDevice::deleteAllBonds(); } diff --git a/src/platform/esp32/ESP32CryptoEngine.cpp b/src/platform/esp32/ESP32CryptoEngine.cpp index 2301390363..b554a3de44 100644 --- a/src/platform/esp32/ESP32CryptoEngine.cpp +++ b/src/platform/esp32/ESP32CryptoEngine.cpp @@ -32,7 +32,7 @@ class ESP32CryptoEngine : public CryptoEngine sizeof(scratch) - numBytes); // Fill rest of buffer with zero (in case cypher looks at it) mbedtls_aes_crypt_ctr(&aes, numBytes, &nc_off, _nonce, stream_block, scratch, bytes); } else { - LOG_ERROR("Packet too large for crypto engine: %d. noop encryption!\n", numBytes); + LOG_ERROR("Packet too large for crypto engine: %d. noop encryption!", numBytes); } } } diff --git a/src/platform/esp32/SimpleAllocator.cpp b/src/platform/esp32/SimpleAllocator.cpp index 04ce35eb32..d482a3f1c8 100644 --- a/src/platform/esp32/SimpleAllocator.cpp +++ b/src/platform/esp32/SimpleAllocator.cpp @@ -12,7 +12,7 @@ void *SimpleAllocator::alloc(size_t size) assert(nextFree + size <= sizeof(bytes)); void *res = &bytes[nextFree]; nextFree += size; - LOG_DEBUG("Total simple allocs %u\n", nextFree); + LOG_DEBUG("Total simple allocs %u", nextFree); return res; } diff --git a/src/platform/esp32/architecture.h b/src/platform/esp32/architecture.h index 01f4166296..ba3050e9ab 100644 --- a/src/platform/esp32/architecture.h +++ b/src/platform/esp32/architecture.h @@ -104,6 +104,8 @@ #define HW_VENDOR meshtastic_HardwareModel_NANO_G1 #elif defined(M5STACK) #define HW_VENDOR meshtastic_HardwareModel_M5STACK +#elif defined(M5STACK_CORES3) +#define HW_VENDOR meshtastic_HardwareModel_M5STACK_CORES3 #elif defined(STATION_G1) #define HW_VENDOR meshtastic_HardwareModel_STATION_G1 #elif defined(DR_DEV) diff --git a/src/platform/esp32/main-esp32.cpp b/src/platform/esp32/main-esp32.cpp index f16accab64..7b3493f95b 100644 --- a/src/platform/esp32/main-esp32.cpp +++ b/src/platform/esp32/main-esp32.cpp @@ -76,17 +76,17 @@ void enableSlowCLK() uint32_t cal_32k = CALIBRATE_ONE(RTC_CAL_32K_XTAL); if (cal_32k == 0) { - LOG_DEBUG("32K XTAL OSC has not started up\n"); + LOG_DEBUG("32K XTAL OSC has not started up"); } else { rtc_clk_slow_freq_set(RTC_SLOW_FREQ_32K_XTAL); - LOG_DEBUG("Switching RTC Source to 32.768Khz succeeded, using 32K XTAL\n"); + LOG_DEBUG("Switching RTC Source to 32.768Khz succeeded, using 32K XTAL"); CALIBRATE_ONE(RTC_CAL_RTC_MUX); CALIBRATE_ONE(RTC_CAL_32K_XTAL); } 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"); + LOG_WARN("Failed to switch 32K XTAL RTC source to 32.768Khz !!! "); return; } } @@ -97,22 +97,22 @@ void esp32Setup() /* We explicitly don't want to do call randomSeed, // as that triggers the esp32 core to use a less secure pseudorandom function. uint32_t seed = esp_random(); - LOG_DEBUG("Setting random seed %u\n", seed); + LOG_DEBUG("Setting random seed %u", seed); randomSeed(seed); */ - LOG_DEBUG("Total heap: %d\n", ESP.getHeapSize()); - LOG_DEBUG("Free heap: %d\n", ESP.getFreeHeap()); - LOG_DEBUG("Total PSRAM: %d\n", ESP.getPsramSize()); - LOG_DEBUG("Free PSRAM: %d\n", ESP.getFreePsram()); + LOG_DEBUG("Total heap: %d", ESP.getHeapSize()); + LOG_DEBUG("Free heap: %d", ESP.getFreeHeap()); + LOG_DEBUG("Total PSRAM: %d", ESP.getPsramSize()); + LOG_DEBUG("Free PSRAM: %d", ESP.getFreePsram()); 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", nvs_stats.used_entries, nvs_stats.free_entries, + nvs_stats.total_entries, nvs_stats.namespace_count); - LOG_DEBUG("Setup Preferences in Flash Storage\n"); + LOG_DEBUG("Setup Preferences in Flash Storage"); // Create object to store our persistent data Preferences preferences; @@ -129,16 +129,16 @@ void esp32Setup() if (hwven != HW_VENDOR) preferences.putUInt("hwVendor", HW_VENDOR); preferences.end(); - LOG_DEBUG("Number of Device Reboots: %d\n", rebootCounter); + LOG_DEBUG("Number of Device Reboots: %d", rebootCounter); #if !MESHTASTIC_EXCLUDE_BLUETOOTH String BLEOTA = BleOta::getOtaAppVersion(); if (BLEOTA.isEmpty()) { - LOG_INFO("No OTA firmware available\n"); + LOG_INFO("No OTA firmware available"); } else { - LOG_INFO("OTA firmware version %s\n", BLEOTA.c_str()); + LOG_INFO("OTA firmware version %s", BLEOTA.c_str()); } #else - LOG_INFO("No OTA firmware available\n"); + LOG_INFO("No OTA firmware available"); #endif // enableModemSleep(); @@ -166,26 +166,6 @@ void esp32Setup() #endif } -#if 0 -// Turn off for now - -uint32_t axpDebugRead() -{ - axp.debugCharging(); - LOG_DEBUG("vbus current %f\n", axp.getVbusCurrent()); - LOG_DEBUG("charge current %f\n", axp.getBattChargeCurrent()); - LOG_DEBUG("bat voltage %f\n", axp.getBattVoltage()); - LOG_DEBUG("batt pct %d\n", axp.getBattPercentage()); - LOG_DEBUG("is battery connected %d\n", axp.isBatteryConnect()); - LOG_DEBUG("is USB connected %d\n", axp.isVBUSPlug()); - LOG_DEBUG("is charging %d\n", axp.isChargeing()); - - return 30 * 1000; -} - -Periodic axpDebugOutput(axpDebugRead); -#endif - /// loop code specific to ESP32 targets void esp32Loop() { @@ -263,4 +243,4 @@ void cpuDeepSleep(uint32_t msecToWake) esp_sleep_enable_timer_wakeup(msecToWake * 1000ULL); // call expects usecs esp_deep_sleep_start(); // TBD mA sleep current (battery) -} \ No newline at end of file +} diff --git a/src/platform/extra_variants/heltec_wireless_tracker/variant.cpp b/src/platform/extra_variants/heltec_wireless_tracker/variant.cpp index 0a19a9c3b3..12960e2d97 100644 --- a/src/platform/extra_variants/heltec_wireless_tracker/variant.cpp +++ b/src/platform/extra_variants/heltec_wireless_tracker/variant.cpp @@ -9,7 +9,7 @@ // Heltec tracker specific init void lateInitVariant() { - // LOG_DEBUG("Heltec tracker initVariant\n"); + // LOG_DEBUG("Heltec tracker initVariant"); #ifndef MESHTASTIC_EXCLUDE_GPS GpioVirtPin *virtGpsEnable = gps ? gps->enablePin : new GpioVirtPin(); diff --git a/src/platform/nrf52/NRF52Bluetooth.cpp b/src/platform/nrf52/NRF52Bluetooth.cpp index fbc0728d76..9326248808 100644 --- a/src/platform/nrf52/NRF52Bluetooth.cpp +++ b/src/platform/nrf52/NRF52Bluetooth.cpp @@ -39,7 +39,7 @@ class BluetoothPhoneAPI : public PhoneAPI { PhoneAPI::onNowHasData(fromRadioNum); - LOG_INFO("BLE notify fromNum\n"); + LOG_INFO("BLE notify fromNum"); fromNum.notify32(fromRadioNum); } @@ -60,7 +60,7 @@ void onConnect(uint16_t conn_handle) connectionHandle = conn_handle; char central_name[32] = {0}; connection->getPeerName(central_name, sizeof(central_name)); - LOG_INFO("BLE Connected to %s\n", central_name); + LOG_INFO("BLE Connected to %s", central_name); } /** * Callback invoked when a connection is dropped @@ -69,7 +69,7 @@ void onConnect(uint16_t conn_handle) */ void onDisconnect(uint16_t conn_handle, uint8_t reason) { - LOG_INFO("BLE Disconnected, reason = 0x%x\n", reason); + LOG_INFO("BLE Disconnected, reason = 0x%x", reason); if (bluetoothPhoneAPI) { bluetoothPhoneAPI->close(); } @@ -77,7 +77,7 @@ void onDisconnect(uint16_t conn_handle, uint8_t reason) void onCccd(uint16_t conn_hdl, BLECharacteristic *chr, uint16_t cccd_value) { // Display the raw request packet - LOG_INFO("CCCD Updated: %u\n", cccd_value); + LOG_INFO("CCCD Updated: %u", cccd_value); // Check the characteristic this CCCD update is associated with in case // this handler is used for multiple CCCD records. @@ -87,9 +87,9 @@ void onCccd(uint16_t conn_hdl, BLECharacteristic *chr, uint16_t cccd_value) if (chr->uuid == fromNum.uuid || chr->uuid == logRadio.uuid) { auto result = cccd_value == 2 ? chr->indicateEnabled(conn_hdl) : chr->notifyEnabled(conn_hdl); if (result) { - LOG_INFO("Notify/Indicate enabled\n"); + LOG_INFO("Notify/Indicate enabled"); } else { - LOG_INFO("Notify/Indicate disabled\n"); + LOG_INFO("Notify/Indicate disabled"); } } } @@ -137,7 +137,7 @@ void onFromRadioAuthorize(uint16_t conn_hdl, BLECharacteristic *chr, ble_gatts_e // or make empty if the queue is empty fromRadio.write(fromRadioBytes, numBytes); } else { - // LOG_INFO("Ignoring successor read\n"); + // LOG_INFO("Ignoring successor read"); } authorizeRead(conn_hdl); } @@ -146,13 +146,13 @@ static uint8_t lastToRadio[MAX_TO_FROM_RADIO_SIZE]; void onToRadioWrite(uint16_t conn_hdl, BLECharacteristic *chr, uint8_t *data, uint16_t len) { - LOG_INFO("toRadioWriteCb data %p, len %u\n", data, len); + LOG_INFO("toRadioWriteCb data %p, len %u", data, len); if (memcmp(lastToRadio, data, len) != 0) { - LOG_DEBUG("New ToRadio packet\n"); + LOG_DEBUG("New ToRadio packet"); memcpy(lastToRadio, data, len); bluetoothPhoneAPI->handleToRadio(data, len); } else { - LOG_DEBUG("Dropping duplicate ToRadio packet we just saw\n"); + LOG_DEBUG("Dropping duplicate ToRadio packet we just saw"); } } @@ -207,11 +207,11 @@ static uint32_t configuredPasskey; void NRF52Bluetooth::shutdown() { // Shutdown bluetooth for minimum power draw - LOG_INFO("Disable NRF52 bluetooth\n"); + LOG_INFO("Disable NRF52 bluetooth"); uint8_t connection_num = Bluefruit.connected(); if (connection_num) { for (uint8_t i = 0; i < connection_num; i++) { - LOG_INFO("NRF52 bluetooth disconnecting handle %d\n", i); + LOG_INFO("NRF52 bluetooth disconnecting handle %d", i); Bluefruit.disconnect(i); } delay(100); // wait for ondisconnect; @@ -225,7 +225,7 @@ void NRF52Bluetooth::startDisabled() // Shutdown bluetooth for minimum power draw Bluefruit.Advertising.stop(); Bluefruit.setTxPower(-40); // Minimum power - LOG_INFO("Disabling NRF52 Bluetooth. (Workaround: tx power min, advertising stopped)\n"); + LOG_INFO("Disabling NRF52 Bluetooth. (Workaround: tx power min, advertising stopped)"); } bool NRF52Bluetooth::isConnected() { @@ -238,7 +238,7 @@ int NRF52Bluetooth::getRssi() void NRF52Bluetooth::setup() { // Initialise the Bluefruit module - LOG_INFO("Initialize the Bluefruit nRF52 module\n"); + LOG_INFO("Initialize the Bluefruit nRF52 module"); Bluefruit.autoConnLed(false); Bluefruit.configPrphBandwidth(BANDWIDTH_MAX); Bluefruit.begin(); @@ -251,7 +251,7 @@ void NRF52Bluetooth::setup() ? config.bluetooth.fixed_pin : random(100000, 999999); auto pinString = std::to_string(configuredPasskey); - LOG_INFO("Bluetooth pin set to '%i'\n", configuredPasskey); + LOG_INFO("Bluetooth pin set to '%i'", configuredPasskey); Bluefruit.Security.setPIN(pinString.c_str()); Bluefruit.Security.setIOCaps(true, false, false); Bluefruit.Security.setPairPasskeyCallback(NRF52Bluetooth::onPairingPasskey); @@ -275,22 +275,22 @@ void NRF52Bluetooth::setup() bledfusecure.begin(); // Install the DFU helper #endif // Configure and Start the Device Information Service - LOG_INFO("Configuring the Device Information Service\n"); + LOG_INFO("Configuring the Device Information Service"); bledis.setModel(optstr(HW_VERSION)); bledis.setFirmwareRev(optstr(APP_VERSION)); bledis.begin(); // Start the BLE Battery Service and set it to 100% - LOG_INFO("Configuring the Battery Service\n"); + LOG_INFO("Configuring the Battery Service"); 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"); + LOG_INFO("Configuring the Mesh bluetooth service"); setupMeshService(); // Setup the advertising packet(s) - LOG_INFO("Setting up the advertising payload(s)\n"); + LOG_INFO("Setting up the advertising payload(s)"); startAdv(); - LOG_INFO("Advertising\n"); + LOG_INFO("Advertising"); } void NRF52Bluetooth::resumeAdvertising() { @@ -306,7 +306,7 @@ void updateBatteryLevel(uint8_t level) } void NRF52Bluetooth::clearBonds() { - LOG_INFO("Clearing bluetooth bonds!\n"); + LOG_INFO("Clearing bluetooth bonds!"); bond_print_list(BLE_GAP_ROLE_PERIPH); bond_print_list(BLE_GAP_ROLE_CENTRAL); Bluefruit.Periph.clearBonds(); @@ -314,12 +314,13 @@ void NRF52Bluetooth::clearBonds() } void NRF52Bluetooth::onConnectionSecured(uint16_t conn_handle) { - LOG_INFO("BLE connection secured\n"); + LOG_INFO("BLE connection secured"); } 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", passkey, passkey + 3); powerFSM.trigger(EVENT_BLUETOOTH_PAIR); +#if !defined(MESHTASTIC_EXCLUDE_SCREEN) screen->startAlert([](OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) -> void { char btPIN[16] = "888888"; snprintf(btPIN, sizeof(btPIN), "%06u", configuredPasskey); @@ -345,6 +346,7 @@ bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passke y_offset = display->height() == 64 ? y_offset + FONT_HEIGHT_LARGE - 6 : y_offset + FONT_HEIGHT_LARGE + 5; display->drawString(x_offset + x, y_offset + y, deviceName); }); +#endif if (match_request) { uint32_t start_time = millis(); while (millis() < start_time + 30000) { @@ -352,15 +354,15 @@ bool NRF52Bluetooth::onPairingPasskey(uint16_t conn_handle, uint8_t const passke break; } } - LOG_INFO("BLE passkey pairing: match_request=%i\n", match_request); + LOG_INFO("BLE passkey pairing: match_request=%i", match_request); return true; } void NRF52Bluetooth::onPairingCompleted(uint16_t conn_handle, uint8_t auth_status) { if (auth_status == BLE_GAP_SEC_STATUS_SUCCESS) - LOG_INFO("BLE pairing success\n"); + LOG_INFO("BLE pairing success"); else - LOG_INFO("BLE pairing failed\n"); + LOG_INFO("BLE pairing failed"); screen->endAlert(); } diff --git a/src/platform/nrf52/main-nrf52.cpp b/src/platform/nrf52/main-nrf52.cpp index 4023a3cb96..72a223c44f 100644 --- a/src/platform/nrf52/main-nrf52.cpp +++ b/src/platform/nrf52/main-nrf52.cpp @@ -35,7 +35,7 @@ bool loopCanSleep() // handle standard gcc assert failures void __attribute__((noreturn)) __assert_func(const char *file, int line, const char *func, const char *failedexpr) { - LOG_ERROR("assert failed %s: %d, %s, test=%s\n", file, line, func, failedexpr); + LOG_ERROR("assert failed %s: %d, %s, test=%s", file, line, func, failedexpr); // debugger_break(); FIXME doesn't work, possibly not for segger // Reboot cpu NVIC_SystemReset(); @@ -74,7 +74,7 @@ void setBluetoothEnable(bool enable) // For debugging use: don't use bluetooth if (!useSoftDevice) { if (enable) - LOG_INFO("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING\n"); + LOG_INFO("DISABLING NRF52 BLUETOOTH WHILE DEBUGGING"); return; } @@ -97,7 +97,7 @@ void setBluetoothEnable(bool enable) // If not yet set-up if (!nrf52Bluetooth) { - LOG_DEBUG("Initializing NRF52 Bluetooth\n"); + LOG_DEBUG("Initializing NRF52 Bluetooth"); nrf52Bluetooth = new NRF52Bluetooth(); nrf52Bluetooth->setup(); @@ -141,7 +141,7 @@ void checkSDEvents() break; default: - LOG_DEBUG("Unexpected SDevt %d\n", evt); + LOG_DEBUG("Unexpected SDevt %d", evt); break; } } @@ -188,7 +188,7 @@ void nrf52Setup() uint32_t why = NRF_POWER->RESETREAS; // per // https://infocenter.nordicsemi.com/index.jsp?topic=%2Fcom.nordic.infocenter.nrf52832.ps.v1.1%2Fpower.html - LOG_DEBUG("Reset reason: 0x%x\n", why); + LOG_DEBUG("Reset reason: 0x%x", why); #ifdef USE_SEMIHOSTING nrf52InitSemiHosting(); @@ -202,7 +202,7 @@ void nrf52Setup() #ifdef BQ25703A_ADDR auto *bq = new BQ25713(); if (!bq->setup()) - LOG_ERROR("ERROR! Charge controller init failed\n"); + LOG_ERROR("ERROR! Charge controller init failed"); #endif // Init random seed @@ -212,7 +212,7 @@ void nrf52Setup() } seed; nRFCrypto.begin(); nRFCrypto.Random.generate(seed.seed8, sizeof(seed.seed8)); - LOG_DEBUG("Setting random seed %u\n", seed.seed32); + LOG_DEBUG("Setting random seed %u", seed.seed32); randomSeed(seed.seed32); nRFCrypto.end(); } @@ -270,12 +270,17 @@ void cpuDeepSleep(uint32_t msecToWake) delay(msecToWake); NVIC_SystemReset(); } else { + // Resume on user button press + // https://github.com/lyusupov/SoftRF/blob/81c519ca75693b696752235d559e881f2e0511ee/software/firmware/source/SoftRF/src/platform/nRF52.cpp#L1738 + constexpr uint32_t DFU_MAGIC_SKIP = 0x6d; + sd_power_gpregret_set(0, DFU_MAGIC_SKIP); // Equivalent NRF_POWER->GPREGRET = DFU_MAGIC_SKIP + // FIXME, use system off mode with ram retention for key state? // FIXME, use non-init RAM per // https://devzone.nordicsemi.com/f/nordic-q-a/48919/ram-retention-settings-with-softdevice-enabled auto ok = sd_power_system_off(); if (ok != NRF_SUCCESS) { - LOG_ERROR("FIXME: Ignoring soft device (EasyDMA pending?) and forcing system-off!\n"); + LOG_ERROR("FIXME: Ignoring soft device (EasyDMA pending?) and forcing system-off!"); NRF_POWER->SYSTEMOFF = 1; } } diff --git a/src/platform/portduino/SimRadio.cpp b/src/platform/portduino/SimRadio.cpp index 12757fe6ba..840a0f5bac 100644 --- a/src/platform/portduino/SimRadio.cpp +++ b/src/platform/portduino/SimRadio.cpp @@ -22,7 +22,7 @@ ErrorCode SimRadio::send(meshtastic_MeshPacket *p) // 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"); + LOG_DEBUG("Set random delay before transmitting."); setTransmitDelay(); return res; } @@ -42,7 +42,7 @@ void SimRadio::setTransmitDelay() 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); + LOG_DEBUG("rx_snr found. hop_limit:%d rx_snr:%f", p->hop_limit, p->rx_snr); startTransmitTimerSNR(p->rx_snr); } } @@ -52,7 +52,7 @@ void SimRadio::startTransmitTimer(bool withDelay) // If we have work to do and the timer wasn't already scheduled, schedule it now if (!txQueue.empty()) { uint32_t delayMsec = !withDelay ? 1 : getTxDelayMsec(); - // LOG_DEBUG("xmit timer %d\n", delay); + // LOG_DEBUG("xmit timer %d", delay); notifyLater(delayMsec, TRANSMIT_DELAY_COMPLETED, false); } } @@ -62,7 +62,7 @@ void SimRadio::startTransmitTimerSNR(float snr) // If we have work to do and the timer wasn't already scheduled, schedule it now if (!txQueue.empty()) { uint32_t delayMsec = getTxDelayMsecWeighted(snr); - // LOG_DEBUG("xmit timer %d\n", delay); + // LOG_DEBUG("xmit timer %d", delay); notifyLater(delayMsec, TRANSMIT_DELAY_COMPLETED, false); } } @@ -88,7 +88,7 @@ void SimRadio::completeSending() // We are done sending that packet, release it packetPool.release(p); - // LOG_DEBUG("Done with send\n"); + // LOG_DEBUG("Done with send"); } } @@ -103,9 +103,9 @@ bool SimRadio::canSendImmediately() if (busyTx || busyRx) { if (busyTx) - LOG_WARN("Can not send yet, busyTx\n"); + LOG_WARN("Can not send yet, busyTx"); if (busyRx) - LOG_WARN("Can not send yet, busyRx\n"); + LOG_WARN("Can not send yet, busyRx"); return false; } else return true; @@ -129,7 +129,7 @@ bool SimRadio::cancelSending(NodeNum from, PacketId id) packetPool.release(p); // free the packet we just removed bool result = (p != NULL); - LOG_DEBUG("cancelSending id=0x%x, removed=%d\n", id, result); + LOG_DEBUG("cancelSending id=0x%x, removed=%d", id, result); return result; } @@ -138,25 +138,25 @@ void SimRadio::onNotify(uint32_t notification) switch (notification) { case ISR_TX: handleTransmitInterrupt(); - // LOG_DEBUG("tx complete - starting timer\n"); + // LOG_DEBUG("tx complete - starting timer"); startTransmitTimer(); break; case ISR_RX: - // LOG_DEBUG("rx complete - starting timer\n"); + // LOG_DEBUG("rx complete - starting timer"); startTransmitTimer(); break; case TRANSMIT_DELAY_COMPLETED: - LOG_DEBUG("delay done\n"); + LOG_DEBUG("delay done"); // 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"); + // LOG_DEBUG("Currently Rx/Tx-ing: set random delay"); 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"); + // LOG_DEBUG("Channel is active: set random delay"); setTransmitDelay(); // reset random delay } else { // Send any outgoing packets we have ready @@ -171,7 +171,7 @@ void SimRadio::onNotify(uint32_t notification) } } } else { - // LOG_DEBUG("done with txqueue\n"); + // LOG_DEBUG("done with txqueue"); } break; default: @@ -188,12 +188,12 @@ void SimRadio::startSend(meshtastic_MeshPacket *txp) perhapsDecode(p); 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); + // LOG_DEBUG("Sending back to simulator with portNum %d", 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; } else { - LOG_WARN("Payload size is larger than compressed message allows! Sending empty payload.\n"); + LOG_WARN("Payload size is larger than compressed message allows! Sending empty payload."); } p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &meshtastic_Compressed_msg, &c); @@ -225,11 +225,11 @@ meshtastic_QueueStatus SimRadio::getQueueStatus() void SimRadio::handleReceiveInterrupt(meshtastic_MeshPacket *p) { - LOG_DEBUG("HANDLE RECEIVE INTERRUPT\n"); + LOG_DEBUG("HANDLE RECEIVE INTERRUPT"); uint32_t xmitMsec; if (!isReceiving) { - LOG_DEBUG("*** WAS_ASSERT *** handleReceiveInterrupt called when not in receive mode\n"); + LOG_DEBUG("*** WAS_ASSERT *** handleReceiveInterrupt called when not in receive mode"); return; } @@ -238,7 +238,7 @@ void SimRadio::handleReceiveInterrupt(meshtastic_MeshPacket *p) // read the number of actually received bytes size_t length = getPacketLength(p); xmitMsec = getPacketTime(length); - // LOG_DEBUG("Payload size %d vs length (includes header) %d\n", p->decoded.payload.size, length); + // LOG_DEBUG("Payload size %d vs length (includes header) %d", p->decoded.payload.size, length); meshtastic_MeshPacket *mp = packetPool.allocCopy(*p); // keep a copy in packetPool diff --git a/src/platform/rp2xx0/hardware_rosc/include/hardware/rosc.h b/src/platform/rp2xx0/hardware_rosc/include/hardware/rosc.h new file mode 100644 index 0000000000..e1e014f33a --- /dev/null +++ b/src/platform/rp2xx0/hardware_rosc/include/hardware/rosc.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _HARDWARE_ROSC_H_ +#define _HARDWARE_ROSC_H_ + +#include "hardware/structs/rosc.h" +#include "pico.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file rosc.h + * \defgroup hardware_rosc hardware_rosc + * + * Ring Oscillator (ROSC) API + * + * A Ring Oscillator is an on-chip oscillator that requires no external crystal. Instead, the output is generated from a series of + * inverters that are chained together to create a feedback loop. RP2040 boots from the ring oscillator initially, meaning the + * first stages of the bootrom, including booting from SPI flash, will be clocked by the ring oscillator. If your design has a + * crystal oscillator, you’ll likely want to switch to this as your reference clock as soon as possible, because the frequency is + * more accurate than the ring oscillator. + */ + +/*! \brief Set frequency of the Ring Oscillator + * \ingroup hardware_rosc + * + * \param code The drive strengths. See the RP2040 datasheet for information on this value. + */ +void rosc_set_freq(uint32_t code); + +/*! \brief Set range of the Ring Oscillator + * \ingroup hardware_rosc + * + * Frequency range. Frequencies will vary with Process, Voltage & Temperature (PVT). + * Clock output will not glitch when changing the range up one step at a time. + * + * \param range 0x01 Low, 0x02 Medium, 0x03 High, 0x04 Too High. + */ +void rosc_set_range(uint range); + +/*! \brief Disable the Ring Oscillator + * \ingroup hardware_rosc + * + */ +void rosc_disable(void); + +/*! \brief Put Ring Oscillator in to dormant mode. + * \ingroup hardware_rosc + * + * The ROSC supports a dormant mode,which stops oscillation until woken up up by an asynchronous interrupt. + * This can either come from the RTC, being clocked by an external clock, or a GPIO pin going high or low. + * If no IRQ is configured before going into dormant mode the ROSC will never restart. + * + * PLLs should be stopped before selecting dormant mode. + */ +void rosc_set_dormant(void); + +// FIXME: Add doxygen + +uint32_t next_rosc_code(uint32_t code); + +uint rosc_find_freq(uint32_t low_mhz, uint32_t high_mhz); + +void rosc_set_div(uint32_t div); + +inline static void rosc_clear_bad_write(void) +{ + hw_clear_bits(&rosc_hw->status, ROSC_STATUS_BADWRITE_BITS); +} + +inline static bool rosc_write_okay(void) +{ + return !(rosc_hw->status & ROSC_STATUS_BADWRITE_BITS); +} + +inline static void rosc_write(io_rw_32 *addr, uint32_t value) +{ + rosc_clear_bad_write(); + assert(rosc_write_okay()); + *addr = value; + assert(rosc_write_okay()); +}; + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/src/platform/rp2xx0/hardware_rosc/rosc.c b/src/platform/rp2xx0/hardware_rosc/rosc.c new file mode 100644 index 0000000000..f79929f8d1 --- /dev/null +++ b/src/platform/rp2xx0/hardware_rosc/rosc.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "pico.h" + +// For MHZ definitions etc +#include "hardware/clocks.h" +#include "hardware/rosc.h" + +// Given a ROSC delay stage code, return the next-numerically-higher code. +// Top result bit is set when called on maximum ROSC code. +uint32_t next_rosc_code(uint32_t code) +{ + return ((code | 0x08888888u) + 1u) & 0xf7777777u; +} + +uint rosc_find_freq(uint32_t low_mhz, uint32_t high_mhz) +{ + // TODO: This could be a lot better + rosc_set_div(1); + for (uint32_t code = 0; code <= 0x77777777u; code = next_rosc_code(code)) { + rosc_set_freq(code); + uint rosc_mhz = frequency_count_khz(CLOCKS_FC0_SRC_VALUE_ROSC_CLKSRC) / 1000; + if ((rosc_mhz >= low_mhz) && (rosc_mhz <= high_mhz)) { + return rosc_mhz; + } + } + return 0; +} + +void rosc_set_div(uint32_t div) +{ + assert(div <= 31 && div >= 1); + rosc_write(&rosc_hw->div, ROSC_DIV_VALUE_PASS + div); +} + +void rosc_set_freq(uint32_t code) +{ + rosc_write(&rosc_hw->freqa, (ROSC_FREQA_PASSWD_VALUE_PASS << ROSC_FREQA_PASSWD_LSB) | (code & 0xffffu)); + rosc_write(&rosc_hw->freqb, (ROSC_FREQA_PASSWD_VALUE_PASS << ROSC_FREQA_PASSWD_LSB) | (code >> 16u)); +} + +void rosc_set_range(uint range) +{ + // Range should use enumvals from the headers and thus have the password correct + rosc_write(&rosc_hw->ctrl, (ROSC_CTRL_ENABLE_VALUE_ENABLE << ROSC_CTRL_ENABLE_LSB) | range); +} + +void rosc_disable(void) +{ + uint32_t tmp = rosc_hw->ctrl; + tmp &= (~ROSC_CTRL_ENABLE_BITS); + tmp |= (ROSC_CTRL_ENABLE_VALUE_DISABLE << ROSC_CTRL_ENABLE_LSB); + rosc_write(&rosc_hw->ctrl, tmp); + // Wait for stable to go away + while (rosc_hw->status & ROSC_STATUS_STABLE_BITS) + ; +} + +void rosc_set_dormant(void) +{ + // WARNING: This stops the rosc until woken up by an irq + rosc_write(&rosc_hw->dormant, ROSC_DORMANT_VALUE_DORMANT); + // Wait for it to become stable once woken up + while (!(rosc_hw->status & ROSC_STATUS_STABLE_BITS)) + ; +} \ No newline at end of file diff --git a/src/platform/rp2xx0/main-rp2xx0.cpp b/src/platform/rp2xx0/main-rp2xx0.cpp index 6306f34c11..a46b0face4 100644 --- a/src/platform/rp2xx0/main-rp2xx0.cpp +++ b/src/platform/rp2xx0/main-rp2xx0.cpp @@ -2,22 +2,71 @@ #include "hardware/xosc.h" #include #include +#include #include #include -#include void setBluetoothEnable(bool enable) { // not needed } +static bool awake; + +static void sleep_callback(void) +{ + awake = true; +} + +void epoch_to_datetime(time_t epoch, datetime_t *dt) +{ + struct tm *tm_info; + + tm_info = gmtime(&epoch); + dt->year = tm_info->tm_year; + dt->month = tm_info->tm_mon + 1; + dt->day = tm_info->tm_mday; + dt->dotw = tm_info->tm_wday; + dt->hour = tm_info->tm_hour; + dt->min = tm_info->tm_min; + dt->sec = tm_info->tm_sec; +} + +void debug_date(datetime_t t) +{ + LOG_DEBUG("%d %d %d %d %d %d %d", t.year, t.month, t.day, t.hour, t.min, t.sec, t.dotw); + uart_default_tx_wait_blocking(); +} + void cpuDeepSleep(uint32_t msecs) { - /* Disable both PLL to avoid power dissipation */ - pll_deinit(pll_sys); - pll_deinit(pll_usb); + + time_t seconds = (time_t)(msecs / 1000); + datetime_t t_init, t_alarm; + + awake = false; + // Start the RTC + rtc_init(); + epoch_to_datetime(0, &t_init); + rtc_set_datetime(&t_init); + epoch_to_datetime(seconds, &t_alarm); + // debug_date(t_init); + // debug_date(t_alarm); + uart_default_tx_wait_blocking(); + sleep_run_from_dormant_source(DORMANT_SOURCE_ROSC); + sleep_goto_sleep_until(&t_alarm, &sleep_callback); + + // Make sure we don't wake + while (!awake) { + delay(1); + } + + /* For now, I don't know how to revert this state + We just reboot in order to get back operational */ + rp2040.reboot(); + /* Set RP2040 in dormant mode. Will not wake up. */ - xosc_dormant(); + // xosc_dormant(); } void updateBatteryLevel(uint8_t level) @@ -54,15 +103,15 @@ void rp2040Setup() uint f_clk_adc = frequency_count_khz(CLOCKS_FC0_SRC_VALUE_CLK_ADC); uint f_clk_rtc = frequency_count_khz(CLOCKS_FC0_SRC_VALUE_CLK_RTC); - LOG_INFO("Clock speed:\n"); - LOG_INFO("pll_sys = %dkHz\n", f_pll_sys); - LOG_INFO("pll_usb = %dkHz\n", f_pll_usb); - LOG_INFO("rosc = %dkHz\n", f_rosc); - LOG_INFO("clk_sys = %dkHz\n", f_clk_sys); - LOG_INFO("clk_peri = %dkHz\n", f_clk_peri); - LOG_INFO("clk_usb = %dkHz\n", f_clk_usb); - LOG_INFO("clk_adc = %dkHz\n", f_clk_adc); - LOG_INFO("clk_rtc = %dkHz\n", f_clk_rtc); + LOG_INFO("Clock speed:"); + LOG_INFO("pll_sys = %dkHz", f_pll_sys); + LOG_INFO("pll_usb = %dkHz", f_pll_usb); + LOG_INFO("rosc = %dkHz", f_rosc); + LOG_INFO("clk_sys = %dkHz", f_clk_sys); + LOG_INFO("clk_peri = %dkHz", f_clk_peri); + LOG_INFO("clk_usb = %dkHz", f_clk_usb); + LOG_INFO("clk_adc = %dkHz", f_clk_adc); + LOG_INFO("clk_rtc = %dkHz", f_clk_rtc); #endif } diff --git a/src/platform/rp2xx0/pico_sleep/include/pico/sleep.h b/src/platform/rp2xx0/pico_sleep/include/pico/sleep.h new file mode 100644 index 0000000000..17dff24686 --- /dev/null +++ b/src/platform/rp2xx0/pico_sleep/include/pico/sleep.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _PICO_SLEEP_H_ +#define _PICO_SLEEP_H_ + +#include "hardware/rtc.h" +#include "pico.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file sleep.h + * \defgroup hardware_sleep hardware_sleep + * + * Lower Power Sleep API + * + * The difference between sleep and dormant is that ALL clocks are stopped in dormant mode, + * until the source (either xosc or rosc) is started again by an external event. + * In sleep mode some clocks can be left running controlled by the SLEEP_EN registers in the clocks + * block. For example you could keep clk_rtc running. Some destinations (proc0 and proc1 wakeup logic) + * can't be stopped in sleep mode otherwise there wouldn't be enough logic to wake up again. + * + * \subsection sleep_example Example + * \addtogroup hardware_sleep + * \include hello_sleep.c + + */ +typedef enum { DORMANT_SOURCE_NONE, DORMANT_SOURCE_XOSC, DORMANT_SOURCE_ROSC } dormant_source_t; + +/*! \brief Set all clock sources to the the dormant clock source to prepare for sleep. + * \ingroup hardware_sleep + * + * \param dormant_source The dormant clock source to use + */ +void sleep_run_from_dormant_source(dormant_source_t dormant_source); + +/*! \brief Set the dormant clock source to be the crystal oscillator + * \ingroup hardware_sleep + */ +static inline void sleep_run_from_xosc(void) +{ + sleep_run_from_dormant_source(DORMANT_SOURCE_XOSC); +} + +/*! \brief Set the dormant clock source to be the ring oscillator + * \ingroup hardware_sleep + */ +static inline void sleep_run_from_rosc(void) +{ + sleep_run_from_dormant_source(DORMANT_SOURCE_ROSC); +} + +/*! \brief Send system to sleep until the specified time + * \ingroup hardware_sleep + * + * One of the sleep_run_* functions must be called prior to this call + * + * \param t The time to wake up + * \param callback Function to call on wakeup. + */ +void sleep_goto_sleep_until(datetime_t *t, rtc_callback_t callback); + +/*! \brief Send system to sleep until the specified GPIO changes + * \ingroup hardware_sleep + * + * One of the sleep_run_* functions must be called prior to this call + * + * \param gpio_pin The pin to provide the wake up + * \param edge true for leading edge, false for trailing edge + * \param high true for active high, false for active low + */ +void sleep_goto_dormant_until_pin(uint gpio_pin, bool edge, bool high); + +/*! \brief Send system to sleep until a leading high edge is detected on GPIO + * \ingroup hardware_sleep + * + * One of the sleep_run_* functions must be called prior to this call + * + * \param gpio_pin The pin to provide the wake up + */ +static inline void sleep_goto_dormant_until_edge_high(uint gpio_pin) +{ + sleep_goto_dormant_until_pin(gpio_pin, true, true); +} + +/*! \brief Send system to sleep until a high level is detected on GPIO + * \ingroup hardware_sleep + * + * One of the sleep_run_* functions must be called prior to this call + * + * \param gpio_pin The pin to provide the wake up + */ +static inline void sleep_goto_dormant_until_level_high(uint gpio_pin) +{ + sleep_goto_dormant_until_pin(gpio_pin, false, true); +} + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/src/platform/rp2xx0/pico_sleep/sleep.c b/src/platform/rp2xx0/pico_sleep/sleep.c new file mode 100644 index 0000000000..65096be85c --- /dev/null +++ b/src/platform/rp2xx0/pico_sleep/sleep.c @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "pico.h" + +#include "pico/sleep.h" +#include "pico/stdlib.h" + +#include "hardware/clocks.h" +#include "hardware/pll.h" +#include "hardware/regs/io_bank0.h" +#include "hardware/rosc.h" +#include "hardware/rtc.h" +#include "hardware/xosc.h" +// For __wfi +#include "hardware/sync.h" +// For scb_hw so we can enable deep sleep +#include "hardware/structs/scb.h" +// when using old SDK this macro is not defined +#ifndef XOSC_HZ +#define XOSC_HZ 12000000u +#endif +// The difference between sleep and dormant is that ALL clocks are stopped in dormant mode, +// until the source (either xosc or rosc) is started again by an external event. +// In sleep mode some clocks can be left running controlled by the SLEEP_EN registers in the clocks +// block. For example you could keep clk_rtc running. Some destinations (proc0 and proc1 wakeup logic) +// can't be stopped in sleep mode otherwise there wouldn't be enough logic to wake up again. + +// TODO: Optionally, memories can also be powered down. + +static dormant_source_t _dormant_source; + +bool dormant_source_valid(dormant_source_t dormant_source) +{ + return (dormant_source == DORMANT_SOURCE_XOSC) || (dormant_source == DORMANT_SOURCE_ROSC); +} + +// In order to go into dormant mode we need to be running from a stoppable clock source: +// either the xosc or rosc with no PLLs running. This means we disable the USB and ADC clocks +// and all PLLs +void sleep_run_from_dormant_source(dormant_source_t dormant_source) +{ + assert(dormant_source_valid(dormant_source)); + _dormant_source = dormant_source; + + // FIXME: Just defining average rosc freq here. + uint src_hz = (dormant_source == DORMANT_SOURCE_XOSC) ? XOSC_HZ : 6.5 * MHZ; + uint clk_ref_src = (dormant_source == DORMANT_SOURCE_XOSC) ? CLOCKS_CLK_REF_CTRL_SRC_VALUE_XOSC_CLKSRC + : CLOCKS_CLK_REF_CTRL_SRC_VALUE_ROSC_CLKSRC_PH; + + // CLK_REF = XOSC or ROSC + clock_configure(clk_ref, clk_ref_src, + 0, // No aux mux + src_hz, src_hz); + + // CLK SYS = CLK_REF + clock_configure(clk_sys, CLOCKS_CLK_SYS_CTRL_SRC_VALUE_CLK_REF, + 0, // Using glitchless mux + src_hz, src_hz); + + // CLK USB = 0MHz + clock_stop(clk_usb); + + // CLK ADC = 0MHz + clock_stop(clk_adc); + + // CLK RTC = ideally XOSC (12MHz) / 256 = 46875Hz but could be rosc + uint clk_rtc_src = (dormant_source == DORMANT_SOURCE_XOSC) ? CLOCKS_CLK_RTC_CTRL_AUXSRC_VALUE_XOSC_CLKSRC + : CLOCKS_CLK_RTC_CTRL_AUXSRC_VALUE_ROSC_CLKSRC_PH; + + clock_configure(clk_rtc, + 0, // No GLMUX + clk_rtc_src, src_hz, 46875); + + // CLK PERI = clk_sys. Used as reference clock for Peripherals. No dividers so just select and enable + clock_configure(clk_peri, 0, CLOCKS_CLK_PERI_CTRL_AUXSRC_VALUE_CLK_SYS, src_hz, src_hz); + + pll_deinit(pll_sys); + pll_deinit(pll_usb); + + // Assuming both xosc and rosc are running at the moment + if (dormant_source == DORMANT_SOURCE_XOSC) { + // Can disable rosc + rosc_disable(); + } else { + // Can disable xosc + xosc_disable(); + } + + // Reconfigure uart with new clocks + /* This dones not work with our current core */ + // setup_default_uart(); +} + +// Go to sleep until woken up by the RTC +void sleep_goto_sleep_until(datetime_t *t, rtc_callback_t callback) +{ + // We should have already called the sleep_run_from_dormant_source function + assert(dormant_source_valid(_dormant_source)); + + // Turn off all clocks when in sleep mode except for RTC + clocks_hw->sleep_en0 = CLOCKS_SLEEP_EN0_CLK_RTC_RTC_BITS; + clocks_hw->sleep_en1 = 0x0; + + rtc_set_alarm(t, callback); + + uint save = scb_hw->scr; + // Enable deep sleep at the proc + scb_hw->scr = save | M0PLUS_SCR_SLEEPDEEP_BITS; + + // Go to sleep + __wfi(); +} + +static void _go_dormant(void) +{ + assert(dormant_source_valid(_dormant_source)); + + if (_dormant_source == DORMANT_SOURCE_XOSC) { + xosc_dormant(); + } else { + rosc_set_dormant(); + } +} + +void sleep_goto_dormant_until_pin(uint gpio_pin, bool edge, bool high) +{ + bool low = !high; + bool level = !edge; + + // Configure the appropriate IRQ at IO bank 0 + assert(gpio_pin < NUM_BANK0_GPIOS); + + uint32_t event = 0; + + if (level && low) + event = IO_BANK0_DORMANT_WAKE_INTE0_GPIO0_LEVEL_LOW_BITS; + if (level && high) + event = IO_BANK0_DORMANT_WAKE_INTE0_GPIO0_LEVEL_HIGH_BITS; + if (edge && high) + event = IO_BANK0_DORMANT_WAKE_INTE0_GPIO0_EDGE_HIGH_BITS; + if (edge && low) + event = IO_BANK0_DORMANT_WAKE_INTE0_GPIO0_EDGE_LOW_BITS; + + gpio_set_dormant_irq_enabled(gpio_pin, event, true); + + _go_dormant(); + // Execution stops here until woken up + + // Clear the irq so we can go back to dormant mode again if we want + gpio_acknowledge_irq(gpio_pin, event); +} \ No newline at end of file diff --git a/src/serialization/MeshPacketSerializer.cpp b/src/serialization/MeshPacketSerializer.cpp index acda94face..21fb377b2b 100644 --- a/src/serialization/MeshPacketSerializer.cpp +++ b/src/serialization/MeshPacketSerializer.cpp @@ -1,3 +1,4 @@ +#ifndef NRF52_USE_JSON #include "MeshPacketSerializer.h" #include "JSON.h" #include "NodeDB.h" @@ -25,7 +26,7 @@ std::string MeshPacketSerializer::JsonSerialize(const meshtastic_MeshPacket *mp, msgType = "text"; // convert bytes to string if (shouldLog) - LOG_DEBUG("got text message of size %u\n", mp->decoded.payload.size); + LOG_DEBUG("got text message of size %u", mp->decoded.payload.size); char payloadStr[(mp->decoded.payload.size) + 1]; memcpy(payloadStr, mp->decoded.payload.bytes, mp->decoded.payload.size); @@ -34,7 +35,7 @@ std::string MeshPacketSerializer::JsonSerialize(const meshtastic_MeshPacket *mp, JSONValue *json_value = JSON::Parse(payloadStr); if (json_value != NULL) { if (shouldLog) - LOG_INFO("text message payload is of type json\n"); + LOG_INFO("text message payload is of type json"); // if it is, then we can just use the json object jsonObj["payload"] = json_value; @@ -42,7 +43,7 @@ std::string MeshPacketSerializer::JsonSerialize(const meshtastic_MeshPacket *mp, // if it isn't, then we need to create a json object // with the string as the value if (shouldLog) - LOG_INFO("text message payload is of type plaintext\n"); + LOG_INFO("text message payload is of type plaintext"); msgPayload["text"] = new JSONValue(payloadStr); jsonObj["payload"] = new JSONValue(msgPayload); @@ -293,7 +294,7 @@ std::string MeshPacketSerializer::JsonSerialize(const meshtastic_MeshPacket *mp, break; } } else if (shouldLog) { - LOG_WARN("Couldn't convert encrypted payload of MeshPacket to JSON\n"); + LOG_WARN("Couldn't convert encrypted payload of MeshPacket to JSON"); } jsonObj["id"] = new JSONValue((unsigned int)mp->id); @@ -317,7 +318,7 @@ std::string MeshPacketSerializer::JsonSerialize(const meshtastic_MeshPacket *mp, std::string jsonStr = value->Stringify(); if (shouldLog) - LOG_INFO("serialized json message: %s\n", jsonStr.c_str()); + LOG_INFO("serialized json message: %s", jsonStr.c_str()); delete value; return jsonStr; @@ -353,4 +354,5 @@ std::string MeshPacketSerializer::JsonSerializeEncrypted(const meshtastic_MeshPa delete value; return jsonStr; -} \ No newline at end of file +} +#endif \ No newline at end of file diff --git a/src/serialization/MeshPacketSerializer.h b/src/serialization/MeshPacketSerializer.h index 989f30fc07..f248b2b762 100644 --- a/src/serialization/MeshPacketSerializer.h +++ b/src/serialization/MeshPacketSerializer.h @@ -2,7 +2,7 @@ #include static const char hexChars[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; -static const char *errStr = "Error decoding protobuf for %s message!\n"; +static const char *errStr = "Error decoding protobuf for %s message!"; class MeshPacketSerializer { diff --git a/src/serialization/MeshPacketSerializer_nRF52.cpp b/src/serialization/MeshPacketSerializer_nRF52.cpp new file mode 100644 index 0000000000..6e497f934d --- /dev/null +++ b/src/serialization/MeshPacketSerializer_nRF52.cpp @@ -0,0 +1,353 @@ +#ifdef NRF52_USE_JSON +#warning 'Using nRF52 Serializer' + +#include "ArduinoJson.h" +#include "MeshPacketSerializer.h" +#include "NodeDB.h" +#include "mesh/generated/meshtastic/mqtt.pb.h" +#include "mesh/generated/meshtastic/remote_hardware.pb.h" +#include "mesh/generated/meshtastic/telemetry.pb.h" +#include "modules/RoutingModule.h" +#include +#include + +StaticJsonDocument<1024> jsonObj; +StaticJsonDocument<1024> arrayObj; + +std::string MeshPacketSerializer::JsonSerialize(const meshtastic_MeshPacket *mp, bool shouldLog) +{ + // the created jsonObj is immutable after creation, so + // we need to do the heavy lifting before assembling it. + std::string msgType; + jsonObj.clear(); + arrayObj.clear(); + + if (mp->which_payload_variant == meshtastic_MeshPacket_decoded_tag) { + switch (mp->decoded.portnum) { + case meshtastic_PortNum_TEXT_MESSAGE_APP: { + msgType = "text"; + // convert bytes to string + if (shouldLog) + LOG_DEBUG("got text message of size %u", mp->decoded.payload.size); + + char payloadStr[(mp->decoded.payload.size) + 1]; + memcpy(payloadStr, mp->decoded.payload.bytes, mp->decoded.payload.size); + payloadStr[mp->decoded.payload.size] = 0; // null terminated string + // check if this is a JSON payload + StaticJsonDocument<512> text_doc; + DeserializationError error = deserializeJson(text_doc, payloadStr); + if (error) { + // if it isn't, then we need to create a json object + // with the string as the value + if (shouldLog) + LOG_INFO("text message payload is of type plaintext"); + jsonObj["payload"]["text"] = payloadStr; + } else { + // if it is, then we can just use the json object + if (shouldLog) + LOG_INFO("text message payload is of type json"); + jsonObj["payload"] = text_doc; + } + break; + } + case meshtastic_PortNum_TELEMETRY_APP: { + msgType = "telemetry"; + meshtastic_Telemetry scratch; + meshtastic_Telemetry *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_Telemetry_msg, &scratch)) { + decoded = &scratch; + if (decoded->which_variant == meshtastic_Telemetry_device_metrics_tag) { + jsonObj["payload"]["battery_level"] = (unsigned int)decoded->variant.device_metrics.battery_level; + jsonObj["payload"]["voltage"] = decoded->variant.device_metrics.voltage; + jsonObj["payload"]["channel_utilization"] = decoded->variant.device_metrics.channel_utilization; + jsonObj["payload"]["air_util_tx"] = decoded->variant.device_metrics.air_util_tx; + jsonObj["payload"]["uptime_seconds"] = (unsigned int)decoded->variant.device_metrics.uptime_seconds; + } else if (decoded->which_variant == meshtastic_Telemetry_environment_metrics_tag) { + jsonObj["payload"]["temperature"] = decoded->variant.environment_metrics.temperature; + jsonObj["payload"]["relative_humidity"] = decoded->variant.environment_metrics.relative_humidity; + jsonObj["payload"]["barometric_pressure"] = decoded->variant.environment_metrics.barometric_pressure; + jsonObj["payload"]["gas_resistance"] = decoded->variant.environment_metrics.gas_resistance; + jsonObj["payload"]["voltage"] = decoded->variant.environment_metrics.voltage; + jsonObj["payload"]["current"] = decoded->variant.environment_metrics.current; + jsonObj["payload"]["lux"] = decoded->variant.environment_metrics.lux; + jsonObj["payload"]["white_lux"] = decoded->variant.environment_metrics.white_lux; + jsonObj["payload"]["iaq"] = (uint)decoded->variant.environment_metrics.iaq; + jsonObj["payload"]["wind_speed"] = decoded->variant.environment_metrics.wind_speed; + jsonObj["payload"]["wind_direction"] = (uint)decoded->variant.environment_metrics.wind_direction; + jsonObj["payload"]["wind_gust"] = decoded->variant.environment_metrics.wind_gust; + jsonObj["payload"]["wind_lull"] = decoded->variant.environment_metrics.wind_lull; + } else if (decoded->which_variant == meshtastic_Telemetry_air_quality_metrics_tag) { + jsonObj["payload"]["pm10"] = (unsigned int)decoded->variant.air_quality_metrics.pm10_standard; + jsonObj["payload"]["pm25"] = (unsigned int)decoded->variant.air_quality_metrics.pm25_standard; + jsonObj["payload"]["pm100"] = (unsigned int)decoded->variant.air_quality_metrics.pm100_standard; + jsonObj["payload"]["pm10_e"] = (unsigned int)decoded->variant.air_quality_metrics.pm10_environmental; + jsonObj["payload"]["pm25_e"] = (unsigned int)decoded->variant.air_quality_metrics.pm25_environmental; + jsonObj["payload"]["pm100_e"] = (unsigned int)decoded->variant.air_quality_metrics.pm100_environmental; + } else if (decoded->which_variant == meshtastic_Telemetry_power_metrics_tag) { + jsonObj["payload"]["voltage_ch1"] = decoded->variant.power_metrics.ch1_voltage; + jsonObj["payload"]["current_ch1"] = decoded->variant.power_metrics.ch1_current; + jsonObj["payload"]["voltage_ch2"] = decoded->variant.power_metrics.ch2_voltage; + jsonObj["payload"]["current_ch2"] = decoded->variant.power_metrics.ch2_current; + jsonObj["payload"]["voltage_ch3"] = decoded->variant.power_metrics.ch3_voltage; + jsonObj["payload"]["current_ch3"] = decoded->variant.power_metrics.ch3_current; + } + } else if (shouldLog) { + LOG_ERROR("Error decoding protobuf for telemetry message!"); + return ""; + } + break; + } + case meshtastic_PortNum_NODEINFO_APP: { + msgType = "nodeinfo"; + meshtastic_User scratch; + meshtastic_User *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_User_msg, &scratch)) { + decoded = &scratch; + jsonObj["payload"]["id"] = decoded->id; + jsonObj["payload"]["longname"] = decoded->long_name; + jsonObj["payload"]["shortname"] = decoded->short_name; + jsonObj["payload"]["hardware"] = decoded->hw_model; + jsonObj["payload"]["role"] = (int)decoded->role; + } else if (shouldLog) { + LOG_ERROR("Error decoding protobuf for nodeinfo message!"); + return ""; + } + break; + } + case meshtastic_PortNum_POSITION_APP: { + msgType = "position"; + meshtastic_Position scratch; + meshtastic_Position *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_Position_msg, &scratch)) { + decoded = &scratch; + if ((int)decoded->time) { + jsonObj["payload"]["time"] = (unsigned int)decoded->time; + } + if ((int)decoded->timestamp) { + jsonObj["payload"]["timestamp"] = (unsigned int)decoded->timestamp; + } + jsonObj["payload"]["latitude_i"] = (int)decoded->latitude_i; + jsonObj["payload"]["longitude_i"] = (int)decoded->longitude_i; + if ((int)decoded->altitude) { + jsonObj["payload"]["altitude"] = (int)decoded->altitude; + } + if ((int)decoded->ground_speed) { + jsonObj["payload"]["ground_speed"] = (unsigned int)decoded->ground_speed; + } + if (int(decoded->ground_track)) { + jsonObj["payload"]["ground_track"] = (unsigned int)decoded->ground_track; + } + if (int(decoded->sats_in_view)) { + jsonObj["payload"]["sats_in_view"] = (unsigned int)decoded->sats_in_view; + } + if ((int)decoded->PDOP) { + jsonObj["payload"]["PDOP"] = (int)decoded->PDOP; + } + if ((int)decoded->HDOP) { + jsonObj["payload"]["HDOP"] = (int)decoded->HDOP; + } + if ((int)decoded->VDOP) { + jsonObj["payload"]["VDOP"] = (int)decoded->VDOP; + } + if ((int)decoded->precision_bits) { + jsonObj["payload"]["precision_bits"] = (int)decoded->precision_bits; + } + } else if (shouldLog) { + LOG_ERROR("Error decoding protobuf for position message!"); + return ""; + } + break; + } + case meshtastic_PortNum_WAYPOINT_APP: { + msgType = "position"; + meshtastic_Waypoint scratch; + meshtastic_Waypoint *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_Waypoint_msg, &scratch)) { + decoded = &scratch; + jsonObj["payload"]["id"] = (unsigned int)decoded->id; + jsonObj["payload"]["name"] = decoded->name; + jsonObj["payload"]["description"] = decoded->description; + jsonObj["payload"]["expire"] = (unsigned int)decoded->expire; + jsonObj["payload"]["locked_to"] = (unsigned int)decoded->locked_to; + jsonObj["payload"]["latitude_i"] = (int)decoded->latitude_i; + jsonObj["payload"]["longitude_i"] = (int)decoded->longitude_i; + } else if (shouldLog) { + LOG_ERROR("Error decoding protobuf for position message!"); + return ""; + } + break; + } + case meshtastic_PortNum_NEIGHBORINFO_APP: { + msgType = "neighborinfo"; + meshtastic_NeighborInfo scratch; + meshtastic_NeighborInfo *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_NeighborInfo_msg, + &scratch)) { + decoded = &scratch; + jsonObj["payload"]["node_id"] = (unsigned int)decoded->node_id; + jsonObj["payload"]["node_broadcast_interval_secs"] = (unsigned int)decoded->node_broadcast_interval_secs; + jsonObj["payload"]["last_sent_by_id"] = (unsigned int)decoded->last_sent_by_id; + jsonObj["payload"]["neighbors_count"] = decoded->neighbors_count; + + JsonObject neighbors_obj = arrayObj.to(); + JsonArray neighbors = neighbors_obj.createNestedArray("neighbors"); + JsonObject neighbors_0 = neighbors.createNestedObject(); + + for (uint8_t i = 0; i < decoded->neighbors_count; i++) { + neighbors_0["node_id"] = (unsigned int)decoded->neighbors[i].node_id; + neighbors_0["snr"] = (int)decoded->neighbors[i].snr; + neighbors[i + 1] = neighbors_0; + neighbors_0.clear(); + } + neighbors.remove(0); + jsonObj["payload"]["neighbors"] = neighbors; + } else if (shouldLog) { + LOG_ERROR("Error decoding protobuf for neighborinfo message!"); + return ""; + } + break; + } + case meshtastic_PortNum_TRACEROUTE_APP: { + if (mp->decoded.request_id) { // Only report the traceroute response + msgType = "traceroute"; + meshtastic_RouteDiscovery scratch; + meshtastic_RouteDiscovery *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_RouteDiscovery_msg, + &scratch)) { + decoded = &scratch; + JsonArray route = arrayObj.createNestedArray("route"); + + auto addToRoute = [](JsonArray *route, NodeNum num) { + char long_name[40] = "Unknown"; + meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(num); + bool name_known = node ? node->has_user : false; + if (name_known) + memcpy(long_name, node->user.long_name, sizeof(long_name)); + route->add(long_name); + }; + + addToRoute(&route, mp->to); // route.add(mp->to); + for (uint8_t i = 0; i < decoded->route_count; i++) { + addToRoute(&route, decoded->route[i]); // route.add(decoded->route[i]); + } + addToRoute(&route, + mp->from); // route.add(mp->from); // Ended at the original destination (source of response) + + jsonObj["payload"]["route"] = route; + } else if (shouldLog) { + LOG_ERROR("Error decoding protobuf for traceroute message!"); + return ""; + } + } else { + LOG_WARN("Traceroute response not reported"); + return ""; + } + break; + } + case meshtastic_PortNum_DETECTION_SENSOR_APP: { + msgType = "detection"; + char payloadStr[(mp->decoded.payload.size) + 1]; + memcpy(payloadStr, mp->decoded.payload.bytes, mp->decoded.payload.size); + payloadStr[mp->decoded.payload.size] = 0; // null terminated string + jsonObj["payload"]["text"] = payloadStr; + break; + } + case meshtastic_PortNum_REMOTE_HARDWARE_APP: { + meshtastic_HardwareMessage scratch; + meshtastic_HardwareMessage *decoded = NULL; + memset(&scratch, 0, sizeof(scratch)); + if (pb_decode_from_bytes(mp->decoded.payload.bytes, mp->decoded.payload.size, &meshtastic_HardwareMessage_msg, + &scratch)) { + decoded = &scratch; + if (decoded->type == meshtastic_HardwareMessage_Type_GPIOS_CHANGED) { + msgType = "gpios_changed"; + jsonObj["payload"]["gpio_value"] = (unsigned int)decoded->gpio_value; + } else if (decoded->type == meshtastic_HardwareMessage_Type_READ_GPIOS_REPLY) { + msgType = "gpios_read_reply"; + jsonObj["payload"]["gpio_value"] = (unsigned int)decoded->gpio_value; + jsonObj["payload"]["gpio_mask"] = (unsigned int)decoded->gpio_mask; + } + } else if (shouldLog) { + LOG_ERROR("Error decoding protobuf for RemoteHardware message!"); + return ""; + } + break; + } + // add more packet types here if needed + default: + LOG_WARN("Unsupported packet type %d", mp->decoded.portnum); + return ""; + break; + } + } else if (shouldLog) { + LOG_WARN("Couldn't convert encrypted payload of MeshPacket to JSON"); + return ""; + } + + jsonObj["id"] = (unsigned int)mp->id; + jsonObj["timestamp"] = (unsigned int)mp->rx_time; + jsonObj["to"] = (unsigned int)mp->to; + jsonObj["from"] = (unsigned int)mp->from; + jsonObj["channel"] = (unsigned int)mp->channel; + jsonObj["type"] = msgType.c_str(); + jsonObj["sender"] = owner.id; + if (mp->rx_rssi != 0) + jsonObj["rssi"] = (int)mp->rx_rssi; + if (mp->rx_snr != 0) + jsonObj["snr"] = (float)mp->rx_snr; + if (mp->hop_start != 0 && mp->hop_limit <= mp->hop_start) { + jsonObj["hops_away"] = (unsigned int)(mp->hop_start - mp->hop_limit); + jsonObj["hop_start"] = (unsigned int)(mp->hop_start); + } + + // serialize and write it to the stream + + // Serial.printf("serialized json message: \r"); + // serializeJson(jsonObj, Serial); + // Serial.println(""); + + std::string jsonStr = ""; + serializeJson(jsonObj, jsonStr); + + if (shouldLog) + LOG_INFO("serialized json message: %s", jsonStr.c_str()); + + return jsonStr; +} + +std::string MeshPacketSerializer::JsonSerializeEncrypted(const meshtastic_MeshPacket *mp) +{ + jsonObj.clear(); + jsonObj["id"] = (unsigned int)mp->id; + jsonObj["time_ms"] = (double)millis(); + jsonObj["timestamp"] = (unsigned int)mp->rx_time; + jsonObj["to"] = (unsigned int)mp->to; + jsonObj["from"] = (unsigned int)mp->from; + jsonObj["channel"] = (unsigned int)mp->channel; + jsonObj["want_ack"] = mp->want_ack; + + if (mp->rx_rssi != 0) + jsonObj["rssi"] = (int)mp->rx_rssi; + if (mp->rx_snr != 0) + jsonObj["snr"] = (float)mp->rx_snr; + if (mp->hop_start != 0 && mp->hop_limit <= mp->hop_start) { + jsonObj["hops_away"] = (unsigned int)(mp->hop_start - mp->hop_limit); + jsonObj["hop_start"] = (unsigned int)(mp->hop_start); + } + jsonObj["size"] = (unsigned int)mp->encrypted.size; + auto encryptedStr = bytesToHex(mp->encrypted.bytes, mp->encrypted.size); + jsonObj["bytes"] = encryptedStr.c_str(); + + // serialize and write it to the stream + std::string jsonStr = ""; + serializeJson(jsonObj, jsonStr); + + return jsonStr; +} +#endif \ No newline at end of file diff --git a/src/shutdown.h b/src/shutdown.h index 3f191eea88..4bf3036c02 100644 --- a/src/shutdown.h +++ b/src/shutdown.h @@ -12,7 +12,7 @@ void powerCommandsCheck() { if (rebootAtMsec && millis() > rebootAtMsec) { - LOG_INFO("Rebooting\n"); + LOG_INFO("Rebooting"); #if defined(ARCH_ESP32) ESP.restart(); #elif defined(ARCH_NRF52) @@ -28,11 +28,11 @@ void powerCommandsCheck() Serial1.end(); if (screen) delete screen; - LOG_DEBUG("final reboot!\n"); + LOG_DEBUG("final reboot!"); reboot(); #else rebootAtMsec = -1; - LOG_WARN("FIXME implement reboot for this platform. Note that some settings require a restart to be applied.\n"); + LOG_WARN("FIXME implement reboot for this platform. Note that some settings require a restart to be applied."); #endif } @@ -43,8 +43,8 @@ void powerCommandsCheck() #endif if (shutdownAtMsec && millis() > shutdownAtMsec) { - LOG_INFO("Shutting down from admin command\n"); -#if defined(ARCH_NRF52) || defined(ARCH_ESP32) + LOG_INFO("Shutting down from admin command"); +#if defined(ARCH_NRF52) || defined(ARCH_ESP32) || defined(ARCH_RP2040) playShutdownMelody(); power->shutdown(); #elif defined(ARCH_PORTDUINO) diff --git a/src/sleep.cpp b/src/sleep.cpp index 60f83f537b..3bc1042bb5 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -71,7 +71,7 @@ void setCPUFast(bool on) * (Added: Dec 23, 2021 by Jm Casler) */ #ifndef CONFIG_IDF_TARGET_ESP32C3 - LOG_DEBUG("Setting CPU to 240MHz because WiFi is in use.\n"); + LOG_DEBUG("Setting CPU to 240MHz because WiFi is in use."); setCpuFrequencyMhz(240); #endif return; @@ -134,13 +134,13 @@ void initDeepSleep() if (hwReason == TG1WDT_SYS_RESET) reason = "intWatchdog"; - LOG_INFO("Booted, wake cause %d (boot count %d), reset_reason=%s\n", wakeCause, bootCount, reason); + LOG_INFO("Booted, wake cause %d (boot count %d), reset_reason=%s", wakeCause, bootCount, reason); #endif #if SOC_RTCIO_HOLD_SUPPORTED // If waking from sleep, release any and all RTC GPIOs if (wakeCause != ESP_SLEEP_WAKEUP_UNDEFINED) { - LOG_DEBUG("Disabling any holds on RTC IO pads\n"); + LOG_DEBUG("Disabling any holds on RTC IO pads"); for (uint8_t i = 0; i <= GPIO_NUM_MAX; i++) { if (rtc_gpio_is_valid_gpio((gpio_num_t)i)) rtc_gpio_hold_dis((gpio_num_t)i); @@ -190,9 +190,9 @@ static void waitEnterSleep(bool skipPreflight = false) void doDeepSleep(uint32_t msecToWake, bool skipPreflight = false) { if (INCLUDE_vTaskSuspend && (msecToWake == portMAX_DELAY)) { - LOG_INFO("Entering deep sleep forever\n"); + LOG_INFO("Entering deep sleep forever"); } else { - LOG_INFO("Entering deep sleep for %u seconds\n", msecToWake / 1000); + LOG_INFO("Entering deep sleep for %u seconds", msecToWake / 1000); } // not using wifi yet, but once we are this is needed to shutoff the radio hw @@ -305,7 +305,7 @@ void doDeepSleep(uint32_t msecToWake, bool skipPreflight = false) PMU->disablePowerOutput(XPOWERS_LDO2); // lora radio power channel } if (msecToWake == portMAX_DELAY) { - LOG_INFO("PMU shutdown.\n"); + LOG_INFO("PMU shutdown."); console->flush(); PMU->shutdown(); } @@ -332,7 +332,7 @@ void doDeepSleep(uint32_t msecToWake, bool skipPreflight = false) */ esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more reasonable default { - // LOG_DEBUG("Enter light sleep\n"); + // LOG_DEBUG("Enter light sleep"); waitEnterSleep(false); @@ -387,19 +387,19 @@ esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more r #endif auto res = esp_sleep_enable_gpio_wakeup(); if (res != ESP_OK) { - LOG_ERROR("esp_sleep_enable_gpio_wakeup result %d\n", res); + LOG_ERROR("esp_sleep_enable_gpio_wakeup result %d", res); } assert(res == ESP_OK); res = esp_sleep_enable_timer_wakeup(sleepUsec); if (res != ESP_OK) { - LOG_ERROR("esp_sleep_enable_timer_wakeup result %d\n", res); + LOG_ERROR("esp_sleep_enable_timer_wakeup result %d", res); } assert(res == ESP_OK); console->flush(); res = esp_light_sleep_start(); if (res != ESP_OK) { - LOG_ERROR("esp_light_sleep_start result %d\n", res); + LOG_ERROR("esp_light_sleep_start result %d", res); } // commented out because it's not that crucial; // if it sporadically happens the node will go into light sleep during the next round @@ -429,12 +429,12 @@ esp_sleep_wakeup_cause_t doLightSleep(uint64_t sleepMsec) // FIXME, use a more r esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause(); #ifdef BUTTON_PIN if (cause == ESP_SLEEP_WAKEUP_GPIO) { - LOG_INFO("Exit light sleep gpio: btn=%d\n", + LOG_INFO("Exit light sleep gpio: btn=%d", !digitalRead(config.device.button_gpio ? config.device.button_gpio : BUTTON_PIN)); } else #endif { - LOG_INFO("Exit light sleep cause: %d\n", cause); + LOG_INFO("Exit light sleep cause: %d", cause); } return cause; @@ -470,7 +470,7 @@ void enableModemSleep() esp32_config.min_freq_mhz = 20; // 10Mhz is minimum recommended esp32_config.light_sleep_enable = false; int rv = esp_pm_configure(&esp32_config); - LOG_DEBUG("Sleep request result %x\n", rv); + LOG_DEBUG("Sleep request result %x", rv); } bool shouldLoraWake(uint32_t msecToWake) @@ -492,22 +492,22 @@ void enableLoraInterrupt() if (rtc_gpio_is_valid_gpio((gpio_num_t)LORA_DIO1)) { // Setup light/deep sleep with wakeup by external source - LOG_INFO("setup LORA_DIO1 (GPIO%02d) with wakeup by external source\n", LORA_DIO1); + LOG_INFO("setup LORA_DIO1 (GPIO%02d) with wakeup by external source", LORA_DIO1); esp_sleep_enable_ext0_wakeup((gpio_num_t)LORA_DIO1, HIGH); } else { - LOG_INFO("setup LORA_DIO1 (GPIO%02d) with wakeup by gpio interrupt\n", LORA_DIO1); + LOG_INFO("setup LORA_DIO1 (GPIO%02d) with wakeup by gpio interrupt", LORA_DIO1); gpio_wakeup_enable((gpio_num_t)LORA_DIO1, GPIO_INTR_HIGH_LEVEL); } #elif defined(LORA_DIO1) && (LORA_DIO1 != RADIOLIB_NC) if (radioType != RF95_RADIO) { - LOG_INFO("setup LORA_DIO1 (GPIO%02d) with wakeup by gpio interrupt\n", LORA_DIO1); + LOG_INFO("setup LORA_DIO1 (GPIO%02d) with wakeup by gpio interrupt", LORA_DIO1); gpio_wakeup_enable((gpio_num_t)LORA_DIO1, GPIO_INTR_HIGH_LEVEL); // SX126x/SX128x interrupt, active high } #endif #if defined(RF95_IRQ) && (RF95_IRQ != RADIOLIB_NC) if (radioType == RF95_RADIO) { - LOG_INFO("setup RF95_IRQ (GPIO%02d) with wakeup by gpio interrupt\n", RF95_IRQ); + LOG_INFO("setup RF95_IRQ (GPIO%02d) with wakeup by gpio interrupt", RF95_IRQ); gpio_wakeup_enable((gpio_num_t)RF95_IRQ, GPIO_INTR_HIGH_LEVEL); // RF95 interrupt, active high } #endif diff --git a/src/xmodem.cpp b/src/xmodem.cpp index de73e86684..9eef9690b8 100644 --- a/src/xmodem.cpp +++ b/src/xmodem.cpp @@ -97,7 +97,7 @@ void XModemAdapter::sendControl(meshtastic_XModem_Control c) { xmodemStore = meshtastic_XModem_init_zero; xmodemStore.control = c; - LOG_DEBUG("XModem: Notify Sending control %d.\n", c); + LOG_DEBUG("XModem: Notify Sending control %d.", c); packetReady.notifyObservers(packetno); } @@ -131,7 +131,7 @@ void XModemAdapter::handlePacket(meshtastic_XModem xmodemPacket) isReceiving = false; break; } else { // Transmit this file from Flash - LOG_INFO("XModem: Transmitting file %s\n", filename); + LOG_INFO("XModem: Transmitting file %s", filename); file = FSCom.open(filename, FILE_O_READ); if (file) { packetno = 1; @@ -141,7 +141,7 @@ void XModemAdapter::handlePacket(meshtastic_XModem xmodemPacket) 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); + LOG_DEBUG("XModem: STX Notify Sending packet %d, %d Bytes.", packetno, xmodemStore.buffer.size); if (xmodemStore.buffer.size < sizeof(meshtastic_XModem_buffer_t::bytes)) { isEOT = true; // send EOT on next Ack @@ -196,7 +196,7 @@ void XModemAdapter::handlePacket(meshtastic_XModem xmodemPacket) if (isEOT) { sendControl(meshtastic_XModem_Control_EOT); file.close(); - LOG_INFO("XModem: Finished sending file %s\n", filename); + LOG_INFO("XModem: Finished sending file %s", filename); isTransmitting = false; isEOT = false; break; @@ -208,7 +208,7 @@ void XModemAdapter::handlePacket(meshtastic_XModem xmodemPacket) 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); + LOG_DEBUG("XModem: ACK Notify Sending packet %d, %d Bytes.", packetno, xmodemStore.buffer.size); if (xmodemStore.buffer.size < sizeof(meshtastic_XModem_buffer_t::bytes)) { isEOT = true; // send EOT on next Ack @@ -225,7 +225,7 @@ void XModemAdapter::handlePacket(meshtastic_XModem xmodemPacket) if (--retrans <= 0) { sendControl(meshtastic_XModem_Control_CAN); file.close(); - LOG_INFO("XModem: Retransmit timeout, cancelling file %s\n", filename); + LOG_INFO("XModem: Retransmit timeout, cancelling file %s", filename); isTransmitting = false; break; } @@ -235,7 +235,7 @@ void XModemAdapter::handlePacket(meshtastic_XModem xmodemPacket) 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); + LOG_DEBUG("XModem: NAK Notify Sending packet %d, %d Bytes.", packetno, xmodemStore.buffer.size); if (xmodemStore.buffer.size < sizeof(meshtastic_XModem_buffer_t::bytes)) { isEOT = true; // send EOT on next Ack diff --git a/test/test_crypto/test_main.cpp b/test/test_crypto/test_main.cpp index cbe3660486..652d5dbcbc 100644 --- a/test/test_crypto/test_main.cpp +++ b/test/test_crypto/test_main.cpp @@ -111,7 +111,7 @@ void test_DH25519(void) void test_PKC_Decrypt(void) { uint8_t private_key[32]; - uint8_t public_key[32]; + meshtastic_UserLite_public_key_t public_key; uint8_t expected_shared[32]; uint8_t expected_decrypted[32]; uint8_t radioBytes[128] __attribute__((__aligned__)); @@ -119,7 +119,8 @@ void test_PKC_Decrypt(void) uint8_t expected_nonce[16]; uint32_t fromNode; - HexToBytes(public_key, "db18fc50eea47f00251cb784819a3cf5fc361882597f589f0d7ff820e8064457"); + HexToBytes(public_key.bytes, "db18fc50eea47f00251cb784819a3cf5fc361882597f589f0d7ff820e8064457"); + public_key.size = 32; HexToBytes(private_key, "a00330633e63522f8a4d81ec6d9d1e6617f6c8ffd3a4c698229537d44e522277"); HexToBytes(expected_shared, "777b1545c9d6f9a2"); HexToBytes(expected_decrypted, "08011204746573744800"); @@ -127,9 +128,9 @@ void test_PKC_Decrypt(void) HexToBytes(expected_nonce, "62d6b213036a792b2909000000"); fromNode = 0x0929; crypto->setDHPrivateKey(private_key); - TEST_ASSERT(crypto->setDHPublicKey(public_key)); - crypto->hash(crypto->shared_key, 32); - crypto->decryptCurve25519(fromNode, 0x13b2d662, 22, radioBytes + 16, decrypted); + // TEST_ASSERT(crypto->setDHPublicKey(public_key)); + // crypto->hash(crypto->shared_key, 32); + crypto->decryptCurve25519(fromNode, public_key, 0x13b2d662, 22, radioBytes + 16, decrypted); TEST_ASSERT_EQUAL_MEMORY(expected_shared, crypto->shared_key, 8); TEST_ASSERT_EQUAL_MEMORY(expected_nonce, crypto->nonce, 13); diff --git a/userPrefs.h b/userPrefs.h index ed622bcfbd..58a44fef07 100644 --- a/userPrefs.h +++ b/userPrefs.h @@ -26,6 +26,8 @@ */ // #define USERPREFS_CHANNEL_0_NAME "DEFCONnect" // #define USERPREFS_CHANNEL_0_PRECISION 14 +// #define USERPREFS_CHANNEL_0_UPLINK_ENABLED true +// #define USERPREFS_CHANNEL_0_DOWNLINK_ENABLED true /* #define USERPREFS_CHANNEL_1_PSK \ { \ @@ -35,6 +37,8 @@ */ // #define USERPREFS_CHANNEL_1_NAME "REPLACEME" // #define USERPREFS_CHANNEL_1_PRECISION 14 +// #define USERPREFS_CHANNEL_1_UPLINK_ENABLED true +// #define USERPREFS_CHANNEL_1_DOWNLINK_ENABLED true /* #define USERPREFS_CHANNEL_2_PSK \ { \ @@ -44,6 +48,8 @@ */ // #define USERPREFS_CHANNEL_2_NAME "REPLACEME" // #define USERPREFS_CHANNEL_2_PRECISION 14 +// #define USERPREFS_CHANNEL_2_UPLINK_ENABLED true +// #define USERPREFS_CHANNEL_2_DOWNLINK_ENABLED true // #define USERPREFS_CONFIG_OWNER_LONG_NAME "My Long Name" // #define USERPREFS_CONFIG_OWNER_SHORT_NAME "MLN" diff --git a/variants/betafpv_2400_tx_micro/variant.h b/variants/betafpv_2400_tx_micro/variant.h index fd06183ee1..67699e7c87 100644 --- a/variants/betafpv_2400_tx_micro/variant.h +++ b/variants/betafpv_2400_tx_micro/variant.h @@ -34,4 +34,4 @@ #define SX128X_TXEN 26 #define SX128X_RXEN 27 #define SX128X_RESET LORA_RESET -#define SX128X_MAX_POWER 13 \ No newline at end of file +#define SX128X_MAX_POWER 3 diff --git a/variants/diy/nrf52_promicro_diy_tcxo/variant.h b/variants/diy/nrf52_promicro_diy_tcxo/variant.h index 05d4a088c8..5c535ba1e8 100644 --- a/variants/diy/nrf52_promicro_diy_tcxo/variant.h +++ b/variants/diy/nrf52_promicro_diy_tcxo/variant.h @@ -22,26 +22,26 @@ extern "C" { /* NRF52 PRO MICRO PIN ASSIGNMENT -| Pin | Function | | Pin | Function | -|-------|------------|---|---------|-------------| -| Gnd | | | vbat | | -| P0.06 | Serial2 RX | | vbat | | -| P0.08 | Serial2 TX | | Gnd | | -| Gnd | | | reset | | -| Gnd | | | ext_vcc | *see 0.13 | -| P0.17 | RXEN | | P0.31 | BATTERY_PIN | -| P0.20 | GPS_RX | | P0.29 | BUSY | -| P0.22 | GPS_TX | | P0.02 | MISO | -| P0.24 | GPS_EN | | P1.15 | MOSI | -| P1.00 | BUTTON_PIN | | P1.13 | CS | -| P0.11 | SCL | | P1.11 | SCK | -| P1.04 | SDA | | P0.10 | DIO1/IRQ | -| P1.06 | Free pin | | P0.09 | RESET | -| | | | | | -| | Mid board | | | Internal | -| P1.01 | Free pin | | 0.15 | LED | -| P1.02 | Free pin | | 0.13 | 3V3_EN | -| P1.07 | Free pin | | | | +| Pin   | Function   |   | Pin     | Function     | RF95 | +| ----- | ----------- | --- | -------- | ------------ | ----- | +| Gnd   |             |   | vbat     |             | | +| P0.06 | Serial2 RX |   | vbat     |             | | +| P0.08 | Serial2 TX |   | Gnd     |             | | +| Gnd   |             |   | reset   |             | | +| Gnd   |             |   | ext_vcc | *see 0.13   | | +| P0.17 | RXEN       |   | P0.31   | BATTERY_PIN | | +| P0.20 | GPS_RX     |   | P0.29   | BUSY         | DIO0 | +| P0.22 | GPS_TX     |   | P0.02   | MISO | MISO | +| P0.24 | GPS_EN     |   | P1.15   | MOSI         | MOSI | +| P1.00 | BUTTON_PIN |   | P1.13   | CS           | CS   | +| P0.11 | SCL         |   | P1.11   | SCK         | SCK | +| P1.04 | SDA         |   | P0.10   | DIO1/IRQ     | DIO1 | +| P1.06 | Free pin   |   | P0.09   | RESET       | RST | +|       |             |   |         |             | | +|       | Mid board   |   |         | Internal     | | +| P1.01 | Free pin   |   | 0.15     | LED         | | +| P1.02 | Free pin   |   | 0.13     | 3V3_EN       | | +| P1.07 | Free pin   |   |         |             | | */ // Number of pins defined in PinDescription array @@ -112,13 +112,28 @@ NRF52 PRO MICRO PIN ASSIGNMENT #define PIN_SPI_MOSI (32 + 15) // P1.15 #define PIN_SPI_SCK (32 + 11) // P1.11 +#define LORA_MISO PIN_SPI_MISO +#define LORA_MOSI PIN_SPI_MOSI +#define LORA_SCK PIN_SPI_SCK +#define LORA_CS (32 + 13) // P1.13 + // LORA MODULES #define USE_LLCC68 #define USE_SX1262 -// #define USE_RF95 +#define USE_RF95 #define USE_SX1268 -// LORA CONFIG +// RF95 CONFIG + +#define LORA_DIO0 (0 + 29) // P0.10 IRQ +#define LORA_DIO1 (0 + 10) // P0.10 IRQ +#define LORA_RESET (0 + 9) // P0.09 + +// RX/TX for RFM95/SX127x +#define RF95_RXEN (0 + 17) // P0.17 +#define RF95_TXEN RADIOLIB_NC // Assuming that DIO2 is connected to TXEN pin. If not, TXEN must be connected. + +// SX126X CONFIG #define SX126X_CS (32 + 13) // P1.13 FIXME - we really should define LORA_CS instead #define SX126X_DIO1 (0 + 10) // P0.10 IRQ #define SX126X_DIO2_AS_RF_SWITCH // Note for E22 modules: DIO2 is not attached internally to TXEN for automatic TX/RX switching, @@ -134,18 +149,21 @@ NRF52 PRO MICRO PIN ASSIGNMENT On the SX1262, DIO3 sets the voltage for an external TCXO, if one is present. If one is not present, use TCXO_OPTIONAL to try both settings. -| Mfr | Module | TCXO | RF Switch | Notes | -| ---------- | ---------------- | ---- | --------- | -------------------------------------------- | -| Ebyte | E22-900M22S | Yes | Ext | | -| Ebyte | E22-900MM22S | No | Ext | | -| Ebyte | E22-900M30S | Yes | Ext | | -| Ebyte | E22-900M33S | Yes | Ext | MAX_POWER must be set to 8 for this | -| Ebyte | E220-900M22S | No | Ext | LLCC68, looks like DIO3 not connected at all | -| AI-Thinker | RA-01SH | No | Int | | -| Heltec | HT-RA62 | Yes | Int | | -| NiceRF | Lora1262 | yes | Int | | -| Waveshare | Core1262-HF | yes | Ext | | -| Waveshare | LoRa Node Module | yes | Int | | +| Mfr | Module | TCXO | RF Switch | Notes | +| ------------ | ---------------- | ---- | --------- | ------------------------------------- | +| Ebyte | E22-900M22S | Yes | Ext | | +| Ebyte | E22-900MM22S | No | Ext | | +| Ebyte | E22-900M30S | Yes | Ext | | +| Ebyte | E22-900M33S | Yes | Ext | MAX_POWER must be set to 8 for this | +| Ebyte | E220-900M22S | No | Ext | LLCC68, looks like DIO3 not connected | +| AI-Thinker | RA-01SH | No | Int | SX1262 | +| Heltec | HT-RA62 | Yes | Int | | +| NiceRF | Lora1262 | yes | Int | | +| Waveshare | Core1262-HF | yes | Ext | | +| Waveshare | LoRa Node Module | yes | Int | | +| Seeed | Wio-SX1262 | yes | Int | Sooooo cute! | +| AI-Thinker | RA-02 | No | Int | SX1278 **433mhz band only** | +| RF Solutions | RFM95 | No | Int | Untested | */ diff --git a/variants/dreamcatcher/platformio.ini b/variants/dreamcatcher/platformio.ini new file mode 100644 index 0000000000..46f9b9871b --- /dev/null +++ b/variants/dreamcatcher/platformio.ini @@ -0,0 +1,27 @@ +[env:dreamcatcher] ; 2301, latest revision +extends = esp32s3_base +board = esp32s3box +board_level = extra + +build_flags = + ${esp32s3_base.build_flags} + -D PRIVATE_HW + -D OTHERNET_DC_REV=2301 + -I variants/dreamcatcher + -DARDUINO_USB_CDC_ON_BOOT=1 + +lib_deps = ${esp32s3_base.lib_deps} + earlephilhower/ESP8266Audio@^1.9.7 + earlephilhower/ESP8266SAM@^1.0.1 + +[env:dreamcatcher-2206] +extends = esp32s3_base +board = esp32s3box +board_level = extra + +build_flags = + ${esp32s3_base.build_flags} + -D PRIVATE_HW + -D OTHERNET_DC_REV=2206 + -I variants/dreamcatcher + -DARDUINO_USB_CDC_ON_BOOT=1 \ No newline at end of file diff --git a/variants/dreamcatcher/rfswitch.h b/variants/dreamcatcher/rfswitch.h new file mode 100644 index 0000000000..74edb25d11 --- /dev/null +++ b/variants/dreamcatcher/rfswitch.h @@ -0,0 +1,17 @@ +#include "RadioLib.h" + +// RF Switch Matrix SubG RFO_HP_LF / RFO_LP_LF / RFI_[NP]_LF0 +// DIO5 -> RFSW0_V1 +// DIO6 -> RFSW1_V2 +// DIO7 -> ANT_CTRL_ON + ESP_IO9/LR_GPS_ANT_DC_EN -> RFI_GPS (Bias-T GPS) + +static const uint32_t rfswitch_dio_pins[] = {RADIOLIB_LR11X0_DIO5, RADIOLIB_LR11X0_DIO6, RADIOLIB_LR11X0_DIO7, RADIOLIB_NC, + RADIOLIB_NC}; + +static const Module::RfSwitchMode_t rfswitch_table[] = { + // mode DIO5 DIO6 DIO7 + {LR11x0::MODE_STBY, {LOW, LOW, LOW}}, {LR11x0::MODE_RX, {HIGH, LOW, LOW}}, + {LR11x0::MODE_TX, {LOW, HIGH, LOW}}, {LR11x0::MODE_TX_HP, {LOW, HIGH, LOW}}, + {LR11x0::MODE_TX_HF, {LOW, LOW, LOW}}, {LR11x0::MODE_GNSS, {LOW, LOW, HIGH}}, + {LR11x0::MODE_WIFI, {LOW, LOW, LOW}}, END_OF_MODE_TABLE, +}; \ No newline at end of file diff --git a/variants/dreamcatcher/variant.h b/variants/dreamcatcher/variant.h new file mode 100644 index 0000000000..eb95a95dde --- /dev/null +++ b/variants/dreamcatcher/variant.h @@ -0,0 +1,109 @@ +#undef I2C_SDA +#undef I2C_SCL +#define I2C_SDA 16 // I2C pins for this board +#define I2C_SCL 17 + +#define I2C_SDA1 45 +#define I2C_SCL1 46 + +#define LED_PIN 6 +#define LED_STATE_ON 1 +#define BUTTON_PIN 0 + +#define HAS_TPS65233 + +// V1 of SubG Switch SMA 0 or F Selector 1 +// #define RF_SW_SUBG1 8 +// V2 of SubG Switch SMA 1 or F Selector 0 +// #define RF_SW_SUBG2 5 + +#define RESET_OLED 8 // Emulate RF_SW_SUBG1, Use F Connector +#define VTFT_CTRL 5 // Emulate RF_SW_SUBG2, for SMA swap the pin values + +#if OTHERNET_DC_REV == 2206 +#define USE_LR1120 + +#define SPI_MISO 37 +#define SPI_MOSI 39 +#define SPI_SCK 38 +#define SDCARD_CS 40 + +#define PIN_BUZZER 48 + +// These can either be used for GPS or a serial link. Define through Protobufs +// #define GPS_RX_PIN 10 +// #define GPS_TX_PIN 21 + +#define PIN_POWER_EN 7 // RF section power supply enable +#define PERIPHERAL_WARMUP_MS 1000 // wait for TPS chip to initialize +#define TPS_EXTM 45 // connected, but not used +#define BIAS_T_ENABLE 9 // needs to be low +#define BIAS_T_VALUE 0 +#else // 2301 +#define USE_LR1121 +#define SPI_MISO 10 +#define SPI_MOSI 39 +#define SPI_SCK 38 + +#define SDCARD_CS 40 + +// This is only informational, we always use SD cards in 1 bit mode +#define SPI_DATA1 15 +#define SPI_DATA2 18 + +// These can either be used for GPS or a serial link. Define through Protobufs +// #define GPS_RX_PIN 36 +// #define GPS_TX_PIN 37 + +// dac / amp instead of buzzer +#define HAS_I2S +#define DAC_I2S_BCK 21 +#define DAC_I2S_WS 9 +#define DAC_I2S_DOUT 48 + +#define BIAS_T_ENABLE 7 // needs to be low +#define BIAS_T_VALUE 0 +#define BIAS_T_SUBGHZ 2 // also needs to be low, we hijack SENSOR_POWER_CTRL_PIN to emulate this +#define SENSOR_POWER_CTRL_PIN BIAS_T_SUBGHZ +#define SENSOR_POWER_ON 0 +#endif + +#define HAS_SDCARD // Have SPI interface SD card slot +#define SDCARD_USE_SPI1 + +#define LORA_RESET 3 +#define LORA_SCK 12 +#define LORA_MISO 13 +#define LORA_MOSI 11 +#define LORA_CS 14 +#define LORA_DIO9 4 +#define LORA_DIO2 47 + +#define LR1120_IRQ_PIN LORA_DIO9 +#define LR1120_NRESET_PIN LORA_RESET +#define LR1120_BUSY_PIN LORA_DIO2 +#define LR1120_SPI_NSS_PIN LORA_CS +#define LR1120_SPI_SCK_PIN LORA_SCK +#define LR1120_SPI_MOSI_PIN LORA_MOSI +#define LR1120_SPI_MISO_PIN LORA_MISO + +#define LR1121_IRQ_PIN LORA_DIO9 +#define LR1121_NRESET_PIN LORA_RESET +#define LR1121_BUSY_PIN LORA_DIO2 +#define LR1121_SPI_NSS_PIN LORA_CS +#define LR1121_SPI_SCK_PIN LORA_SCK +#define LR1121_SPI_MOSI_PIN LORA_MOSI +#define LR1121_SPI_MISO_PIN LORA_MISO + +#define LR11X0_DIO3_TCXO_VOLTAGE 1.8 +#define LR11X0_DIO_AS_RF_SWITCH + +// This board needs external switching between sub-GHz and 2.4G circuits + +// V1 of RF1 selector SubG 1 or 2.4GHz 0 +// #define RF_SW_SMA1 42 +// V2 of RF1 Selector SubG 0 or 2.4GHz 1 +// #define RF_SW_SMA2 41 + +#define LR11X0_RF_SWITCH_SUBGHZ 42 +#define LR11X0_RF_SWITCH_2_4GHZ 41 diff --git a/variants/heltec_v2.1/platformio.ini b/variants/heltec_v2.1/platformio.ini index 5aa04fc58a..ea22819117 100644 --- a/variants/heltec_v2.1/platformio.ini +++ b/variants/heltec_v2.1/platformio.ini @@ -1,4 +1,5 @@ [env:heltec-v2_1] +board_level = extra ;build_type = debug ; to make it possible to step through our jtag debugger extends = esp32_base board = heltec_wifi_lora_32_V2 diff --git a/variants/heltec_v2/platformio.ini b/variants/heltec_v2/platformio.ini index cee1537d03..c81bca8ba6 100644 --- a/variants/heltec_v2/platformio.ini +++ b/variants/heltec_v2/platformio.ini @@ -1,5 +1,6 @@ [env:heltec-v2_0] -;build_type = debug ; to make it possible to step through our jtag debugger +;build_type = debug ; to make it possible to step through our jtag debugger +board_level = extra extends = esp32_base board = heltec_wifi_lora_32_V2 build_flags = diff --git a/variants/m5stack_cores3/pins_arduino.h b/variants/m5stack_cores3/pins_arduino.h new file mode 100644 index 0000000000..78e9369907 --- /dev/null +++ b/variants/m5stack_cores3/pins_arduino.h @@ -0,0 +1,63 @@ +#ifndef Pins_Arduino_h +#define Pins_Arduino_h + +#include "soc/soc_caps.h" +#include + +#define USB_VID 0x303a +#define USB_PID 0x1001 + +// Some boards have too low voltage on this pin (board design bug) +// Use different pin with 3V and connect with 48 +// and change this setup for the chosen pin (for example 38) +static const uint8_t LED_BUILTIN = SOC_GPIO_PIN_COUNT + 48; +#define BUILTIN_LED LED_BUILTIN // backward compatibility +#define LED_BUILTIN LED_BUILTIN +#define RGB_BUILTIN LED_BUILTIN +#define RGB_BRIGHTNESS 64 + +static const uint8_t TX = 43; +static const uint8_t RX = 44; + +static const uint8_t TXD2 = 17; +static const uint8_t RXD2 = 18; + +static const uint8_t SDA = 12; +static const uint8_t SCL = 11; + +static const uint8_t SS = 15; +static const uint8_t MOSI = 37; +static const uint8_t MISO = 35; +static const uint8_t SCK = 36; + +static const uint8_t G0 = 0; +static const uint8_t G1 = 1; +static const uint8_t G2 = 2; +static const uint8_t G3 = 3; +static const uint8_t G4 = 4; +static const uint8_t G5 = 5; +static const uint8_t G6 = 6; +static const uint8_t G7 = 7; +static const uint8_t G8 = 8; +static const uint8_t G9 = 9; +static const uint8_t G11 = 11; +static const uint8_t G12 = 12; +static const uint8_t G13 = 13; +static const uint8_t G14 = 14; +static const uint8_t G17 = 17; +static const uint8_t G18 = 18; +static const uint8_t G19 = 19; +static const uint8_t G20 = 20; +static const uint8_t G21 = 21; +static const uint8_t G33 = 33; +static const uint8_t G34 = 34; +static const uint8_t G35 = 35; +static const uint8_t G36 = 36; +static const uint8_t G37 = 37; +static const uint8_t G38 = 38; +static const uint8_t G45 = 45; +static const uint8_t G46 = 46; + +static const uint8_t ADC = 10; + +#endif /* Pins_Arduino_h */ diff --git a/variants/m5stack_cores3/platformio.ini b/variants/m5stack_cores3/platformio.ini new file mode 100644 index 0000000000..fc73fabaea --- /dev/null +++ b/variants/m5stack_cores3/platformio.ini @@ -0,0 +1,14 @@ +; M5stack CoreS3 +[env:m5stack-cores3] +extends = esp32s3_base +board = m5stack-cores3 +board_check = true +upload_protocol = esptool + +build_flags = ${esp32_base.build_flags} + -DPRIVATE_HW + -DM5STACK_CORES3 + -Ivariants/m5stack_cores3 + +lib_deps = + ${esp32_base.lib_deps} diff --git a/variants/m5stack_cores3/variant.h b/variants/m5stack_cores3/variant.h new file mode 100644 index 0000000000..2ad4fcbddd --- /dev/null +++ b/variants/m5stack_cores3/variant.h @@ -0,0 +1,22 @@ +#define I2C_SDA 12 +#define I2C_SCL 11 + +#undef LORA_SCK +#undef LORA_MISO +#undef LORA_MOSI +#undef LORA_CS + +#define LORA_SCK 36 +#define LORA_MISO 35 +#define LORA_MOSI 37 +#define LORA_CS 6 // NSS + +#define USE_RF95 +#define LORA_DIO0 14 // IRQ +#define LORA_RESET 5 // RESET +#define LORA_RST 5 // RESET +#define LORA_IRQ 14 // DIO0 +#define LORA_DIO1 RADIOLIB_NC // Not really used +#define LORA_DIO2 RADIOLIB_NC // Not really used + +#define HAS_AXP2101 diff --git a/variants/rak11310/platformio.ini b/variants/rak11310/platformio.ini index e1bd2b1b0a..c7b3504fed 100644 --- a/variants/rak11310/platformio.ini +++ b/variants/rak11310/platformio.ini @@ -2,6 +2,8 @@ extends = rp2040_base board = wiscore_rak11300 upload_protocol = picotool +# keep an old SDK to use less memory. +platform_packages = framework-arduinopico@https://github.com/earlephilhower/arduino-pico.git#3.7.2 # add our variants files to the include and src paths build_flags = ${rp2040_base.build_flags} diff --git a/variants/rak11310/variant.h b/variants/rak11310/variant.h index f9dcbd91a3..54e403ee79 100644 --- a/variants/rak11310/variant.h +++ b/variants/rak11310/variant.h @@ -6,6 +6,7 @@ #define LED_CONN PIN_LED2 #define LED_PIN LED_BUILTIN +#define ledOff(pin) pinMode(pin, INPUT) #define BUTTON_PIN 9 #define BUTTON_NEED_PULLUP diff --git a/variants/rak4631_eth_gw/platformio.ini b/variants/rak4631_eth_gw/platformio.ini new file mode 100644 index 0000000000..62b7e737dc --- /dev/null +++ b/variants/rak4631_eth_gw/platformio.ini @@ -0,0 +1,66 @@ +; The very slick RAK wireless RAK 4631 / 4630 board - Unified firmware for 5005/19003, with or without OLED RAK 1921 +[env:rak4631_eth_gw] +extends = nrf52840_base +board = wiscore_rak4631 +board_check = true +build_flags = ${nrf52840_base.build_flags} -Ivariants/rak4631_eth_gw -D RAK_4631 + -L "${platformio.libdeps_dir}/${this.__env__}/bsec2/src/cortex-m4/fpv4-sp-d16-hard" + -DGPS_POWER_TOGGLE ; comment this line to disable triple press function on the user button to turn off gps entirely. + -DEINK_DISPLAY_MODEL=GxEPD2_213_BN + -DEINK_WIDTH=250 + -DEINK_HEIGHT=122 + -DNRF52_USE_JSON=1 + -DMESHTASTIC_EXCLUDE_GPS=1 + -DMESHTASTIC_EXCLUDE_WIFI=1 + -DMESHTASTIC_EXCLUDE_SCREEN=1 +; -DMESHTASTIC_EXCLUDE_PKI=1 + -DMESHTASTIC_EXCLUDE_POWER_FSM=1 + -DMESHTASTIC_EXCLUDE_POWERMON=1 +; -DMESHTASTIC_EXCLUDE_TZ=1 + -DMESHTASTIC_EXCLUDE_EXTERNALNOTIFICATION=1 + -DMESHTASTIC_EXCLUDE_PAXCOUNTER=1 + -DMESHTASTIC_EXCLUDE_REMOTEHARDWARE=1 + -DMESHTASTIC_EXCLUDE_STOREFORWARD=1 + -DMESHTASTIC_EXCLUDE_CANNEDMESSAGES=1 + -DMESHTASTIC_EXCLUDE_WAYPOINT=1 +build_src_filter = ${nrf52_base.build_src_filter} +<../variants/rak4631_eth_gw> + + + +lib_deps = + ${nrf52840_base.lib_deps} + ${networking_base.lib_deps} + melopero/Melopero RV3028@^1.1.0 + https://github.com/RAKWireless/RAK13800-W5100S.git#1.0.2 + rakwireless/RAKwireless NCP5623 RGB LED library@^1.0.2 + https://github.com/meshtastic/RAK12034-BMX160.git#4821355fb10390ba8557dc43ca29a023bcfbb9d9 + bblanchon/ArduinoJson @ 6.21.4 +; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) +; Note: as of 6/2013 the serial/bootloader based programming takes approximately 30 seconds +;upload_protocol = jlink + +; Allows programming and debug via the RAK NanoDAP as the default debugger tool for the RAK4631 (it is only $10!) +; programming time is about the same as the bootloader version. +; For information on this see the meshtastic developers documentation for "Development on the NRF52" +[env:rak4631_eth_gw_dbg] +extends = env:rak4631 +board_level = extra + +; if the builtin version of openocd has a buggy version of semihosting, so use the external version +; platform_packages = platformio/tool-openocd@^3.1200.0 + +build_flags = + ${env:rak4631_eth_gw.build_flags} + -D USE_SEMIHOSTING + +lib_deps = + ${env:rak4631_eth_gw.lib_deps} + https://github.com/geeksville/Armduino-Semihosting.git#35b538fdf208c3530c1434cd099a08e486672ee4 + +; NOTE: the pyocd support for semihosting is buggy. So I switched to using the builtin platformio support for the stlink adapter which worked much better. +; However the built in openocd version in platformio has buggy support for TCP to semihosting. +; +; So I'm now trying the external openocd - but the openocd scripts for nrf52.cfg assume you are using a DAP adapter not an STLINK adapter. +; In theory I could change those scripts. But for now I'm trying going back to a DAP adapter but with the external openocd. + +upload_protocol = stlink +; eventually use platformio/tool-pyocd@^2.3600.0 instad +;upload_protocol = custom +;upload_command = pyocd flash -t nrf52840 $UPLOADERFLAGS $SOURCE \ No newline at end of file diff --git a/variants/rak4631_eth_gw/variant.cpp b/variants/rak4631_eth_gw/variant.cpp new file mode 100644 index 0000000000..e84b60b3b9 --- /dev/null +++ b/variants/rak4631_eth_gw/variant.cpp @@ -0,0 +1,45 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + Copyright (c) 2016 Sandeep Mistry All right reserved. + Copyright (c) 2018, Adafruit Industries (adafruit.com) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "variant.h" +#include "nrf.h" +#include "wiring_constants.h" +#include "wiring_digital.h" + +const uint32_t g_ADigitalPinMap[] = { + // P0 + 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); + + pinMode(PIN_LED2, OUTPUT); + ledOff(PIN_LED2); + + // 3V3 Power Rail + pinMode(PIN_3V3_EN, OUTPUT); + digitalWrite(PIN_3V3_EN, HIGH); +} diff --git a/variants/rak4631_eth_gw/variant.h b/variants/rak4631_eth_gw/variant.h new file mode 100644 index 0000000000..bc55413368 --- /dev/null +++ b/variants/rak4631_eth_gw/variant.h @@ -0,0 +1,273 @@ +/* + Copyright (c) 2014-2015 Arduino LLC. All right reserved. + Copyright (c) 2016 Sandeep Mistry All right reserved. + Copyright (c) 2018, Adafruit Industries (adafruit.com) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the GNU Lesser General Public License for more details. + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _VARIANT_RAK4630_ +#define _VARIANT_RAK4630_ + +#define RAK4630 + +/** Master clock frequency */ +#define VARIANT_MCK (64000000ul) + +#define USE_LFXO // Board uses 32khz crystal for LF +// define USE_LFRC // Board uses RC for LF + +/*---------------------------------------------------------------------------- + * Headers + *----------------------------------------------------------------------------*/ + +#include "WVariant.h" + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// Number of pins defined in PinDescription array +#define PINS_COUNT (48) +#define NUM_DIGITAL_PINS (48) +#define NUM_ANALOG_INPUTS (6) +#define NUM_ANALOG_OUTPUTS (0) + +// LEDs +#define PIN_LED1 (35) +#define PIN_LED2 (36) + +#define LED_BUILTIN PIN_LED1 +#define LED_CONN PIN_LED2 + +#define LED_GREEN PIN_LED1 +#define LED_BLUE PIN_LED2 + +#define LED_STATE_ON 1 // State when LED is litted + +/* + * Buttons + */ + +#define PIN_BUTTON1 9 // Pin for button on E-ink button module or IO expansion +#define BUTTON_NEED_PULLUP +#define PIN_BUTTON2 12 +#define PIN_BUTTON3 24 +#define PIN_BUTTON4 25 + +/* + * Analog pins + */ +#define PIN_A0 (5) +#define PIN_A1 (31) +#define PIN_A2 (28) +#define PIN_A3 (29) +#define PIN_A4 (30) +#define PIN_A5 (31) +#define PIN_A6 (0xff) +#define PIN_A7 (0xff) + +static const uint8_t A0 = PIN_A0; +static const uint8_t A1 = PIN_A1; +static const uint8_t A2 = PIN_A2; +static const uint8_t A3 = PIN_A3; +static const uint8_t A4 = PIN_A4; +static const uint8_t A5 = PIN_A5; +static const uint8_t A6 = PIN_A6; +static const uint8_t A7 = PIN_A7; +#define ADC_RESOLUTION 14 + +// Other pins +#define PIN_AREF (2) +#define PIN_NFC1 (9) +#define PIN_NFC2 (10) + +static const uint8_t AREF = PIN_AREF; + +/* + * Serial interfaces + */ +#define PIN_SERIAL1_RX (15) +#define PIN_SERIAL1_TX (16) + +// Connected to Jlink CDC +#define PIN_SERIAL2_RX (8) +#define PIN_SERIAL2_TX (6) + +/* + * SPI Interfaces + */ +#define SPI_INTERFACES_COUNT 2 + +#define PIN_SPI_MISO (45) +#define PIN_SPI_MOSI (44) +#define PIN_SPI_SCK (43) + +#define PIN_SPI1_MISO (29) // (0 + 29) +#define PIN_SPI1_MOSI (30) // (0 + 30) +#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 + */ + +#define PIN_EINK_CS (0 + 26) +#define PIN_EINK_BUSY (0 + 4) +#define PIN_EINK_DC (0 + 17) +#define PIN_EINK_RES (-1) +#define PIN_EINK_SCLK (0 + 3) +#define PIN_EINK_MOSI (0 + 30) // also called SDI + +// #define USE_EINK + +// RAKRGB +#define HAS_NCP5623 + +/* + * Wire Interfaces + */ +#define WIRE_INTERFACES_COUNT 1 + +#define PIN_WIRE_SDA (13) +#define PIN_WIRE_SCL (14) + +// QSPI Pins +#define PIN_QSPI_SCK 3 +#define PIN_QSPI_CS 26 +#define PIN_QSPI_IO0 30 +#define PIN_QSPI_IO1 29 +#define PIN_QSPI_IO2 28 +#define PIN_QSPI_IO3 2 + +// On-board QSPI Flash +#define EXTERNAL_FLASH_DEVICES IS25LP080D +#define EXTERNAL_FLASH_USE_QSPI + +/* @note RAK5005-O GPIO mapping to RAK4631 GPIO ports + RAK5005-O <-> nRF52840 + IO1 <-> P0.17 (Arduino GPIO number 17) + IO2 <-> P1.02 (Arduino GPIO number 34) + IO3 <-> P0.21 (Arduino GPIO number 21) + IO4 <-> P0.04 (Arduino GPIO number 4) + IO5 <-> P0.09 (Arduino GPIO number 9) + IO6 <-> P0.10 (Arduino GPIO number 10) + IO7 <-> P0.28 (Arduino GPIO number 28) + 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) + */ + +// 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 DETECTION_SENSOR_EN 4 + +#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_POWER_EN (37) +// DIO2 controlls an antenna switch and the TCXO voltage is controlled by DIO3 +#define SX126X_DIO2_AS_RF_SWITCH +#define SX126X_DIO3_TCXO_VOLTAGE 1.8 + +// Testing USB detection +#define NRF_APM + +// enables 3.3V periphery like GPS or IO Module +// Do not toggle this for GPS power savings +#define PIN_3V3_EN (34) + +// RAK1910 GPS module +// If using the wisblock GPS module and pluged into Port A on WisBlock base +// IO1 is hooked to PPS (pin 12 on header) = gpio 17 +// IO2 is hooked to GPS RESET = gpio 34, but it can not be used to this because IO2 is ALSO used to control 3V3_S power (1 is on). +// Therefore must be 1 to keep peripherals powered +// Power is on the controllable 3V3_S rail +// #define PIN_GPS_RESET (34) +// #define PIN_GPS_EN PIN_3V3_EN +#define PIN_GPS_PPS (17) // Pulse per second input from the GPS + +#define GPS_RX_PIN PIN_SERIAL1_RX +#define GPS_TX_PIN PIN_SERIAL1_TX + +// Define pin to enable GPS toggle (set GPIO to LOW) via user button triple press + +// RAK12002 RTC Module +#define RV3028_RTC (uint8_t)0b1010010 + +// RAK18001 Buzzer in Slot C +// #define PIN_BUZZER 21 // IO3 is PWM2 +// NEW: set this via protobuf instead! + +// Battery +// The battery sense is hooked to pin A0 (5) +#define BATTERY_PIN PIN_A0 +// and has 12 bit resolution +#define BATTERY_SENSE_RESOLUTION_BITS 12 +#define BATTERY_SENSE_RESOLUTION 4096.0 +#undef AREF_VOLTAGE +#define AREF_VOLTAGE 3.0 +#define VBAT_AR_INTERNAL AR_INTERNAL_3_0 +#define ADC_MULTIPLIER 1.73 + +#define HAS_RTC 1 + +#define HAS_ETHERNET 1 + +#define RAK_4631 1 + +#define PIN_ETHERNET_RESET 21 +#define PIN_ETHERNET_SS PIN_EINK_CS +#define ETH_SPI_PORT SPI1 +#define AQ_SET_PIN 10 + +#ifdef __cplusplus +} +#endif + +/*---------------------------------------------------------------------------- + * Arduino objects - C++ only + *----------------------------------------------------------------------------*/ + +#endif \ No newline at end of file diff --git a/variants/rp2040-lora/variant.h b/variants/rp2040-lora/variant.h index d0bbc0ec39..f1826605f5 100644 --- a/variants/rp2040-lora/variant.h +++ b/variants/rp2040-lora/variant.h @@ -23,6 +23,7 @@ // ratio of voltage divider = 3.0 (R17=200k, R18=100k) // #define ADC_MULTIPLIER 3.1 // 3.0 + a bit for being optimistic +#define HAS_CPU_SHUTDOWN 1 #define USE_SX1262 #undef LORA_SCK diff --git a/variants/tlora_v1/platformio.ini b/variants/tlora_v1/platformio.ini index c90daed904..65ec4bcdcb 100644 --- a/variants/tlora_v1/platformio.ini +++ b/variants/tlora_v1/platformio.ini @@ -1,4 +1,5 @@ [env:tlora-v1] +board_level = extra extends = esp32_base board = ttgo-lora32-v1 build_flags = diff --git a/variants/tlora_v1_3/platformio.ini b/variants/tlora_v1_3/platformio.ini index 9d9f41a7cb..99df28e560 100644 --- a/variants/tlora_v1_3/platformio.ini +++ b/variants/tlora_v1_3/platformio.ini @@ -1,4 +1,5 @@ [env:tlora_v1_3] +board_level = extra extends = esp32_base board = ttgo-lora32-v1 build_flags = diff --git a/variants/tlora_v2/platformio.ini b/variants/tlora_v2/platformio.ini index 8710068aff..8087a30e36 100644 --- a/variants/tlora_v2/platformio.ini +++ b/variants/tlora_v2/platformio.ini @@ -1,4 +1,5 @@ [env:tlora-v2] +board_level = extra extends = esp32_base board = ttgo-lora32-v1 build_flags = diff --git a/variants/tracker-t1000-e/platformio.ini b/variants/tracker-t1000-e/platformio.ini index dfc72f3f03..0758116100 100644 --- a/variants/tracker-t1000-e/platformio.ini +++ b/variants/tracker-t1000-e/platformio.ini @@ -1,16 +1,14 @@ -; tracker-t1000-e v0.9.1 [env:tracker-t1000-e] extends = nrf52840_base board = tracker-t1000-e -; board_level = extra -; platform = https://github.com/maxgerhardt/platform-nordicnrf52#cac6fcf943a41accd2aeb4f3659ae297a73f422e build_flags = ${nrf52840_base.build_flags} -Ivariants/tracker-t1000-e -Isrc/platform/nrf52/softdevice -Isrc/platform/nrf52/softdevice/nrf52 -DTRACKER_T1000_E -L "${platformio.libdeps_dir}/${this.__env__}/bsec2/src/cortex-m4/fpv4-sp-d16-hard" - -DGPS_POWER_TOGGLE ; comment this line to disable triple press function on the user button to turn off gps entirely. + -DGPS_POWER_TOGGLE board_build.ldscript = src/platform/nrf52/nrf52840_s140_v7.ld build_src_filter = ${nrf52_base.build_src_filter} +<../variants/tracker-t1000-e> lib_deps = ${nrf52840_base.lib_deps} + https://github.com/meshtastic/QMA6100P_Arduino_Library.git#14c900b8b2e4feaac5007a7e41e0c1b7f0841136 debug_tool = jlink ; If not set we will default to uploading over serial (first it forces bootloader entry by talking 1200bps to cdcacm) upload_protocol = nrfutil diff --git a/variants/tracker-t1000-e/variant.cpp b/variants/tracker-t1000-e/variant.cpp index 85e0c44f39..8096705d02 100644 --- a/variants/tracker-t1000-e/variant.cpp +++ b/variants/tracker-t1000-e/variant.cpp @@ -40,7 +40,7 @@ void initVariant() digitalWrite(PIN_3V3_EN, HIGH); pinMode(PIN_3V3_ACC_EN, OUTPUT); - digitalWrite(PIN_3V3_ACC_EN, LOW); + digitalWrite(PIN_3V3_ACC_EN, HIGH); pinMode(BUZZER_EN_PIN, OUTPUT); digitalWrite(BUZZER_EN_PIN, HIGH); diff --git a/variants/tracker-t1000-e/variant.h b/variants/tracker-t1000-e/variant.h index b8eb59b318..6a1f996002 100644 --- a/variants/tracker-t1000-e/variant.h +++ b/variants/tracker-t1000-e/variant.h @@ -52,7 +52,7 @@ extern "C" { #define LED_BLUE -1 // Actually green #define LED_STATE_ON 1 // State when LED is lit -#define BUTTON_PIN (0 + 6) // P0.6 +#define BUTTON_PIN (0 + 6) // P0.06 #define BUTTON_ACTIVE_LOW false #define BUTTON_ACTIVE_PULLUP false #define BUTTON_SENSE_TYPE 0x6 @@ -61,9 +61,11 @@ extern "C" { #define WIRE_INTERFACES_COUNT 1 -// unused pins -#define PIN_WIRE_SDA (0 + 9) // P0.26 -#define PIN_WIRE_SCL (0 + 10) // P0.27 +#define PIN_WIRE_SDA (0 + 26) // P0.26 +#define PIN_WIRE_SCL (0 + 27) // P0.27 +#define I2C_NO_RESCAN // I2C is a bit finicky, don't scan too much +#define HAS_QMA6100P // very rare beast, only on this board. +#define QMA_6100P_INT_PIN (32 + 2) // P1.02 /* * Serial interfaces @@ -116,14 +118,22 @@ extern "C" { #define PIN_GPS_RESET (32 + 15) // P1.15 #define GPS_RESET_MODE HIGH -#define GPS_VRTC_EN (0 + 8) // P0.8, awlays high -#define GPS_SLEEP_INT (32 + 12) // P1.12, awlays high +#define GPS_VRTC_EN (0 + 8) // P0.8, always high +#define GPS_SLEEP_INT (32 + 12) // P1.12, always high #define GPS_RTC_INT (0 + 15) // P0.15, normal is LOW, wake by HIGH -#define GPS_RESETB_OUT (32 + 14) // P1.14, awlays input pull_up +#define GPS_RESETB_OUT (32 + 14) // P1.14, always input pull_up #define GPS_FIX_HOLD_TIME 15000 // ms -#define BATTERY_PIN 2 +#define BATTERY_PIN 2 // P0.02/AIN0, BAT_ADC +#define BATTERY_IMMUTABLE #define ADC_MULTIPLIER (2.0F) +// P0.04/AIN2 is VCC_ADC, P0.05/AIN3 is CHARGER_DET, P1.03 is CHARGE_STA, P1.04 is CHARGE_DONE + +#define EXT_CHRG_DETECT (32 + 3) // P1.03 +#define EXT_CHRG_DETECT_VALUE LOW +// #define EXT_IS_CHRGD (32 + 4) // P1.04 +// #define EXT_IS_CHRGD_VALUE LOW +#define EXT_PWR_DETECT (0 + 5) // P0.05 #define ADC_RESOLUTION 14 #define BATTERY_SENSE_RESOLUTION_BITS 12 @@ -133,13 +143,13 @@ extern "C" { #define VBAT_AR_INTERNAL AR_INTERNAL_3_0 // Buzzer -#define BUZZER_EN_PIN (32 + 5) // P1.05, awlays high +#define BUZZER_EN_PIN (32 + 5) // P1.05, always high #define PIN_BUZZER (0 + 25) // P0.25, pwm output #define T1000X_SENSOR_EN #define T1000X_VCC_PIN (0 + 4) // P0.4 -#define T1000X_NTC_PIN (0 + 31) // P0.31 -#define T1000X_LUX_PIN (0 + 29) // P0.29 +#define T1000X_NTC_PIN (0 + 31) // P0.31/AIN7 +#define T1000X_LUX_PIN (0 + 29) // P0.29/AIN5 #ifdef __cplusplus } diff --git a/version.properties b/version.properties index df7ba70c73..58380fa5ef 100644 --- a/version.properties +++ b/version.properties @@ -1,4 +1,4 @@ [VERSION] major = 2 minor = 5 -build = 6 +build = 9