diff --git a/.github/actions/build-variant/action.yml b/.github/actions/build-variant/action.yml index f611908ee..a71ddfc4d 100644 --- a/.github/actions/build-variant/action.yml +++ b/.github/actions/build-variant/action.yml @@ -100,7 +100,7 @@ runs: id: version - name: Store binaries as an artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: firmware-${{ inputs.arch }}-${{ inputs.board }}-${{ steps.version.outputs.long }}.zip overwrite: true diff --git a/.github/workflows/build_debian_src.yml b/.github/workflows/build_debian_src.yml index 7f3f8b672..d36e7fea1 100644 --- a/.github/workflows/build_debian_src.yml +++ b/.github/workflows/build_debian_src.yml @@ -64,7 +64,7 @@ jobs: PKG_VERSION: ${{ steps.version.outputs.deb }} - name: Store binaries as an artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: firmware-debian-${{ steps.version.outputs.deb }}~${{ inputs.series }}-src overwrite: true diff --git a/.github/workflows/build_firmware.yml b/.github/workflows/build_firmware.yml index b62729332..57c1e72c7 100644 --- a/.github/workflows/build_firmware.yml +++ b/.github/workflows/build_firmware.yml @@ -56,7 +56,7 @@ jobs: ota_firmware_target: ${{ steps.ota_dir.outputs.tgt || '' }} - name: Store binaries as an artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 id: upload with: name: firmware-${{ inputs.platform }}-${{ inputs.pio_env }}-${{ inputs.version }}.zip diff --git a/.github/workflows/build_one_arch.yml b/.github/workflows/build_one_arch.yml index 9c57f8b7d..6d5462c93 100644 --- a/.github/workflows/build_one_arch.yml +++ b/.github/workflows/build_one_arch.yml @@ -113,7 +113,7 @@ jobs: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: path: ./ pattern: firmware-${{inputs.arch}}-* @@ -126,7 +126,7 @@ jobs: run: mv -b -t ./ ./bin/device-*.sh ./bin/device-*.bat - name: Repackage in single firmware zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: firmware-${{inputs.arch}}-${{ needs.version.outputs.long }} overwrite: true @@ -142,7 +142,7 @@ jobs: ./Meshtastic_nRF52_factory_erase*.uf2 retention-days: 30 - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: name: firmware-${{inputs.arch}}-${{ needs.version.outputs.long }} merge-multiple: true @@ -161,7 +161,7 @@ jobs: run: zip -j -9 -r ./firmware-${{inputs.arch}}-${{ needs.version.outputs.long }}.zip ./output - name: Repackage in single elfs zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: debug-elfs-${{inputs.arch}}-${{ needs.version.outputs.long }}.zip overwrite: true diff --git a/.github/workflows/build_one_target.yml b/.github/workflows/build_one_target.yml index 15b3fdba9..46362a629 100644 --- a/.github/workflows/build_one_target.yml +++ b/.github/workflows/build_one_target.yml @@ -119,7 +119,7 @@ jobs: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: path: ./ pattern: firmware-*-* @@ -132,7 +132,7 @@ jobs: run: mv -b -t ./ ./bin/device-*.sh ./bin/device-*.bat - name: Repackage in single firmware zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: firmware-${{inputs.target}}-${{ needs.version.outputs.long }} overwrite: true @@ -148,7 +148,7 @@ jobs: ./Meshtastic_nRF52_factory_erase*.uf2 retention-days: 30 - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: firmware-*-${{ needs.version.outputs.long }} merge-multiple: true @@ -167,7 +167,7 @@ jobs: run: zip -j -9 -r ./firmware-${{inputs.target}}-${{ needs.version.outputs.long }}.zip ./output - name: Repackage in single elfs zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: debug-elfs-${{inputs.target}}-${{ needs.version.outputs.long }}.zip overwrite: true diff --git a/.github/workflows/main_matrix.yml b/.github/workflows/main_matrix.yml index 02a4c23b8..7ea033d55 100644 --- a/.github/workflows/main_matrix.yml +++ b/.github/workflows/main_matrix.yml @@ -168,7 +168,7 @@ jobs: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: path: ./ pattern: firmware-${{matrix.arch}}-* @@ -181,7 +181,7 @@ jobs: run: mv -b -t ./ ./bin/device-*.sh ./bin/device-*.bat - name: Repackage in single firmware zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: firmware-${{matrix.arch}}-${{ needs.version.outputs.long }} overwrite: true @@ -197,7 +197,7 @@ jobs: ./Meshtastic_nRF52_factory_erase*.uf2 retention-days: 30 - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: name: firmware-${{matrix.arch}}-${{ needs.version.outputs.long }} merge-multiple: true @@ -216,7 +216,7 @@ jobs: run: zip -j -9 -r ./firmware-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip ./output - name: Repackage in single elfs zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: debug-elfs-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip overwrite: true @@ -261,14 +261,14 @@ jobs: Autogenerated by github action, developer should edit as required before publishing... - name: Download source deb - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: pattern: firmware-debian-${{ needs.version.outputs.deb }}~UNRELEASED-src merge-multiple: true path: ./output/debian-src - name: Download `native-tft` pio deps - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: pattern: platformio-deps-native-tft-${{ needs.version.outputs.long }} merge-multiple: true @@ -318,7 +318,7 @@ jobs: with: python-version: 3.x - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: firmware-${{matrix.arch}}-${{ needs.version.outputs.long }} merge-multiple: true @@ -335,7 +335,7 @@ jobs: - name: Zip firmware run: zip -j -9 -r ./firmware-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip ./output - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: name: debug-elfs-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip merge-multiple: true @@ -373,7 +373,7 @@ jobs: with: python-version: 3.x - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: firmware-{${{ env.targets }}}-${{ needs.version.outputs.long }} merge-multiple: true diff --git a/.github/workflows/merge_queue.yml b/.github/workflows/merge_queue.yml index e8c3d3450..6d69258c9 100644 --- a/.github/workflows/merge_queue.yml +++ b/.github/workflows/merge_queue.yml @@ -147,7 +147,7 @@ jobs: ref: ${{github.event.pull_request.head.ref}} repository: ${{github.event.pull_request.head.repo.full_name}} - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: path: ./ pattern: firmware-${{matrix.arch}}-* @@ -160,7 +160,7 @@ jobs: run: mv -b -t ./ ./bin/device-*.sh ./bin/device-*.bat - name: Repackage in single firmware zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: firmware-${{matrix.arch}}-${{ needs.version.outputs.long }} overwrite: true @@ -176,7 +176,7 @@ jobs: ./Meshtastic_nRF52_factory_erase*.uf2 retention-days: 30 - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: name: firmware-${{matrix.arch}}-${{ needs.version.outputs.long }} merge-multiple: true @@ -195,7 +195,7 @@ jobs: run: zip -j -9 -r ./firmware-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip ./output - name: Repackage in single elfs zip - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: debug-elfs-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip overwrite: true @@ -240,14 +240,14 @@ jobs: Autogenerated by github action, developer should edit as required before publishing... - name: Download source deb - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: pattern: firmware-debian-${{ needs.version.outputs.deb }}~UNRELEASED-src merge-multiple: true path: ./output/debian-src - name: Download `native-tft` pio deps - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: pattern: platformio-deps-native-tft-${{ needs.version.outputs.long }} merge-multiple: true @@ -297,7 +297,7 @@ jobs: with: python-version: 3.x - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: firmware-${{matrix.arch}}-${{ needs.version.outputs.long }} merge-multiple: true @@ -314,7 +314,7 @@ jobs: - name: Zip firmware run: zip -j -9 -r ./firmware-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip ./output - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: name: debug-elfs-${{matrix.arch}}-${{ needs.version.outputs.long }}.zip merge-multiple: true @@ -352,7 +352,7 @@ jobs: with: python-version: 3.x - - uses: actions/download-artifact@v5 + - uses: actions/download-artifact@v6 with: pattern: firmware-{${{ env.targets }}}-${{ needs.version.outputs.long }} merge-multiple: true diff --git a/.github/workflows/package_obs.yml b/.github/workflows/package_obs.yml index 4c547eadc..b8a829d9a 100644 --- a/.github/workflows/package_obs.yml +++ b/.github/workflows/package_obs.yml @@ -58,7 +58,7 @@ jobs: id: version - name: Download artifacts - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: firmware-debian-${{ steps.version.outputs.deb }}~${{ inputs.series }}-src merge-multiple: true diff --git a/.github/workflows/package_pio_deps.yml b/.github/workflows/package_pio_deps.yml index d8ff6e631..c52dfe348 100644 --- a/.github/workflows/package_pio_deps.yml +++ b/.github/workflows/package_pio_deps.yml @@ -56,7 +56,7 @@ jobs: PLATFORMIO_CORE_DIR: pio/core - name: Store binaries as an artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: platformio-deps-${{ inputs.pio_env }}-${{ steps.version.outputs.long }} overwrite: true diff --git a/.github/workflows/package_ppa.yml b/.github/workflows/package_ppa.yml index aece730a0..2d6c257e6 100644 --- a/.github/workflows/package_ppa.yml +++ b/.github/workflows/package_ppa.yml @@ -60,7 +60,7 @@ jobs: id: version - name: Download artifacts - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: firmware-debian-${{ steps.version.outputs.deb }}~${{ inputs.series }}-src merge-multiple: true diff --git a/.github/workflows/pr_tests.yml b/.github/workflows/pr_tests.yml index 4e285852d..c3a964e04 100644 --- a/.github/workflows/pr_tests.yml +++ b/.github/workflows/pr_tests.yml @@ -50,7 +50,7 @@ jobs: - name: Download test artifacts if: needs.native-tests.result != 'skipped' - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: platformio-test-report-${{ steps.version.outputs.long }}.zip merge-multiple: true diff --git a/.github/workflows/sec_sast_semgrep_cron.yml b/.github/workflows/sec_sast_semgrep_cron.yml index 2059fde2c..dfb828bf6 100644 --- a/.github/workflows/sec_sast_semgrep_cron.yml +++ b/.github/workflows/sec_sast_semgrep_cron.yml @@ -33,7 +33,7 @@ jobs: # step 3 - name: save report as pipeline artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: report.sarif overwrite: true diff --git a/.github/workflows/test_native.yml b/.github/workflows/test_native.yml index 9cf1c9e53..3f3d02e4c 100644 --- a/.github/workflows/test_native.yml +++ b/.github/workflows/test_native.yml @@ -59,7 +59,7 @@ jobs: id: version - name: Save coverage information - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 if: always() # run this step even if previous step failed with: name: lcov-coverage-info-native-simulator-test-${{ steps.version.outputs.long }}.zip @@ -94,7 +94,7 @@ jobs: - name: Save test results if: always() # run this step even if previous step failed - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: platformio-test-report-${{ steps.version.outputs.long }}.zip overwrite: true @@ -108,7 +108,7 @@ jobs: sed -i -e "s#${PWD}#.#" coverage_tests.info # Make paths relative. - name: Save coverage information - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 if: always() # run this step even if previous step failed with: name: lcov-coverage-info-native-platformio-tests-${{ steps.version.outputs.long }}.zip @@ -137,7 +137,7 @@ jobs: id: version - name: Download test artifacts - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: name: platformio-test-report-${{ steps.version.outputs.long }}.zip merge-multiple: true @@ -150,7 +150,7 @@ jobs: reporter: java-junit - name: Download coverage artifacts - uses: actions/download-artifact@v5 + uses: actions/download-artifact@v6 with: pattern: lcov-coverage-info-native-*-${{ steps.version.outputs.long }}.zip path: code-coverage-report @@ -163,7 +163,7 @@ jobs: genhtml --quiet --legend --prefix "${PWD}" code-coverage-report/coverage_src.info --output-directory code-coverage-report - name: Save Code Coverage Report - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: code-coverage-report-${{ steps.version.outputs.long }}.zip path: code-coverage-report diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 5bec39ae2..0a43c3079 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -8,15 +8,15 @@ plugins: uri: https://github.com/trunk-io/plugins lint: enabled: - - checkov@3.2.483 - - renovate@41.148.2 + - checkov@3.2.486 + - renovate@41.157.0 - prettier@3.6.2 - - trufflehog@3.90.8 + - trufflehog@3.90.11 - yamllint@1.37.1 - bandit@1.8.6 - trivy@0.67.2 - taplo@0.10.0 - - ruff@0.14.0 + - ruff@0.14.1 - isort@7.0.0 - markdownlint@0.45.0 - oxipng@9.1.5 diff --git a/src/Power.cpp b/src/Power.cpp index 1f4c341f0..d7fd5b33b 100644 --- a/src/Power.cpp +++ b/src/Power.cpp @@ -839,8 +839,11 @@ void Power::readPowerStatus() // Notify any status instances that are observing us const PowerStatus powerStatus2 = PowerStatus(hasBattery, usbPowered, isChargingNow, batteryVoltageMv, batteryChargePercent); - LOG_DEBUG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d", powerStatus2.getHasUSB(), powerStatus2.getIsCharging(), - powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); + if (millis() > lastLogTime + 50 * 1000) { + LOG_DEBUG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d", powerStatus2.getHasUSB(), + powerStatus2.getIsCharging(), powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent()); + lastLogTime = millis(); + } newStatus.notifyObservers(&powerStatus2); #ifdef DEBUG_HEAP if (lastheap != memGet.getFreeHeap()) { diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp index 297ed3dfa..6c6cdba6d 100644 --- a/src/gps/GPS.cpp +++ b/src/gps/GPS.cpp @@ -1659,8 +1659,12 @@ bool GPS::lookForLocation() #ifndef TINYGPS_OPTION_NO_STATISTICS if (reader.failedChecksum() > lastChecksumFailCount) { - LOG_WARN("%u new GPS checksum failures, for a total of %u", reader.failedChecksum() - lastChecksumFailCount, - reader.failedChecksum()); +// In a GPS_DEBUG build we want to log all of these. In production, we only care if there are many of them. +#ifndef GPS_DEBUG + if (reader.failedChecksum() > 4) +#endif + LOG_WARN("%u new GPS checksum failures, for a total of %u", reader.failedChecksum() - lastChecksumFailCount, + reader.failedChecksum()); lastChecksumFailCount = reader.failedChecksum(); } #endif diff --git a/src/graphics/draw/MenuHandler.cpp b/src/graphics/draw/MenuHandler.cpp index 701062e08..803fb87ea 100644 --- a/src/graphics/draw/MenuHandler.cpp +++ b/src/graphics/draw/MenuHandler.cpp @@ -784,6 +784,7 @@ void menuHandler::nodeNameLengthMenu() screen->runNow(); } }; + bannerOptions.InitialSelected = config.display.use_long_node_name == true ? 1 : 2; screen->showOverlayBanner(bannerOptions); } diff --git a/src/graphics/draw/NodeListRenderer.cpp b/src/graphics/draw/NodeListRenderer.cpp index 39ccbef16..e8f454fc2 100644 --- a/src/graphics/draw/NodeListRenderer.cpp +++ b/src/graphics/draw/NodeListRenderer.cpp @@ -53,7 +53,7 @@ static int scrollIndex = 0; // Utility Functions // ============================= -const char *getSafeNodeName(meshtastic_NodeInfoLite *node) +const char *getSafeNodeName(OLEDDisplay *display, meshtastic_NodeInfoLite *node) { const char *name = NULL; static char nodeName[16] = "?"; @@ -81,6 +81,28 @@ const char *getSafeNodeName(meshtastic_NodeInfoLite *node) snprintf(nodeName, sizeof(nodeName), "(%04X)", (uint16_t)(node->num & 0xFFFF)); } + if (config.display.use_long_node_name == true) { + int availWidth = (SCREEN_WIDTH / 2) - 65; + if (availWidth < 0) + availWidth = 0; + + size_t origLen = strlen(nodeName); + while (nodeName[0] && display->getStringWidth(nodeName) > availWidth) { + nodeName[strlen(nodeName) - 1] = '\0'; + } + + // If we actually truncated, append "..." (ensure space remains in buffer) + if (strlen(nodeName) < origLen) { + size_t len = strlen(nodeName); + size_t maxLen = sizeof(nodeName) - 4; // 3 for "..." and 1 for '\0' + if (len > maxLen) { + nodeName[maxLen] = '\0'; + len = maxLen; + } + strcat(nodeName, "..."); + } + } + return nodeName; } @@ -147,7 +169,7 @@ void drawEntryLastHeard(OLEDDisplay *display, meshtastic_NodeInfoLite *node, int bool isLeftCol = (x < SCREEN_WIDTH / 2); int timeOffset = (isHighResolution) ? (isLeftCol ? 7 : 10) : (isLeftCol ? 3 : 7); - const char *nodeName = getSafeNodeName(node); + const char *nodeName = getSafeNodeName(display, node); char timeStr[10]; uint32_t seconds = sinceLastSeen(node); @@ -192,7 +214,7 @@ void drawEntryHopSignal(OLEDDisplay *display, meshtastic_NodeInfoLite *node, int int barsXOffset = columnWidth - barsOffset; - const char *nodeName = getSafeNodeName(node); + const char *nodeName = getSafeNodeName(display, node); display->setTextAlignment(TEXT_ALIGN_LEFT); display->setFont(FONT_SMALL); @@ -236,7 +258,7 @@ void drawNodeDistance(OLEDDisplay *display, meshtastic_NodeInfoLite *node, int16 bool isLeftCol = (x < SCREEN_WIDTH / 2); int nameMaxWidth = columnWidth - (isHighResolution ? (isLeftCol ? 25 : 28) : (isLeftCol ? 20 : 22)); - const char *nodeName = getSafeNodeName(node); + const char *nodeName = getSafeNodeName(display, node); char distStr[10] = ""; meshtastic_NodeInfoLite *ourNode = nodeDB->getMeshNode(nodeDB->getNodeNum()); @@ -331,7 +353,7 @@ void drawEntryCompass(OLEDDisplay *display, meshtastic_NodeInfoLite *node, int16 // Adjust max text width depending on column and screen width int nameMaxWidth = columnWidth - (isHighResolution ? (isLeftCol ? 25 : 28) : (isLeftCol ? 20 : 22)); - const char *nodeName = getSafeNodeName(node); + const char *nodeName = getSafeNodeName(display, node); display->setTextAlignment(TEXT_ALIGN_LEFT); display->setFont(FONT_SMALL); @@ -362,11 +384,11 @@ void drawCompassArrow(OLEDDisplay *display, meshtastic_NodeInfoLite *node, int16 float bearing = GeoCoord::bearing(userLat, userLon, nodeLat, nodeLon); float bearingToNode = RAD_TO_DEG * bearing; float relativeBearing = fmod((bearingToNode - myHeading + 360), 360); - float angle = relativeBearing * DEG_TO_RAD; // Shrink size by 2px int size = FONT_HEIGHT_SMALL - 5; CompassRenderer::drawArrowToNode(display, centerX, centerY, size, relativeBearing); /* + float angle = relativeBearing * DEG_TO_RAD; float halfSize = size / 2.0; // Point of the arrow diff --git a/src/graphics/draw/UIRenderer.cpp b/src/graphics/draw/UIRenderer.cpp index e0d046587..625a69a70 100644 --- a/src/graphics/draw/UIRenderer.cpp +++ b/src/graphics/draw/UIRenderer.cpp @@ -563,6 +563,7 @@ void UIRenderer::drawDeviceFocused(OLEDDisplay *display, OLEDDisplayUiState *sta display->setTextAlignment(TEXT_ALIGN_LEFT); display->setFont(FONT_SMALL); int line = 1; + meshtastic_NodeInfoLite *ourNode = nodeDB->getMeshNode(nodeDB->getNodeNum()); // === Header === #if defined(M5STACK_UNITC6L) @@ -740,7 +741,6 @@ void UIRenderer::drawDeviceFocused(OLEDDisplay *display, OLEDDisplayUiState *sta int yOffset = (isHighResolution) ? 0 : 5; std::string longNameStr; - meshtastic_NodeInfoLite *ourNode = nodeDB->getMeshNode(nodeDB->getNodeNum()); if (ourNode && ourNode->has_user && strlen(ourNode->user.long_name) > 0) { longNameStr = sanitizeString(ourNode->user.long_name); } @@ -1000,24 +1000,7 @@ void UIRenderer::drawCompassAndLocationScreen(OLEDDisplay *display, OLEDDisplayU const char *displayLine = ""; // Initialize to empty string by default meshtastic_NodeInfoLite *ourNode = nodeDB->getMeshNode(nodeDB->getNodeNum()); - bool usePhoneGPS = (ourNode && nodeDB->hasValidPosition(ourNode) && - config.position.gps_mode != meshtastic_Config_PositionConfig_GpsMode_ENABLED); - - if (usePhoneGPS) { - // Phone-provided GPS is active - displayLine = "Phone GPS"; - int yOffset = (isHighResolution) ? 3 : 1; - if (isHighResolution) { - NodeListRenderer::drawScaledXBitmap16x16(x, getTextPositions(display)[line] + yOffset - 5, imgSatellite_width, - imgSatellite_height, imgSatellite, display); - } else { - display->drawXbm(x + 1, getTextPositions(display)[line] + yOffset, imgSatellite_width, imgSatellite_height, - imgSatellite); - } - int xOffset = (isHighResolution) ? 6 : 0; - display->drawString(x + 11 + xOffset, getTextPositions(display)[line++], displayLine); - } else if (config.position.gps_mode != meshtastic_Config_PositionConfig_GpsMode_ENABLED) { - // GPS disabled / not present + if (config.position.gps_mode != meshtastic_Config_PositionConfig_GpsMode_ENABLED) { if (config.position.fixed_position) { displayLine = "Fixed GPS"; } else { @@ -1108,9 +1091,7 @@ void UIRenderer::drawCompassAndLocationScreen(OLEDDisplay *display, OLEDDisplayU // === Final Row: Altitude === char altitudeLine[32] = {0}; - int32_t alt = (strcmp(displayLine, "Phone GPS") == 0 && ourNode && nodeDB->hasValidPosition(ourNode)) - ? ourNode->position.altitude - : geoCoord.getAltitude(); + int32_t alt = geoCoord.getAltitude(); if (config.display.units == meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL) { snprintf(altitudeLine, sizeof(altitudeLine), "Alt: %.0fft", alt * METERS_TO_FEET); } else { diff --git a/src/graphics/niche/InkHUD/Applets/Bases/Map/MapApplet.cpp b/src/graphics/niche/InkHUD/Applets/Bases/Map/MapApplet.cpp index db0805f4e..818c68070 100644 --- a/src/graphics/niche/InkHUD/Applets/Bases/Map/MapApplet.cpp +++ b/src/graphics/niche/InkHUD/Applets/Bases/Map/MapApplet.cpp @@ -13,45 +13,147 @@ void InkHUD::MapApplet::onRender() return; } + // Helper: draw rounded rectangle centered at x,y + auto fillRoundedRect = [&](int16_t cx, int16_t cy, int16_t w, int16_t h, int16_t r, uint16_t color) { + int16_t x = cx - (w / 2); + int16_t y = cy - (h / 2); + + // center rects + fillRect(x + r, y, w - 2 * r, h, color); + fillRect(x, y + r, r, h - 2 * r, color); + fillRect(x + w - r, y + r, r, h - 2 * r, color); + + // corners + fillCircle(x + r, y + r, r, color); + fillCircle(x + w - r - 1, y + r, r, color); + fillCircle(x + r, y + h - r - 1, r, color); + fillCircle(x + w - r - 1, y + h - r - 1, r, color); + }; + // Find center of map - // - latitude and longitude - // - will be placed at X(0.5), Y(0.5) getMapCenter(&latCenter, &lngCenter); - - // Calculate North+East distance of each node to map center - // - which nodes to use controlled by virtual shouldDrawNode method calculateAllMarkers(); - - // Set the region shown on the map - // - default: fit all nodes, plus padding - // - maybe overriden by derived applet - // - getMapSize *sets* passed parameters (C-style) getMapSize(&widthMeters, &heightMeters); - - // Set the metersToPx conversion value calculateMapScale(); - // Special marker for own node - meshtastic_NodeInfoLite *ourNode = nodeDB->getMeshNode(nodeDB->getNodeNum()); - if (ourNode && nodeDB->hasValidPosition(ourNode)) - drawLabeledMarker(ourNode); - - // Draw all markers + // Draw all markers first for (Marker m : markers) { int16_t x = X(0.5) + (m.eastMeters * metersToPx); int16_t y = Y(0.5) - (m.northMeters * metersToPx); - // Cross Size - constexpr uint16_t csMin = 5; - constexpr uint16_t csMax = 12; + // Add white halo outline first + constexpr int outlinePad = 1; + int boxSize = 11; + int radius = 2; // rounded corner radius - // Too many hops away - if (m.hasHopsAway && m.hopsAway > config.lora.hop_limit) // Too many mops - printAt(x, y, "!", CENTER, MIDDLE); - else if (!m.hasHopsAway) // Unknown hops - drawCross(x, y, csMin); - else // The fewer hops, the larger the cross - drawCross(x, y, map(m.hopsAway, 0, config.lora.hop_limit, csMax, csMin)); + // White halo background + fillRoundedRect(x, y, boxSize + (outlinePad * 2), boxSize + (outlinePad * 2), radius + 1, WHITE); + + // Draw inner box + fillRoundedRect(x, y, boxSize, boxSize, radius, BLACK); + + // Text inside + setFont(fontSmall); + setTextColor(WHITE); + + // Draw actual marker on top + if (m.hasHopsAway && m.hopsAway > config.lora.hop_limit) { + printAt(x + 1, y + 1, "X", CENTER, MIDDLE); + } else if (!m.hasHopsAway) { + printAt(x + 1, y + 1, "?", CENTER, MIDDLE); + } else { + char hopStr[4]; + snprintf(hopStr, sizeof(hopStr), "%d", m.hopsAway); + printAt(x, y + 1, hopStr, CENTER, MIDDLE); + } + + // Restore default font and color + setFont(fontSmall); + setTextColor(BLACK); + } + + // Dual map scale bars + int16_t horizPx = width() * 0.25f; + int16_t vertPx = height() * 0.25f; + float horizMeters = horizPx / metersToPx; + float vertMeters = vertPx / metersToPx; + + auto formatDistance = [&](float meters, char *out, size_t len) { + if (config.display.units == meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL) { + float feet = meters * 3.28084f; + if (feet < 528) + snprintf(out, len, "%.0f ft", feet); + else { + float miles = feet / 5280.0f; + snprintf(out, len, miles < 10 ? "%.1f mi" : "%.0f mi", miles); + } + } else { + if (meters >= 1000) + snprintf(out, len, "%.1f km", meters / 1000.0f); + else + snprintf(out, len, "%.0f m", meters); + } + }; + + // Horizontal scale bar + int16_t horizBarY = height() - 2; + int16_t horizBarX = 1; + drawLine(horizBarX, horizBarY, horizBarX + horizPx, horizBarY, BLACK); + drawLine(horizBarX, horizBarY - 3, horizBarX, horizBarY + 3, BLACK); + drawLine(horizBarX + horizPx, horizBarY - 3, horizBarX + horizPx, horizBarY + 3, BLACK); + + char horizLabel[32]; + formatDistance(horizMeters, horizLabel, sizeof(horizLabel)); + int16_t horizLabelW = getTextWidth(horizLabel); + int16_t horizLabelH = getFont().lineHeight(); + int16_t horizLabelX = horizBarX + horizPx + 4; + int16_t horizLabelY = horizBarY - horizLabelH + 1; + fillRect(horizLabelX - 2, horizLabelY - 1, horizLabelW + 4, horizLabelH + 2, WHITE); + printAt(horizLabelX, horizBarY, horizLabel, LEFT, BOTTOM); + + // Vertical scale bar + int16_t vertBarX = 1; + int16_t vertBarBottom = horizBarY; + int16_t vertBarTop = vertBarBottom - vertPx; + drawLine(vertBarX, vertBarBottom, vertBarX, vertBarTop, BLACK); + drawLine(vertBarX - 3, vertBarBottom, vertBarX + 3, vertBarBottom, BLACK); + drawLine(vertBarX - 3, vertBarTop, vertBarX + 3, vertBarTop, BLACK); + + char vertTopLabel[32]; + formatDistance(vertMeters, vertTopLabel, sizeof(vertTopLabel)); + int16_t topLabelY = vertBarTop - getFont().lineHeight() - 2; + int16_t topLabelW = getTextWidth(vertTopLabel); + int16_t topLabelH = getFont().lineHeight(); + fillRect(vertBarX - 2, topLabelY - 1, topLabelW + 6, topLabelH + 2, WHITE); + printAt(vertBarX + (topLabelW / 2) + 1, topLabelY + (topLabelH / 2), vertTopLabel, CENTER, MIDDLE); + + char vertBottomLabel[32]; + formatDistance(vertMeters, vertBottomLabel, sizeof(vertBottomLabel)); + int16_t bottomLabelY = vertBarBottom + 4; + int16_t bottomLabelW = getTextWidth(vertBottomLabel); + int16_t bottomLabelH = getFont().lineHeight(); + fillRect(vertBarX - 2, bottomLabelY - 1, bottomLabelW + 6, bottomLabelH + 2, WHITE); + printAt(vertBarX + (bottomLabelW / 2) + 1, bottomLabelY + (bottomLabelH / 2), vertBottomLabel, CENTER, MIDDLE); + + // Draw our node LAST with full white fill + outline + meshtastic_NodeInfoLite *ourNode = nodeDB->getMeshNode(nodeDB->getNodeNum()); + if (ourNode && nodeDB->hasValidPosition(ourNode)) { + Marker self = calculateMarker(ourNode->position.latitude_i * 1e-7, ourNode->position.longitude_i * 1e-7, false, 0); + + int16_t centerX = X(0.5) + (self.eastMeters * metersToPx); + int16_t centerY = Y(0.5) - (self.northMeters * metersToPx); + + // White fill background + halo + fillCircle(centerX, centerY, 8, WHITE); // big white base + drawCircle(centerX, centerY, 8, WHITE); // crisp edge + + // Black bullseye on top + drawCircle(centerX, centerY, 6, BLACK); + fillCircle(centerX, centerY, 2, BLACK); + + // Crosshairs + drawLine(centerX - 8, centerY, centerX + 8, centerY, BLACK); + drawLine(centerX, centerY - 8, centerX, centerY + 8, BLACK); } } @@ -63,110 +165,123 @@ void InkHUD::MapApplet::onRender() void InkHUD::MapApplet::getMapCenter(float *lat, float *lng) { - // Find mean lat long coords - // ============================ - // - assigning X, Y and Z values to position on Earth's surface in 3D space, relative to center of planet - // - averages the x, y and z coords - // - uses tan to find angles for lat / long degrees - // - longitude: triangle formed by x and y (on plane of the equator) - // - latitude: triangle formed by z (north south), - // and the line along plane of equator which stretches from earth's axis to where point xyz intersects planet's surface + // If we have a valid position for our own node, use that as the anchor + meshtastic_NodeInfoLite *ourNode = nodeDB->getMeshNode(nodeDB->getNodeNum()); + if (ourNode && nodeDB->hasValidPosition(ourNode)) { + *lat = ourNode->position.latitude_i * 1e-7; + *lng = ourNode->position.longitude_i * 1e-7; + } else { + // Find mean lat long coords + // ============================ + // - assigning X, Y and Z values to position on Earth's surface in 3D space, relative to center of planet + // - averages the x, y and z coords + // - uses tan to find angles for lat / long degrees + // - longitude: triangle formed by x and y (on plane of the equator) + // - latitude: triangle formed by z (north south), + // and the line along plane of equator which stretches from earth's axis to where point xyz intersects planet's + // surface - // Working totals, averaged after nodeDB processed - uint32_t positionCount = 0; - float xAvg = 0; - float yAvg = 0; - float zAvg = 0; + // Working totals, averaged after nodeDB processed + uint32_t positionCount = 0; + float xAvg = 0; + float yAvg = 0; + float zAvg = 0; - // For each node in db - for (uint32_t i = 0; i < nodeDB->getNumMeshNodes(); i++) { - meshtastic_NodeInfoLite *node = nodeDB->getMeshNodeByIndex(i); + // For each node in db + for (uint32_t i = 0; i < nodeDB->getNumMeshNodes(); i++) { + meshtastic_NodeInfoLite *node = nodeDB->getMeshNodeByIndex(i); - // Skip if no position - if (!nodeDB->hasValidPosition(node)) - continue; + // Skip if no position + if (!nodeDB->hasValidPosition(node)) + continue; - // Skip if derived applet doesn't want to show this node on the map - if (!shouldDrawNode(node)) - continue; + // Skip if derived applet doesn't want to show this node on the map + if (!shouldDrawNode(node)) + continue; - // Latitude and Longitude of node, in radians - float latRad = node->position.latitude_i * (1e-7) * DEG_TO_RAD; - float lngRad = node->position.longitude_i * (1e-7) * DEG_TO_RAD; + // Latitude and Longitude of node, in radians + float latRad = node->position.latitude_i * (1e-7) * DEG_TO_RAD; + float lngRad = node->position.longitude_i * (1e-7) * DEG_TO_RAD; - // Convert to cartesian points, with center of earth at 0, 0, 0 - // Exact distance from center is irrelevant, as we're only interested in the vector - float x = cos(latRad) * cos(lngRad); - float y = cos(latRad) * sin(lngRad); - float z = sin(latRad); + // Convert to cartesian points, with center of earth at 0, 0, 0 + // Exact distance from center is irrelevant, as we're only interested in the vector + float x = cos(latRad) * cos(lngRad); + float y = cos(latRad) * sin(lngRad); + float z = sin(latRad); - // To find mean values shortly - xAvg += x; - yAvg += y; - zAvg += z; - positionCount++; + // To find mean values shortly + xAvg += x; + yAvg += y; + zAvg += z; + positionCount++; + } + + // All NodeDB processed, find mean values + xAvg /= positionCount; + yAvg /= positionCount; + zAvg /= positionCount; + + // Longitude from cartesian coords + // (Angle from 3D coords describing a point of globe's surface) + /* + UK + /-------\ + (Top View) /- -\ + /- (You) -\ + /- . -\ + /- . X -\ + Asia - ... - USA + \- Y -/ + \- -/ + \- -/ + \- -/ + \- -----/ + Pacific + + */ + + *lng = atan2(yAvg, xAvg) * RAD_TO_DEG; + + // Latitude from cartesian coords + // (Angle from 3D coords describing a point on the globe's surface) + // As latitude increases, distance from the Earth's north-south axis out to our surface point decreases. + // Means we need to first find the hypotenuse which becomes base of our triangle in the second step + /* + UK North + /-------\ (Front View) /-------\ + (Top View) /- -\ /- -\ + /- (You) -\ /-(You) -\ + /- /. -\ /- . -\ + /- √X²+Y²/ . X -\ /- Z . -\ + Asia - /... - USA - ..... - + \- Y -/ \- √X²+Y² -/ + \- -/ \- -/ + \- -/ \- -/ + \- -/ \- -/ + \- -----/ \- -----/ + Pacific South + */ + + float hypotenuse = sqrt((xAvg * xAvg) + (yAvg * yAvg)); // Distance from globe's north-south axis to surface intersect + *lat = atan2(zAvg, hypotenuse) * RAD_TO_DEG; } - // All NodeDB processed, find mean values - xAvg /= positionCount; - yAvg /= positionCount; - zAvg /= positionCount; - - // Longitude from cartesian coords - // (Angle from 3D coords describing a point of globe's surface) - /* - UK - /-------\ - (Top View) /- -\ - /- (You) -\ - /- . -\ - /- . X -\ - Asia - ... - USA - \- Y -/ - \- -/ - \- -/ - \- -/ - \- -----/ - Pacific - - */ - - *lng = atan2(yAvg, xAvg) * RAD_TO_DEG; - - // Latitude from cartesian coords - // (Angle from 3D coords describing a point on the globe's surface) - // As latitude increases, distance from the Earth's north-south axis out to our surface point decreases. - // Means we need to first find the hypotenuse which becomes base of our triangle in the second step - /* - UK North - /-------\ (Front View) /-------\ - (Top View) /- -\ /- -\ - /- (You) -\ /-(You) -\ - /- /. -\ /- . -\ - /- √X²+Y²/ . X -\ /- Z . -\ - Asia - /... - USA - ..... - - \- Y -/ \- √X²+Y² -/ - \- -/ \- -/ - \- -/ \- -/ - \- -/ \- -/ - \- -----/ \- -----/ - Pacific South - */ - - float hypotenuse = sqrt((xAvg * xAvg) + (yAvg * yAvg)); // Distance from globe's north-south axis to surface intersect - *lat = atan2(zAvg, hypotenuse) * RAD_TO_DEG; + // Use either our node position, or the mean fallback as the center + latCenter = *lat; + lngCenter = *lng; // ---------------------------------------------- - // This has given us the "mean position" - // This will be a position *somewhere* near the center of our nodes. - // What we actually want is to place our center so that our outermost nodes end up on the border of our map. - // The only real use of our "mean position" is to give us a reference frame: - // which direction is east, and which is west. + // This has given us either: + // - our actual position (preferred), or + // - a mean position (fallback if we had no fix) + // + // What we actually want is to place our center so that our outermost nodes + // end up on the border of our map. The only real use of our "center" is to give + // us a reference frame: which direction is east, and which is west. //------------------------------------------------ - // Find furthest nodes from "mean lat long" + // Find furthest nodes from our center // ======================================== - float northernmost = latCenter; float southernmost = latCenter; float easternmost = lngCenter; @@ -184,14 +299,14 @@ void InkHUD::MapApplet::getMapCenter(float *lat, float *lng) continue; // Check for a new top or bottom latitude - float lat = node->position.latitude_i * 1e-7; - northernmost = max(northernmost, lat); - southernmost = min(southernmost, lat); + float latNode = node->position.latitude_i * 1e-7; + northernmost = max(northernmost, latNode); + southernmost = min(southernmost, latNode); // Longitude is trickier - float lng = node->position.longitude_i * 1e-7; - float degEastward = fmod(((lng - lngCenter) + 360), 360); // Degrees traveled east from lngCenter to reach node - float degWestward = abs(fmod(((lng - lngCenter) - 360), 360)); // Degrees traveled west from lngCenter to reach node + float lngNode = node->position.longitude_i * 1e-7; + float degEastward = fmod(((lngNode - lngCenter) + 360), 360); // Degrees traveled east from lngCenter to reach node + float degWestward = abs(fmod(((lngNode - lngCenter) - 360), 360)); // Degrees traveled west from lngCenter to reach node if (degEastward < degWestward) easternmost = max(easternmost, lngCenter + degEastward); else @@ -250,7 +365,6 @@ InkHUD::MapApplet::Marker InkHUD::MapApplet::calculateMarker(float lat, float ln m.hopsAway = hopsAway; return m; } - // Draw a marker on the map for a node, with a shortname label, and backing box void InkHUD::MapApplet::drawLabeledMarker(meshtastic_NodeInfoLite *node) { @@ -324,6 +438,18 @@ void InkHUD::MapApplet::drawLabeledMarker(meshtastic_NodeInfoLite *node) textX = labelX + paddingW; } + // Prevent overlap with scale bars and their labels + // Define a "safe zone" in the bottom-left where the scale bars and text are drawn + constexpr int16_t safeZoneHeight = 28; // adjust based on your label font height + constexpr int16_t safeZoneWidth = 60; // adjust based on horizontal label width zone + bool overlapsScale = (labelY + labelH > height() - safeZoneHeight) && (labelX < safeZoneWidth); + + // If it overlaps, shift label upward slightly above the safe zone + if (overlapsScale) { + labelY = height() - safeZoneHeight - labelH - 2; + textY = labelY + (labelH / 2); + } + // Backing box fillRect(labelX, labelY, labelW, labelH, WHITE); drawRect(labelX, labelY, labelW, labelH, BLACK); diff --git a/src/graphics/niche/InkHUD/Applets/Bases/NodeList/NodeListApplet.cpp b/src/graphics/niche/InkHUD/Applets/Bases/NodeList/NodeListApplet.cpp index 1b0bfa9d0..5c9906fba 100644 --- a/src/graphics/niche/InkHUD/Applets/Bases/NodeList/NodeListApplet.cpp +++ b/src/graphics/niche/InkHUD/Applets/Bases/NodeList/NodeListApplet.cpp @@ -127,6 +127,11 @@ void InkHUD::NodeListApplet::onRender() // Y value (top) of the current card. Increases as we draw. uint16_t cardTopY = headerDivY + padDivH; + // Clean up deleted nodes before drawing + cards.erase( + std::remove_if(cards.begin(), cards.end(), [](const CardInfo &c) { return nodeDB->getMeshNode(c.nodeNum) == nullptr; }), + cards.end()); + // -- Each node in list -- for (auto card = cards.begin(); card != cards.end(); ++card) { @@ -141,6 +146,11 @@ void InkHUD::NodeListApplet::onRender() meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeNum); + // Skip deleted nodes + if (!node) { + continue; + } + // -- Shortname -- // Parse special chars in the short name // Use "?" if unknown @@ -188,7 +198,7 @@ void InkHUD::NodeListApplet::onRender() drawSignalIndicator(signalX, signalY, signalW, signalH, signal); } // Otherwise, print "hops away" info, if available - else if (hopsAway != CardInfo::HOPS_UNKNOWN) { + else if (hopsAway != CardInfo::HOPS_UNKNOWN && node) { std::string hopString = to_string(node->hops_away); hopString += " Hop"; if (node->hops_away != 1) diff --git a/src/main.cpp b/src/main.cpp index df58d5d8c..672276f66 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -449,6 +449,12 @@ void setup() LOG_INFO("\n\n//\\ E S H T /\\ S T / C\n"); +#if defined(DEBUG_MUTE) && defined(DEBUG_PORT) + DEBUG_PORT.printf("\r\n\r\n//\\ E S H T /\\ S T / C\r\n"); + DEBUG_PORT.printf("Version %s for %s from %s\r\n", optstr(APP_VERSION), optstr(APP_ENV), optstr(APP_REPO)); + DEBUG_PORT.printf("Debug mute is enabled, there will be no serial output.\r\n"); +#endif + initDeepSleep(); #if defined(MODEM_POWER_EN) diff --git a/src/mesh/Default.h b/src/mesh/Default.h index 2f05da98d..d0d4678ff 100644 --- a/src/mesh/Default.h +++ b/src/mesh/Default.h @@ -27,7 +27,7 @@ #ifdef USERPREFS_RINGTONE_NAG_SECS #define default_ringtone_nag_secs USERPREFS_RINGTONE_NAG_SECS #else -#define default_ringtone_nag_secs 60 +#define default_ringtone_nag_secs 15 #endif #define default_mqtt_address "mqtt.meshtastic.org" @@ -84,4 +84,4 @@ class Default return 1.0 + (nodesOverForty * throttlingFactor); // Each number of online node scales by 0.075 (default) } } -}; \ No newline at end of file +}; diff --git a/src/mesh/FloodingRouter.cpp b/src/mesh/FloodingRouter.cpp index 1d8ac247f..032be241b 100644 --- a/src/mesh/FloodingRouter.cpp +++ b/src/mesh/FloodingRouter.cpp @@ -31,33 +31,8 @@ bool FloodingRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) wasSeenRecently(p, true, nullptr, nullptr, &wasUpgraded); // Updates history; returns false when an upgrade is detected // Handle hop_limit upgrade scenario for rebroadcasters - // isRebroadcaster() is duplicated in perhapsRebroadcast(), but this avoids confusing log messages - if (wasUpgraded && isRebroadcaster() && iface && p->hop_limit > 0) { - // wasSeenRecently() reports false in upgrade cases so we handle replacement before the duplicate short-circuit - // If we overhear a duplicate copy of the packet with more hops left than the one we are waiting to - // rebroadcast, then remove the packet currently sitting in the TX queue and use this one instead. - uint8_t dropThreshold = p->hop_limit; // remove queued packets that have fewer hops remaining - if (iface->removePendingTXPacket(getFrom(p), p->id, dropThreshold)) { - LOG_DEBUG("Processing upgraded packet 0x%08x for rebroadcast with hop limit %d (dropping queued < %d)", p->id, - p->hop_limit, dropThreshold); - - if (nodeDB) - nodeDB->updateFrom(*p); -#if !MESHTASTIC_EXCLUDE_TRACEROUTE - if (traceRouteModule && p->which_payload_variant == meshtastic_MeshPacket_decoded_tag && - p->decoded.portnum == meshtastic_PortNum_TRACEROUTE_APP) - traceRouteModule->processUpgradedPacket(*p); -#endif - - perhapsRebroadcast(p); - - // We already enqueued the improved copy, so make sure the incoming packet stops here. - return true; - } - - // No queue entry was replaced by this upgraded copy, so treat it as a duplicate to avoid - // delivering the same packet to applications/phone twice with different hop limits. - seenRecently = true; + if (wasUpgraded && perhapsHandleUpgradedPacket(p)) { + return true; // we handled it, so stop processing } if (seenRecently) { @@ -70,8 +45,10 @@ bool FloodingRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) if (isRepeated) { LOG_DEBUG("Repeated reliable tx"); // Check if it's still in the Tx queue, if not, we have to relay it again - if (!findInTxQueue(p->from, p->id)) + if (!findInTxQueue(p->from, p->id)) { + reprocessPacket(p); perhapsRebroadcast(p); + } } else { perhapsCancelDupe(p); } @@ -82,6 +59,40 @@ bool FloodingRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) return Router::shouldFilterReceived(p); } +bool FloodingRouter::perhapsHandleUpgradedPacket(const meshtastic_MeshPacket *p) +{ + // isRebroadcaster() is duplicated in perhapsRebroadcast(), but this avoids confusing log messages + if (isRebroadcaster() && iface && p->hop_limit > 0) { + // If we overhear a duplicate copy of the packet with more hops left than the one we are waiting to + // rebroadcast, then remove the packet currently sitting in the TX queue and use this one instead. + uint8_t dropThreshold = p->hop_limit; // remove queued packets that have fewer hops remaining + if (iface->removePendingTXPacket(getFrom(p), p->id, dropThreshold)) { + LOG_DEBUG("Processing upgraded packet 0x%08x for rebroadcast with hop limit %d (dropping queued < %d)", p->id, + p->hop_limit, dropThreshold); + + reprocessPacket(p); + perhapsRebroadcast(p); + + rxDupe++; + // We already enqueued the improved copy, so make sure the incoming packet stops here. + return true; + } + } + + return false; +} + +void FloodingRouter::reprocessPacket(const meshtastic_MeshPacket *p) +{ + if (nodeDB) + nodeDB->updateFrom(*p); +#if !MESHTASTIC_EXCLUDE_TRACEROUTE + if (traceRouteModule && p->which_payload_variant == meshtastic_MeshPacket_decoded_tag && + p->decoded.portnum == meshtastic_PortNum_TRACEROUTE_APP) + traceRouteModule->processUpgradedPacket(*p); +#endif +} + bool FloodingRouter::roleAllowsCancelingDupe(const meshtastic_MeshPacket *p) { if (config.device.role == meshtastic_Config_DeviceConfig_Role_ROUTER || @@ -121,41 +132,6 @@ bool FloodingRouter::isRebroadcaster() config.device.rebroadcast_mode != meshtastic_Config_DeviceConfig_RebroadcastMode_NONE; } -void FloodingRouter::perhapsRebroadcast(const meshtastic_MeshPacket *p) -{ - if (!isToUs(p) && (p->hop_limit > 0) && !isFromUs(p)) { - if (p->id != 0) { - if (isRebroadcaster()) { - meshtastic_MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it - - // Use shared logic to determine if hop_limit should be decremented - if (shouldDecrementHopLimit(p)) { - tosend->hop_limit--; // bump down the hop count - } else { - LOG_INFO("favorite-ROUTER/CLIENT_BASE-to-ROUTER/CLIENT_BASE flood: preserving hop_limit"); - } -#if USERPREFS_EVENT_MODE - if (tosend->hop_limit > 2) { - // if we are "correcting" the hop_limit, "correct" the hop_start by the same amount to preserve hops away. - tosend->hop_start -= (tosend->hop_limit - 2); - tosend->hop_limit = 2; - } -#endif - - tosend->next_hop = NO_NEXT_HOP_PREFERENCE; // this should already be the case, but just in case - - LOG_INFO("Rebroadcast received floodmsg"); - // Note: we are careful to resend using the original senders node id - send(tosend); - } else { - LOG_DEBUG("No rebroadcast: Role = CLIENT_MUTE or Rebroadcast Mode = NONE"); - } - } else { - LOG_DEBUG("Ignore 0 id broadcast"); - } - } -} - void FloodingRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) { bool isAckorReply = (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) && diff --git a/src/mesh/FloodingRouter.h b/src/mesh/FloodingRouter.h index eaf71d294..e8a2e9685 100644 --- a/src/mesh/FloodingRouter.h +++ b/src/mesh/FloodingRouter.h @@ -27,10 +27,6 @@ */ class FloodingRouter : public Router { - private: - /* Check if we should rebroadcast this packet, and do so if needed */ - void perhapsRebroadcast(const meshtastic_MeshPacket *p); - public: /** * Constructor @@ -59,6 +55,17 @@ class FloodingRouter : public Router */ virtual void sniffReceived(const meshtastic_MeshPacket *p, const meshtastic_Routing *c) override; + /* Check if we should rebroadcast this packet, and do so if needed */ + virtual bool perhapsRebroadcast(const meshtastic_MeshPacket *p) = 0; + + /* Check if we should handle an upgraded packet (with higher hop_limit) + * @return true if we handled it (so stop processing) + */ + bool perhapsHandleUpgradedPacket(const meshtastic_MeshPacket *p); + + /* Call when we receive a packet that needs some reprocessing, but afterwards should be filtered */ + void reprocessPacket(const meshtastic_MeshPacket *p); + // Return false for roles like ROUTER which should always rebroadcast even when we've heard another rebroadcast of // the same packet bool roleAllowsCancelingDupe(const meshtastic_MeshPacket *p); diff --git a/src/mesh/NextHopRouter.cpp b/src/mesh/NextHopRouter.cpp index 0461d7eb6..afdb4d096 100644 --- a/src/mesh/NextHopRouter.cpp +++ b/src/mesh/NextHopRouter.cpp @@ -43,31 +43,8 @@ bool NextHopRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) &wasUpgraded); // Updates history; returns false when an upgrade is detected // Handle hop_limit upgrade scenario for rebroadcasters - // isRebroadcaster() is duplicated in perhapsRelay(), but this avoids confusing log messages - if (wasUpgraded && isRebroadcaster() && iface && p->hop_limit > 0) { - // Upgrade detection bypasses the duplicate short-circuit so we replace the queued packet before exiting - uint8_t dropThreshold = p->hop_limit; // remove queued packets that have fewer hops remaining - if (iface->removePendingTXPacket(getFrom(p), p->id, dropThreshold)) { - LOG_DEBUG("Processing upgraded packet 0x%08x for relay with hop limit %d (dropping queued < %d)", p->id, p->hop_limit, - dropThreshold); - - if (nodeDB) - nodeDB->updateFrom(*p); -#if !MESHTASTIC_EXCLUDE_TRACEROUTE - if (traceRouteModule && p->which_payload_variant == meshtastic_MeshPacket_decoded_tag && - p->decoded.portnum == meshtastic_PortNum_TRACEROUTE_APP) - traceRouteModule->processUpgradedPacket(*p); -#endif - - perhapsRelay(p); - - // We already enqueued the improved copy, so make sure the incoming packet stops here. - return true; - } - - // No queue entry was replaced by this upgraded copy, so treat it as a duplicate to avoid - // delivering the same packet to applications/phone twice with different hop limits. - seenRecently = true; + if (wasUpgraded && perhapsHandleUpgradedPacket(p)) { + return true; // we handled it, so stop processing } if (seenRecently) { @@ -82,14 +59,20 @@ bool NextHopRouter::shouldFilterReceived(const meshtastic_MeshPacket *p) if (wasFallback) { LOG_INFO("Fallback to flooding from relay_node=0x%x", p->relay_node); // Check if it's still in the Tx queue, if not, we have to relay it again - if (!findInTxQueue(p->from, p->id)) - perhapsRelay(p); + if (!findInTxQueue(p->from, p->id)) { + reprocessPacket(p); + perhapsRebroadcast(p); + } } else { bool isRepeated = p->hop_start > 0 && p->hop_start == p->hop_limit; // If repeated and not in Tx queue anymore, try relaying again, or if we are the destination, send the ACK again if (isRepeated) { - if (!findInTxQueue(p->from, p->id) && !perhapsRelay(p) && isToUs(p) && p->want_ack) - sendAckNak(meshtastic_Routing_Error_NONE, getFrom(p), p->id, p->channel, 0); + if (!findInTxQueue(p->from, p->id)) { + reprocessPacket(p); + if (!perhapsRebroadcast(p) && isToUs(p) && p->want_ack) { + sendAckNak(meshtastic_Routing_Error_NONE, getFrom(p), p->id, p->channel, 0); + } + } } else if (!weWereNextHop) { perhapsCancelDupe(p); // If it's a dupe, cancel relay if we were not explicitly asked to relay } @@ -107,13 +90,14 @@ void NextHopRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtast bool isAckorReply = (p->which_payload_variant == meshtastic_MeshPacket_decoded_tag) && (p->decoded.request_id != 0 || p->decoded.reply_id != 0); if (isAckorReply) { - // Update next-hop for the original transmitter of this successful transmission to the relay node, but ONLY if "from" is - // not 0 (means implicit ACK) and original packet was also relayed by this node, or we sent it directly to the destination + // Update next-hop for the original transmitter of this successful transmission to the relay node, but ONLY if "from" + // is not 0 (means implicit ACK) and original packet was also relayed by this node, or we sent it directly to the + // destination if (p->from != 0) { meshtastic_NodeInfoLite *origTx = nodeDB->getMeshNode(p->from); if (origTx) { - // Either relayer of ACK was also a relayer of the packet, or we were the *only* relayer and the ACK came directly - // from the destination + // Either relayer of ACK was also a relayer of the packet, or we were the *only* relayer and the ACK came + // directly from the destination bool wasAlreadyRelayer = wasRelayer(p->relay_node, p->decoded.request_id, p->to); bool weWereSoleRelayer = false; bool weWereRelayer = wasRelayer(ourRelayID, p->decoded.request_id, p->to, &weWereSoleRelayer); @@ -134,34 +118,49 @@ void NextHopRouter::sniffReceived(const meshtastic_MeshPacket *p, const meshtast } } - perhapsRelay(p); + perhapsRebroadcast(p); // handle the packet as normal Router::sniffReceived(p, c); } -/* Check if we should be relaying this packet if so, do so. */ -bool NextHopRouter::perhapsRelay(const meshtastic_MeshPacket *p) +/* Check if we should be rebroadcasting this packet if so, do so. */ +bool NextHopRouter::perhapsRebroadcast(const meshtastic_MeshPacket *p) { if (!isToUs(p) && !isFromUs(p) && p->hop_limit > 0) { - if (p->next_hop == NO_NEXT_HOP_PREFERENCE || p->next_hop == nodeDB->getLastByteOfNodeNum(getNodeNum())) { + if (p->id != 0) { if (isRebroadcaster()) { - meshtastic_MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it - LOG_INFO("Relaying received message coming from %x", p->relay_node); + if (p->next_hop == NO_NEXT_HOP_PREFERENCE || p->next_hop == nodeDB->getLastByteOfNodeNum(getNodeNum())) { + meshtastic_MeshPacket *tosend = packetPool.allocCopy(*p); // keep a copy because we will be sending it + LOG_INFO("Rebroadcast received message coming from %x", p->relay_node); - // Use shared logic to determine if hop_limit should be decremented - if (shouldDecrementHopLimit(p)) { - tosend->hop_limit--; // bump down the hop count - } else { - LOG_INFO("Router/CLIENT_BASE-to-favorite-router/CLIENT_BASE relay: preserving hop_limit"); + // Use shared logic to determine if hop_limit should be decremented + if (shouldDecrementHopLimit(p)) { + tosend->hop_limit--; // bump down the hop count + } else { + LOG_INFO("favorite-ROUTER/CLIENT_BASE-to-ROUTER/CLIENT_BASE rebroadcast: preserving hop_limit"); + } +#if USERPREFS_EVENT_MODE + if (tosend->hop_limit > 2) { + // if we are "correcting" the hop_limit, "correct" the hop_start by the same amount to preserve hops away. + tosend->hop_start -= (tosend->hop_limit - 2); + tosend->hop_limit = 2; + } +#endif + + if (p->next_hop == NO_NEXT_HOP_PREFERENCE) { + FloodingRouter::send(tosend); + } else { + NextHopRouter::send(tosend); + } + + return true; } - - NextHopRouter::send(tosend); - - return true; } else { - LOG_DEBUG("Not rebroadcasting: Role = CLIENT_MUTE or Rebroadcast Mode = NONE"); + LOG_DEBUG("No rebroadcast: Role = CLIENT_MUTE or Rebroadcast Mode = NONE"); } + } else { + LOG_DEBUG("Ignore 0 id broadcast"); } } @@ -231,13 +230,13 @@ bool NextHopRouter::stopRetransmission(GlobalPacketId key) } } - // Regardless of whether or not we canceled this packet from the txQueue, remove it from our pending list so it doesn't - // get scheduled again. (This is the core of stopRetransmission.) + // Regardless of whether or not we canceled this packet from the txQueue, remove it from our pending list so it + // doesn't get scheduled again. (This is the core of stopRetransmission.) auto numErased = pending.erase(key); assert(numErased == 1); - // When we remove an entry from pending, always be sure to release the copy of the packet that was allocated in the call - // to startRetransmission. + // When we remove an entry from pending, always be sure to release the copy of the packet that was allocated in the + // call to startRetransmission. packetPool.release(p); return true; diff --git a/src/mesh/NextHopRouter.h b/src/mesh/NextHopRouter.h index 0022644e9..c1df3596b 100644 --- a/src/mesh/NextHopRouter.h +++ b/src/mesh/NextHopRouter.h @@ -148,7 +148,7 @@ class NextHopRouter : public FloodingRouter */ uint8_t getNextHop(NodeNum to, uint8_t relay_node); - /** Check if we should be relaying this packet if so, do so. - * @return true if we did relay */ - bool perhapsRelay(const meshtastic_MeshPacket *p); + /** Check if we should be rebroadcasting this packet if so, do so. + * @return true if we did rebroadcast */ + bool perhapsRebroadcast(const meshtastic_MeshPacket *p) override; }; \ No newline at end of file diff --git a/src/mesh/PacketHistory.cpp b/src/mesh/PacketHistory.cpp index 49d581d9a..b4af707ae 100644 --- a/src/mesh/PacketHistory.cpp +++ b/src/mesh/PacketHistory.cpp @@ -94,7 +94,6 @@ bool PacketHistory::wasSeenRecently(const meshtastic_MeshPacket *p, bool withUpd LOG_DEBUG("Packet History - Hop limit upgrade: packet 0x%08x from hop_limit=%d to hop_limit=%d", p->id, found->hop_limit, p->hop_limit); *wasUpgraded = true; - seenRecently = false; // Allow router processing but prevent duplicate app delivery } else if (wasUpgraded) { *wasUpgraded = false; // Initialize to false if not an upgrade } diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp index 31ec5acc5..3c0da4494 100644 --- a/src/mesh/RadioInterface.cpp +++ b/src/mesh/RadioInterface.cpp @@ -272,10 +272,10 @@ uint32_t RadioInterface::getTxDelayMsec() uint8_t RadioInterface::getCWsize(float snr) { // The minimum value for a LoRa SNR - const uint32_t SNR_MIN = -20; + const int32_t SNR_MIN = -20; // The maximum value for a LoRa SNR - const uint32_t SNR_MAX = 10; + const int32_t SNR_MAX = 10; return map(snr, SNR_MIN, SNR_MAX, CWmin, CWmax); } diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index 2567d9e7f..80e51b8bc 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -289,12 +289,7 @@ void RadioLibInterface::onNotify(uint32_t notification) // actual transmission as short as possible txp = txQueue.dequeue(); assert(txp); - bool sent = startSend(txp); - if (sent) { - // Packet has been sent, count it toward our TX airtime utilization. - uint32_t xmitMsec = getPacketTime(txp); - airTime->logAirtime(TX_LOG, xmitMsec); - } + startSend(txp); LOG_DEBUG("%d packets remain in the TX queue", txQueue.getMaxLen() - txQueue.getFree()); } } @@ -413,6 +408,10 @@ void RadioLibInterface::completeSending() sendingPacket = NULL; if (p) { + // Packet has been sent, count it toward our TX airtime utilization. + uint32_t xmitMsec = getPacketTime(p); + airTime->logAirtime(TX_LOG, xmitMsec); + txGood++; if (!isFromUs(p)) txRelay++; diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp index 60637cbd1..5cf8bfa7d 100644 --- a/src/mesh/Router.cpp +++ b/src/mesh/Router.cpp @@ -35,6 +35,15 @@ (MAX_RX_TOPHONE + MAX_RX_FROMRADIO + 2 * MAX_TX_QUEUE + \ 2) // max number of packets which can be in flight (either queued from reception or queued for sending) +static MemoryDynamic dynamicPool; +Allocator &packetPool = dynamicPool; +#elif defined(ARCH_STM32WL) +// On STM32 there isn't enough heap left over for the rest of the firmware if we allocate this statically. +// For now, make it dynamic again. +#define MAX_PACKETS \ + (MAX_RX_TOPHONE + MAX_RX_FROMRADIO + 2 * MAX_TX_QUEUE + \ + 2) // max number of packets which can be in flight (either queued from reception or queued for sending) + static MemoryDynamic dynamicPool; Allocator &packetPool = dynamicPool; #else diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index f87c6e3b0..7b7ebb595 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -148,6 +148,8 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) { + if (webServerThread) + webServerThread->markActivity(); LOG_DEBUG("webAPI handleAPIv1FromRadio"); @@ -391,6 +393,9 @@ void handleFsDeleteStatic(HTTPRequest *req, HTTPResponse *res) void handleStatic(HTTPRequest *req, HTTPResponse *res) { + if (webServerThread) + webServerThread->markActivity(); + // Get access to the parameters ResourceParameters *params = req->getParams(); diff --git a/src/mesh/http/WebServer.cpp b/src/mesh/http/WebServer.cpp index bf170de59..3a264fa5a 100644 --- a/src/mesh/http/WebServer.cpp +++ b/src/mesh/http/WebServer.cpp @@ -49,6 +49,12 @@ Preferences prefs; using namespace httpsserver; #include "mesh/http/ContentHandler.h" +static const uint32_t ACTIVE_THRESHOLD_MS = 5000; +static const uint32_t MEDIUM_THRESHOLD_MS = 30000; +static const int32_t ACTIVE_INTERVAL_MS = 50; +static const int32_t MEDIUM_INTERVAL_MS = 200; +static const int32_t IDLE_INTERVAL_MS = 1000; + static SSLCert *cert; static HTTPSServer *secureServer; static HTTPServer *insecureServer; @@ -175,6 +181,32 @@ WebServerThread::WebServerThread() : concurrency::OSThread("WebServer") if (!config.network.wifi_enabled && !config.network.eth_enabled) { disable(); } + lastActivityTime = millis(); +} + +void WebServerThread::markActivity() +{ + lastActivityTime = millis(); +} + +int32_t WebServerThread::getAdaptiveInterval() +{ + uint32_t currentTime = millis(); + uint32_t timeSinceActivity; + + if (currentTime >= lastActivityTime) { + timeSinceActivity = currentTime - lastActivityTime; + } else { + timeSinceActivity = (UINT32_MAX - lastActivityTime) + currentTime + 1; + } + + if (timeSinceActivity < ACTIVE_THRESHOLD_MS) { + return ACTIVE_INTERVAL_MS; + } else if (timeSinceActivity < MEDIUM_THRESHOLD_MS) { + return MEDIUM_INTERVAL_MS; + } else { + return IDLE_INTERVAL_MS; + } } int32_t WebServerThread::runOnce() @@ -189,8 +221,7 @@ int32_t WebServerThread::runOnce() ESP.restart(); } - // Loop every 5ms. - return (5); + return getAdaptiveInterval(); } void initWebServer() diff --git a/src/mesh/http/WebServer.h b/src/mesh/http/WebServer.h index 815d87432..e7a29a5a7 100644 --- a/src/mesh/http/WebServer.h +++ b/src/mesh/http/WebServer.h @@ -10,13 +10,17 @@ void createSSLCert(); class WebServerThread : private concurrency::OSThread { + private: + uint32_t lastActivityTime = 0; public: WebServerThread(); uint32_t requestRestart = 0; + void markActivity(); protected: virtual int32_t runOnce() override; + int32_t getAdaptiveInterval(); }; extern WebServerThread *webServerThread; diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp index ffc789275..2b1730e9c 100644 --- a/src/modules/ExternalNotificationModule.cpp +++ b/src/modules/ExternalNotificationModule.cpp @@ -94,8 +94,8 @@ int32_t ExternalNotificationModule::runOnce() // audioThread->isPlaying() also handles actually playing the RTTTL, needs to be called in loop isRtttlPlaying = isRtttlPlaying || audioThread->isPlaying(); #endif - if ((nagCycleCutoff < millis()) && !isRtttlPlaying) { - // let the song finish if we reach timeout + if ((nagCycleCutoff <= millis())) { + // Turn off external notification immediately when timeout is reached, regardless of song state nagCycleCutoff = UINT32_MAX; LOG_INFO("Turning off external notification: "); for (int i = 0; i < 3; i++) { @@ -103,7 +103,6 @@ int32_t ExternalNotificationModule::runOnce() externalTurnedOn[i] = 0; LOG_INFO("%d ", i); } - 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 diff --git a/src/modules/RangeTestModule.cpp b/src/modules/RangeTestModule.cpp index 3d78d0dc9..026b3028d 100644 --- a/src/modules/RangeTestModule.cpp +++ b/src/modules/RangeTestModule.cpp @@ -159,6 +159,7 @@ ProcessMessage RangeTestModuleRadio::handleReceived(const meshtastic_MeshPacket LOG_DEBUG("---- Received Packet:"); LOG_DEBUG("mp.from %d", mp.from); LOG_DEBUG("mp.rx_snr %f", mp.rx_snr); + LOG_DEBUG("mp.rx_rssi %f", mp.rx_rssi); LOG_DEBUG("mp.hop_limit %d", mp.hop_limit); LOG_DEBUG("---- Node Information of Received Packet (mp.from):"); LOG_DEBUG("n->user.long_name %s", n->user.long_name); @@ -234,8 +235,8 @@ bool RangeTestModuleRadio::appendFile(const meshtastic_MeshPacket &mp) } // 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")) { + if (fileToWrite.println("time,from,sender name,sender lat,sender long,rx lat,rx long,rx elevation,rx " + "snr,distance,hop limit,payload,rx rssi")) { LOG_INFO("File was written"); } else { LOG_ERROR("File write failed"); @@ -297,6 +298,8 @@ bool RangeTestModuleRadio::appendFile(const meshtastic_MeshPacket &mp) // TODO: If quotes are found in the payload, it has to be escaped. fileToAppend.printf("\"%s\"\n", p.payload.bytes); + fileToAppend.printf("%i,", mp.rx_rssi); // RX RSSI + fileToAppend.flush(); fileToAppend.close(); diff --git a/src/modules/TraceRouteModule.cpp b/src/modules/TraceRouteModule.cpp index fc2cc232b..5bdde1919 100644 --- a/src/modules/TraceRouteModule.cpp +++ b/src/modules/TraceRouteModule.cpp @@ -21,6 +21,11 @@ void TraceRouteModule::alterReceivedProtobuf(meshtastic_MeshPacket &p, meshtasti { const meshtastic_Data &incoming = p.decoded; + // Update next-hops using returned route + if (incoming.request_id) { + updateNextHops(p, r); + } + // Insert unknown hops if necessary insertUnknownHops(p, r, !incoming.request_id); @@ -153,6 +158,65 @@ void TraceRouteModule::alterReceivedProtobuf(meshtastic_MeshPacket &p, meshtasti } } +void TraceRouteModule::updateNextHops(meshtastic_MeshPacket &p, meshtastic_RouteDiscovery *r) +{ + // E.g. if the route is A->B->C->D and we are B, we can set C as next-hop for C and D + // Similarly, if we are C, we can set D as next-hop for D + // If we are A, we can set B as next-hop for B, C and D + + // First check if we were the original sender or in the original route + int8_t nextHopIndex = -1; + if (isToUs(&p)) { + nextHopIndex = 0; // We are the original sender, next hop is first in route + } else { + // Check if we are in the original route + for (uint8_t i = 0; i < r->route_count; i++) { + if (r->route[i] == nodeDB->getNodeNum()) { + nextHopIndex = i + 1; // Next hop is the one after us + break; + } + } + } + + // If we are in the original route, update the next hops + if (nextHopIndex != -1) { + // For every node after us, we can set the next-hop to the first node after us + NodeNum nextHop; + if (nextHopIndex == r->route_count) { + nextHop = p.from; // We are the last in the route, next hop is destination + } else { + nextHop = r->route[nextHopIndex]; + } + + if (nextHop == NODENUM_BROADCAST) { + return; + } + uint8_t nextHopByte = nodeDB->getLastByteOfNodeNum(nextHop); + + // For the rest of the nodes in the route, set their next-hop + // Note: if we are the last in the route, this loop will not run + for (int8_t i = nextHopIndex; i < r->route_count; i++) { + NodeNum targetNode = r->route[i]; + maybeSetNextHop(targetNode, nextHopByte); + } + + // Also set next-hop for the destination node + maybeSetNextHop(p.from, nextHopByte); + } +} + +void TraceRouteModule::maybeSetNextHop(NodeNum target, uint8_t nextHopByte) +{ + if (target == NODENUM_BROADCAST) + return; + + meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(target); + if (node && node->next_hop != nextHopByte) { + LOG_INFO("Updating next-hop for 0x%08x to 0x%02x based on traceroute", target, nextHopByte); + node->next_hop = nextHopByte; + } +} + void TraceRouteModule::processUpgradedPacket(const meshtastic_MeshPacket &mp) { if (mp.which_payload_variant != meshtastic_MeshPacket_decoded_tag || mp.decoded.portnum != meshtastic_PortNum_TRACEROUTE_APP) diff --git a/src/modules/TraceRouteModule.h b/src/modules/TraceRouteModule.h index a069f7157..dac422388 100644 --- a/src/modules/TraceRouteModule.h +++ b/src/modules/TraceRouteModule.h @@ -55,6 +55,12 @@ class TraceRouteModule : public ProtobufModule, // Call to add your ID to the route array of a RouteDiscovery message void appendMyIDandSNR(meshtastic_RouteDiscovery *r, float snr, bool isTowardsDestination, bool SNRonly); + // Update next-hops in the routing table based on the returned route + void updateNextHops(meshtastic_MeshPacket &p, meshtastic_RouteDiscovery *r); + + // Helper to update next-hop for a single node + void maybeSetNextHop(NodeNum target, uint8_t nextHopByte); + /* Call to print the route array of a RouteDiscovery message. Set origin to where the request came from. Set dest to the ID of its destination, or NODENUM_BROADCAST if it has not yet arrived there. */ diff --git a/src/nimble/NimbleBluetooth.cpp b/src/nimble/NimbleBluetooth.cpp index 9accf23c6..6238031f6 100644 --- a/src/nimble/NimbleBluetooth.cpp +++ b/src/nimble/NimbleBluetooth.cpp @@ -49,7 +49,7 @@ NimBLECharacteristic *logRadioCharacteristic; NimBLEServer *bleServer; static bool passkeyShowing; -static std::atomic nimbleBluetoothConnHandle{-1}; // actual handles are uint16_t, so -1 means "no connection" +static std::atomic nimbleBluetoothConnHandle{BLE_HS_CONN_HANDLE_NONE}; // BLE_HS_CONN_HANDLE_NONE means "no connection" class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread { @@ -144,21 +144,28 @@ class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread protected: virtual int32_t runOnce() override { - bool shouldBreakAndRetryLater = false; - while (runOnceHasWorkToDo()) { - // Important that we service onRead first, because the onRead callback blocks NimBLE until we clear - // onReadCallbackIsWaitingForData. - shouldBreakAndRetryLater = runOnceHandleToPhoneQueue(); // push data from getFromRadio to onRead - runOnceHandleFromPhoneQueue(); // pull data from onWrite to handleToRadio + /* + PROCESS fromPhoneQueue BEFORE toPhoneQueue: - if (shouldBreakAndRetryLater) { - // onRead still wants data, but it's not available yet. Return so we can try again when a packet may be ready. -#ifdef DEBUG_NIMBLE_ON_READ_TIMING - LOG_INFO("BLE runOnce breaking to retry later (leaving onRead waiting)"); -#endif - return 100; // try again in 100ms - } + In normal STATE_SEND_PACKETS operation, it's unlikely that we'll have both writes and reads to process at the same + time, because either onWrite or onRead will trigger this runOnce. And in STATE_SEND_PACKETS, it's generally ok to + service either the reads or writes first. + + However, during the initial setup wantConfig packet, the clients send a write and immediately send a read, and they + expect the read will respond to the write. (This also happens when a client goes from STATE_SEND_PACKETS back to + another wantConfig, like the iOS client does when requesting the nodedb after requesting the main config only.) + + So it's safest to always service writes (fromPhoneQueue) before reads (toPhoneQueue), so that any "synchronous" + write-then-read sequences from the client work as expected, even if this means we block onRead for a while: this is + what the client wants! + */ + + // PHONE -> RADIO: + runOnceHandleFromPhoneQueue(); // pull data from onWrite to handleToRadio + + // RADIO -> PHONE: + runOnceHandleToPhoneQueue(); // push data from getFromRadio to onRead } // the run is triggered via NimbleBluetoothToRadioCallback and NimbleBluetoothFromRadioCallback @@ -171,9 +178,9 @@ class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread // Prefer high throughput during config/setup, at the cost of high power consumption (for a few seconds) if (bleServer && isConnected()) { - int32_t conn_handle = nimbleBluetoothConnHandle.load(); - if (conn_handle != -1) { - requestHighThroughputConnection(static_cast(conn_handle)); + uint16_t conn_handle = nimbleBluetoothConnHandle.load(); + if (conn_handle != BLE_HS_CONN_HANDLE_NONE) { + requestHighThroughputConnection(conn_handle); } } } @@ -184,9 +191,9 @@ class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread // Switch to lower power consumption BLE connection params for steady-state use after config/setup is complete if (bleServer && isConnected()) { - int32_t conn_handle = nimbleBluetoothConnHandle.load(); - if (conn_handle != -1) { - requestLowerPowerConnection(static_cast(conn_handle)); + uint16_t conn_handle = nimbleBluetoothConnHandle.load(); + if (conn_handle != BLE_HS_CONN_HANDLE_NONE) { + requestLowerPowerConnection(conn_handle); } } } @@ -220,12 +227,8 @@ class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread } } - bool runOnceHandleToPhoneQueue() + void runOnceHandleToPhoneQueue() { - // Returns false normally. - // Returns true if we should break out of runOnce and retry later, such as setup states where getFromRadio returns 0 - // bytes. - // Stack buffer for getFromRadio packet uint8_t fromRadioBytes[meshtastic_FromRadio_size] = {0}; size_t numBytes = 0; @@ -234,28 +237,15 @@ class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread numBytes = getFromRadio(fromRadioBytes); if (numBytes == 0) { - // Client expected a read, but we have nothing to send. - // Returning a 0-byte packet breaks clients during the config phase, so we have to block onRead until there's a - // packet ready. - if (isSendingPackets()) { - // In STATE_SEND_PACKETS, it is 100% OK to return a 0-byte response, as we expect clients to do read beyond - // notifies regularly, to make sure they have nothing else to read. -#ifdef DEBUG_NIMBLE_ON_READ_TIMING - LOG_DEBUG("BLE getFromRadio returned numBytes=0, but in STATE_SEND_PACKETS, so clearing " - "onReadCallbackIsWaitingForData flag"); -#endif - } else { - // In other states, this breaks clients. - // Return early, leaving onReadCallbackIsWaitingForData==true so onRead knows to try again. - // This gives runOnce a chance to handleToRadio and produce a response. -#ifdef DEBUG_NIMBLE_ON_READ_TIMING - LOG_DEBUG("BLE getFromRadio returned numBytes=0. Blocking onRead until we have data"); -#endif + /* + Client expected a read, but we have nothing to send. - // Return true to tell runOnce to shouldBreakAndRetryLater, so we don't busy-loop in runOnce even though - // onRead is still waiting! - return true; - } + In STATE_SEND_PACKETS, it is 100% OK to return a 0-byte response, as we expect clients to do read beyond + notifies regularly, to make sure they have nothing else to read. + + In other states, this is fine **so long as we've already processed pending onWrites first**, because the client + may requesting wantConfig and immediately doing a read. + */ } else { // Push to toPhoneQueue, protected by toPhoneMutex. Hold the mutex as briefly as possible. if (toPhoneQueueSize < NIMBLE_BLUETOOTH_TO_PHONE_QUEUE_SIZE) { @@ -282,8 +272,6 @@ class BluetoothPhoneAPI : public PhoneAPI, public concurrency::OSThread // Clear the onReadCallbackIsWaitingForData flag so onRead knows it can proceed. onReadCallbackIsWaitingForData = false; // only clear this flag AFTER the push } - - return false; } bool runOnceHasWorkFromPhone() { return fromPhoneQueueSize > 0; } @@ -466,10 +454,6 @@ class NimbleBluetoothFromRadioCallback : public NimBLECharacteristicCallbacks virtual void onRead(NimBLECharacteristic *pCharacteristic) #endif { - // In some cases, it seems a new connection starts with a read. - // The API has no bytes to send, leading to a timeout. This short-circuits this problem. - if (!bluetoothPhoneAPI->isConnected()) - return; // CAUTION: This callback runs in the NimBLE task!!! Don't do anything except communicate with the main task's runOnce. int currentReadCount = bluetoothPhoneAPI->readCount.fetch_add(1); @@ -726,7 +710,7 @@ class NimbleBluetoothServerCallback : public NimBLEServerCallbacks // Clear the last ToRadio packet buffer to avoid rejecting first packet from new connection memset(lastToRadio, 0, sizeof(lastToRadio)); - nimbleBluetoothConnHandle = -1; // -1 means "no connection" + nimbleBluetoothConnHandle = BLE_HS_CONN_HANDLE_NONE; // BLE_HS_CONN_HANDLE_NONE means "no connection" #ifdef NIMBLE_TWO // Restart Advertising diff --git a/src/power.h b/src/power.h index 23eb95064..cdbdd3ea0 100644 --- a/src/power.h +++ b/src/power.h @@ -138,6 +138,7 @@ class Power : private concurrency::OSThread void reboot(); // open circuit voltage lookup table uint8_t low_voltage_counter; + int32_t lastLogTime = 0; #ifdef DEBUG_HEAP uint32_t lastheap; #endif diff --git a/src/sleep.cpp b/src/sleep.cpp index c6efb0efd..756582c74 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -244,6 +244,10 @@ void doDeepSleep(uint32_t msecToWake, bool skipPreflight = false, bool skipSaveN // pinMode(PIN_POWER_EN1, INPUT_PULLDOWN); #endif +#ifdef RAK_WISMESH_TAP_V2 + digitalWrite(SDCARD_CS, LOW); +#endif + #ifdef TRACKER_T1000_E #ifdef GNSS_AIROHA digitalWrite(GPS_VRTC_EN, LOW);