node-red-contrib-octopus-intelligent 1.6.1 → 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 (45) hide show
  1. package/CHANGELOG.md +129 -19
  2. package/README.md +386 -156
  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 +67 -2
  9. package/examples/mqtt-integration.json +1 -1
  10. package/examples/node-red-dashboard-flow.json +92 -2
  11. package/examples/set-preferences.json +1 -1
  12. package/lib/active-now.js +33 -0
  13. package/lib/auth.js +6 -1
  14. package/lib/boost.js +85 -0
  15. package/lib/categories/account.js +3 -3
  16. package/lib/categories/applicable-rates.js +29 -19
  17. package/lib/categories/completed-dispatches.js +2 -1
  18. package/lib/categories/electricity.js +23 -13
  19. package/lib/categories/flex-planned-dispatches.js +2 -2
  20. package/lib/categories/free-electricity.js +13 -1
  21. package/lib/categories/gas.js +13 -6
  22. package/lib/categories/home-mini.js +11 -3
  23. package/lib/categories/intelligent.js +87 -21
  24. package/lib/categories/octoplus.js +6 -3
  25. package/lib/categories/saving-sessions.js +15 -1
  26. package/lib/categories/smartflex-inverter.js +95 -0
  27. package/lib/categories/smartflex-vehicle.js +198 -0
  28. package/lib/categories/wheel-of-fortune.js +3 -2
  29. package/lib/commands.js +25 -3
  30. package/lib/discovery-retry.js +4 -1
  31. package/lib/discovery.js +71 -9
  32. package/lib/graphql-errors.js +160 -4
  33. package/lib/graphql.js +104 -7
  34. package/lib/http-get-json.js +64 -6
  35. package/lib/payload.js +15 -0
  36. package/lib/poll-retry.js +71 -0
  37. package/lib/poll-tick.js +88 -20
  38. package/lib/preferences.js +4 -2
  39. package/lib/scheduler.js +46 -8
  40. package/lib/sensor-definitions.js +51 -1
  41. package/lib/timezone.js +19 -1
  42. package/lib/values.js +47 -0
  43. package/octopus-intelligent.html +74 -34
  44. package/octopus-intelligent.js +1379 -250
  45. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  // lib/categories/flex-planned-dispatches.js
2
2
  'use strict';
3
+ const { toNumber } = require('../values');
3
4
 
4
5
  const QUERY = `
5
6
  query getFlexPlannedDispatches($deviceId: String!) {
@@ -19,8 +20,7 @@ function parseResponse(data) {
19
20
  start: d.start,
20
21
  end: d.end,
21
22
  type: d.type || null,
22
- energy_kwh: d.energyAddedKwh !== null && d.energyAddedKwh !== undefined
23
- ? parseFloat(d.energyAddedKwh) : null
23
+ energy_kwh: toNumber(d.energyAddedKwh)
24
24
  })),
25
25
  flex_planned_dispatches_count: dispatches.length,
26
26
  flex_planned_dispatches_error: null
@@ -2,6 +2,7 @@
2
2
  // Detects upcoming and active "Free Electricity" sessions (0p/kWh windows).
3
3
  // Requires account number and MPAN from account discovery.
4
4
  'use strict';
5
+ const { capStrings } = require('../values');
5
6
 
6
7
  const QUERY = `
7
8
  query getFreeElectricity($account: String!, $mpan: String!) {
@@ -50,6 +51,16 @@ function parseResponse(data) {
50
51
  };
51
52
  }
52
53
 
54
+ // Active flag for `nowMs` from the stored next session (state from parseResponse).
55
+ // Used on the node's 10 s tick so it switches at the session start/end, not at the next poll.
56
+ function activeFields(state, nowMs) {
57
+ if (!state.free_electricity_start || !state.free_electricity_end) return {};
58
+ return {
59
+ free_electricity_active: new Date(state.free_electricity_start).getTime() <= nowMs
60
+ && new Date(state.free_electricity_end).getTime() > nowMs,
61
+ };
62
+ }
63
+
53
64
  const defaultData = {
54
65
  free_electricity_active: null,
55
66
  free_electricity_available: null,
@@ -58,4 +69,5 @@ const defaultData = {
58
69
  free_electricity_error: null
59
70
  };
60
71
 
61
- module.exports = { buildQuery, parseResponse, defaultData };
72
+ // Text fields cut to the HA state limit (lib/values.js).
73
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), activeFields, defaultData };
@@ -1,5 +1,7 @@
1
1
  // lib/categories/gas.js
2
2
  'use strict';
3
+ const { toNumber, capStrings } = require('../values');
4
+ const { latestReading } = require('./electricity');
3
5
 
4
6
  // GasTariffType is a single object type (not a union) — direct field access, no fragments.
5
7
  const RATES_QUERY = `
@@ -52,10 +54,10 @@ function parseRatesResponse(data) {
52
54
  }
53
55
  const latest = agreements[0];
54
56
  const tariff = latest.tariff || {};
55
- // Kraken Float scalars can serialise as strings — coerce defensively
57
+ // Kraken Float scalars can serialise as strings; anything not a finite number is null
56
58
  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_unit_rate: toNumber(tariff.unitRate),
60
+ gas_standing_charge: toNumber(tariff.standingCharge),
59
61
  gas_tariff_code: tariff.productCode || null,
60
62
  gas_valid_from: latest.validFrom || null,
61
63
  gas_valid_to: latest.validTo || null,
@@ -69,7 +71,7 @@ function parseConsumptionResponse(data) {
69
71
  const meter = meterPoint ? (meterPoint.meters || [])[0] : null;
70
72
  const connection = meter ? meter.consumption : null;
71
73
  const edges = connection ? (connection.edges || []) : [];
72
- const entry = edges.length > 0 ? edges[edges.length - 1].node : null;
74
+ const entry = latestReading(edges); // skips a reading with no value
73
75
  if (!entry) {
74
76
  return {
75
77
  gas_consumption_kwh: null, gas_consumption_cost: null,
@@ -77,7 +79,7 @@ function parseConsumptionResponse(data) {
77
79
  };
78
80
  }
79
81
  return {
80
- gas_consumption_kwh: parseFloat(entry.value),
82
+ gas_consumption_kwh: toNumber(entry.value),
81
83
  gas_consumption_cost: null,
82
84
  gas_consumption_from: entry.startAt,
83
85
  gas_consumption_to: entry.endAt,
@@ -92,4 +94,9 @@ const defaultData = {
92
94
  gas_consumption_from: null, gas_consumption_to: null, gas_consumption_error: null
93
95
  };
94
96
 
95
- module.exports = { buildRatesQuery, buildConsumptionQuery, parseRatesResponse, parseConsumptionResponse, defaultData };
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,4 +1,5 @@
1
1
  'use strict';
2
+ const { toNumber, capStrings } = require('../values');
2
3
 
3
4
  const QUERY = `
4
5
  query getSmartMeterTelemetry($deviceId: String!, $start: DateTime!, $end: DateTime!) {
@@ -13,15 +14,21 @@ function buildQuery(smartMeterDeviceId) {
13
14
  return { query: QUERY, variables: { deviceId: smartMeterDeviceId, start, end } };
14
15
  }
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
+
16
23
  function parseResponse(data) {
17
24
  const readings = data.smartMeterTelemetry || [];
18
25
  const latest = readings.length > 0 ? readings[readings.length - 1] : null;
19
26
 
20
27
  return {
21
28
  // demand is in Watts from API — negative means exporting
22
- mini_demand_kw: latest && latest.demand != null ? parseFloat(latest.demand) / 1000 : null,
29
+ mini_demand_kw: latest ? toKilo(latest.demand) : null,
23
30
  // consumptionDelta is in Wh per half-hour period
24
- mini_consumption_delta_kwh: latest && latest.consumptionDelta != null ? parseFloat(latest.consumptionDelta) / 1000 : null,
31
+ mini_consumption_delta_kwh: latest ? toKilo(latest.consumptionDelta) : null,
25
32
  mini_read_at: latest ? latest.readAt ?? null : null,
26
33
  home_mini_error: null
27
34
  };
@@ -34,4 +41,5 @@ const defaultData = {
34
41
  home_mini_error: null
35
42
  };
36
43
 
37
- module.exports = { buildQuery, parseResponse, defaultData };
44
+ // Text fields cut to the HA state limit (lib/values.js).
45
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), defaultData };
@@ -1,10 +1,29 @@
1
1
  // lib/categories/intelligent.js
2
2
  'use strict';
3
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');
4
8
 
5
9
  const WEEKDAYS = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY'];
6
10
 
7
- const DEVICES_QUERY = `
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 `
8
27
  query getDevices($account: String!) {
9
28
  devices(accountNumber: $account) {
10
29
  id
@@ -19,14 +38,19 @@ query getDevices($account: String!) {
19
38
  }
20
39
  }
21
40
  # Separate alias: the Charge Cap field is non-null, so an error on it nulls its parent
22
- # selection. Keeping it apart stops such an error from blanking the schedules above.
41
+ # selection (preferences is nullable). Keeping it apart stops such an error from
42
+ # blanking the schedules above.
23
43
  chargeCap: preferences {
24
44
  ... on SmartFlexDevicePreferences {
25
45
  isChargingDurationCapped
26
46
  }
27
- }
47
+ }${withStatus ? STATUS_SELECTION : ''}
28
48
  }
29
49
  }`;
50
+ }
51
+
52
+ const DEVICES_QUERY = devicesQuery(true);
53
+ const DEVICES_QUERY_NO_STATUS = devicesQuery(false);
30
54
 
31
55
  const DISPATCH_QUERY = `
32
56
  query getDispatches($deviceId: String!) {
@@ -35,30 +59,60 @@ query getDispatches($deviceId: String!) {
35
59
  }
36
60
  }`;
37
61
 
38
- function buildDevicesQuery(account) {
39
- return { query: DEVICES_QUERY, variables: { account } };
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 } };
40
65
  }
41
66
 
42
67
  function buildDispatchQuery(deviceId) {
43
68
  return { query: DISPATCH_QUERY, variables: { deviceId } };
44
69
  }
45
70
 
46
- function extractEvDevice(devices) {
47
- return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
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;
48
77
  }
49
78
 
50
79
  // isChargingDurationCapped: ENABLED | DISABLED | NOT_APPLICABLE (live-verified 2026-09-29).
51
80
  // Anything other than ENABLED/DISABLED (incl. missing) -> null.
52
- function extractChargeCap(devices) {
53
- const ev = extractEvDevice(devices);
81
+ function extractChargeCap(devices, preferredId) {
82
+ const ev = extractEvDevice(devices, preferredId);
54
83
  const raw = ev && ev.chargeCap ? ev.chargeCap.isChargingDurationCapped : undefined;
55
84
  if (raw === 'ENABLED') return true;
56
85
  if (raw === 'DISABLED') return false;
57
86
  return null;
58
87
  }
59
88
 
60
- function extractPreferences(devices) {
61
- const ev = extractEvDevice(devices);
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);
62
116
  if (!ev || !ev.preferences) return { confirmed_limit: 80, confirmed_time: '07:30' };
63
117
 
64
118
  const schedules = ev.preferences.schedules || [];
@@ -67,26 +121,35 @@ function extractPreferences(devices) {
67
121
 
68
122
  // time may arrive as 'HH:MM:SS' or 'HH:MM' — normalise to 'HH:MM'
69
123
  const time = weekday.time ? weekday.time.substring(0, 5) : '07:30';
70
- // parseFloat: '' / ' ' / 'abc' give NaN (Number('') would give 0); a 0% target is never real
71
- const maxValue = weekday.max == null ? NaN : parseFloat(weekday.max);
124
+ // toNumber: '' / ' ' / 'abc' give null (Number('') would give 0); a 0% target is never real
125
+ const maxValue = toNumber(weekday.max);
72
126
  return {
73
127
  // Float scalars can arrive as JSON strings; this value is sent back in setDevicePreferences
74
- confirmed_limit: Number.isFinite(maxValue) && maxValue > 0 ? maxValue : 80,
128
+ confirmed_limit: maxValue !== null && maxValue > 0 ? maxValue : 80,
75
129
  confirmed_time: time,
76
130
  };
77
131
  }
78
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
+
79
140
  // data must be merged result: { devices: [...], flexPlannedDispatches: [...] }
80
- function parseResponse(data, { tz, serverTz }) {
141
+ // evId: the EV discovery picked (optional); see extractEvDevice.
142
+ function parseResponse(data, { tz, serverTz, evId }) {
81
143
  const devices = data.devices || [];
82
144
  const dispatches = data.flexPlannedDispatches || [];
83
- const prefs = extractPreferences(devices);
145
+ const prefs = extractPreferences(devices, evId);
84
146
 
85
147
  const now = new Date();
86
148
  const active = dispatches.filter(s => new Date(s.end) > now);
87
149
  const nextSlot = active[0] || null;
88
150
  // energyAddedKwh arrives from live API as a string — coerce before arithmetic
89
- const totalEnergy = active.reduce((sum, s) => sum + (parseFloat(s.energyAddedKwh) || 0), 0);
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
90
153
 
91
154
  function conv(dt) { return dt ? convertToTimezone(dt, tz) : null; }
92
155
  function locale(dt) { return dt ? convertToTimezone(dt, serverTz) : null; }
@@ -94,12 +157,14 @@ function parseResponse(data, { tz, serverTz }) {
94
157
  return {
95
158
  confirmed_limit: prefs.confirmed_limit,
96
159
  confirmed_time: prefs.confirmed_time,
97
- charge_cap: extractChargeCap(devices),
160
+ charge_cap: extractChargeCap(devices, evId),
161
+ boosting: extractBoosting(devices, evId),
162
+ device_state: extractDeviceState(devices, evId),
98
163
  next_start: nextSlot ? conv(nextSlot.start) : null,
99
164
  next_start_raw: nextSlot ? nextSlot.start : null,
100
165
  next_start_locale: nextSlot ? locale(nextSlot.start) : null,
101
166
  total_energy: parseFloat(totalEnergy.toFixed(2)),
102
- next_kwh: nextSlot && nextSlot.energyAddedKwh != null ? parseFloat(nextSlot.energyAddedKwh).toFixed(2) : '0',
167
+ next_kwh: nextKwh(nextSlot),
103
168
  next_source: nextSlot ? (nextSlot.type || 'unknown').toLowerCase() : 'unknown',
104
169
  slot1_start: active[0] ? conv(active[0].start) : null,
105
170
  slot1_end: active[0] ? conv(active[0].end) : null,
@@ -140,7 +205,7 @@ function slotsChanged(previous, fresh, nowMs = Date.now()) {
140
205
  }
141
206
 
142
207
  const defaultData = {
143
- confirmed_limit: 80, confirmed_time: '07:30', charge_cap: null,
208
+ confirmed_limit: 80, confirmed_time: '07:30', charge_cap: null, boosting: null, device_state: null,
144
209
  next_start: null, next_start_raw: null, next_start_locale: null,
145
210
  total_energy: 0, next_kwh: '0', next_source: 'unknown',
146
211
  slot1_start: null, slot1_end: null, slot2_start: null, slot2_end: null,
@@ -152,4 +217,5 @@ const defaultData = {
152
217
  _activeSlots: []
153
218
  };
154
219
 
155
- module.exports = { buildDevicesQuery, buildDispatchQuery, extractEvDevice, parseResponse, slotsChanged, defaultData };
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 };
@@ -1,10 +1,11 @@
1
1
  // lib/categories/octoplus.js
2
2
  'use strict';
3
+ const { capStrings } = require('../values');
3
4
 
4
5
  const QUERY = `
5
6
  query getOctoplusInfo($account: String!) {
6
7
  octoplusAccountInfo(accountNumber: $account) {
7
- isOctoplusEnrolled enrollmentStatus isLoyaltyPointsUser
8
+ enrollmentStatus isLoyaltyPointsUser
8
9
  }
9
10
  }`;
10
11
 
@@ -15,7 +16,8 @@ function buildQuery(account) {
15
16
  function parseResponse(data) {
16
17
  const info = data.octoplusAccountInfo || {};
17
18
  return {
18
- octoplus_enrolled: info.isOctoplusEnrolled ?? null,
19
+ // isOctoplusEnrolled is deprecated by Kraken, so derive it from enrollmentStatus.
20
+ octoplus_enrolled: info.enrollmentStatus ? info.enrollmentStatus === 'ENROLLED' : null,
19
21
  octoplus_enrollment_status: info.enrollmentStatus || null,
20
22
  octoplus_loyalty_points_user: info.isLoyaltyPointsUser ?? null,
21
23
  octoplus_error: null
@@ -29,4 +31,5 @@ const defaultData = {
29
31
  octoplus_error: null
30
32
  };
31
33
 
32
- module.exports = { buildQuery, parseResponse, defaultData };
34
+ // Text fields cut to the HA state limit (lib/values.js).
35
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), defaultData };
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ const { capStrings } = require('../values');
2
3
 
3
4
  // savingSessions moved to api.backend.octopus.energy — the field was removed
4
5
  // from api.octopus.energy. Requires User-Agent header (set in lib/graphql.js)
@@ -55,10 +56,23 @@ function parseResponse(data) {
55
56
  };
56
57
  }
57
58
 
59
+ // Window/active flags for `nowMs` from the stored next session (state from parseResponse).
60
+ // Used on the node's 10 s tick so they switch at the session start/end, not at the next poll.
61
+ function activeFields(state, nowMs) {
62
+ if (!state.saving_session_start || !state.saving_session_end) return {};
63
+ const inWindow = new Date(state.saving_session_start).getTime() <= nowMs
64
+ && new Date(state.saving_session_end).getTime() > nowMs;
65
+ return {
66
+ saving_session_window_active: inWindow,
67
+ saving_session_active: inWindow && state.saving_session_joined === true,
68
+ };
69
+ }
70
+
58
71
  const defaultData = {
59
72
  saving_session_available: null, saving_session_start: null, saving_session_end: null,
60
73
  saving_session_joined: null, saving_session_window_active: null, saving_session_active: null,
61
74
  saving_sessions_error: null
62
75
  };
63
76
 
64
- module.exports = { buildQuery, parseResponse, defaultData };
77
+ // Text fields cut to the HA state limit (lib/values.js).
78
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), activeFields, defaultData };
@@ -0,0 +1,95 @@
1
+ // lib/categories/smartflex-inverter.js
2
+ 'use strict';
3
+ const { toNumber, capStrings } = require('../values');
4
+
5
+ // v1.7.0 EXPERIMENTAL: SmartFlex inverter details and live telemetry.
6
+ // Field names come from live schema introspection (6 Oct 2026), but no account we can
7
+ // test has an inverter, so the response shape is NOT live-verified. This category is
8
+ // off by default and only runs when the editor option is ticked.
9
+ // Kraken sends Decimal fields as strings, so every number goes through toNumber().
10
+
11
+ const QUERY = `
12
+ query smartflexInverter($account: String!) {
13
+ devices(accountNumber: $account) {
14
+ __typename
15
+ id
16
+ ... on SmartFlexInverter {
17
+ make model
18
+ details { solar { peakSolarPowerInKw } }
19
+ telemetry {
20
+ inverter { connectionStatus powerInKw }
21
+ battery { connectionStatus powerInKw stateOfCharge }
22
+ solar { powerInKw }
23
+ grid { powerInKw }
24
+ site { consumptionInKw exportInKw }
25
+ }
26
+ }
27
+ }
28
+ }`;
29
+
30
+ // Connection status values treated as online. The enum has not been seen live.
31
+ const ONLINE_STATES = ['CONNECTED', 'ONLINE'];
32
+
33
+ function buildQuery(account) {
34
+ return { query: QUERY, variables: { account } };
35
+ }
36
+
37
+ // The schema may return a single reading or a list of readings; use the latest.
38
+ function latest(x) {
39
+ if (Array.isArray(x)) return x.length ? (x[x.length - 1] || {}) : {};
40
+ return x || {};
41
+ }
42
+
43
+ function pickDevice(devices, deviceId) {
44
+ return devices.find(d => d && deviceId && d.id === deviceId)
45
+ || devices.find(d => d && d.__typename === 'SmartFlexInverter')
46
+ || null;
47
+ }
48
+
49
+ function parseResponse(data, deviceId) {
50
+ const device = pickDevice((data && data.devices) || [], deviceId);
51
+ if (!device) return { ...defaultData };
52
+
53
+ const details = latest(device.details);
54
+ const telemetry = latest(device.telemetry);
55
+ const inv = latest(telemetry.inverter);
56
+ const battery = latest(telemetry.battery);
57
+ const solar = latest(telemetry.solar);
58
+ const grid = latest(telemetry.grid);
59
+ const site = latest(telemetry.site);
60
+ const connection = inv.connectionStatus || null;
61
+
62
+ return {
63
+ inverter_make: device.make || null,
64
+ inverter_model: device.model || null,
65
+ solar_peak_kw: toNumber(latest(details.solar).peakSolarPowerInKw),
66
+ inverter_power_kw: toNumber(inv.powerInKw),
67
+ inverter_connection_status: connection,
68
+ inverter_online: connection === null ? null : ONLINE_STATES.includes(connection),
69
+ home_battery_power_kw: toNumber(battery.powerInKw),
70
+ home_battery_soc: toNumber(battery.stateOfCharge),
71
+ solar_power_kw: toNumber(solar.powerInKw),
72
+ grid_power_kw: toNumber(grid.powerInKw),
73
+ site_consumption_kw: toNumber(site.consumptionInKw),
74
+ site_export_kw: toNumber(site.exportInKw),
75
+ smartflex_inverter_error: null,
76
+ };
77
+ }
78
+
79
+ const defaultData = {
80
+ inverter_make: null,
81
+ inverter_model: null,
82
+ solar_peak_kw: null,
83
+ inverter_power_kw: null,
84
+ inverter_connection_status: null,
85
+ inverter_online: null,
86
+ home_battery_power_kw: null,
87
+ home_battery_soc: null,
88
+ solar_power_kw: null,
89
+ grid_power_kw: null,
90
+ site_consumption_kw: null,
91
+ site_export_kw: null,
92
+ smartflex_inverter_error: null,
93
+ };
94
+
95
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), defaultData };