node-red-contrib-octopus-intelligent 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +597 -442
  2. package/README.md +1234 -980
  3. package/examples/basic-monitoring.json +1 -1
  4. package/examples/boost-on-cheap-or-surplus.json +171 -0
  5. package/examples/charging-and-error-alerts.json +95 -0
  6. package/examples/cheapest-window-planner.json +165 -0
  7. package/examples/daily-charging-summary.json +165 -0
  8. package/examples/ha-dashboard.yaml +667 -599
  9. package/examples/mqtt-integration.json +1 -1
  10. package/examples/node-red-dashboard-flow.json +1377 -1199
  11. package/examples/set-preferences.json +1 -1
  12. package/lib/active-now.js +33 -0
  13. package/lib/api-metrics.js +31 -31
  14. package/lib/auth.js +25 -20
  15. package/lib/boost.js +85 -0
  16. package/lib/categories/account.js +32 -32
  17. package/lib/categories/applicable-rates.js +137 -127
  18. package/lib/categories/completed-dispatches.js +36 -35
  19. package/lib/categories/electricity.js +156 -146
  20. package/lib/categories/flex-planned-dispatches.js +36 -36
  21. package/lib/categories/free-electricity.js +73 -61
  22. package/lib/categories/gas.js +102 -95
  23. package/lib/categories/home-mini.js +45 -37
  24. package/lib/categories/intelligent.js +221 -124
  25. package/lib/categories/octoplus.js +35 -32
  26. package/lib/categories/saving-sessions.js +78 -64
  27. package/lib/categories/smartflex-inverter.js +95 -0
  28. package/lib/categories/smartflex-vehicle.js +198 -0
  29. package/lib/categories/wheel-of-fortune.js +50 -49
  30. package/lib/commands.js +69 -0
  31. package/lib/discovery-retry.js +16 -0
  32. package/lib/discovery.js +154 -85
  33. package/lib/graphql-errors.js +174 -0
  34. package/lib/graphql.js +141 -44
  35. package/lib/http-get-json.js +80 -22
  36. package/lib/payload.js +104 -88
  37. package/lib/poll-retry.js +71 -0
  38. package/lib/poll-tick.js +112 -44
  39. package/lib/preferences.js +34 -0
  40. package/lib/scheduler.js +85 -47
  41. package/lib/sensor-definitions.js +269 -0
  42. package/lib/timezone.js +67 -49
  43. package/lib/update-check.js +38 -38
  44. package/lib/values.js +47 -0
  45. package/octopus-intelligent.html +258 -205
  46. package/octopus-intelligent.js +2816 -1807
  47. package/package.json +54 -54
@@ -1 +1 @@
1
- [{"id":"1","type":"inject","name":"Every 5 min","props":[{"p":"payload"}],"repeat":"300","crontab":"","once":true,"topic":"","payload":"","payloadType":"date","x":130,"y":80,"wires":[["2"]]},{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":false,"x":340,"y":80,"wires":[["3"]]},{"id":"3","type":"debug","name":"Debug Output","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":570,"y":80,"wires":[]}]
1
+ [{"id":"2","type":"octopus-intelligent","name":"Octopus Intelligent","accountNumber":"A-XXXXXXXX","refreshInterval":"5","enableMqtt":false,"x":340,"y":80,"wires":[["3"]]},{"id":"3","type":"debug","name":"Debug Output","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":570,"y":80,"wires":[]}]
@@ -0,0 +1,171 @@
1
+ [
2
+ {
3
+ "id": "ex17-boost-tab",
4
+ "type": "tab",
5
+ "label": "Boost on cheap or spare power",
6
+ "disabled": false,
7
+ "info": "## Boost on cheap or spare power\n\nStarts a boost charge (`set_boost: true`) when the import rate is at or below a threshold, or when you export more than a set number of kW. Cancels it (`set_boost: false`) when that ends.\n\n**Inputs it reads:** `boosting`, `applicable_rates_current_pence`, `site_export_kw`, `boost_error`.\n\n**Setup**\n\n1. Edit the thresholds at the top of the **Decide boost** function.\n2. For the price rule you need a half-hourly import schedule (`applicable_rates`). It suits Agile and other tariffs where prices can drop to zero or below.\n3. For the surplus rule, either tick the experimental SmartFlex inverter option on the node (fills `site_export_kw`, polled every 5 minutes), or send your own reading into the function with `msg.topic = \"surplus_kw\"` and `msg.payload` in kW. Set `SURPLUS_START_KW` to `null` to turn it off.\n4. Octopus can refuse a boost, for example when the car is unplugged or full. The flow then waits `RETRY_MINUTES` before it asks again.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n3. Add a **link in** node before your Octopus Intelligent node and wire it to the node's input.\n4. Open **To Octopus node** on this tab and tick that link in.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead."
8
+ },
9
+ {
10
+ "id": "ex17-boost-comment",
11
+ "type": "comment",
12
+ "z": "ex17-boost-tab",
13
+ "name": "Read me: boost when power is cheap or spare (edit thresholds in Decide boost)",
14
+ "info": "## Boost on cheap or spare power\n\nStarts a boost charge (`set_boost: true`) when the import rate is at or below a threshold, or when you export more than a set number of kW. Cancels it (`set_boost: false`) when that ends.\n\n**Inputs it reads:** `boosting`, `applicable_rates_current_pence`, `site_export_kw`, `boost_error`.\n\n**Setup**\n\n1. Edit the thresholds at the top of the **Decide boost** function.\n2. For the price rule you need a half-hourly import schedule (`applicable_rates`). It suits Agile and other tariffs where prices can drop to zero or below.\n3. For the surplus rule, either tick the experimental SmartFlex inverter option on the node (fills `site_export_kw`, polled every 5 minutes), or send your own reading into the function with `msg.topic = \"surplus_kw\"` and `msg.payload` in kW. Set `SURPLUS_START_KW` to `null` to turn it off.\n4. Octopus can refuse a boost, for example when the car is unplugged or full. The flow then waits `RETRY_MINUTES` before it asks again.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n3. Add a **link in** node before your Octopus Intelligent node and wire it to the node's input.\n4. Open **To Octopus node** on this tab and tick that link in.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead.",
15
+ "x": 310,
16
+ "y": 40,
17
+ "wires": []
18
+ },
19
+ {
20
+ "id": "ex17-boost-from-octopus",
21
+ "type": "link in",
22
+ "z": "ex17-boost-tab",
23
+ "name": "From Octopus node",
24
+ "links": [],
25
+ "x": 145,
26
+ "y": 160,
27
+ "wires": [
28
+ [
29
+ "ex17-boost-decide"
30
+ ]
31
+ ]
32
+ },
33
+ {
34
+ "id": "ex17-boost-resume",
35
+ "type": "inject",
36
+ "z": "ex17-boost-tab",
37
+ "name": "Automation on",
38
+ "props": [
39
+ {
40
+ "p": "payload"
41
+ },
42
+ {
43
+ "p": "topic",
44
+ "vt": "str"
45
+ }
46
+ ],
47
+ "repeat": "",
48
+ "crontab": "",
49
+ "once": false,
50
+ "onceDelay": 0.1,
51
+ "topic": "automation",
52
+ "payload": "true",
53
+ "payloadType": "bool",
54
+ "x": 170,
55
+ "y": 220,
56
+ "wires": [
57
+ [
58
+ "ex17-boost-decide"
59
+ ]
60
+ ]
61
+ },
62
+ {
63
+ "id": "ex17-boost-pause",
64
+ "type": "inject",
65
+ "z": "ex17-boost-tab",
66
+ "name": "Automation paused",
67
+ "props": [
68
+ {
69
+ "p": "payload"
70
+ },
71
+ {
72
+ "p": "topic",
73
+ "vt": "str"
74
+ }
75
+ ],
76
+ "repeat": "",
77
+ "crontab": "",
78
+ "once": false,
79
+ "onceDelay": 0.1,
80
+ "topic": "automation",
81
+ "payload": "false",
82
+ "payloadType": "bool",
83
+ "x": 180,
84
+ "y": 260,
85
+ "wires": [
86
+ [
87
+ "ex17-boost-decide"
88
+ ]
89
+ ]
90
+ },
91
+ {
92
+ "id": "ex17-boost-surplus",
93
+ "type": "inject",
94
+ "z": "ex17-boost-tab",
95
+ "name": "Test: exporting 2 kW (surplus_kw)",
96
+ "props": [
97
+ {
98
+ "p": "payload"
99
+ },
100
+ {
101
+ "p": "topic",
102
+ "vt": "str"
103
+ }
104
+ ],
105
+ "repeat": "",
106
+ "crontab": "",
107
+ "once": false,
108
+ "onceDelay": 0.1,
109
+ "topic": "surplus_kw",
110
+ "payload": "2",
111
+ "payloadType": "num",
112
+ "x": 210,
113
+ "y": 320,
114
+ "wires": [
115
+ [
116
+ "ex17-boost-decide"
117
+ ]
118
+ ]
119
+ },
120
+ {
121
+ "id": "ex17-boost-decide",
122
+ "type": "function",
123
+ "z": "ex17-boost-tab",
124
+ "name": "Decide boost [edit thresholds]",
125
+ "func": "// Starts a boost charge when import power is cheap (or free, or negative) or when\n// you are exporting spare solar, and cancels it when that ends.\n// It only cancels a boost that this flow started: a boost you start yourself, from\n// the app, Home Assistant or another flow, is left alone.\n//\n// ===== EDIT THESE =====\nconst CHEAP_START_PENCE = 0; // boost when the import rate is at or below this (p/kWh). 0 = free or negative only\nconst CHEAP_STOP_PENCE = 2; // cancel once the rate is above this. Keep it at or above CHEAP_START_PENCE\nconst SURPLUS_START_KW = 1.5; // boost when exporting at least this many kW. null turns the surplus rule off\nconst SURPLUS_STOP_KW = 0.5; // cancel once export drops below this. Keep it at or below SURPLUS_START_KW\nconst RETRY_MINUTES = 30; // ask again after this long if Octopus refused or the boost ended early\nconst OWN_READING_MAX_AGE_MINUTES = 15; // how long a \"surplus_kw\" reading of your own stays valid\n// ======================\n\nconst now = Date.now();\n\n// Pause or resume from the inject nodes: topic \"automation\", payload true or false.\n// Pausing never cancels a boost that is already running.\nif (msg.topic === 'automation') {\n const on = msg.payload === true;\n flow.set('boostAutomationOn', on);\n node.status({ fill: on ? 'green' : 'grey', shape: 'dot', text: on ? 'automation on' : 'automation paused' });\n return null;\n}\n\n// Your own export reading: topic \"surplus_kw\", payload a number in kW (for example from\n// your inverter or meter nodes). It wins over site_export_kw while it is fresh.\nif (msg.topic === 'surplus_kw') {\n const kw = parseFloat(msg.payload);\n flow.set('ownSurplusKw', Number.isFinite(kw) ? kw : null);\n flow.set('ownSurplusAt', now);\n}\n\n// Everything else is the Octopus node's output. Keep the latest so a surplus_kw\n// reading can be judged against it.\nconst p = msg.topic === 'surplus_kw' ? flow.get('lastOctopusPayload') : msg.payload;\nif (!p || typeof p !== 'object') return null;\nflow.set('lastOctopusPayload', p);\n\nif (flow.get('boostAutomationOn') === false) return null; // on unless paused\n\n// boosting: true while a boost runs, false when not, null until the node knows.\nconst boosting = p.boosting;\nif (typeof boosting !== 'boolean') return null;\n\n// Import rate now, in p/kWh, from the half-hourly applicable_rates schedule.\nconst rate = typeof p.applicable_rates_current_pence === 'number' ? p.applicable_rates_current_pence : null;\n\n// Export in kW. site_export_kw needs the experimental SmartFlex inverter option.\nlet surplus = typeof p.site_export_kw === 'number' ? p.site_export_kw : null;\nconst own = flow.get('ownSurplusKw');\nconst ownAt = flow.get('ownSurplusAt') || 0;\nif (typeof own === 'number' && now - ownAt < OWN_READING_MAX_AGE_MINUTES * 60000) surplus = own;\n\nconst cheapStart = rate !== null && rate <= CHEAP_START_PENCE;\nconst cheapHold = rate !== null && rate <= CHEAP_STOP_PENCE;\nconst surplusRule = SURPLUS_START_KW !== null && surplus !== null;\nconst surplusStart = surplusRule && surplus >= SURPLUS_START_KW;\nconst surplusHold = surplusRule && surplus >= SURPLUS_STOP_KW;\n\nconst reason = cheapStart ? `import rate ${rate} p/kWh`\n : surplusStart ? `exporting ${surplus} kW` : null;\nconst keepGoing = cheapHold || surplusHold;\n\nconst startedByFlow = flow.get('boostStartedByFlow') === true;\nconst lastAsk = flow.get('boostLastAskAt') || 0;\nconst retryDue = now - lastAsk >= RETRY_MINUTES * 60000;\n\nnode.status({\n fill: boosting ? 'green' : 'blue', shape: startedByFlow ? 'dot' : 'ring',\n text: `rate ${rate === null ? '--' : rate}p, export ${surplus === null ? '--' : surplus} kW, boosting ${boosting}`,\n});\n\n// Start (or ask again after a refusal or an early finish).\nif (reason && !boosting && (!startedByFlow || retryDue)) {\n flow.set('boostStartedByFlow', true);\n flow.set('boostLastAskAt', now);\n const note = p.boost_error ? ` Last boost error: ${p.boost_error}` : '';\n return [{ payload: { set_boost: true } }, { payload: `Boost requested: ${reason}.${note}` }];\n}\n\n// Stop, but only a boost this flow started.\nif (startedByFlow && !keepGoing) {\n flow.set('boostStartedByFlow', false);\n if (boosting) {\n return [{ payload: { set_boost: false } }, { payload: 'Boost cancelled: no longer cheap or spare.' }];\n }\n}\nreturn null;\n",
126
+ "outputs": 2,
127
+ "timeout": 0,
128
+ "noerr": 0,
129
+ "initialize": "",
130
+ "finalize": "",
131
+ "libs": [],
132
+ "x": 480,
133
+ "y": 220,
134
+ "wires": [
135
+ [
136
+ "ex17-boost-to-octopus"
137
+ ],
138
+ [
139
+ "ex17-boost-debug"
140
+ ]
141
+ ]
142
+ },
143
+ {
144
+ "id": "ex17-boost-to-octopus",
145
+ "type": "link out",
146
+ "z": "ex17-boost-tab",
147
+ "name": "To Octopus node",
148
+ "mode": "link",
149
+ "links": [],
150
+ "x": 715,
151
+ "y": 200,
152
+ "wires": []
153
+ },
154
+ {
155
+ "id": "ex17-boost-debug",
156
+ "type": "debug",
157
+ "z": "ex17-boost-tab",
158
+ "name": "Boost decisions",
159
+ "active": true,
160
+ "tosidebar": true,
161
+ "console": false,
162
+ "tostatus": true,
163
+ "complete": "payload",
164
+ "targetType": "msg",
165
+ "statusVal": "payload",
166
+ "statusType": "auto",
167
+ "x": 740,
168
+ "y": 240,
169
+ "wires": []
170
+ }
171
+ ]
@@ -0,0 +1,95 @@
1
+ [
2
+ {
3
+ "id": "ex17-alerts-tab",
4
+ "type": "tab",
5
+ "label": "Charging and error alerts",
6
+ "disabled": false,
7
+ "info": "## Charging and error alerts\n\nSends a short alert when charging starts or stops, when a boost starts or ends, when any `*_error` field gets a value, changes or clears, and when Octopus posts a new alert for your car or charge point.\n\n**Inputs it reads:** `charging_now`, `boosting`, every field ending in `_error` (for example `intelligent_error`, `applicable_rates_error`, `boost_error`, `smartflex_vehicle_error`), `device_alerts`, `confirmed_limit`, `confirmed_time`, `next_start_locale`.\n\n**Output:** one message per change, with a title in `msg.topic` and the text in `msg.payload`.\n\n**Setup**\n\n1. Choose which alerts you want with the switches at the top of **Spot changes**.\n2. Replace the debug node with your notifier, for example email, Pushover, Telegram or ntfy.\n3. The rate limit node lets one alert through every 10 seconds, so a burst after an outage arrives as a short queue rather than all at once.\n4. The first message after a deploy or restart only sets the baseline, so you are not sent alerts for things that were already true.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead."
8
+ },
9
+ {
10
+ "id": "ex17-alerts-comment",
11
+ "type": "comment",
12
+ "z": "ex17-alerts-tab",
13
+ "name": "Read me: alerts for charging, boosts, errors and device alerts",
14
+ "info": "## Charging and error alerts\n\nSends a short alert when charging starts or stops, when a boost starts or ends, when any `*_error` field gets a value, changes or clears, and when Octopus posts a new alert for your car or charge point.\n\n**Inputs it reads:** `charging_now`, `boosting`, every field ending in `_error` (for example `intelligent_error`, `applicable_rates_error`, `boost_error`, `smartflex_vehicle_error`), `device_alerts`, `confirmed_limit`, `confirmed_time`, `next_start_locale`.\n\n**Output:** one message per change, with a title in `msg.topic` and the text in `msg.payload`.\n\n**Setup**\n\n1. Choose which alerts you want with the switches at the top of **Spot changes**.\n2. Replace the debug node with your notifier, for example email, Pushover, Telegram or ntfy.\n3. The rate limit node lets one alert through every 10 seconds, so a burst after an outage arrives as a short queue rather than all at once.\n4. The first message after a deploy or restart only sets the baseline, so you are not sent alerts for things that were already true.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead.",
15
+ "x": 290,
16
+ "y": 40,
17
+ "wires": []
18
+ },
19
+ {
20
+ "id": "ex17-alerts-from-octopus",
21
+ "type": "link in",
22
+ "z": "ex17-alerts-tab",
23
+ "name": "From Octopus node",
24
+ "links": [],
25
+ "x": 165,
26
+ "y": 140,
27
+ "wires": [
28
+ [
29
+ "ex17-alerts-spot"
30
+ ]
31
+ ]
32
+ },
33
+ {
34
+ "id": "ex17-alerts-spot",
35
+ "type": "function",
36
+ "z": "ex17-alerts-tab",
37
+ "name": "Spot changes [edit switches]",
38
+ "func": "// Turns the node's output into short alerts. It compares each message with the last\n// one and sends one msg per change: msg.topic is a short title, msg.payload the text.\n//\n// ===== EDIT THESE =====\nconst ALERT_CHARGING = true; // charging_now started / stopped\nconst ALERT_BOOST = true; // boosting started / ended\nconst ALERT_ERRORS = true; // any *_error field becoming set or changing\nconst ALERT_RECOVERY = true; // also say when an error clears\nconst ALERT_DEVICE_ALERTS = true; // new Octopus alerts for the car or charge point (device_alerts)\nconst DEVICE_ALERT_MAX_AGE_HOURS = 24; // skip device alerts older than this\nconst IGNORE_ERRORS = ['update_check_error']; // *_error fields you do not want alerts for\n// ======================\n\nconst p = msg.payload;\nif (!p || typeof p !== 'object') return null;\n\nconst prev = context.get('prev');\nconst keepBool = (v, old) => (typeof v === 'boolean' ? v : old);\n\n// Keep only what is compared, not the whole payload. charging_now and boosting can\n// be null for a while (for example during an Octopus outage): the last known value is kept.\nconst snap = {\n charging_now: keepBool(p.charging_now, prev ? prev.charging_now : null),\n boosting: keepBool(p.boosting, prev ? prev.boosting : null),\n errors: {},\n alerts: (Array.isArray(p.device_alerts) ? p.device_alerts : [])\n .map((a) => `${a.published_at}|${a.message}`),\n};\nfor (const [k, v] of Object.entries(p)) {\n if (k.endsWith('_error') && !IGNORE_ERRORS.includes(k)) snap.errors[k] = v || null;\n}\ncontext.set('prev', snap);\n\n// The first message after a deploy or restart only sets the baseline.\nif (!prev) return null;\n\nconst out = [];\nconst say = (topic, text) => out.push({ topic, payload: text });\n\nif (ALERT_CHARGING && typeof prev.charging_now === 'boolean' && prev.charging_now !== snap.charging_now) {\n if (snap.charging_now) {\n const why = snap.boosting ? 'boost' : 'planned slot';\n say('Charging started', `Charging started (${why}). Target ${p.confirmed_limit}% by ${p.confirmed_time}.`);\n } else {\n const next = p.next_start_locale ? ` Next slot starts ${p.next_start_locale}.` : '';\n say('Charging stopped', `Charging stopped.${next}`);\n }\n}\n\nif (ALERT_BOOST && typeof prev.boosting === 'boolean' && prev.boosting !== snap.boosting) {\n say(snap.boosting ? 'Boost started' : 'Boost ended',\n snap.boosting ? 'A boost charge has started.' : 'The boost charge has ended.');\n}\n\nif (ALERT_ERRORS) {\n const label = (k) => k.replace(/_error$/, '').replace(/_/g, ' ');\n const keys = new Set([...Object.keys(prev.errors), ...Object.keys(snap.errors)]);\n for (const k of keys) {\n const was = prev.errors[k] || null;\n const is = snap.errors[k] || null;\n if (!was && is) say(`Error: ${label(k)}`, `${label(k)}: ${is}`);\n else if (was && is && was !== is) say(`Error: ${label(k)}`, `${label(k)} (changed): ${is}`);\n else if (was && !is && ALERT_RECOVERY) say(`Recovered: ${label(k)}`, `${label(k)}: error cleared.`);\n }\n}\n\nif (ALERT_DEVICE_ALERTS) {\n const seen = new Set(prev.alerts);\n const cutoff = Date.now() - DEVICE_ALERT_MAX_AGE_HOURS * 3600000;\n for (const a of p.device_alerts || []) {\n const key = `${a.published_at}|${a.message}`;\n const at = Date.parse(a.published_at);\n if (seen.has(key) || !a.message || (Number.isFinite(at) && at < cutoff)) continue;\n say('Octopus device alert', a.message);\n }\n}\n\nreturn out.length ? [out] : null;\n",
39
+ "outputs": 1,
40
+ "timeout": 0,
41
+ "noerr": 0,
42
+ "initialize": "",
43
+ "finalize": "",
44
+ "libs": [],
45
+ "x": 440,
46
+ "y": 140,
47
+ "wires": [
48
+ [
49
+ "ex17-alerts-rate"
50
+ ]
51
+ ]
52
+ },
53
+ {
54
+ "id": "ex17-alerts-rate",
55
+ "type": "delay",
56
+ "z": "ex17-alerts-tab",
57
+ "name": "1 alert per 10 s",
58
+ "pauseType": "rate",
59
+ "timeout": "5",
60
+ "timeoutUnits": "seconds",
61
+ "rate": "1",
62
+ "nbRateUnits": "10",
63
+ "rateUnits": "second",
64
+ "randomFirst": "1",
65
+ "randomLast": "5",
66
+ "randomUnits": "seconds",
67
+ "drop": false,
68
+ "allowrate": false,
69
+ "outputs": 1,
70
+ "x": 660,
71
+ "y": 140,
72
+ "wires": [
73
+ [
74
+ "ex17-alerts-debug"
75
+ ]
76
+ ]
77
+ },
78
+ {
79
+ "id": "ex17-alerts-debug",
80
+ "type": "debug",
81
+ "z": "ex17-alerts-tab",
82
+ "name": "Alert (swap for your notifier)",
83
+ "active": true,
84
+ "tosidebar": true,
85
+ "console": false,
86
+ "tostatus": true,
87
+ "complete": "payload",
88
+ "targetType": "msg",
89
+ "statusVal": "payload",
90
+ "statusType": "auto",
91
+ "x": 900,
92
+ "y": 140,
93
+ "wires": []
94
+ }
95
+ ]
@@ -0,0 +1,165 @@
1
+ [
2
+ {
3
+ "id": "ex17-window-tab",
4
+ "type": "tab",
5
+ "label": "Cheapest window planner",
6
+ "disabled": false,
7
+ "info": "## Cheapest window planner\n\nEach evening, finds the cheapest run of back-to-back half hours for an appliance (dishwasher, washing machine, hot water) that finishes by a deadline. Then sends a second message when that window starts, which you can wire to a smart plug.\n\n**Inputs it reads:** `applicable_rates` (a list of `{ valid_from, valid_to, value_pence_per_kwh }` for the next 24 hours).\n\n**Setup**\n\n1. Edit `RUN_MINUTES`, `FINISH_BY` and `TIME_ZONE` in **Find cheapest window**.\n2. The **Plan at 18:00** inject runs every day. Agile prices for the next day are usually out by then. Use **Plan now** to test.\n3. Wire the **Window started** output to the thing you want to switch on.\n4. On a tariff with the same price all night the earliest window wins, which is still a sensible answer.\n\nThe planner needs the node to have read the rate schedule at least once. That needs an electricity meter point (MPAN) on the account.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead."
8
+ },
9
+ {
10
+ "id": "ex17-window-comment",
11
+ "type": "comment",
12
+ "z": "ex17-window-tab",
13
+ "name": "Read me: cheapest appliance window before a deadline (edit Find cheapest window)",
14
+ "info": "## Cheapest window planner\n\nEach evening, finds the cheapest run of back-to-back half hours for an appliance (dishwasher, washing machine, hot water) that finishes by a deadline. Then sends a second message when that window starts, which you can wire to a smart plug.\n\n**Inputs it reads:** `applicable_rates` (a list of `{ valid_from, valid_to, value_pence_per_kwh }` for the next 24 hours).\n\n**Setup**\n\n1. Edit `RUN_MINUTES`, `FINISH_BY` and `TIME_ZONE` in **Find cheapest window**.\n2. The **Plan at 18:00** inject runs every day. Agile prices for the next day are usually out by then. Use **Plan now** to test.\n3. Wire the **Window started** output to the thing you want to switch on.\n4. On a tariff with the same price all night the earliest window wins, which is still a sensible answer.\n\nThe planner needs the node to have read the rate schedule at least once. That needs an electricity meter point (MPAN) on the account.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead.",
15
+ "x": 330,
16
+ "y": 40,
17
+ "wires": []
18
+ },
19
+ {
20
+ "id": "ex17-window-from-octopus",
21
+ "type": "link in",
22
+ "z": "ex17-window-tab",
23
+ "name": "From Octopus node",
24
+ "links": [],
25
+ "x": 165,
26
+ "y": 120,
27
+ "wires": [
28
+ [
29
+ "ex17-window-remember"
30
+ ]
31
+ ]
32
+ },
33
+ {
34
+ "id": "ex17-window-remember",
35
+ "type": "function",
36
+ "z": "ex17-window-tab",
37
+ "name": "Remember rates, spot window start",
38
+ "func": "// Keeps the latest import rate schedule (applicable_rates) for the planner, and says\n// when the planned window starts.\n// The node resends its output when the current half-hour rate changes, so this runs\n// at each half-hour boundary as well as after each poll.\nconst p = msg.payload;\nif (!p || typeof p !== 'object') return null;\nif (Array.isArray(p.applicable_rates) && p.applicable_rates.length > 0) {\n flow.set('latestImportRates', p.applicable_rates);\n}\n\nconst plan = flow.get('plannedWindow');\nif (!plan || plan.announced) return null;\nconst now = Date.now();\nconst start = Date.parse(plan.start);\nconst end = Date.parse(plan.end);\nif (now < start) return null;\nplan.announced = true;\nflow.set('plannedWindow', plan);\nif (now >= end) return null; // missed it (for example Node-RED was down)\nreturn { topic: 'Cheapest window started', payload: plan };\n",
39
+ "outputs": 1,
40
+ "timeout": 0,
41
+ "noerr": 0,
42
+ "initialize": "",
43
+ "finalize": "",
44
+ "libs": [],
45
+ "x": 480,
46
+ "y": 120,
47
+ "wires": [
48
+ [
49
+ "ex17-window-started-debug"
50
+ ]
51
+ ]
52
+ },
53
+ {
54
+ "id": "ex17-window-started-debug",
55
+ "type": "debug",
56
+ "z": "ex17-window-tab",
57
+ "name": "Window started (wire to your plug)",
58
+ "active": true,
59
+ "tosidebar": true,
60
+ "console": false,
61
+ "tostatus": true,
62
+ "complete": "payload",
63
+ "targetType": "msg",
64
+ "statusVal": "payload",
65
+ "statusType": "auto",
66
+ "x": 800,
67
+ "y": 120,
68
+ "wires": []
69
+ },
70
+ {
71
+ "id": "ex17-window-daily",
72
+ "type": "inject",
73
+ "z": "ex17-window-tab",
74
+ "name": "Plan at 18:00",
75
+ "props": [
76
+ {
77
+ "p": "payload"
78
+ },
79
+ {
80
+ "p": "topic",
81
+ "vt": "str"
82
+ }
83
+ ],
84
+ "repeat": "",
85
+ "crontab": "00 18 * * *",
86
+ "once": false,
87
+ "onceDelay": 0.1,
88
+ "topic": "",
89
+ "payload": "",
90
+ "payloadType": "date",
91
+ "x": 170,
92
+ "y": 220,
93
+ "wires": [
94
+ [
95
+ "ex17-window-find"
96
+ ]
97
+ ]
98
+ },
99
+ {
100
+ "id": "ex17-window-now",
101
+ "type": "inject",
102
+ "z": "ex17-window-tab",
103
+ "name": "Plan now",
104
+ "props": [
105
+ {
106
+ "p": "payload"
107
+ },
108
+ {
109
+ "p": "topic",
110
+ "vt": "str"
111
+ }
112
+ ],
113
+ "repeat": "",
114
+ "crontab": "",
115
+ "once": false,
116
+ "onceDelay": 0.1,
117
+ "topic": "",
118
+ "payload": "",
119
+ "payloadType": "date",
120
+ "x": 160,
121
+ "y": 260,
122
+ "wires": [
123
+ [
124
+ "ex17-window-find"
125
+ ]
126
+ ]
127
+ },
128
+ {
129
+ "id": "ex17-window-find",
130
+ "type": "function",
131
+ "z": "ex17-window-tab",
132
+ "name": "Find cheapest window [edit settings]",
133
+ "func": "// Finds the cheapest run of back-to-back half hours in the import schedule\n// (applicable_rates) that finishes by your deadline.\n//\n// ===== EDIT THESE =====\nconst RUN_MINUTES = 120; // how long the appliance needs, in minutes\nconst FINISH_BY = '07:00'; // latest finish, HH:MM on the hour or half hour. null = any time in the schedule\nconst TIME_ZONE = 'Europe/London'; // used for FINISH_BY and for the times in the message\n// ======================\n\nconst slots = flow.get('latestImportRates') || [];\nconst now = Date.now();\nconst fmt = (ms) => new Date(ms).toLocaleTimeString('en-GB', { timeZone: TIME_ZONE, hour: '2-digit', minute: '2-digit' });\n\n// Future slots only, in time order, with a price.\nconst future = slots\n .map((s) => ({ from: Date.parse(s.valid_from), to: Date.parse(s.valid_to), p: s.value_pence_per_kwh }))\n .filter((s) => Number.isFinite(s.from) && Number.isFinite(s.to) && typeof s.p === 'number' && s.from >= now)\n .sort((a, b) => a.from - b.from);\n\n// Stop at the first slot that ends at FINISH_BY (in TIME_ZONE).\nlet usable = future;\nif (FINISH_BY) {\n const cut = future.findIndex((s) => fmt(s.to) === FINISH_BY);\n if (cut !== -1) usable = future.slice(0, cut + 1);\n}\n\nconst need = Math.ceil(RUN_MINUTES / 30);\nlet best = null;\nfor (let i = 0; i + need <= usable.length; i++) {\n const run = usable.slice(i, i + need);\n // Back-to-back only: each slot must start where the last one ended.\n if (run.some((s, j) => j > 0 && s.from !== run[j - 1].to)) continue;\n const avg = run.reduce((sum, s) => sum + s.p, 0) / need;\n if (!best || avg < best.avg) best = { start: run[0].from, end: run[need - 1].to, avg };\n}\n\nif (!best) {\n flow.set('plannedWindow', null);\n node.status({ fill: 'yellow', shape: 'ring', text: 'no window found' });\n return { topic: 'No cheapest window', payload: `No ${RUN_MINUTES}-minute window found${FINISH_BY ? ` before ${FINISH_BY}` : ''}. The node may not have read the rate schedule yet.` };\n}\n\nconst plan = {\n start: new Date(best.start).toISOString(),\n end: new Date(best.end).toISOString(),\n avg_pence: Math.round(best.avg * 100) / 100,\n text: `Cheapest ${RUN_MINUTES} minutes: ${fmt(best.start)} to ${fmt(best.end)}, average ${best.avg.toFixed(2)} p/kWh.`,\n announced: false,\n};\nflow.set('plannedWindow', plan);\nnode.status({ fill: 'green', shape: 'dot', text: `${fmt(best.start)} to ${fmt(best.end)}` });\nreturn { topic: 'Cheapest window planned', payload: plan };\n",
134
+ "outputs": 1,
135
+ "timeout": 0,
136
+ "noerr": 0,
137
+ "initialize": "",
138
+ "finalize": "",
139
+ "libs": [],
140
+ "x": 440,
141
+ "y": 240,
142
+ "wires": [
143
+ [
144
+ "ex17-window-plan-debug"
145
+ ]
146
+ ]
147
+ },
148
+ {
149
+ "id": "ex17-window-plan-debug",
150
+ "type": "debug",
151
+ "z": "ex17-window-tab",
152
+ "name": "Planned window",
153
+ "active": true,
154
+ "tosidebar": true,
155
+ "console": false,
156
+ "tostatus": true,
157
+ "complete": "payload",
158
+ "targetType": "msg",
159
+ "statusVal": "payload",
160
+ "statusType": "auto",
161
+ "x": 730,
162
+ "y": 240,
163
+ "wires": []
164
+ }
165
+ ]
@@ -0,0 +1,165 @@
1
+ [
2
+ {
3
+ "id": "ex17-summary-tab",
4
+ "type": "tab",
5
+ "label": "Daily charging summary",
6
+ "disabled": false,
7
+ "info": "## Daily charging summary\n\nSends a morning summary of the charging sessions that ended in the last 24 hours: count, energy, cost and any problems. It also sends a short message as soon as a new session finishes.\n\n**Inputs it reads:** `charging_sessions`, `last_session` (each session has `start`, `end`, `kwh_added`, `soc_change`, `soc_final`, `type`, `cost`, `problems`), `vehicle_make`, `vehicle_model`, `smartflex_vehicle_error`.\n\n**Setup**\n\n1. Change the time on the **Every day at 08:00** inject if you like.\n2. Edit `SUMMARY_HOURS` and `TIME_ZONE` in **Build daily summary**, and `TIME_ZONE` in **Remember sessions**.\n3. Replace the debug nodes with your notifier.\n\nSession data needs a car or charge point under Octopus SmartFlex control. The node reads it every 30 minutes and keeps the last 5 sessions.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead."
8
+ },
9
+ {
10
+ "id": "ex17-summary-comment",
11
+ "type": "comment",
12
+ "z": "ex17-summary-tab",
13
+ "name": "Read me: daily charging summary and session-finished message",
14
+ "info": "## Daily charging summary\n\nSends a morning summary of the charging sessions that ended in the last 24 hours: count, energy, cost and any problems. It also sends a short message as soon as a new session finishes.\n\n**Inputs it reads:** `charging_sessions`, `last_session` (each session has `start`, `end`, `kwh_added`, `soc_change`, `soc_final`, `type`, `cost`, `problems`), `vehicle_make`, `vehicle_model`, `smartflex_vehicle_error`.\n\n**Setup**\n\n1. Change the time on the **Every day at 08:00** inject if you like.\n2. Edit `SUMMARY_HOURS` and `TIME_ZONE` in **Build daily summary**, and `TIME_ZONE` in **Remember sessions**.\n3. Replace the debug nodes with your notifier.\n\nSession data needs a car or charge point under Octopus SmartFlex control. The node reads it every 30 minutes and keeps the last 5 sessions.\n\n**Wiring to your Octopus Intelligent node**\n\nThis flow has no Octopus node of its own. Use the one you already have: each node polls Octopus by itself, so several nodes on one account multiply your API use and can hit Octopus's rate limits.\n\n1. Add a **link out** node after your Octopus Intelligent node and wire the node's output to it.\n2. Open that link out and tick **From Octopus node** on this tab.\n\nIf your node is on the same tab, you can delete the link nodes and wire it directly instead.",
15
+ "x": 300,
16
+ "y": 40,
17
+ "wires": []
18
+ },
19
+ {
20
+ "id": "ex17-summary-from-octopus",
21
+ "type": "link in",
22
+ "z": "ex17-summary-tab",
23
+ "name": "From Octopus node",
24
+ "links": [],
25
+ "x": 165,
26
+ "y": 120,
27
+ "wires": [
28
+ [
29
+ "ex17-summary-remember"
30
+ ]
31
+ ]
32
+ },
33
+ {
34
+ "id": "ex17-summary-remember",
35
+ "type": "function",
36
+ "z": "ex17-summary-tab",
37
+ "name": "Remember sessions, spot new one",
38
+ "func": "// Keeps the latest SmartFlex session data for the daily summary, and sends a short\n// message as soon as a new charging session has finished.\n// Octopus session data is read every 30 minutes, so the message can arrive up to\n// about half an hour after the car stops.\n\nconst TIME_ZONE = 'Europe/London'; // EDIT: used for the times in the text\nconst when = (iso) => (iso ? new Date(iso).toLocaleString('en-GB', { timeZone: TIME_ZONE, weekday: 'short', hour: '2-digit', minute: '2-digit' }) : '?');\nconst describe = (s) => {\n const kwh = typeof s.kwh_added === 'number' ? `${s.kwh_added.toFixed(1)} kWh` : 'unknown kWh';\n const soc = typeof s.soc_final === 'number' ? `, ended at ${s.soc_final}%` : '';\n const cost = s.cost && typeof s.cost.amount === 'number'\n ? (s.cost.currency === 'GBP' ? `, cost £${s.cost.amount.toFixed(2)}` : `, cost ${s.cost.amount} ${s.cost.currency || ''}`.trim())\n : '';\n const problems = s.problems && s.problems.length ? `. Problems: ${s.problems.join(', ')}` : '';\n return `${when(s.start)} to ${when(s.end)}: ${kwh}${soc}${cost}${problems}`;\n};\n\nconst p = msg.payload;\nif (!p || typeof p !== 'object') return null;\n\n// Only store once the vehicle has been read (charging_sessions starts as an empty list).\nif (p.last_session || (Array.isArray(p.charging_sessions) && p.charging_sessions.length)) {\n flow.set('vehicleSessions', {\n vehicle: [p.vehicle_make, p.vehicle_model].filter(Boolean).join(' ') || 'Your car',\n last_session: p.last_session,\n charging_sessions: p.charging_sessions || [],\n read_at: new Date().toISOString(),\n });\n}\nflow.set('vehicleError', p.smartflex_vehicle_error || null);\n\nconst last = p.last_session;\nif (!last) return null;\nconst key = `${last.start}|${last.end}`;\nconst known = context.get('lastSessionKey');\ncontext.set('lastSessionKey', key);\n// The first session seen after a deploy is the baseline, not news.\nif (!known || known === key) return null;\nreturn { topic: 'Charging session finished', payload: `Charging session finished. ${describe(last)}.` };\n",
39
+ "outputs": 1,
40
+ "timeout": 0,
41
+ "noerr": 0,
42
+ "initialize": "",
43
+ "finalize": "",
44
+ "libs": [],
45
+ "x": 470,
46
+ "y": 120,
47
+ "wires": [
48
+ [
49
+ "ex17-summary-new-debug"
50
+ ]
51
+ ]
52
+ },
53
+ {
54
+ "id": "ex17-summary-new-debug",
55
+ "type": "debug",
56
+ "z": "ex17-summary-tab",
57
+ "name": "Session finished",
58
+ "active": true,
59
+ "tosidebar": true,
60
+ "console": false,
61
+ "tostatus": true,
62
+ "complete": "payload",
63
+ "targetType": "msg",
64
+ "statusVal": "payload",
65
+ "statusType": "auto",
66
+ "x": 750,
67
+ "y": 120,
68
+ "wires": []
69
+ },
70
+ {
71
+ "id": "ex17-summary-daily",
72
+ "type": "inject",
73
+ "z": "ex17-summary-tab",
74
+ "name": "Every day at 08:00",
75
+ "props": [
76
+ {
77
+ "p": "payload"
78
+ },
79
+ {
80
+ "p": "topic",
81
+ "vt": "str"
82
+ }
83
+ ],
84
+ "repeat": "",
85
+ "crontab": "00 08 * * *",
86
+ "once": false,
87
+ "onceDelay": 0.1,
88
+ "topic": "",
89
+ "payload": "",
90
+ "payloadType": "date",
91
+ "x": 180,
92
+ "y": 220,
93
+ "wires": [
94
+ [
95
+ "ex17-summary-build"
96
+ ]
97
+ ]
98
+ },
99
+ {
100
+ "id": "ex17-summary-now",
101
+ "type": "inject",
102
+ "z": "ex17-summary-tab",
103
+ "name": "Summary now",
104
+ "props": [
105
+ {
106
+ "p": "payload"
107
+ },
108
+ {
109
+ "p": "topic",
110
+ "vt": "str"
111
+ }
112
+ ],
113
+ "repeat": "",
114
+ "crontab": "",
115
+ "once": false,
116
+ "onceDelay": 0.1,
117
+ "topic": "",
118
+ "payload": "",
119
+ "payloadType": "date",
120
+ "x": 160,
121
+ "y": 260,
122
+ "wires": [
123
+ [
124
+ "ex17-summary-build"
125
+ ]
126
+ ]
127
+ },
128
+ {
129
+ "id": "ex17-summary-build",
130
+ "type": "function",
131
+ "z": "ex17-summary-tab",
132
+ "name": "Build daily summary [edit settings]",
133
+ "func": "// Builds a short daily summary from the sessions the node has read (last 5 sessions).\n//\n// ===== EDIT THESE =====\nconst SUMMARY_HOURS = 24; // sessions that ended within this many hours count as \"today\"\n// TIME_ZONE is the EDIT line just below this block.\n// ======================\n\nconst TIME_ZONE = 'Europe/London'; // EDIT: used for the times in the text\nconst when = (iso) => (iso ? new Date(iso).toLocaleString('en-GB', { timeZone: TIME_ZONE, weekday: 'short', hour: '2-digit', minute: '2-digit' }) : '?');\nconst describe = (s) => {\n const kwh = typeof s.kwh_added === 'number' ? `${s.kwh_added.toFixed(1)} kWh` : 'unknown kWh';\n const soc = typeof s.soc_final === 'number' ? `, ended at ${s.soc_final}%` : '';\n const cost = s.cost && typeof s.cost.amount === 'number'\n ? (s.cost.currency === 'GBP' ? `, cost £${s.cost.amount.toFixed(2)}` : `, cost ${s.cost.amount} ${s.cost.currency || ''}`.trim())\n : '';\n const problems = s.problems && s.problems.length ? `. Problems: ${s.problems.join(', ')}` : '';\n return `${when(s.start)} to ${when(s.end)}: ${kwh}${soc}${cost}${problems}`;\n};\n\nconst data = flow.get('vehicleSessions');\nconst err = flow.get('vehicleError');\nif (!data) {\n const why = err ? ` Last error: ${err}` : '';\n return { topic: 'Daily charging summary', payload: `No SmartFlex session data yet. The node reads it every 30 minutes.${why}` };\n}\n\nconst cutoff = Date.now() - SUMMARY_HOURS * 3600000;\nconst recent = data.charging_sessions.filter((s) => s.end && Date.parse(s.end) >= cutoff);\nconst kwh = recent.reduce((sum, s) => sum + (typeof s.kwh_added === 'number' ? s.kwh_added : 0), 0);\nconst pounds = recent.reduce((sum, s) => sum + (s.cost && s.cost.currency === 'GBP' && typeof s.cost.amount === 'number' ? s.cost.amount : 0), 0);\n\nconst lines = [];\nif (recent.length) {\n lines.push(`${data.vehicle}: ${recent.length} session${recent.length === 1 ? '' : 's'} in the last ${SUMMARY_HOURS} hours, ${kwh.toFixed(1)} kWh, £${pounds.toFixed(2)}.`);\n recent.forEach((s) => lines.push(`- ${describe(s)}`));\n} else {\n lines.push(`${data.vehicle}: no charging sessions ended in the last ${SUMMARY_HOURS} hours.`);\n if (data.last_session) lines.push(`Last session: ${describe(data.last_session)}.`);\n}\nif (err) lines.push(`Note: the last vehicle read had an error: ${err}`);\n\nreturn { topic: 'Daily charging summary', payload: lines.join('\\n') };\n",
134
+ "outputs": 1,
135
+ "timeout": 0,
136
+ "noerr": 0,
137
+ "initialize": "",
138
+ "finalize": "",
139
+ "libs": [],
140
+ "x": 440,
141
+ "y": 240,
142
+ "wires": [
143
+ [
144
+ "ex17-summary-debug"
145
+ ]
146
+ ]
147
+ },
148
+ {
149
+ "id": "ex17-summary-debug",
150
+ "type": "debug",
151
+ "z": "ex17-summary-tab",
152
+ "name": "Daily summary",
153
+ "active": true,
154
+ "tosidebar": true,
155
+ "console": false,
156
+ "tostatus": true,
157
+ "complete": "payload",
158
+ "targetType": "msg",
159
+ "statusVal": "payload",
160
+ "statusType": "auto",
161
+ "x": 720,
162
+ "y": 240,
163
+ "wires": []
164
+ }
165
+ ]