Skip to content

2. RS-485 Modbus RTU Acquisition, Meter Drivers, Energy Math & Telemetry Scheduling

Repository: Converters (planovi-converter) • Rule Prefix: BR-MODBUS • Documented Rules: 10 • Open [TEAM_WHY_NEEDED] Questions: 5

1. Business Purpose & Actors

Polls up to 50 three-phase industrial energy meters (Zamel LEM-60 and CHINT DTSU666) over a shared RS-485 Modbus RTU half-duplex bus, discovers connected meters during commissioning, normalizes manufacturer-specific registers into a unified Schema 3 measurement model with zero-point offset and milli-kWh precision, detects RS-485 outages/recoveries, and buffers records onto encrypted storage on a configurable schedule or AC power-loss Last Gasp.

  • Actors: Autonomous TelemetryTask scheduler, Field Installer triggering bus scan / manual meter CRUD / test-run via Local Web UI, Cloud Operator adjusting remote polling policy (telemetry_interval_sec, telemetry_enabled).

2. All Features & End-to-End Flows

  • RS-485 Bus Discovery (src/modbus/bus_scanner.c):
    • Trigger: POST /api/scan/start -> bus_scanner_start_async(1, 247, baudrate) wakes persistent "ModbusScan" task.
    • Validation: Rejects unsupported baudrates (must match modbus_baudrate_is_supported()), start > end, or out-of-range [1..247].
    • Processing: For each slave ID (yielding 10 ms between addresses for Wi-Fi/HTTP responsiveness), issues 0-retry modbus_rtu_probe_registers() with dynamic timeout max(wire_ms + 30, 50) ms in fixed order: (1) CHINT DTSU666 (FC03 0x2006 V L1 in [0..500] V + FC03 0x002D baud/address self-match), (2) Zamel LEM-60 (FC04 0x0000 12 regs V/I + FC04 0x0046 freq in [40..70] Hz), (3) Generic Modbus (FC04 or FC03 0x0000 1 reg). Stores up to 50 results; supports mid-scan cancel via bus_scanner_stop().
  • Periodic Telemetry Acquisition & Last Gasp (src/app/telemetry_task.c, src/app/meter_manager.c):
    • Trigger: Monotonic FreeRTOS tick schedule (next_poll += interval_ms), telemetry_task_trigger_now(), or POWER_AC_LOST ISR notification (g_last_gasp_pending).
    • Validation: Checks config_store_get_telemetry_enabled() and time_sync_is_measurement_ready(). If a single prior sample is held in RAM backpressure (g_pending_telemetry_valid), flushes it first and aborts new Modbus polls until persisted.
    • Processing: Serialized under g_meter_poll_mutex. For each active meter (up to 50), acquires g_modbus_mutex, switches UART0 baudrate to meter’s configured baudrate (restoring 9600 afterward), executes driver burst reads with up to MODBUS_RETRY_LIMIT = 2 retries (3 total attempts), validates all measurement bounds (measurement_valid()), verifies RTC did not jump backward mid-read, applies energy_apply_zero_offset() + energy_quantize_millikwh(), snapshots all Schema 3 semantic metadata, and persists via cloud_client_store_telemetry().
    • Failure / Recovery: On 3 consecutive read failures (METER_OFFLINE_ALERT_THRESHOLD = 3), classifies cause from modbus_rtu_get_diagnostics() delta (1001 Timeout, 1002 CRC, 1003 Invalid Resp, 1004 Exception, 1005 Data Invalid, 1099 Comm Error) and buffers RS485/warning/ACTIVE event. First subsequent valid read (or meter removal while offline) emits MODBUS_RECOVERED (1000, info, RESOLVED, duration_s = now - outage_first_ts).
  • Device Event Serialization (src/app/device_event.c): Validates strict schema rules and serializes JSON schema: 1 events for RS-485, SD quarantine, cloud unavailability, and Last Gasp (6001).

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

  • BR-MODBUS-01 (RS-485 Physical Framing & Baudrates): UART0 (GPIO 0 TX, GPIO 1 RX) uses hardcoded 8N1 (UART_PARITY_NONE, no parity configuration) with automatic hardware direction switching (src/hal/uart_rs485.c:32). Allowed baudrates (src/config.h:66-71): {1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200}; default 9600.
  • BR-MODBUS-02 (Inter-Frame Silence, Retries & Function Limits): modbus_rtu.c enforces 3.5-character silence required_us = ceil(38,500,000 / baudrate) (4011 µs at 9600 bps) before each frame, standard CRC-16 polynomial 0xA001 init 0xFFFF (modbus_codec.c), MODBUS_RETRY_LIMIT = 2 (3 total attempts; 1 attempt for probes), max 125 regs for FC03/FC04 and 123 for FC10, ADU max 256 B, and driver response timeout 500 ms. Watchdog progress callback pulses SYSTEM_HEALTH_TELEMETRY before and after every attempt.
  • BR-MODBUS-03 (CHINT-First Scanner Order): bus_scanner.c probes CHINT DTSU666 before Zamel LEM-60 because certain DTSU666 revisions also answer FC04 at 0x0000. CHINT identification requires baud code 0..4 (1200..19200) at reg 0x002D matching active scan baudrate and reg 0x002E == slave_addr.
  • BR-MODBUS-04 (Zamel LEM-60 Register Map — FC04, IEEE-754 ABCD, Scale 1.0): src/meters/meter_lem60.c performs 3 burst reads: (1) 0x0000 (36 regs; decodes V L1/L2/L3 at 0x0000/02/04, I L1/L2/L3 at 0x0006/08/0A, P L1/L2/L3 at 0x000C/0E/10; discards 0x0012..0x0023), (2) 0x0034 (12 regs; P total 0x0034, S total 0x0038, Q total 0x003C, PF 0x003E), (3) 0x0046 (6 regs; Hz 0x0046, active import kWh 0x0048, active export kWh 0x004A). Directional reactive energies are always 0.0.
  • BR-MODBUS-05 (CHINT DTSU666 Register Map — FC03, IEEE-754 ABCD, Scaled): src/meters/meter_chint666.c & meter_chint666_codec.c perform 4 reads: (1) 0x2006 (22 regs: V L1-3 ×0.1, I L1-3 ×0.001, P total/L1-3 ×0.1, Q total ×0.1), (2) 0x202A (2 regs: PF ×0.001), (3) 0x2044 (2 regs: Hz ×0.01), (4) 0x101E (12 regs: import kWh at 0x101E ×1.0, export kWh at 0x1028 ×1.0). Apparent power is derived: S = hypotf(P_total, Q_total). Directional reactive energies are 0.0.
  • BR-MODBUS-06 (Measurement Validation Bounds): measurement_valid() (src/app/meter_manager.c:179-223) requires all 18 measurements finite (isfinite()), V ∈ [0, 1000] V, I ∈ [0, 100000] A, P_total ∈ [-1e9, 1e9] W, S ∈ [0, 1e9] VA, PF ∈ [-1.001, 1.001], Hz == 0 || Hz ∈ [40, 70] Hz, and all 4 energies ∈ [0, 1e12].
  • BR-MODBUS-07 (Zero-Point Offset & Milli-kWh Quantization): energy_apply_zero_offset() (src/common/energy_math.c) clamps raw < offset to 0.0 (never negative); energy_quantize_millikwh() rounds to 0.001 kWh (round(v * 1000.0) / 1000.0) as double. meter_manager_update_device() preserves existing Flash zero_offset_import/zero_offset_export across meter edits.
  • BR-MODBUS-08 (Polling Cadence & Single-Sample RAM Backpressure): telemetry_task.c polls on monotonic FreeRTOS ticks (NOT wall-clock aligned), clamped to [5, 86400] s (default 300 s). If storage write fails, meter_manager.c holds at most 1 sample in g_pending_telemetry, sets storage_backpressure = true, and suspends further Modbus polling until flushed.
  • BR-MODBUS-09 (Meter Semantic Topology & Max Capacity): Max 50 meters (MAX_METERS_PER_CONVERTER), bus_channel == 0 only, unique slave_id (1..247) and logical_id (1..65535), measurement_point regex ^[A-Z0-9_-]{1,15}$. If role == SUBMETER (2), parent_logical_id MUST reference an existing MAIN (1) meter in the same measurement_point with parent_logical_id != logical_id; otherwise parent_logical_id == 0.
  • BR-MODBUS-10 (Strict Event Schema Validation): device_event.c enforces code 3..48 [A-Z][A-Z0-9_]*, code_num 1..999999, ts/first_ts ∈ [946684800, 4102444800], first_ts <= ts, occurrences >= 1, ACTIVE => duration_s == 0, RESOLVED => duration_s == ts - first_ts, and mutual exclusion between has_meter and has_storage_details (storage details allowed only for SD_RECORD_QUARANTINED).

4. State Machines & Data Lifecycle

  • Per-Meter Outage Lifecycle (meter_runtime_t in meter_manager.c): HEALTHY (err=0) -> DEGRADED (err=1..2) -> OFFLINE_ALERT_PENDING (err>=3, buffering event) -> OFFLINE_ACTIVE (alert persisted) -> HEALTHY (on valid read or meter deletion -> emits MODBUS_RECOVERED RESOLVED). Outage state survives rebuild_devices() keyed by logical_id.
  • Telemetry Task Lifecycle: STOPPED -> WAITING_TIME_OR_DISABLED <-> POLLING <-> STORAGE_BACKPRESSURE (plus asynchronous LAST_GASP_RETRY overlay).

5. Technical Contract (Inputs -> Processing -> Side Effects)

  • Inputs: RS-485 UART0 frames, NVS meter list (config_store), RTC epoch (rtc_pcf8523), time_sync_is_measurement_ready(), AC-loss ISR notification.
  • Processing: Modbus RTU master transactions, driver register decoding, unit scaling, zero-offset & rounding, failure classification, strict JSON parsing (json_parser.c: max depth 8, max 32 fields, rejects duplicate keys & UTF-8 overlongs).
  • Side Effects: Buffers Schema 3 telemetry & Schema 1 event JSON into encrypted SD FIFO via cloud_client_store_telemetry() / cloud_client_store_alert(), triggers portable_config_request_backup() on meter CRUD, pulses SYSTEM_HEALTH_TELEMETRY.

6. Cross-Repository Dependencies

  • Firmware meter_data_t Schema 3 wire fields (mt, mr, mp, pa, md, bc, br, pc, mn, v, i, p, q, s, pf, hz, e_*, er_*) must strictly match supabase/functions/ingest-telemetry/schema3_adapter.ts, cloud/telemetry_schemas.py, and cloud/migrations/019_fix_converter_sync_and_telemetry_rpc.sql.

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • 1-Tick vTaskDelay Instead of sleep_us(100) (uart_rs485.c:92-110): Prevents Pico SDK alarm-pool exhaustion and CYW43/lwIP starvation during 247-address Modbus scans.
  • Zero-Allocation Strict JSON Parser (json_parser.c): Avoids heap fragmentation inside FreeRTOS/lwIP callbacks and defends against duplicate-key ambiguity in security-sensitive time/storage commands.
  • [TEAM_WHY_NEEDED: src/hal/uart_rs485.c:32 hardcodes 8N1 parity despite modbus_rtu.c comments mentioning 8E1. Are all target LEM-60/DTSU666 deployments standardized on 8N1?]
  • [TEAM_WHY_NEEDED: src/modbus/bus_scanner.h:76 states baudrate=0 auto-scans all standard rates, but bus_scanner.c:229,267 only defaults 0 to 9600 bps. Is multi-baud auto-scan intentionally omitted?]
  • [TEAM_WHY_NEEDED: src/meters/meter_lem60.c:43 bursts 36 registers (0x0000..0x0023) every poll while decoding only the first 18 (0x0000..0x0011). Is this intentional for future power/phase registers or leftover?]
  • [TEAM_WHY_NEEDED: src/app/meter_manager.c:179-223 leaves per-phase active_power_l1..l3 and reactive_power_total unbounded beyond isfinite(), and bus_scanner.c allows LEM-60 current up to 1,000,000 A vs meter_manager's 100,000 A.]
  • [TEAM_WHY_NEEDED: src/app/device_event.c:12 allows timestamps starting at 2000-01-01 (946684800), while meter_manager.c/time_sync.c enforce 2020-01-01 (1577836800).]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact CommandFix
Bus scan finds nothing at baudrate=0 for a 19200 bps meterbus_scanner.c:229 maps 0 -> 9600 instead of sweeping baudratesGET /api/scan/status (baudrate: 9600)Explicitly pass {"baudrate": 19200} to POST /api/scan/start
CHINT DTSU666 at 38400+ bps identified as GENERIC_MODBUSchint666_communication_parameters_match() (meter_chint666_codec.c:33-35) only maps baud codes 0..4 (1200..19200)GET /api/scan/status returns type: 0Configure DTSU666 to 1200..19200 bps (default 9600)
TelemetryTask running (cycles frozen at 0)Either telemetry_enabled == false, time_sync_is_measurement_ready() == false (RTC invalid/bootstrap/hold), or storage_backpressure == trueGET /api/status (rtc_valid, time_bootstrap_pending, time_measurement_hold_until, meter_storage.backpressure)Set valid UTC time (POST /api/system/time) or resolve SD write failure
Meter emits MODBUS_TIMEOUT (1001) / MODBUS_CRC_ERROR (1002)RS-485 wiring/polarity/termination, wrong slave ID/baudrate, or meter parity != 8N1POST /api/test-run + GET /api/test-status (modbus.{timeouts,crc,invalid,exceptions})Verify A/B polarity, 120 Ω termination, 8N1 framing, and run diagnostics/lem60_probe.c