Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Converters (IoT & Cloud) v1.0 (frozen on 2026-11-23, commit 71e82be). Switch to Latest →

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_transport from NVS: CLOUD_TRANSPORT_HTTPS (2) selects HTTPS exclusively (MQTT client is never allocated or connected); CLOUD_TRANSPORT_AUTO (0) or CLOUD_TRANSPORT_MQTT (1) selects MQTTS.
  • 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.3 altcp_tls connection with SNI (mbedtls_ssl_set_hostname) and OTP client cert/key + compiled planovi_ca_pem, sends POST /functions/v1/ingest-telemetry with X-Device-Serial, X-Planovi-Record-Type (telemetry|event|storage), X-Storage-Stream-ID, and Idempotency-Key: <stream_id>:<seq> (30 s timeout, 1400 B max req/resp).
    • ACK / State Change: Pops FIFO head (fifo_buffer_ack_head(seq)) only when server returns 2xx JSON with outcome == "PROCESSED" and matching stream_id + seq. Also marks SD key registered, clears cloud host rollback and Wi-Fi 60 s rollback, and sets g_sync_required = true if response contains "sync_required": true.
    • Error Paths: 401/403 -> 1 h backoff + immediate CLOUD_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 other 4xx -> sets delivery_blocked = true (head-of-line halt; record preserved on SD until admin issues retry, skip, or replay).
  • 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, on sync_required: true, or when a last_command_ack awaits delivery. Runs independently of telemetry retry backoff so operators can always recover misconfigured units.
    • Processing: Posts device telemetry/Wi-Fi diagnostics + last_command_ack; parses server_time_utc (-> time_sync_set_utc), desired_config (telemetry_interval_sec 5..86400, cloud_host/cloud_port live switch with 10 min fail-safe rollback to prior endpoint), and pending_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).

3. Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-SYNC-01 (Single Multiplexed HTTPS Path): Firmware sends ALL 4 HTTPS traffic classes exclusively to POST /functions/v1/ingest-telemetry (CLOUD_HTTPS_INGRESS_PATH), discriminated solely by header X-Planovi-Record-Type (telemetry, event, storage, sync). Max HTTP request/response buffer is 1400 B (HTTPS_TELEMETRY_REQUEST_MAX/RESPONSE_MAX); max JSON body is 768 B (HTTP_BODY_MAX); socket timeout is 30,000 ms.
  • BR-SYNC-02 (Strict Application-Level ACK & Head-of-Line Preservation): fifo_buffer_ack_head(seq) runs ONLY on 2xx + outcome == "PROCESSED" + exact stream_id and seq match (http_delivery_codec.c:357-400). Rejected (outcome == "REJECTED") or permanent 4xx (400/404/405/409/413/422) records never drop silently; they set g_fifo_server_rejected_blocked = true.
  • BR-SYNC-03 (Stepped Exponential Backoff + ±10% Jitter): cloud_retry_policy.c:6-62 schedules delays for consecutive transient failures 1..6+: 5 s, 15 s, 60 s, 300 s, 900 s, 3600 s. CLOUD_FAILURE_AUTH (401/403) and CLOUD_FAILURE_PERMANENT use fixed 3600 s. 429 (CLOUD_FAILURE_RATE_LIMIT) uses max(stepped_delay, Retry-After * 1000). All delays add symmetric ±10% jitter (permille = (entropy % 201) - 100, floor 1000 ms). Wi-Fi link restoration immediately resets next_attempt_ms = 0.
  • BR-SYNC-04 (Cloud Unavailability Alert Cadence): CLOUD_DELIVERY_UNAVAILABLE (code_num = 5002) is raised immediately on AUTH/PERMANENT failure or at CLOUD_FAST_RETRY_LIMIT = 3 transient failures, repeats every CLOUD_ALERT_REPEAT_MS = 3,600,000 ms (1 h), and resolves on the first PROCESSED response.
  • BR-SYNC-05 (10-Minute Cloud Host Fail-Safe Rollback): When /sync switches cloud_host/cloud_port, firmware arms CLOUD_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-873 validates planovi_ca_pem via mbedtls_x509_crt_parse(), constructs altcp_tls_create_config_client_2wayauth(), enforces ALTCP_MBEDTLS_AUTHMODE=MBEDTLS_SSL_VERIFY_REQUIRED + SNI, and immediately clears OTP private key RAM via secure_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 B buffer) 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 ms on reboot), 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 /sync independently 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-105 vs http_delivery_codec.c:329-337): http_delivery_parse_response() decodes Transfer-Encoding: chunked into a local stack buffer, but https_telemetry_transport.c copies the raw undecoded body into g_https.response_body passed to process_sync_response() and storage_transfer_handle_command(). Chunked HTTP responses on sync or storage will fail JSON parsing.
  • Confirmed Bug (cloud_client.c:1960, 1965): now >= g_delayed_reboot_deadline_ms and now >= g_rollback_deadline_ms use unsigned comparison (breaks across 49.7-day 32-bit ms wraparound), unlike signed (int32_t)(now - deadline) >= 0 used elsewhere.
  • Confirmed Stub (cloud_client.c:1650-1658): Remote ota_update command replies status: "APPLIED" without invoking ota_update.h.
  • Confirmed Silent Drop (cloud_client.c:997-1017): cloud_client_publish_raw() in HTTPS mode silently returns true for "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), and https_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 MessageRoot Cause in CodeHow to Verify / Exact CommandFix
delivery_blocked: true, last_reject_reason setCloud 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/403Expired/revoked/wrong-CA client cert, serial != CN, or stream assigned to different converterCheck Nginx mtls_diag log and mtls_gateway logs; run tools/mtls_smoke_test.pyRe-provision matching client cert or complete SD card adoption
sync fails JSON parse behind proxyUpstream 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