node-red-contrib-octopus-intelligent 1.0.2 → 1.0.4

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.
@@ -1,862 +1,1164 @@
1
- const axios = require("axios");
2
-
3
- module.exports = function (RED) {
4
- function OctopusIntelligentNode(config) {
5
- RED.nodes.createNode(this, config);
6
- var node = this;
7
-
8
- // 1. Configuration
9
- const account = config.accountNumber ? config.accountNumber.trim() : "";
10
- const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
11
- const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
12
- const enableMqtt = config.enableMqtt;
13
-
14
- // MQTT Topics
15
- this.broker = RED.nodes.getNode(config.broker);
16
- const mqttPrefix = `homeassistant`;
17
- const uniqueIdPrefix = `nodered_${account}`;
18
- const stateTopic = `nodered_octopus/${account}/status`;
19
-
20
- // Command Topics (For listening)
21
- const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
22
- const cmdTopicTime = `nodered_octopus/${account}/set_time`;
23
- const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
24
-
25
- // 2. Constants & Validation
26
- const TIME_OPTIONS = [
27
- "04:00", "04:30", "05:00", "05:30",
28
- "06:00", "06:30", "07:00", "07:30",
29
- "08:00", "08:30", "09:00", "09:30",
30
- "10:00", "10:30", "11:00"
31
- ];
32
-
33
- // 3. Sensor Definitions (Read-Only)
34
- const sensors = [
35
- // Formatted timestamps (show "1 hour ago" in Home Assistant)
36
- { id: "next_charge", name: "Next Charge Time", class: "timestamp", icon: "mdi:timer", val: "next_start" },
37
- { id: "total_energy", name: "Total Planned Energy", class: "energy", unit: "kWh", val: "total_energy" },
38
- { id: "next_kwh", name: "Next Slot Energy", class: "energy", unit: "kWh", val: "next_kwh" },
39
- { id: "source", name: "Charge Source", icon: "mdi:help-circle", val: "next_source" },
40
- // Individual slot times (formatted)
41
- { id: "slot1_start", name: "Slot 1 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot1_start" },
42
- { id: "slot1_end", name: "Slot 1 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot1_end" },
43
- { id: "slot2_start", name: "Slot 2 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot2_start" },
44
- { id: "slot2_end", name: "Slot 2 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot2_end" },
45
- { id: "slot3_start", name: "Slot 3 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot3_start" },
46
- { id: "slot3_end", name: "Slot 3 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot3_end" },
47
- // Overall window (formatted)
48
- { id: "window_start", name: "Overall Window Start", class: "timestamp", icon: "mdi:timer-play", val: "window_start" },
49
- { id: "window_end", name: "Overall Window End", class: "timestamp", icon: "mdi:timer-stop", val: "window_end" },
50
-
51
- // Raw timestamp strings (show exact API timestamp)
52
- { id: "next_charge_raw", name: "Next Charge Time (Raw)", icon: "mdi:timer", val: "next_start_raw" },
53
- { id: "slot1_start_raw", name: "Slot 1 Start (Raw)", icon: "mdi:timer-outline", val: "slot1_start_raw" },
54
- { id: "slot1_end_raw", name: "Slot 1 End (Raw)", icon: "mdi:timer-outline", val: "slot1_end_raw" },
55
- { id: "slot2_start_raw", name: "Slot 2 Start (Raw)", icon: "mdi:timer-outline", val: "slot2_start_raw" },
56
- { id: "slot2_end_raw", name: "Slot 2 End (Raw)", icon: "mdi:timer-outline", val: "slot2_end_raw" },
57
- { id: "slot3_start_raw", name: "Slot 3 Start (Raw)", icon: "mdi:timer-outline", val: "slot3_start_raw" },
58
- { id: "slot3_end_raw", name: "Slot 3 End (Raw)", icon: "mdi:timer-outline", val: "slot3_end_raw" },
59
- { id: "window_start_raw", name: "Overall Window Start (Raw)", icon: "mdi:timer-play", val: "window_start_raw" },
60
- { id: "window_end_raw", name: "Overall Window End (Raw)", icon: "mdi:timer-stop", val: "window_end_raw" }
61
- ];
62
-
63
- // 4. Helper: Announce Controls (Write-Enabled)
64
- function announceControls() {
65
- if (!enableMqtt || !node.broker) return;
66
-
67
- // Single device definition with branding
68
- const device = {
69
- identifiers: [`nodered_octopus_${account}`],
70
- name: "Octopus Intelligent",
71
- manufacturer: "Octopus Energy",
72
- model: "Intelligent Octopus Go",
73
- sw_version: "1.0.0",
74
- suggested_area: "Energy",
75
- configuration_url: "https://octopus.energy/intelligent/"
76
- };
77
-
78
- // A. The Slider (Number) - now shows pending value
79
- const limitConfig = {
80
- name: "Octopus Target Charge",
81
- unique_id: `${uniqueIdPrefix}_target_limit`,
82
- state_topic: stateTopic,
83
- command_topic: cmdTopicLimit,
84
- value_template: "{{ value_json.pending_limit }}",
85
- min: 50, max: 100, step: 5,
86
- unit_of_measurement: "%",
87
- icon: "mdi:battery-charging-high",
88
- device: device
89
- };
90
- node.broker.client.publish(`${mqttPrefix}/number/${uniqueIdPrefix}_limit/config`, JSON.stringify(limitConfig), { retain: true });
91
-
92
- // B. The Dropdown (Select) - now shows pending value
93
- const timeConfig = {
94
- name: "Octopus Ready Time",
95
- unique_id: `${uniqueIdPrefix}_target_time`,
96
- state_topic: stateTopic,
97
- command_topic: cmdTopicTime,
98
- value_template: "{{ value_json.pending_time }}",
99
- options: TIME_OPTIONS,
100
- icon: "mdi:clock-time-four-outline",
101
- device: device
102
- };
103
- node.broker.client.publish(`${mqttPrefix}/select/${uniqueIdPrefix}_time/config`, JSON.stringify(timeConfig), { retain: true });
104
-
105
- // C. Submit Button
106
- const buttonConfig = {
107
- name: "Octopus Apply Changes",
108
- unique_id: `${uniqueIdPrefix}_submit_button`,
109
- command_topic: cmdTopicSubmit,
110
- payload_press: "SUBMIT",
111
- icon: "mdi:check-circle",
112
- device_class: "update",
113
- device: device
114
- };
115
- node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
116
-
117
- // D. Add sensors for confirmed values (read-only display)
118
- const confirmedLimitSensor = {
119
- name: "Octopus Confirmed Charge Limit",
120
- unique_id: `${uniqueIdPrefix}_confirmed_limit`,
121
- state_topic: stateTopic,
122
- value_template: "{{ value_json.confirmed_limit }}",
123
- unit_of_measurement: "%",
124
- icon: "mdi:battery-check",
125
- device: device
126
- };
127
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_limit/config`, JSON.stringify(confirmedLimitSensor), { retain: true });
128
-
129
- const confirmedTimeSensor = {
130
- name: "Octopus Confirmed Ready Time",
131
- unique_id: `${uniqueIdPrefix}_confirmed_time`,
132
- state_topic: stateTopic,
133
- value_template: "{{ value_json.confirmed_time }}",
134
- icon: "mdi:clock-check",
135
- device: device
136
- };
137
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
138
-
139
- // F. Charging Now Binary Sensor (main sensor for automations)
140
- const chargingNowBinarySensor = {
141
- name: "Octopus Charging Now",
142
- unique_id: `${uniqueIdPrefix}_charging_now`,
143
- state_topic: `${stateTopic}/charging_now`,
144
- device_class: "battery_charging",
145
- payload_on: "ON",
146
- payload_off: "OFF",
147
- icon: "mdi:ev-station",
148
- device: device
149
- };
150
- node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
151
-
152
- // G. Announce Read-Only Sensors
153
- sensors.forEach(sensor => {
154
- const payload = {
155
- name: `Octopus ${sensor.name}`,
156
- unique_id: `${uniqueIdPrefix}_${sensor.id}`,
157
- state_topic: stateTopic,
158
- value_template: `{{ value_json.${sensor.val} }}`,
159
- device: device
160
- };
161
- if (sensor.class) payload.device_class = sensor.class;
162
- if (sensor.unit) payload.unit_of_measurement = sensor.unit;
163
- if (sensor.icon) payload.icon = sensor.icon;
164
-
165
- // Mark raw sensors as diagnostic (moves to Diagnostics section)
166
- if (sensor.id.includes('_raw')) {
167
- payload.entity_category = "diagnostic";
168
- }
169
-
170
- node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
171
- });
172
-
173
- // Subscribe to Commands
174
- node.broker.client.subscribe(cmdTopicLimit);
175
- node.broker.client.subscribe(cmdTopicTime);
176
- node.broker.client.subscribe(cmdTopicSubmit);
177
- }
178
-
179
- // 5. Helper: Set Preferences (The Mutation)
180
- let retryTimeouts = []; // Track pending retry timeouts
181
- let expectedLimit = null;
182
- let expectedTime = null;
183
-
184
- // Pending vs Confirmed state
185
- let pendingLimit = 80;
186
- let pendingTime = "08:00";
187
- let confirmedLimit = 80;
188
- let confirmedTime = "08:00";
189
-
190
- // Charging Now feature - timer-based state management
191
- let chargingNow = false;
192
- let preValidationTimer = null; // Fires 30s before slot start
193
- let slotStartTimer = null; // Fires at exact slot start
194
- let slotEndTimer = null; // Fires at exact slot end
195
- let cachedSlots = []; // Fresh slot data from pre-validation
196
-
197
- async function setPreferences(newLimit, newTime) {
198
- // Validation
199
- let limit = parseInt(newLimit);
200
- let time = newTime;
201
-
202
- // Enforce Limits
203
- if (isNaN(limit) || limit < 50) limit = 50;
204
- if (limit > 100) limit = 100;
205
- // Round to nearest 5
206
- limit = Math.round(limit / 5) * 5;
207
-
208
- // Validate Time
209
- if (!TIME_OPTIONS.includes(time)) {
210
- node.warn(`Invalid time '${time}' requested. Defaulting to 08:00`);
211
- time = "08:00";
212
- }
213
-
214
- // Cancel any pending retry attempts from previous changes
215
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
216
- retryTimeouts = [];
217
-
218
- try {
219
- node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
220
-
221
- // A. Get Token
222
- const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
223
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
224
- variables: { input: { APIKey: apiKey } }
225
- });
226
-
227
- if (authResponse.data.errors) {
228
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
229
- }
230
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
231
- throw new Error(`Auth response missing token data`);
232
- }
233
-
234
- const token = authResponse.data.data.obtainKrakenToken.token;
235
-
236
- // B. Send Mutation
237
- const mutation = `
238
- mutation setPreferences($input: VehicleChargingPreferencesInput!) {
239
- setVehicleChargePreferences(input: $input) { __typename }
240
- }`;
241
-
242
- const variables = {
243
- input: {
244
- accountNumber: account,
245
- weekdayTargetSoc: limit,
246
- weekendTargetSoc: limit,
247
- weekdayTargetTime: time,
248
- weekendTargetTime: time
249
- }
250
- };
251
-
252
- const mutationResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
253
- query: mutation,
254
- variables: variables
255
- }, { headers: { Authorization: token } });
256
-
257
- if (mutationResponse.data.errors) {
258
- throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
259
- }
260
-
261
- // C. Start exponential backoff validation
262
- expectedLimit = limit;
263
- expectedTime = time;
264
- node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
265
-
266
- // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
267
- const retryIntervals = [15000, 30000, 60000, 120000];
268
- scheduleRetries(retryIntervals, 0);
269
-
270
- } catch (err) {
271
- node.error("Failed to set preferences: " + err.message);
272
- if (err.response) {
273
- node.error(`Response: ${JSON.stringify(err.response.data)}`);
274
- }
275
- node.status({ fill: "red", shape: "ring", text: "Update Failed" });
276
- expectedLimit = null;
277
- expectedTime = null;
278
- }
279
- }
280
-
281
- function scheduleRetries(intervals, index) {
282
- if (index >= intervals.length) {
283
- // All retries exhausted, let normal interval take over
284
- node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
285
- expectedLimit = null;
286
- expectedTime = null;
287
- return;
288
- }
289
-
290
- const timeout = setTimeout(async () => {
291
- await fetchDataWithValidation(intervals, index);
292
- }, intervals[index]);
293
-
294
- retryTimeouts.push(timeout);
295
- }
296
-
297
- async function fetchDataWithValidation(intervals, currentIndex) {
298
- try {
299
- const result = await fetchData(true); // Pass flag to indicate validation mode
300
-
301
- // Check if the data matches our expected values
302
- if (result && result.validated) {
303
- // Success! Changes confirmed
304
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${result.confirmedLimit}% @ ${result.confirmedTime}` });
305
- expectedLimit = null;
306
- expectedTime = null;
307
- // Clear remaining timeouts
308
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
309
- retryTimeouts = [];
310
- } else {
311
- // Not yet updated, schedule next retry
312
- const attempt = currentIndex + 1;
313
- const totalAttempts = intervals.length;
314
- node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
315
- scheduleRetries(intervals, currentIndex + 1);
316
- }
317
- } catch (error) {
318
- // Error during fetch, schedule next retry
319
- node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
320
- scheduleRetries(intervals, currentIndex + 1);
321
- }
322
- }
323
-
324
- // 6. Logic: Fetch Data (Read)
325
- async function fetchData(validationMode = false) {
326
- // Debug object to track API calls
327
- const debugInfo = {
328
- timestamp: new Date().toISOString(),
329
- step: null,
330
- success: false,
331
- error: null,
332
- apiCalls: [],
333
- validationMode: validationMode
334
- };
335
-
336
- if (!apiKey || !account) {
337
- debugInfo.error = "Missing configuration: apiKey or account number not provided";
338
- debugInfo.step = "validation";
339
- node.status({ fill: "red", shape: "ring", text: "Config Missing" });
340
- node.send({
341
- payload: buildDefaultPayload(),
342
- debug: debugInfo
343
- });
344
- return { validated: false };
345
- }
346
-
347
- try {
348
- // STEP 1: Get Token
349
- debugInfo.step = "authentication";
350
- node.status({ fill: "yellow", shape: "ring", text: "Authenticating..." });
351
-
352
- const authRequest = {
353
- url: "https://api.octopus.energy/v1/graphql/",
354
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
355
- variables: { input: { APIKey: apiKey } }
356
- };
357
-
358
- const authResponse = await axios.post(authRequest.url, {
359
- query: authRequest.query,
360
- variables: authRequest.variables
361
- });
362
-
363
- debugInfo.apiCalls.push({
364
- step: 1,
365
- name: "authentication",
366
- url: authRequest.url,
367
- statusCode: authResponse.status,
368
- hasErrors: !!(authResponse.data.errors),
369
- errors: authResponse.data.errors || null
370
- });
371
-
372
- // Validate auth response
373
- if (authResponse.data.errors) {
374
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
375
- }
376
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
377
- throw new Error(`Auth response missing token data. Response: ${JSON.stringify(authResponse.data)}`);
378
- }
379
-
380
- const token = authResponse.data.data.obtainKrakenToken.token;
381
- debugInfo.apiCalls[0].tokenObtained = !!token;
382
- debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
383
-
384
- // STEP 2: Fetch Data
385
- debugInfo.step = "fetching_data";
386
- node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
387
-
388
- const masterQuery = `
389
- query getData($account: String!) {
390
- plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } }
391
- vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
392
- }`;
393
-
394
- const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
395
- query: masterQuery,
396
- variables: { account: account }
397
- }, { headers: { Authorization: token } });
398
-
399
- debugInfo.apiCalls.push({
400
- step: 2,
401
- name: "data_query",
402
- url: "https://api.octopus.energy/v1/graphql/",
403
- accountNumber: account,
404
- authHeaderFormat: "Raw token (no Bearer/JWT prefix)",
405
- statusCode: dataResponse.status,
406
- hasErrors: !!(dataResponse.data.errors),
407
- errors: dataResponse.data.errors || null,
408
- hasData: !!(dataResponse.data.data)
409
- });
410
-
411
- // Validate data response
412
- if (dataResponse.data.errors) {
413
- throw new Error(`Data query failed: ${JSON.stringify(dataResponse.data.errors)}`);
414
- }
415
- if (!dataResponse.data.data) {
416
- throw new Error(`Data response missing data field. Response: ${JSON.stringify(dataResponse.data)}`);
417
- }
418
-
419
- // STEP 3: Extract and Process
420
- debugInfo.step = "processing";
421
- const data = dataResponse.data.data || {};
422
- const slots = data.plannedDispatches || [];
423
- const prefs = data.vehicleChargingPreferences || {};
424
-
425
- debugInfo.apiCalls[1].slotsFound = slots.length;
426
- debugInfo.apiCalls[1].preferencesFound = !!(prefs.weekdayTargetSoc);
427
- debugInfo.apiCalls[1].slotDetails = slots.map(s => ({
428
- start: s.startDt,
429
- end: s.endDt,
430
- kwh: s.deltaKwh,
431
- source: s.meta?.source
432
- }));
433
-
434
- // Update Confirmed State (from API)
435
- confirmedLimit = prefs.weekdayTargetSoc || confirmedLimit;
436
- confirmedTime = prefs.weekdayTargetTime || confirmedTime;
437
-
438
- // On successful fetch, sync pending to confirmed if not in validation mode
439
- if (!validationMode) {
440
- pendingLimit = confirmedLimit;
441
- pendingTime = confirmedTime;
442
- }
443
-
444
- // Process slots
445
- const now = new Date();
446
- // Include active slots (endDt in future) and future slots
447
- const activeAndFutureSlots = slots.filter(s => new Date(s.endDt) > now);
448
- const nextSlot = activeAndFutureSlots[0] || null;
449
-
450
- // Total energy for all active/future slots
451
- const totalEnergy = activeAndFutureSlots.reduce((sum, s) => sum + (s.deltaKwh || 0), 0);
452
-
453
- debugInfo.apiCalls[1].activeAndFutureSlots = activeAndFutureSlots.length;
454
- debugInfo.processingTime = now.toISOString();
455
-
456
- // Setup charging timers (only in non-validation mode)
457
- if (!validationMode) {
458
- setupChargingTimers(activeAndFutureSlots);
459
- }
460
-
461
- // Build Payload
462
- const statusPayload = {
463
- next_start: nextSlot ? nextSlot.startDt : null,
464
- total_energy: parseFloat(totalEnergy.toFixed(2)),
465
- next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
466
- next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
467
- // Confirmed values (from API)
468
- confirmed_limit: confirmedLimit,
469
- confirmed_time: confirmedTime,
470
- // Pending values (user's current selections)
471
- pending_limit: pendingLimit,
472
- pending_time: pendingTime,
473
- // Charging Now state
474
- charging_now: chargingNow,
475
- // Individual slots (first 3 active/future) - formatted timestamps
476
- slot1_start: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
477
- slot1_end: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
478
- slot2_start: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
479
- slot2_end: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
480
- slot3_start: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
481
- slot3_end: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
482
- // Overall window (first start to last end) - formatted timestamps
483
- window_start: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
484
- window_end: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
485
- // Raw timestamp strings (exact API output)
486
- next_start_raw: nextSlot ? nextSlot.startDt : null,
487
- slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
488
- slot1_end_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
489
- slot2_start_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
490
- slot2_end_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
491
- slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
492
- slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
493
- window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
494
- window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null
495
- };
496
-
497
- // Success!
498
- debugInfo.success = true;
499
- debugInfo.step = "complete";
500
-
501
- // Check if we're validating a preference change
502
- let isValidated = false;
503
- if (validationMode && expectedLimit !== null && expectedTime !== null) {
504
- // Check if the returned values match what we set
505
- isValidated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
506
- debugInfo.expectedLimit = expectedLimit;
507
- debugInfo.expectedTime = expectedTime;
508
- debugInfo.receivedLimit = confirmedLimit;
509
- debugInfo.receivedTime = confirmedTime;
510
- debugInfo.validated = isValidated;
511
- }
512
-
513
- // ALWAYS publish data to prevent sensors becoming unavailable
514
- node.send({
515
- payload: statusPayload,
516
- debug: debugInfo
517
- });
518
-
519
- if (enableMqtt && node.broker) {
520
- node.broker.client.publish(stateTopic, JSON.stringify(statusPayload), { retain: true });
521
- // Also publish charging_now state to binary sensor topic
522
- const chargingPayload = chargingNow ? "ON" : "OFF";
523
- node.broker.client.publish(`${stateTopic}/charging_now`, chargingPayload, { retain: true });
524
- }
525
-
526
- // Update status (validation mode will override this in fetchDataWithValidation)
527
- if (!validationMode) {
528
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
529
- }
530
-
531
- // Return validation result
532
- return { validated: isValidated || !validationMode, confirmedLimit, confirmedTime };
533
-
534
- } catch (error) {
535
- debugInfo.success = false;
536
- debugInfo.error = {
537
- message: error.message,
538
- stack: error.stack,
539
- response: error.response ? {
540
- status: error.response.status,
541
- statusText: error.response.statusText,
542
- data: error.response.data
543
- } : null
544
- };
545
-
546
- // Log to Node-RED (only if not in validation mode to avoid spam)
547
- if (!validationMode) {
548
- node.error(`Octopus API Error at ${debugInfo.step}: ${error.message}`);
549
- if (error.response) {
550
- node.error(`Response: ${JSON.stringify(error.response.data)}`);
551
- }
552
-
553
- // Update status
554
- node.status({
555
- fill: "red",
556
- shape: "ring",
557
- text: `Error: ${debugInfo.step}`
558
- });
559
-
560
- // Send default payload with debug info
561
- node.send({
562
- payload: buildDefaultPayload(),
563
- debug: debugInfo
564
- });
565
- }
566
-
567
- // Return failure for validation
568
- return { validated: false };
569
- }
570
- }
571
-
572
- // Helper: Build default payload when errors occur
573
- function buildDefaultPayload() {
574
- return {
575
- next_start: null,
576
- total_energy: 0,
577
- next_kwh: "0",
578
- next_source: "unknown",
579
- confirmed_limit: confirmedLimit,
580
- confirmed_time: confirmedTime,
581
- pending_limit: pendingLimit,
582
- pending_time: pendingTime,
583
- charging_now: chargingNow,
584
- slot1_start: null,
585
- slot1_end: null,
586
- slot2_start: null,
587
- slot2_end: null,
588
- slot3_start: null,
589
- slot3_end: null,
590
- window_start: null,
591
- window_end: null,
592
- // Raw timestamp strings
593
- next_start_raw: null,
594
- slot1_start_raw: null,
595
- slot1_end_raw: null,
596
- slot2_start_raw: null,
597
- slot2_end_raw: null,
598
- slot3_start_raw: null,
599
- slot3_end_raw: null,
600
- window_start_raw: null,
601
- window_end_raw: null
602
- };
603
- }
604
-
605
- // 6a. Charging Now - Timer Management Functions
606
-
607
- // Clear all charging timers
608
- function clearChargingTimers() {
609
- if (preValidationTimer) {
610
- clearTimeout(preValidationTimer);
611
- preValidationTimer = null;
612
- }
613
- if (slotStartTimer) {
614
- clearTimeout(slotStartTimer);
615
- slotStartTimer = null;
616
- }
617
- if (slotEndTimer) {
618
- clearTimeout(slotEndTimer);
619
- slotEndTimer = null;
620
- }
621
- }
622
-
623
- // Publish charging state to MQTT
624
- function publishChargingState(state) {
625
- chargingNow = state;
626
- if (enableMqtt && node.broker) {
627
- const payload = state ? "ON" : "OFF";
628
- node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
629
- }
630
- }
631
-
632
- // Setup pre-validation timer (30s before slot starts)
633
- function setupPreValidationTimer(nextSlot) {
634
- const now = new Date();
635
- const slotStart = new Date(nextSlot.startDt);
636
- const preValidationTime = slotStart.getTime() - 30000; // 30s before
637
- const msUntilPreValidation = preValidationTime - now.getTime();
638
-
639
- if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
640
- preValidationTimer = setTimeout(async () => {
641
- node.warn("Pre-validating slot data (30s before start)");
642
- try {
643
- // Fetch fresh data from API
644
- const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
645
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
646
- variables: { input: { APIKey: apiKey } }
647
- });
648
-
649
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
650
- throw new Error("Pre-validation auth failed");
651
- }
652
-
653
- const token = authResponse.data.data.obtainKrakenToken.token;
654
-
655
- const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
656
- query: `query getData($account: String!) { plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } } }`,
657
- variables: { account: account }
658
- }, { headers: { Authorization: token } });
659
-
660
- if (dataResponse.data.data && dataResponse.data.data.plannedDispatches) {
661
- cachedSlots = dataResponse.data.data.plannedDispatches;
662
-
663
- // Check if slot still exists (within 1 minute tolerance)
664
- const stillExists = cachedSlots.find(s =>
665
- Math.abs(new Date(s.startDt).getTime() - slotStart.getTime()) < 60000
666
- );
667
-
668
- if (stillExists) {
669
- node.warn(`Slot confirmed at ${stillExists.startDt}`);
670
- setupSlotStartTimer(stillExists);
671
- } else {
672
- node.warn("Slot was cancelled or modified - not setting start timer");
673
- }
674
- }
675
- } catch (error) {
676
- node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
677
- // Fallback: use original slot data
678
- setupSlotStartTimer(nextSlot);
679
- }
680
- }, msUntilPreValidation);
681
-
682
- const minutesUntil = Math.round(msUntilPreValidation / 60000);
683
- node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
684
- }
685
- }
686
-
687
- // Setup slot start timer (exact start time)
688
- function setupSlotStartTimer(slot) {
689
- const now = new Date();
690
- const slotStart = new Date(slot.startDt);
691
- const msUntilStart = slotStart.getTime() - now.getTime();
692
-
693
- if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
694
- slotStartTimer = setTimeout(() => {
695
- publishChargingState(true);
696
- node.warn(`Charging slot started at ${slot.startDt}`);
697
- setupSlotEndTimer(slot);
698
- }, msUntilStart);
699
-
700
- const secondsUntil = Math.round(msUntilStart / 1000);
701
- node.log(`Slot start timer set for ${secondsUntil}s (${slot.startDt})`);
702
- } else if (msUntilStart <= 0) {
703
- // Slot already started, check if it's still active
704
- const slotEnd = new Date(slot.endDt);
705
- if (slotEnd > now) {
706
- publishChargingState(true);
707
- setupSlotEndTimer(slot);
708
- }
709
- }
710
- }
711
-
712
- // Setup slot end timer (exact end time)
713
- function setupSlotEndTimer(slot) {
714
- const now = new Date();
715
- const slotEnd = new Date(slot.endDt);
716
- const msUntilEnd = slotEnd.getTime() - now.getTime();
717
-
718
- if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
719
- slotEndTimer = setTimeout(() => {
720
- node.warn(`Charging slot ended at ${slot.endDt}`);
721
-
722
- // Check if another slot starts immediately (within cached data)
723
- const now = new Date();
724
- const immediateNextSlot = cachedSlots.find(s => {
725
- const start = new Date(s.startDt);
726
- const end = new Date(s.endDt);
727
- return start <= now && end > now;
728
- });
729
-
730
- if (immediateNextSlot) {
731
- node.warn("Next slot starting immediately");
732
- publishChargingState(true);
733
- setupSlotEndTimer(immediateNextSlot);
734
- } else {
735
- publishChargingState(false);
736
- }
737
- }, msUntilEnd);
738
-
739
- const minutesUntil = Math.round(msUntilEnd / 60000);
740
- node.log(`Slot end timer set for ${minutesUntil} min (${slot.endDt})`);
741
- }
742
- }
743
-
744
- // Main timer setup - called on each poll
745
- function setupChargingTimers(slots) {
746
- // Clear existing timers
747
- clearChargingTimers();
748
-
749
- // Cache slots for later use
750
- cachedSlots = slots;
751
-
752
- const now = new Date();
753
-
754
- // Check if currently in a charging slot
755
- const activeSlot = slots.find(s => {
756
- const start = new Date(s.startDt);
757
- const end = new Date(s.endDt);
758
- return start <= now && end > now;
759
- });
760
-
761
- if (activeSlot) {
762
- // Currently charging
763
- const newState = true;
764
- if (chargingNow !== newState) {
765
- publishChargingState(newState);
766
- }
767
- setupSlotEndTimer(activeSlot);
768
- node.log("Currently charging - end timer set");
769
- } else {
770
- // Not currently charging
771
- const newState = false;
772
- if (chargingNow !== newState) {
773
- publishChargingState(newState);
774
- }
775
-
776
- // Find next future slot
777
- const nextSlot = slots.find(s => new Date(s.startDt) > now);
778
-
779
- if (nextSlot) {
780
- setupPreValidationTimer(nextSlot);
781
- node.log(`Next slot at ${nextSlot.startDt}`);
782
- }
783
- }
784
- }
785
-
786
- // 7. Event Listeners
787
-
788
- // Helper: Publish current state (both pending and confirmed)
789
- function publishCurrentState() {
790
- if (enableMqtt && node.broker) {
791
- const quickState = {
792
- pending_limit: pendingLimit,
793
- pending_time: pendingTime,
794
- confirmed_limit: confirmedLimit,
795
- confirmed_time: confirmedTime
796
- };
797
- node.broker.client.publish(stateTopic, JSON.stringify(quickState), { retain: false });
798
- }
799
- }
800
-
801
- // A. Handle Node-RED Input Messages
802
- node.on('input', function (msg) {
803
- // Check for control commands
804
- if (msg.payload && typeof msg.payload === 'object') {
805
- if (msg.payload.set_limit || msg.payload.set_time) {
806
- // Use new values if present, otherwise keep existing
807
- const targetLimit = msg.payload.set_limit || confirmedLimit;
808
- const targetTime = msg.payload.set_time || confirmedTime;
809
- setPreferences(targetLimit, targetTime);
810
- return; // Don't run standard fetch if setting
811
- }
812
- }
813
- // If just a trigger, run fetch
814
- fetchData();
815
- });
816
-
817
- // B. Handle MQTT Commands (Home Assistant)
818
- if (enableMqtt && node.broker) {
819
- node.broker.register(this);
820
-
821
- // Slider changed - update pending value only
822
- node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
823
- const val = parseInt(payload.toString());
824
- pendingLimit = val;
825
- publishCurrentState(); // Update display immediately
826
- node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
827
- });
828
-
829
- // Dropdown changed - update pending value only
830
- node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
831
- const val = payload.toString();
832
- pendingTime = val;
833
- publishCurrentState(); // Update display immediately
834
- node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
835
- });
836
-
837
- // Button pressed - submit changes to API
838
- node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
839
- setPreferences(pendingLimit, pendingTime);
840
- });
841
-
842
- setTimeout(announceControls, 2000);
843
- }
844
-
845
- // Init
846
- const intervalId = setInterval(fetchData, refreshRate);
847
- setTimeout(fetchData, 1000);
848
- node.on('close', () => {
849
- clearInterval(intervalId);
850
- // Clear any pending retry timeouts
851
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
852
- retryTimeouts = [];
853
- // Clear charging timers
854
- clearChargingTimers();
855
- if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit);
856
- });
857
- }
858
-
859
- RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
860
- credentials: { apiKey: { type: "password" } }
861
- });
1
+ const axios = require("axios");
2
+
3
+ module.exports = function (RED) {
4
+ function OctopusIntelligentNode(config) {
5
+ RED.nodes.createNode(this, config);
6
+ var node = this;
7
+
8
+ // 1. Configuration
9
+ const account = config.accountNumber ? config.accountNumber.trim() : "";
10
+ const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
11
+ const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
12
+ const enableMqtt = config.enableMqtt;
13
+
14
+ // MQTT Topics
15
+ this.broker = RED.nodes.getNode(config.broker);
16
+ const mqttPrefix = `homeassistant`;
17
+ const uniqueIdPrefix = `nodered_${account}`;
18
+ const stateTopic = `nodered_octopus/${account}/status`;
19
+
20
+ // Command Topics (For listening)
21
+ const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
22
+ const cmdTopicTime = `nodered_octopus/${account}/set_time`;
23
+ const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
24
+ const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
25
+
26
+ // 2. Constants & Validation
27
+ const TIME_OPTIONS = [
28
+ "04:00", "04:30", "05:00", "05:30",
29
+ "06:00", "06:30", "07:00", "07:30",
30
+ "08:00", "08:30", "09:00", "09:30",
31
+ "10:00", "10:30", "11:00"
32
+ ];
33
+
34
+ // 3. Sensor Definitions (Read-Only)
35
+ const sensors = [
36
+ // Formatted timestamps (show "1 hour ago" in Home Assistant)
37
+ { id: "next_charge", name: "Next Charge Time", class: "timestamp", icon: "mdi:timer", val: "next_start" },
38
+ { id: "total_energy", name: "Total Planned Energy", class: "energy", unit: "kWh", val: "total_energy" },
39
+ { id: "next_kwh", name: "Next Slot Energy", class: "energy", unit: "kWh", val: "next_kwh" },
40
+ { id: "source", name: "Charge Source", icon: "mdi:help-circle", val: "next_source" },
41
+ // Individual slot times (formatted)
42
+ { id: "slot1_start", name: "Slot 1 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot1_start" },
43
+ { id: "slot1_end", name: "Slot 1 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot1_end" },
44
+ { id: "slot2_start", name: "Slot 2 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot2_start" },
45
+ { id: "slot2_end", name: "Slot 2 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot2_end" },
46
+ { id: "slot3_start", name: "Slot 3 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot3_start" },
47
+ { id: "slot3_end", name: "Slot 3 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot3_end" },
48
+ // Overall window (formatted)
49
+ { id: "window_start", name: "Overall Window Start", class: "timestamp", icon: "mdi:timer-play", val: "window_start" },
50
+ { id: "window_end", name: "Overall Window End", class: "timestamp", icon: "mdi:timer-stop", val: "window_end" },
51
+
52
+ // v1.0.4: Next poll timer
53
+ { id: "next_poll", name: "Next Poll Time", class: "timestamp", icon: "mdi:clock-outline", val: "next_poll" },
54
+
55
+ // v1.0.4: Refresh available timestamp (diagnostic) - for Home Assistant countdown
56
+ { id: "refresh_available_at", name: "Refresh Available At", class: "timestamp", icon: "mdi:timer-sand", val: "refresh_available_at" },
57
+
58
+ // v1.0.4: API complexity tracking (diagnostic)
59
+ { id: "api_requests_hour", name: "API Requests (Last Hour)", icon: "mdi:api", val: "api_requests_hour" },
60
+ { id: "api_complexity_hour", name: "API Complexity (Last Hour)", icon: "mdi:chart-line", val: "api_complexity_hour" },
61
+ { id: "api_complexity_percent", name: "API Complexity Usage", icon: "mdi:percent", unit: "%", val: "api_complexity_percent" },
62
+
63
+ // Raw timestamp strings (show exact API timestamp) - marked as diagnostic
64
+ { id: "next_charge_raw", name: "Next Charge Time (Raw)", icon: "mdi:timer", val: "next_start_raw" },
65
+ { id: "next_poll_raw", name: "Next Poll Time (Raw)", icon: "mdi:clock-outline", val: "next_poll_raw" },
66
+ { id: "slot1_start_raw", name: "Slot 1 Start (Raw)", icon: "mdi:timer-outline", val: "slot1_start_raw" },
67
+ { id: "slot1_end_raw", name: "Slot 1 End (Raw)", icon: "mdi:timer-outline", val: "slot1_end_raw" },
68
+ { id: "slot2_start_raw", name: "Slot 2 Start (Raw)", icon: "mdi:timer-outline", val: "slot2_start_raw" },
69
+ { id: "slot2_end_raw", name: "Slot 2 End (Raw)", icon: "mdi:timer-outline", val: "slot2_end_raw" },
70
+ { id: "slot3_start_raw", name: "Slot 3 Start (Raw)", icon: "mdi:timer-outline", val: "slot3_start_raw" },
71
+ { id: "slot3_end_raw", name: "Slot 3 End (Raw)", icon: "mdi:timer-outline", val: "slot3_end_raw" },
72
+ { id: "window_start_raw", name: "Overall Window Start (Raw)", icon: "mdi:timer-play", val: "window_start_raw" },
73
+ { id: "window_end_raw", name: "Overall Window End (Raw)", icon: "mdi:timer-stop", val: "window_end_raw" }
74
+ ];
75
+
76
+ // 4. Helper: Announce Controls (Write-Enabled)
77
+ function announceControls() {
78
+ if (!enableMqtt || !node.broker) return;
79
+
80
+ // Single device definition with branding
81
+ const device = {
82
+ identifiers: [`nodered_octopus_${account}`],
83
+ name: "Octopus Intelligent",
84
+ manufacturer: "Octopus Energy",
85
+ model: "Intelligent Octopus Go",
86
+ sw_version: "1.0.0",
87
+ suggested_area: "Energy",
88
+ configuration_url: "https://octopus.energy/intelligent/"
89
+ };
90
+
91
+ // A. The Slider (Number) - now shows pending value
92
+ const limitConfig = {
93
+ name: "Octopus Target Charge",
94
+ unique_id: `${uniqueIdPrefix}_target_limit`,
95
+ state_topic: stateTopic,
96
+ command_topic: cmdTopicLimit,
97
+ value_template: "{{ value_json.pending_limit }}",
98
+ min: 50, max: 100, step: 5,
99
+ unit_of_measurement: "%",
100
+ icon: "mdi:battery-charging-high",
101
+ device: device
102
+ };
103
+ node.broker.client.publish(`${mqttPrefix}/number/${uniqueIdPrefix}_limit/config`, JSON.stringify(limitConfig), { retain: true });
104
+
105
+ // B. The Dropdown (Select) - now shows pending value
106
+ const timeConfig = {
107
+ name: "Octopus Ready Time",
108
+ unique_id: `${uniqueIdPrefix}_target_time`,
109
+ state_topic: stateTopic,
110
+ command_topic: cmdTopicTime,
111
+ value_template: "{{ value_json.pending_time }}",
112
+ options: TIME_OPTIONS,
113
+ icon: "mdi:clock-time-four-outline",
114
+ device: device
115
+ };
116
+ node.broker.client.publish(`${mqttPrefix}/select/${uniqueIdPrefix}_time/config`, JSON.stringify(timeConfig), { retain: true });
117
+
118
+ // C. Submit Button
119
+ const buttonConfig = {
120
+ name: "Octopus Apply Changes",
121
+ unique_id: `${uniqueIdPrefix}_submit_button`,
122
+ command_topic: cmdTopicSubmit,
123
+ payload_press: "SUBMIT",
124
+ icon: "mdi:check-circle",
125
+ device_class: "update",
126
+ device: device
127
+ };
128
+ node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
129
+
130
+ // D. Refresh Button
131
+ const refreshButtonConfig = {
132
+ name: "Octopus Refresh API",
133
+ unique_id: `${uniqueIdPrefix}_refresh_button`,
134
+ command_topic: cmdTopicRefresh,
135
+ payload_press: "REFRESH",
136
+ icon: "mdi:refresh",
137
+ device_class: "restart",
138
+ device: device
139
+ };
140
+ node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_refresh/config`, JSON.stringify(refreshButtonConfig), { retain: true });
141
+
142
+ // E. Add sensors for confirmed values (read-only display)
143
+ const confirmedLimitSensor = {
144
+ name: "Octopus Confirmed Charge Limit",
145
+ unique_id: `${uniqueIdPrefix}_confirmed_limit`,
146
+ state_topic: stateTopic,
147
+ value_template: "{{ value_json.confirmed_limit }}",
148
+ unit_of_measurement: "%",
149
+ icon: "mdi:battery-check",
150
+ device: device
151
+ };
152
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_limit/config`, JSON.stringify(confirmedLimitSensor), { retain: true });
153
+
154
+ const confirmedTimeSensor = {
155
+ name: "Octopus Confirmed Ready Time",
156
+ unique_id: `${uniqueIdPrefix}_confirmed_time`,
157
+ state_topic: stateTopic,
158
+ value_template: "{{ value_json.confirmed_time }}",
159
+ icon: "mdi:clock-check",
160
+ device: device
161
+ };
162
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
163
+
164
+ // G. Charging Now Binary Sensor (main sensor for automations)
165
+ const chargingNowBinarySensor = {
166
+ name: "Octopus Charging Now",
167
+ unique_id: `${uniqueIdPrefix}_charging_now`,
168
+ state_topic: `${stateTopic}/charging_now`,
169
+ device_class: "battery_charging",
170
+ payload_on: "ON",
171
+ payload_off: "OFF",
172
+ icon: "mdi:ev-station",
173
+ device: device
174
+ };
175
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
176
+
177
+ // H. Announce Read-Only Sensors
178
+ sensors.forEach(sensor => {
179
+ const payload = {
180
+ name: `Octopus ${sensor.name}`,
181
+ unique_id: `${uniqueIdPrefix}_${sensor.id}`,
182
+ state_topic: stateTopic,
183
+ value_template: `{{ value_json.${sensor.val} }}`,
184
+ device: device
185
+ };
186
+ if (sensor.class) payload.device_class = sensor.class;
187
+ if (sensor.unit) payload.unit_of_measurement = sensor.unit;
188
+ if (sensor.icon) payload.icon = sensor.icon;
189
+
190
+ // Mark raw sensors, refresh timestamp, and API metrics as diagnostic (moves to Diagnostics section)
191
+ if (sensor.id.includes('_raw') ||
192
+ sensor.id === 'refresh_available_at' ||
193
+ sensor.id.startsWith('api_')) {
194
+ payload.entity_category = "diagnostic";
195
+ }
196
+
197
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
198
+ });
199
+
200
+ // Subscribe to Commands
201
+ node.broker.client.subscribe(cmdTopicLimit);
202
+ node.broker.client.subscribe(cmdTopicTime);
203
+ node.broker.client.subscribe(cmdTopicSubmit);
204
+ node.broker.client.subscribe(cmdTopicRefresh);
205
+ }
206
+
207
+ // 5. Helper: Set Preferences (The Mutation)
208
+ let retryTimeouts = []; // Track pending retry timeouts
209
+ let expectedLimit = null;
210
+ let expectedTime = null;
211
+
212
+ // Pending vs Confirmed state
213
+ let pendingLimit = 80;
214
+ let pendingTime = "08:00";
215
+ let confirmedLimit = 80;
216
+ let confirmedTime = "08:00";
217
+
218
+ // Charging Now feature - timer-based state management
219
+ let chargingNow = false;
220
+ let preValidationTimer = null; // Fires 30s before slot start
221
+ let slotStartTimer = null; // Fires at exact slot start
222
+ let slotEndTimer = null; // Fires at exact slot end
223
+ let cachedSlots = []; // Fresh slot data from pre-validation
224
+ let stateCheckInterval = null; // Reconciliation loop (every 10s)
225
+ let lastSentChargingState = null; // Track last sent state to avoid duplicates
226
+
227
+ // Manual refresh rate limiting (only for MQTT button, not Node-RED input)
228
+ let lastManualRefresh = 0; // Timestamp of last manual refresh
229
+ const MANUAL_REFRESH_COOLDOWN = 30000; // 30 seconds in milliseconds
230
+ let cooldownExpiryTimer = null; // Timer to clear cooldown state at expiry
231
+
232
+ // Polling metrics
233
+ let nextPollTime = null; // ISO timestamp of next scheduled poll
234
+ let pollIntervalHandle = null; // Reference to setInterval handle
235
+ let pollHistory = []; // Array of {timestamp, complexity} for last 60 min
236
+
237
+ // API Complexity Tracking
238
+ // Octopus Energy API does not return actual complexity values in headers or extensions,
239
+ // so we use estimated complexity based on query types:
240
+ // - Regular poll (auth + data query): ~300
241
+ // - Mutation (auth + setPreferences): ~250
242
+ // - Pre-validation (auth + plannedDispatches only): ~200
243
+
244
+ // Last known full state - prevents sensors going unknown when controls change
245
+ let lastKnownState = buildDefaultPayload();
246
+
247
+ async function setPreferences(newLimit, newTime) {
248
+ // Validation
249
+ let limit = parseInt(newLimit);
250
+ let time = newTime;
251
+
252
+ // Enforce Limits
253
+ if (isNaN(limit) || limit < 50) limit = 50;
254
+ if (limit > 100) limit = 100;
255
+ // Round to nearest 5
256
+ limit = Math.round(limit / 5) * 5;
257
+
258
+ // Validate Time
259
+ if (!TIME_OPTIONS.includes(time)) {
260
+ node.warn(`Invalid time '${time}' requested. Defaulting to 08:00`);
261
+ time = "08:00";
262
+ }
263
+
264
+ // Cancel any pending retry attempts from previous changes
265
+ retryTimeouts.forEach(timeout => clearTimeout(timeout));
266
+ retryTimeouts = [];
267
+
268
+ try {
269
+ node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
270
+
271
+ // A. Get Token
272
+ const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
273
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
274
+ variables: { input: { APIKey: apiKey } }
275
+ });
276
+
277
+ if (authResponse.data.errors) {
278
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
279
+ }
280
+ if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
281
+ throw new Error(`Auth response missing token data`);
282
+ }
283
+
284
+ const token = authResponse.data.data.obtainKrakenToken.token;
285
+
286
+ // B. Send Mutation
287
+ const mutation = `
288
+ mutation setPreferences($input: VehicleChargingPreferencesInput!) {
289
+ setVehicleChargePreferences(input: $input) { __typename }
290
+ }`;
291
+
292
+ const variables = {
293
+ input: {
294
+ accountNumber: account,
295
+ weekdayTargetSoc: limit,
296
+ weekendTargetSoc: limit,
297
+ weekdayTargetTime: time,
298
+ weekendTargetTime: time
299
+ }
300
+ };
301
+
302
+ const mutationResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
303
+ query: mutation,
304
+ variables: variables
305
+ }, { headers: { Authorization: token } });
306
+
307
+ if (mutationResponse.data.errors) {
308
+ throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
309
+ }
310
+
311
+ // Record mutation API usage (auth + mutation = ~250 complexity)
312
+ const ESTIMATED_MUTATION_COMPLEXITY = 250;
313
+ recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
314
+
315
+ // C. Start exponential backoff validation
316
+ expectedLimit = limit;
317
+ expectedTime = time;
318
+ node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
319
+
320
+ // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
321
+ const retryIntervals = [15000, 30000, 60000, 120000];
322
+ scheduleRetries(retryIntervals, 0);
323
+
324
+ } catch (err) {
325
+ node.error("Failed to set preferences: " + err.message);
326
+ if (err.response) {
327
+ node.error(`Response: ${JSON.stringify(err.response.data)}`);
328
+ }
329
+ node.status({ fill: "red", shape: "ring", text: "Update Failed" });
330
+ expectedLimit = null;
331
+ expectedTime = null;
332
+ }
333
+ }
334
+
335
+ function scheduleRetries(intervals, index) {
336
+ if (index >= intervals.length) {
337
+ // All retries exhausted, let normal interval take over
338
+ node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
339
+ expectedLimit = null;
340
+ expectedTime = null;
341
+ return;
342
+ }
343
+
344
+ const timeout = setTimeout(async () => {
345
+ await fetchDataWithValidation(intervals, index);
346
+ }, intervals[index]);
347
+
348
+ retryTimeouts.push(timeout);
349
+ }
350
+
351
+ async function fetchDataWithValidation(intervals, currentIndex) {
352
+ try {
353
+ const result = await fetchData(true); // Pass flag to indicate validation mode
354
+
355
+ // Check if the data matches our expected values
356
+ if (result && result.validated) {
357
+ // Success! Changes confirmed
358
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${result.confirmedLimit}% @ ${result.confirmedTime}` });
359
+ expectedLimit = null;
360
+ expectedTime = null;
361
+ // Clear remaining timeouts
362
+ retryTimeouts.forEach(timeout => clearTimeout(timeout));
363
+ retryTimeouts = [];
364
+ } else {
365
+ // Not yet updated, schedule next retry
366
+ const attempt = currentIndex + 1;
367
+ const totalAttempts = intervals.length;
368
+ node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
369
+ scheduleRetries(intervals, currentIndex + 1);
370
+ }
371
+ } catch (error) {
372
+ // Error during fetch, schedule next retry
373
+ node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
374
+ scheduleRetries(intervals, currentIndex + 1);
375
+ }
376
+ }
377
+
378
+ // 6. Logic: Fetch Data (Read)
379
+ async function fetchData(validationMode = false) {
380
+ // Estimated complexity per poll:
381
+ // - Auth mutation: ~100 complexity
382
+ // - Data query (plannedDispatches + vehicleChargingPreferences): ~200 complexity
383
+ // - Total: ~300 complexity per poll
384
+ const ESTIMATED_POLL_COMPLEXITY = 300;
385
+
386
+ // Debug object to track API calls
387
+ const debugInfo = {
388
+ timestamp: new Date().toISOString(),
389
+ step: null,
390
+ success: false,
391
+ error: null,
392
+ apiCalls: [],
393
+ validationMode: validationMode
394
+ };
395
+
396
+ if (!apiKey || !account) {
397
+ debugInfo.error = "Missing configuration: apiKey or account number not provided";
398
+ debugInfo.step = "validation";
399
+ node.status({ fill: "red", shape: "ring", text: "Config Missing" });
400
+ node.send({
401
+ payload: buildDefaultPayload(),
402
+ debug: debugInfo
403
+ });
404
+ return { validated: false };
405
+ }
406
+
407
+ try {
408
+ // STEP 1: Get Token
409
+ debugInfo.step = "authentication";
410
+ node.status({ fill: "yellow", shape: "ring", text: "Authenticating..." });
411
+
412
+ const authRequest = {
413
+ url: "https://api.octopus.energy/v1/graphql/",
414
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
415
+ variables: { input: { APIKey: apiKey } }
416
+ };
417
+
418
+ const authResponse = await axios.post(authRequest.url, {
419
+ query: authRequest.query,
420
+ variables: authRequest.variables
421
+ });
422
+
423
+ debugInfo.apiCalls.push({
424
+ step: 1,
425
+ name: "authentication",
426
+ url: authRequest.url,
427
+ statusCode: authResponse.status,
428
+ hasErrors: !!(authResponse.data.errors),
429
+ errors: authResponse.data.errors || null
430
+ });
431
+
432
+ // Validate auth response
433
+ if (authResponse.data.errors) {
434
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
435
+ }
436
+ if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
437
+ throw new Error(`Auth response missing token data. Response: ${JSON.stringify(authResponse.data)}`);
438
+ }
439
+
440
+ const token = authResponse.data.data.obtainKrakenToken.token;
441
+ debugInfo.apiCalls[0].tokenObtained = !!token;
442
+ debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
443
+
444
+ // STEP 2: Fetch Data
445
+ debugInfo.step = "fetching_data";
446
+ node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
447
+
448
+ // Note: rateLimitInfo query may not be available on all API versions
449
+ // If it fails, we'll use fallback estimated complexity
450
+ const masterQuery = `
451
+ query getData($account: String!) {
452
+ plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } }
453
+ vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
454
+ }`;
455
+
456
+ const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
457
+ query: masterQuery,
458
+ variables: { account: account }
459
+ }, { headers: { Authorization: token } });
460
+
461
+ debugInfo.apiCalls.push({
462
+ step: 2,
463
+ name: "data_query",
464
+ url: "https://api.octopus.energy/v1/graphql/",
465
+ accountNumber: account,
466
+ authHeaderFormat: "Raw token (no Bearer/JWT prefix)",
467
+ statusCode: dataResponse.status,
468
+ hasErrors: !!(dataResponse.data.errors),
469
+ errors: dataResponse.data.errors || null,
470
+ hasData: !!(dataResponse.data.data),
471
+ // Capture response headers for rate limit analysis
472
+ responseHeaders: dataResponse.headers || {}
473
+ });
474
+
475
+ // Validate data response
476
+ if (dataResponse.data.errors) {
477
+ throw new Error(`Data query failed: ${JSON.stringify(dataResponse.data.errors)}`);
478
+ }
479
+ if (!dataResponse.data.data) {
480
+ throw new Error(`Data response missing data field. Response: ${JSON.stringify(dataResponse.data)}`);
481
+ }
482
+
483
+ // STEP 3: Extract and Process
484
+ debugInfo.step = "processing";
485
+ const data = dataResponse.data.data || {};
486
+ const slots = data.plannedDispatches || [];
487
+ const prefs = data.vehicleChargingPreferences || {};
488
+
489
+ // Check for GraphQL extensions (may contain complexity/rate limit info)
490
+ let actualComplexity = null;
491
+ if (dataResponse.data.extensions) {
492
+ debugInfo.apiCalls[1].extensions = dataResponse.data.extensions;
493
+ // Try to extract complexity if available
494
+ actualComplexity = dataResponse.data.extensions.complexity ||
495
+ dataResponse.data.extensions.cost ||
496
+ null;
497
+ }
498
+
499
+ // Record poll with estimated or actual complexity
500
+ recordPoll(actualComplexity || ESTIMATED_POLL_COMPLEXITY);
501
+
502
+ debugInfo.apiCalls[1].slotsFound = slots.length;
503
+ debugInfo.apiCalls[1].preferencesFound = !!(prefs.weekdayTargetSoc);
504
+ debugInfo.apiCalls[1].slotDetails = slots.map(s => ({
505
+ start: s.startDt,
506
+ end: s.endDt,
507
+ kwh: s.deltaKwh,
508
+ source: s.meta?.source
509
+ }));
510
+
511
+ // Update Confirmed State (from API)
512
+ confirmedLimit = prefs.weekdayTargetSoc || confirmedLimit;
513
+ confirmedTime = prefs.weekdayTargetTime || confirmedTime;
514
+
515
+ // On successful fetch, sync pending to confirmed if not in validation mode
516
+ if (!validationMode) {
517
+ pendingLimit = confirmedLimit;
518
+ pendingTime = confirmedTime;
519
+ }
520
+
521
+ // Process slots
522
+ const now = new Date();
523
+ // Include active slots (endDt in future) and future slots
524
+ const activeAndFutureSlots = slots.filter(s => new Date(s.endDt) > now);
525
+ const nextSlot = activeAndFutureSlots[0] || null;
526
+
527
+ // Total energy for all active/future slots
528
+ const totalEnergy = activeAndFutureSlots.reduce((sum, s) => sum + (s.deltaKwh || 0), 0);
529
+
530
+ debugInfo.apiCalls[1].activeAndFutureSlots = activeAndFutureSlots.length;
531
+ debugInfo.processingTime = now.toISOString();
532
+
533
+ // Setup charging timers (always update charging state)
534
+ setupChargingTimers(activeAndFutureSlots);
535
+
536
+ // Start reconciliation loop on first successful data fetch (only in non-validation mode)
537
+ if (!validationMode && !stateCheckInterval) {
538
+ startStateReconciliation();
539
+ }
540
+
541
+ // Update next poll time after successful fetch
542
+ updateNextPollTime();
543
+
544
+ // Get API metrics for inclusion in payload
545
+ const apiMetrics = getApiMetrics();
546
+
547
+ // Build Payload
548
+ const statusPayload = {
549
+ next_start: nextSlot ? nextSlot.startDt : null,
550
+ total_energy: parseFloat(totalEnergy.toFixed(2)),
551
+ next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
552
+ next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
553
+ // Confirmed values (from API)
554
+ confirmed_limit: confirmedLimit,
555
+ confirmed_time: confirmedTime,
556
+ // Pending values (user's current selections)
557
+ pending_limit: pendingLimit,
558
+ pending_time: pendingTime,
559
+ // Charging Now state
560
+ charging_now: chargingNow,
561
+ // Next poll time
562
+ next_poll: nextPollTime,
563
+ next_poll_raw: nextPollTime,
564
+ // Refresh available timestamp (null = ready, ISO timestamp = counting down)
565
+ refresh_available_at: getRefreshAvailableAt(),
566
+ // API complexity metrics
567
+ api_requests_hour: apiMetrics.requests_last_hour,
568
+ api_complexity_hour: apiMetrics.complexity_last_hour,
569
+ api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
570
+ // Individual slots (first 3 active/future) - formatted timestamps
571
+ slot1_start: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
572
+ slot1_end: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
573
+ slot2_start: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
574
+ slot2_end: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
575
+ slot3_start: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
576
+ slot3_end: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
577
+ // Overall window (first start to last end) - formatted timestamps
578
+ window_start: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
579
+ window_end: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
580
+ // Raw timestamp strings (exact API output)
581
+ next_start_raw: nextSlot ? nextSlot.startDt : null,
582
+ slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
583
+ slot1_end_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
584
+ slot2_start_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
585
+ slot2_end_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
586
+ slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
587
+ slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
588
+ window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
589
+ window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null
590
+ };
591
+
592
+ // Success!
593
+ debugInfo.success = true;
594
+ debugInfo.step = "complete";
595
+
596
+ // Check if we're validating a preference change
597
+ let isValidated = false;
598
+ if (validationMode && expectedLimit !== null && expectedTime !== null) {
599
+ // Check if the returned values match what we set
600
+ isValidated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
601
+ debugInfo.expectedLimit = expectedLimit;
602
+ debugInfo.expectedTime = expectedTime;
603
+ debugInfo.receivedLimit = confirmedLimit;
604
+ debugInfo.receivedTime = confirmedTime;
605
+ debugInfo.validated = isValidated;
606
+ }
607
+
608
+ // Add API usage metrics to debug info (already fetched above)
609
+ debugInfo.api_usage = {
610
+ requests_last_hour: apiMetrics.requests_last_hour,
611
+ complexity_last_hour: apiMetrics.complexity_last_hour,
612
+ complexity_percent_used: apiMetrics.complexity_percent,
613
+ api_limit_hourly: 50000,
614
+ request_complexity: actualComplexity || ESTIMATED_POLL_COMPLEXITY,
615
+ complexity_source: actualComplexity ? "api" : "estimated"
616
+ };
617
+
618
+ // Store this as the last known full state
619
+ lastKnownState = statusPayload;
620
+
621
+ // ALWAYS publish data to prevent sensors becoming unavailable
622
+ node.send({
623
+ payload: statusPayload,
624
+ debug: debugInfo
625
+ });
626
+
627
+ // Update last sent charging state to prevent duplicate messages
628
+ lastSentChargingState = chargingNow;
629
+
630
+ if (enableMqtt && node.broker) {
631
+ node.broker.client.publish(stateTopic, JSON.stringify(statusPayload), { retain: true });
632
+ // Also publish charging_now state to binary sensor topic
633
+ const chargingPayload = chargingNow ? "ON" : "OFF";
634
+ node.broker.client.publish(`${stateTopic}/charging_now`, chargingPayload, { retain: true });
635
+ }
636
+
637
+ // Update status (validation mode will override this in fetchDataWithValidation)
638
+ if (!validationMode) {
639
+ node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
640
+ }
641
+
642
+ // Return validation result
643
+ return { validated: isValidated || !validationMode, confirmedLimit, confirmedTime };
644
+
645
+ } catch (error) {
646
+ debugInfo.success = false;
647
+ debugInfo.error = {
648
+ message: error.message,
649
+ stack: error.stack,
650
+ response: error.response ? {
651
+ status: error.response.status,
652
+ statusText: error.response.statusText,
653
+ data: error.response.data
654
+ } : null
655
+ };
656
+
657
+ // Log to Node-RED (only if not in validation mode to avoid spam)
658
+ if (!validationMode) {
659
+ node.error(`Octopus API Error at ${debugInfo.step}: ${error.message}`);
660
+ if (error.response) {
661
+ node.error(`Response: ${JSON.stringify(error.response.data)}`);
662
+ }
663
+
664
+ // Update status
665
+ node.status({
666
+ fill: "red",
667
+ shape: "ring",
668
+ text: `Error: ${debugInfo.step}`
669
+ });
670
+
671
+ // Send default payload with debug info
672
+ node.send({
673
+ payload: buildDefaultPayload(),
674
+ debug: debugInfo
675
+ });
676
+ }
677
+
678
+ // Return failure for validation
679
+ return { validated: false };
680
+ }
681
+ }
682
+
683
+ // Helper: Build default payload when errors occur
684
+ function buildDefaultPayload() {
685
+ return {
686
+ next_start: null,
687
+ total_energy: 0,
688
+ next_kwh: "0",
689
+ next_source: "unknown",
690
+ confirmed_limit: confirmedLimit,
691
+ confirmed_time: confirmedTime,
692
+ pending_limit: pendingLimit,
693
+ pending_time: pendingTime,
694
+ charging_now: chargingNow,
695
+ refresh_available_at: null,
696
+ api_requests_hour: 0,
697
+ api_complexity_hour: 0,
698
+ api_complexity_percent: 0,
699
+ slot1_start: null,
700
+ slot1_end: null,
701
+ slot2_start: null,
702
+ slot2_end: null,
703
+ slot3_start: null,
704
+ slot3_end: null,
705
+ window_start: null,
706
+ window_end: null,
707
+ // Raw timestamp strings
708
+ next_start_raw: null,
709
+ slot1_start_raw: null,
710
+ slot1_end_raw: null,
711
+ slot2_start_raw: null,
712
+ slot2_end_raw: null,
713
+ slot3_start_raw: null,
714
+ slot3_end_raw: null,
715
+ window_start_raw: null,
716
+ window_end_raw: null
717
+ };
718
+ }
719
+
720
+ // 6a. Charging Now - Timer Management Functions
721
+
722
+ // State reconciliation - checks every 10s if charging state matches reality
723
+ function reconcileChargingState() {
724
+ if (!cachedSlots || cachedSlots.length === 0) return;
725
+
726
+ const now = new Date();
727
+
728
+ // Check if we should be charging RIGHT NOW based on cached slots
729
+ const shouldBeCharging = cachedSlots.some(slot => {
730
+ const start = new Date(slot.startDt);
731
+ const end = new Date(slot.endDt);
732
+ return start <= now && end > now;
733
+ });
734
+
735
+ // Update state if it doesn't match reality
736
+ if (shouldBeCharging !== chargingNow) {
737
+ node.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
738
+ publishChargingState(shouldBeCharging);
739
+ }
740
+ }
741
+
742
+ // Start state reconciliation loop (every 10 seconds)
743
+ function startStateReconciliation() {
744
+ // Clear existing interval
745
+ if (stateCheckInterval) {
746
+ clearInterval(stateCheckInterval);
747
+ }
748
+
749
+ // Check state every 10 seconds
750
+ stateCheckInterval = setInterval(() => {
751
+ reconcileChargingState();
752
+ }, 10000);
753
+
754
+ node.log("State reconciliation loop started (every 10s)");
755
+ }
756
+
757
+ // Clear all charging timers
758
+ function clearChargingTimers() {
759
+ if (preValidationTimer) {
760
+ clearTimeout(preValidationTimer);
761
+ preValidationTimer = null;
762
+ }
763
+ if (slotStartTimer) {
764
+ clearTimeout(slotStartTimer);
765
+ slotStartTimer = null;
766
+ }
767
+ if (slotEndTimer) {
768
+ clearTimeout(slotEndTimer);
769
+ slotEndTimer = null;
770
+ }
771
+ if (stateCheckInterval) {
772
+ clearInterval(stateCheckInterval);
773
+ stateCheckInterval = null;
774
+ }
775
+ }
776
+
777
+ // Manual refresh rate limiting helpers
778
+ function canManualRefresh() {
779
+ const now = Date.now();
780
+ const timeSinceLastRefresh = now - lastManualRefresh;
781
+ return lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN;
782
+ }
783
+
784
+ function getSecondsUntilNextRefresh() {
785
+ const now = Date.now();
786
+ const timeSinceLastRefresh = now - lastManualRefresh;
787
+ const timeRemaining = MANUAL_REFRESH_COOLDOWN - timeSinceLastRefresh;
788
+ return Math.max(0, Math.ceil(timeRemaining / 1000));
789
+ }
790
+
791
+ function getRefreshAvailableAt() {
792
+ const now = Date.now();
793
+ const timeSinceLastRefresh = now - lastManualRefresh;
794
+
795
+ // If never refreshed OR cooldown expired, ready now
796
+ if (lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN) {
797
+ return null; // Ready - no cooldown
798
+ }
799
+
800
+ // Cooldown active - return timestamp when it expires
801
+ return new Date(lastManualRefresh + MANUAL_REFRESH_COOLDOWN).toISOString();
802
+ }
803
+
804
+ function publishRefreshCooldownState() {
805
+ if (enableMqtt && node.broker) {
806
+ const fullState = {
807
+ ...lastKnownState,
808
+ refresh_available_at: getRefreshAvailableAt()
809
+ };
810
+ node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: true });
811
+ }
812
+ }
813
+
814
+ // Polling metrics helpers
815
+ function updateNextPollTime() {
816
+ nextPollTime = new Date(Date.now() + refreshRate).toISOString();
817
+ }
818
+
819
+ function recordPoll(complexity = null) {
820
+ const now = Date.now();
821
+ pollHistory.push({
822
+ timestamp: now,
823
+ complexity: complexity || null
824
+ });
825
+
826
+ // Remove entries older than 60 minutes
827
+ const sixtyMinAgo = now - (60 * 60 * 1000);
828
+ pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
829
+ }
830
+
831
+ function getApiMetrics() {
832
+ // Clean up old entries first
833
+ const now = Date.now();
834
+ const sixtyMinAgo = now - (60 * 60 * 1000);
835
+ pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
836
+
837
+ const requestCount = pollHistory.length;
838
+ const totalComplexity = pollHistory.reduce((sum, entry) => sum + (entry.complexity || 0), 0);
839
+ const percentUsed = requestCount > 0 && totalComplexity > 0 ? (totalComplexity / 50000) * 100 : 0;
840
+
841
+ return {
842
+ requests_last_hour: requestCount,
843
+ complexity_last_hour: totalComplexity,
844
+ complexity_percent: percentUsed.toFixed(1)
845
+ };
846
+ }
847
+
848
+ // Publish charging state to MQTT and Node-RED
849
+ function publishChargingState(state) {
850
+ chargingNow = state;
851
+
852
+ // Update MQTT
853
+ if (enableMqtt && node.broker) {
854
+ const payload = state ? "ON" : "OFF";
855
+ node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
856
+ }
857
+
858
+ // Output message to Node-RED flow if state actually changed
859
+ if (lastSentChargingState !== state) {
860
+ lastSentChargingState = state;
861
+
862
+ // Merge updated charging_now into last known full state
863
+ const outputPayload = {
864
+ ...lastKnownState,
865
+ charging_now: state
866
+ };
867
+
868
+ node.send({
869
+ payload: outputPayload,
870
+ debug: {
871
+ timestamp: new Date().toISOString(),
872
+ trigger: 'charging_state_change',
873
+ success: true,
874
+ previous_state: !state,
875
+ new_state: state
876
+ }
877
+ });
878
+
879
+ node.log(`Charging state changed: ${!state} → ${state}, message sent`);
880
+ }
881
+ }
882
+
883
+ // Setup pre-validation timer (30s before slot starts)
884
+ function setupPreValidationTimer(nextSlot) {
885
+ const now = new Date();
886
+ const slotStart = new Date(nextSlot.startDt);
887
+ const preValidationTime = slotStart.getTime() - 30000; // 30s before
888
+ const msUntilPreValidation = preValidationTime - now.getTime();
889
+
890
+ if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
891
+ preValidationTimer = setTimeout(async () => {
892
+ node.warn("Pre-validating slot data (30s before start)");
893
+ try {
894
+ // Fetch fresh data from API
895
+ const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
896
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
897
+ variables: { input: { APIKey: apiKey } }
898
+ });
899
+
900
+ if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
901
+ throw new Error("Pre-validation auth failed");
902
+ }
903
+
904
+ const token = authResponse.data.data.obtainKrakenToken.token;
905
+
906
+ const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
907
+ query: `query getData($account: String!) { plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } } }`,
908
+ variables: { account: account }
909
+ }, { headers: { Authorization: token } });
910
+
911
+ if (dataResponse.data.data && dataResponse.data.data.plannedDispatches) {
912
+ cachedSlots = dataResponse.data.data.plannedDispatches;
913
+
914
+ // Record pre-validation API usage (auth + simple query = ~200 complexity)
915
+ const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
916
+ recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
917
+
918
+ // Check if slot still exists (within 1 minute tolerance)
919
+ const stillExists = cachedSlots.find(s =>
920
+ Math.abs(new Date(s.startDt).getTime() - slotStart.getTime()) < 60000
921
+ );
922
+
923
+ if (stillExists) {
924
+ node.warn(`Slot confirmed at ${stillExists.startDt}`);
925
+ setupSlotStartTimer(stillExists);
926
+ } else {
927
+ node.warn("Slot was cancelled or modified - not setting start timer");
928
+ }
929
+ }
930
+ } catch (error) {
931
+ node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
932
+ // Fallback: use original slot data
933
+ setupSlotStartTimer(nextSlot);
934
+ }
935
+ }, msUntilPreValidation);
936
+
937
+ const minutesUntil = Math.round(msUntilPreValidation / 60000);
938
+ node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
939
+ }
940
+ }
941
+
942
+ // Setup slot start timer (exact start time)
943
+ function setupSlotStartTimer(slot) {
944
+ const now = new Date();
945
+ const slotStart = new Date(slot.startDt);
946
+ const msUntilStart = slotStart.getTime() - now.getTime();
947
+
948
+ if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
949
+ slotStartTimer = setTimeout(() => {
950
+ publishChargingState(true);
951
+ node.warn(`Charging slot started at ${slot.startDt}`);
952
+ setupSlotEndTimer(slot);
953
+ }, msUntilStart);
954
+
955
+ const secondsUntil = Math.round(msUntilStart / 1000);
956
+ node.log(`Slot start timer set for ${secondsUntil}s (${slot.startDt})`);
957
+ } else if (msUntilStart <= 0) {
958
+ // Slot already started, check if it's still active
959
+ const slotEnd = new Date(slot.endDt);
960
+ if (slotEnd > now) {
961
+ publishChargingState(true);
962
+ setupSlotEndTimer(slot);
963
+ }
964
+ }
965
+ }
966
+
967
+ // Setup slot end timer (exact end time)
968
+ function setupSlotEndTimer(slot) {
969
+ const now = new Date();
970
+ const slotEnd = new Date(slot.endDt);
971
+ const msUntilEnd = slotEnd.getTime() - now.getTime();
972
+
973
+ if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
974
+ slotEndTimer = setTimeout(() => {
975
+ node.warn(`Charging slot ended at ${slot.endDt}`);
976
+
977
+ // Check if another slot starts immediately (within cached data)
978
+ const now = new Date();
979
+ const immediateNextSlot = cachedSlots.find(s => {
980
+ const start = new Date(s.startDt);
981
+ const end = new Date(s.endDt);
982
+ return start <= now && end > now;
983
+ });
984
+
985
+ if (immediateNextSlot) {
986
+ node.warn("Next slot starting immediately");
987
+ publishChargingState(true);
988
+ setupSlotEndTimer(immediateNextSlot);
989
+ } else {
990
+ publishChargingState(false);
991
+ }
992
+ }, msUntilEnd);
993
+
994
+ const minutesUntil = Math.round(msUntilEnd / 60000);
995
+ node.log(`Slot end timer set for ${minutesUntil} min (${slot.endDt})`);
996
+ }
997
+ }
998
+
999
+ // Main timer setup - called on each poll
1000
+ function setupChargingTimers(slots) {
1001
+ // Clear existing timers
1002
+ clearChargingTimers();
1003
+
1004
+ // Cache slots for later use
1005
+ cachedSlots = slots;
1006
+
1007
+ const now = new Date();
1008
+
1009
+ // Check if currently in a charging slot
1010
+ const activeSlot = slots.find(s => {
1011
+ const start = new Date(s.startDt);
1012
+ const end = new Date(s.endDt);
1013
+ return start <= now && end > now;
1014
+ });
1015
+
1016
+ if (activeSlot) {
1017
+ // Currently charging
1018
+ const newState = true;
1019
+ if (chargingNow !== newState) {
1020
+ publishChargingState(newState);
1021
+ }
1022
+ setupSlotEndTimer(activeSlot);
1023
+ node.log("Currently charging - end timer set");
1024
+ } else {
1025
+ // Not currently charging
1026
+ const newState = false;
1027
+ if (chargingNow !== newState) {
1028
+ publishChargingState(newState);
1029
+ }
1030
+
1031
+ // Find next future slot
1032
+ const nextSlot = slots.find(s => new Date(s.startDt) > now);
1033
+
1034
+ if (nextSlot) {
1035
+ setupPreValidationTimer(nextSlot);
1036
+ node.log(`Next slot at ${nextSlot.startDt}`);
1037
+ }
1038
+ }
1039
+ }
1040
+
1041
+ // 7. Event Listeners
1042
+
1043
+ // Helper: Publish current state (both pending and confirmed)
1044
+ // This merges pending values into last known full state to prevent sensors going unknown
1045
+ function publishCurrentState() {
1046
+ if (enableMqtt && node.broker) {
1047
+ // Merge pending values into last known state
1048
+ const fullState = {
1049
+ ...lastKnownState,
1050
+ pending_limit: pendingLimit,
1051
+ pending_time: pendingTime,
1052
+ confirmed_limit: confirmedLimit,
1053
+ confirmed_time: confirmedTime
1054
+ };
1055
+ node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: false });
1056
+ }
1057
+ }
1058
+
1059
+ // A. Handle Node-RED Input Messages (NO rate limiting - programmers control this)
1060
+ node.on('input', function (msg) {
1061
+ // Check for control commands (preference updates)
1062
+ if (msg.payload && typeof msg.payload === 'object') {
1063
+ if (msg.payload.set_limit || msg.payload.set_time) {
1064
+ // Use new values if present, otherwise keep existing
1065
+ const targetLimit = msg.payload.set_limit || confirmedLimit;
1066
+ const targetTime = msg.payload.set_time || confirmedTime;
1067
+ setPreferences(targetLimit, targetTime);
1068
+ return; // Don't run standard fetch if setting
1069
+ }
1070
+ }
1071
+
1072
+ // Manual refresh request from Node-RED - NO rate limiting
1073
+ // (Programmers can control rate limiting in their flows if needed)
1074
+ // Update timestamp so HA sees cooldown, but don't block the refresh
1075
+ lastManualRefresh = Date.now();
1076
+ node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1077
+ fetchData();
1078
+ });
1079
+
1080
+ // B. Handle MQTT Commands (Home Assistant)
1081
+ if (enableMqtt && node.broker) {
1082
+ node.broker.register(this);
1083
+
1084
+ // Slider changed - update pending value only
1085
+ node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
1086
+ const val = parseInt(payload.toString());
1087
+ pendingLimit = val;
1088
+ publishCurrentState(); // Update display immediately
1089
+ node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1090
+ });
1091
+
1092
+ // Dropdown changed - update pending value only
1093
+ node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
1094
+ const val = payload.toString();
1095
+ pendingTime = val;
1096
+ publishCurrentState(); // Update display immediately
1097
+ node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
1098
+ });
1099
+
1100
+ // Button pressed - submit changes to API
1101
+ node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
1102
+ setPreferences(pendingLimit, pendingTime);
1103
+ });
1104
+
1105
+ // Refresh button pressed - MQTT has hardcoded 30s rate limiting
1106
+ node.broker.subscribe(cmdTopicRefresh, 0, (topic, payload) => {
1107
+ // Check rate limit (only for MQTT button)
1108
+ if (!canManualRefresh()) {
1109
+ const secondsRemaining = getSecondsUntilNextRefresh();
1110
+ node.status({
1111
+ fill: "red",
1112
+ shape: "dot",
1113
+ text: `Cooldown: ${secondsRemaining}s`
1114
+ });
1115
+ node.warn(`MQTT refresh blocked. Please wait ${secondsRemaining} seconds.`);
1116
+ return; // Block the refresh
1117
+ }
1118
+
1119
+ // Refresh allowed - set cooldown timestamp
1120
+ lastManualRefresh = Date.now();
1121
+
1122
+ // Publish immediate update with countdown timestamp
1123
+ publishRefreshCooldownState();
1124
+
1125
+ // Schedule cleanup at exactly 30 seconds to clear countdown
1126
+ if (cooldownExpiryTimer) clearTimeout(cooldownExpiryTimer);
1127
+ cooldownExpiryTimer = setTimeout(() => {
1128
+ // Cooldown expired - publish null to clear countdown in HA
1129
+ publishRefreshCooldownState();
1130
+ cooldownExpiryTimer = null;
1131
+ }, MANUAL_REFRESH_COOLDOWN);
1132
+
1133
+ // Trigger the actual refresh
1134
+ node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1135
+ fetchData();
1136
+ });
1137
+
1138
+ setTimeout(announceControls, 2000);
1139
+ }
1140
+
1141
+ // Init
1142
+ pollIntervalHandle = setInterval(fetchData, refreshRate);
1143
+ updateNextPollTime(); // Set initial next poll time
1144
+ setTimeout(fetchData, 1000);
1145
+ node.on('close', () => {
1146
+ clearInterval(pollIntervalHandle);
1147
+ // Clear any pending retry timeouts
1148
+ retryTimeouts.forEach(timeout => clearTimeout(timeout));
1149
+ retryTimeouts = [];
1150
+ // Clear charging timers
1151
+ clearChargingTimers();
1152
+ // Clear cooldown expiry timer
1153
+ if (cooldownExpiryTimer) {
1154
+ clearTimeout(cooldownExpiryTimer);
1155
+ cooldownExpiryTimer = null;
1156
+ }
1157
+ if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh);
1158
+ });
1159
+ }
1160
+
1161
+ RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
1162
+ credentials: { apiKey: { type: "password" } }
1163
+ });
862
1164
  };