5. Firmware Cloud Transport (mTLS HTTPS Primary, Legacy MQTTS, Codec & Retry Policy)
Repository:
Converters (planovi-converter)• Rule Prefix:BR-SYNC• Documented Rules: 7 • Open[TEAM_WHY_NEEDED]Questions: 2
1. Business Purpose & Actors
Guarantees at-least-once, strictly ordered, mutually authenticated (mTLS) delivery of encrypted SD FIFO records (Schema 3 telemetry, Schema 1 device events) and portable storage requests to Planovi Cloud over HTTPS (v1 production primary) or MQTTS (legacy/staging), while polling the cloud control plane for authoritative UTC time, desired configuration changes (with automatic 10-minute fail-safe host rollback), and remote operational commands.
- Actors: Autonomous
NetSysTask(cloud_client_process()), Public mTLS Nginx + Gateway (api.planovi.app:443/dev-telemetry.planovi.app:443), Optional Mosquitto MQTTS broker (:8883), Cloud Admin queuing commands/config changes.
2. All Features & End-to-End Flows
- Runtime Transport Selection (
src/net/cloud_client.c:849-851, 901-906, 1891):- Reads
cloud_transportfrom NVS:CLOUD_TRANSPORT_HTTPS (2)selects HTTPS exclusively (MQTT client is never allocated or connected);CLOUD_TRANSPORT_AUTO (0)orCLOUD_TRANSPORT_MQTT (1)selects MQTTS.
- Reads
- Single-Record mTLS HTTPS Data Delivery (
https_telemetry_transport.c,http_delivery_codec.c,cloud_client.c):- Trigger:
cloud_client_process()when Wi-Fi STA has IP, delivery is not paused/blocked, backoff deadline elapsed, and SD FIFO is non-empty. - Processing: Peeks FIFO head (never pops early), wraps payload with
seq,stream_id, and (for telemetry)"replay":bool, opens fresh TLS 1.2/1.3altcp_tlsconnection with SNI (mbedtls_ssl_set_hostname) and OTP client cert/key + compiledplanovi_ca_pem, sendsPOST /functions/v1/ingest-telemetrywithX-Device-Serial,X-Planovi-Record-Type(telemetry|event|storage),X-Storage-Stream-ID, andIdempotency-Key: <stream_id>:<seq>(30 stimeout,1400 Bmax req/resp). - ACK / State Change: Pops FIFO head (
fifo_buffer_ack_head(seq)) only when server returns2xxJSON withoutcome == "PROCESSED"and matchingstream_id+seq. Also marks SD key registered, clears cloud host rollback and Wi-Fi 60 s rollback, and setsg_sync_required = trueif response contains"sync_required": true. - Error Paths:
401/403-> 1 h backoff + immediateCLOUD_DELIVERY_UNAVAILABLE(5002) alert;408/425/429/5xx/network/parse errors -> stepped jittered backoff + Wi-Fi self-healing ladder (Tier 2 at 3/6, Tier 3 at 10);2xx"REJECTED"or other4xx-> setsdelivery_blocked = true(head-of-line halt; record preserved on SD until admin issuesretry,skip, orreplay).
- Trigger:
- HTTPS Control-Plane Heartbeat & Command Dispatch (
/functions/v1/ingest-telemetry,X-Planovi-Record-Type: sync):- Trigger: Every
60 s(CLOUD_HTTPS_SYNC_INTERVAL_MS), on boot/Wi-Fi reconnect, onsync_required: true, or when alast_command_ackawaits delivery. Runs independently of telemetry retry backoff so operators can always recover misconfigured units. - Processing: Posts device telemetry/Wi-Fi diagnostics +
last_command_ack; parsesserver_time_utc(->time_sync_set_utc),desired_config(telemetry_interval_sec5..86400,cloud_host/cloud_portlive switch with10 minfail-safe rollback to prior endpoint), andpending_command(reboot,clear_queue,sync_time,reset_sd,trigger_telemetry,replay_from_seq,ota_update[no-op stub],reconnect_wifi,update_wifi_credentials,reset_wifi_ap).
- Trigger: Every
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-SYNC-01(Single Multiplexed HTTPS Path): Firmware sends ALL 4 HTTPS traffic classes exclusively toPOST /functions/v1/ingest-telemetry(CLOUD_HTTPS_INGRESS_PATH), discriminated solely by headerX-Planovi-Record-Type(telemetry,event,storage,sync). Max HTTP request/response buffer is1400 B(HTTPS_TELEMETRY_REQUEST_MAX/RESPONSE_MAX); max JSON body is768 B(HTTP_BODY_MAX); socket timeout is30,000 ms.BR-SYNC-02(Strict Application-Level ACK & Head-of-Line Preservation):fifo_buffer_ack_head(seq)runs ONLY on2xx+outcome == "PROCESSED"+ exactstream_idandseqmatch (http_delivery_codec.c:357-400). Rejected (outcome == "REJECTED") or permanent4xx(400/404/405/409/413/422) records never drop silently; they setg_fifo_server_rejected_blocked = true.BR-SYNC-03(Stepped Exponential Backoff + ±10% Jitter):cloud_retry_policy.c:6-62schedules delays for consecutive transient failures1..6+:5 s,15 s,60 s,300 s,900 s,3600 s.CLOUD_FAILURE_AUTH(401/403) andCLOUD_FAILURE_PERMANENTuse fixed3600 s.429(CLOUD_FAILURE_RATE_LIMIT) usesmax(stepped_delay, Retry-After * 1000). All delays add symmetric±10%jitter (permille = (entropy % 201) - 100, floor1000 ms). Wi-Fi link restoration immediately resetsnext_attempt_ms = 0.BR-SYNC-04(Cloud Unavailability Alert Cadence):CLOUD_DELIVERY_UNAVAILABLE(code_num = 5002) is raised immediately onAUTH/PERMANENTfailure or atCLOUD_FAST_RETRY_LIMIT = 3transient failures, repeats everyCLOUD_ALERT_REPEAT_MS = 3,600,000 ms(1 h), and resolves on the firstPROCESSEDresponse.BR-SYNC-05(10-Minute Cloud Host Fail-Safe Rollback): When/syncswitchescloud_host/cloud_port, firmware armsCLOUD_FAILSAFE_ROLLBACK_TIMEOUT_MS = 600,000 ms(cloud_client.c:106, 1570-1586). If no telemetry or sync succeeds on the new endpoint within 10 minutes, firmware reverts to the prior endpoint.BR-SYNC-06(Mutual TLS 1.2/1.3 & Private Key Wipe):cloud_client.c:815-873validatesplanovi_ca_pemviambedtls_x509_crt_parse(), constructsaltcp_tls_create_config_client_2wayauth(), enforcesALTCP_MBEDTLS_AUTHMODE=MBEDTLS_SSL_VERIFY_REQUIRED+ SNI, and immediately clears OTP private key RAM viasecure_clear().BR-SYNC-07(Single-Record In-Flight Discipline): Firmware transmits strictly 1 FIFO record at a time (no HTTP batching), ensuring bounded RAM (1400 Bbuffer) and exact per-sequence ACK attribution.
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> IDLE: Init mTLS config
IDLE --> SYNCING: Boot / Wi-Fi up / 60s timer / sync_required / pending ACK
IDLE --> SENDING_STORAGE: SD needs register or adopt (15s cadence)
IDLE --> SENDING_RECORD: FIFO non-empty & !paused & !blocked & backoff elapsed
SYNCING --> IDLE: 2xx parsed -> apply UTC/config/command
SENDING_STORAGE --> IDLE: 2xx registered/adopt-key -> update sd_journal
SENDING_RECORD --> IDLE: 2xx PROCESSED (stream+seq match) -> ack_head & reset backoff
SENDING_RECORD --> BACKOFF: 401/403 (1h) or 408/425/429/5xx/TLS err (5s..3600s ±10%)
SENDING_RECORD --> BLOCKED: 2xx REJECTED or permanent 4xx -> halt queue head
BACKOFF --> IDLE: Backoff timer expires or Wi-Fi reconnects
BLOCKED --> IDLE: Admin retry / skip / replay command
5. Technical Contract (Inputs -> Processing -> Side Effects)
- Inputs: SD FIFO records (
fifo_buffer_peek_result), OTP client cert/key & serial,planovi_ca_pem, NVS cloud endpoint, HTTP responses / MQTT command payloads. - Processing: JSON envelope wrapping, TLS 1.2/1.3 handshake with SNI, HTTP/1.1 serialization/parsing, stepped jittered retry policy, command dispatch.
- Side Effects: FIFO head ACKs/replays/clears, NVS cloud endpoint & interval updates, RTC UTC updates, Wi-Fi Tier 2/3 healing & credential swaps, delayed reboots (
1000 msonreboot), SD reprovision (reset_sd),CLOUD_DELIVERY_UNAVAILABLE(5002) events.
6. Cross-Repository Dependencies
src/net/cloud_client.c->deploy/nginx.api.planovi.conf->cloud/mtls_gateway.py| HTTPS TLS 1.2/1.3 mTLS (Client Cert CN ==X-Device-Serial) |POST /functions/v1/ingest-telemetry(X-Planovi-Record-Type: telemetry|event|storage|sync).- Optional legacy path:
src/net/cloud_client.c-> Mosquitto (:8883, mTLS) ->cloud/mqtt_ingress.py| MQTTS QoS 1 |v1/devices/{serial}/{telemetry,alerts,attributes,storage}&v1/devices/{serial}/commands/#.
7. Why It Works This Way (Decisions, Trade-offs & Workarounds)
- Decoupled Control-Plane
/sync: Running/syncindependently of telemetry retry backoff prevents a permanent telemetry rejection or rate limit from locking out remote recovery commands (clear_queue,replay_from_seq,reboot,desired_config). - Confirmed Bug (
https_telemetry_transport.c:92-105vshttp_delivery_codec.c:329-337):http_delivery_parse_response()decodesTransfer-Encoding: chunkedinto a local stack buffer, buthttps_telemetry_transport.ccopies the raw undecoded body intog_https.response_bodypassed toprocess_sync_response()andstorage_transfer_handle_command(). Chunked HTTP responses onsyncorstoragewill fail JSON parsing. - Confirmed Bug (
cloud_client.c:1960, 1965):now >= g_delayed_reboot_deadline_msandnow >= g_rollback_deadline_msuse unsigned comparison (breaks across 49.7-day 32-bit ms wraparound), unlike signed(int32_t)(now - deadline) >= 0used elsewhere. - Confirmed Stub (
cloud_client.c:1650-1658): Remoteota_updatecommand repliesstatus: "APPLIED"without invokingota_update.h. - Confirmed Silent Drop (
cloud_client.c:997-1017):cloud_client_publish_raw()in HTTPS mode silently returnstruefor"alerts"and"attributes"without transmitting anything (only"storage"is sent). - Dead Code:
CLOUD_COMMAND_BROKER_HOST/PORT(cloud_client.c:41-51),cloud_retry_fallback_allowed()(cloud_retry_policy.c:91-97), andhttps_fallback_count(cloud_client.c:1121-1131) are unreachable because MQTT is never started in HTTPS mode. [TEAM_WHY_NEEDED: Should remote ota_update return status="FAILED" ("OTA disabled in v1") instead of falsely reporting status="APPLIED"?][TEAM_WHY_NEEDED: Is the vestigial HTTPS->MQTT fallback policy permanently deprecated (safe to delete) or planned for future dual-transport builds?]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Command | Fix |
|---|---|---|---|
delivery_blocked: true, last_reject_reason set | Cloud returned REJECTED or permanent 4xx (cloud_client.c) | GET /api/cloud (delivery_sequence, last_rejected_sequence, last_reject_reason, last_http_status) | Fix meter/time config and send retry, skip (tools/device_recover_invalid_timestamps.py), or replay |
https_alert_active: true, last_http_status: 401/403 | Expired/revoked/wrong-CA client cert, serial != CN, or stream assigned to different converter | Check Nginx mtls_diag log and mtls_gateway logs; run tools/mtls_smoke_test.py | Re-provision matching client cert or complete SD card adoption |
sync fails JSON parse behind proxy | Upstream sent Transfer-Encoding: chunked (https_telemetry_transport.c:92-105 raw copy bug) | Inspect proxy response headers on POST /functions/v1/ingest-telemetry (X-Planovi-Record-Type: sync) | Ensure Nginx/gateway buffers response (Content-Length, non-chunked) or fix firmware chunked body copy |