node-red-contrib-octopus-intelligent 1.5.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +487 -442
  2. package/README.md +1004 -980
  3. package/examples/basic-monitoring.json +1 -1
  4. package/examples/ha-dashboard.yaml +602 -599
  5. package/examples/mqtt-integration.json +1 -1
  6. package/examples/node-red-dashboard-flow.json +1287 -1199
  7. package/examples/set-preferences.json +1 -1
  8. package/lib/api-metrics.js +31 -31
  9. package/lib/auth.js +20 -20
  10. package/lib/categories/account.js +32 -32
  11. package/lib/categories/applicable-rates.js +127 -127
  12. package/lib/categories/completed-dispatches.js +35 -35
  13. package/lib/categories/electricity.js +146 -146
  14. package/lib/categories/flex-planned-dispatches.js +36 -36
  15. package/lib/categories/free-electricity.js +61 -61
  16. package/lib/categories/gas.js +95 -95
  17. package/lib/categories/home-mini.js +37 -37
  18. package/lib/categories/intelligent.js +155 -124
  19. package/lib/categories/octoplus.js +32 -32
  20. package/lib/categories/saving-sessions.js +64 -64
  21. package/lib/categories/wheel-of-fortune.js +49 -49
  22. package/lib/commands.js +47 -0
  23. package/lib/discovery-retry.js +13 -0
  24. package/lib/discovery.js +92 -85
  25. package/lib/graphql-errors.js +18 -0
  26. package/lib/graphql.js +44 -44
  27. package/lib/http-get-json.js +22 -22
  28. package/lib/payload.js +89 -88
  29. package/lib/poll-tick.js +44 -44
  30. package/lib/preferences.js +32 -0
  31. package/lib/scheduler.js +47 -47
  32. package/lib/sensor-definitions.js +219 -0
  33. package/lib/timezone.js +49 -49
  34. package/lib/update-check.js +38 -38
  35. package/octopus-intelligent.html +218 -205
  36. package/octopus-intelligent.js +1687 -1807
  37. package/package.json +54 -54
package/CHANGELOG.md CHANGED
@@ -1,442 +1,487 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
- ## [1.5.0] — 2026-06-13
9
-
10
- Schedule visibility, tariff rate bands, proactive update notification, and a Node-RED Dashboard 2.0 example.
11
-
12
- ### Added — Schedule visibility (import & export)
13
- - 24h schedule stats: `applicable_rates_{min,max,median,avg}_pence` and `electricity_export_rate_*` equivalents — min/max/median/avg over the next 24h of half-hourly rates.
14
- - The full `applicable_rates` / `electricity_export_rate` slot arrays are now exposed as MQTT entity attributes on the existing `*_count` sensors, accessible via `state_attr(...)` in HA templates.
15
-
16
- ### Added — Tariff rate bands
17
- - `electricity_day_rate`, `electricity_night_rate`, `electricity_ev_peak_rate`, `electricity_ev_off_peak_rate` — raw tariff-defined bands from the Kraken `DayNightTariff` / `FourRateEvTariff` types. Null on tariffs without banding (half-hourly/Agile users see nulls; Economy 7 / FourRateEv users see values).
18
-
19
- ### Added — Update notification
20
- - HA MQTT Update entity (`update.octopus_intelligent_node_update`) surfacing newer-version availability in HA's Settings → Updates panel. Requires HA ≥ 2022.4.
21
- - Node-RED debug log emits `node.warn` once per detected new version, with install instructions.
22
- - New payload fields: `installed_version`, `latest_version`, `update_available`, `update_check_at`, `update_check_error`. Checked once per 24h via the unified scheduler.
23
-
24
- ### Added — Promotion to MQTT entities (closing v1.3.0 gaps)
25
- - 8 previously payload-only fields promoted to MQTT entities: `applicable_rates_prev_pence/_gbp/_to`, `applicable_rates_next_pence/_gbp/_from`, `electricity_export_rate_prev_gbp`, `electricity_export_rate_next_gbp`.
26
-
27
- ### Added — Per-category error binary sensors
28
- - 15 new `binary_sensor`s with `device_class: problem`, one per category. `OFF` when healthy / `ON` when the corresponding `<category>_error` payload field is set. Existing string error sensors retained — no breakage.
29
-
30
- ### Added — Node-RED Dashboard 2.0 example
31
- - `examples/node-red-dashboard-flow.json` — importable Dashboard 2.0 flow with 32 widgets across 6 pages (Controls, Status, Tariff, Optimization, Account, Diagnostics), plus writable controls routed back into the node input.
32
- - Two annotated **sample function nodes** (`find-cheapest-window`, `is-cheapest-now`) demonstrating user-side derivation over `applicable_rates`. Example code only — not part of the published payload, keeping with the "expose raw data, no inference" principle.
33
-
34
- ### Fixed — Example HA dashboard (`examples/ha-dashboard.yaml`)
35
- - Home Mini live-demand gauge now floors at `-10 kW` (was `min: 0`) so solar export displays, with the green severity band extended to cover the negative range.
36
- - Tariff rate-bands card is hidden on half-hourly/Agile tariffs (null bands render to `"None"`/`unknown`, not `unavailable` — the conditional now excludes all three).
37
- - Gas cards are hidden for electricity-only homes (gated on `gas_tariff_code`).
38
-
39
- ### Backwards compatibility
40
- - All existing payload field names, MQTT topics, HA entity `unique_id`s, input commands, and node config fields are preserved. v1.4.0 → v1.5.0 is a zero-config upgrade.
41
-
42
- ## [1.4.0] — 2026-05-29
43
-
44
- Single poll loop. The V1 `setInterval(fetchData)` intelligent loop and the V2 `createScheduler(pollDueCategories)` category loop are merged into one clock-aligned scheduler with one auth and one emit per tick. No HA-side changes.
45
-
46
- ### Fixed
47
- - **Intermittent `KT-CT-1199` "Too many requests"** on `flexPlannedDispatches` — the standalone `flex_planned_dispatches` V2 category queried the same endpoint as the V1 intelligent poll, and the two unsynchronised loops phase-drifted into bursts that tripped Kraken's burst limit. The intelligent poll now owns `flexPlannedDispatches`; the standalone category is removed.
48
- - **Whole payload was nuked on any single-category error**, and `intelligent_error` was never set. Every category now follows one error policy: record `<category>_error`, keep last-good data, retry next interval. No permanent disable.
49
- - **Slow polls could overlap a tick** — added an in-flight guard around the scheduler.
50
-
51
- ### Changed (internal architecture; no HA-side breakage)
52
- - Every category exposes `async poll(token) → partialPayload`. Simple categories use a `simplePoll` factory; the intelligent poll is a bespoke category that owns both the devices and dispatch queries.
53
- - Tick / poll / error-merge logic moved into `lib/poll-tick.js` and `lib/scheduler.js` for unit-test coverage.
54
- - Manual refresh, MQTT refresh, and post-mutation validation re-polls all go through the same scheduler / intelligent-poll path.
55
-
56
- ### Unchanged
57
- - All payload field names, MQTT topics, `unique_id`s, HA entity IDs, input commands, and node config fields.
58
-
59
- ## [1.3.3] — 2026-05-22
60
-
61
- ### Fixed
62
- - **Saving Sessions card showed a 2-year-old session as "next"** — the category was emitting `events[0]` with no filter/sort, so stale historical events surfaced in `saving_session_start/end` and `saving_session_available` was effectively true forever. Now matches the `free-electricity` pattern: filter out ended events, sort earliest-first, take the first. `saving_session_available` now means "an upcoming session exists" as originally intended.
63
- - **Octoplus "Enrolled" and "Loyalty points user" stuck at "unavailable"** — both binary sensors were published with `entity_category: config`, which makes read-only sensor state stick at "unavailable" on some HA installs. Removed — same fix as the v1.3.0 tariff-sensor cleanup. Entity IDs are unchanged; not a breaking change.
64
- - **Example dashboard — Wheel of Fortune cards showed "Entity not found"** — `examples/ha-dashboard.yaml` referenced `..._wheel_of_fortune_*_spins`, but the entities are named "WoF …" so HA generates `..._wof_*_spins`. Corrected.
65
- - **Example dashboard — Home Mini gauge showed "Entity is non-numeric"** on accounts with no Home Mini — the gauge is now wrapped in a conditional card that hides until the entity reports a value.
66
-
67
- ### Added
68
- - `saving_session_window_active` (binary sensor) — true when an upcoming session window is currently happening, regardless of whether you joined.
69
- - `saving_session_active` (binary sensor) — true only when you have joined the current session AND we are inside its window. Use this to drive automations that should only run when there is a payoff.
70
-
71
- ### Changed (HA-side breaking)
72
- - `saving_session_joined` now publishes as `binary_sensor` instead of `sensor` — fixes the "False" display anomaly caused by HA's sensor domain rejecting raw booleans. **Update automations and dashboards referencing `sensor.saving_session_joined` to use `binary_sensor.saving_session_joined`.** Payload field name (`msg.payload.saving_session_joined`) is unchanged. Mirror of the v1.3.0 `octoplus_enrolled` migration. The plugin publishes an empty config to the old `sensor/.../config` topic on startup to clean the orphan from HA.
73
-
74
- ## [1.3.2] — 2026-05-14
75
-
76
- Defensive hardening pass following the v1.3.1 hotfix audit. No user-facing behaviour change against the current live Kraken API — every affected field already arrives as a JSON number today. The fix forecloses the same latent crash class (`TypeError: ...toFixed is not a function`) if Kraken ever serialises these scalars as strings, matching how `energyAddedKwh` is already returned.
77
-
78
- ### Fixed
79
- - `lib/categories/electricity.js` — `tariff.unitRate` and `tariff.standingCharge` (both import and export branches) now coerce via `parseFloat()` before emitting. Prevents string passthrough that would (a) break `device_class: monetary` sensors in HA and (b) crash any downstream arithmetic.
80
- - `lib/categories/gas.js` — same treatment for `tariff.unitRate` and `tariff.standingCharge`.
81
- - `lib/categories/account.js` — `balance` (pence) now coerces via `parseFloat()` before emitting `account_balance_pence`. JavaScript's `/` operator was already coercing for `account_balance_pounds`, so this only tightens type consistency on the integer pence field.
82
-
83
- ### Tests
84
- - Added string-input regression tests for each coerced field, asserting `typeof === 'number'`. 4 new tests, 237 total (was 233).
85
-
86
- ## [1.3.1] — 2026-05-14
87
-
88
- Critical hotfix for v1.3.0. Users on 1.3.0 should upgrade immediately.
89
-
90
- ### Fixed
91
- - **Intelligent category crash on numeric string inputs** — `flexPlannedDispatches.energyAddedKwh` is returned by the live Kraken API as a string. The intelligent category's reduce accumulator concatenated strings instead of summing, then called `.toFixed()` on the resulting string, raising `TypeError: totalEnergy.toFixed is not a function`. Whole intelligent payload section fell back to `defaultData` (null slot times, `total_energy: 0`, `next_kwh: "0"`), which surfaced in Home Assistant as "Error updating entity" for every intelligent sensor. Fixed by coercing `energyAddedKwh` via `parseFloat()` before arithmetic and formatting in `lib/categories/intelligent.js`, matching the pattern already used in `lib/categories/flex-planned-dispatches.js`. Added regression tests covering both positive and negative (export dispatch) string inputs.
92
- - `next_kwh` now consistently formats with two decimal places (e.g. `"5.50"`, `"15.20"`) per the documented contract in README, HTML help, and `test-mocks.js`. The v1.3.0 path stripped trailing zeros via `String(parseFloat(...))` — that branch is unreachable now because it always crashed before reaching it, but the format is corrected for completeness.
93
-
94
- ## [1.3.0] — 2026-05-12
95
-
96
- Major additive release covering the full Octopus Energy consumer read surface. No breaking changes to v1.2.x payload fields, entity IDs, MQTT topics, input commands, or node config fields. All v1.2.x automations and dashboards continue to work unchanged.
97
-
98
- ### Added — Electricity (import)
99
- - `electricity_standing_charge` — daily standing charge (p/day)
100
- - `electricity_unit_rate` — fixed unit rate (p/kWh); `null` on half-hourly tariffs
101
- - `electricity_tariff_code`, `electricity_valid_from`, `electricity_valid_to`
102
- - `electricity_consumption_kwh` — previous day import consumption
103
- - `electricity_consumption_from`, `electricity_consumption_to` — period boundaries
104
- - `applicable_rates`, `applicable_rates_count` — full 48-slot half-hourly schedule
105
- - `applicable_rates_current_pence`, `applicable_rates_current_gbp` — live rate (use these on half-hourly tariffs)
106
- - `applicable_rates_prev_pence/_gbp/_to`, `applicable_rates_next_pence/_gbp/_from` — adjacent slot rates and transition timestamps (payload-only; not currently exposed as MQTT entities — see README)
107
-
108
- ### Added — Electricity (export)
109
- - `electricity_export_standing_charge` — typically `0` for Agile Outgoing
110
- - `electricity_export_unit_rate` — fixed; `null` on half-hourly export tariffs
111
- - `electricity_export_tariff_code` (e.g. `AGILE-OUTGOING-19-05-13`), `electricity_export_valid_from`, `electricity_export_valid_to`
112
- - `electricity_export_consumption_kwh`, `_from`, `_to` — previous day export from the export meter
113
- - `electricity_export_rate`, `electricity_export_rate_count` — full 48-slot half-hourly export schedule
114
- - `electricity_export_rate_current_pence/_gbp` — live export rate
115
- - `electricity_export_rate_prev_pence/_to`, `electricity_export_rate_next_pence/_from` — adjacent export slot rates
116
-
117
- ### Added — Gas
118
- - `gas_standing_charge`, `gas_unit_rate`, `gas_tariff_code`, `gas_valid_from`, `gas_valid_to`
119
- - `gas_consumption_kwh`, `gas_consumption_from`, `gas_consumption_to`
120
-
121
- ### Added — Home Mini
122
- - `mini_demand_kw` (kW, numeric) — real-time grid demand
123
- - `mini_consumption_delta_kwh` (kWh, numeric) — half-hour period consumption
124
- - `mini_read_at` — timestamp of most recent telemetry
125
- - Opt-in via "Enable Home Mini" checkbox in node config
126
-
127
- ### Added — Rewards
128
- - `saving_session_available` (binary), `saving_session_start`, `saving_session_end`, `saving_session_joined`
129
- - `free_electricity_active` (binary), `free_electricity_available` (binary), `free_electricity_start`, `free_electricity_end`
130
- - `wheel_of_fortune_electricity_spins`, `wheel_of_fortune_gas_spins` — opt-in via node config checkbox
131
- - `octoplus_enrolled` (binary sensor), `octoplus_enrollment_status` (string), `octoplus_loyalty_points_user` (binary sensor)
132
-
133
- ### Added — Account & dispatches
134
- - `account_balance_pounds`, `account_balance_pence`
135
- - `completed_dispatches` (array), `completed_dispatches_count` — completed intelligent dispatch history
136
- - `flex_planned_dispatches` (array), `flex_planned_dispatches_count` — upcoming flex dispatches (replaces deprecated `plannedDispatches`)
137
-
138
- ### Added — Infrastructure
139
- - **Account discovery** — automatic product detection at startup; categories auto-enable based on registered products and discover both import and export meter points by `direction`, not array position
140
- - **Per-category poll intervals** — configurable in node editor for each data source
141
- - **1-second clock-aligned category scheduler** — independent polling; one slow category doesn't block others
142
-
143
- ### Changed
144
- - **Octopus `wheelOfFortuneSpins` migrated to `wheelOfFortuneSpinsAllowed`** on `api.backend.octopus.energy` — the old field was deprecated and scheduled for removal 2026-04-20
145
- - **Octopus `savingSessions` migrated to `api.backend.octopus.energy`** endpoint — the field was removed from the main endpoint
146
- - **`octoplus_enrolled` and `octoplus_loyalty_points_user` now publish as `binary_sensor` instead of `sensor`** — these are boolean values and HA's sensor domain rejects raw booleans. **HA-side breaking change for users referencing the old `sensor.*` entity IDs**: update automations and dashboards to use `binary_sensor.*`. Payload field names (`msg.payload.octoplus_enrolled`, `msg.payload.octoplus_loyalty_points_user`) are unchanged.
147
- - **`entity_category: config` removed** from read-only tariff/validity sensors (`electricity_unit_rate`, `electricity_tariff_code`, `electricity_valid_from/to`, `gas_*`, `electricity_export_*`, `saving_session_start/end`, `free_electricity_start/end`, `octoplus_enrollment_status`). These now appear in the main device entity list rather than a separate Configuration section. HA's `entity_category: config` is intended for user-configurable entities (switches, numbers, selects) — applying it to read-only sensors caused state to stick at "unavailable" on some installs.
148
-
149
- ### Fixed
150
- - **Import/export meter point selection** — discovery now selects meter points by the `direction` field (`IMPORT` or `EXPORT`), not array position. Earlier dev builds on accounts with both meters could surface export data as import (live "current rate" showing the export Agile rate instead of the import tariff). No stable v1.x release was affected; caught and fixed before v1.3.0 ship.
151
- - **MQTT transport headers** — `lib/graphql.js` now sends `User-Agent: node-red-contrib-octopus-intelligent/<version>` on every request. Without it, `api.backend.octopus.energy` returns 403 at the edge — which previously surfaced as "WoF returns HTML" and silently broken saving sessions.
152
- - **MQTT auth format** — uses raw JWT in the Authorization header (no `JWT ` prefix). Main endpoint accepts both; backend endpoint sub-resolvers require the raw form.
153
- - **Saving sessions schema migration** — removed deprecated `octopoints` field from `SavingSessionsAccountType` query (Octopus moved loyalty points to the Octoplus query).
154
- - **Gas tariff query fragments** — `GasTariffType` is an object type, not a union — removed inline fragments that caused "Fragment cannot be spread here" errors.
155
-
156
- ### Unchanged (no breaking changes)
157
- - All v1.2.x payload field names in `msg.payload`
158
- - All v1.2.x MQTT topics, `unique_id` values, and HA entity IDs (except the Octoplus domain change noted above)
159
- - All v1.2.x input commands: `set_limit`, `set_time`, `set_smart_charging`, `set_timezone`
160
- - All v1.2.x node config fields: `accountNumber`, `apiKey`, `broker`, `enableMqtt`, `name`, `refreshInterval`, `timezoneOverride`
161
- - Intelligent Octopus Go charging schedule, smart charging toggle, charging preferences
162
-
163
- ---
164
-
165
- ## [1.2.1] — 2026-04-29
166
-
167
- ### Fixed
168
- - **Deprecated API migration** — moved smart-charging verification from the deprecated `registeredKrakenflexDevice` query to the current `devices` query
169
- - **Mutation migration** — `setVehicleChargePreferences` (deprecated) replaced with `setDevicePreferences` using the 7-day schedule input
170
- - **Startup device fetch** — uses the current `devices` query instead of deprecated `registeredKrakenflexDevice`
171
-
172
- ### Unchanged
173
- - All v1.2.0 payload fields, MQTT topics, and entity IDs preserved
174
-
175
- ---
176
-
177
- ## [1.2.0] - 2026-04-26
178
-
179
- ### Added
180
- - **Smart Charging Toggle** — suspend or unsuspend Octopus intelligent charging from Node-RED or Home Assistant
181
- - `msg.payload = { set_smart_charging: true }` — enable (unsuspend)
182
- - `msg.payload = { set_smart_charging: false }` — disable (suspend)
183
- - **HA MQTT Switch** — "Smart Charging" switch entity in Home Assistant (auto-discovered)
184
- - **`smart_charging` payload field** — `true` = active, `false` = suspended, `null` = unknown (startup fetch pending or failed)
185
- - **Device ID startup fetch** — `krakenflexDeviceId` fetched once at startup via `registeredKrakenflexDevice` query; cached permanently
186
-
187
- ### Technical
188
- - Mirrors `setPreferences` pattern: auth → mutation → optimistic update → exponential backoff verification (15s/30s/60s/120s)
189
- - Verification re-fetches `registeredKrakenflexDevice.suspended` to confirm state change
190
- - Zero new npm dependencies
191
-
192
- ---
193
-
194
- ## [1.1.1] - 2026-04-26
195
-
196
- ### Security
197
- - **Removed `axios` dependency** — replaced with Node.js built-in `https` module; eliminates 13 transitive packages and all associated supply chain risk
198
- - **Removed test/mock files from npm package** — `__tests__/` and `test-mocks.js` no longer published; removes 139 kB of dev artefacts from end-user installs
199
- - **Removed images from npm package** — 364 kB of images no longer bundled; README images now reference GitHub raw URLs and render correctly on npmjs.com
200
-
201
- ### Changed
202
- - Package size reduced from 369 kB → 27 kB (93% reduction)
203
- - Zero production dependencies (was: `axios ^1.6.0`)
204
-
205
- ---
206
-
207
- ## [1.1.0] - 2026-04-24
208
-
209
- ### Added
210
- - **Locale Timestamps** — new `*_locale` fields in every payload, always in server auto-detected timezone
211
- - `slot1_start_locale`, `slot1_end_locale`, `slot2_start_locale`, `slot2_end_locale`
212
- - `slot3_start_locale`, `slot3_end_locale`, `window_start_locale`, `window_end_locale`
213
- - `next_start_locale`
214
- - **Timezone Metadata** — `timezone_detected` (server auto-detect) and `timezone_applied` (active TZ for display fields)
215
- - **HA Timezone Select Entity** — `select.octopus_timezone` with 15 curated IANA timezones covering all Octopus operating countries (UK, AU, DE, ES, NZ, US)
216
- - Selection persists across Node-RED restarts via node context storage
217
- - State republished to HA on Node-RED startup
218
- - **`set_timezone` Input Command** — `msg.payload = { set_timezone: "Europe/London" }`, same pattern as `set_limit`/`set_time`
219
- - **`timezoneOverride` Node Config Field** — optional IANA timezone in node editor, leave blank for auto-detect
220
- - **Timezone Diagnostic Sensors** — `sensor.octopus_timezone_detected` and `sensor.octopus_timezone_applied`
221
-
222
- ### Changed
223
- - **Display timestamp fields now output resolved timezone** instead of raw UTC
224
- - Affected fields: `slot1_start`, `slot1_end`, `slot2_start`, `slot2_end`, `slot3_start`, `slot3_end`, `window_start`, `window_end`, `next_start`
225
- - Resolution order: HA-persisted selection → `timezoneOverride` config → server auto-detected
226
- - **Raw fields (`*_raw`) remain unchanged** — always exact UTC strings from the API
227
-
228
- ### Technical
229
- - Zero new npm dependencies — native `Intl.DateTimeFormat` API (Node 14 compatible)
230
- - `convertToTimezone(dateStr, tz)` — handles DST correctly, falls back to original string on error
231
- - `resolveTimezone(node)` — reads node context storage, config field, or server auto-detect
232
-
233
- ## [1.0.5] - 2025-12-31
234
-
235
- ### Fixed
236
- - **README Documentation** - Removed misleading "Octopus Energy branded device cards" claim
237
- - Changed to accurate description: "Clean Organization" and "Professional Layout"
238
- - No actual Octopus Energy branding exists in Home Assistant device cards
239
- - Avoids potential trademark/copyright concerns
240
-
241
- ## [1.0.4] - 2025-12-11
242
-
243
- ### Added
244
- - **Manual Refresh Button (MQTT)** - "Octopus Refresh API" button in Home Assistant
245
- - Hardcoded 30-second rate limiting to prevent API spam
246
- - Shows warning in Node-RED when rate limited
247
- - Publishes refresh cooldown state to MQTT
248
- - **Refresh Available At Sensor** - Diagnostic timestamp sensor
249
- - Shows ISO timestamp when manual refresh becomes available
250
- - Displays as countdown in Home Assistant ("in 25 seconds")
251
- - Automatically clears to `null` after 30 seconds
252
- - Leverages Home Assistant's native timestamp handling
253
- - **Next Poll Time Sensors** - Shows when next automatic poll will occur
254
- - `sensor.octopus_next_poll_time` - Main sensor (timestamp class)
255
- - `sensor.octopus_next_poll_time_raw` - Diagnostic raw timestamp
256
- - Updates after each successful poll
257
- - **API Complexity Tracking** - Monitor API usage against 50,000 hourly limit
258
- - `sensor.octopus_api_requests_hour` - Count of requests (last 60 min)
259
- - `sensor.octopus_api_complexity_hour` - Total complexity used
260
- - `sensor.octopus_api_complexity_usage` - Percentage of limit used
261
- - Estimated complexity: Regular poll (300), Mutation (250), Pre-validation (200)
262
- - All API complexity sensors in Diagnostics section
263
- - **Enhanced Debug Output** - `msg.debug` now includes:
264
- - `responseHeaders` - Full HTTP response headers from API
265
- - `extensions` - GraphQL extensions field (if present)
266
- - `api_usage` - Comprehensive API usage metrics per request
267
- - **Comprehensive Test Coverage** - Added 5 new tests
268
- - Tests for MQTT refresh button rate limiting
269
- - Tests for countdown expiry behavior
270
- - Validates countdown doesn't go negative
271
- - Tests timer cleanup and MQTT message structure
272
-
273
- ### Changed
274
- - **Rate Limiting Strategy** - Different behavior for MQTT vs Node-RED
275
- - MQTT Button: Hardcoded 30-second cooldown (enforced)
276
- - Node-RED Input: No rate limiting (programmers control this)
277
- - Timestamp-based cooldown (not seconds counter)
278
- - **State Output** - Node-RED now outputs state on every poll
279
- - Previously only output on changes
280
- - Now outputs full `statusPayload` every poll cycle
281
- - Better for automations and monitoring
282
- - **Global Setter** - Updated `NodeRed_Global_Setter.js` with new fields:
283
- - `octopus_next_poll`
284
- - `octopus_refresh_available_at`
285
- - `octopus_api_requests_hour`
286
- - `octopus_api_complexity_hour`
287
- - `octopus_api_complexity_percent`
288
-
289
- ### Fixed
290
- - **Cooldown Timer Expiry** - Properly publishes `null` at 30 seconds
291
- - Prevents countdown showing negative values in Home Assistant
292
- - Timer cleanup prevents memory leaks
293
- - Exactly 2 MQTT messages per refresh (start + expiry)
294
-
295
- ### Technical Details
296
- - **API Complexity Estimation** - Since Octopus API doesn't provide actual complexity:
297
- - Uses estimated values based on query types
298
- - Tracks rolling 60-minute window
299
- - If actual complexity becomes available, will use it automatically
300
- - **Timestamp-Based Cooldown** - Uses ISO timestamps instead of seconds
301
- - Home Assistant handles countdown display automatically
302
- - Zero MQTT spam during countdown
303
- - Clean `null` state when ready
304
-
305
- ## [1.0.3] - 2025-12-04
306
-
307
- ### Added
308
- - **State reconciliation loop** for charging detection (every 10 seconds)
309
- - Automatically detects charging state based on cached slot timestamps
310
- - No API calls - uses local data only
311
- - Handles imminent/immediate slots when car is plugged in
312
- - Self-healing: corrects state if timers miss edge cases
313
- - **Flow Library scorecard compliance**
314
- - Added `version` field to `node-red` section in package.json (>=2.0.0)
315
- - Added `examples/` folder with 3 demonstration flows
316
- - Satisfies Node-RED Flow Library requirements
317
-
318
- ### Fixed
319
- - **Home Assistant sensors going "unknown"** when adjusting controls
320
- - Sensors now maintain last known values while editing pending preferences
321
- - Only update when fresh data arrives from API
322
- - Added `lastKnownState` cache and state merging in `publishCurrentState()`
323
- - **Charging state not updating** for imminent/immediate slots
324
- - Fixed edge case where slots starting <30s after poll were not detected
325
- - Reconciliation loop catches these within 10 seconds
326
- - Ensures accurate "Charging Now" sensor in Home Assistant
327
-
328
- ### Changed
329
- - Improved charging state management with redundant detection methods
330
- - Enhanced MQTT state publishing to preserve sensor data during control updates
331
-
332
- ## [1.0.2] - 2025-11-30
333
-
334
- ### Changed
335
- - Updated flow example description in Node-RED help panel for better clarity
336
- - Improved explanation of default behavior: reads by default, manually refreshable, and accepts commands
337
-
338
- ## [1.0.1] - 2025-11-30
339
-
340
- ### Added
341
- - **Node.js and Node-RED version requirements** in package.json engines field
342
- - Minimum Node.js: >=14.0.0
343
- - Minimum Node-RED: >=2.0.0
344
- - Addresses Flow Library scorecard requirements
345
- - **Comprehensive example flows** in Node-RED help panel
346
- - Basic monitoring flow (inject every 5 min)
347
- - Set preferences from flow (JSON payload with set_limit/set_time)
348
- - Home Assistant MQTT integration example
349
- - **Visual documentation** with screenshots
350
- - Node-RED flow examples showing monitoring, preferences, and preset buttons
351
- - MQTT integration flow example
352
- - Home Assistant device page with all entities
353
- - **Visual Examples section** in Node-RED help panel with embedded GitHub-hosted images
354
- - **Screenshots section** in README.md showing real-world usage
355
-
356
- ### Changed
357
- - Updated README.md with Screenshots section after Features
358
- - Updated .npmignore to exclude images/ folder (keeps npm package lightweight)
359
- - Updated .gitignore to exclude local documentation files
360
-
361
- ### Fixed
362
- - Flow Library scorecard now shows supported Node-RED and Node.js versions
363
- - Flow Library scorecard "Nodes have examples" requirement now satisfied
364
-
365
- ## [1.0.0] - 2025-11-30
366
-
367
- ### Added
368
- - Initial public release
369
- - **Octopus Energy GraphQL API integration**
370
- - Authentication via API key
371
- - Fetch planned charging dispatches (smart-charge and bump-charge slots)
372
- - Query vehicle charging preferences (target SOC and ready time)
373
- - Update charging preferences via GraphQL mutations
374
- - **Home Assistant MQTT auto-discovery**
375
- - Number entity: Target charge limit (50-100%)
376
- - Select entity: Ready time (04:00-11:00)
377
- - Button entity: Apply changes
378
- - Sensor entities: Confirmed settings, next charge time, total energy, slot times
379
- - Binary sensor: Charging now (ON/OFF)
380
- - Organized into Controls, Sensors, and Diagnostics categories
381
- - **Real-time charging slot detection**
382
- - Detects currently active charging slots
383
- - Calculates next charging start time
384
- - Provides individual slot start/end times (up to 3 slots)
385
- - Calculates overall charging window
386
- - Shows charge source (smart-charge vs bump-charge)
387
- - **Exponential backoff validation**
388
- - Smart retry mechanism when updating preferences
389
- - Prevents sensors from becoming "unavailable" during API updates
390
- - Validates changes at 15s, 30s, 60s, 120s intervals
391
- - **Comprehensive debugging**
392
- - Full API call tracking in msg.debug
393
- - Success/failure status for each operation
394
- - Detailed error messages
395
- - **Node-RED flow control**
396
- - Accept input messages to set preferences programmatically
397
- - Output payload with all charging data
398
- - 5-minute default refresh interval (configurable)
399
- - **Octopus Energy branding**
400
- - Professional pink theme (#E8146F)
401
- - Device branded as "Octopus Intelligent" in Home Assistant
402
- - Suggested "Energy" area in Home Assistant
403
- - **Unit test coverage**
404
- - Data processing tests (10 tests)
405
- - Timer management tests (10 tests)
406
- - Mock API responses for consistent testing
407
-
408
- ### Security
409
- - API key stored securely as Node-RED credential (not exposed in flows)
410
- - Account numbers sanitized in MQTT topics and entity IDs
411
-
412
- ### Documentation
413
- - Comprehensive README.md with:
414
- - Feature list and capabilities
415
- - Installation instructions (npm and palette manager)
416
- - Configuration guide
417
- - Home Assistant setup instructions
418
- - Node-RED usage examples
419
- - Home Assistant automation examples
420
- - Troubleshooting section
421
- - Support options (GitHub Star, Sponsor, PayPal donate)
422
- - MIT License
423
- - GitHub repository with issue tracking
424
-
425
- ## Release Notes
426
-
427
- ### Version Numbering
428
- This project follows [Semantic Versioning](https://semver.org/):
429
- - **MAJOR** version (X.0.0): Breaking changes
430
- - **MINOR** version (1.X.0): New features (backwards compatible)
431
- - **PATCH** version (1.0.X): Bug fixes (backwards compatible)
432
-
433
- ### Links
434
- - [npm Package](https://www.npmjs.com/package/node-red-contrib-octopus-intelligent)
435
- - [GitHub Repository](https://github.com/ASomerN/node-red-contrib-octopus-intelligent)
436
- - [Node-RED Flow Library](https://flows.nodered.org/node/node-red-contrib-octopus-intelligent)
437
- - [Issues & Bug Reports](https://github.com/ASomerN/node-red-contrib-octopus-intelligent/issues)
438
-
439
- ### Support
440
- - ⭐ [Star on GitHub](https://github.com/ASomerN/node-red-contrib-octopus-intelligent)
441
- - 💖 [Become a Sponsor](https://github.com/sponsors/ASomerN)
442
- - ☕ [Donate via PayPal](https://www.paypal.com/donate?hosted_button_id=A2B8ZFEJBE2S6)
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.6.1] — 2026-10-03
9
+
10
+ First public 1.6 release. 1.6.0 was only distributed as a preview build; everything in it is included here.
11
+
12
+ ### Added
13
+ - **Charge Cap** — new Home Assistant switch, `set_charge_cap` input and `charge_cap` payload field (limit smart charging to off-peak rates only, as in the Octopus app).
14
+ - One input message can now carry several commands; each is applied independently.
15
+
16
+ ### Changed
17
+ - Ready-by time accepts any half-hour slot from 00:00 to 23:30, matching the Octopus app (was 04:00–11:00).
18
+ - Target charge accepts 5–100%, matching the Octopus app (was 50–100). Values still round to the nearest 5. The Home Assistant slider and the Dashboard 2.0 example go down to 5%.
19
+ - Invalid values are now rejected with an error and nothing is sent to Octopus, including `set_limit: 0` and empty strings. Previously an invalid time was silently replaced with 08:00 and sent. `null` values are ignored as before.
20
+ - Dashboard 2.0 example flow (`examples/node-red-dashboard-flow.json`) updated for 1.6: 34 widgets, including the Charge Cap switch and all 48 ready-by times; the target charge input goes down to 5%.
21
+ - HA dashboard example (`examples/ha-dashboard.yaml`) updated for 1.6: all 48 ready-by times and the Charge Cap switch.
22
+
23
+ ### Fixed
24
+ - Ready-by times after 11:00 were rejected (#3).
25
+ - Target charge values below 50% were silently raised to 50% (#3).
26
+ - **Day/Night and EV Peak/Off-Peak rate sensors stuck at "unavailable"** —
27
+ `electricity_day_rate`, `electricity_night_rate`, `electricity_ev_peak_rate`,
28
+ `electricity_ev_off_peak_rate` were published with `entity_category: config`, which
29
+ is invalid for read-only sensors (same issue fixed for tariff codes in v1.3.0; missed
30
+ on these four when added in v1.5.0). On some HA Core versions this now causes outright
31
+ entity-registration failure rather than just a stuck state. Removed the category — no
32
+ entity ID changes, not a breaking change. On upgrade these four sensors move from the
33
+ Configuration section to the Sensors section of the Home Assistant device page. Sensor definitions also extracted to
34
+ `lib/sensor-definitions.js` with regression coverage asserting no read-only sensor
35
+ carries `entity_category: config`.
36
+ - **Node stopped polling after a transient Octopus error at startup** — if Octopus's API returned a
37
+ temporary error while the node was starting (seen live as `KT-CT-4360` on device status), the node
38
+ gave up on product discovery and never started polling; a manual refresh then stayed on
39
+ "Manual refresh..." until Node-RED restarted. Discovery now retries (30 s, 1 min, 2 min, then every
40
+ 5 min) and shows "Discovery failed — retrying in …" while it does, and a failure on the device
41
+ status field alone no longer blocks discovery.
42
+ - **Slot sensors could show an out-of-date charging plan** — the check made 30 s before each slot
43
+ picks up a re-planned schedule and `charging_now` follows it, but the slot and window sensors kept
44
+ the old plan until the next scheduled poll. The node now polls immediately when that check finds
45
+ the plan has changed.
46
+ - **One failing field could stop all charging updates** — if Octopus returned an error for the Charge Cap
47
+ setting alone, the whole charging poll failed and slot sensors stopped updating. Charge Cap is now read
48
+ separately, so slots, limit and ready-by time keep updating and the switch keeps its last known state.
49
+
50
+ ### Backwards compatibility
51
+ - No MQTT topic, `unique_id` or entity ID changes from npm 1.5.0 or the 1.6.0 preview. New since 1.5.0: the Charge Cap switch, its `set_charge_cap` command topic, and 48 options on the Ready Time select. Pinned by `__tests__/discovery-snapshot.test.js`.
52
+
53
+ ## [1.5.0] — 2026-06-13
54
+
55
+ Schedule visibility, tariff rate bands, proactive update notification, and a Node-RED Dashboard 2.0 example.
56
+
57
+ ### Added — Schedule visibility (import & export)
58
+ - 24h schedule stats: `applicable_rates_{min,max,median,avg}_pence` and `electricity_export_rate_*` equivalents — min/max/median/avg over the next 24h of half-hourly rates.
59
+ - The full `applicable_rates` / `electricity_export_rate` slot arrays are now exposed as MQTT entity attributes on the existing `*_count` sensors, accessible via `state_attr(...)` in HA templates.
60
+
61
+ ### Added — Tariff rate bands
62
+ - `electricity_day_rate`, `electricity_night_rate`, `electricity_ev_peak_rate`, `electricity_ev_off_peak_rate` — raw tariff-defined bands from the Kraken `DayNightTariff` / `FourRateEvTariff` types. Null on tariffs without banding (half-hourly/Agile users see nulls; Economy 7 / FourRateEv users see values).
63
+
64
+ ### Added — Update notification
65
+ - HA MQTT Update entity (`update.octopus_intelligent_node_update`) surfacing newer-version availability in HA's Settings → Updates panel. Requires HA ≥ 2022.4.
66
+ - Node-RED debug log emits `node.warn` once per detected new version, with install instructions.
67
+ - New payload fields: `installed_version`, `latest_version`, `update_available`, `update_check_at`, `update_check_error`. Checked once per 24h via the unified scheduler.
68
+
69
+ ### Added — Promotion to MQTT entities (closing v1.3.0 gaps)
70
+ - 8 previously payload-only fields promoted to MQTT entities: `applicable_rates_prev_pence/_gbp/_to`, `applicable_rates_next_pence/_gbp/_from`, `electricity_export_rate_prev_gbp`, `electricity_export_rate_next_gbp`.
71
+
72
+ ### Added — Per-category error binary sensors
73
+ - 15 new `binary_sensor`s with `device_class: problem`, one per category. `OFF` when healthy / `ON` when the corresponding `<category>_error` payload field is set. Existing string error sensors retained — no breakage.
74
+
75
+ ### Added — Node-RED Dashboard 2.0 example
76
+ - `examples/node-red-dashboard-flow.json` — importable Dashboard 2.0 flow with 32 widgets across 6 pages (Controls, Status, Tariff, Optimization, Account, Diagnostics), plus writable controls routed back into the node input.
77
+ - Two annotated **sample function nodes** (`find-cheapest-window`, `is-cheapest-now`) demonstrating user-side derivation over `applicable_rates`. Example code only — not part of the published payload, keeping with the "expose raw data, no inference" principle.
78
+
79
+ ### Fixed — Example HA dashboard (`examples/ha-dashboard.yaml`)
80
+ - Home Mini live-demand gauge now floors at `-10 kW` (was `min: 0`) so solar export displays, with the green severity band extended to cover the negative range.
81
+ - Tariff rate-bands card is hidden on half-hourly/Agile tariffs (null bands render to `"None"`/`unknown`, not `unavailable` — the conditional now excludes all three).
82
+ - Gas cards are hidden for electricity-only homes (gated on `gas_tariff_code`).
83
+
84
+ ### Backwards compatibility
85
+ - All existing payload field names, MQTT topics, HA entity `unique_id`s, input commands, and node config fields are preserved. v1.4.0 → v1.5.0 is a zero-config upgrade.
86
+
87
+ ## [1.4.0] — 2026-05-29
88
+
89
+ Single poll loop. The V1 `setInterval(fetchData)` intelligent loop and the V2 `createScheduler(pollDueCategories)` category loop are merged into one clock-aligned scheduler with one auth and one emit per tick. No HA-side changes.
90
+
91
+ ### Fixed
92
+ - **Intermittent `KT-CT-1199` "Too many requests"** on `flexPlannedDispatches` — the standalone `flex_planned_dispatches` V2 category queried the same endpoint as the V1 intelligent poll, and the two unsynchronised loops phase-drifted into bursts that tripped Kraken's burst limit. The intelligent poll now owns `flexPlannedDispatches`; the standalone category is removed.
93
+ - **Whole payload was nuked on any single-category error**, and `intelligent_error` was never set. Every category now follows one error policy: record `<category>_error`, keep last-good data, retry next interval. No permanent disable.
94
+ - **Slow polls could overlap a tick** — added an in-flight guard around the scheduler.
95
+
96
+ ### Changed (internal architecture; no HA-side breakage)
97
+ - Every category exposes `async poll(token) → partialPayload`. Simple categories use a `simplePoll` factory; the intelligent poll is a bespoke category that owns both the devices and dispatch queries.
98
+ - Tick / poll / error-merge logic moved into `lib/poll-tick.js` and `lib/scheduler.js` for unit-test coverage.
99
+ - Manual refresh, MQTT refresh, and post-mutation validation re-polls all go through the same scheduler / intelligent-poll path.
100
+
101
+ ### Unchanged
102
+ - All payload field names, MQTT topics, `unique_id`s, HA entity IDs, input commands, and node config fields.
103
+
104
+ ## [1.3.3] — 2026-05-22
105
+
106
+ ### Fixed
107
+ - **Saving Sessions card showed a 2-year-old session as "next"** — the category was emitting `events[0]` with no filter/sort, so stale historical events surfaced in `saving_session_start/end` and `saving_session_available` was effectively true forever. Now matches the `free-electricity` pattern: filter out ended events, sort earliest-first, take the first. `saving_session_available` now means "an upcoming session exists" as originally intended.
108
+ - **Octoplus "Enrolled" and "Loyalty points user" stuck at "unavailable"** — both binary sensors were published with `entity_category: config`, which makes read-only sensor state stick at "unavailable" on some HA installs. Removed — same fix as the v1.3.0 tariff-sensor cleanup. Entity IDs are unchanged; not a breaking change.
109
+ - **Example dashboard — Wheel of Fortune cards showed "Entity not found"** — `examples/ha-dashboard.yaml` referenced `..._wheel_of_fortune_*_spins`, but the entities are named "WoF …" so HA generates `..._wof_*_spins`. Corrected.
110
+ - **Example dashboard — Home Mini gauge showed "Entity is non-numeric"** on accounts with no Home Mini — the gauge is now wrapped in a conditional card that hides until the entity reports a value.
111
+
112
+ ### Added
113
+ - `saving_session_window_active` (binary sensor) — true when an upcoming session window is currently happening, regardless of whether you joined.
114
+ - `saving_session_active` (binary sensor) — true only when you have joined the current session AND we are inside its window. Use this to drive automations that should only run when there is a payoff.
115
+
116
+ ### Changed (HA-side breaking)
117
+ - `saving_session_joined` now publishes as `binary_sensor` instead of `sensor` — fixes the "False" display anomaly caused by HA's sensor domain rejecting raw booleans. **Update automations and dashboards referencing `sensor.saving_session_joined` to use `binary_sensor.saving_session_joined`.** Payload field name (`msg.payload.saving_session_joined`) is unchanged. Mirror of the v1.3.0 `octoplus_enrolled` migration. The plugin publishes an empty config to the old `sensor/.../config` topic on startup to clean the orphan from HA.
118
+
119
+ ## [1.3.2] — 2026-05-14
120
+
121
+ Defensive hardening pass following the v1.3.1 hotfix audit. No user-facing behaviour change against the current live Kraken API — every affected field already arrives as a JSON number today. The fix forecloses the same latent crash class (`TypeError: ...toFixed is not a function`) if Kraken ever serialises these scalars as strings, matching how `energyAddedKwh` is already returned.
122
+
123
+ ### Fixed
124
+ - `lib/categories/electricity.js` — `tariff.unitRate` and `tariff.standingCharge` (both import and export branches) now coerce via `parseFloat()` before emitting. Prevents string passthrough that would (a) break `device_class: monetary` sensors in HA and (b) crash any downstream arithmetic.
125
+ - `lib/categories/gas.js` — same treatment for `tariff.unitRate` and `tariff.standingCharge`.
126
+ - `lib/categories/account.js` — `balance` (pence) now coerces via `parseFloat()` before emitting `account_balance_pence`. JavaScript's `/` operator was already coercing for `account_balance_pounds`, so this only tightens type consistency on the integer pence field.
127
+
128
+ ### Tests
129
+ - Added string-input regression tests for each coerced field, asserting `typeof === 'number'`. 4 new tests, 237 total (was 233).
130
+
131
+ ## [1.3.1] — 2026-05-14
132
+
133
+ Critical hotfix for v1.3.0. Users on 1.3.0 should upgrade immediately.
134
+
135
+ ### Fixed
136
+ - **Intelligent category crash on numeric string inputs** — `flexPlannedDispatches.energyAddedKwh` is returned by the live Kraken API as a string. The intelligent category's reduce accumulator concatenated strings instead of summing, then called `.toFixed()` on the resulting string, raising `TypeError: totalEnergy.toFixed is not a function`. Whole intelligent payload section fell back to `defaultData` (null slot times, `total_energy: 0`, `next_kwh: "0"`), which surfaced in Home Assistant as "Error updating entity" for every intelligent sensor. Fixed by coercing `energyAddedKwh` via `parseFloat()` before arithmetic and formatting in `lib/categories/intelligent.js`, matching the pattern already used in `lib/categories/flex-planned-dispatches.js`. Added regression tests covering both positive and negative (export dispatch) string inputs.
137
+ - `next_kwh` now consistently formats with two decimal places (e.g. `"5.50"`, `"15.20"`) per the documented contract in README, HTML help, and `test-mocks.js`. The v1.3.0 path stripped trailing zeros via `String(parseFloat(...))` — that branch is unreachable now because it always crashed before reaching it, but the format is corrected for completeness.
138
+
139
+ ## [1.3.0] — 2026-05-12
140
+
141
+ Major additive release covering the full Octopus Energy consumer read surface. No breaking changes to v1.2.x payload fields, entity IDs, MQTT topics, input commands, or node config fields. All v1.2.x automations and dashboards continue to work unchanged.
142
+
143
+ ### Added — Electricity (import)
144
+ - `electricity_standing_charge` — daily standing charge (p/day)
145
+ - `electricity_unit_rate` — fixed unit rate (p/kWh); `null` on half-hourly tariffs
146
+ - `electricity_tariff_code`, `electricity_valid_from`, `electricity_valid_to`
147
+ - `electricity_consumption_kwh` — previous day import consumption
148
+ - `electricity_consumption_from`, `electricity_consumption_to` — period boundaries
149
+ - `applicable_rates`, `applicable_rates_count` — full 48-slot half-hourly schedule
150
+ - `applicable_rates_current_pence`, `applicable_rates_current_gbp` — live rate (use these on half-hourly tariffs)
151
+ - `applicable_rates_prev_pence/_gbp/_to`, `applicable_rates_next_pence/_gbp/_from` — adjacent slot rates and transition timestamps (payload-only; not currently exposed as MQTT entities — see README)
152
+
153
+ ### Added — Electricity (export)
154
+ - `electricity_export_standing_charge` — typically `0` for Agile Outgoing
155
+ - `electricity_export_unit_rate` — fixed; `null` on half-hourly export tariffs
156
+ - `electricity_export_tariff_code` (e.g. `AGILE-OUTGOING-19-05-13`), `electricity_export_valid_from`, `electricity_export_valid_to`
157
+ - `electricity_export_consumption_kwh`, `_from`, `_to` — previous day export from the export meter
158
+ - `electricity_export_rate`, `electricity_export_rate_count` — full 48-slot half-hourly export schedule
159
+ - `electricity_export_rate_current_pence/_gbp` — live export rate
160
+ - `electricity_export_rate_prev_pence/_to`, `electricity_export_rate_next_pence/_from` — adjacent export slot rates
161
+
162
+ ### Added — Gas
163
+ - `gas_standing_charge`, `gas_unit_rate`, `gas_tariff_code`, `gas_valid_from`, `gas_valid_to`
164
+ - `gas_consumption_kwh`, `gas_consumption_from`, `gas_consumption_to`
165
+
166
+ ### Added — Home Mini
167
+ - `mini_demand_kw` (kW, numeric) — real-time grid demand
168
+ - `mini_consumption_delta_kwh` (kWh, numeric) — half-hour period consumption
169
+ - `mini_read_at` — timestamp of most recent telemetry
170
+ - Opt-in via "Enable Home Mini" checkbox in node config
171
+
172
+ ### Added — Rewards
173
+ - `saving_session_available` (binary), `saving_session_start`, `saving_session_end`, `saving_session_joined`
174
+ - `free_electricity_active` (binary), `free_electricity_available` (binary), `free_electricity_start`, `free_electricity_end`
175
+ - `wheel_of_fortune_electricity_spins`, `wheel_of_fortune_gas_spins` — opt-in via node config checkbox
176
+ - `octoplus_enrolled` (binary sensor), `octoplus_enrollment_status` (string), `octoplus_loyalty_points_user` (binary sensor)
177
+
178
+ ### Added — Account & dispatches
179
+ - `account_balance_pounds`, `account_balance_pence`
180
+ - `completed_dispatches` (array), `completed_dispatches_count` — completed intelligent dispatch history
181
+ - `flex_planned_dispatches` (array), `flex_planned_dispatches_count` — upcoming flex dispatches (replaces deprecated `plannedDispatches`)
182
+
183
+ ### Added — Infrastructure
184
+ - **Account discovery** — automatic product detection at startup; categories auto-enable based on registered products and discover both import and export meter points by `direction`, not array position
185
+ - **Per-category poll intervals** — configurable in node editor for each data source
186
+ - **1-second clock-aligned category scheduler** — independent polling; one slow category doesn't block others
187
+
188
+ ### Changed
189
+ - **Octopus `wheelOfFortuneSpins` migrated to `wheelOfFortuneSpinsAllowed`** on `api.backend.octopus.energy` — the old field was deprecated and scheduled for removal 2026-04-20
190
+ - **Octopus `savingSessions` migrated to `api.backend.octopus.energy`** endpoint — the field was removed from the main endpoint
191
+ - **`octoplus_enrolled` and `octoplus_loyalty_points_user` now publish as `binary_sensor` instead of `sensor`** — these are boolean values and HA's sensor domain rejects raw booleans. **HA-side breaking change for users referencing the old `sensor.*` entity IDs**: update automations and dashboards to use `binary_sensor.*`. Payload field names (`msg.payload.octoplus_enrolled`, `msg.payload.octoplus_loyalty_points_user`) are unchanged.
192
+ - **`entity_category: config` removed** from read-only tariff/validity sensors (`electricity_unit_rate`, `electricity_tariff_code`, `electricity_valid_from/to`, `gas_*`, `electricity_export_*`, `saving_session_start/end`, `free_electricity_start/end`, `octoplus_enrollment_status`). These now appear in the main device entity list rather than a separate Configuration section. HA's `entity_category: config` is intended for user-configurable entities (switches, numbers, selects) — applying it to read-only sensors caused state to stick at "unavailable" on some installs.
193
+
194
+ ### Fixed
195
+ - **Import/export meter point selection** — discovery now selects meter points by the `direction` field (`IMPORT` or `EXPORT`), not array position. Earlier dev builds on accounts with both meters could surface export data as import (live "current rate" showing the export Agile rate instead of the import tariff). No stable v1.x release was affected; caught and fixed before v1.3.0 ship.
196
+ - **MQTT transport headers** — `lib/graphql.js` now sends `User-Agent: node-red-contrib-octopus-intelligent/<version>` on every request. Without it, `api.backend.octopus.energy` returns 403 at the edge — which previously surfaced as "WoF returns HTML" and silently broken saving sessions.
197
+ - **MQTT auth format** — uses raw JWT in the Authorization header (no `JWT ` prefix). Main endpoint accepts both; backend endpoint sub-resolvers require the raw form.
198
+ - **Saving sessions schema migration** — removed deprecated `octopoints` field from `SavingSessionsAccountType` query (Octopus moved loyalty points to the Octoplus query).
199
+ - **Gas tariff query fragments** — `GasTariffType` is an object type, not a union — removed inline fragments that caused "Fragment cannot be spread here" errors.
200
+
201
+ ### Unchanged (no breaking changes)
202
+ - All v1.2.x payload field names in `msg.payload`
203
+ - All v1.2.x MQTT topics, `unique_id` values, and HA entity IDs (except the Octoplus domain change noted above)
204
+ - All v1.2.x input commands: `set_limit`, `set_time`, `set_smart_charging`, `set_timezone`
205
+ - All v1.2.x node config fields: `accountNumber`, `apiKey`, `broker`, `enableMqtt`, `name`, `refreshInterval`, `timezoneOverride`
206
+ - Intelligent Octopus Go charging schedule, smart charging toggle, charging preferences
207
+
208
+ ---
209
+
210
+ ## [1.2.1] — 2026-04-29
211
+
212
+ ### Fixed
213
+ - **Deprecated API migration** — moved smart-charging verification from the deprecated `registeredKrakenflexDevice` query to the current `devices` query
214
+ - **Mutation migration** — `setVehicleChargePreferences` (deprecated) replaced with `setDevicePreferences` using the 7-day schedule input
215
+ - **Startup device fetch** — uses the current `devices` query instead of deprecated `registeredKrakenflexDevice`
216
+
217
+ ### Unchanged
218
+ - All v1.2.0 payload fields, MQTT topics, and entity IDs preserved
219
+
220
+ ---
221
+
222
+ ## [1.2.0] - 2026-04-26
223
+
224
+ ### Added
225
+ - **Smart Charging Toggle** — suspend or unsuspend Octopus intelligent charging from Node-RED or Home Assistant
226
+ - `msg.payload = { set_smart_charging: true }` — enable (unsuspend)
227
+ - `msg.payload = { set_smart_charging: false }` — disable (suspend)
228
+ - **HA MQTT Switch** — "Smart Charging" switch entity in Home Assistant (auto-discovered)
229
+ - **`smart_charging` payload field** — `true` = active, `false` = suspended, `null` = unknown (startup fetch pending or failed)
230
+ - **Device ID startup fetch** — `krakenflexDeviceId` fetched once at startup via `registeredKrakenflexDevice` query; cached permanently
231
+
232
+ ### Technical
233
+ - Mirrors `setPreferences` pattern: auth → mutation → optimistic update → exponential backoff verification (15s/30s/60s/120s)
234
+ - Verification re-fetches `registeredKrakenflexDevice.suspended` to confirm state change
235
+ - Zero new npm dependencies
236
+
237
+ ---
238
+
239
+ ## [1.1.1] - 2026-04-26
240
+
241
+ ### Security
242
+ - **Removed `axios` dependency** — replaced with Node.js built-in `https` module; eliminates 13 transitive packages and all associated supply chain risk
243
+ - **Removed test/mock files from npm package** — `__tests__/` and `test-mocks.js` no longer published; removes 139 kB of dev artefacts from end-user installs
244
+ - **Removed images from npm package** — 364 kB of images no longer bundled; README images now reference GitHub raw URLs and render correctly on npmjs.com
245
+
246
+ ### Changed
247
+ - Package size reduced from 369 kB → 27 kB (93% reduction)
248
+ - Zero production dependencies (was: `axios ^1.6.0`)
249
+
250
+ ---
251
+
252
+ ## [1.1.0] - 2026-04-24
253
+
254
+ ### Added
255
+ - **Locale Timestamps** — new `*_locale` fields in every payload, always in server auto-detected timezone
256
+ - `slot1_start_locale`, `slot1_end_locale`, `slot2_start_locale`, `slot2_end_locale`
257
+ - `slot3_start_locale`, `slot3_end_locale`, `window_start_locale`, `window_end_locale`
258
+ - `next_start_locale`
259
+ - **Timezone Metadata** — `timezone_detected` (server auto-detect) and `timezone_applied` (active TZ for display fields)
260
+ - **HA Timezone Select Entity** — `select.octopus_timezone` with 15 curated IANA timezones covering all Octopus operating countries (UK, AU, DE, ES, NZ, US)
261
+ - Selection persists across Node-RED restarts via node context storage
262
+ - State republished to HA on Node-RED startup
263
+ - **`set_timezone` Input Command** — `msg.payload = { set_timezone: "Europe/London" }`, same pattern as `set_limit`/`set_time`
264
+ - **`timezoneOverride` Node Config Field** — optional IANA timezone in node editor, leave blank for auto-detect
265
+ - **Timezone Diagnostic Sensors** — `sensor.octopus_timezone_detected` and `sensor.octopus_timezone_applied`
266
+
267
+ ### Changed
268
+ - **Display timestamp fields now output resolved timezone** instead of raw UTC
269
+ - Affected fields: `slot1_start`, `slot1_end`, `slot2_start`, `slot2_end`, `slot3_start`, `slot3_end`, `window_start`, `window_end`, `next_start`
270
+ - Resolution order: HA-persisted selection → `timezoneOverride` config → server auto-detected
271
+ - **Raw fields (`*_raw`) remain unchanged** — always exact UTC strings from the API
272
+
273
+ ### Technical
274
+ - Zero new npm dependencies — native `Intl.DateTimeFormat` API (Node 14 compatible)
275
+ - `convertToTimezone(dateStr, tz)` — handles DST correctly, falls back to original string on error
276
+ - `resolveTimezone(node)` — reads node context storage, config field, or server auto-detect
277
+
278
+ ## [1.0.5] - 2025-12-31
279
+
280
+ ### Fixed
281
+ - **README Documentation** - Removed misleading "Octopus Energy branded device cards" claim
282
+ - Changed to accurate description: "Clean Organization" and "Professional Layout"
283
+ - No actual Octopus Energy branding exists in Home Assistant device cards
284
+ - Avoids potential trademark/copyright concerns
285
+
286
+ ## [1.0.4] - 2025-12-11
287
+
288
+ ### Added
289
+ - **Manual Refresh Button (MQTT)** - "Octopus Refresh API" button in Home Assistant
290
+ - Hardcoded 30-second rate limiting to prevent API spam
291
+ - Shows warning in Node-RED when rate limited
292
+ - Publishes refresh cooldown state to MQTT
293
+ - **Refresh Available At Sensor** - Diagnostic timestamp sensor
294
+ - Shows ISO timestamp when manual refresh becomes available
295
+ - Displays as countdown in Home Assistant ("in 25 seconds")
296
+ - Automatically clears to `null` after 30 seconds
297
+ - Leverages Home Assistant's native timestamp handling
298
+ - **Next Poll Time Sensors** - Shows when next automatic poll will occur
299
+ - `sensor.octopus_next_poll_time` - Main sensor (timestamp class)
300
+ - `sensor.octopus_next_poll_time_raw` - Diagnostic raw timestamp
301
+ - Updates after each successful poll
302
+ - **API Complexity Tracking** - Monitor API usage against 50,000 hourly limit
303
+ - `sensor.octopus_api_requests_hour` - Count of requests (last 60 min)
304
+ - `sensor.octopus_api_complexity_hour` - Total complexity used
305
+ - `sensor.octopus_api_complexity_usage` - Percentage of limit used
306
+ - Estimated complexity: Regular poll (300), Mutation (250), Pre-validation (200)
307
+ - All API complexity sensors in Diagnostics section
308
+ - **Enhanced Debug Output** - `msg.debug` now includes:
309
+ - `responseHeaders` - Full HTTP response headers from API
310
+ - `extensions` - GraphQL extensions field (if present)
311
+ - `api_usage` - Comprehensive API usage metrics per request
312
+ - **Comprehensive Test Coverage** - Added 5 new tests
313
+ - Tests for MQTT refresh button rate limiting
314
+ - Tests for countdown expiry behavior
315
+ - Validates countdown doesn't go negative
316
+ - Tests timer cleanup and MQTT message structure
317
+
318
+ ### Changed
319
+ - **Rate Limiting Strategy** - Different behavior for MQTT vs Node-RED
320
+ - MQTT Button: Hardcoded 30-second cooldown (enforced)
321
+ - Node-RED Input: No rate limiting (programmers control this)
322
+ - Timestamp-based cooldown (not seconds counter)
323
+ - **State Output** - Node-RED now outputs state on every poll
324
+ - Previously only output on changes
325
+ - Now outputs full `statusPayload` every poll cycle
326
+ - Better for automations and monitoring
327
+ - **Global Setter** - Updated `NodeRed_Global_Setter.js` with new fields:
328
+ - `octopus_next_poll`
329
+ - `octopus_refresh_available_at`
330
+ - `octopus_api_requests_hour`
331
+ - `octopus_api_complexity_hour`
332
+ - `octopus_api_complexity_percent`
333
+
334
+ ### Fixed
335
+ - **Cooldown Timer Expiry** - Properly publishes `null` at 30 seconds
336
+ - Prevents countdown showing negative values in Home Assistant
337
+ - Timer cleanup prevents memory leaks
338
+ - Exactly 2 MQTT messages per refresh (start + expiry)
339
+
340
+ ### Technical Details
341
+ - **API Complexity Estimation** - Since Octopus API doesn't provide actual complexity:
342
+ - Uses estimated values based on query types
343
+ - Tracks rolling 60-minute window
344
+ - If actual complexity becomes available, will use it automatically
345
+ - **Timestamp-Based Cooldown** - Uses ISO timestamps instead of seconds
346
+ - Home Assistant handles countdown display automatically
347
+ - Zero MQTT spam during countdown
348
+ - Clean `null` state when ready
349
+
350
+ ## [1.0.3] - 2025-12-04
351
+
352
+ ### Added
353
+ - **State reconciliation loop** for charging detection (every 10 seconds)
354
+ - Automatically detects charging state based on cached slot timestamps
355
+ - No API calls - uses local data only
356
+ - Handles imminent/immediate slots when car is plugged in
357
+ - Self-healing: corrects state if timers miss edge cases
358
+ - **Flow Library scorecard compliance**
359
+ - Added `version` field to `node-red` section in package.json (>=2.0.0)
360
+ - Added `examples/` folder with 3 demonstration flows
361
+ - Satisfies Node-RED Flow Library requirements
362
+
363
+ ### Fixed
364
+ - **Home Assistant sensors going "unknown"** when adjusting controls
365
+ - Sensors now maintain last known values while editing pending preferences
366
+ - Only update when fresh data arrives from API
367
+ - Added `lastKnownState` cache and state merging in `publishCurrentState()`
368
+ - **Charging state not updating** for imminent/immediate slots
369
+ - Fixed edge case where slots starting <30s after poll were not detected
370
+ - Reconciliation loop catches these within 10 seconds
371
+ - Ensures accurate "Charging Now" sensor in Home Assistant
372
+
373
+ ### Changed
374
+ - Improved charging state management with redundant detection methods
375
+ - Enhanced MQTT state publishing to preserve sensor data during control updates
376
+
377
+ ## [1.0.2] - 2025-11-30
378
+
379
+ ### Changed
380
+ - Updated flow example description in Node-RED help panel for better clarity
381
+ - Improved explanation of default behavior: reads by default, manually refreshable, and accepts commands
382
+
383
+ ## [1.0.1] - 2025-11-30
384
+
385
+ ### Added
386
+ - **Node.js and Node-RED version requirements** in package.json engines field
387
+ - Minimum Node.js: >=14.0.0
388
+ - Minimum Node-RED: >=2.0.0
389
+ - Addresses Flow Library scorecard requirements
390
+ - **Comprehensive example flows** in Node-RED help panel
391
+ - Basic monitoring flow (inject every 5 min)
392
+ - Set preferences from flow (JSON payload with set_limit/set_time)
393
+ - Home Assistant MQTT integration example
394
+ - **Visual documentation** with screenshots
395
+ - Node-RED flow examples showing monitoring, preferences, and preset buttons
396
+ - MQTT integration flow example
397
+ - Home Assistant device page with all entities
398
+ - **Visual Examples section** in Node-RED help panel with embedded GitHub-hosted images
399
+ - **Screenshots section** in README.md showing real-world usage
400
+
401
+ ### Changed
402
+ - Updated README.md with Screenshots section after Features
403
+ - Updated .npmignore to exclude images/ folder (keeps npm package lightweight)
404
+ - Updated .gitignore to exclude local documentation files
405
+
406
+ ### Fixed
407
+ - Flow Library scorecard now shows supported Node-RED and Node.js versions
408
+ - Flow Library scorecard "Nodes have examples" requirement now satisfied
409
+
410
+ ## [1.0.0] - 2025-11-30
411
+
412
+ ### Added
413
+ - Initial public release
414
+ - **Octopus Energy GraphQL API integration**
415
+ - Authentication via API key
416
+ - Fetch planned charging dispatches (smart-charge and bump-charge slots)
417
+ - Query vehicle charging preferences (target SOC and ready time)
418
+ - Update charging preferences via GraphQL mutations
419
+ - **Home Assistant MQTT auto-discovery**
420
+ - Number entity: Target charge limit (50-100%)
421
+ - Select entity: Ready time (04:00-11:00)
422
+ - Button entity: Apply changes
423
+ - Sensor entities: Confirmed settings, next charge time, total energy, slot times
424
+ - Binary sensor: Charging now (ON/OFF)
425
+ - Organized into Controls, Sensors, and Diagnostics categories
426
+ - **Real-time charging slot detection**
427
+ - Detects currently active charging slots
428
+ - Calculates next charging start time
429
+ - Provides individual slot start/end times (up to 3 slots)
430
+ - Calculates overall charging window
431
+ - Shows charge source (smart-charge vs bump-charge)
432
+ - **Exponential backoff validation**
433
+ - Smart retry mechanism when updating preferences
434
+ - Prevents sensors from becoming "unavailable" during API updates
435
+ - Validates changes at 15s, 30s, 60s, 120s intervals
436
+ - **Comprehensive debugging**
437
+ - Full API call tracking in msg.debug
438
+ - Success/failure status for each operation
439
+ - Detailed error messages
440
+ - **Node-RED flow control**
441
+ - Accept input messages to set preferences programmatically
442
+ - Output payload with all charging data
443
+ - 5-minute default refresh interval (configurable)
444
+ - **Octopus Energy branding**
445
+ - Professional pink theme (#E8146F)
446
+ - Device branded as "Octopus Intelligent" in Home Assistant
447
+ - Suggested "Energy" area in Home Assistant
448
+ - **Unit test coverage**
449
+ - Data processing tests (10 tests)
450
+ - Timer management tests (10 tests)
451
+ - Mock API responses for consistent testing
452
+
453
+ ### Security
454
+ - API key stored securely as Node-RED credential (not exposed in flows)
455
+ - Account numbers sanitized in MQTT topics and entity IDs
456
+
457
+ ### Documentation
458
+ - Comprehensive README.md with:
459
+ - Feature list and capabilities
460
+ - Installation instructions (npm and palette manager)
461
+ - Configuration guide
462
+ - Home Assistant setup instructions
463
+ - Node-RED usage examples
464
+ - Home Assistant automation examples
465
+ - Troubleshooting section
466
+ - Support options (GitHub Star, Sponsor, PayPal donate)
467
+ - MIT License
468
+ - GitHub repository with issue tracking
469
+
470
+ ## Release Notes
471
+
472
+ ### Version Numbering
473
+ This project follows [Semantic Versioning](https://semver.org/):
474
+ - **MAJOR** version (X.0.0): Breaking changes
475
+ - **MINOR** version (1.X.0): New features (backwards compatible)
476
+ - **PATCH** version (1.0.X): Bug fixes (backwards compatible)
477
+
478
+ ### Links
479
+ - [npm Package](https://www.npmjs.com/package/node-red-contrib-octopus-intelligent)
480
+ - [GitHub Repository](https://github.com/ASomerN/node-red-contrib-octopus-intelligent)
481
+ - [Node-RED Flow Library](https://flows.nodered.org/node/node-red-contrib-octopus-intelligent)
482
+ - [Issues & Bug Reports](https://github.com/ASomerN/node-red-contrib-octopus-intelligent/issues)
483
+
484
+ ### Support
485
+ - ⭐ [Star on GitHub](https://github.com/ASomerN/node-red-contrib-octopus-intelligent)
486
+ - 💖 [Become a Sponsor](https://github.com/sponsors/ASomerN)
487
+ - ☕ [Donate via PayPal](https://www.paypal.com/donate?hosted_button_id=A2B8ZFEJBE2S6)