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