node-red-contrib-octopus-intelligent 1.1.1 → 1.2.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,23 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.2.0] - 2026-04-26
9
+
10
+ ### Added
11
+ - **Smart Charging Toggle** — suspend or unsuspend Octopus intelligent charging from Node-RED or Home Assistant
12
+ - `msg.payload = { set_smart_charging: true }` — enable (unsuspend)
13
+ - `msg.payload = { set_smart_charging: false }` — disable (suspend)
14
+ - **HA MQTT Switch** — "Smart Charging" switch entity in Home Assistant (auto-discovered)
15
+ - **`smart_charging` payload field** — `true` = active, `false` = suspended, `null` = unknown (startup fetch pending or failed)
16
+ - **Device ID startup fetch** — `krakenflexDeviceId` fetched once at startup via `registeredKrakenflexDevice` query; cached permanently
17
+
18
+ ### Technical
19
+ - Mirrors `setPreferences` pattern: auth → mutation → optimistic update → exponential backoff verification (15s/30s/60s/120s)
20
+ - Verification re-fetches `registeredKrakenflexDevice.suspended` to confirm state change
21
+ - Zero new npm dependencies
22
+
23
+ ---
24
+
8
25
  ## [1.1.1] - 2026-04-26
9
26
 
10
27
  ### Security
package/README.md CHANGED
@@ -77,6 +77,11 @@ If this project has helped you!
77
77
  - **Professional Layout** - Organized entity categories in device card
78
78
  - **Suggested Area** - Auto-suggests "Energy" area
79
79
 
80
+ ### ⚡ Smart Charging Control
81
+ - **Smart Charging Toggle** — suspend or resume Octopus intelligent charging from Node-RED or Home Assistant
82
+ - **HA MQTT Switch** — "Smart Charging" switch entity auto-discovered in Home Assistant
83
+ - **`smart_charging` field** — live state in every payload (`true` = active, `false` = suspended, `null` = unknown)
84
+
80
85
  ### 🌍 Timezone Support
81
86
  - **Locale Timestamps** (`*_locale` fields) — always in server auto-detected timezone
82
87
  - **Resolved Display Fields** — slot and window times in your configured timezone
@@ -125,12 +130,19 @@ This flow shows the complete MQTT setup:
125
130
 
126
131
  After enabling MQTT in the Node-RED node, Home Assistant automatically creates:
127
132
 
133
+ ### Home Assistant Controls Configuration
134
+
135
+ ![Home Assistant Controls Configuration](https://raw.githubusercontent.com/ASomerN/node-red-contrib-octopus-intelligent/master/images/examples/configuration.png)
136
+
137
+ The Controls section of the device card includes the **Timezone** select and the new **Smart Charging** toggle, letting you suspend or resume intelligent charging directly from Home Assistant.
138
+
128
139
  #### Controls (Top Section)
129
140
  - **Target Charge** - Number slider (50-100%) to set desired battery level
130
141
  - **Ready Time** - Dropdown selector (04:00-11:00) for when car needs to be ready
131
142
  - **Apply Changes** - Button to submit new settings (prevents API spam while adjusting)
132
143
  - **Refresh API** - Button to force manual refresh (30-second cooldown prevents spam)
133
144
  - **Timezone** — Select entity for choosing display timezone (15 IANA options, persists across restarts)
145
+ - **Smart Charging** — Switch to suspend or resume Octopus intelligent charging
134
146
 
135
147
  #### Sensors (Main Section)
136
148
  - **Confirmed Charge Limit** - Current API-validated charge limit
@@ -215,6 +227,7 @@ select.octopus_ready_time Ready by time (04:00-11:00)
215
227
  button.octopus_apply_changes Submit changes to API
216
228
  button.octopus_refresh_api Manual refresh (30s cooldown)
217
229
  select.octopus_timezone Display timezone (15 IANA options)
230
+ switch.octopus_smart_charging Enable/disable smart charging
218
231
  ```
219
232
 
220
233
  ### Main Sensors
@@ -324,6 +337,14 @@ msg.payload = { set_timezone: "Australia/Sydney" };
324
337
  return msg;
325
338
  ```
326
339
 
340
+ ### Toggle Smart Charging from Flow
341
+
342
+ ```javascript
343
+ msg.payload = { set_smart_charging: true }; // enable (unsuspend)
344
+ msg.payload = { set_smart_charging: false }; // disable (suspend)
345
+ return msg;
346
+ ```
347
+
327
348
  Valid values: any IANA timezone string (e.g. `Europe/London`, `UTC`, `America/New_York`).
328
349
 
329
350
  ### Output Format
@@ -349,6 +370,7 @@ Valid values: any IANA timezone string (e.g. `Europe/London`, `UTC`, `America/Ne
349
370
  "slot1_end": "2025-11-29 05:30:00+00:00",
350
371
  "timezone_detected": "Europe/London",
351
372
  "timezone_applied": "Europe/London",
373
+ "smart_charging": true,
352
374
  "next_start_locale": "2025-11-29 01:30:00+00:00",
353
375
  "slot1_start_locale": "2025-11-29 01:30:00+00:00",
354
376
  "slot1_end_locale": "2025-11-29 05:30:00+00:00",
@@ -535,10 +557,10 @@ Use at your own risk. The Octopus Energy name and logo are trademarks of Octopus
535
557
 
536
558
  See [CHANGELOG.md](CHANGELOG.md) for detailed version history and release notes.
537
559
 
538
- ### Latest Release: v1.1.1 (2026-04-26)
539
- - **Timezone Support** - Locale timestamps, HA timezone select entity, `set_timezone` command
540
- - **`*_locale` Sensors** - All slot/window times in server auto-detected timezone
541
- - **Configurable Display Timezone** - Override via node config, HA select, or flow command
560
+ ### Latest Release: v1.2.0 (2026-04-26)
561
+ - **Smart Charging Toggle** — suspend/resume Octopus intelligent charging from Node-RED or Home Assistant
562
+ - **HA MQTT Switch** — auto-discovered Smart Charging switch entity
563
+ - **`smart_charging` payload field** — live state in every message
542
564
 
543
565
  ### Previous Release: v1.0.5 (2025-12-31)
544
566
  - **Documentation Fix** - Corrected misleading "branded device cards" claim in README
@@ -54,6 +54,7 @@ module.exports = function (RED) {
54
54
  const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
55
55
  const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
56
56
  const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
57
+ const cmdTopicSmartCharging = `nodered_octopus/${account}/set_smart_charging`;
57
58
 
58
59
  // 2. Constants & Validation
59
60
  const TIME_OPTIONS = [
@@ -324,12 +325,30 @@ module.exports = function (RED) {
324
325
  { retain: true }
325
326
  );
326
327
 
328
+ // J. Smart Charging Switch
329
+ node.broker.client.publish(
330
+ `${mqttPrefix}/switch/${uniqueIdPrefix}_smart_charging/config`,
331
+ JSON.stringify({
332
+ name: "Smart Charging",
333
+ unique_id: `${uniqueIdPrefix}_smart_charging`,
334
+ command_topic: cmdTopicSmartCharging,
335
+ state_topic: `${stateTopic}/smart_charging`,
336
+ payload_on: "ON",
337
+ payload_off: "OFF",
338
+ icon: "mdi:lightning-bolt",
339
+ entity_category: "config",
340
+ device: device
341
+ }),
342
+ { retain: true }
343
+ );
344
+
327
345
  // Subscribe to Commands
328
346
  node.broker.client.subscribe(cmdTopicLimit);
329
347
  node.broker.client.subscribe(cmdTopicTime);
330
348
  node.broker.client.subscribe(cmdTopicSubmit);
331
349
  node.broker.client.subscribe(cmdTopicRefresh);
332
350
  node.broker.client.subscribe(cmdTopicTimezone);
351
+ node.broker.client.subscribe(cmdTopicSmartCharging);
333
352
  }
334
353
 
335
354
  // 5. Helper: Set Preferences (The Mutation)
@@ -369,6 +388,11 @@ module.exports = function (RED) {
369
388
  // - Mutation (auth + setPreferences): ~250
370
389
  // - Pre-validation (auth + plannedDispatches only): ~200
371
390
 
391
+ // Smart charging state (fetched once at startup)
392
+ let krakenflexDeviceId = null;
393
+ let smartChargingSuspended = null; // null=unknown, true=suspended(off), false=active(on)
394
+ let smartChargingRetryTimeouts = [];
395
+
372
396
  // Last known full state - prevents sensors going unknown when controls change
373
397
  let lastKnownState = buildDefaultPayload();
374
398
 
@@ -503,6 +527,123 @@ module.exports = function (RED) {
503
527
  }
504
528
  }
505
529
 
530
+ // Helper: Toggle smart charging on/off
531
+ async function setSmartCharging(enable) {
532
+ if (!krakenflexDeviceId) {
533
+ node.warn("Device ID not available — cannot toggle smart charging");
534
+ return;
535
+ }
536
+
537
+ // Cancel any pending verification retries
538
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
539
+ smartChargingRetryTimeouts = [];
540
+
541
+ const previousSuspended = smartChargingSuspended;
542
+
543
+ try {
544
+ node.status({ fill: "blue", shape: "dot", text: enable ? "Enabling smart charging..." : "Suspending smart charging..." });
545
+
546
+ const authResponse = await graphqlPost({
547
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
548
+ variables: { input: { APIKey: apiKey } }
549
+ });
550
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
551
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
552
+ }
553
+ const token = authResponse.data.data.obtainKrakenToken.token;
554
+
555
+ const action = enable ? "UNSUSPEND" : "SUSPEND";
556
+ const mutationResponse = await graphqlPost({
557
+ query: `mutation UpdateSmartControl($deviceId: ID!, $action: SmartControlAction!) { updateDeviceSmartControl(input: { deviceId: $deviceId, action: $action }) { id } }`,
558
+ variables: { deviceId: krakenflexDeviceId, action: action }
559
+ }, token);
560
+
561
+ if (mutationResponse.data.errors) {
562
+ throw new Error(`Smart charging mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
563
+ }
564
+
565
+ // Record mutation API usage (auth + mutation = ~250 complexity)
566
+ const ESTIMATED_MUTATION_COMPLEXITY = 250;
567
+ recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
568
+
569
+ // Optimistically update cached state
570
+ const expectedSuspended = !enable;
571
+ smartChargingSuspended = expectedSuspended;
572
+
573
+ // Publish new state to HA switch topic immediately
574
+ if (enableMqtt && node.broker && node.broker.client) {
575
+ node.broker.client.publish(`${stateTopic}/smart_charging`, enable ? "ON" : "OFF", { retain: true });
576
+ }
577
+
578
+ // Schedule verification: 15s / 30s / 60s / 120s
579
+ scheduleSmartChargingVerification(expectedSuspended, [15000, 30000, 60000, 120000], 0);
580
+
581
+ } catch (e) {
582
+ node.error(`Failed to toggle smart charging: ${e.message}`);
583
+ // Revert optimistic update to pre-mutation state
584
+ smartChargingSuspended = previousSuspended;
585
+ node.status({ fill: "red", shape: "ring", text: "Smart charging update failed" });
586
+ // Republish previous state so HA switch UI re-syncs
587
+ if (enableMqtt && node.broker && node.broker.client && previousSuspended !== null) {
588
+ node.broker.client.publish(
589
+ `${stateTopic}/smart_charging`,
590
+ previousSuspended ? "OFF" : "ON",
591
+ { retain: true }
592
+ );
593
+ }
594
+ }
595
+ }
596
+
597
+ function scheduleSmartChargingVerification(expectedSuspended, intervals, index) {
598
+ if (index >= intervals.length) {
599
+ node.warn("Smart charging state could not be confirmed after all retries");
600
+ node.status({ fill: "red", shape: "ring", text: "Smart charging: update unconfirmed" });
601
+ return;
602
+ }
603
+ const timeout = setTimeout(async () => {
604
+ try {
605
+ const authResponse = await graphqlPost({
606
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
607
+ variables: { input: { APIKey: apiKey } }
608
+ });
609
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
610
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
611
+ return;
612
+ }
613
+ const token = authResponse.data.data.obtainKrakenToken.token;
614
+
615
+ const deviceResponse = await graphqlPost({
616
+ query: `query registeredKrakenflexDevice($accountNumber: String!) { registeredKrakenflexDevice(accountNumber: $accountNumber) { krakenflexDeviceId suspended } }`,
617
+ variables: { accountNumber: account }
618
+ }, token);
619
+
620
+ if (deviceResponse.data.errors || !deviceResponse.data.data || !deviceResponse.data.data.registeredKrakenflexDevice) {
621
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
622
+ return;
623
+ }
624
+
625
+ // Record verification API usage (auth + device query = ~200 complexity)
626
+ const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
627
+ recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
628
+
629
+ const actualSuspended = deviceResponse.data.data.registeredKrakenflexDevice.suspended;
630
+ if (actualSuspended === expectedSuspended) {
631
+ // Confirmed — clear remaining retries
632
+ smartChargingSuspended = actualSuspended;
633
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
634
+ smartChargingRetryTimeouts = [];
635
+ node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
636
+ } else {
637
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
638
+ }
639
+ } catch (e) {
640
+ node.warn(`Smart charging verification attempt ${index + 1} failed: ${e.message}`);
641
+ scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
642
+ }
643
+ }, intervals[index]);
644
+ smartChargingRetryTimeouts.push(timeout);
645
+ }
646
+
506
647
  // 6. Logic: Fetch Data (Read)
507
648
  async function fetchData(validationMode = false) {
508
649
  // Estimated complexity per poll:
@@ -729,7 +870,8 @@ module.exports = function (RED) {
729
870
  slot3_start_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, serverTz) : null,
730
871
  slot3_end_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, serverTz) : null,
731
872
  window_start_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
732
- window_end_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, serverTz) : null
873
+ window_end_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, serverTz) : null,
874
+ smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
733
875
  };
734
876
 
735
877
  // Success!
@@ -869,10 +1011,43 @@ module.exports = function (RED) {
869
1011
  slot3_start_locale: null,
870
1012
  slot3_end_locale: null,
871
1013
  window_start_locale: null,
872
- window_end_locale: null
1014
+ window_end_locale: null,
1015
+ smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
873
1016
  };
874
1017
  }
875
1018
 
1019
+ // Helper: Fetch device ID and initial smart charging state (called once at startup)
1020
+ async function fetchDeviceId() {
1021
+ try {
1022
+ const authResponse = await graphqlPost({
1023
+ query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
1024
+ variables: { input: { APIKey: apiKey } }
1025
+ });
1026
+ if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
1027
+ throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
1028
+ }
1029
+ const token = authResponse.data.data.obtainKrakenToken.token;
1030
+
1031
+ const deviceResponse = await graphqlPost({
1032
+ query: `query registeredKrakenflexDevice($accountNumber: String!) { registeredKrakenflexDevice(accountNumber: $accountNumber) { krakenflexDeviceId suspended } }`,
1033
+ variables: { accountNumber: account }
1034
+ }, token);
1035
+
1036
+ if (deviceResponse.data.errors || !deviceResponse.data.data || !deviceResponse.data.data.registeredKrakenflexDevice) {
1037
+ throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
1038
+ }
1039
+
1040
+ const d = deviceResponse.data.data.registeredKrakenflexDevice;
1041
+ krakenflexDeviceId = d.krakenflexDeviceId;
1042
+ smartChargingSuspended = d.suspended;
1043
+ node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
1044
+ } catch (e) {
1045
+ node.warn(`Failed to fetch device ID at startup: ${e.message}. Smart charging toggle unavailable.`);
1046
+ krakenflexDeviceId = null;
1047
+ smartChargingSuspended = null;
1048
+ }
1049
+ }
1050
+
876
1051
  // 6a. Charging Now - Timer Management Functions
877
1052
 
878
1053
  // State reconciliation - checks every 10s if charging state matches reality
@@ -1231,6 +1406,14 @@ module.exports = function (RED) {
1231
1406
  }
1232
1407
  return;
1233
1408
  }
1409
+ if (msg.payload.set_smart_charging !== undefined) {
1410
+ const val = msg.payload.set_smart_charging;
1411
+ if (typeof val === 'boolean') {
1412
+ setSmartCharging(val);
1413
+ }
1414
+ // silently ignore non-boolean (consistent with other handlers)
1415
+ return;
1416
+ }
1234
1417
  }
1235
1418
 
1236
1419
  // Manual refresh request from Node-RED - NO rate limiting
@@ -1309,6 +1492,13 @@ module.exports = function (RED) {
1309
1492
  }
1310
1493
  });
1311
1494
 
1495
+ // Smart charging switch toggled in Home Assistant
1496
+ node.broker.subscribe(cmdTopicSmartCharging, 0, (topic, payload) => {
1497
+ const val = payload.toString().trim();
1498
+ if (val === "ON") setSmartCharging(true);
1499
+ else if (val === "OFF") setSmartCharging(false);
1500
+ });
1501
+
1312
1502
  setTimeout(announceControls, 2000);
1313
1503
 
1314
1504
  // Republish persisted timezone to HA select on startup
@@ -1320,17 +1510,31 @@ module.exports = function (RED) {
1320
1510
  }
1321
1511
  } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
1322
1512
  }, 2500);
1513
+
1514
+ // Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
1515
+ setTimeout(() => {
1516
+ try {
1517
+ if (smartChargingSuspended !== null && node.broker && node.broker.client) {
1518
+ const stateVal = smartChargingSuspended ? "OFF" : "ON";
1519
+ node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
1520
+ }
1521
+ } catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
1522
+ }, 3000);
1323
1523
  }
1324
1524
 
1325
1525
  // Init
1326
1526
  pollIntervalHandle = setInterval(fetchData, refreshRate);
1327
1527
  updateNextPollTime(); // Set initial next poll time
1328
1528
  setTimeout(fetchData, 1000);
1529
+ setTimeout(fetchDeviceId, 1500);
1329
1530
  node.on('close', () => {
1330
1531
  clearInterval(pollIntervalHandle);
1331
1532
  // Clear any pending retry timeouts
1332
1533
  retryTimeouts.forEach(timeout => clearTimeout(timeout));
1333
1534
  retryTimeouts = [];
1535
+ // Clear smart charging retry timeouts
1536
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1537
+ smartChargingRetryTimeouts = [];
1334
1538
  // Clear charging timers
1335
1539
  clearChargingTimers();
1336
1540
  // Clear cooldown expiry timer
@@ -1338,7 +1542,7 @@ module.exports = function (RED) {
1338
1542
  clearTimeout(cooldownExpiryTimer);
1339
1543
  cooldownExpiryTimer = null;
1340
1544
  }
1341
- if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone);
1545
+ if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging);
1342
1546
  });
1343
1547
  }
1344
1548
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-octopus-intelligent",
3
- "version": "1.1.1",
3
+ "version": "1.2.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": {