node-red-contrib-octopus-intelligent 1.3.3 → 1.5.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 +51 -0
- package/examples/ha-dashboard.yaml +159 -46
- package/examples/node-red-dashboard-flow.json +1199 -0
- package/lib/categories/applicable-rates.js +39 -3
- package/lib/categories/electricity.js +15 -2
- package/lib/http-get-json.js +22 -0
- package/lib/payload.js +12 -1
- package/lib/poll-tick.js +44 -0
- package/lib/scheduler.js +17 -3
- package/lib/update-check.js +38 -0
- package/octopus-intelligent.js +348 -379
- package/package.json +1 -1
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');
|
|
@@ -18,6 +19,8 @@ const flexPlannedDispatchesCategory = require('./lib/categories/flex-planned-dis
|
|
|
18
19
|
const applicableRatesCategory = require('./lib/categories/applicable-rates');
|
|
19
20
|
const savingSessionsCategory = require('./lib/categories/saving-sessions');
|
|
20
21
|
const freeElectricityCategory = require('./lib/categories/free-electricity');
|
|
22
|
+
const httpGetJson = require('./lib/http-get-json');
|
|
23
|
+
const { checkUpdate } = require('./lib/update-check');
|
|
21
24
|
|
|
22
25
|
module.exports = function (RED) {
|
|
23
26
|
function OctopusIntelligentNode(config) {
|
|
@@ -106,6 +109,10 @@ module.exports = function (RED) {
|
|
|
106
109
|
{ id: 'electricity_consumption_kwh', name: 'Electricity Consumption', unit: 'kWh', class: 'energy', val: 'electricity_consumption_kwh' },
|
|
107
110
|
// --- Electricity (config) ---
|
|
108
111
|
{ id: 'electricity_unit_rate', name: 'Electricity Unit Rate', unit: 'p/kWh', icon: 'mdi:flash', val: 'electricity_unit_rate' },
|
|
112
|
+
{ id: 'electricity_day_rate', name: 'Electricity Day Rate', unit: 'p/kWh', icon: 'mdi:weather-sunny', val: 'electricity_day_rate', category: 'config' },
|
|
113
|
+
{ id: 'electricity_night_rate', name: 'Electricity Night Rate', unit: 'p/kWh', icon: 'mdi:weather-night', val: 'electricity_night_rate', category: 'config' },
|
|
114
|
+
{ id: 'electricity_ev_peak_rate', name: 'Electricity EV Peak Rate', unit: 'p/kWh', icon: 'mdi:car-electric-outline', val: 'electricity_ev_peak_rate', category: 'config' },
|
|
115
|
+
{ id: 'electricity_ev_off_peak_rate', name: 'Electricity EV Off-Peak Rate', unit: 'p/kWh', icon: 'mdi:car-electric', val: 'electricity_ev_off_peak_rate', category: 'config' },
|
|
109
116
|
{ id: 'electricity_tariff_code', name: 'Electricity Tariff Code', icon: 'mdi:tag', val: 'electricity_tariff_code' },
|
|
110
117
|
{ id: 'electricity_valid_from', name: 'Electricity Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'electricity_valid_from' },
|
|
111
118
|
{ id: 'electricity_valid_to', name: 'Electricity Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'electricity_valid_to' },
|
|
@@ -136,6 +143,8 @@ module.exports = function (RED) {
|
|
|
136
143
|
{ id: 'electricity_export_rate_prev_to', name: 'Electricity Export Rate Prev Ends', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_rate_prev_to', category: 'diagnostic' },
|
|
137
144
|
{ id: 'electricity_export_rate_next_pence', name: 'Electricity Export Rate Next', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_next_pence', category: 'diagnostic' },
|
|
138
145
|
{ id: 'electricity_export_rate_next_from', name: 'Electricity Export Rate Next From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_rate_next_from', category: 'diagnostic' },
|
|
146
|
+
{ id: 'electricity_export_rate_prev_gbp', name: 'Electricity Export Rate Prev (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_prev_gbp', stateClass: 'measurement', category: 'diagnostic' },
|
|
147
|
+
{ id: 'electricity_export_rate_next_gbp', name: 'Electricity Export Rate Next (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_next_gbp', stateClass: 'measurement', category: 'diagnostic' },
|
|
139
148
|
{ id: 'electricity_export_rate_error', name: 'Electricity Export Rate Error', icon: 'mdi:alert-circle', val: 'electricity_export_rate_error', category: 'diagnostic' },
|
|
140
149
|
|
|
141
150
|
// --- Gas (main) ---
|
|
@@ -158,6 +167,21 @@ module.exports = function (RED) {
|
|
|
158
167
|
// --- Applicable Rates (diagnostic) ---
|
|
159
168
|
{ id: 'applicable_rates_count', name: 'Applicable Rates Slots', icon: 'mdi:format-list-numbered', val: 'applicable_rates_count', category: 'diagnostic' },
|
|
160
169
|
{ id: 'applicable_rates_error', name: 'Applicable Rates Error', icon: 'mdi:alert-circle', val: 'applicable_rates_error', category: 'diagnostic' },
|
|
170
|
+
{ id: 'applicable_rates_prev_pence', name: 'Applicable Rate Prev', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_prev_pence', category: 'diagnostic' },
|
|
171
|
+
{ id: 'applicable_rates_prev_gbp', name: 'Applicable Rate Prev (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_prev_gbp', stateClass: 'measurement', category: 'diagnostic' },
|
|
172
|
+
{ id: 'applicable_rates_prev_to', name: 'Applicable Rate Prev Ends', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'applicable_rates_prev_to', category: 'diagnostic' },
|
|
173
|
+
{ id: 'applicable_rates_next_pence', name: 'Applicable Rate Next', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_next_pence', category: 'diagnostic' },
|
|
174
|
+
{ id: 'applicable_rates_next_gbp', name: 'Applicable Rate Next (GBP)', unit: 'GBP/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_next_gbp', stateClass: 'measurement', category: 'diagnostic' },
|
|
175
|
+
{ id: 'applicable_rates_next_from', name: 'Applicable Rate Next From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'applicable_rates_next_from', category: 'diagnostic' },
|
|
176
|
+
// Applicable rates — 24h schedule stats (v1.5)
|
|
177
|
+
{ id: 'applicable_rates_min_pence', name: 'Applicable Rates Min', unit: 'p/kWh', icon: 'mdi:arrow-down', val: 'applicable_rates_min_pence', category: 'diagnostic' },
|
|
178
|
+
{ id: 'applicable_rates_max_pence', name: 'Applicable Rates Max', unit: 'p/kWh', icon: 'mdi:arrow-up', val: 'applicable_rates_max_pence', category: 'diagnostic' },
|
|
179
|
+
{ id: 'applicable_rates_median_pence', name: 'Applicable Rates Median', unit: 'p/kWh', icon: 'mdi:approximately-equal', val: 'applicable_rates_median_pence', category: 'diagnostic' },
|
|
180
|
+
{ id: 'applicable_rates_avg_pence', name: 'Applicable Rates Avg', unit: 'p/kWh', icon: 'mdi:chart-line', val: 'applicable_rates_avg_pence', category: 'diagnostic' },
|
|
181
|
+
{ id: 'electricity_export_rate_min_pence', name: 'Electricity Export Rate Min', unit: 'p/kWh', icon: 'mdi:arrow-down', val: 'electricity_export_rate_min_pence', category: 'diagnostic' },
|
|
182
|
+
{ id: 'electricity_export_rate_max_pence', name: 'Electricity Export Rate Max', unit: 'p/kWh', icon: 'mdi:arrow-up', val: 'electricity_export_rate_max_pence', category: 'diagnostic' },
|
|
183
|
+
{ id: 'electricity_export_rate_median_pence', name: 'Electricity Export Rate Median', unit: 'p/kWh', icon: 'mdi:approximately-equal', val: 'electricity_export_rate_median_pence', category: 'diagnostic' },
|
|
184
|
+
{ id: 'electricity_export_rate_avg_pence', name: 'Electricity Export Rate Avg', unit: 'p/kWh', icon: 'mdi:chart-line', val: 'electricity_export_rate_avg_pence', category: 'diagnostic' },
|
|
161
185
|
|
|
162
186
|
// --- Account (main) ---
|
|
163
187
|
{ id: 'account_balance_pounds', name: 'Account Balance', unit: '£', icon: 'mdi:cash-multiple', val: 'account_balance_pounds' },
|
|
@@ -210,6 +234,33 @@ module.exports = function (RED) {
|
|
|
210
234
|
{ id: 'completed_dispatches_error', name: 'Completed Dispatches Error', icon: 'mdi:alert-circle', val: 'completed_dispatches_error', category: 'diagnostic' },
|
|
211
235
|
{ id: 'flex_planned_dispatches_error', name: 'Flex Planned Dispatches Error', icon: 'mdi:alert-circle', val: 'flex_planned_dispatches_error', category: 'diagnostic' },
|
|
212
236
|
{ id: 'intelligent_error', name: 'Intelligent Error', icon: 'mdi:alert-circle', val: 'intelligent_error', category: 'diagnostic' },
|
|
237
|
+
|
|
238
|
+
// v1.5 — update check (MQTT Update entity itself lands in Task 21)
|
|
239
|
+
{ id: 'installed_version', name: 'Installed Version', icon: 'mdi:package-variant', val: 'installed_version', category: 'diagnostic' },
|
|
240
|
+
{ id: 'latest_version', name: 'Latest Version', icon: 'mdi:package-variant-closed-plus', val: 'latest_version', category: 'diagnostic' },
|
|
241
|
+
{ id: 'update_check_at', name: 'Update Check At', class: 'timestamp', icon: 'mdi:clock-check-outline', val: 'update_check_at', category: 'diagnostic' },
|
|
242
|
+
{ id: 'update_check_error', name: 'Update Check Error', icon: 'mdi:alert-circle', val: 'update_check_error', category: 'diagnostic' },
|
|
243
|
+
];
|
|
244
|
+
|
|
245
|
+
// v1.5 — derived binary_sensors for the unified <category>_error fields.
|
|
246
|
+
// OFF when the underlying field is null/empty (healthy), ON when populated.
|
|
247
|
+
// The string sensors stay; these are additional indicators.
|
|
248
|
+
const errorSensors = [
|
|
249
|
+
{ id: 'intelligent_error_state', name: 'Intelligent Error State', val: 'intelligent_error' },
|
|
250
|
+
{ id: 'electricity_rates_error_state', name: 'Electricity Rates Error State', val: 'electricity_rates_error' },
|
|
251
|
+
{ id: 'electricity_consumption_error_state', name: 'Electricity Consumption Error State', val: 'electricity_consumption_error' },
|
|
252
|
+
{ id: 'electricity_export_rate_error_state', name: 'Electricity Export Rate Error State', val: 'electricity_export_rate_error' },
|
|
253
|
+
{ id: 'gas_rates_error_state', name: 'Gas Rates Error State', val: 'gas_rates_error' },
|
|
254
|
+
{ id: 'gas_consumption_error_state', name: 'Gas Consumption Error State', val: 'gas_consumption_error' },
|
|
255
|
+
{ id: 'applicable_rates_error_state', name: 'Applicable Rates Error State', val: 'applicable_rates_error' },
|
|
256
|
+
{ id: 'account_error_state', name: 'Account Error State', val: 'account_error' },
|
|
257
|
+
{ id: 'octoplus_error_state', name: 'Octoplus Error State', val: 'octoplus_error' },
|
|
258
|
+
{ id: 'wheel_of_fortune_error_state', name: 'Wheel of Fortune Error State', val: 'wheel_of_fortune_error' },
|
|
259
|
+
{ id: 'home_mini_error_state', name: 'Home Mini Error State', val: 'home_mini_error' },
|
|
260
|
+
{ id: 'saving_sessions_error_state', name: 'Saving Sessions Error State', val: 'saving_sessions_error' },
|
|
261
|
+
{ id: 'free_electricity_error_state', name: 'Free Electricity Error State', val: 'free_electricity_error' },
|
|
262
|
+
{ id: 'completed_dispatches_error_state', name: 'Completed Dispatches Error State', val: 'completed_dispatches_error' },
|
|
263
|
+
{ id: 'flex_planned_dispatches_error_state', name: 'Flex Planned Dispatches Error State', val: 'flex_planned_dispatches_error' },
|
|
213
264
|
];
|
|
214
265
|
|
|
215
266
|
// 4. Helper: Announce Controls (Write-Enabled)
|
|
@@ -447,9 +498,33 @@ module.exports = function (RED) {
|
|
|
447
498
|
payload.entity_category = sensor.category;
|
|
448
499
|
}
|
|
449
500
|
|
|
501
|
+
if (sensor.id === 'applicable_rates_count') {
|
|
502
|
+
payload.json_attributes_topic = stateTopic;
|
|
503
|
+
payload.json_attributes_template = '{ "rates": {{ value_json.applicable_rates | tojson }} }';
|
|
504
|
+
} else if (sensor.id === 'electricity_export_rate_count') {
|
|
505
|
+
payload.json_attributes_topic = stateTopic;
|
|
506
|
+
payload.json_attributes_template = '{ "rates": {{ value_json.electricity_export_rate | tojson }} }';
|
|
507
|
+
}
|
|
508
|
+
|
|
450
509
|
node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
|
|
451
510
|
});
|
|
452
511
|
|
|
512
|
+
// H2. v1.5 — error binary_sensors (device_class: problem)
|
|
513
|
+
errorSensors.forEach(e => {
|
|
514
|
+
const payload = {
|
|
515
|
+
name: `Octopus ${e.name}`,
|
|
516
|
+
unique_id: `${uniqueIdPrefix}_${e.id}`,
|
|
517
|
+
state_topic: stateTopic,
|
|
518
|
+
value_template: `{{ 'OFF' if value_json.${e.val} in [None, ''] else 'ON' }}`,
|
|
519
|
+
payload_on: 'ON',
|
|
520
|
+
payload_off: 'OFF',
|
|
521
|
+
device_class: 'problem',
|
|
522
|
+
entity_category: 'diagnostic',
|
|
523
|
+
device: device,
|
|
524
|
+
};
|
|
525
|
+
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_${e.id}/config`, JSON.stringify(payload), { retain: true });
|
|
526
|
+
});
|
|
527
|
+
|
|
453
528
|
// I. Timezone Select Entity
|
|
454
529
|
const TIMEZONE_OPTIONS = [
|
|
455
530
|
"Europe/London", "Europe/Berlin", "Europe/Madrid",
|
|
@@ -490,6 +565,20 @@ module.exports = function (RED) {
|
|
|
490
565
|
{ retain: true }
|
|
491
566
|
);
|
|
492
567
|
|
|
568
|
+
// K. v1.5 — Update entity (notify-only; Palette Manager is the install path)
|
|
569
|
+
node.broker.client.publish(
|
|
570
|
+
`${mqttPrefix}/update/${uniqueIdPrefix}_node_update/config`,
|
|
571
|
+
JSON.stringify({
|
|
572
|
+
name: 'Octopus Intelligent Node',
|
|
573
|
+
unique_id: `${uniqueIdPrefix}_node_update`,
|
|
574
|
+
state_topic: `${stateTopic}/node_update`,
|
|
575
|
+
title: 'node-red-contrib-octopus-intelligent',
|
|
576
|
+
release_url: 'https://github.com/ASomerN/node-red-contrib-octopus-intelligent/releases',
|
|
577
|
+
device: device,
|
|
578
|
+
}),
|
|
579
|
+
{ retain: true }
|
|
580
|
+
);
|
|
581
|
+
|
|
493
582
|
// Subscribe to Commands
|
|
494
583
|
node.broker.client.subscribe(cmdTopicLimit);
|
|
495
584
|
node.broker.client.subscribe(cmdTopicTime);
|
|
@@ -503,6 +592,7 @@ module.exports = function (RED) {
|
|
|
503
592
|
let retryTimeouts = []; // Track pending retry timeouts
|
|
504
593
|
let expectedLimit = null;
|
|
505
594
|
let expectedTime = null;
|
|
595
|
+
let validationMode = false;
|
|
506
596
|
|
|
507
597
|
// Pending vs Confirmed state
|
|
508
598
|
let pendingLimit = 80;
|
|
@@ -526,7 +616,6 @@ module.exports = function (RED) {
|
|
|
526
616
|
|
|
527
617
|
// Polling metrics
|
|
528
618
|
let nextPollTime = null; // ISO timestamp of next scheduled poll
|
|
529
|
-
let pollIntervalHandle = null; // Reference to setInterval handle
|
|
530
619
|
const metrics = createApiMetrics();
|
|
531
620
|
|
|
532
621
|
// API Complexity Tracking
|
|
@@ -543,13 +632,33 @@ module.exports = function (RED) {
|
|
|
543
632
|
|
|
544
633
|
// Last known full state - prevents sensors going unknown when controls change
|
|
545
634
|
let lastKnownState = buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
|
|
635
|
+
lastKnownState.installed_version = require('./package.json').version;
|
|
546
636
|
|
|
547
637
|
// V2 category registry — populated after discovery
|
|
548
638
|
let categories = [];
|
|
549
639
|
|
|
640
|
+
// Lifecycle tracking — init setTimeouts must be clearable on close, and async
|
|
641
|
+
// callbacks inside them must short-circuit if the node was closed mid-await,
|
|
642
|
+
// otherwise a redeploy during the 2s warmup leaves an orphan V2 scheduler.
|
|
643
|
+
let initTimeoutHandles = [];
|
|
644
|
+
let nodeClosed = false;
|
|
645
|
+
let lastWarnedVersion = null;
|
|
646
|
+
let prevPublishedInstalled = null;
|
|
647
|
+
let prevPublishedLatest = null;
|
|
648
|
+
|
|
550
649
|
async function initCategories(discovered) {
|
|
551
650
|
categories = [];
|
|
552
651
|
|
|
652
|
+
if (discovered.hasIntelligent) {
|
|
653
|
+
categories.push({
|
|
654
|
+
id: 'intelligent',
|
|
655
|
+
enabled: true,
|
|
656
|
+
intervalMs: (config.refreshInterval || 5) * 60 * 1000,
|
|
657
|
+
lastPolled: 0,
|
|
658
|
+
poll: intelligentPoll,
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
|
|
553
662
|
const electricityEnabled = config.electricityEnabled !== false;
|
|
554
663
|
const gasEnabled = config.gasEnabled !== false;
|
|
555
664
|
|
|
@@ -562,7 +671,12 @@ module.exports = function (RED) {
|
|
|
562
671
|
intervalMs: ratesMs,
|
|
563
672
|
lastPolled: 0,
|
|
564
673
|
queryFn: () => electricityCategory.buildRatesQuery(account),
|
|
565
|
-
parseFn: d => electricityCategory.parseRatesResponse(d)
|
|
674
|
+
parseFn: d => electricityCategory.parseRatesResponse(d),
|
|
675
|
+
poll: simplePoll(
|
|
676
|
+
() => electricityCategory.buildRatesQuery(account),
|
|
677
|
+
d => electricityCategory.parseRatesResponse(d),
|
|
678
|
+
graphqlPost
|
|
679
|
+
),
|
|
566
680
|
});
|
|
567
681
|
categories.push({
|
|
568
682
|
id: 'electricity_consumption',
|
|
@@ -570,7 +684,12 @@ module.exports = function (RED) {
|
|
|
570
684
|
intervalMs: consumptionMs,
|
|
571
685
|
lastPolled: 0,
|
|
572
686
|
queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
573
|
-
parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan)
|
|
687
|
+
parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
|
|
688
|
+
poll: simplePoll(
|
|
689
|
+
() => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
690
|
+
d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan),
|
|
691
|
+
graphqlPost
|
|
692
|
+
),
|
|
574
693
|
});
|
|
575
694
|
}
|
|
576
695
|
|
|
@@ -583,7 +702,12 @@ module.exports = function (RED) {
|
|
|
583
702
|
intervalMs: ratesMs,
|
|
584
703
|
lastPolled: 0,
|
|
585
704
|
queryFn: () => gasCategory.buildRatesQuery(account),
|
|
586
|
-
parseFn: d => gasCategory.parseRatesResponse(d)
|
|
705
|
+
parseFn: d => gasCategory.parseRatesResponse(d),
|
|
706
|
+
poll: simplePoll(
|
|
707
|
+
() => gasCategory.buildRatesQuery(account),
|
|
708
|
+
d => gasCategory.parseRatesResponse(d),
|
|
709
|
+
graphqlPost
|
|
710
|
+
),
|
|
587
711
|
});
|
|
588
712
|
categories.push({
|
|
589
713
|
id: 'gas_consumption',
|
|
@@ -591,7 +715,12 @@ module.exports = function (RED) {
|
|
|
591
715
|
intervalMs: consumptionMs,
|
|
592
716
|
lastPolled: 0,
|
|
593
717
|
queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
594
|
-
parseFn: d => gasCategory.parseConsumptionResponse(d)
|
|
718
|
+
parseFn: d => gasCategory.parseConsumptionResponse(d),
|
|
719
|
+
poll: simplePoll(
|
|
720
|
+
() => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
721
|
+
d => gasCategory.parseConsumptionResponse(d),
|
|
722
|
+
graphqlPost
|
|
723
|
+
),
|
|
595
724
|
});
|
|
596
725
|
}
|
|
597
726
|
|
|
@@ -601,7 +730,12 @@ module.exports = function (RED) {
|
|
|
601
730
|
intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
|
|
602
731
|
lastPolled: 0,
|
|
603
732
|
queryFn: () => wheelOfFortuneCategory.buildQuery(account),
|
|
604
|
-
parseFn: d => wheelOfFortuneCategory.parseResponse(d)
|
|
733
|
+
parseFn: d => wheelOfFortuneCategory.parseResponse(d),
|
|
734
|
+
poll: simplePoll(
|
|
735
|
+
() => wheelOfFortuneCategory.buildQuery(account),
|
|
736
|
+
d => wheelOfFortuneCategory.parseResponse(d),
|
|
737
|
+
graphqlPost
|
|
738
|
+
),
|
|
605
739
|
});
|
|
606
740
|
if (discovered.smartMeterDeviceId) {
|
|
607
741
|
categories.push({
|
|
@@ -610,7 +744,12 @@ module.exports = function (RED) {
|
|
|
610
744
|
intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
|
|
611
745
|
lastPolled: 0,
|
|
612
746
|
queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
|
|
613
|
-
parseFn: d => homeMiniCategory.parseResponse(d)
|
|
747
|
+
parseFn: d => homeMiniCategory.parseResponse(d),
|
|
748
|
+
poll: simplePoll(
|
|
749
|
+
() => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
|
|
750
|
+
d => homeMiniCategory.parseResponse(d),
|
|
751
|
+
graphqlPost
|
|
752
|
+
),
|
|
614
753
|
});
|
|
615
754
|
}
|
|
616
755
|
categories.push({
|
|
@@ -619,7 +758,12 @@ module.exports = function (RED) {
|
|
|
619
758
|
intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
|
|
620
759
|
lastPolled: 0,
|
|
621
760
|
queryFn: () => savingSessionsCategory.buildQuery(account),
|
|
622
|
-
parseFn: d => savingSessionsCategory.parseResponse(d)
|
|
761
|
+
parseFn: d => savingSessionsCategory.parseResponse(d),
|
|
762
|
+
poll: simplePoll(
|
|
763
|
+
() => savingSessionsCategory.buildQuery(account),
|
|
764
|
+
d => savingSessionsCategory.parseResponse(d),
|
|
765
|
+
graphqlPost
|
|
766
|
+
),
|
|
623
767
|
});
|
|
624
768
|
|
|
625
769
|
if (discovered.hasIntelligent) {
|
|
@@ -629,18 +773,13 @@ module.exports = function (RED) {
|
|
|
629
773
|
intervalMs: 60 * 60 * 1000,
|
|
630
774
|
lastPolled: 0,
|
|
631
775
|
queryFn: () => completedDispatchesCategory.buildQuery(account),
|
|
632
|
-
parseFn: d => completedDispatchesCategory.parseResponse(d)
|
|
776
|
+
parseFn: d => completedDispatchesCategory.parseResponse(d),
|
|
777
|
+
poll: simplePoll(
|
|
778
|
+
() => completedDispatchesCategory.buildQuery(account),
|
|
779
|
+
d => completedDispatchesCategory.parseResponse(d),
|
|
780
|
+
graphqlPost
|
|
781
|
+
),
|
|
633
782
|
});
|
|
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
783
|
}
|
|
645
784
|
|
|
646
785
|
if (discovered.hasElectricity && discovered.electricityMpan) {
|
|
@@ -650,7 +789,12 @@ module.exports = function (RED) {
|
|
|
650
789
|
intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
|
|
651
790
|
lastPolled: 0,
|
|
652
791
|
queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
|
|
653
|
-
parseFn: d => applicableRatesCategory.parseResponse(d)
|
|
792
|
+
parseFn: d => applicableRatesCategory.parseResponse(d),
|
|
793
|
+
poll: simplePoll(
|
|
794
|
+
() => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
|
|
795
|
+
d => applicableRatesCategory.parseResponse(d),
|
|
796
|
+
graphqlPost
|
|
797
|
+
),
|
|
654
798
|
});
|
|
655
799
|
}
|
|
656
800
|
|
|
@@ -663,7 +807,12 @@ module.exports = function (RED) {
|
|
|
663
807
|
intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
|
|
664
808
|
lastPolled: 0,
|
|
665
809
|
queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
|
|
666
|
-
parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' })
|
|
810
|
+
parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
|
|
811
|
+
poll: simplePoll(
|
|
812
|
+
() => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
|
|
813
|
+
d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' }),
|
|
814
|
+
graphqlPost
|
|
815
|
+
),
|
|
667
816
|
});
|
|
668
817
|
}
|
|
669
818
|
|
|
@@ -674,7 +823,12 @@ module.exports = function (RED) {
|
|
|
674
823
|
intervalMs: 30 * 60 * 1000, // 30 minutes
|
|
675
824
|
lastPolled: 0,
|
|
676
825
|
queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
|
|
677
|
-
parseFn: d => freeElectricityCategory.parseResponse(d)
|
|
826
|
+
parseFn: d => freeElectricityCategory.parseResponse(d),
|
|
827
|
+
poll: simplePoll(
|
|
828
|
+
() => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
|
|
829
|
+
d => freeElectricityCategory.parseResponse(d),
|
|
830
|
+
graphqlPost
|
|
831
|
+
),
|
|
678
832
|
});
|
|
679
833
|
}
|
|
680
834
|
|
|
@@ -684,7 +838,12 @@ module.exports = function (RED) {
|
|
|
684
838
|
intervalMs: 60 * 60 * 1000,
|
|
685
839
|
lastPolled: 0,
|
|
686
840
|
queryFn: () => accountCategory.buildQuery(account),
|
|
687
|
-
parseFn: d => accountCategory.parseResponse(d)
|
|
841
|
+
parseFn: d => accountCategory.parseResponse(d),
|
|
842
|
+
poll: simplePoll(
|
|
843
|
+
() => accountCategory.buildQuery(account),
|
|
844
|
+
d => accountCategory.parseResponse(d),
|
|
845
|
+
graphqlPost
|
|
846
|
+
),
|
|
688
847
|
});
|
|
689
848
|
|
|
690
849
|
categories.push({
|
|
@@ -693,49 +852,75 @@ module.exports = function (RED) {
|
|
|
693
852
|
intervalMs: 60 * 60 * 1000,
|
|
694
853
|
lastPolled: 0,
|
|
695
854
|
queryFn: () => octoplusCategory.buildQuery(account),
|
|
696
|
-
parseFn: d => octoplusCategory.parseResponse(d)
|
|
855
|
+
parseFn: d => octoplusCategory.parseResponse(d),
|
|
856
|
+
poll: simplePoll(
|
|
857
|
+
() => octoplusCategory.buildQuery(account),
|
|
858
|
+
d => octoplusCategory.parseResponse(d),
|
|
859
|
+
graphqlPost
|
|
860
|
+
),
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
categories.push({
|
|
864
|
+
id: 'update_check',
|
|
865
|
+
enabled: true,
|
|
866
|
+
intervalMs: 24 * 60 * 60 * 1000, // 24h — once daily npm registry check
|
|
867
|
+
lastPolled: 0, // fires on first scheduler tick
|
|
868
|
+
poll: intelligentUpdateCheck, // token ignored
|
|
697
869
|
});
|
|
698
870
|
}
|
|
699
871
|
|
|
700
872
|
async function pollDueCategories() {
|
|
701
|
-
const
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
if (
|
|
712
|
-
|
|
873
|
+
const result = await runTick({
|
|
874
|
+
categories,
|
|
875
|
+
state: lastKnownState,
|
|
876
|
+
getToken: obtainTickToken,
|
|
877
|
+
});
|
|
878
|
+
if (!result.emitted) return;
|
|
879
|
+
lastKnownState = result.state;
|
|
880
|
+
if (enableMqtt && node.broker && node.broker.client) {
|
|
881
|
+
node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
|
|
882
|
+
// v1.5 — publish update entity state only when version values change
|
|
883
|
+
if (prevPublishedInstalled !== lastKnownState.installed_version
|
|
884
|
+
|| prevPublishedLatest !== lastKnownState.latest_version) {
|
|
885
|
+
const updateState = {
|
|
886
|
+
installed_version: lastKnownState.installed_version,
|
|
887
|
+
latest_version: lastKnownState.latest_version || lastKnownState.installed_version,
|
|
888
|
+
};
|
|
889
|
+
node.broker.client.publish(`${stateTopic}/node_update`, JSON.stringify(updateState), { retain: true });
|
|
890
|
+
prevPublishedInstalled = lastKnownState.installed_version;
|
|
891
|
+
prevPublishedLatest = lastKnownState.latest_version;
|
|
713
892
|
}
|
|
714
|
-
token = response.data.data.obtainKrakenToken.token;
|
|
715
|
-
} catch (e) {
|
|
716
|
-
node.warn(`V2 category poll: auth failed: ${e.message}`);
|
|
717
|
-
return;
|
|
718
893
|
}
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
node.warn(`V2 category ${cat.id} failed (disabled until redeploy): ${e.message}`);
|
|
894
|
+
node.send({ payload: lastKnownState });
|
|
895
|
+
if (lastKnownState.update_available === true
|
|
896
|
+
&& lastKnownState.latest_version
|
|
897
|
+
&& lastKnownState.latest_version !== lastWarnedVersion) {
|
|
898
|
+
node.warn(`Update available: v${lastKnownState.latest_version} (running v${lastKnownState.installed_version}). Install via Node-RED → Manage Palette → Upgrade.`);
|
|
899
|
+
lastWarnedVersion = lastKnownState.latest_version;
|
|
900
|
+
}
|
|
901
|
+
if (!validationMode) {
|
|
902
|
+
if (lastKnownState.intelligent_error) {
|
|
903
|
+
node.status({ fill: "red", shape: "ring", text: `Error: ${String(lastKnownState.intelligent_error).slice(0, 40)}` });
|
|
904
|
+
} else {
|
|
905
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
|
|
732
906
|
}
|
|
733
907
|
}
|
|
908
|
+
}
|
|
734
909
|
|
|
735
|
-
|
|
736
|
-
|
|
910
|
+
async function obtainTickToken() {
|
|
911
|
+
const response = await graphqlPost({
|
|
912
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
913
|
+
variables: { input: { APIKey: apiKey } },
|
|
914
|
+
});
|
|
915
|
+
if (!response.data.data || !response.data.data.obtainKrakenToken) {
|
|
916
|
+
throw new Error('Auth response missing token: ' + JSON.stringify(response.data.errors || response.data));
|
|
737
917
|
}
|
|
738
|
-
|
|
918
|
+
return response.data.data.obtainKrakenToken.token;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function forceCategoryDue(id) {
|
|
922
|
+
const cat = categories.find((c) => c.id === id);
|
|
923
|
+
if (cat) cat.lastPolled = 0;
|
|
739
924
|
}
|
|
740
925
|
|
|
741
926
|
async function setPreferences(newLimit, newTime) {
|
|
@@ -822,6 +1007,7 @@ module.exports = function (RED) {
|
|
|
822
1007
|
// C. Start exponential backoff validation
|
|
823
1008
|
expectedLimit = limit;
|
|
824
1009
|
expectedTime = time;
|
|
1010
|
+
validationMode = true;
|
|
825
1011
|
node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
|
|
826
1012
|
|
|
827
1013
|
// Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
|
|
@@ -836,6 +1022,7 @@ module.exports = function (RED) {
|
|
|
836
1022
|
node.status({ fill: "red", shape: "ring", text: "Update Failed" });
|
|
837
1023
|
expectedLimit = null;
|
|
838
1024
|
expectedTime = null;
|
|
1025
|
+
validationMode = false;
|
|
839
1026
|
}
|
|
840
1027
|
}
|
|
841
1028
|
|
|
@@ -845,6 +1032,7 @@ module.exports = function (RED) {
|
|
|
845
1032
|
node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
|
|
846
1033
|
expectedLimit = null;
|
|
847
1034
|
expectedTime = null;
|
|
1035
|
+
validationMode = false;
|
|
848
1036
|
return;
|
|
849
1037
|
}
|
|
850
1038
|
|
|
@@ -857,28 +1045,39 @@ module.exports = function (RED) {
|
|
|
857
1045
|
|
|
858
1046
|
async function fetchDataWithValidation(intervals, currentIndex) {
|
|
859
1047
|
try {
|
|
860
|
-
const
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
if (
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
1048
|
+
const token = await obtainTickToken();
|
|
1049
|
+
const partial = await intelligentPoll(token);
|
|
1050
|
+
lastKnownState = Object.assign({}, lastKnownState, partial, { intelligent_error: null });
|
|
1051
|
+
if (enableMqtt && node.broker && node.broker.client) {
|
|
1052
|
+
node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
|
|
1053
|
+
}
|
|
1054
|
+
node.send({ payload: lastKnownState });
|
|
1055
|
+
|
|
1056
|
+
const validated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
|
|
1057
|
+
if (validated) {
|
|
1058
|
+
validationMode = false;
|
|
1059
|
+
retryTimeouts.forEach((t) => clearTimeout(t));
|
|
870
1060
|
retryTimeouts = [];
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
1061
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const totalAttempts = intervals.length;
|
|
1065
|
+
const attempt = currentIndex + 1;
|
|
1066
|
+
if (currentIndex < intervals.length - 1) {
|
|
875
1067
|
node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
|
|
876
1068
|
scheduleRetries(intervals, currentIndex + 1);
|
|
1069
|
+
} else {
|
|
1070
|
+
validationMode = false;
|
|
1071
|
+
node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
|
|
877
1072
|
}
|
|
878
1073
|
} catch (error) {
|
|
879
|
-
// Error during fetch, schedule next retry
|
|
880
1074
|
node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
|
|
881
|
-
|
|
1075
|
+
if (currentIndex < intervals.length - 1) {
|
|
1076
|
+
scheduleRetries(intervals, currentIndex + 1);
|
|
1077
|
+
} else {
|
|
1078
|
+
validationMode = false;
|
|
1079
|
+
node.status({ fill: "red", shape: "ring", text: "Validation failed" });
|
|
1080
|
+
}
|
|
882
1081
|
}
|
|
883
1082
|
}
|
|
884
1083
|
|
|
@@ -1006,302 +1205,68 @@ module.exports = function (RED) {
|
|
|
1006
1205
|
smartChargingRetryTimeouts.push(timeout);
|
|
1007
1206
|
}
|
|
1008
1207
|
|
|
1009
|
-
// 6. Logic:
|
|
1010
|
-
async function
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
// - Data query (devices + flexPlannedDispatches — two sequential calls): ~400 complexity
|
|
1014
|
-
// - Total: ~300 complexity per poll
|
|
1015
|
-
const ESTIMATED_POLL_COMPLEXITY = 300;
|
|
1016
|
-
|
|
1017
|
-
// Debug object to track API calls
|
|
1018
|
-
const debugInfo = {
|
|
1019
|
-
timestamp: new Date().toISOString(),
|
|
1020
|
-
step: null,
|
|
1021
|
-
success: false,
|
|
1022
|
-
error: null,
|
|
1023
|
-
apiCalls: [],
|
|
1024
|
-
validationMode: validationMode
|
|
1025
|
-
};
|
|
1026
|
-
|
|
1027
|
-
if (!apiKey || !account) {
|
|
1028
|
-
debugInfo.error = "Missing configuration: apiKey or account number not provided";
|
|
1029
|
-
debugInfo.step = "validation";
|
|
1030
|
-
node.status({ fill: "red", shape: "ring", text: "Config Missing" });
|
|
1031
|
-
node.send({
|
|
1032
|
-
payload: getDefaultPayload(),
|
|
1033
|
-
debug: debugInfo
|
|
1034
|
-
});
|
|
1035
|
-
return { validated: false };
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
try {
|
|
1039
|
-
// STEP 1: Get Token
|
|
1040
|
-
debugInfo.step = "authentication";
|
|
1041
|
-
node.status({ fill: "yellow", shape: "ring", text: "Authenticating..." });
|
|
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
|
-
}
|
|
1208
|
+
// 6. Logic: Update Check (bespoke poll that ignores token)
|
|
1209
|
+
async function intelligentUpdateCheck(/* token ignored */) {
|
|
1210
|
+
return checkUpdate(httpGetJson, require('./package.json').version);
|
|
1211
|
+
}
|
|
1295
1212
|
|
|
1296
|
-
|
|
1297
|
-
|
|
1213
|
+
// 6. Logic: Intelligent Poll (single-scheduler bespoke poll)
|
|
1214
|
+
async function intelligentPoll(token) {
|
|
1215
|
+
// 1. devices query
|
|
1216
|
+
const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
|
|
1217
|
+
const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
|
|
1218
|
+
if (devicesResponse.data.errors) throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
|
|
1219
|
+
if (!devicesResponse.data.data) throw new Error('Devices response missing data');
|
|
1220
|
+
const devicesData = devicesResponse.data.data;
|
|
1221
|
+
const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
|
|
1222
|
+
if (!evDevice) throw new Error('No ELECTRIC_VEHICLES device found on account');
|
|
1223
|
+
krakenflexDeviceId = evDevice.id;
|
|
1224
|
+
|
|
1225
|
+
// 2. dispatches query (the single one that used to be duplicated by V1 + V2)
|
|
1226
|
+
const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
|
|
1227
|
+
const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
|
|
1228
|
+
if (dispatchResponse.data.errors) throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
|
|
1229
|
+
if (!dispatchResponse.data.data) throw new Error('Dispatches response missing data');
|
|
1230
|
+
|
|
1231
|
+
// 3. parse twice — intelligent (slots/window) + flex-planned-dispatches (array/count)
|
|
1232
|
+
const data = { devices: devicesData.devices, flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || [] };
|
|
1233
|
+
const appliedTz = resolveTimezone(node);
|
|
1234
|
+
const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch (e) { return 'UTC'; } })();
|
|
1235
|
+
const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
|
|
1236
|
+
const { _activeSlots, ...catPublic } = catResult;
|
|
1237
|
+
const flexResult = flexPlannedDispatchesCategory.parseResponse(dispatchResponse.data.data);
|
|
1238
|
+
|
|
1239
|
+
// 4. metrics + side effects
|
|
1240
|
+
metrics.recordPoll(300);
|
|
1241
|
+
confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
|
|
1242
|
+
confirmedTime = catResult.confirmed_time || confirmedTime;
|
|
1243
|
+
if (!validationMode) {
|
|
1244
|
+
pendingLimit = confirmedLimit;
|
|
1245
|
+
pendingTime = confirmedTime;
|
|
1298
1246
|
}
|
|
1247
|
+
setupChargingTimers(_activeSlots);
|
|
1248
|
+
if (!stateCheckInterval) startStateReconciliation();
|
|
1249
|
+
updateNextPollTime();
|
|
1250
|
+
|
|
1251
|
+
const apiMetrics = metrics.getMetrics();
|
|
1252
|
+
|
|
1253
|
+
// 5. merged partial payload
|
|
1254
|
+
return Object.assign({}, catPublic, flexResult, {
|
|
1255
|
+
pending_limit: pendingLimit,
|
|
1256
|
+
pending_time: pendingTime,
|
|
1257
|
+
charging_now: chargingNow,
|
|
1258
|
+
next_poll: nextPollTime,
|
|
1259
|
+
next_poll_raw: nextPollTime,
|
|
1260
|
+
refresh_available_at: getRefreshAvailableAt(),
|
|
1261
|
+
api_requests_hour: apiMetrics.requests_last_hour,
|
|
1262
|
+
api_complexity_hour: apiMetrics.complexity_last_hour,
|
|
1263
|
+
api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
|
|
1264
|
+
timezone_detected: serverTz,
|
|
1265
|
+
timezone_applied: appliedTz,
|
|
1266
|
+
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
|
|
1267
|
+
});
|
|
1299
1268
|
}
|
|
1300
1269
|
|
|
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
1270
|
|
|
1306
1271
|
// Helper: Fetch device ID and initial smart charging state (called once at startup)
|
|
1307
1272
|
async function fetchDeviceId() {
|
|
@@ -1688,7 +1653,7 @@ module.exports = function (RED) {
|
|
|
1688
1653
|
// Update timestamp so HA sees cooldown, but don't block the refresh
|
|
1689
1654
|
lastManualRefresh = Date.now();
|
|
1690
1655
|
node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
|
|
1691
|
-
|
|
1656
|
+
forceCategoryDue('intelligent');
|
|
1692
1657
|
});
|
|
1693
1658
|
|
|
1694
1659
|
// B. Handle MQTT Commands (Home Assistant)
|
|
@@ -1746,7 +1711,7 @@ module.exports = function (RED) {
|
|
|
1746
1711
|
|
|
1747
1712
|
// Trigger the actual refresh
|
|
1748
1713
|
node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
|
|
1749
|
-
|
|
1714
|
+
forceCategoryDue('intelligent');
|
|
1750
1715
|
});
|
|
1751
1716
|
|
|
1752
1717
|
// Timezone select changed in Home Assistant
|
|
@@ -1766,44 +1731,45 @@ module.exports = function (RED) {
|
|
|
1766
1731
|
else if (val === "OFF") setSmartCharging(false);
|
|
1767
1732
|
});
|
|
1768
1733
|
|
|
1769
|
-
setTimeout(announceControls, 2000);
|
|
1734
|
+
initTimeoutHandles.push(setTimeout(announceControls, 2000));
|
|
1770
1735
|
|
|
1771
1736
|
// Republish persisted timezone to HA select on startup
|
|
1772
|
-
setTimeout(() => {
|
|
1737
|
+
initTimeoutHandles.push(setTimeout(() => {
|
|
1773
1738
|
try {
|
|
1774
1739
|
const persistedTz = node.context().get('timezone');
|
|
1775
1740
|
if (persistedTz && node.broker) {
|
|
1776
1741
|
node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
|
|
1777
1742
|
}
|
|
1778
1743
|
} catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
|
|
1779
|
-
}, 2500);
|
|
1744
|
+
}, 2500));
|
|
1780
1745
|
|
|
1781
1746
|
// Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
|
|
1782
|
-
setTimeout(() => {
|
|
1747
|
+
initTimeoutHandles.push(setTimeout(() => {
|
|
1783
1748
|
try {
|
|
1784
1749
|
if (smartChargingSuspended !== null && node.broker && node.broker.client) {
|
|
1785
1750
|
const stateVal = smartChargingSuspended ? "OFF" : "ON";
|
|
1786
1751
|
node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
|
|
1787
1752
|
}
|
|
1788
1753
|
} catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
|
|
1789
|
-
}, 3000);
|
|
1754
|
+
}, 3000));
|
|
1790
1755
|
}
|
|
1791
1756
|
|
|
1792
1757
|
// Init
|
|
1793
|
-
|
|
1794
|
-
updateNextPollTime(); // Set initial next poll time
|
|
1795
|
-
setTimeout(fetchData, 1000);
|
|
1796
|
-
setTimeout(fetchDeviceId, 1500);
|
|
1758
|
+
initTimeoutHandles.push(setTimeout(fetchDeviceId, 1500));
|
|
1797
1759
|
|
|
1798
|
-
// V2 category discovery and scheduler
|
|
1799
|
-
|
|
1760
|
+
// V2 category discovery and scheduler. Tracked + nodeClosed-guarded so that a
|
|
1761
|
+
// node redeploy during the 2s warmup (or during the async discovery/init) can
|
|
1762
|
+
// never leave an orphan scheduler running.
|
|
1763
|
+
initTimeoutHandles.push(setTimeout(async () => {
|
|
1800
1764
|
try {
|
|
1801
1765
|
const discovered = await discoverProducts(apiKey, account);
|
|
1766
|
+
if (nodeClosed) return;
|
|
1802
1767
|
if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
|
|
1803
1768
|
smartChargingSuspended = discovered.deviceSuspended;
|
|
1804
1769
|
lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
|
|
1805
1770
|
}
|
|
1806
1771
|
await initCategories(discovered);
|
|
1772
|
+
if (nodeClosed) return;
|
|
1807
1773
|
node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}`);
|
|
1808
1774
|
const v2Scheduler = createScheduler(pollDueCategories);
|
|
1809
1775
|
v2Scheduler.start();
|
|
@@ -1811,10 +1777,13 @@ module.exports = function (RED) {
|
|
|
1811
1777
|
} catch (e) {
|
|
1812
1778
|
node.warn(`V2 discovery failed: ${e.message}. New categories unavailable.`);
|
|
1813
1779
|
}
|
|
1814
|
-
}, 2000);
|
|
1780
|
+
}, 2000));
|
|
1815
1781
|
|
|
1816
1782
|
node.on('close', () => {
|
|
1817
|
-
|
|
1783
|
+
nodeClosed = true;
|
|
1784
|
+
// Clear init setTimeouts so a redeploy during warmup can't leave an orphan scheduler
|
|
1785
|
+
initTimeoutHandles.forEach(h => clearTimeout(h));
|
|
1786
|
+
initTimeoutHandles = [];
|
|
1818
1787
|
// Clear any pending retry timeouts
|
|
1819
1788
|
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
1820
1789
|
retryTimeouts = [];
|