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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +487 -408
  2. package/README.md +1004 -980
  3. package/examples/basic-monitoring.json +1 -1
  4. package/examples/ha-dashboard.yaml +602 -486
  5. package/examples/mqtt-integration.json +1 -1
  6. package/examples/node-red-dashboard-flow.json +1287 -0
  7. package/examples/set-preferences.json +1 -1
  8. package/lib/api-metrics.js +31 -31
  9. package/lib/auth.js +20 -20
  10. package/lib/categories/account.js +32 -32
  11. package/lib/categories/applicable-rates.js +127 -91
  12. package/lib/categories/completed-dispatches.js +35 -35
  13. package/lib/categories/electricity.js +146 -133
  14. package/lib/categories/flex-planned-dispatches.js +36 -36
  15. package/lib/categories/free-electricity.js +61 -61
  16. package/lib/categories/gas.js +95 -95
  17. package/lib/categories/home-mini.js +37 -37
  18. package/lib/categories/intelligent.js +155 -124
  19. package/lib/categories/octoplus.js +32 -32
  20. package/lib/categories/saving-sessions.js +64 -64
  21. package/lib/categories/wheel-of-fortune.js +49 -49
  22. package/lib/commands.js +47 -0
  23. package/lib/discovery-retry.js +13 -0
  24. package/lib/discovery.js +92 -85
  25. package/lib/graphql-errors.js +18 -0
  26. package/lib/graphql.js +44 -44
  27. package/lib/http-get-json.js +22 -0
  28. package/lib/payload.js +89 -77
  29. package/lib/poll-tick.js +44 -44
  30. package/lib/preferences.js +32 -0
  31. package/lib/scheduler.js +47 -47
  32. package/lib/sensor-definitions.js +219 -0
  33. package/lib/timezone.js +49 -49
  34. package/lib/update-check.js +38 -0
  35. package/octopus-intelligent.html +218 -205
  36. package/octopus-intelligent.js +1687 -1685
  37. package/package.json +54 -54
@@ -1,1686 +1,1688 @@
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
-
23
- module.exports = function (RED) {
24
- function OctopusIntelligentNode(config) {
25
- RED.nodes.createNode(this, config);
26
- var node = this;
27
-
28
- // 1. Configuration
29
- const account = config.accountNumber ? config.accountNumber.trim() : "";
30
- const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
31
- const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
32
- const enableMqtt = config.enableMqtt;
33
- node.timezoneOverride = config.timezoneOverride || "";
34
-
35
- // MQTT Topics
36
- this.broker = RED.nodes.getNode(config.broker);
37
- const mqttPrefix = `homeassistant`;
38
- const uniqueIdPrefix = `nodered_${account}`;
39
- const stateTopic = `nodered_octopus/${account}/status`;
40
-
41
- // Command Topics (For listening)
42
- const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
43
- const cmdTopicTime = `nodered_octopus/${account}/set_time`;
44
- const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
45
- const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
46
- const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
47
- const cmdTopicSmartCharging = `nodered_octopus/${account}/set_smart_charging`;
48
-
49
- // 2. Constants & Validation
50
- const TIME_OPTIONS = [
51
- "04:00", "04:30", "05:00", "05:30",
52
- "06:00", "06:30", "07:00", "07:30",
53
- "08:00", "08:30", "09:00", "09:30",
54
- "10:00", "10:30", "11:00"
55
- ];
56
-
57
- // 3. Sensor Definitions (Read-Only)
58
- // category: undefined = main, 'config' = Configuration, 'diagnostic' = Diagnostics
59
- const sensors = [
60
- // --- EV Charging (main) ---
61
- { id: 'next_charge', name: 'Next Charge Time', class: 'timestamp', icon: 'mdi:timer', val: 'next_start' },
62
- { id: 'total_energy', name: 'Total Planned Energy', unit: 'kWh', class: 'energy', val: 'total_energy' },
63
- { id: 'next_kwh', name: 'Next Slot Energy', unit: 'kWh', class: 'energy', val: 'next_kwh' },
64
- { id: 'source', name: 'Charge Source', icon: 'mdi:help-circle', val: 'next_source' },
65
- { id: 'slot1_start', name: 'Slot 1 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot1_start' },
66
- { id: 'slot1_end', name: 'Slot 1 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot1_end' },
67
- { id: 'slot2_start', name: 'Slot 2 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot2_start' },
68
- { id: 'slot2_end', name: 'Slot 2 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot2_end' },
69
- { id: 'slot3_start', name: 'Slot 3 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot3_start' },
70
- { id: 'slot3_end', name: 'Slot 3 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot3_end' },
71
- { id: 'window_start', name: 'Overall Window Start', class: 'timestamp', icon: 'mdi:timer-play', val: 'window_start' },
72
- { id: 'window_end', name: 'Overall Window End', class: 'timestamp', icon: 'mdi:timer-stop', val: 'window_end' },
73
-
74
- // --- EV Charging (diagnostic) ---
75
- { id: 'next_poll', name: 'Next Poll Time', class: 'timestamp', icon: 'mdi:clock-outline', val: 'next_poll', category: 'diagnostic' },
76
- { id: 'refresh_available_at', name: 'Refresh Available At', class: 'timestamp', icon: 'mdi:timer-sand', val: 'refresh_available_at', category: 'diagnostic' },
77
- { id: 'api_requests_hour', name: 'API Requests (Last Hour)', icon: 'mdi:api', val: 'api_requests_hour', category: 'diagnostic' },
78
- { id: 'api_complexity_hour', name: 'API Complexity (Last Hour)', icon: 'mdi:chart-line', val: 'api_complexity_hour', category: 'diagnostic' },
79
- { id: 'api_complexity_percent', name: 'API Complexity Usage', unit: '%', icon: 'mdi:percent', val: 'api_complexity_percent', category: 'diagnostic' },
80
-
81
- // --- Raw timestamps (diagnostic) ---
82
- { id: 'next_charge_raw', name: 'Next Charge Time (Raw)', icon: 'mdi:timer', val: 'next_start_raw', category: 'diagnostic' },
83
- { id: 'next_poll_raw', name: 'Next Poll Time (Raw)', icon: 'mdi:clock-outline', val: 'next_poll_raw', category: 'diagnostic' },
84
- { id: 'slot1_start_raw', name: 'Slot 1 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot1_start_raw', category: 'diagnostic' },
85
- { id: 'slot1_end_raw', name: 'Slot 1 End (Raw)', icon: 'mdi:timer-outline', val: 'slot1_end_raw', category: 'diagnostic' },
86
- { id: 'slot2_start_raw', name: 'Slot 2 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot2_start_raw', category: 'diagnostic' },
87
- { id: 'slot2_end_raw', name: 'Slot 2 End (Raw)', icon: 'mdi:timer-outline', val: 'slot2_end_raw', category: 'diagnostic' },
88
- { id: 'slot3_start_raw', name: 'Slot 3 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot3_start_raw', category: 'diagnostic' },
89
- { id: 'slot3_end_raw', name: 'Slot 3 End (Raw)', icon: 'mdi:timer-outline', val: 'slot3_end_raw', category: 'diagnostic' },
90
- { id: 'window_start_raw', name: 'Overall Window Start (Raw)', icon: 'mdi:timer-play', val: 'window_start_raw', category: 'diagnostic' },
91
- { id: 'window_end_raw', name: 'Overall Window End (Raw)', icon: 'mdi:timer-stop', val: 'window_end_raw', category: 'diagnostic' },
92
-
93
- // --- Locale timestamps (diagnostic) ---
94
- { id: 'next_charge_locale', name: 'Next Charge Time (Locale)', icon: 'mdi:timer', val: 'next_start_locale', category: 'diagnostic' },
95
- { id: 'slot1_start_locale', name: 'Slot 1 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot1_start_locale', category: 'diagnostic' },
96
- { id: 'slot1_end_locale', name: 'Slot 1 End (Locale)', icon: 'mdi:timer-outline', val: 'slot1_end_locale', category: 'diagnostic' },
97
- { id: 'slot2_start_locale', name: 'Slot 2 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot2_start_locale', category: 'diagnostic' },
98
- { id: 'slot2_end_locale', name: 'Slot 2 End (Locale)', icon: 'mdi:timer-outline', val: 'slot2_end_locale', category: 'diagnostic' },
99
- { id: 'slot3_start_locale', name: 'Slot 3 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot3_start_locale', category: 'diagnostic' },
100
- { id: 'slot3_end_locale', name: 'Slot 3 End (Locale)', icon: 'mdi:timer-outline', val: 'slot3_end_locale', category: 'diagnostic' },
101
- { id: 'window_start_locale', name: 'Overall Window Start (Locale)', icon: 'mdi:timer-play', val: 'window_start_locale', category: 'diagnostic' },
102
- { id: 'window_end_locale', name: 'Overall Window End (Locale)', icon: 'mdi:timer-stop', val: 'window_end_locale', category: 'diagnostic' },
103
- { id: 'timezone_detected', name: 'Timezone Detected', icon: 'mdi:earth', val: 'timezone_detected', category: 'diagnostic' },
104
- { id: 'timezone_applied', name: 'Timezone Applied', icon: 'mdi:earth-plus', val: 'timezone_applied', category: 'diagnostic' },
105
- // --- Electricity (main) ---
106
- { id: 'electricity_standing_charge', name: 'Electricity Standing Charge', unit: 'p/day', icon: 'mdi:cash', val: 'electricity_standing_charge' },
107
- { id: 'electricity_consumption_kwh', name: 'Electricity Consumption', unit: 'kWh', class: 'energy', val: 'electricity_consumption_kwh' },
108
- // --- Electricity (config) ---
109
- { id: 'electricity_unit_rate', name: 'Electricity Unit Rate', unit: 'p/kWh', icon: 'mdi:flash', val: 'electricity_unit_rate' },
110
- { id: 'electricity_tariff_code', name: 'Electricity Tariff Code', icon: 'mdi:tag', val: 'electricity_tariff_code' },
111
- { id: 'electricity_valid_from', name: 'Electricity Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'electricity_valid_from' },
112
- { id: 'electricity_valid_to', name: 'Electricity Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'electricity_valid_to' },
113
- // --- Electricity (diagnostic) ---
114
- { id: 'electricity_consumption_from', name: 'Electricity Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_consumption_from', category: 'diagnostic' },
115
- { id: 'electricity_consumption_to', name: 'Electricity Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_consumption_to', category: 'diagnostic' },
116
- { id: 'electricity_rates_error', name: 'Electricity Rates Error', icon: 'mdi:alert-circle', val: 'electricity_rates_error', category: 'diagnostic' },
117
- { id: 'electricity_consumption_error', name: 'Electricity Consumption Error', icon: 'mdi:alert-circle', val: 'electricity_consumption_error', category: 'diagnostic' },
118
-
119
- // --- Electricity Export (main) ---
120
- { id: 'electricity_export_consumption_kwh', name: 'Electricity Export Consumption', unit: 'kWh', class: 'energy', val: 'electricity_export_consumption_kwh' },
121
- { id: 'electricity_export_rate_current_pence', name: 'Current Electricity Export Rate', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_current_pence' },
122
- { 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' },
123
- // --- Electricity Export (config) ---
124
- // Solar/export users have a second agreement with productCode containing "OUTGOING".
125
- // unit_rate is null for half-hourly export tariffs (e.g. Agile Outgoing) — current
126
- // half-hourly export rate comes from electricity_export_rate_current_pence.
127
- { id: 'electricity_export_unit_rate', name: 'Electricity Export Unit Rate', unit: 'p/kWh', icon: 'mdi:transmission-tower-export', val: 'electricity_export_unit_rate' },
128
- { id: 'electricity_export_standing_charge',name: 'Electricity Export Standing Charge',unit: 'p/day', icon: 'mdi:cash', val: 'electricity_export_standing_charge' },
129
- { id: 'electricity_export_tariff_code', name: 'Electricity Export Tariff Code', icon: 'mdi:tag', val: 'electricity_export_tariff_code' },
130
- { id: 'electricity_export_valid_from', name: 'Electricity Export Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'electricity_export_valid_from' },
131
- { id: 'electricity_export_valid_to', name: 'Electricity Export Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'electricity_export_valid_to' },
132
- // --- Electricity Export (diagnostic) ---
133
- { id: 'electricity_export_consumption_from', name: 'Electricity Export Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_consumption_from', category: 'diagnostic' },
134
- { id: 'electricity_export_consumption_to', name: 'Electricity Export Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_consumption_to', category: 'diagnostic' },
135
- { id: 'electricity_export_rate_count', name: 'Electricity Export Rate Slots', icon: 'mdi:format-list-numbered', val: 'electricity_export_rate_count', category: 'diagnostic' },
136
- { 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' },
137
- { 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' },
138
- { 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' },
139
- { 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' },
140
- { id: 'electricity_export_rate_error', name: 'Electricity Export Rate Error', icon: 'mdi:alert-circle', val: 'electricity_export_rate_error', category: 'diagnostic' },
141
-
142
- // --- Gas (main) ---
143
- { id: 'gas_standing_charge', name: 'Gas Standing Charge', unit: 'p/day', icon: 'mdi:cash', val: 'gas_standing_charge' },
144
- { id: 'gas_consumption_kwh', name: 'Gas Consumption', unit: 'kWh', class: 'energy', val: 'gas_consumption_kwh' },
145
- // --- Gas (config) ---
146
- { id: 'gas_unit_rate', name: 'Gas Unit Rate', unit: 'p/kWh', icon: 'mdi:fire', val: 'gas_unit_rate' },
147
- { id: 'gas_tariff_code', name: 'Gas Tariff Code', icon: 'mdi:tag', val: 'gas_tariff_code' },
148
- { id: 'gas_valid_from', name: 'Gas Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'gas_valid_from' },
149
- { id: 'gas_valid_to', name: 'Gas Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'gas_valid_to' },
150
- // --- Gas (diagnostic) ---
151
- { id: 'gas_consumption_from', name: 'Gas Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'gas_consumption_from', category: 'diagnostic' },
152
- { id: 'gas_consumption_to', name: 'Gas Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'gas_consumption_to', category: 'diagnostic' },
153
- { id: 'gas_rates_error', name: 'Gas Rates Error', icon: 'mdi:alert-circle', val: 'gas_rates_error', category: 'diagnostic' },
154
- { id: 'gas_consumption_error', name: 'Gas Consumption Error', icon: 'mdi:alert-circle', val: 'gas_consumption_error', category: 'diagnostic' },
155
-
156
- // --- Applicable Rates (main) ---
157
- { id: 'applicable_rates_current_pence', name: 'Current Electricity Rate', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_current_pence' },
158
- { id: 'applicable_rates_current_gbp', name: 'Electricity Rate', unit: 'GBP/kWh', icon: 'mdi:cash-clock', stateClass: 'measurement', val: 'applicable_rates_current_gbp' },
159
- // --- Applicable Rates (diagnostic) ---
160
- { id: 'applicable_rates_count', name: 'Applicable Rates Slots', icon: 'mdi:format-list-numbered', val: 'applicable_rates_count', category: 'diagnostic' },
161
- { id: 'applicable_rates_error', name: 'Applicable Rates Error', icon: 'mdi:alert-circle', val: 'applicable_rates_error', category: 'diagnostic' },
162
-
163
- // --- Account (main) ---
164
- { id: 'account_balance_pounds', name: 'Account Balance', unit: '£', icon: 'mdi:cash-multiple', val: 'account_balance_pounds' },
165
- // --- Account (diagnostic) ---
166
- { id: 'account_balance_pence', name: 'Account Balance (Pence)', unit: 'p', icon: 'mdi:cash', val: 'account_balance_pence', category: 'diagnostic' },
167
- { id: 'account_error', name: 'Account Error', icon: 'mdi:alert-circle', val: 'account_error', category: 'diagnostic' },
168
-
169
- // --- Octoplus (config) ---
170
- // octoplus_enrolled and octoplus_loyalty_points_user are booleans — published as
171
- // binary_sensor entities further down. Leaving them out of this array.
172
- { id: 'octoplus_enrollment_status', name: 'Octoplus Status', icon: 'mdi:star-circle-outline', val: 'octoplus_enrollment_status' },
173
- // --- Octoplus (diagnostic) ---
174
- { id: 'octoplus_error', name: 'Octoplus Error', icon: 'mdi:alert-circle', val: 'octoplus_error', category: 'diagnostic' },
175
-
176
- // --- Wheel of Fortune (main) ---
177
- { id: 'wheel_of_fortune_electricity_spins', name: 'WoF Electricity Spins', icon: 'mdi:star-circle', val: 'wheel_of_fortune_electricity_spins' },
178
- { id: 'wheel_of_fortune_gas_spins', name: 'WoF Gas Spins', icon: 'mdi:star-circle', val: 'wheel_of_fortune_gas_spins' },
179
- // --- Wheel of Fortune (diagnostic) ---
180
- { id: 'wheel_of_fortune_electricity_max', name: 'WoF Electricity Max', icon: 'mdi:star-outline', val: 'wheel_of_fortune_electricity_max', category: 'diagnostic' },
181
- { id: 'wheel_of_fortune_electricity_used', name: 'WoF Electricity Used', icon: 'mdi:star-outline', val: 'wheel_of_fortune_electricity_used', category: 'diagnostic' },
182
- { id: 'wheel_of_fortune_gas_max', name: 'WoF Gas Max', icon: 'mdi:star-outline', val: 'wheel_of_fortune_gas_max', category: 'diagnostic' },
183
- { id: 'wheel_of_fortune_gas_used', name: 'WoF Gas Used', icon: 'mdi:star-outline', val: 'wheel_of_fortune_gas_used', category: 'diagnostic' },
184
- { id: 'wheel_of_fortune_error', name: 'WoF Error', icon: 'mdi:alert-circle', val: 'wheel_of_fortune_error', category: 'diagnostic' },
185
-
186
- // --- Home Mini (main) ---
187
- { id: 'mini_demand_kw', name: 'Home Mini Demand', unit: 'kW', class: 'power', icon: 'mdi:home-lightning-bolt', val: 'mini_demand_kw' },
188
- { id: 'mini_consumption_delta_kwh', name: 'Home Mini Period Consumption', unit: 'kWh', class: 'energy', icon: 'mdi:home-lightning-bolt', val: 'mini_consumption_delta_kwh' },
189
- // --- Home Mini (diagnostic) ---
190
- { id: 'mini_read_at', name: 'Home Mini Reading Time', class: 'timestamp', icon: 'mdi:clock-outline', val: 'mini_read_at', category: 'diagnostic' },
191
- { id: 'home_mini_error', name: 'Home Mini Error', icon: 'mdi:alert-circle', val: 'home_mini_error', category: 'diagnostic' },
192
-
193
- // --- Saving Sessions (main) ---
194
- { id: 'saving_session_points', name: 'Octopus Points', icon: 'mdi:star', val: 'saving_session_points' },
195
- // --- Saving Sessions (config) ---
196
- { id: 'saving_session_start', name: 'Saving Session Start', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'saving_session_start' },
197
- { id: 'saving_session_end', name: 'Saving Session End', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'saving_session_end' },
198
- // --- Saving Sessions (diagnostic) ---
199
- { id: 'saving_sessions_error', name: 'Saving Sessions Error', icon: 'mdi:alert-circle', val: 'saving_sessions_error', category: 'diagnostic' },
200
-
201
- // --- Free Electricity (config) ---
202
- { id: 'free_electricity_start', name: 'Free Electricity Start', class: 'timestamp', icon: 'mdi:flash-circle', val: 'free_electricity_start' },
203
- { id: 'free_electricity_end', name: 'Free Electricity End', class: 'timestamp', icon: 'mdi:flash-circle', val: 'free_electricity_end' },
204
- // --- Free Electricity (diagnostic) ---
205
- { id: 'free_electricity_error', name: 'Free Electricity Error', icon: 'mdi:alert-circle', val: 'free_electricity_error', category: 'diagnostic' },
206
-
207
- // --- Dispatches (main) ---
208
- { id: 'completed_dispatches_count', name: 'Completed Dispatches', icon: 'mdi:history', val: 'completed_dispatches_count' },
209
- { id: 'flex_planned_dispatches_count', name: 'Flex Planned Dispatches', icon: 'mdi:lightning-bolt-circle', val: 'flex_planned_dispatches_count' },
210
- // --- Dispatches (diagnostic) ---
211
- { id: 'completed_dispatches_error', name: 'Completed Dispatches Error', icon: 'mdi:alert-circle', val: 'completed_dispatches_error', category: 'diagnostic' },
212
- { id: 'flex_planned_dispatches_error', name: 'Flex Planned Dispatches Error', icon: 'mdi:alert-circle', val: 'flex_planned_dispatches_error', category: 'diagnostic' },
213
- { id: 'intelligent_error', name: 'Intelligent Error', icon: 'mdi:alert-circle', val: 'intelligent_error', category: 'diagnostic' },
214
- ];
215
-
216
- // 4. Helper: Announce Controls (Write-Enabled)
217
- function announceControls() {
218
- if (!enableMqtt || !node.broker) return;
219
-
220
- // Single device definition with branding
221
- const device = {
222
- identifiers: [`nodered_octopus_${account}`],
223
- name: "Octopus Intelligent",
224
- manufacturer: "Octopus Energy",
225
- model: "Intelligent Octopus Go",
226
- sw_version: "2.0.0",
227
- suggested_area: "Energy",
228
- configuration_url: "https://octopus.energy/intelligent/"
229
- };
230
-
231
- // A. The Slider (Number) - now shows pending value
232
- const limitConfig = {
233
- name: "Octopus Target Charge",
234
- unique_id: `${uniqueIdPrefix}_target_limit`,
235
- state_topic: stateTopic,
236
- command_topic: cmdTopicLimit,
237
- value_template: "{{ value_json.pending_limit }}",
238
- min: 50, max: 100, step: 5,
239
- unit_of_measurement: "%",
240
- icon: "mdi:battery-charging-high",
241
- device: device
242
- };
243
- node.broker.client.publish(`${mqttPrefix}/number/${uniqueIdPrefix}_limit/config`, JSON.stringify(limitConfig), { retain: true });
244
-
245
- // B. The Dropdown (Select) - now shows pending value
246
- const timeConfig = {
247
- name: "Octopus Ready Time",
248
- unique_id: `${uniqueIdPrefix}_target_time`,
249
- state_topic: stateTopic,
250
- command_topic: cmdTopicTime,
251
- value_template: "{{ value_json.pending_time }}",
252
- options: TIME_OPTIONS,
253
- icon: "mdi:clock-time-four-outline",
254
- device: device
255
- };
256
- node.broker.client.publish(`${mqttPrefix}/select/${uniqueIdPrefix}_time/config`, JSON.stringify(timeConfig), { retain: true });
257
-
258
- // C. Submit Button
259
- const buttonConfig = {
260
- name: "Octopus Apply Changes",
261
- unique_id: `${uniqueIdPrefix}_submit_button`,
262
- command_topic: cmdTopicSubmit,
263
- payload_press: "SUBMIT",
264
- icon: "mdi:check-circle",
265
- device_class: "update",
266
- device: device
267
- };
268
- node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
269
-
270
- // D. Refresh Button
271
- const refreshButtonConfig = {
272
- name: "Octopus Refresh API",
273
- unique_id: `${uniqueIdPrefix}_refresh_button`,
274
- command_topic: cmdTopicRefresh,
275
- payload_press: "REFRESH",
276
- icon: "mdi:refresh",
277
- device_class: "restart",
278
- device: device
279
- };
280
- node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_refresh/config`, JSON.stringify(refreshButtonConfig), { retain: true });
281
-
282
- // E. Add sensors for confirmed values (read-only display)
283
- const confirmedLimitSensor = {
284
- name: "Octopus Confirmed Charge Limit",
285
- unique_id: `${uniqueIdPrefix}_confirmed_limit`,
286
- state_topic: stateTopic,
287
- value_template: "{{ value_json.confirmed_limit }}",
288
- unit_of_measurement: "%",
289
- icon: "mdi:battery-check",
290
- device: device
291
- };
292
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_limit/config`, JSON.stringify(confirmedLimitSensor), { retain: true });
293
-
294
- const confirmedTimeSensor = {
295
- name: "Octopus Confirmed Ready Time",
296
- unique_id: `${uniqueIdPrefix}_confirmed_time`,
297
- state_topic: stateTopic,
298
- value_template: "{{ value_json.confirmed_time }}",
299
- icon: "mdi:clock-check",
300
- device: device
301
- };
302
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
303
-
304
- // G. Charging Now Binary Sensor (main sensor for automations)
305
- const chargingNowBinarySensor = {
306
- name: "Octopus Charging Now",
307
- unique_id: `${uniqueIdPrefix}_charging_now`,
308
- state_topic: `${stateTopic}/charging_now`,
309
- device_class: "battery_charging",
310
- payload_on: "ON",
311
- payload_off: "OFF",
312
- icon: "mdi:ev-station",
313
- device: device
314
- };
315
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
316
-
317
- // G2. Saving Session Available Binary Sensor
318
- const savingSessionBinarySensor = {
319
- name: "Octopus Saving Session Available",
320
- unique_id: `${uniqueIdPrefix}_saving_session_available`,
321
- state_topic: stateTopic,
322
- value_template: "{{ value_json.saving_session_available }}",
323
- payload_on: "True",
324
- payload_off: "False",
325
- icon: "mdi:lightning-bolt-circle",
326
- device: device
327
- };
328
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_available/config`, JSON.stringify(savingSessionBinarySensor), { retain: true });
329
-
330
- // G2a. Saving Session Window Active Binary Sensor (v1.3.3)
331
- const savingSessionWindowActiveSensor = {
332
- name: "Octopus Saving Session Window Active",
333
- unique_id: `${uniqueIdPrefix}_saving_session_window_active`,
334
- state_topic: stateTopic,
335
- value_template: "{{ value_json.saving_session_window_active }}",
336
- payload_on: "True",
337
- payload_off: "False",
338
- icon: "mdi:clock-check-outline",
339
- device: device
340
- };
341
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_window_active/config`, JSON.stringify(savingSessionWindowActiveSensor), { retain: true });
342
-
343
- // G2b. Saving Session Active Binary Sensor (v1.3.3) — joined AND in window
344
- const savingSessionActiveSensor = {
345
- name: "Octopus Saving Session Active",
346
- unique_id: `${uniqueIdPrefix}_saving_session_active`,
347
- state_topic: stateTopic,
348
- value_template: "{{ value_json.saving_session_active }}",
349
- payload_on: "True",
350
- payload_off: "False",
351
- icon: "mdi:home-export-outline",
352
- device: device
353
- };
354
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_active/config`, JSON.stringify(savingSessionActiveSensor), { retain: true });
355
-
356
- // G2c. v1.3.3 migration: delete the deprecated sensor.saving_session_joined
357
- // entity. HA's sensor domain doesn't render booleans cleanly. Empty
358
- // payload on the discovery topic with retain tells HA the entity no
359
- // longer exists. Safe to keep across releases.
360
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_saving_session_joined/config`, "", { retain: true });
361
-
362
- // G2d. Saving Session Joined Binary Sensor (v1.3.3 migration)
363
- const savingSessionJoinedSensor = {
364
- name: "Octopus Saving Session Joined",
365
- unique_id: `${uniqueIdPrefix}_saving_session_joined`,
366
- state_topic: stateTopic,
367
- value_template: "{{ value_json.saving_session_joined }}",
368
- payload_on: "True",
369
- payload_off: "False",
370
- icon: "mdi:account-check",
371
- device: device
372
- };
373
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_joined/config`, JSON.stringify(savingSessionJoinedSensor), { retain: true });
374
-
375
- // G3. Free Electricity Active Binary Sensor
376
- const freeElectricityActiveSensor = {
377
- name: "Octopus Free Electricity Active",
378
- unique_id: `${uniqueIdPrefix}_free_electricity_active`,
379
- state_topic: stateTopic,
380
- value_template: "{{ value_json.free_electricity_active }}",
381
- payload_on: "True",
382
- payload_off: "False",
383
- icon: "mdi:flash-circle",
384
- device: device
385
- };
386
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_active/config`, JSON.stringify(freeElectricityActiveSensor), { retain: true });
387
-
388
- // G4. Free Electricity Available Binary Sensor
389
- const freeElectricityAvailableSensor = {
390
- name: "Octopus Free Electricity Available",
391
- unique_id: `${uniqueIdPrefix}_free_electricity_available`,
392
- state_topic: stateTopic,
393
- value_template: "{{ value_json.free_electricity_available }}",
394
- payload_on: "True",
395
- payload_off: "False",
396
- icon: "mdi:flash-circle-outline",
397
- device: device
398
- };
399
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_available/config`, JSON.stringify(freeElectricityAvailableSensor), { retain: true });
400
-
401
- // G5. Octoplus Enrolled Binary Sensor
402
- // Published as binary_sensor (not sensor) because the value is a boolean —
403
- // HA's sensor domain rejects booleans without a device_class, leaving the
404
- // entity unregistered. No entity_category: 'config' on a read-only sensor
405
- // makes its state stick at "unavailable" on some HA installs (same fix as
406
- // the v1.3.0 tariff-sensor cleanup — see CHANGELOG).
407
- const octoplusEnrolledBinarySensor = {
408
- name: "Octopus Octoplus Enrolled",
409
- unique_id: `${uniqueIdPrefix}_octoplus_enrolled`,
410
- state_topic: stateTopic,
411
- value_template: "{{ value_json.octoplus_enrolled }}",
412
- payload_on: "True",
413
- payload_off: "False",
414
- icon: "mdi:star-circle",
415
- device: device
416
- };
417
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_enrolled/config`, JSON.stringify(octoplusEnrolledBinarySensor), { retain: true });
418
-
419
- // G6. Octoplus Loyalty Points (boolean) Binary Sensor
420
- // No entity_category — see G5.
421
- const octoplusLoyaltyBinarySensor = {
422
- name: "Octopus Octoplus Loyalty Points",
423
- unique_id: `${uniqueIdPrefix}_octoplus_loyalty_points_user`,
424
- state_topic: stateTopic,
425
- value_template: "{{ value_json.octoplus_loyalty_points_user }}",
426
- payload_on: "True",
427
- payload_off: "False",
428
- icon: "mdi:star",
429
- device: device
430
- };
431
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_loyalty_points_user/config`, JSON.stringify(octoplusLoyaltyBinarySensor), { retain: true });
432
-
433
- // H. Announce Read-Only Sensors
434
- sensors.forEach(sensor => {
435
- const payload = {
436
- name: `Octopus ${sensor.name}`,
437
- unique_id: `${uniqueIdPrefix}_${sensor.id}`,
438
- state_topic: stateTopic,
439
- value_template: `{{ value_json.${sensor.val} }}`,
440
- device: device
441
- };
442
- if (sensor.class) payload.device_class = sensor.class;
443
- if (sensor.unit) payload.unit_of_measurement = sensor.unit;
444
- if (sensor.stateClass) payload.state_class = sensor.stateClass;
445
- if (sensor.icon) payload.icon = sensor.icon;
446
-
447
- if (sensor.category) {
448
- payload.entity_category = sensor.category;
449
- }
450
-
451
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
452
- });
453
-
454
- // I. Timezone Select Entity
455
- const TIMEZONE_OPTIONS = [
456
- "Europe/London", "Europe/Berlin", "Europe/Madrid",
457
- "Australia/Sydney", "Australia/Melbourne", "Australia/Brisbane",
458
- "Australia/Perth", "Australia/Adelaide", "Pacific/Auckland",
459
- "America/New_York", "America/Chicago", "America/Denver",
460
- "America/Los_Angeles", "Asia/Tokyo", "UTC"
461
- ];
462
- node.broker.client.publish(
463
- `${mqttPrefix}/select/${uniqueIdPrefix}_timezone/config`,
464
- JSON.stringify({
465
- name: "Timezone",
466
- unique_id: `${uniqueIdPrefix}_timezone`,
467
- options: TIMEZONE_OPTIONS,
468
- command_topic: cmdTopicTimezone,
469
- state_topic: `${stateTopic}/timezone`,
470
- icon: "mdi:earth",
471
- entity_category: "config",
472
- device: device
473
- }),
474
- { retain: true }
475
- );
476
-
477
- // J. Smart Charging Switch
478
- node.broker.client.publish(
479
- `${mqttPrefix}/switch/${uniqueIdPrefix}_smart_charging/config`,
480
- JSON.stringify({
481
- name: "Smart Charging",
482
- unique_id: `${uniqueIdPrefix}_smart_charging`,
483
- command_topic: cmdTopicSmartCharging,
484
- state_topic: `${stateTopic}/smart_charging`,
485
- payload_on: "ON",
486
- payload_off: "OFF",
487
- icon: "mdi:lightning-bolt",
488
- entity_category: "config",
489
- device: device
490
- }),
491
- { retain: true }
492
- );
493
-
494
- // Subscribe to Commands
495
- node.broker.client.subscribe(cmdTopicLimit);
496
- node.broker.client.subscribe(cmdTopicTime);
497
- node.broker.client.subscribe(cmdTopicSubmit);
498
- node.broker.client.subscribe(cmdTopicRefresh);
499
- node.broker.client.subscribe(cmdTopicTimezone);
500
- node.broker.client.subscribe(cmdTopicSmartCharging);
501
- }
502
-
503
- // 5. Helper: Set Preferences (The Mutation)
504
- let retryTimeouts = []; // Track pending retry timeouts
505
- let expectedLimit = null;
506
- let expectedTime = null;
507
- let validationMode = false;
508
-
509
- // Pending vs Confirmed state
510
- let pendingLimit = 80;
511
- let pendingTime = "08:00";
512
- let confirmedLimit = 80;
513
- let confirmedTime = "08:00";
514
-
515
- // Charging Now feature - timer-based state management
516
- let chargingNow = false;
517
- let preValidationTimer = null; // Fires 30s before slot start
518
- let slotStartTimer = null; // Fires at exact slot start
519
- let slotEndTimer = null; // Fires at exact slot end
520
- let cachedSlots = []; // Fresh slot data from pre-validation
521
- let stateCheckInterval = null; // Reconciliation loop (every 10s)
522
- let lastSentChargingState = null; // Track last sent state to avoid duplicates
523
-
524
- // Manual refresh rate limiting (only for MQTT button, not Node-RED input)
525
- let lastManualRefresh = 0; // Timestamp of last manual refresh
526
- const MANUAL_REFRESH_COOLDOWN = 30000; // 30 seconds in milliseconds
527
- let cooldownExpiryTimer = null; // Timer to clear cooldown state at expiry
528
-
529
- // Polling metrics
530
- let nextPollTime = null; // ISO timestamp of next scheduled poll
531
- const metrics = createApiMetrics();
532
-
533
- // API Complexity Tracking
534
- // Octopus Energy API does not return actual complexity values in headers or extensions,
535
- // so we use estimated complexity based on query types:
536
- // - Regular poll (auth + data query): ~300
537
- // - Mutation (auth + setPreferences): ~250
538
- // - Pre-validation (auth + flexPlannedDispatches only): ~200
539
-
540
- // Smart charging state (fetched once at startup)
541
- let krakenflexDeviceId = null;
542
- let smartChargingSuspended = null; // null=unknown, true=suspended(off), false=active(on)
543
- let smartChargingRetryTimeouts = [];
544
-
545
- // Last known full state - prevents sensors going unknown when controls change
546
- let lastKnownState = buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
547
-
548
- // V2 category registry — populated after discovery
549
- let categories = [];
550
-
551
- // Lifecycle tracking — init setTimeouts must be clearable on close, and async
552
- // callbacks inside them must short-circuit if the node was closed mid-await,
553
- // otherwise a redeploy during the 2s warmup leaves an orphan V2 scheduler.
554
- let initTimeoutHandles = [];
555
- let nodeClosed = false;
556
-
557
- async function initCategories(discovered) {
558
- categories = [];
559
-
560
- if (discovered.hasIntelligent) {
561
- categories.push({
562
- id: 'intelligent',
563
- enabled: true,
564
- intervalMs: (config.refreshInterval || 5) * 60 * 1000,
565
- lastPolled: 0,
566
- poll: intelligentPoll,
567
- });
568
- }
569
-
570
- const electricityEnabled = config.electricityEnabled !== false;
571
- const gasEnabled = config.gasEnabled !== false;
572
-
573
- if (discovered.hasElectricity && electricityEnabled) {
574
- const ratesMs = (config.electricityRatesInterval || 60) * 60 * 1000;
575
- const consumptionMs = (config.electricityConsumptionInterval || 60) * 60 * 1000;
576
- categories.push({
577
- id: 'electricity_rates',
578
- enabled: true,
579
- intervalMs: ratesMs,
580
- lastPolled: 0,
581
- queryFn: () => electricityCategory.buildRatesQuery(account),
582
- parseFn: d => electricityCategory.parseRatesResponse(d),
583
- poll: simplePoll(
584
- () => electricityCategory.buildRatesQuery(account),
585
- d => electricityCategory.parseRatesResponse(d),
586
- graphqlPost
587
- ),
588
- });
589
- categories.push({
590
- id: 'electricity_consumption',
591
- enabled: true,
592
- intervalMs: consumptionMs,
593
- lastPolled: 0,
594
- queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
595
- parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
596
- poll: simplePoll(
597
- () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
598
- d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
599
- graphqlPost
600
- ),
601
- });
602
- }
603
-
604
- if (discovered.hasGas && gasEnabled) {
605
- const ratesMs = (config.gasRatesInterval || 60) * 60 * 1000;
606
- const consumptionMs = (config.gasConsumptionInterval || 60) * 60 * 1000;
607
- categories.push({
608
- id: 'gas_rates',
609
- enabled: true,
610
- intervalMs: ratesMs,
611
- lastPolled: 0,
612
- queryFn: () => gasCategory.buildRatesQuery(account),
613
- parseFn: d => gasCategory.parseRatesResponse(d),
614
- poll: simplePoll(
615
- () => gasCategory.buildRatesQuery(account),
616
- d => gasCategory.parseRatesResponse(d),
617
- graphqlPost
618
- ),
619
- });
620
- categories.push({
621
- id: 'gas_consumption',
622
- enabled: true,
623
- intervalMs: consumptionMs,
624
- lastPolled: 0,
625
- queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
626
- parseFn: d => gasCategory.parseConsumptionResponse(d),
627
- poll: simplePoll(
628
- () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
629
- d => gasCategory.parseConsumptionResponse(d),
630
- graphqlPost
631
- ),
632
- });
633
- }
634
-
635
- categories.push({
636
- id: 'wheel_of_fortune',
637
- enabled: config.enableWheelOfFortune || false,
638
- intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
639
- lastPolled: 0,
640
- queryFn: () => wheelOfFortuneCategory.buildQuery(account),
641
- parseFn: d => wheelOfFortuneCategory.parseResponse(d),
642
- poll: simplePoll(
643
- () => wheelOfFortuneCategory.buildQuery(account),
644
- d => wheelOfFortuneCategory.parseResponse(d),
645
- graphqlPost
646
- ),
647
- });
648
- if (discovered.smartMeterDeviceId) {
649
- categories.push({
650
- id: 'home_mini',
651
- enabled: config.enableHomeMini || false,
652
- intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
653
- lastPolled: 0,
654
- queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
655
- parseFn: d => homeMiniCategory.parseResponse(d),
656
- poll: simplePoll(
657
- () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
658
- d => homeMiniCategory.parseResponse(d),
659
- graphqlPost
660
- ),
661
- });
662
- }
663
- categories.push({
664
- id: 'saving_sessions',
665
- enabled: true,
666
- intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
667
- lastPolled: 0,
668
- queryFn: () => savingSessionsCategory.buildQuery(account),
669
- parseFn: d => savingSessionsCategory.parseResponse(d),
670
- poll: simplePoll(
671
- () => savingSessionsCategory.buildQuery(account),
672
- d => savingSessionsCategory.parseResponse(d),
673
- graphqlPost
674
- ),
675
- });
676
-
677
- if (discovered.hasIntelligent) {
678
- categories.push({
679
- id: 'completed_dispatches',
680
- enabled: true,
681
- intervalMs: 60 * 60 * 1000,
682
- lastPolled: 0,
683
- queryFn: () => completedDispatchesCategory.buildQuery(account),
684
- parseFn: d => completedDispatchesCategory.parseResponse(d),
685
- poll: simplePoll(
686
- () => completedDispatchesCategory.buildQuery(account),
687
- d => completedDispatchesCategory.parseResponse(d),
688
- graphqlPost
689
- ),
690
- });
691
- }
692
-
693
- if (discovered.hasElectricity && discovered.electricityMpan) {
694
- categories.push({
695
- id: 'applicable_rates',
696
- enabled: true,
697
- intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
698
- lastPolled: 0,
699
- queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
700
- parseFn: d => applicableRatesCategory.parseResponse(d),
701
- poll: simplePoll(
702
- () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
703
- d => applicableRatesCategory.parseResponse(d),
704
- graphqlPost
705
- ),
706
- });
707
- }
708
-
709
- // Export applicable rates — second query with the export MPAN. Same parser,
710
- // different field prefix so the output keys don't collide with import.
711
- if (discovered.hasElectricity && discovered.electricityExportMpan) {
712
- categories.push({
713
- id: 'applicable_rates_export',
714
- enabled: true,
715
- intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
716
- lastPolled: 0,
717
- queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
718
- parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
719
- poll: simplePoll(
720
- () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
721
- d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
722
- graphqlPost
723
- ),
724
- });
725
- }
726
-
727
- if (discovered.hasElectricity && discovered.electricityMpan) {
728
- categories.push({
729
- id: 'free_electricity',
730
- enabled: true,
731
- intervalMs: 30 * 60 * 1000, // 30 minutes
732
- lastPolled: 0,
733
- queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
734
- parseFn: d => freeElectricityCategory.parseResponse(d),
735
- poll: simplePoll(
736
- () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
737
- d => freeElectricityCategory.parseResponse(d),
738
- graphqlPost
739
- ),
740
- });
741
- }
742
-
743
- categories.push({
744
- id: 'account',
745
- enabled: true,
746
- intervalMs: 60 * 60 * 1000,
747
- lastPolled: 0,
748
- queryFn: () => accountCategory.buildQuery(account),
749
- parseFn: d => accountCategory.parseResponse(d),
750
- poll: simplePoll(
751
- () => accountCategory.buildQuery(account),
752
- d => accountCategory.parseResponse(d),
753
- graphqlPost
754
- ),
755
- });
756
-
757
- categories.push({
758
- id: 'octoplus',
759
- enabled: true,
760
- intervalMs: 60 * 60 * 1000,
761
- lastPolled: 0,
762
- queryFn: () => octoplusCategory.buildQuery(account),
763
- parseFn: d => octoplusCategory.parseResponse(d),
764
- poll: simplePoll(
765
- () => octoplusCategory.buildQuery(account),
766
- d => octoplusCategory.parseResponse(d),
767
- graphqlPost
768
- ),
769
- });
770
- }
771
-
772
- async function pollDueCategories() {
773
- const result = await runTick({
774
- categories,
775
- state: lastKnownState,
776
- getToken: obtainTickToken,
777
- });
778
- if (!result.emitted) return;
779
- lastKnownState = result.state;
780
- if (enableMqtt && node.broker && node.broker.client) {
781
- node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
782
- }
783
- node.send({ payload: lastKnownState });
784
- if (!validationMode) {
785
- if (lastKnownState.intelligent_error) {
786
- node.status({ fill: "red", shape: "ring", text: `Error: ${String(lastKnownState.intelligent_error).slice(0, 40)}` });
787
- } else {
788
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
789
- }
790
- }
791
- }
792
-
793
- async function obtainTickToken() {
794
- const response = await graphqlPost({
795
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
796
- variables: { input: { APIKey: apiKey } },
797
- });
798
- if (!response.data.data || !response.data.data.obtainKrakenToken) {
799
- throw new Error('Auth response missing token: ' + JSON.stringify(response.data.errors || response.data));
800
- }
801
- return response.data.data.obtainKrakenToken.token;
802
- }
803
-
804
- function forceCategoryDue(id) {
805
- const cat = categories.find((c) => c.id === id);
806
- if (cat) cat.lastPolled = 0;
807
- }
808
-
809
- async function setPreferences(newLimit, newTime) {
810
- // Validation
811
- let limit = parseInt(newLimit);
812
- let time = newTime;
813
-
814
- // Enforce Limits
815
- if (isNaN(limit) || limit < 50) limit = 50;
816
- if (limit > 100) limit = 100;
817
- // Round to nearest 5
818
- limit = Math.round(limit / 5) * 5;
819
-
820
- // Validate Time
821
- if (!TIME_OPTIONS.includes(time)) {
822
- node.warn(`Invalid time '${time}' requested. Defaulting to 08:00`);
823
- time = "08:00";
824
- }
825
-
826
- // Cancel any pending retry attempts from previous changes
827
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
828
- retryTimeouts = [];
829
-
830
- try {
831
- node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
832
-
833
- // A. Get Token
834
- const authResponse = await graphqlPost({
835
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
836
- variables: { input: { APIKey: apiKey } }
837
- });
838
-
839
- if (authResponse.data.errors) {
840
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
841
- }
842
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
843
- throw new Error(`Auth response missing token data`);
844
- }
845
-
846
- const token = authResponse.data.data.obtainKrakenToken.token;
847
-
848
- // B. Send Mutation
849
- if (!krakenflexDeviceId) {
850
- throw new Error('Device ID not available — cannot set preferences');
851
- }
852
-
853
- const mutation = `
854
- mutation setPreferences($input: SmartFlexDevicePreferencesInput!) {
855
- setDevicePreferences(input: $input) { __typename }
856
- }`;
857
-
858
- const DAYS = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'];
859
- function buildDevicePreferencesInput(deviceId, socLimit, readyTime) {
860
- return {
861
- deviceId,
862
- mode: 'CHARGE',
863
- unit: 'PERCENTAGE',
864
- schedules: DAYS.map(dayOfWeek => ({
865
- dayOfWeek,
866
- time: readyTime + ':00',
867
- min: 0,
868
- max: socLimit
869
- }))
870
- };
871
- }
872
-
873
- const variables = {
874
- input: buildDevicePreferencesInput(krakenflexDeviceId, limit, time)
875
- };
876
-
877
- const mutationResponse = await graphqlPost({
878
- query: mutation,
879
- variables: variables
880
- }, token);
881
-
882
- if (mutationResponse.data.errors) {
883
- throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
884
- }
885
-
886
- // Record mutation API usage (auth + mutation = ~250 complexity)
887
- const ESTIMATED_MUTATION_COMPLEXITY = 250;
888
- metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
889
-
890
- // C. Start exponential backoff validation
891
- expectedLimit = limit;
892
- expectedTime = time;
893
- validationMode = true;
894
- node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
895
-
896
- // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
897
- const retryIntervals = [15000, 30000, 60000, 120000];
898
- scheduleRetries(retryIntervals, 0);
899
-
900
- } catch (err) {
901
- node.error("Failed to set preferences: " + err.message);
902
- if (err.response) {
903
- node.error(`Response: ${JSON.stringify(err.response.data)}`);
904
- }
905
- node.status({ fill: "red", shape: "ring", text: "Update Failed" });
906
- expectedLimit = null;
907
- expectedTime = null;
908
- validationMode = false;
909
- }
910
- }
911
-
912
- function scheduleRetries(intervals, index) {
913
- if (index >= intervals.length) {
914
- // All retries exhausted, let normal interval take over
915
- node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
916
- expectedLimit = null;
917
- expectedTime = null;
918
- validationMode = false;
919
- return;
920
- }
921
-
922
- const timeout = setTimeout(async () => {
923
- await fetchDataWithValidation(intervals, index);
924
- }, intervals[index]);
925
-
926
- retryTimeouts.push(timeout);
927
- }
928
-
929
- async function fetchDataWithValidation(intervals, currentIndex) {
930
- try {
931
- const token = await obtainTickToken();
932
- const partial = await intelligentPoll(token);
933
- lastKnownState = Object.assign({}, lastKnownState, partial, { intelligent_error: null });
934
- if (enableMqtt && node.broker && node.broker.client) {
935
- node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
936
- }
937
- node.send({ payload: lastKnownState });
938
-
939
- const validated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
940
- if (validated) {
941
- validationMode = false;
942
- retryTimeouts.forEach((t) => clearTimeout(t));
943
- retryTimeouts = [];
944
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
945
- return;
946
- }
947
- const totalAttempts = intervals.length;
948
- const attempt = currentIndex + 1;
949
- if (currentIndex < intervals.length - 1) {
950
- node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
951
- scheduleRetries(intervals, currentIndex + 1);
952
- } else {
953
- validationMode = false;
954
- node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
955
- }
956
- } catch (error) {
957
- node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
958
- if (currentIndex < intervals.length - 1) {
959
- scheduleRetries(intervals, currentIndex + 1);
960
- } else {
961
- validationMode = false;
962
- node.status({ fill: "red", shape: "ring", text: "Validation failed" });
963
- }
964
- }
965
- }
966
-
967
- // Helper: Toggle smart charging on/off
968
- async function setSmartCharging(enable) {
969
- if (!krakenflexDeviceId) {
970
- node.warn("Device ID not available — cannot toggle smart charging");
971
- return;
972
- }
973
-
974
- // Cancel any pending verification retries
975
- smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
976
- smartChargingRetryTimeouts = [];
977
-
978
- const previousSuspended = smartChargingSuspended;
979
-
980
- try {
981
- node.status({ fill: "blue", shape: "dot", text: enable ? "Enabling smart charging..." : "Suspending smart charging..." });
982
-
983
- const authResponse = await graphqlPost({
984
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
985
- variables: { input: { APIKey: apiKey } }
986
- });
987
- if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
988
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
989
- }
990
- const token = authResponse.data.data.obtainKrakenToken.token;
991
-
992
- const action = enable ? "UNSUSPEND" : "SUSPEND";
993
- const mutationResponse = await graphqlPost({
994
- query: `mutation UpdateSmartControl($deviceId: ID!, $action: SmartControlAction!) { updateDeviceSmartControl(input: { deviceId: $deviceId, action: $action }) { id } }`,
995
- variables: { deviceId: krakenflexDeviceId, action: action }
996
- }, token);
997
-
998
- if (mutationResponse.data.errors) {
999
- throw new Error(`Smart charging mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
1000
- }
1001
-
1002
- // Record mutation API usage (auth + mutation = ~250 complexity)
1003
- const ESTIMATED_MUTATION_COMPLEXITY = 250;
1004
- metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
1005
-
1006
- // Optimistically update cached state
1007
- const expectedSuspended = !enable;
1008
- smartChargingSuspended = expectedSuspended;
1009
-
1010
- // Publish new state to HA switch topic immediately
1011
- if (enableMqtt && node.broker && node.broker.client) {
1012
- node.broker.client.publish(`${stateTopic}/smart_charging`, enable ? "ON" : "OFF", { retain: true });
1013
- }
1014
-
1015
- // Schedule verification: 15s / 30s / 60s / 120s
1016
- scheduleSmartChargingVerification(expectedSuspended, [15000, 30000, 60000, 120000], 0);
1017
-
1018
- } catch (e) {
1019
- node.error(`Failed to toggle smart charging: ${e.message}`);
1020
- // Revert optimistic update to pre-mutation state
1021
- smartChargingSuspended = previousSuspended;
1022
- node.status({ fill: "red", shape: "ring", text: "Smart charging update failed" });
1023
- // Republish previous state so HA switch UI re-syncs
1024
- if (enableMqtt && node.broker && node.broker.client && previousSuspended !== null) {
1025
- node.broker.client.publish(
1026
- `${stateTopic}/smart_charging`,
1027
- previousSuspended ? "OFF" : "ON",
1028
- { retain: true }
1029
- );
1030
- }
1031
- }
1032
- }
1033
-
1034
- function scheduleSmartChargingVerification(expectedSuspended, intervals, index) {
1035
- if (index >= intervals.length) {
1036
- node.warn("Smart charging state could not be confirmed after all retries");
1037
- node.status({ fill: "red", shape: "ring", text: "Smart charging: update unconfirmed" });
1038
- return;
1039
- }
1040
- const timeout = setTimeout(async () => {
1041
- try {
1042
- const authResponse = await graphqlPost({
1043
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1044
- variables: { input: { APIKey: apiKey } }
1045
- });
1046
- if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1047
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1048
- return;
1049
- }
1050
- const token = authResponse.data.data.obtainKrakenToken.token;
1051
-
1052
- const deviceResponse = await graphqlPost({
1053
- query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1054
- variables: { accountNumber: account }
1055
- }, token);
1056
-
1057
- if (deviceResponse.data.errors || !deviceResponse.data.data) {
1058
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1059
- return;
1060
- }
1061
-
1062
- const evDevice = (deviceResponse.data.data.devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES');
1063
- if (!evDevice) {
1064
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1065
- return;
1066
- }
1067
-
1068
- // Record verification API usage (auth + device query = ~200 complexity)
1069
- const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
1070
- metrics.recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
1071
-
1072
- const actualSuspended = evDevice.status.isSuspended;
1073
- if (actualSuspended === expectedSuspended) {
1074
- // Confirmed — clear remaining retries
1075
- smartChargingSuspended = actualSuspended;
1076
- smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1077
- smartChargingRetryTimeouts = [];
1078
- node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
1079
- node.status({ fill: "green", shape: "dot", text: actualSuspended ? "Smart charging suspended" : "Smart charging enabled" });
1080
- } else {
1081
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1082
- }
1083
- } catch (e) {
1084
- node.warn(`Smart charging verification attempt ${index + 1} failed: ${e.message}`);
1085
- scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1086
- }
1087
- }, intervals[index]);
1088
- smartChargingRetryTimeouts.push(timeout);
1089
- }
1090
-
1091
- // 6. Logic: Intelligent Poll (single-scheduler bespoke poll)
1092
- async function intelligentPoll(token) {
1093
- // 1. devices query
1094
- const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
1095
- const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
1096
- if (devicesResponse.data.errors) throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
1097
- if (!devicesResponse.data.data) throw new Error('Devices response missing data');
1098
- const devicesData = devicesResponse.data.data;
1099
- const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
1100
- if (!evDevice) throw new Error('No ELECTRIC_VEHICLES device found on account');
1101
- krakenflexDeviceId = evDevice.id;
1102
-
1103
- // 2. dispatches query (the single one that used to be duplicated by V1 + V2)
1104
- const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
1105
- const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
1106
- if (dispatchResponse.data.errors) throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
1107
- if (!dispatchResponse.data.data) throw new Error('Dispatches response missing data');
1108
-
1109
- // 3. parse twice — intelligent (slots/window) + flex-planned-dispatches (array/count)
1110
- const data = { devices: devicesData.devices, flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
1111
- const appliedTz = resolveTimezone(node);
1112
- const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (e) { return 'UTC'; } })();
1113
- const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
1114
- const { _activeSlots, ...catPublic } = catResult;
1115
- const flexResult = flexPlannedDispatchesCategory.parseResponse(dispatchResponse.data.data);
1116
-
1117
- // 4. metrics + side effects
1118
- metrics.recordPoll(300);
1119
- confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
1120
- confirmedTime = catResult.confirmed_time || confirmedTime;
1121
- if (!validationMode) {
1122
- pendingLimit = confirmedLimit;
1123
- pendingTime = confirmedTime;
1124
- }
1125
- setupChargingTimers(_activeSlots);
1126
- if (!stateCheckInterval) startStateReconciliation();
1127
- updateNextPollTime();
1128
-
1129
- const apiMetrics = metrics.getMetrics();
1130
-
1131
- // 5. merged partial payload
1132
- return Object.assign({}, catPublic, flexResult, {
1133
- pending_limit: pendingLimit,
1134
- pending_time: pendingTime,
1135
- charging_now: chargingNow,
1136
- next_poll: nextPollTime,
1137
- next_poll_raw: nextPollTime,
1138
- refresh_available_at: getRefreshAvailableAt(),
1139
- api_requests_hour: apiMetrics.requests_last_hour,
1140
- api_complexity_hour: apiMetrics.complexity_last_hour,
1141
- api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
1142
- timezone_detected: serverTz,
1143
- timezone_applied: appliedTz,
1144
- smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
1145
- });
1146
- }
1147
-
1148
-
1149
- // Helper: Fetch device ID and initial smart charging state (called once at startup)
1150
- async function fetchDeviceId() {
1151
- try {
1152
- const authResponse = await graphqlPost({
1153
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1154
- variables: { input: { APIKey: apiKey } }
1155
- });
1156
- if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1157
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1158
- }
1159
- const token = authResponse.data.data.obtainKrakenToken.token;
1160
-
1161
- const deviceResponse = await graphqlPost({
1162
- query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1163
- variables: { accountNumber: account }
1164
- }, token);
1165
-
1166
- if (deviceResponse.data.errors || !deviceResponse.data.data) {
1167
- throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
1168
- }
1169
-
1170
- function extractEvDevice(devices) {
1171
- return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
1172
- }
1173
-
1174
- const evDevice = extractEvDevice(deviceResponse.data.data.devices);
1175
- if (!evDevice) {
1176
- throw new Error('No ELECTRIC_VEHICLES device found on account');
1177
- }
1178
-
1179
- krakenflexDeviceId = evDevice.id;
1180
- smartChargingSuspended = evDevice.status.isSuspended;
1181
- node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
1182
- } catch (e) {
1183
- node.warn(`Failed to fetch device ID at startup: ${e.message}. Smart charging toggle unavailable.`);
1184
- krakenflexDeviceId = null;
1185
- smartChargingSuspended = null;
1186
- }
1187
- }
1188
-
1189
- // 6a. Charging Now - Timer Management Functions
1190
-
1191
- // State reconciliation - checks every 10s if charging state matches reality
1192
- function reconcileChargingState() {
1193
- if (!cachedSlots || cachedSlots.length === 0) return;
1194
-
1195
- const now = new Date();
1196
-
1197
- // Check if we should be charging RIGHT NOW based on cached slots
1198
- const shouldBeCharging = cachedSlots.some(slot => {
1199
- const start = new Date(slot.start);
1200
- const end = new Date(slot.end);
1201
- return start <= now && end > now;
1202
- });
1203
-
1204
- // Update state if it doesn't match reality
1205
- if (shouldBeCharging !== chargingNow) {
1206
- node.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
1207
- publishChargingState(shouldBeCharging);
1208
- }
1209
- }
1210
-
1211
- // Start state reconciliation loop (every 10 seconds)
1212
- function startStateReconciliation() {
1213
- // Clear existing interval
1214
- if (stateCheckInterval) {
1215
- clearInterval(stateCheckInterval);
1216
- }
1217
-
1218
- // Check state every 10 seconds
1219
- stateCheckInterval = setInterval(() => {
1220
- reconcileChargingState();
1221
- }, 10000);
1222
-
1223
- node.log("State reconciliation loop started (every 10s)");
1224
- }
1225
-
1226
- // Clear all charging timers
1227
- function clearChargingTimers() {
1228
- if (preValidationTimer) {
1229
- clearTimeout(preValidationTimer);
1230
- preValidationTimer = null;
1231
- }
1232
- if (slotStartTimer) {
1233
- clearTimeout(slotStartTimer);
1234
- slotStartTimer = null;
1235
- }
1236
- if (slotEndTimer) {
1237
- clearTimeout(slotEndTimer);
1238
- slotEndTimer = null;
1239
- }
1240
- if (stateCheckInterval) {
1241
- clearInterval(stateCheckInterval);
1242
- stateCheckInterval = null;
1243
- }
1244
- }
1245
-
1246
- // Manual refresh rate limiting helpers
1247
- function canManualRefresh() {
1248
- const now = Date.now();
1249
- const timeSinceLastRefresh = now - lastManualRefresh;
1250
- return lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN;
1251
- }
1252
-
1253
- function getSecondsUntilNextRefresh() {
1254
- const now = Date.now();
1255
- const timeSinceLastRefresh = now - lastManualRefresh;
1256
- const timeRemaining = MANUAL_REFRESH_COOLDOWN - timeSinceLastRefresh;
1257
- return Math.max(0, Math.ceil(timeRemaining / 1000));
1258
- }
1259
-
1260
- function getRefreshAvailableAt() {
1261
- const now = Date.now();
1262
- const timeSinceLastRefresh = now - lastManualRefresh;
1263
-
1264
- // If never refreshed OR cooldown expired, ready now
1265
- if (lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN) {
1266
- return null; // Ready - no cooldown
1267
- }
1268
-
1269
- // Cooldown active - return timestamp when it expires
1270
- return new Date(lastManualRefresh + MANUAL_REFRESH_COOLDOWN).toISOString();
1271
- }
1272
-
1273
- function publishRefreshCooldownState() {
1274
- if (enableMqtt && node.broker) {
1275
- const fullState = {
1276
- ...lastKnownState,
1277
- refresh_available_at: getRefreshAvailableAt()
1278
- };
1279
- node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: true });
1280
- }
1281
- }
1282
-
1283
- // Polling metrics helpers
1284
- function updateNextPollTime() {
1285
- nextPollTime = new Date(Date.now() + refreshRate).toISOString();
1286
- }
1287
-
1288
- // Publish charging state to MQTT and Node-RED
1289
- function publishChargingState(state) {
1290
- chargingNow = state;
1291
-
1292
- // Update MQTT
1293
- if (enableMqtt && node.broker) {
1294
- const payload = state ? "ON" : "OFF";
1295
- node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
1296
- }
1297
-
1298
- // Output message to Node-RED flow if state actually changed
1299
- if (lastSentChargingState !== state) {
1300
- lastSentChargingState = state;
1301
-
1302
- // Merge updated charging_now into last known full state
1303
- const outputPayload = {
1304
- ...lastKnownState,
1305
- charging_now: state
1306
- };
1307
-
1308
- node.send({
1309
- payload: outputPayload,
1310
- debug: {
1311
- timestamp: new Date().toISOString(),
1312
- trigger: 'charging_state_change',
1313
- success: true,
1314
- previous_state: !state,
1315
- new_state: state
1316
- }
1317
- });
1318
-
1319
- node.log(`Charging state changed: ${!state} → ${state}, message sent`);
1320
- }
1321
- }
1322
-
1323
- // Setup pre-validation timer (30s before slot starts)
1324
- function setupPreValidationTimer(nextSlot) {
1325
- const now = new Date();
1326
- const slotStart = new Date(nextSlot.start);
1327
- const preValidationTime = slotStart.getTime() - 30000; // 30s before
1328
- const msUntilPreValidation = preValidationTime - now.getTime();
1329
-
1330
- if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
1331
- preValidationTimer = setTimeout(async () => {
1332
- node.warn("Pre-validating slot data (30s before start)");
1333
- try {
1334
- if (!krakenflexDeviceId) {
1335
- throw new Error("Device ID not available for pre-validation");
1336
- }
1337
-
1338
- const authResponse = await graphqlPost({
1339
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1340
- variables: { input: { APIKey: apiKey } }
1341
- });
1342
-
1343
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1344
- throw new Error("Pre-validation auth failed");
1345
- }
1346
-
1347
- const token = authResponse.data.data.obtainKrakenToken.token;
1348
-
1349
- const { query: dq, variables: dv } = intelligentCategory.buildDispatchQuery(krakenflexDeviceId);
1350
- const dataResponse = await graphqlPost({ query: dq, variables: dv }, token);
1351
-
1352
- if (dataResponse.data.data && dataResponse.data.data.flexPlannedDispatches) {
1353
- cachedSlots = dataResponse.data.data.flexPlannedDispatches;
1354
-
1355
- // Record pre-validation API usage (auth + simple query = ~200 complexity)
1356
- const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
1357
- metrics.recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
1358
-
1359
- // Check if slot still exists (within 1 minute tolerance)
1360
- const stillExists = cachedSlots.find(s =>
1361
- Math.abs(new Date(s.start).getTime() - slotStart.getTime()) < 60000
1362
- );
1363
-
1364
- if (stillExists) {
1365
- node.warn(`Slot confirmed at ${stillExists.start}`);
1366
- setupSlotStartTimer(stillExists);
1367
- } else {
1368
- node.warn("Slot was cancelled or modified - not setting start timer");
1369
- }
1370
- }
1371
- } catch (error) {
1372
- node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
1373
- // Fallback: use original slot data
1374
- setupSlotStartTimer(nextSlot);
1375
- }
1376
- }, msUntilPreValidation);
1377
-
1378
- const minutesUntil = Math.round(msUntilPreValidation / 60000);
1379
- node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
1380
- }
1381
- }
1382
-
1383
- // Setup slot start timer (exact start time)
1384
- function setupSlotStartTimer(slot) {
1385
- const now = new Date();
1386
- const slotStart = new Date(slot.start);
1387
- const msUntilStart = slotStart.getTime() - now.getTime();
1388
-
1389
- if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
1390
- slotStartTimer = setTimeout(() => {
1391
- publishChargingState(true);
1392
- node.warn(`Charging slot started at ${slot.start}`);
1393
- setupSlotEndTimer(slot);
1394
- }, msUntilStart);
1395
-
1396
- const secondsUntil = Math.round(msUntilStart / 1000);
1397
- node.log(`Slot start timer set for ${secondsUntil}s (${slot.start})`);
1398
- } else if (msUntilStart <= 0) {
1399
- // Slot already started, check if it's still active
1400
- const slotEnd = new Date(slot.end);
1401
- if (slotEnd > now) {
1402
- publishChargingState(true);
1403
- setupSlotEndTimer(slot);
1404
- }
1405
- }
1406
- }
1407
-
1408
- // Setup slot end timer (exact end time)
1409
- function setupSlotEndTimer(slot) {
1410
- const now = new Date();
1411
- const slotEnd = new Date(slot.end);
1412
- const msUntilEnd = slotEnd.getTime() - now.getTime();
1413
-
1414
- if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
1415
- slotEndTimer = setTimeout(() => {
1416
- node.warn(`Charging slot ended at ${slot.end}`);
1417
-
1418
- // Check if another slot starts immediately (within cached data)
1419
- const now = new Date();
1420
- const immediateNextSlot = cachedSlots.find(s => {
1421
- const start = new Date(s.start);
1422
- const end = new Date(s.end);
1423
- return start <= now && end > now;
1424
- });
1425
-
1426
- if (immediateNextSlot) {
1427
- node.warn("Next slot starting immediately");
1428
- publishChargingState(true);
1429
- setupSlotEndTimer(immediateNextSlot);
1430
- } else {
1431
- publishChargingState(false);
1432
- }
1433
- }, msUntilEnd);
1434
-
1435
- const minutesUntil = Math.round(msUntilEnd / 60000);
1436
- node.log(`Slot end timer set for ${minutesUntil} min (${slot.end})`);
1437
- }
1438
- }
1439
-
1440
- // Main timer setup - called on each poll
1441
- function setupChargingTimers(slots) {
1442
- // Clear existing timers
1443
- clearChargingTimers();
1444
-
1445
- // Cache slots for later use
1446
- cachedSlots = slots;
1447
-
1448
- const now = new Date();
1449
-
1450
- // Check if currently in a charging slot
1451
- const activeSlot = slots.find(s => {
1452
- const start = new Date(s.start);
1453
- const end = new Date(s.end);
1454
- return start <= now && end > now;
1455
- });
1456
-
1457
- if (activeSlot) {
1458
- // Currently charging
1459
- const newState = true;
1460
- if (chargingNow !== newState) {
1461
- publishChargingState(newState);
1462
- }
1463
- setupSlotEndTimer(activeSlot);
1464
- node.log("Currently charging - end timer set");
1465
- } else {
1466
- // Not currently charging
1467
- const newState = false;
1468
- if (chargingNow !== newState) {
1469
- publishChargingState(newState);
1470
- }
1471
-
1472
- // Find next future slot
1473
- const nextSlot = slots.find(s => new Date(s.start) > now);
1474
-
1475
- if (nextSlot) {
1476
- setupPreValidationTimer(nextSlot);
1477
- node.log(`Next slot at ${nextSlot.start}`);
1478
- }
1479
- }
1480
- }
1481
-
1482
- // 7. Event Listeners
1483
-
1484
- // Helper: Publish current state (both pending and confirmed)
1485
- // This merges pending values into last known full state to prevent sensors going unknown
1486
- function publishCurrentState() {
1487
- if (enableMqtt && node.broker) {
1488
- // Merge pending values into last known state
1489
- const fullState = {
1490
- ...lastKnownState,
1491
- pending_limit: pendingLimit,
1492
- pending_time: pendingTime,
1493
- confirmed_limit: confirmedLimit,
1494
- confirmed_time: confirmedTime
1495
- };
1496
- node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: false });
1497
- }
1498
- }
1499
-
1500
- // A. Handle Node-RED Input Messages (NO rate limiting - programmers control this)
1501
- node.on('input', function (msg) {
1502
- // Check for control commands (preference updates)
1503
- if (msg.payload && typeof msg.payload === 'object') {
1504
- if (msg.payload.set_limit || msg.payload.set_time) {
1505
- // Use new values if present, otherwise keep existing
1506
- const targetLimit = msg.payload.set_limit || confirmedLimit;
1507
- const targetTime = msg.payload.set_time || confirmedTime;
1508
- setPreferences(targetLimit, targetTime);
1509
- return; // Don't run standard fetch if setting
1510
- }
1511
- if (msg.payload.set_timezone !== undefined) {
1512
- const tz = msg.payload.set_timezone;
1513
- if (typeof tz === 'string' && tz.trim().length > 0) {
1514
- node.context().set('timezone', tz.trim());
1515
- node.log(`Timezone set to: ${tz.trim()}`);
1516
- }
1517
- return;
1518
- }
1519
- if (msg.payload.set_smart_charging !== undefined) {
1520
- const val = msg.payload.set_smart_charging;
1521
- if (typeof val === 'boolean') {
1522
- setSmartCharging(val);
1523
- }
1524
- // silently ignore non-boolean (consistent with other handlers)
1525
- return;
1526
- }
1527
- }
1528
-
1529
- // Manual refresh request from Node-RED - NO rate limiting
1530
- // (Programmers can control rate limiting in their flows if needed)
1531
- // Update timestamp so HA sees cooldown, but don't block the refresh
1532
- lastManualRefresh = Date.now();
1533
- node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1534
- forceCategoryDue('intelligent');
1535
- });
1536
-
1537
- // B. Handle MQTT Commands (Home Assistant)
1538
- if (enableMqtt && node.broker) {
1539
- node.broker.register(this);
1540
-
1541
- // Slider changed - update pending value only
1542
- node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
1543
- const val = parseInt(payload.toString());
1544
- pendingLimit = val;
1545
- publishCurrentState(); // Update display immediately
1546
- node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1547
- });
1548
-
1549
- // Dropdown changed - update pending value only
1550
- node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
1551
- const val = payload.toString();
1552
- pendingTime = val;
1553
- publishCurrentState(); // Update display immediately
1554
- node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1555
- });
1556
-
1557
- // Button pressed - submit changes to API
1558
- node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
1559
- setPreferences(pendingLimit, pendingTime);
1560
- });
1561
-
1562
- // Refresh button pressed - MQTT has hardcoded 30s rate limiting
1563
- node.broker.subscribe(cmdTopicRefresh, 0, (topic, payload) => {
1564
- // Check rate limit (only for MQTT button)
1565
- if (!canManualRefresh()) {
1566
- const secondsRemaining = getSecondsUntilNextRefresh();
1567
- node.status({
1568
- fill: "red",
1569
- shape: "dot",
1570
- text: `Cooldown: ${secondsRemaining}s`
1571
- });
1572
- node.warn(`MQTT refresh blocked. Please wait ${secondsRemaining} seconds.`);
1573
- return; // Block the refresh
1574
- }
1575
-
1576
- // Refresh allowed - set cooldown timestamp
1577
- lastManualRefresh = Date.now();
1578
-
1579
- // Publish immediate update with countdown timestamp
1580
- publishRefreshCooldownState();
1581
-
1582
- // Schedule cleanup at exactly 30 seconds to clear countdown
1583
- if (cooldownExpiryTimer) clearTimeout(cooldownExpiryTimer);
1584
- cooldownExpiryTimer = setTimeout(() => {
1585
- // Cooldown expired - publish null to clear countdown in HA
1586
- publishRefreshCooldownState();
1587
- cooldownExpiryTimer = null;
1588
- }, MANUAL_REFRESH_COOLDOWN);
1589
-
1590
- // Trigger the actual refresh
1591
- node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1592
- forceCategoryDue('intelligent');
1593
- });
1594
-
1595
- // Timezone select changed in Home Assistant
1596
- node.broker.subscribe(cmdTopicTimezone, 0, (topic, payload) => {
1597
- const tz = payload.toString().trim();
1598
- if (tz.length > 0) {
1599
- node.context().set('timezone', tz);
1600
- node.log(`Timezone set via MQTT to: ${tz}`);
1601
- node.broker.client.publish(`${stateTopic}/timezone`, tz, { retain: true });
1602
- }
1603
- });
1604
-
1605
- // Smart charging switch toggled in Home Assistant
1606
- node.broker.subscribe(cmdTopicSmartCharging, 0, (topic, payload) => {
1607
- const val = payload.toString().trim();
1608
- if (val === "ON") setSmartCharging(true);
1609
- else if (val === "OFF") setSmartCharging(false);
1610
- });
1611
-
1612
- initTimeoutHandles.push(setTimeout(announceControls, 2000));
1613
-
1614
- // Republish persisted timezone to HA select on startup
1615
- initTimeoutHandles.push(setTimeout(() => {
1616
- try {
1617
- const persistedTz = node.context().get('timezone');
1618
- if (persistedTz && node.broker) {
1619
- node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
1620
- }
1621
- } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
1622
- }, 2500));
1623
-
1624
- // Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
1625
- initTimeoutHandles.push(setTimeout(() => {
1626
- try {
1627
- if (smartChargingSuspended !== null && node.broker && node.broker.client) {
1628
- const stateVal = smartChargingSuspended ? "OFF" : "ON";
1629
- node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
1630
- }
1631
- } catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
1632
- }, 3000));
1633
- }
1634
-
1635
- // Init
1636
- initTimeoutHandles.push(setTimeout(fetchDeviceId, 1500));
1637
-
1638
- // V2 category discovery and scheduler. Tracked + nodeClosed-guarded so that a
1639
- // node redeploy during the 2s warmup (or during the async discovery/init) can
1640
- // never leave an orphan scheduler running.
1641
- initTimeoutHandles.push(setTimeout(async () => {
1642
- try {
1643
- const discovered = await discoverProducts(apiKey, account);
1644
- if (nodeClosed) return;
1645
- if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
1646
- smartChargingSuspended = discovered.deviceSuspended;
1647
- lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
1648
- }
1649
- await initCategories(discovered);
1650
- if (nodeClosed) return;
1651
- node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}`);
1652
- const v2Scheduler = createScheduler(pollDueCategories);
1653
- v2Scheduler.start();
1654
- node._v2Scheduler = v2Scheduler;
1655
- } catch (e) {
1656
- node.warn(`V2 discovery failed: ${e.message}. New categories unavailable.`);
1657
- }
1658
- }, 2000));
1659
-
1660
- node.on('close', () => {
1661
- nodeClosed = true;
1662
- // Clear init setTimeouts so a redeploy during warmup can't leave an orphan scheduler
1663
- initTimeoutHandles.forEach(h => clearTimeout(h));
1664
- initTimeoutHandles = [];
1665
- // Clear any pending retry timeouts
1666
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
1667
- retryTimeouts = [];
1668
- // Clear smart charging retry timeouts
1669
- smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1670
- smartChargingRetryTimeouts = [];
1671
- // Clear charging timers
1672
- clearChargingTimers();
1673
- // Clear cooldown expiry timer
1674
- if (cooldownExpiryTimer) {
1675
- clearTimeout(cooldownExpiryTimer);
1676
- cooldownExpiryTimer = null;
1677
- }
1678
- if (node._v2Scheduler) node._v2Scheduler.stop();
1679
- if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging);
1680
- });
1681
- }
1682
-
1683
- RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
1684
- credentials: { apiKey: { type: "password" } }
1685
- });
1
+ 'use strict';
2
+ const { graphqlPost } = require('./lib/graphql');
3
+ const { onlyDeviceFieldErrors } = require('./lib/graphql-errors');
4
+ const { convertToTimezone, resolveTimezone } = require('./lib/timezone');
5
+ const { createApiMetrics } = require('./lib/api-metrics');
6
+ const intelligentCategory = require('./lib/categories/intelligent');
7
+ const { buildDefaultPayload } = require('./lib/payload');
8
+ const { createScheduler } = require('./lib/scheduler');
9
+ const { discoveryRetryDelay } = require('./lib/discovery-retry');
10
+ const { simplePoll, runTick } = require('./lib/poll-tick');
11
+ const { discoverProducts } = require('./lib/discovery');
12
+ const { mergePayload } = require('./lib/payload');
13
+ const electricityCategory = require('./lib/categories/electricity');
14
+ const gasCategory = require('./lib/categories/gas');
15
+ const wheelOfFortuneCategory = require('./lib/categories/wheel-of-fortune');
16
+ const homeMiniCategory = require('./lib/categories/home-mini');
17
+ const completedDispatchesCategory = require('./lib/categories/completed-dispatches');
18
+ const accountCategory = require('./lib/categories/account');
19
+ const octoplusCategory = require('./lib/categories/octoplus');
20
+ const flexPlannedDispatchesCategory = require('./lib/categories/flex-planned-dispatches');
21
+ const applicableRatesCategory = require('./lib/categories/applicable-rates');
22
+ const savingSessionsCategory = require('./lib/categories/saving-sessions');
23
+ const freeElectricityCategory = require('./lib/categories/free-electricity');
24
+ const httpGetJson = require('./lib/http-get-json');
25
+ const { TIME_OPTIONS, validateTime, validateLimit } = require('./lib/preferences');
26
+ const { planCommands } = require('./lib/commands');
27
+ const { checkUpdate } = require('./lib/update-check');
28
+ const { sensors, errorSensors } = require('./lib/sensor-definitions');
29
+
30
+ module.exports = function (RED) {
31
+ function OctopusIntelligentNode(config) {
32
+ RED.nodes.createNode(this, config);
33
+ var node = this;
34
+
35
+ // 1. Configuration
36
+ const account = config.accountNumber ? config.accountNumber.trim() : "";
37
+ const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
38
+ const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
39
+ const enableMqtt = config.enableMqtt;
40
+ node.timezoneOverride = config.timezoneOverride || "";
41
+
42
+ // MQTT Topics
43
+ this.broker = RED.nodes.getNode(config.broker);
44
+ const mqttPrefix = `homeassistant`;
45
+ const uniqueIdPrefix = `nodered_${account}`;
46
+ const stateTopic = `nodered_octopus/${account}/status`;
47
+
48
+ // Command Topics (For listening)
49
+ const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
50
+ const cmdTopicTime = `nodered_octopus/${account}/set_time`;
51
+ const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
52
+ const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
53
+ const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
54
+ const cmdTopicSmartCharging = `nodered_octopus/${account}/set_smart_charging`;
55
+ const cmdTopicChargeCap = `nodered_octopus/${account}/set_charge_cap`;
56
+
57
+ // 2. Constants & Validation — TIME_OPTIONS / validators live in lib/preferences.js
58
+
59
+ // 3. Sensor Definitions (Read-Only) — imported from lib/sensor-definitions.js
60
+
61
+ // 4. Helper: Announce Controls (Write-Enabled)
62
+ function announceControls() {
63
+ if (!enableMqtt || !node.broker) return;
64
+
65
+ // Single device definition with branding
66
+ const device = {
67
+ identifiers: [`nodered_octopus_${account}`],
68
+ name: "Octopus Intelligent",
69
+ manufacturer: "Octopus Energy",
70
+ model: "Intelligent Octopus Go",
71
+ sw_version: "2.0.0",
72
+ suggested_area: "Energy",
73
+ configuration_url: "https://octopus.energy/intelligent/"
74
+ };
75
+
76
+ // A. The Slider (Number) - now shows pending value
77
+ const limitConfig = {
78
+ name: "Octopus Target Charge",
79
+ unique_id: `${uniqueIdPrefix}_target_limit`,
80
+ state_topic: stateTopic,
81
+ command_topic: cmdTopicLimit,
82
+ value_template: "{{ value_json.pending_limit }}",
83
+ min: 5, max: 100, step: 5,
84
+ unit_of_measurement: "%",
85
+ icon: "mdi:battery-charging-high",
86
+ device: device
87
+ };
88
+ node.broker.client.publish(`${mqttPrefix}/number/${uniqueIdPrefix}_limit/config`, JSON.stringify(limitConfig), { retain: true });
89
+
90
+ // B. The Dropdown (Select) - now shows pending value
91
+ const timeConfig = {
92
+ name: "Octopus Ready Time",
93
+ unique_id: `${uniqueIdPrefix}_target_time`,
94
+ state_topic: stateTopic,
95
+ command_topic: cmdTopicTime,
96
+ value_template: "{{ value_json.pending_time }}",
97
+ options: TIME_OPTIONS,
98
+ icon: "mdi:clock-time-four-outline",
99
+ device: device
100
+ };
101
+ node.broker.client.publish(`${mqttPrefix}/select/${uniqueIdPrefix}_time/config`, JSON.stringify(timeConfig), { retain: true });
102
+
103
+ // C. Submit Button
104
+ const buttonConfig = {
105
+ name: "Octopus Apply Changes",
106
+ unique_id: `${uniqueIdPrefix}_submit_button`,
107
+ command_topic: cmdTopicSubmit,
108
+ payload_press: "SUBMIT",
109
+ icon: "mdi:check-circle",
110
+ device_class: "update",
111
+ device: device
112
+ };
113
+ node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
114
+
115
+ // D. Refresh Button
116
+ const refreshButtonConfig = {
117
+ name: "Octopus Refresh API",
118
+ unique_id: `${uniqueIdPrefix}_refresh_button`,
119
+ command_topic: cmdTopicRefresh,
120
+ payload_press: "REFRESH",
121
+ icon: "mdi:refresh",
122
+ device_class: "restart",
123
+ device: device
124
+ };
125
+ node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_refresh/config`, JSON.stringify(refreshButtonConfig), { retain: true });
126
+
127
+ // E. Add sensors for confirmed values (read-only display)
128
+ const confirmedLimitSensor = {
129
+ name: "Octopus Confirmed Charge Limit",
130
+ unique_id: `${uniqueIdPrefix}_confirmed_limit`,
131
+ state_topic: stateTopic,
132
+ value_template: "{{ value_json.confirmed_limit }}",
133
+ unit_of_measurement: "%",
134
+ icon: "mdi:battery-check",
135
+ device: device
136
+ };
137
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_limit/config`, JSON.stringify(confirmedLimitSensor), { retain: true });
138
+
139
+ const confirmedTimeSensor = {
140
+ name: "Octopus Confirmed Ready Time",
141
+ unique_id: `${uniqueIdPrefix}_confirmed_time`,
142
+ state_topic: stateTopic,
143
+ value_template: "{{ value_json.confirmed_time }}",
144
+ icon: "mdi:clock-check",
145
+ device: device
146
+ };
147
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
148
+
149
+ // G. Charging Now Binary Sensor (main sensor for automations)
150
+ const chargingNowBinarySensor = {
151
+ name: "Octopus Charging Now",
152
+ unique_id: `${uniqueIdPrefix}_charging_now`,
153
+ state_topic: `${stateTopic}/charging_now`,
154
+ device_class: "battery_charging",
155
+ payload_on: "ON",
156
+ payload_off: "OFF",
157
+ icon: "mdi:ev-station",
158
+ device: device
159
+ };
160
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
161
+
162
+ // G2. Saving Session Available Binary Sensor
163
+ const savingSessionBinarySensor = {
164
+ name: "Octopus Saving Session Available",
165
+ unique_id: `${uniqueIdPrefix}_saving_session_available`,
166
+ state_topic: stateTopic,
167
+ value_template: "{{ value_json.saving_session_available }}",
168
+ payload_on: "True",
169
+ payload_off: "False",
170
+ icon: "mdi:lightning-bolt-circle",
171
+ device: device
172
+ };
173
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_available/config`, JSON.stringify(savingSessionBinarySensor), { retain: true });
174
+
175
+ // G2a. Saving Session Window Active Binary Sensor (v1.3.3)
176
+ const savingSessionWindowActiveSensor = {
177
+ name: "Octopus Saving Session Window Active",
178
+ unique_id: `${uniqueIdPrefix}_saving_session_window_active`,
179
+ state_topic: stateTopic,
180
+ value_template: "{{ value_json.saving_session_window_active }}",
181
+ payload_on: "True",
182
+ payload_off: "False",
183
+ icon: "mdi:clock-check-outline",
184
+ device: device
185
+ };
186
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_window_active/config`, JSON.stringify(savingSessionWindowActiveSensor), { retain: true });
187
+
188
+ // G2b. Saving Session Active Binary Sensor (v1.3.3) — joined AND in window
189
+ const savingSessionActiveSensor = {
190
+ name: "Octopus Saving Session Active",
191
+ unique_id: `${uniqueIdPrefix}_saving_session_active`,
192
+ state_topic: stateTopic,
193
+ value_template: "{{ value_json.saving_session_active }}",
194
+ payload_on: "True",
195
+ payload_off: "False",
196
+ icon: "mdi:home-export-outline",
197
+ device: device
198
+ };
199
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_active/config`, JSON.stringify(savingSessionActiveSensor), { retain: true });
200
+
201
+ // G2c. v1.3.3 migration: delete the deprecated sensor.saving_session_joined
202
+ // entity. HA's sensor domain doesn't render booleans cleanly. Empty
203
+ // payload on the discovery topic with retain tells HA the entity no
204
+ // longer exists. Safe to keep across releases.
205
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_saving_session_joined/config`, "", { retain: true });
206
+
207
+ // G2d. Saving Session Joined Binary Sensor (v1.3.3 migration)
208
+ const savingSessionJoinedSensor = {
209
+ name: "Octopus Saving Session Joined",
210
+ unique_id: `${uniqueIdPrefix}_saving_session_joined`,
211
+ state_topic: stateTopic,
212
+ value_template: "{{ value_json.saving_session_joined }}",
213
+ payload_on: "True",
214
+ payload_off: "False",
215
+ icon: "mdi:account-check",
216
+ device: device
217
+ };
218
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_joined/config`, JSON.stringify(savingSessionJoinedSensor), { retain: true });
219
+
220
+ // G3. Free Electricity Active Binary Sensor
221
+ const freeElectricityActiveSensor = {
222
+ name: "Octopus Free Electricity Active",
223
+ unique_id: `${uniqueIdPrefix}_free_electricity_active`,
224
+ state_topic: stateTopic,
225
+ value_template: "{{ value_json.free_electricity_active }}",
226
+ payload_on: "True",
227
+ payload_off: "False",
228
+ icon: "mdi:flash-circle",
229
+ device: device
230
+ };
231
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_active/config`, JSON.stringify(freeElectricityActiveSensor), { retain: true });
232
+
233
+ // G4. Free Electricity Available Binary Sensor
234
+ const freeElectricityAvailableSensor = {
235
+ name: "Octopus Free Electricity Available",
236
+ unique_id: `${uniqueIdPrefix}_free_electricity_available`,
237
+ state_topic: stateTopic,
238
+ value_template: "{{ value_json.free_electricity_available }}",
239
+ payload_on: "True",
240
+ payload_off: "False",
241
+ icon: "mdi:flash-circle-outline",
242
+ device: device
243
+ };
244
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_available/config`, JSON.stringify(freeElectricityAvailableSensor), { retain: true });
245
+
246
+ // G5. Octoplus Enrolled Binary Sensor
247
+ // Published as binary_sensor (not sensor) because the value is a boolean —
248
+ // HA's sensor domain rejects booleans without a device_class, leaving the
249
+ // entity unregistered. No entity_category: 'config' on a read-only sensor
250
+ // makes its state stick at "unavailable" on some HA installs (same fix as
251
+ // the v1.3.0 tariff-sensor cleanup — see CHANGELOG).
252
+ const octoplusEnrolledBinarySensor = {
253
+ name: "Octopus Octoplus Enrolled",
254
+ unique_id: `${uniqueIdPrefix}_octoplus_enrolled`,
255
+ state_topic: stateTopic,
256
+ value_template: "{{ value_json.octoplus_enrolled }}",
257
+ payload_on: "True",
258
+ payload_off: "False",
259
+ icon: "mdi:star-circle",
260
+ device: device
261
+ };
262
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_enrolled/config`, JSON.stringify(octoplusEnrolledBinarySensor), { retain: true });
263
+
264
+ // G6. Octoplus Loyalty Points (boolean) Binary Sensor
265
+ // No entity_category — see G5.
266
+ const octoplusLoyaltyBinarySensor = {
267
+ name: "Octopus Octoplus Loyalty Points",
268
+ unique_id: `${uniqueIdPrefix}_octoplus_loyalty_points_user`,
269
+ state_topic: stateTopic,
270
+ value_template: "{{ value_json.octoplus_loyalty_points_user }}",
271
+ payload_on: "True",
272
+ payload_off: "False",
273
+ icon: "mdi:star",
274
+ device: device
275
+ };
276
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_loyalty_points_user/config`, JSON.stringify(octoplusLoyaltyBinarySensor), { retain: true });
277
+
278
+ // H. Announce Read-Only Sensors
279
+ sensors.forEach(sensor => {
280
+ const payload = {
281
+ name: `Octopus ${sensor.name}`,
282
+ unique_id: `${uniqueIdPrefix}_${sensor.id}`,
283
+ state_topic: stateTopic,
284
+ value_template: `{{ value_json.${sensor.val} }}`,
285
+ device: device
286
+ };
287
+ if (sensor.class) payload.device_class = sensor.class;
288
+ if (sensor.unit) payload.unit_of_measurement = sensor.unit;
289
+ if (sensor.stateClass) payload.state_class = sensor.stateClass;
290
+ if (sensor.icon) payload.icon = sensor.icon;
291
+
292
+ if (sensor.category) {
293
+ payload.entity_category = sensor.category;
294
+ }
295
+
296
+ if (sensor.id === 'applicable_rates_count') {
297
+ payload.json_attributes_topic = stateTopic;
298
+ payload.json_attributes_template = '{ "rates": {{ value_json.applicable_rates | tojson }} }';
299
+ } else if (sensor.id === 'electricity_export_rate_count') {
300
+ payload.json_attributes_topic = stateTopic;
301
+ payload.json_attributes_template = '{ "rates": {{ value_json.electricity_export_rate | tojson }} }';
302
+ }
303
+
304
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
305
+ });
306
+
307
+ // H2. v1.5 — error binary_sensors (device_class: problem)
308
+ errorSensors.forEach(e => {
309
+ const payload = {
310
+ name: `Octopus ${e.name}`,
311
+ unique_id: `${uniqueIdPrefix}_${e.id}`,
312
+ state_topic: stateTopic,
313
+ value_template: `{{ 'OFF' if value_json.${e.val} in [None, ''] else 'ON' }}`,
314
+ payload_on: 'ON',
315
+ payload_off: 'OFF',
316
+ device_class: 'problem',
317
+ entity_category: 'diagnostic',
318
+ device: device,
319
+ };
320
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_${e.id}/config`, JSON.stringify(payload), { retain: true });
321
+ });
322
+
323
+ // I. Timezone Select Entity
324
+ const TIMEZONE_OPTIONS = [
325
+ "Europe/London", "Europe/Berlin", "Europe/Madrid",
326
+ "Australia/Sydney", "Australia/Melbourne", "Australia/Brisbane",
327
+ "Australia/Perth", "Australia/Adelaide", "Pacific/Auckland",
328
+ "America/New_York", "America/Chicago", "America/Denver",
329
+ "America/Los_Angeles", "Asia/Tokyo", "UTC"
330
+ ];
331
+ node.broker.client.publish(
332
+ `${mqttPrefix}/select/${uniqueIdPrefix}_timezone/config`,
333
+ JSON.stringify({
334
+ name: "Timezone",
335
+ unique_id: `${uniqueIdPrefix}_timezone`,
336
+ options: TIMEZONE_OPTIONS,
337
+ command_topic: cmdTopicTimezone,
338
+ state_topic: `${stateTopic}/timezone`,
339
+ icon: "mdi:earth",
340
+ entity_category: "config",
341
+ device: device
342
+ }),
343
+ { retain: true }
344
+ );
345
+
346
+ // J. Smart Charging Switch
347
+ node.broker.client.publish(
348
+ `${mqttPrefix}/switch/${uniqueIdPrefix}_smart_charging/config`,
349
+ JSON.stringify({
350
+ name: "Smart Charging",
351
+ unique_id: `${uniqueIdPrefix}_smart_charging`,
352
+ command_topic: cmdTopicSmartCharging,
353
+ state_topic: `${stateTopic}/smart_charging`,
354
+ payload_on: "ON",
355
+ payload_off: "OFF",
356
+ icon: "mdi:lightning-bolt",
357
+ entity_category: "config",
358
+ device: device
359
+ }),
360
+ { retain: true }
361
+ );
362
+
363
+ // J2. Charge Cap Switch — limit smart charging to off-peak rates only (v1.6)
364
+ node.broker.client.publish(
365
+ `${mqttPrefix}/switch/${uniqueIdPrefix}_charge_cap/config`,
366
+ JSON.stringify({
367
+ name: "Charge Cap",
368
+ unique_id: `${uniqueIdPrefix}_charge_cap`,
369
+ command_topic: cmdTopicChargeCap,
370
+ state_topic: `${stateTopic}/charge_cap`,
371
+ payload_on: "ON",
372
+ payload_off: "OFF",
373
+ icon: "mdi:cash-clock",
374
+ entity_category: "config",
375
+ device: device
376
+ }),
377
+ { retain: true }
378
+ );
379
+
380
+ // K. v1.5 — Update entity (notify-only; Palette Manager is the install path)
381
+ node.broker.client.publish(
382
+ `${mqttPrefix}/update/${uniqueIdPrefix}_node_update/config`,
383
+ JSON.stringify({
384
+ name: 'Octopus Intelligent Node',
385
+ unique_id: `${uniqueIdPrefix}_node_update`,
386
+ state_topic: `${stateTopic}/node_update`,
387
+ title: 'node-red-contrib-octopus-intelligent',
388
+ release_url: 'https://github.com/ASomerN/node-red-contrib-octopus-intelligent/releases',
389
+ device: device,
390
+ }),
391
+ { retain: true }
392
+ );
393
+
394
+ // Subscribe to Commands
395
+ node.broker.client.subscribe(cmdTopicLimit);
396
+ node.broker.client.subscribe(cmdTopicTime);
397
+ node.broker.client.subscribe(cmdTopicSubmit);
398
+ node.broker.client.subscribe(cmdTopicRefresh);
399
+ node.broker.client.subscribe(cmdTopicTimezone);
400
+ node.broker.client.subscribe(cmdTopicSmartCharging);
401
+ node.broker.client.subscribe(cmdTopicChargeCap);
402
+ }
403
+
404
+ // 5. Helper: Set Preferences (The Mutation)
405
+ let retryTimeouts = []; // Track pending retry timeouts
406
+ let expectedLimit = null;
407
+ let expectedTime = null;
408
+ let validationMode = false;
409
+
410
+ // Pending vs Confirmed state
411
+ let pendingLimit = 80;
412
+ let pendingTime = "08:00";
413
+ let confirmedLimit = 80;
414
+ let confirmedTime = "08:00";
415
+ let chargeCapNaWarned = false; // warn once when the API says Charge Cap doesn't apply
416
+
417
+ // Charging Now feature - timer-based state management
418
+ let chargingNow = false;
419
+ let preValidationTimer = null; // Fires 30s before slot start
420
+ let slotStartTimer = null; // Fires at exact slot start
421
+ let slotEndTimer = null; // Fires at exact slot end
422
+ let cachedSlots = []; // Fresh slot data from pre-validation
423
+ let stateCheckInterval = null; // Reconciliation loop (every 10s)
424
+ let lastSentChargingState = null; // Track last sent state to avoid duplicates
425
+
426
+ // Manual refresh rate limiting (only for MQTT button, not Node-RED input)
427
+ let lastManualRefresh = 0; // Timestamp of last manual refresh
428
+ const MANUAL_REFRESH_COOLDOWN = 30000; // 30 seconds in milliseconds
429
+ let cooldownExpiryTimer = null; // Timer to clear cooldown state at expiry
430
+
431
+ // Polling metrics
432
+ let nextPollTime = null; // ISO timestamp of next scheduled poll
433
+ const metrics = createApiMetrics();
434
+
435
+ // API Complexity Tracking
436
+ // Octopus Energy API does not return actual complexity values in headers or extensions,
437
+ // so we use estimated complexity based on query types:
438
+ // - Regular poll (auth + data query): ~300
439
+ // - Mutation (auth + setPreferences): ~250
440
+ // - Pre-validation (auth + flexPlannedDispatches only): ~200
441
+
442
+ // Smart charging state (fetched once at startup)
443
+ let krakenflexDeviceId = null;
444
+ let smartChargingSuspended = null; // null=unknown, true=suspended(off), false=active(on)
445
+ let smartChargingRetryTimeouts = [];
446
+
447
+ // Last known full state - prevents sensors going unknown when controls change
448
+ let lastKnownState = buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
449
+ lastKnownState.installed_version = require('./package.json').version;
450
+
451
+ // V2 category registry — populated after discovery
452
+ let categories = [];
453
+
454
+ // Lifecycle tracking — init setTimeouts must be clearable on close, and async
455
+ // callbacks inside them must short-circuit if the node was closed mid-await,
456
+ // otherwise a redeploy during the 2s warmup leaves an orphan V2 scheduler.
457
+ let initTimeoutHandles = [];
458
+ let nodeClosed = false;
459
+ let lastWarnedVersion = null;
460
+ let prevPublishedInstalled = null;
461
+ let prevPublishedLatest = null;
462
+
463
+ async function initCategories(discovered) {
464
+ categories = [];
465
+
466
+ if (discovered.hasIntelligent) {
467
+ categories.push({
468
+ id: 'intelligent',
469
+ enabled: true,
470
+ intervalMs: (config.refreshInterval || 5) * 60 * 1000,
471
+ lastPolled: 0,
472
+ poll: intelligentPoll,
473
+ });
474
+ }
475
+
476
+ const electricityEnabled = config.electricityEnabled !== false;
477
+ const gasEnabled = config.gasEnabled !== false;
478
+
479
+ if (discovered.hasElectricity && electricityEnabled) {
480
+ const ratesMs = (config.electricityRatesInterval || 60) * 60 * 1000;
481
+ const consumptionMs = (config.electricityConsumptionInterval || 60) * 60 * 1000;
482
+ categories.push({
483
+ id: 'electricity_rates',
484
+ enabled: true,
485
+ intervalMs: ratesMs,
486
+ lastPolled: 0,
487
+ queryFn: () => electricityCategory.buildRatesQuery(account),
488
+ parseFn: d => electricityCategory.parseRatesResponse(d),
489
+ poll: simplePoll(
490
+ () => electricityCategory.buildRatesQuery(account),
491
+ d => electricityCategory.parseRatesResponse(d),
492
+ graphqlPost
493
+ ),
494
+ });
495
+ categories.push({
496
+ id: 'electricity_consumption',
497
+ enabled: true,
498
+ intervalMs: consumptionMs,
499
+ lastPolled: 0,
500
+ queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
501
+ parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
502
+ poll: simplePoll(
503
+ () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
504
+ d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
505
+ graphqlPost
506
+ ),
507
+ });
508
+ }
509
+
510
+ if (discovered.hasGas && gasEnabled) {
511
+ const ratesMs = (config.gasRatesInterval || 60) * 60 * 1000;
512
+ const consumptionMs = (config.gasConsumptionInterval || 60) * 60 * 1000;
513
+ categories.push({
514
+ id: 'gas_rates',
515
+ enabled: true,
516
+ intervalMs: ratesMs,
517
+ lastPolled: 0,
518
+ queryFn: () => gasCategory.buildRatesQuery(account),
519
+ parseFn: d => gasCategory.parseRatesResponse(d),
520
+ poll: simplePoll(
521
+ () => gasCategory.buildRatesQuery(account),
522
+ d => gasCategory.parseRatesResponse(d),
523
+ graphqlPost
524
+ ),
525
+ });
526
+ categories.push({
527
+ id: 'gas_consumption',
528
+ enabled: true,
529
+ intervalMs: consumptionMs,
530
+ lastPolled: 0,
531
+ queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
532
+ parseFn: d => gasCategory.parseConsumptionResponse(d),
533
+ poll: simplePoll(
534
+ () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
535
+ d => gasCategory.parseConsumptionResponse(d),
536
+ graphqlPost
537
+ ),
538
+ });
539
+ }
540
+
541
+ categories.push({
542
+ id: 'wheel_of_fortune',
543
+ enabled: config.enableWheelOfFortune || false,
544
+ intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
545
+ lastPolled: 0,
546
+ queryFn: () => wheelOfFortuneCategory.buildQuery(account),
547
+ parseFn: d => wheelOfFortuneCategory.parseResponse(d),
548
+ poll: simplePoll(
549
+ () => wheelOfFortuneCategory.buildQuery(account),
550
+ d => wheelOfFortuneCategory.parseResponse(d),
551
+ graphqlPost
552
+ ),
553
+ });
554
+ if (discovered.smartMeterDeviceId) {
555
+ categories.push({
556
+ id: 'home_mini',
557
+ enabled: config.enableHomeMini || false,
558
+ intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
559
+ lastPolled: 0,
560
+ queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
561
+ parseFn: d => homeMiniCategory.parseResponse(d),
562
+ poll: simplePoll(
563
+ () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
564
+ d => homeMiniCategory.parseResponse(d),
565
+ graphqlPost
566
+ ),
567
+ });
568
+ }
569
+ categories.push({
570
+ id: 'saving_sessions',
571
+ enabled: true,
572
+ intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
573
+ lastPolled: 0,
574
+ queryFn: () => savingSessionsCategory.buildQuery(account),
575
+ parseFn: d => savingSessionsCategory.parseResponse(d),
576
+ poll: simplePoll(
577
+ () => savingSessionsCategory.buildQuery(account),
578
+ d => savingSessionsCategory.parseResponse(d),
579
+ graphqlPost
580
+ ),
581
+ });
582
+
583
+ if (discovered.hasIntelligent) {
584
+ categories.push({
585
+ id: 'completed_dispatches',
586
+ enabled: true,
587
+ intervalMs: 60 * 60 * 1000,
588
+ lastPolled: 0,
589
+ queryFn: () => completedDispatchesCategory.buildQuery(account),
590
+ parseFn: d => completedDispatchesCategory.parseResponse(d),
591
+ poll: simplePoll(
592
+ () => completedDispatchesCategory.buildQuery(account),
593
+ d => completedDispatchesCategory.parseResponse(d),
594
+ graphqlPost
595
+ ),
596
+ });
597
+ }
598
+
599
+ if (discovered.hasElectricity && discovered.electricityMpan) {
600
+ categories.push({
601
+ id: 'applicable_rates',
602
+ enabled: true,
603
+ intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
604
+ lastPolled: 0,
605
+ queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
606
+ parseFn: d => applicableRatesCategory.parseResponse(d),
607
+ poll: simplePoll(
608
+ () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
609
+ d => applicableRatesCategory.parseResponse(d),
610
+ graphqlPost
611
+ ),
612
+ });
613
+ }
614
+
615
+ // Export applicable rates — second query with the export MPAN. Same parser,
616
+ // different field prefix so the output keys don't collide with import.
617
+ if (discovered.hasElectricity && discovered.electricityExportMpan) {
618
+ categories.push({
619
+ id: 'applicable_rates_export',
620
+ enabled: true,
621
+ intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
622
+ lastPolled: 0,
623
+ queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
624
+ parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
625
+ poll: simplePoll(
626
+ () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
627
+ d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
628
+ graphqlPost
629
+ ),
630
+ });
631
+ }
632
+
633
+ if (discovered.hasElectricity && discovered.electricityMpan) {
634
+ categories.push({
635
+ id: 'free_electricity',
636
+ enabled: true,
637
+ intervalMs: 30 * 60 * 1000, // 30 minutes
638
+ lastPolled: 0,
639
+ queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
640
+ parseFn: d => freeElectricityCategory.parseResponse(d),
641
+ poll: simplePoll(
642
+ () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
643
+ d => freeElectricityCategory.parseResponse(d),
644
+ graphqlPost
645
+ ),
646
+ });
647
+ }
648
+
649
+ categories.push({
650
+ id: 'account',
651
+ enabled: true,
652
+ intervalMs: 60 * 60 * 1000,
653
+ lastPolled: 0,
654
+ queryFn: () => accountCategory.buildQuery(account),
655
+ parseFn: d => accountCategory.parseResponse(d),
656
+ poll: simplePoll(
657
+ () => accountCategory.buildQuery(account),
658
+ d => accountCategory.parseResponse(d),
659
+ graphqlPost
660
+ ),
661
+ });
662
+
663
+ categories.push({
664
+ id: 'octoplus',
665
+ enabled: true,
666
+ intervalMs: 60 * 60 * 1000,
667
+ lastPolled: 0,
668
+ queryFn: () => octoplusCategory.buildQuery(account),
669
+ parseFn: d => octoplusCategory.parseResponse(d),
670
+ poll: simplePoll(
671
+ () => octoplusCategory.buildQuery(account),
672
+ d => octoplusCategory.parseResponse(d),
673
+ graphqlPost
674
+ ),
675
+ });
676
+
677
+ categories.push({
678
+ id: 'update_check',
679
+ enabled: true,
680
+ intervalMs: 24 * 60 * 60 * 1000, // 24h — once daily npm registry check
681
+ lastPolled: 0, // fires on first scheduler tick
682
+ poll: intelligentUpdateCheck, // token ignored
683
+ });
684
+ }
685
+
686
+ async function pollDueCategories() {
687
+ const result = await runTick({
688
+ categories,
689
+ state: lastKnownState,
690
+ getToken: obtainTickToken,
691
+ });
692
+ if (!result.emitted) return;
693
+ lastKnownState = result.state;
694
+ if (enableMqtt && node.broker && node.broker.client) {
695
+ node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
696
+ // v1.5 — publish update entity state only when version values change
697
+ if (prevPublishedInstalled !== lastKnownState.installed_version
698
+ || prevPublishedLatest !== lastKnownState.latest_version) {
699
+ const updateState = {
700
+ installed_version: lastKnownState.installed_version,
701
+ latest_version: lastKnownState.latest_version || lastKnownState.installed_version,
702
+ };
703
+ node.broker.client.publish(`${stateTopic}/node_update`, JSON.stringify(updateState), { retain: true });
704
+ prevPublishedInstalled = lastKnownState.installed_version;
705
+ prevPublishedLatest = lastKnownState.latest_version;
706
+ }
707
+ }
708
+ node.send({ payload: lastKnownState });
709
+ if (lastKnownState.update_available === true
710
+ && lastKnownState.latest_version
711
+ && lastKnownState.latest_version !== lastWarnedVersion) {
712
+ node.warn(`Update available: v${lastKnownState.latest_version} (running v${lastKnownState.installed_version}). Install via Node-RED → Manage Palette → Upgrade.`);
713
+ lastWarnedVersion = lastKnownState.latest_version;
714
+ }
715
+ if (!validationMode) {
716
+ if (lastKnownState.intelligent_error) {
717
+ node.status({ fill: "red", shape: "ring", text: `Error: ${String(lastKnownState.intelligent_error).slice(0, 40)}` });
718
+ } else {
719
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
720
+ }
721
+ }
722
+ }
723
+
724
+ async function obtainTickToken() {
725
+ const response = await graphqlPost({
726
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
727
+ variables: { input: { APIKey: apiKey } },
728
+ });
729
+ if (!response.data.data || !response.data.data.obtainKrakenToken) {
730
+ throw new Error('Auth response missing token: ' + JSON.stringify(response.data.errors || response.data));
731
+ }
732
+ return response.data.data.obtainKrakenToken.token;
733
+ }
734
+
735
+ function forceCategoryDue(id) {
736
+ const cat = categories.find((c) => c.id === id);
737
+ if (cat) cat.lastPolled = 0;
738
+ }
739
+
740
+ // limit/time are validated by the caller (or come from the API as confirmed values).
741
+ async function setPreferences(limit, time) {
742
+
743
+ // Cancel any pending retry attempts from previous changes
744
+ retryTimeouts.forEach(timeout => clearTimeout(timeout));
745
+ retryTimeouts = [];
746
+
747
+ try {
748
+ node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
749
+
750
+ // A. Get Token
751
+ const authResponse = await graphqlPost({
752
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
753
+ variables: { input: { APIKey: apiKey } }
754
+ });
755
+
756
+ if (authResponse.data.errors) {
757
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
758
+ }
759
+ if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
760
+ throw new Error(`Auth response missing token data`);
761
+ }
762
+
763
+ const token = authResponse.data.data.obtainKrakenToken.token;
764
+
765
+ // B. Send Mutation
766
+ if (!krakenflexDeviceId) {
767
+ throw new Error('Device ID not available — cannot set preferences');
768
+ }
769
+
770
+ const mutation = `
771
+ mutation setPreferences($input: SmartFlexDevicePreferencesInput!) {
772
+ setDevicePreferences(input: $input) { __typename }
773
+ }`;
774
+
775
+ const DAYS = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'];
776
+ function buildDevicePreferencesInput(deviceId, socLimit, readyTime) {
777
+ return {
778
+ deviceId,
779
+ mode: 'CHARGE',
780
+ unit: 'PERCENTAGE',
781
+ schedules: DAYS.map(dayOfWeek => ({
782
+ dayOfWeek,
783
+ time: readyTime + ':00',
784
+ min: 0,
785
+ max: socLimit
786
+ }))
787
+ };
788
+ }
789
+
790
+ const variables = {
791
+ input: buildDevicePreferencesInput(krakenflexDeviceId, limit, time)
792
+ };
793
+
794
+ const mutationResponse = await graphqlPost({
795
+ query: mutation,
796
+ variables: variables
797
+ }, token);
798
+
799
+ if (mutationResponse.data.errors) {
800
+ throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
801
+ }
802
+
803
+ // Record mutation API usage (auth + mutation = ~250 complexity)
804
+ const ESTIMATED_MUTATION_COMPLEXITY = 250;
805
+ metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
806
+
807
+ // C. Start exponential backoff validation
808
+ expectedLimit = limit;
809
+ expectedTime = time;
810
+ validationMode = true;
811
+ node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
812
+
813
+ // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
814
+ const retryIntervals = [15000, 30000, 60000, 120000];
815
+ scheduleRetries(retryIntervals, 0);
816
+
817
+ } catch (err) {
818
+ node.error("Failed to set preferences: " + err.message);
819
+ if (err.response) {
820
+ node.error(`Response: ${JSON.stringify(err.response.data)}`);
821
+ }
822
+ node.status({ fill: "red", shape: "ring", text: "Update Failed" });
823
+ expectedLimit = null;
824
+ expectedTime = null;
825
+ validationMode = false;
826
+ }
827
+ }
828
+
829
+ function scheduleRetries(intervals, index) {
830
+ if (index >= intervals.length) {
831
+ // All retries exhausted, let normal interval take over
832
+ node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
833
+ expectedLimit = null;
834
+ expectedTime = null;
835
+ validationMode = false;
836
+ return;
837
+ }
838
+
839
+ const timeout = setTimeout(async () => {
840
+ await fetchDataWithValidation(intervals, index);
841
+ }, intervals[index]);
842
+
843
+ retryTimeouts.push(timeout);
844
+ }
845
+
846
+ async function fetchDataWithValidation(intervals, currentIndex) {
847
+ try {
848
+ const token = await obtainTickToken();
849
+ const partial = await intelligentPoll(token);
850
+ lastKnownState = Object.assign({}, lastKnownState, partial, { intelligent_error: null });
851
+ if (enableMqtt && node.broker && node.broker.client) {
852
+ node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
853
+ }
854
+ node.send({ payload: lastKnownState });
855
+
856
+ const validated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
857
+ if (validated) {
858
+ validationMode = false;
859
+ retryTimeouts.forEach((t) => clearTimeout(t));
860
+ retryTimeouts = [];
861
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
862
+ return;
863
+ }
864
+ const totalAttempts = intervals.length;
865
+ const attempt = currentIndex + 1;
866
+ if (currentIndex < intervals.length - 1) {
867
+ node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
868
+ scheduleRetries(intervals, currentIndex + 1);
869
+ } else {
870
+ validationMode = false;
871
+ node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
872
+ }
873
+ } catch (error) {
874
+ node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
875
+ if (currentIndex < intervals.length - 1) {
876
+ scheduleRetries(intervals, currentIndex + 1);
877
+ } else {
878
+ validationMode = false;
879
+ node.status({ fill: "red", shape: "ring", text: "Validation failed" });
880
+ }
881
+ }
882
+ }
883
+
884
+ // Helper: Toggle smart charging on/off
885
+ async function setSmartCharging(enable) {
886
+ if (!krakenflexDeviceId) {
887
+ node.warn("Device ID not available — cannot toggle smart charging");
888
+ return;
889
+ }
890
+
891
+ // Cancel any pending verification retries
892
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
893
+ smartChargingRetryTimeouts = [];
894
+
895
+ const previousSuspended = smartChargingSuspended;
896
+
897
+ try {
898
+ node.status({ fill: "blue", shape: "dot", text: enable ? "Enabling smart charging..." : "Suspending smart charging..." });
899
+
900
+ const authResponse = await graphqlPost({
901
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
902
+ variables: { input: { APIKey: apiKey } }
903
+ });
904
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
905
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
906
+ }
907
+ const token = authResponse.data.data.obtainKrakenToken.token;
908
+
909
+ const action = enable ? "UNSUSPEND" : "SUSPEND";
910
+ const mutationResponse = await graphqlPost({
911
+ query: `mutation UpdateSmartControl($deviceId: ID!, $action: SmartControlAction!) { updateDeviceSmartControl(input: { deviceId: $deviceId, action: $action }) { id } }`,
912
+ variables: { deviceId: krakenflexDeviceId, action: action }
913
+ }, token);
914
+
915
+ if (mutationResponse.data.errors) {
916
+ throw new Error(`Smart charging mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
917
+ }
918
+
919
+ // Record mutation API usage (auth + mutation = ~250 complexity)
920
+ const ESTIMATED_MUTATION_COMPLEXITY = 250;
921
+ metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
922
+
923
+ // Optimistically update cached state
924
+ const expectedSuspended = !enable;
925
+ smartChargingSuspended = expectedSuspended;
926
+
927
+ // Publish new state to HA switch topic immediately
928
+ if (enableMqtt && node.broker && node.broker.client) {
929
+ node.broker.client.publish(`${stateTopic}/smart_charging`, enable ? "ON" : "OFF", { retain: true });
930
+ }
931
+
932
+ // Schedule verification: 15s / 30s / 60s / 120s
933
+ scheduleSmartChargingVerification(expectedSuspended, [15000, 30000, 60000, 120000], 0);
934
+
935
+ } catch (e) {
936
+ node.error(`Failed to toggle smart charging: ${e.message}`);
937
+ // Revert optimistic update to pre-mutation state
938
+ smartChargingSuspended = previousSuspended;
939
+ node.status({ fill: "red", shape: "ring", text: "Smart charging update failed" });
940
+ // Republish previous state so HA switch UI re-syncs
941
+ if (enableMqtt && node.broker && node.broker.client && previousSuspended !== null) {
942
+ node.broker.client.publish(
943
+ `${stateTopic}/smart_charging`,
944
+ previousSuspended ? "OFF" : "ON",
945
+ { retain: true }
946
+ );
947
+ }
948
+ }
949
+ }
950
+
951
+ // Helper: Toggle Charge Cap (off-peak-only smart charging). State is confirmed by the
952
+ // next intelligent poll, so no bespoke verification loop.
953
+ async function setChargeCap(enabled) {
954
+ if (!krakenflexDeviceId) {
955
+ node.warn("Device ID not available — cannot change Charge Cap");
956
+ return;
957
+ }
958
+ const previous = lastKnownState ? lastKnownState.charge_cap : null;
959
+ try {
960
+ node.status({ fill: "blue", shape: "dot", text: enabled ? "Enabling Charge Cap..." : "Disabling Charge Cap..." });
961
+ const token = await obtainTickToken();
962
+ const res = await graphqlPost({
963
+ query: `mutation SetChargeCap($input: UpdateIsChargingDurationCappedInput!) { updateIsChargingDurationCapped(input: $input) { __typename } }`,
964
+ variables: { input: { deviceId: krakenflexDeviceId, enabled } }
965
+ }, token);
966
+ if (res.data.errors) {
967
+ throw new Error(`Charge Cap mutation failed: ${JSON.stringify(res.data.errors)}`);
968
+ }
969
+ metrics.recordPoll(250); // auth + mutation, same estimate as other mutations
970
+ lastKnownState = mergePayload(lastKnownState, { charge_cap: enabled });
971
+ if (enableMqtt && node.broker && node.broker.client) {
972
+ node.broker.client.publish(`${stateTopic}/charge_cap`, enabled ? "ON" : "OFF", { retain: true });
973
+ }
974
+ node.status({ fill: "green", shape: "dot", text: `Charge Cap ${enabled ? "on" : "off"}` });
975
+ forceCategoryDue('intelligent'); // next tick confirms from the API
976
+ } catch (e) {
977
+ node.error(`Failed to change Charge Cap: ${e.message}`);
978
+ node.status({ fill: "red", shape: "ring", text: "Charge Cap update failed" });
979
+ // Republish previous state so the HA switch re-syncs
980
+ if (enableMqtt && node.broker && node.broker.client && typeof previous === 'boolean') {
981
+ node.broker.client.publish(`${stateTopic}/charge_cap`, previous ? "ON" : "OFF", { retain: true });
982
+ }
983
+ }
984
+ }
985
+
986
+ function scheduleSmartChargingVerification(expectedSuspended, intervals, index) {
987
+ if (index >= intervals.length) {
988
+ node.warn("Smart charging state could not be confirmed after all retries");
989
+ node.status({ fill: "red", shape: "ring", text: "Smart charging: update unconfirmed" });
990
+ return;
991
+ }
992
+ const timeout = setTimeout(async () => {
993
+ try {
994
+ const authResponse = await graphqlPost({
995
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
996
+ variables: { input: { APIKey: apiKey } }
997
+ });
998
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
999
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1000
+ return;
1001
+ }
1002
+ const token = authResponse.data.data.obtainKrakenToken.token;
1003
+
1004
+ const deviceResponse = await graphqlPost({
1005
+ query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1006
+ variables: { accountNumber: account }
1007
+ }, token);
1008
+
1009
+ if (deviceResponse.data.errors || !deviceResponse.data.data) {
1010
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1011
+ return;
1012
+ }
1013
+
1014
+ const evDevice = (deviceResponse.data.data.devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES');
1015
+ if (!evDevice) {
1016
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1017
+ return;
1018
+ }
1019
+
1020
+ // Record verification API usage (auth + device query = ~200 complexity)
1021
+ const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
1022
+ metrics.recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
1023
+
1024
+ const actualSuspended = evDevice.status.isSuspended;
1025
+ if (actualSuspended === expectedSuspended) {
1026
+ // Confirmed — clear remaining retries
1027
+ smartChargingSuspended = actualSuspended;
1028
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1029
+ smartChargingRetryTimeouts = [];
1030
+ node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
1031
+ node.status({ fill: "green", shape: "dot", text: actualSuspended ? "Smart charging suspended" : "Smart charging enabled" });
1032
+ } else {
1033
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1034
+ }
1035
+ } catch (e) {
1036
+ node.warn(`Smart charging verification attempt ${index + 1} failed: ${e.message}`);
1037
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1038
+ }
1039
+ }, intervals[index]);
1040
+ smartChargingRetryTimeouts.push(timeout);
1041
+ }
1042
+
1043
+ // 6. Logic: Update Check (bespoke poll that ignores token)
1044
+ async function intelligentUpdateCheck(/* token ignored */) {
1045
+ return checkUpdate(httpGetJson, require('./package.json').version);
1046
+ }
1047
+
1048
+ // 6. Logic: Intelligent Poll (single-scheduler bespoke poll)
1049
+ async function intelligentPoll(token) {
1050
+ // 1. devices query
1051
+ const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
1052
+ const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
1053
+ // An error on the Charge Cap field alone must not stop slot/settings updates (KT-CT-4360 pattern).
1054
+ const devicesErrors = devicesResponse.data.errors;
1055
+ const chargeCapFailed = onlyDeviceFieldErrors(devicesErrors, devicesResponse.data.data, 'chargeCap');
1056
+ if (devicesErrors && !chargeCapFailed) throw new Error(`Devices query failed: ${JSON.stringify(devicesErrors)}`);
1057
+ if (!devicesResponse.data.data) throw new Error('Devices response missing data');
1058
+ const devicesData = devicesResponse.data.data;
1059
+ const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
1060
+ if (!evDevice) throw new Error('No ELECTRIC_VEHICLES device found on account');
1061
+ krakenflexDeviceId = evDevice.id;
1062
+
1063
+ // 2. dispatches query (the single one that used to be duplicated by V1 + V2)
1064
+ const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
1065
+ const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
1066
+ if (dispatchResponse.data.errors) throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
1067
+ if (!dispatchResponse.data.data) throw new Error('Dispatches response missing data');
1068
+
1069
+ // 3. parse twice — intelligent (slots/window) + flex-planned-dispatches (array/count)
1070
+ const data = { devices: devicesData.devices, flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
1071
+ const appliedTz = resolveTimezone(node);
1072
+ const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (e) { return 'UTC'; } })();
1073
+ const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
1074
+ const { _activeSlots, ...catPublic } = catResult;
1075
+ if (chargeCapFailed) delete catPublic.charge_cap; // unknown this poll: keep the last value
1076
+ const flexResult = flexPlannedDispatchesCategory.parseResponse(dispatchResponse.data.data);
1077
+
1078
+ // 4. metrics + side effects
1079
+ metrics.recordPoll(300);
1080
+ confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
1081
+ confirmedTime = catResult.confirmed_time || confirmedTime;
1082
+ if (!validationMode) {
1083
+ pendingLimit = confirmedLimit;
1084
+ pendingTime = confirmedTime;
1085
+ }
1086
+ if (chargeCapFailed) {
1087
+ node.warn("Charge Cap state unavailable this poll — keeping the last known value");
1088
+ } else if (typeof catResult.charge_cap === 'boolean') {
1089
+ if (enableMqtt && node.broker && node.broker.client) {
1090
+ node.broker.client.publish(`${stateTopic}/charge_cap`, catResult.charge_cap ? "ON" : "OFF", { retain: true });
1091
+ }
1092
+ } else if (!chargeCapNaWarned) {
1093
+ chargeCapNaWarned = true;
1094
+ node.warn("Charge Cap not applicable for this device — switch will show unknown");
1095
+ }
1096
+ setupChargingTimers(_activeSlots);
1097
+ if (!stateCheckInterval) startStateReconciliation();
1098
+ updateNextPollTime();
1099
+
1100
+ const apiMetrics = metrics.getMetrics();
1101
+
1102
+ // 5. merged partial payload
1103
+ return Object.assign({}, catPublic, flexResult, {
1104
+ pending_limit: pendingLimit,
1105
+ pending_time: pendingTime,
1106
+ charging_now: chargingNow,
1107
+ next_poll: nextPollTime,
1108
+ next_poll_raw: nextPollTime,
1109
+ refresh_available_at: getRefreshAvailableAt(),
1110
+ api_requests_hour: apiMetrics.requests_last_hour,
1111
+ api_complexity_hour: apiMetrics.complexity_last_hour,
1112
+ api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
1113
+ timezone_detected: serverTz,
1114
+ timezone_applied: appliedTz,
1115
+ smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
1116
+ });
1117
+ }
1118
+
1119
+
1120
+ // Helper: Fetch device ID and initial smart charging state (called once at startup)
1121
+ async function fetchDeviceId() {
1122
+ try {
1123
+ const authResponse = await graphqlPost({
1124
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1125
+ variables: { input: { APIKey: apiKey } }
1126
+ });
1127
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1128
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1129
+ }
1130
+ const token = authResponse.data.data.obtainKrakenToken.token;
1131
+
1132
+ const deviceResponse = await graphqlPost({
1133
+ query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1134
+ variables: { accountNumber: account }
1135
+ }, token);
1136
+
1137
+ if (deviceResponse.data.errors || !deviceResponse.data.data) {
1138
+ throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
1139
+ }
1140
+
1141
+ function extractEvDevice(devices) {
1142
+ return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
1143
+ }
1144
+
1145
+ const evDevice = extractEvDevice(deviceResponse.data.data.devices);
1146
+ if (!evDevice) {
1147
+ throw new Error('No ELECTRIC_VEHICLES device found on account');
1148
+ }
1149
+
1150
+ krakenflexDeviceId = evDevice.id;
1151
+ smartChargingSuspended = evDevice.status.isSuspended;
1152
+ node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
1153
+ } catch (e) {
1154
+ node.warn(`Failed to fetch device ID at startup: ${e.message}. Smart charging toggle unavailable.`);
1155
+ krakenflexDeviceId = null;
1156
+ smartChargingSuspended = null;
1157
+ }
1158
+ }
1159
+
1160
+ // 6a. Charging Now - Timer Management Functions
1161
+
1162
+ // State reconciliation - checks every 10s if charging state matches reality
1163
+ function reconcileChargingState() {
1164
+ if (!cachedSlots || cachedSlots.length === 0) return;
1165
+
1166
+ const now = new Date();
1167
+
1168
+ // Check if we should be charging RIGHT NOW based on cached slots
1169
+ const shouldBeCharging = cachedSlots.some(slot => {
1170
+ const start = new Date(slot.start);
1171
+ const end = new Date(slot.end);
1172
+ return start <= now && end > now;
1173
+ });
1174
+
1175
+ // Update state if it doesn't match reality
1176
+ if (shouldBeCharging !== chargingNow) {
1177
+ node.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
1178
+ publishChargingState(shouldBeCharging);
1179
+ }
1180
+ }
1181
+
1182
+ // Start state reconciliation loop (every 10 seconds)
1183
+ function startStateReconciliation() {
1184
+ // Clear existing interval
1185
+ if (stateCheckInterval) {
1186
+ clearInterval(stateCheckInterval);
1187
+ }
1188
+
1189
+ // Check state every 10 seconds
1190
+ stateCheckInterval = setInterval(() => {
1191
+ reconcileChargingState();
1192
+ }, 10000);
1193
+
1194
+ node.log("State reconciliation loop started (every 10s)");
1195
+ }
1196
+
1197
+ // Clear all charging timers
1198
+ function clearChargingTimers() {
1199
+ if (preValidationTimer) {
1200
+ clearTimeout(preValidationTimer);
1201
+ preValidationTimer = null;
1202
+ }
1203
+ if (slotStartTimer) {
1204
+ clearTimeout(slotStartTimer);
1205
+ slotStartTimer = null;
1206
+ }
1207
+ if (slotEndTimer) {
1208
+ clearTimeout(slotEndTimer);
1209
+ slotEndTimer = null;
1210
+ }
1211
+ if (stateCheckInterval) {
1212
+ clearInterval(stateCheckInterval);
1213
+ stateCheckInterval = null;
1214
+ }
1215
+ }
1216
+
1217
+ // Manual refresh rate limiting helpers
1218
+ function canManualRefresh() {
1219
+ const now = Date.now();
1220
+ const timeSinceLastRefresh = now - lastManualRefresh;
1221
+ return lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN;
1222
+ }
1223
+
1224
+ function getSecondsUntilNextRefresh() {
1225
+ const now = Date.now();
1226
+ const timeSinceLastRefresh = now - lastManualRefresh;
1227
+ const timeRemaining = MANUAL_REFRESH_COOLDOWN - timeSinceLastRefresh;
1228
+ return Math.max(0, Math.ceil(timeRemaining / 1000));
1229
+ }
1230
+
1231
+ function getRefreshAvailableAt() {
1232
+ const now = Date.now();
1233
+ const timeSinceLastRefresh = now - lastManualRefresh;
1234
+
1235
+ // If never refreshed OR cooldown expired, ready now
1236
+ if (lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN) {
1237
+ return null; // Ready - no cooldown
1238
+ }
1239
+
1240
+ // Cooldown active - return timestamp when it expires
1241
+ return new Date(lastManualRefresh + MANUAL_REFRESH_COOLDOWN).toISOString();
1242
+ }
1243
+
1244
+ function publishRefreshCooldownState() {
1245
+ if (enableMqtt && node.broker) {
1246
+ const fullState = {
1247
+ ...lastKnownState,
1248
+ refresh_available_at: getRefreshAvailableAt()
1249
+ };
1250
+ node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: true });
1251
+ }
1252
+ }
1253
+
1254
+ // Polling metrics helpers
1255
+ function updateNextPollTime() {
1256
+ nextPollTime = new Date(Date.now() + refreshRate).toISOString();
1257
+ }
1258
+
1259
+ // Publish charging state to MQTT and Node-RED
1260
+ function publishChargingState(state) {
1261
+ chargingNow = state;
1262
+
1263
+ // Update MQTT
1264
+ if (enableMqtt && node.broker) {
1265
+ const payload = state ? "ON" : "OFF";
1266
+ node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
1267
+ }
1268
+
1269
+ // Output message to Node-RED flow if state actually changed
1270
+ if (lastSentChargingState !== state) {
1271
+ lastSentChargingState = state;
1272
+
1273
+ // Merge updated charging_now into last known full state
1274
+ const outputPayload = {
1275
+ ...lastKnownState,
1276
+ charging_now: state
1277
+ };
1278
+
1279
+ node.send({
1280
+ payload: outputPayload,
1281
+ debug: {
1282
+ timestamp: new Date().toISOString(),
1283
+ trigger: 'charging_state_change',
1284
+ success: true,
1285
+ previous_state: !state,
1286
+ new_state: state
1287
+ }
1288
+ });
1289
+
1290
+ node.log(`Charging state changed: ${!state} → ${state}, message sent`);
1291
+ }
1292
+ }
1293
+
1294
+ // Setup pre-validation timer (30s before slot starts)
1295
+ function setupPreValidationTimer(nextSlot) {
1296
+ const now = new Date();
1297
+ const slotStart = new Date(nextSlot.start);
1298
+ const preValidationTime = slotStart.getTime() - 30000; // 30s before
1299
+ const msUntilPreValidation = preValidationTime - now.getTime();
1300
+
1301
+ if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
1302
+ preValidationTimer = setTimeout(async () => {
1303
+ node.warn("Pre-validating slot data (30s before start)");
1304
+ try {
1305
+ if (!krakenflexDeviceId) {
1306
+ throw new Error("Device ID not available for pre-validation");
1307
+ }
1308
+
1309
+ const authResponse = await graphqlPost({
1310
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1311
+ variables: { input: { APIKey: apiKey } }
1312
+ });
1313
+
1314
+ if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1315
+ throw new Error("Pre-validation auth failed");
1316
+ }
1317
+
1318
+ const token = authResponse.data.data.obtainKrakenToken.token;
1319
+
1320
+ const { query: dq, variables: dv } = intelligentCategory.buildDispatchQuery(krakenflexDeviceId);
1321
+ const dataResponse = await graphqlPost({ query: dq, variables: dv }, token);
1322
+
1323
+ if (dataResponse.data.data && dataResponse.data.data.flexPlannedDispatches) {
1324
+ const freshSlots = dataResponse.data.data.flexPlannedDispatches;
1325
+ // Octopus re-planned since the last poll: poll now so the slot/window
1326
+ // sensors match what charging_now is about to do.
1327
+ if (intelligentCategory.slotsChanged(cachedSlots, freshSlots)) {
1328
+ node.warn("Charging plan changed since last poll - refreshing");
1329
+ forceCategoryDue('intelligent');
1330
+ }
1331
+ cachedSlots = freshSlots;
1332
+
1333
+ // Record pre-validation API usage (auth + simple query = ~200 complexity)
1334
+ const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
1335
+ metrics.recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
1336
+
1337
+ // Check if slot still exists (within 1 minute tolerance)
1338
+ const stillExists = cachedSlots.find(s =>
1339
+ Math.abs(new Date(s.start).getTime() - slotStart.getTime()) < 60000
1340
+ );
1341
+
1342
+ if (stillExists) {
1343
+ node.warn(`Slot confirmed at ${stillExists.start}`);
1344
+ setupSlotStartTimer(stillExists);
1345
+ } else {
1346
+ node.warn("Slot was cancelled or modified - not setting start timer");
1347
+ }
1348
+ }
1349
+ } catch (error) {
1350
+ node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
1351
+ // Fallback: use original slot data
1352
+ setupSlotStartTimer(nextSlot);
1353
+ }
1354
+ }, msUntilPreValidation);
1355
+
1356
+ const minutesUntil = Math.round(msUntilPreValidation / 60000);
1357
+ node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
1358
+ } else if (msUntilPreValidation <= 0 && slotStart.getTime() > now.getTime()) {
1359
+ // Polled inside the last 30s (e.g. the refresh after a re-plan): the data is
1360
+ // already fresh, so set the start timer directly instead of losing it.
1361
+ setupSlotStartTimer(nextSlot);
1362
+ }
1363
+ }
1364
+
1365
+ // Setup slot start timer (exact start time)
1366
+ function setupSlotStartTimer(slot) {
1367
+ // A poll and an in-flight pre-validation can both set this; never leave an orphan.
1368
+ if (slotStartTimer) { clearTimeout(slotStartTimer); slotStartTimer = null; }
1369
+ const now = new Date();
1370
+ const slotStart = new Date(slot.start);
1371
+ const msUntilStart = slotStart.getTime() - now.getTime();
1372
+
1373
+ if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
1374
+ slotStartTimer = setTimeout(() => {
1375
+ publishChargingState(true);
1376
+ node.warn(`Charging slot started at ${slot.start}`);
1377
+ setupSlotEndTimer(slot);
1378
+ }, msUntilStart);
1379
+
1380
+ const secondsUntil = Math.round(msUntilStart / 1000);
1381
+ node.log(`Slot start timer set for ${secondsUntil}s (${slot.start})`);
1382
+ } else if (msUntilStart <= 0) {
1383
+ // Slot already started, check if it's still active
1384
+ const slotEnd = new Date(slot.end);
1385
+ if (slotEnd > now) {
1386
+ publishChargingState(true);
1387
+ setupSlotEndTimer(slot);
1388
+ }
1389
+ }
1390
+ }
1391
+
1392
+ // Setup slot end timer (exact end time)
1393
+ function setupSlotEndTimer(slot) {
1394
+ if (slotEndTimer) { clearTimeout(slotEndTimer); slotEndTimer = null; }
1395
+ const now = new Date();
1396
+ const slotEnd = new Date(slot.end);
1397
+ const msUntilEnd = slotEnd.getTime() - now.getTime();
1398
+
1399
+ if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
1400
+ slotEndTimer = setTimeout(() => {
1401
+ node.warn(`Charging slot ended at ${slot.end}`);
1402
+
1403
+ // Check if another slot starts immediately (within cached data)
1404
+ const now = new Date();
1405
+ const immediateNextSlot = cachedSlots.find(s => {
1406
+ const start = new Date(s.start);
1407
+ const end = new Date(s.end);
1408
+ return start <= now && end > now;
1409
+ });
1410
+
1411
+ if (immediateNextSlot) {
1412
+ node.warn("Next slot starting immediately");
1413
+ publishChargingState(true);
1414
+ setupSlotEndTimer(immediateNextSlot);
1415
+ } else {
1416
+ publishChargingState(false);
1417
+ }
1418
+ }, msUntilEnd);
1419
+
1420
+ const minutesUntil = Math.round(msUntilEnd / 60000);
1421
+ node.log(`Slot end timer set for ${minutesUntil} min (${slot.end})`);
1422
+ }
1423
+ }
1424
+
1425
+ // Main timer setup - called on each poll
1426
+ function setupChargingTimers(slots) {
1427
+ // Clear existing timers
1428
+ clearChargingTimers();
1429
+
1430
+ // Cache slots for later use
1431
+ cachedSlots = slots;
1432
+
1433
+ const now = new Date();
1434
+
1435
+ // Check if currently in a charging slot
1436
+ const activeSlot = slots.find(s => {
1437
+ const start = new Date(s.start);
1438
+ const end = new Date(s.end);
1439
+ return start <= now && end > now;
1440
+ });
1441
+
1442
+ if (activeSlot) {
1443
+ // Currently charging
1444
+ const newState = true;
1445
+ if (chargingNow !== newState) {
1446
+ publishChargingState(newState);
1447
+ }
1448
+ setupSlotEndTimer(activeSlot);
1449
+ node.log("Currently charging - end timer set");
1450
+ } else {
1451
+ // Not currently charging
1452
+ const newState = false;
1453
+ if (chargingNow !== newState) {
1454
+ publishChargingState(newState);
1455
+ }
1456
+
1457
+ // Find next future slot
1458
+ const nextSlot = slots.find(s => new Date(s.start) > now);
1459
+
1460
+ if (nextSlot) {
1461
+ setupPreValidationTimer(nextSlot);
1462
+ node.log(`Next slot at ${nextSlot.start}`);
1463
+ }
1464
+ }
1465
+ }
1466
+
1467
+ // 7. Event Listeners
1468
+
1469
+ // Helper: Publish current state (both pending and confirmed)
1470
+ // This merges pending values into last known full state to prevent sensors going unknown
1471
+ function publishCurrentState() {
1472
+ if (enableMqtt && node.broker) {
1473
+ // Merge pending values into last known state
1474
+ const fullState = {
1475
+ ...lastKnownState,
1476
+ pending_limit: pendingLimit,
1477
+ pending_time: pendingTime,
1478
+ confirmed_limit: confirmedLimit,
1479
+ confirmed_time: confirmedTime
1480
+ };
1481
+ node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: false });
1482
+ }
1483
+ }
1484
+
1485
+ // A. Handle Node-RED Input Messages (NO rate limiting - programmers control this)
1486
+ node.on('input', function (msg) {
1487
+ // Check for control commands (preference updates)
1488
+ if (msg.payload && typeof msg.payload === 'object') {
1489
+ const plan = planCommands(msg.payload, { confirmedLimit, confirmedTime });
1490
+ plan.errors.forEach((e) => node.error(e, msg));
1491
+ if (plan.errors.length && !plan.actions.length) {
1492
+ node.status({ fill: "red", shape: "ring", text: plan.errors[0].split(' —')[0] });
1493
+ }
1494
+ for (const a of plan.actions) {
1495
+ if (a.type === 'preferences') setPreferences(a.limit, a.time);
1496
+ else if (a.type === 'timezone') {
1497
+ node.context().set('timezone', a.timezone);
1498
+ node.log(`Timezone set to: ${a.timezone}`);
1499
+ }
1500
+ else if (a.type === 'smart_charging') setSmartCharging(a.enabled);
1501
+ else if (a.type === 'charge_cap') setChargeCap(a.enabled);
1502
+ }
1503
+ if (plan.hasCommand) return; // commands never trigger a manual refresh
1504
+ }
1505
+
1506
+ // Manual refresh request from Node-RED - NO rate limiting
1507
+ // (Programmers can control rate limiting in their flows if needed)
1508
+ // Update timestamp so HA sees cooldown, but don't block the refresh
1509
+ lastManualRefresh = Date.now();
1510
+ node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1511
+ forceCategoryDue('intelligent');
1512
+ });
1513
+
1514
+ // B. Handle MQTT Commands (Home Assistant)
1515
+ if (enableMqtt && node.broker) {
1516
+ node.broker.register(this);
1517
+
1518
+ // Slider changed - update pending value only
1519
+ node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
1520
+ const r = validateLimit(payload.toString());
1521
+ if (!r.ok) {
1522
+ node.warn(r.error);
1523
+ publishCurrentState(); // snap slider back
1524
+ return;
1525
+ }
1526
+ pendingLimit = r.limit;
1527
+ publishCurrentState(); // Update display immediately
1528
+ node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1529
+ });
1530
+
1531
+ // Dropdown changed - update pending value only
1532
+ node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
1533
+ const r = validateTime(payload.toString());
1534
+ if (!r.ok) {
1535
+ node.warn(r.error);
1536
+ publishCurrentState(); // snap dropdown back
1537
+ return;
1538
+ }
1539
+ pendingTime = r.time;
1540
+ publishCurrentState(); // Update display immediately
1541
+ node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1542
+ });
1543
+
1544
+ // Button pressed - submit changes to API
1545
+ node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
1546
+ setPreferences(pendingLimit, pendingTime);
1547
+ });
1548
+
1549
+ // Refresh button pressed - MQTT has hardcoded 30s rate limiting
1550
+ node.broker.subscribe(cmdTopicRefresh, 0, (topic, payload) => {
1551
+ // Check rate limit (only for MQTT button)
1552
+ if (!canManualRefresh()) {
1553
+ const secondsRemaining = getSecondsUntilNextRefresh();
1554
+ node.status({
1555
+ fill: "red",
1556
+ shape: "dot",
1557
+ text: `Cooldown: ${secondsRemaining}s`
1558
+ });
1559
+ node.warn(`MQTT refresh blocked. Please wait ${secondsRemaining} seconds.`);
1560
+ return; // Block the refresh
1561
+ }
1562
+
1563
+ // Refresh allowed - set cooldown timestamp
1564
+ lastManualRefresh = Date.now();
1565
+
1566
+ // Publish immediate update with countdown timestamp
1567
+ publishRefreshCooldownState();
1568
+
1569
+ // Schedule cleanup at exactly 30 seconds to clear countdown
1570
+ if (cooldownExpiryTimer) clearTimeout(cooldownExpiryTimer);
1571
+ cooldownExpiryTimer = setTimeout(() => {
1572
+ // Cooldown expired - publish null to clear countdown in HA
1573
+ publishRefreshCooldownState();
1574
+ cooldownExpiryTimer = null;
1575
+ }, MANUAL_REFRESH_COOLDOWN);
1576
+
1577
+ // Trigger the actual refresh
1578
+ node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1579
+ forceCategoryDue('intelligent');
1580
+ });
1581
+
1582
+ // Timezone select changed in Home Assistant
1583
+ node.broker.subscribe(cmdTopicTimezone, 0, (topic, payload) => {
1584
+ const tz = payload.toString().trim();
1585
+ if (tz.length > 0) {
1586
+ node.context().set('timezone', tz);
1587
+ node.log(`Timezone set via MQTT to: ${tz}`);
1588
+ node.broker.client.publish(`${stateTopic}/timezone`, tz, { retain: true });
1589
+ }
1590
+ });
1591
+
1592
+ // Smart charging switch toggled in Home Assistant
1593
+ node.broker.subscribe(cmdTopicSmartCharging, 0, (topic, payload) => {
1594
+ const val = payload.toString().trim();
1595
+ if (val === "ON") setSmartCharging(true);
1596
+ else if (val === "OFF") setSmartCharging(false);
1597
+ });
1598
+
1599
+ // Charge Cap switch toggled in HA
1600
+ node.broker.subscribe(cmdTopicChargeCap, 0, (topic, payload) => {
1601
+ const val = payload.toString().trim();
1602
+ if (val === "ON") setChargeCap(true);
1603
+ else if (val === "OFF") setChargeCap(false);
1604
+ });
1605
+
1606
+ initTimeoutHandles.push(setTimeout(announceControls, 2000));
1607
+
1608
+ // Republish persisted timezone to HA select on startup
1609
+ initTimeoutHandles.push(setTimeout(() => {
1610
+ try {
1611
+ const persistedTz = node.context().get('timezone');
1612
+ if (persistedTz && node.broker) {
1613
+ node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
1614
+ }
1615
+ } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
1616
+ }, 2500));
1617
+
1618
+ // Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
1619
+ initTimeoutHandles.push(setTimeout(() => {
1620
+ try {
1621
+ if (smartChargingSuspended !== null && node.broker && node.broker.client) {
1622
+ const stateVal = smartChargingSuspended ? "OFF" : "ON";
1623
+ node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
1624
+ }
1625
+ } catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
1626
+ }, 3000));
1627
+ }
1628
+
1629
+ // Init
1630
+ initTimeoutHandles.push(setTimeout(fetchDeviceId, 1500));
1631
+
1632
+ // V2 category discovery and scheduler. Retries with backoff until discovery succeeds
1633
+ // (a transient Kraken error at startup used to leave the node with no scheduler until
1634
+ // restart). Tracked + nodeClosed-guarded so a redeploy can never leave an orphan
1635
+ // scheduler or retry timer.
1636
+ async function startV2(attempt) {
1637
+ if (nodeClosed) return;
1638
+ try {
1639
+ const discovered = await discoverProducts(apiKey, account);
1640
+ if (nodeClosed) return;
1641
+ if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
1642
+ smartChargingSuspended = discovered.deviceSuspended;
1643
+ lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
1644
+ }
1645
+ await initCategories(discovered);
1646
+ if (nodeClosed) return;
1647
+ node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}`);
1648
+ const v2Scheduler = createScheduler(pollDueCategories);
1649
+ v2Scheduler.start();
1650
+ node._v2Scheduler = v2Scheduler;
1651
+ } catch (e) {
1652
+ if (nodeClosed) return;
1653
+ const delay = discoveryRetryDelay(attempt);
1654
+ const secs = Math.round(delay / 1000);
1655
+ node.warn(`V2 discovery failed: ${e.message}. Retrying in ${secs}s.`);
1656
+ node.status({ fill: "yellow", shape: "ring", text: `Discovery failed — retrying in ${secs}s` });
1657
+ initTimeoutHandles.push(setTimeout(() => startV2(attempt + 1), delay));
1658
+ }
1659
+ }
1660
+ initTimeoutHandles.push(setTimeout(() => startV2(0), 2000));
1661
+
1662
+ node.on('close', () => {
1663
+ nodeClosed = true;
1664
+ // Clear init setTimeouts so a redeploy during warmup can't leave an orphan scheduler
1665
+ initTimeoutHandles.forEach(h => clearTimeout(h));
1666
+ initTimeoutHandles = [];
1667
+ // Clear any pending retry timeouts
1668
+ retryTimeouts.forEach(timeout => clearTimeout(timeout));
1669
+ retryTimeouts = [];
1670
+ // Clear smart charging retry timeouts
1671
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1672
+ smartChargingRetryTimeouts = [];
1673
+ // Clear charging timers
1674
+ clearChargingTimers();
1675
+ // Clear cooldown expiry timer
1676
+ if (cooldownExpiryTimer) {
1677
+ clearTimeout(cooldownExpiryTimer);
1678
+ cooldownExpiryTimer = null;
1679
+ }
1680
+ if (node._v2Scheduler) node._v2Scheduler.stop();
1681
+ if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging, cmdTopicChargeCap);
1682
+ });
1683
+ }
1684
+
1685
+ RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
1686
+ credentials: { apiKey: { type: "password" } }
1687
+ });
1686
1688
  };