Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Backend (Edge Functions) v1.0 (frozen on 2026-11-23, commit f026e3b). Switch to Latest →

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:8000 control 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

  1. Dual-Write Edge Telemetry Ingestion (ingest-telemetry/index.ts, schema3_adapter.ts, public.ingest_telemetry_record):
    • Pre-checks: OPTIONS -> 200; non-POST -> 405; content-length or rawBody.length > 2048 (or empty) -> 413; invalid JSON -> 400.
    • Preview Flow (no X-Device-Serial + string hardware_id): Unauthenticated service-role lookup in converters (404 if missing) + device_live_state -> returns latest metrics JSON.
    • Edge Record Flow: Checks x-ssl-client-verify (if present, must be 'SUCCESS' -> 401), requires x-device-serial (401), validates x-planovi-record-type ∈ {telemetry, event, sync, storage} (400).
    • Step A (Control-Plane Forward): Forwards raw body to PLANOVI_INGEST_ORIGIN_URL (15_000ms timeout, X-Planovi-Edge-Token).
      • sync/storage: returns upstream response (503 if unreachable/5xx); skips DB RPC.
      • event: returns upstream response (200 fallback even if origin fails!); skips DB RPC.
      • telemetry: runs mapSchema3ToRawTelemetry (422 on TelemetryValidationError) -> calls ingest_telemetry_record RPC (503 on RPC error, 403 on UNKNOWN_DEVICE/DISABLED_DEVICE, 200 on PROCESSED or DUPLICATE mapped to 'PROCESSED', echoing sync_required: true if origin set it).
    • Inside ingest_telemetry_record: Verifies converter active/standby & non-deleted -> upserts gateway_registry, logical_points (separating MAIN/PV/SUBMETER), counters -> deduplicates on (logical_point_id, source_sequence, COALESCE(batch_id,'')) even for replay=true -> inserts raw_telemetry (firing BEFORE trigger fn_audit_telemetry_reset & AFTER trigger fn_upsert_live_state) -> if v_replay OR v_device_ts < date_trunc('hour', now) (and not SUBMETER), immediately calls fn_aggregate_hourly_telemetry for that hour -> updates converters & devices (last_seen, current_power).
  2. Legacy InCharge Poller (ingest-telemetry-old/index.ts): Unauthenticated pull poller using Deno KV cached token (REFRESH_BUFFER_MS = 300_000, default 23h TTL), checks system_settings.telemetry_enabled, polls incharge.insolve.pl/sensors/get_readings for active gateway_registry gateways, directly inserts raw_telemetry, logs fatal errors to telemetry_quarantine.
  3. Two Parallel Aggregation Pipelines:
    • Active SQL (fn_aggregate_hourly_telemetry on pg_cron '10 * * * *'): LAG-based deltas into hourly_telemetry_summaries; consumed by get_hourly_energy & get_daily_energy (hybrid 7-day cutoff: < 7d from raw_telemetry, >= 7d from hourly_telemetry_summaries) and get_15min_energy (raw only).
    • Legacy Edge Functions (aggregate-hourly -> telemetry_hourly -> aggregate-daily -> telemetry_daily): validateAuth protected. aggregate-daily clamps days ∈ [1, 31] (default 2), paginates telemetry_hourly (page 1000), buckets by Europe/Warsaw date, upserts telemetry_daily onConflict: "bucket_date,logical_point_id".
  4. Live State Refresh (refresh-live-state/index.ts): Unauthenticated; reads raw_telemetry ordered device_ts DESC (no pagination!), classifies online/stale/offline, upserts device_live_state (feeds device_health_status view).
  5. Alert Engine (process-alerts/index.ts): validateAuth; scans device_live_state, bulk-inserts alerts into system_alerts (no deduplication).
  6. Retention Cleanup (cleanup-telemetry/index.ts): validateAuth; hard-deletes raw_telemetry (>60d), telemetry_hourly (>180d), telemetry_daily (>730d). Does NOT touch hourly_telemetry_summaries.
  7. Tauron CSV Reconciliation (process-tauron-csv/index.ts, 20260813173407): validateAuth; parses Storage webhook {record: {name: "<coop_id>/<import_id>.csv"}}, downloads from private tauron_csvs (50 MB limit), parses ;/, CSV, compares against legacy device_telemetry, inserts tauron_reconciliation_logs, sets tauron_imports.status to 'anomalies_detected' or 'completed'.
  8. CSV Export (export-csv/index.ts): User JWT + company_members check (RLS anon client); generates UTF-8 BOM Polish CSV (financial, kpi, members, devices, voting, helpdesk, energy_balance), uploads to coop_reports, returns 60s signed URL (400 on 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 > 2048 bytes (or empty) with HTTP 413 "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: integer 1..247.
    • When valid !== false: v[3] in 0..1000 V, i[3] in 0..100_000 A, p[4] in -1e9..1e9 W, e_import_kwh >= 0.
    • When schema === 3: mt, mr, mp, pa required; if mr === 2 (submeter), pa > 0 && pa !== meter_id; if mr !== 2, pa === 0. Violations -> HTTP 422.
  • 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 (including replay=true); Edge Function returns DUPLICATE as outcome: "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: If NEW.import_kwh < prev_import - 0.1, flags is_suspect = true, telemetry_status = 'suspect'.
  • BR-IOT-06 (Monotonic Live State — fn_upsert_live_state): 20261030131000:40-113: Overwrites metric columns in device_live_state ONLY when EXCLUDED.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_telemetry filters telemetry_status='valid', excludes (0,0) frames and SUBMETER, uses 2h lookback ordered by COALESCE(device_ts, ts), source_sequence NULLS LAST, drops pairs with gap > 2h or delta > 1000 kWh, clamps negative deltas to 0.
  • BR-IOT-08 (7-Day Hybrid Energy Queries): get_hourly_energy & get_daily_energy split at NOW() - INTERVAL '7 days' (Europe/Warsaw), timeouts 30s (15min/hourly) and 60s (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_telemetry 60d, telemetry_hourly 180d, telemetry_daily 730d.
  • BR-IOT-11 (Tauron Bucket & Export Signed URL): tauron_csvs private, 50 MB (52_428_800 B), service_role only, path <coop_id>/<import_id>.csv. export-csv signed URL TTL 60s.

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; else 403 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 -> CalleeProtocol & AuthExact Endpoint / Contract
planovi-converter MCU -> mTLS Proxy -> ingest-telemetryHTTPS 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:8000HTTP POST / X-Planovi-Edge-Token (15s timeout)/api/v1/telemetry/edge-record (dual-write)
planovi-flutter-app -> ingest-telemetry (preview), export-csv, energy RPCsHTTPS POST + PostgREST / None (preview!) or User JWTPreview {hardware_id, company_id?}; export-csv; get_{15min,hourly,daily}_energy
Supabase Storage Webhook -> process-tauron-csvHTTPS 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/0 glitch spikes (091000), lost inter-hour energy via LAG() (120000), buffered replay misattribution via device_ts (131000), and SUBMETER double-counting (20261118140000).
  • aggregate-daily v2 rewrite: Fixed OOM crash, missing onConflict duplicates, 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 MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
Unauthorized telemetry injection or live-state leakageingest-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-serialRequire 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_energySecurity regression: 20261118140000:1185 reverted get_15min_energy from SECURITY INVOKER (20261117140000) back to SECURITY DEFINERSELECT prosecdef FROM pg_proc WHERE proname='get_15min_energy';Restore SECURITY INVOKER on get_15min_energy
Offline devices stuck on 'online' in device_live_staterefresh-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 returnedReplace with SQL DISTINCT ON (logical_point_id) or UPDATE device_live_state SQL cron
system_alerts flooded with duplicates; 0V outage never alertsprocess-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: nullSELECT 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 duplicatesaggregate-hourly:20,40-56,184 sets oneHourAgo = now - 24h, hits 1000-row cap, and upserts with no onConflictInspect telemetry_hourly timestamps & countsDeprecate in favor of pg_cron fn_aggregate_hourly_telemetry
Charts disagree at 7-day boundary or spike on 0/0 glitchesLast-7-days raw branches in get_{15min,hourly,daily}_energy use MAX - MIN without skipping 0/0 or capping 1000 kWh jumpsCompare get_hourly_energy vs hourly_telemetry_summaries for same dayApply LAG delta + 0/0 + 1000 kWh filter to recent raw branches
tauron_imports stuck in 'processing' foreverprocess-tauron-csv:102-116 queries legacy device_telemetry and never updates status='failed' in catchCheck process-tauron-csv logs and tauron_imports.statusMigrate 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 = 1Grep migrations for d116b78eNever replay verbatim on PROD; superseded by 20261118140000