node-red-contrib-octopus-intelligent 1.6.1 → 1.7.1

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 +135 -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 +113 -8
  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 +1384 -250
  45. package/package.json +1 -1
package/lib/graphql.js CHANGED
@@ -7,8 +7,71 @@ const { version } = require('../package.json');
7
7
  // the main and backend endpoints reachable from a single transport.
8
8
  const USER_AGENT = `node-red-contrib-octopus-intelligent/${version}`;
9
9
 
10
- function graphqlPost(body, token, hostname = 'api.octopus.energy') {
10
+ // A request with no answer must fail, not hang: a hung poll blocks every later poll.
11
+ // The socket timeout below is an idle timeout; REQUEST_TIMEOUT_MS is also the most a
12
+ // whole request may take, so a response that trickles in is cut off too.
13
+ const REQUEST_TIMEOUT_MS = 30000;
14
+
15
+ // The deadline bounds time, not size. Kraken's real answers are tens of kilobytes; a body
16
+ // past this (an error page served in a loop, a misrouted proxy) is cut off and fails.
17
+ const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
18
+
19
+ // The start of a body that isn't JSON (e.g. an HTML error page), on one line. Only the first
20
+ // kilobyte is looked at, however long the body is.
21
+ function snippet(raw) {
22
+ return String(raw).slice(0, 1024).replace(/\s+/g, ' ').trim().slice(0, 80);
23
+ }
24
+
25
+ // Retry-After (RFC 9110): delay seconds or an HTTP date. In ms, or null when absent or unreadable.
26
+ function retryAfterMs(value, nowMs = Date.now()) {
27
+ if (value === undefined || value === null) return null;
28
+ const s = String(value).trim();
29
+ if (/^\d+$/.test(s)) return Number(s) * 1000;
30
+ const at = Date.parse(s);
31
+ return Number.isFinite(at) ? Math.max(0, at - nowMs) : null;
32
+ }
33
+
34
+ // An HTTP error reply. A rate limit (429) or outage (503) can say when to try again:
35
+ // err.retryAfterMs carries it for the caller's back-off.
36
+ function httpError(message, status, headers) {
37
+ const err = new Error(message);
38
+ err.status = status;
39
+ const wait = retryAfterMs(headers && headers['retry-after']);
40
+ if (wait !== null) err.retryAfterMs = wait;
41
+ return err;
42
+ }
43
+
44
+ function isPlainObject(v) {
45
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
46
+ }
47
+
48
+ // Octopus moved the main API from api.octopus.energy to api.oegb-kraken.energy (announced
49
+ // 29 Sep 2026); the old host answers some queries with DOMAIN_MIGRATED ("This API address
50
+ // has changed", issue #4) and is to be retired. savingSessions and wheelOfFortune exist only
51
+ // on the backend host, which has no oegb-kraken.energy equivalent (live probe 2 Dec 2026:
52
+ // the new host returns 400 "Cannot query field"), so those categories pass BACKEND_HOST.
53
+ const MAIN_HOST = 'api.oegb-kraken.energy';
54
+ const BACKEND_HOST = 'api.backend.octopus.energy';
55
+
56
+ function graphqlPost(body, token, hostname = MAIN_HOST) {
11
57
  return new Promise((resolve, reject) => {
58
+ // Settle exactly once: error, close, timeout and end can all arrive for one request.
59
+ let settled = false;
60
+ let deadline = null;
61
+ let req = null;
62
+ const settle = (fn, value) => {
63
+ if (settled) return;
64
+ settled = true;
65
+ if (deadline) clearTimeout(deadline);
66
+ fn(value);
67
+ };
68
+ const fail = (err) => settle(reject, err);
69
+ const timedOut = () => {
70
+ if (settled) return;
71
+ if (req && typeof req.destroy === 'function') req.destroy();
72
+ fail(new Error(`Octopus API request timed out after ${REQUEST_TIMEOUT_MS / 1000}s`));
73
+ };
74
+
12
75
  const payload = JSON.stringify(body);
13
76
  const headers = {
14
77
  'Content-Type': 'application/json',
@@ -19,26 +82,68 @@ function graphqlPost(body, token, hostname = 'api.octopus.energy') {
19
82
  // "JWT " prefix passes main-endpoint validation but fails sub-resolver
20
83
  // auth on api.backend.octopus.energy (verified live 2026-05-11).
21
84
  if (token) headers['Authorization'] = token;
22
- const req = https.request({
85
+ let gotResponse = false;
86
+ // Set before the request: a mocked or very fast response can settle synchronously.
87
+ deadline = setTimeout(timedOut, REQUEST_TIMEOUT_MS);
88
+ req = https.request({
23
89
  hostname,
24
90
  path: '/v1/graphql/',
25
91
  method: 'POST',
26
- headers
92
+ headers,
93
+ timeout: REQUEST_TIMEOUT_MS // also covers DNS and connecting
27
94
  }, (res) => {
95
+ gotResponse = true;
28
96
  let raw = '';
29
- res.on('data', chunk => raw += chunk);
97
+ let bytes = 0;
98
+ let ended = false;
99
+ res.on('data', (chunk) => {
100
+ if (settled) return;
101
+ bytes += chunk.length;
102
+ if (bytes > MAX_RESPONSE_BYTES) {
103
+ if (req && typeof req.destroy === 'function') req.destroy();
104
+ fail(new Error('Octopus API response too large'));
105
+ return;
106
+ }
107
+ raw += chunk;
108
+ });
30
109
  res.on('end', () => {
110
+ ended = true;
111
+ if (settled) return;
112
+ const status = res.statusCode;
113
+ // A gateway, rate-limit or outage reply: say so ("HTTP 503"), unless it carries
114
+ // GraphQL errors, which callers read for the Kraken error code.
115
+ const notOk = typeof status === 'number' && (status < 200 || status >= 300);
116
+ let data;
31
117
  try {
32
- resolve({ data: JSON.parse(raw), status: res.statusCode, headers: res.headers });
118
+ data = JSON.parse(raw);
33
119
  } catch (e) {
34
- reject(new Error('Failed to parse API response: ' + e.message));
120
+ if (notOk) return fail(httpError(`HTTP ${status}: ${snippet(raw)}`, status, res.headers));
121
+ return fail(new Error('Failed to parse API response: ' + e.message));
35
122
  }
123
+ if (notOk && !(data && Array.isArray(data.errors))) return fail(httpError(`HTTP ${status}`, status, res.headers));
124
+ // Callers read data.errors and data.data: a body of null, a string or a list is
125
+ // not a GraphQL answer and would only fail later with a TypeError.
126
+ if (!isPlainObject(data)) return fail(new Error(`Unexpected response shape: ${snippet(raw)}`));
127
+ settle(resolve, { data, status, headers: res.headers });
36
128
  });
129
+ // A connection closed part way through the body gives no 'end' and no 'error'.
130
+ const closedEarly = () => {
131
+ if (!ended && !res.complete) fail(new Error('Octopus API connection closed before the response completed'));
132
+ };
133
+ res.on('aborted', closedEarly);
134
+ res.on('close', closedEarly);
135
+ });
136
+ req.on('error', fail);
137
+ // Once a response has started, its own close handling above decides.
138
+ req.on('close', () => {
139
+ if (!gotResponse) fail(new Error('Octopus API connection closed before a response arrived'));
37
140
  });
38
- req.on('error', reject);
141
+ if (typeof req.setTimeout === 'function') {
142
+ req.setTimeout(REQUEST_TIMEOUT_MS, timedOut);
143
+ }
39
144
  req.write(payload);
40
145
  req.end();
41
146
  });
42
147
  }
43
148
 
44
- module.exports = { graphqlPost };
149
+ module.exports = { graphqlPost, MAIN_HOST, BACKEND_HOST, snippet, retryAfterMs, REQUEST_TIMEOUT_MS, MAX_RESPONSE_BYTES };
@@ -1,22 +1,80 @@
1
1
  'use strict';
2
2
  const https = require('https');
3
3
 
4
+ // Idle timeout for the socket, and also the most a whole request may take.
5
+ const REQUEST_TIMEOUT_MS = 30000;
6
+ // The npm registry answer is a few kilobytes; a body past this is cut off and fails.
7
+ const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
8
+
4
9
  function httpGetJson(url) {
5
10
  return new Promise((resolve, reject) => {
6
- const req = https.get(url, res => {
11
+ // Settle exactly once: error, close, timeout and end can all arrive for one request.
12
+ let settled = false;
13
+ let deadline = null;
14
+ let req = null;
15
+ let gotResponse = false;
16
+ const settle = (fn, value) => {
17
+ if (settled) return;
18
+ settled = true;
19
+ if (deadline) clearTimeout(deadline);
20
+ fn(value);
21
+ };
22
+ const fail = (err) => settle(reject, err);
23
+ const timedOut = () => {
24
+ if (settled) return;
25
+ if (req && typeof req.destroy === 'function') req.destroy();
26
+ fail(new Error(`Request timed out after ${REQUEST_TIMEOUT_MS / 1000}s`));
27
+ };
28
+ // Set before the request: a mocked or very fast response can settle synchronously.
29
+ deadline = setTimeout(timedOut, REQUEST_TIMEOUT_MS);
30
+ req = https.get(url, { timeout: REQUEST_TIMEOUT_MS }, res => {
31
+ gotResponse = true;
7
32
  if (res.statusCode < 200 || res.statusCode >= 300) {
8
33
  res.resume();
9
- return reject(new Error(`HTTP ${res.statusCode}`));
34
+ return fail(new Error(`HTTP ${res.statusCode}`));
10
35
  }
11
36
  let body = '';
12
- res.on('data', chunk => { body += chunk; });
37
+ let bytes = 0;
38
+ let ended = false;
39
+ res.on('data', (chunk) => {
40
+ if (settled) return;
41
+ bytes += chunk.length;
42
+ if (bytes > MAX_RESPONSE_BYTES) {
43
+ if (req && typeof req.destroy === 'function') req.destroy();
44
+ fail(new Error('Response too large'));
45
+ return;
46
+ }
47
+ body += chunk;
48
+ });
13
49
  res.on('end', () => {
14
- try { resolve(JSON.parse(body)); }
15
- catch (e) { reject(new Error(`JSON parse: ${e.message}`)); }
50
+ ended = true;
51
+ if (settled) return;
52
+ let data;
53
+ try { data = JSON.parse(body); }
54
+ catch (e) { return fail(new Error(`JSON parse: ${e.message}`)); }
55
+ // Callers read fields off the answer: null, a string or a list is not one.
56
+ if (data === null || typeof data !== 'object' || Array.isArray(data)) {
57
+ return fail(new Error('Unexpected response shape'));
58
+ }
59
+ settle(resolve, data);
16
60
  });
61
+ // A connection closed part way through the body gives no 'end' and no 'error'.
62
+ const closedEarly = () => {
63
+ if (!ended && !res.complete) fail(new Error('Connection closed before the response completed'));
64
+ };
65
+ res.on('aborted', closedEarly);
66
+ res.on('close', closedEarly);
67
+ });
68
+ req.on('error', fail);
69
+ // Once a response has started, its own close handling above decides.
70
+ req.on('close', () => {
71
+ if (!gotResponse) fail(new Error('Connection closed before a response arrived'));
17
72
  });
18
- req.on('error', reject);
73
+ if (typeof req.setTimeout === 'function') {
74
+ req.setTimeout(REQUEST_TIMEOUT_MS, timedOut);
75
+ }
19
76
  });
20
77
  }
21
78
 
22
79
  module.exports = httpGetJson;
80
+ module.exports.MAX_RESPONSE_BYTES = MAX_RESPONSE_BYTES;
package/lib/payload.js CHANGED
@@ -34,6 +34,7 @@ function buildDefaultPayload(state) {
34
34
  window_start_locale: null, window_end_locale: null,
35
35
  smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended,
36
36
  charge_cap: null,
37
+ boosting: null, boost_error: null,
37
38
  // V2 fields — new categories
38
39
  electricity_unit_rate: null, electricity_standing_charge: null,
39
40
  electricity_tariff_code: null, electricity_valid_from: null, electricity_valid_to: null,
@@ -80,6 +81,20 @@ function buildDefaultPayload(state) {
80
81
  applicable_rates_median_pence: null, applicable_rates_avg_pence: null,
81
82
  electricity_export_rate_min_pence: null, electricity_export_rate_max_pence: null,
82
83
  electricity_export_rate_median_pence: null, electricity_export_rate_avg_pence: null,
84
+ // v1.7.0 — SmartFlex vehicle / charge point (smartflex_vehicle category)
85
+ vehicle_make: null, vehicle_model: null,
86
+ vehicle_battery_kwh: null, charger_power_kw: null,
87
+ device_state: null, device_alerts: [],
88
+ last_session: null, charging_sessions: [],
89
+ last_session_kwh: null, last_session_soc_final: null, last_session_problem: null,
90
+ smartflex_vehicle_error: null,
91
+ // v1.7.0 — SmartFlex inverter, experimental (smartflex_inverter category)
92
+ inverter_make: null, inverter_model: null, solar_peak_kw: null,
93
+ inverter_power_kw: null, inverter_connection_status: null, inverter_online: null,
94
+ home_battery_power_kw: null, home_battery_soc: null,
95
+ solar_power_kw: null, grid_power_kw: null,
96
+ site_consumption_kw: null, site_export_kw: null,
97
+ smartflex_inverter_error: null,
83
98
  // v1.5 — update check
84
99
  installed_version: null, latest_version: null,
85
100
  update_available: false, update_check_at: null, update_check_error: null
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ // Quick retry of the charging poll (1.6.2). Octopus fails flexPlannedDispatches (KT-CT-4340)
4
+ // and sometimes devices.preferences (KT-CT-4339) for a few minutes around :00 and :30.
5
+ const RETRY_CODES = ['KT-CT-4340', 'KT-CT-4339'];
6
+
7
+ // Delay before retry 1, 2, 3; every later retry waits as long as the last one.
8
+ const RETRY_DELAYS_MS = [30000, 60000, 120000];
9
+
10
+ // Octopus allows 5 flexPlannedDispatches queries a minute; stay at 3 or fewer.
11
+ const DISPATCH_RATE_MAX = 3;
12
+ const DISPATCH_RATE_WINDOW_MS = 60000;
13
+
14
+ // A backward wall-clock step of at least this much is a real clock change (lib/scheduler.js
15
+ // re-polls after one); a smaller step is an NTP correction and is ignored.
16
+ const CLOCK_STEP_BACK_MS = 60 * 1000;
17
+
18
+ function retryDelay(retryNo) {
19
+ const i = Math.min(Math.max(retryNo, 1), RETRY_DELAYS_MS.length) - 1;
20
+ return RETRY_DELAYS_MS[i];
21
+ }
22
+
23
+ function isRetryable(err) {
24
+ return !!err && RETRY_CODES.includes(err.code);
25
+ }
26
+
27
+ // Start of the next interval slot, counted from the epoch as the scheduler's isDue does.
28
+ function nextSlotStart(nowMs, intervalMs) {
29
+ return (Math.floor(nowMs / intervalMs) + 1) * intervalMs;
30
+ }
31
+
32
+ // Sliding record of query times. A query at time t counts against every closed window
33
+ // [t, t + windowMs]; nextAllowedAt gives the earliest time one more query keeps every
34
+ // such window at or under max.
35
+ function createRateWindow({ max = DISPATCH_RATE_MAX, windowMs = DISPATCH_RATE_WINDOW_MS } = {}) {
36
+ let times = [];
37
+ // A time after `now` is left from before the wall clock stepped back. After a large step
38
+ // it no longer counts; after a small one (an NTP correction) it counts as made now.
39
+ const recentAt = (now) => times
40
+ .filter((t) => t - now < CLOCK_STEP_BACK_MS)
41
+ .map((t) => Math.min(t, now))
42
+ .filter((t) => now - t <= windowMs);
43
+ const prune = (now) => { times = recentAt(now); };
44
+ return {
45
+ record(now = Date.now()) {
46
+ prune(now);
47
+ times.push(now);
48
+ },
49
+ // Read-only: asking must not change the window.
50
+ nextAllowedAt(now = Date.now()) {
51
+ const recent = recentAt(now).sort((a, b) => a - b);
52
+ if (recent.length < max) return now;
53
+ return recent[recent.length - max] + windowMs + 1;
54
+ },
55
+ };
56
+ }
57
+
58
+ function formatDuration(ms) {
59
+ const total = Math.max(0, Math.round(ms / 1000));
60
+ const h = Math.floor(total / 3600);
61
+ const m = Math.floor((total % 3600) / 60);
62
+ const s = total % 60;
63
+ if (h > 0) return `${h}h ${m}m ${s}s`;
64
+ if (m > 0) return `${m}m ${s}s`;
65
+ return `${s}s`;
66
+ }
67
+
68
+ module.exports = {
69
+ RETRY_CODES, RETRY_DELAYS_MS, DISPATCH_RATE_MAX, DISPATCH_RATE_WINDOW_MS, CLOCK_STEP_BACK_MS,
70
+ retryDelay, isRetryable, nextSlotStart, createRateWindow, formatDuration,
71
+ };
package/lib/poll-tick.js CHANGED
@@ -1,10 +1,15 @@
1
1
  'use strict';
2
2
 
3
+ const { graphqlError, truncate, isNetworkError } = require('./graphql-errors');
4
+
5
+ // Every <category>_error is short text ("KT-CT-1111: Unauthorized" or the plain message),
6
+ // never the raw Kraken errors JSON, and under 255 characters: Home Assistant rejects a
7
+ // longer state.
3
8
  function simplePoll(queryFn, parseFn, graphqlPost) {
4
9
  return async function poll(token) {
5
10
  const { query, variables, hostname } = queryFn();
6
11
  const response = await graphqlPost({ query, variables }, token, hostname);
7
- if (response.data.errors) throw new Error(JSON.stringify(response.data.errors));
12
+ if (response.data.errors) throw graphqlError(response.data.errors);
8
13
  if (!response.data.data) throw new Error('Response missing data');
9
14
  return parseFn(response.data.data);
10
15
  };
@@ -13,32 +18,95 @@ function simplePoll(queryFn, parseFn, graphqlPost) {
13
18
  const { isDue } = require('./scheduler');
14
19
  const { mergePayload } = require('./payload');
15
20
 
16
- async function runTick({ categories, state, getToken, now = Date.now }) {
21
+ // A category's error goes to <id>_error and, when the category sets errorField, to that field
22
+ // too (the export rates poll feeds the Electricity Export Rate Error sensors this way).
23
+ function errorUpdate(cat, value) {
24
+ const update = { [`${cat.id}_error`]: value };
25
+ if (cat.errorField) update[cat.errorField] = value;
26
+ return update;
27
+ }
28
+
29
+ // Mark a category polled, unless it was forced due (forceCategoryDue bumps forceSeq) after
30
+ // `seq` was read: then it stays due, so the forced poll isn't lost behind one in flight.
31
+ function markPolled(cat, seq, at) {
32
+ cat.lastPolled = (cat.forceSeq || 0) !== seq ? 0 : at;
33
+ }
34
+
35
+ // After a failed token request a category is retried after 60 s, then 2, 4, 8 and at most
36
+ // 10 minutes while auth keeps failing, rather than waiting a whole interval (up to an hour)
37
+ // or trying again every second. Its normal slot still applies if that comes sooner.
38
+ const AUTH_RETRY_BASE_MS = 60000;
39
+ const AUTH_RETRY_MAX_MS = 600000;
40
+
41
+ function authRetryDelay(failures) {
42
+ return Math.min(AUTH_RETRY_BASE_MS * 2 ** (Math.max(failures, 1) - 1), AUTH_RETRY_MAX_MS);
43
+ }
44
+
45
+ // update_check reads npm, not Octopus: it sets needsToken: false.
46
+ const needsToken = (cat) => cat.needsToken !== false;
47
+
48
+ async function runTick({ categories, state, getToken, now = Date.now, isStale }) {
17
49
  const due = categories.filter((c) => c.enabled && isDue(c));
18
- if (due.length === 0) return { state, emitted: false };
50
+ if (due.length === 0) return { state, changes: {}, emitted: false };
51
+ // `changes` holds only what this tick wrote, so the caller can apply it onto its current
52
+ // state: anything written there while the tick waited on Octopus is kept.
53
+ let newState = state;
54
+ let changes = {};
55
+ const apply = (partial) => {
56
+ newState = mergePayload(newState, partial);
57
+ changes = mergePayload(changes, partial);
58
+ };
59
+ let toPoll = due;
19
60
  let token;
20
- try {
21
- token = await getToken();
22
- } catch (e) {
23
- let newState = state;
24
- for (const cat of due) {
25
- newState = mergePayload(newState, { [`${cat.id}_error`]: `Auth failed: ${e.message}` });
26
- cat.lastPolled = now();
61
+ if (due.some(needsToken)) {
62
+ const seqAtAuth = due.map((c) => c.forceSeq || 0);
63
+ try {
64
+ token = await getToken();
65
+ } catch (e) {
66
+ const text = truncate(`Auth failed: ${e.message}`);
67
+ due.forEach((cat, i) => {
68
+ if (!needsToken(cat)) return;
69
+ apply(errorUpdate(cat, text));
70
+ markPolled(cat, seqAtAuth[i], now());
71
+ cat.authFailures = (cat.authFailures || 0) + 1;
72
+ // A rate-limited token request (429 with Retry-After) waits at least that long.
73
+ const wait = Number.isFinite(e && e.retryAfterMs) ? Math.min(e.retryAfterMs, AUTH_RETRY_MAX_MS) : 0;
74
+ cat.authRetryAt = now() + Math.max(authRetryDelay(cat.authFailures), wait);
75
+ });
76
+ // Categories that need no token still run.
77
+ toPoll = due.filter((cat) => !needsToken(cat));
27
78
  }
28
- return { state: newState, emitted: true };
29
79
  }
30
- let newState = state;
31
- for (const cat of due) {
80
+ // Set after the first time-out, dropped connection or HTTP 5xx from Octopus. The other
81
+ // Octopus categories are then left due for the next tick rather than each waiting up to
82
+ // 30 s here, so an outage can't make one tick run for 10 minutes.
83
+ let octopusDown = false;
84
+ // Marked polled only when the tick ends current: a tick replaced by a newer one (the
85
+ // watchdog in lib/scheduler.js) has its results dropped by the caller, so what it polled
86
+ // must stay due for the newer tick.
87
+ const polled = [];
88
+ for (const cat of toPoll) {
89
+ // A newer tick has taken over: stop here so categories aren't polled twice.
90
+ if (isStale && isStale()) break;
91
+ if (octopusDown && needsToken(cat)) continue;
92
+ const seq = cat.forceSeq || 0;
93
+ // Auth worked (or isn't needed): back to the normal interval.
94
+ cat.authFailures = 0;
95
+ cat.authRetryAt = null;
32
96
  try {
33
- const partial = await cat.poll(token);
34
- newState = mergePayload(newState, partial);
35
- newState = mergePayload(newState, { [`${cat.id}_error`]: null });
97
+ const partial = await (isStale ? cat.poll(token, isStale) : cat.poll(token));
98
+ apply(partial);
99
+ // A poll that kept part of its data can report what failed in <id>_error.
100
+ const ownError = partial && partial[`${cat.id}_error`];
101
+ apply(errorUpdate(cat, ownError ? truncate(ownError) : null));
36
102
  } catch (e) {
37
- newState = mergePayload(newState, { [`${cat.id}_error`]: e.message });
103
+ apply(errorUpdate(cat, truncate(e.message)));
104
+ if (needsToken(cat) && isNetworkError(e)) octopusDown = true;
38
105
  }
39
- cat.lastPolled = now();
106
+ polled.push({ cat, seq, at: now() });
40
107
  }
41
- return { state: newState, emitted: true };
108
+ if (!(isStale && isStale())) polled.forEach(({ cat, seq, at }) => markPolled(cat, seq, at));
109
+ return { state: newState, changes, emitted: true };
42
110
  }
43
111
 
44
- module.exports = { simplePoll, runTick };
112
+ module.exports = { simplePoll, runTick, AUTH_RETRY_BASE_MS, AUTH_RETRY_MAX_MS };
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ const { shown } = require('./values');
2
3
 
3
4
  // Ready-by times offered by the Octopus app: every half hour, 00:00–23:30.
4
5
  const TIME_OPTIONS = Array.from({ length: 48 }, (_, i) => {
@@ -12,7 +13,8 @@ function validateTime(time) {
12
13
  }
13
14
  return {
14
15
  ok: false,
15
- error: `Invalid ready-by time '${time}' — must be HH:MM on the hour or half hour (00:00–23:30)`,
16
+ // shown(): at most 40 characters of the value, and no throw for a Symbol or a bare object
17
+ error: `Invalid ready-by time '${shown(time)}' — must be HH:MM on the hour or half hour (00:00–23:30)`,
16
18
  };
17
19
  }
18
20
 
@@ -23,7 +25,7 @@ function validateLimit(limit) {
23
25
  if (typeof limit === 'number') n = limit;
24
26
  else if (typeof limit === 'string' && /^\s*\d+(\.\d+)?\s*$/.test(limit)) n = Number(limit);
25
27
  if (!Number.isFinite(n) || n <= 0) {
26
- return { ok: false, error: `Invalid charge limit '${limit}' — must be a number between 5 and 100` };
28
+ return { ok: false, error: `Invalid charge limit '${shown(limit)}' — must be a number between 5 and 100` };
27
29
  }
28
30
  const clamped = Math.min(100, Math.max(5, n));
29
31
  return { ok: true, limit: Math.round(clamped / 5) * 5 };
package/lib/scheduler.js CHANGED
@@ -1,8 +1,32 @@
1
1
  'use strict';
2
2
 
3
+ // A tick running longer than this is treated as stuck: later ticks may run again.
4
+ // A busy tick can make about 17 requests, each allowed 30 s, so stay well above that.
5
+ const STUCK_TICK_MS = 10 * 60 * 1000;
6
+
7
+ // Monotonic clock: a wall-clock jump (e.g. NTP on a Pi) must not look like a stuck tick.
8
+ // `performance` is only a global from Node 16; package.json allows Node 14, so fall back
9
+ // to perf_hooks. Looked up on each call so test fake timers still apply.
10
+ const { performance: perfHooksPerformance } = require('perf_hooks');
11
+ const monotonicNow = () => (typeof performance !== 'undefined' ? performance : perfHooksPerformance).now();
12
+
13
+ // A backward wall-clock step of at least this much re-polls what was polled "in the future".
14
+ // A smaller step (an NTP correction of a second or two) only moves lastPolled back to now.
15
+ const { CLOCK_STEP_BACK_MS } = require('./poll-retry');
16
+
3
17
  function isDue(cat) {
4
18
  if (!cat.enabled) return false;
5
19
  if (cat.lastPolled === 0) return true;
20
+ // Polled "in the future": the wall clock has stepped back. After a large step, poll now
21
+ // rather than wait for the clock to catch up. After a small one, treat it as polled now,
22
+ // so a correction of a second or two does not re-poll every category.
23
+ const nowMs = Date.now();
24
+ if (cat.lastPolled > nowMs) {
25
+ if (cat.lastPolled - nowMs >= CLOCK_STEP_BACK_MS) return true;
26
+ cat.lastPolled = nowMs;
27
+ }
28
+ // A short retry after a failed token request (lib/poll-tick.js).
29
+ if (cat.authRetryAt && Date.now() >= cat.authRetryAt) return true;
6
30
  const slot = ts => Math.floor(ts / cat.intervalMs);
7
31
  return slot(Date.now()) > slot(cat.lastPolled);
8
32
  }
@@ -12,36 +36,50 @@ function alignedStart(nowMs) {
12
36
  return ms === 0 ? 1000 : 1000 - ms;
13
37
  }
14
38
 
15
- function wrapWithInFlightGuard(fn) {
39
+ function wrapWithInFlightGuard(fn, { maxMs = STUCK_TICK_MS, onStuck } = {}) {
16
40
  let inFlight = false;
41
+ let startedAt = 0;
42
+ let run = 0;
17
43
  return async function guarded(...args) {
18
- if (inFlight) return;
44
+ if (inFlight) {
45
+ const age = monotonicNow() - startedAt;
46
+ if (age < maxMs) return;
47
+ if (onStuck) onStuck(age);
48
+ }
49
+ const id = ++run;
19
50
  inFlight = true;
51
+ startedAt = monotonicNow();
52
+ // The tick can ask whether a newer tick has replaced it, and stop.
53
+ const isStale = () => id !== run;
20
54
  try {
21
- return await fn(...args);
55
+ return await fn(...args, isStale);
22
56
  } finally {
23
- inFlight = false;
57
+ // Only the newest tick may clear the flag; a stuck tick that ends late must not.
58
+ if (id === run) inFlight = false;
24
59
  }
25
60
  };
26
61
  }
27
62
 
28
- function createScheduler(onTick) {
29
- const guarded = wrapWithInFlightGuard(onTick);
63
+ function createScheduler(onTick, { onStuck } = {}) {
64
+ const guarded = wrapWithInFlightGuard(onTick, { onStuck });
65
+ let startTimer = null;
30
66
  let handle = null;
31
67
 
32
68
  function start() {
33
69
  const delay = alignedStart(Date.now());
34
- setTimeout(() => {
70
+ startTimer = setTimeout(() => {
71
+ startTimer = null;
35
72
  guarded();
36
73
  handle = setInterval(guarded, 1000);
37
74
  }, delay);
38
75
  }
39
76
 
40
77
  function stop() {
78
+ if (startTimer) { clearTimeout(startTimer); startTimer = null; }
41
79
  if (handle) { clearInterval(handle); handle = null; }
42
80
  }
43
81
 
44
82
  return { start, stop };
45
83
  }
46
84
 
47
- module.exports = { isDue, alignedStart, createScheduler, wrapWithInFlightGuard };
85
+ module.exports = { isDue, alignedStart, createScheduler, wrapWithInFlightGuard, STUCK_TICK_MS, CLOCK_STEP_BACK_MS };
@@ -216,4 +216,54 @@ const errorSensors = [
216
216
  { id: 'flex_planned_dispatches_error_state', name: 'Flex Planned Dispatches Error State', val: 'flex_planned_dispatches_error' },
217
217
  ];
218
218
 
219
- module.exports = { sensors, errorSensors };
219
+ // v1.7.0 — SmartFlex vehicle / charge point sensors. Kept out of `sensors` because they are
220
+ // only announced when product discovery finds a vehicle or charge point; otherwise their
221
+ // discovery topics are cleared. Names are frozen into HA entity_ids at first discovery:
222
+ // never rename these. The last-session problem flag is a boolean, so it is a binary_sensor
223
+ // in octopus-intelligent.js.
224
+ // nullUnavailable: a text sensor whose null value should read Unavailable in Home Assistant,
225
+ // not the text "None" (review L1). Error text sensors keep "None" for healthy, as before.
226
+ const vehicleSensors = [
227
+ // state_class total: last_reset is the session end (octopus-intelligent.js), so each new
228
+ // finished session adds its kWh to the long-term statistics once (review L2).
229
+ { id: 'last_session_kwh', name: 'Last Charge Session Energy', unit: 'kWh', class: 'energy', stateClass: 'total', icon: 'mdi:ev-station', val: 'last_session_kwh' },
230
+ // No device_class (review L5): battery would feed low-battery alerts and the device's
231
+ // battery display with a value that is only the charge at the end of the last session.
232
+ { id: 'last_session_soc_final', name: 'Last Charge Session Final Charge', unit: '%', stateClass: 'measurement', icon: 'mdi:battery-charging', val: 'last_session_soc_final' },
233
+ { id: 'vehicle_make', name: 'Vehicle Make', icon: 'mdi:car-info', val: 'vehicle_make', category: 'diagnostic', nullUnavailable: true },
234
+ { id: 'vehicle_model', name: 'Vehicle Model', icon: 'mdi:car-info', val: 'vehicle_model', category: 'diagnostic', nullUnavailable: true },
235
+ { id: 'vehicle_battery_kwh', name: 'Vehicle Battery Size', unit: 'kWh', class: 'energy_storage', icon: 'mdi:car-battery', val: 'vehicle_battery_kwh', category: 'diagnostic' },
236
+ { id: 'charger_power_kw', name: 'Charger Power', unit: 'kW', class: 'power', icon: 'mdi:ev-plug-type2', val: 'charger_power_kw', category: 'diagnostic' },
237
+ { id: 'vehicle_device_state', name: 'Vehicle Device State', icon: 'mdi:car-connected', val: 'device_state', category: 'diagnostic', nullUnavailable: true },
238
+ { id: 'smartflex_vehicle_error', name: 'SmartFlex Vehicle Error', icon: 'mdi:alert-circle', val: 'smartflex_vehicle_error', category: 'diagnostic' },
239
+ ];
240
+
241
+ const vehicleErrorSensors = [
242
+ { id: 'smartflex_vehicle_error_state', name: 'SmartFlex Vehicle Error State', val: 'smartflex_vehicle_error' },
243
+ ];
244
+
245
+ // v1.7.0 — SmartFlex inverter sensors, EXPERIMENTAL (not yet verified on a real inverter).
246
+ // Kept out of `sensors` because they are only announced when the editor option
247
+ // enableSmartflexInverter is ticked AND discovery finds an inverter; otherwise their
248
+ // discovery topics are cleared.
249
+ // inverter_online is a boolean, so it is a binary_sensor in octopus-intelligent.js.
250
+ const inverterSensors = [
251
+ { id: 'solar_power_kw', name: 'Solar Power', unit: 'kW', class: 'power', stateClass: 'measurement', icon: 'mdi:solar-power', val: 'solar_power_kw' },
252
+ { id: 'home_battery_power_kw', name: 'Home Battery Power', unit: 'kW', class: 'power', stateClass: 'measurement', icon: 'mdi:home-battery', val: 'home_battery_power_kw' },
253
+ { id: 'home_battery_soc', name: 'Home Battery Charge', unit: '%', class: 'battery', stateClass: 'measurement', val: 'home_battery_soc' },
254
+ { id: 'grid_power_kw', name: 'Grid Power', unit: 'kW', class: 'power', stateClass: 'measurement', icon: 'mdi:transmission-tower', val: 'grid_power_kw' },
255
+ { id: 'site_consumption_kw', name: 'Site Consumption', unit: 'kW', class: 'power', stateClass: 'measurement', icon: 'mdi:home-lightning-bolt', val: 'site_consumption_kw' },
256
+ { id: 'site_export_kw', name: 'Site Export', unit: 'kW', class: 'power', stateClass: 'measurement', icon: 'mdi:transmission-tower-export', val: 'site_export_kw' },
257
+ { id: 'inverter_power_kw', name: 'Inverter Power', unit: 'kW', class: 'power', stateClass: 'measurement', icon: 'mdi:solar-power-variant', val: 'inverter_power_kw' },
258
+ { id: 'inverter_make', name: 'Inverter Make', icon: 'mdi:information-outline', val: 'inverter_make', category: 'diagnostic', nullUnavailable: true },
259
+ { id: 'inverter_model', name: 'Inverter Model', icon: 'mdi:information-outline', val: 'inverter_model', category: 'diagnostic', nullUnavailable: true },
260
+ { id: 'solar_peak_kw', name: 'Solar Peak Power', unit: 'kW', class: 'power', icon: 'mdi:solar-panel-large', val: 'solar_peak_kw', category: 'diagnostic' },
261
+ { id: 'inverter_connection_status', name: 'Inverter Connection Status', icon: 'mdi:lan-connect', val: 'inverter_connection_status', category: 'diagnostic', nullUnavailable: true },
262
+ { id: 'smartflex_inverter_error', name: 'SmartFlex Inverter Error', icon: 'mdi:alert-circle', val: 'smartflex_inverter_error', category: 'diagnostic' },
263
+ ];
264
+
265
+ const inverterErrorSensors = [
266
+ { id: 'smartflex_inverter_error_state', name: 'SmartFlex Inverter Error State', val: 'smartflex_inverter_error' },
267
+ ];
268
+
269
+ module.exports = { sensors, errorSensors, vehicleSensors, vehicleErrorSensors, inverterSensors, inverterErrorSensors };