Files
HomeAssistant/docs/plans/2026-03-17-power-monitor-design.md
T
2026-03-17 12:37:56 +02:00

8.6 KiB
Raw Blame History

Power Monitor — "Other" Power Usage & Cost Tracking

Problem

A P1 smart meter tracks total home power consumption in near real-time (~1-10s updates). Over 30 Sonoff and Zigbee devices each report individual power usage but with up to ~30 seconds of staleness. There is no visibility into what untracked devices are consuming, and no per-device or whole-home cost tracking integrated with NordPool electricity prices.

Goals

  • Calculate "other" (untracked) power usage: total - sum(known devices)
  • Track electricity cost at three levels: total home, per device, and "other"
  • Detect anomalies when untracked power exceeds a configurable threshold
  • Expose everything as HA entities for dashboards and automations
  • Auto-discover power sensors with manual re-discovery via HA button

Approach

Periodic polling with exponential moving average smoothing. Every 15 seconds (configurable), read all power sensors, compute "other" power, apply smoothing, calculate costs, and push to HA entities.

Architecture

Project Structure

PowerMonitor.Manager/
├── PowerMonitorInit.cs              # [NetDaemonApp] orchestrator, schedules polling
├── PowerMonitorEntityService.cs     # Creates/updates MQTT entities in HA
├── PowerSensorDiscoveryService.cs   # Auto-discovers power sensors from HA
├── OtherPowerCalculationService.cs  # total - sum(known) + smoothing
├── PowerCostCalculationService.cs   # NordPool price integration, cost accumulation
├── Interface/
│   ├── IPowerMonitorInit.cs
│   ├── IPowerMonitorEntityService.cs
│   ├── IPowerSensorDiscoveryService.cs
│   ├── IOtherPowerCalculationService.cs
│   └── IPowerCostCalculationService.cs
└── Models/
    ├── PowerCalculationResult.cs
    ├── PowerUpdateContext.cs
    ├── PowerSensorConfig.cs
    ├── CostAccumulator.cs
    └── Consts/
        └── PowerMonitorConsts.cs

PowerMonitor.Models/
├── PowerMonitorEntity.cs
└── PowerSensorInfo.cs

PowerMonitor.Manager.Tests/
├── OtherPowerCalculationServiceTests.cs
├── CostAccumulatorTests.cs
├── PowerSensorDiscoveryServiceTests.cs
├── PowerCostCalculationServiceTests.cs
└── PowerMonitorEntityServiceTests.cs

Service Responsibilities

Service Responsibility
PowerMonitorInit NetDaemon app entry point. Runs initialization, schedules periodic polling, subscribes to re-discovery button.
PowerSensorDiscoveryService Queries HA for all power sensors (device_class: power, unit: W/kW). Applies exclusion patterns. Identifies main meter vs device sensors.
OtherPowerCalculationService Computes other = total - sum(devices), clamps negatives to 0, applies exponential moving average smoothing.
PowerCostCalculationService Maintains CostAccumulator instances per tracked source. Computes cost = power_kW × price × (interval / 3600). Manages four accumulation windows.
PowerMonitorEntityService Creates, updates, resets, and cleans up all MQTT entities in HA. Handles per-device entity lifecycle.

Sensor Discovery

Initial Discovery

Runs once at startup:

  1. Query all HA entities with device_class: power and unit_of_measurement: W or kW
  2. Identify main meter by configured MainMeterEntityId
  3. Exclude sensors matching ExcludedSensorPatterns
  4. Everything remaining is a tracked device sensor

Re-Discovery

Triggered manually via button.powermonitor_rediscover_sensors in HA:

  • Re-scans all power sensors
  • Creates entities for newly discovered sensors
  • Cleans up entities for removed sensors
  • Updates the sensor.powermonitor_status discovered sensors list

Configuration (appsettings.json)

{
  "PowerMonitor": {
    "MainMeterEntityId": "sensor.p1_meter_power",
    "PollIntervalSeconds": 15,
    "SmoothingWindowSize": 10,
    "AnomalyThresholdWatts": 500,
    "ExcludedSensorPatterns": [
      "sensor.nordpool_*",
      "sensor.powermonitor_*"
    ]
  }
}
Setting Default Purpose
MainMeterEntityId — P1 meter entity ID (required)
PollIntervalSeconds 15 Poll interval in seconds
SmoothingWindowSize 10 EMA window size (10 × 15s = 2.5 min)
AnomalyThresholdWatts 500 Threshold for anomaly binary sensor
ExcludedSensorPatterns [] Glob patterns for sensors to ignore

Calculation & Data Flow

Poll Cycle (every 15 seconds)

  1. Read P1 main meter → total power (W)
  2. Read all discovered device sensors → individual power readings
  3. Compute raw other: total - sum(devices), clamp to 0
  4. Apply EMA smoothing: smoothed = α × raw + (1 - α) × previous, where α = 2 / (windowSize + 1)
  5. Get current NordPool price from INordPoolPriceService
  6. For each source (total, each device, other): cost_increment = power_kW × price × (interval_s / 3600)
  7. Add increment to all four accumulation buckets
  8. At window boundaries, store completed value as previous_* and reset
  9. Push all values to HA entities via MQTT

Cost Accumulation Windows

Window Resets At Purpose
15 min :00, :15, :30, :45 Granular recent cost
1 hour Top of each hour Short-term trends
1 day Midnight Daily cost tracking
1 month 1st of month, midnight Billing cycle tracking

Edge Cases

Condition Behavior
Main meter unavailable Skip cycle, log warning, increment circuit breaker counter
5+ consecutive main meter failures Set status to "warning" with reason, resume when available
Device sensor unavailable Treat as 0W, add to degraded_sensors list in status entity
Negative "other" (devices > total) Clamp to 0, set data_quality: "device_sum_exceeds_total"
NordPool price unavailable Use last known price, set price_source: "stale"
Mid-window restart Buckets start at 0, partial_window: true until first full window

HA Entities

System-Level Entities

Entity ID Type State Key Attributes
sensor.powermonitor_total_power sensor Total W unit: W, device_class: power
sensor.powermonitor_total_cost_15min sensor EUR device_class: monetary, previous_15min
sensor.powermonitor_total_cost_1h sensor EUR device_class: monetary, previous_1h
sensor.powermonitor_total_cost_daily sensor EUR device_class: monetary, previous_daily
sensor.powermonitor_total_cost_monthly sensor EUR device_class: monetary, previous_monthly
sensor.powermonitor_other_power sensor Smoothed W raw_power, smoothed_power, data_quality
sensor.powermonitor_other_cost_15min sensor EUR Same pattern as total
sensor.powermonitor_other_cost_1h sensor EUR
sensor.powermonitor_other_cost_daily sensor EUR
sensor.powermonitor_other_cost_monthly sensor EUR
binary_sensor.powermonitor_anomaly binary_sensor on/off smoothed_watts, threshold, duration_above
sensor.powermonitor_status sensor ok/warning tracked_sensors_count, last_poll, discovered_sensors, degraded_sensors
button.powermonitor_rediscover_sensors button — Triggers re-discovery

Per-Device Entities (auto-generated)

For each discovered sensor (e.g., sonoff_1002230e32):

Entity ID Type State
sensor.powermonitor_<device>_cost_15min sensor EUR
sensor.powermonitor_<device>_cost_1h sensor EUR
sensor.powermonitor_<device>_cost_daily sensor EUR
sensor.powermonitor_<device>_cost_monthly sensor EUR

All cost entities share: unit_of_measurement: EUR, device_class: monetary, state_class: total, partial_window, price_source, last_updated.

Error Handling

  • All entity writes use safe wrappers (try/catch per write, log and continue)
  • Circuit breaker on main meter: 5 consecutive failures → warning state
  • Individual device failures don't block the poll cycle
  • Thread safety via ConcurrentDictionary for cost accumulators
  • All HA entity writes parallelized via Task.WhenAll

Testing

Test Class Coverage
OtherPowerCalculationServiceTests Raw calculation, EMA smoothing, negative clamping, edge cases
CostAccumulatorTests Window resets (15min, 1h, daily, monthly), partial windows, thread safety
PowerSensorDiscoveryServiceTests Pattern matching, exclusion filters, re-discovery, new/removed sensors
PowerCostCalculationServiceTests NordPool integration, stale price fallback, per-device cost
PowerMonitorEntityServiceTests Entity creation, update, cleanup, per-device lifecycle

All tests use xUnit, Moq, and FluentAssertions.