4. IoT Telemetry Ingestion, Aggregation, Live State & Alerts
Repository:
Backend (planovi-backend)• Rule Prefix:BR-IOT• Documented Rules: 11 • Open[TEAM_WHY_NEEDED]Questions: 3
1. Business Purpose & Actors
Ingests real-time and buffered/replayed electrical meter telemetry, device events, config syncs, and storage records from Planovi Edge Converters (and legacy InCharge meters); deduplicates and detects meter resets; maintains device_live_state; computes 15-min/hourly/daily energy deltas; triggers device health/voltage/power alerts; enforces retention cleanup; reconciles Tauron DSO CSV exports; and exports cooperative CSVs.
- Actors: Planovi Edge Converter firmware (behind mTLS reverse proxy),
converters-api-dev:8000control plane, legacy InCharge Cloud API,pg_cron/ external schedulers, Supabase Storage webhook (tauron_csvs), and Flutter app (converter preview, energy charts, CSV export).
2. All Features & End-to-End Flows
- Dual-Write Edge Telemetry Ingestion (
ingest-telemetry/index.ts,schema3_adapter.ts,public.ingest_telemetry_record):- Pre-checks:
OPTIONS->200; non-POST->405;content-lengthorrawBody.length > 2048(or empty) ->413; invalid JSON ->400. - Preview Flow (no
X-Device-Serial+ stringhardware_id): Unauthenticated service-role lookup inconverters(404if missing) +device_live_state-> returns latest metrics JSON. - Edge Record Flow: Checks
x-ssl-client-verify(if present, must be'SUCCESS'->401), requiresx-device-serial(401), validatesx-planovi-record-type ∈ {telemetry, event, sync, storage}(400). - Step A (Control-Plane Forward): Forwards raw body to
PLANOVI_INGEST_ORIGIN_URL(15_000mstimeout,X-Planovi-Edge-Token).sync/storage: returns upstream response (503if unreachable/5xx); skips DB RPC.event: returns upstream response (200fallback even if origin fails!); skips DB RPC.telemetry: runsmapSchema3ToRawTelemetry(422onTelemetryValidationError) -> callsingest_telemetry_recordRPC (503on RPC error,403onUNKNOWN_DEVICE/DISABLED_DEVICE,200onPROCESSEDorDUPLICATEmapped to'PROCESSED', echoingsync_required: trueif origin set it).
- Inside
ingest_telemetry_record: Verifies converter active/standby & non-deleted -> upsertsgateway_registry,logical_points(separatingMAIN/PV/SUBMETER),counters-> deduplicates on(logical_point_id, source_sequence, COALESCE(batch_id,''))even forreplay=true-> insertsraw_telemetry(firing BEFORE triggerfn_audit_telemetry_reset& AFTER triggerfn_upsert_live_state) -> ifv_replay OR v_device_ts < date_trunc('hour', now)(and notSUBMETER), immediately callsfn_aggregate_hourly_telemetryfor that hour -> updatesconverters&devices(last_seen,current_power).
- Pre-checks:
- Legacy InCharge Poller (
ingest-telemetry-old/index.ts): Unauthenticated pull poller using Deno KV cached token (REFRESH_BUFFER_MS = 300_000, default 23h TTL), checkssystem_settings.telemetry_enabled, pollsincharge.insolve.pl/sensors/get_readingsfor activegateway_registrygateways, directly insertsraw_telemetry, logs fatal errors totelemetry_quarantine. - Two Parallel Aggregation Pipelines:
- Active SQL (
fn_aggregate_hourly_telemetryonpg_cron'10 * * * *'): LAG-based deltas intohourly_telemetry_summaries; consumed byget_hourly_energy&get_daily_energy(hybrid 7-day cutoff:< 7dfromraw_telemetry,>= 7dfromhourly_telemetry_summaries) andget_15min_energy(raw only). - Legacy Edge Functions (
aggregate-hourly->telemetry_hourly->aggregate-daily->telemetry_daily):validateAuthprotected.aggregate-dailyclampsdays ∈ [1, 31](default2), paginatestelemetry_hourly(page1000), buckets byEurope/Warsawdate, upsertstelemetry_dailyonConflict: "bucket_date,logical_point_id".
- Active SQL (
- Live State Refresh (
refresh-live-state/index.ts): Unauthenticated; readsraw_telemetryordereddevice_ts DESC(no pagination!), classifiesonline/stale/offline, upsertsdevice_live_state(feedsdevice_health_statusview). - Alert Engine (
process-alerts/index.ts):validateAuth; scansdevice_live_state, bulk-inserts alerts intosystem_alerts(no deduplication). - Retention Cleanup (
cleanup-telemetry/index.ts):validateAuth; hard-deletesraw_telemetry(>60d),telemetry_hourly(>180d),telemetry_daily(>730d). Does NOT touchhourly_telemetry_summaries. - Tauron CSV Reconciliation (
process-tauron-csv/index.ts,20260813173407):validateAuth; parses Storage webhook{record: {name: "<coop_id>/<import_id>.csv"}}, downloads from privatetauron_csvs(50 MB limit), parses;/,CSV, compares against legacydevice_telemetry, insertstauron_reconciliation_logs, setstauron_imports.statusto'anomalies_detected'or'completed'. - CSV Export (
export-csv/index.ts): User JWT +company_memberscheck (RLS anon client); generates UTF-8 BOM Polish CSV (financial,kpi,members,devices,voting,helpdesk,energy_balance), uploads tocoop_reports, returns 60s signed URL (400on all errors).
3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-IOT)
BR-IOT-01(Payload Limit):ingest-telemetry/index.ts:17,52-69: Rejects payloads> 2048bytes (or empty) with HTTP413 "Payload exceeds 2048 bytes".BR-IOT-02(Schema 2/3 Bounds):schema3_adapter.ts:98-146:seq: integer>= 1.ts: integer in[946_684_800, 4_102_444_800](2000–2100 UTC) AND<= now + 600s.meter_addr: integer1..247.- When
valid !== false:v[3]in0..1000 V,i[3]in0..100_000 A,p[4]in-1e9..1e9 W,e_import_kwh >= 0. - When
schema === 3:mt, mr, mp, parequired; ifmr === 2(submeter),pa > 0 && pa !== meter_id; ifmr !== 2,pa === 0. Violations -> HTTP422.
BR-IOT-03(Adapter Unit Conversions):voltage_v = avg(v[0..2]),current_a = sum(i[0..2]),active_power_kw = p[3] / 1000,reactive_power_kvar = q / 1000,apparent_power_kva = s / 1000.BR-IOT-04(Replay Dedup & ACK Translation): Deduplicates(logical_point_id, source_sequence, COALESCE(batch_id,''))unconditionally (includingreplay=true); Edge Function returnsDUPLICATEasoutcome: "PROCESSED"so firmware clears its upload queue (ingest-telemetry/index.ts:376).BR-IOT-05(Meter Reset Detection —fn_audit_telemetry_reset):20261030131000:14-37: IfNEW.import_kwh < prev_import - 0.1, flagsis_suspect = true, telemetry_status = 'suspect'.BR-IOT-06(Monotonic Live State —fn_upsert_live_state):20261030131000:40-113: Overwrites metric columns indevice_live_stateONLY whenEXCLUDED.latest_ts >= COALESCE(device_live_state.latest_ts, '-infinity')so replays never roll back live readings.BR-IOT-07(Hourly LAG Delta & Anomaly Guards):fn_aggregate_hourly_telemetryfilterstelemetry_status='valid', excludes(0,0)frames andSUBMETER, uses 2h lookback ordered byCOALESCE(device_ts, ts), source_sequence NULLS LAST, drops pairs with gap> 2hor delta> 1000 kWh, clamps negative deltas to0.BR-IOT-08(7-Day Hybrid Energy Queries):get_hourly_energy&get_daily_energysplit atNOW() - INTERVAL '7 days'(Europe/Warsaw), timeouts30s(15min/hourly) and60s(daily).BR-IOT-09(Health & Alert Thresholds):refresh-live-state:<= 15m'online',16–60m'stale',> 60m'offline'.process-alerts:offline(critical),stale(medium),latest_voltage_v > 260 || < 180(high),latest_active_power_kw > 1000(high).BR-IOT-10(Retention Windows):cleanup-telemetry:raw_telemetry60d,telemetry_hourly180d,telemetry_daily730d.BR-IOT-11(Tauron Bucket & Export Signed URL):tauron_csvsprivate,50 MB(52_428_800B),service_roleonly, path<coop_id>/<import_id>.csv.export-csvsigned URL TTL60s.
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> Valid : ingest_telemetry_record (valid=true)
[*] --> Suspect : valid=false OR import_kwh < prev - 0.1
Valid --> Online : fn_upsert_live_state (<=15m)
Online --> Stale : refresh-live-state (16-60m) -> alert(medium)
Stale --> Offline : refresh-live-state (>60m) -> alert(critical)
Stale --> Online : new telemetry packet
Offline --> Online : new telemetry packet
- Converter ingestion eligibility:
status IN ('active','standby')&deleted_at IS NULL-> accepted; else403 DISABLED_DEVICE/UNKNOWN_DEVICE. tauron_imports.status: uploaded ->'completed'|'anomalies_detected'('failed'never implemented).
5. Technical Contract
- Endpoints:
ingest-telemetry,ingest-telemetry-old,aggregate-hourly,aggregate-daily,refresh-live-state,cleanup-telemetry,process-alerts,process-tauron-csv,export-csv. - SQL RPCs/Triggers/Jobs:
ingest_telemetry_record,fn_aggregate_hourly_telemetry(pg_cron'aggregate-hourly-summaries''10 * * * *'),get_15min_energy,get_hourly_energy,get_daily_energy,fn_audit_telemetry_reset,fn_upsert_live_state,fn_sync_edge_converter_to_converters. - Tables:
raw_telemetry,device_live_state,device_health_status(view),hourly_telemetry_summaries,backup_hourly_telemetry_summaries_2026_10_30,telemetry_hourly,telemetry_daily,telemetry_quarantine,converters,edge_converters,gateway_registry,logical_points,counters,devices,facilities,edge_system_settings,system_settings,system_alerts,tauron_imports,tauron_reconciliation_logs,device_telemetry,telemetry_logs. - Storage Buckets:
tauron_csvs(private, 50 MB),coop_reports(60s signed URL).
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
planovi-converter MCU -> mTLS Proxy -> ingest-telemetry | HTTPS POST / mTLS (X-SSL-Client-Verify, X-Device-Serial) | Schema 2/3 JSON (<=2048 B) -> {stream_id, seq, outcome, sync_required?} |
ingest-telemetry -> converters-api-dev:8000 | HTTP POST / X-Planovi-Edge-Token (15s timeout) | /api/v1/telemetry/edge-record (dual-write) |
planovi-flutter-app -> ingest-telemetry (preview), export-csv, energy RPCs | HTTPS POST + PostgREST / None (preview!) or User JWT | Preview {hardware_id, company_id?}; export-csv; get_{15min,hourly,daily}_energy |
Supabase Storage Webhook -> process-tauron-csv | HTTPS POST / validateAuth | {record: {name: "<coop_id>/<import_id>.csv"}} |
7. Why It Works This Way
- Dual-write in
ingest-telemetry: Keeps both Converter Admin tables (edge_converters,telemetry_data,device_events,energy_meters,storage_streams) and Flutter app tables (converters,raw_telemetry,device_live_state) synced on DEV. - 5-migration evolution of
fn_aggregate_hourly_telemetry: Fixed swapped import/export (090000),0/0glitch spikes (091000), lost inter-hour energy viaLAG()(120000), buffered replay misattribution viadevice_ts(131000), andSUBMETERdouble-counting (20261118140000). aggregate-dailyv2 rewrite: Fixed OOM crash, missingonConflictduplicates, and UTC day-boundary cutoffs (Europe/Warsaw).[TEAM_WHY_NEEDED: Why do parallel pipelines telemetry_hourly/telemetry_daily (Edge Functions) AND hourly_telemetry_summaries (pg_cron SQL) coexist, and which is authoritative in PROD?][TEAM_WHY_NEEDED: Why does Flutter call unauthenticated POST ingest-telemetry for converter preview instead of querying device_live_state via RLS?][TEAM_WHY_NEEDED: Should pre-2026-10-18 swapped rows in hourly_telemetry_summaries (noted in 20261030090000:13 "ask Mat") be swapped or left immutable?]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
| Unauthorized telemetry injection or live-state leakage | ingest-telemetry:81-135 preview mode has zero auth, and :137-141 skips mTLS check when x-ssl-client-verify header is absent! | Send direct POST without x-ssl-client-verify or x-device-serial | Require JWT/RLS for preview; reject missing x-ssl-client-verify !== 'SUCCESS' (or enforce network-level mTLS gateway only) |
Cross-tenant data accessible via get_15min_energy | Security regression: 20261118140000:1185 reverted get_15min_energy from SECURITY INVOKER (20261117140000) back to SECURITY DEFINER | SELECT prosecdef FROM pg_proc WHERE proname='get_15min_energy'; | Restore SECURITY INVOKER on get_15min_energy |
Offline devices stuck on 'online' in device_live_state | refresh-live-state:22-30 reads raw_telemetry with no pagination (PostgREST 1000-row cap hides quiet devices) | Check count(*) of raw_telemetry vs distinct logical_point_id returned | Replace with SQL DISTINCT ON (logical_point_id) or UPDATE device_live_state SQL cron |
system_alerts flooded with duplicates; 0V outage never alerts | process-alerts:44-137 has no open-alert dedup, treats 0V as falsy (if (device.latest_voltage_v && ...)), ignores < -1000 kW export spikes, and sets converter_id: null | SELECT alert_type, count(*) FROM system_alerts GROUP BY 1; | Add open-alert dedup, explicit != null voltage check, Math.abs(power) > 1000, and proper converter join |
aggregate-hourly collapses 24h into 1 bucket & creates duplicates | aggregate-hourly:20,40-56,184 sets oneHourAgo = now - 24h, hits 1000-row cap, and upserts with no onConflict | Inspect telemetry_hourly timestamps & counts | Deprecate in favor of pg_cron fn_aggregate_hourly_telemetry |
Charts disagree at 7-day boundary or spike on 0/0 glitches | Last-7-days raw branches in get_{15min,hourly,daily}_energy use MAX - MIN without skipping 0/0 or capping 1000 kWh jumps | Compare get_hourly_energy vs hourly_telemetry_summaries for same day | Apply LAG delta + 0/0 + 1000 kWh filter to recent raw branches |
tauron_imports stuck in 'processing' forever | process-tauron-csv:102-116 queries legacy device_telemetry and never updates status='failed' in catch | Check process-tauron-csv logs and tauron_imports.status | Migrate query to raw_telemetry/hourly_telemetry_summaries and write status='failed' on catch |
Hardcoded DEV UUIDs/serials in migrations (20261016171900, 20261024231000) | Hardcoded d116b78e-..., 'ASL-EC-12332453574787', 'Jodłowa', facilities.id = 1 | Grep migrations for d116b78e | Never replay verbatim on PROD; superseded by 20261118140000 |