node-red-contrib-octopus-intelligent 1.0.2 → 1.0.3
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 +145 -118
- package/NodeRed_Global_Setter.js +76 -0
- package/RELEASE.md +140 -0
- package/examples/basic-monitoring.json +1 -0
- package/examples/mqtt-integration.json +1 -0
- package/examples/set-preferences.json +1 -0
- package/octopus-intelligent.js +914 -861
- package/package.json +47 -46
package/octopus-intelligent.js
CHANGED
|
@@ -1,862 +1,915 @@
|
|
|
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
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
//
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
input: {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
node.
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
//
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
//
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
debugInfo.
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
//
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
//
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
//
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
const
|
|
628
|
-
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
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
|
+
|
|
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
|
+
let stateCheckInterval = null; // Reconciliation loop (every 10s)
|
|
197
|
+
|
|
198
|
+
// Last known full state - prevents sensors going unknown when controls change
|
|
199
|
+
let lastKnownState = buildDefaultPayload();
|
|
200
|
+
|
|
201
|
+
async function setPreferences(newLimit, newTime) {
|
|
202
|
+
// Validation
|
|
203
|
+
let limit = parseInt(newLimit);
|
|
204
|
+
let time = newTime;
|
|
205
|
+
|
|
206
|
+
// Enforce Limits
|
|
207
|
+
if (isNaN(limit) || limit < 50) limit = 50;
|
|
208
|
+
if (limit > 100) limit = 100;
|
|
209
|
+
// Round to nearest 5
|
|
210
|
+
limit = Math.round(limit / 5) * 5;
|
|
211
|
+
|
|
212
|
+
// Validate Time
|
|
213
|
+
if (!TIME_OPTIONS.includes(time)) {
|
|
214
|
+
node.warn(`Invalid time '${time}' requested. Defaulting to 08:00`);
|
|
215
|
+
time = "08:00";
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Cancel any pending retry attempts from previous changes
|
|
219
|
+
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
220
|
+
retryTimeouts = [];
|
|
221
|
+
|
|
222
|
+
try {
|
|
223
|
+
node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
|
|
224
|
+
|
|
225
|
+
// A. Get Token
|
|
226
|
+
const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
227
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
228
|
+
variables: { input: { APIKey: apiKey } }
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
if (authResponse.data.errors) {
|
|
232
|
+
throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
|
|
233
|
+
}
|
|
234
|
+
if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
235
|
+
throw new Error(`Auth response missing token data`);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
239
|
+
|
|
240
|
+
// B. Send Mutation
|
|
241
|
+
const mutation = `
|
|
242
|
+
mutation setPreferences($input: VehicleChargingPreferencesInput!) {
|
|
243
|
+
setVehicleChargePreferences(input: $input) { __typename }
|
|
244
|
+
}`;
|
|
245
|
+
|
|
246
|
+
const variables = {
|
|
247
|
+
input: {
|
|
248
|
+
accountNumber: account,
|
|
249
|
+
weekdayTargetSoc: limit,
|
|
250
|
+
weekendTargetSoc: limit,
|
|
251
|
+
weekdayTargetTime: time,
|
|
252
|
+
weekendTargetTime: time
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const mutationResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
257
|
+
query: mutation,
|
|
258
|
+
variables: variables
|
|
259
|
+
}, { headers: { Authorization: token } });
|
|
260
|
+
|
|
261
|
+
if (mutationResponse.data.errors) {
|
|
262
|
+
throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// C. Start exponential backoff validation
|
|
266
|
+
expectedLimit = limit;
|
|
267
|
+
expectedTime = time;
|
|
268
|
+
node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
|
|
269
|
+
|
|
270
|
+
// Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
|
|
271
|
+
const retryIntervals = [15000, 30000, 60000, 120000];
|
|
272
|
+
scheduleRetries(retryIntervals, 0);
|
|
273
|
+
|
|
274
|
+
} catch (err) {
|
|
275
|
+
node.error("Failed to set preferences: " + err.message);
|
|
276
|
+
if (err.response) {
|
|
277
|
+
node.error(`Response: ${JSON.stringify(err.response.data)}`);
|
|
278
|
+
}
|
|
279
|
+
node.status({ fill: "red", shape: "ring", text: "Update Failed" });
|
|
280
|
+
expectedLimit = null;
|
|
281
|
+
expectedTime = null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function scheduleRetries(intervals, index) {
|
|
286
|
+
if (index >= intervals.length) {
|
|
287
|
+
// All retries exhausted, let normal interval take over
|
|
288
|
+
node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
|
|
289
|
+
expectedLimit = null;
|
|
290
|
+
expectedTime = null;
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const timeout = setTimeout(async () => {
|
|
295
|
+
await fetchDataWithValidation(intervals, index);
|
|
296
|
+
}, intervals[index]);
|
|
297
|
+
|
|
298
|
+
retryTimeouts.push(timeout);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function fetchDataWithValidation(intervals, currentIndex) {
|
|
302
|
+
try {
|
|
303
|
+
const result = await fetchData(true); // Pass flag to indicate validation mode
|
|
304
|
+
|
|
305
|
+
// Check if the data matches our expected values
|
|
306
|
+
if (result && result.validated) {
|
|
307
|
+
// Success! Changes confirmed
|
|
308
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${result.confirmedLimit}% @ ${result.confirmedTime}` });
|
|
309
|
+
expectedLimit = null;
|
|
310
|
+
expectedTime = null;
|
|
311
|
+
// Clear remaining timeouts
|
|
312
|
+
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
313
|
+
retryTimeouts = [];
|
|
314
|
+
} else {
|
|
315
|
+
// Not yet updated, schedule next retry
|
|
316
|
+
const attempt = currentIndex + 1;
|
|
317
|
+
const totalAttempts = intervals.length;
|
|
318
|
+
node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
|
|
319
|
+
scheduleRetries(intervals, currentIndex + 1);
|
|
320
|
+
}
|
|
321
|
+
} catch (error) {
|
|
322
|
+
// Error during fetch, schedule next retry
|
|
323
|
+
node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
|
|
324
|
+
scheduleRetries(intervals, currentIndex + 1);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// 6. Logic: Fetch Data (Read)
|
|
329
|
+
async function fetchData(validationMode = false) {
|
|
330
|
+
// Debug object to track API calls
|
|
331
|
+
const debugInfo = {
|
|
332
|
+
timestamp: new Date().toISOString(),
|
|
333
|
+
step: null,
|
|
334
|
+
success: false,
|
|
335
|
+
error: null,
|
|
336
|
+
apiCalls: [],
|
|
337
|
+
validationMode: validationMode
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
if (!apiKey || !account) {
|
|
341
|
+
debugInfo.error = "Missing configuration: apiKey or account number not provided";
|
|
342
|
+
debugInfo.step = "validation";
|
|
343
|
+
node.status({ fill: "red", shape: "ring", text: "Config Missing" });
|
|
344
|
+
node.send({
|
|
345
|
+
payload: buildDefaultPayload(),
|
|
346
|
+
debug: debugInfo
|
|
347
|
+
});
|
|
348
|
+
return { validated: false };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
try {
|
|
352
|
+
// STEP 1: Get Token
|
|
353
|
+
debugInfo.step = "authentication";
|
|
354
|
+
node.status({ fill: "yellow", shape: "ring", text: "Authenticating..." });
|
|
355
|
+
|
|
356
|
+
const authRequest = {
|
|
357
|
+
url: "https://api.octopus.energy/v1/graphql/",
|
|
358
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
359
|
+
variables: { input: { APIKey: apiKey } }
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
const authResponse = await axios.post(authRequest.url, {
|
|
363
|
+
query: authRequest.query,
|
|
364
|
+
variables: authRequest.variables
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
debugInfo.apiCalls.push({
|
|
368
|
+
step: 1,
|
|
369
|
+
name: "authentication",
|
|
370
|
+
url: authRequest.url,
|
|
371
|
+
statusCode: authResponse.status,
|
|
372
|
+
hasErrors: !!(authResponse.data.errors),
|
|
373
|
+
errors: authResponse.data.errors || null
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
// Validate auth response
|
|
377
|
+
if (authResponse.data.errors) {
|
|
378
|
+
throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
|
|
379
|
+
}
|
|
380
|
+
if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
381
|
+
throw new Error(`Auth response missing token data. Response: ${JSON.stringify(authResponse.data)}`);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
385
|
+
debugInfo.apiCalls[0].tokenObtained = !!token;
|
|
386
|
+
debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
|
|
387
|
+
|
|
388
|
+
// STEP 2: Fetch Data
|
|
389
|
+
debugInfo.step = "fetching_data";
|
|
390
|
+
node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
|
|
391
|
+
|
|
392
|
+
const masterQuery = `
|
|
393
|
+
query getData($account: String!) {
|
|
394
|
+
plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } }
|
|
395
|
+
vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
|
|
396
|
+
}`;
|
|
397
|
+
|
|
398
|
+
const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
399
|
+
query: masterQuery,
|
|
400
|
+
variables: { account: account }
|
|
401
|
+
}, { headers: { Authorization: token } });
|
|
402
|
+
|
|
403
|
+
debugInfo.apiCalls.push({
|
|
404
|
+
step: 2,
|
|
405
|
+
name: "data_query",
|
|
406
|
+
url: "https://api.octopus.energy/v1/graphql/",
|
|
407
|
+
accountNumber: account,
|
|
408
|
+
authHeaderFormat: "Raw token (no Bearer/JWT prefix)",
|
|
409
|
+
statusCode: dataResponse.status,
|
|
410
|
+
hasErrors: !!(dataResponse.data.errors),
|
|
411
|
+
errors: dataResponse.data.errors || null,
|
|
412
|
+
hasData: !!(dataResponse.data.data)
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
// Validate data response
|
|
416
|
+
if (dataResponse.data.errors) {
|
|
417
|
+
throw new Error(`Data query failed: ${JSON.stringify(dataResponse.data.errors)}`);
|
|
418
|
+
}
|
|
419
|
+
if (!dataResponse.data.data) {
|
|
420
|
+
throw new Error(`Data response missing data field. Response: ${JSON.stringify(dataResponse.data)}`);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// STEP 3: Extract and Process
|
|
424
|
+
debugInfo.step = "processing";
|
|
425
|
+
const data = dataResponse.data.data || {};
|
|
426
|
+
const slots = data.plannedDispatches || [];
|
|
427
|
+
const prefs = data.vehicleChargingPreferences || {};
|
|
428
|
+
|
|
429
|
+
debugInfo.apiCalls[1].slotsFound = slots.length;
|
|
430
|
+
debugInfo.apiCalls[1].preferencesFound = !!(prefs.weekdayTargetSoc);
|
|
431
|
+
debugInfo.apiCalls[1].slotDetails = slots.map(s => ({
|
|
432
|
+
start: s.startDt,
|
|
433
|
+
end: s.endDt,
|
|
434
|
+
kwh: s.deltaKwh,
|
|
435
|
+
source: s.meta?.source
|
|
436
|
+
}));
|
|
437
|
+
|
|
438
|
+
// Update Confirmed State (from API)
|
|
439
|
+
confirmedLimit = prefs.weekdayTargetSoc || confirmedLimit;
|
|
440
|
+
confirmedTime = prefs.weekdayTargetTime || confirmedTime;
|
|
441
|
+
|
|
442
|
+
// On successful fetch, sync pending to confirmed if not in validation mode
|
|
443
|
+
if (!validationMode) {
|
|
444
|
+
pendingLimit = confirmedLimit;
|
|
445
|
+
pendingTime = confirmedTime;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// Process slots
|
|
449
|
+
const now = new Date();
|
|
450
|
+
// Include active slots (endDt in future) and future slots
|
|
451
|
+
const activeAndFutureSlots = slots.filter(s => new Date(s.endDt) > now);
|
|
452
|
+
const nextSlot = activeAndFutureSlots[0] || null;
|
|
453
|
+
|
|
454
|
+
// Total energy for all active/future slots
|
|
455
|
+
const totalEnergy = activeAndFutureSlots.reduce((sum, s) => sum + (s.deltaKwh || 0), 0);
|
|
456
|
+
|
|
457
|
+
debugInfo.apiCalls[1].activeAndFutureSlots = activeAndFutureSlots.length;
|
|
458
|
+
debugInfo.processingTime = now.toISOString();
|
|
459
|
+
|
|
460
|
+
// Setup charging timers (only in non-validation mode)
|
|
461
|
+
if (!validationMode) {
|
|
462
|
+
setupChargingTimers(activeAndFutureSlots);
|
|
463
|
+
// Start reconciliation loop on first successful data fetch
|
|
464
|
+
if (!stateCheckInterval) {
|
|
465
|
+
startStateReconciliation();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// Build Payload
|
|
470
|
+
const statusPayload = {
|
|
471
|
+
next_start: nextSlot ? nextSlot.startDt : null,
|
|
472
|
+
total_energy: parseFloat(totalEnergy.toFixed(2)),
|
|
473
|
+
next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
|
|
474
|
+
next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
|
|
475
|
+
// Confirmed values (from API)
|
|
476
|
+
confirmed_limit: confirmedLimit,
|
|
477
|
+
confirmed_time: confirmedTime,
|
|
478
|
+
// Pending values (user's current selections)
|
|
479
|
+
pending_limit: pendingLimit,
|
|
480
|
+
pending_time: pendingTime,
|
|
481
|
+
// Charging Now state
|
|
482
|
+
charging_now: chargingNow,
|
|
483
|
+
// Individual slots (first 3 active/future) - formatted timestamps
|
|
484
|
+
slot1_start: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
|
|
485
|
+
slot1_end: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
|
|
486
|
+
slot2_start: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
|
|
487
|
+
slot2_end: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
|
|
488
|
+
slot3_start: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
|
|
489
|
+
slot3_end: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
|
|
490
|
+
// Overall window (first start to last end) - formatted timestamps
|
|
491
|
+
window_start: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
|
|
492
|
+
window_end: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
|
|
493
|
+
// Raw timestamp strings (exact API output)
|
|
494
|
+
next_start_raw: nextSlot ? nextSlot.startDt : null,
|
|
495
|
+
slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
|
|
496
|
+
slot1_end_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
|
|
497
|
+
slot2_start_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
|
|
498
|
+
slot2_end_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
|
|
499
|
+
slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
|
|
500
|
+
slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
|
|
501
|
+
window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
|
|
502
|
+
window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
// Success!
|
|
506
|
+
debugInfo.success = true;
|
|
507
|
+
debugInfo.step = "complete";
|
|
508
|
+
|
|
509
|
+
// Check if we're validating a preference change
|
|
510
|
+
let isValidated = false;
|
|
511
|
+
if (validationMode && expectedLimit !== null && expectedTime !== null) {
|
|
512
|
+
// Check if the returned values match what we set
|
|
513
|
+
isValidated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
|
|
514
|
+
debugInfo.expectedLimit = expectedLimit;
|
|
515
|
+
debugInfo.expectedTime = expectedTime;
|
|
516
|
+
debugInfo.receivedLimit = confirmedLimit;
|
|
517
|
+
debugInfo.receivedTime = confirmedTime;
|
|
518
|
+
debugInfo.validated = isValidated;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Store this as the last known full state
|
|
522
|
+
lastKnownState = statusPayload;
|
|
523
|
+
|
|
524
|
+
// ALWAYS publish data to prevent sensors becoming unavailable
|
|
525
|
+
node.send({
|
|
526
|
+
payload: statusPayload,
|
|
527
|
+
debug: debugInfo
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
if (enableMqtt && node.broker) {
|
|
531
|
+
node.broker.client.publish(stateTopic, JSON.stringify(statusPayload), { retain: true });
|
|
532
|
+
// Also publish charging_now state to binary sensor topic
|
|
533
|
+
const chargingPayload = chargingNow ? "ON" : "OFF";
|
|
534
|
+
node.broker.client.publish(`${stateTopic}/charging_now`, chargingPayload, { retain: true });
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// Update status (validation mode will override this in fetchDataWithValidation)
|
|
538
|
+
if (!validationMode) {
|
|
539
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// Return validation result
|
|
543
|
+
return { validated: isValidated || !validationMode, confirmedLimit, confirmedTime };
|
|
544
|
+
|
|
545
|
+
} catch (error) {
|
|
546
|
+
debugInfo.success = false;
|
|
547
|
+
debugInfo.error = {
|
|
548
|
+
message: error.message,
|
|
549
|
+
stack: error.stack,
|
|
550
|
+
response: error.response ? {
|
|
551
|
+
status: error.response.status,
|
|
552
|
+
statusText: error.response.statusText,
|
|
553
|
+
data: error.response.data
|
|
554
|
+
} : null
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
// Log to Node-RED (only if not in validation mode to avoid spam)
|
|
558
|
+
if (!validationMode) {
|
|
559
|
+
node.error(`Octopus API Error at ${debugInfo.step}: ${error.message}`);
|
|
560
|
+
if (error.response) {
|
|
561
|
+
node.error(`Response: ${JSON.stringify(error.response.data)}`);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// Update status
|
|
565
|
+
node.status({
|
|
566
|
+
fill: "red",
|
|
567
|
+
shape: "ring",
|
|
568
|
+
text: `Error: ${debugInfo.step}`
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
// Send default payload with debug info
|
|
572
|
+
node.send({
|
|
573
|
+
payload: buildDefaultPayload(),
|
|
574
|
+
debug: debugInfo
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// Return failure for validation
|
|
579
|
+
return { validated: false };
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Helper: Build default payload when errors occur
|
|
584
|
+
function buildDefaultPayload() {
|
|
585
|
+
return {
|
|
586
|
+
next_start: null,
|
|
587
|
+
total_energy: 0,
|
|
588
|
+
next_kwh: "0",
|
|
589
|
+
next_source: "unknown",
|
|
590
|
+
confirmed_limit: confirmedLimit,
|
|
591
|
+
confirmed_time: confirmedTime,
|
|
592
|
+
pending_limit: pendingLimit,
|
|
593
|
+
pending_time: pendingTime,
|
|
594
|
+
charging_now: chargingNow,
|
|
595
|
+
slot1_start: null,
|
|
596
|
+
slot1_end: null,
|
|
597
|
+
slot2_start: null,
|
|
598
|
+
slot2_end: null,
|
|
599
|
+
slot3_start: null,
|
|
600
|
+
slot3_end: null,
|
|
601
|
+
window_start: null,
|
|
602
|
+
window_end: null,
|
|
603
|
+
// Raw timestamp strings
|
|
604
|
+
next_start_raw: null,
|
|
605
|
+
slot1_start_raw: null,
|
|
606
|
+
slot1_end_raw: null,
|
|
607
|
+
slot2_start_raw: null,
|
|
608
|
+
slot2_end_raw: null,
|
|
609
|
+
slot3_start_raw: null,
|
|
610
|
+
slot3_end_raw: null,
|
|
611
|
+
window_start_raw: null,
|
|
612
|
+
window_end_raw: null
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// 6a. Charging Now - Timer Management Functions
|
|
617
|
+
|
|
618
|
+
// State reconciliation - checks every 10s if charging state matches reality
|
|
619
|
+
function reconcileChargingState() {
|
|
620
|
+
if (!cachedSlots || cachedSlots.length === 0) return;
|
|
621
|
+
|
|
622
|
+
const now = new Date();
|
|
623
|
+
|
|
624
|
+
// Check if we should be charging RIGHT NOW based on cached slots
|
|
625
|
+
const shouldBeCharging = cachedSlots.some(slot => {
|
|
626
|
+
const start = new Date(slot.startDt);
|
|
627
|
+
const end = new Date(slot.endDt);
|
|
628
|
+
return start <= now && end > now;
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
// Update state if it doesn't match reality
|
|
632
|
+
if (shouldBeCharging !== chargingNow) {
|
|
633
|
+
node.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
|
|
634
|
+
publishChargingState(shouldBeCharging);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// Start state reconciliation loop (every 10 seconds)
|
|
639
|
+
function startStateReconciliation() {
|
|
640
|
+
// Clear existing interval
|
|
641
|
+
if (stateCheckInterval) {
|
|
642
|
+
clearInterval(stateCheckInterval);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Check state every 10 seconds
|
|
646
|
+
stateCheckInterval = setInterval(() => {
|
|
647
|
+
reconcileChargingState();
|
|
648
|
+
}, 10000);
|
|
649
|
+
|
|
650
|
+
node.log("State reconciliation loop started (every 10s)");
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// Clear all charging timers
|
|
654
|
+
function clearChargingTimers() {
|
|
655
|
+
if (preValidationTimer) {
|
|
656
|
+
clearTimeout(preValidationTimer);
|
|
657
|
+
preValidationTimer = null;
|
|
658
|
+
}
|
|
659
|
+
if (slotStartTimer) {
|
|
660
|
+
clearTimeout(slotStartTimer);
|
|
661
|
+
slotStartTimer = null;
|
|
662
|
+
}
|
|
663
|
+
if (slotEndTimer) {
|
|
664
|
+
clearTimeout(slotEndTimer);
|
|
665
|
+
slotEndTimer = null;
|
|
666
|
+
}
|
|
667
|
+
if (stateCheckInterval) {
|
|
668
|
+
clearInterval(stateCheckInterval);
|
|
669
|
+
stateCheckInterval = null;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Publish charging state to MQTT
|
|
674
|
+
function publishChargingState(state) {
|
|
675
|
+
chargingNow = state;
|
|
676
|
+
if (enableMqtt && node.broker) {
|
|
677
|
+
const payload = state ? "ON" : "OFF";
|
|
678
|
+
node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// Setup pre-validation timer (30s before slot starts)
|
|
683
|
+
function setupPreValidationTimer(nextSlot) {
|
|
684
|
+
const now = new Date();
|
|
685
|
+
const slotStart = new Date(nextSlot.startDt);
|
|
686
|
+
const preValidationTime = slotStart.getTime() - 30000; // 30s before
|
|
687
|
+
const msUntilPreValidation = preValidationTime - now.getTime();
|
|
688
|
+
|
|
689
|
+
if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
690
|
+
preValidationTimer = setTimeout(async () => {
|
|
691
|
+
node.warn("Pre-validating slot data (30s before start)");
|
|
692
|
+
try {
|
|
693
|
+
// Fetch fresh data from API
|
|
694
|
+
const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
695
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
696
|
+
variables: { input: { APIKey: apiKey } }
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
700
|
+
throw new Error("Pre-validation auth failed");
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
704
|
+
|
|
705
|
+
const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
706
|
+
query: `query getData($account: String!) { plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } } }`,
|
|
707
|
+
variables: { account: account }
|
|
708
|
+
}, { headers: { Authorization: token } });
|
|
709
|
+
|
|
710
|
+
if (dataResponse.data.data && dataResponse.data.data.plannedDispatches) {
|
|
711
|
+
cachedSlots = dataResponse.data.data.plannedDispatches;
|
|
712
|
+
|
|
713
|
+
// Check if slot still exists (within 1 minute tolerance)
|
|
714
|
+
const stillExists = cachedSlots.find(s =>
|
|
715
|
+
Math.abs(new Date(s.startDt).getTime() - slotStart.getTime()) < 60000
|
|
716
|
+
);
|
|
717
|
+
|
|
718
|
+
if (stillExists) {
|
|
719
|
+
node.warn(`Slot confirmed at ${stillExists.startDt}`);
|
|
720
|
+
setupSlotStartTimer(stillExists);
|
|
721
|
+
} else {
|
|
722
|
+
node.warn("Slot was cancelled or modified - not setting start timer");
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
} catch (error) {
|
|
726
|
+
node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
|
|
727
|
+
// Fallback: use original slot data
|
|
728
|
+
setupSlotStartTimer(nextSlot);
|
|
729
|
+
}
|
|
730
|
+
}, msUntilPreValidation);
|
|
731
|
+
|
|
732
|
+
const minutesUntil = Math.round(msUntilPreValidation / 60000);
|
|
733
|
+
node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// Setup slot start timer (exact start time)
|
|
738
|
+
function setupSlotStartTimer(slot) {
|
|
739
|
+
const now = new Date();
|
|
740
|
+
const slotStart = new Date(slot.startDt);
|
|
741
|
+
const msUntilStart = slotStart.getTime() - now.getTime();
|
|
742
|
+
|
|
743
|
+
if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
744
|
+
slotStartTimer = setTimeout(() => {
|
|
745
|
+
publishChargingState(true);
|
|
746
|
+
node.warn(`Charging slot started at ${slot.startDt}`);
|
|
747
|
+
setupSlotEndTimer(slot);
|
|
748
|
+
}, msUntilStart);
|
|
749
|
+
|
|
750
|
+
const secondsUntil = Math.round(msUntilStart / 1000);
|
|
751
|
+
node.log(`Slot start timer set for ${secondsUntil}s (${slot.startDt})`);
|
|
752
|
+
} else if (msUntilStart <= 0) {
|
|
753
|
+
// Slot already started, check if it's still active
|
|
754
|
+
const slotEnd = new Date(slot.endDt);
|
|
755
|
+
if (slotEnd > now) {
|
|
756
|
+
publishChargingState(true);
|
|
757
|
+
setupSlotEndTimer(slot);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// Setup slot end timer (exact end time)
|
|
763
|
+
function setupSlotEndTimer(slot) {
|
|
764
|
+
const now = new Date();
|
|
765
|
+
const slotEnd = new Date(slot.endDt);
|
|
766
|
+
const msUntilEnd = slotEnd.getTime() - now.getTime();
|
|
767
|
+
|
|
768
|
+
if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
769
|
+
slotEndTimer = setTimeout(() => {
|
|
770
|
+
node.warn(`Charging slot ended at ${slot.endDt}`);
|
|
771
|
+
|
|
772
|
+
// Check if another slot starts immediately (within cached data)
|
|
773
|
+
const now = new Date();
|
|
774
|
+
const immediateNextSlot = cachedSlots.find(s => {
|
|
775
|
+
const start = new Date(s.startDt);
|
|
776
|
+
const end = new Date(s.endDt);
|
|
777
|
+
return start <= now && end > now;
|
|
778
|
+
});
|
|
779
|
+
|
|
780
|
+
if (immediateNextSlot) {
|
|
781
|
+
node.warn("Next slot starting immediately");
|
|
782
|
+
publishChargingState(true);
|
|
783
|
+
setupSlotEndTimer(immediateNextSlot);
|
|
784
|
+
} else {
|
|
785
|
+
publishChargingState(false);
|
|
786
|
+
}
|
|
787
|
+
}, msUntilEnd);
|
|
788
|
+
|
|
789
|
+
const minutesUntil = Math.round(msUntilEnd / 60000);
|
|
790
|
+
node.log(`Slot end timer set for ${minutesUntil} min (${slot.endDt})`);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// Main timer setup - called on each poll
|
|
795
|
+
function setupChargingTimers(slots) {
|
|
796
|
+
// Clear existing timers
|
|
797
|
+
clearChargingTimers();
|
|
798
|
+
|
|
799
|
+
// Cache slots for later use
|
|
800
|
+
cachedSlots = slots;
|
|
801
|
+
|
|
802
|
+
const now = new Date();
|
|
803
|
+
|
|
804
|
+
// Check if currently in a charging slot
|
|
805
|
+
const activeSlot = slots.find(s => {
|
|
806
|
+
const start = new Date(s.startDt);
|
|
807
|
+
const end = new Date(s.endDt);
|
|
808
|
+
return start <= now && end > now;
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
if (activeSlot) {
|
|
812
|
+
// Currently charging
|
|
813
|
+
const newState = true;
|
|
814
|
+
if (chargingNow !== newState) {
|
|
815
|
+
publishChargingState(newState);
|
|
816
|
+
}
|
|
817
|
+
setupSlotEndTimer(activeSlot);
|
|
818
|
+
node.log("Currently charging - end timer set");
|
|
819
|
+
} else {
|
|
820
|
+
// Not currently charging
|
|
821
|
+
const newState = false;
|
|
822
|
+
if (chargingNow !== newState) {
|
|
823
|
+
publishChargingState(newState);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// Find next future slot
|
|
827
|
+
const nextSlot = slots.find(s => new Date(s.startDt) > now);
|
|
828
|
+
|
|
829
|
+
if (nextSlot) {
|
|
830
|
+
setupPreValidationTimer(nextSlot);
|
|
831
|
+
node.log(`Next slot at ${nextSlot.startDt}`);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
// 7. Event Listeners
|
|
837
|
+
|
|
838
|
+
// Helper: Publish current state (both pending and confirmed)
|
|
839
|
+
// This merges pending values into last known full state to prevent sensors going unknown
|
|
840
|
+
function publishCurrentState() {
|
|
841
|
+
if (enableMqtt && node.broker) {
|
|
842
|
+
// Merge pending values into last known state
|
|
843
|
+
const fullState = {
|
|
844
|
+
...lastKnownState,
|
|
845
|
+
pending_limit: pendingLimit,
|
|
846
|
+
pending_time: pendingTime,
|
|
847
|
+
confirmed_limit: confirmedLimit,
|
|
848
|
+
confirmed_time: confirmedTime
|
|
849
|
+
};
|
|
850
|
+
node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: false });
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// A. Handle Node-RED Input Messages
|
|
855
|
+
node.on('input', function (msg) {
|
|
856
|
+
// Check for control commands
|
|
857
|
+
if (msg.payload && typeof msg.payload === 'object') {
|
|
858
|
+
if (msg.payload.set_limit || msg.payload.set_time) {
|
|
859
|
+
// Use new values if present, otherwise keep existing
|
|
860
|
+
const targetLimit = msg.payload.set_limit || confirmedLimit;
|
|
861
|
+
const targetTime = msg.payload.set_time || confirmedTime;
|
|
862
|
+
setPreferences(targetLimit, targetTime);
|
|
863
|
+
return; // Don't run standard fetch if setting
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
// If just a trigger, run fetch
|
|
867
|
+
fetchData();
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
// B. Handle MQTT Commands (Home Assistant)
|
|
871
|
+
if (enableMqtt && node.broker) {
|
|
872
|
+
node.broker.register(this);
|
|
873
|
+
|
|
874
|
+
// Slider changed - update pending value only
|
|
875
|
+
node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
|
|
876
|
+
const val = parseInt(payload.toString());
|
|
877
|
+
pendingLimit = val;
|
|
878
|
+
publishCurrentState(); // Update display immediately
|
|
879
|
+
node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
|
|
880
|
+
});
|
|
881
|
+
|
|
882
|
+
// Dropdown changed - update pending value only
|
|
883
|
+
node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
|
|
884
|
+
const val = payload.toString();
|
|
885
|
+
pendingTime = val;
|
|
886
|
+
publishCurrentState(); // Update display immediately
|
|
887
|
+
node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
|
|
888
|
+
});
|
|
889
|
+
|
|
890
|
+
// Button pressed - submit changes to API
|
|
891
|
+
node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
|
|
892
|
+
setPreferences(pendingLimit, pendingTime);
|
|
893
|
+
});
|
|
894
|
+
|
|
895
|
+
setTimeout(announceControls, 2000);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// Init
|
|
899
|
+
const intervalId = setInterval(fetchData, refreshRate);
|
|
900
|
+
setTimeout(fetchData, 1000);
|
|
901
|
+
node.on('close', () => {
|
|
902
|
+
clearInterval(intervalId);
|
|
903
|
+
// Clear any pending retry timeouts
|
|
904
|
+
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
905
|
+
retryTimeouts = [];
|
|
906
|
+
// Clear charging timers
|
|
907
|
+
clearChargingTimers();
|
|
908
|
+
if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit);
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
|
|
913
|
+
credentials: { apiKey: { type: "password" } }
|
|
914
|
+
});
|
|
862
915
|
};
|