node-red-contrib-octopus-intelligent 1.6.1 → 1.7.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 (45) hide show
  1. package/CHANGELOG.md +135 -19
  2. package/README.md +386 -156
  3. package/examples/basic-monitoring.json +1 -1
  4. package/examples/boost-on-cheap-or-surplus.json +171 -0
  5. package/examples/charging-and-error-alerts.json +95 -0
  6. package/examples/cheapest-window-planner.json +165 -0
  7. package/examples/daily-charging-summary.json +165 -0
  8. package/examples/ha-dashboard.yaml +67 -2
  9. package/examples/mqtt-integration.json +1 -1
  10. package/examples/node-red-dashboard-flow.json +92 -2
  11. package/examples/set-preferences.json +1 -1
  12. package/lib/active-now.js +33 -0
  13. package/lib/auth.js +6 -1
  14. package/lib/boost.js +85 -0
  15. package/lib/categories/account.js +3 -3
  16. package/lib/categories/applicable-rates.js +29 -19
  17. package/lib/categories/completed-dispatches.js +2 -1
  18. package/lib/categories/electricity.js +23 -13
  19. package/lib/categories/flex-planned-dispatches.js +2 -2
  20. package/lib/categories/free-electricity.js +13 -1
  21. package/lib/categories/gas.js +13 -6
  22. package/lib/categories/home-mini.js +11 -3
  23. package/lib/categories/intelligent.js +87 -21
  24. package/lib/categories/octoplus.js +6 -3
  25. package/lib/categories/saving-sessions.js +15 -1
  26. package/lib/categories/smartflex-inverter.js +95 -0
  27. package/lib/categories/smartflex-vehicle.js +198 -0
  28. package/lib/categories/wheel-of-fortune.js +3 -2
  29. package/lib/commands.js +25 -3
  30. package/lib/discovery-retry.js +4 -1
  31. package/lib/discovery.js +71 -9
  32. package/lib/graphql-errors.js +160 -4
  33. package/lib/graphql.js +113 -8
  34. package/lib/http-get-json.js +64 -6
  35. package/lib/payload.js +15 -0
  36. package/lib/poll-retry.js +71 -0
  37. package/lib/poll-tick.js +88 -20
  38. package/lib/preferences.js +4 -2
  39. package/lib/scheduler.js +46 -8
  40. package/lib/sensor-definitions.js +51 -1
  41. package/lib/timezone.js +19 -1
  42. package/lib/values.js +47 -0
  43. package/octopus-intelligent.html +74 -34
  44. package/octopus-intelligent.js +1384 -250
  45. package/package.json +1 -1
@@ -4,16 +4,20 @@ path: octopus-intelligent
4
4
  icon: mdi:lightning-bolt
5
5
  max_columns: 4
6
6
  # ────────────────────────────────────────────────────────────────────────────────
7
- # Octopus Intelligent — comprehensive v1.6.1 dashboard
7
+ # Octopus Intelligent — comprehensive v1.7.0 dashboard
8
8
  #
9
9
  # Each section is a single focused card so the sections view packs them into a
10
10
  # uniform grid without big empty gaps. On wide screens HA renders up to 4
11
11
  # columns; narrower viewports collapse to fewer columns automatically.
12
12
  #
13
- # Covers every MQTT entity published by node-red-contrib-octopus-intelligent
13
+ # Covers all controls, live values, and error state binary sensors published by node-red-contrib-octopus-intelligent
14
14
  # v1.6.1 (adds the Charge Cap switch and 48 ready-by times over v1.5.0, which
15
15
  # added tariff rate bands, 24h schedule stats, the Update entity, and
16
16
  # per-category error binary_sensors over the v1.3.0 baseline).
17
+ # v1.7.0 adds the Boost Charge switch and SmartFlex vehicle cards. The vehicle
18
+ # cards hide on accounts where Octopus does not control a car or charge point.
19
+ # The experimental inverter entities are not shown here.
20
+ # A few diagnostic sensors are left out. See the README for the full entity list.
17
21
  # Fresh install entity-id prefix: octopus_intelligent_octopus_*.
18
22
  # Upgraders from pre-v1.0 may have node_red_octopus_intelligent_octopus_*
19
23
  # on carry-over entities (see Dev Tools → States to look up the actual ID).
@@ -38,6 +42,8 @@ sections:
38
42
  name: Smart Charging
39
43
  - entity: switch.octopus_intelligent_charge_cap
40
44
  name: Charge Cap
45
+ - entity: switch.octopus_intelligent_boost_charge
46
+ name: Boost Charge
41
47
  - entity: button.octopus_intelligent_octopus_refresh_api
42
48
  name: Refresh API
43
49
 
@@ -102,6 +108,63 @@ sections:
102
108
  - entity: sensor.octopus_intelligent_octopus_completed_dispatches
103
109
  name: Completed (12h)
104
110
 
111
+ # SmartFlex vehicle cards (v1.7.0). Hidden until the node has read a vehicle
112
+ # make, so accounts without a SmartFlex car or charge point do not see them.
113
+ - type: grid
114
+ cards:
115
+ - type: conditional
116
+ conditions:
117
+ - condition: state
118
+ entity: sensor.octopus_intelligent_octopus_vehicle_make
119
+ state_not: unavailable
120
+ - condition: state
121
+ entity: sensor.octopus_intelligent_octopus_vehicle_make
122
+ state_not: unknown
123
+ - condition: state
124
+ entity: sensor.octopus_intelligent_octopus_vehicle_make
125
+ state_not: "None"
126
+ card:
127
+ type: entities
128
+ title: EV vehicle
129
+ icon: mdi:car-info
130
+ entities:
131
+ - entity: sensor.octopus_intelligent_octopus_vehicle_make
132
+ name: Make
133
+ - entity: sensor.octopus_intelligent_octopus_vehicle_model
134
+ name: Model
135
+ - entity: sensor.octopus_intelligent_octopus_vehicle_battery_size
136
+ name: Battery size
137
+ - entity: sensor.octopus_intelligent_octopus_charger_power
138
+ name: Charger power
139
+ - entity: sensor.octopus_intelligent_octopus_vehicle_device_state
140
+ name: Device state
141
+
142
+ - type: grid
143
+ cards:
144
+ # The session list and device alerts are attributes of Last Charge Session Energy.
145
+ - type: conditional
146
+ conditions:
147
+ - condition: state
148
+ entity: sensor.octopus_intelligent_octopus_vehicle_make
149
+ state_not: unavailable
150
+ - condition: state
151
+ entity: sensor.octopus_intelligent_octopus_vehicle_make
152
+ state_not: unknown
153
+ - condition: state
154
+ entity: sensor.octopus_intelligent_octopus_vehicle_make
155
+ state_not: "None"
156
+ card:
157
+ type: entities
158
+ title: EV last session
159
+ icon: mdi:ev-station
160
+ entities:
161
+ - entity: sensor.octopus_intelligent_octopus_last_charge_session_energy
162
+ name: Energy added
163
+ - entity: sensor.octopus_intelligent_octopus_last_charge_session_final_charge
164
+ name: Final charge
165
+ - entity: binary_sensor.octopus_intelligent_octopus_last_charge_session_problem
166
+ name: Problem
167
+
105
168
  # ════════════════════════════════════════════════════════════════════════════
106
169
  # Electricity — import
107
170
  # ════════════════════════════════════════════════════════════════════════════
@@ -586,6 +649,8 @@ sections:
586
649
  name: Completed dispatches
587
650
  - entity: binary_sensor.octopus_intelligent_octopus_flex_planned_dispatches_error_state
588
651
  name: Flex planned dispatches
652
+ - entity: binary_sensor.octopus_intelligent_octopus_smartflex_vehicle_error_state
653
+ name: SmartFlex vehicle
589
654
 
590
655
  - type: grid
591
656
  cards:
@@ -1 +1 @@
1
- [{"id":"1","type":"inject","name":"Every 5 min","props":[{"p":"payload"}],"repeat":"300","crontab":"","once":true,"topic":"","payload":"","payloadType":"date","x":130,"y":200,"wires":[["2"]]},{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":true,"broker":"mqtt-broker","x":340,"y":200,"wires":[["3"]]},{"id":"3","type":"debug","name":"Debug Output","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":570,"y":200,"wires":[]},{"id":"mqtt-broker","type":"mqtt-broker","name":"Home Assistant MQTT","broker":"localhost","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"autoUnsubscribe":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""}]
1
+ [{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":true,"broker":"mqtt-broker","x":340,"y":200,"wires":[["3"]]},{"id":"3","type":"debug","name":"Debug Output","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":570,"y":200,"wires":[]},{"id":"mqtt-broker","type":"mqtt-broker","name":"Home Assistant MQTT","broker":"localhost","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"autoUnsubscribe":true,"birthTopic":"","birthQos":"0","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""}]
@@ -153,6 +153,19 @@
153
153
  "visible": true,
154
154
  "disabled": false
155
155
  },
156
+ {
157
+ "id": "ui-group-status-vehicle",
158
+ "type": "ui-group",
159
+ "name": "Vehicle",
160
+ "page": "ui-page-status",
161
+ "width": "6",
162
+ "height": "1",
163
+ "order": 3,
164
+ "showTitle": true,
165
+ "className": "",
166
+ "visible": true,
167
+ "disabled": false
168
+ },
156
169
  {
157
170
  "id": "ui-group-tariff-current",
158
171
  "type": "ui-group",
@@ -306,6 +319,7 @@
306
319
  [
307
320
  "fn-controls-status",
308
321
  "fn-controls-charge-cap-state",
322
+ "fn-controls-boost-state",
309
323
  "widget-status-charging-now",
310
324
  "widget-status-source",
311
325
  "widget-status-confirmed-limit",
@@ -318,6 +332,7 @@
318
332
  "widget-tariff-bands-template",
319
333
  "widget-opt-schedule-template",
320
334
  "widget-status-slots-template",
335
+ "widget-status-vehicle-template",
321
336
  "widget-account-balance",
322
337
  "widget-account-octoplus",
323
338
  "widget-account-saving-session",
@@ -339,7 +354,7 @@
339
354
  "type": "function",
340
355
  "name": "Extract current confirmed settings for Controls page",
341
356
  "z": "tab-octopus-main",
342
- "func": "// Provides a status summary text for the Controls page.\nmsg.payload = [\n 'Confirmed limit: ' + (msg.payload.confirmed_limit || '--') + '%',\n 'Confirmed time: ' + (msg.payload.confirmed_time || '--'),\n 'Smart charging: ' + (msg.payload.smart_charging ? 'ON' : 'OFF'),\n 'Charging now: ' + (msg.payload.charging_now ? 'YES' : 'NO')\n].join(' | ');\nreturn msg;",
357
+ "func": "// Provides a status summary text for the Controls page.\nmsg.payload = [\n 'Confirmed limit: ' + (msg.payload.confirmed_limit || '--') + '%',\n 'Confirmed time: ' + (msg.payload.confirmed_time || '--'),\n 'Smart charging: ' + (msg.payload.smart_charging ? 'ON' : 'OFF'),\n 'Boost: ' + (msg.payload.boosting ? 'ON' : 'OFF'),\n 'Charging now: ' + (msg.payload.charging_now ? 'YES' : 'NO')\n].join(' | ');\nreturn msg;",
343
358
  "outputs": 1,
344
359
  "noerr": 0,
345
360
  "initialize": "",
@@ -454,6 +469,36 @@
454
469
  "y": 580,
455
470
  "wires": [["widget-controls-charge-cap"]]
456
471
  },
472
+ {
473
+ "id": "fn-apply-boost",
474
+ "type": "function",
475
+ "name": "Wrap Boost Charge toggle as set_boost command",
476
+ "z": "tab-octopus-main",
477
+ "func": "// Receives true/false from the ui-switch and wraps it\n// into the command shape expected by the Octopus Intelligent node.\n// true starts a boost (charge now, outside the plan). false cancels it.\nmsg.payload = { set_boost: msg.payload === true || msg.payload === 'true' };\nreturn msg;",
478
+ "outputs": 1,
479
+ "noerr": 0,
480
+ "initialize": "",
481
+ "finalize": "",
482
+ "libs": [],
483
+ "x": 760,
484
+ "y": 640,
485
+ "wires": [["node-octopus-main"]]
486
+ },
487
+ {
488
+ "id": "fn-controls-boost-state",
489
+ "type": "function",
490
+ "name": "Drive Boost Charge switch from boosting",
491
+ "z": "tab-octopus-main",
492
+ "func": "// Sets the Boost Charge switch from the node's boosting output field.\n// boosting is true/false, or null until the node knows: then nothing\n// is sent and the switch keeps its state.\n// The switch has passthru off, so this never loops back as a command.\nconst v = msg.payload && msg.payload.boosting;\nif (typeof v !== 'boolean') return null;\nreturn { payload: v };",
493
+ "outputs": 1,
494
+ "noerr": 0,
495
+ "initialize": "",
496
+ "finalize": "",
497
+ "libs": [],
498
+ "x": 760,
499
+ "y": 700,
500
+ "wires": [["widget-controls-boost"]]
501
+ },
457
502
  {
458
503
  "id": "fn-apply-timezone",
459
504
  "type": "function",
@@ -625,6 +670,31 @@
625
670
  "y": 400,
626
671
  "wires": [["fn-apply-charge-cap"]]
627
672
  },
673
+ {
674
+ "id": "widget-controls-boost",
675
+ "type": "ui-switch",
676
+ "z": "tab-octopus-main",
677
+ "group": "ui-group-controls-ev",
678
+ "name": "Boost Charge",
679
+ "label": "Boost Charge",
680
+ "tooltip": "Charge now, outside the Octopus plan. Turn off to cancel the boost. Octopus can refuse a boost, for example when the car is unplugged or full.",
681
+ "order": 5,
682
+ "width": "6",
683
+ "height": "1",
684
+ "passthru": false,
685
+ "topic": "set_boost",
686
+ "topicType": "str",
687
+ "stateOn": true,
688
+ "stateOff": false,
689
+ "stateOnLabel": "Boosting",
690
+ "stateOffLabel": "Off",
691
+ "colorOn": "#E65100",
692
+ "colorOff": "#ccc",
693
+ "className": "",
694
+ "x": 1180,
695
+ "y": 460,
696
+ "wires": [["fn-apply-boost"]]
697
+ },
628
698
  {
629
699
  "id": "widget-controls-refresh",
630
700
  "type": "ui-button",
@@ -812,6 +882,26 @@
812
882
  "y": 1000,
813
883
  "wires": [[]]
814
884
  },
885
+ {
886
+ "id": "widget-status-vehicle-template",
887
+ "type": "ui-template",
888
+ "z": "tab-octopus-main",
889
+ "group": "ui-group-status-vehicle",
890
+ "name": "SmartFlex Vehicle",
891
+ "order": 1,
892
+ "width": "6",
893
+ "height": "5",
894
+ "className": "",
895
+ "template": "<template>\n <div style=\"font-size:0.9em;\">\n <div v-if=\"!msg.payload.vehicle_make && !msg.payload.device_state\" style=\"color:#888;\">\n No SmartFlex car or charge point found yet. The node reads it every 30 minutes.\n </div>\n <div v-else>\n <div style=\"font-weight:bold;\">{{ msg.payload.vehicle_make || '--' }} {{ msg.payload.vehicle_model || '' }}</div>\n <div>Battery: {{ msg.payload.vehicle_battery_kwh ?? '--' }} kWh | Charger: {{ msg.payload.charger_power_kw ?? '--' }} kW</div>\n <div>Device state: {{ msg.payload.device_state || '--' }}</div>\n <div>Boost: {{ msg.payload.boosting === true ? 'RUNNING' : (msg.payload.boosting === false ? 'Off' : '--') }}</div>\n <div v-if=\"msg.payload.boost_error\" style=\"color:#c62828;\">Last boost failed: {{ msg.payload.boost_error }}</div>\n <div style=\"margin-top:6px;\">\n Last session: {{ msg.payload.last_session_kwh ?? '--' }} kWh added, final charge {{ msg.payload.last_session_soc_final ?? '--' }}%\n <span v-if=\"msg.payload.last_session_problem\" style=\"color:#c62828;\">(problem reported)</span>\n </div>\n <table v-if=\"(msg.payload.charging_sessions || []).length\" style=\"width:100%; border-collapse:collapse; margin-top:6px;\">\n <thead>\n <tr style=\"background:#1565C0; color:#fff;\">\n <th style=\"padding:4px 8px; text-align:left;\">Start</th>\n <th style=\"padding:4px 8px; text-align:left;\">kWh</th>\n <th style=\"padding:4px 8px; text-align:left;\">Final %</th>\n <th style=\"padding:4px 8px; text-align:left;\">Type</th>\n </tr>\n </thead>\n <tbody>\n <tr v-for=\"(s, i) in msg.payload.charging_sessions\" :key=\"i\" :style=\"{ background: i % 2 === 0 ? '#f5f5f5' : '#fff' }\">\n <td style=\"padding:4px 8px;\">{{ s.start ? new Date(s.start).toLocaleString() : '--' }}</td>\n <td style=\"padding:4px 8px;\">{{ s.kwh_added ?? '--' }}</td>\n <td style=\"padding:4px 8px;\">{{ s.soc_final ?? '--' }}</td>\n <td style=\"padding:4px 8px;\">{{ s.type || '--' }}</td>\n </tr>\n </tbody>\n </table>\n <div v-for=\"(a, i) in (msg.payload.device_alerts || [])\" :key=\"'alert-' + i\" style=\"margin-top:4px; color:#E65100;\">\n Alert: {{ a.message }}\n </div>\n <div v-if=\"msg.payload.smartflex_vehicle_error\" style=\"margin-top:4px; color:#c62828;\">\n Error: {{ msg.payload.smartflex_vehicle_error }}\n </div>\n </div>\n </div>\n</template>",
896
+ "storeOutMessages": true,
897
+ "passthru": true,
898
+ "resendOnRefresh": true,
899
+ "templateScope": "local",
900
+ "eventsFromServer": false,
901
+ "x": 970,
902
+ "y": 2260,
903
+ "wires": [[]]
904
+ },
815
905
  {
816
906
  "id": "widget-tariff-import-gauge",
817
907
  "type": "ui-gauge",
@@ -1274,7 +1364,7 @@
1274
1364
  "width": "12",
1275
1365
  "height": "5",
1276
1366
  "className": "",
1277
- "template": "<template>\n <div style=\"font-size:0.85em;\">\n <div style=\"font-weight:bold; margin-bottom:6px;\">Per-Category Errors (null = healthy)</div>\n <table style=\"width:100%; border-collapse:collapse;\">\n <thead>\n <tr style=\"background:#37474F; color:#fff;\">\n <th style=\"padding:4px 8px; text-align:left;\">Category</th>\n <th style=\"padding:4px 8px; text-align:left;\">Status</th>\n </tr>\n </thead>\n <tbody>\n <template v-for=\"(key, i) in [\n 'intelligent_error', 'electricity_tariff_error', 'electricity_consumption_error',\n 'electricity_export_rate_error', 'electricity_export_consumption_error',\n 'gas_tariff_error', 'gas_consumption_error',\n 'account_error', 'octoplus_error', 'saving_sessions_error',\n 'free_electricity_error', 'wheel_of_fortune_error',\n 'home_mini_error', 'update_check_error', 'applicable_rates_error'\n ]\" :key=\"i\">\n <tr v-if=\"msg.payload[key] != null\"\n :style=\"{ background: i % 2 === 0 ? '#fff3f3' : '#ffe0e0' }\">\n <td style=\"padding:4px 8px; font-weight:bold;\">{{ key.replace('_error','') }}</td>\n <td style=\"padding:4px 8px; color:#c62828;\">{{ msg.payload[key] }}</td>\n </tr>\n </template>\n <tr v-if=\"Object.keys(msg.payload).filter(k => k.endsWith('_error') && msg.payload[k] != null).length === 0\">\n <td colspan=\"2\" style=\"padding:10px; text-align:center; color:#00897B; font-weight:bold;\">All categories healthy</td>\n </tr>\n </tbody>\n </table>\n </div>\n</template>",
1367
+ "template": "<template>\n <div style=\"font-size:0.85em;\">\n <div style=\"font-weight:bold; margin-bottom:6px;\">Per-Category Errors (null = healthy)</div>\n <table style=\"width:100%; border-collapse:collapse;\">\n <thead>\n <tr style=\"background:#37474F; color:#fff;\">\n <th style=\"padding:4px 8px; text-align:left;\">Category</th>\n <th style=\"padding:4px 8px; text-align:left;\">Status</th>\n </tr>\n </thead>\n <tbody>\n <template v-for=\"(key, i) in [\n 'intelligent_error', 'electricity_rates_error', 'electricity_consumption_error',\n 'electricity_export_rate_error', 'applicable_rates_error',\n 'gas_rates_error', 'gas_consumption_error',\n 'account_error', 'octoplus_error', 'saving_sessions_error',\n 'free_electricity_error', 'wheel_of_fortune_error',\n 'home_mini_error', 'completed_dispatches_error', 'flex_planned_dispatches_error',\n 'smartflex_vehicle_error', 'smartflex_inverter_error', 'boost_error', 'update_check_error'\n ]\" :key=\"i\">\n <tr v-if=\"msg.payload[key] != null\"\n :style=\"{ background: i % 2 === 0 ? '#fff3f3' : '#ffe0e0' }\">\n <td style=\"padding:4px 8px; font-weight:bold;\">{{ key.replace('_error','') }}</td>\n <td style=\"padding:4px 8px; color:#c62828;\">{{ msg.payload[key] }}</td>\n </tr>\n </template>\n <tr v-if=\"Object.keys(msg.payload).filter(k => k.endsWith('_error') && msg.payload[k] != null).length === 0\">\n <td colspan=\"2\" style=\"padding:10px; text-align:center; color:#00897B; font-weight:bold;\">All categories healthy</td>\n </tr>\n </tbody>\n </table>\n </div>\n</template>",
1278
1368
  "storeOutMessages": true,
1279
1369
  "passthru": true,
1280
1370
  "resendOnRefresh": true,
@@ -1 +1 @@
1
- [{"id":"1","type":"inject","name":"Set 85% by 07:30","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_limit\":85,\"set_time\":\"07:30\"}","payloadType":"json","x":150,"y":140,"wires":[["2"]]},{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":true,"broker":"mqtt-broker","x":380,"y":140,"wires":[["3"]]},{"id":"3","type":"debug","name":"Confirmation","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":610,"y":140,"wires":[]}]
1
+ [{"id":"1","type":"inject","name":"Set 85% by 07:30","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_limit\":85,\"set_time\":\"07:30\"}","payloadType":"json","x":150,"y":140,"wires":[["2"]]},{"id":"4","type":"inject","name":"Boost now","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_boost\":true}","payloadType":"json","x":150,"y":200,"wires":[["2"]]},{"id":"5","type":"inject","name":"Cancel boost","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_boost\":false}","payloadType":"json","x":150,"y":260,"wires":[["2"]]},{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":false,"x":380,"y":140,"wires":[["3"]]},{"id":"3","type":"debug","name":"Confirmation","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":610,"y":140,"wires":[]}]
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+ // "Active now" fields: values that depend on the clock, not only on what Octopus returned.
3
+ // Recomputed from the stored state on the node's 10 s tick, with no API calls.
4
+ const savingSessions = require('./categories/saving-sessions');
5
+ const freeElectricity = require('./categories/free-electricity');
6
+ const applicableRates = require('./categories/applicable-rates');
7
+
8
+ const RATE_PREFIXES = ['applicable_rates', 'electricity_export_rate'];
9
+
10
+ function activeFields(state, nowMs) {
11
+ const out = Object.assign({},
12
+ savingSessions.activeFields(state, nowMs),
13
+ freeElectricity.activeFields(state, nowMs));
14
+ for (const prefix of RATE_PREFIXES) {
15
+ const slots = state[prefix];
16
+ if (Array.isArray(slots) && slots.length > 0) {
17
+ Object.assign(out, applicableRates.currentFields(slots, prefix, nowMs));
18
+ }
19
+ }
20
+ return out;
21
+ }
22
+
23
+ // The recomputed fields whose value differs from `state`, or null when none do.
24
+ function changedActiveFields(state, nowMs) {
25
+ const fresh = activeFields(state, nowMs);
26
+ const changed = {};
27
+ for (const [k, v] of Object.entries(fresh)) {
28
+ if (!Object.is(state[k], v)) changed[k] = v; // Object.is: a NaN rate is not a change
29
+ }
30
+ return Object.keys(changed).length > 0 ? changed : null;
31
+ }
32
+
33
+ module.exports = { activeFields, changedActiveFields };
package/lib/auth.js CHANGED
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
  const { graphqlPost } = require('./graphql');
3
+ const { truncate } = require('./graphql-errors');
4
+
5
+ const MAX_RAW_ERROR_LENGTH = 8192;
3
6
 
4
7
  async function obtainToken(apiKey) {
5
8
  const response = await graphqlPost({
@@ -9,7 +12,9 @@ async function obtainToken(apiKey) {
9
12
  variables: { input: { APIKey: apiKey } }
10
13
  });
11
14
  if (response.data.errors) {
12
- throw new Error(`Auth failed: ${JSON.stringify(response.data.errors)}`);
15
+ // Kraken can echo the APIKey variable in an input error. Shown as it is in Node-RED, so a
16
+ // wrong key can be seen; masked only when published to Home Assistant.
17
+ throw new Error(truncate(`Auth failed: ${JSON.stringify(response.data.errors)}`, MAX_RAW_ERROR_LENGTH));
13
18
  }
14
19
  if (!response.data.data || !response.data.data.obtainKrakenToken) {
15
20
  throw new Error('Auth response missing token data');
package/lib/boost.js ADDED
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+ const { errorCode, truncate } = require('./graphql-errors');
3
+
4
+ // Boost charge: charge now, outside the Octopus plan. Not the same as set_smart_charging,
5
+ // which suspends or resumes Octopus control (updateDeviceSmartControl).
6
+ // Live introspection 6 Oct 2026:
7
+ // updateBoostCharge(input: {deviceId: String!, action: UpdateBoostChargeAction!}) -> SmartFlexDeviceInterface
8
+ // UpdateBoostChargeAction: BOOST | CANCEL
9
+ // The result is the device. Only its id is read back (review A2): status is non-null and
10
+ // KT-CT-4360 has been seen on it, so an error there would null the answer and make a boost
11
+ // that went through look refused. The charging poll that follows reads the state, and it
12
+ // tolerates status errors.
13
+ const BOOST_MUTATION = `mutation UpdateBoostCharge($deviceId: String!, $action: UpdateBoostChargeAction!) { updateBoostCharge(input: { deviceId: $deviceId, action: $action }) { id } }`;
14
+
15
+ function buildBoostRequest(deviceId, enabled) {
16
+ return { query: BOOST_MUTATION, variables: { deviceId, action: enabled ? 'BOOST' : 'CANCEL' } };
17
+ }
18
+
19
+ // currentState BOOSTING -> true, any other known state -> false, missing -> null (unknown).
20
+ function isBoosting(currentState) {
21
+ if (currentState === null || currentState === undefined) return null;
22
+ return currentState === 'BOOSTING';
23
+ }
24
+
25
+ // Short "KT-CT-xxxx: message" form for logs and the boost_error field, the same form as
26
+ // intelligent_error (lib/graphql-errors.js): no trailing full stop, under 255 characters.
27
+ function formatKrakenErrors(errors) {
28
+ if (!Array.isArray(errors) || errors.length === 0) return 'Unknown error';
29
+ return truncate(errors.map((e) => {
30
+ const code = errorCode(e);
31
+ const msg = String((e && e.message) || '').trim().replace(/\.+$/, '') || 'Unknown error';
32
+ return code ? `${code}: ${msg}` : msg;
33
+ }).join('; '));
34
+ }
35
+
36
+ // A clean refusal: Octopus failed the mutation itself (errors at updateBoostCharge or with no
37
+ // path) and sent no device back. The refusal code has not been seen live, so the handling does
38
+ // not depend on it.
39
+ function isCleanRefusal(errors, device) {
40
+ return !device && errors.every((e) => !Array.isArray(e && e.path) || e.path.length <= 1);
41
+ }
42
+
43
+ // Octopus can refuse a boost (car unplugged, full, ...). Returns:
44
+ // ok: true accepted
45
+ // ok: false, unclear: false a clean refusal: nothing changed on the device
46
+ // ok: false, unclear: true not clear whether it went through (an error deeper in the
47
+ // answer, errors next to a device, or no device and no error).
48
+ // The caller must not flip the boost state: a poll tells.
49
+ // A read-back state is not used when there are errors.
50
+ function parseBoostResponse(res) {
51
+ const body = (res && res.data) || {};
52
+ const device = (body.data && body.data.updateBoostCharge) || null;
53
+ if (Array.isArray(body.errors) && body.errors.length > 0) {
54
+ const unclear = !isCleanRefusal(body.errors, device);
55
+ return { ok: false, unclear, currentState: null, boosting: null, error: formatKrakenErrors(body.errors) };
56
+ }
57
+ if (!device) {
58
+ return { ok: false, unclear: true, currentState: null, boosting: null, error: 'Boost response had no device' };
59
+ }
60
+ const currentState = device.status && device.status.currentState ? device.status.currentState : null;
61
+ return { ok: true, unclear: false, currentState, boosting: isBoosting(currentState), error: null };
62
+ }
63
+
64
+ function slotActiveAt(slots, now = new Date()) {
65
+ return (slots || []).some((s) => new Date(s.start) <= now && new Date(s.end) > now);
66
+ }
67
+
68
+ // A boost is charging outside the plan, so it counts as charging.
69
+ function chargingNowFor(slots, boosting, now = new Date()) {
70
+ return slotActiveAt(slots, now) || boosting === true;
71
+ }
72
+
73
+ // The 10 s reconciliation decision. Returns the corrected charging_now, or null for no change.
74
+ // With no slots and no boost it does nothing, as before boosts existed.
75
+ function reconcileChargingNow({ slots, boosting, chargingNow, now = new Date() }) {
76
+ const hasSlots = Array.isArray(slots) && slots.length > 0;
77
+ if (!hasSlots && boosting !== true) return null;
78
+ const shouldBeCharging = chargingNowFor(slots, boosting, now);
79
+ return shouldBeCharging === chargingNow ? null : shouldBeCharging;
80
+ }
81
+
82
+ module.exports = {
83
+ BOOST_MUTATION, buildBoostRequest, parseBoostResponse, formatKrakenErrors,
84
+ isBoosting, slotActiveAt, chargingNowFor, reconcileChargingNow,
85
+ };
@@ -1,5 +1,6 @@
1
1
  // lib/categories/account.js
2
2
  'use strict';
3
+ const { toNumber } = require('../values');
3
4
 
4
5
  const QUERY = `
5
6
  query getAccountBalance($account: String!) {
@@ -13,9 +14,8 @@ function buildQuery(account) {
13
14
  }
14
15
 
15
16
  function parseResponse(data) {
16
- // Kraken numeric scalars can serialise as strings — coerce defensively
17
- const raw = ((data.account || {}).balance) ?? null;
18
- const balancePence = raw !== null ? parseFloat(raw) : null;
17
+ // Kraken numeric scalars can serialise as strings; anything not a finite number is null
18
+ const balancePence = toNumber((data.account || {}).balance);
19
19
  return {
20
20
  account_balance_pence: balancePence,
21
21
  account_balance_pounds: balancePence !== null ? parseFloat((balancePence / 100).toFixed(2)) : null,
@@ -5,6 +5,7 @@
5
5
  // Same parser handles import and export — pass { fieldPrefix } to parseResponse
6
6
  // and exportFields() to swap the output naming to electricity_export_rate_*.
7
7
  'use strict';
8
+ const { toNumber, capStrings } = require('../values');
8
9
 
9
10
  const QUERY = `
10
11
  query getApplicableRates($account: String!, $mpxn: String!, $startAt: DateTime!, $endAt: DateTime!) {
@@ -30,24 +31,35 @@ function _stats(slots) {
30
31
  const min = sorted[0];
31
32
  const max = sorted[sorted.length - 1];
32
33
  const sum = values.reduce((a, v) => a + v, 0);
33
- const avg = parseFloat((sum / values.length).toFixed(4));
34
+ // Finite values can still add up past Number.MAX_VALUE: never publish Infinity.
35
+ const finite = (v) => (Number.isFinite(v) ? v : null);
36
+ const avg = finite(parseFloat((sum / values.length).toFixed(4)));
34
37
  let median;
35
38
  if (sorted.length % 2 === 1) {
36
39
  median = sorted[Math.floor(sorted.length / 2)];
37
40
  } else {
38
41
  const mid = sorted.length / 2;
39
- median = parseFloat(((sorted[mid - 1] + sorted[mid]) / 2).toFixed(4));
42
+ median = finite(parseFloat(((sorted[mid - 1] + sorted[mid]) / 2).toFixed(4)));
40
43
  }
41
44
  return { min, max, median, avg };
42
45
  }
43
46
 
44
- function _emit(prefix, slots, current, prev, next, stats) {
47
+ // Current / previous / next rate fields for `nowMs` from slots sorted by valid_from.
48
+ // Also used on the node's 10 s tick to keep them right between polls.
49
+ function currentFields(slots, prefix, nowMs) {
50
+ const currentIdx = slots.findIndex(s => {
51
+ const from = new Date(s.valid_from).getTime();
52
+ const to = new Date(s.valid_to).getTime();
53
+ return nowMs >= from && nowMs < to;
54
+ });
55
+ const current = currentIdx !== -1 ? slots[currentIdx] : null;
56
+ const prev = currentIdx > 0 ? slots[currentIdx - 1] : null;
57
+ const next = (currentIdx !== -1 && currentIdx < slots.length - 1) ? slots[currentIdx + 1] : null;
58
+
45
59
  const pence = current ? current.value_pence_per_kwh : null;
46
60
  const prevPence = prev ? prev.value_pence_per_kwh : null;
47
61
  const nextPence = next ? next.value_pence_per_kwh : null;
48
62
  const out = {};
49
- out[`${prefix}`] = slots;
50
- out[`${prefix}_count`] = slots.length;
51
63
  out[`${prefix}_current_pence`] = pence;
52
64
  out[`${prefix}_current_gbp`] = pence !== null ? parseFloat((pence / 100).toFixed(4)) : null;
53
65
  out[`${prefix}_prev_pence`] = prevPence;
@@ -56,6 +68,14 @@ function _emit(prefix, slots, current, prev, next, stats) {
56
68
  out[`${prefix}_next_pence`] = nextPence;
57
69
  out[`${prefix}_next_gbp`] = nextPence !== null ? parseFloat((nextPence / 100).toFixed(4)) : null;
58
70
  out[`${prefix}_next_from`] = next ? next.valid_from : null;
71
+ return out;
72
+ }
73
+
74
+ function _emit(prefix, slots, nowMs, stats) {
75
+ const out = {};
76
+ out[`${prefix}`] = slots;
77
+ out[`${prefix}_count`] = slots.length;
78
+ Object.assign(out, currentFields(slots, prefix, nowMs));
59
79
  out[`${prefix}_error`] = null;
60
80
  // v1.5 stats
61
81
  out[`${prefix}_min_pence`] = stats.min;
@@ -71,24 +91,13 @@ function parseResponse(data, options) {
71
91
  const slots = edges.map(e => ({
72
92
  valid_from: e.node.validFrom,
73
93
  valid_to: e.node.validTo,
74
- value_pence_per_kwh: e.node.value !== null ? parseFloat(e.node.value) : null
94
+ value_pence_per_kwh: toNumber(e.node.value)
75
95
  }));
76
96
 
77
97
  slots.sort((a, b) => new Date(a.valid_from) - new Date(b.valid_from));
78
98
 
79
- const now = Date.now();
80
- const currentIdx = slots.findIndex(s => {
81
- const from = new Date(s.valid_from).getTime();
82
- const to = new Date(s.valid_to).getTime();
83
- return now >= from && now < to;
84
- });
85
-
86
- const current = currentIdx !== -1 ? slots[currentIdx] : null;
87
- const prev = currentIdx > 0 ? slots[currentIdx - 1] : null;
88
- const next = (currentIdx !== -1 && currentIdx < slots.length - 1) ? slots[currentIdx + 1] : null;
89
-
90
99
  const stats = _stats(slots);
91
- return _emit(prefix, slots, current, prev, next, stats);
100
+ return _emit(prefix, slots, Date.now(), stats);
92
101
  }
93
102
 
94
103
  const defaultData = {
@@ -124,4 +133,5 @@ const defaultData = {
124
133
  electricity_export_rate_avg_pence: null
125
134
  };
126
135
 
127
- module.exports = { buildQuery, parseResponse, defaultData };
136
+ // Text fields cut to the HA state limit (lib/values.js).
137
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), currentFields: capStrings(currentFields), defaultData };
@@ -1,5 +1,6 @@
1
1
  // lib/categories/completed-dispatches.js
2
2
  'use strict';
3
+ const { toNumber } = require('../values');
3
4
 
4
5
  const QUERY = `
5
6
  query getCompletedDispatches($account: String!) {
@@ -18,7 +19,7 @@ function parseResponse(data) {
18
19
  completed_dispatches: dispatches.map(d => ({
19
20
  start: d.start,
20
21
  end: d.end,
21
- delta_kwh: d.delta !== null && d.delta !== undefined ? parseFloat(d.delta) : null,
22
+ delta_kwh: toNumber(d.delta),
22
23
  source: (d.meta || {}).source || null
23
24
  })),
24
25
  completed_dispatches_count: dispatches.length,
@@ -1,5 +1,6 @@
1
1
  // lib/categories/electricity.js
2
2
  'use strict';
3
+ const { toNumber, capStrings } = require('../values');
3
4
 
4
5
  const RATES_QUERY = `
5
6
  query getElectricityRates($account: String!) {
@@ -55,18 +56,18 @@ function parseRatesResponse(data) {
55
56
  const fieldsFor = (prefix, agreements) => {
56
57
  const latest = agreements[0];
57
58
  const tariff = (latest && latest.tariff) || {};
58
- // Kraken Float scalars can serialise as strings — coerce defensively
59
+ // Kraken Float scalars can serialise as strings; anything not a finite number is null
59
60
  return {
60
- [`${prefix}_unit_rate`]: tariff.unitRate != null ? parseFloat(tariff.unitRate) : null,
61
- [`${prefix}_standing_charge`]: tariff.standingCharge != null ? parseFloat(tariff.standingCharge) : null,
61
+ [`${prefix}_unit_rate`]: toNumber(tariff.unitRate),
62
+ [`${prefix}_standing_charge`]: toNumber(tariff.standingCharge),
62
63
  [`${prefix}_tariff_code`]: tariff.productCode || null,
63
64
  [`${prefix}_valid_from`]: (latest && latest.validFrom) || null,
64
65
  [`${prefix}_valid_to`]: (latest && latest.validTo) || null,
65
66
  // v1.5 rate-band fields — null on tariffs that don't expose them
66
- [`${prefix}_day_rate`]: tariff.dayRate != null ? parseFloat(tariff.dayRate) : null,
67
- [`${prefix}_night_rate`]: tariff.nightRate != null ? parseFloat(tariff.nightRate) : null,
68
- [`${prefix}_ev_peak_rate`]: tariff.evDevicePeakRate != null ? parseFloat(tariff.evDevicePeakRate) : null,
69
- [`${prefix}_ev_off_peak_rate`]: tariff.evDeviceOffPeakRate != null ? parseFloat(tariff.evDeviceOffPeakRate) : null,
67
+ [`${prefix}_day_rate`]: toNumber(tariff.dayRate),
68
+ [`${prefix}_night_rate`]: toNumber(tariff.nightRate),
69
+ [`${prefix}_ev_peak_rate`]: toNumber(tariff.evDevicePeakRate),
70
+ [`${prefix}_ev_off_peak_rate`]: toNumber(tariff.evDeviceOffPeakRate),
70
71
  };
71
72
  };
72
73
 
@@ -77,7 +78,7 @@ function parseRatesResponse(data) {
77
78
  };
78
79
  }
79
80
 
80
- // Picks the latest consumption edge for a given MPAN out of the query response.
81
+ // Picks the latest consumption reading for a given MPAN out of the query response.
81
82
  function _findEntryForMpan(data, mpan) {
82
83
  if (!mpan) return null;
83
84
  const points = ((data.account || {}).properties || [])[0];
@@ -86,7 +87,14 @@ function _findEntryForMpan(data, mpan) {
86
87
  if (!mp) return null;
87
88
  const meter = (mp.meters || [])[0];
88
89
  const edges = ((meter && meter.consumption) || {}).edges || [];
89
- return edges.length > 0 ? edges[edges.length - 1].node : null;
90
+ return latestReading(edges);
91
+ }
92
+
93
+ // The last reading whose value is a number. One with no value (null while Octopus is still
94
+ // collecting it) is skipped, so the totals never show NaN.
95
+ function latestReading(edges) {
96
+ const readings = edges.map((e) => e && e.node).filter((n) => n && toNumber(n.value) !== null);
97
+ return readings.length > 0 ? readings[readings.length - 1] : null;
90
98
  }
91
99
 
92
100
  // Parses both import and export consumption from one response, given both MPANs.
@@ -96,11 +104,11 @@ function parseConsumptionResponse(data, importMpan, exportMpan) {
96
104
  const importEntry = _findEntryForMpan(data, importMpan);
97
105
  const exportEntry = _findEntryForMpan(data, exportMpan);
98
106
  return {
99
- electricity_consumption_kwh: importEntry ? parseFloat(importEntry.value) : null,
107
+ electricity_consumption_kwh: importEntry ? toNumber(importEntry.value) : null,
100
108
  electricity_consumption_cost: null,
101
109
  electricity_consumption_from: importEntry ? importEntry.startAt : null,
102
110
  electricity_consumption_to: importEntry ? importEntry.endAt : null,
103
- electricity_export_consumption_kwh: exportEntry ? parseFloat(exportEntry.value) : null,
111
+ electricity_export_consumption_kwh: exportEntry ? toNumber(exportEntry.value) : null,
104
112
  electricity_export_consumption_from: exportEntry ? exportEntry.startAt : null,
105
113
  electricity_export_consumption_to: exportEntry ? exportEntry.endAt : null,
106
114
  electricity_consumption_error: null
@@ -140,7 +148,9 @@ const defaultData = {
140
148
  module.exports = {
141
149
  buildRatesQuery,
142
150
  buildConsumptionQuery,
143
- parseRatesResponse,
144
- parseConsumptionResponse,
151
+ // Text fields cut to the HA state limit (lib/values.js).
152
+ parseRatesResponse: capStrings(parseRatesResponse),
153
+ parseConsumptionResponse: capStrings(parseConsumptionResponse),
154
+ latestReading,
145
155
  defaultData
146
156
  };