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.
- package/CHANGELOG.md +597 -442
- package/README.md +1234 -980
- 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 +667 -599
- package/examples/mqtt-integration.json +1 -1
- package/examples/node-red-dashboard-flow.json +1377 -1199
- package/examples/set-preferences.json +1 -1
- package/lib/active-now.js +33 -0
- package/lib/api-metrics.js +31 -31
- package/lib/auth.js +25 -20
- package/lib/boost.js +85 -0
- package/lib/categories/account.js +32 -32
- package/lib/categories/applicable-rates.js +137 -127
- package/lib/categories/completed-dispatches.js +36 -35
- package/lib/categories/electricity.js +156 -146
- package/lib/categories/flex-planned-dispatches.js +36 -36
- package/lib/categories/free-electricity.js +73 -61
- package/lib/categories/gas.js +102 -95
- package/lib/categories/home-mini.js +45 -37
- package/lib/categories/intelligent.js +221 -124
- package/lib/categories/octoplus.js +35 -32
- package/lib/categories/saving-sessions.js +78 -64
- package/lib/categories/smartflex-inverter.js +95 -0
- package/lib/categories/smartflex-vehicle.js +198 -0
- package/lib/categories/wheel-of-fortune.js +50 -49
- package/lib/commands.js +69 -0
- package/lib/discovery-retry.js +16 -0
- package/lib/discovery.js +154 -85
- package/lib/graphql-errors.js +174 -0
- package/lib/graphql.js +141 -44
- package/lib/http-get-json.js +80 -22
- package/lib/payload.js +104 -88
- package/lib/poll-retry.js +71 -0
- package/lib/poll-tick.js +112 -44
- package/lib/preferences.js +34 -0
- package/lib/scheduler.js +85 -47
- package/lib/sensor-definitions.js +269 -0
- package/lib/timezone.js +67 -49
- package/lib/update-check.js +38 -38
- package/lib/values.js +47 -0
- package/octopus-intelligent.html +258 -205
- package/octopus-intelligent.js +2816 -1807
- package/package.json +54 -54
|
@@ -1 +1 @@
|
|
|
1
|
-
[{"id":"1","type":"inject","name":"Set 85% by 07:30","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_limit\":85,\"set_time\":\"07:30\"}","payloadType":"json","x":150,"y":140,"wires":[["2"]]},{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":
|
|
1
|
+
[{"id":"1","type":"inject","name":"Set 85% by 07:30","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_limit\":85,\"set_time\":\"07:30\"}","payloadType":"json","x":150,"y":140,"wires":[["2"]]},{"id":"4","type":"inject","name":"Boost now","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_boost\":true}","payloadType":"json","x":150,"y":200,"wires":[["2"]]},{"id":"5","type":"inject","name":"Cancel boost","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"topic":"","payload":"{\"set_boost\":false}","payloadType":"json","x":150,"y":260,"wires":[["2"]]},{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":false,"x":380,"y":140,"wires":[["3"]]},{"id":"3","type":"debug","name":"Confirmation","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":610,"y":140,"wires":[]}]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// "Active now" fields: values that depend on the clock, not only on what Octopus returned.
|
|
3
|
+
// Recomputed from the stored state on the node's 10 s tick, with no API calls.
|
|
4
|
+
const savingSessions = require('./categories/saving-sessions');
|
|
5
|
+
const freeElectricity = require('./categories/free-electricity');
|
|
6
|
+
const applicableRates = require('./categories/applicable-rates');
|
|
7
|
+
|
|
8
|
+
const RATE_PREFIXES = ['applicable_rates', 'electricity_export_rate'];
|
|
9
|
+
|
|
10
|
+
function activeFields(state, nowMs) {
|
|
11
|
+
const out = Object.assign({},
|
|
12
|
+
savingSessions.activeFields(state, nowMs),
|
|
13
|
+
freeElectricity.activeFields(state, nowMs));
|
|
14
|
+
for (const prefix of RATE_PREFIXES) {
|
|
15
|
+
const slots = state[prefix];
|
|
16
|
+
if (Array.isArray(slots) && slots.length > 0) {
|
|
17
|
+
Object.assign(out, applicableRates.currentFields(slots, prefix, nowMs));
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// The recomputed fields whose value differs from `state`, or null when none do.
|
|
24
|
+
function changedActiveFields(state, nowMs) {
|
|
25
|
+
const fresh = activeFields(state, nowMs);
|
|
26
|
+
const changed = {};
|
|
27
|
+
for (const [k, v] of Object.entries(fresh)) {
|
|
28
|
+
if (!Object.is(state[k], v)) changed[k] = v; // Object.is: a NaN rate is not a change
|
|
29
|
+
}
|
|
30
|
+
return Object.keys(changed).length > 0 ? changed : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { activeFields, changedActiveFields };
|
package/lib/api-metrics.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
const HOURLY_LIMIT = 50000;
|
|
3
|
-
const ONE_HOUR_MS = 60 * 60 * 1000;
|
|
4
|
-
|
|
5
|
-
function createApiMetrics() {
|
|
6
|
-
const history = [];
|
|
7
|
-
|
|
8
|
-
function recordPoll(complexity) {
|
|
9
|
-
history.push({ timestamp: Date.now(), complexity: complexity || 0 });
|
|
10
|
-
pruneOld();
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
function pruneOld() {
|
|
14
|
-
const cutoff = Date.now() - ONE_HOUR_MS;
|
|
15
|
-
while (history.length > 0 && history[0].timestamp < cutoff) history.shift();
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function getMetrics() {
|
|
19
|
-
pruneOld();
|
|
20
|
-
const total = history.reduce((sum, e) => sum + e.complexity, 0);
|
|
21
|
-
return {
|
|
22
|
-
requests_last_hour: history.length,
|
|
23
|
-
complexity_last_hour: total,
|
|
24
|
-
complexity_percent: ((total / HOURLY_LIMIT) * 100).toFixed(1)
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
return { recordPoll, getMetrics, _history: history };
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
module.exports = { createApiMetrics };
|
|
1
|
+
'use strict';
|
|
2
|
+
const HOURLY_LIMIT = 50000;
|
|
3
|
+
const ONE_HOUR_MS = 60 * 60 * 1000;
|
|
4
|
+
|
|
5
|
+
function createApiMetrics() {
|
|
6
|
+
const history = [];
|
|
7
|
+
|
|
8
|
+
function recordPoll(complexity) {
|
|
9
|
+
history.push({ timestamp: Date.now(), complexity: complexity || 0 });
|
|
10
|
+
pruneOld();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function pruneOld() {
|
|
14
|
+
const cutoff = Date.now() - ONE_HOUR_MS;
|
|
15
|
+
while (history.length > 0 && history[0].timestamp < cutoff) history.shift();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function getMetrics() {
|
|
19
|
+
pruneOld();
|
|
20
|
+
const total = history.reduce((sum, e) => sum + e.complexity, 0);
|
|
21
|
+
return {
|
|
22
|
+
requests_last_hour: history.length,
|
|
23
|
+
complexity_last_hour: total,
|
|
24
|
+
complexity_percent: ((total / HOURLY_LIMIT) * 100).toFixed(1)
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return { recordPoll, getMetrics, _history: history };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
module.exports = { createApiMetrics };
|
package/lib/auth.js
CHANGED
|
@@ -1,20 +1,25 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
const { graphqlPost } = require('./graphql');
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
if (
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
const { graphqlPost } = require('./graphql');
|
|
3
|
+
const { truncate } = require('./graphql-errors');
|
|
4
|
+
|
|
5
|
+
const MAX_RAW_ERROR_LENGTH = 8192;
|
|
6
|
+
|
|
7
|
+
async function obtainToken(apiKey) {
|
|
8
|
+
const response = await graphqlPost({
|
|
9
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) {
|
|
10
|
+
obtainKrakenToken(input: $input) { token }
|
|
11
|
+
}`,
|
|
12
|
+
variables: { input: { APIKey: apiKey } }
|
|
13
|
+
});
|
|
14
|
+
if (response.data.errors) {
|
|
15
|
+
// Kraken can echo the APIKey variable in an input error. Shown as it is in Node-RED, so a
|
|
16
|
+
// wrong key can be seen; masked only when published to Home Assistant.
|
|
17
|
+
throw new Error(truncate(`Auth failed: ${JSON.stringify(response.data.errors)}`, MAX_RAW_ERROR_LENGTH));
|
|
18
|
+
}
|
|
19
|
+
if (!response.data.data || !response.data.data.obtainKrakenToken) {
|
|
20
|
+
throw new Error('Auth response missing token data');
|
|
21
|
+
}
|
|
22
|
+
return response.data.data.obtainKrakenToken.token;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
module.exports = { obtainToken };
|
package/lib/boost.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { errorCode, truncate } = require('./graphql-errors');
|
|
3
|
+
|
|
4
|
+
// Boost charge: charge now, outside the Octopus plan. Not the same as set_smart_charging,
|
|
5
|
+
// which suspends or resumes Octopus control (updateDeviceSmartControl).
|
|
6
|
+
// Live introspection 6 Oct 2026:
|
|
7
|
+
// updateBoostCharge(input: {deviceId: String!, action: UpdateBoostChargeAction!}) -> SmartFlexDeviceInterface
|
|
8
|
+
// UpdateBoostChargeAction: BOOST | CANCEL
|
|
9
|
+
// The result is the device. Only its id is read back (review A2): status is non-null and
|
|
10
|
+
// KT-CT-4360 has been seen on it, so an error there would null the answer and make a boost
|
|
11
|
+
// that went through look refused. The charging poll that follows reads the state, and it
|
|
12
|
+
// tolerates status errors.
|
|
13
|
+
const BOOST_MUTATION = `mutation UpdateBoostCharge($deviceId: String!, $action: UpdateBoostChargeAction!) { updateBoostCharge(input: { deviceId: $deviceId, action: $action }) { id } }`;
|
|
14
|
+
|
|
15
|
+
function buildBoostRequest(deviceId, enabled) {
|
|
16
|
+
return { query: BOOST_MUTATION, variables: { deviceId, action: enabled ? 'BOOST' : 'CANCEL' } };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// currentState BOOSTING -> true, any other known state -> false, missing -> null (unknown).
|
|
20
|
+
function isBoosting(currentState) {
|
|
21
|
+
if (currentState === null || currentState === undefined) return null;
|
|
22
|
+
return currentState === 'BOOSTING';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Short "KT-CT-xxxx: message" form for logs and the boost_error field, the same form as
|
|
26
|
+
// intelligent_error (lib/graphql-errors.js): no trailing full stop, under 255 characters.
|
|
27
|
+
function formatKrakenErrors(errors) {
|
|
28
|
+
if (!Array.isArray(errors) || errors.length === 0) return 'Unknown error';
|
|
29
|
+
return truncate(errors.map((e) => {
|
|
30
|
+
const code = errorCode(e);
|
|
31
|
+
const msg = String((e && e.message) || '').trim().replace(/\.+$/, '') || 'Unknown error';
|
|
32
|
+
return code ? `${code}: ${msg}` : msg;
|
|
33
|
+
}).join('; '));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// A clean refusal: Octopus failed the mutation itself (errors at updateBoostCharge or with no
|
|
37
|
+
// path) and sent no device back. The refusal code has not been seen live, so the handling does
|
|
38
|
+
// not depend on it.
|
|
39
|
+
function isCleanRefusal(errors, device) {
|
|
40
|
+
return !device && errors.every((e) => !Array.isArray(e && e.path) || e.path.length <= 1);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Octopus can refuse a boost (car unplugged, full, ...). Returns:
|
|
44
|
+
// ok: true accepted
|
|
45
|
+
// ok: false, unclear: false a clean refusal: nothing changed on the device
|
|
46
|
+
// ok: false, unclear: true not clear whether it went through (an error deeper in the
|
|
47
|
+
// answer, errors next to a device, or no device and no error).
|
|
48
|
+
// The caller must not flip the boost state: a poll tells.
|
|
49
|
+
// A read-back state is not used when there are errors.
|
|
50
|
+
function parseBoostResponse(res) {
|
|
51
|
+
const body = (res && res.data) || {};
|
|
52
|
+
const device = (body.data && body.data.updateBoostCharge) || null;
|
|
53
|
+
if (Array.isArray(body.errors) && body.errors.length > 0) {
|
|
54
|
+
const unclear = !isCleanRefusal(body.errors, device);
|
|
55
|
+
return { ok: false, unclear, currentState: null, boosting: null, error: formatKrakenErrors(body.errors) };
|
|
56
|
+
}
|
|
57
|
+
if (!device) {
|
|
58
|
+
return { ok: false, unclear: true, currentState: null, boosting: null, error: 'Boost response had no device' };
|
|
59
|
+
}
|
|
60
|
+
const currentState = device.status && device.status.currentState ? device.status.currentState : null;
|
|
61
|
+
return { ok: true, unclear: false, currentState, boosting: isBoosting(currentState), error: null };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function slotActiveAt(slots, now = new Date()) {
|
|
65
|
+
return (slots || []).some((s) => new Date(s.start) <= now && new Date(s.end) > now);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// A boost is charging outside the plan, so it counts as charging.
|
|
69
|
+
function chargingNowFor(slots, boosting, now = new Date()) {
|
|
70
|
+
return slotActiveAt(slots, now) || boosting === true;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The 10 s reconciliation decision. Returns the corrected charging_now, or null for no change.
|
|
74
|
+
// With no slots and no boost it does nothing, as before boosts existed.
|
|
75
|
+
function reconcileChargingNow({ slots, boosting, chargingNow, now = new Date() }) {
|
|
76
|
+
const hasSlots = Array.isArray(slots) && slots.length > 0;
|
|
77
|
+
if (!hasSlots && boosting !== true) return null;
|
|
78
|
+
const shouldBeCharging = chargingNowFor(slots, boosting, now);
|
|
79
|
+
return shouldBeCharging === chargingNow ? null : shouldBeCharging;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = {
|
|
83
|
+
BOOST_MUTATION, buildBoostRequest, parseBoostResponse, formatKrakenErrors,
|
|
84
|
+
isBoosting, slotActiveAt, chargingNowFor, reconcileChargingNow,
|
|
85
|
+
};
|
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
// lib/categories/account.js
|
|
2
|
-
'use strict';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const balancePence =
|
|
19
|
-
return {
|
|
20
|
-
account_balance_pence: balancePence,
|
|
21
|
-
account_balance_pounds: balancePence !== null ? parseFloat((balancePence / 100).toFixed(2)) : null,
|
|
22
|
-
account_error: null
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const defaultData = {
|
|
27
|
-
account_balance_pence: null,
|
|
28
|
-
account_balance_pounds: null,
|
|
29
|
-
account_error: null
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
module.exports = { buildQuery, parseResponse, defaultData };
|
|
1
|
+
// lib/categories/account.js
|
|
2
|
+
'use strict';
|
|
3
|
+
const { toNumber } = require('../values');
|
|
4
|
+
|
|
5
|
+
const QUERY = `
|
|
6
|
+
query getAccountBalance($account: String!) {
|
|
7
|
+
account(accountNumber: $account) {
|
|
8
|
+
balance
|
|
9
|
+
}
|
|
10
|
+
}`;
|
|
11
|
+
|
|
12
|
+
function buildQuery(account) {
|
|
13
|
+
return { query: QUERY, variables: { account } };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function parseResponse(data) {
|
|
17
|
+
// Kraken numeric scalars can serialise as strings; anything not a finite number is null
|
|
18
|
+
const balancePence = toNumber((data.account || {}).balance);
|
|
19
|
+
return {
|
|
20
|
+
account_balance_pence: balancePence,
|
|
21
|
+
account_balance_pounds: balancePence !== null ? parseFloat((balancePence / 100).toFixed(2)) : null,
|
|
22
|
+
account_error: null
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const defaultData = {
|
|
27
|
+
account_balance_pence: null,
|
|
28
|
+
account_balance_pounds: null,
|
|
29
|
+
account_error: null
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
module.exports = { buildQuery, parseResponse, defaultData };
|
|
@@ -1,127 +1,137 @@
|
|
|
1
|
-
// lib/categories/applicable-rates.js
|
|
2
|
-
// Half-hourly time-of-use rates for a given electricity supply point.
|
|
3
|
-
// Requires MPAN (or MPRN). Returns 30-min slots for the next 24h.
|
|
4
|
-
//
|
|
5
|
-
// Same parser handles import and export — pass { fieldPrefix } to parseResponse
|
|
6
|
-
// and exportFields() to swap the output naming to electricity_export_rate_*.
|
|
7
|
-
'use strict';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
.
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
const
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
median =
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
out
|
|
63
|
-
out[`${prefix}
|
|
64
|
-
out[`${prefix}
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
1
|
+
// lib/categories/applicable-rates.js
|
|
2
|
+
// Half-hourly time-of-use rates for a given electricity supply point.
|
|
3
|
+
// Requires MPAN (or MPRN). Returns 30-min slots for the next 24h.
|
|
4
|
+
//
|
|
5
|
+
// Same parser handles import and export — pass { fieldPrefix } to parseResponse
|
|
6
|
+
// and exportFields() to swap the output naming to electricity_export_rate_*.
|
|
7
|
+
'use strict';
|
|
8
|
+
const { toNumber, capStrings } = require('../values');
|
|
9
|
+
|
|
10
|
+
const QUERY = `
|
|
11
|
+
query getApplicableRates($account: String!, $mpxn: String!, $startAt: DateTime!, $endAt: DateTime!) {
|
|
12
|
+
applicableRates(accountNumber: $account, mpxn: $mpxn, startAt: $startAt, endAt: $endAt, first: 48) {
|
|
13
|
+
edges { node { validFrom validTo value } }
|
|
14
|
+
}
|
|
15
|
+
}`;
|
|
16
|
+
|
|
17
|
+
function buildQuery(account, mpan) {
|
|
18
|
+
const startAt = new Date().toISOString();
|
|
19
|
+
const endAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
|
|
20
|
+
return { query: QUERY, variables: { account, mpxn: mpan, startAt, endAt } };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function _stats(slots) {
|
|
24
|
+
const values = slots
|
|
25
|
+
.map(s => s.value_pence_per_kwh)
|
|
26
|
+
.filter(v => v !== null && v !== undefined);
|
|
27
|
+
if (values.length === 0) {
|
|
28
|
+
return { min: null, max: null, median: null, avg: null };
|
|
29
|
+
}
|
|
30
|
+
const sorted = values.slice().sort((a, b) => a - b);
|
|
31
|
+
const min = sorted[0];
|
|
32
|
+
const max = sorted[sorted.length - 1];
|
|
33
|
+
const sum = values.reduce((a, v) => a + v, 0);
|
|
34
|
+
// Finite values can still add up past Number.MAX_VALUE: never publish Infinity.
|
|
35
|
+
const finite = (v) => (Number.isFinite(v) ? v : null);
|
|
36
|
+
const avg = finite(parseFloat((sum / values.length).toFixed(4)));
|
|
37
|
+
let median;
|
|
38
|
+
if (sorted.length % 2 === 1) {
|
|
39
|
+
median = sorted[Math.floor(sorted.length / 2)];
|
|
40
|
+
} else {
|
|
41
|
+
const mid = sorted.length / 2;
|
|
42
|
+
median = finite(parseFloat(((sorted[mid - 1] + sorted[mid]) / 2).toFixed(4)));
|
|
43
|
+
}
|
|
44
|
+
return { min, max, median, avg };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Current / previous / next rate fields for `nowMs` from slots sorted by valid_from.
|
|
48
|
+
// Also used on the node's 10 s tick to keep them right between polls.
|
|
49
|
+
function currentFields(slots, prefix, nowMs) {
|
|
50
|
+
const currentIdx = slots.findIndex(s => {
|
|
51
|
+
const from = new Date(s.valid_from).getTime();
|
|
52
|
+
const to = new Date(s.valid_to).getTime();
|
|
53
|
+
return nowMs >= from && nowMs < to;
|
|
54
|
+
});
|
|
55
|
+
const current = currentIdx !== -1 ? slots[currentIdx] : null;
|
|
56
|
+
const prev = currentIdx > 0 ? slots[currentIdx - 1] : null;
|
|
57
|
+
const next = (currentIdx !== -1 && currentIdx < slots.length - 1) ? slots[currentIdx + 1] : null;
|
|
58
|
+
|
|
59
|
+
const pence = current ? current.value_pence_per_kwh : null;
|
|
60
|
+
const prevPence = prev ? prev.value_pence_per_kwh : null;
|
|
61
|
+
const nextPence = next ? next.value_pence_per_kwh : null;
|
|
62
|
+
const out = {};
|
|
63
|
+
out[`${prefix}_current_pence`] = pence;
|
|
64
|
+
out[`${prefix}_current_gbp`] = pence !== null ? parseFloat((pence / 100).toFixed(4)) : null;
|
|
65
|
+
out[`${prefix}_prev_pence`] = prevPence;
|
|
66
|
+
out[`${prefix}_prev_gbp`] = prevPence !== null ? parseFloat((prevPence / 100).toFixed(4)) : null;
|
|
67
|
+
out[`${prefix}_prev_to`] = prev ? prev.valid_to : null;
|
|
68
|
+
out[`${prefix}_next_pence`] = nextPence;
|
|
69
|
+
out[`${prefix}_next_gbp`] = nextPence !== null ? parseFloat((nextPence / 100).toFixed(4)) : null;
|
|
70
|
+
out[`${prefix}_next_from`] = next ? next.valid_from : null;
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function _emit(prefix, slots, nowMs, stats) {
|
|
75
|
+
const out = {};
|
|
76
|
+
out[`${prefix}`] = slots;
|
|
77
|
+
out[`${prefix}_count`] = slots.length;
|
|
78
|
+
Object.assign(out, currentFields(slots, prefix, nowMs));
|
|
79
|
+
out[`${prefix}_error`] = null;
|
|
80
|
+
// v1.5 stats
|
|
81
|
+
out[`${prefix}_min_pence`] = stats.min;
|
|
82
|
+
out[`${prefix}_max_pence`] = stats.max;
|
|
83
|
+
out[`${prefix}_median_pence`] = stats.median;
|
|
84
|
+
out[`${prefix}_avg_pence`] = stats.avg;
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseResponse(data, options) {
|
|
89
|
+
const prefix = (options && options.fieldPrefix) || 'applicable_rates';
|
|
90
|
+
const edges = ((data.applicableRates || {}).edges) || [];
|
|
91
|
+
const slots = edges.map(e => ({
|
|
92
|
+
valid_from: e.node.validFrom,
|
|
93
|
+
valid_to: e.node.validTo,
|
|
94
|
+
value_pence_per_kwh: toNumber(e.node.value)
|
|
95
|
+
}));
|
|
96
|
+
|
|
97
|
+
slots.sort((a, b) => new Date(a.valid_from) - new Date(b.valid_from));
|
|
98
|
+
|
|
99
|
+
const stats = _stats(slots);
|
|
100
|
+
return _emit(prefix, slots, Date.now(), stats);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const defaultData = {
|
|
104
|
+
applicable_rates: [],
|
|
105
|
+
applicable_rates_count: 0,
|
|
106
|
+
applicable_rates_current_pence: null,
|
|
107
|
+
applicable_rates_current_gbp: null,
|
|
108
|
+
applicable_rates_prev_pence: null,
|
|
109
|
+
applicable_rates_prev_gbp: null,
|
|
110
|
+
applicable_rates_prev_to: null,
|
|
111
|
+
applicable_rates_next_pence: null,
|
|
112
|
+
applicable_rates_next_gbp: null,
|
|
113
|
+
applicable_rates_next_from: null,
|
|
114
|
+
applicable_rates_error: null,
|
|
115
|
+
applicable_rates_min_pence: null,
|
|
116
|
+
applicable_rates_max_pence: null,
|
|
117
|
+
applicable_rates_median_pence: null,
|
|
118
|
+
applicable_rates_avg_pence: null,
|
|
119
|
+
electricity_export_rate: [],
|
|
120
|
+
electricity_export_rate_count: 0,
|
|
121
|
+
electricity_export_rate_current_pence: null,
|
|
122
|
+
electricity_export_rate_current_gbp: null,
|
|
123
|
+
electricity_export_rate_prev_pence: null,
|
|
124
|
+
electricity_export_rate_prev_gbp: null,
|
|
125
|
+
electricity_export_rate_prev_to: null,
|
|
126
|
+
electricity_export_rate_next_pence: null,
|
|
127
|
+
electricity_export_rate_next_gbp: null,
|
|
128
|
+
electricity_export_rate_next_from: null,
|
|
129
|
+
electricity_export_rate_error: null,
|
|
130
|
+
electricity_export_rate_min_pence: null,
|
|
131
|
+
electricity_export_rate_max_pence: null,
|
|
132
|
+
electricity_export_rate_median_pence: null,
|
|
133
|
+
electricity_export_rate_avg_pence: null
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// Text fields cut to the HA state limit (lib/values.js).
|
|
137
|
+
module.exports = { buildQuery, parseResponse: capStrings(parseResponse), currentFields: capStrings(currentFields), defaultData };
|