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