Repository navigation
feat(rp2350w): add BTstack BLE transport - #3863
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe change adds RP2350 BTstack BLE transport, propagates board build settings, adds ESP32-C6-to-RP2350W OTA orchestration, supports OTA artifact serving and application, adds a Fastbuild executable override, and corrects PARLIO edge configuration. ChangesRP2350 BLE support
AutoResearch peer OTA
Build tooling and PARLIO correction
Estimated code review effort: 5 (Critical) | ~90 minutes Sequence Diagram(s)sequenceDiagram
participant BLEClient
participant BTstackGATT
participant RpBleRuntime
BLEClient->>BTstackGATT: Write JSON request
BTstackGATT->>RpBleRuntime: Queue GATT write
RpBleRuntime->>RpBleRuntime: Parse queued request
RpBleRuntime->>BTstackGATT: Send JSON notification
BTstackGATT->>BLEClient: Receive response
sequenceDiagram
participant Host
participant ESP32C6
participant RP2350W
Host->>ESP32C6: Upload firmware chunks
ESP32C6->>ESP32C6: Verify size and SHA-256
Host->>ESP32C6: Start artifact server
Host->>RP2350W: Queue HTTP update
RP2350W->>ESP32C6: Download firmware
RP2350W->>Host: Reconnect after reboot
Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
ci/tests/test_fbuild_compile_many.py (1)
25-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover invalid
FBUILD_EXECUTABLEvalues.This test covers only a valid file. Add a regression test that expects
FileNotFoundErrorfor a missing path. This protects the fail-fast behavior and prevents a future change from silently falling back toPATH.Suggested regression test
+def test_fbuild_executable_override_rejects_missing_binary( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + missing = tmp_path / "missing-fbuild" + monkeypatch.setenv("FBUILD_EXECUTABLE", str(missing)) + + with pytest.raises(FileNotFoundError, match="FBUILD_EXECUTABLE"): + fbuild_runner.get_fbuild_executable()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ci/tests/test_fbuild_compile_many.py` around lines 25 - 34, Extend the executable override tests around test_fbuild_executable_override_uses_explicit_local_binary with a missing-path case that sets FBUILD_EXECUTABLE to a nonexistent file and asserts fbuild_runner.get_fbuild_executable() raises FileNotFoundError, preserving fail-fast behavior without PATH fallback.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ci/boards.py`:
- Around line 581-587: Update to_platformio_ini() to collect lib_deps from
board_build_options together with project_root/additional_libs before emitting
configuration, then output exactly one combined lib_deps entry per environment.
Ensure the combined value preserves both board and additional dependencies, and
add coverage for the board-plus-additional dependency case.
In `@ci/ci-compile-pio-ci-working.py`:
- Around line 355-358: Propagate Board.lib_deps through both CLI builders: in
ci/ci-compile-pio-ci-working.py lines 355-358, append it as the board-level
lib_deps project option alongside board_build_options; in
ci/util/create_build_dir.py lines 392-394, merge board.lib_deps with
extra_packages and emit the combined dependencies as a single lib_deps project
option.
In `@src/platforms/arm/rp/ble_rp.cpp.hpp`:
- Around line 192-205: Update response_sink to enforce the negotiated ATT
notification payload limit using att_server_get_mtu(state->connection) - 3,
fragmenting oversized JSON responses into frames no larger than that limit. Send
fragments through att_server_request_to_send_notification and the ATT send-ready
callback, advancing only when the ACL buffer is available; preserve the existing
notification error handling for each fragment.
- Around line 197-202: Update the error log in the att_server_notify result
check to use an unsigned integer format and cast result to unsigned, avoiding
pointer interpretation of the u8 error code.
---
Nitpick comments:
In `@ci/tests/test_fbuild_compile_many.py`:
- Around line 25-34: Extend the executable override tests around
test_fbuild_executable_override_uses_explicit_local_binary with a missing-path
case that sets FBUILD_EXECUTABLE to a nonexistent file and asserts
fbuild_runner.get_fbuild_executable() raises FileNotFoundError, preserving
fail-fast behavior without PATH fallback.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: f54cce29-324b-4707-8b07-31f962a5794e
📒 Files selected for processing (10)
ci/boards.pyci/ci-compile-pio-ci-working.pyci/tests/test_fbuild_compile_many.pyci/tests/test_rp2350w_board_config.pyci/util/create_build_dir.pyci/util/fbuild_runner.pysrc/fl/net/ble.hsrc/platforms/arm/rp/_build.cpp.hppsrc/platforms/arm/rp/ble_rp.cpp.hppsrc/platforms/esp/32/drivers/ble/ble_esp32.cpp.hpp
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (5)
examples/AutoResearch/AutoResearchOta.h (1)
44-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePrefer
fl::span<fl::u8>for the chunk parameter.
writeOtaArtifactonly readsbytes.data()andbytes.size(). The header guideline requiresfl::span<T>for function parameters instead offl::vector<T>. The RPC lambda can keep itsfl::vector<fl::u8>binding signature and pass a span into this function.♻️ Proposed change
-fl::json writeOtaArtifact(fl::vector<fl::u8> bytes); +fl::json writeOtaArtifact(fl::span<const fl::u8> bytes);As per coding guidelines: "Use fl::span for function parameters instead of fl::vector or raw arrays".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/AutoResearch/AutoResearchOta.h` around lines 44 - 48, Update the writeOtaArtifact function declaration and corresponding definition to accept fl::span<fl::u8> instead of fl::vector<fl::u8>; keep the RPC lambda’s vector binding unchanged and pass that vector as a span when calling writeOtaArtifact.Source: Coding guidelines
ci/autoresearch/phases.py (1)
2501-2502: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReturn an exit code instead of raising.
_run_tests_or_special_modereturnsinton every other failure path and prints a diagnostic first. This branch raisesRuntimeError, so a missing environment or build driver surfaces as a traceback. Match the surrounding style.♻️ Proposed change
- if ctx.final_environment is None or ctx.build_driver is None: - raise RuntimeError("Peer OTA firmware path is unavailable") + if ctx.final_environment is None or ctx.build_driver is None: + print( + f"{Fore.RED}\u274c Peer OTA firmware path is unavailable" + f"{Style.RESET_ALL}" + ) + return 1🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ci/autoresearch/phases.py` around lines 2501 - 2502, Update _run_tests_or_special_mode so the missing ctx.final_environment or ctx.build_driver branch prints a diagnostic and returns the appropriate nonzero exit code instead of raising RuntimeError, matching the surrounding failure paths and preserving its int return contract.ci/autoresearch/ota.py (2)
164-174: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the cleanup loop.
Both entries use the same
stop_methodvalue, so the pairing adds no information. Iterate over the clients directly and call"stopNet".♻️ Proposed change
- for client, stop_method in ((primary, "stopNet"), (peer, "stopNet")): + for client in (primary, peer): if client is None: continue try: - await client.send(stop_method, timeout=2.0) + await client.send("stopNet", timeout=2.0)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ci/autoresearch/ota.py` around lines 164 - 174, In the cleanup loop within the finally block, iterate directly over primary and peer instead of pairing each client with stop_method. Keep the None check and exception handling unchanged, and call client.send with the literal "stopNet" method before closing each client.
98-104: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider a larger chunk size for the firmware transfer.
Each iteration sends 512 raw bytes as one base64 RPC call and waits for a response. An RP2350W image of about 1 MB needs roughly 2000 round trips. At 115200 baud the base64 payload alone costs over two minutes, and the per-call latency adds more. The default
timeoutof 360.0 s can expire before the transfer completes. A larger chunk (for example 2048 or 4096 bytes) reduces the round trips proportionally, if the device RPC line buffer accepts the longer line.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ci/autoresearch/ota.py` around lines 98 - 104, Increase the OTA transfer chunk size used by the artifact loop in writeOtaArtifact from 512 bytes to a larger device-supported value, such as 2048 or 4096 bytes, while preserving base64 encoding, offset progression, and write failure handling.ci/tests/test_autoresearch_net.py (1)
117-120: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCompute the expected digest instead of hardcoding it.
run_ota_peer_autoresearchcomparesfinished["sha256"]against the digest of the artifact bytes. The literal here must matchhashlib.sha256(b"firmware").hexdigest(). If the fixture content changes, the test fails for a reason unrelated to the code under test. Derive the value from the same bytes.♻️ Proposed change
+ expected_sha256 = hashlib.sha256(b"firmware").hexdigest() ... "finishOtaArtifact": { "success": True, - "sha256": "c3bf47ea1f4a4a605470313cacb3a44f4a461f68c6faeab07e737610cb5ac835", + "sha256": expected_sha256, },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ci/tests/test_autoresearch_net.py` around lines 117 - 120, Update the finishOtaArtifact fixture in run_ota_peer_autoresearch to compute sha256 from the same b"firmware" bytes used by the artifact, using hashlib.sha256(...).hexdigest(), instead of a hardcoded digest.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ci/autoresearch/ota.py`:
- Around line 153-155: Guard the servedRequests conversion in the OTA artifact
status validation near rpc_data and otaArtifactStatus so non-numeric or missing
values produce the existing C6 failure message instead of escaping as ValueError
or TypeError. Preserve the current success requirement of at least one served
request and ensure the conversion failure is handled by the surrounding error
flow.
In `@ci/tests/test_autoresearch_net.py`:
- Line 86: Update test_ota_peer_stages_artifact_without_a_host_wifi_manager to
annotate tmp_path as Path, adding the pathlib.Path import if needed; preserve
the existing test behavior.
In `@examples/AutoResearch/AutoResearch.ino`:
- Around line 606-608: Update pollOtaArtifactUpdate so the synchronous
HTTPUpdate::update download cannot exceed the watchdog interval: either
temporarily disable the watchdog for the OTA operation and restore it afterward,
or register an HTTPUpdate progress callback that calls
FastLED.watchdog().feed().
In `@examples/AutoResearch/AutoResearchOta.cpp`:
- Around line 128-136: Change the read-result variable in the file hashing loop
to a signed type matching File::read’s int return value, so negative errors are
detected before passing the length to mbedtls_sha256_update. Apply the same
correction to the corresponding read handling in serveOtaArtifact, preserving
the existing cleanup and failure behavior.
- Around line 149-154: Move the served_requests increment in serveOtaArtifact
until after the artifact file has been successfully transferred, so missing or
invalid files returning 404 are not counted. Preserve the existing error path
and increment only on the successful response path used by
run_ota_peer_autoresearch.
- Around line 155-170: Remove the Content-Length header from the OTA response in
the file-serving handler and avoid conflicting framing by using httpd_resp_send
with an appropriate complete payload, or verify and preserve chunked transfer
only if the active Arduino-Pico OTA client explicitly supports it. Keep the
existing read, failure, and cleanup behavior intact.
In `@examples/AutoResearch/AutoResearchRemoteNetworkMethods.cpp`:
- Around line 382-384: Update the port validation in the queueOtaArtifactUpdate
call to reject values above UINT16_MAX as well as non-positive values,
preventing narrowing truncation; pass the port only when it is within the valid
uint16_t range, otherwise use the existing invalid-port value.
---
Nitpick comments:
In `@ci/autoresearch/ota.py`:
- Around line 164-174: In the cleanup loop within the finally block, iterate
directly over primary and peer instead of pairing each client with stop_method.
Keep the None check and exception handling unchanged, and call client.send with
the literal "stopNet" method before closing each client.
- Around line 98-104: Increase the OTA transfer chunk size used by the artifact
loop in writeOtaArtifact from 512 bytes to a larger device-supported value, such
as 2048 or 4096 bytes, while preserving base64 encoding, offset progression, and
write failure handling.
In `@ci/autoresearch/phases.py`:
- Around line 2501-2502: Update _run_tests_or_special_mode so the missing
ctx.final_environment or ctx.build_driver branch prints a diagnostic and returns
the appropriate nonzero exit code instead of raising RuntimeError, matching the
surrounding failure paths and preserving its int return contract.
In `@ci/tests/test_autoresearch_net.py`:
- Around line 117-120: Update the finishOtaArtifact fixture in
run_ota_peer_autoresearch to compute sha256 from the same b"firmware" bytes used
by the artifact, using hashlib.sha256(...).hexdigest(), instead of a hardcoded
digest.
In `@examples/AutoResearch/AutoResearchOta.h`:
- Around line 44-48: Update the writeOtaArtifact function declaration and
corresponding definition to accept fl::span<fl::u8> instead of
fl::vector<fl::u8>; keep the RPC lambda’s vector binding unchanged and pass that
vector as a span when calling writeOtaArtifact.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 16ccd081-4121-4a4b-9d9c-59d2051f0bf6
⛔ Files ignored due to path filters (1)
examples/AutoResearch/esp32c6_ota_fixture.csvis excluded by!**/*.csv
📒 Files selected for processing (10)
ci/autoresearch/ota.pyci/autoresearch/phases.pyci/autoresearch/staging.pyci/boards.pyci/tests/test_autoresearch_net.pyci/tests/test_rp2350w_board_config.pyexamples/AutoResearch/AutoResearch.inoexamples/AutoResearch/AutoResearchOta.cppexamples/AutoResearch/AutoResearchOta.hexamples/AutoResearch/AutoResearchRemoteNetworkMethods.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
- ci/tests/test_rp2350w_board_config.py
- ci/boards.py
| served = await rpc_data(peer, "otaArtifactStatus") | ||
| if not served.get("success") or int(served.get("servedRequests", 0)) < 1: | ||
| raise RuntimeError(f"C6 did not serve the RP2350W artifact: {served}") |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Guard the servedRequests conversion.
int(served.get("servedRequests", 0)) raises ValueError or TypeError when the device returns a non-numeric value. Neither exception is in the handler tuple at Line 161, so the run aborts with a traceback instead of the failure message.
🐛 Proposed fix
served = await rpc_data(peer, "otaArtifactStatus")
- if not served.get("success") or int(served.get("servedRequests", 0)) < 1:
+ served_requests = served.get("servedRequests", 0)
+ if not served.get("success") or not isinstance(served_requests, int) or served_requests < 1:
raise RuntimeError(f"C6 did not serve the RP2350W artifact: {served}")📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| served = await rpc_data(peer, "otaArtifactStatus") | |
| if not served.get("success") or int(served.get("servedRequests", 0)) < 1: | |
| raise RuntimeError(f"C6 did not serve the RP2350W artifact: {served}") | |
| served = await rpc_data(peer, "otaArtifactStatus") | |
| served_requests = served.get("servedRequests", 0) | |
| if not served.get("success") or not isinstance(served_requests, int) or served_requests < 1: | |
| raise RuntimeError(f"C6 did not serve the RP2350W artifact: {served}") |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ci/autoresearch/ota.py` around lines 153 - 155, Guard the servedRequests
conversion in the OTA artifact status validation near rpc_data and
otaArtifactStatus so non-numeric or missing values produce the existing C6
failure message instead of escaping as ValueError or TypeError. Preserve the
current success requirement of at least one served request and ensure the
conversion failure is handled by the surrounding error flow.
| peer.close.assert_awaited_once() | ||
|
|
||
|
|
||
| def test_ota_peer_stages_artifact_without_a_host_wifi_manager(tmp_path) -> None: |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Annotate the tmp_path parameter.
-def test_ota_peer_stages_artifact_without_a_host_wifi_manager(tmp_path) -> None:
+def test_ota_peer_stages_artifact_without_a_host_wifi_manager(tmp_path: Path) -> None:Add from pathlib import Path if the module does not import it yet.
As per coding guidelines: "All function parameters MUST have explicit type annotations".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ci/tests/test_autoresearch_net.py` at line 86, Update
test_ota_peer_stages_artifact_without_a_host_wifi_manager to annotate tmp_path
as Path, adding the pathlib.Path import if needed; preserve the existing test
behavior.
Source: Coding guidelines
| // A peer OTA request is queued by JSON-RPC, then executed from loop after | ||
| // the acceptance response is safely written to USB serial. | ||
| pollOtaArtifactUpdate(); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -n 'AUTORESEARCH_WATCHDOG_TIMEOUT_MS' -g '!**/build/**'Repository: FastLED/FastLED
Length of output: 153
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate and inspect the relevant ino and nearby watchdog/OTA code.
fd -a 'AutoResearch\.ino$|WATCHDOG|watchdog|HTTPUpdate' . | sed 's#^\./##' | head -200
echo '--- AutoResearch file size and relevant tags ---'
wc -l examples/AutoResearch/AutoResearch.ino
rg -n 'FL_WATCHDOG|watchdog|pollOtaArtifactUpdate|HTTPUpdate::update|HTTPUpdate|FastLED.watchdog|AUTORESEARCH_WATCHDOG_TIMEOUT_MS|WDT' examples/AutoResearch/AutoResearch.ino FastLED -g '!**/build/**' -g '!**/docs/**' || true
echo '--- lines 560-640 ---'
sed -n '560,640p' examples/AutoResearch/AutoResearch.ino
echo '--- definitions/context for watchdog types ---'
rg -n 'enum .*WATCHDOG|FL_WATCHDOG_|struct.*watchdog|class.*watchdog|FastLED.watchdog' . -g '!**/build/**' -g '!**/docs/**' | head -250Repository: FastLED/FastLED
Length of output: 30669
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- pollOtaArtifactUpdate definition/usages ---'
rg -n 'void pollOtaArtifactUpdate|pollOtaArtifactUpdate\(' examples/AutoResearch -g '!**/build/**'
echo '--- imports and OTA-related includes in AutoResearch.ino ---'
sed -n '1,260p' examples/AutoResearch/AutoResearch.ino
echo '--- AutoResearchNet OTA-related symbols/usages ---'
rg -n 'pollOta|OTA|HTTPUpdate|ArduinoOTA|esp_http_client|Update.begin|onStart|onEnd|onProgress' examples/AutoResearch -g '!**/build/**'
echo '--- inspect watchdog auto macro implementation ---'
sed -n '220,275p' src/fl/wdt/watchdog.hRepository: FastLED/FastLED
Length of output: 24540
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- pollOtaArtifactUpdate implementation ---'
sed -n '500,555p' examples/AutoResearch/AutoResearchOta.cpp
echo '--- fl/net OTA implementation locations ---'
rg -n 'class .*OTA|namespace .*ota|HTTPUpdate|HTTPUpdateServer|HTTPUpdateServer' . -g '!**/build/**' -g '!**/docs/**' | head -300
echo '--- OTA namespace definitions and update implementation ---'
fd -a '.*ota.*' src examples tests | sed 's#^\./##' | while read -r f; do
case "$f" in
*watchdog*|*build*|*docs*) continue ;;
*) ;;
esac
echo '<<< $f'
wc -l "$f"
done
echo '--- candidate OTA implementations ---'
python3 - <<'PY'
import subprocess, pathlib
files = subprocess.run(['git','ls-files'], text=True, check=True).stdout.splitlines()
for f in files:
low = f.lower()
if 'ota' in low or low.endswith(('.ino','.h','.cpp')):
if 'build' in f or 'docs' in f:
continue
try:
data = pathlib.Path(f).read_text(errors='ignore')
except Exception:
continue
if '/OTA' in data[:2000] or 'HTTPUpdate' in data[:2000] or 'OTA::begin' in data[:8000] or 'begin(' in data[:8000] and 'fl::net::OTA' in data[:8000]:
print(f)
PY
echo '--- HTTPUpdate references outside examples/AutoResearch ---'
rg -n 'HTTPUpdate|setUpdateCallback|setCheckScrolls|onStart|onEnd|onProgress|update\(.*fl::net::OTA|class OTA|struct OTA|namespace OTA' src fl tests -g '!**/build/**' || trueRepository: FastLED/FastLED
Length of output: 3004
Feed the watchdog during the blocking OTA download.
pollOtaArtifactUpdate calls HTTPUpdate::update(client, ...) synchronously, but loop() only feeds FastLED.watchdog() at scope start/end via FL_WATCHDG_AUTO(AUTORESEARCH_WATCHDOG_TIMEOUT_MS). A full firmware download can exceed the configured 5000 ms timeout and reset the board mid-upgrade. Disable the watchdog for this update or register an HTTPUpdate progress callback that calls FastLED.watchdog().feed().
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@examples/AutoResearch/AutoResearch.ino` around lines 606 - 608, Update
pollOtaArtifactUpdate so the synchronous HTTPUpdate::update download cannot
exceed the watchdog interval: either temporarily disable the watchdog for the
OTA operation and restore it afterward, or register an HTTPUpdate progress
callback that calls FastLED.watchdog().feed().
| while (file.available()) { | ||
| const size_t read = file.read(bytes, sizeof(bytes)); | ||
| if (read == 0) { | ||
| file.close(); | ||
| mbedtls_sha256_free(&context); | ||
| return false; | ||
| } | ||
| mbedtls_sha256_update(&context, bytes, read); | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Assign the File::read result to a signed type before you use it as a length.
File::read(uint8_t*, size_t) returns int. A read error returns -1. The code stores the result in const size_t read, so -1 becomes SIZE_MAX. The read == 0 guard does not catch it, and mbedtls_sha256_update then reads far past the buffer. The same pattern exists in serveOtaArtifact at Line 161.
🐛 Proposed fix
while (file.available()) {
- const size_t read = file.read(bytes, sizeof(bytes));
- if (read == 0) {
+ const int read = file.read(bytes, sizeof(bytes));
+ if (read <= 0) {
file.close();
mbedtls_sha256_free(&context);
return false;
}
- mbedtls_sha256_update(&context, bytes, read);
+ mbedtls_sha256_update(&context, bytes, static_cast<size_t>(read));
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| while (file.available()) { | |
| const size_t read = file.read(bytes, sizeof(bytes)); | |
| if (read == 0) { | |
| file.close(); | |
| mbedtls_sha256_free(&context); | |
| return false; | |
| } | |
| mbedtls_sha256_update(&context, bytes, read); | |
| } | |
| while (file.available()) { | |
| const int read = file.read(bytes, sizeof(bytes)); | |
| if (read <= 0) { | |
| file.close(); | |
| mbedtls_sha256_free(&context); | |
| return false; | |
| } | |
| mbedtls_sha256_update(&context, bytes, static_cast<size_t>(read)); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@examples/AutoResearch/AutoResearchOta.cpp` around lines 128 - 136, Change the
read-result variable in the file hashing loop to a signed type matching
File::read’s int return value, so negative errors are detected before passing
the length to mbedtls_sha256_update. Apply the same correction to the
corresponding read handling in serveOtaArtifact, preserving the existing cleanup
and failure behavior.
| static esp_err_t serveOtaArtifact(httpd_req_t* request) { | ||
| ++getOtaArtifactState().served_requests; | ||
| File file = LittleFS.open("/rp2350.bin", FILE_READ); | ||
| if (!file || file.isDirectory()) { | ||
| return httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "Artifact unavailable"); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Count only served requests that deliver the artifact.
serveOtaArtifact increments served_requests before it opens the file. A 404 response then still counts. run_ota_peer_autoresearch treats servedRequests >= 1 as proof that the RP2350W downloaded the image, so a failed download can pass the check. Increment the counter after the transfer completes.
🐛 Proposed fix
static esp_err_t serveOtaArtifact(httpd_req_t* request) {
- ++getOtaArtifactState().served_requests;
File file = LittleFS.open("/rp2350.bin", FILE_READ);and at the end of the successful path:
file.close();
+ ++getOtaArtifactState().served_requests;
return httpd_resp_send_chunk(request, nullptr, 0);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@examples/AutoResearch/AutoResearchOta.cpp` around lines 149 - 154, Move the
served_requests increment in serveOtaArtifact until after the artifact file has
been successfully transferred, so missing or invalid files returning 404 are not
counted. Preserve the existing error path and increment only on the successful
response path used by run_ota_peer_autoresearch.
| httpd_resp_set_type(request, "application/octet-stream"); | ||
| char length[16]; | ||
| snprintf(length, sizeof(length), "%u", static_cast<unsigned>(file.size())); | ||
| httpd_resp_set_hdr(request, "Content-Length", length); | ||
| uint8_t bytes[512]; | ||
| while (file.available()) { | ||
| const size_t read = file.read(bytes, sizeof(bytes)); | ||
| if (read == 0 || httpd_resp_send_chunk(request, | ||
| reinterpret_cast<const char*>(bytes), | ||
| read) != ESP_OK) { | ||
| file.close(); | ||
| return ESP_FAIL; | ||
| } | ||
| } | ||
| file.close(); | ||
| return httpd_resp_send_chunk(request, nullptr, 0); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
esp_http_server httpd_resp_send_chunk Content-Length Transfer-Encoding chunked behavior
💡 Result:
The httpd_resp_send_chunk function in the ESP-IDF esp_http_server component is designed to send HTTP responses incrementally using the HTTP/1.1 chunked transfer encoding [1][2]. When you call httpd_resp_send_chunk for the first time, the server automatically manages the response headers [3]. It sends the HTTP status line, any configured content-type, and the Transfer-Encoding: chunked header [3]. Because it enforces chunked transfer encoding, it does not send a Content-Length header for the overall response; instead, it formats each individual chunk according to the HTTP chunked encoding specification (sending the chunk size in hexadecimal, followed by CRLF, the chunk data, and a final CRLF) [3]. Key behaviors include: 1. Automatic Header Management: On the first call to httpd_resp_send_chunk, the function automatically transmits the necessary headers, including Transfer-Encoding: chunked [3]. 2. Chunk Formatting: For every call (including the first), the function takes the provided buffer and prepends the chunk size in hexadecimal followed by CRLF, ensuring the client interprets the data as a chunk [3]. 3. Finalization: To signal the end of the response, you must call httpd_resp_send_chunk with a buf_len of 0 (often by passing NULL as the buffer) [1][4]. This transmits a final zero-length chunk, which is the standard mechanism to terminate a chunked HTTP response [3]. 4. Request Header Purging: Once the response process begins via this API, the original request headers are purged from memory to save resources [1][5]. If you need to access request headers later in your handler, you must cache them in separate buffers before sending any response data [1][5]. Note that while this function is the standard way to send partial or streaming data, it forces the use of Transfer-Encoding: chunked [6]. If your application requires sending partial data without chunked encoding (e.g., streaming raw bytes without the chunk overhead), the current esp_http_server API does not provide a native, supported method to do so, and developers often have to work around this by constructing raw headers manually or using lower-level socket operations [6][7].
Citations:
- 1: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html
- 2: https://github.com/espressif/esp-idf/blob/a9d0f22193/components/esp_http_server/include/esp_http_server.h
- 3: https://github.com/espressif/esp-idf/blob/12f36a02/components/esp_http_server/src/httpd_txrx.c
- 4: https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_http_server.html
- 5: https://esp-rs.github.io/esp-idf-sys/esp_idf_sys/fn.httpd_resp_send_chunk.html
- 6: esp_http_server: provide a method to send response preamble (IDFGH-13182) espressif/esp-idf#14121
- 7: http response: send partial data w/o chunk encoding (IDFGH-4867) espressif/esp-idf#6663
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate files =="
git ls-files | rg '(^|/)(AutoResearchOta\.cpp$|platformio\.ini$|CMakeLists\.txt|.*\.ino$|.*\.h$|.*\.cpp$|.*\.c$|library\.properties$|.*update.*)$' || true
echo
echo "== target file context =="
if [ -f examples/AutoResearch/AutoResearchOta.cpp ]; then
sed -n '1,240p' examples/AutoResearch/AutoResearchOta.cpp | nl -ba | sed -n '120,200p'
else
fd -a 'AutoResearchOta\.cpp$' .
fi
echo
echo "== HTTPUpdate mentions =="
rg -n "HTTPUpdate|Update\.begin\\(|onDownload|http\\.send|setHeader\\(\"Content-Length\"|Content-Length|httpd_resp_send_chunk|httpd_resp_send\\(" . -S || true
echo
echo "== dependency/version hints =="
for f in platformio.ini ArduinoOTA library.json library.properties CMakeLists.txt*; do
[ -f "$f" ] && { echo "--- $f"; sed -n '1,220p' "$f"; }
doneRepository: FastLED/FastLED
Length of output: 50373
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== target source context =="
sed -n '1,230p' examples/AutoResearch/AutoResearchOta.cpp | nl -ba | sed -n '1,230p'
echo
echo "== AutoResearchOta target lines 130-185 =="
sed -n '130,185p' examples/AutoResearch/AutoResearchOta.cpp | nl -ba -v130
echo
echo "== focused dependency/version hints =="
rg -n "(platform|framework|platformio|arduino|arduino-pico|rp2350|HTTPUpdate|ArduinoOTA|update|OTA)" platformio.ini library.properties CMakeLists.txt -S | head -n 200
echo
echo "== local Arduino OTA / Arduino Pico HTTP updates candidates =="
if [ -d "/root/.platformio/packages/framework-arduinoespressif32" ]; then
find /root/.platformio/packages/framework-arduinoespressif32 -type f \( -name 'HTTPUpdate.h' -o -name 'HTTPUpdate.cpp' \) -print 2>/dev/null || true
fi
if [ -d "/root/.platformio/packages/framework-arduino-rp2040" ]; then
find /root/.platformio/packages/framework-arduino-rp2040 -type f \( -name 'HTTPUpdate*.h' -o -name 'HTTPUpdate*.cpp' -o -name 'ota*.cpp' -o -name 'ota*.h' \) -print 2>/dev/null || true
fi
fd -a "HTTPUpdate\.(h|cpp)$|ota\.(h|cpp)$" ~/.platformio 2>/dev/null | head -n 200 || trueRepository: FastLED/FastLED
Length of output: 221
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== target source AutoResearchOta.cpp =="
sed -n '1,230p' examples/AutoResearch/AutoResearchOta.cpp
echo
echo "== dependency/version hints =="
rg -n "(platform|framework|platformio|arduino|arduino-pico|rp2350|HTTPUpdate|ArduinoOTA|update|OTA)" platformio.ini library.properties CMakeLists.txt -S || true
echo
echo "== OTA source files if present =="
for f in examples/OTA/OTA.ino examples/OTA/OTA.ino.cpp src fl/src; do
[ -e "$f" ] && { echo "--- $f"; sed -n '1,220p' "$f"; }
doneRepository: FastLED/FastLED
Length of output: 20451
🌐 Web query:
Arduino OTA HTTPUpdate chunked encoding Content-Length Transfer-Encoding chunked Arduino-pico RP2350
💡 Result:
For the arduino-pico core (which supports RP2040 and RP2350), chunked transfer-encoding support in the HTTPClient library was significantly overhauled in recent releases to address data loss issues [1][2]. As of arduino-pico release 4.6.1 (published July 2025), the core includes a rewrite of the HTTPClient chunked transfer-encoding handling [2]. Previously, getStreamPtr would return the raw WiFiClient (or equivalent transport), forcing users to manually parse chunked encoding headers and markers if they were present [1]. This manual approach often led to race conditions or incomplete data transfer, causing OTA updates to fail when servers responded with chunked-encoded streams [3]. The updated implementation introduces an HTTPStream class (a subclass of WiFiClient) that handles the stripping of chunk markers automatically [1]. This ensures that when using getStreamPtr, the application receives the raw payload without needing to process chunked encoding headers or markers manually [1][3]. Key points regarding OTA and chunked encoding in this environment: - If you are experiencing issues, ensure your arduino-pico core is updated to at least version 4.6.1 [2]. - The HTTPUpdate class relies on the underlying HTTPClient transport [4]. By using a modern version of the core, the HTTPUpdate process should be able to handle servers that force chunked encoding [1][2]. - Historically, if an OTA process failed due to missing Content-Length or Transfer-Encoding: chunked headers, common workarounds included forcing the server to use HTTP/1.0 (disabling chunking) or ensuring the server explicitly provided a Content-Length header [5][6]. These workarounds are generally no longer required for standard setups if the core is up to date [1][2].
Citations:
- 1: Rewrite HTTPClient chunked transfer-encoding earlephilhower/arduino-pico#3034
- 2: https://github.com/earlephilhower/arduino-pico/releases/tag/4.6.1
- 3: HTTP client drops data with chunked transport earlephilhower/arduino-pico#3029
- 4: https://arduino-pico.readthedocs.io/en/latest/ota.html
- 5: https://forum.arduino.cc/t/update-ota-get-request-doesnt-parse-content-length/863114
- 6: InvalidInput when decoding manifest due to HTTP 1.1 call chrisjoyce911/esp32FOTA#131
🌐 Web query:
esp_http_server httpd_resp_send_chunk set_content_type set_header Content-Length automatic headers
💡 Result:
When using the ESP-IDF esp_http_server component, the behavior regarding headers and chunked transfer encoding is as follows: 1. Automatic Chunked Encoding: The function httpd_resp_send_chunk() is specifically designed to use HTTP chunked-encoding [1][2]. When you call this function to send data in increments, the server automatically manages the transfer encoding and transmits the necessary chunked-encoding headers [1][3]. You do not need to manually set Transfer-Encoding: chunked. 2. Content-Length Header: Because httpd_resp_send_chunk() implements chunked-encoding, it does not use a Content-Length header [3]. Chunked encoding allows the server to send a response of unknown size, terminating the transmission when a chunk with a length of 0 is sent [1][2][4]. 3. Header Configuration: You can use httpd_resp_set_type() to set the Content-Type and httpd_resp_set_hdr() to append custom headers [1][5]. These functions should be called before the first httpd_resp_send_chunk() call [1][6]. Once the first chunk is sent, the server sends the status line, content type, and any additional headers configured via httpd_resp_set_hdr() [3]. After the first chunk, the request headers are purged, and you cannot modify response headers [1][4]. 4. Finalizing: To properly terminate the chunked response, you must call httpd_resp_send_chunk(r, NULL, 0) [2][4]. If your application requires a specific Content-Length header, you must have the entire response buffer available beforehand and use httpd_resp_send() instead of httpd_resp_send_chunk(), which sends the complete response in a single operation [1][2][6]. Currently, the esp_http_server component does not support sending partial data without chunked encoding [7].
Citations:
- 1: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html
- 2: https://github.com/espressif/esp-idf/blob/master/components/esp_http_server/include/esp_http_server.h
- 3: https://github.com/espressif/esp-idf/blob/12f36a02/components/esp_http_server/src/httpd_txrx.c
- 4: https://esp-rs.github.io/esp-idf-sys/esp_idf_sys/fn.httpd_resp_send_chunk.html
- 5: https://esp-rs.github.io/esp-idf-sys/esp_idf_sys/fn.httpd_resp_set_hdr.html
- 6: https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/protocols/esp_http_server.html
- 7: http response: send partial data w/o chunk encoding (IDFGH-4867) espressif/esp-idf#6663
🌐 Web query:
"esp_http_server" "httpd_resp_set_hdr" "Content-Length" "httpd_resp_send_chunk"
💡 Result:
In the ESP-IDF esp_http_server component, the use of httpd_resp_send_chunk() automatically triggers chunked transfer encoding [1][2]. Because the server does not know the total size of the response beforehand when using incremental chunks, it does not (and cannot) set a static Content-Length header [3][4]. Key technical points: 1. Chunked Encoding: When you call httpd_resp_send_chunk(), the esp_http_server implementation manages the HTTP response headers to include Transfer-Encoding: chunked [3]. It handles the formatting of the response into chunks, including sending the appropriate hex-encoded length prefix and CRLF delimiters for each chunk [3]. 2. Content-Length Header: You should not attempt to manually set Content-Length using httpd_resp_set_hdr() when using httpd_resp_send_chunk() [5]. Manually setting this header can lead to conflicts or invalid HTTP responses, as the HTTP protocol precludes the use of Content-Length when Transfer-Encoding: chunked is active. 3. Proper Header Management: Use httpd_resp_set_hdr() only for additional custom headers (e.g., Connection, WWW-Authenticate) [1][6][7]. Essential headers like Content-Type must be set using dedicated API functions such as httpd_resp_set_type() [5]. Attempting to set these via httpd_resp_set_hdr() can result in duplicate headers or undesired behavior [5]. If you require a specific Content-Length header, you must have the entire response available in a single buffer and use httpd_resp_send() instead of httpd_resp_send_chunk() [1][2]. In that scenario, the server will automatically calculate and send the Content-Length based on the length of your provided buffer.
Citations:
- 1: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html
- 2: https://github.com/espressif/esp-idf/blob/110d230e3/components/esp_http_server/include/esp_http_server.h
- 3: https://github.com/espressif/esp-idf/blob/12f36a02/components/esp_http_server/src/httpd_txrx.c
- 4: https://esp32.com/viewtopic.php?t=28363
- 5: https://esp32.com/viewtopic.php?t=7829
- 6: https://docs.espressif.com/projects/esp-idf/en/v6.0/esp32/api-reference/protocols/esp_http_server.html
- 7: https://github.com/espressif/esp-idf/blob/master/examples/protocols/http_server/simple/main/main.c
🌐 Web query:
"esp_http_server" "httpd_resp_send_chunk" "header" "Content-Length"
💡 Result:
The esp_http_server library in ESP-IDF does not include a Content-Length header when using httpd_resp_send_chunk [1][2]. When you use httpd_resp_send_chunk, the server is designed to send the HTTP response using Transfer-Encoding: chunked [1][2]. According to the HTTP/1.1 specification (RFC 7230/9112), a Content-Length header must not be sent when Transfer-Encoding is used, as the chunked encoding provides its own mechanism for determining the end of the message body [2]. Internally, the implementation of httpd_resp_send_chunk explicitly sets the response to use chunked transfer encoding [2]. The initial headers sent by this function consist of the HTTP status, the content type, and the Transfer-Encoding: chunked header [2]. It does not calculate or include a Content-Length header, as that would contradict the chunked transfer mechanism [2].
Citations:
- 1: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html
- 2: https://github.com/espressif/esp-idf/blob/12f36a02/components/esp_http_server/src/httpd_txrx.c
Don’t add Content-Length to a chunked OTA response.
httpd_resp_send_chunk sends HTTP responses as chunked transfer encoding. Setting Content-Length adds conflicting OTA framing, so use httpd_resp_send with the full buffer instead, or confirm this Arduino-Pico OTA client accepts chunked responses for the active core version.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@examples/AutoResearch/AutoResearchOta.cpp` around lines 155 - 170, Remove the
Content-Length header from the OTA response in the file-serving handler and
avoid conflicting framing by using httpd_resp_send with an appropriate complete
payload, or verify and preserve chunked transfer only if the active Arduino-Pico
OTA client explicitly supports it. Keep the existing read, failure, and cleanup
behavior intact.
| const int64_t port = args["port"].as_int().value(); | ||
| return queueOtaArtifactUpdate(args["host"].as_string().value().c_str(), | ||
| port > 0 ? static_cast<uint16_t>(port) : 0); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Reject port values outside the uint16_t range.
static_cast<uint16_t>(port) truncates. A request with port: 70000 becomes port 4464 and the update targets the wrong endpoint. Validate the upper bound too.
🐛 Proposed fix
const int64_t port = args["port"].as_int().value();
+ if (port <= 0 || port > 65535) {
+ fl::json response = fl::json::object();
+ response.set("success", false);
+ response.set("error", "Port out of range");
+ return response;
+ }
return queueOtaArtifactUpdate(args["host"].as_string().value().c_str(),
- port > 0 ? static_cast<uint16_t>(port) : 0);
+ static_cast<uint16_t>(port));📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const int64_t port = args["port"].as_int().value(); | |
| return queueOtaArtifactUpdate(args["host"].as_string().value().c_str(), | |
| port > 0 ? static_cast<uint16_t>(port) : 0); | |
| const int64_t port = args["port"].as_int().value(); | |
| if (port <= 0 || port > 65535) { | |
| fl::json response = fl::json::object(); | |
| response.set("success", false); | |
| response.set("error", "Port out of range"); | |
| return response; | |
| } | |
| return queueOtaArtifactUpdate(args["host"].as_string().value().c_str(), | |
| static_cast<uint16_t>(port)); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@examples/AutoResearch/AutoResearchRemoteNetworkMethods.cpp` around lines 382
- 384, Update the port validation in the queueOtaArtifactUpdate call to reject
values above UINT16_MAX as well as non-positive values, preventing narrowing
truncation; pass the port only when it is within the valid uint16_t range,
otherwise use the existing invalid-port value.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ci/autoresearch/ble.py`:
- Around line 131-134: Update the BLE notification loop around
ble_iface.read_lines() to process each yielded line independently rather than
appending it to the shared notification_payload buffer. Pass the current line
directly through the existing payload parsing and json.loads flow, preserving
the handling of each complete JSON-RPC notification even when a later line is
malformed.
In `@src/platforms/arm/rp/ble_rp.cpp.hpp`:
- Around line 42-44: Add an outbound FIFO around notification handling in the
response sink and send-ready flow, preserving each complete RPC response until
all of its chunks are transmitted. Advance and clear the current response only
after its final chunk is sent, then schedule the next queued response; add a
regression test that generates two responses before the send-ready callback
completes and verifies both are delivered intact.
- Around line 171-172: Update onDisconnected to clear notification registration
state when a pending registration exists: set state->notification_scheduled and
runtime.notification_callback_pending to false alongside clearing
notification_payload and notification_offset. Ensure this prevents new writes
from being blocked and callbacks from accessing cleared payload data after
disconnect.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 3b0c9aa9-aab7-4e8b-942f-48e6a3f68e78
📒 Files selected for processing (8)
ci/autoresearch/ble.pyci/boards.pyci/ci-compile-pio-ci-working.pyci/tests/test_board_to_platformio_ini.pyci/tests/test_fbuild_compile_many.pyci/tests/test_rp2350w_board_config.pyci/util/create_build_dir.pysrc/platforms/arm/rp/ble_rp.cpp.hpp
🚧 Files skipped from review as they are similar to previous changes (4)
- ci/util/create_build_dir.py
- ci/tests/test_rp2350w_board_config.py
- ci/tests/test_fbuild_compile_many.py
- ci/boards.py
| notification_payload = "" | ||
| async for line in ble_iface.read_lines(timeout=3.0): | ||
| payload = line | ||
| notification_payload += line | ||
| payload = notification_payload |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 8 \
'read_lines|notification_payload|json\.loads|REMOTE: |pong|notify' \
ci/autoresearch/ble.py ci/util/ble_interface.py ci/util/serial_interface.py ci/testsRepository: FastLED/FastLED
Length of output: 41179
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
ble = Path("ci/autoresearch/ble.py").read_text(encoding="utf-8")
print("File: ci/autoresearch/ble.py")
for i, line in enumerate(ble.splitlines(), 1), []:
if 125 <= i <= 155:
print(f"{i:4}: {line}")
print("\nChanged accumulation loop parse behavior:")
lines = ['{"jsonrpc":"2.0","id":1,"result":{"message":"non-pong"}}', '{"jsonrpc":"2.0","id":1,"result":{"message":"pong"}}']
notification_payload = ""
for line in lines:
notification_payload += line
payload = notification_payload
parsed = None
try:
parsed = __import__("json").loads(payload)
except Exception as exc:
exc_type = type(exc).__name__
print(f"notification_payload={notification_payload!r}")
print(f"payload={payload!r}, parsed={parsed!r}, exception_type={getattr(exc, '_type', None)}")
PY
echo
echo "Inspect BLE interface implementation around read_lines and notification handler:"
sed -n '98,130p' ci/util/ble_interface.py | cat -n
echo
echo "Search BLE characteristic constants and notify payload formatting:"
rg -n 'BLE_CHAR_TX_UUID|BLE_CHAR_RX_UUID|remote|REMOTE|BLE_NOTIFY|start_notify|write_gatt_char|notification_handler' ci -SRepository: FastLED/FastLED
Length of output: 306
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
ble = Path("ci/autoresearch/ble.py").read_text(encoding="utf-8")
print("File: ci/autoresearch/ble.py")
lines = ble.splitlines()
for i in range(125, 156):
if i <= len(lines):
print(f"{i:4}: {lines[i-1]}")
print("\nChanged accumulation loop parse behavior:")
line_values = [
'{"jsonrpc":"2.0","id":1,"result":{"message":"non-pong"}}',
'{"jsonrpc":"2.0","id":1,"result":{"message":"pong"}}',
]
notification_payload = ""
for line in line_values:
notification_payload += line
payload = notification_payload
parsed = None
exc_value = None
try:
parsed = __import__("json").loads(payload)
except Exception as exc:
exc_value = type(exc).__name__
print(f"notification_payload={notification_payload!r}")
print(f"payload={payload!r}, parsed={parsed!r}, exception_type={exc_value}")
PY
echo
echo "Inspect BLE interface implementation around read_lines and notification handler:"
sed -n '98,130p' ci/util/ble_interface.py | cat -n
echo
echo "Search BLE characteristic constants and notify payload formatting:"
rg -n 'BLE_CHAR_TX_UUID|BLE_CHAR_RX_UUID|remote|REMOTE|BLE_NOTIFY|start_notify|write_gatt_char|notification_handler|notify' ci -SRepository: FastLED/FastLED
Length of output: 42403
Handle each BLE notification independently.
read_lines() yields one notification value per line, but this loop accumulates them. If one complete JSON-RPC line arrives and a later json.loads() cannot parse because the next value appends to the previous line, keep parsing completed lines instead of treating notification_payload as a shared fragment buffer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ci/autoresearch/ble.py` around lines 131 - 134, Update the BLE notification
loop around ble_iface.read_lines() to process each yielded line independently
rather than appending it to the shared notification_payload buffer. Pass the
current line directly through the existing payload parsing and json.loads flow,
preserving the handling of each complete JSON-RPC notification even when a later
line is malformed.
| fl::vector<u8> notification_payload; | ||
| size_t notification_offset = 0; | ||
| bool notification_scheduled = false; |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Queue complete responses before notification scheduling.
response_sink clears and replaces the single notification_payload while an earlier response can still have unsent chunks. If two RPC responses are produced before the first transfer completes, the client receives a truncated first response and loses its remaining bytes.
Add an outbound FIFO. Advance to the next response only after all chunks of the current response are sent. Add a regression test that produces two responses before the send-ready callback completes.
Also applies to: 262-268
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/platforms/arm/rp/ble_rp.cpp.hpp` around lines 42 - 44, Add an outbound
FIFO around notification handling in the response sink and send-ready flow,
preserving each complete RPC response until all of its chunks are transmitted.
Advance and clear the current response only after its final chunk is sent, then
schedule the next queued response; add a regression test that generates two
responses before the send-ready callback completes and verifies both are
delivered intact.
| state->notification_payload.clear(); | ||
| state->notification_offset = 0; |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
For the BTstack version bundled with Arduino-Pico, when a connection disconnects while att_server_request_to_send_notification is pending, is the registered callback guaranteed to run? If not, what supported API or lifecycle pattern cancels or resets the pending notification callback safely?
💡 Result:
In BTstack, when you register a request via att_server_request_to_send_notification, there is no explicit or guaranteed API-level cancellation mechanism to remove a pending callback specifically for this request if the connection disconnects before it executes [1][2][3]. Because BTstack manages these registrations internally using linked lists, the application should handle the connection state explicitly [4][5]. To safely manage the lifecycle of such requests, you should implement the following patterns: 1. Use Connection State Tracking: Maintain a record of active connection handles (e.g., using a variable or a flag). When you receive an HCI_EVENT_DISCONNECTION_COMPLETE event, ensure that any pending application-level logic—including attempts to send notifications—is halted [6]. 2. Validate Connection Handle in Callback: Since the callback may be triggered or pending in the run loop queue, verify the connection handle inside your registered callback function before calling att_server_notify [7]. If the connection has already disconnected, the handle will be invalid, and your callback should simply return without attempting to send the notification [7]. 3. Manage Callback Object Lifecycle: The btstack_context_callback_registration_t object should persist only as long as it is needed. Because there is no "unregister" function for this specific request, avoid re-registering or re-using the same registration object if you are not certain that a previous request has either completed or been abandoned [3][4]. 4. Avoid Stale References: If your callback context (the data pointer passed in the registration) points to memory that is local or is cleared upon disconnection, ensure the callback function performs a null check or validates that the context is still valid before dereferencing it [4][5]. In summary, the safest pattern is to treat the notification request as "fire-and-forget" relative to the stack, but rely on your application's connection event handler to ignore or drop any pending notification logic when the connection handle is no longer valid [7][6].
Citations:
- 1: https://bluekitchen-gmbh.com/btstack/appendix/att_server/
- 2: https://bluekitchen-gmbh.com/btstack/appendix/apis/
- 3: https://sourcevu.sysprogs.com/rp2040/lib/btstack/symbols/att_server_request_to_send_notification
- 4: https://github.com/bluekitchen/btstack/blob/501e6d2b/src/btstack_defines.h
- 5: https://sourcevu.sysprogs.com/rp2040/lib/btstack/symbols/btstack_context_callback_registration_t
- 6: https://github.com/bluekitchen/btstack/blob/master/port/arduino/BTstack.cpp
- 7: BLE Notifications: att_server_handle_can_send_now should not be static, or the documentation is incorrect. bluekitchen/btstack#531
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Repository files matching target:"
fd -a 'ble_rp\.cpp\.hpp$|cpp-standards\.md$' . | sed 's#^\./##'
echo
echo "Target excerpt:"
sed -n '130,200p' src/platforms/arm/rp/ble_rp.cpp.hpp
echo
echo "Notify/registration declarations and related symbols:"
rg -n "notification_(scheduled|callback_pending|status|payload|offset)|Notification|att_server_request_to_send_notification|btstack_context_callback_registration_t|onDisconnected" src/platforms/arm/rp src -g '*.cpp' -g '*.hpp' -g '*.h'Repository: FastLED/FastLED
Length of output: 10603
🌐 Web query:
BlueKitchen BTstack att_server_request_to_send_notification cancel pending when connection disconnects att_event_handler pending notification callback.
💡 Result:
In BlueKitchen BTstack, the function att_server_request_to_send_notification is used to register a callback that will be triggered when the Bluetooth stack is ready to send a notification [1][2]. If a connection disconnects while a notification request is pending, the stack typically handles this cleanup naturally via the event system. You should manage the lifecycle of your connection and the associated pending notification state by listening for the ATT_EVENT_DISCONNECTED event in your packet handler [3]. Key considerations for implementation: 1. Connection Lifecycle: When the ATT_EVENT_DISCONNECTED event is received for a specific connection handle, you should clear any internal flags or state associated with that connection [3]. This ensures that your application logic does not attempt to send further notifications or make new requests for that closed handle [3]. 2. Callback Safety: Because the notification callback is registered via a context structure (btstack_context_callback_registration_t), ensure that the memory for this structure and any associated context remains valid until the callback is triggered or the connection is explicitly closed [1][2]. 3. Event Handling: Your main packet handler should process ATT_EVENT_CAN_SEND_NOW for valid connections [3]. If the connection disconnects, the stack will no longer trigger the callback for that connection, effectively canceling the request [3]. By monitoring the disconnection event and resetting your connection state (e.g., setting the connection handle to HCI_CON_HANDLE_INVALID), you prevent the application from incorrectly processing or triggering logic for a stale connection [3].
Citations:
- 1: BLE Notifications: att_server_handle_can_send_now should not be static, or the documentation is incorrect. bluekitchen/btstack#531
- 2: https://github.com/bluekitchen/btstack/blob/501e6d2b/src/ble/att_server.h
- 3: https://github.com/bluekitchen/btstack/blob/master/example/gatt_streamer_server.c
🌐 Web query:
BlueKitchen BTstack att_server_request_to_send_notification source btstack_context_callback_registration queue disconnect callback.
💡 Result:
In BlueKitchen BTstack, att_server_request_to_send_notification is the recommended function to safely send a GATT notification [1]. Because Bluetooth Low Energy (BLE) operations are asynchronous and subject to flow control (e.g., full ACL buffers), directly calling att_server_notify may fail [1][2]. To use this function, you must register a btstack_context_callback_registration_t structure [3][4]. This structure contains a callback function pointer and a context pointer [4]. When the stack determines that it is possible to send, it invokes the registered callback [1]. Inside this callback, you should then call att_server_notify to transmit your data [1][2]. Regarding your query about the disconnect callback: btstack_context_callback_registration_t is used for scheduling tasks within the BTstack run loop [5][6]. It does not inherently handle connection state or automatic disconnection cleanup [6]. If you need to manage cleanup or disconnect-specific logic, you typically monitor the connection status via the standard packet handler, which receives HCI events such as HCI_EVENT_DISCONNECTION_COMPLETE [7]. If a connection is disconnected while a callback request is queued, the request remains associated with that connection handle (con_handle); however, because the connection no longer exists, the notification attempt inside the callback will fail, and you should ensure your application handles this gracefully by checking the connection status or clearing the registration [3]. Top results: [3][4][1][2]
Citations:
- 1: BLE Notifications: att_server_handle_can_send_now should not be static, or the documentation is incorrect. bluekitchen/btstack#531
- 2: BTstackLib LE Peripheral Notify client on Characteristic Change bluekitchen/btstack#551
- 3: https://bluekitchen-gmbh.com/btstack/appendix/att_server/
- 4: https://github.com/bluekitchen/btstack/blob/501e6d2b/src/btstack_defines.h
- 5: https://github.com/bluekitchen/btstack/blob/master/src/btstack_run_loop.c
- 6: https://sourcevu.sysprogs.com/rp2040/lib/btstack/symbols/btstack_context_callback_registration_t
- 7: https://bluekitchen-gmbh.com/btstack/appendix/apis.html
Reset notification registration state on disconnect.
onDisconnected still leaves state->notification_scheduled and runtime.notification_callback_pending set. If a request registers last and the connection drops before ATT_EVENT_CAN_SEND_NOW, new writes can be blocked and a disconnected callback can hit cleared notification_payload. Set both flags false when disconnecting while a pending registration exists.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/platforms/arm/rp/ble_rp.cpp.hpp` around lines 171 - 172, Update
onDisconnected to clear notification registration state when a pending
registration exists: set state->notification_scheduled and
runtime.notification_callback_pending to false alongside clearing
notification_payload and notification_offset. Ensure this prevents new writes
from being blocked and callbacks from accessing cleared payload data after
disconnect.
CI triage + why bench evidence is still missing (from #3864)Full bench transcript: #3864 (comment above). Summary for this PR: Neither red check is caused by this PR.
This PR's build cannot currently be produced from a clean checkout. Hardware is also still down. COM17 remains Recommend holding this PR un-merged until the fbuild release lands and the five HIL flows produce real transcripts. |
Correction — the QEMU
|
Branch updated — the two
|
| Check | Cause | Status |
|---|---|---|
build / build ×2 |
undefined reference to set_audioClock(int, long, unsigned long, bool) |
Fixed on master by #3866 — not a regression from this PR |
esp32s3_qemu_rmt |
qemu-system-xtensa: error while loading shared libraries: libslirp.so.0 |
Known-red environment flake, reproduces on master; tracked upstream at FastLED/fbuild#1266 |
So none of the three were caused by this branch. #3866 vendored PJRC's set_audioClock into pjrc_i2s_config.cpp.hpp — Teensyduino declares it in utility/imxrt_hw.h but the framework library that defines it was not being linked.
The merge also picks up the fbuild==2.5.15 pin (#3871), which carries the RP2350W deployment hardening from FastLED/fbuild#1263 that this PR's HIL validation depends on.
Still not mergeable
Per #3864 this PR needs bench evidence, and the RP2350W is not attached — fbuild port doctor --port COM17 reports NOT PRESENT, last seen 5d ago, i.e. a stale registry record rather than a fault. I am not merging without those HIL runs.
One correction to #3864's premise, though: the ESP32-C6 peer is available. COM9 was recorded there as an ESP32-S3, but 303A:1001 is Espressif's shared USB-Serial-JTAG PID and probing it returns chip_type='ESP32-C6'. Details in #3864 (comment).
…3956) (#3961) * fix(ota): harden RP2350W peer OTA accounting, framing and port range (#3956) Addresses the five CodeRabbit findings from #3863. **Success accounting.** `serveOtaArtifact` incremented `served_requests` before it opened the artifact, so a 404 or a mid-transfer send failure still counted. The host proves the RP2350W downloaded its image by asserting `servedRequests >= 1`, so a failed download reported success. The counter now bumps only after the final chunk is accepted, and a failed send terminates the chunked stream instead of leaving the connection open. **HTTP framing.** The same handler set `Content-Length` while sending via `httpd_resp_send_chunk`, which emits `Transfer-Encoding: chunked` — two conflicting framings in one response. The explicit length is dropped, leaving one standards-compliant mode. **Watchdog.** `pollOtaArtifactUpdate` runs a synchronous multi-second firmware download straight from `loop()`, while the sketch feeds the watchdog only at loop-scope entry and exit with a 5 s timeout — a normal download reset the board mid-flash-write. The window is now widened across the blocking call and restored to the sketch's timeout afterwards, so the board stays protected once the loop resumes rather than being left unguarded. **Port range.** `static_cast<uint16_t>(port)` truncated: 70000 became 4464 and 65537 became 1, silently targeting a different endpoint. The `port > 0` guard caught 65536 only because it happened to truncate to zero. Added `fl::net::tryParsePort`, a range-checked conversion covering the full [1, 65535] range, and routed both `applyOtaArtifact` and `runNetClientTest` through it — the latter previously had no range check at all. **Status parsing.** `int(served.get("servedRequests", 0))` raised ValueError/TypeError on a non-numeric device reply, and neither is in the caller's except tuple, so a malformed status aborted the run with a traceback instead of the failure message. Parsing is now total; anything that is not a plain non-negative int reads as zero served requests and surfaces as the ordinary failure. The artifact-server port reply is range-checked too. Verified: 283/283 host unit tests (new tests/fl/net/port.cpp), 15 new Python tests, 930 Python tests overall (one pre-existing unrelated QEMU failure that reproduces on clean master), bash lint clean, rp2350w and esp32c6 builds green. The new "port must be in [1, 65535]" string is present in the linked rp2350w firmware, confirming the validation is compiled in. Refs #3956 — the issue's final bullet (OTA build-marker, reboot, CDC/network recovery and serial RPC health proven on hardware) still needs a Pico 2 W and is not covered here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(ota): keep Content-Length, halt watchdog, don't fake a complete body Corrects three defects found reviewing the previous commit — two of which made that commit worse than the code it replaced. **Content-Length must stay.** Dropping it would have broken peer OTA outright, not fixed a framing conflict. In the pinned arduino-pico core (rp2040-5.7.0) `HTTPClient::_size` starts at -1 and is only ever assigned from a Content-Length header (HTTPClient.cpp:1111); HTTPUpdate requires `len > 0` or fails with HTTP_UE_SERVER_NOT_REPORT_SIZE (HTTPUpdate.cpp:232, :295). Every `applyOtaArtifact` would have returned "Server did not report size", and the C6 would never have bumped servedRequests. The #3956 review asked to "confirm this Arduino-Pico OTA client accepts chunked responses" — confirmed, and it does not: it decodes the chunked body but takes the image size from Content-Length, so both headers are required. **Re-arming the watchdog did nothing.** `Watchdog::begin()` clamps to FL_WATCHDOG_MAX_TIMEOUT_MS, which is 16777 ms on RP2350 (watchdog_rp.impl.hpp:47, :111) because the counter is 24-bit microseconds. The requested 120 s silently became ~16.8 s, so a real image download still reset the board mid-flash-write — the exact bug the change claimed to fix. The counter is now halted with `disable()` for the transfer and re-armed to the sketch timeout immediately after. **The error path faked a complete body.** A zero-length chunk is precisely the "body ended normally" signal, so emitting one after a failed read presented a half-written firmware image as a well-formed complete response. The failure path now returns ESP_FAIL without a terminator, dropping the connection mid-stream so the client detects the truncation. Tests updated accordingly and made tolerant of reformatting: the body extractor is shared, the watchdog assertions run over whitespace-collapsed source, and the tryParsePort call-site count is a lower bound so a future third caller does not break the suite. Verified: 283/283 host unit tests, 250 OTA/net/autoresearch Python tests (16 in the new file), bash lint clean, rp2350w and esp32c6 builds green. Refs #3956 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Refs #3832, #3861
Summary
--net-peer --ota) that never changes host WiFi or invokes a raw flasherVerification
Remaining validation
bash autoresearch rp2350w --net-peer --ota --upload-port COM17 --peer-environment esp32c6 --peer-upload-port COM9 --timeout 360sSummary by CodeRabbit
New Features
Enhancements
FBUILD_EXECUTABLE.Bug Fixes