node-red-contrib-octopus-intelligent 1.5.0 → 1.7.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +597 -442
  2. package/README.md +1234 -980
  3. package/examples/basic-monitoring.json +1 -1
  4. package/examples/boost-on-cheap-or-surplus.json +171 -0
  5. package/examples/charging-and-error-alerts.json +95 -0
  6. package/examples/cheapest-window-planner.json +165 -0
  7. package/examples/daily-charging-summary.json +165 -0
  8. package/examples/ha-dashboard.yaml +667 -599
  9. package/examples/mqtt-integration.json +1 -1
  10. package/examples/node-red-dashboard-flow.json +1377 -1199
  11. package/examples/set-preferences.json +1 -1
  12. package/lib/active-now.js +33 -0
  13. package/lib/api-metrics.js +31 -31
  14. package/lib/auth.js +25 -20
  15. package/lib/boost.js +85 -0
  16. package/lib/categories/account.js +32 -32
  17. package/lib/categories/applicable-rates.js +137 -127
  18. package/lib/categories/completed-dispatches.js +36 -35
  19. package/lib/categories/electricity.js +156 -146
  20. package/lib/categories/flex-planned-dispatches.js +36 -36
  21. package/lib/categories/free-electricity.js +73 -61
  22. package/lib/categories/gas.js +102 -95
  23. package/lib/categories/home-mini.js +45 -37
  24. package/lib/categories/intelligent.js +221 -124
  25. package/lib/categories/octoplus.js +35 -32
  26. package/lib/categories/saving-sessions.js +78 -64
  27. package/lib/categories/smartflex-inverter.js +95 -0
  28. package/lib/categories/smartflex-vehicle.js +198 -0
  29. package/lib/categories/wheel-of-fortune.js +50 -49
  30. package/lib/commands.js +69 -0
  31. package/lib/discovery-retry.js +16 -0
  32. package/lib/discovery.js +154 -85
  33. package/lib/graphql-errors.js +174 -0
  34. package/lib/graphql.js +141 -44
  35. package/lib/http-get-json.js +80 -22
  36. package/lib/payload.js +104 -88
  37. package/lib/poll-retry.js +71 -0
  38. package/lib/poll-tick.js +112 -44
  39. package/lib/preferences.js +34 -0
  40. package/lib/scheduler.js +85 -47
  41. package/lib/sensor-definitions.js +269 -0
  42. package/lib/timezone.js +67 -49
  43. package/lib/update-check.js +38 -38
  44. package/lib/values.js +47 -0
  45. package/octopus-intelligent.html +258 -205
  46. package/octopus-intelligent.js +2816 -1807
  47. package/package.json +54 -54
@@ -1,95 +1,102 @@
1
- // lib/categories/gas.js
2
- 'use strict';
3
-
4
- // GasTariffType is a single object type (not a union) — direct field access, no fragments.
5
- const RATES_QUERY = `
6
- query getGasRates($account: String!) {
7
- account(accountNumber: $account) {
8
- gasAgreements {
9
- validFrom validTo
10
- tariff {
11
- productCode
12
- standingCharge
13
- unitRate
14
- }
15
- }
16
- }
17
- }`;
18
-
19
- const CONSUMPTION_QUERY = `
20
- query getGasConsumption($account: String!, $startAt: DateTime!, $timezone: String!) {
21
- account(accountNumber: $account) {
22
- properties {
23
- gasMeterPoints {
24
- meters {
25
- consumption(startAt: $startAt, last: 1, grouping: DAY, timezone: $timezone) {
26
- edges { node { startAt endAt value } }
27
- }
28
- }
29
- }
30
- }
31
- }
32
- }`;
33
-
34
- function buildRatesQuery(account) {
35
- return { query: RATES_QUERY, variables: { account } };
36
- }
37
-
38
- function buildConsumptionQuery(account, timezone) {
39
- const tz = timezone || 'UTC';
40
- const startAt = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
41
- return { query: CONSUMPTION_QUERY, variables: { account, startAt, timezone: tz } };
42
- }
43
-
44
- function parseRatesResponse(data) {
45
- const all = (data.account || {}).gasAgreements || [];
46
- const agreements = all.filter(a => !((a.tariff || {}).productCode || '').includes('OUTGOING'));
47
- if (agreements.length === 0) {
48
- return {
49
- gas_unit_rate: null, gas_standing_charge: null, gas_tariff_code: null,
50
- gas_valid_from: null, gas_valid_to: null, gas_rates_error: null
51
- };
52
- }
53
- const latest = agreements[0];
54
- const tariff = latest.tariff || {};
55
- // Kraken Float scalars can serialise as strings — coerce defensively
56
- return {
57
- gas_unit_rate: tariff.unitRate != null ? parseFloat(tariff.unitRate) : null,
58
- gas_standing_charge: tariff.standingCharge != null ? parseFloat(tariff.standingCharge) : null,
59
- gas_tariff_code: tariff.productCode || null,
60
- gas_valid_from: latest.validFrom || null,
61
- gas_valid_to: latest.validTo || null,
62
- gas_rates_error: null
63
- };
64
- }
65
-
66
- function parseConsumptionResponse(data) {
67
- const points = ((data.account || {}).properties || [])[0];
68
- const meterPoint = points ? (points.gasMeterPoints || [])[0] : null;
69
- const meter = meterPoint ? (meterPoint.meters || [])[0] : null;
70
- const connection = meter ? meter.consumption : null;
71
- const edges = connection ? (connection.edges || []) : [];
72
- const entry = edges.length > 0 ? edges[edges.length - 1].node : null;
73
- if (!entry) {
74
- return {
75
- gas_consumption_kwh: null, gas_consumption_cost: null,
76
- gas_consumption_from: null, gas_consumption_to: null, gas_consumption_error: null
77
- };
78
- }
79
- return {
80
- gas_consumption_kwh: parseFloat(entry.value),
81
- gas_consumption_cost: null,
82
- gas_consumption_from: entry.startAt,
83
- gas_consumption_to: entry.endAt,
84
- gas_consumption_error: null
85
- };
86
- }
87
-
88
- const defaultData = {
89
- gas_unit_rate: null, gas_standing_charge: null, gas_tariff_code: null,
90
- gas_valid_from: null, gas_valid_to: null, gas_rates_error: null,
91
- gas_consumption_kwh: null, gas_consumption_cost: null,
92
- gas_consumption_from: null, gas_consumption_to: null, gas_consumption_error: null
93
- };
94
-
95
- module.exports = { buildRatesQuery, buildConsumptionQuery, parseRatesResponse, parseConsumptionResponse, defaultData };
1
+ // lib/categories/gas.js
2
+ 'use strict';
3
+ const { toNumber, capStrings } = require('../values');
4
+ const { latestReading } = require('./electricity');
5
+
6
+ // GasTariffType is a single object type (not a union) — direct field access, no fragments.
7
+ const RATES_QUERY = `
8
+ query getGasRates($account: String!) {
9
+ account(accountNumber: $account) {
10
+ gasAgreements {
11
+ validFrom validTo
12
+ tariff {
13
+ productCode
14
+ standingCharge
15
+ unitRate
16
+ }
17
+ }
18
+ }
19
+ }`;
20
+
21
+ const CONSUMPTION_QUERY = `
22
+ query getGasConsumption($account: String!, $startAt: DateTime!, $timezone: String!) {
23
+ account(accountNumber: $account) {
24
+ properties {
25
+ gasMeterPoints {
26
+ meters {
27
+ consumption(startAt: $startAt, last: 1, grouping: DAY, timezone: $timezone) {
28
+ edges { node { startAt endAt value } }
29
+ }
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }`;
35
+
36
+ function buildRatesQuery(account) {
37
+ return { query: RATES_QUERY, variables: { account } };
38
+ }
39
+
40
+ function buildConsumptionQuery(account, timezone) {
41
+ const tz = timezone || 'UTC';
42
+ const startAt = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
43
+ return { query: CONSUMPTION_QUERY, variables: { account, startAt, timezone: tz } };
44
+ }
45
+
46
+ function parseRatesResponse(data) {
47
+ const all = (data.account || {}).gasAgreements || [];
48
+ const agreements = all.filter(a => !((a.tariff || {}).productCode || '').includes('OUTGOING'));
49
+ if (agreements.length === 0) {
50
+ return {
51
+ gas_unit_rate: null, gas_standing_charge: null, gas_tariff_code: null,
52
+ gas_valid_from: null, gas_valid_to: null, gas_rates_error: null
53
+ };
54
+ }
55
+ const latest = agreements[0];
56
+ const tariff = latest.tariff || {};
57
+ // Kraken Float scalars can serialise as strings; anything not a finite number is null
58
+ return {
59
+ gas_unit_rate: toNumber(tariff.unitRate),
60
+ gas_standing_charge: toNumber(tariff.standingCharge),
61
+ gas_tariff_code: tariff.productCode || null,
62
+ gas_valid_from: latest.validFrom || null,
63
+ gas_valid_to: latest.validTo || null,
64
+ gas_rates_error: null
65
+ };
66
+ }
67
+
68
+ function parseConsumptionResponse(data) {
69
+ const points = ((data.account || {}).properties || [])[0];
70
+ const meterPoint = points ? (points.gasMeterPoints || [])[0] : null;
71
+ const meter = meterPoint ? (meterPoint.meters || [])[0] : null;
72
+ const connection = meter ? meter.consumption : null;
73
+ const edges = connection ? (connection.edges || []) : [];
74
+ const entry = latestReading(edges); // skips a reading with no value
75
+ if (!entry) {
76
+ return {
77
+ gas_consumption_kwh: null, gas_consumption_cost: null,
78
+ gas_consumption_from: null, gas_consumption_to: null, gas_consumption_error: null
79
+ };
80
+ }
81
+ return {
82
+ gas_consumption_kwh: toNumber(entry.value),
83
+ gas_consumption_cost: null,
84
+ gas_consumption_from: entry.startAt,
85
+ gas_consumption_to: entry.endAt,
86
+ gas_consumption_error: null
87
+ };
88
+ }
89
+
90
+ const defaultData = {
91
+ gas_unit_rate: null, gas_standing_charge: null, gas_tariff_code: null,
92
+ gas_valid_from: null, gas_valid_to: null, gas_rates_error: null,
93
+ gas_consumption_kwh: null, gas_consumption_cost: null,
94
+ gas_consumption_from: null, gas_consumption_to: null, gas_consumption_error: null
95
+ };
96
+
97
+ // Text fields cut to the HA state limit (lib/values.js).
98
+ module.exports = {
99
+ buildRatesQuery, buildConsumptionQuery, defaultData,
100
+ parseRatesResponse: capStrings(parseRatesResponse),
101
+ parseConsumptionResponse: capStrings(parseConsumptionResponse),
102
+ };
@@ -1,37 +1,45 @@
1
- 'use strict';
2
-
3
- const QUERY = `
4
- query getSmartMeterTelemetry($deviceId: String!, $start: DateTime!, $end: DateTime!) {
5
- smartMeterTelemetry(deviceId: $deviceId, grouping: HALF_HOURLY, start: $start, end: $end) {
6
- readAt demand consumptionDelta
7
- }
8
- }`;
9
-
10
- function buildQuery(smartMeterDeviceId) {
11
- const end = new Date().toISOString();
12
- const start = new Date(Date.now() - 30 * 60 * 1000).toISOString();
13
- return { query: QUERY, variables: { deviceId: smartMeterDeviceId, start, end } };
14
- }
15
-
16
- function parseResponse(data) {
17
- const readings = data.smartMeterTelemetry || [];
18
- const latest = readings.length > 0 ? readings[readings.length - 1] : null;
19
-
20
- return {
21
- // demand is in Watts from API — negative means exporting
22
- mini_demand_kw: latest && latest.demand != null ? parseFloat(latest.demand) / 1000 : null,
23
- // consumptionDelta is in Wh per half-hour period
24
- mini_consumption_delta_kwh: latest && latest.consumptionDelta != null ? parseFloat(latest.consumptionDelta) / 1000 : null,
25
- mini_read_at: latest ? latest.readAt ?? null : null,
26
- home_mini_error: null
27
- };
28
- }
29
-
30
- const defaultData = {
31
- mini_demand_kw: null,
32
- mini_consumption_delta_kwh: null,
33
- mini_read_at: null,
34
- home_mini_error: null
35
- };
36
-
37
- module.exports = { buildQuery, parseResponse, defaultData };
1
+ 'use strict';
2
+ const { toNumber, capStrings } = require('../values');
3
+
4
+ const QUERY = `
5
+ query getSmartMeterTelemetry($deviceId: String!, $start: DateTime!, $end: DateTime!) {
6
+ smartMeterTelemetry(deviceId: $deviceId, grouping: HALF_HOURLY, start: $start, end: $end) {
7
+ readAt demand consumptionDelta
8
+ }
9
+ }`;
10
+
11
+ function buildQuery(smartMeterDeviceId) {
12
+ const end = new Date().toISOString();
13
+ const start = new Date(Date.now() - 30 * 60 * 1000).toISOString();
14
+ return { query: QUERY, variables: { deviceId: smartMeterDeviceId, start, end } };
15
+ }
16
+
17
+ // W or Wh from the API to kW or kWh; anything not a finite number is null.
18
+ function toKilo(value) {
19
+ const n = toNumber(value);
20
+ return n === null ? null : n / 1000;
21
+ }
22
+
23
+ function parseResponse(data) {
24
+ const readings = data.smartMeterTelemetry || [];
25
+ const latest = readings.length > 0 ? readings[readings.length - 1] : null;
26
+
27
+ return {
28
+ // demand is in Watts from API — negative means exporting
29
+ mini_demand_kw: latest ? toKilo(latest.demand) : null,
30
+ // consumptionDelta is in Wh per half-hour period
31
+ mini_consumption_delta_kwh: latest ? toKilo(latest.consumptionDelta) : null,
32
+ mini_read_at: latest ? latest.readAt ?? null : null,
33
+ home_mini_error: null
34
+ };
35
+ }
36
+
37
+ const defaultData = {
38
+ mini_demand_kw: null,
39
+ mini_consumption_delta_kwh: null,
40
+ mini_read_at: null,
41
+ home_mini_error: null
42
+ };
43
+
44
+ // Text fields cut to the HA state limit (lib/values.js).
45
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), defaultData };
@@ -1,124 +1,221 @@
1
- // lib/categories/intelligent.js
2
- 'use strict';
3
- const { convertToTimezone } = require('../timezone');
4
-
5
- const WEEKDAYS = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
6
-
7
- const DEVICES_QUERY = `
8
- query getDevices($account: String!) {
9
- devices(accountNumber: $account) {
10
- id
11
- deviceType
12
- preferences {
13
- ... on SmartFlexDevicePreferences {
14
- schedules {
15
- dayOfWeek
16
- time
17
- max
18
- }
19
- }
20
- }
21
- }
22
- }`;
23
-
24
- const DISPATCH_QUERY = `
25
- query getDispatches($deviceId: String!) {
26
- flexPlannedDispatches(deviceId: $deviceId) {
27
- start end type energyAddedKwh
28
- }
29
- }`;
30
-
31
- function buildDevicesQuery(account) {
32
- return { query: DEVICES_QUERY, variables: { account } };
33
- }
34
-
35
- function buildDispatchQuery(deviceId) {
36
- return { query: DISPATCH_QUERY, variables: { deviceId } };
37
- }
38
-
39
- function extractEvDevice(devices) {
40
- return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
41
- }
42
-
43
- function extractPreferences(devices) {
44
- const ev = extractEvDevice(devices);
45
- if (!ev || !ev.preferences) return { confirmed_limit: 80, confirmed_time: '07:30' };
46
-
47
- const schedules = ev.preferences.schedules || [];
48
- const weekday = schedules.find(s => WEEKDAYS.includes(s.dayOfWeek));
49
- if (!weekday) return { confirmed_limit: 80, confirmed_time: '07:30' };
50
-
51
- // time may arrive as 'HH:MM:SS' or 'HH:MM' — normalise to 'HH:MM'
52
- const time = weekday.time ? weekday.time.substring(0, 5) : '07:30';
53
- return {
54
- confirmed_limit: weekday.max ?? 80,
55
- confirmed_time: time,
56
- };
57
- }
58
-
59
- // data must be merged result: { devices: [...], flexPlannedDispatches: [...] }
60
- function parseResponse(data, { tz, serverTz }) {
61
- const devices = data.devices || [];
62
- const dispatches = data.flexPlannedDispatches || [];
63
- const prefs = extractPreferences(devices);
64
-
65
- const now = new Date();
66
- const active = dispatches.filter(s => new Date(s.end) > now);
67
- const nextSlot = active[0] || null;
68
- // energyAddedKwh arrives from live API as a string — coerce before arithmetic
69
- const totalEnergy = active.reduce((sum, s) => sum + (parseFloat(s.energyAddedKwh) || 0), 0);
70
-
71
- function conv(dt) { return dt ? convertToTimezone(dt, tz) : null; }
72
- function locale(dt) { return dt ? convertToTimezone(dt, serverTz) : null; }
73
-
74
- return {
75
- confirmed_limit: prefs.confirmed_limit,
76
- confirmed_time: prefs.confirmed_time,
77
- next_start: nextSlot ? conv(nextSlot.start) : null,
78
- next_start_raw: nextSlot ? nextSlot.start : null,
79
- next_start_locale: nextSlot ? locale(nextSlot.start) : null,
80
- total_energy: parseFloat(totalEnergy.toFixed(2)),
81
- next_kwh: nextSlot && nextSlot.energyAddedKwh != null ? parseFloat(nextSlot.energyAddedKwh).toFixed(2) : '0',
82
- next_source: nextSlot ? (nextSlot.type || 'unknown').toLowerCase() : 'unknown',
83
- slot1_start: active[0] ? conv(active[0].start) : null,
84
- slot1_end: active[0] ? conv(active[0].end) : null,
85
- slot2_start: active[1] ? conv(active[1].start) : null,
86
- slot2_end: active[1] ? conv(active[1].end) : null,
87
- slot3_start: active[2] ? conv(active[2].start) : null,
88
- slot3_end: active[2] ? conv(active[2].end) : null,
89
- window_start: active.length > 0 ? conv(active[0].start) : null,
90
- window_end: active.length > 0 ? conv(active[active.length - 1].end) : null,
91
- slot1_start_raw: active[0] ? active[0].start : null,
92
- slot1_end_raw: active[0] ? active[0].end : null,
93
- slot2_start_raw: active[1] ? active[1].start : null,
94
- slot2_end_raw: active[1] ? active[1].end : null,
95
- slot3_start_raw: active[2] ? active[2].start : null,
96
- slot3_end_raw: active[2] ? active[2].end : null,
97
- window_start_raw: active.length > 0 ? active[0].start : null,
98
- window_end_raw: active.length > 0 ? active[active.length - 1].end : null,
99
- slot1_start_locale: active[0] ? locale(active[0].start) : null,
100
- slot1_end_locale: active[0] ? locale(active[0].end) : null,
101
- slot2_start_locale: active[1] ? locale(active[1].start) : null,
102
- slot2_end_locale: active[1] ? locale(active[1].end) : null,
103
- slot3_start_locale: active[2] ? locale(active[2].start) : null,
104
- slot3_end_locale: active[2] ? locale(active[2].end) : null,
105
- window_start_locale: active.length > 0 ? locale(active[0].start) : null,
106
- window_end_locale: active.length > 0 ? locale(active[active.length - 1].end) : null,
107
- _activeSlots: active
108
- };
109
- }
110
-
111
- const defaultData = {
112
- confirmed_limit: 80, confirmed_time: '07:30',
113
- next_start: null, next_start_raw: null, next_start_locale: null,
114
- total_energy: 0, next_kwh: '0', next_source: 'unknown',
115
- slot1_start: null, slot1_end: null, slot2_start: null, slot2_end: null,
116
- slot3_start: null, slot3_end: null, window_start: null, window_end: null,
117
- slot1_start_raw: null, slot1_end_raw: null, slot2_start_raw: null, slot2_end_raw: null,
118
- slot3_start_raw: null, slot3_end_raw: null, window_start_raw: null, window_end_raw: null,
119
- slot1_start_locale: null, slot1_end_locale: null, slot2_start_locale: null, slot2_end_locale: null,
120
- slot3_start_locale: null, slot3_end_locale: null, window_start_locale: null, window_end_locale: null,
121
- _activeSlots: []
122
- };
123
-
124
- module.exports = { buildDevicesQuery, buildDispatchQuery, extractEvDevice, parseResponse, defaultData };
1
+ // lib/categories/intelligent.js
2
+ 'use strict';
3
+ const { convertToTimezone } = require('../timezone');
4
+ const { isBoosting } = require('../boost');
5
+ const { toNumber, capStrings } = require('../values');
6
+ // Shared with discovery (lib/discovery.js); exported here as before.
7
+ const { statusNulledDevices } = require('../graphql-errors');
8
+
9
+ const WEEKDAYS = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
10
+
11
+ // Smart-charging switch state and boost state (currentState). The alias only makes its errors
12
+ // easy to recognise: `status` is non-null on the device and the list items are non-null too,
13
+ // so an error on `status` itself (KT-CT-4360 has been seen there) nulls `devices`, the nearest
14
+ // nullable field: the whole list, schedules included. The charging poll then asks again without this selection
15
+ // (buildDevicesQuery(account, false)).
16
+ const STATUS_SELECTION = `
17
+ # Smart-charging switch state and boost state, under their own alias so an error on
18
+ # status (KT-CT-4360 has been seen) can be told apart from other device errors.
19
+ # currentState is BOOSTING while a boost charge runs.
20
+ smartStatus: status {
21
+ isSuspended
22
+ currentState
23
+ }`;
24
+
25
+ function devicesQuery(withStatus) {
26
+ return `
27
+ query getDevices($account: String!) {
28
+ devices(accountNumber: $account) {
29
+ id
30
+ deviceType
31
+ preferences {
32
+ ... on SmartFlexDevicePreferences {
33
+ schedules {
34
+ dayOfWeek
35
+ time
36
+ max
37
+ }
38
+ }
39
+ }
40
+ # Separate alias: the Charge Cap field is non-null, so an error on it nulls its parent
41
+ # selection (preferences is nullable). Keeping it apart stops such an error from
42
+ # blanking the schedules above.
43
+ chargeCap: preferences {
44
+ ... on SmartFlexDevicePreferences {
45
+ isChargingDurationCapped
46
+ }
47
+ }${withStatus ? STATUS_SELECTION : ''}
48
+ }
49
+ }`;
50
+ }
51
+
52
+ const DEVICES_QUERY = devicesQuery(true);
53
+ const DEVICES_QUERY_NO_STATUS = devicesQuery(false);
54
+
55
+ const DISPATCH_QUERY = `
56
+ query getDispatches($deviceId: String!) {
57
+ flexPlannedDispatches(deviceId: $deviceId) {
58
+ start end type energyAddedKwh
59
+ }
60
+ }`;
61
+
62
+ // withStatus false leaves out the smart-charging status (see STATUS_SELECTION).
63
+ function buildDevicesQuery(account, withStatus = true) {
64
+ return { query: withStatus ? DEVICES_QUERY : DEVICES_QUERY_NO_STATUS, variables: { account } };
65
+ }
66
+
67
+ function buildDispatchQuery(deviceId) {
68
+ return { query: DISPATCH_QUERY, variables: { deviceId } };
69
+ }
70
+
71
+ // Another device's entry can be null when Kraken failed one of its fields (review A11).
72
+ // preferredId: the EV discovery picked (the LIVE one, review L4). Used when it is listed, so
73
+ // every part of the charging poll reads the same device; otherwise the first EV.
74
+ function extractEvDevice(devices, preferredId) {
75
+ const evs = (devices || []).filter(d => d && d.deviceType === 'ELECTRIC_VEHICLES');
76
+ return (preferredId ? evs.find(d => d.id === preferredId) : null) || evs[0] || null;
77
+ }
78
+
79
+ // isChargingDurationCapped: ENABLED | DISABLED | NOT_APPLICABLE (live-verified 2026-09-29).
80
+ // Anything other than ENABLED/DISABLED (incl. missing) -> null.
81
+ function extractChargeCap(devices, preferredId) {
82
+ const ev = extractEvDevice(devices, preferredId);
83
+ const raw = ev && ev.chargeCap ? ev.chargeCap.isChargingDurationCapped : undefined;
84
+ if (raw === 'ENABLED') return true;
85
+ if (raw === 'DISABLED') return false;
86
+ return null;
87
+ }
88
+
89
+ // status.isSuspended (alias smartStatus): true = smart charging suspended (switch OFF).
90
+ // Anything but a boolean (missing, null after an error) -> null (unknown).
91
+ function extractSuspended(devices, preferredId) {
92
+ const ev = extractEvDevice(devices, preferredId);
93
+ const raw = ev && ev.smartStatus ? ev.smartStatus.isSuspended : undefined;
94
+ return typeof raw === 'boolean' ? raw : null;
95
+ }
96
+
97
+ // status.currentState (alias smartStatus) BOOSTING -> true, any other state -> false,
98
+ // missing -> null.
99
+ function extractBoosting(devices, preferredId) {
100
+ const ev = extractEvDevice(devices, preferredId);
101
+ const raw = ev && ev.smartStatus ? ev.smartStatus.currentState : undefined;
102
+ return isBoosting(raw);
103
+ }
104
+
105
+ // status.currentState (alias smartStatus) as it is, e.g. SMART_CONTROL_IN_PROGRESS, BOOSTING,
106
+ // LOST_CONNECTION. Read here (every charging poll) so device_state and boosting always agree.
107
+ // Missing -> null.
108
+ function extractDeviceState(devices, preferredId) {
109
+ const ev = extractEvDevice(devices, preferredId);
110
+ const raw = ev && ev.smartStatus ? ev.smartStatus.currentState : undefined;
111
+ return typeof raw === 'string' && raw.length > 0 ? raw : null;
112
+ }
113
+
114
+ function extractPreferences(devices, preferredId) {
115
+ const ev = extractEvDevice(devices, preferredId);
116
+ if (!ev || !ev.preferences) return { confirmed_limit: 80, confirmed_time: '07:30' };
117
+
118
+ const schedules = ev.preferences.schedules || [];
119
+ const weekday = schedules.find(s => WEEKDAYS.includes(s.dayOfWeek));
120
+ if (!weekday) return { confirmed_limit: 80, confirmed_time: '07:30' };
121
+
122
+ // time may arrive as 'HH:MM:SS' or 'HH:MM' — normalise to 'HH:MM'
123
+ const time = weekday.time ? weekday.time.substring(0, 5) : '07:30';
124
+ // toNumber: '' / ' ' / 'abc' give null (Number('') would give 0); a 0% target is never real
125
+ const maxValue = toNumber(weekday.max);
126
+ return {
127
+ // Float scalars can arrive as JSON strings; this value is sent back in setDevicePreferences
128
+ confirmed_limit: maxValue !== null && maxValue > 0 ? maxValue : 80,
129
+ confirmed_time: time,
130
+ };
131
+ }
132
+
133
+ // energyAddedKwh can arrive as a string; anything non-numeric counts as no energy, as in
134
+ // total_energy, so the sensor never shows "NaN".
135
+ function nextKwh(slot) {
136
+ const kwh = slot ? toNumber(slot.energyAddedKwh) : null;
137
+ return kwh !== null ? kwh.toFixed(2) : '0';
138
+ }
139
+
140
+ // data must be merged result: { devices: [...], flexPlannedDispatches: [...] }
141
+ // evId: the EV discovery picked (optional); see extractEvDevice.
142
+ function parseResponse(data, { tz, serverTz, evId }) {
143
+ const devices = data.devices || [];
144
+ const dispatches = data.flexPlannedDispatches || [];
145
+ const prefs = extractPreferences(devices, evId);
146
+
147
+ const now = new Date();
148
+ const active = dispatches.filter(s => new Date(s.end) > now);
149
+ const nextSlot = active[0] || null;
150
+ // energyAddedKwh arrives from live API as a string — coerce before arithmetic
151
+ const sum = active.reduce((acc, s) => acc + (toNumber(s.energyAddedKwh) || 0), 0);
152
+ const totalEnergy = Number.isFinite(sum) ? sum : 0; // never Infinity, even if the values add up past it
153
+
154
+ function conv(dt) { return dt ? convertToTimezone(dt, tz) : null; }
155
+ function locale(dt) { return dt ? convertToTimezone(dt, serverTz) : null; }
156
+
157
+ return {
158
+ confirmed_limit: prefs.confirmed_limit,
159
+ confirmed_time: prefs.confirmed_time,
160
+ charge_cap: extractChargeCap(devices, evId),
161
+ boosting: extractBoosting(devices, evId),
162
+ device_state: extractDeviceState(devices, evId),
163
+ next_start: nextSlot ? conv(nextSlot.start) : null,
164
+ next_start_raw: nextSlot ? nextSlot.start : null,
165
+ next_start_locale: nextSlot ? locale(nextSlot.start) : null,
166
+ total_energy: parseFloat(totalEnergy.toFixed(2)),
167
+ next_kwh: nextKwh(nextSlot),
168
+ next_source: nextSlot ? (nextSlot.type || 'unknown').toLowerCase() : 'unknown',
169
+ slot1_start: active[0] ? conv(active[0].start) : null,
170
+ slot1_end: active[0] ? conv(active[0].end) : null,
171
+ slot2_start: active[1] ? conv(active[1].start) : null,
172
+ slot2_end: active[1] ? conv(active[1].end) : null,
173
+ slot3_start: active[2] ? conv(active[2].start) : null,
174
+ slot3_end: active[2] ? conv(active[2].end) : null,
175
+ window_start: active.length > 0 ? conv(active[0].start) : null,
176
+ window_end: active.length > 0 ? conv(active[active.length - 1].end) : null,
177
+ slot1_start_raw: active[0] ? active[0].start : null,
178
+ slot1_end_raw: active[0] ? active[0].end : null,
179
+ slot2_start_raw: active[1] ? active[1].start : null,
180
+ slot2_end_raw: active[1] ? active[1].end : null,
181
+ slot3_start_raw: active[2] ? active[2].start : null,
182
+ slot3_end_raw: active[2] ? active[2].end : null,
183
+ window_start_raw: active.length > 0 ? active[0].start : null,
184
+ window_end_raw: active.length > 0 ? active[active.length - 1].end : null,
185
+ slot1_start_locale: active[0] ? locale(active[0].start) : null,
186
+ slot1_end_locale: active[0] ? locale(active[0].end) : null,
187
+ slot2_start_locale: active[1] ? locale(active[1].start) : null,
188
+ slot2_end_locale: active[1] ? locale(active[1].end) : null,
189
+ slot3_start_locale: active[2] ? locale(active[2].start) : null,
190
+ slot3_end_locale: active[2] ? locale(active[2].end) : null,
191
+ window_start_locale: active.length > 0 ? locale(active[0].start) : null,
192
+ window_end_locale: active.length > 0 ? locale(active[active.length - 1].end) : null,
193
+ _activeSlots: active
194
+ };
195
+ }
196
+
197
+ // True when the not-yet-ended slots differ in start/end time. Energy and timestamp
198
+ // formatting are ignored — only a moved, added or cancelled slot counts.
199
+ function slotsChanged(previous, fresh, nowMs = Date.now()) {
200
+ const key = (slots) => (slots || [])
201
+ .filter(s => new Date(s.end).getTime() > nowMs)
202
+ .map(s => `${new Date(s.start).getTime()}-${new Date(s.end).getTime()}`)
203
+ .join(',');
204
+ return key(previous) !== key(fresh);
205
+ }
206
+
207
+ const defaultData = {
208
+ confirmed_limit: 80, confirmed_time: '07:30', charge_cap: null, boosting: null, device_state: null,
209
+ next_start: null, next_start_raw: null, next_start_locale: null,
210
+ total_energy: 0, next_kwh: '0', next_source: 'unknown',
211
+ slot1_start: null, slot1_end: null, slot2_start: null, slot2_end: null,
212
+ slot3_start: null, slot3_end: null, window_start: null, window_end: null,
213
+ slot1_start_raw: null, slot1_end_raw: null, slot2_start_raw: null, slot2_end_raw: null,
214
+ slot3_start_raw: null, slot3_end_raw: null, window_start_raw: null, window_end_raw: null,
215
+ slot1_start_locale: null, slot1_end_locale: null, slot2_start_locale: null, slot2_end_locale: null,
216
+ slot3_start_locale: null, slot3_end_locale: null, window_start_locale: null, window_end_locale: null,
217
+ _activeSlots: []
218
+ };
219
+
220
+ // parseResponse: text fields cut to the HA state limit (lib/values.js).
221
+ module.exports = { buildDevicesQuery, buildDispatchQuery, extractEvDevice, extractSuspended, statusNulledDevices, parseResponse: capStrings(parseResponse), slotsChanged, defaultData };