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