# HomeAssistant.HistoryReplay A debugging tool that fetches real historical data from your Home Assistant instance and replays it through the monitor business logic to verify decisions without side effects. ## Prerequisites - .NET 10 SDK - A running Home Assistant instance with the History API enabled - A [long-lived access token](https://www.home-assistant.io/docs/authentication/#your-account-profile) from Home Assistant ## Quick Start ### 1. Configure the connection Edit `appsettings.json` (or create `appsettings.development.json` for local overrides): ```json { "HomeAssistant": { "Host": "homeassistant.local", "Port": 8123, "Token": "", "Ssl": false } } ``` > **Security note:** Never commit your access token. Use `appsettings.development.json` (already in `.gitignore`) or environment variables instead. ### 2. Set the replay time range ```json { "Replay": { "StartTime": "2026-03-30T00:00:00+02:00", "EndTime": "2026-03-31T00:00:00+02:00" } } ``` Times are in ISO 8601 format with timezone offset. The tool fetches all entity history within this window from the HA REST API (`/api/history/period`). ### 3. Enable or disable monitors ```json { "Replay": { "Monitors": { "NordPool": true, "Boiler": true, "Shower": true, "Power": false, "Light": true } } } ``` Set any monitor to `false` to skip it during replay. ### 4. Run ```bash dotnet run --project HomeAssistant.HistoryReplay ``` Or from the project directory: ```bash cd HomeAssistant.HistoryReplay dotnet run ``` ## What It Does The tool replays historical entity states through the **real business logic services** from each monitor project: | Monitor | Services Used | What It Shows | |---------|--------------|---------------| | **NordPool** | `CheapestIntervalsFinder` | Price changes, cheap interval identification | | **Boiler** | `BoilerControlService`, `WaterReadyService`, `BoilerRunTimeTracker` | Turn on/off decisions, water-ready detection, runtime tracking, budget usage | | **Shower** | `ShowerDetectionService`, `ExhaustFanControlService`, `HumidityRateCalculator` | Shower state transitions (Idle/Suspected/Active/Declining/Completed), fan control | | **Power** | `OtherPowerCalculationService`, `PowerCostCalculationService` | Power breakdown, cost accumulation, anomaly detection | | **Light** | Event-driven replay of sun/person state changes | Light-on decisions based on sunset and person arrivals | ### No side effects - **No MQTT entities** are created or updated - **No HA service calls** are executed (they are logged as "would call" events) - **No NetDaemon runtime** is required - The tool only reads from the HA History API ## Console Output The tool produces a colored timeline report: ``` ═══════════════════════════════════════════════════════════ REPLAY: 2026-03-30 00:00 -> 2026-03-31 00:00 ═══════════════════════════════════════════════════════════ -- NordPool ────────────────────────────────────────────── 00:00 Price: 3.21 ct/kWh 00:15 Price: 3.18 ct/kWh 00:15 -> CHEAP interval active (rank #2, price: 3.18 ct/kWh) -- Boiler ──────────────────────────────────────────────── 00:15 -> TURN ON (cheap: True, water ready: False, budget: 0%) 01:30 Water ready detected (power: 3.2W, threshold: 5.0W) 01:30 -> TURN OFF (cheap: True, water ready: True, budget: 42%) 23:59 Final: 01:15:00 total runtime, 2 session(s) -- Shower ──────────────────────────────────────────────── 07:12 State: Idle -> Suspected (bathroom: 62.1%, home: 53.0%, diff: 9.1%) 07:14 State: Suspected -> Active (bathroom: 65.3%, home: 53.0%, diff: 12.3%) 07:35 State: Declining -> Completed (bathroom: 58.2%, home: 54.1%, diff: 4.1%) -- Service Calls ───────────────────────────────────────── 00:15 -> Would call switch.turn_on on switch.boiler 01:30 -> Would call switch.turn_off on switch.boiler ═══════════════════════════════════════════════════════════ REPLAY SUMMARY ═══════════════════════════════════════════════════════════ Total events: 24 Decisions: 5 Service calls: 4 Warnings: 0 Anomalies: 0 ``` ## Configuration Reference ### Monitor-specific settings The monitor sections (`BoilerMonitor`, `ShowerMonitor`, `PowerMonitor`, `LightMonitor`) use the **same options classes** as the production `HomeAssistant.Server` project. This means thresholds, entity IDs, and poll intervals match what runs in production. #### ShowerMonitor | Setting | Default | Description | |---------|---------|-------------| | `BathroomHumidityEntityId` | `sensor.bathroom_humidity` | Bathroom humidity sensor | | `MainHomeHumidityEntityId` | `sensor.main_home_humidity` | Reference home humidity sensor | | `PollIntervalSeconds` | `30` | Replay step interval | | `SpikeRateThreshold` | `4.0` | Humidity rate (%/min) to trigger suspected state | | `MinDifferentialHumidity` | `8.0` | Minimum bathroom-vs-home humidity difference | | `PeakHumidityThreshold` | `58.0` | Humidity to confirm active shower | #### PowerMonitor | Setting | Default | Description | |---------|---------|-------------| | `MainMeterEntityId` | *(required)* | Main power meter entity | | `PollIntervalSeconds` | `1` | Replay step interval | | `AnomalyThresholdWatts` | `500` | "Other" power threshold for anomaly detection | | `SmoothingWindowSize` | `10` | EMA window for smoothing | #### LightMonitor | Setting | Default | Description | |---------|---------|-------------| | `LightEntityId` | `light.sonoff_1002214d40` | The light entity to control | | `SunEntityId` | `sun.sun` | Sun entity for below-horizon detection | | `PersonEntityIds` | `[...]` | Person entities for presence detection | ### Environment-based configuration You can override any setting via environment variables using the `__` separator: ```bash set Replay__StartTime=2026-03-29T00:00:00+02:00 set HomeAssistant__Token=your_token_here dotnet run --project HomeAssistant.HistoryReplay ``` ## Project Architecture ``` HomeAssistant.HistoryReplay/ ├── Program.cs Entry point, DI wiring, orchestration ├── HomeAssistantClient/ Self-contained HA REST API client │ ├── IHomeAssistantApiClient.cs │ ├── HomeAssistantApiClient.cs │ └── HomeAssistantSettings.cs ├── Configuration/ │ ├── ReplayOptions.cs Time range and monitor flags │ └── ReplayEntityMap.cs Maps monitors to required HA entity IDs ├── HistoryData/ │ ├── IHistoryDataProvider.cs Abstraction for fetching history │ ├── HomeAssistantHistoryProvider.cs Fetches from /api/history/period │ ├── HistoryTimeline.cs Sorted timeline of entity states │ └── HistoryStateEntry.cs Single entity state snapshot ├── Replay/ │ ├── ReplayHaContext.cs IHaContext backed by historical data │ ├── ReplayTimeProvider.cs TimeProvider that steps through time │ └── NoOpEntityManager.cs IEntityManager that logs but does nothing ├── Runners/ │ ├── IMonitorReplayRunner.cs Common runner interface │ ├── NordPoolReplayRunner.cs Price + cheapest interval replay │ ├── BoilerReplayRunner.cs Boiler control decision replay │ ├── ShowerReplayRunner.cs Shower detection state machine replay │ ├── PowerReplayRunner.cs Power calculation + cost replay │ └── LightReplayRunner.cs Sun/person event-driven replay ├── Reporting/ │ ├── ReplayEvent.cs Single decision/event during replay │ ├── ReplayTimeline.cs Collected events across all monitors │ └── ConsoleReportRenderer.cs Colored console output └── appsettings.json Configuration ``` ### Key design: real services, fake infrastructure The replay instantiates **actual production business logic** (e.g., `BoilerControlService.DetermineAction()`, `ShowerDetectionService.Evaluate()`) but replaces infrastructure with replay stubs: - `ReplayHaContext` implements `IHaContext` by returning historical state at the current replay timestamp - `ReplayTimeProvider` extends `TimeProvider` for time-dependent logic (e.g., `WaterReadyService` cooldown periods) - `NoOpEntityManager` implements `IEntityManager` and logs all calls without side effects - Service calls via `IHaContext.CallService()` are captured as replay events All five monitors run their replays **in parallel** via `Task.WhenAll`. ## Troubleshooting ### "History replay failed" with HTTP errors - Verify your HA host, port, and token in `appsettings.json` - Ensure the HA History API is enabled (it is by default) - Check that the token has sufficient permissions ### No events in the output for a monitor - The entity IDs in the monitor config must match your actual HA entities - Check that history data exists for the configured time range (HA purges old history based on the recorder settings) - Verify the monitor is enabled in `Replay.Monitors` ### Shower monitor shows no sessions - Confirm `BathroomHumidityEntityId` and `MainHomeHumidityEntityId` have data in the replay period - Adjust `SpikeRateThreshold` and `MinDifferentialHumidity` if your bathroom has different humidity characteristics ### Boiler shows "not configured" - The boiler replay reads config entity states (`text.boilermonitor_config_power_entity_id`, `text.boilermonitor_config_switch_entity_id`) from history. These must have been set in HA during the replay period.