node-red-contrib-octopus-intelligent 1.3.3 → 1.4.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 +17 -0
- package/lib/poll-tick.js +44 -0
- package/lib/scheduler.js +17 -3
- package/octopus-intelligent.js +228 -381
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.4.0] — 2026-05-29
|
|
9
|
+
|
|
10
|
+
Single poll loop. The V1 `setInterval(fetchData)` intelligent loop and the V2 `createScheduler(pollDueCategories)` category loop are merged into one clock-aligned scheduler with one auth and one emit per tick. No HA-side changes.
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
- **Intermittent `KT-CT-1199` "Too many requests"** on `flexPlannedDispatches` — the standalone `flex_planned_dispatches` V2 category queried the same endpoint as the V1 intelligent poll, and the two unsynchronised loops phase-drifted into bursts that tripped Kraken's burst limit. The intelligent poll now owns `flexPlannedDispatches`; the standalone category is removed.
|
|
14
|
+
- **Whole payload was nuked on any single-category error**, and `intelligent_error` was never set. Every category now follows one error policy: record `<category>_error`, keep last-good data, retry next interval. No permanent disable.
|
|
15
|
+
- **Slow polls could overlap a tick** — added an in-flight guard around the scheduler.
|
|
16
|
+
|
|
17
|
+
### Changed (internal architecture; no HA-side breakage)
|
|
18
|
+
- Every category exposes `async poll(token) → partialPayload`. Simple categories use a `simplePoll` factory; the intelligent poll is a bespoke category that owns both the devices and dispatch queries.
|
|
19
|
+
- Tick / poll / error-merge logic moved into `lib/poll-tick.js` and `lib/scheduler.js` for unit-test coverage.
|
|
20
|
+
- Manual refresh, MQTT refresh, and post-mutation validation re-polls all go through the same scheduler / intelligent-poll path.
|
|
21
|
+
|
|
22
|
+
### Unchanged
|
|
23
|
+
- All payload field names, MQTT topics, `unique_id`s, HA entity IDs, input commands, and node config fields.
|
|
24
|
+
|
|
8
25
|
## [1.3.3] — 2026-05-22
|
|
9
26
|
|
|
10
27
|
### Fixed
|
package/lib/poll-tick.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
function simplePoll(queryFn, parseFn, graphqlPost) {
|
|
4
|
+
return async function poll(token) {
|
|
5
|
+
const { query, variables, hostname } = queryFn();
|
|
6
|
+
const response = await graphqlPost({ query, variables }, token, hostname);
|
|
7
|
+
if (response.data.errors) throw new Error(JSON.stringify(response.data.errors));
|
|
8
|
+
if (!response.data.data) throw new Error('Response missing data');
|
|
9
|
+
return parseFn(response.data.data);
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const { isDue } = require('./scheduler');
|
|
14
|
+
const { mergePayload } = require('./payload');
|
|
15
|
+
|
|
16
|
+
async function runTick({ categories, state, getToken, now = Date.now }) {
|
|
17
|
+
const due = categories.filter((c) => c.enabled && isDue(c));
|
|
18
|
+
if (due.length === 0) return { state, emitted: false };
|
|
19
|
+
let token;
|
|
20
|
+
try {
|
|
21
|
+
token = await getToken();
|
|
22
|
+
} catch (e) {
|
|
23
|
+
let newState = state;
|
|
24
|
+
for (const cat of due) {
|
|
25
|
+
newState = mergePayload(newState, { [`${cat.id}_error`]: `Auth failed: ${e.message}` });
|
|
26
|
+
cat.lastPolled = now();
|
|
27
|
+
}
|
|
28
|
+
return { state: newState, emitted: true };
|
|
29
|
+
}
|
|
30
|
+
let newState = state;
|
|
31
|
+
for (const cat of due) {
|
|
32
|
+
try {
|
|
33
|
+
const partial = await cat.poll(token);
|
|
34
|
+
newState = mergePayload(newState, partial);
|
|
35
|
+
newState = mergePayload(newState, { [`${cat.id}_error`]: null });
|
|
36
|
+
} catch (e) {
|
|
37
|
+
newState = mergePayload(newState, { [`${cat.id}_error`]: e.message });
|
|
38
|
+
}
|
|
39
|
+
cat.lastPolled = now();
|
|
40
|
+
}
|
|
41
|
+
return { state: newState, emitted: true };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
module.exports = { simplePoll, runTick };
|
package/lib/scheduler.js
CHANGED
|
@@ -12,14 +12,28 @@ function alignedStart(nowMs) {
|
|
|
12
12
|
return ms === 0 ? 1000 : 1000 - ms;
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
function wrapWithInFlightGuard(fn) {
|
|
16
|
+
let inFlight = false;
|
|
17
|
+
return async function guarded(...args) {
|
|
18
|
+
if (inFlight) return;
|
|
19
|
+
inFlight = true;
|
|
20
|
+
try {
|
|
21
|
+
return await fn(...args);
|
|
22
|
+
} finally {
|
|
23
|
+
inFlight = false;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
15
28
|
function createScheduler(onTick) {
|
|
29
|
+
const guarded = wrapWithInFlightGuard(onTick);
|
|
16
30
|
let handle = null;
|
|
17
31
|
|
|
18
32
|
function start() {
|
|
19
33
|
const delay = alignedStart(Date.now());
|
|
20
34
|
setTimeout(() => {
|
|
21
|
-
|
|
22
|
-
handle = setInterval(
|
|
35
|
+
guarded();
|
|
36
|
+
handle = setInterval(guarded, 1000);
|
|
23
37
|
}, delay);
|
|
24
38
|
}
|
|
25
39
|
|
|
@@ -30,4 +44,4 @@ function createScheduler(onTick) {
|
|
|
30
44
|
return { start, stop };
|
|
31
45
|
}
|
|
32
46
|
|
|
33
|
-
module.exports = { isDue, alignedStart, createScheduler };
|
|
47
|
+
module.exports = { isDue, alignedStart, createScheduler, wrapWithInFlightGuard };
|
package/octopus-intelligent.js
CHANGED
|
@@ -5,6 +5,7 @@ const { createApiMetrics } = require('./lib/api-metrics');
|
|
|
5
5
|
const intelligentCategory = require('./lib/categories/intelligent');
|
|
6
6
|
const { buildDefaultPayload } = require('./lib/payload');
|
|
7
7
|
const { createScheduler } = require('./lib/scheduler');
|
|
8
|
+
const { simplePoll, runTick } = require('./lib/poll-tick');
|
|
8
9
|
const { discoverProducts } = require('./lib/discovery');
|
|
9
10
|
const { mergePayload } = require('./lib/payload');
|
|
10
11
|
const electricityCategory = require('./lib/categories/electricity');
|
|
@@ -503,6 +504,7 @@ module.exports = function (RED) {
|
|
|
503
504
|
let retryTimeouts = []; // Track pending retry timeouts
|
|
504
505
|
let expectedLimit = null;
|
|
505
506
|
let expectedTime = null;
|
|
507
|
+
let validationMode = false;
|
|
506
508
|
|
|
507
509
|
// Pending vs Confirmed state
|
|
508
510
|
let pendingLimit = 80;
|
|
@@ -526,7 +528,6 @@ module.exports = function (RED) {
|
|
|
526
528
|
|
|
527
529
|
// Polling metrics
|
|
528
530
|
let nextPollTime = null; // ISO timestamp of next scheduled poll
|
|
529
|
-
let pollIntervalHandle = null; // Reference to setInterval handle
|
|
530
531
|
const metrics = createApiMetrics();
|
|
531
532
|
|
|
532
533
|
// API Complexity Tracking
|
|
@@ -547,9 +548,25 @@ module.exports = function (RED) {
|
|
|
547
548
|
// V2 category registry — populated after discovery
|
|
548
549
|
let categories = [];
|
|
549
550
|
|
|
551
|
+
// Lifecycle tracking — init setTimeouts must be clearable on close, and async
|
|
552
|
+
// callbacks inside them must short-circuit if the node was closed mid-await,
|
|
553
|
+
// otherwise a redeploy during the 2s warmup leaves an orphan V2 scheduler.
|
|
554
|
+
let initTimeoutHandles = [];
|
|
555
|
+
let nodeClosed = false;
|
|
556
|
+
|
|
550
557
|
async function initCategories(discovered) {
|
|
551
558
|
categories = [];
|
|
552
559
|
|
|
560
|
+
if (discovered.hasIntelligent) {
|
|
561
|
+
categories.push({
|
|
562
|
+
id: 'intelligent',
|
|
563
|
+
enabled: true,
|
|
564
|
+
intervalMs: (config.refreshInterval || 5) * 60 * 1000,
|
|
565
|
+
lastPolled: 0,
|
|
566
|
+
poll: intelligentPoll,
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
|
|
553
570
|
const electricityEnabled = config.electricityEnabled !== false;
|
|
554
571
|
const gasEnabled = config.gasEnabled !== false;
|
|
555
572
|
|
|
@@ -562,7 +579,12 @@ module.exports = function (RED) {
|
|
|
562
579
|
intervalMs: ratesMs,
|
|
563
580
|
lastPolled: 0,
|
|
564
581
|
queryFn: () => electricityCategory.buildRatesQuery(account),
|
|
565
|
-
parseFn: d => electricityCategory.parseRatesResponse(d)
|
|
582
|
+
parseFn: d => electricityCategory.parseRatesResponse(d),
|
|
583
|
+
poll: simplePoll(
|
|
584
|
+
() => electricityCategory.buildRatesQuery(account),
|
|
585
|
+
d => electricityCategory.parseRatesResponse(d),
|
|
586
|
+
graphqlPost
|
|
587
|
+
),
|
|
566
588
|
});
|
|
567
589
|
categories.push({
|
|
568
590
|
id: 'electricity_consumption',
|
|
@@ -570,7 +592,12 @@ module.exports = function (RED) {
|
|
|
570
592
|
intervalMs: consumptionMs,
|
|
571
593
|
lastPolled: 0,
|
|
572
594
|
queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
573
|
-
parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan)
|
|
595
|
+
parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
|
|
596
|
+
poll: simplePoll(
|
|
597
|
+
() => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
598
|
+
d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
|
|
599
|
+
graphqlPost
|
|
600
|
+
),
|
|
574
601
|
});
|
|
575
602
|
}
|
|
576
603
|
|
|
@@ -583,7 +610,12 @@ module.exports = function (RED) {
|
|
|
583
610
|
intervalMs: ratesMs,
|
|
584
611
|
lastPolled: 0,
|
|
585
612
|
queryFn: () => gasCategory.buildRatesQuery(account),
|
|
586
|
-
parseFn: d => gasCategory.parseRatesResponse(d)
|
|
613
|
+
parseFn: d => gasCategory.parseRatesResponse(d),
|
|
614
|
+
poll: simplePoll(
|
|
615
|
+
() => gasCategory.buildRatesQuery(account),
|
|
616
|
+
d => gasCategory.parseRatesResponse(d),
|
|
617
|
+
graphqlPost
|
|
618
|
+
),
|
|
587
619
|
});
|
|
588
620
|
categories.push({
|
|
589
621
|
id: 'gas_consumption',
|
|
@@ -591,7 +623,12 @@ module.exports = function (RED) {
|
|
|
591
623
|
intervalMs: consumptionMs,
|
|
592
624
|
lastPolled: 0,
|
|
593
625
|
queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
594
|
-
parseFn: d => gasCategory.parseConsumptionResponse(d)
|
|
626
|
+
parseFn: d => gasCategory.parseConsumptionResponse(d),
|
|
627
|
+
poll: simplePoll(
|
|
628
|
+
() => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
629
|
+
d => gasCategory.parseConsumptionResponse(d),
|
|
630
|
+
graphqlPost
|
|
631
|
+
),
|
|
595
632
|
});
|
|
596
633
|
}
|
|
597
634
|
|
|
@@ -601,7 +638,12 @@ module.exports = function (RED) {
|
|
|
601
638
|
intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
|
|
602
639
|
lastPolled: 0,
|
|
603
640
|
queryFn: () => wheelOfFortuneCategory.buildQuery(account),
|
|
604
|
-
parseFn: d => wheelOfFortuneCategory.parseResponse(d)
|
|
641
|
+
parseFn: d => wheelOfFortuneCategory.parseResponse(d),
|
|
642
|
+
poll: simplePoll(
|
|
643
|
+
() => wheelOfFortuneCategory.buildQuery(account),
|
|
644
|
+
d => wheelOfFortuneCategory.parseResponse(d),
|
|
645
|
+
graphqlPost
|
|
646
|
+
),
|
|
605
647
|
});
|
|
606
648
|
if (discovered.smartMeterDeviceId) {
|
|
607
649
|
categories.push({
|
|
@@ -610,7 +652,12 @@ module.exports = function (RED) {
|
|
|
610
652
|
intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
|
|
611
653
|
lastPolled: 0,
|
|
612
654
|
queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
|
|
613
|
-
parseFn: d => homeMiniCategory.parseResponse(d)
|
|
655
|
+
parseFn: d => homeMiniCategory.parseResponse(d),
|
|
656
|
+
poll: simplePoll(
|
|
657
|
+
() => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
|
|
658
|
+
d => homeMiniCategory.parseResponse(d),
|
|
659
|
+
graphqlPost
|
|
660
|
+
),
|
|
614
661
|
});
|
|
615
662
|
}
|
|
616
663
|
categories.push({
|
|
@@ -619,7 +666,12 @@ module.exports = function (RED) {
|
|
|
619
666
|
intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
|
|
620
667
|
lastPolled: 0,
|
|
621
668
|
queryFn: () => savingSessionsCategory.buildQuery(account),
|
|
622
|
-
parseFn: d => savingSessionsCategory.parseResponse(d)
|
|
669
|
+
parseFn: d => savingSessionsCategory.parseResponse(d),
|
|
670
|
+
poll: simplePoll(
|
|
671
|
+
() => savingSessionsCategory.buildQuery(account),
|
|
672
|
+
d => savingSessionsCategory.parseResponse(d),
|
|
673
|
+
graphqlPost
|
|
674
|
+
),
|
|
623
675
|
});
|
|
624
676
|
|
|
625
677
|
if (discovered.hasIntelligent) {
|
|
@@ -629,18 +681,13 @@ module.exports = function (RED) {
|
|
|
629
681
|
intervalMs: 60 * 60 * 1000,
|
|
630
682
|
lastPolled: 0,
|
|
631
683
|
queryFn: () => completedDispatchesCategory.buildQuery(account),
|
|
632
|
-
parseFn: d => completedDispatchesCategory.parseResponse(d)
|
|
684
|
+
parseFn: d => completedDispatchesCategory.parseResponse(d),
|
|
685
|
+
poll: simplePoll(
|
|
686
|
+
() => completedDispatchesCategory.buildQuery(account),
|
|
687
|
+
d => completedDispatchesCategory.parseResponse(d),
|
|
688
|
+
graphqlPost
|
|
689
|
+
),
|
|
633
690
|
});
|
|
634
|
-
if (discovered.deviceId) {
|
|
635
|
-
categories.push({
|
|
636
|
-
id: 'flex_planned_dispatches',
|
|
637
|
-
enabled: true,
|
|
638
|
-
intervalMs: (config.refreshInterval || 5) * 60 * 1000,
|
|
639
|
-
lastPolled: 0,
|
|
640
|
-
queryFn: () => flexPlannedDispatchesCategory.buildQuery(discovered.deviceId),
|
|
641
|
-
parseFn: d => flexPlannedDispatchesCategory.parseResponse(d)
|
|
642
|
-
});
|
|
643
|
-
}
|
|
644
691
|
}
|
|
645
692
|
|
|
646
693
|
if (discovered.hasElectricity && discovered.electricityMpan) {
|
|
@@ -650,7 +697,12 @@ module.exports = function (RED) {
|
|
|
650
697
|
intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
|
|
651
698
|
lastPolled: 0,
|
|
652
699
|
queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
|
|
653
|
-
parseFn: d => applicableRatesCategory.parseResponse(d)
|
|
700
|
+
parseFn: d => applicableRatesCategory.parseResponse(d),
|
|
701
|
+
poll: simplePoll(
|
|
702
|
+
() => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
|
|
703
|
+
d => applicableRatesCategory.parseResponse(d),
|
|
704
|
+
graphqlPost
|
|
705
|
+
),
|
|
654
706
|
});
|
|
655
707
|
}
|
|
656
708
|
|
|
@@ -663,7 +715,12 @@ module.exports = function (RED) {
|
|
|
663
715
|
intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
|
|
664
716
|
lastPolled: 0,
|
|
665
717
|
queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
|
|
666
|
-
parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' })
|
|
718
|
+
parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
|
|
719
|
+
poll: simplePoll(
|
|
720
|
+
() => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
|
|
721
|
+
d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
|
|
722
|
+
graphqlPost
|
|
723
|
+
),
|
|
667
724
|
});
|
|
668
725
|
}
|
|
669
726
|
|
|
@@ -674,7 +731,12 @@ module.exports = function (RED) {
|
|
|
674
731
|
intervalMs: 30 * 60 * 1000, // 30 minutes
|
|
675
732
|
lastPolled: 0,
|
|
676
733
|
queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
|
|
677
|
-
parseFn: d => freeElectricityCategory.parseResponse(d)
|
|
734
|
+
parseFn: d => freeElectricityCategory.parseResponse(d),
|
|
735
|
+
poll: simplePoll(
|
|
736
|
+
() => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
|
|
737
|
+
d => freeElectricityCategory.parseResponse(d),
|
|
738
|
+
graphqlPost
|
|
739
|
+
),
|
|
678
740
|
});
|
|
679
741
|
}
|
|
680
742
|
|
|
@@ -684,7 +746,12 @@ module.exports = function (RED) {
|
|
|
684
746
|
intervalMs: 60 * 60 * 1000,
|
|
685
747
|
lastPolled: 0,
|
|
686
748
|
queryFn: () => accountCategory.buildQuery(account),
|
|
687
|
-
parseFn: d => accountCategory.parseResponse(d)
|
|
749
|
+
parseFn: d => accountCategory.parseResponse(d),
|
|
750
|
+
poll: simplePoll(
|
|
751
|
+
() => accountCategory.buildQuery(account),
|
|
752
|
+
d => accountCategory.parseResponse(d),
|
|
753
|
+
graphqlPost
|
|
754
|
+
),
|
|
688
755
|
});
|
|
689
756
|
|
|
690
757
|
categories.push({
|
|
@@ -693,49 +760,50 @@ module.exports = function (RED) {
|
|
|
693
760
|
intervalMs: 60 * 60 * 1000,
|
|
694
761
|
lastPolled: 0,
|
|
695
762
|
queryFn: () => octoplusCategory.buildQuery(account),
|
|
696
|
-
parseFn: d => octoplusCategory.parseResponse(d)
|
|
763
|
+
parseFn: d => octoplusCategory.parseResponse(d),
|
|
764
|
+
poll: simplePoll(
|
|
765
|
+
() => octoplusCategory.buildQuery(account),
|
|
766
|
+
d => octoplusCategory.parseResponse(d),
|
|
767
|
+
graphqlPost
|
|
768
|
+
),
|
|
697
769
|
});
|
|
698
770
|
}
|
|
699
771
|
|
|
700
772
|
async function pollDueCategories() {
|
|
701
|
-
const
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
});
|
|
711
|
-
if (!response.data.data || !response.data.data.obtainKrakenToken) {
|
|
712
|
-
throw new Error('Auth response missing token');
|
|
713
|
-
}
|
|
714
|
-
token = response.data.data.obtainKrakenToken.token;
|
|
715
|
-
} catch (e) {
|
|
716
|
-
node.warn(`V2 category poll: auth failed: ${e.message}`);
|
|
717
|
-
return;
|
|
773
|
+
const result = await runTick({
|
|
774
|
+
categories,
|
|
775
|
+
state: lastKnownState,
|
|
776
|
+
getToken: obtainTickToken,
|
|
777
|
+
});
|
|
778
|
+
if (!result.emitted) return;
|
|
779
|
+
lastKnownState = result.state;
|
|
780
|
+
if (enableMqtt && node.broker && node.broker.client) {
|
|
781
|
+
node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
|
|
718
782
|
}
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
if (!response.data.data) throw new Error('Response missing data');
|
|
726
|
-
const parsed = cat.parseFn(response.data.data);
|
|
727
|
-
lastKnownState = mergePayload(lastKnownState, parsed);
|
|
728
|
-
cat.lastPolled = Date.now();
|
|
729
|
-
} catch (e) {
|
|
730
|
-
cat.enabled = false;
|
|
731
|
-
node.warn(`V2 category ${cat.id} failed (disabled until redeploy): ${e.message}`);
|
|
783
|
+
node.send({ payload: lastKnownState });
|
|
784
|
+
if (!validationMode) {
|
|
785
|
+
if (lastKnownState.intelligent_error) {
|
|
786
|
+
node.status({ fill: "red", shape: "ring", text: `Error: ${String(lastKnownState.intelligent_error).slice(0, 40)}` });
|
|
787
|
+
} else {
|
|
788
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
|
|
732
789
|
}
|
|
733
790
|
}
|
|
791
|
+
}
|
|
734
792
|
|
|
735
|
-
|
|
736
|
-
|
|
793
|
+
async function obtainTickToken() {
|
|
794
|
+
const response = await graphqlPost({
|
|
795
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
796
|
+
variables: { input: { APIKey: apiKey } },
|
|
797
|
+
});
|
|
798
|
+
if (!response.data.data || !response.data.data.obtainKrakenToken) {
|
|
799
|
+
throw new Error('Auth response missing token: ' + JSON.stringify(response.data.errors || response.data));
|
|
737
800
|
}
|
|
738
|
-
|
|
801
|
+
return response.data.data.obtainKrakenToken.token;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function forceCategoryDue(id) {
|
|
805
|
+
const cat = categories.find((c) => c.id === id);
|
|
806
|
+
if (cat) cat.lastPolled = 0;
|
|
739
807
|
}
|
|
740
808
|
|
|
741
809
|
async function setPreferences(newLimit, newTime) {
|
|
@@ -822,6 +890,7 @@ module.exports = function (RED) {
|
|
|
822
890
|
// C. Start exponential backoff validation
|
|
823
891
|
expectedLimit = limit;
|
|
824
892
|
expectedTime = time;
|
|
893
|
+
validationMode = true;
|
|
825
894
|
node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
|
|
826
895
|
|
|
827
896
|
// Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
|
|
@@ -836,6 +905,7 @@ module.exports = function (RED) {
|
|
|
836
905
|
node.status({ fill: "red", shape: "ring", text: "Update Failed" });
|
|
837
906
|
expectedLimit = null;
|
|
838
907
|
expectedTime = null;
|
|
908
|
+
validationMode = false;
|
|
839
909
|
}
|
|
840
910
|
}
|
|
841
911
|
|
|
@@ -845,6 +915,7 @@ module.exports = function (RED) {
|
|
|
845
915
|
node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
|
|
846
916
|
expectedLimit = null;
|
|
847
917
|
expectedTime = null;
|
|
918
|
+
validationMode = false;
|
|
848
919
|
return;
|
|
849
920
|
}
|
|
850
921
|
|
|
@@ -857,28 +928,39 @@ module.exports = function (RED) {
|
|
|
857
928
|
|
|
858
929
|
async function fetchDataWithValidation(intervals, currentIndex) {
|
|
859
930
|
try {
|
|
860
|
-
const
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
if (
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
931
|
+
const token = await obtainTickToken();
|
|
932
|
+
const partial = await intelligentPoll(token);
|
|
933
|
+
lastKnownState = Object.assign({}, lastKnownState, partial, { intelligent_error: null });
|
|
934
|
+
if (enableMqtt && node.broker && node.broker.client) {
|
|
935
|
+
node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
|
|
936
|
+
}
|
|
937
|
+
node.send({ payload: lastKnownState });
|
|
938
|
+
|
|
939
|
+
const validated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
|
|
940
|
+
if (validated) {
|
|
941
|
+
validationMode = false;
|
|
942
|
+
retryTimeouts.forEach((t) => clearTimeout(t));
|
|
870
943
|
retryTimeouts = [];
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
944
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
const totalAttempts = intervals.length;
|
|
948
|
+
const attempt = currentIndex + 1;
|
|
949
|
+
if (currentIndex < intervals.length - 1) {
|
|
875
950
|
node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
|
|
876
951
|
scheduleRetries(intervals, currentIndex + 1);
|
|
952
|
+
} else {
|
|
953
|
+
validationMode = false;
|
|
954
|
+
node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
|
|
877
955
|
}
|
|
878
956
|
} catch (error) {
|
|
879
|
-
// Error during fetch, schedule next retry
|
|
880
957
|
node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
|
|
881
|
-
|
|
958
|
+
if (currentIndex < intervals.length - 1) {
|
|
959
|
+
scheduleRetries(intervals, currentIndex + 1);
|
|
960
|
+
} else {
|
|
961
|
+
validationMode = false;
|
|
962
|
+
node.status({ fill: "red", shape: "ring", text: "Validation failed" });
|
|
963
|
+
}
|
|
882
964
|
}
|
|
883
965
|
}
|
|
884
966
|
|
|
@@ -1006,302 +1088,63 @@ module.exports = function (RED) {
|
|
|
1006
1088
|
smartChargingRetryTimeouts.push(timeout);
|
|
1007
1089
|
}
|
|
1008
1090
|
|
|
1009
|
-
// 6. Logic:
|
|
1010
|
-
async function
|
|
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
|
-
const authRequest = {
|
|
1044
|
-
url: "https://api.octopus.energy/v1/graphql/",
|
|
1045
|
-
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
1046
|
-
variables: { input: { APIKey: apiKey } }
|
|
1047
|
-
};
|
|
1048
|
-
|
|
1049
|
-
const authResponse = await graphqlPost({
|
|
1050
|
-
query: authRequest.query,
|
|
1051
|
-
variables: authRequest.variables
|
|
1052
|
-
});
|
|
1053
|
-
|
|
1054
|
-
debugInfo.apiCalls.push({
|
|
1055
|
-
step: 1,
|
|
1056
|
-
name: "authentication",
|
|
1057
|
-
url: authRequest.url,
|
|
1058
|
-
statusCode: authResponse.status,
|
|
1059
|
-
hasErrors: !!(authResponse.data.errors),
|
|
1060
|
-
errors: authResponse.data.errors || null
|
|
1061
|
-
});
|
|
1062
|
-
|
|
1063
|
-
// Validate auth response
|
|
1064
|
-
if (authResponse.data.errors) {
|
|
1065
|
-
throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
|
|
1066
|
-
}
|
|
1067
|
-
if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
1068
|
-
throw new Error(`Auth response missing token data. Response: ${JSON.stringify(authResponse.data)}`);
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
1072
|
-
debugInfo.apiCalls[0].tokenObtained = !!token;
|
|
1073
|
-
debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
|
|
1074
|
-
|
|
1075
|
-
// STEP 2a: Fetch devices (preferences + device ID)
|
|
1076
|
-
debugInfo.step = "fetching_devices";
|
|
1077
|
-
node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
|
|
1078
|
-
|
|
1079
|
-
const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
|
|
1080
|
-
const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
|
|
1081
|
-
|
|
1082
|
-
debugInfo.apiCalls.push({
|
|
1083
|
-
step: 2,
|
|
1084
|
-
name: "devices_query",
|
|
1085
|
-
url: "https://api.octopus.energy/v1/graphql/",
|
|
1086
|
-
accountNumber: account,
|
|
1087
|
-
statusCode: devicesResponse.status,
|
|
1088
|
-
hasErrors: !!(devicesResponse.data.errors),
|
|
1089
|
-
errors: devicesResponse.data.errors || null,
|
|
1090
|
-
hasData: !!(devicesResponse.data.data),
|
|
1091
|
-
responseHeaders: devicesResponse.headers || {}
|
|
1092
|
-
});
|
|
1093
|
-
|
|
1094
|
-
if (devicesResponse.data.errors) {
|
|
1095
|
-
throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
|
|
1096
|
-
}
|
|
1097
|
-
if (!devicesResponse.data.data) {
|
|
1098
|
-
throw new Error(`Devices response missing data. Response: ${JSON.stringify(devicesResponse.data)}`);
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
const devicesData = devicesResponse.data.data;
|
|
1102
|
-
const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
|
|
1103
|
-
if (!evDevice) {
|
|
1104
|
-
throw new Error('No ELECTRIC_VEHICLES device found on account');
|
|
1105
|
-
}
|
|
1106
|
-
krakenflexDeviceId = evDevice.id;
|
|
1107
|
-
|
|
1108
|
-
// STEP 2b: Fetch planned dispatches using device ID
|
|
1109
|
-
debugInfo.step = "fetching_dispatches";
|
|
1110
|
-
const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
|
|
1111
|
-
const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
|
|
1112
|
-
|
|
1113
|
-
debugInfo.apiCalls.push({
|
|
1114
|
-
step: 3,
|
|
1115
|
-
name: "dispatches_query",
|
|
1116
|
-
url: "https://api.octopus.energy/v1/graphql/",
|
|
1117
|
-
deviceId: evDevice.id,
|
|
1118
|
-
statusCode: dispatchResponse.status,
|
|
1119
|
-
hasErrors: !!(dispatchResponse.data.errors),
|
|
1120
|
-
errors: dispatchResponse.data.errors || null,
|
|
1121
|
-
hasData: !!(dispatchResponse.data.data),
|
|
1122
|
-
responseHeaders: dispatchResponse.headers || {}
|
|
1123
|
-
});
|
|
1124
|
-
|
|
1125
|
-
if (dispatchResponse.data.errors) {
|
|
1126
|
-
throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
|
|
1127
|
-
}
|
|
1128
|
-
if (!dispatchResponse.data.data) {
|
|
1129
|
-
throw new Error(`Dispatches response missing data. Response: ${JSON.stringify(dispatchResponse.data)}`);
|
|
1130
|
-
}
|
|
1131
|
-
|
|
1132
|
-
// STEP 3: Extract and Process
|
|
1133
|
-
debugInfo.step = "processing";
|
|
1134
|
-
const data = {
|
|
1135
|
-
devices: devicesData.devices,
|
|
1136
|
-
flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || []
|
|
1137
|
-
};
|
|
1138
|
-
const slots = data.flexPlannedDispatches;
|
|
1139
|
-
|
|
1140
|
-
// Check for GraphQL extensions on the dispatches response
|
|
1141
|
-
let actualComplexity = null;
|
|
1142
|
-
if (dispatchResponse.data.extensions) {
|
|
1143
|
-
debugInfo.apiCalls[2].extensions = dispatchResponse.data.extensions;
|
|
1144
|
-
actualComplexity = dispatchResponse.data.extensions.complexity ||
|
|
1145
|
-
dispatchResponse.data.extensions.cost ||
|
|
1146
|
-
null;
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
// Record poll with estimated or actual complexity
|
|
1150
|
-
metrics.recordPoll(actualComplexity || ESTIMATED_POLL_COMPLEXITY);
|
|
1151
|
-
|
|
1152
|
-
debugInfo.apiCalls[2].slotsFound = slots.length;
|
|
1153
|
-
debugInfo.apiCalls[2].slotDetails = slots.map(s => ({
|
|
1154
|
-
start: s.start,
|
|
1155
|
-
end: s.end,
|
|
1156
|
-
kwh: s.energyAddedKwh,
|
|
1157
|
-
type: s.type
|
|
1158
|
-
}));
|
|
1159
|
-
|
|
1160
|
-
// Parse response via intelligent category module
|
|
1161
|
-
const appliedTz = resolveTimezone(node);
|
|
1162
|
-
const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch(e) { return 'UTC'; } })();
|
|
1163
|
-
const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
|
|
1164
|
-
const { _activeSlots, ...catPublic } = catResult;
|
|
1165
|
-
|
|
1166
|
-
// Update Confirmed State (from catResult)
|
|
1167
|
-
confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
|
|
1168
|
-
confirmedTime = catResult.confirmed_time || confirmedTime;
|
|
1169
|
-
|
|
1170
|
-
// On successful fetch, sync pending to confirmed if not in validation mode
|
|
1171
|
-
if (!validationMode) {
|
|
1172
|
-
pendingLimit = confirmedLimit;
|
|
1173
|
-
pendingTime = confirmedTime;
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
debugInfo.apiCalls[1].activeAndFutureSlots = _activeSlots.length;
|
|
1177
|
-
debugInfo.processingTime = new Date().toISOString();
|
|
1178
|
-
|
|
1179
|
-
// Setup charging timers (always update charging state)
|
|
1180
|
-
setupChargingTimers(_activeSlots);
|
|
1181
|
-
|
|
1182
|
-
// Start reconciliation loop on first successful data fetch (only in non-validation mode)
|
|
1183
|
-
if (!validationMode && !stateCheckInterval) {
|
|
1184
|
-
startStateReconciliation();
|
|
1185
|
-
}
|
|
1186
|
-
|
|
1187
|
-
// Update next poll time after successful fetch
|
|
1188
|
-
updateNextPollTime();
|
|
1189
|
-
|
|
1190
|
-
// Get API metrics for inclusion in payload
|
|
1191
|
-
const apiMetrics = metrics.getMetrics();
|
|
1192
|
-
|
|
1193
|
-
// Build Payload — merge catResult into lastKnownState, then add orchestrator-owned fields
|
|
1194
|
-
const statusPayload = Object.assign({}, lastKnownState, catPublic, {
|
|
1195
|
-
// Orchestrator-owned state fields (not in intelligentCategory)
|
|
1196
|
-
pending_limit: pendingLimit,
|
|
1197
|
-
pending_time: pendingTime,
|
|
1198
|
-
charging_now: chargingNow,
|
|
1199
|
-
next_poll: nextPollTime,
|
|
1200
|
-
next_poll_raw: nextPollTime,
|
|
1201
|
-
refresh_available_at: getRefreshAvailableAt(),
|
|
1202
|
-
api_requests_hour: apiMetrics.requests_last_hour,
|
|
1203
|
-
api_complexity_hour: apiMetrics.complexity_last_hour,
|
|
1204
|
-
api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
|
|
1205
|
-
timezone_detected: serverTz,
|
|
1206
|
-
timezone_applied: appliedTz,
|
|
1207
|
-
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
|
|
1208
|
-
});
|
|
1209
|
-
|
|
1210
|
-
// Success!
|
|
1211
|
-
debugInfo.success = true;
|
|
1212
|
-
debugInfo.step = "complete";
|
|
1213
|
-
|
|
1214
|
-
// Check if we're validating a preference change
|
|
1215
|
-
let isValidated = false;
|
|
1216
|
-
if (validationMode && expectedLimit !== null && expectedTime !== null) {
|
|
1217
|
-
// Check if the returned values match what we set
|
|
1218
|
-
isValidated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
|
|
1219
|
-
debugInfo.expectedLimit = expectedLimit;
|
|
1220
|
-
debugInfo.expectedTime = expectedTime;
|
|
1221
|
-
debugInfo.receivedLimit = confirmedLimit;
|
|
1222
|
-
debugInfo.receivedTime = confirmedTime;
|
|
1223
|
-
debugInfo.validated = isValidated;
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
// Add API usage metrics to debug info (already fetched above)
|
|
1227
|
-
debugInfo.api_usage = {
|
|
1228
|
-
requests_last_hour: apiMetrics.requests_last_hour,
|
|
1229
|
-
complexity_last_hour: apiMetrics.complexity_last_hour,
|
|
1230
|
-
complexity_percent_used: apiMetrics.complexity_percent,
|
|
1231
|
-
api_limit_hourly: 50000,
|
|
1232
|
-
request_complexity: actualComplexity || ESTIMATED_POLL_COMPLEXITY,
|
|
1233
|
-
complexity_source: actualComplexity ? "api" : "estimated"
|
|
1234
|
-
};
|
|
1235
|
-
|
|
1236
|
-
// Store this as the last known full state
|
|
1237
|
-
lastKnownState = statusPayload;
|
|
1238
|
-
|
|
1239
|
-
// ALWAYS publish data to prevent sensors becoming unavailable
|
|
1240
|
-
node.send({
|
|
1241
|
-
payload: statusPayload,
|
|
1242
|
-
debug: debugInfo
|
|
1243
|
-
});
|
|
1244
|
-
|
|
1245
|
-
// Update last sent charging state to prevent duplicate messages
|
|
1246
|
-
lastSentChargingState = chargingNow;
|
|
1247
|
-
|
|
1248
|
-
if (enableMqtt && node.broker) {
|
|
1249
|
-
node.broker.client.publish(stateTopic, JSON.stringify(statusPayload), { retain: true });
|
|
1250
|
-
// Also publish charging_now state to binary sensor topic
|
|
1251
|
-
const chargingPayload = chargingNow ? "ON" : "OFF";
|
|
1252
|
-
node.broker.client.publish(`${stateTopic}/charging_now`, chargingPayload, { retain: true });
|
|
1253
|
-
}
|
|
1254
|
-
|
|
1255
|
-
// Update status (validation mode will override this in fetchDataWithValidation)
|
|
1256
|
-
if (!validationMode) {
|
|
1257
|
-
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
// Return validation result
|
|
1261
|
-
return { validated: isValidated || !validationMode, confirmedLimit, confirmedTime };
|
|
1262
|
-
|
|
1263
|
-
} catch (error) {
|
|
1264
|
-
debugInfo.success = false;
|
|
1265
|
-
debugInfo.error = {
|
|
1266
|
-
message: error.message,
|
|
1267
|
-
stack: error.stack,
|
|
1268
|
-
response: error.response ? {
|
|
1269
|
-
status: error.response.status,
|
|
1270
|
-
statusText: error.response.statusText,
|
|
1271
|
-
data: error.response.data
|
|
1272
|
-
} : null
|
|
1273
|
-
};
|
|
1274
|
-
|
|
1275
|
-
// Log to Node-RED (only if not in validation mode to avoid spam)
|
|
1276
|
-
if (!validationMode) {
|
|
1277
|
-
node.error(`Octopus API Error at ${debugInfo.step}: ${error.message}`);
|
|
1278
|
-
if (error.response) {
|
|
1279
|
-
node.error(`Response: ${JSON.stringify(error.response.data)}`);
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
|
-
// Update status
|
|
1283
|
-
node.status({
|
|
1284
|
-
fill: "red",
|
|
1285
|
-
shape: "ring",
|
|
1286
|
-
text: `Error: ${debugInfo.step}`
|
|
1287
|
-
});
|
|
1288
|
-
|
|
1289
|
-
// Send default payload with debug info
|
|
1290
|
-
node.send({
|
|
1291
|
-
payload: getDefaultPayload(),
|
|
1292
|
-
debug: debugInfo
|
|
1293
|
-
});
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
// Return failure for validation
|
|
1297
|
-
return { validated: false };
|
|
1091
|
+
// 6. Logic: Intelligent Poll (single-scheduler bespoke poll)
|
|
1092
|
+
async function intelligentPoll(token) {
|
|
1093
|
+
// 1. devices query
|
|
1094
|
+
const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
|
|
1095
|
+
const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
|
|
1096
|
+
if (devicesResponse.data.errors) throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
|
|
1097
|
+
if (!devicesResponse.data.data) throw new Error('Devices response missing data');
|
|
1098
|
+
const devicesData = devicesResponse.data.data;
|
|
1099
|
+
const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
|
|
1100
|
+
if (!evDevice) throw new Error('No ELECTRIC_VEHICLES device found on account');
|
|
1101
|
+
krakenflexDeviceId = evDevice.id;
|
|
1102
|
+
|
|
1103
|
+
// 2. dispatches query (the single one that used to be duplicated by V1 + V2)
|
|
1104
|
+
const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
|
|
1105
|
+
const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
|
|
1106
|
+
if (dispatchResponse.data.errors) throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
|
|
1107
|
+
if (!dispatchResponse.data.data) throw new Error('Dispatches response missing data');
|
|
1108
|
+
|
|
1109
|
+
// 3. parse twice — intelligent (slots/window) + flex-planned-dispatches (array/count)
|
|
1110
|
+
const data = { devices: devicesData.devices, flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
|
|
1111
|
+
const appliedTz = resolveTimezone(node);
|
|
1112
|
+
const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (e) { return 'UTC'; } })();
|
|
1113
|
+
const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
|
|
1114
|
+
const { _activeSlots, ...catPublic } = catResult;
|
|
1115
|
+
const flexResult = flexPlannedDispatchesCategory.parseResponse(dispatchResponse.data.data);
|
|
1116
|
+
|
|
1117
|
+
// 4. metrics + side effects
|
|
1118
|
+
metrics.recordPoll(300);
|
|
1119
|
+
confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
|
|
1120
|
+
confirmedTime = catResult.confirmed_time || confirmedTime;
|
|
1121
|
+
if (!validationMode) {
|
|
1122
|
+
pendingLimit = confirmedLimit;
|
|
1123
|
+
pendingTime = confirmedTime;
|
|
1298
1124
|
}
|
|
1125
|
+
setupChargingTimers(_activeSlots);
|
|
1126
|
+
if (!stateCheckInterval) startStateReconciliation();
|
|
1127
|
+
updateNextPollTime();
|
|
1128
|
+
|
|
1129
|
+
const apiMetrics = metrics.getMetrics();
|
|
1130
|
+
|
|
1131
|
+
// 5. merged partial payload
|
|
1132
|
+
return Object.assign({}, catPublic, flexResult, {
|
|
1133
|
+
pending_limit: pendingLimit,
|
|
1134
|
+
pending_time: pendingTime,
|
|
1135
|
+
charging_now: chargingNow,
|
|
1136
|
+
next_poll: nextPollTime,
|
|
1137
|
+
next_poll_raw: nextPollTime,
|
|
1138
|
+
refresh_available_at: getRefreshAvailableAt(),
|
|
1139
|
+
api_requests_hour: apiMetrics.requests_last_hour,
|
|
1140
|
+
api_complexity_hour: apiMetrics.complexity_last_hour,
|
|
1141
|
+
api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
|
|
1142
|
+
timezone_detected: serverTz,
|
|
1143
|
+
timezone_applied: appliedTz,
|
|
1144
|
+
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
|
|
1145
|
+
});
|
|
1299
1146
|
}
|
|
1300
1147
|
|
|
1301
|
-
// Helper: Build default payload when errors occur — delegates to lib/payload.js
|
|
1302
|
-
function getDefaultPayload() {
|
|
1303
|
-
return buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
|
|
1304
|
-
}
|
|
1305
1148
|
|
|
1306
1149
|
// Helper: Fetch device ID and initial smart charging state (called once at startup)
|
|
1307
1150
|
async function fetchDeviceId() {
|
|
@@ -1688,7 +1531,7 @@ module.exports = function (RED) {
|
|
|
1688
1531
|
// Update timestamp so HA sees cooldown, but don't block the refresh
|
|
1689
1532
|
lastManualRefresh = Date.now();
|
|
1690
1533
|
node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
|
|
1691
|
-
|
|
1534
|
+
forceCategoryDue('intelligent');
|
|
1692
1535
|
});
|
|
1693
1536
|
|
|
1694
1537
|
// B. Handle MQTT Commands (Home Assistant)
|
|
@@ -1746,7 +1589,7 @@ module.exports = function (RED) {
|
|
|
1746
1589
|
|
|
1747
1590
|
// Trigger the actual refresh
|
|
1748
1591
|
node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
|
|
1749
|
-
|
|
1592
|
+
forceCategoryDue('intelligent');
|
|
1750
1593
|
});
|
|
1751
1594
|
|
|
1752
1595
|
// Timezone select changed in Home Assistant
|
|
@@ -1766,44 +1609,45 @@ module.exports = function (RED) {
|
|
|
1766
1609
|
else if (val === "OFF") setSmartCharging(false);
|
|
1767
1610
|
});
|
|
1768
1611
|
|
|
1769
|
-
setTimeout(announceControls, 2000);
|
|
1612
|
+
initTimeoutHandles.push(setTimeout(announceControls, 2000));
|
|
1770
1613
|
|
|
1771
1614
|
// Republish persisted timezone to HA select on startup
|
|
1772
|
-
setTimeout(() => {
|
|
1615
|
+
initTimeoutHandles.push(setTimeout(() => {
|
|
1773
1616
|
try {
|
|
1774
1617
|
const persistedTz = node.context().get('timezone');
|
|
1775
1618
|
if (persistedTz && node.broker) {
|
|
1776
1619
|
node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
|
|
1777
1620
|
}
|
|
1778
1621
|
} catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
|
|
1779
|
-
}, 2500);
|
|
1622
|
+
}, 2500));
|
|
1780
1623
|
|
|
1781
1624
|
// Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
|
|
1782
|
-
setTimeout(() => {
|
|
1625
|
+
initTimeoutHandles.push(setTimeout(() => {
|
|
1783
1626
|
try {
|
|
1784
1627
|
if (smartChargingSuspended !== null && node.broker && node.broker.client) {
|
|
1785
1628
|
const stateVal = smartChargingSuspended ? "OFF" : "ON";
|
|
1786
1629
|
node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
|
|
1787
1630
|
}
|
|
1788
1631
|
} catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
|
|
1789
|
-
}, 3000);
|
|
1632
|
+
}, 3000));
|
|
1790
1633
|
}
|
|
1791
1634
|
|
|
1792
1635
|
// Init
|
|
1793
|
-
|
|
1794
|
-
updateNextPollTime(); // Set initial next poll time
|
|
1795
|
-
setTimeout(fetchData, 1000);
|
|
1796
|
-
setTimeout(fetchDeviceId, 1500);
|
|
1636
|
+
initTimeoutHandles.push(setTimeout(fetchDeviceId, 1500));
|
|
1797
1637
|
|
|
1798
|
-
// V2 category discovery and scheduler
|
|
1799
|
-
|
|
1638
|
+
// V2 category discovery and scheduler. Tracked + nodeClosed-guarded so that a
|
|
1639
|
+
// node redeploy during the 2s warmup (or during the async discovery/init) can
|
|
1640
|
+
// never leave an orphan scheduler running.
|
|
1641
|
+
initTimeoutHandles.push(setTimeout(async () => {
|
|
1800
1642
|
try {
|
|
1801
1643
|
const discovered = await discoverProducts(apiKey, account);
|
|
1644
|
+
if (nodeClosed) return;
|
|
1802
1645
|
if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
|
|
1803
1646
|
smartChargingSuspended = discovered.deviceSuspended;
|
|
1804
1647
|
lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
|
|
1805
1648
|
}
|
|
1806
1649
|
await initCategories(discovered);
|
|
1650
|
+
if (nodeClosed) return;
|
|
1807
1651
|
node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}`);
|
|
1808
1652
|
const v2Scheduler = createScheduler(pollDueCategories);
|
|
1809
1653
|
v2Scheduler.start();
|
|
@@ -1811,10 +1655,13 @@ module.exports = function (RED) {
|
|
|
1811
1655
|
} catch (e) {
|
|
1812
1656
|
node.warn(`V2 discovery failed: ${e.message}. New categories unavailable.`);
|
|
1813
1657
|
}
|
|
1814
|
-
}, 2000);
|
|
1658
|
+
}, 2000));
|
|
1815
1659
|
|
|
1816
1660
|
node.on('close', () => {
|
|
1817
|
-
|
|
1661
|
+
nodeClosed = true;
|
|
1662
|
+
// Clear init setTimeouts so a redeploy during warmup can't leave an orphan scheduler
|
|
1663
|
+
initTimeoutHandles.forEach(h => clearTimeout(h));
|
|
1664
|
+
initTimeoutHandles = [];
|
|
1818
1665
|
// Clear any pending retry timeouts
|
|
1819
1666
|
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
1820
1667
|
retryTimeouts = [];
|
package/package.json
CHANGED