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,35 +1,36 @@
1
- // lib/categories/completed-dispatches.js
2
- 'use strict';
3
-
4
- const QUERY = `
5
- query getCompletedDispatches($account: String!) {
6
- completedDispatches(accountNumber: $account) {
7
- start end delta meta { source location }
8
- }
9
- }`;
10
-
11
- function buildQuery(account) {
12
- return { query: QUERY, variables: { account } };
13
- }
14
-
15
- function parseResponse(data) {
16
- const dispatches = data.completedDispatches || [];
17
- return {
18
- completed_dispatches: dispatches.map(d => ({
19
- start: d.start,
20
- end: d.end,
21
- delta_kwh: d.delta !== null && d.delta !== undefined ? parseFloat(d.delta) : null,
22
- source: (d.meta || {}).source || null
23
- })),
24
- completed_dispatches_count: dispatches.length,
25
- completed_dispatches_error: null
26
- };
27
- }
28
-
29
- const defaultData = {
30
- completed_dispatches: [],
31
- completed_dispatches_count: 0,
32
- completed_dispatches_error: null
33
- };
34
-
35
- module.exports = { buildQuery, parseResponse, defaultData };
1
+ // lib/categories/completed-dispatches.js
2
+ 'use strict';
3
+ const { toNumber } = require('../values');
4
+
5
+ const QUERY = `
6
+ query getCompletedDispatches($account: String!) {
7
+ completedDispatches(accountNumber: $account) {
8
+ start end delta meta { source location }
9
+ }
10
+ }`;
11
+
12
+ function buildQuery(account) {
13
+ return { query: QUERY, variables: { account } };
14
+ }
15
+
16
+ function parseResponse(data) {
17
+ const dispatches = data.completedDispatches || [];
18
+ return {
19
+ completed_dispatches: dispatches.map(d => ({
20
+ start: d.start,
21
+ end: d.end,
22
+ delta_kwh: toNumber(d.delta),
23
+ source: (d.meta || {}).source || null
24
+ })),
25
+ completed_dispatches_count: dispatches.length,
26
+ completed_dispatches_error: null
27
+ };
28
+ }
29
+
30
+ const defaultData = {
31
+ completed_dispatches: [],
32
+ completed_dispatches_count: 0,
33
+ completed_dispatches_error: null
34
+ };
35
+
36
+ module.exports = { buildQuery, parseResponse, defaultData };
@@ -1,146 +1,156 @@
1
- // lib/categories/electricity.js
2
- 'use strict';
3
-
4
- const RATES_QUERY = `
5
- query getElectricityRates($account: String!) {
6
- account(accountNumber: $account) {
7
- electricityAgreements {
8
- validFrom validTo
9
- tariff {
10
- ... on TariffType { productCode standingCharge }
11
- ... on StandardTariff { productCode standingCharge unitRate }
12
- ... on HalfHourlyTariff { productCode standingCharge }
13
- ... on DayNightTariff { productCode standingCharge dayRate nightRate }
14
- ... on FourRateEvTariff { productCode standingCharge dayRate nightRate evDevicePeakRate evDeviceOffPeakRate }
15
- ... on PrepayTariff { productCode standingCharge unitRate }
16
- }
17
- }
18
- }
19
- }`;
20
-
21
- const CONSUMPTION_QUERY = `
22
- query getElectricityConsumption($account: String!, $startAt: DateTime!, $timezone: String!) {
23
- account(accountNumber: $account) {
24
- properties {
25
- electricityMeterPoints {
26
- mpan
27
- meters {
28
- consumption(startAt: $startAt, last: 1, grouping: DAY, timezone: $timezone) {
29
- edges { node { startAt endAt value } }
30
- }
31
- }
32
- }
33
- }
34
- }
35
- }`;
36
-
37
- function buildRatesQuery(account) {
38
- return { query: RATES_QUERY, variables: { account } };
39
- }
40
-
41
- function buildConsumptionQuery(account, timezone) {
42
- const tz = timezone || 'UTC';
43
- const startAt = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
44
- return { query: CONSUMPTION_QUERY, variables: { account, startAt, timezone: tz } };
45
- }
46
-
47
- // Tariff productCodes containing "OUTGOING" are export agreements (e.g. AGILE-OUTGOING-19-05-13).
48
- // We surface both import and export tariff metadata as separate fields.
49
- function parseRatesResponse(data) {
50
- const all = (data.account || {}).electricityAgreements || [];
51
- const isExport = (a) => ((a.tariff || {}).productCode || '').includes('OUTGOING');
52
- const importAgreements = all.filter(a => !isExport(a));
53
- const exportAgreements = all.filter(isExport);
54
-
55
- const fieldsFor = (prefix, agreements) => {
56
- const latest = agreements[0];
57
- const tariff = (latest && latest.tariff) || {};
58
- // Kraken Float scalars can serialise as strings — coerce defensively
59
- return {
60
- [`${prefix}_unit_rate`]: tariff.unitRate != null ? parseFloat(tariff.unitRate) : null,
61
- [`${prefix}_standing_charge`]: tariff.standingCharge != null ? parseFloat(tariff.standingCharge) : null,
62
- [`${prefix}_tariff_code`]: tariff.productCode || null,
63
- [`${prefix}_valid_from`]: (latest && latest.validFrom) || null,
64
- [`${prefix}_valid_to`]: (latest && latest.validTo) || null,
65
- // v1.5 rate-band fields — null on tariffs that don't expose them
66
- [`${prefix}_day_rate`]: tariff.dayRate != null ? parseFloat(tariff.dayRate) : null,
67
- [`${prefix}_night_rate`]: tariff.nightRate != null ? parseFloat(tariff.nightRate) : null,
68
- [`${prefix}_ev_peak_rate`]: tariff.evDevicePeakRate != null ? parseFloat(tariff.evDevicePeakRate) : null,
69
- [`${prefix}_ev_off_peak_rate`]: tariff.evDeviceOffPeakRate != null ? parseFloat(tariff.evDeviceOffPeakRate) : null,
70
- };
71
- };
72
-
73
- return {
74
- ...fieldsFor('electricity', importAgreements),
75
- ...fieldsFor('electricity_export', exportAgreements),
76
- electricity_rates_error: null
77
- };
78
- }
79
-
80
- // Picks the latest consumption edge for a given MPAN out of the query response.
81
- function _findEntryForMpan(data, mpan) {
82
- if (!mpan) return null;
83
- const points = ((data.account || {}).properties || [])[0];
84
- const meterPoints = points ? (points.electricityMeterPoints || []) : [];
85
- const mp = meterPoints.find(p => p.mpan === mpan);
86
- if (!mp) return null;
87
- const meter = (mp.meters || [])[0];
88
- const edges = ((meter && meter.consumption) || {}).edges || [];
89
- return edges.length > 0 ? edges[edges.length - 1].node : null;
90
- }
91
-
92
- // Parses both import and export consumption from one response, given both MPANs.
93
- // Either MPAN may be null on accounts without that direction — the corresponding
94
- // fields will be null without affecting the other direction.
95
- function parseConsumptionResponse(data, importMpan, exportMpan) {
96
- const importEntry = _findEntryForMpan(data, importMpan);
97
- const exportEntry = _findEntryForMpan(data, exportMpan);
98
- return {
99
- electricity_consumption_kwh: importEntry ? parseFloat(importEntry.value) : null,
100
- electricity_consumption_cost: null,
101
- electricity_consumption_from: importEntry ? importEntry.startAt : null,
102
- electricity_consumption_to: importEntry ? importEntry.endAt : null,
103
- electricity_export_consumption_kwh: exportEntry ? parseFloat(exportEntry.value) : null,
104
- electricity_export_consumption_from: exportEntry ? exportEntry.startAt : null,
105
- electricity_export_consumption_to: exportEntry ? exportEntry.endAt : null,
106
- electricity_consumption_error: null
107
- };
108
- }
109
-
110
- const defaultData = {
111
- electricity_unit_rate: null,
112
- electricity_standing_charge: null,
113
- electricity_tariff_code: null,
114
- electricity_valid_from: null,
115
- electricity_valid_to: null,
116
- electricity_day_rate: null,
117
- electricity_night_rate: null,
118
- electricity_ev_peak_rate: null,
119
- electricity_ev_off_peak_rate: null,
120
- electricity_export_unit_rate: null,
121
- electricity_export_standing_charge: null,
122
- electricity_export_tariff_code: null,
123
- electricity_export_valid_from: null,
124
- electricity_export_valid_to: null,
125
- electricity_export_day_rate: null,
126
- electricity_export_night_rate: null,
127
- electricity_export_ev_peak_rate: null,
128
- electricity_export_ev_off_peak_rate: null,
129
- electricity_rates_error: null,
130
- electricity_consumption_kwh: null,
131
- electricity_consumption_cost: null,
132
- electricity_consumption_from: null,
133
- electricity_consumption_to: null,
134
- electricity_export_consumption_kwh: null,
135
- electricity_export_consumption_from: null,
136
- electricity_export_consumption_to: null,
137
- electricity_consumption_error: null
138
- };
139
-
140
- module.exports = {
141
- buildRatesQuery,
142
- buildConsumptionQuery,
143
- parseRatesResponse,
144
- parseConsumptionResponse,
145
- defaultData
146
- };
1
+ // lib/categories/electricity.js
2
+ 'use strict';
3
+ const { toNumber, capStrings } = require('../values');
4
+
5
+ const RATES_QUERY = `
6
+ query getElectricityRates($account: String!) {
7
+ account(accountNumber: $account) {
8
+ electricityAgreements {
9
+ validFrom validTo
10
+ tariff {
11
+ ... on TariffType { productCode standingCharge }
12
+ ... on StandardTariff { productCode standingCharge unitRate }
13
+ ... on HalfHourlyTariff { productCode standingCharge }
14
+ ... on DayNightTariff { productCode standingCharge dayRate nightRate }
15
+ ... on FourRateEvTariff { productCode standingCharge dayRate nightRate evDevicePeakRate evDeviceOffPeakRate }
16
+ ... on PrepayTariff { productCode standingCharge unitRate }
17
+ }
18
+ }
19
+ }
20
+ }`;
21
+
22
+ const CONSUMPTION_QUERY = `
23
+ query getElectricityConsumption($account: String!, $startAt: DateTime!, $timezone: String!) {
24
+ account(accountNumber: $account) {
25
+ properties {
26
+ electricityMeterPoints {
27
+ mpan
28
+ meters {
29
+ consumption(startAt: $startAt, last: 1, grouping: DAY, timezone: $timezone) {
30
+ edges { node { startAt endAt value } }
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }`;
37
+
38
+ function buildRatesQuery(account) {
39
+ return { query: RATES_QUERY, variables: { account } };
40
+ }
41
+
42
+ function buildConsumptionQuery(account, timezone) {
43
+ const tz = timezone || 'UTC';
44
+ const startAt = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString();
45
+ return { query: CONSUMPTION_QUERY, variables: { account, startAt, timezone: tz } };
46
+ }
47
+
48
+ // Tariff productCodes containing "OUTGOING" are export agreements (e.g. AGILE-OUTGOING-19-05-13).
49
+ // We surface both import and export tariff metadata as separate fields.
50
+ function parseRatesResponse(data) {
51
+ const all = (data.account || {}).electricityAgreements || [];
52
+ const isExport = (a) => ((a.tariff || {}).productCode || '').includes('OUTGOING');
53
+ const importAgreements = all.filter(a => !isExport(a));
54
+ const exportAgreements = all.filter(isExport);
55
+
56
+ const fieldsFor = (prefix, agreements) => {
57
+ const latest = agreements[0];
58
+ const tariff = (latest && latest.tariff) || {};
59
+ // Kraken Float scalars can serialise as strings; anything not a finite number is null
60
+ return {
61
+ [`${prefix}_unit_rate`]: toNumber(tariff.unitRate),
62
+ [`${prefix}_standing_charge`]: toNumber(tariff.standingCharge),
63
+ [`${prefix}_tariff_code`]: tariff.productCode || null,
64
+ [`${prefix}_valid_from`]: (latest && latest.validFrom) || null,
65
+ [`${prefix}_valid_to`]: (latest && latest.validTo) || null,
66
+ // v1.5 rate-band fields — null on tariffs that don't expose them
67
+ [`${prefix}_day_rate`]: toNumber(tariff.dayRate),
68
+ [`${prefix}_night_rate`]: toNumber(tariff.nightRate),
69
+ [`${prefix}_ev_peak_rate`]: toNumber(tariff.evDevicePeakRate),
70
+ [`${prefix}_ev_off_peak_rate`]: toNumber(tariff.evDeviceOffPeakRate),
71
+ };
72
+ };
73
+
74
+ return {
75
+ ...fieldsFor('electricity', importAgreements),
76
+ ...fieldsFor('electricity_export', exportAgreements),
77
+ electricity_rates_error: null
78
+ };
79
+ }
80
+
81
+ // Picks the latest consumption reading for a given MPAN out of the query response.
82
+ function _findEntryForMpan(data, mpan) {
83
+ if (!mpan) return null;
84
+ const points = ((data.account || {}).properties || [])[0];
85
+ const meterPoints = points ? (points.electricityMeterPoints || []) : [];
86
+ const mp = meterPoints.find(p => p.mpan === mpan);
87
+ if (!mp) return null;
88
+ const meter = (mp.meters || [])[0];
89
+ const edges = ((meter && meter.consumption) || {}).edges || [];
90
+ return latestReading(edges);
91
+ }
92
+
93
+ // The last reading whose value is a number. One with no value (null while Octopus is still
94
+ // collecting it) is skipped, so the totals never show NaN.
95
+ function latestReading(edges) {
96
+ const readings = edges.map((e) => e && e.node).filter((n) => n && toNumber(n.value) !== null);
97
+ return readings.length > 0 ? readings[readings.length - 1] : null;
98
+ }
99
+
100
+ // Parses both import and export consumption from one response, given both MPANs.
101
+ // Either MPAN may be null on accounts without that direction — the corresponding
102
+ // fields will be null without affecting the other direction.
103
+ function parseConsumptionResponse(data, importMpan, exportMpan) {
104
+ const importEntry = _findEntryForMpan(data, importMpan);
105
+ const exportEntry = _findEntryForMpan(data, exportMpan);
106
+ return {
107
+ electricity_consumption_kwh: importEntry ? toNumber(importEntry.value) : null,
108
+ electricity_consumption_cost: null,
109
+ electricity_consumption_from: importEntry ? importEntry.startAt : null,
110
+ electricity_consumption_to: importEntry ? importEntry.endAt : null,
111
+ electricity_export_consumption_kwh: exportEntry ? toNumber(exportEntry.value) : null,
112
+ electricity_export_consumption_from: exportEntry ? exportEntry.startAt : null,
113
+ electricity_export_consumption_to: exportEntry ? exportEntry.endAt : null,
114
+ electricity_consumption_error: null
115
+ };
116
+ }
117
+
118
+ const defaultData = {
119
+ electricity_unit_rate: null,
120
+ electricity_standing_charge: null,
121
+ electricity_tariff_code: null,
122
+ electricity_valid_from: null,
123
+ electricity_valid_to: null,
124
+ electricity_day_rate: null,
125
+ electricity_night_rate: null,
126
+ electricity_ev_peak_rate: null,
127
+ electricity_ev_off_peak_rate: null,
128
+ electricity_export_unit_rate: null,
129
+ electricity_export_standing_charge: null,
130
+ electricity_export_tariff_code: null,
131
+ electricity_export_valid_from: null,
132
+ electricity_export_valid_to: null,
133
+ electricity_export_day_rate: null,
134
+ electricity_export_night_rate: null,
135
+ electricity_export_ev_peak_rate: null,
136
+ electricity_export_ev_off_peak_rate: null,
137
+ electricity_rates_error: null,
138
+ electricity_consumption_kwh: null,
139
+ electricity_consumption_cost: null,
140
+ electricity_consumption_from: null,
141
+ electricity_consumption_to: null,
142
+ electricity_export_consumption_kwh: null,
143
+ electricity_export_consumption_from: null,
144
+ electricity_export_consumption_to: null,
145
+ electricity_consumption_error: null
146
+ };
147
+
148
+ module.exports = {
149
+ buildRatesQuery,
150
+ buildConsumptionQuery,
151
+ // Text fields cut to the HA state limit (lib/values.js).
152
+ parseRatesResponse: capStrings(parseRatesResponse),
153
+ parseConsumptionResponse: capStrings(parseConsumptionResponse),
154
+ latestReading,
155
+ defaultData
156
+ };
@@ -1,36 +1,36 @@
1
- // lib/categories/flex-planned-dispatches.js
2
- 'use strict';
3
-
4
- const QUERY = `
5
- query getFlexPlannedDispatches($deviceId: String!) {
6
- flexPlannedDispatches(deviceId: $deviceId) {
7
- start end type energyAddedKwh
8
- }
9
- }`;
10
-
11
- function buildQuery(deviceId) {
12
- return { query: QUERY, variables: { deviceId } };
13
- }
14
-
15
- function parseResponse(data) {
16
- const dispatches = data.flexPlannedDispatches || [];
17
- return {
18
- flex_planned_dispatches: dispatches.map(d => ({
19
- start: d.start,
20
- end: d.end,
21
- type: d.type || null,
22
- energy_kwh: d.energyAddedKwh !== null && d.energyAddedKwh !== undefined
23
- ? parseFloat(d.energyAddedKwh) : null
24
- })),
25
- flex_planned_dispatches_count: dispatches.length,
26
- flex_planned_dispatches_error: null
27
- };
28
- }
29
-
30
- const defaultData = {
31
- flex_planned_dispatches: [],
32
- flex_planned_dispatches_count: 0,
33
- flex_planned_dispatches_error: null
34
- };
35
-
36
- module.exports = { buildQuery, parseResponse, defaultData };
1
+ // lib/categories/flex-planned-dispatches.js
2
+ 'use strict';
3
+ const { toNumber } = require('../values');
4
+
5
+ const QUERY = `
6
+ query getFlexPlannedDispatches($deviceId: String!) {
7
+ flexPlannedDispatches(deviceId: $deviceId) {
8
+ start end type energyAddedKwh
9
+ }
10
+ }`;
11
+
12
+ function buildQuery(deviceId) {
13
+ return { query: QUERY, variables: { deviceId } };
14
+ }
15
+
16
+ function parseResponse(data) {
17
+ const dispatches = data.flexPlannedDispatches || [];
18
+ return {
19
+ flex_planned_dispatches: dispatches.map(d => ({
20
+ start: d.start,
21
+ end: d.end,
22
+ type: d.type || null,
23
+ energy_kwh: toNumber(d.energyAddedKwh)
24
+ })),
25
+ flex_planned_dispatches_count: dispatches.length,
26
+ flex_planned_dispatches_error: null
27
+ };
28
+ }
29
+
30
+ const defaultData = {
31
+ flex_planned_dispatches: [],
32
+ flex_planned_dispatches_count: 0,
33
+ flex_planned_dispatches_error: null
34
+ };
35
+
36
+ module.exports = { buildQuery, parseResponse, defaultData };
@@ -1,61 +1,73 @@
1
- // lib/categories/free-electricity.js
2
- // Detects upcoming and active "Free Electricity" sessions (0p/kWh windows).
3
- // Requires account number and MPAN from account discovery.
4
- 'use strict';
5
-
6
- const QUERY = `
7
- query getFreeElectricity($account: String!, $mpan: String!) {
8
- customerFlexibilityCampaignEvents(
9
- accountNumber: $account,
10
- supplyPointIdentifier: $mpan,
11
- campaignSlug: "free_electricity",
12
- first: 50
13
- ) {
14
- edges {
15
- node {
16
- code
17
- startAt
18
- endAt
19
- }
20
- }
21
- }
22
- }`;
23
-
24
- function buildQuery(account, mpan) {
25
- return { query: QUERY, variables: { account, mpan } };
26
- }
27
-
28
- function parseResponse(data) {
29
- const now = new Date();
30
-
31
- const edges = ((data.customerFlexibilityCampaignEvents || {}).edges) || [];
32
- const sessions = edges.map(e => ({ startAt: e.node.startAt, endAt: e.node.endAt }));
33
-
34
- // Filter to sessions not yet ended, sort by startAt ascending, take the first
35
- const future = sessions
36
- .filter(s => new Date(s.endAt) > now)
37
- .sort((a, b) => new Date(a.startAt) - new Date(b.startAt));
38
-
39
- const next = future[0] || null;
40
-
41
- const active = next !== null && new Date(next.startAt) <= now && new Date(next.endAt) > now;
42
- const available = next !== null;
43
-
44
- return {
45
- free_electricity_active: active,
46
- free_electricity_available: available,
47
- free_electricity_start: next ? next.startAt : null,
48
- free_electricity_end: next ? next.endAt : null,
49
- free_electricity_error: null
50
- };
51
- }
52
-
53
- const defaultData = {
54
- free_electricity_active: null,
55
- free_electricity_available: null,
56
- free_electricity_start: null,
57
- free_electricity_end: null,
58
- free_electricity_error: null
59
- };
60
-
61
- module.exports = { buildQuery, parseResponse, defaultData };
1
+ // lib/categories/free-electricity.js
2
+ // Detects upcoming and active "Free Electricity" sessions (0p/kWh windows).
3
+ // Requires account number and MPAN from account discovery.
4
+ 'use strict';
5
+ const { capStrings } = require('../values');
6
+
7
+ const QUERY = `
8
+ query getFreeElectricity($account: String!, $mpan: String!) {
9
+ customerFlexibilityCampaignEvents(
10
+ accountNumber: $account,
11
+ supplyPointIdentifier: $mpan,
12
+ campaignSlug: "free_electricity",
13
+ first: 50
14
+ ) {
15
+ edges {
16
+ node {
17
+ code
18
+ startAt
19
+ endAt
20
+ }
21
+ }
22
+ }
23
+ }`;
24
+
25
+ function buildQuery(account, mpan) {
26
+ return { query: QUERY, variables: { account, mpan } };
27
+ }
28
+
29
+ function parseResponse(data) {
30
+ const now = new Date();
31
+
32
+ const edges = ((data.customerFlexibilityCampaignEvents || {}).edges) || [];
33
+ const sessions = edges.map(e => ({ startAt: e.node.startAt, endAt: e.node.endAt }));
34
+
35
+ // Filter to sessions not yet ended, sort by startAt ascending, take the first
36
+ const future = sessions
37
+ .filter(s => new Date(s.endAt) > now)
38
+ .sort((a, b) => new Date(a.startAt) - new Date(b.startAt));
39
+
40
+ const next = future[0] || null;
41
+
42
+ const active = next !== null && new Date(next.startAt) <= now && new Date(next.endAt) > now;
43
+ const available = next !== null;
44
+
45
+ return {
46
+ free_electricity_active: active,
47
+ free_electricity_available: available,
48
+ free_electricity_start: next ? next.startAt : null,
49
+ free_electricity_end: next ? next.endAt : null,
50
+ free_electricity_error: null
51
+ };
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
+
64
+ const defaultData = {
65
+ free_electricity_active: null,
66
+ free_electricity_available: null,
67
+ free_electricity_start: null,
68
+ free_electricity_end: null,
69
+ free_electricity_error: null
70
+ };
71
+
72
+ // Text fields cut to the HA state limit (lib/values.js).
73
+ module.exports = { buildQuery, parseResponse: capStrings(parseResponse), activeFields, defaultData };