node-red-contrib-octopus-intelligent 1.0.5 → 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.
@@ -1,4 +1,34 @@
1
- const axios = require("axios");
1
+ const https = require("https");
2
+
3
+ function graphqlPost(body, token) {
4
+ return new Promise((resolve, reject) => {
5
+ const payload = JSON.stringify(body);
6
+ const headers = {
7
+ "Content-Type": "application/json",
8
+ "Content-Length": Buffer.byteLength(payload)
9
+ };
10
+ if (token) headers["Authorization"] = token;
11
+ const req = https.request({
12
+ hostname: "api.octopus.energy",
13
+ path: "/v1/graphql/",
14
+ method: "POST",
15
+ headers
16
+ }, (res) => {
17
+ let raw = "";
18
+ res.on("data", chunk => raw += chunk);
19
+ res.on("end", () => {
20
+ try {
21
+ resolve({ data: JSON.parse(raw), status: res.statusCode, headers: res.headers });
22
+ } catch (e) {
23
+ reject(new Error("Failed to parse API response: " + e.message));
24
+ }
25
+ });
26
+ });
27
+ req.on("error", reject);
28
+ req.write(payload);
29
+ req.end();
30
+ });
31
+ }
2
32
 
3
33
  module.exports = function (RED) {
4
34
  function OctopusIntelligentNode(config) {
@@ -10,6 +40,7 @@ module.exports = function (RED) {
10
40
  const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
11
41
  const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
12
42
  const enableMqtt = config.enableMqtt;
43
+ node.timezoneOverride = config.timezoneOverride || "";
13
44
 
14
45
  // MQTT Topics
15
46
  this.broker = RED.nodes.getNode(config.broker);
@@ -22,6 +53,8 @@ module.exports = function (RED) {
22
53
  const cmdTopicTime = `nodered_octopus/${account}/set_time`;
23
54
  const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
24
55
  const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
56
+ const cmdTopicTimezone = `nodered_octopus/${account}/set_timezone`;
57
+ const cmdTopicSmartCharging = `nodered_octopus/${account}/set_smart_charging`;
25
58
 
26
59
  // 2. Constants & Validation
27
60
  const TIME_OPTIONS = [
@@ -70,9 +103,80 @@ module.exports = function (RED) {
70
103
  { id: "slot3_start_raw", name: "Slot 3 Start (Raw)", icon: "mdi:timer-outline", val: "slot3_start_raw" },
71
104
  { id: "slot3_end_raw", name: "Slot 3 End (Raw)", icon: "mdi:timer-outline", val: "slot3_end_raw" },
72
105
  { id: "window_start_raw", name: "Overall Window Start (Raw)", icon: "mdi:timer-play", val: "window_start_raw" },
73
- { id: "window_end_raw", name: "Overall Window End (Raw)", icon: "mdi:timer-stop", val: "window_end_raw" }
106
+ { id: "window_end_raw", name: "Overall Window End (Raw)", icon: "mdi:timer-stop", val: "window_end_raw" },
107
+ // v1.1.0: Locale timestamp sensors (plain string — already human-readable local time, no device_class)
108
+ { id: "next_charge_locale", name: "Next Charge Time (Locale)", icon: "mdi:timer", val: "next_start_locale" },
109
+ { id: "slot1_start_locale", name: "Slot 1 Start (Locale)", icon: "mdi:timer-outline", val: "slot1_start_locale" },
110
+ { id: "slot1_end_locale", name: "Slot 1 End (Locale)", icon: "mdi:timer-outline", val: "slot1_end_locale" },
111
+ { id: "slot2_start_locale", name: "Slot 2 Start (Locale)", icon: "mdi:timer-outline", val: "slot2_start_locale" },
112
+ { id: "slot2_end_locale", name: "Slot 2 End (Locale)", icon: "mdi:timer-outline", val: "slot2_end_locale" },
113
+ { id: "slot3_start_locale", name: "Slot 3 Start (Locale)", icon: "mdi:timer-outline", val: "slot3_start_locale" },
114
+ { id: "slot3_end_locale", name: "Slot 3 End (Locale)", icon: "mdi:timer-outline", val: "slot3_end_locale" },
115
+ { id: "window_start_locale", name: "Overall Window Start (Locale)", icon: "mdi:timer-play", val: "window_start_locale" },
116
+ { id: "window_end_locale", name: "Overall Window End (Locale)", icon: "mdi:timer-stop", val: "window_end_locale" },
117
+ // v1.1.0: Timezone diagnostic sensors
118
+ { id: "timezone_detected", name: "Timezone Detected", icon: "mdi:earth", val: "timezone_detected" },
119
+ { id: "timezone_applied", name: "Timezone Applied", icon: "mdi:earth-plus", val: "timezone_applied" }
74
120
  ];
75
121
 
122
+ // 3. Timezone Helpers
123
+ function convertToTimezone(dateStr, tz) {
124
+ if (!dateStr || typeof dateStr !== 'string') return dateStr;
125
+ try {
126
+ const date = new Date(dateStr.replace(' ', 'T'));
127
+ if (isNaN(date.getTime())) return dateStr;
128
+
129
+ const parts = new Intl.DateTimeFormat('en-CA', {
130
+ timeZone: tz,
131
+ year: 'numeric', month: '2-digit', day: '2-digit',
132
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
133
+ hour12: false, hourCycle: 'h23'
134
+ }).formatToParts(date);
135
+
136
+ const get = (type) => (parts.find(p => p.type === type) || {}).value || '00';
137
+ const y = get('year');
138
+ const mo = get('month');
139
+ const d = get('day');
140
+ const h = get('hour');
141
+ const mi = get('minute');
142
+ const s = get('second');
143
+
144
+ const localAsUtc = Date.UTC(
145
+ parseInt(y, 10), parseInt(mo, 10) - 1, parseInt(d, 10),
146
+ parseInt(h, 10), parseInt(mi, 10), parseInt(s, 10)
147
+ );
148
+ const offsetMins = Math.round((localAsUtc - date.getTime()) / 60000);
149
+ const sign = offsetMins >= 0 ? '+' : '-';
150
+ const absMin = Math.abs(offsetMins);
151
+ const offsetStr = `${sign}${String(Math.floor(absMin / 60)).padStart(2, '0')}:${String(absMin % 60).padStart(2, '0')}`;
152
+
153
+ return `${y}-${mo}-${d} ${h}:${mi}:${s}${offsetStr}`;
154
+ } catch (e) {
155
+ node.warn(`Invalid timezone: ${tz}, falling back to auto-detected`);
156
+ return dateStr;
157
+ }
158
+ }
159
+
160
+ function resolveTimezone(nd) {
161
+ try {
162
+ const persisted = nd.context().get('timezone');
163
+ if (persisted && typeof persisted === 'string' && persisted.trim().length > 0) {
164
+ return persisted.trim();
165
+ }
166
+ } catch (e) {}
167
+
168
+ const override = nd.timezoneOverride;
169
+ if (override && typeof override === 'string' && override.trim().length > 0) {
170
+ return override.trim();
171
+ }
172
+
173
+ try {
174
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
175
+ } catch (e) {
176
+ return 'UTC';
177
+ }
178
+ }
179
+
76
180
  // 4. Helper: Announce Controls (Write-Enabled)
77
181
  function announceControls() {
78
182
  if (!enableMqtt || !node.broker) return;
@@ -187,21 +291,64 @@ module.exports = function (RED) {
187
291
  if (sensor.unit) payload.unit_of_measurement = sensor.unit;
188
292
  if (sensor.icon) payload.icon = sensor.icon;
189
293
 
190
- // Mark raw sensors, refresh timestamp, and API metrics as diagnostic (moves to Diagnostics section)
294
+ // Mark raw sensors, refresh timestamp, API metrics, and timezone diagnostics as diagnostic
191
295
  if (sensor.id.includes('_raw') ||
192
296
  sensor.id === 'refresh_available_at' ||
193
- sensor.id.startsWith('api_')) {
297
+ sensor.id.startsWith('api_') ||
298
+ sensor.id.startsWith('timezone_')) {
194
299
  payload.entity_category = "diagnostic";
195
300
  }
196
301
 
197
302
  node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
198
303
  });
199
304
 
305
+ // I. Timezone Select Entity
306
+ const TIMEZONE_OPTIONS = [
307
+ "Europe/London", "Europe/Berlin", "Europe/Madrid",
308
+ "Australia/Sydney", "Australia/Melbourne", "Australia/Brisbane",
309
+ "Australia/Perth", "Australia/Adelaide", "Pacific/Auckland",
310
+ "America/New_York", "America/Chicago", "America/Denver",
311
+ "America/Los_Angeles", "Asia/Tokyo", "UTC"
312
+ ];
313
+ node.broker.client.publish(
314
+ `${mqttPrefix}/select/${uniqueIdPrefix}_timezone/config`,
315
+ JSON.stringify({
316
+ name: "Timezone",
317
+ unique_id: `${uniqueIdPrefix}_timezone`,
318
+ options: TIMEZONE_OPTIONS,
319
+ command_topic: cmdTopicTimezone,
320
+ state_topic: `${stateTopic}/timezone`,
321
+ icon: "mdi:earth",
322
+ entity_category: "config",
323
+ device: device
324
+ }),
325
+ { retain: true }
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
+
200
345
  // Subscribe to Commands
201
346
  node.broker.client.subscribe(cmdTopicLimit);
202
347
  node.broker.client.subscribe(cmdTopicTime);
203
348
  node.broker.client.subscribe(cmdTopicSubmit);
204
349
  node.broker.client.subscribe(cmdTopicRefresh);
350
+ node.broker.client.subscribe(cmdTopicTimezone);
351
+ node.broker.client.subscribe(cmdTopicSmartCharging);
205
352
  }
206
353
 
207
354
  // 5. Helper: Set Preferences (The Mutation)
@@ -241,6 +388,11 @@ module.exports = function (RED) {
241
388
  // - Mutation (auth + setPreferences): ~250
242
389
  // - Pre-validation (auth + plannedDispatches only): ~200
243
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
+
244
396
  // Last known full state - prevents sensors going unknown when controls change
245
397
  let lastKnownState = buildDefaultPayload();
246
398
 
@@ -269,7 +421,7 @@ module.exports = function (RED) {
269
421
  node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
270
422
 
271
423
  // A. Get Token
272
- const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
424
+ const authResponse = await graphqlPost({
273
425
  query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
274
426
  variables: { input: { APIKey: apiKey } }
275
427
  });
@@ -299,10 +451,10 @@ module.exports = function (RED) {
299
451
  }
300
452
  };
301
453
 
302
- const mutationResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
454
+ const mutationResponse = await graphqlPost({
303
455
  query: mutation,
304
456
  variables: variables
305
- }, { headers: { Authorization: token } });
457
+ }, token);
306
458
 
307
459
  if (mutationResponse.data.errors) {
308
460
  throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
@@ -375,6 +527,123 @@ module.exports = function (RED) {
375
527
  }
376
528
  }
377
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
+
378
647
  // 6. Logic: Fetch Data (Read)
379
648
  async function fetchData(validationMode = false) {
380
649
  // Estimated complexity per poll:
@@ -415,7 +684,7 @@ module.exports = function (RED) {
415
684
  variables: { input: { APIKey: apiKey } }
416
685
  };
417
686
 
418
- const authResponse = await axios.post(authRequest.url, {
687
+ const authResponse = await graphqlPost({
419
688
  query: authRequest.query,
420
689
  variables: authRequest.variables
421
690
  });
@@ -453,10 +722,10 @@ module.exports = function (RED) {
453
722
  vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
454
723
  }`;
455
724
 
456
- const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
725
+ const dataResponse = await graphqlPost({
457
726
  query: masterQuery,
458
727
  variables: { account: account }
459
- }, { headers: { Authorization: token } });
728
+ }, token);
460
729
 
461
730
  debugInfo.apiCalls.push({
462
731
  step: 2,
@@ -545,8 +814,10 @@ module.exports = function (RED) {
545
814
  const apiMetrics = getApiMetrics();
546
815
 
547
816
  // Build Payload
817
+ const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch(e) { return 'UTC'; } })();
818
+ const appliedTz = resolveTimezone(node);
548
819
  const statusPayload = {
549
- next_start: nextSlot ? nextSlot.startDt : null,
820
+ next_start: nextSlot ? convertToTimezone(nextSlot.startDt, appliedTz) : null,
550
821
  total_energy: parseFloat(totalEnergy.toFixed(2)),
551
822
  next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
552
823
  next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
@@ -567,16 +838,16 @@ module.exports = function (RED) {
567
838
  api_requests_hour: apiMetrics.requests_last_hour,
568
839
  api_complexity_hour: apiMetrics.complexity_last_hour,
569
840
  api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
570
- // Individual slots (first 3 active/future) - formatted timestamps
571
- slot1_start: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
572
- slot1_end: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
573
- slot2_start: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
574
- slot2_end: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
575
- slot3_start: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
576
- slot3_end: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
577
- // Overall window (first start to last end) - formatted timestamps
578
- window_start: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
579
- window_end: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
841
+ // Individual slots (first 3 active/future) — timezone-converted (appliedTz)
842
+ slot1_start: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
843
+ slot1_end: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, appliedTz) : null,
844
+ slot2_start: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, appliedTz) : null,
845
+ slot2_end: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, appliedTz) : null,
846
+ slot3_start: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, appliedTz) : null,
847
+ slot3_end: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, appliedTz) : null,
848
+ // Overall window (first start to last end) — timezone-converted (appliedTz)
849
+ window_start: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
850
+ window_end: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, appliedTz) : null,
580
851
  // Raw timestamp strings (exact API output)
581
852
  next_start_raw: nextSlot ? nextSlot.startDt : null,
582
853
  slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
@@ -586,7 +857,21 @@ module.exports = function (RED) {
586
857
  slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
587
858
  slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
588
859
  window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
589
- window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null
860
+ window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
861
+ // Timezone metadata
862
+ timezone_detected: serverTz,
863
+ timezone_applied: appliedTz,
864
+ // Locale timestamps — always server auto-detected timezone (never overridden)
865
+ next_start_locale: nextSlot ? convertToTimezone(nextSlot.startDt, serverTz) : null,
866
+ slot1_start_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
867
+ slot1_end_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, serverTz) : null,
868
+ slot2_start_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, serverTz) : null,
869
+ slot2_end_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, serverTz) : null,
870
+ slot3_start_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, serverTz) : null,
871
+ slot3_end_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, serverTz) : null,
872
+ window_start_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
873
+ window_end_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, serverTz) : null,
874
+ smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
590
875
  };
591
876
 
592
877
  // Success!
@@ -713,10 +998,56 @@ module.exports = function (RED) {
713
998
  slot3_start_raw: null,
714
999
  slot3_end_raw: null,
715
1000
  window_start_raw: null,
716
- window_end_raw: null
1001
+ window_end_raw: null,
1002
+ // Timezone metadata
1003
+ timezone_detected: null,
1004
+ timezone_applied: null,
1005
+ // Locale timestamps
1006
+ next_start_locale: null,
1007
+ slot1_start_locale: null,
1008
+ slot1_end_locale: null,
1009
+ slot2_start_locale: null,
1010
+ slot2_end_locale: null,
1011
+ slot3_start_locale: null,
1012
+ slot3_end_locale: null,
1013
+ window_start_locale: null,
1014
+ window_end_locale: null,
1015
+ smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
717
1016
  };
718
1017
  }
719
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
+
720
1051
  // 6a. Charging Now - Timer Management Functions
721
1052
 
722
1053
  // State reconciliation - checks every 10s if charging state matches reality
@@ -892,7 +1223,7 @@ module.exports = function (RED) {
892
1223
  node.warn("Pre-validating slot data (30s before start)");
893
1224
  try {
894
1225
  // Fetch fresh data from API
895
- const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
1226
+ const authResponse = await graphqlPost({
896
1227
  query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
897
1228
  variables: { input: { APIKey: apiKey } }
898
1229
  });
@@ -903,10 +1234,10 @@ module.exports = function (RED) {
903
1234
 
904
1235
  const token = authResponse.data.data.obtainKrakenToken.token;
905
1236
 
906
- const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
1237
+ const dataResponse = await graphqlPost({
907
1238
  query: `query getData($account: String!) { plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } } }`,
908
1239
  variables: { account: account }
909
- }, { headers: { Authorization: token } });
1240
+ }, token);
910
1241
 
911
1242
  if (dataResponse.data.data && dataResponse.data.data.plannedDispatches) {
912
1243
  cachedSlots = dataResponse.data.data.plannedDispatches;
@@ -1067,6 +1398,22 @@ module.exports = function (RED) {
1067
1398
  setPreferences(targetLimit, targetTime);
1068
1399
  return; // Don't run standard fetch if setting
1069
1400
  }
1401
+ if (msg.payload.set_timezone !== undefined) {
1402
+ const tz = msg.payload.set_timezone;
1403
+ if (typeof tz === 'string' && tz.trim().length > 0) {
1404
+ node.context().set('timezone', tz.trim());
1405
+ node.log(`Timezone set to: ${tz.trim()}`);
1406
+ }
1407
+ return;
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
+ }
1070
1417
  }
1071
1418
 
1072
1419
  // Manual refresh request from Node-RED - NO rate limiting
@@ -1135,18 +1482,59 @@ module.exports = function (RED) {
1135
1482
  fetchData();
1136
1483
  });
1137
1484
 
1485
+ // Timezone select changed in Home Assistant
1486
+ node.broker.subscribe(cmdTopicTimezone, 0, (topic, payload) => {
1487
+ const tz = payload.toString().trim();
1488
+ if (tz.length > 0) {
1489
+ node.context().set('timezone', tz);
1490
+ node.log(`Timezone set via MQTT to: ${tz}`);
1491
+ node.broker.client.publish(`${stateTopic}/timezone`, tz, { retain: true });
1492
+ }
1493
+ });
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
+
1138
1502
  setTimeout(announceControls, 2000);
1503
+
1504
+ // Republish persisted timezone to HA select on startup
1505
+ setTimeout(() => {
1506
+ try {
1507
+ const persistedTz = node.context().get('timezone');
1508
+ if (persistedTz && node.broker) {
1509
+ node.broker.client.publish(`${stateTopic}/timezone`, persistedTz, { retain: true });
1510
+ }
1511
+ } catch (e) { node.warn('Failed to republish timezone on startup: ' + e.message); }
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);
1139
1523
  }
1140
1524
 
1141
1525
  // Init
1142
1526
  pollIntervalHandle = setInterval(fetchData, refreshRate);
1143
1527
  updateNextPollTime(); // Set initial next poll time
1144
1528
  setTimeout(fetchData, 1000);
1529
+ setTimeout(fetchDeviceId, 1500);
1145
1530
  node.on('close', () => {
1146
1531
  clearInterval(pollIntervalHandle);
1147
1532
  // Clear any pending retry timeouts
1148
1533
  retryTimeouts.forEach(timeout => clearTimeout(timeout));
1149
1534
  retryTimeouts = [];
1535
+ // Clear smart charging retry timeouts
1536
+ smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
1537
+ smartChargingRetryTimeouts = [];
1150
1538
  // Clear charging timers
1151
1539
  clearChargingTimers();
1152
1540
  // Clear cooldown expiry timer
@@ -1154,7 +1542,7 @@ module.exports = function (RED) {
1154
1542
  clearTimeout(cooldownExpiryTimer);
1155
1543
  cooldownExpiryTimer = null;
1156
1544
  }
1157
- if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh);
1545
+ if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging);
1158
1546
  });
1159
1547
  }
1160
1548
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-octopus-intelligent",
3
- "version": "1.0.5",
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": {
@@ -25,10 +25,7 @@
25
25
  "README.md",
26
26
  "CHANGELOG.md",
27
27
  "LICENSE",
28
- "examples/",
29
- "images/",
30
- "__tests__/",
31
- "test-mocks.js"
28
+ "examples/"
32
29
  ],
33
30
  "node-red": {
34
31
  "version": ">=2.0.0",
@@ -40,9 +37,7 @@
40
37
  "node": ">=14.0.0",
41
38
  "node-red": ">=2.0.0"
42
39
  },
43
- "dependencies": {
44
- "axios": "^1.6.0"
45
- },
40
+ "dependencies": {},
46
41
  "devDependencies": {
47
42
  "jest": "^29.7.0",
48
43
  "@types/jest": "^29.5.0"