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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +135 -19
  2. package/README.md +386 -156
  3. package/examples/basic-monitoring.json +1 -1
  4. package/examples/boost-on-cheap-or-surplus.json +171 -0
  5. package/examples/charging-and-error-alerts.json +95 -0
  6. package/examples/cheapest-window-planner.json +165 -0
  7. package/examples/daily-charging-summary.json +165 -0
  8. package/examples/ha-dashboard.yaml +67 -2
  9. package/examples/mqtt-integration.json +1 -1
  10. package/examples/node-red-dashboard-flow.json +92 -2
  11. package/examples/set-preferences.json +1 -1
  12. package/lib/active-now.js +33 -0
  13. package/lib/auth.js +6 -1
  14. package/lib/boost.js +85 -0
  15. package/lib/categories/account.js +3 -3
  16. package/lib/categories/applicable-rates.js +29 -19
  17. package/lib/categories/completed-dispatches.js +2 -1
  18. package/lib/categories/electricity.js +23 -13
  19. package/lib/categories/flex-planned-dispatches.js +2 -2
  20. package/lib/categories/free-electricity.js +13 -1
  21. package/lib/categories/gas.js +13 -6
  22. package/lib/categories/home-mini.js +11 -3
  23. package/lib/categories/intelligent.js +87 -21
  24. package/lib/categories/octoplus.js +6 -3
  25. package/lib/categories/saving-sessions.js +15 -1
  26. package/lib/categories/smartflex-inverter.js +95 -0
  27. package/lib/categories/smartflex-vehicle.js +198 -0
  28. package/lib/categories/wheel-of-fortune.js +3 -2
  29. package/lib/commands.js +25 -3
  30. package/lib/discovery-retry.js +4 -1
  31. package/lib/discovery.js +71 -9
  32. package/lib/graphql-errors.js +160 -4
  33. package/lib/graphql.js +113 -8
  34. package/lib/http-get-json.js +64 -6
  35. package/lib/payload.js +15 -0
  36. package/lib/poll-retry.js +71 -0
  37. package/lib/poll-tick.js +88 -20
  38. package/lib/preferences.js +4 -2
  39. package/lib/scheduler.js +46 -8
  40. package/lib/sensor-definitions.js +51 -1
  41. package/lib/timezone.js +19 -1
  42. package/lib/values.js +47 -0
  43. package/octopus-intelligent.html +74 -34
  44. package/octopus-intelligent.js +1384 -250
  45. package/package.json +1 -1
@@ -1,12 +1,18 @@
1
1
  'use strict';
2
2
  const { graphqlPost } = require('./lib/graphql');
3
- const { onlyDeviceFieldErrors } = require('./lib/graphql-errors');
4
- const { convertToTimezone, resolveTimezone } = require('./lib/timezone');
3
+ const { onlyDeviceFieldErrors, graphqlError, errorCode, truncate, maskSecretsDeep, isUnconfirmedWriteError } = require('./lib/graphql-errors');
4
+
5
+ // Kraken: "Your device charging preferences could not be fetched" (devices.preferences).
6
+ const PREFERENCES_ERROR_CODE = 'KT-CT-4339';
7
+ // Device fields of the charging poll whose errors are tolerated (aliases in DEVICES_QUERY).
8
+ const TOLERATED_DEVICE_FIELDS = ['preferences', 'chargeCap', 'smartStatus'];
9
+ const { convertToTimezone, resolveTimezone, validateTimezone } = require('./lib/timezone');
5
10
  const { createApiMetrics } = require('./lib/api-metrics');
6
11
  const intelligentCategory = require('./lib/categories/intelligent');
7
12
  const { buildDefaultPayload } = require('./lib/payload');
8
13
  const { createScheduler } = require('./lib/scheduler');
9
- const { discoveryRetryDelay } = require('./lib/discovery-retry');
14
+ const { retryDelay, isRetryable, nextSlotStart, createRateWindow, formatDuration } = require('./lib/poll-retry');
15
+ const { discoveryRetryDelay, EMPTY_DEVICES_MAX_RETRIES } = require('./lib/discovery-retry');
10
16
  const { simplePoll, runTick } = require('./lib/poll-tick');
11
17
  const { discoverProducts } = require('./lib/discovery');
12
18
  const { mergePayload } = require('./lib/payload');
@@ -21,11 +27,17 @@ const flexPlannedDispatchesCategory = require('./lib/categories/flex-planned-dis
21
27
  const applicableRatesCategory = require('./lib/categories/applicable-rates');
22
28
  const savingSessionsCategory = require('./lib/categories/saving-sessions');
23
29
  const freeElectricityCategory = require('./lib/categories/free-electricity');
30
+ const smartflexVehicleCategory = require('./lib/categories/smartflex-vehicle');
31
+ const smartflexInverterCategory = require('./lib/categories/smartflex-inverter');
24
32
  const httpGetJson = require('./lib/http-get-json');
25
33
  const { TIME_OPTIONS, validateTime, validateLimit } = require('./lib/preferences');
26
34
  const { planCommands } = require('./lib/commands');
35
+ const { buildBoostRequest, parseBoostResponse, chargingNowFor, reconcileChargingNow } = require('./lib/boost');
27
36
  const { checkUpdate } = require('./lib/update-check');
28
- const { sensors, errorSensors } = require('./lib/sensor-definitions');
37
+ const {
38
+ sensors, errorSensors, vehicleSensors, vehicleErrorSensors, inverterSensors, inverterErrorSensors,
39
+ } = require('./lib/sensor-definitions');
40
+ const { changedActiveFields } = require('./lib/active-now');
29
41
 
30
42
  module.exports = function (RED) {
31
43
  function OctopusIntelligentNode(config) {
@@ -35,6 +47,31 @@ module.exports = function (RED) {
35
47
  // 1. Configuration
36
48
  const account = config.accountNumber ? config.accountNumber.trim() : "";
37
49
  const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
50
+
51
+ // Kraken error text can echo the request, API key included. The Node-RED log, status and
52
+ // msg show it as it is, so a wrong key can be seen. Keys and tokens are masked only in
53
+ // what is published to Home Assistant (stateJson), where they would be kept in its history.
54
+ // A log line is at most MAX_LOG_LENGTH characters. An over-long line keeps its start and
55
+ // its end (". Retrying in 30s."); error text embedded in a line is cut to 300 characters
56
+ // first (short), so normally nothing is cut here.
57
+ const MAX_LOG_LENGTH = 500;
58
+ const capLine = (m) => (m.length > MAX_LOG_LENGTH ? `${m.slice(0, 380)} ... ${m.slice(-(MAX_LOG_LENGTH - 385))}` : m);
59
+ const clean = (m) => (typeof m === 'string' ? capLine(m) : m);
60
+ const short = (m) => truncate(m, 300);
61
+ // The JSON published to the MQTT state topic, with keys and tokens masked.
62
+ const stateJson = (state) => JSON.stringify(maskSecretsDeep(state, [apiKey]));
63
+ // Every log, warn and error line starts with the package version, so a log excerpt in a
64
+ // bug report says which build wrote it. Status text is not prefixed (it is shown in the editor).
65
+ const VERSION_PREFIX = `v${require('./package.json').version}: `;
66
+ const tag = (m) => (typeof m === 'string' ? VERSION_PREFIX + clean(m) : m);
67
+ const rawLog = node.log, rawWarn = node.warn, rawError = node.error, rawStatus = node.status;
68
+ node.log = function (m, ...rest) { return rawLog.call(node, tag(m), ...rest); };
69
+ node.warn = function (m, ...rest) { return rawWarn.call(node, tag(m), ...rest); };
70
+ node.error = function (m, ...rest) { return rawError.call(node, tag(m), ...rest); };
71
+ node.status = function (s, ...rest) {
72
+ const masked = s && typeof s === 'object' && typeof s.text === 'string' ? Object.assign({}, s, { text: clean(s.text) }) : clean(s);
73
+ return rawStatus.call(node, masked, ...rest);
74
+ };
38
75
  const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
39
76
  const enableMqtt = config.enableMqtt;
40
77
  node.timezoneOverride = config.timezoneOverride || "";
@@ -53,25 +90,108 @@ module.exports = function (RED) {
53
90
  const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
54
91
  const cmdTopicSmartCharging = `nodered_octopus/${account}/set_smart_charging`;
55
92
  const cmdTopicChargeCap = `nodered_octopus/${account}/set_charge_cap`;
93
+ const cmdTopicBoost = `nodered_octopus/${account}/set_boost`;
94
+ const commandTopics = [cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh,
95
+ cmdTopicTimezone, cmdTopicSmartCharging, cmdTopicChargeCap, cmdTopicBoost];
56
96
 
57
97
  // 2. Constants & Validation — TIME_OPTIONS / validators live in lib/preferences.js
58
98
 
59
99
  // 3. Sensor Definitions (Read-Only) — imported from lib/sensor-definitions.js
60
100
 
61
101
  // 4. Helper: Announce Controls (Write-Enabled)
62
- function announceControls() {
63
- if (!enableMqtt || !node.broker) return;
102
+ // Single Home Assistant device: every entity sits on it (never split).
103
+ const device = {
104
+ identifiers: [`nodered_octopus_${account}`],
105
+ name: "Octopus Intelligent",
106
+ manufacturer: "Octopus Energy",
107
+ model: "Intelligent Octopus Go",
108
+ // The package version (review L5). Not part of any unique_id, so no entity moves.
109
+ sw_version: require('./package.json').version,
110
+ suggested_area: "Energy",
111
+ configuration_url: "https://octopus.energy/intelligent/"
112
+ };
113
+
114
+ // Review A3: the 1.7 SmartFlex fields are missing from the state JSON of an older version
115
+ // (after a rollback, which never clears these retained configs) and from a retained 1.6
116
+ // state read before the first 1.7 poll. Their templates check `is defined`, so Home
117
+ // Assistant logs no template warnings and shows no false Problem.
118
+ // Review L1: a template that renders None gives unknown only on a numeric sensor (unit,
119
+ // state_class or numeric device_class) and on binary sensors. A text sensor stores the
120
+ // text "None". So every SmartFlex entity also gets an availability check on the state
121
+ // topic: a missing field reads Unavailable. Text sensors marked nullUnavailable also read
122
+ // Unavailable when the field is null (HA has no way to show unknown for a text sensor).
123
+ const valueOrNone = (field) => `value_json.${field} if value_json.${field} is defined else None`;
124
+ const listOrEmpty = (field) => `(value_json.${field} if value_json.${field} is defined else [])`;
125
+ const fieldAvailability = (field, nullUnavailable) => [{
126
+ topic: stateTopic,
127
+ value_template: nullUnavailable === true
128
+ ? `{{ 'online' if value_json.${field} is defined and value_json.${field} is not none else 'offline' }}`
129
+ : `{{ 'online' if value_json.${field} is defined else 'offline' }}`,
130
+ }];
131
+
132
+ // Read-only sensor discovery config (definitions in lib/sensor-definitions.js).
133
+ // missingSafe: the field may be missing from the state JSON (SmartFlex, review A3).
134
+ function announceSensor(sensor, missingSafe) {
135
+ const payload = {
136
+ name: `Octopus ${sensor.name}`,
137
+ unique_id: `${uniqueIdPrefix}_${sensor.id}`,
138
+ state_topic: stateTopic,
139
+ value_template: missingSafe === true ? `{{ ${valueOrNone(sensor.val)} }}` : `{{ value_json.${sensor.val} }}`,
140
+ device: device
141
+ };
142
+ if (sensor.class) payload.device_class = sensor.class;
143
+ if (sensor.unit) payload.unit_of_measurement = sensor.unit;
144
+ if (sensor.stateClass) payload.state_class = sensor.stateClass;
145
+ if (sensor.icon) payload.icon = sensor.icon;
146
+ if (missingSafe === true) payload.availability = fieldAvailability(sensor.val, sensor.nullUnavailable);
147
+
148
+ if (sensor.category) {
149
+ payload.entity_category = sensor.category;
150
+ }
64
151
 
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/"
152
+ if (sensor.id === 'applicable_rates_count') {
153
+ payload.json_attributes_topic = stateTopic;
154
+ payload.json_attributes_template = '{ "rates": {{ value_json.applicable_rates | tojson }} }';
155
+ } else if (sensor.id === 'electricity_export_rate_count') {
156
+ payload.json_attributes_topic = stateTopic;
157
+ payload.json_attributes_template = '{ "rates": {{ value_json.electricity_export_rate | tojson }} }';
158
+ } else if (sensor.id === 'last_session_kwh') {
159
+ // v1.7.0: the full SmartFlex session list and device alerts go in attributes only.
160
+ payload.json_attributes_topic = stateTopic;
161
+ payload.json_attributes_template = `{ "sessions": {{ ${listOrEmpty('charging_sessions')} | tojson }}, "alerts": {{ ${listOrEmpty('device_alerts')} | tojson }} }`;
162
+ // state_class total (review L2): the energy counts from a new cycle at each session
163
+ // end, so HA adds each finished session's kWh to the statistics once. last_session
164
+ // is always a finished session (it has an end). An empty string is ignored by HA:
165
+ // no session yet, or the state JSON of an older version.
166
+ payload.last_reset_value_template = "{{ value_json.last_session.end if value_json.last_session is defined and value_json.last_session and value_json.last_session.end else '' }}";
167
+ }
168
+
169
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
170
+ }
171
+
172
+ // v1.5 — error binary_sensor discovery config (device_class: problem).
173
+ // missingSafe: a missing field reads OFF, not ON (review A3: Jinja's Undefined is not
174
+ // in [None, ''], so the 1.5 template shows a false Problem when the field is missing).
175
+ function announceErrorSensor(e, missingSafe) {
176
+ const payload = {
177
+ name: `Octopus ${e.name}`,
178
+ unique_id: `${uniqueIdPrefix}_${e.id}`,
179
+ state_topic: stateTopic,
180
+ value_template: missingSafe === true
181
+ ? `{{ 'ON' if value_json.${e.val} is defined and value_json.${e.val} not in [None, ''] else 'OFF' }}`
182
+ : `{{ 'OFF' if value_json.${e.val} in [None, ''] else 'ON' }}`,
183
+ payload_on: 'ON',
184
+ payload_off: 'OFF',
185
+ device_class: 'problem',
186
+ entity_category: 'diagnostic',
187
+ device: device,
74
188
  };
189
+ if (missingSafe === true) payload.availability = fieldAvailability(e.val);
190
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_${e.id}/config`, JSON.stringify(payload), { retain: true });
191
+ }
192
+
193
+ function announceControls() {
194
+ if (!enableMqtt || !node.broker) return;
75
195
 
76
196
  // A. The Slider (Number) - now shows pending value
77
197
  const limitConfig = {
@@ -276,49 +396,13 @@ module.exports = function (RED) {
276
396
  node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_loyalty_points_user/config`, JSON.stringify(octoplusLoyaltyBinarySensor), { retain: true });
277
397
 
278
398
  // 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
- });
399
+ sensors.forEach(announceSensor);
306
400
 
307
401
  // 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
- });
402
+ errorSensors.forEach(announceErrorSensor);
403
+
404
+ // H3. v1.7.0 SmartFlex vehicle and inverter entities depend on the devices Octopus
405
+ // lists, so announceSmartflexEntities() publishes them once discovery has run.
322
406
 
323
407
  // I. Timezone Select Entity
324
408
  const TIMEZONE_OPTIONS = [
@@ -377,6 +461,9 @@ module.exports = function (RED) {
377
461
  { retain: true }
378
462
  );
379
463
 
464
+ // J3. The Boost Charge switch (v1.7) needs an EV, so announceSmartflexEntities()
465
+ // publishes it once discovery has run.
466
+
380
467
  // K. v1.5 — Update entity (notify-only; Palette Manager is the install path)
381
468
  node.broker.client.publish(
382
469
  `${mqttPrefix}/update/${uniqueIdPrefix}_node_update/config`,
@@ -391,14 +478,97 @@ module.exports = function (RED) {
391
478
  { retain: true }
392
479
  );
393
480
 
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);
481
+ // Command topics are subscribed through node.broker.subscribe (see Handle MQTT Commands);
482
+ // the broker subscribes the client when connected and again after every reconnect.
483
+ }
484
+
485
+ // 4b. v1.7.0 — SmartFlex entities, announced once product discovery has run. The Boost
486
+ // Charge switch and the vehicle entities only when Octopus lists an ELECTRIC_VEHICLES
487
+ // device (a car or a charge point: Kraken lists both that way); the experimental
488
+ // inverter entities only when the editor option is ticked AND Octopus lists an inverter.
489
+ // Otherwise their discovery topics are cleared, so Home Assistant removes them. A retained
490
+ // empty config deletes the entity (names, areas, ids), so this only happens when Octopus
491
+ // listed devices and none was of that kind: a transient empty list leaves them alone.
492
+ function announceSmartflexEntities(discovered) {
493
+ if (!enableMqtt || !node.broker || !node.broker.client) return;
494
+ const clearSensor = (s) => node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${s.id}/config`, "", { retain: true });
495
+ const clearBinarySensor = (e) => node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_${e.id}/config`, "", { retain: true });
496
+ const devicesListed = discovered.deviceCount > 0
497
+ || !!(discovered.deviceId || discovered.vehicleDeviceId || discovered.inverterDeviceId);
498
+ const inverterOption = config.enableSmartflexInverter === true;
499
+ if (!devicesListed) {
500
+ node.log("SmartFlex: Octopus listed no devices, so the SmartFlex entities in Home Assistant are left as they are");
501
+ }
502
+
503
+ // Boost Charge switch: charge now, outside the plan (v1.7). Boost acts on the car or
504
+ // charge point Octopus controls, so it is announced only when discovery found one
505
+ // (review A10), by the same rule as the vehicle entities. Not a config setting, so no entity_category:
506
+ // it sits with the main controls.
507
+ const boostTopic = `${mqttPrefix}/switch/${uniqueIdPrefix}_boost/config`;
508
+ if (discovered.deviceId) {
509
+ node.broker.client.publish(boostTopic, JSON.stringify({
510
+ name: "Boost Charge",
511
+ unique_id: `${uniqueIdPrefix}_boost`,
512
+ command_topic: cmdTopicBoost,
513
+ state_topic: `${stateTopic}/boost`,
514
+ payload_on: "ON",
515
+ payload_off: "OFF",
516
+ // Its own icon: mdi:lightning-bolt-circle is already on two other entities.
517
+ icon: "mdi:rocket-launch",
518
+ device: device
519
+ }), { retain: true });
520
+ } else if (devicesListed) {
521
+ node.broker.client.publish(boostTopic, "", { retain: true });
522
+ }
523
+
524
+ // Vehicle / charge point. The last-session problem flag is a boolean, so binary_sensor.
525
+ const lastSessionProblemTopic = `${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_last_session_problem/config`;
526
+ if (discovered.vehicleDeviceId) {
527
+ vehicleSensors.forEach((s) => announceSensor(s, true));
528
+ vehicleErrorSensors.forEach((e) => announceErrorSensor(e, true));
529
+ const lastSessionProblemSensor = {
530
+ name: "Octopus Last Charge Session Problem",
531
+ unique_id: `${uniqueIdPrefix}_last_session_problem`,
532
+ state_topic: stateTopic,
533
+ value_template: `{{ ${valueOrNone('last_session_problem')} }}`,
534
+ availability: fieldAvailability('last_session_problem'),
535
+ payload_on: "True",
536
+ payload_off: "False",
537
+ // No icon: the problem class shows its own OK and Problem icons.
538
+ device_class: "problem",
539
+ device: device
540
+ };
541
+ node.broker.client.publish(lastSessionProblemTopic, JSON.stringify(lastSessionProblemSensor), { retain: true });
542
+ } else if (devicesListed) {
543
+ vehicleSensors.forEach(clearSensor);
544
+ vehicleErrorSensors.forEach(clearBinarySensor);
545
+ node.broker.client.publish(lastSessionProblemTopic, "", { retain: true });
546
+ }
547
+
548
+ // Inverter, EXPERIMENTAL.
549
+ const inverterOnlineTopic = `${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_inverter_online/config`;
550
+ if (discovered.inverterDeviceId && inverterOption) {
551
+ inverterSensors.forEach((s) => announceSensor(s, true));
552
+ inverterErrorSensors.forEach((e) => announceErrorSensor(e, true));
553
+ const inverterOnlineSensor = {
554
+ name: "Octopus Inverter Online",
555
+ unique_id: `${uniqueIdPrefix}_inverter_online`,
556
+ state_topic: stateTopic,
557
+ value_template: `{{ ${valueOrNone('inverter_online')} }}`,
558
+ availability: fieldAvailability('inverter_online'),
559
+ payload_on: "True",
560
+ payload_off: "False",
561
+ device_class: "connectivity",
562
+ entity_category: "diagnostic",
563
+ device: device
564
+ };
565
+ node.broker.client.publish(inverterOnlineTopic, JSON.stringify(inverterOnlineSensor), { retain: true });
566
+ } else if (!inverterOption || devicesListed) {
567
+ // Option off: removed on purpose. Option on: only when the list had devices.
568
+ inverterSensors.forEach(clearSensor);
569
+ inverterErrorSensors.forEach(clearBinarySensor);
570
+ node.broker.client.publish(inverterOnlineTopic, "", { retain: true });
571
+ }
402
572
  }
403
573
 
404
574
  // 5. Helper: Set Preferences (The Mutation)
@@ -406,6 +576,10 @@ module.exports = function (RED) {
406
576
  let expectedLimit = null;
407
577
  let expectedTime = null;
408
578
  let validationMode = false;
579
+ let validationGen = 0; // each submit bumps it; an older validation chain then stops
580
+ // Bumped when a preferences or Charge Cap write is sent and when a validation confirms.
581
+ // A charging poll that started before a bump read the old values: it must not apply them.
582
+ let prefsGen = 0;
409
583
 
410
584
  // Pending vs Confirmed state
411
585
  let pendingLimit = 80;
@@ -422,6 +596,16 @@ module.exports = function (RED) {
422
596
  let cachedSlots = []; // Fresh slot data from pre-validation
423
597
  let stateCheckInterval = null; // Reconciliation loop (every 10s)
424
598
  let lastSentChargingState = null; // Track last sent state to avoid duplicates
599
+ let chargingNowPublished = false; // charging_now topic written since start (clears a stale retained ON)
600
+ let boosting = null; // null=unknown; true while status.currentState is BOOSTING
601
+ let boostingConfirmedAt = 0; // when Octopus last told us boosting (poll or boost answer)
602
+ let boostHold = null; // { value, since, until } after Octopus accepted a set_boost
603
+ const BOOST_HOLD_MS = 2 * 60 * 1000;
604
+ let boostError = null; // last failed set_boost (also lastKnownState.boost_error)
605
+ let boostErrorAt = 0;
606
+ // A charging poll that starts this long after the failure and reads the device state
607
+ // clears boost_error, so one refusal does not stay in every payload for days.
608
+ const BOOST_ERROR_CLEAR_MS = 60 * 1000;
425
609
 
426
610
  // Manual refresh rate limiting (only for MQTT button, not Node-RED input)
427
611
  let lastManualRefresh = 0; // Timestamp of last manual refresh
@@ -439,14 +623,33 @@ module.exports = function (RED) {
439
623
  // - Mutation (auth + setPreferences): ~250
440
624
  // - Pre-validation (auth + flexPlannedDispatches only): ~200
441
625
 
442
- // Smart charging state (fetched once at startup)
626
+ // Smart charging state (startup, discovery, then every charging poll)
443
627
  let krakenflexDeviceId = null;
628
+ // The EV discovery picked (the LIVE one, review L4). The charging poll, the startup
629
+ // device fetch and the smart charging check read this device when it is listed.
630
+ let preferredEvId = null;
444
631
  let smartChargingSuspended = null; // null=unknown, true=suspended(off), false=active(on)
445
632
  let smartChargingRetryTimeouts = [];
633
+ let smartChargingVerifying = false; // a toggle is waiting for Octopus to confirm it
634
+ let publishedSmartCharging = null; // last value written to the switch state topic
635
+ let otherDeviceErrorLogged = false; // charging poll: an error on another device was logged
636
+ let statusWarned = false; // warned that Octopus could not return the device status
637
+
638
+ // Write the switch state topic (retained) when it differs from the last one written.
639
+ function publishSmartChargingState(force) {
640
+ if (smartChargingSuspended === null) return;
641
+ const value = smartChargingSuspended ? "OFF" : "ON";
642
+ if (!force && value === publishedSmartCharging) return;
643
+ if (enableMqtt && node.broker && node.broker.client) {
644
+ node.broker.client.publish(`${stateTopic}/smart_charging`, value, { retain: true });
645
+ publishedSmartCharging = value;
646
+ }
647
+ }
446
648
 
447
649
  // Last known full state - prevents sensors going unknown when controls change
448
650
  let lastKnownState = buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
449
651
  lastKnownState.installed_version = require('./package.json').version;
652
+ node.log('starting');
450
653
 
451
654
  // V2 category registry — populated after discovery
452
655
  let categories = [];
@@ -454,24 +657,195 @@ module.exports = function (RED) {
454
657
  // Lifecycle tracking — init setTimeouts must be clearable on close, and async
455
658
  // callbacks inside them must short-circuit if the node was closed mid-await,
456
659
  // otherwise a redeploy during the 2s warmup leaves an orphan V2 scheduler.
457
- let initTimeoutHandles = [];
660
+ // Each handle is removed when its timer fires, so the set stays small however long
661
+ // discovery keeps retrying (it retries every 5 minutes for as long as it fails).
662
+ const initTimeoutHandles = new Set();
663
+ function initTimeout(fn, ms) {
664
+ const handle = setTimeout(() => {
665
+ initTimeoutHandles.delete(handle);
666
+ return fn();
667
+ }, ms);
668
+ initTimeoutHandles.add(handle);
669
+ return handle;
670
+ }
458
671
  let nodeClosed = false;
459
672
  let lastWarnedVersion = null;
460
673
  let prevPublishedInstalled = null;
461
674
  let prevPublishedLatest = null;
462
675
 
463
- async function initCategories(discovered) {
464
- categories = [];
676
+ // Quick retry of the charging poll (1.6.2). Octopus fails flexPlannedDispatches
677
+ // (KT-CT-4340) or the device preferences (KT-CT-4339) for a few minutes around :00/:30.
678
+ // A retry only forces the charging category due, so it runs through the scheduler's
679
+ // in-flight guard and never alongside a normal tick; nothing runs once the node closes.
680
+ const dispatchRate = createRateWindow(); // max 3 flexPlannedDispatches queries in any 60 s
681
+ let chargingOutage = null; // { since, retryNo, retryAt, nextNormalAt } while the poll fails
682
+ let retryPollRunning = false;
683
+ // prefsGen when this tick's charging poll started (null: no charging poll this tick).
684
+ let tickChargingPollGen = null;
685
+ const PREFERENCE_FIELDS = ['confirmed_limit', 'confirmed_time', 'pending_limit', 'pending_time', 'charge_cap'];
686
+
687
+ function noteDispatchQuery() {
688
+ dispatchRate.record(Date.now());
689
+ }
465
690
 
691
+ // Called at the start of each tick: force the charging poll due when a retry is due.
692
+ function startDueChargingRetry() {
693
+ if (!chargingOutage || !chargingOutage.retryAt) return;
694
+ const now = Date.now();
695
+ if (now < chargingOutage.retryAt) return;
696
+ const cat = categories.find((c) => c.id === 'intelligent');
697
+ if (!cat || !cat.enabled || now >= chargingOutage.nextNormalAt) {
698
+ chargingOutage.retryAt = null; // the normal poll takes over
699
+ return;
700
+ }
701
+ const allowedAt = dispatchRate.nextAllowedAt(now);
702
+ if (allowedAt > now) {
703
+ // Too many dispatch queries this minute: wait, unless the normal poll comes first.
704
+ chargingOutage.retryAt = allowedAt < chargingOutage.nextNormalAt ? allowedAt : null;
705
+ return;
706
+ }
707
+ chargingOutage.retryAt = null;
708
+ retryPollRunning = true;
709
+ forceCategoryDue('intelligent');
710
+ }
711
+
712
+ function noteChargingPollFailure(err, isRetry, intervalMs) {
713
+ const now = Date.now();
714
+ if (!chargingOutage) chargingOutage = { since: now, retryNo: 0, retryAt: null, nextNormalAt: 0 };
715
+ chargingOutage.nextNormalAt = nextSlotStart(now, intervalMs);
716
+ chargingOutage.retryAt = null;
717
+ // A Kraken error carries code and detail; a socket error (ENOTFOUND) has a code only.
718
+ const text = err.code && err.detail !== undefined ? `${err.code} ${err.detail}` : err.message;
719
+ let suffix = '';
720
+ if (isRetryable(err)) {
721
+ const retryNo = isRetry ? chargingOutage.retryNo + 1 : 1;
722
+ const delay = retryDelay(retryNo);
723
+ if (now + delay < chargingOutage.nextNormalAt) {
724
+ chargingOutage.retryNo = retryNo;
725
+ chargingOutage.retryAt = now + delay;
726
+ suffix = ` (retry ${retryNo} in ${Math.round(delay / 1000)}s)`;
727
+ } else {
728
+ suffix = ` (next poll in ${Math.ceil((chargingOutage.nextNormalAt - now) / 1000)}s)`;
729
+ }
730
+ }
731
+ node.warn(`Charging poll failed: ${short(text)}${suffix}`);
732
+ }
733
+
734
+ function noteChargingPollSuccess() {
735
+ if (!chargingOutage) return;
736
+ node.log(`Charging poll recovered after ${formatDuration(Date.now() - chargingOutage.since)}`);
737
+ chargingOutage = null;
738
+ }
739
+
740
+ // The scheduler's charging poll: logs each failure and schedules the quick retry.
741
+ async function scheduledIntelligentPoll(token, isStale) {
742
+ const isRetry = retryPollRunning;
743
+ retryPollRunning = false;
744
+ tickChargingPollGen = prefsGen;
745
+ try {
746
+ return await intelligentPoll(token, isStale);
747
+ } catch (e) {
748
+ if (!nodeClosed && !(isStale && isStale())) {
749
+ const cat = categories.find((c) => c.id === 'intelligent');
750
+ noteChargingPollFailure(e, isRetry, cat ? cat.intervalMs : refreshRate);
751
+ }
752
+ if (typeof e.message === 'string') e.message = truncate(e.message);
753
+ throw e;
754
+ }
755
+ }
756
+
757
+ // The charging poll (first in the list) and completed dispatches, for an account with an EV.
758
+ function intelligentCategoryEntry() {
759
+ return {
760
+ id: 'intelligent',
761
+ enabled: true,
762
+ intervalMs: (config.refreshInterval || 5) * 60 * 1000,
763
+ lastPolled: 0,
764
+ poll: scheduledIntelligentPoll,
765
+ };
766
+ }
767
+
768
+ function completedDispatchesCategoryEntry() {
769
+ return {
770
+ id: 'completed_dispatches',
771
+ enabled: true,
772
+ intervalMs: 60 * 60 * 1000,
773
+ lastPolled: 0,
774
+ queryFn: () => completedDispatchesCategory.buildQuery(account),
775
+ parseFn: d => completedDispatchesCategory.parseResponse(d),
776
+ poll: simplePoll(
777
+ () => completedDispatchesCategory.buildQuery(account),
778
+ d => completedDispatchesCategory.parseResponse(d),
779
+ graphqlPost
780
+ ),
781
+ };
782
+ }
783
+
784
+ // v1.7.0 — SmartFlex vehicle / charge point details and charging sessions.
785
+ function smartflexVehicleCategoryEntry(discovered) {
786
+ return {
787
+ id: 'smartflex_vehicle',
788
+ enabled: true,
789
+ intervalMs: 30 * 60 * 1000,
790
+ lastPolled: 0,
791
+ queryFn: () => smartflexVehicleCategory.buildQuery(account),
792
+ parseFn: d => smartflexVehicleCategory.parseResponse(d, discovered.vehicleDeviceId),
793
+ // Tolerates partial errors (e.g. on chargingSessions): keeps what came back
794
+ // and the last values for the rest. Throws only when no vehicle data came back.
795
+ poll: async (token) => {
796
+ const { query, variables } = smartflexVehicleCategory.buildQuery(account);
797
+ const response = await graphqlPost({ query, variables }, token);
798
+ const result = smartflexVehicleCategory.parseGraphqlResponse(response.data, discovered.vehicleDeviceId);
799
+ if (result.smartflex_vehicle_error && !nodeClosed) {
800
+ node.warn(`SmartFlex vehicle poll partly failed: ${result.smartflex_vehicle_error} - keeping the last values for the missing fields`);
801
+ }
802
+ // device_state comes from the charging poll: a charge point is listed as
803
+ // ELECTRIC_VEHICLES too, so every vehicle device has one.
804
+ return result;
805
+ },
806
+ };
807
+ }
808
+
809
+ // v1.7.0 — SmartFlex inverter telemetry. Experimental: not yet verified on a real
810
+ // inverter, so it only runs when the editor option is ticked.
811
+ function smartflexInverterCategoryEntry(discovered) {
812
+ return {
813
+ id: 'smartflex_inverter',
814
+ enabled: true,
815
+ intervalMs: 5 * 60 * 1000,
816
+ lastPolled: 0,
817
+ queryFn: () => smartflexInverterCategory.buildQuery(account),
818
+ parseFn: d => smartflexInverterCategory.parseResponse(d, discovered.inverterDeviceId),
819
+ poll: simplePoll(
820
+ () => smartflexInverterCategory.buildQuery(account),
821
+ d => smartflexInverterCategory.parseResponse(d, discovered.inverterDeviceId),
822
+ graphqlPost
823
+ ),
824
+ };
825
+ }
826
+
827
+ // The categories that need a device from discovery. Used by initCategories and by the
828
+ // empty-device re-check, so both set up the same polls (review4 #1). `lead` goes first
829
+ // in the list (the charging poll); `rest` goes after the account categories.
830
+ function deviceCategoryEntries(discovered) {
831
+ const lead = [];
832
+ const rest = [];
466
833
  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
- });
834
+ lead.push(intelligentCategoryEntry());
835
+ rest.push(completedDispatchesCategoryEntry());
836
+ }
837
+ if (discovered.vehicleDeviceId) rest.push(smartflexVehicleCategoryEntry(discovered));
838
+ if (discovered.inverterDeviceId && config.enableSmartflexInverter === true) {
839
+ rest.push(smartflexInverterCategoryEntry(discovered));
474
840
  }
841
+ return { lead, rest };
842
+ }
843
+
844
+ async function initCategories(discovered) {
845
+ categories = [];
846
+ const deviceCategories = deviceCategoryEntries(discovered);
847
+
848
+ categories.push(...deviceCategories.lead);
475
849
 
476
850
  const electricityEnabled = config.electricityEnabled !== false;
477
851
  const gasEnabled = config.gasEnabled !== false;
@@ -580,21 +954,8 @@ module.exports = function (RED) {
580
954
  ),
581
955
  });
582
956
 
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
- }
957
+ // Completed dispatches and the SmartFlex categories.
958
+ categories.push(...deviceCategories.rest);
598
959
 
599
960
  if (discovered.hasElectricity && discovered.electricityMpan) {
600
961
  categories.push({
@@ -617,6 +978,7 @@ module.exports = function (RED) {
617
978
  if (discovered.hasElectricity && discovered.electricityExportMpan) {
618
979
  categories.push({
619
980
  id: 'applicable_rates_export',
981
+ errorField: 'electricity_export_rate_error',
620
982
  enabled: true,
621
983
  intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
622
984
  lastPolled: 0,
@@ -680,19 +1042,54 @@ module.exports = function (RED) {
680
1042
  intervalMs: 24 * 60 * 60 * 1000, // 24h — once daily npm registry check
681
1043
  lastPolled: 0, // fires on first scheduler tick
682
1044
  poll: intelligentUpdateCheck, // token ignored
1045
+ needsToken: false, // still runs when the Octopus token request fails
683
1046
  });
684
1047
  }
685
1048
 
686
- async function pollDueCategories() {
1049
+ async function pollDueCategories(isStale) {
1050
+ if (nodeClosed) return;
1051
+ startDueChargingRetry();
1052
+ startDeferredChargingPoll();
1053
+ tickChargingPollGen = null;
687
1054
  const result = await runTick({
688
1055
  categories,
689
1056
  state: lastKnownState,
690
- getToken: obtainTickToken,
1057
+ getToken: tickToken,
1058
+ // Stop at the next category once the node is closed, not only when superseded.
1059
+ isStale: () => nodeClosed || !!(isStale && isStale()),
691
1060
  });
1061
+ // A retry tick whose poll never ran (e.g. auth failed) must not mark the next poll a retry.
1062
+ retryPollRunning = false;
1063
+ if (nodeClosed || (isStale && isStale())) return;
692
1064
  if (!result.emitted) return;
693
- lastKnownState = result.state;
1065
+ logCategoryFailures(result.changes);
1066
+ // Apply only this tick's changes onto the current state: a validation poll, a Charge
1067
+ // Cap change or an active-fields refresh may have written it while the tick waited
1068
+ // on Octopus. A slot timer may have changed charging_now, and a set_boost answer
1069
+ // boosting or boost_error, meanwhile (review F4).
1070
+ let changes = result.changes;
1071
+ // A change was sent or confirmed after this tick's charging poll started (for example
1072
+ // a validation poll while a later category ran): the poll's target, ready-by time and
1073
+ // Charge Cap are older than what the state holds now, so keep the state's values.
1074
+ if (tickChargingPollGen !== null && prefsGen !== tickChargingPollGen) {
1075
+ changes = Object.assign({}, changes);
1076
+ PREFERENCE_FIELDS.forEach((f) => { delete changes[f]; });
1077
+ }
1078
+ tickChargingPollGen = null;
1079
+ // charging_now, boosting and boost_error, and the pending target and ready-by time,
1080
+ // from the node's own values: a slot timer, a set_boost answer, or a slider or
1081
+ // ready-by change in Home Assistant that was not applied yet (it does not bump
1082
+ // prefsGen), may have changed them while the tick waited (review F4). The charging
1083
+ // poll sets these values itself, so they never disagree with a fresh poll.
1084
+ lastKnownState = mergePayload(mergePayload(lastKnownState, changes), {
1085
+ charging_now: chargingNow,
1086
+ boosting,
1087
+ boost_error: boostError,
1088
+ pending_limit: pendingLimit,
1089
+ pending_time: pendingTime,
1090
+ });
694
1091
  if (enableMqtt && node.broker && node.broker.client) {
695
- node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
1092
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
696
1093
  // v1.5 — publish update entity state only when version values change
697
1094
  if (prevPublishedInstalled !== lastKnownState.installed_version
698
1095
  || prevPublishedLatest !== lastKnownState.latest_version) {
@@ -712,37 +1109,153 @@ module.exports = function (RED) {
712
1109
  node.warn(`Update available: v${lastKnownState.latest_version} (running v${lastKnownState.installed_version}). Install via Node-RED → Manage Palette → Upgrade.`);
713
1110
  lastWarnedVersion = lastKnownState.latest_version;
714
1111
  }
715
- if (!validationMode) {
716
- if (lastKnownState.intelligent_error) {
717
- node.status({ fill: "red", shape: "ring", text: `Error: ${String(lastKnownState.intelligent_error).slice(0, 40)}` });
1112
+ const octopusCategories = categories.filter((c) => c.enabled && c.needsToken !== false);
1113
+ const hasChargingPoll = categories.some((c) => c.id === 'intelligent');
1114
+ if (!hasChargingPoll) {
1115
+ // No car or charger: there is no "Confirmed" status to show, so show the first
1116
+ // Octopus poll error (red when every Octopus poll failed, yellow when some did).
1117
+ const failed = octopusCategories.filter((c) => lastKnownState[`${c.id}_error`]);
1118
+ if (failed.length > 0) {
1119
+ const first = failed[0];
1120
+ node.status({
1121
+ fill: failed.length === octopusCategories.length ? "red" : "yellow",
1122
+ shape: "ring",
1123
+ text: truncate(`${first.id}: ${lastKnownState[`${first.id}_error`]}`, 80),
1124
+ });
718
1125
  } else {
719
1126
  node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
720
1127
  }
1128
+ } else if (!validationMode) {
1129
+ if (writeNotApplied) {
1130
+ // A write that got no answer was checked by this tick's charging poll: not applied.
1131
+ node.status({ fill: "red", shape: "ring", text: writeNotApplied });
1132
+ writeNotApplied = null;
1133
+ } else if (lastKnownState.intelligent_error) {
1134
+ // "Error: KT-CT-4340: Unable to fetch planned dispatches", capped for the editor.
1135
+ // The "Error: " prefix is what 1.6.1 showed: flows can match it in a Status node.
1136
+ node.status({ fill: "red", shape: "ring", text: truncate('Error: ' + lastKnownState.intelligent_error, 80) });
1137
+ } else {
1138
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
1139
+ }
1140
+ }
1141
+ }
1142
+
1143
+ // A failed category poll (or update check) used to show only in its <id>_error field.
1144
+ // Warn once when a run of failures starts and log one line when it works again. The
1145
+ // charging poll logs its own failures, and a failed login is logged by tickToken.
1146
+ function logCategoryFailures(changes) {
1147
+ for (const cat of categories) {
1148
+ if (cat.id === 'intelligent') continue;
1149
+ const field = `${cat.id}_error`;
1150
+ if (!(field in changes)) continue; // not polled this tick
1151
+ const err = changes[field];
1152
+ if (typeof err === 'string' && err) {
1153
+ if (/^Auth failed: /.test(err)) continue;
1154
+ if (!cat.failureLogged) {
1155
+ cat.failureLogged = true;
1156
+ node.warn(`${cat.id} poll failed: ${truncate(err)}`);
1157
+ }
1158
+ } else if (err === null && cat.failureLogged) {
1159
+ cat.failureLogged = false;
1160
+ node.log(`${cat.id} poll working again`);
1161
+ }
721
1162
  }
722
1163
  }
723
1164
 
1165
+ // The tick's token request. A failure used to write nothing to the log (only the
1166
+ // *_error fields): warn once when a run of failures starts and log when it ends.
1167
+ let tickAuthFailing = false;
1168
+ async function tickToken() {
1169
+ let token;
1170
+ try {
1171
+ token = await obtainTickToken();
1172
+ } catch (e) {
1173
+ if (!tickAuthFailing && !nodeClosed) {
1174
+ tickAuthFailing = true;
1175
+ node.warn(`Octopus login failed: ${truncate(e.message)}. Polls try again with back-off.`);
1176
+ }
1177
+ throw e;
1178
+ }
1179
+ if (tickAuthFailing && !nodeClosed) {
1180
+ tickAuthFailing = false;
1181
+ node.log('Octopus login working again');
1182
+ }
1183
+ return token;
1184
+ }
1185
+
724
1186
  async function obtainTickToken() {
725
1187
  const response = await graphqlPost({
726
1188
  query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
727
1189
  variables: { input: { APIKey: apiKey } },
728
1190
  });
729
1191
  if (!response.data.data || !response.data.data.obtainKrakenToken) {
730
- throw new Error('Auth response missing token: ' + JSON.stringify(response.data.errors || response.data));
1192
+ const why = response.data.errors ? graphqlError(response.data.errors).message : JSON.stringify(response.data);
1193
+ throw new Error(truncate('Auth response missing token: ' + why));
731
1194
  }
732
1195
  return response.data.data.obtainKrakenToken.token;
733
1196
  }
734
1197
 
1198
+ // forceSeq lets runTick keep the category due when this lands during its poll.
735
1199
  function forceCategoryDue(id) {
736
1200
  const cat = categories.find((c) => c.id === id);
737
- if (cat) cat.lastPolled = 0;
1201
+ if (!cat) return;
1202
+ cat.forceSeq = (cat.forceSeq || 0) + 1;
1203
+ cat.lastPolled = 0;
1204
+ }
1205
+
1206
+ // A write mutation that got no answer (time-out, connection closed after the request
1207
+ // was sent, HTTP 5xx) may still have been applied by Octopus. Mark it so the caller
1208
+ // checks with the next charging poll rather than reporting a failure. A DNS or connect
1209
+ // error, an HTTP 4xx or an unreadable reply is a plain failure, and so is a GraphQL
1210
+ // refusal (it comes back as `errors`).
1211
+ function unconfirmedWrite(e) {
1212
+ if (!isUnconfirmedWriteError(e)) throw e;
1213
+ const err = new Error(e && e.message ? e.message : String(e));
1214
+ err.unconfirmed = true;
1215
+ throw err;
1216
+ }
1217
+
1218
+ // Writes that got no answer, checked against what the next charging poll reads.
1219
+ let unconfirmedPrefs = null; // { limit, time }
1220
+ let unconfirmedCap = null; // { enabled }
1221
+ let writeNotApplied = null; // red status text for the end of the tick: a check failed
1222
+
1223
+ // Called by a charging poll that read the preferences (prefsRead) and/or Charge Cap
1224
+ // (capRead). A match is a normal confirmed change; a mismatch means Octopus did not
1225
+ // apply the write.
1226
+ function checkUnconfirmedWrites(chargeCap, prefsRead, capRead) {
1227
+ if (unconfirmedPrefs && prefsRead) {
1228
+ const want = unconfirmedPrefs;
1229
+ unconfirmedPrefs = null;
1230
+ if (confirmedLimit === want.limit && confirmedTime === want.time) {
1231
+ node.log(`Preferences update confirmed: ${confirmedLimit}% @ ${confirmedTime}`);
1232
+ } else {
1233
+ node.warn(`Preferences update not applied: sent ${want.limit}% @ ${want.time}, Octopus has ${confirmedLimit}% @ ${confirmedTime}`);
1234
+ writeNotApplied = "Update Failed";
1235
+ }
1236
+ }
1237
+ if (unconfirmedCap && capRead) {
1238
+ const want = unconfirmedCap;
1239
+ unconfirmedCap = null;
1240
+ if (chargeCap === want.enabled) {
1241
+ node.log(`Charge Cap change confirmed: ${want.enabled ? "on" : "off"}`);
1242
+ } else {
1243
+ node.warn(`Charge Cap change not applied: sent ${want.enabled ? "on" : "off"}, Octopus has ${chargeCap === null ? "unknown" : (chargeCap ? "on" : "off")}`);
1244
+ writeNotApplied = "Charge Cap update failed";
1245
+ }
1246
+ }
738
1247
  }
739
1248
 
740
1249
  // limit/time are validated by the caller (or come from the API as confirmed values).
741
1250
  async function setPreferences(limit, time) {
742
1251
 
743
- // Cancel any pending retry attempts from previous changes
1252
+ // Cancel any pending retry attempts from previous changes. A check already waiting
1253
+ // on Octopus sees the new generation and stops, so two chains never run at once.
744
1254
  retryTimeouts.forEach(timeout => clearTimeout(timeout));
745
1255
  retryTimeouts = [];
1256
+ const gen = ++validationGen;
1257
+ unconfirmedPrefs = null; // a newer change replaces one still to be checked
1258
+ writeNotApplied = null;
746
1259
 
747
1260
  try {
748
1261
  node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
@@ -791,10 +1304,13 @@ module.exports = function (RED) {
791
1304
  input: buildDevicePreferencesInput(krakenflexDeviceId, limit, time)
792
1305
  };
793
1306
 
1307
+ prefsGen++;
794
1308
  const mutationResponse = await graphqlPost({
795
1309
  query: mutation,
796
1310
  variables: variables
797
- }, token);
1311
+ }, token).catch(unconfirmedWrite);
1312
+ if (nodeClosed) return;
1313
+ if (gen !== validationGen) return; // a newer submit owns validation now
798
1314
 
799
1315
  if (mutationResponse.data.errors) {
800
1316
  throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
@@ -812,21 +1328,34 @@ module.exports = function (RED) {
812
1328
 
813
1329
  // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
814
1330
  const retryIntervals = [15000, 30000, 60000, 120000];
815
- scheduleRetries(retryIntervals, 0);
1331
+ scheduleRetries(retryIntervals, 0, gen);
816
1332
 
817
1333
  } catch (err) {
818
- node.error("Failed to set preferences: " + err.message);
819
- if (err.response) {
820
- node.error(`Response: ${JSON.stringify(err.response.data)}`);
1334
+ if (nodeClosed) return;
1335
+ if (err.unconfirmed) {
1336
+ node.warn(`Preferences update not confirmed (${short(err.message)}) - checking with Octopus`);
1337
+ } else {
1338
+ node.error("Failed to set preferences: " + short(err.message));
1339
+ if (err.response) {
1340
+ node.error(`Response: ${short(JSON.stringify(err.response.data))}`);
1341
+ }
821
1342
  }
822
- node.status({ fill: "red", shape: "ring", text: "Update Failed" });
1343
+ if (gen !== validationGen) return; // a newer submit owns the status and validation
823
1344
  expectedLimit = null;
824
1345
  expectedTime = null;
825
1346
  validationMode = false;
1347
+ if (err.unconfirmed) {
1348
+ unconfirmedPrefs = { limit, time }; // the next charging poll checks it
1349
+ node.status({ fill: "yellow", shape: "ring", text: "Update unconfirmed - checking" });
1350
+ forceCategoryDue('intelligent'); // the next tick reads what Octopus has
1351
+ return;
1352
+ }
1353
+ node.status({ fill: "red", shape: "ring", text: "Update Failed" });
826
1354
  }
827
1355
  }
828
1356
 
829
- function scheduleRetries(intervals, index) {
1357
+ function scheduleRetries(intervals, index, gen) {
1358
+ if (nodeClosed || gen !== validationGen) return;
830
1359
  if (index >= intervals.length) {
831
1360
  // All retries exhausted, let normal interval take over
832
1361
  node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
@@ -837,24 +1366,26 @@ module.exports = function (RED) {
837
1366
  }
838
1367
 
839
1368
  const timeout = setTimeout(async () => {
840
- await fetchDataWithValidation(intervals, index);
1369
+ await fetchDataWithValidation(intervals, index, gen);
841
1370
  }, intervals[index]);
842
1371
 
843
1372
  retryTimeouts.push(timeout);
844
1373
  }
845
1374
 
846
- async function fetchDataWithValidation(intervals, currentIndex) {
1375
+ async function fetchDataWithValidation(intervals, currentIndex, gen) {
847
1376
  try {
848
1377
  const token = await obtainTickToken();
849
1378
  const partial = await intelligentPoll(token);
1379
+ if (nodeClosed || gen !== validationGen) return;
850
1380
  lastKnownState = Object.assign({}, lastKnownState, partial, { intelligent_error: null });
851
1381
  if (enableMqtt && node.broker && node.broker.client) {
852
- node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
1382
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
853
1383
  }
854
1384
  node.send({ payload: lastKnownState });
855
1385
 
856
1386
  const validated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
857
1387
  if (validated) {
1388
+ prefsGen++; // a charging poll still in flight read the old values
858
1389
  validationMode = false;
859
1390
  retryTimeouts.forEach((t) => clearTimeout(t));
860
1391
  retryTimeouts = [];
@@ -865,15 +1396,16 @@ module.exports = function (RED) {
865
1396
  const attempt = currentIndex + 1;
866
1397
  if (currentIndex < intervals.length - 1) {
867
1398
  node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
868
- scheduleRetries(intervals, currentIndex + 1);
1399
+ scheduleRetries(intervals, currentIndex + 1, gen);
869
1400
  } else {
870
1401
  validationMode = false;
871
1402
  node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
872
1403
  }
873
1404
  } catch (error) {
874
- node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
1405
+ if (nodeClosed || gen !== validationGen) return;
1406
+ node.warn(`Retry ${currentIndex + 1} failed: ${short(error.message)}`);
875
1407
  if (currentIndex < intervals.length - 1) {
876
- scheduleRetries(intervals, currentIndex + 1);
1408
+ scheduleRetries(intervals, currentIndex + 1, gen);
877
1409
  } else {
878
1410
  validationMode = false;
879
1411
  node.status({ fill: "red", shape: "ring", text: "Validation failed" });
@@ -910,7 +1442,8 @@ module.exports = function (RED) {
910
1442
  const mutationResponse = await graphqlPost({
911
1443
  query: `mutation UpdateSmartControl($deviceId: ID!, $action: SmartControlAction!) { updateDeviceSmartControl(input: { deviceId: $deviceId, action: $action }) { id } }`,
912
1444
  variables: { deviceId: krakenflexDeviceId, action: action }
913
- }, token);
1445
+ }, token).catch(unconfirmedWrite);
1446
+ if (nodeClosed) return;
914
1447
 
915
1448
  if (mutationResponse.data.errors) {
916
1449
  throw new Error(`Smart charging mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
@@ -925,26 +1458,32 @@ module.exports = function (RED) {
925
1458
  smartChargingSuspended = expectedSuspended;
926
1459
 
927
1460
  // 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
- }
1461
+ publishSmartChargingState(true);
931
1462
 
932
1463
  // Schedule verification: 15s / 30s / 60s / 120s
1464
+ smartChargingVerifying = true;
933
1465
  scheduleSmartChargingVerification(expectedSuspended, [15000, 30000, 60000, 120000], 0);
934
1466
 
935
1467
  } catch (e) {
936
- node.error(`Failed to toggle smart charging: ${e.message}`);
1468
+ if (nodeClosed) return;
1469
+ if (e.unconfirmed) {
1470
+ // No answer: Octopus may have made the change. The switch keeps the last known
1471
+ // state while the usual 15/30/60/120 s checks read what Octopus has.
1472
+ node.warn(`Smart charging change not confirmed (${short(e.message)}) - checking with Octopus`);
1473
+ smartChargingSuspended = previousSuspended;
1474
+ publishSmartChargingState(true);
1475
+ node.status({ fill: "yellow", shape: "ring", text: "Smart charging unconfirmed - checking" });
1476
+ smartChargingVerifying = true;
1477
+ scheduleSmartChargingVerification(!enable, [15000, 30000, 60000, 120000], 0);
1478
+ return;
1479
+ }
1480
+ node.error(`Failed to toggle smart charging: ${short(e.message)}`);
937
1481
  // Revert optimistic update to pre-mutation state
938
1482
  smartChargingSuspended = previousSuspended;
1483
+ smartChargingVerifying = false;
939
1484
  node.status({ fill: "red", shape: "ring", text: "Smart charging update failed" });
940
1485
  // 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
- }
1486
+ publishSmartChargingState(true);
948
1487
  }
949
1488
  }
950
1489
 
@@ -956,13 +1495,17 @@ module.exports = function (RED) {
956
1495
  return;
957
1496
  }
958
1497
  const previous = lastKnownState ? lastKnownState.charge_cap : null;
1498
+ unconfirmedCap = null; // a newer change replaces one still to be checked
1499
+ writeNotApplied = null;
959
1500
  try {
960
1501
  node.status({ fill: "blue", shape: "dot", text: enabled ? "Enabling Charge Cap..." : "Disabling Charge Cap..." });
961
1502
  const token = await obtainTickToken();
1503
+ prefsGen++;
962
1504
  const res = await graphqlPost({
963
1505
  query: `mutation SetChargeCap($input: UpdateIsChargingDurationCappedInput!) { updateIsChargingDurationCapped(input: $input) { __typename } }`,
964
1506
  variables: { input: { deviceId: krakenflexDeviceId, enabled } }
965
- }, token);
1507
+ }, token).catch(unconfirmedWrite);
1508
+ if (nodeClosed) return;
966
1509
  if (res.data.errors) {
967
1510
  throw new Error(`Charge Cap mutation failed: ${JSON.stringify(res.data.errors)}`);
968
1511
  }
@@ -974,8 +1517,16 @@ module.exports = function (RED) {
974
1517
  node.status({ fill: "green", shape: "dot", text: `Charge Cap ${enabled ? "on" : "off"}` });
975
1518
  forceCategoryDue('intelligent'); // next tick confirms from the API
976
1519
  } catch (e) {
977
- node.error(`Failed to change Charge Cap: ${e.message}`);
978
- node.status({ fill: "red", shape: "ring", text: "Charge Cap update failed" });
1520
+ if (nodeClosed) return;
1521
+ if (e.unconfirmed) {
1522
+ unconfirmedCap = { enabled }; // the next charging poll checks it
1523
+ node.warn(`Charge Cap change not confirmed (${short(e.message)}) - checking with Octopus`);
1524
+ node.status({ fill: "yellow", shape: "ring", text: "Charge Cap unconfirmed - checking" });
1525
+ forceCategoryDue('intelligent'); // the next tick reads what Octopus has
1526
+ } else {
1527
+ node.error(`Failed to change Charge Cap: ${short(e.message)}`);
1528
+ node.status({ fill: "red", shape: "ring", text: "Charge Cap update failed" });
1529
+ }
979
1530
  // Republish previous state so the HA switch re-syncs
980
1531
  if (enableMqtt && node.broker && node.broker.client && typeof previous === 'boolean') {
981
1532
  node.broker.client.publish(`${stateTopic}/charge_cap`, previous ? "ON" : "OFF", { retain: true });
@@ -983,8 +1534,272 @@ module.exports = function (RED) {
983
1534
  }
984
1535
  }
985
1536
 
1537
+ // Boosting changed (mutation read-back): publish it and let charging_now follow,
1538
+ // since a boost counts as charging (charging_now = slot active OR boosting).
1539
+ function applyBoosting(value) {
1540
+ if (typeof value !== 'boolean') return;
1541
+ boosting = value;
1542
+ boostingConfirmedAt = Date.now();
1543
+ lastKnownState = mergePayload(lastKnownState, { boosting: value });
1544
+ publishBoostSwitch(value);
1545
+ const shouldBeCharging = chargingNowFor(cachedSlots, boosting);
1546
+ if (shouldBeCharging !== chargingNow) publishChargingState(shouldBeCharging);
1547
+ }
1548
+
1549
+ // Boost Charge switch state topic (retained): ON, OFF, or None, which Home Assistant
1550
+ // shows as unknown.
1551
+ function publishBoostSwitch(value) {
1552
+ if (!(enableMqtt && node.broker && node.broker.client)) return;
1553
+ const text = value === true ? "ON" : value === false ? "OFF" : "None";
1554
+ node.broker.client.publish(`${stateTopic}/boost`, text, { retain: true });
1555
+ }
1556
+
1557
+ // A set_boost that failed: warn, set boost_error and send it at once (a refusal forces
1558
+ // no poll), and put the HA switch back to the last known state so it re-syncs.
1559
+ function reportBoostFailure(enabled, rawError) {
1560
+ const label = enabled ? "Boost request" : "Boost cancel";
1561
+ // Masked and cut here, so boost_error keeps its contract whatever the caller passes.
1562
+ const error = truncate(rawError == null ? 'Unknown error' : rawError);
1563
+ node.warn(`${label} failed: ${error}`);
1564
+ boostError = error;
1565
+ boostErrorAt = Date.now();
1566
+ lastKnownState = mergePayload(lastKnownState, { boost_error: error });
1567
+ node.status({ fill: "red", shape: "ring", text: `${label} failed` });
1568
+ if (typeof boosting === 'boolean') publishBoostSwitch(boosting);
1569
+ if (enableMqtt && node.broker && node.broker.client) {
1570
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
1571
+ }
1572
+ // Tagged like the other extra messages (review L6), so a flow can tell it from a poll.
1573
+ node.send({
1574
+ payload: lastKnownState,
1575
+ debug: { timestamp: new Date().toISOString(), trigger: 'boost_failed', request: enabled ? 'BOOST' : 'CANCEL', error },
1576
+ });
1577
+ }
1578
+
1579
+ // Boost requests are serialised (sweep #2/#3, review F2): one updateBoostCharge in flight,
1580
+ // the latest requested value wins, a repeat of the value in flight (or just sent and
1581
+ // accepted) is dropped, and mutations are at least BOOST_SPACING_MS apart. A flood of ON/OFF messages
1582
+ // therefore makes only a few calls, and ON then OFF can never reach Octopus out of order.
1583
+ const BOOST_SPACING_MS = 5000;
1584
+ // A request still unanswered after this long is given up (review A1): a connection that
1585
+ // drops mid-answer can leave it pending for ever, and the queue would wait for ever too.
1586
+ // 2 x the 30 s request timeout (auth + mutation) plus a margin.
1587
+ const BOOST_WATCHDOG_MS = 75 * 1000;
1588
+ const boostQueue = { inFlight: null, pending: null, lastValue: null, lastOk: false, lastAt: 0, timer: null, watchdog: null };
1589
+ // Review A5: a flow or automation that asks again after every refusal would otherwise
1590
+ // send the same refused request every 5 s, all day, on the API key the polls use.
1591
+ // 3 refusals of one value in 10 minutes pause that value for 10 minutes (one warning).
1592
+ // An accepted request ends the pause.
1593
+ const BOOST_REFUSAL_LIMIT = 3;
1594
+ const BOOST_REFUSAL_WINDOW_MS = 10 * 60 * 1000;
1595
+ const BOOST_PAUSE_MS = 10 * 60 * 1000;
1596
+ let boostRefusals = { value: null, times: [] };
1597
+ let boostPause = null; // { value, until }
1598
+
1599
+ function noteBoostRefusal(enabled) {
1600
+ const now = Date.now();
1601
+ if (boostRefusals.value !== enabled) boostRefusals = { value: enabled, times: [] };
1602
+ boostRefusals.times = boostRefusals.times.filter((t) => now - t < BOOST_REFUSAL_WINDOW_MS);
1603
+ boostRefusals.times.push(now);
1604
+ if (boostRefusals.times.length < BOOST_REFUSAL_LIMIT) return;
1605
+ boostRefusals = { value: null, times: [] };
1606
+ boostPause = { value: enabled, until: now + BOOST_PAUSE_MS };
1607
+ const what = enabled ? "boost requests" : "boost cancels";
1608
+ node.warn(`Octopus refused ${BOOST_REFUSAL_LIMIT} ${what} in ${BOOST_REFUSAL_WINDOW_MS / 60000} minutes: ignoring further ${what} for ${BOOST_PAUSE_MS / 60000} minutes`);
1609
+ }
1610
+
1611
+ function clearBoostRefusals() {
1612
+ boostRefusals = { value: null, times: [] };
1613
+ boostPause = null;
1614
+ }
1615
+
1616
+ function requestBoost(enabled) {
1617
+ if (nodeClosed) return;
1618
+ const q = boostQueue;
1619
+ if (boostPause && boostPause.value === enabled) {
1620
+ if (Date.now() < boostPause.until) {
1621
+ // Paused after repeated refusals: ignored (the warning was logged once).
1622
+ if (typeof boosting === 'boolean' && boosting !== enabled) publishBoostSwitch(boosting);
1623
+ return;
1624
+ }
1625
+ boostPause = null;
1626
+ }
1627
+ if (q.inFlight !== null) {
1628
+ // Sent when the one in flight ends; asking for the in-flight value cancels it.
1629
+ q.pending = enabled === q.inFlight ? null : enabled;
1630
+ return;
1631
+ }
1632
+ // Already done and Octopus agrees (e.g. a flow sending set_boost true in a loop).
1633
+ // After a refusal, or once the boost has ended, the same value is sent again.
1634
+ const alreadyDone = enabled === q.lastValue && q.lastOk && boosting === enabled;
1635
+ const waitMs = q.lastAt + BOOST_SPACING_MS - Date.now();
1636
+ if (alreadyDone || waitMs > 0) {
1637
+ // The latest request wins: a repeat of the value just sent and accepted cancels a
1638
+ // waiting one and is dropped. After a failure the same value waits for the gap
1639
+ // and is sent again, instead of being dropped (review A9).
1640
+ const repeat = alreadyDone || (enabled === q.lastValue && q.lastOk);
1641
+ q.pending = repeat ? null : enabled;
1642
+ if (q.pending === null) {
1643
+ if (q.timer) { clearTimeout(q.timer); q.timer = null; }
1644
+ // The HA switch may show the tapped value: put it back to the known state.
1645
+ if (typeof boosting === 'boolean' && boosting !== enabled) publishBoostSwitch(boosting);
1646
+ } else if (!q.timer) {
1647
+ q.timer = setTimeout(sendPendingBoost, waitMs);
1648
+ }
1649
+ return;
1650
+ }
1651
+ sendBoost(enabled);
1652
+ }
1653
+
1654
+ function sendPendingBoost() {
1655
+ boostQueue.timer = null;
1656
+ const value = boostQueue.pending;
1657
+ boostQueue.pending = null;
1658
+ if (value !== null) requestBoost(value);
1659
+ }
1660
+
1661
+ function sendBoost(enabled) {
1662
+ const q = boostQueue;
1663
+ // This request replaces any one waiting for the gap (review A8): a late timer
1664
+ // must not send an older value after this newer one.
1665
+ if (q.timer) { clearTimeout(q.timer); q.timer = null; }
1666
+ q.pending = null;
1667
+ q.inFlight = enabled;
1668
+ q.lastValue = enabled;
1669
+ q.lastOk = false;
1670
+ q.lastAt = Date.now();
1671
+ // abandoned: the watchdog gave up on this request, so a late answer changes nothing.
1672
+ const call = { settled: false, abandoned: false };
1673
+ const done = (ok) => {
1674
+ if (call.settled) return;
1675
+ call.settled = true;
1676
+ if (q.watchdog) { clearTimeout(q.watchdog); q.watchdog = null; }
1677
+ q.lastOk = ok === true;
1678
+ q.inFlight = null;
1679
+ if (nodeClosed || q.pending === null) return;
1680
+ const value = q.pending;
1681
+ q.pending = null;
1682
+ requestBoost(value); // waits out the spacing if this one was quick
1683
+ };
1684
+ q.watchdog = setTimeout(() => {
1685
+ q.watchdog = null;
1686
+ if (call.settled || nodeClosed) return;
1687
+ call.abandoned = true;
1688
+ // The request may still have reached Octopus: report it, then poll to find out.
1689
+ reportBoostFailure(enabled, `No answer from Octopus after ${Math.round(BOOST_WATCHDOG_MS / 1000)}s`);
1690
+ requestChargingPoll();
1691
+ done(false);
1692
+ }, BOOST_WATCHDOG_MS);
1693
+ // A newer, different request is waiting: this answer must not move the switch.
1694
+ setBoost(enabled, call, () => q.pending !== null).then(done, () => done(false));
1695
+ }
1696
+
1697
+ // A forced charging poll also queries flexPlannedDispatches, so it goes through the same
1698
+ // rate window as the quick retries (review F2). Not allowed now: it runs when allowed.
1699
+ let deferredChargingPollAt = null;
1700
+
1701
+ function requestChargingPoll() {
1702
+ const now = Date.now();
1703
+ const allowedAt = dispatchRate.nextAllowedAt(now);
1704
+ if (allowedAt <= now) {
1705
+ deferredChargingPollAt = null;
1706
+ forceCategoryDue('intelligent');
1707
+ return;
1708
+ }
1709
+ if (deferredChargingPollAt === null) {
1710
+ node.log(`Charging poll after boost waits ${Math.ceil((allowedAt - now) / 1000)}s: 3 planned-dispatch queries already went out this minute`);
1711
+ }
1712
+ deferredChargingPollAt = allowedAt;
1713
+ }
1714
+
1715
+ // Called at the start of each tick, next to startDueChargingRetry.
1716
+ function startDeferredChargingPoll() {
1717
+ if (deferredChargingPollAt === null || Date.now() < deferredChargingPollAt) return;
1718
+ deferredChargingPollAt = null;
1719
+ requestChargingPoll();
1720
+ }
1721
+
1722
+ // Helper: Boost charge (charge now, outside the plan) or cancel a boost. Different from
1723
+ // setSmartCharging, which suspends/resumes Octopus control. Octopus may refuse (e.g. car
1724
+ // unplugged or full); its error is passed through, not second-guessed here.
1725
+ // Called through requestBoost only, so one runs at a time. Resolves true when Octopus
1726
+ // accepted the request and its answer was used.
1727
+ async function setBoost(enabled, call, isSuperseded) {
1728
+ const label = enabled ? "Boost request" : "Boost cancel";
1729
+ // Closed, or given up by the watchdog: a late answer changes nothing.
1730
+ const gone = () => nodeClosed || call.abandoned;
1731
+ const superseded = () => {
1732
+ if (!isSuperseded || !isSuperseded()) return false;
1733
+ node.log(`${label} answered, but a newer request follows: ignoring this answer`);
1734
+ return true;
1735
+ };
1736
+ const fail = (error) => reportBoostFailure(enabled, error);
1737
+ if (!krakenflexDeviceId) {
1738
+ fail("Device ID not available");
1739
+ return false;
1740
+ }
1741
+ try {
1742
+ node.status({ fill: "blue", shape: "dot", text: enabled ? "Requesting boost..." : "Cancelling boost..." });
1743
+ const token = await obtainTickToken();
1744
+ if (gone()) return false;
1745
+ const res = await graphqlPost(buildBoostRequest(krakenflexDeviceId, enabled), token);
1746
+ if (gone()) return false;
1747
+ metrics.recordPoll(250); // auth + mutation, same estimate as other mutations
1748
+ if (superseded()) {
1749
+ // This one may have changed the device; if the newer one is refused, only a
1750
+ // poll shows the real state (review A2).
1751
+ requestChargingPoll();
1752
+ return false;
1753
+ }
1754
+ const result = parseBoostResponse(res);
1755
+ if (!result.ok && result.unclear) {
1756
+ // Not clear whether it went through (review A2): do not flip the state or
1757
+ // report a refusal; a charging poll reads what Octopus really did.
1758
+ node.warn(`${label}: unclear answer from Octopus (${result.error}). Checking the boost state with a charging poll`);
1759
+ node.status({ fill: "yellow", shape: "ring", text: `${label}: checking` });
1760
+ if (typeof boosting === 'boolean') publishBoostSwitch(boosting); // re-sync HA
1761
+ requestChargingPoll();
1762
+ return false;
1763
+ }
1764
+ if (!result.ok) {
1765
+ // Octopus refused: nothing changed on the device, so no forced poll.
1766
+ fail(result.error);
1767
+ noteBoostRefusal(enabled);
1768
+ return false;
1769
+ }
1770
+ clearBoostRefusals();
1771
+ node.log(enabled ? "Boost requested" : "Boost cancelled");
1772
+ boostError = null;
1773
+ lastKnownState = mergePayload(lastKnownState, { boost_error: null });
1774
+ // Octopus accepted it, but its device state can lag behind (sweep #4): show the
1775
+ // requested state and hold it until a later poll agrees or BOOST_HOLD_MS passes,
1776
+ // so a stale read-back or poll cannot snap the switch back.
1777
+ const acceptedAt = Date.now();
1778
+ boostHold = { value: enabled, since: acceptedAt, until: acceptedAt + BOOST_HOLD_MS };
1779
+ if (typeof result.boosting === 'boolean' && result.boosting !== enabled) {
1780
+ node.log(`${label} accepted. Octopus still reports ${result.currentState}, so the switch stays ${enabled ? "on" : "off"} while it catches up`);
1781
+ }
1782
+ applyBoosting(enabled);
1783
+ node.status({ fill: "green", shape: "dot", text: enabled ? "Boost requested" : "Boost cancelled" });
1784
+ } catch (e) {
1785
+ if (gone()) return false;
1786
+ if (superseded()) {
1787
+ requestChargingPoll(); // it may still have reached Octopus
1788
+ return false;
1789
+ }
1790
+ // No answer (e.g. a timeout): the request may still have reached Octopus.
1791
+ fail(e.message);
1792
+ requestChargingPoll();
1793
+ return false;
1794
+ }
1795
+ requestChargingPoll(); // poll soon so device state, charging_now and slots update
1796
+ return true;
1797
+ }
1798
+
986
1799
  function scheduleSmartChargingVerification(expectedSuspended, intervals, index) {
1800
+ if (nodeClosed) return;
987
1801
  if (index >= intervals.length) {
1802
+ smartChargingVerifying = false; // the next charging poll reports the real state
988
1803
  node.warn("Smart charging state could not be confirmed after all retries");
989
1804
  node.status({ fill: "red", shape: "ring", text: "Smart charging: update unconfirmed" });
990
1805
  return;
@@ -995,6 +1810,7 @@ module.exports = function (RED) {
995
1810
  query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
996
1811
  variables: { input: { APIKey: apiKey } }
997
1812
  });
1813
+ if (nodeClosed) return;
998
1814
  if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
999
1815
  scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1000
1816
  return;
@@ -1005,13 +1821,14 @@ module.exports = function (RED) {
1005
1821
  query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1006
1822
  variables: { accountNumber: account }
1007
1823
  }, token);
1824
+ if (nodeClosed) return;
1008
1825
 
1009
1826
  if (deviceResponse.data.errors || !deviceResponse.data.data) {
1010
1827
  scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1011
1828
  return;
1012
1829
  }
1013
1830
 
1014
- const evDevice = (deviceResponse.data.data.devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES');
1831
+ const evDevice = intelligentCategory.extractEvDevice(deviceResponse.data.data.devices, preferredEvId);
1015
1832
  if (!evDevice) {
1016
1833
  scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1017
1834
  return;
@@ -1025,6 +1842,8 @@ module.exports = function (RED) {
1025
1842
  if (actualSuspended === expectedSuspended) {
1026
1843
  // Confirmed — clear remaining retries
1027
1844
  smartChargingSuspended = actualSuspended;
1845
+ smartChargingVerifying = false;
1846
+ publishSmartChargingState();
1028
1847
  smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1029
1848
  smartChargingRetryTimeouts = [];
1030
1849
  node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
@@ -1033,7 +1852,8 @@ module.exports = function (RED) {
1033
1852
  scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1034
1853
  }
1035
1854
  } catch (e) {
1036
- node.warn(`Smart charging verification attempt ${index + 1} failed: ${e.message}`);
1855
+ if (nodeClosed) return;
1856
+ node.warn(`Smart charging verification attempt ${index + 1} failed: ${short(e.message)}`);
1037
1857
  scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
1038
1858
  }
1039
1859
  }, intervals[index]);
@@ -1046,45 +1866,137 @@ module.exports = function (RED) {
1046
1866
  }
1047
1867
 
1048
1868
  // 6. Logic: Intelligent Poll (single-scheduler bespoke poll)
1049
- async function intelligentPoll(token) {
1869
+ async function intelligentPoll(token, isStale) {
1870
+ const pollStartedAt = Date.now();
1871
+ deferredChargingPollAt = null; // this poll covers a deferred one
1872
+ const prefsGenAtStart = prefsGen;
1050
1873
  // 1. devices query
1051
1874
  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;
1875
+ let devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
1876
+ // Closed or superseded while waiting: don't send the dispatch query.
1877
+ if (nodeClosed || (isStale && isStale())) throw new Error('Poll superseded');
1878
+ // The device status is non-null inside a non-null list, so an error on it (e.g.
1879
+ // KT-CT-4360) nulls the whole device list. Ask once more without the status: the
1880
+ // preferences, Charge Cap and device id still come through, and the Smart Charging
1881
+ // switch keeps its last value.
1882
+ let statusUnavailable = false;
1883
+ if (intelligentCategory.statusNulledDevices(devicesResponse.data.errors, devicesResponse.data.data)) {
1884
+ const statusCode = errorCode(devicesResponse.data.errors.find((e) => errorCode(e))) || null;
1885
+ const retry = intelligentCategory.buildDevicesQuery(account, false);
1886
+ devicesResponse = await graphqlPost({ query: retry.query, variables: retry.variables }, token);
1887
+ if (nodeClosed || (isStale && isStale())) throw new Error('Poll superseded');
1888
+ statusUnavailable = true;
1889
+ if (!statusWarned) {
1890
+ statusWarned = true;
1891
+ node.warn(`Smart charging state unavailable${statusCode ? ` (${statusCode})` : ''} - keeping the last value until Octopus returns it`);
1892
+ }
1893
+ }
1894
+ // An error on the Charge Cap field alone (KT-CT-4360 pattern) or on the preferences
1895
+ // (KT-CT-4339; the same resolver backs both aliases) must not stop the slot updates:
1896
+ // keep the last confirmed values and still read the dispatches.
1897
+ const devicesData = devicesResponse.data.data || null;
1898
+ const hasDeviceList = !!devicesData && Array.isArray(devicesData.devices);
1899
+ // The query lists every device on the account. An error on another one (an inverter,
1900
+ // a second charger) says nothing about the EV, so it is left out (review A11): it
1901
+ // must not freeze the EV's switch, preferences and boost state.
1902
+ const polledEv = hasDeviceList ? intelligentCategory.extractEvDevice(devicesData.devices, preferredEvId) : null;
1903
+ const evIndex = polledEv ? devicesData.devices.indexOf(polledEv) : -1;
1904
+ const isOtherDeviceError = (e) => evIndex !== -1 && Array.isArray(e && e.path)
1905
+ && e.path[0] === 'devices' && Number.isInteger(e.path[1]) && e.path[1] !== evIndex;
1906
+ const allDevicesErrors = Array.isArray(devicesResponse.data.errors) ? devicesResponse.data.errors : null;
1907
+ const evDevicesErrors = allDevicesErrors ? allDevicesErrors.filter((e) => !isOtherDeviceError(e)) : null;
1908
+ if (allDevicesErrors && evDevicesErrors.length < allDevicesErrors.length && !otherDeviceErrorLogged) {
1909
+ otherDeviceErrorLogged = true; // once: it can repeat every poll
1910
+ const other = allDevicesErrors.find(isOtherDeviceError);
1911
+ node.log(`Charging poll: Octopus could not read another device on the account (${truncate(graphqlError([other]).message, 120)}). Ignored: it does not affect the EV`);
1912
+ }
1913
+ const devicesErrors = allDevicesErrors
1914
+ ? (evDevicesErrors.length > 0 ? evDevicesErrors : undefined)
1915
+ : devicesResponse.data.errors;
1916
+ const fieldErrorsOnly = onlyDeviceFieldErrors(devicesErrors, devicesData, TOLERATED_DEVICE_FIELDS);
1917
+ // Device list itself missing, but only because of a tolerated field (for example a
1918
+ // KT-CT-4339 that nulled the list, or the status error again on the ask without it):
1919
+ // the cached id still works.
1920
+ const toleratedNoList = !!devicesErrors && !hasDeviceList && !!krakenflexDeviceId
1921
+ && Array.isArray(devicesErrors) && devicesErrors.length > 0
1922
+ && devicesErrors.every((e) => errorCode(e) === PREFERENCES_ERROR_CODE
1923
+ || (Array.isArray(e.path) && e.path[0] === 'devices' && TOLERATED_DEVICE_FIELDS.includes(e.path[2])));
1924
+ if (devicesErrors && !fieldErrorsOnly && !toleratedNoList) throw graphqlError(devicesErrors, 'Devices query failed');
1925
+ if (!devicesData) throw new Error('Devices response missing data');
1926
+ const fieldFailed = (f) => toleratedNoList
1927
+ || (fieldErrorsOnly && devicesErrors.some((e) => e.path[2] === f));
1928
+ const prefsFailed = fieldFailed('preferences');
1929
+ const chargeCapFailed = fieldFailed('chargeCap');
1930
+ // smartStatus carries isSuspended and currentState (boosting, device_state); both unknown
1931
+ // when the status errored or the poll asked again without it.
1932
+ const smartStatusFailed = statusUnavailable || fieldFailed('smartStatus');
1933
+ const suspended = hasDeviceList && !smartStatusFailed
1934
+ ? intelligentCategory.extractSuspended(devicesData.devices, preferredEvId) : null;
1935
+ if (!statusUnavailable && suspended !== null) statusWarned = false; // read again: warn on the next streak
1936
+ let deviceId = krakenflexDeviceId;
1937
+ if (hasDeviceList) {
1938
+ if (!polledEv) throw new Error('No ELECTRIC_VEHICLES device found on account');
1939
+ deviceId = polledEv.id;
1940
+ krakenflexDeviceId = deviceId;
1941
+ }
1062
1942
 
1063
1943
  // 2. dispatches query (the single one that used to be duplicated by V1 + V2)
1064
- const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
1944
+ const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(deviceId);
1945
+ noteDispatchQuery();
1065
1946
  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)}`);
1947
+ if (dispatchResponse.data.errors) throw graphqlError(dispatchResponse.data.errors, 'Dispatches query failed');
1067
1948
  if (!dispatchResponse.data.data) throw new Error('Dispatches response missing data');
1068
1949
 
1069
1950
  // 3. parse twice — intelligent (slots/window) + flex-planned-dispatches (array/count)
1070
- const data = { devices: devicesData.devices, flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
1951
+ const data = { devices: hasDeviceList ? devicesData.devices : [], flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
1071
1952
  const appliedTz = resolveTimezone(node);
1072
1953
  const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (e) { return 'UTC'; } })();
1073
- const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
1954
+ const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz, evId: preferredEvId });
1074
1955
  const { _activeSlots, ...catPublic } = catResult;
1075
1956
  if (chargeCapFailed) delete catPublic.charge_cap; // unknown this poll: keep the last value
1957
+ if (prefsFailed) {
1958
+ // parseResponse fell back to defaults: keep the last confirmed schedule instead.
1959
+ delete catPublic.confirmed_limit;
1960
+ delete catPublic.confirmed_time;
1961
+ }
1962
+ if (smartStatusFailed || catPublic.boosting === null) delete catPublic.boosting; // unknown: keep the last value
1963
+ if (smartStatusFailed || catPublic.device_state === null) delete catPublic.device_state; // same source as boosting
1076
1964
  const flexResult = flexPlannedDispatchesCategory.parseResponse(dispatchResponse.data.data);
1077
1965
 
1966
+ // A late answer from a closed node or a superseded poll must not reset timers.
1967
+ if (nodeClosed || (isStale && isStale())) throw new Error('Poll superseded');
1968
+
1969
+ // A change was sent or confirmed while this poll waited: its target, ready-by time
1970
+ // and Charge Cap are older than that. Keep the dispatches, drop those values and read
1971
+ // again on the next tick.
1972
+ const prefsStale = prefsGen !== prefsGenAtStart;
1973
+ if (prefsStale) {
1974
+ delete catPublic.confirmed_limit;
1975
+ delete catPublic.confirmed_time;
1976
+ delete catPublic.charge_cap;
1977
+ forceCategoryDue('intelligent');
1978
+ }
1979
+
1078
1980
  // 4. metrics + side effects
1981
+ noteChargingPollSuccess();
1079
1982
  metrics.recordPoll(300);
1080
- confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
1081
- confirmedTime = catResult.confirmed_time || confirmedTime;
1082
- if (!validationMode) {
1983
+ if (!prefsFailed && !prefsStale) {
1984
+ confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
1985
+ confirmedTime = catResult.confirmed_time || confirmedTime;
1986
+ }
1987
+ if (!validationMode && !prefsStale) {
1083
1988
  pendingLimit = confirmedLimit;
1084
1989
  pendingTime = confirmedTime;
1085
1990
  }
1086
- if (chargeCapFailed) {
1087
- node.warn("Charge Cap state unavailable this poll — keeping the last known value");
1991
+ if (prefsFailed) {
1992
+ // One line covers both aliases (they share the preferences resolver).
1993
+ const code = errorCode(devicesErrors[0]);
1994
+ node.warn(`Charging preferences unavailable this poll${code ? ` (${code})` : ''} - keeping ${confirmedLimit}% @ ${confirmedTime}`);
1995
+ }
1996
+ if (prefsStale) {
1997
+ // The Charge Cap switch keeps what the newer change set.
1998
+ } else if (chargeCapFailed) {
1999
+ if (!prefsFailed) node.warn("Charge Cap state unavailable this poll — keeping the last known value");
1088
2000
  } else if (typeof catResult.charge_cap === 'boolean') {
1089
2001
  if (enableMqtt && node.broker && node.broker.client) {
1090
2002
  node.broker.client.publish(`${stateTopic}/charge_cap`, catResult.charge_cap ? "ON" : "OFF", { retain: true });
@@ -1093,16 +2005,42 @@ module.exports = function (RED) {
1093
2005
  chargeCapNaWarned = true;
1094
2006
  node.warn("Charge Cap not applicable for this device — switch will show unknown");
1095
2007
  }
1096
- setupChargingTimers(_activeSlots);
2008
+ // Smart charging changed outside the node (e.g. in the Octopus app). A toggle still
2009
+ // waiting for confirmation wins: Octopus can report the old state for a while.
2010
+ if (suspended !== null && !smartChargingVerifying) {
2011
+ smartChargingSuspended = suspended;
2012
+ publishSmartChargingState();
2013
+ }
2014
+ if (typeof catPublic.boosting === 'boolean') {
2015
+ // The device state was read: an old boost refusal no longer applies.
2016
+ if (boostError !== null && pollStartedAt >= boostErrorAt + BOOST_ERROR_CLEAR_MS) boostError = null;
2017
+ // A set_boost Octopus accepted is held until a poll sent after it agrees, or
2018
+ // until BOOST_HOLD_MS has passed; then the poll wins (as smartChargingVerifying).
2019
+ if (boostHold) {
2020
+ const agrees = catPublic.boosting === boostHold.value;
2021
+ if (agrees && pollStartedAt >= boostHold.since) {
2022
+ boostHold = null;
2023
+ } else if (Date.now() >= boostHold.until) {
2024
+ if (!agrees) node.log(`Octopus still reports boosting=${catPublic.boosting} ${Math.round(BOOST_HOLD_MS / 60000)} min after the boost change: showing what Octopus reports`);
2025
+ boostHold = null;
2026
+ } else {
2027
+ catPublic.boosting = boostHold.value;
2028
+ }
2029
+ }
2030
+ boosting = catPublic.boosting;
2031
+ boostingConfirmedAt = Date.now();
2032
+ publishBoostSwitch(boosting);
2033
+ }
2034
+ checkUnconfirmedWrites(catResult.charge_cap, !prefsFailed && !prefsStale, !chargeCapFailed && !prefsStale);
2035
+ setupChargingTimers(_activeSlots); // charging_now = slot active OR boosting
1097
2036
  if (!stateCheckInterval) startStateReconciliation();
1098
2037
  updateNextPollTime();
1099
2038
 
1100
2039
  const apiMetrics = metrics.getMetrics();
1101
2040
 
1102
- // 5. merged partial payload
1103
- return Object.assign({}, catPublic, flexResult, {
1104
- pending_limit: pendingLimit,
1105
- pending_time: pendingTime,
2041
+ // 5. merged partial payload (no pending values from a poll whose preferences are stale)
2042
+ const pending = prefsStale ? {} : { pending_limit: pendingLimit, pending_time: pendingTime };
2043
+ return Object.assign({}, catPublic, flexResult, pending, {
1106
2044
  charging_now: chargingNow,
1107
2045
  next_poll: nextPollTime,
1108
2046
  next_poll_raw: nextPollTime,
@@ -1113,6 +2051,7 @@ module.exports = function (RED) {
1113
2051
  timezone_detected: serverTz,
1114
2052
  timezone_applied: appliedTz,
1115
2053
  smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
2054
+ boost_error: boostError,
1116
2055
  });
1117
2056
  }
1118
2057
 
@@ -1124,6 +2063,7 @@ module.exports = function (RED) {
1124
2063
  query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1125
2064
  variables: { input: { APIKey: apiKey } }
1126
2065
  });
2066
+ if (nodeClosed) return; // closed while waiting: send nothing more
1127
2067
  if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1128
2068
  throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1129
2069
  }
@@ -1133,54 +2073,86 @@ module.exports = function (RED) {
1133
2073
  query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
1134
2074
  variables: { accountNumber: account }
1135
2075
  }, token);
2076
+ if (nodeClosed) return; // closed while waiting: no publish, no log
1136
2077
 
1137
2078
  if (deviceResponse.data.errors || !deviceResponse.data.data) {
1138
2079
  throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
1139
2080
  }
1140
2081
 
1141
- function extractEvDevice(devices) {
1142
- return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
1143
- }
1144
-
1145
- const evDevice = extractEvDevice(deviceResponse.data.data.devices);
2082
+ const evDevice = intelligentCategory.extractEvDevice(deviceResponse.data.data.devices, preferredEvId);
1146
2083
  if (!evDevice) {
1147
2084
  throw new Error('No ELECTRIC_VEHICLES device found on account');
1148
2085
  }
1149
2086
 
1150
2087
  krakenflexDeviceId = evDevice.id;
1151
- smartChargingSuspended = evDevice.status.isSuspended;
2088
+ if (evDevice.status && typeof evDevice.status.isSuspended === 'boolean') {
2089
+ smartChargingSuspended = evDevice.status.isSuspended;
2090
+ publishSmartChargingState();
2091
+ }
1152
2092
  node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
1153
2093
  } catch (e) {
1154
- node.warn(`Failed to fetch device ID at startup: ${e.message}. Smart charging toggle unavailable.`);
1155
- krakenflexDeviceId = null;
1156
- smartChargingSuspended = null;
2094
+ if (nodeClosed) return;
2095
+ // Keep whatever discovery or a charging poll has found meanwhile.
2096
+ node.warn(`Failed to fetch device ID at startup: ${short(e.message)}. Smart charging toggle unavailable until the first charging poll.`);
1157
2097
  }
1158
2098
  }
1159
2099
 
1160
2100
  // 6a. Charging Now - Timer Management Functions
1161
2101
 
1162
2102
  // State reconciliation - checks every 10s if charging state matches reality
2103
+ // A boost counts as charging, so it is never corrected back to false (lib/boost.js).
1163
2104
  function reconcileChargingState() {
1164
- if (!cachedSlots || cachedSlots.length === 0) return;
2105
+ expireStaleBoosting();
2106
+ const shouldBeCharging = reconcileChargingNow({ slots: cachedSlots, boosting, chargingNow });
2107
+ if (shouldBeCharging !== null) {
2108
+ node.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
2109
+ publishChargingState(shouldBeCharging);
2110
+ }
2111
+ }
1165
2112
 
1166
- const now = new Date();
2113
+ // Sweep #5: boosting is only as good as the last time Octopus confirmed it. With no
2114
+ // confirmation for 2 charging-poll intervals (an outage, repeated status errors) it is
2115
+ // unknown, so a boost that ended long ago cannot hold charging_now on for ever.
2116
+ function boostingTtlMs() {
2117
+ const cat = categories.find((c) => c.id === 'intelligent');
2118
+ return 2 * (cat ? cat.intervalMs : refreshRate);
2119
+ }
1167
2120
 
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
- });
2121
+ function expireStaleBoosting() {
2122
+ if (boosting === null || !boostingConfirmedAt) return;
2123
+ const age = Date.now() - boostingConfirmedAt;
2124
+ if (age <= boostingTtlMs()) return;
2125
+ const text = `Boost state not confirmed by Octopus for ${formatDuration(age)}: treating it as unknown`;
2126
+ if (boosting === true) node.warn(text); else node.log(text);
2127
+ boosting = null;
2128
+ boostHold = null;
2129
+ lastKnownState = mergePayload(lastKnownState, { boosting: null });
2130
+ // The HA Boost switch shows unknown too, not its last ON or OFF (review A7).
2131
+ publishBoostSwitch(null);
2132
+ const shouldBeCharging = chargingNowFor(cachedSlots, null);
2133
+ if (shouldBeCharging !== chargingNow) publishChargingState(shouldBeCharging);
2134
+ }
1174
2135
 
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);
2136
+ // Saving session / free electricity / current rate flags change at their start and end
2137
+ // times, not when the category is polled. Recompute them from the stored data (no API
2138
+ // call) and publish only when a value changed.
2139
+ function refreshActiveFields() {
2140
+ if (nodeClosed) return;
2141
+ const changed = changedActiveFields(lastKnownState, Date.now());
2142
+ if (!changed) return;
2143
+ lastKnownState = mergePayload(lastKnownState, changed);
2144
+ if (enableMqtt && node.broker && node.broker.client) {
2145
+ node.broker.client.publish(stateTopic, stateJson(lastKnownState), { retain: true });
1179
2146
  }
2147
+ node.send({
2148
+ payload: lastKnownState,
2149
+ debug: { timestamp: new Date().toISOString(), trigger: 'active_fields_change', changed: Object.keys(changed) },
2150
+ });
1180
2151
  }
1181
2152
 
1182
2153
  // Start state reconciliation loop (every 10 seconds)
1183
2154
  function startStateReconciliation() {
2155
+ if (nodeClosed) return; // a late callback must not leave an interval on a closed node
1184
2156
  // Clear existing interval
1185
2157
  if (stateCheckInterval) {
1186
2158
  clearInterval(stateCheckInterval);
@@ -1189,6 +2161,7 @@ module.exports = function (RED) {
1189
2161
  // Check state every 10 seconds
1190
2162
  stateCheckInterval = setInterval(() => {
1191
2163
  reconcileChargingState();
2164
+ refreshActiveFields();
1192
2165
  }, 10000);
1193
2166
 
1194
2167
  node.log("State reconciliation loop started (every 10s)");
@@ -1247,7 +2220,7 @@ module.exports = function (RED) {
1247
2220
  ...lastKnownState,
1248
2221
  refresh_available_at: getRefreshAvailableAt()
1249
2222
  };
1250
- node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: true });
2223
+ node.broker.client.publish(stateTopic, stateJson(fullState), { retain: true });
1251
2224
  }
1252
2225
  }
1253
2226
 
@@ -1256,15 +2229,22 @@ module.exports = function (RED) {
1256
2229
  nextPollTime = new Date(Date.now() + refreshRate).toISOString();
1257
2230
  }
1258
2231
 
2232
+ // Retained charging_now topic for the Home Assistant binary_sensor
2233
+ function publishChargingNowTopic(state) {
2234
+ chargingNowPublished = true;
2235
+ if (enableMqtt && node.broker && node.broker.client) {
2236
+ node.broker.client.publish(`${stateTopic}/charging_now`, state ? "ON" : "OFF", { retain: true });
2237
+ }
2238
+ }
2239
+
1259
2240
  // Publish charging state to MQTT and Node-RED
1260
2241
  function publishChargingState(state) {
1261
2242
  chargingNow = state;
2243
+ // Keep the JSON state in step, so every later message and publish carries it.
2244
+ lastKnownState = mergePayload(lastKnownState, { charging_now: state });
1262
2245
 
1263
2246
  // 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
- }
2247
+ publishChargingNowTopic(state);
1268
2248
 
1269
2249
  // Output message to Node-RED flow if state actually changed
1270
2250
  if (lastSentChargingState !== state) {
@@ -1293,6 +2273,7 @@ module.exports = function (RED) {
1293
2273
 
1294
2274
  // Setup pre-validation timer (30s before slot starts)
1295
2275
  function setupPreValidationTimer(nextSlot) {
2276
+ if (nodeClosed) return;
1296
2277
  const now = new Date();
1297
2278
  const slotStart = new Date(nextSlot.start);
1298
2279
  const preValidationTime = slotStart.getTime() - 30000; // 30s before
@@ -1300,6 +2281,7 @@ module.exports = function (RED) {
1300
2281
 
1301
2282
  if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
1302
2283
  preValidationTimer = setTimeout(async () => {
2284
+ if (nodeClosed) return;
1303
2285
  node.warn("Pre-validating slot data (30s before start)");
1304
2286
  try {
1305
2287
  if (!krakenflexDeviceId) {
@@ -1311,6 +2293,7 @@ module.exports = function (RED) {
1311
2293
  variables: { input: { APIKey: apiKey } }
1312
2294
  });
1313
2295
 
2296
+ if (nodeClosed) return;
1314
2297
  if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1315
2298
  throw new Error("Pre-validation auth failed");
1316
2299
  }
@@ -1318,36 +2301,45 @@ module.exports = function (RED) {
1318
2301
  const token = authResponse.data.data.obtainKrakenToken.token;
1319
2302
 
1320
2303
  const { query: dq, variables: dv } = intelligentCategory.buildDispatchQuery(krakenflexDeviceId);
2304
+ noteDispatchQuery(); // counts toward the retry rate limit
1321
2305
  const dataResponse = await graphqlPost({ query: dq, variables: dv }, token);
2306
+ if (nodeClosed) return;
2307
+ // Kraken fails with HTTP 200, GraphQL errors and null data (e.g. KT-CT-4340):
2308
+ // a failed check, so fall back to the cached slot below.
2309
+ if (dataResponse.data.errors) throw graphqlError(dataResponse.data.errors, 'Dispatches query failed');
2310
+ if (!dataResponse.data.data || !dataResponse.data.data.flexPlannedDispatches) {
2311
+ throw new Error('Dispatches response missing data');
2312
+ }
1322
2313
 
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
- }
2314
+ const freshSlots = dataResponse.data.data.flexPlannedDispatches;
2315
+ // Octopus re-planned since the last poll: poll now so the slot/window
2316
+ // sensors match what charging_now is about to do.
2317
+ if (intelligentCategory.slotsChanged(cachedSlots, freshSlots)) {
2318
+ node.warn("Charging plan changed since last poll - refreshing");
2319
+ forceCategoryDue('intelligent');
2320
+ }
2321
+ cachedSlots = freshSlots;
2322
+
2323
+ // Record pre-validation API usage (auth + simple query = ~200 complexity)
2324
+ const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
2325
+ metrics.recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
2326
+
2327
+ // Check if slot still exists (within 1 minute tolerance)
2328
+ const stillExists = cachedSlots.find(s =>
2329
+ Math.abs(new Date(s.start).getTime() - slotStart.getTime()) < 60000
2330
+ );
2331
+
2332
+ if (stillExists) {
2333
+ node.warn(`Slot confirmed at ${stillExists.start}`);
2334
+ setupSlotStartTimer(stillExists);
2335
+ } else {
2336
+ // Cancel the start timer armed from the known plan.
2337
+ if (slotStartTimer) { clearTimeout(slotStartTimer); slotStartTimer = null; }
2338
+ node.warn("Slot was cancelled or modified - not setting start timer");
1348
2339
  }
1349
2340
  } catch (error) {
1350
- node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
2341
+ if (nodeClosed) return;
2342
+ node.warn(`Pre-validation failed: ${short(error.message)}, using cached slot`);
1351
2343
  // Fallback: use original slot data
1352
2344
  setupSlotStartTimer(nextSlot);
1353
2345
  }
@@ -1355,6 +2347,10 @@ module.exports = function (RED) {
1355
2347
 
1356
2348
  const minutesUntil = Math.round(msUntilPreValidation / 60000);
1357
2349
  node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
2350
+ // Arm the start from the known plan now. Pre-validation makes two requests of up to
2351
+ // 30 s each; if they are still running at the slot start, the slot starts on time
2352
+ // anyway. Pre-validation then moves the timer (slot confirmed) or cancels it.
2353
+ setupSlotStartTimer(nextSlot);
1358
2354
  } else if (msUntilPreValidation <= 0 && slotStart.getTime() > now.getTime()) {
1359
2355
  // Polled inside the last 30s (e.g. the refresh after a re-plan): the data is
1360
2356
  // already fresh, so set the start timer directly instead of losing it.
@@ -1364,6 +2360,7 @@ module.exports = function (RED) {
1364
2360
 
1365
2361
  // Setup slot start timer (exact start time)
1366
2362
  function setupSlotStartTimer(slot) {
2363
+ if (nodeClosed) return;
1367
2364
  // A poll and an in-flight pre-validation can both set this; never leave an orphan.
1368
2365
  if (slotStartTimer) { clearTimeout(slotStartTimer); slotStartTimer = null; }
1369
2366
  const now = new Date();
@@ -1383,7 +2380,8 @@ module.exports = function (RED) {
1383
2380
  // Slot already started, check if it's still active
1384
2381
  const slotEnd = new Date(slot.end);
1385
2382
  if (slotEnd > now) {
1386
- publishChargingState(true);
2383
+ // Already on when the start timer armed from the known plan has fired.
2384
+ if (!chargingNow) publishChargingState(true);
1387
2385
  setupSlotEndTimer(slot);
1388
2386
  }
1389
2387
  }
@@ -1391,6 +2389,7 @@ module.exports = function (RED) {
1391
2389
 
1392
2390
  // Setup slot end timer (exact end time)
1393
2391
  function setupSlotEndTimer(slot) {
2392
+ if (nodeClosed) return;
1394
2393
  if (slotEndTimer) { clearTimeout(slotEndTimer); slotEndTimer = null; }
1395
2394
  const now = new Date();
1396
2395
  const slotEnd = new Date(slot.end);
@@ -1413,7 +2412,7 @@ module.exports = function (RED) {
1413
2412
  publishChargingState(true);
1414
2413
  setupSlotEndTimer(immediateNextSlot);
1415
2414
  } else {
1416
- publishChargingState(false);
2415
+ publishChargingState(boosting === true); // a boost keeps charging_now on
1417
2416
  }
1418
2417
  }, msUntilEnd);
1419
2418
 
@@ -1424,6 +2423,7 @@ module.exports = function (RED) {
1424
2423
 
1425
2424
  // Main timer setup - called on each poll
1426
2425
  function setupChargingTimers(slots) {
2426
+ if (nodeClosed) return;
1427
2427
  // Clear existing timers
1428
2428
  clearChargingTimers();
1429
2429
 
@@ -1448,10 +2448,13 @@ module.exports = function (RED) {
1448
2448
  setupSlotEndTimer(activeSlot);
1449
2449
  node.log("Currently charging - end timer set");
1450
2450
  } else {
1451
- // Not currently charging
1452
- const newState = false;
2451
+ // No slot active: charging only if a boost is running
2452
+ const newState = boosting === true;
1453
2453
  if (chargingNow !== newState) {
1454
2454
  publishChargingState(newState);
2455
+ } else if (!chargingNowPublished) {
2456
+ // First poll since start: overwrite a retained ON left from before a restart.
2457
+ publishChargingNowTopic(newState);
1455
2458
  }
1456
2459
 
1457
2460
  // Find next future slot
@@ -1478,7 +2481,7 @@ module.exports = function (RED) {
1478
2481
  confirmed_limit: confirmedLimit,
1479
2482
  confirmed_time: confirmedTime
1480
2483
  };
1481
- node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: false });
2484
+ node.broker.client.publish(stateTopic, stateJson(fullState), { retain: false });
1482
2485
  }
1483
2486
  }
1484
2487
 
@@ -1499,6 +2502,7 @@ module.exports = function (RED) {
1499
2502
  }
1500
2503
  else if (a.type === 'smart_charging') setSmartCharging(a.enabled);
1501
2504
  else if (a.type === 'charge_cap') setChargeCap(a.enabled);
2505
+ else if (a.type === 'boost') requestBoost(a.enabled);
1502
2506
  }
1503
2507
  if (plan.hasCommand) return; // commands never trigger a manual refresh
1504
2508
  }
@@ -1515,8 +2519,28 @@ module.exports = function (RED) {
1515
2519
  if (enableMqtt && node.broker) {
1516
2520
  node.broker.register(this);
1517
2521
 
2522
+ // Subscribe with this node's id as the ref so close can remove exactly these
2523
+ // subscriptions (Node-RED broker API: subscribe(topic, options, callback, ref)).
2524
+ const subscribeCommand = (topic, callback) => node.broker.subscribe(topic, 0, callback, node.id);
2525
+
2526
+ // Action commands (they write to Octopus or force a poll) ignore retained messages.
2527
+ // The broker replays a retained message on every restart, redeploy and reconnect, so
2528
+ // a retained ON on set_boost would boost again each time. Home Assistant publishes
2529
+ // these without retain; a live publish reaches the node with the retain flag off.
2530
+ const retainedWarned = new Set();
2531
+ const subscribeAction = (topic, callback) => subscribeCommand(topic, (t, payload, packet) => {
2532
+ if (packet && packet.retain === true) {
2533
+ if (!retainedWarned.has(topic)) {
2534
+ retainedWarned.add(topic);
2535
+ node.warn(`Ignored a retained message on ${topic}. Commands are never taken from retained messages. Clear it by publishing an empty retained message to that topic.`);
2536
+ }
2537
+ return;
2538
+ }
2539
+ callback(t, payload, packet);
2540
+ });
2541
+
1518
2542
  // Slider changed - update pending value only
1519
- node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
2543
+ subscribeCommand(cmdTopicLimit, (topic, payload) => {
1520
2544
  const r = validateLimit(payload.toString());
1521
2545
  if (!r.ok) {
1522
2546
  node.warn(r.error);
@@ -1529,7 +2553,7 @@ module.exports = function (RED) {
1529
2553
  });
1530
2554
 
1531
2555
  // Dropdown changed - update pending value only
1532
- node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
2556
+ subscribeCommand(cmdTopicTime, (topic, payload) => {
1533
2557
  const r = validateTime(payload.toString());
1534
2558
  if (!r.ok) {
1535
2559
  node.warn(r.error);
@@ -1542,12 +2566,12 @@ module.exports = function (RED) {
1542
2566
  });
1543
2567
 
1544
2568
  // Button pressed - submit changes to API
1545
- node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
2569
+ subscribeAction(cmdTopicSubmit, (topic, payload) => {
1546
2570
  setPreferences(pendingLimit, pendingTime);
1547
2571
  });
1548
2572
 
1549
2573
  // Refresh button pressed - MQTT has hardcoded 30s rate limiting
1550
- node.broker.subscribe(cmdTopicRefresh, 0, (topic, payload) => {
2574
+ subscribeAction(cmdTopicRefresh, (topic, payload) => {
1551
2575
  // Check rate limit (only for MQTT button)
1552
2576
  if (!canManualRefresh()) {
1553
2577
  const secondsRemaining = getSecondsUntilNextRefresh();
@@ -1580,54 +2604,59 @@ module.exports = function (RED) {
1580
2604
  });
1581
2605
 
1582
2606
  // 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 });
2607
+ subscribeCommand(cmdTopicTimezone, (topic, payload) => {
2608
+ const text = payload.toString();
2609
+ if (text.trim().length === 0) return; // empty: ignored
2610
+ const r = validateTimezone(text);
2611
+ if (!r.ok) {
2612
+ node.error(r.error); // nothing stored or published
2613
+ return;
1589
2614
  }
2615
+ node.context().set('timezone', r.timezone);
2616
+ node.log(`Timezone set via MQTT to: ${r.timezone}`);
2617
+ node.broker.client.publish(`${stateTopic}/timezone`, r.timezone, { retain: true });
1590
2618
  });
1591
2619
 
1592
2620
  // Smart charging switch toggled in Home Assistant
1593
- node.broker.subscribe(cmdTopicSmartCharging, 0, (topic, payload) => {
2621
+ subscribeAction(cmdTopicSmartCharging, (topic, payload) => {
1594
2622
  const val = payload.toString().trim();
1595
2623
  if (val === "ON") setSmartCharging(true);
1596
2624
  else if (val === "OFF") setSmartCharging(false);
1597
2625
  });
1598
2626
 
1599
2627
  // Charge Cap switch toggled in HA
1600
- node.broker.subscribe(cmdTopicChargeCap, 0, (topic, payload) => {
2628
+ subscribeAction(cmdTopicChargeCap, (topic, payload) => {
1601
2629
  const val = payload.toString().trim();
1602
2630
  if (val === "ON") setChargeCap(true);
1603
2631
  else if (val === "OFF") setChargeCap(false);
1604
2632
  });
1605
2633
 
1606
- initTimeoutHandles.push(setTimeout(announceControls, 2000));
2634
+ // Boost Charge switch toggled in HA
2635
+ subscribeAction(cmdTopicBoost, (topic, payload) => {
2636
+ const val = payload.toString().trim();
2637
+ if (val === "ON") requestBoost(true);
2638
+ else if (val === "OFF") requestBoost(false);
2639
+ else node.warn(`Ignored set_boost command '${truncate(val, 40)}': send ON or OFF`);
2640
+ });
2641
+
2642
+ initTimeout(announceControls, 2000);
1607
2643
 
1608
2644
  // Republish persisted timezone to HA select on startup
1609
- initTimeoutHandles.push(setTimeout(() => {
2645
+ initTimeout(() => {
1610
2646
  try {
1611
2647
  const persistedTz = node.context().get('timezone');
1612
2648
  if (persistedTz && node.broker) {
1613
2649
  node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
1614
2650
  }
1615
2651
  } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
1616
- }, 2500));
2652
+ }, 2500);
1617
2653
 
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));
2654
+ // The smart charging switch state is published by the startup device fetch,
2655
+ // discovery and every charging poll as soon as each one knows it.
1627
2656
  }
1628
2657
 
1629
2658
  // Init
1630
- initTimeoutHandles.push(setTimeout(fetchDeviceId, 1500));
2659
+ initTimeout(fetchDeviceId, 1500);
1631
2660
 
1632
2661
  // V2 category discovery and scheduler. Retries with backoff until discovery succeeds
1633
2662
  // (a transient Kraken error at startup used to leave the node with no scheduler until
@@ -1636,40 +2665,128 @@ module.exports = function (RED) {
1636
2665
  async function startV2(attempt) {
1637
2666
  if (nodeClosed) return;
1638
2667
  try {
1639
- const discovered = await discoverProducts(apiKey, account);
2668
+ const discovered = await discoverProducts(apiKey, account, { isClosed: () => nodeClosed });
1640
2669
  if (nodeClosed) return;
1641
- if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
1642
- smartChargingSuspended = discovered.deviceSuspended;
1643
- lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
1644
- }
2670
+ applyDiscoveredSuspended(discovered);
1645
2671
  await initCategories(discovered);
1646
2672
  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);
2673
+ announceSmartflexEntities(discovered);
2674
+ node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}, vehicle=${!!discovered.vehicleDeviceId}, inverter=${!!discovered.inverterDeviceId}${discovered.inverterDeviceId && config.enableSmartflexInverter !== true ? ' (inverter option off)' : ''}`);
2675
+ const v2Scheduler = createScheduler(pollDueCategories, {
2676
+ onStuck: (ms) => node.warn(`Poll still running after ${Math.round(ms / 1000)}s - starting a new poll`),
2677
+ });
1649
2678
  v2Scheduler.start();
1650
2679
  node._v2Scheduler = v2Scheduler;
2680
+ // The 10 s tick also keeps the "active now" fields current, so run it on
2681
+ // accounts without a charger too (the charging poll restarts it with its timers).
2682
+ if (!stateCheckInterval) startStateReconciliation();
2683
+ // An empty device list can be transient: check again before giving up on a charger.
2684
+ if (!discovered.hasIntelligent && discovered.deviceCount === 0) scheduleDeviceCheck(0);
1651
2685
  } catch (e) {
1652
2686
  if (nodeClosed) return;
1653
2687
  const delay = discoveryRetryDelay(attempt);
1654
2688
  const secs = Math.round(delay / 1000);
1655
- node.warn(`V2 discovery failed: ${e.message}. Retrying in ${secs}s.`);
2689
+ node.warn(`V2 discovery failed: ${short(e.message)}. Retrying in ${secs}s.`);
1656
2690
  node.status({ fill: "yellow", shape: "ring", text: `Discovery failed — retrying in ${secs}s` });
1657
- initTimeoutHandles.push(setTimeout(() => startV2(attempt + 1), delay));
2691
+ initTimeout(() => startV2(attempt + 1), delay);
2692
+ }
2693
+ }
2694
+ initTimeout(() => startV2(0), 2000);
2695
+
2696
+ function applyDiscoveredSuspended(discovered) {
2697
+ // The EV discovery chose (the LIVE one when several are listed): later polls read it.
2698
+ preferredEvId = discovered.deviceId || null;
2699
+ // The startup device fetch can fail (it has no tolerance for a status error) and so
2700
+ // can the first charging poll. Discovery found the device: the switch, Charge Cap and
2701
+ // preference writes can use it until a charging poll reads it again. It also replaces
2702
+ // an id the startup fetch found: that fetch runs before preferredEvId is known and
2703
+ // takes the first EV listed, which can be a RETIRED one.
2704
+ if (discovered.deviceId) krakenflexDeviceId = discovered.deviceId;
2705
+ // Discovery had to ask again without the device status: one warning, shared with the
2706
+ // charging poll's, until the state is read again.
2707
+ if (discovered.statusErrorCode !== undefined && !statusWarned && !nodeClosed) {
2708
+ statusWarned = true;
2709
+ const code = discovered.statusErrorCode;
2710
+ node.warn(`Smart charging state unavailable${code ? ` (${code})` : ''} - keeping the last value until Octopus returns it`);
2711
+ }
2712
+ if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
2713
+ smartChargingSuspended = discovered.deviceSuspended;
2714
+ lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
2715
+ publishSmartChargingState();
2716
+ }
2717
+ }
2718
+
2719
+ // Discovery found no devices at all (devices: []), which can be transient. Check again
2720
+ // on the discovery retry delays, at most EMPTY_DEVICES_MAX_RETRIES times. `done` is the
2721
+ // number of checks made so far. The other categories keep polling meanwhile.
2722
+ function scheduleDeviceCheck(done) {
2723
+ if (nodeClosed) return;
2724
+ if (done >= EMPTY_DEVICES_MAX_RETRIES) {
2725
+ node.log(`No charging device found after ${done} checks - charging polls stay off until the node restarts`);
2726
+ return;
1658
2727
  }
2728
+ const delay = discoveryRetryDelay(done);
2729
+ node.log(`V2 discovery found no devices - checking again in ${Math.round(delay / 1000)}s`);
2730
+ initTimeout(() => checkDevicesAgain(done + 1), delay);
1659
2731
  }
1660
- initTimeoutHandles.push(setTimeout(() => startV2(0), 2000));
1661
2732
 
1662
- node.on('close', () => {
2733
+ async function checkDevicesAgain(done) {
2734
+ if (nodeClosed) return;
2735
+ let discovered;
2736
+ try {
2737
+ discovered = await discoverProducts(apiKey, account, { isClosed: () => nodeClosed });
2738
+ } catch (e) {
2739
+ if (nodeClosed) return;
2740
+ node.warn(`Device check failed: ${short(e.message)}`);
2741
+ scheduleDeviceCheck(done);
2742
+ return;
2743
+ }
2744
+ if (nodeClosed) return;
2745
+ if (!discovered.hasIntelligent) {
2746
+ // Still empty: check again. Devices but no EV: that is the answer.
2747
+ if (discovered.deviceCount === 0) scheduleDeviceCheck(done);
2748
+ return;
2749
+ }
2750
+ if (categories.some((c) => c.id === 'intelligent')) return;
2751
+ applyDiscoveredSuspended(discovered);
2752
+ // Added in place: the other categories keep their schedule. The same set as a
2753
+ // normal start (deviceCategoryEntries), then the SmartFlex entities (review4 #1).
2754
+ const deviceCategories = deviceCategoryEntries(discovered);
2755
+ const isNew = (entry) => !categories.some((c) => c.id === entry.id);
2756
+ categories.unshift(...deviceCategories.lead.filter(isNew));
2757
+ categories.push(...deviceCategories.rest.filter(isNew));
2758
+ announceSmartflexEntities(discovered);
2759
+ node.log(`V2 discovery: charging device found on check ${done} - charging polls started`);
2760
+ }
2761
+
2762
+ // Node-RED passes (removed, done) to a two-argument close handler; a caller that
2763
+ // passes only done is also handled.
2764
+ node.on('close', function (removed, done) {
2765
+ if (typeof removed === 'function') { done = removed; removed = false; }
2766
+ let finished = false;
2767
+ const finish = () => {
2768
+ if (finished) return;
2769
+ finished = true;
2770
+ if (typeof done === 'function') done();
2771
+ };
1663
2772
  nodeClosed = true;
2773
+ // Retries are tick-driven; dropping the outage state stops any pending one.
2774
+ chargingOutage = null;
2775
+ retryPollRunning = false;
1664
2776
  // Clear init setTimeouts so a redeploy during warmup can't leave an orphan scheduler
1665
2777
  initTimeoutHandles.forEach(h => clearTimeout(h));
1666
- initTimeoutHandles = [];
2778
+ initTimeoutHandles.clear();
1667
2779
  // Clear any pending retry timeouts
1668
2780
  retryTimeouts.forEach(timeout => clearTimeout(timeout));
1669
2781
  retryTimeouts = [];
1670
2782
  // Clear smart charging retry timeouts
1671
2783
  smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1672
2784
  smartChargingRetryTimeouts = [];
2785
+ // Drop a boost request still waiting for its turn
2786
+ if (boostQueue.timer) { clearTimeout(boostQueue.timer); boostQueue.timer = null; }
2787
+ if (boostQueue.watchdog) { clearTimeout(boostQueue.watchdog); boostQueue.watchdog = null; }
2788
+ boostQueue.pending = null;
2789
+ deferredChargingPollAt = null;
1673
2790
  // Clear charging timers
1674
2791
  clearChargingTimers();
1675
2792
  // Clear cooldown expiry timer
@@ -1678,7 +2795,24 @@ module.exports = function (RED) {
1678
2795
  cooldownExpiryTimer = null;
1679
2796
  }
1680
2797
  if (node._v2Scheduler) node._v2Scheduler.stop();
1681
- if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging, cmdTopicChargeCap);
2798
+ // Remove only this node's command subscriptions, then deregister from the broker
2799
+ // (unsubscribe(topic, ref, removeClientSubscription); deregister(node, done, autoDisconnect)).
2800
+ if (enableMqtt && node.broker) {
2801
+ try {
2802
+ for (const topic of commandTopics) node.broker.unsubscribe(topic, node.id, true);
2803
+ } catch (e) {
2804
+ node.warn(`MQTT unsubscribe failed: ${e.message}`);
2805
+ }
2806
+ if (typeof node.broker.deregister === 'function') {
2807
+ try {
2808
+ node.broker.deregister(node, finish, removed);
2809
+ return;
2810
+ } catch (e) {
2811
+ node.warn(`MQTT deregister failed: ${e.message}`);
2812
+ }
2813
+ }
2814
+ }
2815
+ finish();
1682
2816
  });
1683
2817
  }
1684
2818