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

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 (47) hide show
  1. package/CHANGELOG.md +597 -442
  2. package/README.md +1234 -980
  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 +667 -599
  9. package/examples/mqtt-integration.json +1 -1
  10. package/examples/node-red-dashboard-flow.json +1377 -1199
  11. package/examples/set-preferences.json +1 -1
  12. package/lib/active-now.js +33 -0
  13. package/lib/api-metrics.js +31 -31
  14. package/lib/auth.js +25 -20
  15. package/lib/boost.js +85 -0
  16. package/lib/categories/account.js +32 -32
  17. package/lib/categories/applicable-rates.js +137 -127
  18. package/lib/categories/completed-dispatches.js +36 -35
  19. package/lib/categories/electricity.js +156 -146
  20. package/lib/categories/flex-planned-dispatches.js +36 -36
  21. package/lib/categories/free-electricity.js +73 -61
  22. package/lib/categories/gas.js +102 -95
  23. package/lib/categories/home-mini.js +45 -37
  24. package/lib/categories/intelligent.js +221 -124
  25. package/lib/categories/octoplus.js +35 -32
  26. package/lib/categories/saving-sessions.js +78 -64
  27. package/lib/categories/smartflex-inverter.js +95 -0
  28. package/lib/categories/smartflex-vehicle.js +198 -0
  29. package/lib/categories/wheel-of-fortune.js +50 -49
  30. package/lib/commands.js +69 -0
  31. package/lib/discovery-retry.js +16 -0
  32. package/lib/discovery.js +154 -85
  33. package/lib/graphql-errors.js +174 -0
  34. package/lib/graphql.js +141 -44
  35. package/lib/http-get-json.js +80 -22
  36. package/lib/payload.js +104 -88
  37. package/lib/poll-retry.js +71 -0
  38. package/lib/poll-tick.js +112 -44
  39. package/lib/preferences.js +34 -0
  40. package/lib/scheduler.js +85 -47
  41. package/lib/sensor-definitions.js +269 -0
  42. package/lib/timezone.js +67 -49
  43. package/lib/update-check.js +38 -38
  44. package/lib/values.js +47 -0
  45. package/octopus-intelligent.html +258 -205
  46. package/octopus-intelligent.js +2816 -1807
  47. package/package.json +54 -54
@@ -1,1808 +1,2817 @@
1
- 'use strict';
2
- const { graphqlPost } = require('./lib/graphql');
3
- const { convertToTimezone, resolveTimezone } = require('./lib/timezone');
4
- const { createApiMetrics } = require('./lib/api-metrics');
5
- const intelligentCategory = require('./lib/categories/intelligent');
6
- const { buildDefaultPayload } = require('./lib/payload');
7
- const { createScheduler } = require('./lib/scheduler');
8
- const { simplePoll, runTick } = require('./lib/poll-tick');
9
- const { discoverProducts } = require('./lib/discovery');
10
- const { mergePayload } = require('./lib/payload');
11
- const electricityCategory = require('./lib/categories/electricity');
12
- const gasCategory = require('./lib/categories/gas');
13
- const wheelOfFortuneCategory = require('./lib/categories/wheel-of-fortune');
14
- const homeMiniCategory = require('./lib/categories/home-mini');
15
- const completedDispatchesCategory = require('./lib/categories/completed-dispatches');
16
- const accountCategory = require('./lib/categories/account');
17
- const octoplusCategory = require('./lib/categories/octoplus');
18
- const flexPlannedDispatchesCategory = require('./lib/categories/flex-planned-dispatches');
19
- const applicableRatesCategory = require('./lib/categories/applicable-rates');
20
- const savingSessionsCategory = require('./lib/categories/saving-sessions');
21
- const freeElectricityCategory = require('./lib/categories/free-electricity');
22
- const httpGetJson = require('./lib/http-get-json');
23
- const { checkUpdate } = require('./lib/update-check');
24
-
25
- module.exports = function (RED) {
26
- function OctopusIntelligentNode(config) {
27
- RED.nodes.createNode(this, config);
28
- var node = this;
29
-
30
- // 1. Configuration
31
- const account = config.accountNumber ? config.accountNumber.trim() : "";
32
- const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
33
- const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
34
- const enableMqtt = config.enableMqtt;
35
- node.timezoneOverride = config.timezoneOverride || "";
36
-
37
- // MQTT Topics
38
- this.broker = RED.nodes.getNode(config.broker);
39
- const mqttPrefix = `homeassistant`;
40
- const uniqueIdPrefix = `nodered_${account}`;
41
- const stateTopic = `nodered_octopus/${account}/status`;
42
-
43
- // Command Topics (For listening)
44
- const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
45
- const cmdTopicTime = `nodered_octopus/${account}/set_time`;
46
- const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
47
- const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
48
- const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
49
- const cmdTopicSmartCharging = `nodered_octopus/${account}/set_smart_charging`;
50
-
51
- // 2. Constants & Validation
52
- const TIME_OPTIONS = [
53
- "04:00", "04:30", "05:00", "05:30",
54
- "06:00", "06:30", "07:00", "07:30",
55
- "08:00", "08:30", "09:00", "09:30",
56
- "10:00", "10:30", "11:00"
57
- ];
58
-
59
- // 3. Sensor Definitions (Read-Only)
60
- // category: undefined = main, 'config' = Configuration, 'diagnostic' = Diagnostics
61
- const sensors = [
62
- // --- EV Charging (main) ---
63
- { id: 'next_charge', name: 'Next Charge Time', class: 'timestamp', icon: 'mdi:timer', val: 'next_start' },
64
- { id: 'total_energy', name: 'Total Planned Energy', unit: 'kWh', class: 'energy', val: 'total_energy' },
65
- { id: 'next_kwh', name: 'Next Slot Energy', unit: 'kWh', class: 'energy', val: 'next_kwh' },
66
- { id: 'source', name: 'Charge Source', icon: 'mdi:help-circle', val: 'next_source' },
67
- { id: 'slot1_start', name: 'Slot 1 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot1_start' },
68
- { id: 'slot1_end', name: 'Slot 1 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot1_end' },
69
- { id: 'slot2_start', name: 'Slot 2 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot2_start' },
70
- { id: 'slot2_end', name: 'Slot 2 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot2_end' },
71
- { id: 'slot3_start', name: 'Slot 3 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot3_start' },
72
- { id: 'slot3_end', name: 'Slot 3 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot3_end' },
73
- { id: 'window_start', name: 'Overall Window Start', class: 'timestamp', icon: 'mdi:timer-play', val: 'window_start' },
74
- { id: 'window_end', name: 'Overall Window End', class: 'timestamp', icon: 'mdi:timer-stop', val: 'window_end' },
75
-
76
- // --- EV Charging (diagnostic) ---
77
- { id: 'next_poll', name: 'Next Poll Time', class: 'timestamp', icon: 'mdi:clock-outline', val: 'next_poll', category: 'diagnostic' },
78
- { id: 'refresh_available_at', name: 'Refresh Available At', class: 'timestamp', icon: 'mdi:timer-sand', val: 'refresh_available_at', category: 'diagnostic' },
79
- { id: 'api_requests_hour', name: 'API Requests (Last Hour)', icon: 'mdi:api', val: 'api_requests_hour', category: 'diagnostic' },
80
- { id: 'api_complexity_hour', name: 'API Complexity (Last Hour)', icon: 'mdi:chart-line', val: 'api_complexity_hour', category: 'diagnostic' },
81
- { id: 'api_complexity_percent', name: 'API Complexity Usage', unit: '%', icon: 'mdi:percent', val: 'api_complexity_percent', category: 'diagnostic' },
82
-
83
- // --- Raw timestamps (diagnostic) ---
84
- { id: 'next_charge_raw', name: 'Next Charge Time (Raw)', icon: 'mdi:timer', val: 'next_start_raw', category: 'diagnostic' },
85
- { id: 'next_poll_raw', name: 'Next Poll Time (Raw)', icon: 'mdi:clock-outline', val: 'next_poll_raw', category: 'diagnostic' },
86
- { id: 'slot1_start_raw', name: 'Slot 1 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot1_start_raw', category: 'diagnostic' },
87
- { id: 'slot1_end_raw', name: 'Slot 1 End (Raw)', icon: 'mdi:timer-outline', val: 'slot1_end_raw', category: 'diagnostic' },
88
- { id: 'slot2_start_raw', name: 'Slot 2 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot2_start_raw', category: 'diagnostic' },
89
- { id: 'slot2_end_raw', name: 'Slot 2 End (Raw)', icon: 'mdi:timer-outline', val: 'slot2_end_raw', category: 'diagnostic' },
90
- { id: 'slot3_start_raw', name: 'Slot 3 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot3_start_raw', category: 'diagnostic' },
91
- { id: 'slot3_end_raw', name: 'Slot 3 End (Raw)', icon: 'mdi:timer-outline', val: 'slot3_end_raw', category: 'diagnostic' },
92
- { id: 'window_start_raw', name: 'Overall Window Start (Raw)', icon: 'mdi:timer-play', val: 'window_start_raw', category: 'diagnostic' },
93
- { id: 'window_end_raw', name: 'Overall Window End (Raw)', icon: 'mdi:timer-stop', val: 'window_end_raw', category: 'diagnostic' },
94
-
95
- // --- Locale timestamps (diagnostic) ---
96
- { id: 'next_charge_locale', name: 'Next Charge Time (Locale)', icon: 'mdi:timer', val: 'next_start_locale', category: 'diagnostic' },
97
- { id: 'slot1_start_locale', name: 'Slot 1 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot1_start_locale', category: 'diagnostic' },
98
- { id: 'slot1_end_locale', name: 'Slot 1 End (Locale)', icon: 'mdi:timer-outline', val: 'slot1_end_locale', category: 'diagnostic' },
99
- { id: 'slot2_start_locale', name: 'Slot 2 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot2_start_locale', category: 'diagnostic' },
100
- { id: 'slot2_end_locale', name: 'Slot 2 End (Locale)', icon: 'mdi:timer-outline', val: 'slot2_end_locale', category: 'diagnostic' },
101
- { id: 'slot3_start_locale', name: 'Slot 3 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot3_start_locale', category: 'diagnostic' },
102
- { id: 'slot3_end_locale', name: 'Slot 3 End (Locale)', icon: 'mdi:timer-outline', val: 'slot3_end_locale', category: 'diagnostic' },
103
- { id: 'window_start_locale', name: 'Overall Window Start (Locale)', icon: 'mdi:timer-play', val: 'window_start_locale', category: 'diagnostic' },
104
- { id: 'window_end_locale', name: 'Overall Window End (Locale)', icon: 'mdi:timer-stop', val: 'window_end_locale', category: 'diagnostic' },
105
- { id: 'timezone_detected', name: 'Timezone Detected', icon: 'mdi:earth', val: 'timezone_detected', category: 'diagnostic' },
106
- { id: 'timezone_applied', name: 'Timezone Applied', icon: 'mdi:earth-plus', val: 'timezone_applied', category: 'diagnostic' },
107
- // --- Electricity (main) ---
108
- { id: 'electricity_standing_charge', name: 'Electricity Standing Charge', unit: 'p/day', icon: 'mdi:cash', val: 'electricity_standing_charge' },
109
- { id: 'electricity_consumption_kwh', name: 'Electricity Consumption', unit: 'kWh', class: 'energy', val: 'electricity_consumption_kwh' },
110
- // --- Electricity (config) ---
111
- { id: 'electricity_unit_rate', name: 'Electricity Unit Rate', unit: 'p/kWh', icon: 'mdi:flash', val: 'electricity_unit_rate' },
112
- { id: 'electricity_day_rate', name: 'Electricity Day Rate', unit: 'p/kWh', icon: 'mdi:weather-sunny', val: 'electricity_day_rate', category: 'config' },
113
- { id: 'electricity_night_rate', name: 'Electricity Night Rate', unit: 'p/kWh', icon: 'mdi:weather-night', val: 'electricity_night_rate', category: 'config' },
114
- { id: 'electricity_ev_peak_rate', name: 'Electricity EV Peak Rate', unit: 'p/kWh', icon: 'mdi:car-electric-outline', val: 'electricity_ev_peak_rate', category: 'config' },
115
- { id: 'electricity_ev_off_peak_rate', name: 'Electricity EV Off-Peak Rate', unit: 'p/kWh', icon: 'mdi:car-electric', val: 'electricity_ev_off_peak_rate', category: 'config' },
116
- { id: 'electricity_tariff_code', name: 'Electricity Tariff Code', icon: 'mdi:tag', val: 'electricity_tariff_code' },
117
- { id: 'electricity_valid_from', name: 'Electricity Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'electricity_valid_from' },
118
- { id: 'electricity_valid_to', name: 'Electricity Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'electricity_valid_to' },
119
- // --- Electricity (diagnostic) ---
120
- { id: 'electricity_consumption_from', name: 'Electricity Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_consumption_from', category: 'diagnostic' },
121
- { id: 'electricity_consumption_to', name: 'Electricity Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_consumption_to', category: 'diagnostic' },
122
- { id: 'electricity_rates_error', name: 'Electricity Rates Error', icon: 'mdi:alert-circle', val: 'electricity_rates_error', category: 'diagnostic' },
123
- { id: 'electricity_consumption_error', name: 'Electricity Consumption Error', icon: 'mdi:alert-circle', val: 'electricity_consumption_error', category: 'diagnostic' },
124
-
125
- // --- Electricity Export (main) ---
126
- { id: 'electricity_export_consumption_kwh', name: 'Electricity Export Consumption', unit: 'kWh', class: 'energy', val: 'electricity_export_consumption_kwh' },
127
- { id: 'electricity_export_rate_current_pence', name: 'Current Electricity Export Rate', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_current_pence' },
128
- { id: 'electricity_export_rate_current_gbp', name: 'Electricity Export Rate', unit: 'GBP/kWh', icon: 'mdi:cash-clock', stateClass: 'measurement', val: 'electricity_export_rate_current_gbp' },
129
- // --- Electricity Export (config) ---
130
- // Solar/export users have a second agreement with productCode containing "OUTGOING".
131
- // unit_rate is null for half-hourly export tariffs (e.g. Agile Outgoing) — current
132
- // half-hourly export rate comes from electricity_export_rate_current_pence.
133
- { id: 'electricity_export_unit_rate', name: 'Electricity Export Unit Rate', unit: 'p/kWh', icon: 'mdi:transmission-tower-export', val: 'electricity_export_unit_rate' },
134
- { id: 'electricity_export_standing_charge',name: 'Electricity Export Standing Charge',unit: 'p/day', icon: 'mdi:cash', val: 'electricity_export_standing_charge' },
135
- { id: 'electricity_export_tariff_code', name: 'Electricity Export Tariff Code', icon: 'mdi:tag', val: 'electricity_export_tariff_code' },
136
- { id: 'electricity_export_valid_from', name: 'Electricity Export Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'electricity_export_valid_from' },
137
- { id: 'electricity_export_valid_to', name: 'Electricity Export Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'electricity_export_valid_to' },
138
- // --- Electricity Export (diagnostic) ---
139
- { id: 'electricity_export_consumption_from', name: 'Electricity Export Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_consumption_from', category: 'diagnostic' },
140
- { id: 'electricity_export_consumption_to', name: 'Electricity Export Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_consumption_to', category: 'diagnostic' },
141
- { id: 'electricity_export_rate_count', name: 'Electricity Export Rate Slots', icon: 'mdi:format-list-numbered', val: 'electricity_export_rate_count', category: 'diagnostic' },
142
- { id: 'electricity_export_rate_prev_pence', name: 'Electricity Export Rate Prev', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_prev_pence', category: 'diagnostic' },
143
- { id: 'electricity_export_rate_prev_to', name: 'Electricity Export Rate Prev Ends', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_rate_prev_to', category: 'diagnostic' },
144
- { id: 'electricity_export_rate_next_pence', name: 'Electricity Export Rate Next', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_next_pence', category: 'diagnostic' },
145
- { id: 'electricity_export_rate_next_from', name: 'Electricity Export Rate Next From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_rate_next_from', category: 'diagnostic' },
146
- { id: 'electricity_export_rate_prev_gbp', name: 'Electricity Export Rate Prev (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_prev_gbp', stateClass: 'measurement', category: 'diagnostic' },
147
- { id: 'electricity_export_rate_next_gbp', name: 'Electricity Export Rate Next (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_next_gbp', stateClass: 'measurement', category: 'diagnostic' },
148
- { id: 'electricity_export_rate_error', name: 'Electricity Export Rate Error', icon: 'mdi:alert-circle', val: 'electricity_export_rate_error', category: 'diagnostic' },
149
-
150
- // --- Gas (main) ---
151
- { id: 'gas_standing_charge', name: 'Gas Standing Charge', unit: 'p/day', icon: 'mdi:cash', val: 'gas_standing_charge' },
152
- { id: 'gas_consumption_kwh', name: 'Gas Consumption', unit: 'kWh', class: 'energy', val: 'gas_consumption_kwh' },
153
- // --- Gas (config) ---
154
- { id: 'gas_unit_rate', name: 'Gas Unit Rate', unit: 'p/kWh', icon: 'mdi:fire', val: 'gas_unit_rate' },
155
- { id: 'gas_tariff_code', name: 'Gas Tariff Code', icon: 'mdi:tag', val: 'gas_tariff_code' },
156
- { id: 'gas_valid_from', name: 'Gas Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'gas_valid_from' },
157
- { id: 'gas_valid_to', name: 'Gas Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'gas_valid_to' },
158
- // --- Gas (diagnostic) ---
159
- { id: 'gas_consumption_from', name: 'Gas Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'gas_consumption_from', category: 'diagnostic' },
160
- { id: 'gas_consumption_to', name: 'Gas Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'gas_consumption_to', category: 'diagnostic' },
161
- { id: 'gas_rates_error', name: 'Gas Rates Error', icon: 'mdi:alert-circle', val: 'gas_rates_error', category: 'diagnostic' },
162
- { id: 'gas_consumption_error', name: 'Gas Consumption Error', icon: 'mdi:alert-circle', val: 'gas_consumption_error', category: 'diagnostic' },
163
-
164
- // --- Applicable Rates (main) ---
165
- { id: 'applicable_rates_current_pence', name: 'Current Electricity Rate', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_current_pence' },
166
- { id: 'applicable_rates_current_gbp', name: 'Electricity Rate', unit: 'GBP/kWh', icon: 'mdi:cash-clock', stateClass: 'measurement', val: 'applicable_rates_current_gbp' },
167
- // --- Applicable Rates (diagnostic) ---
168
- { id: 'applicable_rates_count', name: 'Applicable Rates Slots', icon: 'mdi:format-list-numbered', val: 'applicable_rates_count', category: 'diagnostic' },
169
- { id: 'applicable_rates_error', name: 'Applicable Rates Error', icon: 'mdi:alert-circle', val: 'applicable_rates_error', category: 'diagnostic' },
170
- { id: 'applicable_rates_prev_pence', name: 'Applicable Rate Prev', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_prev_pence', category: 'diagnostic' },
171
- { id: 'applicable_rates_prev_gbp', name: 'Applicable Rate Prev (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_prev_gbp', stateClass: 'measurement', category: 'diagnostic' },
172
- { id: 'applicable_rates_prev_to', name: 'Applicable Rate Prev Ends', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'applicable_rates_prev_to', category: 'diagnostic' },
173
- { id: 'applicable_rates_next_pence', name: 'Applicable Rate Next', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_next_pence', category: 'diagnostic' },
174
- { id: 'applicable_rates_next_gbp', name: 'Applicable Rate Next (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_next_gbp', stateClass: 'measurement', category: 'diagnostic' },
175
- { id: 'applicable_rates_next_from', name: 'Applicable Rate Next From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'applicable_rates_next_from', category: 'diagnostic' },
176
- // Applicable rates — 24h schedule stats (v1.5)
177
- { id: 'applicable_rates_min_pence', name: 'Applicable Rates Min', unit: 'p/kWh', icon: 'mdi:arrow-down', val: 'applicable_rates_min_pence', category: 'diagnostic' },
178
- { id: 'applicable_rates_max_pence', name: 'Applicable Rates Max', unit: 'p/kWh', icon: 'mdi:arrow-up', val: 'applicable_rates_max_pence', category: 'diagnostic' },
179
- { id: 'applicable_rates_median_pence', name: 'Applicable Rates Median', unit: 'p/kWh', icon: 'mdi:approximately-equal', val: 'applicable_rates_median_pence', category: 'diagnostic' },
180
- { id: 'applicable_rates_avg_pence', name: 'Applicable Rates Avg', unit: 'p/kWh', icon: 'mdi:chart-line', val: 'applicable_rates_avg_pence', category: 'diagnostic' },
181
- { id: 'electricity_export_rate_min_pence', name: 'Electricity Export Rate Min', unit: 'p/kWh', icon: 'mdi:arrow-down', val: 'electricity_export_rate_min_pence', category: 'diagnostic' },
182
- { id: 'electricity_export_rate_max_pence', name: 'Electricity Export Rate Max', unit: 'p/kWh', icon: 'mdi:arrow-up', val: 'electricity_export_rate_max_pence', category: 'diagnostic' },
183
- { id: 'electricity_export_rate_median_pence', name: 'Electricity Export Rate Median', unit: 'p/kWh', icon: 'mdi:approximately-equal', val: 'electricity_export_rate_median_pence', category: 'diagnostic' },
184
- { id: 'electricity_export_rate_avg_pence', name: 'Electricity Export Rate Avg', unit: 'p/kWh', icon: 'mdi:chart-line', val: 'electricity_export_rate_avg_pence', category: 'diagnostic' },
185
-
186
- // --- Account (main) ---
187
- { id: 'account_balance_pounds', name: 'Account Balance', unit: '£', icon: 'mdi:cash-multiple', val: 'account_balance_pounds' },
188
- // --- Account (diagnostic) ---
189
- { id: 'account_balance_pence', name: 'Account Balance (Pence)', unit: 'p', icon: 'mdi:cash', val: 'account_balance_pence', category: 'diagnostic' },
190
- { id: 'account_error', name: 'Account Error', icon: 'mdi:alert-circle', val: 'account_error', category: 'diagnostic' },
191
-
192
- // --- Octoplus (config) ---
193
- // octoplus_enrolled and octoplus_loyalty_points_user are booleans — published as
194
- // binary_sensor entities further down. Leaving them out of this array.
195
- { id: 'octoplus_enrollment_status', name: 'Octoplus Status', icon: 'mdi:star-circle-outline', val: 'octoplus_enrollment_status' },
196
- // --- Octoplus (diagnostic) ---
197
- { id: 'octoplus_error', name: 'Octoplus Error', icon: 'mdi:alert-circle', val: 'octoplus_error', category: 'diagnostic' },
198
-
199
- // --- Wheel of Fortune (main) ---
200
- { id: 'wheel_of_fortune_electricity_spins', name: 'WoF Electricity Spins', icon: 'mdi:star-circle', val: 'wheel_of_fortune_electricity_spins' },
201
- { id: 'wheel_of_fortune_gas_spins', name: 'WoF Gas Spins', icon: 'mdi:star-circle', val: 'wheel_of_fortune_gas_spins' },
202
- // --- Wheel of Fortune (diagnostic) ---
203
- { id: 'wheel_of_fortune_electricity_max', name: 'WoF Electricity Max', icon: 'mdi:star-outline', val: 'wheel_of_fortune_electricity_max', category: 'diagnostic' },
204
- { id: 'wheel_of_fortune_electricity_used', name: 'WoF Electricity Used', icon: 'mdi:star-outline', val: 'wheel_of_fortune_electricity_used', category: 'diagnostic' },
205
- { id: 'wheel_of_fortune_gas_max', name: 'WoF Gas Max', icon: 'mdi:star-outline', val: 'wheel_of_fortune_gas_max', category: 'diagnostic' },
206
- { id: 'wheel_of_fortune_gas_used', name: 'WoF Gas Used', icon: 'mdi:star-outline', val: 'wheel_of_fortune_gas_used', category: 'diagnostic' },
207
- { id: 'wheel_of_fortune_error', name: 'WoF Error', icon: 'mdi:alert-circle', val: 'wheel_of_fortune_error', category: 'diagnostic' },
208
-
209
- // --- Home Mini (main) ---
210
- { id: 'mini_demand_kw', name: 'Home Mini Demand', unit: 'kW', class: 'power', icon: 'mdi:home-lightning-bolt', val: 'mini_demand_kw' },
211
- { id: 'mini_consumption_delta_kwh', name: 'Home Mini Period Consumption', unit: 'kWh', class: 'energy', icon: 'mdi:home-lightning-bolt', val: 'mini_consumption_delta_kwh' },
212
- // --- Home Mini (diagnostic) ---
213
- { id: 'mini_read_at', name: 'Home Mini Reading Time', class: 'timestamp', icon: 'mdi:clock-outline', val: 'mini_read_at', category: 'diagnostic' },
214
- { id: 'home_mini_error', name: 'Home Mini Error', icon: 'mdi:alert-circle', val: 'home_mini_error', category: 'diagnostic' },
215
-
216
- // --- Saving Sessions (main) ---
217
- { id: 'saving_session_points', name: 'Octopus Points', icon: 'mdi:star', val: 'saving_session_points' },
218
- // --- Saving Sessions (config) ---
219
- { id: 'saving_session_start', name: 'Saving Session Start', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'saving_session_start' },
220
- { id: 'saving_session_end', name: 'Saving Session End', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'saving_session_end' },
221
- // --- Saving Sessions (diagnostic) ---
222
- { id: 'saving_sessions_error', name: 'Saving Sessions Error', icon: 'mdi:alert-circle', val: 'saving_sessions_error', category: 'diagnostic' },
223
-
224
- // --- Free Electricity (config) ---
225
- { id: 'free_electricity_start', name: 'Free Electricity Start', class: 'timestamp', icon: 'mdi:flash-circle', val: 'free_electricity_start' },
226
- { id: 'free_electricity_end', name: 'Free Electricity End', class: 'timestamp', icon: 'mdi:flash-circle', val: 'free_electricity_end' },
227
- // --- Free Electricity (diagnostic) ---
228
- { id: 'free_electricity_error', name: 'Free Electricity Error', icon: 'mdi:alert-circle', val: 'free_electricity_error', category: 'diagnostic' },
229
-
230
- // --- Dispatches (main) ---
231
- { id: 'completed_dispatches_count', name: 'Completed Dispatches', icon: 'mdi:history', val: 'completed_dispatches_count' },
232
- { id: 'flex_planned_dispatches_count', name: 'Flex Planned Dispatches', icon: 'mdi:lightning-bolt-circle', val: 'flex_planned_dispatches_count' },
233
- // --- Dispatches (diagnostic) ---
234
- { id: 'completed_dispatches_error', name: 'Completed Dispatches Error', icon: 'mdi:alert-circle', val: 'completed_dispatches_error', category: 'diagnostic' },
235
- { id: 'flex_planned_dispatches_error', name: 'Flex Planned Dispatches Error', icon: 'mdi:alert-circle', val: 'flex_planned_dispatches_error', category: 'diagnostic' },
236
- { id: 'intelligent_error', name: 'Intelligent Error', icon: 'mdi:alert-circle', val: 'intelligent_error', category: 'diagnostic' },
237
-
238
- // v1.5 — update check (MQTT Update entity itself lands in Task 21)
239
- { id: 'installed_version', name: 'Installed Version', icon: 'mdi:package-variant', val: 'installed_version', category: 'diagnostic' },
240
- { id: 'latest_version', name: 'Latest Version', icon: 'mdi:package-variant-closed-plus', val: 'latest_version', category: 'diagnostic' },
241
- { id: 'update_check_at', name: 'Update Check At', class: 'timestamp', icon: 'mdi:clock-check-outline', val: 'update_check_at', category: 'diagnostic' },
242
- { id: 'update_check_error', name: 'Update Check Error', icon: 'mdi:alert-circle', val: 'update_check_error', category: 'diagnostic' },
243
- ];
244
-
245
- // v1.5 — derived binary_sensors for the unified <category>_error fields.
246
- // OFF when the underlying field is null/empty (healthy), ON when populated.
247
- // The string sensors stay; these are additional indicators.
248
- const errorSensors = [
249
- { id: 'intelligent_error_state', name: 'Intelligent Error State', val: 'intelligent_error' },
250
- { id: 'electricity_rates_error_state', name: 'Electricity Rates Error State', val: 'electricity_rates_error' },
251
- { id: 'electricity_consumption_error_state', name: 'Electricity Consumption Error State', val: 'electricity_consumption_error' },
252
- { id: 'electricity_export_rate_error_state', name: 'Electricity Export Rate Error State', val: 'electricity_export_rate_error' },
253
- { id: 'gas_rates_error_state', name: 'Gas Rates Error State', val: 'gas_rates_error' },
254
- { id: 'gas_consumption_error_state', name: 'Gas Consumption Error State', val: 'gas_consumption_error' },
255
- { id: 'applicable_rates_error_state', name: 'Applicable Rates Error State', val: 'applicable_rates_error' },
256
- { id: 'account_error_state', name: 'Account Error State', val: 'account_error' },
257
- { id: 'octoplus_error_state', name: 'Octoplus Error State', val: 'octoplus_error' },
258
- { id: 'wheel_of_fortune_error_state', name: 'Wheel of Fortune Error State', val: 'wheel_of_fortune_error' },
259
- { id: 'home_mini_error_state', name: 'Home Mini Error State', val: 'home_mini_error' },
260
- { id: 'saving_sessions_error_state', name: 'Saving Sessions Error State', val: 'saving_sessions_error' },
261
- { id: 'free_electricity_error_state', name: 'Free Electricity Error State', val: 'free_electricity_error' },
262
- { id: 'completed_dispatches_error_state', name: 'Completed Dispatches Error State', val: 'completed_dispatches_error' },
263
- { id: 'flex_planned_dispatches_error_state', name: 'Flex Planned Dispatches Error State', val: 'flex_planned_dispatches_error' },
264
- ];
265
-
266
- // 4. Helper: Announce Controls (Write-Enabled)
267
- function announceControls() {
268
- if (!enableMqtt || !node.broker) return;
269
-
270
- // Single device definition with branding
271
- const device = {
272
- identifiers: [`nodered_octopus_${account}`],
273
- name: "Octopus Intelligent",
274
- manufacturer: "Octopus Energy",
275
- model: "Intelligent Octopus Go",
276
- sw_version: "2.0.0",
277
- suggested_area: "Energy",
278
- configuration_url: "https://octopus.energy/intelligent/"
279
- };
280
-
281
- // A. The Slider (Number) - now shows pending value
282
- const limitConfig = {
283
- name: "Octopus Target Charge",
284
- unique_id: `${uniqueIdPrefix}_target_limit`,
285
- state_topic: stateTopic,
286
- command_topic: cmdTopicLimit,
287
- value_template: "{{ value_json.pending_limit }}",
288
- min: 50, max: 100, step: 5,
289
- unit_of_measurement: "%",
290
- icon: "mdi:battery-charging-high",
291
- device: device
292
- };
293
- node.broker.client.publish(`${mqttPrefix}/number/${uniqueIdPrefix}_limit/config`, JSON.stringify(limitConfig), { retain: true });
294
-
295
- // B. The Dropdown (Select) - now shows pending value
296
- const timeConfig = {
297
- name: "Octopus Ready Time",
298
- unique_id: `${uniqueIdPrefix}_target_time`,
299
- state_topic: stateTopic,
300
- command_topic: cmdTopicTime,
301
- value_template: "{{ value_json.pending_time }}",
302
- options: TIME_OPTIONS,
303
- icon: "mdi:clock-time-four-outline",
304
- device: device
305
- };
306
- node.broker.client.publish(`${mqttPrefix}/select/${uniqueIdPrefix}_time/config`, JSON.stringify(timeConfig), { retain: true });
307
-
308
- // C. Submit Button
309
- const buttonConfig = {
310
- name: "Octopus Apply Changes",
311
- unique_id: `${uniqueIdPrefix}_submit_button`,
312
- command_topic: cmdTopicSubmit,
313
- payload_press: "SUBMIT",
314
- icon: "mdi:check-circle",
315
- device_class: "update",
316
- device: device
317
- };
318
- node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
319
-
320
- // D. Refresh Button
321
- const refreshButtonConfig = {
322
- name: "Octopus Refresh API",
323
- unique_id: `${uniqueIdPrefix}_refresh_button`,
324
- command_topic: cmdTopicRefresh,
325
- payload_press: "REFRESH",
326
- icon: "mdi:refresh",
327
- device_class: "restart",
328
- device: device
329
- };
330
- node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_refresh/config`, JSON.stringify(refreshButtonConfig), { retain: true });
331
-
332
- // E. Add sensors for confirmed values (read-only display)
333
- const confirmedLimitSensor = {
334
- name: "Octopus Confirmed Charge Limit",
335
- unique_id: `${uniqueIdPrefix}_confirmed_limit`,
336
- state_topic: stateTopic,
337
- value_template: "{{ value_json.confirmed_limit }}",
338
- unit_of_measurement: "%",
339
- icon: "mdi:battery-check",
340
- device: device
341
- };
342
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_limit/config`, JSON.stringify(confirmedLimitSensor), { retain: true });
343
-
344
- const confirmedTimeSensor = {
345
- name: "Octopus Confirmed Ready Time",
346
- unique_id: `${uniqueIdPrefix}_confirmed_time`,
347
- state_topic: stateTopic,
348
- value_template: "{{ value_json.confirmed_time }}",
349
- icon: "mdi:clock-check",
350
- device: device
351
- };
352
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
353
-
354
- // G. Charging Now Binary Sensor (main sensor for automations)
355
- const chargingNowBinarySensor = {
356
- name: "Octopus Charging Now",
357
- unique_id: `${uniqueIdPrefix}_charging_now`,
358
- state_topic: `${stateTopic}/charging_now`,
359
- device_class: "battery_charging",
360
- payload_on: "ON",
361
- payload_off: "OFF",
362
- icon: "mdi:ev-station",
363
- device: device
364
- };
365
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
366
-
367
- // G2. Saving Session Available Binary Sensor
368
- const savingSessionBinarySensor = {
369
- name: "Octopus Saving Session Available",
370
- unique_id: `${uniqueIdPrefix}_saving_session_available`,
371
- state_topic: stateTopic,
372
- value_template: "{{ value_json.saving_session_available }}",
373
- payload_on: "True",
374
- payload_off: "False",
375
- icon: "mdi:lightning-bolt-circle",
376
- device: device
377
- };
378
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_available/config`, JSON.stringify(savingSessionBinarySensor), { retain: true });
379
-
380
- // G2a. Saving Session Window Active Binary Sensor (v1.3.3)
381
- const savingSessionWindowActiveSensor = {
382
- name: "Octopus Saving Session Window Active",
383
- unique_id: `${uniqueIdPrefix}_saving_session_window_active`,
384
- state_topic: stateTopic,
385
- value_template: "{{ value_json.saving_session_window_active }}",
386
- payload_on: "True",
387
- payload_off: "False",
388
- icon: "mdi:clock-check-outline",
389
- device: device
390
- };
391
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_window_active/config`, JSON.stringify(savingSessionWindowActiveSensor), { retain: true });
392
-
393
- // G2b. Saving Session Active Binary Sensor (v1.3.3) — joined AND in window
394
- const savingSessionActiveSensor = {
395
- name: "Octopus Saving Session Active",
396
- unique_id: `${uniqueIdPrefix}_saving_session_active`,
397
- state_topic: stateTopic,
398
- value_template: "{{ value_json.saving_session_active }}",
399
- payload_on: "True",
400
- payload_off: "False",
401
- icon: "mdi:home-export-outline",
402
- device: device
403
- };
404
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_active/config`, JSON.stringify(savingSessionActiveSensor), { retain: true });
405
-
406
- // G2c. v1.3.3 migration: delete the deprecated sensor.saving_session_joined
407
- // entity. HA's sensor domain doesn't render booleans cleanly. Empty
408
- // payload on the discovery topic with retain tells HA the entity no
409
- // longer exists. Safe to keep across releases.
410
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_saving_session_joined/config`, "", { retain: true });
411
-
412
- // G2d. Saving Session Joined Binary Sensor (v1.3.3 migration)
413
- const savingSessionJoinedSensor = {
414
- name: "Octopus Saving Session Joined",
415
- unique_id: `${uniqueIdPrefix}_saving_session_joined`,
416
- state_topic: stateTopic,
417
- value_template: "{{ value_json.saving_session_joined }}",
418
- payload_on: "True",
419
- payload_off: "False",
420
- icon: "mdi:account-check",
421
- device: device
422
- };
423
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_joined/config`, JSON.stringify(savingSessionJoinedSensor), { retain: true });
424
-
425
- // G3. Free Electricity Active Binary Sensor
426
- const freeElectricityActiveSensor = {
427
- name: "Octopus Free Electricity Active",
428
- unique_id: `${uniqueIdPrefix}_free_electricity_active`,
429
- state_topic: stateTopic,
430
- value_template: "{{ value_json.free_electricity_active }}",
431
- payload_on: "True",
432
- payload_off: "False",
433
- icon: "mdi:flash-circle",
434
- device: device
435
- };
436
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_active/config`, JSON.stringify(freeElectricityActiveSensor), { retain: true });
437
-
438
- // G4. Free Electricity Available Binary Sensor
439
- const freeElectricityAvailableSensor = {
440
- name: "Octopus Free Electricity Available",
441
- unique_id: `${uniqueIdPrefix}_free_electricity_available`,
442
- state_topic: stateTopic,
443
- value_template: "{{ value_json.free_electricity_available }}",
444
- payload_on: "True",
445
- payload_off: "False",
446
- icon: "mdi:flash-circle-outline",
447
- device: device
448
- };
449
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_available/config`, JSON.stringify(freeElectricityAvailableSensor), { retain: true });
450
-
451
- // G5. Octoplus Enrolled Binary Sensor
452
- // Published as binary_sensor (not sensor) because the value is a boolean —
453
- // HA's sensor domain rejects booleans without a device_class, leaving the
454
- // entity unregistered. No entity_category: 'config' on a read-only sensor
455
- // makes its state stick at "unavailable" on some HA installs (same fix as
456
- // the v1.3.0 tariff-sensor cleanup — see CHANGELOG).
457
- const octoplusEnrolledBinarySensor = {
458
- name: "Octopus Octoplus Enrolled",
459
- unique_id: `${uniqueIdPrefix}_octoplus_enrolled`,
460
- state_topic: stateTopic,
461
- value_template: "{{ value_json.octoplus_enrolled }}",
462
- payload_on: "True",
463
- payload_off: "False",
464
- icon: "mdi:star-circle",
465
- device: device
466
- };
467
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_enrolled/config`, JSON.stringify(octoplusEnrolledBinarySensor), { retain: true });
468
-
469
- // G6. Octoplus Loyalty Points (boolean) Binary Sensor
470
- // No entity_category — see G5.
471
- const octoplusLoyaltyBinarySensor = {
472
- name: "Octopus Octoplus Loyalty Points",
473
- unique_id: `${uniqueIdPrefix}_octoplus_loyalty_points_user`,
474
- state_topic: stateTopic,
475
- value_template: "{{ value_json.octoplus_loyalty_points_user }}",
476
- payload_on: "True",
477
- payload_off: "False",
478
- icon: "mdi:star",
479
- device: device
480
- };
481
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_loyalty_points_user/config`, JSON.stringify(octoplusLoyaltyBinarySensor), { retain: true });
482
-
483
- // H. Announce Read-Only Sensors
484
- sensors.forEach(sensor => {
485
- const payload = {
486
- name: `Octopus ${sensor.name}`,
487
- unique_id: `${uniqueIdPrefix}_${sensor.id}`,
488
- state_topic: stateTopic,
489
- value_template: `{{ value_json.${sensor.val} }}`,
490
- device: device
491
- };
492
- if (sensor.class) payload.device_class = sensor.class;
493
- if (sensor.unit) payload.unit_of_measurement = sensor.unit;
494
- if (sensor.stateClass) payload.state_class = sensor.stateClass;
495
- if (sensor.icon) payload.icon = sensor.icon;
496
-
497
- if (sensor.category) {
498
- payload.entity_category = sensor.category;
499
- }
500
-
501
- if (sensor.id === 'applicable_rates_count') {
502
- payload.json_attributes_topic = stateTopic;
503
- payload.json_attributes_template = '{ "rates": {{ value_json.applicable_rates | tojson }} }';
504
- } else if (sensor.id === 'electricity_export_rate_count') {
505
- payload.json_attributes_topic = stateTopic;
506
- payload.json_attributes_template = '{ "rates": {{ value_json.electricity_export_rate | tojson }} }';
507
- }
508
-
509
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
510
- });
511
-
512
- // H2. v1.5 — error binary_sensors (device_class: problem)
513
- errorSensors.forEach(e => {
514
- const payload = {
515
- name: `Octopus ${e.name}`,
516
- unique_id: `${uniqueIdPrefix}_${e.id}`,
517
- state_topic: stateTopic,
518
- value_template: `{{ 'OFF' if value_json.${e.val} in [None, ''] else 'ON' }}`,
519
- payload_on: 'ON',
520
- payload_off: 'OFF',
521
- device_class: 'problem',
522
- entity_category: 'diagnostic',
523
- device: device,
524
- };
525
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_${e.id}/config`, JSON.stringify(payload), { retain: true });
526
- });
527
-
528
- // I. Timezone Select Entity
529
- const TIMEZONE_OPTIONS = [
530
- "Europe/London", "Europe/Berlin", "Europe/Madrid",
531
- "Australia/Sydney", "Australia/Melbourne", "Australia/Brisbane",
532
- "Australia/Perth", "Australia/Adelaide", "Pacific/Auckland",
533
- "America/New_York", "America/Chicago", "America/Denver",
534
- "America/Los_Angeles", "Asia/Tokyo", "UTC"
535
- ];
536
- node.broker.client.publish(
537
- `${mqttPrefix}/select/${uniqueIdPrefix}_timezone/config`,
538
- JSON.stringify({
539
- name: "Timezone",
540
- unique_id: `${uniqueIdPrefix}_timezone`,
541
- options: TIMEZONE_OPTIONS,
542
- command_topic: cmdTopicTimezone,
543
- state_topic: `${stateTopic}/timezone`,
544
- icon: "mdi:earth",
545
- entity_category: "config",
546
- device: device
547
- }),
548
- { retain: true }
549
- );
550
-
551
- // J. Smart Charging Switch
552
- node.broker.client.publish(
553
- `${mqttPrefix}/switch/${uniqueIdPrefix}_smart_charging/config`,
554
- JSON.stringify({
555
- name: "Smart Charging",
556
- unique_id: `${uniqueIdPrefix}_smart_charging`,
557
- command_topic: cmdTopicSmartCharging,
558
- state_topic: `${stateTopic}/smart_charging`,
559
- payload_on: "ON",
560
- payload_off: "OFF",
561
- icon: "mdi:lightning-bolt",
562
- entity_category: "config",
563
- device: device
564
- }),
565
- { retain: true }
566
- );
567
-
568
- // K. v1.5 — Update entity (notify-only; Palette Manager is the install path)
569
- node.broker.client.publish(
570
- `${mqttPrefix}/update/${uniqueIdPrefix}_node_update/config`,
571
- JSON.stringify({
572
- name: 'Octopus Intelligent Node',
573
- unique_id: `${uniqueIdPrefix}_node_update`,
574
- state_topic: `${stateTopic}/node_update`,
575
- title: 'node-red-contrib-octopus-intelligent',
576
- release_url: 'https://github.com/ASomerN/node-red-contrib-octopus-intelligent/releases',
577
- device: device,
578
- }),
579
- { retain: true }
580
- );
581
-
582
- // Subscribe to Commands
583
- node.broker.client.subscribe(cmdTopicLimit);
584
- node.broker.client.subscribe(cmdTopicTime);
585
- node.broker.client.subscribe(cmdTopicSubmit);
586
- node.broker.client.subscribe(cmdTopicRefresh);
587
- node.broker.client.subscribe(cmdTopicTimezone);
588
- node.broker.client.subscribe(cmdTopicSmartCharging);
589
- }
590
-
591
- // 5. Helper: Set Preferences (The Mutation)
592
- let retryTimeouts = []; // Track pending retry timeouts
593
- let expectedLimit = null;
594
- let expectedTime = null;
595
- let validationMode = false;
596
-
597
- // Pending vs Confirmed state
598
- let pendingLimit = 80;
599
- let pendingTime = "08:00";
600
- let confirmedLimit = 80;
601
- let confirmedTime = "08:00";
602
-
603
- // Charging Now feature - timer-based state management
604
- let chargingNow = false;
605
- let preValidationTimer = null; // Fires 30s before slot start
606
- let slotStartTimer = null; // Fires at exact slot start
607
- let slotEndTimer = null; // Fires at exact slot end
608
- let cachedSlots = []; // Fresh slot data from pre-validation
609
- let stateCheckInterval = null; // Reconciliation loop (every 10s)
610
- let lastSentChargingState = null; // Track last sent state to avoid duplicates
611
-
612
- // Manual refresh rate limiting (only for MQTT button, not Node-RED input)
613
- let lastManualRefresh = 0; // Timestamp of last manual refresh
614
- const MANUAL_REFRESH_COOLDOWN = 30000; // 30 seconds in milliseconds
615
- let cooldownExpiryTimer = null; // Timer to clear cooldown state at expiry
616
-
617
- // Polling metrics
618
- let nextPollTime = null; // ISO timestamp of next scheduled poll
619
- const metrics = createApiMetrics();
620
-
621
- // API Complexity Tracking
622
- // Octopus Energy API does not return actual complexity values in headers or extensions,
623
- // so we use estimated complexity based on query types:
624
- // - Regular poll (auth + data query): ~300
625
- // - Mutation (auth + setPreferences): ~250
626
- // - Pre-validation (auth + flexPlannedDispatches only): ~200
627
-
628
- // Smart charging state (fetched once at startup)
629
- let krakenflexDeviceId = null;
630
- let smartChargingSuspended = null; // null=unknown, true=suspended(off), false=active(on)
631
- let smartChargingRetryTimeouts = [];
632
-
633
- // Last known full state - prevents sensors going unknown when controls change
634
- let lastKnownState = buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
635
- lastKnownState.installed_version = require('./package.json').version;
636
-
637
- // V2 category registry — populated after discovery
638
- let categories = [];
639
-
640
- // Lifecycle tracking — init setTimeouts must be clearable on close, and async
641
- // callbacks inside them must short-circuit if the node was closed mid-await,
642
- // otherwise a redeploy during the 2s warmup leaves an orphan V2 scheduler.
643
- let initTimeoutHandles = [];
644
- let nodeClosed = false;
645
- let lastWarnedVersion = null;
646
- let prevPublishedInstalled = null;
647
- let prevPublishedLatest = null;
648
-
649
- async function initCategories(discovered) {
650
- categories = [];
651
-
652
- if (discovered.hasIntelligent) {
653
- categories.push({
654
- id: 'intelligent',
655
- enabled: true,
656
- intervalMs: (config.refreshInterval || 5) * 60 * 1000,
657
- lastPolled: 0,
658
- poll: intelligentPoll,
659
- });
660
- }
661
-
662
- const electricityEnabled = config.electricityEnabled !== false;
663
- const gasEnabled = config.gasEnabled !== false;
664
-
665
- if (discovered.hasElectricity && electricityEnabled) {
666
- const ratesMs = (config.electricityRatesInterval || 60) * 60 * 1000;
667
- const consumptionMs = (config.electricityConsumptionInterval || 60) * 60 * 1000;
668
- categories.push({
669
- id: 'electricity_rates',
670
- enabled: true,
671
- intervalMs: ratesMs,
672
- lastPolled: 0,
673
- queryFn: () => electricityCategory.buildRatesQuery(account),
674
- parseFn: d => electricityCategory.parseRatesResponse(d),
675
- poll: simplePoll(
676
- () => electricityCategory.buildRatesQuery(account),
677
- d => electricityCategory.parseRatesResponse(d),
678
- graphqlPost
679
- ),
680
- });
681
- categories.push({
682
- id: 'electricity_consumption',
683
- enabled: true,
684
- intervalMs: consumptionMs,
685
- lastPolled: 0,
686
- queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
687
- parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
688
- poll: simplePoll(
689
- () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
690
- d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
691
- graphqlPost
692
- ),
693
- });
694
- }
695
-
696
- if (discovered.hasGas && gasEnabled) {
697
- const ratesMs = (config.gasRatesInterval || 60) * 60 * 1000;
698
- const consumptionMs = (config.gasConsumptionInterval || 60) * 60 * 1000;
699
- categories.push({
700
- id: 'gas_rates',
701
- enabled: true,
702
- intervalMs: ratesMs,
703
- lastPolled: 0,
704
- queryFn: () => gasCategory.buildRatesQuery(account),
705
- parseFn: d => gasCategory.parseRatesResponse(d),
706
- poll: simplePoll(
707
- () => gasCategory.buildRatesQuery(account),
708
- d => gasCategory.parseRatesResponse(d),
709
- graphqlPost
710
- ),
711
- });
712
- categories.push({
713
- id: 'gas_consumption',
714
- enabled: true,
715
- intervalMs: consumptionMs,
716
- lastPolled: 0,
717
- queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
718
- parseFn: d => gasCategory.parseConsumptionResponse(d),
719
- poll: simplePoll(
720
- () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
721
- d => gasCategory.parseConsumptionResponse(d),
722
- graphqlPost
723
- ),
724
- });
725
- }
726
-
727
- categories.push({
728
- id: 'wheel_of_fortune',
729
- enabled: config.enableWheelOfFortune || false,
730
- intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
731
- lastPolled: 0,
732
- queryFn: () => wheelOfFortuneCategory.buildQuery(account),
733
- parseFn: d => wheelOfFortuneCategory.parseResponse(d),
734
- poll: simplePoll(
735
- () => wheelOfFortuneCategory.buildQuery(account),
736
- d => wheelOfFortuneCategory.parseResponse(d),
737
- graphqlPost
738
- ),
739
- });
740
- if (discovered.smartMeterDeviceId) {
741
- categories.push({
742
- id: 'home_mini',
743
- enabled: config.enableHomeMini || false,
744
- intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
745
- lastPolled: 0,
746
- queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
747
- parseFn: d => homeMiniCategory.parseResponse(d),
748
- poll: simplePoll(
749
- () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
750
- d => homeMiniCategory.parseResponse(d),
751
- graphqlPost
752
- ),
753
- });
754
- }
755
- categories.push({
756
- id: 'saving_sessions',
757
- enabled: true,
758
- intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
759
- lastPolled: 0,
760
- queryFn: () => savingSessionsCategory.buildQuery(account),
761
- parseFn: d => savingSessionsCategory.parseResponse(d),
762
- poll: simplePoll(
763
- () => savingSessionsCategory.buildQuery(account),
764
- d => savingSessionsCategory.parseResponse(d),
765
- graphqlPost
766
- ),
767
- });
768
-
769
- if (discovered.hasIntelligent) {
770
- categories.push({
771
- id: 'completed_dispatches',
772
- enabled: true,
773
- intervalMs: 60 * 60 * 1000,
774
- lastPolled: 0,
775
- queryFn: () => completedDispatchesCategory.buildQuery(account),
776
- parseFn: d => completedDispatchesCategory.parseResponse(d),
777
- poll: simplePoll(
778
- () => completedDispatchesCategory.buildQuery(account),
779
- d => completedDispatchesCategory.parseResponse(d),
780
- graphqlPost
781
- ),
782
- });
783
- }
784
-
785
- if (discovered.hasElectricity && discovered.electricityMpan) {
786
- categories.push({
787
- id: 'applicable_rates',
788
- enabled: true,
789
- intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
790
- lastPolled: 0,
791
- queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
792
- parseFn: d => applicableRatesCategory.parseResponse(d),
793
- poll: simplePoll(
794
- () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
795
- d => applicableRatesCategory.parseResponse(d),
796
- graphqlPost
797
- ),
798
- });
799
- }
800
-
801
- // Export applicable rates — second query with the export MPAN. Same parser,
802
- // different field prefix so the output keys don't collide with import.
803
- if (discovered.hasElectricity && discovered.electricityExportMpan) {
804
- categories.push({
805
- id: 'applicable_rates_export',
806
- enabled: true,
807
- intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
808
- lastPolled: 0,
809
- queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
810
- parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
811
- poll: simplePoll(
812
- () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
813
- d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
814
- graphqlPost
815
- ),
816
- });
817
- }
818
-
819
- if (discovered.hasElectricity && discovered.electricityMpan) {
820
- categories.push({
821
- id: 'free_electricity',
822
- enabled: true,
823
- intervalMs: 30 * 60 * 1000, // 30 minutes
824
- lastPolled: 0,
825
- queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
826
- parseFn: d => freeElectricityCategory.parseResponse(d),
827
- poll: simplePoll(
828
- () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
829
- d => freeElectricityCategory.parseResponse(d),
830
- graphqlPost
831
- ),
832
- });
833
- }
834
-
835
- categories.push({
836
- id: 'account',
837
- enabled: true,
838
- intervalMs: 60 * 60 * 1000,
839
- lastPolled: 0,
840
- queryFn: () => accountCategory.buildQuery(account),
841
- parseFn: d => accountCategory.parseResponse(d),
842
- poll: simplePoll(
843
- () => accountCategory.buildQuery(account),
844
- d => accountCategory.parseResponse(d),
845
- graphqlPost
846
- ),
847
- });
848
-
849
- categories.push({
850
- id: 'octoplus',
851
- enabled: true,
852
- intervalMs: 60 * 60 * 1000,
853
- lastPolled: 0,
854
- queryFn: () => octoplusCategory.buildQuery(account),
855
- parseFn: d => octoplusCategory.parseResponse(d),
856
- poll: simplePoll(
857
- () => octoplusCategory.buildQuery(account),
858
- d => octoplusCategory.parseResponse(d),
859
- graphqlPost
860
- ),
861
- });
862
-
863
- categories.push({
864
- id: 'update_check',
865
- enabled: true,
866
- intervalMs: 24 * 60 * 60 * 1000, // 24h — once daily npm registry check
867
- lastPolled: 0, // fires on first scheduler tick
868
- poll: intelligentUpdateCheck, // token ignored
869
- });
870
- }
871
-
872
- async function pollDueCategories() {
873
- const result = await runTick({
874
- categories,
875
- state: lastKnownState,
876
- getToken: obtainTickToken,
877
- });
878
- if (!result.emitted) return;
879
- lastKnownState = result.state;
880
- if (enableMqtt && node.broker && node.broker.client) {
881
- node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
882
- // v1.5 — publish update entity state only when version values change
883
- if (prevPublishedInstalled !== lastKnownState.installed_version
884
- || prevPublishedLatest !== lastKnownState.latest_version) {
885
- const updateState = {
886
- installed_version: lastKnownState.installed_version,
887
- latest_version: lastKnownState.latest_version || lastKnownState.installed_version,
888
- };
889
- node.broker.client.publish(`${stateTopic}/node_update`, JSON.stringify(updateState), { retain: true });
890
- prevPublishedInstalled = lastKnownState.installed_version;
891
- prevPublishedLatest = lastKnownState.latest_version;
892
- }
893
- }
894
- node.send({ payload: lastKnownState });
895
- if (lastKnownState.update_available === true
896
- && lastKnownState.latest_version
897
- && lastKnownState.latest_version !== lastWarnedVersion) {
898
- node.warn(`Update available: v${lastKnownState.latest_version} (running v${lastKnownState.installed_version}). Install via Node-RED → Manage Palette → Upgrade.`);
899
- lastWarnedVersion = lastKnownState.latest_version;
900
- }
901
- if (!validationMode) {
902
- if (lastKnownState.intelligent_error) {
903
- node.status({ fill: "red", shape: "ring", text: `Error: ${String(lastKnownState.intelligent_error).slice(0, 40)}` });
904
- } else {
905
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
906
- }
907
- }
908
- }
909
-
910
- async function obtainTickToken() {
911
- const response = await graphqlPost({
912
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
913
- variables: { input: { APIKey: apiKey } },
914
- });
915
- if (!response.data.data || !response.data.data.obtainKrakenToken) {
916
- throw new Error('Auth response missing token: ' + JSON.stringify(response.data.errors || response.data));
917
- }
918
- return response.data.data.obtainKrakenToken.token;
919
- }
920
-
921
- function forceCategoryDue(id) {
922
- const cat = categories.find((c) => c.id === id);
923
- if (cat) cat.lastPolled = 0;
924
- }
925
-
926
- async function setPreferences(newLimit, newTime) {
927
- // Validation
928
- let limit = parseInt(newLimit);
929
- let time = newTime;
930
-
931
- // Enforce Limits
932
- if (isNaN(limit) || limit < 50) limit = 50;
933
- if (limit > 100) limit = 100;
934
- // Round to nearest 5
935
- limit = Math.round(limit / 5) * 5;
936
-
937
- // Validate Time
938
- if (!TIME_OPTIONS.includes(time)) {
939
- node.warn(`Invalid time '${time}' requested. Defaulting to 08:00`);
940
- time = "08:00";
941
- }
942
-
943
- // Cancel any pending retry attempts from previous changes
944
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
945
- retryTimeouts = [];
946
-
947
- try {
948
- node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
949
-
950
- // A. Get Token
951
- const authResponse = await graphqlPost({
952
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
953
- variables: { input: { APIKey: apiKey } }
954
- });
955
-
956
- if (authResponse.data.errors) {
957
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
958
- }
959
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
960
- throw new Error(`Auth response missing token data`);
961
- }
962
-
963
- const token = authResponse.data.data.obtainKrakenToken.token;
964
-
965
- // B. Send Mutation
966
- if (!krakenflexDeviceId) {
967
- throw new Error('Device ID not available — cannot set preferences');
968
- }
969
-
970
- const mutation = `
971
- mutation setPreferences($input: SmartFlexDevicePreferencesInput!) {
972
- setDevicePreferences(input: $input) { __typename }
973
- }`;
974
-
975
- const DAYS = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'];
976
- function buildDevicePreferencesInput(deviceId, socLimit, readyTime) {
977
- return {
978
- deviceId,
979
- mode: 'CHARGE',
980
- unit: 'PERCENTAGE',
981
- schedules: DAYS.map(dayOfWeek => ({
982
- dayOfWeek,
983
- time: readyTime + ':00',
984
- min: 0,
985
- max: socLimit
986
- }))
987
- };
988
- }
989
-
990
- const variables = {
991
- input: buildDevicePreferencesInput(krakenflexDeviceId, limit, time)
992
- };
993
-
994
- const mutationResponse = await graphqlPost({
995
- query: mutation,
996
- variables: variables
997
- }, token);
998
-
999
- if (mutationResponse.data.errors) {
1000
- throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
1001
- }
1002
-
1003
- // Record mutation API usage (auth + mutation = ~250 complexity)
1004
- const ESTIMATED_MUTATION_COMPLEXITY = 250;
1005
- metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
1006
-
1007
- // C. Start exponential backoff validation
1008
- expectedLimit = limit;
1009
- expectedTime = time;
1010
- validationMode = true;
1011
- node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
1012
-
1013
- // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
1014
- const retryIntervals = [15000, 30000, 60000, 120000];
1015
- scheduleRetries(retryIntervals, 0);
1016
-
1017
- } catch (err) {
1018
- node.error("Failed to set preferences: " + err.message);
1019
- if (err.response) {
1020
- node.error(`Response: ${JSON.stringify(err.response.data)}`);
1021
- }
1022
- node.status({ fill: "red", shape: "ring", text: "Update Failed" });
1023
- expectedLimit = null;
1024
- expectedTime = null;
1025
- validationMode = false;
1026
- }
1027
- }
1028
-
1029
- function scheduleRetries(intervals, index) {
1030
- if (index >= intervals.length) {
1031
- // All retries exhausted, let normal interval take over
1032
- node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
1033
- expectedLimit = null;
1034
- expectedTime = null;
1035
- validationMode = false;
1036
- return;
1037
- }
1038
-
1039
- const timeout = setTimeout(async () => {
1040
- await fetchDataWithValidation(intervals, index);
1041
- }, intervals[index]);
1042
-
1043
- retryTimeouts.push(timeout);
1044
- }
1045
-
1046
- async function fetchDataWithValidation(intervals, currentIndex) {
1047
- try {
1048
- const token = await obtainTickToken();
1049
- const partial = await intelligentPoll(token);
1050
- lastKnownState = Object.assign({}, lastKnownState, partial, { intelligent_error: null });
1051
- if (enableMqtt && node.broker && node.broker.client) {
1052
- node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
1053
- }
1054
- node.send({ payload: lastKnownState });
1055
-
1056
- const validated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
1057
- if (validated) {
1058
- validationMode = false;
1059
- retryTimeouts.forEach((t) => clearTimeout(t));
1060
- retryTimeouts = [];
1061
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
1062
- return;
1063
- }
1064
- const totalAttempts = intervals.length;
1065
- const attempt = currentIndex + 1;
1066
- if (currentIndex < intervals.length - 1) {
1067
- node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
1068
- scheduleRetries(intervals, currentIndex + 1);
1069
- } else {
1070
- validationMode = false;
1071
- node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
1072
- }
1073
- } catch (error) {
1074
- node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
1075
- if (currentIndex < intervals.length - 1) {
1076
- scheduleRetries(intervals, currentIndex + 1);
1077
- } else {
1078
- validationMode = false;
1079
- node.status({ fill: "red", shape: "ring", text: "Validation failed" });
1080
- }
1081
- }
1082
- }
1083
-
1084
- // Helper: Toggle smart charging on/off
1085
- async function setSmartCharging(enable) {
1086
- if (!krakenflexDeviceId) {
1087
- node.warn("Device ID not available — cannot toggle smart charging");
1088
- return;
1089
- }
1090
-
1091
- // Cancel any pending verification retries
1092
- smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1093
- smartChargingRetryTimeouts = [];
1094
-
1095
- const previousSuspended = smartChargingSuspended;
1096
-
1097
- try {
1098
- node.status({ fill: "blue", shape: "dot", text: enable ? "Enabling smart charging..." : "Suspending smart charging..." });
1099
-
1100
- const authResponse = await graphqlPost({
1101
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1102
- variables: { input: { APIKey: apiKey } }
1103
- });
1104
- if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1105
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1106
- }
1107
- const token = authResponse.data.data.obtainKrakenToken.token;
1108
-
1109
- const action = enable ? "UNSUSPEND" : "SUSPEND";
1110
- const mutationResponse = await graphqlPost({
1111
- query: `mutation UpdateSmartControl($deviceId: ID!, $action: SmartControlAction!) { updateDeviceSmartControl(input: { deviceId: $deviceId, action: $action }) { id } }`,
1112
- variables: { deviceId: krakenflexDeviceId, action: action }
1113
- }, token);
1114
-
1115
- if (mutationResponse.data.errors) {
1116
- throw new Error(`Smart charging mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
1117
- }
1118
-
1119
- // Record mutation API usage (auth + mutation = ~250 complexity)
1120
- const ESTIMATED_MUTATION_COMPLEXITY = 250;
1121
- metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
1122
-
1123
- // Optimistically update cached state
1124
- const expectedSuspended = !enable;
1125
- smartChargingSuspended = expectedSuspended;
1126
-
1127
- // Publish new state to HA switch topic immediately
1128
- if (enableMqtt && node.broker && node.broker.client) {
1129
- node.broker.client.publish(`${stateTopic}/smart_charging`, enable ? "ON" : "OFF", { retain: true });
1130
- }
1131
-
1132
- // Schedule verification: 15s / 30s / 60s / 120s
1133
- scheduleSmartChargingVerification(expectedSuspended, [15000, 30000, 60000, 120000], 0);
1134
-
1135
- } catch (e) {
1136
- node.error(`Failed to toggle smart charging: ${e.message}`);
1137
- // Revert optimistic update to pre-mutation state
1138
- smartChargingSuspended = previousSuspended;
1139
- node.status({ fill: "red", shape: "ring", text: "Smart charging update failed" });
1140
- // Republish previous state so HA switch UI re-syncs
1141
- if (enableMqtt && node.broker && node.broker.client && previousSuspended !== null) {
1142
- node.broker.client.publish(
1143
- `${stateTopic}/smart_charging`,
1144
- previousSuspended ? "OFF" : "ON",
1145
- { retain: true }
1146
- );
1147
- }
1148
- }
1149
- }
1150
-
1151
- function scheduleSmartChargingVerification(expectedSuspended, intervals, index) {
1152
- if (index >= intervals.length) {
1153
- node.warn("Smart charging state could not be confirmed after all retries");
1154
- node.status({ fill: "red", shape: "ring", text: "Smart charging: update unconfirmed" });
1155
- return;
1156
- }
1157
- const timeout = setTimeout(async () => {
1158
- try {
1159
- const authResponse = await graphqlPost({
1160
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1161
- variables: { input: { APIKey: apiKey } }
1162
- });
1163
- if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1164
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1165
- return;
1166
- }
1167
- const token = authResponse.data.data.obtainKrakenToken.token;
1168
-
1169
- const deviceResponse = await graphqlPost({
1170
- query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1171
- variables: { accountNumber: account }
1172
- }, token);
1173
-
1174
- if (deviceResponse.data.errors || !deviceResponse.data.data) {
1175
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1176
- return;
1177
- }
1178
-
1179
- const evDevice = (deviceResponse.data.data.devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES');
1180
- if (!evDevice) {
1181
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1182
- return;
1183
- }
1184
-
1185
- // Record verification API usage (auth + device query = ~200 complexity)
1186
- const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
1187
- metrics.recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
1188
-
1189
- const actualSuspended = evDevice.status.isSuspended;
1190
- if (actualSuspended === expectedSuspended) {
1191
- // Confirmed — clear remaining retries
1192
- smartChargingSuspended = actualSuspended;
1193
- smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1194
- smartChargingRetryTimeouts = [];
1195
- node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
1196
- node.status({ fill: "green", shape: "dot", text: actualSuspended ? "Smart charging suspended" : "Smart charging enabled" });
1197
- } else {
1198
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1199
- }
1200
- } catch (e) {
1201
- node.warn(`Smart charging verification attempt ${index + 1} failed: ${e.message}`);
1202
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1203
- }
1204
- }, intervals[index]);
1205
- smartChargingRetryTimeouts.push(timeout);
1206
- }
1207
-
1208
- // 6. Logic: Update Check (bespoke poll that ignores token)
1209
- async function intelligentUpdateCheck(/* token ignored */) {
1210
- return checkUpdate(httpGetJson, require('./package.json').version);
1211
- }
1212
-
1213
- // 6. Logic: Intelligent Poll (single-scheduler bespoke poll)
1214
- async function intelligentPoll(token) {
1215
- // 1. devices query
1216
- const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
1217
- const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
1218
- if (devicesResponse.data.errors) throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
1219
- if (!devicesResponse.data.data) throw new Error('Devices response missing data');
1220
- const devicesData = devicesResponse.data.data;
1221
- const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
1222
- if (!evDevice) throw new Error('No ELECTRIC_VEHICLES device found on account');
1223
- krakenflexDeviceId = evDevice.id;
1224
-
1225
- // 2. dispatches query (the single one that used to be duplicated by V1 + V2)
1226
- const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
1227
- const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
1228
- if (dispatchResponse.data.errors) throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
1229
- if (!dispatchResponse.data.data) throw new Error('Dispatches response missing data');
1230
-
1231
- // 3. parse twice — intelligent (slots/window) + flex-planned-dispatches (array/count)
1232
- const data = { devices: devicesData.devices, flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
1233
- const appliedTz = resolveTimezone(node);
1234
- const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (e) { return 'UTC'; } })();
1235
- const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
1236
- const { _activeSlots, ...catPublic } = catResult;
1237
- const flexResult = flexPlannedDispatchesCategory.parseResponse(dispatchResponse.data.data);
1238
-
1239
- // 4. metrics + side effects
1240
- metrics.recordPoll(300);
1241
- confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
1242
- confirmedTime = catResult.confirmed_time || confirmedTime;
1243
- if (!validationMode) {
1244
- pendingLimit = confirmedLimit;
1245
- pendingTime = confirmedTime;
1246
- }
1247
- setupChargingTimers(_activeSlots);
1248
- if (!stateCheckInterval) startStateReconciliation();
1249
- updateNextPollTime();
1250
-
1251
- const apiMetrics = metrics.getMetrics();
1252
-
1253
- // 5. merged partial payload
1254
- return Object.assign({}, catPublic, flexResult, {
1255
- pending_limit: pendingLimit,
1256
- pending_time: pendingTime,
1257
- charging_now: chargingNow,
1258
- next_poll: nextPollTime,
1259
- next_poll_raw: nextPollTime,
1260
- refresh_available_at: getRefreshAvailableAt(),
1261
- api_requests_hour: apiMetrics.requests_last_hour,
1262
- api_complexity_hour: apiMetrics.complexity_last_hour,
1263
- api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
1264
- timezone_detected: serverTz,
1265
- timezone_applied: appliedTz,
1266
- smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
1267
- });
1268
- }
1269
-
1270
-
1271
- // Helper: Fetch device ID and initial smart charging state (called once at startup)
1272
- async function fetchDeviceId() {
1273
- try {
1274
- const authResponse = await graphqlPost({
1275
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1276
- variables: { input: { APIKey: apiKey } }
1277
- });
1278
- if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1279
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1280
- }
1281
- const token = authResponse.data.data.obtainKrakenToken.token;
1282
-
1283
- const deviceResponse = await graphqlPost({
1284
- query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1285
- variables: { accountNumber: account }
1286
- }, token);
1287
-
1288
- if (deviceResponse.data.errors || !deviceResponse.data.data) {
1289
- throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
1290
- }
1291
-
1292
- function extractEvDevice(devices) {
1293
- return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
1294
- }
1295
-
1296
- const evDevice = extractEvDevice(deviceResponse.data.data.devices);
1297
- if (!evDevice) {
1298
- throw new Error('No ELECTRIC_VEHICLES device found on account');
1299
- }
1300
-
1301
- krakenflexDeviceId = evDevice.id;
1302
- smartChargingSuspended = evDevice.status.isSuspended;
1303
- node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
1304
- } catch (e) {
1305
- node.warn(`Failed to fetch device ID at startup: ${e.message}. Smart charging toggle unavailable.`);
1306
- krakenflexDeviceId = null;
1307
- smartChargingSuspended = null;
1308
- }
1309
- }
1310
-
1311
- // 6a. Charging Now - Timer Management Functions
1312
-
1313
- // State reconciliation - checks every 10s if charging state matches reality
1314
- function reconcileChargingState() {
1315
- if (!cachedSlots || cachedSlots.length === 0) return;
1316
-
1317
- const now = new Date();
1318
-
1319
- // Check if we should be charging RIGHT NOW based on cached slots
1320
- const shouldBeCharging = cachedSlots.some(slot => {
1321
- const start = new Date(slot.start);
1322
- const end = new Date(slot.end);
1323
- return start <= now && end > now;
1324
- });
1325
-
1326
- // Update state if it doesn't match reality
1327
- if (shouldBeCharging !== chargingNow) {
1328
- node.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
1329
- publishChargingState(shouldBeCharging);
1330
- }
1331
- }
1332
-
1333
- // Start state reconciliation loop (every 10 seconds)
1334
- function startStateReconciliation() {
1335
- // Clear existing interval
1336
- if (stateCheckInterval) {
1337
- clearInterval(stateCheckInterval);
1338
- }
1339
-
1340
- // Check state every 10 seconds
1341
- stateCheckInterval = setInterval(() => {
1342
- reconcileChargingState();
1343
- }, 10000);
1344
-
1345
- node.log("State reconciliation loop started (every 10s)");
1346
- }
1347
-
1348
- // Clear all charging timers
1349
- function clearChargingTimers() {
1350
- if (preValidationTimer) {
1351
- clearTimeout(preValidationTimer);
1352
- preValidationTimer = null;
1353
- }
1354
- if (slotStartTimer) {
1355
- clearTimeout(slotStartTimer);
1356
- slotStartTimer = null;
1357
- }
1358
- if (slotEndTimer) {
1359
- clearTimeout(slotEndTimer);
1360
- slotEndTimer = null;
1361
- }
1362
- if (stateCheckInterval) {
1363
- clearInterval(stateCheckInterval);
1364
- stateCheckInterval = null;
1365
- }
1366
- }
1367
-
1368
- // Manual refresh rate limiting helpers
1369
- function canManualRefresh() {
1370
- const now = Date.now();
1371
- const timeSinceLastRefresh = now - lastManualRefresh;
1372
- return lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN;
1373
- }
1374
-
1375
- function getSecondsUntilNextRefresh() {
1376
- const now = Date.now();
1377
- const timeSinceLastRefresh = now - lastManualRefresh;
1378
- const timeRemaining = MANUAL_REFRESH_COOLDOWN - timeSinceLastRefresh;
1379
- return Math.max(0, Math.ceil(timeRemaining / 1000));
1380
- }
1381
-
1382
- function getRefreshAvailableAt() {
1383
- const now = Date.now();
1384
- const timeSinceLastRefresh = now - lastManualRefresh;
1385
-
1386
- // If never refreshed OR cooldown expired, ready now
1387
- if (lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN) {
1388
- return null; // Ready - no cooldown
1389
- }
1390
-
1391
- // Cooldown active - return timestamp when it expires
1392
- return new Date(lastManualRefresh + MANUAL_REFRESH_COOLDOWN).toISOString();
1393
- }
1394
-
1395
- function publishRefreshCooldownState() {
1396
- if (enableMqtt && node.broker) {
1397
- const fullState = {
1398
- ...lastKnownState,
1399
- refresh_available_at: getRefreshAvailableAt()
1400
- };
1401
- node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: true });
1402
- }
1403
- }
1404
-
1405
- // Polling metrics helpers
1406
- function updateNextPollTime() {
1407
- nextPollTime = new Date(Date.now() + refreshRate).toISOString();
1408
- }
1409
-
1410
- // Publish charging state to MQTT and Node-RED
1411
- function publishChargingState(state) {
1412
- chargingNow = state;
1413
-
1414
- // Update MQTT
1415
- if (enableMqtt && node.broker) {
1416
- const payload = state ? "ON" : "OFF";
1417
- node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
1418
- }
1419
-
1420
- // Output message to Node-RED flow if state actually changed
1421
- if (lastSentChargingState !== state) {
1422
- lastSentChargingState = state;
1423
-
1424
- // Merge updated charging_now into last known full state
1425
- const outputPayload = {
1426
- ...lastKnownState,
1427
- charging_now: state
1428
- };
1429
-
1430
- node.send({
1431
- payload: outputPayload,
1432
- debug: {
1433
- timestamp: new Date().toISOString(),
1434
- trigger: 'charging_state_change',
1435
- success: true,
1436
- previous_state: !state,
1437
- new_state: state
1438
- }
1439
- });
1440
-
1441
- node.log(`Charging state changed: ${!state} → ${state}, message sent`);
1442
- }
1443
- }
1444
-
1445
- // Setup pre-validation timer (30s before slot starts)
1446
- function setupPreValidationTimer(nextSlot) {
1447
- const now = new Date();
1448
- const slotStart = new Date(nextSlot.start);
1449
- const preValidationTime = slotStart.getTime() - 30000; // 30s before
1450
- const msUntilPreValidation = preValidationTime - now.getTime();
1451
-
1452
- if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
1453
- preValidationTimer = setTimeout(async () => {
1454
- node.warn("Pre-validating slot data (30s before start)");
1455
- try {
1456
- if (!krakenflexDeviceId) {
1457
- throw new Error("Device ID not available for pre-validation");
1458
- }
1459
-
1460
- const authResponse = await graphqlPost({
1461
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1462
- variables: { input: { APIKey: apiKey } }
1463
- });
1464
-
1465
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1466
- throw new Error("Pre-validation auth failed");
1467
- }
1468
-
1469
- const token = authResponse.data.data.obtainKrakenToken.token;
1470
-
1471
- const { query: dq, variables: dv } = intelligentCategory.buildDispatchQuery(krakenflexDeviceId);
1472
- const dataResponse = await graphqlPost({ query: dq, variables: dv }, token);
1473
-
1474
- if (dataResponse.data.data && dataResponse.data.data.flexPlannedDispatches) {
1475
- cachedSlots = dataResponse.data.data.flexPlannedDispatches;
1476
-
1477
- // Record pre-validation API usage (auth + simple query = ~200 complexity)
1478
- const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
1479
- metrics.recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
1480
-
1481
- // Check if slot still exists (within 1 minute tolerance)
1482
- const stillExists = cachedSlots.find(s =>
1483
- Math.abs(new Date(s.start).getTime() - slotStart.getTime()) < 60000
1484
- );
1485
-
1486
- if (stillExists) {
1487
- node.warn(`Slot confirmed at ${stillExists.start}`);
1488
- setupSlotStartTimer(stillExists);
1489
- } else {
1490
- node.warn("Slot was cancelled or modified - not setting start timer");
1491
- }
1492
- }
1493
- } catch (error) {
1494
- node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
1495
- // Fallback: use original slot data
1496
- setupSlotStartTimer(nextSlot);
1497
- }
1498
- }, msUntilPreValidation);
1499
-
1500
- const minutesUntil = Math.round(msUntilPreValidation / 60000);
1501
- node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
1502
- }
1503
- }
1504
-
1505
- // Setup slot start timer (exact start time)
1506
- function setupSlotStartTimer(slot) {
1507
- const now = new Date();
1508
- const slotStart = new Date(slot.start);
1509
- const msUntilStart = slotStart.getTime() - now.getTime();
1510
-
1511
- if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
1512
- slotStartTimer = setTimeout(() => {
1513
- publishChargingState(true);
1514
- node.warn(`Charging slot started at ${slot.start}`);
1515
- setupSlotEndTimer(slot);
1516
- }, msUntilStart);
1517
-
1518
- const secondsUntil = Math.round(msUntilStart / 1000);
1519
- node.log(`Slot start timer set for ${secondsUntil}s (${slot.start})`);
1520
- } else if (msUntilStart <= 0) {
1521
- // Slot already started, check if it's still active
1522
- const slotEnd = new Date(slot.end);
1523
- if (slotEnd > now) {
1524
- publishChargingState(true);
1525
- setupSlotEndTimer(slot);
1526
- }
1527
- }
1528
- }
1529
-
1530
- // Setup slot end timer (exact end time)
1531
- function setupSlotEndTimer(slot) {
1532
- const now = new Date();
1533
- const slotEnd = new Date(slot.end);
1534
- const msUntilEnd = slotEnd.getTime() - now.getTime();
1535
-
1536
- if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
1537
- slotEndTimer = setTimeout(() => {
1538
- node.warn(`Charging slot ended at ${slot.end}`);
1539
-
1540
- // Check if another slot starts immediately (within cached data)
1541
- const now = new Date();
1542
- const immediateNextSlot = cachedSlots.find(s => {
1543
- const start = new Date(s.start);
1544
- const end = new Date(s.end);
1545
- return start <= now && end > now;
1546
- });
1547
-
1548
- if (immediateNextSlot) {
1549
- node.warn("Next slot starting immediately");
1550
- publishChargingState(true);
1551
- setupSlotEndTimer(immediateNextSlot);
1552
- } else {
1553
- publishChargingState(false);
1554
- }
1555
- }, msUntilEnd);
1556
-
1557
- const minutesUntil = Math.round(msUntilEnd / 60000);
1558
- node.log(`Slot end timer set for ${minutesUntil} min (${slot.end})`);
1559
- }
1560
- }
1561
-
1562
- // Main timer setup - called on each poll
1563
- function setupChargingTimers(slots) {
1564
- // Clear existing timers
1565
- clearChargingTimers();
1566
-
1567
- // Cache slots for later use
1568
- cachedSlots = slots;
1569
-
1570
- const now = new Date();
1571
-
1572
- // Check if currently in a charging slot
1573
- const activeSlot = slots.find(s => {
1574
- const start = new Date(s.start);
1575
- const end = new Date(s.end);
1576
- return start <= now && end > now;
1577
- });
1578
-
1579
- if (activeSlot) {
1580
- // Currently charging
1581
- const newState = true;
1582
- if (chargingNow !== newState) {
1583
- publishChargingState(newState);
1584
- }
1585
- setupSlotEndTimer(activeSlot);
1586
- node.log("Currently charging - end timer set");
1587
- } else {
1588
- // Not currently charging
1589
- const newState = false;
1590
- if (chargingNow !== newState) {
1591
- publishChargingState(newState);
1592
- }
1593
-
1594
- // Find next future slot
1595
- const nextSlot = slots.find(s => new Date(s.start) > now);
1596
-
1597
- if (nextSlot) {
1598
- setupPreValidationTimer(nextSlot);
1599
- node.log(`Next slot at ${nextSlot.start}`);
1600
- }
1601
- }
1602
- }
1603
-
1604
- // 7. Event Listeners
1605
-
1606
- // Helper: Publish current state (both pending and confirmed)
1607
- // This merges pending values into last known full state to prevent sensors going unknown
1608
- function publishCurrentState() {
1609
- if (enableMqtt && node.broker) {
1610
- // Merge pending values into last known state
1611
- const fullState = {
1612
- ...lastKnownState,
1613
- pending_limit: pendingLimit,
1614
- pending_time: pendingTime,
1615
- confirmed_limit: confirmedLimit,
1616
- confirmed_time: confirmedTime
1617
- };
1618
- node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: false });
1619
- }
1620
- }
1621
-
1622
- // A. Handle Node-RED Input Messages (NO rate limiting - programmers control this)
1623
- node.on('input', function (msg) {
1624
- // Check for control commands (preference updates)
1625
- if (msg.payload && typeof msg.payload === 'object') {
1626
- if (msg.payload.set_limit || msg.payload.set_time) {
1627
- // Use new values if present, otherwise keep existing
1628
- const targetLimit = msg.payload.set_limit || confirmedLimit;
1629
- const targetTime = msg.payload.set_time || confirmedTime;
1630
- setPreferences(targetLimit, targetTime);
1631
- return; // Don't run standard fetch if setting
1632
- }
1633
- if (msg.payload.set_timezone !== undefined) {
1634
- const tz = msg.payload.set_timezone;
1635
- if (typeof tz === 'string' && tz.trim().length > 0) {
1636
- node.context().set('timezone', tz.trim());
1637
- node.log(`Timezone set to: ${tz.trim()}`);
1638
- }
1639
- return;
1640
- }
1641
- if (msg.payload.set_smart_charging !== undefined) {
1642
- const val = msg.payload.set_smart_charging;
1643
- if (typeof val === 'boolean') {
1644
- setSmartCharging(val);
1645
- }
1646
- // silently ignore non-boolean (consistent with other handlers)
1647
- return;
1648
- }
1649
- }
1650
-
1651
- // Manual refresh request from Node-RED - NO rate limiting
1652
- // (Programmers can control rate limiting in their flows if needed)
1653
- // Update timestamp so HA sees cooldown, but don't block the refresh
1654
- lastManualRefresh = Date.now();
1655
- node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1656
- forceCategoryDue('intelligent');
1657
- });
1658
-
1659
- // B. Handle MQTT Commands (Home Assistant)
1660
- if (enableMqtt && node.broker) {
1661
- node.broker.register(this);
1662
-
1663
- // Slider changed - update pending value only
1664
- node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
1665
- const val = parseInt(payload.toString());
1666
- pendingLimit = val;
1667
- publishCurrentState(); // Update display immediately
1668
- node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1669
- });
1670
-
1671
- // Dropdown changed - update pending value only
1672
- node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
1673
- const val = payload.toString();
1674
- pendingTime = val;
1675
- publishCurrentState(); // Update display immediately
1676
- node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1677
- });
1678
-
1679
- // Button pressed - submit changes to API
1680
- node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
1681
- setPreferences(pendingLimit, pendingTime);
1682
- });
1683
-
1684
- // Refresh button pressed - MQTT has hardcoded 30s rate limiting
1685
- node.broker.subscribe(cmdTopicRefresh, 0, (topic, payload) => {
1686
- // Check rate limit (only for MQTT button)
1687
- if (!canManualRefresh()) {
1688
- const secondsRemaining = getSecondsUntilNextRefresh();
1689
- node.status({
1690
- fill: "red",
1691
- shape: "dot",
1692
- text: `Cooldown: ${secondsRemaining}s`
1693
- });
1694
- node.warn(`MQTT refresh blocked. Please wait ${secondsRemaining} seconds.`);
1695
- return; // Block the refresh
1696
- }
1697
-
1698
- // Refresh allowed - set cooldown timestamp
1699
- lastManualRefresh = Date.now();
1700
-
1701
- // Publish immediate update with countdown timestamp
1702
- publishRefreshCooldownState();
1703
-
1704
- // Schedule cleanup at exactly 30 seconds to clear countdown
1705
- if (cooldownExpiryTimer) clearTimeout(cooldownExpiryTimer);
1706
- cooldownExpiryTimer = setTimeout(() => {
1707
- // Cooldown expired - publish null to clear countdown in HA
1708
- publishRefreshCooldownState();
1709
- cooldownExpiryTimer = null;
1710
- }, MANUAL_REFRESH_COOLDOWN);
1711
-
1712
- // Trigger the actual refresh
1713
- node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1714
- forceCategoryDue('intelligent');
1715
- });
1716
-
1717
- // Timezone select changed in Home Assistant
1718
- node.broker.subscribe(cmdTopicTimezone, 0, (topic, payload) => {
1719
- const tz = payload.toString().trim();
1720
- if (tz.length > 0) {
1721
- node.context().set('timezone', tz);
1722
- node.log(`Timezone set via MQTT to: ${tz}`);
1723
- node.broker.client.publish(`${stateTopic}/timezone`, tz, { retain: true });
1724
- }
1725
- });
1726
-
1727
- // Smart charging switch toggled in Home Assistant
1728
- node.broker.subscribe(cmdTopicSmartCharging, 0, (topic, payload) => {
1729
- const val = payload.toString().trim();
1730
- if (val === "ON") setSmartCharging(true);
1731
- else if (val === "OFF") setSmartCharging(false);
1732
- });
1733
-
1734
- initTimeoutHandles.push(setTimeout(announceControls, 2000));
1735
-
1736
- // Republish persisted timezone to HA select on startup
1737
- initTimeoutHandles.push(setTimeout(() => {
1738
- try {
1739
- const persistedTz = node.context().get('timezone');
1740
- if (persistedTz && node.broker) {
1741
- node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
1742
- }
1743
- } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
1744
- }, 2500));
1745
-
1746
- // Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
1747
- initTimeoutHandles.push(setTimeout(() => {
1748
- try {
1749
- if (smartChargingSuspended !== null && node.broker && node.broker.client) {
1750
- const stateVal = smartChargingSuspended ? "OFF" : "ON";
1751
- node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
1752
- }
1753
- } catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
1754
- }, 3000));
1755
- }
1756
-
1757
- // Init
1758
- initTimeoutHandles.push(setTimeout(fetchDeviceId, 1500));
1759
-
1760
- // V2 category discovery and scheduler. Tracked + nodeClosed-guarded so that a
1761
- // node redeploy during the 2s warmup (or during the async discovery/init) can
1762
- // never leave an orphan scheduler running.
1763
- initTimeoutHandles.push(setTimeout(async () => {
1764
- try {
1765
- const discovered = await discoverProducts(apiKey, account);
1766
- if (nodeClosed) return;
1767
- if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
1768
- smartChargingSuspended = discovered.deviceSuspended;
1769
- lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
1770
- }
1771
- await initCategories(discovered);
1772
- if (nodeClosed) return;
1773
- node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}`);
1774
- const v2Scheduler = createScheduler(pollDueCategories);
1775
- v2Scheduler.start();
1776
- node._v2Scheduler = v2Scheduler;
1777
- } catch (e) {
1778
- node.warn(`V2 discovery failed: ${e.message}. New categories unavailable.`);
1779
- }
1780
- }, 2000));
1781
-
1782
- node.on('close', () => {
1783
- nodeClosed = true;
1784
- // Clear init setTimeouts so a redeploy during warmup can't leave an orphan scheduler
1785
- initTimeoutHandles.forEach(h => clearTimeout(h));
1786
- initTimeoutHandles = [];
1787
- // Clear any pending retry timeouts
1788
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
1789
- retryTimeouts = [];
1790
- // Clear smart charging retry timeouts
1791
- smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1792
- smartChargingRetryTimeouts = [];
1793
- // Clear charging timers
1794
- clearChargingTimers();
1795
- // Clear cooldown expiry timer
1796
- if (cooldownExpiryTimer) {
1797
- clearTimeout(cooldownExpiryTimer);
1798
- cooldownExpiryTimer = null;
1799
- }
1800
- if (node._v2Scheduler) node._v2Scheduler.stop();
1801
- if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging);
1802
- });
1803
- }
1804
-
1805
- RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
1806
- credentials: { apiKey: { type: "password" } }
1807
- });
1
+ 'use strict';
2
+ const { graphqlPost } = require('./lib/graphql');
3
+ const { onlyDeviceFieldErrors, graphqlError, errorCode, truncate, maskSecretsDeep, isUnconfirmedWriteError } = require('./lib/graphql-errors');
4
+
5
+ // Kraken: "Your device charging preferences could not be fetched" (devices.preferences).
6
+ const PREFERENCES_ERROR_CODE = 'KT-CT-4339';
7
+ // Device fields of the charging poll whose errors are tolerated (aliases in DEVICES_QUERY).
8
+ const TOLERATED_DEVICE_FIELDS = ['preferences', 'chargeCap', 'smartStatus'];
9
+ const { convertToTimezone, resolveTimezone, validateTimezone } = require('./lib/timezone');
10
+ const { createApiMetrics } = require('./lib/api-metrics');
11
+ const intelligentCategory = require('./lib/categories/intelligent');
12
+ const { buildDefaultPayload } = require('./lib/payload');
13
+ const { createScheduler } = require('./lib/scheduler');
14
+ const { retryDelay, isRetryable, nextSlotStart, createRateWindow, formatDuration } = require('./lib/poll-retry');
15
+ const { discoveryRetryDelay, EMPTY_DEVICES_MAX_RETRIES } = require('./lib/discovery-retry');
16
+ const { simplePoll, runTick } = require('./lib/poll-tick');
17
+ const { discoverProducts } = require('./lib/discovery');
18
+ const { mergePayload } = require('./lib/payload');
19
+ const electricityCategory = require('./lib/categories/electricity');
20
+ const gasCategory = require('./lib/categories/gas');
21
+ const wheelOfFortuneCategory = require('./lib/categories/wheel-of-fortune');
22
+ const homeMiniCategory = require('./lib/categories/home-mini');
23
+ const completedDispatchesCategory = require('./lib/categories/completed-dispatches');
24
+ const accountCategory = require('./lib/categories/account');
25
+ const octoplusCategory = require('./lib/categories/octoplus');
26
+ const flexPlannedDispatchesCategory = require('./lib/categories/flex-planned-dispatches');
27
+ const applicableRatesCategory = require('./lib/categories/applicable-rates');
28
+ const savingSessionsCategory = require('./lib/categories/saving-sessions');
29
+ const freeElectricityCategory = require('./lib/categories/free-electricity');
30
+ const smartflexVehicleCategory = require('./lib/categories/smartflex-vehicle');
31
+ const smartflexInverterCategory = require('./lib/categories/smartflex-inverter');
32
+ const httpGetJson = require('./lib/http-get-json');
33
+ const { TIME_OPTIONS, validateTime, validateLimit } = require('./lib/preferences');
34
+ const { planCommands } = require('./lib/commands');
35
+ const { buildBoostRequest, parseBoostResponse, chargingNowFor, reconcileChargingNow } = require('./lib/boost');
36
+ const { checkUpdate } = require('./lib/update-check');
37
+ const {
38
+ sensors, errorSensors, vehicleSensors, vehicleErrorSensors, inverterSensors, inverterErrorSensors,
39
+ } = require('./lib/sensor-definitions');
40
+ const { changedActiveFields } = require('./lib/active-now');
41
+
42
+ module.exports = function (RED) {
43
+ function OctopusIntelligentNode(config) {
44
+ RED.nodes.createNode(this, config);
45
+ var node = this;
46
+
47
+ // 1. Configuration
48
+ const account = config.accountNumber ? config.accountNumber.trim() : "";
49
+ const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
50
+
51
+ // Kraken error text can echo the request, API key included. The Node-RED log, status and
52
+ // msg show it as it is, so a wrong key can be seen. Keys and tokens are masked only in
53
+ // what is published to Home Assistant (stateJson), where they would be kept in its history.
54
+ // A log line is at most MAX_LOG_LENGTH characters. An over-long line keeps its start and
55
+ // its end (". Retrying in 30s."); error text embedded in a line is cut to 300 characters
56
+ // first (short), so normally nothing is cut here.
57
+ const MAX_LOG_LENGTH = 500;
58
+ const capLine = (m) => (m.length > MAX_LOG_LENGTH ? `${m.slice(0, 380)} ... ${m.slice(-(MAX_LOG_LENGTH - 385))}` : m);
59
+ const clean = (m) => (typeof m === 'string' ? capLine(m) : m);
60
+ const short = (m) => truncate(m, 300);
61
+ // The JSON published to the MQTT state topic, with keys and tokens masked.
62
+ const stateJson = (state) => JSON.stringify(maskSecretsDeep(state, [apiKey]));
63
+ const rawLog = node.log, rawWarn = node.warn, rawError = node.error, rawStatus = node.status;
64
+ node.log = function (m, ...rest) { return rawLog.call(node, clean(m), ...rest); };
65
+ node.warn = function (m, ...rest) { return rawWarn.call(node, clean(m), ...rest); };
66
+ node.error = function (m, ...rest) { return rawError.call(node, clean(m), ...rest); };
67
+ node.status = function (s, ...rest) {
68
+ const masked = s && typeof s === 'object' && typeof s.text === 'string' ? Object.assign({}, s, { text: clean(s.text) }) : clean(s);
69
+ return rawStatus.call(node, masked, ...rest);
70
+ };
71
+ const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
72
+ const enableMqtt = config.enableMqtt;
73
+ node.timezoneOverride = config.timezoneOverride || "";
74
+
75
+ // MQTT Topics
76
+ this.broker = RED.nodes.getNode(config.broker);
77
+ const mqttPrefix = `homeassistant`;
78
+ const uniqueIdPrefix = `nodered_${account}`;
79
+ const stateTopic = `nodered_octopus/${account}/status`;
80
+
81
+ // Command Topics (For listening)
82
+ const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
83
+ const cmdTopicTime = `nodered_octopus/${account}/set_time`;
84
+ const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
85
+ const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
86
+ const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
87
+ const cmdTopicSmartCharging = `nodered_octopus/${account}/set_smart_charging`;
88
+ const cmdTopicChargeCap = `nodered_octopus/${account}/set_charge_cap`;
89
+ const cmdTopicBoost = `nodered_octopus/${account}/set_boost`;
90
+ const commandTopics = [cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh,
91
+ cmdTopicTimezone, cmdTopicSmartCharging, cmdTopicChargeCap, cmdTopicBoost];
92
+
93
+ // 2. Constants & Validation — TIME_OPTIONS / validators live in lib/preferences.js
94
+
95
+ // 3. Sensor Definitions (Read-Only) — imported from lib/sensor-definitions.js
96
+
97
+ // 4. Helper: Announce Controls (Write-Enabled)
98
+ // Single Home Assistant device: every entity sits on it (never split).
99
+ const device = {
100
+ identifiers: [`nodered_octopus_${account}`],
101
+ name: "Octopus Intelligent",
102
+ manufacturer: "Octopus Energy",
103
+ model: "Intelligent Octopus Go",
104
+ // The package version (review L5). Not part of any unique_id, so no entity moves.
105
+ sw_version: require('./package.json').version,
106
+ suggested_area: "Energy",
107
+ configuration_url: "https://octopus.energy/intelligent/"
108
+ };
109
+
110
+ // Review A3: the 1.7 SmartFlex fields are missing from the state JSON of an older version
111
+ // (after a rollback, which never clears these retained configs) and from a retained 1.6
112
+ // state read before the first 1.7 poll. Their templates check `is defined`, so Home
113
+ // Assistant logs no template warnings and shows no false Problem.
114
+ // Review L1: a template that renders None gives unknown only on a numeric sensor (unit,
115
+ // state_class or numeric device_class) and on binary sensors. A text sensor stores the
116
+ // text "None". So every SmartFlex entity also gets an availability check on the state
117
+ // topic: a missing field reads Unavailable. Text sensors marked nullUnavailable also read
118
+ // Unavailable when the field is null (HA has no way to show unknown for a text sensor).
119
+ const valueOrNone = (field) => `value_json.${field} if value_json.${field} is defined else None`;
120
+ const listOrEmpty = (field) => `(value_json.${field} if value_json.${field} is defined else [])`;
121
+ const fieldAvailability = (field, nullUnavailable) => [{
122
+ topic: stateTopic,
123
+ value_template: nullUnavailable === true
124
+ ? `{{ 'online' if value_json.${field} is defined and value_json.${field} is not none else 'offline' }}`
125
+ : `{{ 'online' if value_json.${field} is defined else 'offline' }}`,
126
+ }];
127
+
128
+ // Read-only sensor discovery config (definitions in lib/sensor-definitions.js).
129
+ // missingSafe: the field may be missing from the state JSON (SmartFlex, review A3).
130
+ function announceSensor(sensor, missingSafe) {
131
+ const payload = {
132
+ name: `Octopus ${sensor.name}`,
133
+ unique_id: `${uniqueIdPrefix}_${sensor.id}`,
134
+ state_topic: stateTopic,
135
+ value_template: missingSafe === true ? `{{ ${valueOrNone(sensor.val)} }}` : `{{ value_json.${sensor.val} }}`,
136
+ device: device
137
+ };
138
+ if (sensor.class) payload.device_class = sensor.class;
139
+ if (sensor.unit) payload.unit_of_measurement = sensor.unit;
140
+ if (sensor.stateClass) payload.state_class = sensor.stateClass;
141
+ if (sensor.icon) payload.icon = sensor.icon;
142
+ if (missingSafe === true) payload.availability = fieldAvailability(sensor.val, sensor.nullUnavailable);
143
+
144
+ if (sensor.category) {
145
+ payload.entity_category = sensor.category;
146
+ }
147
+
148
+ if (sensor.id === 'applicable_rates_count') {
149
+ payload.json_attributes_topic = stateTopic;
150
+ payload.json_attributes_template = '{ "rates": {{ value_json.applicable_rates | tojson }} }';
151
+ } else if (sensor.id === 'electricity_export_rate_count') {
152
+ payload.json_attributes_topic = stateTopic;
153
+ payload.json_attributes_template = '{ "rates": {{ value_json.electricity_export_rate | tojson }} }';
154
+ } else if (sensor.id === 'last_session_kwh') {
155
+ // v1.7.0: the full SmartFlex session list and device alerts go in attributes only.
156
+ payload.json_attributes_topic = stateTopic;
157
+ payload.json_attributes_template = `{ "sessions": {{ ${listOrEmpty('charging_sessions')} | tojson }}, "alerts": {{ ${listOrEmpty('device_alerts')} | tojson }} }`;
158
+ // state_class total (review L2): the energy counts from a new cycle at each session
159
+ // end, so HA adds each finished session's kWh to the statistics once. last_session
160
+ // is always a finished session (it has an end). An empty string is ignored by HA:
161
+ // no session yet, or the state JSON of an older version.
162
+ payload.last_reset_value_template = "{{ value_json.last_session.end if value_json.last_session is defined and value_json.last_session and value_json.last_session.end else '' }}";
163
+ }
164
+
165
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
166
+ }
167
+
168
+ // v1.5 — error binary_sensor discovery config (device_class: problem).
169
+ // missingSafe: a missing field reads OFF, not ON (review A3: Jinja's Undefined is not
170
+ // in [None, ''], so the 1.5 template shows a false Problem when the field is missing).
171
+ function announceErrorSensor(e, missingSafe) {
172
+ const payload = {
173
+ name: `Octopus ${e.name}`,
174
+ unique_id: `${uniqueIdPrefix}_${e.id}`,
175
+ state_topic: stateTopic,
176
+ value_template: missingSafe === true
177
+ ? `{{ 'ON' if value_json.${e.val} is defined and value_json.${e.val} not in [None, ''] else 'OFF' }}`
178
+ : `{{ 'OFF' if value_json.${e.val} in [None, ''] else 'ON' }}`,
179
+ payload_on: 'ON',
180
+ payload_off: 'OFF',
181
+ device_class: 'problem',
182
+ entity_category: 'diagnostic',
183
+ device: device,
184
+ };
185
+ if (missingSafe === true) payload.availability = fieldAvailability(e.val);
186
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_${e.id}/config`, JSON.stringify(payload), { retain: true });
187
+ }
188
+
189
+ function announceControls() {
190
+ if (!enableMqtt || !node.broker) return;
191
+
192
+ // A. The Slider (Number) - now shows pending value
193
+ const limitConfig = {
194
+ name: "Octopus Target Charge",
195
+ unique_id: `${uniqueIdPrefix}_target_limit`,
196
+ state_topic: stateTopic,
197
+ command_topic: cmdTopicLimit,
198
+ value_template: "{{ value_json.pending_limit }}",
199
+ min: 5, max: 100, step: 5,
200
+ unit_of_measurement: "%",
201
+ icon: "mdi:battery-charging-high",
202
+ device: device
203
+ };
204
+ node.broker.client.publish(`${mqttPrefix}/number/${uniqueIdPrefix}_limit/config`, JSON.stringify(limitConfig), { retain: true });
205
+
206
+ // B. The Dropdown (Select) - now shows pending value
207
+ const timeConfig = {
208
+ name: "Octopus Ready Time",
209
+ unique_id: `${uniqueIdPrefix}_target_time`,
210
+ state_topic: stateTopic,
211
+ command_topic: cmdTopicTime,
212
+ value_template: "{{ value_json.pending_time }}",
213
+ options: TIME_OPTIONS,
214
+ icon: "mdi:clock-time-four-outline",
215
+ device: device
216
+ };
217
+ node.broker.client.publish(`${mqttPrefix}/select/${uniqueIdPrefix}_time/config`, JSON.stringify(timeConfig), { retain: true });
218
+
219
+ // C. Submit Button
220
+ const buttonConfig = {
221
+ name: "Octopus Apply Changes",
222
+ unique_id: `${uniqueIdPrefix}_submit_button`,
223
+ command_topic: cmdTopicSubmit,
224
+ payload_press: "SUBMIT",
225
+ icon: "mdi:check-circle",
226
+ device_class: "update",
227
+ device: device
228
+ };
229
+ node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
230
+
231
+ // D. Refresh Button
232
+ const refreshButtonConfig = {
233
+ name: "Octopus Refresh API",
234
+ unique_id: `${uniqueIdPrefix}_refresh_button`,
235
+ command_topic: cmdTopicRefresh,
236
+ payload_press: "REFRESH",
237
+ icon: "mdi:refresh",
238
+ device_class: "restart",
239
+ device: device
240
+ };
241
+ node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_refresh/config`, JSON.stringify(refreshButtonConfig), { retain: true });
242
+
243
+ // E. Add sensors for confirmed values (read-only display)
244
+ const confirmedLimitSensor = {
245
+ name: "Octopus Confirmed Charge Limit",
246
+ unique_id: `${uniqueIdPrefix}_confirmed_limit`,
247
+ state_topic: stateTopic,
248
+ value_template: "{{ value_json.confirmed_limit }}",
249
+ unit_of_measurement: "%",
250
+ icon: "mdi:battery-check",
251
+ device: device
252
+ };
253
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_limit/config`, JSON.stringify(confirmedLimitSensor), { retain: true });
254
+
255
+ const confirmedTimeSensor = {
256
+ name: "Octopus Confirmed Ready Time",
257
+ unique_id: `${uniqueIdPrefix}_confirmed_time`,
258
+ state_topic: stateTopic,
259
+ value_template: "{{ value_json.confirmed_time }}",
260
+ icon: "mdi:clock-check",
261
+ device: device
262
+ };
263
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
264
+
265
+ // G. Charging Now Binary Sensor (main sensor for automations)
266
+ const chargingNowBinarySensor = {
267
+ name: "Octopus Charging Now",
268
+ unique_id: `${uniqueIdPrefix}_charging_now`,
269
+ state_topic: `${stateTopic}/charging_now`,
270
+ device_class: "battery_charging",
271
+ payload_on: "ON",
272
+ payload_off: "OFF",
273
+ icon: "mdi:ev-station",
274
+ device: device
275
+ };
276
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
277
+
278
+ // G2. Saving Session Available Binary Sensor
279
+ const savingSessionBinarySensor = {
280
+ name: "Octopus Saving Session Available",
281
+ unique_id: `${uniqueIdPrefix}_saving_session_available`,
282
+ state_topic: stateTopic,
283
+ value_template: "{{ value_json.saving_session_available }}",
284
+ payload_on: "True",
285
+ payload_off: "False",
286
+ icon: "mdi:lightning-bolt-circle",
287
+ device: device
288
+ };
289
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_available/config`, JSON.stringify(savingSessionBinarySensor), { retain: true });
290
+
291
+ // G2a. Saving Session Window Active Binary Sensor (v1.3.3)
292
+ const savingSessionWindowActiveSensor = {
293
+ name: "Octopus Saving Session Window Active",
294
+ unique_id: `${uniqueIdPrefix}_saving_session_window_active`,
295
+ state_topic: stateTopic,
296
+ value_template: "{{ value_json.saving_session_window_active }}",
297
+ payload_on: "True",
298
+ payload_off: "False",
299
+ icon: "mdi:clock-check-outline",
300
+ device: device
301
+ };
302
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_window_active/config`, JSON.stringify(savingSessionWindowActiveSensor), { retain: true });
303
+
304
+ // G2b. Saving Session Active Binary Sensor (v1.3.3) — joined AND in window
305
+ const savingSessionActiveSensor = {
306
+ name: "Octopus Saving Session Active",
307
+ unique_id: `${uniqueIdPrefix}_saving_session_active`,
308
+ state_topic: stateTopic,
309
+ value_template: "{{ value_json.saving_session_active }}",
310
+ payload_on: "True",
311
+ payload_off: "False",
312
+ icon: "mdi:home-export-outline",
313
+ device: device
314
+ };
315
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_active/config`, JSON.stringify(savingSessionActiveSensor), { retain: true });
316
+
317
+ // G2c. v1.3.3 migration: delete the deprecated sensor.saving_session_joined
318
+ // entity. HA's sensor domain doesn't render booleans cleanly. Empty
319
+ // payload on the discovery topic with retain tells HA the entity no
320
+ // longer exists. Safe to keep across releases.
321
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_saving_session_joined/config`, "", { retain: true });
322
+
323
+ // G2d. Saving Session Joined Binary Sensor (v1.3.3 migration)
324
+ const savingSessionJoinedSensor = {
325
+ name: "Octopus Saving Session Joined",
326
+ unique_id: `${uniqueIdPrefix}_saving_session_joined`,
327
+ state_topic: stateTopic,
328
+ value_template: "{{ value_json.saving_session_joined }}",
329
+ payload_on: "True",
330
+ payload_off: "False",
331
+ icon: "mdi:account-check",
332
+ device: device
333
+ };
334
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_joined/config`, JSON.stringify(savingSessionJoinedSensor), { retain: true });
335
+
336
+ // G3. Free Electricity Active Binary Sensor
337
+ const freeElectricityActiveSensor = {
338
+ name: "Octopus Free Electricity Active",
339
+ unique_id: `${uniqueIdPrefix}_free_electricity_active`,
340
+ state_topic: stateTopic,
341
+ value_template: "{{ value_json.free_electricity_active }}",
342
+ payload_on: "True",
343
+ payload_off: "False",
344
+ icon: "mdi:flash-circle",
345
+ device: device
346
+ };
347
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_active/config`, JSON.stringify(freeElectricityActiveSensor), { retain: true });
348
+
349
+ // G4. Free Electricity Available Binary Sensor
350
+ const freeElectricityAvailableSensor = {
351
+ name: "Octopus Free Electricity Available",
352
+ unique_id: `${uniqueIdPrefix}_free_electricity_available`,
353
+ state_topic: stateTopic,
354
+ value_template: "{{ value_json.free_electricity_available }}",
355
+ payload_on: "True",
356
+ payload_off: "False",
357
+ icon: "mdi:flash-circle-outline",
358
+ device: device
359
+ };
360
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_available/config`, JSON.stringify(freeElectricityAvailableSensor), { retain: true });
361
+
362
+ // G5. Octoplus Enrolled Binary Sensor
363
+ // Published as binary_sensor (not sensor) because the value is a boolean —
364
+ // HA's sensor domain rejects booleans without a device_class, leaving the
365
+ // entity unregistered. No entity_category: 'config' on a read-only sensor
366
+ // makes its state stick at "unavailable" on some HA installs (same fix as
367
+ // the v1.3.0 tariff-sensor cleanup — see CHANGELOG).
368
+ const octoplusEnrolledBinarySensor = {
369
+ name: "Octopus Octoplus Enrolled",
370
+ unique_id: `${uniqueIdPrefix}_octoplus_enrolled`,
371
+ state_topic: stateTopic,
372
+ value_template: "{{ value_json.octoplus_enrolled }}",
373
+ payload_on: "True",
374
+ payload_off: "False",
375
+ icon: "mdi:star-circle",
376
+ device: device
377
+ };
378
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_enrolled/config`, JSON.stringify(octoplusEnrolledBinarySensor), { retain: true });
379
+
380
+ // G6. Octoplus Loyalty Points (boolean) Binary Sensor
381
+ // No entity_category — see G5.
382
+ const octoplusLoyaltyBinarySensor = {
383
+ name: "Octopus Octoplus Loyalty Points",
384
+ unique_id: `${uniqueIdPrefix}_octoplus_loyalty_points_user`,
385
+ state_topic: stateTopic,
386
+ value_template: "{{ value_json.octoplus_loyalty_points_user }}",
387
+ payload_on: "True",
388
+ payload_off: "False",
389
+ icon: "mdi:star",
390
+ device: device
391
+ };
392
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_loyalty_points_user/config`, JSON.stringify(octoplusLoyaltyBinarySensor), { retain: true });
393
+
394
+ // H. Announce Read-Only Sensors
395
+ sensors.forEach(announceSensor);
396
+
397
+ // H2. v1.5 — error binary_sensors (device_class: problem)
398
+ errorSensors.forEach(announceErrorSensor);
399
+
400
+ // H3. v1.7.0 SmartFlex vehicle and inverter entities depend on the devices Octopus
401
+ // lists, so announceSmartflexEntities() publishes them once discovery has run.
402
+
403
+ // I. Timezone Select Entity
404
+ const TIMEZONE_OPTIONS = [
405
+ "Europe/London", "Europe/Berlin", "Europe/Madrid",
406
+ "Australia/Sydney", "Australia/Melbourne", "Australia/Brisbane",
407
+ "Australia/Perth", "Australia/Adelaide", "Pacific/Auckland",
408
+ "America/New_York", "America/Chicago", "America/Denver",
409
+ "America/Los_Angeles", "Asia/Tokyo", "UTC"
410
+ ];
411
+ node.broker.client.publish(
412
+ `${mqttPrefix}/select/${uniqueIdPrefix}_timezone/config`,
413
+ JSON.stringify({
414
+ name: "Timezone",
415
+ unique_id: `${uniqueIdPrefix}_timezone`,
416
+ options: TIMEZONE_OPTIONS,
417
+ command_topic: cmdTopicTimezone,
418
+ state_topic: `${stateTopic}/timezone`,
419
+ icon: "mdi:earth",
420
+ entity_category: "config",
421
+ device: device
422
+ }),
423
+ { retain: true }
424
+ );
425
+
426
+ // J. Smart Charging Switch
427
+ node.broker.client.publish(
428
+ `${mqttPrefix}/switch/${uniqueIdPrefix}_smart_charging/config`,
429
+ JSON.stringify({
430
+ name: "Smart Charging",
431
+ unique_id: `${uniqueIdPrefix}_smart_charging`,
432
+ command_topic: cmdTopicSmartCharging,
433
+ state_topic: `${stateTopic}/smart_charging`,
434
+ payload_on: "ON",
435
+ payload_off: "OFF",
436
+ icon: "mdi:lightning-bolt",
437
+ entity_category: "config",
438
+ device: device
439
+ }),
440
+ { retain: true }
441
+ );
442
+
443
+ // J2. Charge Cap Switch — limit smart charging to off-peak rates only (v1.6)
444
+ node.broker.client.publish(
445
+ `${mqttPrefix}/switch/${uniqueIdPrefix}_charge_cap/config`,
446
+ JSON.stringify({
447
+ name: "Charge Cap",
448
+ unique_id: `${uniqueIdPrefix}_charge_cap`,
449
+ command_topic: cmdTopicChargeCap,
450
+ state_topic: `${stateTopic}/charge_cap`,
451
+ payload_on: "ON",
452
+ payload_off: "OFF",
453
+ icon: "mdi:cash-clock",
454
+ entity_category: "config",
455
+ device: device
456
+ }),
457
+ { retain: true }
458
+ );
459
+
460
+ // J3. The Boost Charge switch (v1.7) needs an EV, so announceSmartflexEntities()
461
+ // publishes it once discovery has run.
462
+
463
+ // K. v1.5 — Update entity (notify-only; Palette Manager is the install path)
464
+ node.broker.client.publish(
465
+ `${mqttPrefix}/update/${uniqueIdPrefix}_node_update/config`,
466
+ JSON.stringify({
467
+ name: 'Octopus Intelligent Node',
468
+ unique_id: `${uniqueIdPrefix}_node_update`,
469
+ state_topic: `${stateTopic}/node_update`,
470
+ title: 'node-red-contrib-octopus-intelligent',
471
+ release_url: 'https://github.com/ASomerN/node-red-contrib-octopus-intelligent/releases',
472
+ device: device,
473
+ }),
474
+ { retain: true }
475
+ );
476
+
477
+ // Command topics are subscribed through node.broker.subscribe (see Handle MQTT Commands);
478
+ // the broker subscribes the client when connected and again after every reconnect.
479
+ }
480
+
481
+ // 4b. v1.7.0 — SmartFlex entities, announced once product discovery has run. The Boost
482
+ // Charge switch and the vehicle entities only when Octopus lists an ELECTRIC_VEHICLES
483
+ // device (a car or a charge point: Kraken lists both that way); the experimental
484
+ // inverter entities only when the editor option is ticked AND Octopus lists an inverter.
485
+ // Otherwise their discovery topics are cleared, so Home Assistant removes them. A retained
486
+ // empty config deletes the entity (names, areas, ids), so this only happens when Octopus
487
+ // listed devices and none was of that kind: a transient empty list leaves them alone.
488
+ function announceSmartflexEntities(discovered) {
489
+ if (!enableMqtt || !node.broker || !node.broker.client) return;
490
+ const clearSensor = (s) => node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${s.id}/config`, "", { retain: true });
491
+ const clearBinarySensor = (e) => node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_${e.id}/config`, "", { retain: true });
492
+ const devicesListed = discovered.deviceCount > 0
493
+ || !!(discovered.deviceId || discovered.vehicleDeviceId || discovered.inverterDeviceId);
494
+ const inverterOption = config.enableSmartflexInverter === true;
495
+ if (!devicesListed) {
496
+ node.log("SmartFlex: Octopus listed no devices, so the SmartFlex entities in Home Assistant are left as they are");
497
+ }
498
+
499
+ // Boost Charge switch: charge now, outside the plan (v1.7). Boost acts on the car or
500
+ // charge point Octopus controls, so it is announced only when discovery found one
501
+ // (review A10), by the same rule as the vehicle entities. Not a config setting, so no entity_category:
502
+ // it sits with the main controls.
503
+ const boostTopic = `${mqttPrefix}/switch/${uniqueIdPrefix}_boost/config`;
504
+ if (discovered.deviceId) {
505
+ node.broker.client.publish(boostTopic, JSON.stringify({
506
+ name: "Boost Charge",
507
+ unique_id: `${uniqueIdPrefix}_boost`,
508
+ command_topic: cmdTopicBoost,
509
+ state_topic: `${stateTopic}/boost`,
510
+ payload_on: "ON",
511
+ payload_off: "OFF",
512
+ // Its own icon: mdi:lightning-bolt-circle is already on two other entities.
513
+ icon: "mdi:rocket-launch",
514
+ device: device
515
+ }), { retain: true });
516
+ } else if (devicesListed) {
517
+ node.broker.client.publish(boostTopic, "", { retain: true });
518
+ }
519
+
520
+ // Vehicle / charge point. The last-session problem flag is a boolean, so binary_sensor.
521
+ const lastSessionProblemTopic = `${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_last_session_problem/config`;
522
+ if (discovered.vehicleDeviceId) {
523
+ vehicleSensors.forEach((s) => announceSensor(s, true));
524
+ vehicleErrorSensors.forEach((e) => announceErrorSensor(e, true));
525
+ const lastSessionProblemSensor = {
526
+ name: "Octopus Last Charge Session Problem",
527
+ unique_id: `${uniqueIdPrefix}_last_session_problem`,
528
+ state_topic: stateTopic,
529
+ value_template: `{{ ${valueOrNone('last_session_problem')} }}`,
530
+ availability: fieldAvailability('last_session_problem'),
531
+ payload_on: "True",
532
+ payload_off: "False",
533
+ // No icon: the problem class shows its own OK and Problem icons.
534
+ device_class: "problem",
535
+ device: device
536
+ };
537
+ node.broker.client.publish(lastSessionProblemTopic, JSON.stringify(lastSessionProblemSensor), { retain: true });
538
+ } else if (devicesListed) {
539
+ vehicleSensors.forEach(clearSensor);
540
+ vehicleErrorSensors.forEach(clearBinarySensor);
541
+ node.broker.client.publish(lastSessionProblemTopic, "", { retain: true });
542
+ }
543
+
544
+ // Inverter, EXPERIMENTAL.
545
+ const inverterOnlineTopic = `${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_inverter_online/config`;
546
+ if (discovered.inverterDeviceId && inverterOption) {
547
+ inverterSensors.forEach((s) => announceSensor(s, true));
548
+ inverterErrorSensors.forEach((e) => announceErrorSensor(e, true));
549
+ const inverterOnlineSensor = {
550
+ name: "Octopus Inverter Online",
551
+ unique_id: `${uniqueIdPrefix}_inverter_online`,
552
+ state_topic: stateTopic,
553
+ value_template: `{{ ${valueOrNone('inverter_online')} }}`,
554
+ availability: fieldAvailability('inverter_online'),
555
+ payload_on: "True",
556
+ payload_off: "False",
557
+ device_class: "connectivity",
558
+ entity_category: "diagnostic",
559
+ device: device
560
+ };
561
+ node.broker.client.publish(inverterOnlineTopic, JSON.stringify(inverterOnlineSensor), { retain: true });
562
+ } else if (!inverterOption || devicesListed) {
563
+ // Option off: removed on purpose. Option on: only when the list had devices.
564
+ inverterSensors.forEach(clearSensor);
565
+ inverterErrorSensors.forEach(clearBinarySensor);
566
+ node.broker.client.publish(inverterOnlineTopic, "", { retain: true });
567
+ }
568
+ }
569
+
570
+ // 5. Helper: Set Preferences (The Mutation)
571
+ let retryTimeouts = []; // Track pending retry timeouts
572
+ let expectedLimit = null;
573
+ let expectedTime = null;
574
+ let validationMode = false;
575
+ let validationGen = 0; // each submit bumps it; an older validation chain then stops
576
+ // Bumped when a preferences or Charge Cap write is sent and when a validation confirms.
577
+ // A charging poll that started before a bump read the old values: it must not apply them.
578
+ let prefsGen = 0;
579
+
580
+ // Pending vs Confirmed state
581
+ let pendingLimit = 80;
582
+ let pendingTime = "08:00";
583
+ let confirmedLimit = 80;
584
+ let confirmedTime = "08:00";
585
+ let chargeCapNaWarned = false; // warn once when the API says Charge Cap doesn't apply
586
+
587
+ // Charging Now feature - timer-based state management
588
+ let chargingNow = false;
589
+ let preValidationTimer = null; // Fires 30s before slot start
590
+ let slotStartTimer = null; // Fires at exact slot start
591
+ let slotEndTimer = null; // Fires at exact slot end
592
+ let cachedSlots = []; // Fresh slot data from pre-validation
593
+ let stateCheckInterval = null; // Reconciliation loop (every 10s)
594
+ let lastSentChargingState = null; // Track last sent state to avoid duplicates
595
+ let chargingNowPublished = false; // charging_now topic written since start (clears a stale retained ON)
596
+ let boosting = null; // null=unknown; true while status.currentState is BOOSTING
597
+ let boostingConfirmedAt = 0; // when Octopus last told us boosting (poll or boost answer)
598
+ let boostHold = null; // { value, since, until } after Octopus accepted a set_boost
599
+ const BOOST_HOLD_MS = 2 * 60 * 1000;
600
+ let boostError = null; // last failed set_boost (also lastKnownState.boost_error)
601
+ let boostErrorAt = 0;
602
+ // A charging poll that starts this long after the failure and reads the device state
603
+ // clears boost_error, so one refusal does not stay in every payload for days.
604
+ const BOOST_ERROR_CLEAR_MS = 60 * 1000;
605
+
606
+ // Manual refresh rate limiting (only for MQTT button, not Node-RED input)
607
+ let lastManualRefresh = 0; // Timestamp of last manual refresh
608
+ const MANUAL_REFRESH_COOLDOWN = 30000; // 30 seconds in milliseconds
609
+ let cooldownExpiryTimer = null; // Timer to clear cooldown state at expiry
610
+
611
+ // Polling metrics
612
+ let nextPollTime = null; // ISO timestamp of next scheduled poll
613
+ const metrics = createApiMetrics();
614
+
615
+ // API Complexity Tracking
616
+ // Octopus Energy API does not return actual complexity values in headers or extensions,
617
+ // so we use estimated complexity based on query types:
618
+ // - Regular poll (auth + data query): ~300
619
+ // - Mutation (auth + setPreferences): ~250
620
+ // - Pre-validation (auth + flexPlannedDispatches only): ~200
621
+
622
+ // Smart charging state (startup, discovery, then every charging poll)
623
+ let krakenflexDeviceId = null;
624
+ // The EV discovery picked (the LIVE one, review L4). The charging poll, the startup
625
+ // device fetch and the smart charging check read this device when it is listed.
626
+ let preferredEvId = null;
627
+ let smartChargingSuspended = null; // null=unknown, true=suspended(off), false=active(on)
628
+ let smartChargingRetryTimeouts = [];
629
+ let smartChargingVerifying = false; // a toggle is waiting for Octopus to confirm it
630
+ let publishedSmartCharging = null; // last value written to the switch state topic
631
+ let otherDeviceErrorLogged = false; // charging poll: an error on another device was logged
632
+ let statusWarned = false; // warned that Octopus could not return the device status
633
+
634
+ // Write the switch state topic (retained) when it differs from the last one written.
635
+ function publishSmartChargingState(force) {
636
+ if (smartChargingSuspended === null) return;
637
+ const value = smartChargingSuspended ? "OFF" : "ON";
638
+ if (!force && value === publishedSmartCharging) return;
639
+ if (enableMqtt && node.broker && node.broker.client) {
640
+ node.broker.client.publish(`${stateTopic}/smart_charging`, value, { retain: true });
641
+ publishedSmartCharging = value;
642
+ }
643
+ }
644
+
645
+ // Last known full state - prevents sensors going unknown when controls change
646
+ let lastKnownState = buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
647
+ lastKnownState.installed_version = require('./package.json').version;
648
+
649
+ // V2 category registry — populated after discovery
650
+ let categories = [];
651
+
652
+ // Lifecycle tracking — init setTimeouts must be clearable on close, and async
653
+ // callbacks inside them must short-circuit if the node was closed mid-await,
654
+ // otherwise a redeploy during the 2s warmup leaves an orphan V2 scheduler.
655
+ // Each handle is removed when its timer fires, so the set stays small however long
656
+ // discovery keeps retrying (it retries every 5 minutes for as long as it fails).
657
+ const initTimeoutHandles = new Set();
658
+ function initTimeout(fn, ms) {
659
+ const handle = setTimeout(() => {
660
+ initTimeoutHandles.delete(handle);
661
+ return fn();
662
+ }, ms);
663
+ initTimeoutHandles.add(handle);
664
+ return handle;
665
+ }
666
+ let nodeClosed = false;
667
+ let lastWarnedVersion = null;
668
+ let prevPublishedInstalled = null;
669
+ let prevPublishedLatest = null;
670
+
671
+ // Quick retry of the charging poll (1.6.2). Octopus fails flexPlannedDispatches
672
+ // (KT-CT-4340) or the device preferences (KT-CT-4339) for a few minutes around :00/:30.
673
+ // A retry only forces the charging category due, so it runs through the scheduler's
674
+ // in-flight guard and never alongside a normal tick; nothing runs once the node closes.
675
+ const dispatchRate = createRateWindow(); // max 3 flexPlannedDispatches queries in any 60 s
676
+ let chargingOutage = null; // { since, retryNo, retryAt, nextNormalAt } while the poll fails
677
+ let retryPollRunning = false;
678
+ // prefsGen when this tick's charging poll started (null: no charging poll this tick).
679
+ let tickChargingPollGen = null;
680
+ const PREFERENCE_FIELDS = ['confirmed_limit', 'confirmed_time', 'pending_limit', 'pending_time', 'charge_cap'];
681
+
682
+ function noteDispatchQuery() {
683
+ dispatchRate.record(Date.now());
684
+ }
685
+
686
+ // Called at the start of each tick: force the charging poll due when a retry is due.
687
+ function startDueChargingRetry() {
688
+ if (!chargingOutage || !chargingOutage.retryAt) return;
689
+ const now = Date.now();
690
+ if (now < chargingOutage.retryAt) return;
691
+ const cat = categories.find((c) => c.id === 'intelligent');
692
+ if (!cat || !cat.enabled || now >= chargingOutage.nextNormalAt) {
693
+ chargingOutage.retryAt = null; // the normal poll takes over
694
+ return;
695
+ }
696
+ const allowedAt = dispatchRate.nextAllowedAt(now);
697
+ if (allowedAt > now) {
698
+ // Too many dispatch queries this minute: wait, unless the normal poll comes first.
699
+ chargingOutage.retryAt = allowedAt < chargingOutage.nextNormalAt ? allowedAt : null;
700
+ return;
701
+ }
702
+ chargingOutage.retryAt = null;
703
+ retryPollRunning = true;
704
+ forceCategoryDue('intelligent');
705
+ }
706
+
707
+ function noteChargingPollFailure(err, isRetry, intervalMs) {
708
+ const now = Date.now();
709
+ if (!chargingOutage) chargingOutage = { since: now, retryNo: 0, retryAt: null, nextNormalAt: 0 };
710
+ chargingOutage.nextNormalAt = nextSlotStart(now, intervalMs);
711
+ chargingOutage.retryAt = null;
712
+ // A Kraken error carries code and detail; a socket error (ENOTFOUND) has a code only.
713
+ const text = err.code && err.detail !== undefined ? `${err.code} ${err.detail}` : err.message;
714
+ let suffix = '';
715
+ if (isRetryable(err)) {
716
+ const retryNo = isRetry ? chargingOutage.retryNo + 1 : 1;
717
+ const delay = retryDelay(retryNo);
718
+ if (now + delay < chargingOutage.nextNormalAt) {
719
+ chargingOutage.retryNo = retryNo;
720
+ chargingOutage.retryAt = now + delay;
721
+ suffix = ` (retry ${retryNo} in ${Math.round(delay / 1000)}s)`;
722
+ } else {
723
+ suffix = ` (next poll in ${Math.ceil((chargingOutage.nextNormalAt - now) / 1000)}s)`;
724
+ }
725
+ }
726
+ node.warn(`Charging poll failed: ${short(text)}${suffix}`);
727
+ }
728
+
729
+ function noteChargingPollSuccess() {
730
+ if (!chargingOutage) return;
731
+ node.log(`Charging poll recovered after ${formatDuration(Date.now() - chargingOutage.since)}`);
732
+ chargingOutage = null;
733
+ }
734
+
735
+ // The scheduler's charging poll: logs each failure and schedules the quick retry.
736
+ async function scheduledIntelligentPoll(token, isStale) {
737
+ const isRetry = retryPollRunning;
738
+ retryPollRunning = false;
739
+ tickChargingPollGen = prefsGen;
740
+ try {
741
+ return await intelligentPoll(token, isStale);
742
+ } catch (e) {
743
+ if (!nodeClosed && !(isStale && isStale())) {
744
+ const cat = categories.find((c) => c.id === 'intelligent');
745
+ noteChargingPollFailure(e, isRetry, cat ? cat.intervalMs : refreshRate);
746
+ }
747
+ if (typeof e.message === 'string') e.message = truncate(e.message);
748
+ throw e;
749
+ }
750
+ }
751
+
752
+ // The charging poll (first in the list) and completed dispatches, for an account with an EV.
753
+ function intelligentCategoryEntry() {
754
+ return {
755
+ id: 'intelligent',
756
+ enabled: true,
757
+ intervalMs: (config.refreshInterval || 5) * 60 * 1000,
758
+ lastPolled: 0,
759
+ poll: scheduledIntelligentPoll,
760
+ };
761
+ }
762
+
763
+ function completedDispatchesCategoryEntry() {
764
+ return {
765
+ id: 'completed_dispatches',
766
+ enabled: true,
767
+ intervalMs: 60 * 60 * 1000,
768
+ lastPolled: 0,
769
+ queryFn: () => completedDispatchesCategory.buildQuery(account),
770
+ parseFn: d => completedDispatchesCategory.parseResponse(d),
771
+ poll: simplePoll(
772
+ () => completedDispatchesCategory.buildQuery(account),
773
+ d => completedDispatchesCategory.parseResponse(d),
774
+ graphqlPost
775
+ ),
776
+ };
777
+ }
778
+
779
+ // v1.7.0 — SmartFlex vehicle / charge point details and charging sessions.
780
+ function smartflexVehicleCategoryEntry(discovered) {
781
+ return {
782
+ id: 'smartflex_vehicle',
783
+ enabled: true,
784
+ intervalMs: 30 * 60 * 1000,
785
+ lastPolled: 0,
786
+ queryFn: () => smartflexVehicleCategory.buildQuery(account),
787
+ parseFn: d => smartflexVehicleCategory.parseResponse(d, discovered.vehicleDeviceId),
788
+ // Tolerates partial errors (e.g. on chargingSessions): keeps what came back
789
+ // and the last values for the rest. Throws only when no vehicle data came back.
790
+ poll: async (token) => {
791
+ const { query, variables } = smartflexVehicleCategory.buildQuery(account);
792
+ const response = await graphqlPost({ query, variables }, token);
793
+ const result = smartflexVehicleCategory.parseGraphqlResponse(response.data, discovered.vehicleDeviceId);
794
+ if (result.smartflex_vehicle_error && !nodeClosed) {
795
+ node.warn(`SmartFlex vehicle poll partly failed: ${result.smartflex_vehicle_error} - keeping the last values for the missing fields`);
796
+ }
797
+ // device_state comes from the charging poll: a charge point is listed as
798
+ // ELECTRIC_VEHICLES too, so every vehicle device has one.
799
+ return result;
800
+ },
801
+ };
802
+ }
803
+
804
+ // v1.7.0 — SmartFlex inverter telemetry. Experimental: not yet verified on a real
805
+ // inverter, so it only runs when the editor option is ticked.
806
+ function smartflexInverterCategoryEntry(discovered) {
807
+ return {
808
+ id: 'smartflex_inverter',
809
+ enabled: true,
810
+ intervalMs: 5 * 60 * 1000,
811
+ lastPolled: 0,
812
+ queryFn: () => smartflexInverterCategory.buildQuery(account),
813
+ parseFn: d => smartflexInverterCategory.parseResponse(d, discovered.inverterDeviceId),
814
+ poll: simplePoll(
815
+ () => smartflexInverterCategory.buildQuery(account),
816
+ d => smartflexInverterCategory.parseResponse(d, discovered.inverterDeviceId),
817
+ graphqlPost
818
+ ),
819
+ };
820
+ }
821
+
822
+ // The categories that need a device from discovery. Used by initCategories and by the
823
+ // empty-device re-check, so both set up the same polls (review4 #1). `lead` goes first
824
+ // in the list (the charging poll); `rest` goes after the account categories.
825
+ function deviceCategoryEntries(discovered) {
826
+ const lead = [];
827
+ const rest = [];
828
+ if (discovered.hasIntelligent) {
829
+ lead.push(intelligentCategoryEntry());
830
+ rest.push(completedDispatchesCategoryEntry());
831
+ }
832
+ if (discovered.vehicleDeviceId) rest.push(smartflexVehicleCategoryEntry(discovered));
833
+ if (discovered.inverterDeviceId && config.enableSmartflexInverter === true) {
834
+ rest.push(smartflexInverterCategoryEntry(discovered));
835
+ }
836
+ return { lead, rest };
837
+ }
838
+
839
+ async function initCategories(discovered) {
840
+ categories = [];
841
+ const deviceCategories = deviceCategoryEntries(discovered);
842
+
843
+ categories.push(...deviceCategories.lead);
844
+
845
+ const electricityEnabled = config.electricityEnabled !== false;
846
+ const gasEnabled = config.gasEnabled !== false;
847
+
848
+ if (discovered.hasElectricity && electricityEnabled) {
849
+ const ratesMs = (config.electricityRatesInterval || 60) * 60 * 1000;
850
+ const consumptionMs = (config.electricityConsumptionInterval || 60) * 60 * 1000;
851
+ categories.push({
852
+ id: 'electricity_rates',
853
+ enabled: true,
854
+ intervalMs: ratesMs,
855
+ lastPolled: 0,
856
+ queryFn: () => electricityCategory.buildRatesQuery(account),
857
+ parseFn: d => electricityCategory.parseRatesResponse(d),
858
+ poll: simplePoll(
859
+ () => electricityCategory.buildRatesQuery(account),
860
+ d => electricityCategory.parseRatesResponse(d),
861
+ graphqlPost
862
+ ),
863
+ });
864
+ categories.push({
865
+ id: 'electricity_consumption',
866
+ enabled: true,
867
+ intervalMs: consumptionMs,
868
+ lastPolled: 0,
869
+ queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
870
+ parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
871
+ poll: simplePoll(
872
+ () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
873
+ d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
874
+ graphqlPost
875
+ ),
876
+ });
877
+ }
878
+
879
+ if (discovered.hasGas && gasEnabled) {
880
+ const ratesMs = (config.gasRatesInterval || 60) * 60 * 1000;
881
+ const consumptionMs = (config.gasConsumptionInterval || 60) * 60 * 1000;
882
+ categories.push({
883
+ id: 'gas_rates',
884
+ enabled: true,
885
+ intervalMs: ratesMs,
886
+ lastPolled: 0,
887
+ queryFn: () => gasCategory.buildRatesQuery(account),
888
+ parseFn: d => gasCategory.parseRatesResponse(d),
889
+ poll: simplePoll(
890
+ () => gasCategory.buildRatesQuery(account),
891
+ d => gasCategory.parseRatesResponse(d),
892
+ graphqlPost
893
+ ),
894
+ });
895
+ categories.push({
896
+ id: 'gas_consumption',
897
+ enabled: true,
898
+ intervalMs: consumptionMs,
899
+ lastPolled: 0,
900
+ queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
901
+ parseFn: d => gasCategory.parseConsumptionResponse(d),
902
+ poll: simplePoll(
903
+ () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
904
+ d => gasCategory.parseConsumptionResponse(d),
905
+ graphqlPost
906
+ ),
907
+ });
908
+ }
909
+
910
+ categories.push({
911
+ id: 'wheel_of_fortune',
912
+ enabled: config.enableWheelOfFortune || false,
913
+ intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
914
+ lastPolled: 0,
915
+ queryFn: () => wheelOfFortuneCategory.buildQuery(account),
916
+ parseFn: d => wheelOfFortuneCategory.parseResponse(d),
917
+ poll: simplePoll(
918
+ () => wheelOfFortuneCategory.buildQuery(account),
919
+ d => wheelOfFortuneCategory.parseResponse(d),
920
+ graphqlPost
921
+ ),
922
+ });
923
+ if (discovered.smartMeterDeviceId) {
924
+ categories.push({
925
+ id: 'home_mini',
926
+ enabled: config.enableHomeMini || false,
927
+ intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
928
+ lastPolled: 0,
929
+ queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
930
+ parseFn: d => homeMiniCategory.parseResponse(d),
931
+ poll: simplePoll(
932
+ () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
933
+ d => homeMiniCategory.parseResponse(d),
934
+ graphqlPost
935
+ ),
936
+ });
937
+ }
938
+ categories.push({
939
+ id: 'saving_sessions',
940
+ enabled: true,
941
+ intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
942
+ lastPolled: 0,
943
+ queryFn: () => savingSessionsCategory.buildQuery(account),
944
+ parseFn: d => savingSessionsCategory.parseResponse(d),
945
+ poll: simplePoll(
946
+ () => savingSessionsCategory.buildQuery(account),
947
+ d => savingSessionsCategory.parseResponse(d),
948
+ graphqlPost
949
+ ),
950
+ });
951
+
952
+ // Completed dispatches and the SmartFlex categories.
953
+ categories.push(...deviceCategories.rest);
954
+
955
+ if (discovered.hasElectricity && discovered.electricityMpan) {
956
+ categories.push({
957
+ id: 'applicable_rates',
958
+ enabled: true,
959
+ intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
960
+ lastPolled: 0,
961
+ queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
962
+ parseFn: d => applicableRatesCategory.parseResponse(d),
963
+ poll: simplePoll(
964
+ () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
965
+ d => applicableRatesCategory.parseResponse(d),
966
+ graphqlPost
967
+ ),
968
+ });
969
+ }
970
+
971
+ // Export applicable rates — second query with the export MPAN. Same parser,
972
+ // different field prefix so the output keys don't collide with import.
973
+ if (discovered.hasElectricity && discovered.electricityExportMpan) {
974
+ categories.push({
975
+ id: 'applicable_rates_export',
976
+ errorField: 'electricity_export_rate_error',
977
+ enabled: true,
978
+ intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
979
+ lastPolled: 0,
980
+ queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
981
+ parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
982
+ poll: simplePoll(
983
+ () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
984
+ d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
985
+ graphqlPost
986
+ ),
987
+ });
988
+ }
989
+
990
+ if (discovered.hasElectricity && discovered.electricityMpan) {
991
+ categories.push({
992
+ id: 'free_electricity',
993
+ enabled: true,
994
+ intervalMs: 30 * 60 * 1000, // 30 minutes
995
+ lastPolled: 0,
996
+ queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
997
+ parseFn: d => freeElectricityCategory.parseResponse(d),
998
+ poll: simplePoll(
999
+ () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
1000
+ d => freeElectricityCategory.parseResponse(d),
1001
+ graphqlPost
1002
+ ),
1003
+ });
1004
+ }
1005
+
1006
+ categories.push({
1007
+ id: 'account',
1008
+ enabled: true,
1009
+ intervalMs: 60 * 60 * 1000,
1010
+ lastPolled: 0,
1011
+ queryFn: () => accountCategory.buildQuery(account),
1012
+ parseFn: d => accountCategory.parseResponse(d),
1013
+ poll: simplePoll(
1014
+ () => accountCategory.buildQuery(account),
1015
+ d => accountCategory.parseResponse(d),
1016
+ graphqlPost
1017
+ ),
1018
+ });
1019
+
1020
+ categories.push({
1021
+ id: 'octoplus',
1022
+ enabled: true,
1023
+ intervalMs: 60 * 60 * 1000,
1024
+ lastPolled: 0,
1025
+ queryFn: () => octoplusCategory.buildQuery(account),
1026
+ parseFn: d => octoplusCategory.parseResponse(d),
1027
+ poll: simplePoll(
1028
+ () => octoplusCategory.buildQuery(account),
1029
+ d => octoplusCategory.parseResponse(d),
1030
+ graphqlPost
1031
+ ),
1032
+ });
1033
+
1034
+ categories.push({
1035
+ id: 'update_check',
1036
+ enabled: true,
1037
+ intervalMs: 24 * 60 * 60 * 1000, // 24h — once daily npm registry check
1038
+ lastPolled: 0, // fires on first scheduler tick
1039
+ poll: intelligentUpdateCheck, // token ignored
1040
+ needsToken: false, // still runs when the Octopus token request fails
1041
+ });
1042
+ }
1043
+
1044
+ async function pollDueCategories(isStale) {
1045
+ if (nodeClosed) return;
1046
+ startDueChargingRetry();
1047
+ startDeferredChargingPoll();
1048
+ tickChargingPollGen = null;
1049
+ const result = await runTick({
1050
+ categories,
1051
+ state: lastKnownState,
1052
+ getToken: tickToken,
1053
+ // Stop at the next category once the node is closed, not only when superseded.
1054
+ isStale: () => nodeClosed || !!(isStale && isStale()),
1055
+ });
1056
+ // A retry tick whose poll never ran (e.g. auth failed) must not mark the next poll a retry.
1057
+ retryPollRunning = false;
1058
+ if (nodeClosed || (isStale && isStale())) return;
1059
+ if (!result.emitted) return;
1060
+ logCategoryFailures(result.changes);
1061
+ // Apply only this tick's changes onto the current state: a validation poll, a Charge
1062
+ // Cap change or an active-fields refresh may have written it while the tick waited
1063
+ // on Octopus. A slot timer may have changed charging_now, and a set_boost answer
1064
+ // boosting or boost_error, meanwhile (review F4).
1065
+ let changes = result.changes;
1066
+ // A change was sent or confirmed after this tick's charging poll started (for example
1067
+ // a validation poll while a later category ran): the poll's target, ready-by time and
1068
+ // Charge Cap are older than what the state holds now, so keep the state's values.
1069
+ if (tickChargingPollGen !== null && prefsGen !== tickChargingPollGen) {
1070
+ changes = Object.assign({}, changes);
1071
+ PREFERENCE_FIELDS.forEach((f) => { delete changes[f]; });
1072
+ }
1073
+ tickChargingPollGen = null;
1074
+ // charging_now, boosting and boost_error, and the pending target and ready-by time,
1075
+ // from the node's own values: a slot timer, a set_boost answer, or a slider or
1076
+ // ready-by change in Home Assistant that was not applied yet (it does not bump
1077
+ // prefsGen), may have changed them while the tick waited (review F4). The charging
1078
+ // poll sets these values itself, so they never disagree with a fresh poll.
1079
+ lastKnownState = mergePayload(mergePayload(lastKnownState, changes), {
1080
+ charging_now: chargingNow,
1081
+ boosting,
1082
+ boost_error: boostError,
1083
+ pending_limit: pendingLimit,
1084
+ pending_time: pendingTime,
1085
+ });
1086
+ if (enableMqtt && node.broker && node.broker.client) {
1087
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
1088
+ // v1.5 — publish update entity state only when version values change
1089
+ if (prevPublishedInstalled !== lastKnownState.installed_version
1090
+ || prevPublishedLatest !== lastKnownState.latest_version) {
1091
+ const updateState = {
1092
+ installed_version: lastKnownState.installed_version,
1093
+ latest_version: lastKnownState.latest_version || lastKnownState.installed_version,
1094
+ };
1095
+ node.broker.client.publish(`${stateTopic}/node_update`, JSON.stringify(updateState), { retain: true });
1096
+ prevPublishedInstalled = lastKnownState.installed_version;
1097
+ prevPublishedLatest = lastKnownState.latest_version;
1098
+ }
1099
+ }
1100
+ node.send({ payload: lastKnownState });
1101
+ if (lastKnownState.update_available === true
1102
+ && lastKnownState.latest_version
1103
+ && lastKnownState.latest_version !== lastWarnedVersion) {
1104
+ node.warn(`Update available: v${lastKnownState.latest_version} (running v${lastKnownState.installed_version}). Install via Node-RED → Manage Palette → Upgrade.`);
1105
+ lastWarnedVersion = lastKnownState.latest_version;
1106
+ }
1107
+ const octopusCategories = categories.filter((c) => c.enabled && c.needsToken !== false);
1108
+ const hasChargingPoll = categories.some((c) => c.id === 'intelligent');
1109
+ if (!hasChargingPoll) {
1110
+ // No car or charger: there is no "Confirmed" status to show, so show the first
1111
+ // Octopus poll error (red when every Octopus poll failed, yellow when some did).
1112
+ const failed = octopusCategories.filter((c) => lastKnownState[`${c.id}_error`]);
1113
+ if (failed.length > 0) {
1114
+ const first = failed[0];
1115
+ node.status({
1116
+ fill: failed.length === octopusCategories.length ? "red" : "yellow",
1117
+ shape: "ring",
1118
+ text: truncate(`${first.id}: ${lastKnownState[`${first.id}_error`]}`, 80),
1119
+ });
1120
+ } else {
1121
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
1122
+ }
1123
+ } else if (!validationMode) {
1124
+ if (writeNotApplied) {
1125
+ // A write that got no answer was checked by this tick's charging poll: not applied.
1126
+ node.status({ fill: "red", shape: "ring", text: writeNotApplied });
1127
+ writeNotApplied = null;
1128
+ } else if (lastKnownState.intelligent_error) {
1129
+ // "Error: KT-CT-4340: Unable to fetch planned dispatches", capped for the editor.
1130
+ // The "Error: " prefix is what 1.6.1 showed: flows can match it in a Status node.
1131
+ node.status({ fill: "red", shape: "ring", text: truncate('Error: ' + lastKnownState.intelligent_error, 80) });
1132
+ } else {
1133
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
1134
+ }
1135
+ }
1136
+ }
1137
+
1138
+ // A failed category poll (or update check) used to show only in its <id>_error field.
1139
+ // Warn once when a run of failures starts and log one line when it works again. The
1140
+ // charging poll logs its own failures, and a failed login is logged by tickToken.
1141
+ function logCategoryFailures(changes) {
1142
+ for (const cat of categories) {
1143
+ if (cat.id === 'intelligent') continue;
1144
+ const field = `${cat.id}_error`;
1145
+ if (!(field in changes)) continue; // not polled this tick
1146
+ const err = changes[field];
1147
+ if (typeof err === 'string' && err) {
1148
+ if (/^Auth failed: /.test(err)) continue;
1149
+ if (!cat.failureLogged) {
1150
+ cat.failureLogged = true;
1151
+ node.warn(`${cat.id} poll failed: ${truncate(err)}`);
1152
+ }
1153
+ } else if (err === null && cat.failureLogged) {
1154
+ cat.failureLogged = false;
1155
+ node.log(`${cat.id} poll working again`);
1156
+ }
1157
+ }
1158
+ }
1159
+
1160
+ // The tick's token request. A failure used to write nothing to the log (only the
1161
+ // *_error fields): warn once when a run of failures starts and log when it ends.
1162
+ let tickAuthFailing = false;
1163
+ async function tickToken() {
1164
+ let token;
1165
+ try {
1166
+ token = await obtainTickToken();
1167
+ } catch (e) {
1168
+ if (!tickAuthFailing && !nodeClosed) {
1169
+ tickAuthFailing = true;
1170
+ node.warn(`Octopus login failed: ${truncate(e.message)}. Polls try again with back-off.`);
1171
+ }
1172
+ throw e;
1173
+ }
1174
+ if (tickAuthFailing && !nodeClosed) {
1175
+ tickAuthFailing = false;
1176
+ node.log('Octopus login working again');
1177
+ }
1178
+ return token;
1179
+ }
1180
+
1181
+ async function obtainTickToken() {
1182
+ const response = await graphqlPost({
1183
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1184
+ variables: { input: { APIKey: apiKey } },
1185
+ });
1186
+ if (!response.data.data || !response.data.data.obtainKrakenToken) {
1187
+ const why = response.data.errors ? graphqlError(response.data.errors).message : JSON.stringify(response.data);
1188
+ throw new Error(truncate('Auth response missing token: ' + why));
1189
+ }
1190
+ return response.data.data.obtainKrakenToken.token;
1191
+ }
1192
+
1193
+ // forceSeq lets runTick keep the category due when this lands during its poll.
1194
+ function forceCategoryDue(id) {
1195
+ const cat = categories.find((c) => c.id === id);
1196
+ if (!cat) return;
1197
+ cat.forceSeq = (cat.forceSeq || 0) + 1;
1198
+ cat.lastPolled = 0;
1199
+ }
1200
+
1201
+ // A write mutation that got no answer (time-out, connection closed after the request
1202
+ // was sent, HTTP 5xx) may still have been applied by Octopus. Mark it so the caller
1203
+ // checks with the next charging poll rather than reporting a failure. A DNS or connect
1204
+ // error, an HTTP 4xx or an unreadable reply is a plain failure, and so is a GraphQL
1205
+ // refusal (it comes back as `errors`).
1206
+ function unconfirmedWrite(e) {
1207
+ if (!isUnconfirmedWriteError(e)) throw e;
1208
+ const err = new Error(e && e.message ? e.message : String(e));
1209
+ err.unconfirmed = true;
1210
+ throw err;
1211
+ }
1212
+
1213
+ // Writes that got no answer, checked against what the next charging poll reads.
1214
+ let unconfirmedPrefs = null; // { limit, time }
1215
+ let unconfirmedCap = null; // { enabled }
1216
+ let writeNotApplied = null; // red status text for the end of the tick: a check failed
1217
+
1218
+ // Called by a charging poll that read the preferences (prefsRead) and/or Charge Cap
1219
+ // (capRead). A match is a normal confirmed change; a mismatch means Octopus did not
1220
+ // apply the write.
1221
+ function checkUnconfirmedWrites(chargeCap, prefsRead, capRead) {
1222
+ if (unconfirmedPrefs && prefsRead) {
1223
+ const want = unconfirmedPrefs;
1224
+ unconfirmedPrefs = null;
1225
+ if (confirmedLimit === want.limit && confirmedTime === want.time) {
1226
+ node.log(`Preferences update confirmed: ${confirmedLimit}% @ ${confirmedTime}`);
1227
+ } else {
1228
+ node.warn(`Preferences update not applied: sent ${want.limit}% @ ${want.time}, Octopus has ${confirmedLimit}% @ ${confirmedTime}`);
1229
+ writeNotApplied = "Update Failed";
1230
+ }
1231
+ }
1232
+ if (unconfirmedCap && capRead) {
1233
+ const want = unconfirmedCap;
1234
+ unconfirmedCap = null;
1235
+ if (chargeCap === want.enabled) {
1236
+ node.log(`Charge Cap change confirmed: ${want.enabled ? "on" : "off"}`);
1237
+ } else {
1238
+ node.warn(`Charge Cap change not applied: sent ${want.enabled ? "on" : "off"}, Octopus has ${chargeCap === null ? "unknown" : (chargeCap ? "on" : "off")}`);
1239
+ writeNotApplied = "Charge Cap update failed";
1240
+ }
1241
+ }
1242
+ }
1243
+
1244
+ // limit/time are validated by the caller (or come from the API as confirmed values).
1245
+ async function setPreferences(limit, time) {
1246
+
1247
+ // Cancel any pending retry attempts from previous changes. A check already waiting
1248
+ // on Octopus sees the new generation and stops, so two chains never run at once.
1249
+ retryTimeouts.forEach(timeout => clearTimeout(timeout));
1250
+ retryTimeouts = [];
1251
+ const gen = ++validationGen;
1252
+ unconfirmedPrefs = null; // a newer change replaces one still to be checked
1253
+ writeNotApplied = null;
1254
+
1255
+ try {
1256
+ node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
1257
+
1258
+ // A. Get Token
1259
+ const authResponse = await graphqlPost({
1260
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1261
+ variables: { input: { APIKey: apiKey } }
1262
+ });
1263
+
1264
+ if (authResponse.data.errors) {
1265
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1266
+ }
1267
+ if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1268
+ throw new Error(`Auth response missing token data`);
1269
+ }
1270
+
1271
+ const token = authResponse.data.data.obtainKrakenToken.token;
1272
+
1273
+ // B. Send Mutation
1274
+ if (!krakenflexDeviceId) {
1275
+ throw new Error('Device ID not available — cannot set preferences');
1276
+ }
1277
+
1278
+ const mutation = `
1279
+ mutation setPreferences($input: SmartFlexDevicePreferencesInput!) {
1280
+ setDevicePreferences(input: $input) { __typename }
1281
+ }`;
1282
+
1283
+ const DAYS = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'];
1284
+ function buildDevicePreferencesInput(deviceId, socLimit, readyTime) {
1285
+ return {
1286
+ deviceId,
1287
+ mode: 'CHARGE',
1288
+ unit: 'PERCENTAGE',
1289
+ schedules: DAYS.map(dayOfWeek => ({
1290
+ dayOfWeek,
1291
+ time: readyTime + ':00',
1292
+ min: 0,
1293
+ max: socLimit
1294
+ }))
1295
+ };
1296
+ }
1297
+
1298
+ const variables = {
1299
+ input: buildDevicePreferencesInput(krakenflexDeviceId, limit, time)
1300
+ };
1301
+
1302
+ prefsGen++;
1303
+ const mutationResponse = await graphqlPost({
1304
+ query: mutation,
1305
+ variables: variables
1306
+ }, token).catch(unconfirmedWrite);
1307
+ if (nodeClosed) return;
1308
+ if (gen !== validationGen) return; // a newer submit owns validation now
1309
+
1310
+ if (mutationResponse.data.errors) {
1311
+ throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
1312
+ }
1313
+
1314
+ // Record mutation API usage (auth + mutation = ~250 complexity)
1315
+ const ESTIMATED_MUTATION_COMPLEXITY = 250;
1316
+ metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
1317
+
1318
+ // C. Start exponential backoff validation
1319
+ expectedLimit = limit;
1320
+ expectedTime = time;
1321
+ validationMode = true;
1322
+ node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
1323
+
1324
+ // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
1325
+ const retryIntervals = [15000, 30000, 60000, 120000];
1326
+ scheduleRetries(retryIntervals, 0, gen);
1327
+
1328
+ } catch (err) {
1329
+ if (nodeClosed) return;
1330
+ if (err.unconfirmed) {
1331
+ node.warn(`Preferences update not confirmed (${short(err.message)}) - checking with Octopus`);
1332
+ } else {
1333
+ node.error("Failed to set preferences: " + short(err.message));
1334
+ if (err.response) {
1335
+ node.error(`Response: ${short(JSON.stringify(err.response.data))}`);
1336
+ }
1337
+ }
1338
+ if (gen !== validationGen) return; // a newer submit owns the status and validation
1339
+ expectedLimit = null;
1340
+ expectedTime = null;
1341
+ validationMode = false;
1342
+ if (err.unconfirmed) {
1343
+ unconfirmedPrefs = { limit, time }; // the next charging poll checks it
1344
+ node.status({ fill: "yellow", shape: "ring", text: "Update unconfirmed - checking" });
1345
+ forceCategoryDue('intelligent'); // the next tick reads what Octopus has
1346
+ return;
1347
+ }
1348
+ node.status({ fill: "red", shape: "ring", text: "Update Failed" });
1349
+ }
1350
+ }
1351
+
1352
+ function scheduleRetries(intervals, index, gen) {
1353
+ if (nodeClosed || gen !== validationGen) return;
1354
+ if (index >= intervals.length) {
1355
+ // All retries exhausted, let normal interval take over
1356
+ node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
1357
+ expectedLimit = null;
1358
+ expectedTime = null;
1359
+ validationMode = false;
1360
+ return;
1361
+ }
1362
+
1363
+ const timeout = setTimeout(async () => {
1364
+ await fetchDataWithValidation(intervals, index, gen);
1365
+ }, intervals[index]);
1366
+
1367
+ retryTimeouts.push(timeout);
1368
+ }
1369
+
1370
+ async function fetchDataWithValidation(intervals, currentIndex, gen) {
1371
+ try {
1372
+ const token = await obtainTickToken();
1373
+ const partial = await intelligentPoll(token);
1374
+ if (nodeClosed || gen !== validationGen) return;
1375
+ lastKnownState = Object.assign({}, lastKnownState, partial, { intelligent_error: null });
1376
+ if (enableMqtt && node.broker && node.broker.client) {
1377
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
1378
+ }
1379
+ node.send({ payload: lastKnownState });
1380
+
1381
+ const validated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
1382
+ if (validated) {
1383
+ prefsGen++; // a charging poll still in flight read the old values
1384
+ validationMode = false;
1385
+ retryTimeouts.forEach((t) => clearTimeout(t));
1386
+ retryTimeouts = [];
1387
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
1388
+ return;
1389
+ }
1390
+ const totalAttempts = intervals.length;
1391
+ const attempt = currentIndex + 1;
1392
+ if (currentIndex < intervals.length - 1) {
1393
+ node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
1394
+ scheduleRetries(intervals, currentIndex + 1, gen);
1395
+ } else {
1396
+ validationMode = false;
1397
+ node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
1398
+ }
1399
+ } catch (error) {
1400
+ if (nodeClosed || gen !== validationGen) return;
1401
+ node.warn(`Retry ${currentIndex + 1} failed: ${short(error.message)}`);
1402
+ if (currentIndex < intervals.length - 1) {
1403
+ scheduleRetries(intervals, currentIndex + 1, gen);
1404
+ } else {
1405
+ validationMode = false;
1406
+ node.status({ fill: "red", shape: "ring", text: "Validation failed" });
1407
+ }
1408
+ }
1409
+ }
1410
+
1411
+ // Helper: Toggle smart charging on/off
1412
+ async function setSmartCharging(enable) {
1413
+ if (!krakenflexDeviceId) {
1414
+ node.warn("Device ID not available — cannot toggle smart charging");
1415
+ return;
1416
+ }
1417
+
1418
+ // Cancel any pending verification retries
1419
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1420
+ smartChargingRetryTimeouts = [];
1421
+
1422
+ const previousSuspended = smartChargingSuspended;
1423
+
1424
+ try {
1425
+ node.status({ fill: "blue", shape: "dot", text: enable ? "Enabling smart charging..." : "Suspending smart charging..." });
1426
+
1427
+ const authResponse = await graphqlPost({
1428
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1429
+ variables: { input: { APIKey: apiKey } }
1430
+ });
1431
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1432
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1433
+ }
1434
+ const token = authResponse.data.data.obtainKrakenToken.token;
1435
+
1436
+ const action = enable ? "UNSUSPEND" : "SUSPEND";
1437
+ const mutationResponse = await graphqlPost({
1438
+ query: `mutation UpdateSmartControl($deviceId: ID!, $action: SmartControlAction!) { updateDeviceSmartControl(input: { deviceId: $deviceId, action: $action }) { id } }`,
1439
+ variables: { deviceId: krakenflexDeviceId, action: action }
1440
+ }, token).catch(unconfirmedWrite);
1441
+ if (nodeClosed) return;
1442
+
1443
+ if (mutationResponse.data.errors) {
1444
+ throw new Error(`Smart charging mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
1445
+ }
1446
+
1447
+ // Record mutation API usage (auth + mutation = ~250 complexity)
1448
+ const ESTIMATED_MUTATION_COMPLEXITY = 250;
1449
+ metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
1450
+
1451
+ // Optimistically update cached state
1452
+ const expectedSuspended = !enable;
1453
+ smartChargingSuspended = expectedSuspended;
1454
+
1455
+ // Publish new state to HA switch topic immediately
1456
+ publishSmartChargingState(true);
1457
+
1458
+ // Schedule verification: 15s / 30s / 60s / 120s
1459
+ smartChargingVerifying = true;
1460
+ scheduleSmartChargingVerification(expectedSuspended, [15000, 30000, 60000, 120000], 0);
1461
+
1462
+ } catch (e) {
1463
+ if (nodeClosed) return;
1464
+ if (e.unconfirmed) {
1465
+ // No answer: Octopus may have made the change. The switch keeps the last known
1466
+ // state while the usual 15/30/60/120 s checks read what Octopus has.
1467
+ node.warn(`Smart charging change not confirmed (${short(e.message)}) - checking with Octopus`);
1468
+ smartChargingSuspended = previousSuspended;
1469
+ publishSmartChargingState(true);
1470
+ node.status({ fill: "yellow", shape: "ring", text: "Smart charging unconfirmed - checking" });
1471
+ smartChargingVerifying = true;
1472
+ scheduleSmartChargingVerification(!enable, [15000, 30000, 60000, 120000], 0);
1473
+ return;
1474
+ }
1475
+ node.error(`Failed to toggle smart charging: ${short(e.message)}`);
1476
+ // Revert optimistic update to pre-mutation state
1477
+ smartChargingSuspended = previousSuspended;
1478
+ smartChargingVerifying = false;
1479
+ node.status({ fill: "red", shape: "ring", text: "Smart charging update failed" });
1480
+ // Republish previous state so HA switch UI re-syncs
1481
+ publishSmartChargingState(true);
1482
+ }
1483
+ }
1484
+
1485
+ // Helper: Toggle Charge Cap (off-peak-only smart charging). State is confirmed by the
1486
+ // next intelligent poll, so no bespoke verification loop.
1487
+ async function setChargeCap(enabled) {
1488
+ if (!krakenflexDeviceId) {
1489
+ node.warn("Device ID not available — cannot change Charge Cap");
1490
+ return;
1491
+ }
1492
+ const previous = lastKnownState ? lastKnownState.charge_cap : null;
1493
+ unconfirmedCap = null; // a newer change replaces one still to be checked
1494
+ writeNotApplied = null;
1495
+ try {
1496
+ node.status({ fill: "blue", shape: "dot", text: enabled ? "Enabling Charge Cap..." : "Disabling Charge Cap..." });
1497
+ const token = await obtainTickToken();
1498
+ prefsGen++;
1499
+ const res = await graphqlPost({
1500
+ query: `mutation SetChargeCap($input: UpdateIsChargingDurationCappedInput!) { updateIsChargingDurationCapped(input: $input) { __typename } }`,
1501
+ variables: { input: { deviceId: krakenflexDeviceId, enabled } }
1502
+ }, token).catch(unconfirmedWrite);
1503
+ if (nodeClosed) return;
1504
+ if (res.data.errors) {
1505
+ throw new Error(`Charge Cap mutation failed: ${JSON.stringify(res.data.errors)}`);
1506
+ }
1507
+ metrics.recordPoll(250); // auth + mutation, same estimate as other mutations
1508
+ lastKnownState = mergePayload(lastKnownState, { charge_cap: enabled });
1509
+ if (enableMqtt && node.broker && node.broker.client) {
1510
+ node.broker.client.publish(`${stateTopic}/charge_cap`, enabled ? "ON" : "OFF", { retain: true });
1511
+ }
1512
+ node.status({ fill: "green", shape: "dot", text: `Charge Cap ${enabled ? "on" : "off"}` });
1513
+ forceCategoryDue('intelligent'); // next tick confirms from the API
1514
+ } catch (e) {
1515
+ if (nodeClosed) return;
1516
+ if (e.unconfirmed) {
1517
+ unconfirmedCap = { enabled }; // the next charging poll checks it
1518
+ node.warn(`Charge Cap change not confirmed (${short(e.message)}) - checking with Octopus`);
1519
+ node.status({ fill: "yellow", shape: "ring", text: "Charge Cap unconfirmed - checking" });
1520
+ forceCategoryDue('intelligent'); // the next tick reads what Octopus has
1521
+ } else {
1522
+ node.error(`Failed to change Charge Cap: ${short(e.message)}`);
1523
+ node.status({ fill: "red", shape: "ring", text: "Charge Cap update failed" });
1524
+ }
1525
+ // Republish previous state so the HA switch re-syncs
1526
+ if (enableMqtt && node.broker && node.broker.client && typeof previous === 'boolean') {
1527
+ node.broker.client.publish(`${stateTopic}/charge_cap`, previous ? "ON" : "OFF", { retain: true });
1528
+ }
1529
+ }
1530
+ }
1531
+
1532
+ // Boosting changed (mutation read-back): publish it and let charging_now follow,
1533
+ // since a boost counts as charging (charging_now = slot active OR boosting).
1534
+ function applyBoosting(value) {
1535
+ if (typeof value !== 'boolean') return;
1536
+ boosting = value;
1537
+ boostingConfirmedAt = Date.now();
1538
+ lastKnownState = mergePayload(lastKnownState, { boosting: value });
1539
+ publishBoostSwitch(value);
1540
+ const shouldBeCharging = chargingNowFor(cachedSlots, boosting);
1541
+ if (shouldBeCharging !== chargingNow) publishChargingState(shouldBeCharging);
1542
+ }
1543
+
1544
+ // Boost Charge switch state topic (retained): ON, OFF, or None, which Home Assistant
1545
+ // shows as unknown.
1546
+ function publishBoostSwitch(value) {
1547
+ if (!(enableMqtt && node.broker && node.broker.client)) return;
1548
+ const text = value === true ? "ON" : value === false ? "OFF" : "None";
1549
+ node.broker.client.publish(`${stateTopic}/boost`, text, { retain: true });
1550
+ }
1551
+
1552
+ // A set_boost that failed: warn, set boost_error and send it at once (a refusal forces
1553
+ // no poll), and put the HA switch back to the last known state so it re-syncs.
1554
+ function reportBoostFailure(enabled, rawError) {
1555
+ const label = enabled ? "Boost request" : "Boost cancel";
1556
+ // Masked and cut here, so boost_error keeps its contract whatever the caller passes.
1557
+ const error = truncate(rawError == null ? 'Unknown error' : rawError);
1558
+ node.warn(`${label} failed: ${error}`);
1559
+ boostError = error;
1560
+ boostErrorAt = Date.now();
1561
+ lastKnownState = mergePayload(lastKnownState, { boost_error: error });
1562
+ node.status({ fill: "red", shape: "ring", text: `${label} failed` });
1563
+ if (typeof boosting === 'boolean') publishBoostSwitch(boosting);
1564
+ if (enableMqtt && node.broker && node.broker.client) {
1565
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
1566
+ }
1567
+ // Tagged like the other extra messages (review L6), so a flow can tell it from a poll.
1568
+ node.send({
1569
+ payload: lastKnownState,
1570
+ debug: { timestamp: new Date().toISOString(), trigger: 'boost_failed', request: enabled ? 'BOOST' : 'CANCEL', error },
1571
+ });
1572
+ }
1573
+
1574
+ // Boost requests are serialised (sweep #2/#3, review F2): one updateBoostCharge in flight,
1575
+ // the latest requested value wins, a repeat of the value in flight (or just sent and
1576
+ // accepted) is dropped, and mutations are at least BOOST_SPACING_MS apart. A flood of ON/OFF messages
1577
+ // therefore makes only a few calls, and ON then OFF can never reach Octopus out of order.
1578
+ const BOOST_SPACING_MS = 5000;
1579
+ // A request still unanswered after this long is given up (review A1): a connection that
1580
+ // drops mid-answer can leave it pending for ever, and the queue would wait for ever too.
1581
+ // 2 x the 30 s request timeout (auth + mutation) plus a margin.
1582
+ const BOOST_WATCHDOG_MS = 75 * 1000;
1583
+ const boostQueue = { inFlight: null, pending: null, lastValue: null, lastOk: false, lastAt: 0, timer: null, watchdog: null };
1584
+ // Review A5: a flow or automation that asks again after every refusal would otherwise
1585
+ // send the same refused request every 5 s, all day, on the API key the polls use.
1586
+ // 3 refusals of one value in 10 minutes pause that value for 10 minutes (one warning).
1587
+ // An accepted request ends the pause.
1588
+ const BOOST_REFUSAL_LIMIT = 3;
1589
+ const BOOST_REFUSAL_WINDOW_MS = 10 * 60 * 1000;
1590
+ const BOOST_PAUSE_MS = 10 * 60 * 1000;
1591
+ let boostRefusals = { value: null, times: [] };
1592
+ let boostPause = null; // { value, until }
1593
+
1594
+ function noteBoostRefusal(enabled) {
1595
+ const now = Date.now();
1596
+ if (boostRefusals.value !== enabled) boostRefusals = { value: enabled, times: [] };
1597
+ boostRefusals.times = boostRefusals.times.filter((t) => now - t < BOOST_REFUSAL_WINDOW_MS);
1598
+ boostRefusals.times.push(now);
1599
+ if (boostRefusals.times.length < BOOST_REFUSAL_LIMIT) return;
1600
+ boostRefusals = { value: null, times: [] };
1601
+ boostPause = { value: enabled, until: now + BOOST_PAUSE_MS };
1602
+ const what = enabled ? "boost requests" : "boost cancels";
1603
+ node.warn(`Octopus refused ${BOOST_REFUSAL_LIMIT} ${what} in ${BOOST_REFUSAL_WINDOW_MS / 60000} minutes: ignoring further ${what} for ${BOOST_PAUSE_MS / 60000} minutes`);
1604
+ }
1605
+
1606
+ function clearBoostRefusals() {
1607
+ boostRefusals = { value: null, times: [] };
1608
+ boostPause = null;
1609
+ }
1610
+
1611
+ function requestBoost(enabled) {
1612
+ if (nodeClosed) return;
1613
+ const q = boostQueue;
1614
+ if (boostPause && boostPause.value === enabled) {
1615
+ if (Date.now() < boostPause.until) {
1616
+ // Paused after repeated refusals: ignored (the warning was logged once).
1617
+ if (typeof boosting === 'boolean' && boosting !== enabled) publishBoostSwitch(boosting);
1618
+ return;
1619
+ }
1620
+ boostPause = null;
1621
+ }
1622
+ if (q.inFlight !== null) {
1623
+ // Sent when the one in flight ends; asking for the in-flight value cancels it.
1624
+ q.pending = enabled === q.inFlight ? null : enabled;
1625
+ return;
1626
+ }
1627
+ // Already done and Octopus agrees (e.g. a flow sending set_boost true in a loop).
1628
+ // After a refusal, or once the boost has ended, the same value is sent again.
1629
+ const alreadyDone = enabled === q.lastValue && q.lastOk && boosting === enabled;
1630
+ const waitMs = q.lastAt + BOOST_SPACING_MS - Date.now();
1631
+ if (alreadyDone || waitMs > 0) {
1632
+ // The latest request wins: a repeat of the value just sent and accepted cancels a
1633
+ // waiting one and is dropped. After a failure the same value waits for the gap
1634
+ // and is sent again, instead of being dropped (review A9).
1635
+ const repeat = alreadyDone || (enabled === q.lastValue && q.lastOk);
1636
+ q.pending = repeat ? null : enabled;
1637
+ if (q.pending === null) {
1638
+ if (q.timer) { clearTimeout(q.timer); q.timer = null; }
1639
+ // The HA switch may show the tapped value: put it back to the known state.
1640
+ if (typeof boosting === 'boolean' && boosting !== enabled) publishBoostSwitch(boosting);
1641
+ } else if (!q.timer) {
1642
+ q.timer = setTimeout(sendPendingBoost, waitMs);
1643
+ }
1644
+ return;
1645
+ }
1646
+ sendBoost(enabled);
1647
+ }
1648
+
1649
+ function sendPendingBoost() {
1650
+ boostQueue.timer = null;
1651
+ const value = boostQueue.pending;
1652
+ boostQueue.pending = null;
1653
+ if (value !== null) requestBoost(value);
1654
+ }
1655
+
1656
+ function sendBoost(enabled) {
1657
+ const q = boostQueue;
1658
+ // This request replaces any one waiting for the gap (review A8): a late timer
1659
+ // must not send an older value after this newer one.
1660
+ if (q.timer) { clearTimeout(q.timer); q.timer = null; }
1661
+ q.pending = null;
1662
+ q.inFlight = enabled;
1663
+ q.lastValue = enabled;
1664
+ q.lastOk = false;
1665
+ q.lastAt = Date.now();
1666
+ // abandoned: the watchdog gave up on this request, so a late answer changes nothing.
1667
+ const call = { settled: false, abandoned: false };
1668
+ const done = (ok) => {
1669
+ if (call.settled) return;
1670
+ call.settled = true;
1671
+ if (q.watchdog) { clearTimeout(q.watchdog); q.watchdog = null; }
1672
+ q.lastOk = ok === true;
1673
+ q.inFlight = null;
1674
+ if (nodeClosed || q.pending === null) return;
1675
+ const value = q.pending;
1676
+ q.pending = null;
1677
+ requestBoost(value); // waits out the spacing if this one was quick
1678
+ };
1679
+ q.watchdog = setTimeout(() => {
1680
+ q.watchdog = null;
1681
+ if (call.settled || nodeClosed) return;
1682
+ call.abandoned = true;
1683
+ // The request may still have reached Octopus: report it, then poll to find out.
1684
+ reportBoostFailure(enabled, `No answer from Octopus after ${Math.round(BOOST_WATCHDOG_MS / 1000)}s`);
1685
+ requestChargingPoll();
1686
+ done(false);
1687
+ }, BOOST_WATCHDOG_MS);
1688
+ // A newer, different request is waiting: this answer must not move the switch.
1689
+ setBoost(enabled, call, () => q.pending !== null).then(done, () => done(false));
1690
+ }
1691
+
1692
+ // A forced charging poll also queries flexPlannedDispatches, so it goes through the same
1693
+ // rate window as the quick retries (review F2). Not allowed now: it runs when allowed.
1694
+ let deferredChargingPollAt = null;
1695
+
1696
+ function requestChargingPoll() {
1697
+ const now = Date.now();
1698
+ const allowedAt = dispatchRate.nextAllowedAt(now);
1699
+ if (allowedAt <= now) {
1700
+ deferredChargingPollAt = null;
1701
+ forceCategoryDue('intelligent');
1702
+ return;
1703
+ }
1704
+ if (deferredChargingPollAt === null) {
1705
+ node.log(`Charging poll after boost waits ${Math.ceil((allowedAt - now) / 1000)}s: 3 planned-dispatch queries already went out this minute`);
1706
+ }
1707
+ deferredChargingPollAt = allowedAt;
1708
+ }
1709
+
1710
+ // Called at the start of each tick, next to startDueChargingRetry.
1711
+ function startDeferredChargingPoll() {
1712
+ if (deferredChargingPollAt === null || Date.now() < deferredChargingPollAt) return;
1713
+ deferredChargingPollAt = null;
1714
+ requestChargingPoll();
1715
+ }
1716
+
1717
+ // Helper: Boost charge (charge now, outside the plan) or cancel a boost. Different from
1718
+ // setSmartCharging, which suspends/resumes Octopus control. Octopus may refuse (e.g. car
1719
+ // unplugged or full); its error is passed through, not second-guessed here.
1720
+ // Called through requestBoost only, so one runs at a time. Resolves true when Octopus
1721
+ // accepted the request and its answer was used.
1722
+ async function setBoost(enabled, call, isSuperseded) {
1723
+ const label = enabled ? "Boost request" : "Boost cancel";
1724
+ // Closed, or given up by the watchdog: a late answer changes nothing.
1725
+ const gone = () => nodeClosed || call.abandoned;
1726
+ const superseded = () => {
1727
+ if (!isSuperseded || !isSuperseded()) return false;
1728
+ node.log(`${label} answered, but a newer request follows: ignoring this answer`);
1729
+ return true;
1730
+ };
1731
+ const fail = (error) => reportBoostFailure(enabled, error);
1732
+ if (!krakenflexDeviceId) {
1733
+ fail("Device ID not available");
1734
+ return false;
1735
+ }
1736
+ try {
1737
+ node.status({ fill: "blue", shape: "dot", text: enabled ? "Requesting boost..." : "Cancelling boost..." });
1738
+ const token = await obtainTickToken();
1739
+ if (gone()) return false;
1740
+ const res = await graphqlPost(buildBoostRequest(krakenflexDeviceId, enabled), token);
1741
+ if (gone()) return false;
1742
+ metrics.recordPoll(250); // auth + mutation, same estimate as other mutations
1743
+ if (superseded()) {
1744
+ // This one may have changed the device; if the newer one is refused, only a
1745
+ // poll shows the real state (review A2).
1746
+ requestChargingPoll();
1747
+ return false;
1748
+ }
1749
+ const result = parseBoostResponse(res);
1750
+ if (!result.ok && result.unclear) {
1751
+ // Not clear whether it went through (review A2): do not flip the state or
1752
+ // report a refusal; a charging poll reads what Octopus really did.
1753
+ node.warn(`${label}: unclear answer from Octopus (${result.error}). Checking the boost state with a charging poll`);
1754
+ node.status({ fill: "yellow", shape: "ring", text: `${label}: checking` });
1755
+ if (typeof boosting === 'boolean') publishBoostSwitch(boosting); // re-sync HA
1756
+ requestChargingPoll();
1757
+ return false;
1758
+ }
1759
+ if (!result.ok) {
1760
+ // Octopus refused: nothing changed on the device, so no forced poll.
1761
+ fail(result.error);
1762
+ noteBoostRefusal(enabled);
1763
+ return false;
1764
+ }
1765
+ clearBoostRefusals();
1766
+ node.log(enabled ? "Boost requested" : "Boost cancelled");
1767
+ boostError = null;
1768
+ lastKnownState = mergePayload(lastKnownState, { boost_error: null });
1769
+ // Octopus accepted it, but its device state can lag behind (sweep #4): show the
1770
+ // requested state and hold it until a later poll agrees or BOOST_HOLD_MS passes,
1771
+ // so a stale read-back or poll cannot snap the switch back.
1772
+ const acceptedAt = Date.now();
1773
+ boostHold = { value: enabled, since: acceptedAt, until: acceptedAt + BOOST_HOLD_MS };
1774
+ if (typeof result.boosting === 'boolean' && result.boosting !== enabled) {
1775
+ node.log(`${label} accepted. Octopus still reports ${result.currentState}, so the switch stays ${enabled ? "on" : "off"} while it catches up`);
1776
+ }
1777
+ applyBoosting(enabled);
1778
+ node.status({ fill: "green", shape: "dot", text: enabled ? "Boost requested" : "Boost cancelled" });
1779
+ } catch (e) {
1780
+ if (gone()) return false;
1781
+ if (superseded()) {
1782
+ requestChargingPoll(); // it may still have reached Octopus
1783
+ return false;
1784
+ }
1785
+ // No answer (e.g. a timeout): the request may still have reached Octopus.
1786
+ fail(e.message);
1787
+ requestChargingPoll();
1788
+ return false;
1789
+ }
1790
+ requestChargingPoll(); // poll soon so device state, charging_now and slots update
1791
+ return true;
1792
+ }
1793
+
1794
+ function scheduleSmartChargingVerification(expectedSuspended, intervals, index) {
1795
+ if (nodeClosed) return;
1796
+ if (index >= intervals.length) {
1797
+ smartChargingVerifying = false; // the next charging poll reports the real state
1798
+ node.warn("Smart charging state could not be confirmed after all retries");
1799
+ node.status({ fill: "red", shape: "ring", text: "Smart charging: update unconfirmed" });
1800
+ return;
1801
+ }
1802
+ const timeout = setTimeout(async () => {
1803
+ try {
1804
+ const authResponse = await graphqlPost({
1805
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1806
+ variables: { input: { APIKey: apiKey } }
1807
+ });
1808
+ if (nodeClosed) return;
1809
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1810
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1811
+ return;
1812
+ }
1813
+ const token = authResponse.data.data.obtainKrakenToken.token;
1814
+
1815
+ const deviceResponse = await graphqlPost({
1816
+ query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1817
+ variables: { accountNumber: account }
1818
+ }, token);
1819
+ if (nodeClosed) return;
1820
+
1821
+ if (deviceResponse.data.errors || !deviceResponse.data.data) {
1822
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1823
+ return;
1824
+ }
1825
+
1826
+ const evDevice = intelligentCategory.extractEvDevice(deviceResponse.data.data.devices, preferredEvId);
1827
+ if (!evDevice) {
1828
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1829
+ return;
1830
+ }
1831
+
1832
+ // Record verification API usage (auth + device query = ~200 complexity)
1833
+ const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
1834
+ metrics.recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
1835
+
1836
+ const actualSuspended = evDevice.status.isSuspended;
1837
+ if (actualSuspended === expectedSuspended) {
1838
+ // Confirmed — clear remaining retries
1839
+ smartChargingSuspended = actualSuspended;
1840
+ smartChargingVerifying = false;
1841
+ publishSmartChargingState();
1842
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1843
+ smartChargingRetryTimeouts = [];
1844
+ node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
1845
+ node.status({ fill: "green", shape: "dot", text: actualSuspended ? "Smart charging suspended" : "Smart charging enabled" });
1846
+ } else {
1847
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1848
+ }
1849
+ } catch (e) {
1850
+ if (nodeClosed) return;
1851
+ node.warn(`Smart charging verification attempt ${index + 1} failed: ${short(e.message)}`);
1852
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1853
+ }
1854
+ }, intervals[index]);
1855
+ smartChargingRetryTimeouts.push(timeout);
1856
+ }
1857
+
1858
+ // 6. Logic: Update Check (bespoke poll that ignores token)
1859
+ async function intelligentUpdateCheck(/* token ignored */) {
1860
+ return checkUpdate(httpGetJson, require('./package.json').version);
1861
+ }
1862
+
1863
+ // 6. Logic: Intelligent Poll (single-scheduler bespoke poll)
1864
+ async function intelligentPoll(token, isStale) {
1865
+ const pollStartedAt = Date.now();
1866
+ deferredChargingPollAt = null; // this poll covers a deferred one
1867
+ const prefsGenAtStart = prefsGen;
1868
+ // 1. devices query
1869
+ const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
1870
+ let devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
1871
+ // Closed or superseded while waiting: don't send the dispatch query.
1872
+ if (nodeClosed || (isStale && isStale())) throw new Error('Poll superseded');
1873
+ // The device status is non-null inside a non-null list, so an error on it (e.g.
1874
+ // KT-CT-4360) nulls the whole device list. Ask once more without the status: the
1875
+ // preferences, Charge Cap and device id still come through, and the Smart Charging
1876
+ // switch keeps its last value.
1877
+ let statusUnavailable = false;
1878
+ if (intelligentCategory.statusNulledDevices(devicesResponse.data.errors, devicesResponse.data.data)) {
1879
+ const statusCode = errorCode(devicesResponse.data.errors.find((e) => errorCode(e))) || null;
1880
+ const retry = intelligentCategory.buildDevicesQuery(account, false);
1881
+ devicesResponse = await graphqlPost({ query: retry.query, variables: retry.variables }, token);
1882
+ if (nodeClosed || (isStale && isStale())) throw new Error('Poll superseded');
1883
+ statusUnavailable = true;
1884
+ if (!statusWarned) {
1885
+ statusWarned = true;
1886
+ node.warn(`Smart charging state unavailable${statusCode ? ` (${statusCode})` : ''} - keeping the last value until Octopus returns it`);
1887
+ }
1888
+ }
1889
+ // An error on the Charge Cap field alone (KT-CT-4360 pattern) or on the preferences
1890
+ // (KT-CT-4339; the same resolver backs both aliases) must not stop the slot updates:
1891
+ // keep the last confirmed values and still read the dispatches.
1892
+ const devicesData = devicesResponse.data.data || null;
1893
+ const hasDeviceList = !!devicesData && Array.isArray(devicesData.devices);
1894
+ // The query lists every device on the account. An error on another one (an inverter,
1895
+ // a second charger) says nothing about the EV, so it is left out (review A11): it
1896
+ // must not freeze the EV's switch, preferences and boost state.
1897
+ const polledEv = hasDeviceList ? intelligentCategory.extractEvDevice(devicesData.devices, preferredEvId) : null;
1898
+ const evIndex = polledEv ? devicesData.devices.indexOf(polledEv) : -1;
1899
+ const isOtherDeviceError = (e) => evIndex !== -1 && Array.isArray(e && e.path)
1900
+ && e.path[0] === 'devices' && Number.isInteger(e.path[1]) && e.path[1] !== evIndex;
1901
+ const allDevicesErrors = Array.isArray(devicesResponse.data.errors) ? devicesResponse.data.errors : null;
1902
+ const evDevicesErrors = allDevicesErrors ? allDevicesErrors.filter((e) => !isOtherDeviceError(e)) : null;
1903
+ if (allDevicesErrors && evDevicesErrors.length < allDevicesErrors.length && !otherDeviceErrorLogged) {
1904
+ otherDeviceErrorLogged = true; // once: it can repeat every poll
1905
+ const other = allDevicesErrors.find(isOtherDeviceError);
1906
+ node.log(`Charging poll: Octopus could not read another device on the account (${truncate(graphqlError([other]).message, 120)}). Ignored: it does not affect the EV`);
1907
+ }
1908
+ const devicesErrors = allDevicesErrors
1909
+ ? (evDevicesErrors.length > 0 ? evDevicesErrors : undefined)
1910
+ : devicesResponse.data.errors;
1911
+ const fieldErrorsOnly = onlyDeviceFieldErrors(devicesErrors, devicesData, TOLERATED_DEVICE_FIELDS);
1912
+ // Device list itself missing, but only because of a tolerated field (for example a
1913
+ // KT-CT-4339 that nulled the list, or the status error again on the ask without it):
1914
+ // the cached id still works.
1915
+ const toleratedNoList = !!devicesErrors && !hasDeviceList && !!krakenflexDeviceId
1916
+ && Array.isArray(devicesErrors) && devicesErrors.length > 0
1917
+ && devicesErrors.every((e) => errorCode(e) === PREFERENCES_ERROR_CODE
1918
+ || (Array.isArray(e.path) && e.path[0] === 'devices' && TOLERATED_DEVICE_FIELDS.includes(e.path[2])));
1919
+ if (devicesErrors && !fieldErrorsOnly && !toleratedNoList) throw graphqlError(devicesErrors, 'Devices query failed');
1920
+ if (!devicesData) throw new Error('Devices response missing data');
1921
+ const fieldFailed = (f) => toleratedNoList
1922
+ || (fieldErrorsOnly && devicesErrors.some((e) => e.path[2] === f));
1923
+ const prefsFailed = fieldFailed('preferences');
1924
+ const chargeCapFailed = fieldFailed('chargeCap');
1925
+ // smartStatus carries isSuspended and currentState (boosting, device_state); both unknown
1926
+ // when the status errored or the poll asked again without it.
1927
+ const smartStatusFailed = statusUnavailable || fieldFailed('smartStatus');
1928
+ const suspended = hasDeviceList && !smartStatusFailed
1929
+ ? intelligentCategory.extractSuspended(devicesData.devices, preferredEvId) : null;
1930
+ if (!statusUnavailable && suspended !== null) statusWarned = false; // read again: warn on the next streak
1931
+ let deviceId = krakenflexDeviceId;
1932
+ if (hasDeviceList) {
1933
+ if (!polledEv) throw new Error('No ELECTRIC_VEHICLES device found on account');
1934
+ deviceId = polledEv.id;
1935
+ krakenflexDeviceId = deviceId;
1936
+ }
1937
+
1938
+ // 2. dispatches query (the single one that used to be duplicated by V1 + V2)
1939
+ const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(deviceId);
1940
+ noteDispatchQuery();
1941
+ const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
1942
+ if (dispatchResponse.data.errors) throw graphqlError(dispatchResponse.data.errors, 'Dispatches query failed');
1943
+ if (!dispatchResponse.data.data) throw new Error('Dispatches response missing data');
1944
+
1945
+ // 3. parse twice — intelligent (slots/window) + flex-planned-dispatches (array/count)
1946
+ const data = { devices: hasDeviceList ? devicesData.devices : [], flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
1947
+ const appliedTz = resolveTimezone(node);
1948
+ const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (e) { return 'UTC'; } })();
1949
+ const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz, evId: preferredEvId });
1950
+ const { _activeSlots, ...catPublic } = catResult;
1951
+ if (chargeCapFailed) delete catPublic.charge_cap; // unknown this poll: keep the last value
1952
+ if (prefsFailed) {
1953
+ // parseResponse fell back to defaults: keep the last confirmed schedule instead.
1954
+ delete catPublic.confirmed_limit;
1955
+ delete catPublic.confirmed_time;
1956
+ }
1957
+ if (smartStatusFailed || catPublic.boosting === null) delete catPublic.boosting; // unknown: keep the last value
1958
+ if (smartStatusFailed || catPublic.device_state === null) delete catPublic.device_state; // same source as boosting
1959
+ const flexResult = flexPlannedDispatchesCategory.parseResponse(dispatchResponse.data.data);
1960
+
1961
+ // A late answer from a closed node or a superseded poll must not reset timers.
1962
+ if (nodeClosed || (isStale && isStale())) throw new Error('Poll superseded');
1963
+
1964
+ // A change was sent or confirmed while this poll waited: its target, ready-by time
1965
+ // and Charge Cap are older than that. Keep the dispatches, drop those values and read
1966
+ // again on the next tick.
1967
+ const prefsStale = prefsGen !== prefsGenAtStart;
1968
+ if (prefsStale) {
1969
+ delete catPublic.confirmed_limit;
1970
+ delete catPublic.confirmed_time;
1971
+ delete catPublic.charge_cap;
1972
+ forceCategoryDue('intelligent');
1973
+ }
1974
+
1975
+ // 4. metrics + side effects
1976
+ noteChargingPollSuccess();
1977
+ metrics.recordPoll(300);
1978
+ if (!prefsFailed && !prefsStale) {
1979
+ confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
1980
+ confirmedTime = catResult.confirmed_time || confirmedTime;
1981
+ }
1982
+ if (!validationMode && !prefsStale) {
1983
+ pendingLimit = confirmedLimit;
1984
+ pendingTime = confirmedTime;
1985
+ }
1986
+ if (prefsFailed) {
1987
+ // One line covers both aliases (they share the preferences resolver).
1988
+ const code = errorCode(devicesErrors[0]);
1989
+ node.warn(`Charging preferences unavailable this poll${code ? ` (${code})` : ''} - keeping ${confirmedLimit}% @ ${confirmedTime}`);
1990
+ }
1991
+ if (prefsStale) {
1992
+ // The Charge Cap switch keeps what the newer change set.
1993
+ } else if (chargeCapFailed) {
1994
+ if (!prefsFailed) node.warn("Charge Cap state unavailable this poll — keeping the last known value");
1995
+ } else if (typeof catResult.charge_cap === 'boolean') {
1996
+ if (enableMqtt && node.broker && node.broker.client) {
1997
+ node.broker.client.publish(`${stateTopic}/charge_cap`, catResult.charge_cap ? "ON" : "OFF", { retain: true });
1998
+ }
1999
+ } else if (!chargeCapNaWarned) {
2000
+ chargeCapNaWarned = true;
2001
+ node.warn("Charge Cap not applicable for this device — switch will show unknown");
2002
+ }
2003
+ // Smart charging changed outside the node (e.g. in the Octopus app). A toggle still
2004
+ // waiting for confirmation wins: Octopus can report the old state for a while.
2005
+ if (suspended !== null && !smartChargingVerifying) {
2006
+ smartChargingSuspended = suspended;
2007
+ publishSmartChargingState();
2008
+ }
2009
+ if (typeof catPublic.boosting === 'boolean') {
2010
+ // The device state was read: an old boost refusal no longer applies.
2011
+ if (boostError !== null && pollStartedAt >= boostErrorAt + BOOST_ERROR_CLEAR_MS) boostError = null;
2012
+ // A set_boost Octopus accepted is held until a poll sent after it agrees, or
2013
+ // until BOOST_HOLD_MS has passed; then the poll wins (as smartChargingVerifying).
2014
+ if (boostHold) {
2015
+ const agrees = catPublic.boosting === boostHold.value;
2016
+ if (agrees && pollStartedAt >= boostHold.since) {
2017
+ boostHold = null;
2018
+ } else if (Date.now() >= boostHold.until) {
2019
+ if (!agrees) node.log(`Octopus still reports boosting=${catPublic.boosting} ${Math.round(BOOST_HOLD_MS / 60000)} min after the boost change: showing what Octopus reports`);
2020
+ boostHold = null;
2021
+ } else {
2022
+ catPublic.boosting = boostHold.value;
2023
+ }
2024
+ }
2025
+ boosting = catPublic.boosting;
2026
+ boostingConfirmedAt = Date.now();
2027
+ publishBoostSwitch(boosting);
2028
+ }
2029
+ checkUnconfirmedWrites(catResult.charge_cap, !prefsFailed && !prefsStale, !chargeCapFailed && !prefsStale);
2030
+ setupChargingTimers(_activeSlots); // charging_now = slot active OR boosting
2031
+ if (!stateCheckInterval) startStateReconciliation();
2032
+ updateNextPollTime();
2033
+
2034
+ const apiMetrics = metrics.getMetrics();
2035
+
2036
+ // 5. merged partial payload (no pending values from a poll whose preferences are stale)
2037
+ const pending = prefsStale ? {} : { pending_limit: pendingLimit, pending_time: pendingTime };
2038
+ return Object.assign({}, catPublic, flexResult, pending, {
2039
+ charging_now: chargingNow,
2040
+ next_poll: nextPollTime,
2041
+ next_poll_raw: nextPollTime,
2042
+ refresh_available_at: getRefreshAvailableAt(),
2043
+ api_requests_hour: apiMetrics.requests_last_hour,
2044
+ api_complexity_hour: apiMetrics.complexity_last_hour,
2045
+ api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
2046
+ timezone_detected: serverTz,
2047
+ timezone_applied: appliedTz,
2048
+ smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
2049
+ boost_error: boostError,
2050
+ });
2051
+ }
2052
+
2053
+
2054
+ // Helper: Fetch device ID and initial smart charging state (called once at startup)
2055
+ async function fetchDeviceId() {
2056
+ try {
2057
+ const authResponse = await graphqlPost({
2058
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
2059
+ variables: { input: { APIKey: apiKey } }
2060
+ });
2061
+ if (nodeClosed) return; // closed while waiting: send nothing more
2062
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
2063
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
2064
+ }
2065
+ const token = authResponse.data.data.obtainKrakenToken.token;
2066
+
2067
+ const deviceResponse = await graphqlPost({
2068
+ query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
2069
+ variables: { accountNumber: account }
2070
+ }, token);
2071
+ if (nodeClosed) return; // closed while waiting: no publish, no log
2072
+
2073
+ if (deviceResponse.data.errors || !deviceResponse.data.data) {
2074
+ throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
2075
+ }
2076
+
2077
+ const evDevice = intelligentCategory.extractEvDevice(deviceResponse.data.data.devices, preferredEvId);
2078
+ if (!evDevice) {
2079
+ throw new Error('No ELECTRIC_VEHICLES device found on account');
2080
+ }
2081
+
2082
+ krakenflexDeviceId = evDevice.id;
2083
+ if (evDevice.status && typeof evDevice.status.isSuspended === 'boolean') {
2084
+ smartChargingSuspended = evDevice.status.isSuspended;
2085
+ publishSmartChargingState();
2086
+ }
2087
+ node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
2088
+ } catch (e) {
2089
+ if (nodeClosed) return;
2090
+ // Keep whatever discovery or a charging poll has found meanwhile.
2091
+ node.warn(`Failed to fetch device ID at startup: ${short(e.message)}. Smart charging toggle unavailable until the first charging poll.`);
2092
+ }
2093
+ }
2094
+
2095
+ // 6a. Charging Now - Timer Management Functions
2096
+
2097
+ // State reconciliation - checks every 10s if charging state matches reality
2098
+ // A boost counts as charging, so it is never corrected back to false (lib/boost.js).
2099
+ function reconcileChargingState() {
2100
+ expireStaleBoosting();
2101
+ const shouldBeCharging = reconcileChargingNow({ slots: cachedSlots, boosting, chargingNow });
2102
+ if (shouldBeCharging !== null) {
2103
+ node.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
2104
+ publishChargingState(shouldBeCharging);
2105
+ }
2106
+ }
2107
+
2108
+ // Sweep #5: boosting is only as good as the last time Octopus confirmed it. With no
2109
+ // confirmation for 2 charging-poll intervals (an outage, repeated status errors) it is
2110
+ // unknown, so a boost that ended long ago cannot hold charging_now on for ever.
2111
+ function boostingTtlMs() {
2112
+ const cat = categories.find((c) => c.id === 'intelligent');
2113
+ return 2 * (cat ? cat.intervalMs : refreshRate);
2114
+ }
2115
+
2116
+ function expireStaleBoosting() {
2117
+ if (boosting === null || !boostingConfirmedAt) return;
2118
+ const age = Date.now() - boostingConfirmedAt;
2119
+ if (age <= boostingTtlMs()) return;
2120
+ const text = `Boost state not confirmed by Octopus for ${formatDuration(age)}: treating it as unknown`;
2121
+ if (boosting === true) node.warn(text); else node.log(text);
2122
+ boosting = null;
2123
+ boostHold = null;
2124
+ lastKnownState = mergePayload(lastKnownState, { boosting: null });
2125
+ // The HA Boost switch shows unknown too, not its last ON or OFF (review A7).
2126
+ publishBoostSwitch(null);
2127
+ const shouldBeCharging = chargingNowFor(cachedSlots, null);
2128
+ if (shouldBeCharging !== chargingNow) publishChargingState(shouldBeCharging);
2129
+ }
2130
+
2131
+ // Saving session / free electricity / current rate flags change at their start and end
2132
+ // times, not when the category is polled. Recompute them from the stored data (no API
2133
+ // call) and publish only when a value changed.
2134
+ function refreshActiveFields() {
2135
+ if (nodeClosed) return;
2136
+ const changed = changedActiveFields(lastKnownState, Date.now());
2137
+ if (!changed) return;
2138
+ lastKnownState = mergePayload(lastKnownState, changed);
2139
+ if (enableMqtt && node.broker && node.broker.client) {
2140
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
2141
+ }
2142
+ node.send({
2143
+ payload: lastKnownState,
2144
+ debug: { timestamp: new Date().toISOString(), trigger: 'active_fields_change', changed: Object.keys(changed) },
2145
+ });
2146
+ }
2147
+
2148
+ // Start state reconciliation loop (every 10 seconds)
2149
+ function startStateReconciliation() {
2150
+ if (nodeClosed) return; // a late callback must not leave an interval on a closed node
2151
+ // Clear existing interval
2152
+ if (stateCheckInterval) {
2153
+ clearInterval(stateCheckInterval);
2154
+ }
2155
+
2156
+ // Check state every 10 seconds
2157
+ stateCheckInterval = setInterval(() => {
2158
+ reconcileChargingState();
2159
+ refreshActiveFields();
2160
+ }, 10000);
2161
+
2162
+ node.log("State reconciliation loop started (every 10s)");
2163
+ }
2164
+
2165
+ // Clear all charging timers
2166
+ function clearChargingTimers() {
2167
+ if (preValidationTimer) {
2168
+ clearTimeout(preValidationTimer);
2169
+ preValidationTimer = null;
2170
+ }
2171
+ if (slotStartTimer) {
2172
+ clearTimeout(slotStartTimer);
2173
+ slotStartTimer = null;
2174
+ }
2175
+ if (slotEndTimer) {
2176
+ clearTimeout(slotEndTimer);
2177
+ slotEndTimer = null;
2178
+ }
2179
+ if (stateCheckInterval) {
2180
+ clearInterval(stateCheckInterval);
2181
+ stateCheckInterval = null;
2182
+ }
2183
+ }
2184
+
2185
+ // Manual refresh rate limiting helpers
2186
+ function canManualRefresh() {
2187
+ const now = Date.now();
2188
+ const timeSinceLastRefresh = now - lastManualRefresh;
2189
+ return lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN;
2190
+ }
2191
+
2192
+ function getSecondsUntilNextRefresh() {
2193
+ const now = Date.now();
2194
+ const timeSinceLastRefresh = now - lastManualRefresh;
2195
+ const timeRemaining = MANUAL_REFRESH_COOLDOWN - timeSinceLastRefresh;
2196
+ return Math.max(0, Math.ceil(timeRemaining / 1000));
2197
+ }
2198
+
2199
+ function getRefreshAvailableAt() {
2200
+ const now = Date.now();
2201
+ const timeSinceLastRefresh = now - lastManualRefresh;
2202
+
2203
+ // If never refreshed OR cooldown expired, ready now
2204
+ if (lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN) {
2205
+ return null; // Ready - no cooldown
2206
+ }
2207
+
2208
+ // Cooldown active - return timestamp when it expires
2209
+ return new Date(lastManualRefresh + MANUAL_REFRESH_COOLDOWN).toISOString();
2210
+ }
2211
+
2212
+ function publishRefreshCooldownState() {
2213
+ if (enableMqtt && node.broker) {
2214
+ const fullState = {
2215
+ ...lastKnownState,
2216
+ refresh_available_at: getRefreshAvailableAt()
2217
+ };
2218
+ node.broker.client.publish(stateTopic, stateJson(fullState), { retain: true });
2219
+ }
2220
+ }
2221
+
2222
+ // Polling metrics helpers
2223
+ function updateNextPollTime() {
2224
+ nextPollTime = new Date(Date.now() + refreshRate).toISOString();
2225
+ }
2226
+
2227
+ // Retained charging_now topic for the Home Assistant binary_sensor
2228
+ function publishChargingNowTopic(state) {
2229
+ chargingNowPublished = true;
2230
+ if (enableMqtt && node.broker && node.broker.client) {
2231
+ node.broker.client.publish(`${stateTopic}/charging_now`, state ? "ON" : "OFF", { retain: true });
2232
+ }
2233
+ }
2234
+
2235
+ // Publish charging state to MQTT and Node-RED
2236
+ function publishChargingState(state) {
2237
+ chargingNow = state;
2238
+ // Keep the JSON state in step, so every later message and publish carries it.
2239
+ lastKnownState = mergePayload(lastKnownState, { charging_now: state });
2240
+
2241
+ // Update MQTT
2242
+ publishChargingNowTopic(state);
2243
+
2244
+ // Output message to Node-RED flow if state actually changed
2245
+ if (lastSentChargingState !== state) {
2246
+ lastSentChargingState = state;
2247
+
2248
+ // Merge updated charging_now into last known full state
2249
+ const outputPayload = {
2250
+ ...lastKnownState,
2251
+ charging_now: state
2252
+ };
2253
+
2254
+ node.send({
2255
+ payload: outputPayload,
2256
+ debug: {
2257
+ timestamp: new Date().toISOString(),
2258
+ trigger: 'charging_state_change',
2259
+ success: true,
2260
+ previous_state: !state,
2261
+ new_state: state
2262
+ }
2263
+ });
2264
+
2265
+ node.log(`Charging state changed: ${!state} → ${state}, message sent`);
2266
+ }
2267
+ }
2268
+
2269
+ // Setup pre-validation timer (30s before slot starts)
2270
+ function setupPreValidationTimer(nextSlot) {
2271
+ if (nodeClosed) return;
2272
+ const now = new Date();
2273
+ const slotStart = new Date(nextSlot.start);
2274
+ const preValidationTime = slotStart.getTime() - 30000; // 30s before
2275
+ const msUntilPreValidation = preValidationTime - now.getTime();
2276
+
2277
+ if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
2278
+ preValidationTimer = setTimeout(async () => {
2279
+ if (nodeClosed) return;
2280
+ node.warn("Pre-validating slot data (30s before start)");
2281
+ try {
2282
+ if (!krakenflexDeviceId) {
2283
+ throw new Error("Device ID not available for pre-validation");
2284
+ }
2285
+
2286
+ const authResponse = await graphqlPost({
2287
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
2288
+ variables: { input: { APIKey: apiKey } }
2289
+ });
2290
+
2291
+ if (nodeClosed) return;
2292
+ if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
2293
+ throw new Error("Pre-validation auth failed");
2294
+ }
2295
+
2296
+ const token = authResponse.data.data.obtainKrakenToken.token;
2297
+
2298
+ const { query: dq, variables: dv } = intelligentCategory.buildDispatchQuery(krakenflexDeviceId);
2299
+ noteDispatchQuery(); // counts toward the retry rate limit
2300
+ const dataResponse = await graphqlPost({ query: dq, variables: dv }, token);
2301
+ if (nodeClosed) return;
2302
+ // Kraken fails with HTTP 200, GraphQL errors and null data (e.g. KT-CT-4340):
2303
+ // a failed check, so fall back to the cached slot below.
2304
+ if (dataResponse.data.errors) throw graphqlError(dataResponse.data.errors, 'Dispatches query failed');
2305
+ if (!dataResponse.data.data || !dataResponse.data.data.flexPlannedDispatches) {
2306
+ throw new Error('Dispatches response missing data');
2307
+ }
2308
+
2309
+ const freshSlots = dataResponse.data.data.flexPlannedDispatches;
2310
+ // Octopus re-planned since the last poll: poll now so the slot/window
2311
+ // sensors match what charging_now is about to do.
2312
+ if (intelligentCategory.slotsChanged(cachedSlots, freshSlots)) {
2313
+ node.warn("Charging plan changed since last poll - refreshing");
2314
+ forceCategoryDue('intelligent');
2315
+ }
2316
+ cachedSlots = freshSlots;
2317
+
2318
+ // Record pre-validation API usage (auth + simple query = ~200 complexity)
2319
+ const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
2320
+ metrics.recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
2321
+
2322
+ // Check if slot still exists (within 1 minute tolerance)
2323
+ const stillExists = cachedSlots.find(s =>
2324
+ Math.abs(new Date(s.start).getTime() - slotStart.getTime()) < 60000
2325
+ );
2326
+
2327
+ if (stillExists) {
2328
+ node.warn(`Slot confirmed at ${stillExists.start}`);
2329
+ setupSlotStartTimer(stillExists);
2330
+ } else {
2331
+ // Cancel the start timer armed from the known plan.
2332
+ if (slotStartTimer) { clearTimeout(slotStartTimer); slotStartTimer = null; }
2333
+ node.warn("Slot was cancelled or modified - not setting start timer");
2334
+ }
2335
+ } catch (error) {
2336
+ if (nodeClosed) return;
2337
+ node.warn(`Pre-validation failed: ${short(error.message)}, using cached slot`);
2338
+ // Fallback: use original slot data
2339
+ setupSlotStartTimer(nextSlot);
2340
+ }
2341
+ }, msUntilPreValidation);
2342
+
2343
+ const minutesUntil = Math.round(msUntilPreValidation / 60000);
2344
+ node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
2345
+ // Arm the start from the known plan now. Pre-validation makes two requests of up to
2346
+ // 30 s each; if they are still running at the slot start, the slot starts on time
2347
+ // anyway. Pre-validation then moves the timer (slot confirmed) or cancels it.
2348
+ setupSlotStartTimer(nextSlot);
2349
+ } else if (msUntilPreValidation <= 0 && slotStart.getTime() > now.getTime()) {
2350
+ // Polled inside the last 30s (e.g. the refresh after a re-plan): the data is
2351
+ // already fresh, so set the start timer directly instead of losing it.
2352
+ setupSlotStartTimer(nextSlot);
2353
+ }
2354
+ }
2355
+
2356
+ // Setup slot start timer (exact start time)
2357
+ function setupSlotStartTimer(slot) {
2358
+ if (nodeClosed) return;
2359
+ // A poll and an in-flight pre-validation can both set this; never leave an orphan.
2360
+ if (slotStartTimer) { clearTimeout(slotStartTimer); slotStartTimer = null; }
2361
+ const now = new Date();
2362
+ const slotStart = new Date(slot.start);
2363
+ const msUntilStart = slotStart.getTime() - now.getTime();
2364
+
2365
+ if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
2366
+ slotStartTimer = setTimeout(() => {
2367
+ publishChargingState(true);
2368
+ node.warn(`Charging slot started at ${slot.start}`);
2369
+ setupSlotEndTimer(slot);
2370
+ }, msUntilStart);
2371
+
2372
+ const secondsUntil = Math.round(msUntilStart / 1000);
2373
+ node.log(`Slot start timer set for ${secondsUntil}s (${slot.start})`);
2374
+ } else if (msUntilStart <= 0) {
2375
+ // Slot already started, check if it's still active
2376
+ const slotEnd = new Date(slot.end);
2377
+ if (slotEnd > now) {
2378
+ // Already on when the start timer armed from the known plan has fired.
2379
+ if (!chargingNow) publishChargingState(true);
2380
+ setupSlotEndTimer(slot);
2381
+ }
2382
+ }
2383
+ }
2384
+
2385
+ // Setup slot end timer (exact end time)
2386
+ function setupSlotEndTimer(slot) {
2387
+ if (nodeClosed) return;
2388
+ if (slotEndTimer) { clearTimeout(slotEndTimer); slotEndTimer = null; }
2389
+ const now = new Date();
2390
+ const slotEnd = new Date(slot.end);
2391
+ const msUntilEnd = slotEnd.getTime() - now.getTime();
2392
+
2393
+ if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
2394
+ slotEndTimer = setTimeout(() => {
2395
+ node.warn(`Charging slot ended at ${slot.end}`);
2396
+
2397
+ // Check if another slot starts immediately (within cached data)
2398
+ const now = new Date();
2399
+ const immediateNextSlot = cachedSlots.find(s => {
2400
+ const start = new Date(s.start);
2401
+ const end = new Date(s.end);
2402
+ return start <= now && end > now;
2403
+ });
2404
+
2405
+ if (immediateNextSlot) {
2406
+ node.warn("Next slot starting immediately");
2407
+ publishChargingState(true);
2408
+ setupSlotEndTimer(immediateNextSlot);
2409
+ } else {
2410
+ publishChargingState(boosting === true); // a boost keeps charging_now on
2411
+ }
2412
+ }, msUntilEnd);
2413
+
2414
+ const minutesUntil = Math.round(msUntilEnd / 60000);
2415
+ node.log(`Slot end timer set for ${minutesUntil} min (${slot.end})`);
2416
+ }
2417
+ }
2418
+
2419
+ // Main timer setup - called on each poll
2420
+ function setupChargingTimers(slots) {
2421
+ if (nodeClosed) return;
2422
+ // Clear existing timers
2423
+ clearChargingTimers();
2424
+
2425
+ // Cache slots for later use
2426
+ cachedSlots = slots;
2427
+
2428
+ const now = new Date();
2429
+
2430
+ // Check if currently in a charging slot
2431
+ const activeSlot = slots.find(s => {
2432
+ const start = new Date(s.start);
2433
+ const end = new Date(s.end);
2434
+ return start <= now && end > now;
2435
+ });
2436
+
2437
+ if (activeSlot) {
2438
+ // Currently charging
2439
+ const newState = true;
2440
+ if (chargingNow !== newState) {
2441
+ publishChargingState(newState);
2442
+ }
2443
+ setupSlotEndTimer(activeSlot);
2444
+ node.log("Currently charging - end timer set");
2445
+ } else {
2446
+ // No slot active: charging only if a boost is running
2447
+ const newState = boosting === true;
2448
+ if (chargingNow !== newState) {
2449
+ publishChargingState(newState);
2450
+ } else if (!chargingNowPublished) {
2451
+ // First poll since start: overwrite a retained ON left from before a restart.
2452
+ publishChargingNowTopic(newState);
2453
+ }
2454
+
2455
+ // Find next future slot
2456
+ const nextSlot = slots.find(s => new Date(s.start) > now);
2457
+
2458
+ if (nextSlot) {
2459
+ setupPreValidationTimer(nextSlot);
2460
+ node.log(`Next slot at ${nextSlot.start}`);
2461
+ }
2462
+ }
2463
+ }
2464
+
2465
+ // 7. Event Listeners
2466
+
2467
+ // Helper: Publish current state (both pending and confirmed)
2468
+ // This merges pending values into last known full state to prevent sensors going unknown
2469
+ function publishCurrentState() {
2470
+ if (enableMqtt && node.broker) {
2471
+ // Merge pending values into last known state
2472
+ const fullState = {
2473
+ ...lastKnownState,
2474
+ pending_limit: pendingLimit,
2475
+ pending_time: pendingTime,
2476
+ confirmed_limit: confirmedLimit,
2477
+ confirmed_time: confirmedTime
2478
+ };
2479
+ node.broker.client.publish(stateTopic, stateJson(fullState), { retain: false });
2480
+ }
2481
+ }
2482
+
2483
+ // A. Handle Node-RED Input Messages (NO rate limiting - programmers control this)
2484
+ node.on('input', function (msg) {
2485
+ // Check for control commands (preference updates)
2486
+ if (msg.payload && typeof msg.payload === 'object') {
2487
+ const plan = planCommands(msg.payload, { confirmedLimit, confirmedTime });
2488
+ plan.errors.forEach((e) => node.error(e, msg));
2489
+ if (plan.errors.length && !plan.actions.length) {
2490
+ node.status({ fill: "red", shape: "ring", text: plan.errors[0].split(' —')[0] });
2491
+ }
2492
+ for (const a of plan.actions) {
2493
+ if (a.type === 'preferences') setPreferences(a.limit, a.time);
2494
+ else if (a.type === 'timezone') {
2495
+ node.context().set('timezone', a.timezone);
2496
+ node.log(`Timezone set to: ${a.timezone}`);
2497
+ }
2498
+ else if (a.type === 'smart_charging') setSmartCharging(a.enabled);
2499
+ else if (a.type === 'charge_cap') setChargeCap(a.enabled);
2500
+ else if (a.type === 'boost') requestBoost(a.enabled);
2501
+ }
2502
+ if (plan.hasCommand) return; // commands never trigger a manual refresh
2503
+ }
2504
+
2505
+ // Manual refresh request from Node-RED - NO rate limiting
2506
+ // (Programmers can control rate limiting in their flows if needed)
2507
+ // Update timestamp so HA sees cooldown, but don't block the refresh
2508
+ lastManualRefresh = Date.now();
2509
+ node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
2510
+ forceCategoryDue('intelligent');
2511
+ });
2512
+
2513
+ // B. Handle MQTT Commands (Home Assistant)
2514
+ if (enableMqtt && node.broker) {
2515
+ node.broker.register(this);
2516
+
2517
+ // Subscribe with this node's id as the ref so close can remove exactly these
2518
+ // subscriptions (Node-RED broker API: subscribe(topic, options, callback, ref)).
2519
+ const subscribeCommand = (topic, callback) => node.broker.subscribe(topic, 0, callback, node.id);
2520
+
2521
+ // Action commands (they write to Octopus or force a poll) ignore retained messages.
2522
+ // The broker replays a retained message on every restart, redeploy and reconnect, so
2523
+ // a retained ON on set_boost would boost again each time. Home Assistant publishes
2524
+ // these without retain; a live publish reaches the node with the retain flag off.
2525
+ const retainedWarned = new Set();
2526
+ const subscribeAction = (topic, callback) => subscribeCommand(topic, (t, payload, packet) => {
2527
+ if (packet && packet.retain === true) {
2528
+ if (!retainedWarned.has(topic)) {
2529
+ retainedWarned.add(topic);
2530
+ node.warn(`Ignored a retained message on ${topic}. Commands are never taken from retained messages. Clear it by publishing an empty retained message to that topic.`);
2531
+ }
2532
+ return;
2533
+ }
2534
+ callback(t, payload, packet);
2535
+ });
2536
+
2537
+ // Slider changed - update pending value only
2538
+ subscribeCommand(cmdTopicLimit, (topic, payload) => {
2539
+ const r = validateLimit(payload.toString());
2540
+ if (!r.ok) {
2541
+ node.warn(r.error);
2542
+ publishCurrentState(); // snap slider back
2543
+ return;
2544
+ }
2545
+ pendingLimit = r.limit;
2546
+ publishCurrentState(); // Update display immediately
2547
+ node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
2548
+ });
2549
+
2550
+ // Dropdown changed - update pending value only
2551
+ subscribeCommand(cmdTopicTime, (topic, payload) => {
2552
+ const r = validateTime(payload.toString());
2553
+ if (!r.ok) {
2554
+ node.warn(r.error);
2555
+ publishCurrentState(); // snap dropdown back
2556
+ return;
2557
+ }
2558
+ pendingTime = r.time;
2559
+ publishCurrentState(); // Update display immediately
2560
+ node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
2561
+ });
2562
+
2563
+ // Button pressed - submit changes to API
2564
+ subscribeAction(cmdTopicSubmit, (topic, payload) => {
2565
+ setPreferences(pendingLimit, pendingTime);
2566
+ });
2567
+
2568
+ // Refresh button pressed - MQTT has hardcoded 30s rate limiting
2569
+ subscribeAction(cmdTopicRefresh, (topic, payload) => {
2570
+ // Check rate limit (only for MQTT button)
2571
+ if (!canManualRefresh()) {
2572
+ const secondsRemaining = getSecondsUntilNextRefresh();
2573
+ node.status({
2574
+ fill: "red",
2575
+ shape: "dot",
2576
+ text: `Cooldown: ${secondsRemaining}s`
2577
+ });
2578
+ node.warn(`MQTT refresh blocked. Please wait ${secondsRemaining} seconds.`);
2579
+ return; // Block the refresh
2580
+ }
2581
+
2582
+ // Refresh allowed - set cooldown timestamp
2583
+ lastManualRefresh = Date.now();
2584
+
2585
+ // Publish immediate update with countdown timestamp
2586
+ publishRefreshCooldownState();
2587
+
2588
+ // Schedule cleanup at exactly 30 seconds to clear countdown
2589
+ if (cooldownExpiryTimer) clearTimeout(cooldownExpiryTimer);
2590
+ cooldownExpiryTimer = setTimeout(() => {
2591
+ // Cooldown expired - publish null to clear countdown in HA
2592
+ publishRefreshCooldownState();
2593
+ cooldownExpiryTimer = null;
2594
+ }, MANUAL_REFRESH_COOLDOWN);
2595
+
2596
+ // Trigger the actual refresh
2597
+ node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
2598
+ forceCategoryDue('intelligent');
2599
+ });
2600
+
2601
+ // Timezone select changed in Home Assistant
2602
+ subscribeCommand(cmdTopicTimezone, (topic, payload) => {
2603
+ const text = payload.toString();
2604
+ if (text.trim().length === 0) return; // empty: ignored
2605
+ const r = validateTimezone(text);
2606
+ if (!r.ok) {
2607
+ node.error(r.error); // nothing stored or published
2608
+ return;
2609
+ }
2610
+ node.context().set('timezone', r.timezone);
2611
+ node.log(`Timezone set via MQTT to: ${r.timezone}`);
2612
+ node.broker.client.publish(`${stateTopic}/timezone`, r.timezone, { retain: true });
2613
+ });
2614
+
2615
+ // Smart charging switch toggled in Home Assistant
2616
+ subscribeAction(cmdTopicSmartCharging, (topic, payload) => {
2617
+ const val = payload.toString().trim();
2618
+ if (val === "ON") setSmartCharging(true);
2619
+ else if (val === "OFF") setSmartCharging(false);
2620
+ });
2621
+
2622
+ // Charge Cap switch toggled in HA
2623
+ subscribeAction(cmdTopicChargeCap, (topic, payload) => {
2624
+ const val = payload.toString().trim();
2625
+ if (val === "ON") setChargeCap(true);
2626
+ else if (val === "OFF") setChargeCap(false);
2627
+ });
2628
+
2629
+ // Boost Charge switch toggled in HA
2630
+ subscribeAction(cmdTopicBoost, (topic, payload) => {
2631
+ const val = payload.toString().trim();
2632
+ if (val === "ON") requestBoost(true);
2633
+ else if (val === "OFF") requestBoost(false);
2634
+ else node.warn(`Ignored set_boost command '${truncate(val, 40)}': send ON or OFF`);
2635
+ });
2636
+
2637
+ initTimeout(announceControls, 2000);
2638
+
2639
+ // Republish persisted timezone to HA select on startup
2640
+ initTimeout(() => {
2641
+ try {
2642
+ const persistedTz = node.context().get('timezone');
2643
+ if (persistedTz && node.broker) {
2644
+ node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
2645
+ }
2646
+ } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
2647
+ }, 2500);
2648
+
2649
+ // The smart charging switch state is published by the startup device fetch,
2650
+ // discovery and every charging poll as soon as each one knows it.
2651
+ }
2652
+
2653
+ // Init
2654
+ initTimeout(fetchDeviceId, 1500);
2655
+
2656
+ // V2 category discovery and scheduler. Retries with backoff until discovery succeeds
2657
+ // (a transient Kraken error at startup used to leave the node with no scheduler until
2658
+ // restart). Tracked + nodeClosed-guarded so a redeploy can never leave an orphan
2659
+ // scheduler or retry timer.
2660
+ async function startV2(attempt) {
2661
+ if (nodeClosed) return;
2662
+ try {
2663
+ const discovered = await discoverProducts(apiKey, account, { isClosed: () => nodeClosed });
2664
+ if (nodeClosed) return;
2665
+ applyDiscoveredSuspended(discovered);
2666
+ await initCategories(discovered);
2667
+ if (nodeClosed) return;
2668
+ announceSmartflexEntities(discovered);
2669
+ node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}, vehicle=${!!discovered.vehicleDeviceId}, inverter=${!!discovered.inverterDeviceId}${discovered.inverterDeviceId && config.enableSmartflexInverter !== true ? ' (inverter option off)' : ''}`);
2670
+ const v2Scheduler = createScheduler(pollDueCategories, {
2671
+ onStuck: (ms) => node.warn(`Poll still running after ${Math.round(ms / 1000)}s - starting a new poll`),
2672
+ });
2673
+ v2Scheduler.start();
2674
+ node._v2Scheduler = v2Scheduler;
2675
+ // The 10 s tick also keeps the "active now" fields current, so run it on
2676
+ // accounts without a charger too (the charging poll restarts it with its timers).
2677
+ if (!stateCheckInterval) startStateReconciliation();
2678
+ // An empty device list can be transient: check again before giving up on a charger.
2679
+ if (!discovered.hasIntelligent && discovered.deviceCount === 0) scheduleDeviceCheck(0);
2680
+ } catch (e) {
2681
+ if (nodeClosed) return;
2682
+ const delay = discoveryRetryDelay(attempt);
2683
+ const secs = Math.round(delay / 1000);
2684
+ node.warn(`V2 discovery failed: ${short(e.message)}. Retrying in ${secs}s.`);
2685
+ node.status({ fill: "yellow", shape: "ring", text: `Discovery failed — retrying in ${secs}s` });
2686
+ initTimeout(() => startV2(attempt + 1), delay);
2687
+ }
2688
+ }
2689
+ initTimeout(() => startV2(0), 2000);
2690
+
2691
+ function applyDiscoveredSuspended(discovered) {
2692
+ // The EV discovery chose (the LIVE one when several are listed): later polls read it.
2693
+ preferredEvId = discovered.deviceId || null;
2694
+ // The startup device fetch can fail (it has no tolerance for a status error) and so
2695
+ // can the first charging poll. Discovery found the device: the switch, Charge Cap and
2696
+ // preference writes can use it until a charging poll reads it again. It also replaces
2697
+ // an id the startup fetch found: that fetch runs before preferredEvId is known and
2698
+ // takes the first EV listed, which can be a RETIRED one.
2699
+ if (discovered.deviceId) krakenflexDeviceId = discovered.deviceId;
2700
+ // Discovery had to ask again without the device status: one warning, shared with the
2701
+ // charging poll's, until the state is read again.
2702
+ if (discovered.statusErrorCode !== undefined && !statusWarned && !nodeClosed) {
2703
+ statusWarned = true;
2704
+ const code = discovered.statusErrorCode;
2705
+ node.warn(`Smart charging state unavailable${code ? ` (${code})` : ''} - keeping the last value until Octopus returns it`);
2706
+ }
2707
+ if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
2708
+ smartChargingSuspended = discovered.deviceSuspended;
2709
+ lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
2710
+ publishSmartChargingState();
2711
+ }
2712
+ }
2713
+
2714
+ // Discovery found no devices at all (devices: []), which can be transient. Check again
2715
+ // on the discovery retry delays, at most EMPTY_DEVICES_MAX_RETRIES times. `done` is the
2716
+ // number of checks made so far. The other categories keep polling meanwhile.
2717
+ function scheduleDeviceCheck(done) {
2718
+ if (nodeClosed) return;
2719
+ if (done >= EMPTY_DEVICES_MAX_RETRIES) {
2720
+ node.log(`No charging device found after ${done} checks - charging polls stay off until the node restarts`);
2721
+ return;
2722
+ }
2723
+ const delay = discoveryRetryDelay(done);
2724
+ node.log(`V2 discovery found no devices - checking again in ${Math.round(delay / 1000)}s`);
2725
+ initTimeout(() => checkDevicesAgain(done + 1), delay);
2726
+ }
2727
+
2728
+ async function checkDevicesAgain(done) {
2729
+ if (nodeClosed) return;
2730
+ let discovered;
2731
+ try {
2732
+ discovered = await discoverProducts(apiKey, account, { isClosed: () => nodeClosed });
2733
+ } catch (e) {
2734
+ if (nodeClosed) return;
2735
+ node.warn(`Device check failed: ${short(e.message)}`);
2736
+ scheduleDeviceCheck(done);
2737
+ return;
2738
+ }
2739
+ if (nodeClosed) return;
2740
+ if (!discovered.hasIntelligent) {
2741
+ // Still empty: check again. Devices but no EV: that is the answer.
2742
+ if (discovered.deviceCount === 0) scheduleDeviceCheck(done);
2743
+ return;
2744
+ }
2745
+ if (categories.some((c) => c.id === 'intelligent')) return;
2746
+ applyDiscoveredSuspended(discovered);
2747
+ // Added in place: the other categories keep their schedule. The same set as a
2748
+ // normal start (deviceCategoryEntries), then the SmartFlex entities (review4 #1).
2749
+ const deviceCategories = deviceCategoryEntries(discovered);
2750
+ const isNew = (entry) => !categories.some((c) => c.id === entry.id);
2751
+ categories.unshift(...deviceCategories.lead.filter(isNew));
2752
+ categories.push(...deviceCategories.rest.filter(isNew));
2753
+ announceSmartflexEntities(discovered);
2754
+ node.log(`V2 discovery: charging device found on check ${done} - charging polls started`);
2755
+ }
2756
+
2757
+ // Node-RED passes (removed, done) to a two-argument close handler; a caller that
2758
+ // passes only done is also handled.
2759
+ node.on('close', function (removed, done) {
2760
+ if (typeof removed === 'function') { done = removed; removed = false; }
2761
+ let finished = false;
2762
+ const finish = () => {
2763
+ if (finished) return;
2764
+ finished = true;
2765
+ if (typeof done === 'function') done();
2766
+ };
2767
+ nodeClosed = true;
2768
+ // Retries are tick-driven; dropping the outage state stops any pending one.
2769
+ chargingOutage = null;
2770
+ retryPollRunning = false;
2771
+ // Clear init setTimeouts so a redeploy during warmup can't leave an orphan scheduler
2772
+ initTimeoutHandles.forEach(h => clearTimeout(h));
2773
+ initTimeoutHandles.clear();
2774
+ // Clear any pending retry timeouts
2775
+ retryTimeouts.forEach(timeout => clearTimeout(timeout));
2776
+ retryTimeouts = [];
2777
+ // Clear smart charging retry timeouts
2778
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
2779
+ smartChargingRetryTimeouts = [];
2780
+ // Drop a boost request still waiting for its turn
2781
+ if (boostQueue.timer) { clearTimeout(boostQueue.timer); boostQueue.timer = null; }
2782
+ if (boostQueue.watchdog) { clearTimeout(boostQueue.watchdog); boostQueue.watchdog = null; }
2783
+ boostQueue.pending = null;
2784
+ deferredChargingPollAt = null;
2785
+ // Clear charging timers
2786
+ clearChargingTimers();
2787
+ // Clear cooldown expiry timer
2788
+ if (cooldownExpiryTimer) {
2789
+ clearTimeout(cooldownExpiryTimer);
2790
+ cooldownExpiryTimer = null;
2791
+ }
2792
+ if (node._v2Scheduler) node._v2Scheduler.stop();
2793
+ // Remove only this node's command subscriptions, then deregister from the broker
2794
+ // (unsubscribe(topic, ref, removeClientSubscription); deregister(node, done, autoDisconnect)).
2795
+ if (enableMqtt && node.broker) {
2796
+ try {
2797
+ for (const topic of commandTopics) node.broker.unsubscribe(topic, node.id, true);
2798
+ } catch (e) {
2799
+ node.warn(`MQTT unsubscribe failed: ${e.message}`);
2800
+ }
2801
+ if (typeof node.broker.deregister === 'function') {
2802
+ try {
2803
+ node.broker.deregister(node, finish, removed);
2804
+ return;
2805
+ } catch (e) {
2806
+ node.warn(`MQTT deregister failed: ${e.message}`);
2807
+ }
2808
+ }
2809
+ }
2810
+ finish();
2811
+ });
2812
+ }
2813
+
2814
+ RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
2815
+ credentials: { apiKey: { type: "password" } }
2816
+ });
1808
2817
  };