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.
- package/CHANGELOG.md +129 -19
- package/README.md +386 -156
- package/examples/basic-monitoring.json +1 -1
- package/examples/boost-on-cheap-or-surplus.json +171 -0
- package/examples/charging-and-error-alerts.json +95 -0
- package/examples/cheapest-window-planner.json +165 -0
- package/examples/daily-charging-summary.json +165 -0
- package/examples/ha-dashboard.yaml +67 -2
- package/examples/mqtt-integration.json +1 -1
- package/examples/node-red-dashboard-flow.json +92 -2
- package/examples/set-preferences.json +1 -1
- package/lib/active-now.js +33 -0
- package/lib/auth.js +6 -1
- package/lib/boost.js +85 -0
- package/lib/categories/account.js +3 -3
- package/lib/categories/applicable-rates.js +29 -19
- package/lib/categories/completed-dispatches.js +2 -1
- package/lib/categories/electricity.js +23 -13
- package/lib/categories/flex-planned-dispatches.js +2 -2
- package/lib/categories/free-electricity.js +13 -1
- package/lib/categories/gas.js +13 -6
- package/lib/categories/home-mini.js +11 -3
- package/lib/categories/intelligent.js +87 -21
- package/lib/categories/octoplus.js +6 -3
- package/lib/categories/saving-sessions.js +15 -1
- package/lib/categories/smartflex-inverter.js +95 -0
- package/lib/categories/smartflex-vehicle.js +198 -0
- package/lib/categories/wheel-of-fortune.js +3 -2
- package/lib/commands.js +25 -3
- package/lib/discovery-retry.js +4 -1
- package/lib/discovery.js +71 -9
- package/lib/graphql-errors.js +160 -4
- package/lib/graphql.js +104 -7
- package/lib/http-get-json.js +64 -6
- package/lib/payload.js +15 -0
- package/lib/poll-retry.js +71 -0
- package/lib/poll-tick.js +88 -20
- package/lib/preferences.js +4 -2
- package/lib/scheduler.js +46 -8
- package/lib/sensor-definitions.js +51 -1
- package/lib/timezone.js +19 -1
- package/lib/values.js +47 -0
- package/octopus-intelligent.html +74 -34
- package/octopus-intelligent.js +1379 -250
- package/package.json +1 -1
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// lib/categories/smartflex-vehicle.js
|
|
2
|
+
'use strict';
|
|
3
|
+
const { toNumber, capStrings } = require('../values');
|
|
4
|
+
|
|
5
|
+
// v1.7.0: SmartFlex vehicle / charge point details, alerts and the last 5 charging
|
|
6
|
+
// sessions. Field names verified by live introspection (6 Oct 2026).
|
|
7
|
+
// Kraken sends Decimal fields as strings, so every number goes through toNumber().
|
|
8
|
+
// device_state is NOT read here: status is non-null on the device, so an error on it
|
|
9
|
+
// (KT-CT-4360 has been seen) nulls the device and then the whole list. The charging poll
|
|
10
|
+
// already reads status under a tolerated alias every refresh interval and sets device_state.
|
|
11
|
+
// A charge point is listed as ELECTRIC_VEHICLES too, so it always has a charging poll.
|
|
12
|
+
|
|
13
|
+
const { graphqlError, truncate } = require('../graphql-errors');
|
|
14
|
+
|
|
15
|
+
const SESSION_FIELDS = `
|
|
16
|
+
chargingSessions(last: 5) {
|
|
17
|
+
edges { node { ... on SmartFlexChargingSession {
|
|
18
|
+
start end stateOfChargeChange stateOfChargeFinal
|
|
19
|
+
energyAdded { value unit }
|
|
20
|
+
cost { amount currency }
|
|
21
|
+
type
|
|
22
|
+
problems { __typename }
|
|
23
|
+
} } }
|
|
24
|
+
}`;
|
|
25
|
+
|
|
26
|
+
const QUERY = `
|
|
27
|
+
query smartflexVehicle($account: String!) {
|
|
28
|
+
devices(accountNumber: $account) {
|
|
29
|
+
__typename
|
|
30
|
+
id
|
|
31
|
+
deviceType
|
|
32
|
+
alerts { message publishedAt }
|
|
33
|
+
... on SmartFlexVehicle {
|
|
34
|
+
make model vehicleBatterySize chargePointPowerOutput${SESSION_FIELDS}
|
|
35
|
+
}
|
|
36
|
+
... on SmartFlexChargePoint {
|
|
37
|
+
make model vehicleBatterySize chargePointPowerOutput${SESSION_FIELDS}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}`;
|
|
41
|
+
|
|
42
|
+
const VEHICLE_TYPENAMES = ['SmartFlexVehicle', 'SmartFlexChargePoint'];
|
|
43
|
+
|
|
44
|
+
function buildQuery(account) {
|
|
45
|
+
return { query: QUERY, variables: { account } };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// energyAdded comes with its unit. KILOWATT_HOUR is what Octopus sends today; WATT_HOUR is
|
|
49
|
+
// converted so kwh_added (and the kWh sensor) is never out by 1000.
|
|
50
|
+
function energyKwh(energy) {
|
|
51
|
+
if (!energy) return null;
|
|
52
|
+
const value = toNumber(energy.value);
|
|
53
|
+
if (value === null) return null;
|
|
54
|
+
return energy.unit === 'WATT_HOUR' ? value / 1000 : value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function mapSession(n) {
|
|
58
|
+
return {
|
|
59
|
+
start: n.start || null,
|
|
60
|
+
end: n.end || null,
|
|
61
|
+
kwh_added: energyKwh(n.energyAdded),
|
|
62
|
+
soc_change: toNumber(n.stateOfChargeChange),
|
|
63
|
+
soc_final: toNumber(n.stateOfChargeFinal),
|
|
64
|
+
type: n.type || null,
|
|
65
|
+
cost: n.cost ? { amount: toNumber(n.cost.amount), currency: n.cost.currency || null } : null,
|
|
66
|
+
problems: (n.problems || []).filter(Boolean).map(p => p.__typename),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function startTime(s) {
|
|
71
|
+
const t = Date.parse(s.start);
|
|
72
|
+
return Number.isNaN(t) ? -Infinity : t;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Alerts go into the retained state JSON and into Home Assistant attributes (16 KiB recorder
|
|
76
|
+
// limit), so keep only the newest few and cut long messages.
|
|
77
|
+
const MAX_ALERTS = 10;
|
|
78
|
+
const MAX_ALERT_MESSAGE = 250;
|
|
79
|
+
|
|
80
|
+
function alertTime(a) {
|
|
81
|
+
const t = Date.parse(a.published_at);
|
|
82
|
+
return Number.isNaN(t) ? -Infinity : t;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function mapAlerts(alerts) {
|
|
86
|
+
return (alerts || [])
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.map(a => ({
|
|
89
|
+
message: a.message ? truncate(a.message, MAX_ALERT_MESSAGE) : null,
|
|
90
|
+
published_at: a.publishedAt || null,
|
|
91
|
+
}))
|
|
92
|
+
.sort((a, b) => alertTime(b) - alertTime(a))
|
|
93
|
+
.slice(0, MAX_ALERTS);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function pickDevice(devices, deviceId) {
|
|
97
|
+
return devices.find(d => d && deviceId && d.id === deviceId)
|
|
98
|
+
|| devices.find(d => d && VEHICLE_TYPENAMES.includes(d.__typename))
|
|
99
|
+
|| null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function freshDefaults() {
|
|
103
|
+
return { ...defaultData, device_alerts: [], charging_sessions: [] };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function parseResponse(data, deviceId) {
|
|
107
|
+
const device = pickDevice((data && data.devices) || [], deviceId);
|
|
108
|
+
if (!device) return freshDefaults();
|
|
109
|
+
|
|
110
|
+
const edges = (device.chargingSessions && device.chargingSessions.edges) || [];
|
|
111
|
+
const sessions = edges
|
|
112
|
+
.map(e => e && e.node)
|
|
113
|
+
.filter(n => n && n.start)
|
|
114
|
+
.map(mapSession)
|
|
115
|
+
.sort((a, b) => startTime(b) - startTime(a));
|
|
116
|
+
const last = sessions.find(s => s.end) || null;
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
vehicle_make: device.make || null,
|
|
120
|
+
vehicle_model: device.model || null,
|
|
121
|
+
vehicle_battery_kwh: toNumber(device.vehicleBatterySize),
|
|
122
|
+
charger_power_kw: toNumber(device.chargePointPowerOutput),
|
|
123
|
+
device_alerts: mapAlerts(device.alerts),
|
|
124
|
+
last_session: last,
|
|
125
|
+
charging_sessions: sessions,
|
|
126
|
+
last_session_kwh: last ? last.kwh_added : null,
|
|
127
|
+
last_session_soc_final: last ? last.soc_final : null,
|
|
128
|
+
last_session_problem: last ? last.problems.length > 0 : null,
|
|
129
|
+
smartflex_vehicle_error: null,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Device fields of the query and the payload fields built from each. When Kraken fails one
|
|
134
|
+
// (a partial error nulls it), its payload fields are left out so the last values are kept.
|
|
135
|
+
const FIELD_OUTPUTS = {
|
|
136
|
+
make: ['vehicle_make'],
|
|
137
|
+
model: ['vehicle_model'],
|
|
138
|
+
vehicleBatterySize: ['vehicle_battery_kwh'],
|
|
139
|
+
chargePointPowerOutput: ['charger_power_kw'],
|
|
140
|
+
alerts: ['device_alerts'],
|
|
141
|
+
chargingSessions: ['charging_sessions', 'last_session', 'last_session_kwh', 'last_session_soc_final', 'last_session_problem'],
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// Parses the whole GraphQL body ({ data, errors }) and tolerates partial errors: an error on
|
|
145
|
+
// one field of the vehicle (e.g. chargingSessions) keeps everything else, leaves that field's
|
|
146
|
+
// payload fields out (the merge keeps the last values) and sets a short "KT-CT-xxxx: message"
|
|
147
|
+
// smartflex_vehicle_error. Errors on other devices are ignored. Throws when there is no
|
|
148
|
+
// usable vehicle data at all.
|
|
149
|
+
function parseGraphqlResponse(body, deviceId) {
|
|
150
|
+
const errors = Array.isArray(body && body.errors) && body.errors.length ? body.errors : null;
|
|
151
|
+
const data = (body && body.data) || null;
|
|
152
|
+
if (!data) {
|
|
153
|
+
if (errors) throw graphqlError(errors, 'SmartFlex vehicle query failed');
|
|
154
|
+
throw new Error('Response missing data');
|
|
155
|
+
}
|
|
156
|
+
if (!errors) return parseResponse(data, deviceId);
|
|
157
|
+
|
|
158
|
+
const devices = Array.isArray(data.devices) ? data.devices : null;
|
|
159
|
+
// With errors, the discovered device must be the one in the list: when the error nulled
|
|
160
|
+
// it, falling back to another vehicle would show that vehicle's data as this one's.
|
|
161
|
+
// Throwing keeps the last values.
|
|
162
|
+
const device = !devices ? null
|
|
163
|
+
: deviceId ? (devices.find(d => d && d.id === deviceId) || null)
|
|
164
|
+
: pickDevice(devices, null);
|
|
165
|
+
if (!device) throw graphqlError(errors, 'SmartFlex vehicle query failed');
|
|
166
|
+
|
|
167
|
+
const index = devices.indexOf(device);
|
|
168
|
+
const relevant = errors.filter((e) => !(Array.isArray(e && e.path) && e.path[0] === 'devices'
|
|
169
|
+
&& Number.isInteger(e.path[1]) && e.path[1] !== index));
|
|
170
|
+
const result = parseResponse(data, deviceId);
|
|
171
|
+
if (relevant.length === 0) return result;
|
|
172
|
+
|
|
173
|
+
for (const e of relevant) {
|
|
174
|
+
const field = Array.isArray(e && e.path) && e.path[1] === index ? e.path[2] : null;
|
|
175
|
+
// A field that still came back (the error was deeper) is used as it is.
|
|
176
|
+
if (field && FIELD_OUTPUTS[field] && (device[field] === null || device[field] === undefined)) {
|
|
177
|
+
for (const k of FIELD_OUTPUTS[field]) delete result[k];
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
result.smartflex_vehicle_error = graphqlError(relevant, 'SmartFlex vehicle query failed').message;
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const defaultData = {
|
|
185
|
+
vehicle_make: null,
|
|
186
|
+
vehicle_model: null,
|
|
187
|
+
vehicle_battery_kwh: null,
|
|
188
|
+
charger_power_kw: null,
|
|
189
|
+
device_alerts: [],
|
|
190
|
+
last_session: null,
|
|
191
|
+
charging_sessions: [],
|
|
192
|
+
last_session_kwh: null,
|
|
193
|
+
last_session_soc_final: null,
|
|
194
|
+
last_session_problem: null,
|
|
195
|
+
smartflex_vehicle_error: null,
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
module.exports = { buildQuery, parseResponse: capStrings(parseResponse), parseGraphqlResponse: capStrings(parseGraphqlResponse), defaultData };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
+
const { toNumber } = require('../values');
|
|
2
3
|
|
|
3
4
|
// wheelOfFortuneSpinsAllowed is the non-deprecated successor to wheelOfFortuneSpins.
|
|
4
5
|
// It lives on api.backend.octopus.energy (requires User-Agent header — handled in
|
|
@@ -26,10 +27,10 @@ function parseResponse(data) {
|
|
|
26
27
|
const elec = data.electricity || {};
|
|
27
28
|
const gas = data.gas || {};
|
|
28
29
|
return {
|
|
29
|
-
wheel_of_fortune_electricity_spins: elec.spinsAllowed ?? 0,
|
|
30
|
+
wheel_of_fortune_electricity_spins: toNumber(elec.spinsAllowed) ?? 0,
|
|
30
31
|
wheel_of_fortune_electricity_max: null,
|
|
31
32
|
wheel_of_fortune_electricity_used: null,
|
|
32
|
-
wheel_of_fortune_gas_spins: gas.spinsAllowed ?? 0,
|
|
33
|
+
wheel_of_fortune_gas_spins: toNumber(gas.spinsAllowed) ?? 0,
|
|
33
34
|
wheel_of_fortune_gas_max: null,
|
|
34
35
|
wheel_of_fortune_gas_used: null,
|
|
35
36
|
wheel_of_fortune_error: null
|
package/lib/commands.js
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
const { validateTime, validateLimit } = require('./preferences');
|
|
3
|
+
const { validateTimezone } = require('./timezone');
|
|
3
4
|
|
|
4
|
-
|
|
5
|
+
// A short text form of a bad input value for the error message.
|
|
6
|
+
function shown(v) {
|
|
7
|
+
let s;
|
|
8
|
+
try { s = typeof v === 'string' ? v : JSON.stringify(v); } catch (e) { s = String(v); }
|
|
9
|
+
s = String(s);
|
|
10
|
+
return s.length > 40 ? `${s.slice(0, 37)}...` : s;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const COMMAND_KEYS =['set_limit', 'set_time', 'set_timezone', 'set_smart_charging', 'set_charge_cap', 'set_boost'];
|
|
5
14
|
|
|
6
15
|
// Turns a msg.payload into independent actions. Supplied values are validated;
|
|
7
16
|
// fallbacks come from the API (confirmed*) and are passed through unvalidated.
|
|
@@ -28,8 +37,11 @@ function planCommands(payload, current) {
|
|
|
28
37
|
|
|
29
38
|
if (has('set_timezone')) {
|
|
30
39
|
const tz = payload.set_timezone;
|
|
31
|
-
|
|
32
|
-
|
|
40
|
+
// An empty text is ignored; anything else must be a timezone Intl knows.
|
|
41
|
+
if (!(typeof tz === 'string' && tz.trim().length === 0)) {
|
|
42
|
+
const r = validateTimezone(tz);
|
|
43
|
+
if (r.ok) actions.push({ type: 'timezone', timezone: r.timezone });
|
|
44
|
+
else errors.push(r.error);
|
|
33
45
|
}
|
|
34
46
|
}
|
|
35
47
|
|
|
@@ -41,6 +53,16 @@ function planCommands(payload, current) {
|
|
|
41
53
|
actions.push({ type: 'charge_cap', enabled: payload.set_charge_cap });
|
|
42
54
|
}
|
|
43
55
|
|
|
56
|
+
// true = BOOST (charge now, outside the plan), false = CANCEL. Booleans only: a boost
|
|
57
|
+
// spends money, so "true", 1 or "ON" is reported as an error, not guessed at.
|
|
58
|
+
if (has('set_boost')) {
|
|
59
|
+
if (typeof payload.set_boost === 'boolean') {
|
|
60
|
+
actions.push({ type: 'boost', enabled: payload.set_boost });
|
|
61
|
+
} else {
|
|
62
|
+
errors.push(`Invalid set_boost '${shown(payload.set_boost)}' — must be true or false`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
44
66
|
return { actions, errors, hasCommand };
|
|
45
67
|
}
|
|
46
68
|
|
package/lib/discovery-retry.js
CHANGED
|
@@ -5,9 +5,12 @@
|
|
|
5
5
|
// then a steady 5-minute cadence until it succeeds.
|
|
6
6
|
const DISCOVERY_RETRY_DELAYS_MS = [30000, 60000, 120000];
|
|
7
7
|
const DISCOVERY_RETRY_STEADY_MS = 300000;
|
|
8
|
+
// Discovery that returns no devices at all is checked again this many times, on the same
|
|
9
|
+
// delays (about 18 minutes in all), before the node accepts that there is no charger.
|
|
10
|
+
const EMPTY_DEVICES_MAX_RETRIES = 6;
|
|
8
11
|
|
|
9
12
|
function discoveryRetryDelay(attempt) {
|
|
10
13
|
return attempt < DISCOVERY_RETRY_DELAYS_MS.length ? DISCOVERY_RETRY_DELAYS_MS[attempt] : DISCOVERY_RETRY_STEADY_MS;
|
|
11
14
|
}
|
|
12
15
|
|
|
13
|
-
module.exports = { DISCOVERY_RETRY_DELAYS_MS, DISCOVERY_RETRY_STEADY_MS, discoveryRetryDelay };
|
|
16
|
+
module.exports = { DISCOVERY_RETRY_DELAYS_MS, DISCOVERY_RETRY_STEADY_MS, EMPTY_DEVICES_MAX_RETRIES, discoveryRetryDelay };
|
package/lib/discovery.js
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
'use strict';
|
|
3
3
|
const { graphqlPost } = require('./graphql');
|
|
4
4
|
const { obtainToken } = require('./auth');
|
|
5
|
-
const { onlyDeviceFieldErrors } = require('./graphql-errors');
|
|
5
|
+
const { onlyDeviceFieldErrors, statusNulledDevices, errorCode, truncate } = require('./graphql-errors');
|
|
6
|
+
|
|
7
|
+
const MAX_RAW_ERROR_LENGTH = 8192;
|
|
6
8
|
|
|
7
9
|
const DISCOVERY_QUERY = `
|
|
8
10
|
query discover($account: String!) {
|
|
@@ -22,16 +24,44 @@ query discover($account: String!) {
|
|
|
22
24
|
}
|
|
23
25
|
}
|
|
24
26
|
devices(accountNumber: $account) {
|
|
27
|
+
__typename
|
|
28
|
+
id
|
|
29
|
+
deviceType
|
|
30
|
+
status { isSuspended current }
|
|
31
|
+
}
|
|
32
|
+
}`;
|
|
33
|
+
|
|
34
|
+
// v1.7.0 SmartFlex detection. Kraken's device type enum (KrakenFlexDeviceTypes) has no charge
|
|
35
|
+
// point value: a SmartFlexChargePoint is listed as ELECTRIC_VEHICLES, like a SmartFlexVehicle.
|
|
36
|
+
// So deviceType alone picks the device Octopus smart-charges, car or charger. __typename is only
|
|
37
|
+
// needed for the inverter (its deviceType value has not been seen live, so match loosely).
|
|
38
|
+
const isInverterDevice = (d) => d.__typename === 'SmartFlexInverter'
|
|
39
|
+
|| (typeof d.deviceType === 'string' && d.deviceType.includes('INVERTER'));
|
|
40
|
+
|
|
41
|
+
// Asked when an error on the device status nulled the device list: the same devices without
|
|
42
|
+
// the status, so discovery still finds the car or charger.
|
|
43
|
+
const DEVICES_NO_STATUS_QUERY = `
|
|
44
|
+
query discoverDevices($account: String!) {
|
|
45
|
+
devices(accountNumber: $account) {
|
|
46
|
+
__typename
|
|
25
47
|
id
|
|
26
48
|
deviceType
|
|
27
|
-
status { isSuspended }
|
|
28
49
|
}
|
|
29
50
|
}`;
|
|
30
51
|
|
|
31
52
|
function parseDiscovery(data) {
|
|
32
53
|
const acct = data.account || {};
|
|
33
54
|
const devices = data.devices || [];
|
|
34
|
-
|
|
55
|
+
// Review L4: Kraken can keep a replaced car (RETIRED) in the list, possibly first. Prefer
|
|
56
|
+
// the LIVE one (status.current, read in the same status selection, so no new error
|
|
57
|
+
// exposure), and fall back to the first EV.
|
|
58
|
+
const evDevices = devices.filter(d => d && d.deviceType === 'ELECTRIC_VEHICLES');
|
|
59
|
+
const evDevice = evDevices.find(d => d.status && d.status.current === 'LIVE') || evDevices[0] || null;
|
|
60
|
+
// One device for boost, the charging poll and the vehicle sensors, so Vehicle Device State
|
|
61
|
+
// and the Boost switch never describe two different devices. The node passes deviceId to
|
|
62
|
+
// the charging poll, which then reads this same device.
|
|
63
|
+
const vehicleDevice = evDevice;
|
|
64
|
+
const inverterDevice = devices.find(d => d && isInverterDevice(d)) || null;
|
|
35
65
|
const props = (acct.properties || [])[0] || {};
|
|
36
66
|
const elecPoints = props.electricityMeterPoints || [];
|
|
37
67
|
const gasPoints = props.gasMeterPoints || [];
|
|
@@ -58,11 +88,18 @@ function parseDiscovery(data) {
|
|
|
58
88
|
|
|
59
89
|
return {
|
|
60
90
|
hasIntelligent: !!evDevice,
|
|
91
|
+
// 0 for an empty (or missing) list: the node checks again, as that can be transient.
|
|
92
|
+
deviceCount: devices.length,
|
|
61
93
|
hasElectricity: (acct.electricityAgreements || []).length > 0,
|
|
62
94
|
hasGas: (acct.gasAgreements || []).length > 0,
|
|
63
95
|
deviceId: evDevice ? evDevice.id : null,
|
|
64
96
|
deviceSuspended: evDevice && evDevice.status ? evDevice.status.isSuspended : null,
|
|
65
97
|
smartMeterDeviceId,
|
|
98
|
+
// How many devices Octopus listed. 0 can be a transient empty list, so the node only
|
|
99
|
+
// removes SmartFlex entities when the list has devices and none is of that kind.
|
|
100
|
+
deviceCount: devices.filter(Boolean).length,
|
|
101
|
+
vehicleDeviceId: vehicleDevice ? vehicleDevice.id : null,
|
|
102
|
+
inverterDeviceId: inverterDevice ? inverterDevice.id : null,
|
|
66
103
|
electricityMpan: importPoint ? importPoint.mpan : null,
|
|
67
104
|
electricityExportMpan: exportPoint ? exportPoint.mpan : null,
|
|
68
105
|
electricitySerial: firstImportMeter ? firstImportMeter.serialNumber : null,
|
|
@@ -71,22 +108,47 @@ function parseDiscovery(data) {
|
|
|
71
108
|
};
|
|
72
109
|
}
|
|
73
110
|
|
|
74
|
-
|
|
111
|
+
// `isClosed` (optional): true once the node is closed. Checked after each answer, so a late
|
|
112
|
+
// answer sends no further query; discovery then fails with "Node closed".
|
|
113
|
+
async function discoverProducts(apiKey, account, { isClosed } = {}) {
|
|
114
|
+
const stopIfClosed = () => {
|
|
115
|
+
if (isClosed && isClosed()) throw new Error('Node closed');
|
|
116
|
+
};
|
|
75
117
|
const token = await obtainToken(apiKey);
|
|
118
|
+
stopIfClosed();
|
|
76
119
|
const response = await graphqlPost({ query: DISCOVERY_QUERY, variables: { account } }, token);
|
|
77
|
-
|
|
120
|
+
stopIfClosed();
|
|
121
|
+
let errors = response.data.errors;
|
|
122
|
+
let data = response.data.data;
|
|
123
|
+
let statusErrorCode;
|
|
124
|
+
// An error on the device status (KT-CT-4360) nulls the whole device list, and with no
|
|
125
|
+
// device list the node would have no scheduler at all. Ask once more without the status.
|
|
126
|
+
if (data && statusNulledDevices(errors, data)) {
|
|
127
|
+
statusErrorCode = errorCode(errors.find((e) => errorCode(e))) || null;
|
|
128
|
+
const retry = await graphqlPost({ query: DEVICES_NO_STATUS_QUERY, variables: { account } }, token);
|
|
129
|
+
stopIfClosed();
|
|
130
|
+
const retryData = retry.data.data;
|
|
131
|
+
if (retry.data.errors || !retryData || !Array.isArray(retryData.devices)) {
|
|
132
|
+
throw new Error(truncate(`Discovery failed: ${JSON.stringify(retry.data.errors || retry.data)}`, MAX_RAW_ERROR_LENGTH));
|
|
133
|
+
}
|
|
134
|
+
data = Object.assign({}, data, { devices: retryData.devices });
|
|
135
|
+
errors = undefined;
|
|
136
|
+
}
|
|
78
137
|
if (errors) {
|
|
79
138
|
// Kraken can fail just the per-device status resolver (KT-CT-4360, transient) while
|
|
80
139
|
// returning everything else. Treat that as "suspended unknown" instead of failing
|
|
81
140
|
// discovery (which would leave the node with no scheduler).
|
|
82
|
-
if (!onlyDeviceFieldErrors(errors,
|
|
83
|
-
throw new Error(`Discovery failed: ${JSON.stringify(errors)}
|
|
141
|
+
if (!onlyDeviceFieldErrors(errors, data, 'status')) {
|
|
142
|
+
throw new Error(truncate(`Discovery failed: ${JSON.stringify(errors)}`, MAX_RAW_ERROR_LENGTH));
|
|
84
143
|
}
|
|
85
144
|
}
|
|
86
|
-
if (!
|
|
145
|
+
if (!data) {
|
|
87
146
|
throw new Error('Discovery response missing data');
|
|
88
147
|
}
|
|
89
|
-
|
|
148
|
+
const result = parseDiscovery(data);
|
|
149
|
+
// Set when the status could not be read: the node logs it once (null when Octopus gave no code).
|
|
150
|
+
if (statusErrorCode !== undefined) result.statusErrorCode = statusErrorCode;
|
|
151
|
+
return result;
|
|
90
152
|
}
|
|
91
153
|
|
|
92
154
|
module.exports = { discoverProducts, parseDiscovery };
|
package/lib/graphql-errors.js
CHANGED
|
@@ -1,18 +1,174 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
// Error text stored in msg.payload.*_error and shown in HA must stay under 255 characters
|
|
4
|
+
// (the HA state length limit).
|
|
5
|
+
const MAX_ERROR_LENGTH = 254;
|
|
6
|
+
|
|
3
7
|
// Kraken can fail a single per-device field (e.g. KT-CT-4360) while returning everything else.
|
|
4
|
-
// True when every error sits under `devices[i].<field>`
|
|
5
|
-
// are still present
|
|
8
|
+
// True when every error sits under `devices[i].<field>` (field may be a list of fields) and the
|
|
9
|
+
// device list and those devices are still present: the failure stayed inside those fields and
|
|
10
|
+
// the rest is usable.
|
|
6
11
|
function onlyDeviceFieldErrors(errors, data, field) {
|
|
7
12
|
if (!Array.isArray(errors) || errors.length === 0) return false;
|
|
8
13
|
const devices = data && data.devices;
|
|
9
14
|
if (!Array.isArray(devices)) return false;
|
|
15
|
+
const fields = Array.isArray(field) ? field : [field];
|
|
10
16
|
return errors.every((e) => Array.isArray(e.path)
|
|
11
17
|
&& e.path.length >= 3
|
|
12
18
|
&& e.path[0] === 'devices'
|
|
13
19
|
&& Number.isInteger(e.path[1])
|
|
14
20
|
&& devices[e.path[1]] != null
|
|
15
|
-
&& e.path[2]
|
|
21
|
+
&& fields.includes(e.path[2]));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// True when the device list came back null because the device status failed: a GraphQL
|
|
25
|
+
// partial error whose path runs through `status` (or its alias `smartStatus`) on a device.
|
|
26
|
+
// `status` is non-null on the device and the list items are non-null too, so an error on it
|
|
27
|
+
// nulls `devices`, the nearest nullable field. Used by the charging poll and discovery, which
|
|
28
|
+
// then ask again without the status.
|
|
29
|
+
function statusNulledDevices(errors, data) {
|
|
30
|
+
if (data && Array.isArray(data.devices)) return false;
|
|
31
|
+
if (!Array.isArray(errors) || errors.length === 0) return false;
|
|
32
|
+
const onDevice = (e) => !!e && Array.isArray(e.path) && e.path[0] === 'devices';
|
|
33
|
+
const onStatus = (e) => onDevice(e) && (e.path.includes('status') || e.path.includes('smartStatus'));
|
|
34
|
+
return errors.every(onDevice) && errors.some(onStatus);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function errorCode(e) {
|
|
38
|
+
return (e && e.extensions && e.extensions.errorCode) || null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// An Octopus API key, and anything shaped like a JWT (three base64url parts). A GraphQL
|
|
42
|
+
// server can echo request variables in an error message ("Variable '$input' got invalid
|
|
43
|
+
// value {'APIKey': 'sk_live_...'}"), so error text is masked before it is stored or logged.
|
|
44
|
+
// At least one key character, so text that is already masked ("sk_live_***") is left alone.
|
|
45
|
+
const API_KEY_PATTERN = /sk_live_[A-Za-z0-9_-]+/g;
|
|
46
|
+
// Matches only start at the beginning of a run of token characters, so a long run with no
|
|
47
|
+
// dots is scanned once, not from every position (which was quadratic). A run can start just
|
|
48
|
+
// after a dot, and it takes every further dotted part: a JWT straight after a dotted word
|
|
49
|
+
// ("x.authorization_header.<jwt>") is masked whole, signature included, not cut after its
|
|
50
|
+
// second part.
|
|
51
|
+
const JWT_PATTERN = /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]{10,}){2,}/g;
|
|
52
|
+
// Text past this is cut before masking: every caller keeps far less than this.
|
|
53
|
+
const MAX_REDACT_INPUT = 8192;
|
|
54
|
+
const MIN_SECRET_LENGTH = 8;
|
|
55
|
+
|
|
56
|
+
// Any value as text. String() throws for an object with no prototype or a throwing toString.
|
|
57
|
+
function toText(value) {
|
|
58
|
+
try {
|
|
59
|
+
return String(value);
|
|
60
|
+
} catch (e) {
|
|
61
|
+
try {
|
|
62
|
+
return Object.prototype.toString.call(value);
|
|
63
|
+
} catch (e2) {
|
|
64
|
+
return '[unprintable]';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function mask(s, secrets) {
|
|
70
|
+
// Patterns first, so a masked key still reads sk_live_*** and shows what was hidden.
|
|
71
|
+
let out = s.replace(API_KEY_PATTERN, 'sk_live_***').replace(JWT_PATTERN, '[token]');
|
|
72
|
+
for (const secret of secrets || []) {
|
|
73
|
+
if (typeof secret === 'string' && secret.length >= MIN_SECRET_LENGTH) out = out.split(secret).join('***');
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Mask API keys and tokens in `text`. `secrets` are literal values to mask as well (the
|
|
79
|
+
// node's own API key); empty or very short ones are ignored. Never throws, never longer than
|
|
80
|
+
// MAX_REDACT_INPUT, and redact(redact(x)) === redact(x).
|
|
81
|
+
function redact(text, secrets = []) {
|
|
82
|
+
let s = toText(text);
|
|
83
|
+
// Cut first so the work is bounded, mask, then cut again: masking "sk_live_a" makes it
|
|
84
|
+
// longer, so many tiny keys near the cut could push the text past it. The second cut can
|
|
85
|
+
// leave a partial mask but never a partial secret; mask once more to be sure.
|
|
86
|
+
if (s.length > MAX_REDACT_INPUT) s = s.slice(0, MAX_REDACT_INPUT);
|
|
87
|
+
s = mask(s, secrets);
|
|
88
|
+
if (s.length > MAX_REDACT_INPUT) s = mask(s.slice(0, MAX_REDACT_INPUT), secrets);
|
|
89
|
+
return s;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Cut to `max` characters. Not masked: the Node-RED log, status and msg show the real text,
|
|
93
|
+
// including a wrong key echoed by Octopus. What is published to Home Assistant goes through
|
|
94
|
+
// maskSecretsDeep first.
|
|
95
|
+
function truncate(text, max = MAX_ERROR_LENGTH) {
|
|
96
|
+
const s = toText(text);
|
|
97
|
+
return s.length <= max ? s : `${s.slice(0, max - 3)}...`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A copy of `value` with API keys and tokens masked in every string (objects and arrays are
|
|
101
|
+
// walked). Applied to what is published over MQTT, where HA stores it in its history.
|
|
102
|
+
function maskSecretsDeep(value, secrets = [], depth = 0) {
|
|
103
|
+
if (typeof value === 'string') return redact(value, secrets);
|
|
104
|
+
if (value === null || typeof value !== 'object' || depth > 8) return value;
|
|
105
|
+
if (Array.isArray(value)) return value.map((v) => maskSecretsDeep(v, secrets, depth + 1));
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const k of Object.keys(value)) out[k] = maskSecretsDeep(value[k], secrets, depth + 1);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// "Unable to fetch planned dispatches." -> "... dispatches". A loop from the end, not /\.+$/:
|
|
112
|
+
// that regex retries from every dot of a run, so a long run of dots followed by any other
|
|
113
|
+
// character is quadratic.
|
|
114
|
+
function stripTrailingDots(s) {
|
|
115
|
+
let end = s.length;
|
|
116
|
+
while (end > 0 && s.charCodeAt(end - 1) === 46) end--;
|
|
117
|
+
return s.slice(0, end);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A short, readable Error from a Kraken GraphQL errors array: "KT-CT-4340: Unable to fetch
|
|
121
|
+
// planned dispatches". Without a Kraken code the message is prefixed with `context` instead,
|
|
122
|
+
// or is the plain message when no context is given.
|
|
123
|
+
// The Error carries .code (or null) and .detail (the message without the code).
|
|
124
|
+
function graphqlError(errors, context) {
|
|
125
|
+
const first = (Array.isArray(errors) && errors[0]) || {};
|
|
126
|
+
const code = errorCode(first);
|
|
127
|
+
// The message comes from the response body and can be long: every step here is linear.
|
|
128
|
+
const detail = stripTrailingDots(toText(first.message || '').trim()) || 'Unknown error';
|
|
129
|
+
const prefix = code || context;
|
|
130
|
+
const err = new Error(truncate(prefix ? `${prefix}: ${detail}` : detail));
|
|
131
|
+
err.code = code;
|
|
132
|
+
err.detail = detail;
|
|
133
|
+
return err;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Socket-level error codes from Node (err.code) that mean the server could not be reached.
|
|
137
|
+
const NETWORK_ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN',
|
|
138
|
+
'EHOSTUNREACH', 'ENETUNREACH', 'ENETDOWN', 'EPIPE', 'ECONNABORTED'];
|
|
139
|
+
|
|
140
|
+
// True when a request failed because Octopus could not be reached or did not answer: a
|
|
141
|
+
// time-out, a dropped connection, a socket error or an HTTP 5xx (lib/graphql.js messages).
|
|
142
|
+
// A Kraken GraphQL error, an HTTP 4xx (429 included) or a parse error is not one.
|
|
143
|
+
function isNetworkError(err) {
|
|
144
|
+
if (!err) return false;
|
|
145
|
+
if (NETWORK_ERROR_CODES.includes(err.code)) return true;
|
|
146
|
+
const msg = toText(err.message || '');
|
|
147
|
+
return /^HTTP 5\d\d\b/.test(msg)
|
|
148
|
+
|| /request timed out/i.test(msg)
|
|
149
|
+
|| /connection closed before/i.test(msg);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Socket errors raised before the request could reach Octopus: the name did not resolve or
|
|
153
|
+
// the connection was never made. A write that fails like this was not applied.
|
|
154
|
+
const NOT_SENT_ERROR_CODES = ['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'ENETDOWN'];
|
|
155
|
+
// Socket errors on a connection that was made: the request may have reached Octopus.
|
|
156
|
+
const MAYBE_SENT_ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'ECONNABORTED'];
|
|
157
|
+
|
|
158
|
+
// True when a write (mutation) failed in a way that leaves it unknown whether Octopus applied
|
|
159
|
+
// it: a time-out, a connection closed after the request was sent, or an HTTP 5xx. A DNS or
|
|
160
|
+
// connect error, an HTTP 4xx and a reply that could not be read are plain failures.
|
|
161
|
+
function isUnconfirmedWriteError(err) {
|
|
162
|
+
if (!err) return false;
|
|
163
|
+
if (NOT_SENT_ERROR_CODES.includes(err.code)) return false;
|
|
164
|
+
if (MAYBE_SENT_ERROR_CODES.includes(err.code)) return true;
|
|
165
|
+
const msg = toText(err.message || '');
|
|
166
|
+
return /^HTTP 5\d\d\b/.test(msg)
|
|
167
|
+
|| /request timed out/i.test(msg)
|
|
168
|
+
|| /connection closed before/i.test(msg);
|
|
16
169
|
}
|
|
17
170
|
|
|
18
|
-
module.exports = {
|
|
171
|
+
module.exports = {
|
|
172
|
+
onlyDeviceFieldErrors, statusNulledDevices, graphqlError, errorCode, truncate, redact, maskSecretsDeep, isNetworkError, isUnconfirmedWriteError,
|
|
173
|
+
MAX_ERROR_LENGTH,
|
|
174
|
+
};
|