node-red-contrib-octopus-intelligent 1.1.1 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +37 -5
- package/octopus-intelligent.js +244 -12
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.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
|
+

|
|
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,7 +337,25 @@ msg.payload = { set_timezone: "Australia/Sydney" };
|
|
|
324
337
|
return msg;
|
|
325
338
|
```
|
|
326
339
|
|
|
327
|
-
|
|
340
|
+
### Toggle Smart Charging from Flow
|
|
341
|
+
|
|
342
|
+
Send a boolean to enable or disable Octopus intelligent charging:
|
|
343
|
+
|
|
344
|
+
```javascript
|
|
345
|
+
msg.payload = { set_smart_charging: true }; // enable (unsuspend)
|
|
346
|
+
msg.payload = { set_smart_charging: false }; // disable (suspend)
|
|
347
|
+
return msg;
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
Wire an **Inject node** with a JSON payload, or build this in a function node and connect it to the Octopus Intelligent node's input. Non-boolean values are silently ignored.
|
|
351
|
+
|
|
352
|
+
**Example: suspend charging when home battery is in use**
|
|
353
|
+
```
|
|
354
|
+
[Inject: suspend] → [Function: set_smart_charging=false] → [Octopus Intelligent]
|
|
355
|
+
[Inject: resume] → [Function: set_smart_charging=true] → [Octopus Intelligent]
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
The node fetches your device ID at startup — if it hasn't been fetched yet (first few seconds after deploy), the command will log a warning and be ignored. The current smart charging state is always available in `msg.payload.smart_charging` (`true` = active, `false` = suspended, `null` = startup pending).
|
|
328
359
|
|
|
329
360
|
### Output Format
|
|
330
361
|
|
|
@@ -349,6 +380,7 @@ Valid values: any IANA timezone string (e.g. `Europe/London`, `UTC`, `America/Ne
|
|
|
349
380
|
"slot1_end": "2025-11-29 05:30:00+00:00",
|
|
350
381
|
"timezone_detected": "Europe/London",
|
|
351
382
|
"timezone_applied": "Europe/London",
|
|
383
|
+
"smart_charging": true,
|
|
352
384
|
"next_start_locale": "2025-11-29 01:30:00+00:00",
|
|
353
385
|
"slot1_start_locale": "2025-11-29 01:30:00+00:00",
|
|
354
386
|
"slot1_end_locale": "2025-11-29 05:30:00+00:00",
|
|
@@ -535,10 +567,10 @@ Use at your own risk. The Octopus Energy name and logo are trademarks of Octopus
|
|
|
535
567
|
|
|
536
568
|
See [CHANGELOG.md](CHANGELOG.md) for detailed version history and release notes.
|
|
537
569
|
|
|
538
|
-
### Latest Release: v1.
|
|
539
|
-
- **
|
|
540
|
-
-
|
|
541
|
-
-
|
|
570
|
+
### Latest Release: v1.2.0 (2026-04-26)
|
|
571
|
+
- **Smart Charging Toggle** — suspend/resume Octopus intelligent charging from Node-RED or Home Assistant
|
|
572
|
+
- **HA MQTT Switch** — auto-discovered Smart Charging switch entity
|
|
573
|
+
- **`smart_charging` payload field** — live state in every message
|
|
542
574
|
|
|
543
575
|
### Previous Release: v1.0.5 (2025-12-31)
|
|
544
576
|
- **Documentation Fix** - Corrected misleading "branded device cards" claim in README
|
package/octopus-intelligent.js
CHANGED
|
@@ -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
|
|
|
@@ -412,19 +436,32 @@ module.exports = function (RED) {
|
|
|
412
436
|
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
413
437
|
|
|
414
438
|
// B. Send Mutation
|
|
439
|
+
if (!krakenflexDeviceId) {
|
|
440
|
+
throw new Error('Device ID not available — cannot set preferences');
|
|
441
|
+
}
|
|
442
|
+
|
|
415
443
|
const mutation = `
|
|
416
|
-
mutation setPreferences($input:
|
|
417
|
-
|
|
444
|
+
mutation setPreferences($input: SmartFlexDevicePreferencesInput!) {
|
|
445
|
+
setDevicePreferences(input: $input) { __typename }
|
|
418
446
|
}`;
|
|
419
447
|
|
|
448
|
+
const DAYS = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'];
|
|
449
|
+
function buildDevicePreferencesInput(deviceId, socLimit, readyTime) {
|
|
450
|
+
return {
|
|
451
|
+
deviceId,
|
|
452
|
+
mode: 'CHARGE',
|
|
453
|
+
unit: 'PERCENTAGE',
|
|
454
|
+
schedules: DAYS.map(dayOfWeek => ({
|
|
455
|
+
dayOfWeek,
|
|
456
|
+
time: readyTime + ':00',
|
|
457
|
+
min: 0,
|
|
458
|
+
max: socLimit
|
|
459
|
+
}))
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
420
463
|
const variables = {
|
|
421
|
-
input:
|
|
422
|
-
accountNumber: account,
|
|
423
|
-
weekdayTargetSoc: limit,
|
|
424
|
-
weekendTargetSoc: limit,
|
|
425
|
-
weekdayTargetTime: time,
|
|
426
|
-
weekendTargetTime: time
|
|
427
|
-
}
|
|
464
|
+
input: buildDevicePreferencesInput(krakenflexDeviceId, limit, time)
|
|
428
465
|
};
|
|
429
466
|
|
|
430
467
|
const mutationResponse = await graphqlPost({
|
|
@@ -503,6 +540,130 @@ module.exports = function (RED) {
|
|
|
503
540
|
}
|
|
504
541
|
}
|
|
505
542
|
|
|
543
|
+
// Helper: Toggle smart charging on/off
|
|
544
|
+
async function setSmartCharging(enable) {
|
|
545
|
+
if (!krakenflexDeviceId) {
|
|
546
|
+
node.warn("Device ID not available — cannot toggle smart charging");
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// Cancel any pending verification retries
|
|
551
|
+
smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
|
|
552
|
+
smartChargingRetryTimeouts = [];
|
|
553
|
+
|
|
554
|
+
const previousSuspended = smartChargingSuspended;
|
|
555
|
+
|
|
556
|
+
try {
|
|
557
|
+
node.status({ fill: "blue", shape: "dot", text: enable ? "Enabling smart charging..." : "Suspending smart charging..." });
|
|
558
|
+
|
|
559
|
+
const authResponse = await graphqlPost({
|
|
560
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
561
|
+
variables: { input: { APIKey: apiKey } }
|
|
562
|
+
});
|
|
563
|
+
if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
564
|
+
throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
|
|
565
|
+
}
|
|
566
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
567
|
+
|
|
568
|
+
const action = enable ? "UNSUSPEND" : "SUSPEND";
|
|
569
|
+
const mutationResponse = await graphqlPost({
|
|
570
|
+
query: `mutation UpdateSmartControl($deviceId: ID!, $action: SmartControlAction!) { updateDeviceSmartControl(input: { deviceId: $deviceId, action: $action }) { id } }`,
|
|
571
|
+
variables: { deviceId: krakenflexDeviceId, action: action }
|
|
572
|
+
}, token);
|
|
573
|
+
|
|
574
|
+
if (mutationResponse.data.errors) {
|
|
575
|
+
throw new Error(`Smart charging mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// Record mutation API usage (auth + mutation = ~250 complexity)
|
|
579
|
+
const ESTIMATED_MUTATION_COMPLEXITY = 250;
|
|
580
|
+
recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
581
|
+
|
|
582
|
+
// Optimistically update cached state
|
|
583
|
+
const expectedSuspended = !enable;
|
|
584
|
+
smartChargingSuspended = expectedSuspended;
|
|
585
|
+
|
|
586
|
+
// Publish new state to HA switch topic immediately
|
|
587
|
+
if (enableMqtt && node.broker && node.broker.client) {
|
|
588
|
+
node.broker.client.publish(`${stateTopic}/smart_charging`, enable ? "ON" : "OFF", { retain: true });
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// Schedule verification: 15s / 30s / 60s / 120s
|
|
592
|
+
scheduleSmartChargingVerification(expectedSuspended, [15000, 30000, 60000, 120000], 0);
|
|
593
|
+
|
|
594
|
+
} catch (e) {
|
|
595
|
+
node.error(`Failed to toggle smart charging: ${e.message}`);
|
|
596
|
+
// Revert optimistic update to pre-mutation state
|
|
597
|
+
smartChargingSuspended = previousSuspended;
|
|
598
|
+
node.status({ fill: "red", shape: "ring", text: "Smart charging update failed" });
|
|
599
|
+
// Republish previous state so HA switch UI re-syncs
|
|
600
|
+
if (enableMqtt && node.broker && node.broker.client && previousSuspended !== null) {
|
|
601
|
+
node.broker.client.publish(
|
|
602
|
+
`${stateTopic}/smart_charging`,
|
|
603
|
+
previousSuspended ? "OFF" : "ON",
|
|
604
|
+
{ retain: true }
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function scheduleSmartChargingVerification(expectedSuspended, intervals, index) {
|
|
611
|
+
if (index >= intervals.length) {
|
|
612
|
+
node.warn("Smart charging state could not be confirmed after all retries");
|
|
613
|
+
node.status({ fill: "red", shape: "ring", text: "Smart charging: update unconfirmed" });
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const timeout = setTimeout(async () => {
|
|
617
|
+
try {
|
|
618
|
+
const authResponse = await graphqlPost({
|
|
619
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
620
|
+
variables: { input: { APIKey: apiKey } }
|
|
621
|
+
});
|
|
622
|
+
if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
623
|
+
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
627
|
+
|
|
628
|
+
const deviceResponse = await graphqlPost({
|
|
629
|
+
query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
|
|
630
|
+
variables: { accountNumber: account }
|
|
631
|
+
}, token);
|
|
632
|
+
|
|
633
|
+
if (deviceResponse.data.errors || !deviceResponse.data.data) {
|
|
634
|
+
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const evDevice = (deviceResponse.data.data.devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES');
|
|
639
|
+
if (!evDevice) {
|
|
640
|
+
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// Record verification API usage (auth + device query = ~200 complexity)
|
|
645
|
+
const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
|
|
646
|
+
recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
|
|
647
|
+
|
|
648
|
+
const actualSuspended = evDevice.status.isSuspended;
|
|
649
|
+
if (actualSuspended === expectedSuspended) {
|
|
650
|
+
// Confirmed — clear remaining retries
|
|
651
|
+
smartChargingSuspended = actualSuspended;
|
|
652
|
+
smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
|
|
653
|
+
smartChargingRetryTimeouts = [];
|
|
654
|
+
node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
|
|
655
|
+
node.status({ fill: "green", shape: "dot", text: actualSuspended ? "Smart charging suspended" : "Smart charging enabled" });
|
|
656
|
+
} else {
|
|
657
|
+
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
658
|
+
}
|
|
659
|
+
} catch (e) {
|
|
660
|
+
node.warn(`Smart charging verification attempt ${index + 1} failed: ${e.message}`);
|
|
661
|
+
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
662
|
+
}
|
|
663
|
+
}, intervals[index]);
|
|
664
|
+
smartChargingRetryTimeouts.push(timeout);
|
|
665
|
+
}
|
|
666
|
+
|
|
506
667
|
// 6. Logic: Fetch Data (Read)
|
|
507
668
|
async function fetchData(validationMode = false) {
|
|
508
669
|
// Estimated complexity per poll:
|
|
@@ -729,7 +890,8 @@ module.exports = function (RED) {
|
|
|
729
890
|
slot3_start_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, serverTz) : null,
|
|
730
891
|
slot3_end_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, serverTz) : null,
|
|
731
892
|
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
|
|
893
|
+
window_end_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, serverTz) : null,
|
|
894
|
+
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
|
|
733
895
|
};
|
|
734
896
|
|
|
735
897
|
// Success!
|
|
@@ -869,10 +1031,51 @@ module.exports = function (RED) {
|
|
|
869
1031
|
slot3_start_locale: null,
|
|
870
1032
|
slot3_end_locale: null,
|
|
871
1033
|
window_start_locale: null,
|
|
872
|
-
window_end_locale: null
|
|
1034
|
+
window_end_locale: null,
|
|
1035
|
+
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
|
|
873
1036
|
};
|
|
874
1037
|
}
|
|
875
1038
|
|
|
1039
|
+
// Helper: Fetch device ID and initial smart charging state (called once at startup)
|
|
1040
|
+
async function fetchDeviceId() {
|
|
1041
|
+
try {
|
|
1042
|
+
const authResponse = await graphqlPost({
|
|
1043
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
1044
|
+
variables: { input: { APIKey: apiKey } }
|
|
1045
|
+
});
|
|
1046
|
+
if (authResponse.data.errors || !authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
1047
|
+
throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
|
|
1048
|
+
}
|
|
1049
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
1050
|
+
|
|
1051
|
+
const deviceResponse = await graphqlPost({
|
|
1052
|
+
query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
|
|
1053
|
+
variables: { accountNumber: account }
|
|
1054
|
+
}, token);
|
|
1055
|
+
|
|
1056
|
+
if (deviceResponse.data.errors || !deviceResponse.data.data) {
|
|
1057
|
+
throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
function extractEvDevice(devices) {
|
|
1061
|
+
return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
const evDevice = extractEvDevice(deviceResponse.data.data.devices);
|
|
1065
|
+
if (!evDevice) {
|
|
1066
|
+
throw new Error('No ELECTRIC_VEHICLES device found on account');
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
krakenflexDeviceId = evDevice.id;
|
|
1070
|
+
smartChargingSuspended = evDevice.status.isSuspended;
|
|
1071
|
+
node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
|
|
1072
|
+
} catch (e) {
|
|
1073
|
+
node.warn(`Failed to fetch device ID at startup: ${e.message}. Smart charging toggle unavailable.`);
|
|
1074
|
+
krakenflexDeviceId = null;
|
|
1075
|
+
smartChargingSuspended = null;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
|
|
876
1079
|
// 6a. Charging Now - Timer Management Functions
|
|
877
1080
|
|
|
878
1081
|
// State reconciliation - checks every 10s if charging state matches reality
|
|
@@ -1231,6 +1434,14 @@ module.exports = function (RED) {
|
|
|
1231
1434
|
}
|
|
1232
1435
|
return;
|
|
1233
1436
|
}
|
|
1437
|
+
if (msg.payload.set_smart_charging !== undefined) {
|
|
1438
|
+
const val = msg.payload.set_smart_charging;
|
|
1439
|
+
if (typeof val === 'boolean') {
|
|
1440
|
+
setSmartCharging(val);
|
|
1441
|
+
}
|
|
1442
|
+
// silently ignore non-boolean (consistent with other handlers)
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1234
1445
|
}
|
|
1235
1446
|
|
|
1236
1447
|
// Manual refresh request from Node-RED - NO rate limiting
|
|
@@ -1309,6 +1520,13 @@ module.exports = function (RED) {
|
|
|
1309
1520
|
}
|
|
1310
1521
|
});
|
|
1311
1522
|
|
|
1523
|
+
// Smart charging switch toggled in Home Assistant
|
|
1524
|
+
node.broker.subscribe(cmdTopicSmartCharging, 0, (topic, payload) => {
|
|
1525
|
+
const val = payload.toString().trim();
|
|
1526
|
+
if (val === "ON") setSmartCharging(true);
|
|
1527
|
+
else if (val === "OFF") setSmartCharging(false);
|
|
1528
|
+
});
|
|
1529
|
+
|
|
1312
1530
|
setTimeout(announceControls, 2000);
|
|
1313
1531
|
|
|
1314
1532
|
// Republish persisted timezone to HA select on startup
|
|
@@ -1320,17 +1538,31 @@ module.exports = function (RED) {
|
|
|
1320
1538
|
}
|
|
1321
1539
|
} catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
|
|
1322
1540
|
}, 2500);
|
|
1541
|
+
|
|
1542
|
+
// Republish smart charging state to HA switch on startup (after fetchDeviceId runs at 1500ms)
|
|
1543
|
+
setTimeout(() => {
|
|
1544
|
+
try {
|
|
1545
|
+
if (smartChargingSuspended !== null && node.broker && node.broker.client) {
|
|
1546
|
+
const stateVal = smartChargingSuspended ? "OFF" : "ON";
|
|
1547
|
+
node.broker.client.publish(`${stateTopic}/smart_charging`, stateVal, { retain: true });
|
|
1548
|
+
}
|
|
1549
|
+
} catch (e) { node.warn('Failed to republish smart charging state on startup: ' + e.message); }
|
|
1550
|
+
}, 3000);
|
|
1323
1551
|
}
|
|
1324
1552
|
|
|
1325
1553
|
// Init
|
|
1326
1554
|
pollIntervalHandle = setInterval(fetchData, refreshRate);
|
|
1327
1555
|
updateNextPollTime(); // Set initial next poll time
|
|
1328
1556
|
setTimeout(fetchData, 1000);
|
|
1557
|
+
setTimeout(fetchDeviceId, 1500);
|
|
1329
1558
|
node.on('close', () => {
|
|
1330
1559
|
clearInterval(pollIntervalHandle);
|
|
1331
1560
|
// Clear any pending retry timeouts
|
|
1332
1561
|
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
1333
1562
|
retryTimeouts = [];
|
|
1563
|
+
// Clear smart charging retry timeouts
|
|
1564
|
+
smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
|
|
1565
|
+
smartChargingRetryTimeouts = [];
|
|
1334
1566
|
// Clear charging timers
|
|
1335
1567
|
clearChargingTimers();
|
|
1336
1568
|
// Clear cooldown expiry timer
|
|
@@ -1338,7 +1570,7 @@ module.exports = function (RED) {
|
|
|
1338
1570
|
clearTimeout(cooldownExpiryTimer);
|
|
1339
1571
|
cooldownExpiryTimer = null;
|
|
1340
1572
|
}
|
|
1341
|
-
if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone);
|
|
1573
|
+
if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging);
|
|
1342
1574
|
});
|
|
1343
1575
|
}
|
|
1344
1576
|
|
package/package.json
CHANGED