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
TelemetryTaskscheduler, 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 msbetween addresses for Wi-Fi/HTTP responsiveness), issues 0-retrymodbus_rtu_probe_registers()with dynamic timeoutmax(wire_ms + 30, 50)ms in fixed order: (1) CHINT DTSU666 (FC030x2006V L1 in[0..500]V + FC030x002Dbaud/address self-match), (2) Zamel LEM-60 (FC040x000012 regs V/I + FC040x0046freq in[40..70]Hz), (3) Generic Modbus (FC04 or FC030x00001 reg). Stores up to 50 results; supports mid-scan cancel viabus_scanner_stop().
- Trigger:
- 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(), orPOWER_AC_LOSTISR notification (g_last_gasp_pending). - Validation: Checks
config_store_get_telemetry_enabled()andtime_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), acquiresg_modbus_mutex, switches UART0 baudrate to meter’s configured baudrate (restoring9600afterward), executes driver burst reads with up toMODBUS_RETRY_LIMIT = 2retries (3 total attempts), validates all measurement bounds (measurement_valid()), verifies RTC did not jump backward mid-read, appliesenergy_apply_zero_offset()+energy_quantize_millikwh(), snapshots all Schema 3 semantic metadata, and persists viacloud_client_store_telemetry(). - Failure / Recovery: On 3 consecutive read failures (
METER_OFFLINE_ALERT_THRESHOLD = 3), classifies cause frommodbus_rtu_get_diagnostics()delta (1001Timeout,1002CRC,1003Invalid Resp,1004Exception,1005Data Invalid,1099Comm Error) and buffersRS485/warning/ACTIVEevent. First subsequent valid read (or meter removal while offline) emitsMODBUS_RECOVERED(1000,info,RESOLVED,duration_s = now - outage_first_ts).
- Trigger: Monotonic FreeRTOS tick schedule (
- Device Event Serialization (
src/app/device_event.c): Validates strict schema rules and serializes JSONschema: 1events 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}; default9600.BR-MODBUS-02(Inter-Frame Silence, Retries & Function Limits):modbus_rtu.cenforces 3.5-character silencerequired_us = ceil(38,500,000 / baudrate)(4011 µsat 9600 bps) before each frame, standard CRC-16 polynomial0xA001init0xFFFF(modbus_codec.c),MODBUS_RETRY_LIMIT = 2(3 total attempts; 1 attempt for probes), max125regs for FC03/FC04 and123for FC10, ADU max256 B, and driver response timeout500 ms. Watchdog progress callback pulsesSYSTEM_HEALTH_TELEMETRYbefore and after every attempt.BR-MODBUS-03(CHINT-First Scanner Order):bus_scanner.cprobes CHINT DTSU666 before Zamel LEM-60 because certain DTSU666 revisions also answer FC04 at0x0000. CHINT identification requires baud code0..4(1200..19200) at reg0x002Dmatching active scan baudrate and reg0x002E == slave_addr.BR-MODBUS-04(Zamel LEM-60 Register Map — FC04, IEEE-754 ABCD, Scale 1.0):src/meters/meter_lem60.cperforms 3 burst reads: (1)0x0000(36 regs; decodes V L1/L2/L3 at0x0000/02/04, I L1/L2/L3 at0x0006/08/0A, P L1/L2/L3 at0x000C/0E/10; discards0x0012..0x0023), (2)0x0034(12 regs; P total0x0034, S total0x0038, Q total0x003C, PF0x003E), (3)0x0046(6 regs; Hz0x0046, active import kWh0x0048, active export kWh0x004A). Directional reactive energies are always0.0.BR-MODBUS-05(CHINT DTSU666 Register Map — FC03, IEEE-754 ABCD, Scaled):src/meters/meter_chint666.c&meter_chint666_codec.cperform 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 at0x101E ×1.0, export kWh at0x1028 ×1.0). Apparent power is derived:S = hypotf(P_total, Q_total). Directional reactive energies are0.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) clampsraw < offsetto0.0(never negative);energy_quantize_millikwh()rounds to0.001 kWh(round(v * 1000.0) / 1000.0) asdouble.meter_manager_update_device()preserves existing Flashzero_offset_import/zero_offset_exportacross meter edits.BR-MODBUS-08(Polling Cadence & Single-Sample RAM Backpressure):telemetry_task.cpolls on monotonic FreeRTOS ticks (NOT wall-clock aligned), clamped to[5, 86400]s (default300 s). If storage write fails,meter_manager.cholds at most 1 sample ing_pending_telemetry, setsstorage_backpressure = true, and suspends further Modbus polling until flushed.BR-MODBUS-09(Meter Semantic Topology & Max Capacity): Max50meters (MAX_METERS_PER_CONVERTER),bus_channel == 0only, uniqueslave_id (1..247)andlogical_id (1..65535),measurement_pointregex^[A-Z0-9_-]{1,15}$. Ifrole == SUBMETER (2),parent_logical_idMUST reference an existingMAIN (1)meter in the samemeasurement_pointwithparent_logical_id != logical_id; otherwiseparent_logical_id == 0.BR-MODBUS-10(Strict Event Schema Validation):device_event.cenforcescode3..48[A-Z][A-Z0-9_]*,code_num1..999999,ts/first_ts ∈ [946684800, 4102444800],first_ts <= ts,occurrences >= 1,ACTIVE => duration_s == 0,RESOLVED => duration_s == ts - first_ts, and mutual exclusion betweenhas_meterandhas_storage_details(storage details allowed only forSD_RECORD_QUARANTINED).
4. State Machines & Data Lifecycle
- Per-Meter Outage Lifecycle (
meter_runtime_tinmeter_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 -> emitsMODBUS_RECOVEREDRESOLVED). Outage state survivesrebuild_devices()keyed bylogical_id. - Telemetry Task Lifecycle:
STOPPED->WAITING_TIME_OR_DISABLED<->POLLING<->STORAGE_BACKPRESSURE(plus asynchronousLAST_GASP_RETRYoverlay).
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(), triggersportable_config_request_backup()on meter CRUD, pulsesSYSTEM_HEALTH_TELEMETRY.
6. Cross-Repository Dependencies
- Firmware
meter_data_tSchema 3 wire fields (mt,mr,mp,pa,md,bc,br,pc,mn,v,i,p,q,s,pf,hz,e_*,er_*) must strictly matchsupabase/functions/ingest-telemetry/schema3_adapter.ts,cloud/telemetry_schemas.py, andcloud/migrations/019_fix_converter_sync_and_telemetry_rpc.sql.
7. Why It Works This Way (Decisions, Trade-offs & Workarounds)
- 1-Tick
vTaskDelayInstead ofsleep_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 Message | Root Cause in Code | How to Verify / Exact Command | Fix |
|---|---|---|---|
Bus scan finds nothing at baudrate=0 for a 19200 bps meter | bus_scanner.c:229 maps 0 -> 9600 instead of sweeping baudrates | GET /api/scan/status (baudrate: 9600) | Explicitly pass {"baudrate": 19200} to POST /api/scan/start |
CHINT DTSU666 at 38400+ bps identified as GENERIC_MODBUS | chint666_communication_parameters_match() (meter_chint666_codec.c:33-35) only maps baud codes 0..4 (1200..19200) | GET /api/scan/status returns type: 0 | Configure 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 == true | GET /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 != 8N1 | POST /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 |