node-red-contrib-octopus-intelligent 1.3.2 → 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 CHANGED
@@ -5,6 +5,38 @@ 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
+
25
+ ## [1.3.3] — 2026-05-22
26
+
27
+ ### Fixed
28
+ - **Saving Sessions card showed a 2-year-old session as "next"** — the category was emitting `events[0]` with no filter/sort, so stale historical events surfaced in `saving_session_start/end` and `saving_session_available` was effectively true forever. Now matches the `free-electricity` pattern: filter out ended events, sort earliest-first, take the first. `saving_session_available` now means "an upcoming session exists" as originally intended.
29
+ - **Octoplus "Enrolled" and "Loyalty points user" stuck at "unavailable"** — both binary sensors were published with `entity_category: config`, which makes read-only sensor state stick at "unavailable" on some HA installs. Removed — same fix as the v1.3.0 tariff-sensor cleanup. Entity IDs are unchanged; not a breaking change.
30
+ - **Example dashboard — Wheel of Fortune cards showed "Entity not found"** — `examples/ha-dashboard.yaml` referenced `..._wheel_of_fortune_*_spins`, but the entities are named "WoF …" so HA generates `..._wof_*_spins`. Corrected.
31
+ - **Example dashboard — Home Mini gauge showed "Entity is non-numeric"** on accounts with no Home Mini — the gauge is now wrapped in a conditional card that hides until the entity reports a value.
32
+
33
+ ### Added
34
+ - `saving_session_window_active` (binary sensor) — true when an upcoming session window is currently happening, regardless of whether you joined.
35
+ - `saving_session_active` (binary sensor) — true only when you have joined the current session AND we are inside its window. Use this to drive automations that should only run when there is a payoff.
36
+
37
+ ### Changed (HA-side breaking)
38
+ - `saving_session_joined` now publishes as `binary_sensor` instead of `sensor` — fixes the "False" display anomaly caused by HA's sensor domain rejecting raw booleans. **Update automations and dashboards referencing `sensor.saving_session_joined` to use `binary_sensor.saving_session_joined`.** Payload field name (`msg.payload.saving_session_joined`) is unchanged. Mirror of the v1.3.0 `octoplus_enrolled` migration. The plugin publishes an empty config to the old `sensor/.../config` topic on startup to clean the orphan from HA.
39
+
8
40
  ## [1.3.2] — 2026-05-14
9
41
 
10
42
  Defensive hardening pass following the v1.3.1 hotfix audit. No user-facing behaviour change against the current live Kraken API — every affected field already arrives as a JSON number today. The fix forecloses the same latent crash class (`TypeError: ...toFixed is not a function`) if Kraken ever serialises these scalars as strings, matching how `energyAddedKwh` is already returned.
@@ -290,11 +290,15 @@ sections:
290
290
  entities:
291
291
  - entity: binary_sensor.octopus_intelligent_octopus_saving_session_available
292
292
  name: Next session available
293
+ - entity: binary_sensor.octopus_intelligent_octopus_saving_session_window_active
294
+ name: Session window active
295
+ - entity: binary_sensor.octopus_intelligent_octopus_saving_session_active
296
+ name: Session active (joined)
293
297
  - entity: sensor.octopus_intelligent_octopus_saving_session_start
294
298
  name: Next session — starts
295
299
  - entity: sensor.octopus_intelligent_octopus_saving_session_end
296
300
  name: Next session — ends
297
- - entity: sensor.octopus_intelligent_octopus_saving_session_joined
301
+ - entity: binary_sensor.octopus_intelligent_octopus_saving_session_joined
298
302
  name: Joined
299
303
 
300
304
  - type: grid
@@ -317,23 +321,35 @@ sections:
317
321
  - type: glance
318
322
  title: Wheel of Fortune
319
323
  entities:
320
- - entity: sensor.octopus_intelligent_octopus_wheel_of_fortune_electricity_spins
324
+ - entity: sensor.octopus_intelligent_octopus_wof_electricity_spins
321
325
  name: Elec spins
322
- - entity: sensor.octopus_intelligent_octopus_wheel_of_fortune_gas_spins
326
+ - entity: sensor.octopus_intelligent_octopus_wof_gas_spins
323
327
  name: Gas spins
324
328
 
325
329
  - type: grid
326
330
  cards:
327
- - type: gauge
328
- entity: sensor.octopus_intelligent_octopus_home_mini_demand
329
- name: Home Mini — live demand
330
- unit: kW
331
- min: 0
332
- max: 10
333
- severity:
334
- green: 0
335
- yellow: 3
336
- red: 6
331
+ # Conditional wrapper: the gauge card errors with "Entity is non-numeric"
332
+ # on accounts without a Home Mini (mini_demand_kw is null). Hide it until
333
+ # the entity reports a real value.
334
+ - type: conditional
335
+ conditions:
336
+ - condition: state
337
+ entity: sensor.octopus_intelligent_octopus_home_mini_demand
338
+ state_not: unknown
339
+ - condition: state
340
+ entity: sensor.octopus_intelligent_octopus_home_mini_demand
341
+ state_not: unavailable
342
+ card:
343
+ type: gauge
344
+ entity: sensor.octopus_intelligent_octopus_home_mini_demand
345
+ name: Home Mini — live demand
346
+ unit: kW
347
+ min: 0
348
+ max: 10
349
+ severity:
350
+ green: 0
351
+ yellow: 3
352
+ red: 6
337
353
 
338
354
  - type: grid
339
355
  cards:
@@ -26,25 +26,39 @@ function buildQuery(account) {
26
26
  }
27
27
 
28
28
  function parseResponse(data) {
29
+ const now = new Date();
29
30
  const ss = data.savingSessions || {};
30
31
  const acct = ss.account || {};
31
32
  const events = ss.events || [];
32
- const nextEvent = events[0] || null;
33
+
34
+ // Filter to events not yet ended; sort earliest-first; take the first
35
+ const upcoming = events
36
+ .filter(e => new Date(e.endAt) > now)
37
+ .sort((a, b) => new Date(a.startAt) - new Date(b.startAt));
38
+ const next = upcoming[0] || null;
39
+
33
40
  const joinedIds = (acct.joinedEvents || []).map(e => e.eventId);
34
- const isJoined = nextEvent ? joinedIds.includes(nextEvent.id) : false;
41
+ const isJoined = next ? joinedIds.includes(next.id) : false;
42
+
43
+ const inWindow = next
44
+ && new Date(next.startAt) <= now
45
+ && new Date(next.endAt) > now;
35
46
 
36
47
  return {
37
- saving_session_available: events.length > 0,
38
- saving_session_start: nextEvent ? nextEvent.startAt : null,
39
- saving_session_end: nextEvent ? nextEvent.endAt : null,
48
+ saving_session_available: next !== null,
49
+ saving_session_start: next ? next.startAt : null,
50
+ saving_session_end: next ? next.endAt : null,
40
51
  saving_session_joined: isJoined,
52
+ saving_session_window_active: !!inWindow,
53
+ saving_session_active: !!(inWindow && isJoined),
41
54
  saving_sessions_error: null
42
55
  };
43
56
  }
44
57
 
45
58
  const defaultData = {
46
59
  saving_session_available: null, saving_session_start: null, saving_session_end: null,
47
- saving_session_joined: null, saving_sessions_error: null
60
+ saving_session_joined: null, saving_session_window_active: null, saving_session_active: null,
61
+ saving_sessions_error: null
48
62
  };
49
63
 
50
64
  module.exports = { buildQuery, parseResponse, defaultData };
package/lib/payload.js CHANGED
@@ -59,7 +59,8 @@ function buildDefaultPayload(state) {
59
59
  wheel_of_fortune_gas_used: null, wheel_of_fortune_error: null,
60
60
  mini_demand_kw: null, mini_consumption_delta_kwh: null, mini_read_at: null, home_mini_error: null,
61
61
  saving_session_available: null, saving_session_start: null, saving_session_end: null,
62
- saving_session_joined: null, saving_session_points: null, saving_sessions_error: null,
62
+ saving_session_joined: null, saving_session_window_active: null, saving_session_active: null,
63
+ saving_session_points: null, saving_sessions_error: null,
63
64
  free_electricity_active: null, free_electricity_available: null,
64
65
  free_electricity_start: null, free_electricity_end: null, free_electricity_error: null,
65
66
  intelligent_error: null,
@@ -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
- onTick();
22
- handle = setInterval(onTick, 1000);
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 };
@@ -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');
@@ -190,7 +191,6 @@ module.exports = function (RED) {
190
191
  { id: 'home_mini_error', name: 'Home Mini Error', icon: 'mdi:alert-circle', val: 'home_mini_error', category: 'diagnostic' },
191
192
 
192
193
  // --- Saving Sessions (main) ---
193
- { id: 'saving_session_joined', name: 'Saving Session Joined', icon: 'mdi:lightning-bolt-circle', val: 'saving_session_joined' },
194
194
  { id: 'saving_session_points', name: 'Octopus Points', icon: 'mdi:star', val: 'saving_session_points' },
195
195
  // --- Saving Sessions (config) ---
196
196
  { id: 'saving_session_start', name: 'Saving Session Start', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'saving_session_start' },
@@ -327,6 +327,51 @@ module.exports = function (RED) {
327
327
  };
328
328
  node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_available/config`, JSON.stringify(savingSessionBinarySensor), { retain: true });
329
329
 
330
+ // G2a. Saving Session Window Active Binary Sensor (v1.3.3)
331
+ const savingSessionWindowActiveSensor = {
332
+ name: "Octopus Saving Session Window Active",
333
+ unique_id: `${uniqueIdPrefix}_saving_session_window_active`,
334
+ state_topic: stateTopic,
335
+ value_template: "{{ value_json.saving_session_window_active }}",
336
+ payload_on: "True",
337
+ payload_off: "False",
338
+ icon: "mdi:clock-check-outline",
339
+ device: device
340
+ };
341
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_window_active/config`, JSON.stringify(savingSessionWindowActiveSensor), { retain: true });
342
+
343
+ // G2b. Saving Session Active Binary Sensor (v1.3.3) — joined AND in window
344
+ const savingSessionActiveSensor = {
345
+ name: "Octopus Saving Session Active",
346
+ unique_id: `${uniqueIdPrefix}_saving_session_active`,
347
+ state_topic: stateTopic,
348
+ value_template: "{{ value_json.saving_session_active }}",
349
+ payload_on: "True",
350
+ payload_off: "False",
351
+ icon: "mdi:home-export-outline",
352
+ device: device
353
+ };
354
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_active/config`, JSON.stringify(savingSessionActiveSensor), { retain: true });
355
+
356
+ // G2c. v1.3.3 migration: delete the deprecated sensor.saving_session_joined
357
+ // entity. HA's sensor domain doesn't render booleans cleanly. Empty
358
+ // payload on the discovery topic with retain tells HA the entity no
359
+ // longer exists. Safe to keep across releases.
360
+ node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_saving_session_joined/config`, "", { retain: true });
361
+
362
+ // G2d. Saving Session Joined Binary Sensor (v1.3.3 migration)
363
+ const savingSessionJoinedSensor = {
364
+ name: "Octopus Saving Session Joined",
365
+ unique_id: `${uniqueIdPrefix}_saving_session_joined`,
366
+ state_topic: stateTopic,
367
+ value_template: "{{ value_json.saving_session_joined }}",
368
+ payload_on: "True",
369
+ payload_off: "False",
370
+ icon: "mdi:account-check",
371
+ device: device
372
+ };
373
+ node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_joined/config`, JSON.stringify(savingSessionJoinedSensor), { retain: true });
374
+
330
375
  // G3. Free Electricity Active Binary Sensor
331
376
  const freeElectricityActiveSensor = {
332
377
  name: "Octopus Free Electricity Active",
@@ -356,7 +401,9 @@ module.exports = function (RED) {
356
401
  // G5. Octoplus Enrolled Binary Sensor
357
402
  // Published as binary_sensor (not sensor) because the value is a boolean —
358
403
  // HA's sensor domain rejects booleans without a device_class, leaving the
359
- // entity unregistered.
404
+ // entity unregistered. No entity_category: 'config' on a read-only sensor
405
+ // makes its state stick at "unavailable" on some HA installs (same fix as
406
+ // the v1.3.0 tariff-sensor cleanup — see CHANGELOG).
360
407
  const octoplusEnrolledBinarySensor = {
361
408
  name: "Octopus Octoplus Enrolled",
362
409
  unique_id: `${uniqueIdPrefix}_octoplus_enrolled`,
@@ -365,12 +412,12 @@ module.exports = function (RED) {
365
412
  payload_on: "True",
366
413
  payload_off: "False",
367
414
  icon: "mdi:star-circle",
368
- entity_category: "config",
369
415
  device: device
370
416
  };
371
417
  node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_enrolled/config`, JSON.stringify(octoplusEnrolledBinarySensor), { retain: true });
372
418
 
373
419
  // G6. Octoplus Loyalty Points (boolean) Binary Sensor
420
+ // No entity_category — see G5.
374
421
  const octoplusLoyaltyBinarySensor = {
375
422
  name: "Octopus Octoplus Loyalty Points",
376
423
  unique_id: `${uniqueIdPrefix}_octoplus_loyalty_points_user`,
@@ -379,7 +426,6 @@ module.exports = function (RED) {
379
426
  payload_on: "True",
380
427
  payload_off: "False",
381
428
  icon: "mdi:star",
382
- entity_category: "config",
383
429
  device: device
384
430
  };
385
431
  node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_loyalty_points_user/config`, JSON.stringify(octoplusLoyaltyBinarySensor), { retain: true });
@@ -458,6 +504,7 @@ module.exports = function (RED) {
458
504
  let retryTimeouts = []; // Track pending retry timeouts
459
505
  let expectedLimit = null;
460
506
  let expectedTime = null;
507
+ let validationMode = false;
461
508
 
462
509
  // Pending vs Confirmed state
463
510
  let pendingLimit = 80;
@@ -481,7 +528,6 @@ module.exports = function (RED) {
481
528
 
482
529
  // Polling metrics
483
530
  let nextPollTime = null; // ISO timestamp of next scheduled poll
484
- let pollIntervalHandle = null; // Reference to setInterval handle
485
531
  const metrics = createApiMetrics();
486
532
 
487
533
  // API Complexity Tracking
@@ -502,9 +548,25 @@ module.exports = function (RED) {
502
548
  // V2 category registry — populated after discovery
503
549
  let categories = [];
504
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
+
505
557
  async function initCategories(discovered) {
506
558
  categories = [];
507
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
+
508
570
  const electricityEnabled = config.electricityEnabled !== false;
509
571
  const gasEnabled = config.gasEnabled !== false;
510
572
 
@@ -517,7 +579,12 @@ module.exports = function (RED) {
517
579
  intervalMs: ratesMs,
518
580
  lastPolled: 0,
519
581
  queryFn: () => electricityCategory.buildRatesQuery(account),
520
- 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
+ ),
521
588
  });
522
589
  categories.push({
523
590
  id: 'electricity_consumption',
@@ -525,7 +592,12 @@ module.exports = function (RED) {
525
592
  intervalMs: consumptionMs,
526
593
  lastPolled: 0,
527
594
  queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
528
- 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
+ ),
529
601
  });
530
602
  }
531
603
 
@@ -538,7 +610,12 @@ module.exports = function (RED) {
538
610
  intervalMs: ratesMs,
539
611
  lastPolled: 0,
540
612
  queryFn: () => gasCategory.buildRatesQuery(account),
541
- 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
+ ),
542
619
  });
543
620
  categories.push({
544
621
  id: 'gas_consumption',
@@ -546,7 +623,12 @@ module.exports = function (RED) {
546
623
  intervalMs: consumptionMs,
547
624
  lastPolled: 0,
548
625
  queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
549
- 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
+ ),
550
632
  });
551
633
  }
552
634
 
@@ -556,7 +638,12 @@ module.exports = function (RED) {
556
638
  intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
557
639
  lastPolled: 0,
558
640
  queryFn: () => wheelOfFortuneCategory.buildQuery(account),
559
- 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
+ ),
560
647
  });
561
648
  if (discovered.smartMeterDeviceId) {
562
649
  categories.push({
@@ -565,7 +652,12 @@ module.exports = function (RED) {
565
652
  intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
566
653
  lastPolled: 0,
567
654
  queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
568
- 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
+ ),
569
661
  });
570
662
  }
571
663
  categories.push({
@@ -574,7 +666,12 @@ module.exports = function (RED) {
574
666
  intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
575
667
  lastPolled: 0,
576
668
  queryFn: () => savingSessionsCategory.buildQuery(account),
577
- 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
+ ),
578
675
  });
579
676
 
580
677
  if (discovered.hasIntelligent) {
@@ -584,18 +681,13 @@ module.exports = function (RED) {
584
681
  intervalMs: 60 * 60 * 1000,
585
682
  lastPolled: 0,
586
683
  queryFn: () => completedDispatchesCategory.buildQuery(account),
587
- 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
+ ),
588
690
  });
589
- if (discovered.deviceId) {
590
- categories.push({
591
- id: 'flex_planned_dispatches',
592
- enabled: true,
593
- intervalMs: (config.refreshInterval || 5) * 60 * 1000,
594
- lastPolled: 0,
595
- queryFn: () => flexPlannedDispatchesCategory.buildQuery(discovered.deviceId),
596
- parseFn: d => flexPlannedDispatchesCategory.parseResponse(d)
597
- });
598
- }
599
691
  }
600
692
 
601
693
  if (discovered.hasElectricity && discovered.electricityMpan) {
@@ -605,7 +697,12 @@ module.exports = function (RED) {
605
697
  intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
606
698
  lastPolled: 0,
607
699
  queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
608
- 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
+ ),
609
706
  });
610
707
  }
611
708
 
@@ -618,7 +715,12 @@ module.exports = function (RED) {
618
715
  intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
619
716
  lastPolled: 0,
620
717
  queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
621
- 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
+ ),
622
724
  });
623
725
  }
624
726
 
@@ -629,7 +731,12 @@ module.exports = function (RED) {
629
731
  intervalMs: 30 * 60 * 1000, // 30 minutes
630
732
  lastPolled: 0,
631
733
  queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
632
- 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
+ ),
633
740
  });
634
741
  }
635
742
 
@@ -639,7 +746,12 @@ module.exports = function (RED) {
639
746
  intervalMs: 60 * 60 * 1000,
640
747
  lastPolled: 0,
641
748
  queryFn: () => accountCategory.buildQuery(account),
642
- 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
+ ),
643
755
  });
644
756
 
645
757
  categories.push({
@@ -648,49 +760,50 @@ module.exports = function (RED) {
648
760
  intervalMs: 60 * 60 * 1000,
649
761
  lastPolled: 0,
650
762
  queryFn: () => octoplusCategory.buildQuery(account),
651
- 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
+ ),
652
769
  });
653
770
  }
654
771
 
655
772
  async function pollDueCategories() {
656
- const { isDue } = require('./lib/scheduler');
657
- const due = categories.filter(c => c.enabled && isDue(c));
658
- if (due.length === 0) return;
659
-
660
- let token;
661
- try {
662
- const response = await graphqlPost({
663
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
664
- variables: { input: { APIKey: apiKey } }
665
- });
666
- if (!response.data.data || !response.data.data.obtainKrakenToken) {
667
- throw new Error('Auth response missing token');
668
- }
669
- token = response.data.data.obtainKrakenToken.token;
670
- } catch (e) {
671
- node.warn(`V2 category poll: auth failed: ${e.message}`);
672
- 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 });
673
782
  }
674
-
675
- for (const cat of due) {
676
- try {
677
- const { query, variables, hostname } = cat.queryFn();
678
- const response = await graphqlPost({ query, variables }, token, hostname);
679
- if (response.data.errors) throw new Error(JSON.stringify(response.data.errors));
680
- if (!response.data.data) throw new Error('Response missing data');
681
- const parsed = cat.parseFn(response.data.data);
682
- lastKnownState = mergePayload(lastKnownState, parsed);
683
- cat.lastPolled = Date.now();
684
- } catch (e) {
685
- cat.enabled = false;
686
- 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}` });
687
789
  }
688
790
  }
791
+ }
689
792
 
690
- if (enableMqtt && node.broker && node.broker.client) {
691
- node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
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));
692
800
  }
693
- node.send({ payload: lastKnownState });
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;
694
807
  }
695
808
 
696
809
  async function setPreferences(newLimit, newTime) {
@@ -777,6 +890,7 @@ module.exports = function (RED) {
777
890
  // C. Start exponential backoff validation
778
891
  expectedLimit = limit;
779
892
  expectedTime = time;
893
+ validationMode = true;
780
894
  node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
781
895
 
782
896
  // Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
@@ -791,6 +905,7 @@ module.exports = function (RED) {
791
905
  node.status({ fill: "red", shape: "ring", text: "Update Failed" });
792
906
  expectedLimit = null;
793
907
  expectedTime = null;
908
+ validationMode = false;
794
909
  }
795
910
  }
796
911
 
@@ -800,6 +915,7 @@ module.exports = function (RED) {
800
915
  node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
801
916
  expectedLimit = null;
802
917
  expectedTime = null;
918
+ validationMode = false;
803
919
  return;
804
920
  }
805
921
 
@@ -812,28 +928,39 @@ module.exports = function (RED) {
812
928
 
813
929
  async function fetchDataWithValidation(intervals, currentIndex) {
814
930
  try {
815
- const result = await fetchData(true); // Pass flag to indicate validation mode
816
-
817
- // Check if the data matches our expected values
818
- if (result && result.validated) {
819
- // Success! Changes confirmed
820
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${result.confirmedLimit}% @ ${result.confirmedTime}` });
821
- expectedLimit = null;
822
- expectedTime = null;
823
- // Clear remaining timeouts
824
- retryTimeouts.forEach(timeout => clearTimeout(timeout));
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));
825
943
  retryTimeouts = [];
826
- } else {
827
- // Not yet updated, schedule next retry
828
- const attempt = currentIndex + 1;
829
- const totalAttempts = intervals.length;
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) {
830
950
  node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
831
951
  scheduleRetries(intervals, currentIndex + 1);
952
+ } else {
953
+ validationMode = false;
954
+ node.status({ fill: "red", shape: "ring", text: "Validation timed out" });
832
955
  }
833
956
  } catch (error) {
834
- // Error during fetch, schedule next retry
835
957
  node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
836
- scheduleRetries(intervals, currentIndex + 1);
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
+ }
837
964
  }
838
965
  }
839
966
 
@@ -961,302 +1088,63 @@ module.exports = function (RED) {
961
1088
  smartChargingRetryTimeouts.push(timeout);
962
1089
  }
963
1090
 
964
- // 6. Logic: Fetch Data (Read)
965
- async function fetchData(validationMode = false) {
966
- // Estimated complexity per poll:
967
- // - Auth mutation: ~100 complexity
968
- // - Data query (devices + flexPlannedDispatches — two sequential calls): ~400 complexity
969
- // - Total: ~300 complexity per poll
970
- const ESTIMATED_POLL_COMPLEXITY = 300;
971
-
972
- // Debug object to track API calls
973
- const debugInfo = {
974
- timestamp: new Date().toISOString(),
975
- step: null,
976
- success: false,
977
- error: null,
978
- apiCalls: [],
979
- validationMode: validationMode
980
- };
981
-
982
- if (!apiKey || !account) {
983
- debugInfo.error = "Missing configuration: apiKey or account number not provided";
984
- debugInfo.step = "validation";
985
- node.status({ fill: "red", shape: "ring", text: "Config Missing" });
986
- node.send({
987
- payload: getDefaultPayload(),
988
- debug: debugInfo
989
- });
990
- return { validated: false };
991
- }
992
-
993
- try {
994
- // STEP 1: Get Token
995
- debugInfo.step = "authentication";
996
- node.status({ fill: "yellow", shape: "ring", text: "Authenticating..." });
997
-
998
- const authRequest = {
999
- url: "https://api.octopus.energy/v1/graphql/",
1000
- query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1001
- variables: { input: { APIKey: apiKey } }
1002
- };
1003
-
1004
- const authResponse = await graphqlPost({
1005
- query: authRequest.query,
1006
- variables: authRequest.variables
1007
- });
1008
-
1009
- debugInfo.apiCalls.push({
1010
- step: 1,
1011
- name: "authentication",
1012
- url: authRequest.url,
1013
- statusCode: authResponse.status,
1014
- hasErrors: !!(authResponse.data.errors),
1015
- errors: authResponse.data.errors || null
1016
- });
1017
-
1018
- // Validate auth response
1019
- if (authResponse.data.errors) {
1020
- throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1021
- }
1022
- if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1023
- throw new Error(`Auth response missing token data. Response: ${JSON.stringify(authResponse.data)}`);
1024
- }
1025
-
1026
- const token = authResponse.data.data.obtainKrakenToken.token;
1027
- debugInfo.apiCalls[0].tokenObtained = !!token;
1028
- debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
1029
-
1030
- // STEP 2a: Fetch devices (preferences + device ID)
1031
- debugInfo.step = "fetching_devices";
1032
- node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
1033
-
1034
- const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
1035
- const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
1036
-
1037
- debugInfo.apiCalls.push({
1038
- step: 2,
1039
- name: "devices_query",
1040
- url: "https://api.octopus.energy/v1/graphql/",
1041
- accountNumber: account,
1042
- statusCode: devicesResponse.status,
1043
- hasErrors: !!(devicesResponse.data.errors),
1044
- errors: devicesResponse.data.errors || null,
1045
- hasData: !!(devicesResponse.data.data),
1046
- responseHeaders: devicesResponse.headers || {}
1047
- });
1048
-
1049
- if (devicesResponse.data.errors) {
1050
- throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
1051
- }
1052
- if (!devicesResponse.data.data) {
1053
- throw new Error(`Devices response missing data. Response: ${JSON.stringify(devicesResponse.data)}`);
1054
- }
1055
-
1056
- const devicesData = devicesResponse.data.data;
1057
- const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
1058
- if (!evDevice) {
1059
- throw new Error('No ELECTRIC_VEHICLES device found on account');
1060
- }
1061
- krakenflexDeviceId = evDevice.id;
1062
-
1063
- // STEP 2b: Fetch planned dispatches using device ID
1064
- debugInfo.step = "fetching_dispatches";
1065
- const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
1066
- const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
1067
-
1068
- debugInfo.apiCalls.push({
1069
- step: 3,
1070
- name: "dispatches_query",
1071
- url: "https://api.octopus.energy/v1/graphql/",
1072
- deviceId: evDevice.id,
1073
- statusCode: dispatchResponse.status,
1074
- hasErrors: !!(dispatchResponse.data.errors),
1075
- errors: dispatchResponse.data.errors || null,
1076
- hasData: !!(dispatchResponse.data.data),
1077
- responseHeaders: dispatchResponse.headers || {}
1078
- });
1079
-
1080
- if (dispatchResponse.data.errors) {
1081
- throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
1082
- }
1083
- if (!dispatchResponse.data.data) {
1084
- throw new Error(`Dispatches response missing data. Response: ${JSON.stringify(dispatchResponse.data)}`);
1085
- }
1086
-
1087
- // STEP 3: Extract and Process
1088
- debugInfo.step = "processing";
1089
- const data = {
1090
- devices: devicesData.devices,
1091
- flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || []
1092
- };
1093
- const slots = data.flexPlannedDispatches;
1094
-
1095
- // Check for GraphQL extensions on the dispatches response
1096
- let actualComplexity = null;
1097
- if (dispatchResponse.data.extensions) {
1098
- debugInfo.apiCalls[2].extensions = dispatchResponse.data.extensions;
1099
- actualComplexity = dispatchResponse.data.extensions.complexity ||
1100
- dispatchResponse.data.extensions.cost ||
1101
- null;
1102
- }
1103
-
1104
- // Record poll with estimated or actual complexity
1105
- metrics.recordPoll(actualComplexity || ESTIMATED_POLL_COMPLEXITY);
1106
-
1107
- debugInfo.apiCalls[2].slotsFound = slots.length;
1108
- debugInfo.apiCalls[2].slotDetails = slots.map(s => ({
1109
- start: s.start,
1110
- end: s.end,
1111
- kwh: s.energyAddedKwh,
1112
- type: s.type
1113
- }));
1114
-
1115
- // Parse response via intelligent category module
1116
- const appliedTz = resolveTimezone(node);
1117
- const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch(e) { return 'UTC'; } })();
1118
- const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
1119
- const { _activeSlots, ...catPublic } = catResult;
1120
-
1121
- // Update Confirmed State (from catResult)
1122
- confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
1123
- confirmedTime = catResult.confirmed_time || confirmedTime;
1124
-
1125
- // On successful fetch, sync pending to confirmed if not in validation mode
1126
- if (!validationMode) {
1127
- pendingLimit = confirmedLimit;
1128
- pendingTime = confirmedTime;
1129
- }
1130
-
1131
- debugInfo.apiCalls[1].activeAndFutureSlots = _activeSlots.length;
1132
- debugInfo.processingTime = new Date().toISOString();
1133
-
1134
- // Setup charging timers (always update charging state)
1135
- setupChargingTimers(_activeSlots);
1136
-
1137
- // Start reconciliation loop on first successful data fetch (only in non-validation mode)
1138
- if (!validationMode && !stateCheckInterval) {
1139
- startStateReconciliation();
1140
- }
1141
-
1142
- // Update next poll time after successful fetch
1143
- updateNextPollTime();
1144
-
1145
- // Get API metrics for inclusion in payload
1146
- const apiMetrics = metrics.getMetrics();
1147
-
1148
- // Build Payload — merge catResult into lastKnownState, then add orchestrator-owned fields
1149
- const statusPayload = Object.assign({}, lastKnownState, catPublic, {
1150
- // Orchestrator-owned state fields (not in intelligentCategory)
1151
- pending_limit: pendingLimit,
1152
- pending_time: pendingTime,
1153
- charging_now: chargingNow,
1154
- next_poll: nextPollTime,
1155
- next_poll_raw: nextPollTime,
1156
- refresh_available_at: getRefreshAvailableAt(),
1157
- api_requests_hour: apiMetrics.requests_last_hour,
1158
- api_complexity_hour: apiMetrics.complexity_last_hour,
1159
- api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
1160
- timezone_detected: serverTz,
1161
- timezone_applied: appliedTz,
1162
- smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
1163
- });
1164
-
1165
- // Success!
1166
- debugInfo.success = true;
1167
- debugInfo.step = "complete";
1168
-
1169
- // Check if we're validating a preference change
1170
- let isValidated = false;
1171
- if (validationMode && expectedLimit !== null && expectedTime !== null) {
1172
- // Check if the returned values match what we set
1173
- isValidated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
1174
- debugInfo.expectedLimit = expectedLimit;
1175
- debugInfo.expectedTime = expectedTime;
1176
- debugInfo.receivedLimit = confirmedLimit;
1177
- debugInfo.receivedTime = confirmedTime;
1178
- debugInfo.validated = isValidated;
1179
- }
1180
-
1181
- // Add API usage metrics to debug info (already fetched above)
1182
- debugInfo.api_usage = {
1183
- requests_last_hour: apiMetrics.requests_last_hour,
1184
- complexity_last_hour: apiMetrics.complexity_last_hour,
1185
- complexity_percent_used: apiMetrics.complexity_percent,
1186
- api_limit_hourly: 50000,
1187
- request_complexity: actualComplexity || ESTIMATED_POLL_COMPLEXITY,
1188
- complexity_source: actualComplexity ? "api" : "estimated"
1189
- };
1190
-
1191
- // Store this as the last known full state
1192
- lastKnownState = statusPayload;
1193
-
1194
- // ALWAYS publish data to prevent sensors becoming unavailable
1195
- node.send({
1196
- payload: statusPayload,
1197
- debug: debugInfo
1198
- });
1199
-
1200
- // Update last sent charging state to prevent duplicate messages
1201
- lastSentChargingState = chargingNow;
1202
-
1203
- if (enableMqtt && node.broker) {
1204
- node.broker.client.publish(stateTopic, JSON.stringify(statusPayload), { retain: true });
1205
- // Also publish charging_now state to binary sensor topic
1206
- const chargingPayload = chargingNow ? "ON" : "OFF";
1207
- node.broker.client.publish(`${stateTopic}/charging_now`, chargingPayload, { retain: true });
1208
- }
1209
-
1210
- // Update status (validation mode will override this in fetchDataWithValidation)
1211
- if (!validationMode) {
1212
- node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
1213
- }
1214
-
1215
- // Return validation result
1216
- return { validated: isValidated || !validationMode, confirmedLimit, confirmedTime };
1217
-
1218
- } catch (error) {
1219
- debugInfo.success = false;
1220
- debugInfo.error = {
1221
- message: error.message,
1222
- stack: error.stack,
1223
- response: error.response ? {
1224
- status: error.response.status,
1225
- statusText: error.response.statusText,
1226
- data: error.response.data
1227
- } : null
1228
- };
1229
-
1230
- // Log to Node-RED (only if not in validation mode to avoid spam)
1231
- if (!validationMode) {
1232
- node.error(`Octopus API Error at ${debugInfo.step}: ${error.message}`);
1233
- if (error.response) {
1234
- node.error(`Response: ${JSON.stringify(error.response.data)}`);
1235
- }
1236
-
1237
- // Update status
1238
- node.status({
1239
- fill: "red",
1240
- shape: "ring",
1241
- text: `Error: ${debugInfo.step}`
1242
- });
1243
-
1244
- // Send default payload with debug info
1245
- node.send({
1246
- payload: getDefaultPayload(),
1247
- debug: debugInfo
1248
- });
1249
- }
1250
-
1251
- // Return failure for validation
1252
- 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;
1253
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
+ });
1254
1146
  }
1255
1147
 
1256
- // Helper: Build default payload when errors occur — delegates to lib/payload.js
1257
- function getDefaultPayload() {
1258
- return buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
1259
- }
1260
1148
 
1261
1149
  // Helper: Fetch device ID and initial smart charging state (called once at startup)
1262
1150
  async function fetchDeviceId() {
@@ -1643,7 +1531,7 @@ module.exports = function (RED) {
1643
1531
  // Update timestamp so HA sees cooldown, but don't block the refresh
1644
1532
  lastManualRefresh = Date.now();
1645
1533
  node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1646
- fetchData();
1534
+ forceCategoryDue('intelligent');
1647
1535
  });
1648
1536
 
1649
1537
  // B. Handle MQTT Commands (Home Assistant)
@@ -1701,7 +1589,7 @@ module.exports = function (RED) {
1701
1589
 
1702
1590
  // Trigger the actual refresh
1703
1591
  node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
1704
- fetchData();
1592
+ forceCategoryDue('intelligent');
1705
1593
  });
1706
1594
 
1707
1595
  // Timezone select changed in Home Assistant
@@ -1721,44 +1609,45 @@ module.exports = function (RED) {
1721
1609
  else if (val === "OFF") setSmartCharging(false);
1722
1610
  });
1723
1611
 
1724
- setTimeout(announceControls, 2000);
1612
+ initTimeoutHandles.push(setTimeout(announceControls, 2000));
1725
1613
 
1726
1614
  // Republish persisted timezone to HA select on startup
1727
- setTimeout(() => {
1615
+ initTimeoutHandles.push(setTimeout(() => {
1728
1616
  try {
1729
1617
  const persistedTz = node.context().get('timezone');
1730
1618
  if (persistedTz && node.broker) {
1731
1619
  node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
1732
1620
  }
1733
1621
  } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
1734
- }, 2500);
1622
+ }, 2500));
1735
1623
 
1736
1624
  // Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
1737
- setTimeout(() => {
1625
+ initTimeoutHandles.push(setTimeout(() => {
1738
1626
  try {
1739
1627
  if (smartChargingSuspended !== null && node.broker && node.broker.client) {
1740
1628
  const stateVal = smartChargingSuspended ? "OFF" : "ON";
1741
1629
  node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
1742
1630
  }
1743
1631
  } catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
1744
- }, 3000);
1632
+ }, 3000));
1745
1633
  }
1746
1634
 
1747
1635
  // Init
1748
- pollIntervalHandle = setInterval(fetchData, refreshRate);
1749
- updateNextPollTime(); // Set initial next poll time
1750
- setTimeout(fetchData, 1000);
1751
- setTimeout(fetchDeviceId, 1500);
1636
+ initTimeoutHandles.push(setTimeout(fetchDeviceId, 1500));
1752
1637
 
1753
- // V2 category discovery and scheduler
1754
- setTimeout(async () => {
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 () => {
1755
1642
  try {
1756
1643
  const discovered = await discoverProducts(apiKey, account);
1644
+ if (nodeClosed) return;
1757
1645
  if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
1758
1646
  smartChargingSuspended = discovered.deviceSuspended;
1759
1647
  lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
1760
1648
  }
1761
1649
  await initCategories(discovered);
1650
+ if (nodeClosed) return;
1762
1651
  node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}`);
1763
1652
  const v2Scheduler = createScheduler(pollDueCategories);
1764
1653
  v2Scheduler.start();
@@ -1766,10 +1655,13 @@ module.exports = function (RED) {
1766
1655
  } catch (e) {
1767
1656
  node.warn(`V2 discovery failed: ${e.message}. New categories unavailable.`);
1768
1657
  }
1769
- }, 2000);
1658
+ }, 2000));
1770
1659
 
1771
1660
  node.on('close', () => {
1772
- clearInterval(pollIntervalHandle);
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 = [];
1773
1665
  // Clear any pending retry timeouts
1774
1666
  retryTimeouts.forEach(timeout => clearTimeout(timeout));
1775
1667
  retryTimeouts = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-octopus-intelligent",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "description": "Node-RED integration for Octopus Energy Intelligent Octopus Go with Home Assistant MQTT discovery",
5
5
  "main": "octopus-intelligent.js",
6
6
  "scripts": {