node-red-contrib-octopus-intelligent 1.0.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/LICENSE +21 -0
- package/README.md +370 -0
- package/octopus-intelligent.html +63 -0
- package/octopus-intelligent.js +862 -0
- package/package.json +42 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Andrew Somerharju Neale
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
# node-red-contrib-octopus-intelligent
|
|
2
|
+
|
|
3
|
+
> Node-RED integration for **Octopus Energy Intelligent Octopus Go** with automatic Home Assistant MQTT discovery
|
|
4
|
+
|
|
5
|
+
Monitor your EV charging slots, control charge limits, and manage ready times directly from Home Assistant - all automatically configured via MQTT discovery.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/node-red-contrib-octopus-intelligent)
|
|
8
|
+
[](https://opensource.org/licenses/MIT)
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 🤝 Support This Project
|
|
13
|
+
|
|
14
|
+
Found this useful? Support continued development:
|
|
15
|
+
|
|
16
|
+
<table>
|
|
17
|
+
<tr>
|
|
18
|
+
<td width="33%" align="center">
|
|
19
|
+
|
|
20
|
+
### ⭐ GitHub Star
|
|
21
|
+
Star the repository to show your support!
|
|
22
|
+
|
|
23
|
+
[⭐ Star on GitHub](https://github.com/ASomerN/node-red-contrib-octopus-intelligent)
|
|
24
|
+
|
|
25
|
+
</td>
|
|
26
|
+
<td width="33%" align="center">
|
|
27
|
+
|
|
28
|
+
### 💖 Sponsor
|
|
29
|
+
Support ongoing development and maintenance
|
|
30
|
+
|
|
31
|
+
[Become a Sponsor](https://github.com/sponsors/ASomerN)
|
|
32
|
+
|
|
33
|
+
</td>
|
|
34
|
+
<td width="33%" align="center">
|
|
35
|
+
|
|
36
|
+
### ☕ Buy Me a Coffee
|
|
37
|
+
If this project has helped you!
|
|
38
|
+
|
|
39
|
+
[](https://www.paypal.com/donate?hosted_button_id=A2B8ZFEJBE2S6)
|
|
40
|
+
|
|
41
|
+
</td>
|
|
42
|
+
</tr>
|
|
43
|
+
</table>
|
|
44
|
+
|
|
45
|
+
**Your support helps with:** Bug fixes and maintenance • New feature development • Documentation improvements • Community support • Feeding my children
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## ✨ Features
|
|
50
|
+
|
|
51
|
+
### 🎮 Smart Controls
|
|
52
|
+
- **Target Charge Slider** (50-100%) - Set your desired battery level
|
|
53
|
+
- **Ready Time Dropdown** (04:00-11:00) - When your car needs to be ready
|
|
54
|
+
- **Apply Changes Button** - Prevents API spam while adjusting settings
|
|
55
|
+
- **Confirmed Values** - See your current API-validated settings
|
|
56
|
+
|
|
57
|
+
### ⚡ Real-Time Charging Data
|
|
58
|
+
- **Next Charge Time** - When your next slot starts
|
|
59
|
+
- **Total Planned Energy** - Total kWh across all upcoming slots
|
|
60
|
+
- **Individual Slot Times** - Up to 3 slots with start/end times
|
|
61
|
+
- **Charging Window** - Overall window from first to last slot
|
|
62
|
+
- **Charge Source** - Smart-charge vs bump-charge indicator
|
|
63
|
+
|
|
64
|
+
### 🔧 Advanced Features
|
|
65
|
+
- **Raw Timestamps** - Exact API responses in Diagnostics section
|
|
66
|
+
- **Exponential Backoff** - Smart retry prevents sensor unavailability
|
|
67
|
+
- **Comprehensive Debugging** - Full API call tracking in msg.debug
|
|
68
|
+
- **Active Slot Detection** - Shows currently running sessions
|
|
69
|
+
- **Entity Categories** - Organized Controls, Sensors, and Diagnostics
|
|
70
|
+
|
|
71
|
+
### 🏠 Home Assistant Integration
|
|
72
|
+
- **Zero Configuration** - MQTT auto-discovery sets everything up
|
|
73
|
+
- **Professional UI** - Octopus Energy branded device cards
|
|
74
|
+
- **Organized Entities** - Controls, main sensors, and diagnostics neatly grouped
|
|
75
|
+
- **Suggested Area** - Auto-suggests "Energy" area
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 📋 Requirements
|
|
80
|
+
|
|
81
|
+
- **Node-RED** v2.0+
|
|
82
|
+
- **Octopus Energy Account** with [Intelligent Octopus Go](https://octopus.energy/intelligent/) tariff
|
|
83
|
+
- **API Key** - [Generate here](https://octopus.energy/dashboard/new/accounts/personal-details/api-access)
|
|
84
|
+
- **MQTT Broker** (optional, for Home Assistant integration)
|
|
85
|
+
- **Home Assistant** (optional, for MQTT features)
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 🚀 Quick Start
|
|
90
|
+
|
|
91
|
+
### 1. Install via Node-RED Palette
|
|
92
|
+
|
|
93
|
+
1. Open Node-RED → **Menu** → **Manage Palette**
|
|
94
|
+
2. **Install** tab → Search `node-red-contrib-octopus-intelligent`
|
|
95
|
+
3. Click **Install**
|
|
96
|
+
|
|
97
|
+
### 2. Get Your Credentials
|
|
98
|
+
|
|
99
|
+
**Account Number** (format: `A-XXXXXXXX`):
|
|
100
|
+
- Found at https://octopus.energy/dashboard/
|
|
101
|
+
|
|
102
|
+
**API Key** (format: `sk_live_...`):
|
|
103
|
+
- Get from https://octopus.energy/dashboard/new/accounts/personal-details/api-access
|
|
104
|
+
- Click "Generate API Key"
|
|
105
|
+
|
|
106
|
+
### 3. Configure the Node
|
|
107
|
+
|
|
108
|
+
1. Drag **Octopus Intelligent** into your flow
|
|
109
|
+
2. Double-click to configure:
|
|
110
|
+
- Account Number
|
|
111
|
+
- API Key (stored securely)
|
|
112
|
+
- Refresh Interval (default: 5 min)
|
|
113
|
+
- Enable MQTT if using Home Assistant
|
|
114
|
+
3. **Deploy**
|
|
115
|
+
|
|
116
|
+
### 4. Home Assistant (Optional)
|
|
117
|
+
|
|
118
|
+
If MQTT enabled:
|
|
119
|
+
1. Wait ~5 seconds after deploy
|
|
120
|
+
2. **Settings** → **Devices & Services** → **MQTT**
|
|
121
|
+
3. Find "Octopus Intelligent" device
|
|
122
|
+
4. All entities created automatically!
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## 📊 Home Assistant Entities
|
|
127
|
+
|
|
128
|
+
### Controls
|
|
129
|
+
```
|
|
130
|
+
number.octopus_target_charge Battery charge limit (50-100%)
|
|
131
|
+
select.octopus_ready_time Ready by time (04:00-11:00)
|
|
132
|
+
button.octopus_apply_changes Submit changes to API
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Main Sensors
|
|
136
|
+
```
|
|
137
|
+
sensor.octopus_confirmed_charge_limit API-confirmed charge limit
|
|
138
|
+
sensor.octopus_confirmed_ready_time API-confirmed ready time
|
|
139
|
+
sensor.octopus_next_charge_time Next charging slot start
|
|
140
|
+
sensor.octopus_total_planned_energy Total kWh planned
|
|
141
|
+
sensor.octopus_next_slot_energy Energy in next slot
|
|
142
|
+
sensor.octopus_charge_source smart-charge/bump-charge
|
|
143
|
+
sensor.octopus_slot_[1-3]_start Individual slot starts
|
|
144
|
+
sensor.octopus_slot_[1-3]_end Individual slot ends
|
|
145
|
+
sensor.octopus_overall_window_start First slot start
|
|
146
|
+
sensor.octopus_overall_window_end Last slot end
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Diagnostics (Raw Timestamps)
|
|
150
|
+
```
|
|
151
|
+
sensor.octopus_next_charge_time_raw Exact API timestamp
|
|
152
|
+
sensor.octopus_slot_[1-3]_start_raw Raw slot start times
|
|
153
|
+
sensor.octopus_slot_[1-3]_end_raw Raw slot end times
|
|
154
|
+
sensor.octopus_overall_window_start_raw Raw window start
|
|
155
|
+
sensor.octopus_overall_window_end_raw Raw window end
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
## 💡 Node-RED Usage
|
|
161
|
+
|
|
162
|
+
### Basic Monitoring
|
|
163
|
+
|
|
164
|
+
```
|
|
165
|
+
[Inject: Every 5 min] → [Octopus Intelligent] → [Debug]
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### Set Preferences from Flow
|
|
169
|
+
|
|
170
|
+
```javascript
|
|
171
|
+
msg.payload = {
|
|
172
|
+
set_limit: 85, // 85% charge
|
|
173
|
+
set_time: "07:30" // Ready by 07:30
|
|
174
|
+
};
|
|
175
|
+
return msg;
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Output Format
|
|
179
|
+
|
|
180
|
+
```json
|
|
181
|
+
{
|
|
182
|
+
"payload": {
|
|
183
|
+
"next_start": "2025-11-29T01:30:00Z",
|
|
184
|
+
"total_energy": 42.5,
|
|
185
|
+
"next_kwh": "15.20",
|
|
186
|
+
"next_source": "smart-charge",
|
|
187
|
+
"confirmed_limit": 80,
|
|
188
|
+
"confirmed_time": "07:00",
|
|
189
|
+
"slot1_start": "2025-11-29T01:30:00Z",
|
|
190
|
+
"slot1_end": "2025-11-29T05:30:00Z"
|
|
191
|
+
},
|
|
192
|
+
"debug": {
|
|
193
|
+
"success": true,
|
|
194
|
+
"step": "complete",
|
|
195
|
+
"apiCalls": [...]
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
---
|
|
201
|
+
|
|
202
|
+
## 🏡 Home Assistant Automation Examples
|
|
203
|
+
|
|
204
|
+
### Notify When Charging Starts
|
|
205
|
+
|
|
206
|
+
```yaml
|
|
207
|
+
automation:
|
|
208
|
+
- alias: "EV Charging Starting"
|
|
209
|
+
trigger:
|
|
210
|
+
platform: state
|
|
211
|
+
entity_id: sensor.octopus_next_charge_time
|
|
212
|
+
condition:
|
|
213
|
+
condition: template
|
|
214
|
+
value_template: "{{ trigger.to_state.state != 'None' }}"
|
|
215
|
+
action:
|
|
216
|
+
service: notify.mobile_app
|
|
217
|
+
data:
|
|
218
|
+
message: "EV charging at {{ states('sensor.octopus_next_charge_time') }}"
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### Run Dishwasher During Cheap Rate
|
|
222
|
+
|
|
223
|
+
```yaml
|
|
224
|
+
automation:
|
|
225
|
+
- alias: "Dishwasher During Cheap Window"
|
|
226
|
+
trigger:
|
|
227
|
+
platform: time_pattern
|
|
228
|
+
minutes: "/5"
|
|
229
|
+
condition:
|
|
230
|
+
- condition: template
|
|
231
|
+
value_template: >
|
|
232
|
+
{% set start = as_timestamp(states('sensor.octopus_slot1_start')) %}
|
|
233
|
+
{% set end = as_timestamp(states('sensor.octopus_slot1_end')) %}
|
|
234
|
+
{% set now = as_timestamp(now()) %}
|
|
235
|
+
{{ start <= now <= end }}
|
|
236
|
+
action:
|
|
237
|
+
service: switch.turn_on
|
|
238
|
+
target:
|
|
239
|
+
entity_id: switch.dishwasher
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
---
|
|
243
|
+
|
|
244
|
+
## 🔍 Troubleshooting
|
|
245
|
+
|
|
246
|
+
### No Data (All Sensors Null/0)
|
|
247
|
+
|
|
248
|
+
**Check `msg.debug` output** in a Debug node:
|
|
249
|
+
|
|
250
|
+
Common issues:
|
|
251
|
+
- ❌ Account format must include `A-` prefix
|
|
252
|
+
- ❌ Invalid API key - regenerate at Octopus dashboard
|
|
253
|
+
- ❌ Not on Intelligent Octopus tariff
|
|
254
|
+
- ❌ Car not plugged in (no slots scheduled)
|
|
255
|
+
|
|
256
|
+
### Authentication Failing
|
|
257
|
+
|
|
258
|
+
Check `msg.debug.apiCalls[0].errors` for details.
|
|
259
|
+
|
|
260
|
+
**Solution:** Regenerate API key and update node configuration.
|
|
261
|
+
|
|
262
|
+
### Sensors Unavailable in Home Assistant
|
|
263
|
+
|
|
264
|
+
1. Verify MQTT broker is running
|
|
265
|
+
2. Check Node-RED can connect to MQTT
|
|
266
|
+
3. Deploy the flow to trigger discovery
|
|
267
|
+
4. Confirm Home Assistant MQTT integration is enabled
|
|
268
|
+
|
|
269
|
+
### Raw Sensors Not in Diagnostics
|
|
270
|
+
|
|
271
|
+
If entities existed before v1.0:
|
|
272
|
+
1. Delete "Octopus Intelligent" device in Home Assistant
|
|
273
|
+
2. Redeploy Node-RED flow
|
|
274
|
+
3. Entities will be rediscovered with proper categories
|
|
275
|
+
|
|
276
|
+
### Changes Not Applying
|
|
277
|
+
|
|
278
|
+
**Working as designed!** Use the **Apply Changes** button to submit.
|
|
279
|
+
|
|
280
|
+
This prevents API spam when making multiple adjustments.
|
|
281
|
+
|
|
282
|
+
---
|
|
283
|
+
|
|
284
|
+
## 🛠️ How It Works
|
|
285
|
+
|
|
286
|
+
### Authentication Flow
|
|
287
|
+
|
|
288
|
+
1. **Get Token** - Exchange API key for token
|
|
289
|
+
2. **Fetch Data** - Query planned dispatches & preferences
|
|
290
|
+
3. **Process** - Filter active/future slots, calculate totals
|
|
291
|
+
4. **Publish** - Send to Node-RED + MQTT
|
|
292
|
+
|
|
293
|
+
### Exponential Backoff
|
|
294
|
+
|
|
295
|
+
When changing preferences:
|
|
296
|
+
|
|
297
|
+
```
|
|
298
|
+
Mutation sent → Wait 15s → Validate
|
|
299
|
+
↓ If not confirmed
|
|
300
|
+
→ Wait 30s → Validate
|
|
301
|
+
↓ If not confirmed
|
|
302
|
+
→ Wait 60s → Validate
|
|
303
|
+
↓ If not confirmed
|
|
304
|
+
→ Wait 120s → Final check
|
|
305
|
+
↓ Then normal interval resumes
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
This prevents sensors becoming "unavailable" during updates.
|
|
309
|
+
|
|
310
|
+
### Debug Information
|
|
311
|
+
|
|
312
|
+
Every message includes `msg.debug`:
|
|
313
|
+
|
|
314
|
+
```json
|
|
315
|
+
{
|
|
316
|
+
"timestamp": "2025-11-29T10:30:00Z",
|
|
317
|
+
"success": true,
|
|
318
|
+
"step": "complete",
|
|
319
|
+
"apiCalls": [
|
|
320
|
+
{"name": "authentication", "tokenObtained": true},
|
|
321
|
+
{"name": "data_query", "slotsFound": 3}
|
|
322
|
+
]
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
---
|
|
327
|
+
|
|
328
|
+
## 📝 License
|
|
329
|
+
|
|
330
|
+
MIT License - Copyright (c) 2025 Andrew Somerharju Neale
|
|
331
|
+
|
|
332
|
+
See [LICENSE](LICENSE) file for full details.
|
|
333
|
+
|
|
334
|
+
---
|
|
335
|
+
|
|
336
|
+
## ⚠️ Disclaimer
|
|
337
|
+
|
|
338
|
+
This is an **unofficial integration** and is not affiliated with, endorsed by, or connected to Octopus Energy Ltd.
|
|
339
|
+
|
|
340
|
+
Use at your own risk. The Octopus Energy name and logo are trademarks of Octopus Energy Ltd.
|
|
341
|
+
|
|
342
|
+
---
|
|
343
|
+
|
|
344
|
+
## 🔗 Links
|
|
345
|
+
|
|
346
|
+
- **npm**: https://www.npmjs.com/package/node-red-contrib-octopus-intelligent
|
|
347
|
+
- **GitHub**: https://github.com/ASomerN/node-red-contrib-octopus-intelligent
|
|
348
|
+
- **Issues**: https://github.com/ASomerN/node-red-contrib-octopus-intelligent/issues
|
|
349
|
+
- **Octopus Intelligent**: https://octopus.energy/intelligent/
|
|
350
|
+
- **API Docs**: https://developer.octopus.energy/docs/api/
|
|
351
|
+
|
|
352
|
+
---
|
|
353
|
+
|
|
354
|
+
## 📜 Changelog
|
|
355
|
+
|
|
356
|
+
### v1.0.0 (2025-11-29)
|
|
357
|
+
|
|
358
|
+
- ✅ Octopus Energy GraphQL API integration
|
|
359
|
+
- ✅ Home Assistant MQTT auto-discovery
|
|
360
|
+
- ✅ Submit button for preference changes
|
|
361
|
+
- ✅ Raw timestamp sensors in diagnostics
|
|
362
|
+
- ✅ Active charging slot detection
|
|
363
|
+
- ✅ Exponential backoff validation
|
|
364
|
+
- ✅ Comprehensive debug output
|
|
365
|
+
- ✅ Entity category organization
|
|
366
|
+
- ✅ Octopus Energy branding
|
|
367
|
+
|
|
368
|
+
---
|
|
369
|
+
|
|
370
|
+
**Made with ⚡ for the Octopus Energy & Home Assistant communities**
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
<script type="text/javascript">
|
|
2
|
+
RED.nodes.registerType('octopus-intelligent', {
|
|
3
|
+
category: 'Octopus',
|
|
4
|
+
color: '#E8146F', // Octopus Energy brand pink
|
|
5
|
+
defaults: {
|
|
6
|
+
name: { value: "Octopus Intelligent" },
|
|
7
|
+
accountNumber: { value: "", required: true },
|
|
8
|
+
broker: { type: "mqtt-broker", required: false }, // Optional MQTT
|
|
9
|
+
refreshInterval: { value: 5, validate: RED.validators.number() },
|
|
10
|
+
enableMqtt: { value: true }
|
|
11
|
+
},
|
|
12
|
+
credentials: {
|
|
13
|
+
apiKey: { type: "password" }
|
|
14
|
+
},
|
|
15
|
+
inputs: 1,
|
|
16
|
+
outputs: 1,
|
|
17
|
+
icon: "font-awesome/fa-bolt",
|
|
18
|
+
label: function() {
|
|
19
|
+
return this.name || "Octopus Intelligent";
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
</script>
|
|
23
|
+
|
|
24
|
+
<script type="text/html" data-template-name="octopus-intelligent">
|
|
25
|
+
<div class="form-row">
|
|
26
|
+
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
|
|
27
|
+
<input type="text" id="node-input-name" placeholder="Name">
|
|
28
|
+
</div>
|
|
29
|
+
<div class="form-row">
|
|
30
|
+
<label for="node-input-accountNumber"><i class="fa fa-id-card"></i> Account No</label>
|
|
31
|
+
<input type="text" id="node-input-accountNumber" placeholder="A-12345678">
|
|
32
|
+
</div>
|
|
33
|
+
<div class="form-row">
|
|
34
|
+
<label for="node-input-apiKey"><i class="fa fa-key"></i> API Key</label>
|
|
35
|
+
<input type="password" id="node-input-apiKey" placeholder="sk_live_...">
|
|
36
|
+
</div>
|
|
37
|
+
|
|
38
|
+
<hr>
|
|
39
|
+
|
|
40
|
+
<div class="form-row">
|
|
41
|
+
<label for="node-input-refreshInterval"><i class="fa fa-clock-o"></i> Refresh (Min)</label>
|
|
42
|
+
<input type="number" id="node-input-refreshInterval" placeholder="5">
|
|
43
|
+
</div>
|
|
44
|
+
|
|
45
|
+
<div class="form-row">
|
|
46
|
+
<label for="node-input-enableMqtt"><i class="fa fa-rss"></i> HA Discovery</label>
|
|
47
|
+
<input type="checkbox" id="node-input-enableMqtt" style="display: inline-block; width: auto; vertical-align: top;">
|
|
48
|
+
<label for="node-input-enableMqtt" style="width: 70%;">Enable Home Assistant MQTT</label>
|
|
49
|
+
</div>
|
|
50
|
+
|
|
51
|
+
<div class="form-row">
|
|
52
|
+
<label for="node-input-broker"><i class="fa fa-globe"></i> MQTT Broker</label>
|
|
53
|
+
<input type="text" id="node-input-broker">
|
|
54
|
+
</div>
|
|
55
|
+
</script>
|
|
56
|
+
|
|
57
|
+
<script type="text/html" data-help-name="octopus-intelligent">
|
|
58
|
+
<p>Fetches Intelligent Octopus slots and settings.</p>
|
|
59
|
+
<h3>Outputs</h3>
|
|
60
|
+
<p>Outputs a payload containing <code>next_charge</code>, <code>settings</code>, and raw data.</p>
|
|
61
|
+
<h3>Home Assistant</h3>
|
|
62
|
+
<p>If an MQTT broker is configured, this node will automatically create sensors in Home Assistant.</p>
|
|
63
|
+
</script>
|
|
@@ -0,0 +1,862 @@
|
|
|
1
|
+
const axios = require("axios");
|
|
2
|
+
|
|
3
|
+
module.exports = function (RED) {
|
|
4
|
+
function OctopusIntelligentNode(config) {
|
|
5
|
+
RED.nodes.createNode(this, config);
|
|
6
|
+
var node = this;
|
|
7
|
+
|
|
8
|
+
// 1. Configuration
|
|
9
|
+
const account = config.accountNumber ? config.accountNumber.trim() : "";
|
|
10
|
+
const apiKey = this.credentials.apiKey ? this.credentials.apiKey.trim() : "";
|
|
11
|
+
const refreshRate = (config.refreshInterval || 5) * 60 * 1000;
|
|
12
|
+
const enableMqtt = config.enableMqtt;
|
|
13
|
+
|
|
14
|
+
// MQTT Topics
|
|
15
|
+
this.broker = RED.nodes.getNode(config.broker);
|
|
16
|
+
const mqttPrefix = `homeassistant`;
|
|
17
|
+
const uniqueIdPrefix = `nodered_${account}`;
|
|
18
|
+
const stateTopic = `nodered_octopus/${account}/status`;
|
|
19
|
+
|
|
20
|
+
// Command Topics (For listening)
|
|
21
|
+
const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
|
|
22
|
+
const cmdTopicTime = `nodered_octopus/${account}/set_time`;
|
|
23
|
+
const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
|
|
24
|
+
|
|
25
|
+
// 2. Constants & Validation
|
|
26
|
+
const TIME_OPTIONS = [
|
|
27
|
+
"04:00", "04:30", "05:00", "05:30",
|
|
28
|
+
"06:00", "06:30", "07:00", "07:30",
|
|
29
|
+
"08:00", "08:30", "09:00", "09:30",
|
|
30
|
+
"10:00", "10:30", "11:00"
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
// 3. Sensor Definitions (Read-Only)
|
|
34
|
+
const sensors = [
|
|
35
|
+
// Formatted timestamps (show "1 hour ago" in Home Assistant)
|
|
36
|
+
{ id: "next_charge", name: "Next Charge Time", class: "timestamp", icon: "mdi:timer", val: "next_start" },
|
|
37
|
+
{ id: "total_energy", name: "Total Planned Energy", class: "energy", unit: "kWh", val: "total_energy" },
|
|
38
|
+
{ id: "next_kwh", name: "Next Slot Energy", class: "energy", unit: "kWh", val: "next_kwh" },
|
|
39
|
+
{ id: "source", name: "Charge Source", icon: "mdi:help-circle", val: "next_source" },
|
|
40
|
+
// Individual slot times (formatted)
|
|
41
|
+
{ id: "slot1_start", name: "Slot 1 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot1_start" },
|
|
42
|
+
{ id: "slot1_end", name: "Slot 1 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot1_end" },
|
|
43
|
+
{ id: "slot2_start", name: "Slot 2 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot2_start" },
|
|
44
|
+
{ id: "slot2_end", name: "Slot 2 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot2_end" },
|
|
45
|
+
{ id: "slot3_start", name: "Slot 3 Start", class: "timestamp", icon: "mdi:timer-outline", val: "slot3_start" },
|
|
46
|
+
{ id: "slot3_end", name: "Slot 3 End", class: "timestamp", icon: "mdi:timer-outline", val: "slot3_end" },
|
|
47
|
+
// Overall window (formatted)
|
|
48
|
+
{ id: "window_start", name: "Overall Window Start", class: "timestamp", icon: "mdi:timer-play", val: "window_start" },
|
|
49
|
+
{ id: "window_end", name: "Overall Window End", class: "timestamp", icon: "mdi:timer-stop", val: "window_end" },
|
|
50
|
+
|
|
51
|
+
// Raw timestamp strings (show exact API timestamp)
|
|
52
|
+
{ id: "next_charge_raw", name: "Next Charge Time (Raw)", icon: "mdi:timer", val: "next_start_raw" },
|
|
53
|
+
{ id: "slot1_start_raw", name: "Slot 1 Start (Raw)", icon: "mdi:timer-outline", val: "slot1_start_raw" },
|
|
54
|
+
{ id: "slot1_end_raw", name: "Slot 1 End (Raw)", icon: "mdi:timer-outline", val: "slot1_end_raw" },
|
|
55
|
+
{ id: "slot2_start_raw", name: "Slot 2 Start (Raw)", icon: "mdi:timer-outline", val: "slot2_start_raw" },
|
|
56
|
+
{ id: "slot2_end_raw", name: "Slot 2 End (Raw)", icon: "mdi:timer-outline", val: "slot2_end_raw" },
|
|
57
|
+
{ id: "slot3_start_raw", name: "Slot 3 Start (Raw)", icon: "mdi:timer-outline", val: "slot3_start_raw" },
|
|
58
|
+
{ id: "slot3_end_raw", name: "Slot 3 End (Raw)", icon: "mdi:timer-outline", val: "slot3_end_raw" },
|
|
59
|
+
{ id: "window_start_raw", name: "Overall Window Start (Raw)", icon: "mdi:timer-play", val: "window_start_raw" },
|
|
60
|
+
{ id: "window_end_raw", name: "Overall Window End (Raw)", icon: "mdi:timer-stop", val: "window_end_raw" }
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
// 4. Helper: Announce Controls (Write-Enabled)
|
|
64
|
+
function announceControls() {
|
|
65
|
+
if (!enableMqtt || !node.broker) return;
|
|
66
|
+
|
|
67
|
+
// Single device definition with branding
|
|
68
|
+
const device = {
|
|
69
|
+
identifiers: [`nodered_octopus_${account}`],
|
|
70
|
+
name: "Octopus Intelligent",
|
|
71
|
+
manufacturer: "Octopus Energy",
|
|
72
|
+
model: "Intelligent Octopus Go",
|
|
73
|
+
sw_version: "1.0.0",
|
|
74
|
+
suggested_area: "Energy",
|
|
75
|
+
configuration_url: "https://octopus.energy/intelligent/"
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// A. The Slider (Number) - now shows pending value
|
|
79
|
+
const limitConfig = {
|
|
80
|
+
name: "Octopus Target Charge",
|
|
81
|
+
unique_id: `${uniqueIdPrefix}_target_limit`,
|
|
82
|
+
state_topic: stateTopic,
|
|
83
|
+
command_topic: cmdTopicLimit,
|
|
84
|
+
value_template: "{{ value_json.pending_limit }}",
|
|
85
|
+
min: 50, max: 100, step: 5,
|
|
86
|
+
unit_of_measurement: "%",
|
|
87
|
+
icon: "mdi:battery-charging-high",
|
|
88
|
+
device: device
|
|
89
|
+
};
|
|
90
|
+
node.broker.client.publish(`${mqttPrefix}/number/${uniqueIdPrefix}_limit/config`, JSON.stringify(limitConfig), { retain: true });
|
|
91
|
+
|
|
92
|
+
// B. The Dropdown (Select) - now shows pending value
|
|
93
|
+
const timeConfig = {
|
|
94
|
+
name: "Octopus Ready Time",
|
|
95
|
+
unique_id: `${uniqueIdPrefix}_target_time`,
|
|
96
|
+
state_topic: stateTopic,
|
|
97
|
+
command_topic: cmdTopicTime,
|
|
98
|
+
value_template: "{{ value_json.pending_time }}",
|
|
99
|
+
options: TIME_OPTIONS,
|
|
100
|
+
icon: "mdi:clock-time-four-outline",
|
|
101
|
+
device: device
|
|
102
|
+
};
|
|
103
|
+
node.broker.client.publish(`${mqttPrefix}/select/${uniqueIdPrefix}_time/config`, JSON.stringify(timeConfig), { retain: true });
|
|
104
|
+
|
|
105
|
+
// C. Submit Button
|
|
106
|
+
const buttonConfig = {
|
|
107
|
+
name: "Octopus Apply Changes",
|
|
108
|
+
unique_id: `${uniqueIdPrefix}_submit_button`,
|
|
109
|
+
command_topic: cmdTopicSubmit,
|
|
110
|
+
payload_press: "SUBMIT",
|
|
111
|
+
icon: "mdi:check-circle",
|
|
112
|
+
device_class: "update",
|
|
113
|
+
device: device
|
|
114
|
+
};
|
|
115
|
+
node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
|
|
116
|
+
|
|
117
|
+
// D. Add sensors for confirmed values (read-only display)
|
|
118
|
+
const confirmedLimitSensor = {
|
|
119
|
+
name: "Octopus Confirmed Charge Limit",
|
|
120
|
+
unique_id: `${uniqueIdPrefix}_confirmed_limit`,
|
|
121
|
+
state_topic: stateTopic,
|
|
122
|
+
value_template: "{{ value_json.confirmed_limit }}",
|
|
123
|
+
unit_of_measurement: "%",
|
|
124
|
+
icon: "mdi:battery-check",
|
|
125
|
+
device: device
|
|
126
|
+
};
|
|
127
|
+
node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_limit/config`, JSON.stringify(confirmedLimitSensor), { retain: true });
|
|
128
|
+
|
|
129
|
+
const confirmedTimeSensor = {
|
|
130
|
+
name: "Octopus Confirmed Ready Time",
|
|
131
|
+
unique_id: `${uniqueIdPrefix}_confirmed_time`,
|
|
132
|
+
state_topic: stateTopic,
|
|
133
|
+
value_template: "{{ value_json.confirmed_time }}",
|
|
134
|
+
icon: "mdi:clock-check",
|
|
135
|
+
device: device
|
|
136
|
+
};
|
|
137
|
+
node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
|
|
138
|
+
|
|
139
|
+
// F. Charging Now Binary Sensor (main sensor for automations)
|
|
140
|
+
const chargingNowBinarySensor = {
|
|
141
|
+
name: "Octopus Charging Now",
|
|
142
|
+
unique_id: `${uniqueIdPrefix}_charging_now`,
|
|
143
|
+
state_topic: `${stateTopic}/charging_now`,
|
|
144
|
+
device_class: "battery_charging",
|
|
145
|
+
payload_on: "ON",
|
|
146
|
+
payload_off: "OFF",
|
|
147
|
+
icon: "mdi:ev-station",
|
|
148
|
+
device: device
|
|
149
|
+
};
|
|
150
|
+
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
|
|
151
|
+
|
|
152
|
+
// G. Announce Read-Only Sensors
|
|
153
|
+
sensors.forEach(sensor => {
|
|
154
|
+
const payload = {
|
|
155
|
+
name: `Octopus ${sensor.name}`,
|
|
156
|
+
unique_id: `${uniqueIdPrefix}_${sensor.id}`,
|
|
157
|
+
state_topic: stateTopic,
|
|
158
|
+
value_template: `{{ value_json.${sensor.val} }}`,
|
|
159
|
+
device: device
|
|
160
|
+
};
|
|
161
|
+
if (sensor.class) payload.device_class = sensor.class;
|
|
162
|
+
if (sensor.unit) payload.unit_of_measurement = sensor.unit;
|
|
163
|
+
if (sensor.icon) payload.icon = sensor.icon;
|
|
164
|
+
|
|
165
|
+
// Mark raw sensors as diagnostic (moves to Diagnostics section)
|
|
166
|
+
if (sensor.id.includes('_raw')) {
|
|
167
|
+
payload.entity_category = "diagnostic";
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
// Subscribe to Commands
|
|
174
|
+
node.broker.client.subscribe(cmdTopicLimit);
|
|
175
|
+
node.broker.client.subscribe(cmdTopicTime);
|
|
176
|
+
node.broker.client.subscribe(cmdTopicSubmit);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 5. Helper: Set Preferences (The Mutation)
|
|
180
|
+
let retryTimeouts = []; // Track pending retry timeouts
|
|
181
|
+
let expectedLimit = null;
|
|
182
|
+
let expectedTime = null;
|
|
183
|
+
|
|
184
|
+
// Pending vs Confirmed state
|
|
185
|
+
let pendingLimit = 80;
|
|
186
|
+
let pendingTime = "08:00";
|
|
187
|
+
let confirmedLimit = 80;
|
|
188
|
+
let confirmedTime = "08:00";
|
|
189
|
+
|
|
190
|
+
// Charging Now feature - timer-based state management
|
|
191
|
+
let chargingNow = false;
|
|
192
|
+
let preValidationTimer = null; // Fires 30s before slot start
|
|
193
|
+
let slotStartTimer = null; // Fires at exact slot start
|
|
194
|
+
let slotEndTimer = null; // Fires at exact slot end
|
|
195
|
+
let cachedSlots = []; // Fresh slot data from pre-validation
|
|
196
|
+
|
|
197
|
+
async function setPreferences(newLimit, newTime) {
|
|
198
|
+
// Validation
|
|
199
|
+
let limit = parseInt(newLimit);
|
|
200
|
+
let time = newTime;
|
|
201
|
+
|
|
202
|
+
// Enforce Limits
|
|
203
|
+
if (isNaN(limit) || limit < 50) limit = 50;
|
|
204
|
+
if (limit > 100) limit = 100;
|
|
205
|
+
// Round to nearest 5
|
|
206
|
+
limit = Math.round(limit / 5) * 5;
|
|
207
|
+
|
|
208
|
+
// Validate Time
|
|
209
|
+
if (!TIME_OPTIONS.includes(time)) {
|
|
210
|
+
node.warn(`Invalid time '${time}' requested. Defaulting to 08:00`);
|
|
211
|
+
time = "08:00";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Cancel any pending retry attempts from previous changes
|
|
215
|
+
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
216
|
+
retryTimeouts = [];
|
|
217
|
+
|
|
218
|
+
try {
|
|
219
|
+
node.status({ fill: "blue", shape: "dot", text: "Updating Settings..." });
|
|
220
|
+
|
|
221
|
+
// A. Get Token
|
|
222
|
+
const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
223
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
224
|
+
variables: { input: { APIKey: apiKey } }
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
if (authResponse.data.errors) {
|
|
228
|
+
throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
|
|
229
|
+
}
|
|
230
|
+
if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
231
|
+
throw new Error(`Auth response missing token data`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
235
|
+
|
|
236
|
+
// B. Send Mutation
|
|
237
|
+
const mutation = `
|
|
238
|
+
mutation setPreferences($input: VehicleChargingPreferencesInput!) {
|
|
239
|
+
setVehicleChargePreferences(input: $input) { __typename }
|
|
240
|
+
}`;
|
|
241
|
+
|
|
242
|
+
const variables = {
|
|
243
|
+
input: {
|
|
244
|
+
accountNumber: account,
|
|
245
|
+
weekdayTargetSoc: limit,
|
|
246
|
+
weekendTargetSoc: limit,
|
|
247
|
+
weekdayTargetTime: time,
|
|
248
|
+
weekendTargetTime: time
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const mutationResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
253
|
+
query: mutation,
|
|
254
|
+
variables: variables
|
|
255
|
+
}, { headers: { Authorization: token } });
|
|
256
|
+
|
|
257
|
+
if (mutationResponse.data.errors) {
|
|
258
|
+
throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// C. Start exponential backoff validation
|
|
262
|
+
expectedLimit = limit;
|
|
263
|
+
expectedTime = time;
|
|
264
|
+
node.status({ fill: "blue", shape: "ring", text: "Verifying changes..." });
|
|
265
|
+
|
|
266
|
+
// Schedule retries with exponential backoff: 15s, 30s, 60s, 120s
|
|
267
|
+
const retryIntervals = [15000, 30000, 60000, 120000];
|
|
268
|
+
scheduleRetries(retryIntervals, 0);
|
|
269
|
+
|
|
270
|
+
} catch (err) {
|
|
271
|
+
node.error("Failed to set preferences: " + err.message);
|
|
272
|
+
if (err.response) {
|
|
273
|
+
node.error(`Response: ${JSON.stringify(err.response.data)}`);
|
|
274
|
+
}
|
|
275
|
+
node.status({ fill: "red", shape: "ring", text: "Update Failed" });
|
|
276
|
+
expectedLimit = null;
|
|
277
|
+
expectedTime = null;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function scheduleRetries(intervals, index) {
|
|
282
|
+
if (index >= intervals.length) {
|
|
283
|
+
// All retries exhausted, let normal interval take over
|
|
284
|
+
node.status({ fill: "yellow", shape: "dot", text: "Waiting for normal sync..." });
|
|
285
|
+
expectedLimit = null;
|
|
286
|
+
expectedTime = null;
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const timeout = setTimeout(async () => {
|
|
291
|
+
await fetchDataWithValidation(intervals, index);
|
|
292
|
+
}, intervals[index]);
|
|
293
|
+
|
|
294
|
+
retryTimeouts.push(timeout);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function fetchDataWithValidation(intervals, currentIndex) {
|
|
298
|
+
try {
|
|
299
|
+
const result = await fetchData(true); // Pass flag to indicate validation mode
|
|
300
|
+
|
|
301
|
+
// Check if the data matches our expected values
|
|
302
|
+
if (result && result.validated) {
|
|
303
|
+
// Success! Changes confirmed
|
|
304
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${result.confirmedLimit}% @ ${result.confirmedTime}` });
|
|
305
|
+
expectedLimit = null;
|
|
306
|
+
expectedTime = null;
|
|
307
|
+
// Clear remaining timeouts
|
|
308
|
+
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
309
|
+
retryTimeouts = [];
|
|
310
|
+
} else {
|
|
311
|
+
// Not yet updated, schedule next retry
|
|
312
|
+
const attempt = currentIndex + 1;
|
|
313
|
+
const totalAttempts = intervals.length;
|
|
314
|
+
node.status({ fill: "blue", shape: "ring", text: `Retry ${attempt}/${totalAttempts}...` });
|
|
315
|
+
scheduleRetries(intervals, currentIndex + 1);
|
|
316
|
+
}
|
|
317
|
+
} catch (error) {
|
|
318
|
+
// Error during fetch, schedule next retry
|
|
319
|
+
node.warn(`Retry ${currentIndex + 1} failed: ${error.message}`);
|
|
320
|
+
scheduleRetries(intervals, currentIndex + 1);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// 6. Logic: Fetch Data (Read)
|
|
325
|
+
async function fetchData(validationMode = false) {
|
|
326
|
+
// Debug object to track API calls
|
|
327
|
+
const debugInfo = {
|
|
328
|
+
timestamp: new Date().toISOString(),
|
|
329
|
+
step: null,
|
|
330
|
+
success: false,
|
|
331
|
+
error: null,
|
|
332
|
+
apiCalls: [],
|
|
333
|
+
validationMode: validationMode
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
if (!apiKey || !account) {
|
|
337
|
+
debugInfo.error = "Missing configuration: apiKey or account number not provided";
|
|
338
|
+
debugInfo.step = "validation";
|
|
339
|
+
node.status({ fill: "red", shape: "ring", text: "Config Missing" });
|
|
340
|
+
node.send({
|
|
341
|
+
payload: buildDefaultPayload(),
|
|
342
|
+
debug: debugInfo
|
|
343
|
+
});
|
|
344
|
+
return { validated: false };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
try {
|
|
348
|
+
// STEP 1: Get Token
|
|
349
|
+
debugInfo.step = "authentication";
|
|
350
|
+
node.status({ fill: "yellow", shape: "ring", text: "Authenticating..." });
|
|
351
|
+
|
|
352
|
+
const authRequest = {
|
|
353
|
+
url: "https://api.octopus.energy/v1/graphql/",
|
|
354
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
355
|
+
variables: { input: { APIKey: apiKey } }
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
const authResponse = await axios.post(authRequest.url, {
|
|
359
|
+
query: authRequest.query,
|
|
360
|
+
variables: authRequest.variables
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
debugInfo.apiCalls.push({
|
|
364
|
+
step: 1,
|
|
365
|
+
name: "authentication",
|
|
366
|
+
url: authRequest.url,
|
|
367
|
+
statusCode: authResponse.status,
|
|
368
|
+
hasErrors: !!(authResponse.data.errors),
|
|
369
|
+
errors: authResponse.data.errors || null
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
// Validate auth response
|
|
373
|
+
if (authResponse.data.errors) {
|
|
374
|
+
throw new Error(`Auth failed: ${JSON.stringify(authResponse.data.errors)}`);
|
|
375
|
+
}
|
|
376
|
+
if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
377
|
+
throw new Error(`Auth response missing token data. Response: ${JSON.stringify(authResponse.data)}`);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
381
|
+
debugInfo.apiCalls[0].tokenObtained = !!token;
|
|
382
|
+
debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
|
|
383
|
+
|
|
384
|
+
// STEP 2: Fetch Data
|
|
385
|
+
debugInfo.step = "fetching_data";
|
|
386
|
+
node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
|
|
387
|
+
|
|
388
|
+
const masterQuery = `
|
|
389
|
+
query getData($account: String!) {
|
|
390
|
+
plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } }
|
|
391
|
+
vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
|
|
392
|
+
}`;
|
|
393
|
+
|
|
394
|
+
const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
395
|
+
query: masterQuery,
|
|
396
|
+
variables: { account: account }
|
|
397
|
+
}, { headers: { Authorization: token } });
|
|
398
|
+
|
|
399
|
+
debugInfo.apiCalls.push({
|
|
400
|
+
step: 2,
|
|
401
|
+
name: "data_query",
|
|
402
|
+
url: "https://api.octopus.energy/v1/graphql/",
|
|
403
|
+
accountNumber: account,
|
|
404
|
+
authHeaderFormat: "Raw token (no Bearer/JWT prefix)",
|
|
405
|
+
statusCode: dataResponse.status,
|
|
406
|
+
hasErrors: !!(dataResponse.data.errors),
|
|
407
|
+
errors: dataResponse.data.errors || null,
|
|
408
|
+
hasData: !!(dataResponse.data.data)
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
// Validate data response
|
|
412
|
+
if (dataResponse.data.errors) {
|
|
413
|
+
throw new Error(`Data query failed: ${JSON.stringify(dataResponse.data.errors)}`);
|
|
414
|
+
}
|
|
415
|
+
if (!dataResponse.data.data) {
|
|
416
|
+
throw new Error(`Data response missing data field. Response: ${JSON.stringify(dataResponse.data)}`);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// STEP 3: Extract and Process
|
|
420
|
+
debugInfo.step = "processing";
|
|
421
|
+
const data = dataResponse.data.data || {};
|
|
422
|
+
const slots = data.plannedDispatches || [];
|
|
423
|
+
const prefs = data.vehicleChargingPreferences || {};
|
|
424
|
+
|
|
425
|
+
debugInfo.apiCalls[1].slotsFound = slots.length;
|
|
426
|
+
debugInfo.apiCalls[1].preferencesFound = !!(prefs.weekdayTargetSoc);
|
|
427
|
+
debugInfo.apiCalls[1].slotDetails = slots.map(s => ({
|
|
428
|
+
start: s.startDt,
|
|
429
|
+
end: s.endDt,
|
|
430
|
+
kwh: s.deltaKwh,
|
|
431
|
+
source: s.meta?.source
|
|
432
|
+
}));
|
|
433
|
+
|
|
434
|
+
// Update Confirmed State (from API)
|
|
435
|
+
confirmedLimit = prefs.weekdayTargetSoc || confirmedLimit;
|
|
436
|
+
confirmedTime = prefs.weekdayTargetTime || confirmedTime;
|
|
437
|
+
|
|
438
|
+
// On successful fetch, sync pending to confirmed if not in validation mode
|
|
439
|
+
if (!validationMode) {
|
|
440
|
+
pendingLimit = confirmedLimit;
|
|
441
|
+
pendingTime = confirmedTime;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Process slots
|
|
445
|
+
const now = new Date();
|
|
446
|
+
// Include active slots (endDt in future) and future slots
|
|
447
|
+
const activeAndFutureSlots = slots.filter(s => new Date(s.endDt) > now);
|
|
448
|
+
const nextSlot = activeAndFutureSlots[0] || null;
|
|
449
|
+
|
|
450
|
+
// Total energy for all active/future slots
|
|
451
|
+
const totalEnergy = activeAndFutureSlots.reduce((sum, s) => sum + (s.deltaKwh || 0), 0);
|
|
452
|
+
|
|
453
|
+
debugInfo.apiCalls[1].activeAndFutureSlots = activeAndFutureSlots.length;
|
|
454
|
+
debugInfo.processingTime = now.toISOString();
|
|
455
|
+
|
|
456
|
+
// Setup charging timers (only in non-validation mode)
|
|
457
|
+
if (!validationMode) {
|
|
458
|
+
setupChargingTimers(activeAndFutureSlots);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Build Payload
|
|
462
|
+
const statusPayload = {
|
|
463
|
+
next_start: nextSlot ? nextSlot.startDt : null,
|
|
464
|
+
total_energy: parseFloat(totalEnergy.toFixed(2)),
|
|
465
|
+
next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
|
|
466
|
+
next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
|
|
467
|
+
// Confirmed values (from API)
|
|
468
|
+
confirmed_limit: confirmedLimit,
|
|
469
|
+
confirmed_time: confirmedTime,
|
|
470
|
+
// Pending values (user's current selections)
|
|
471
|
+
pending_limit: pendingLimit,
|
|
472
|
+
pending_time: pendingTime,
|
|
473
|
+
// Charging Now state
|
|
474
|
+
charging_now: chargingNow,
|
|
475
|
+
// Individual slots (first 3 active/future) - formatted timestamps
|
|
476
|
+
slot1_start: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
|
|
477
|
+
slot1_end: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
|
|
478
|
+
slot2_start: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
|
|
479
|
+
slot2_end: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
|
|
480
|
+
slot3_start: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
|
|
481
|
+
slot3_end: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
|
|
482
|
+
// Overall window (first start to last end) - formatted timestamps
|
|
483
|
+
window_start: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
|
|
484
|
+
window_end: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
|
|
485
|
+
// Raw timestamp strings (exact API output)
|
|
486
|
+
next_start_raw: nextSlot ? nextSlot.startDt : null,
|
|
487
|
+
slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
|
|
488
|
+
slot1_end_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
|
|
489
|
+
slot2_start_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
|
|
490
|
+
slot2_end_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
|
|
491
|
+
slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
|
|
492
|
+
slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
|
|
493
|
+
window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
|
|
494
|
+
window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
// Success!
|
|
498
|
+
debugInfo.success = true;
|
|
499
|
+
debugInfo.step = "complete";
|
|
500
|
+
|
|
501
|
+
// Check if we're validating a preference change
|
|
502
|
+
let isValidated = false;
|
|
503
|
+
if (validationMode && expectedLimit !== null && expectedTime !== null) {
|
|
504
|
+
// Check if the returned values match what we set
|
|
505
|
+
isValidated = (confirmedLimit === expectedLimit && confirmedTime === expectedTime);
|
|
506
|
+
debugInfo.expectedLimit = expectedLimit;
|
|
507
|
+
debugInfo.expectedTime = expectedTime;
|
|
508
|
+
debugInfo.receivedLimit = confirmedLimit;
|
|
509
|
+
debugInfo.receivedTime = confirmedTime;
|
|
510
|
+
debugInfo.validated = isValidated;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// ALWAYS publish data to prevent sensors becoming unavailable
|
|
514
|
+
node.send({
|
|
515
|
+
payload: statusPayload,
|
|
516
|
+
debug: debugInfo
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
if (enableMqtt && node.broker) {
|
|
520
|
+
node.broker.client.publish(stateTopic, JSON.stringify(statusPayload), { retain: true });
|
|
521
|
+
// Also publish charging_now state to binary sensor topic
|
|
522
|
+
const chargingPayload = chargingNow ? "ON" : "OFF";
|
|
523
|
+
node.broker.client.publish(`${stateTopic}/charging_now`, chargingPayload, { retain: true });
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Update status (validation mode will override this in fetchDataWithValidation)
|
|
527
|
+
if (!validationMode) {
|
|
528
|
+
node.status({ fill: "green", shape: "dot", text: `Confirmed: ${confirmedLimit}% @ ${confirmedTime}` });
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// Return validation result
|
|
532
|
+
return { validated: isValidated || !validationMode, confirmedLimit, confirmedTime };
|
|
533
|
+
|
|
534
|
+
} catch (error) {
|
|
535
|
+
debugInfo.success = false;
|
|
536
|
+
debugInfo.error = {
|
|
537
|
+
message: error.message,
|
|
538
|
+
stack: error.stack,
|
|
539
|
+
response: error.response ? {
|
|
540
|
+
status: error.response.status,
|
|
541
|
+
statusText: error.response.statusText,
|
|
542
|
+
data: error.response.data
|
|
543
|
+
} : null
|
|
544
|
+
};
|
|
545
|
+
|
|
546
|
+
// Log to Node-RED (only if not in validation mode to avoid spam)
|
|
547
|
+
if (!validationMode) {
|
|
548
|
+
node.error(`Octopus API Error at ${debugInfo.step}: ${error.message}`);
|
|
549
|
+
if (error.response) {
|
|
550
|
+
node.error(`Response: ${JSON.stringify(error.response.data)}`);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// Update status
|
|
554
|
+
node.status({
|
|
555
|
+
fill: "red",
|
|
556
|
+
shape: "ring",
|
|
557
|
+
text: `Error: ${debugInfo.step}`
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
// Send default payload with debug info
|
|
561
|
+
node.send({
|
|
562
|
+
payload: buildDefaultPayload(),
|
|
563
|
+
debug: debugInfo
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Return failure for validation
|
|
568
|
+
return { validated: false };
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// Helper: Build default payload when errors occur
|
|
573
|
+
function buildDefaultPayload() {
|
|
574
|
+
return {
|
|
575
|
+
next_start: null,
|
|
576
|
+
total_energy: 0,
|
|
577
|
+
next_kwh: "0",
|
|
578
|
+
next_source: "unknown",
|
|
579
|
+
confirmed_limit: confirmedLimit,
|
|
580
|
+
confirmed_time: confirmedTime,
|
|
581
|
+
pending_limit: pendingLimit,
|
|
582
|
+
pending_time: pendingTime,
|
|
583
|
+
charging_now: chargingNow,
|
|
584
|
+
slot1_start: null,
|
|
585
|
+
slot1_end: null,
|
|
586
|
+
slot2_start: null,
|
|
587
|
+
slot2_end: null,
|
|
588
|
+
slot3_start: null,
|
|
589
|
+
slot3_end: null,
|
|
590
|
+
window_start: null,
|
|
591
|
+
window_end: null,
|
|
592
|
+
// Raw timestamp strings
|
|
593
|
+
next_start_raw: null,
|
|
594
|
+
slot1_start_raw: null,
|
|
595
|
+
slot1_end_raw: null,
|
|
596
|
+
slot2_start_raw: null,
|
|
597
|
+
slot2_end_raw: null,
|
|
598
|
+
slot3_start_raw: null,
|
|
599
|
+
slot3_end_raw: null,
|
|
600
|
+
window_start_raw: null,
|
|
601
|
+
window_end_raw: null
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// 6a. Charging Now - Timer Management Functions
|
|
606
|
+
|
|
607
|
+
// Clear all charging timers
|
|
608
|
+
function clearChargingTimers() {
|
|
609
|
+
if (preValidationTimer) {
|
|
610
|
+
clearTimeout(preValidationTimer);
|
|
611
|
+
preValidationTimer = null;
|
|
612
|
+
}
|
|
613
|
+
if (slotStartTimer) {
|
|
614
|
+
clearTimeout(slotStartTimer);
|
|
615
|
+
slotStartTimer = null;
|
|
616
|
+
}
|
|
617
|
+
if (slotEndTimer) {
|
|
618
|
+
clearTimeout(slotEndTimer);
|
|
619
|
+
slotEndTimer = null;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// Publish charging state to MQTT
|
|
624
|
+
function publishChargingState(state) {
|
|
625
|
+
chargingNow = state;
|
|
626
|
+
if (enableMqtt && node.broker) {
|
|
627
|
+
const payload = state ? "ON" : "OFF";
|
|
628
|
+
node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// Setup pre-validation timer (30s before slot starts)
|
|
633
|
+
function setupPreValidationTimer(nextSlot) {
|
|
634
|
+
const now = new Date();
|
|
635
|
+
const slotStart = new Date(nextSlot.startDt);
|
|
636
|
+
const preValidationTime = slotStart.getTime() - 30000; // 30s before
|
|
637
|
+
const msUntilPreValidation = preValidationTime - now.getTime();
|
|
638
|
+
|
|
639
|
+
if (msUntilPreValidation > 0 && msUntilPreValidation < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
640
|
+
preValidationTimer = setTimeout(async () => {
|
|
641
|
+
node.warn("Pre-validating slot data (30s before start)");
|
|
642
|
+
try {
|
|
643
|
+
// Fetch fresh data from API
|
|
644
|
+
const authResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
645
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
646
|
+
variables: { input: { APIKey: apiKey } }
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
if (!authResponse.data.data || !authResponse.data.data.obtainKrakenToken) {
|
|
650
|
+
throw new Error("Pre-validation auth failed");
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
654
|
+
|
|
655
|
+
const dataResponse = await axios.post("https://api.octopus.energy/v1/graphql/", {
|
|
656
|
+
query: `query getData($account: String!) { plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } } }`,
|
|
657
|
+
variables: { account: account }
|
|
658
|
+
}, { headers: { Authorization: token } });
|
|
659
|
+
|
|
660
|
+
if (dataResponse.data.data && dataResponse.data.data.plannedDispatches) {
|
|
661
|
+
cachedSlots = dataResponse.data.data.plannedDispatches;
|
|
662
|
+
|
|
663
|
+
// Check if slot still exists (within 1 minute tolerance)
|
|
664
|
+
const stillExists = cachedSlots.find(s =>
|
|
665
|
+
Math.abs(new Date(s.startDt).getTime() - slotStart.getTime()) < 60000
|
|
666
|
+
);
|
|
667
|
+
|
|
668
|
+
if (stillExists) {
|
|
669
|
+
node.warn(`Slot confirmed at ${stillExists.startDt}`);
|
|
670
|
+
setupSlotStartTimer(stillExists);
|
|
671
|
+
} else {
|
|
672
|
+
node.warn("Slot was cancelled or modified - not setting start timer");
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
} catch (error) {
|
|
676
|
+
node.warn(`Pre-validation failed: ${error.message}, using cached slot`);
|
|
677
|
+
// Fallback: use original slot data
|
|
678
|
+
setupSlotStartTimer(nextSlot);
|
|
679
|
+
}
|
|
680
|
+
}, msUntilPreValidation);
|
|
681
|
+
|
|
682
|
+
const minutesUntil = Math.round(msUntilPreValidation / 60000);
|
|
683
|
+
node.log(`Pre-validation timer set for ${minutesUntil} min before slot start`);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// Setup slot start timer (exact start time)
|
|
688
|
+
function setupSlotStartTimer(slot) {
|
|
689
|
+
const now = new Date();
|
|
690
|
+
const slotStart = new Date(slot.startDt);
|
|
691
|
+
const msUntilStart = slotStart.getTime() - now.getTime();
|
|
692
|
+
|
|
693
|
+
if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
694
|
+
slotStartTimer = setTimeout(() => {
|
|
695
|
+
publishChargingState(true);
|
|
696
|
+
node.warn(`Charging slot started at ${slot.startDt}`);
|
|
697
|
+
setupSlotEndTimer(slot);
|
|
698
|
+
}, msUntilStart);
|
|
699
|
+
|
|
700
|
+
const secondsUntil = Math.round(msUntilStart / 1000);
|
|
701
|
+
node.log(`Slot start timer set for ${secondsUntil}s (${slot.startDt})`);
|
|
702
|
+
} else if (msUntilStart <= 0) {
|
|
703
|
+
// Slot already started, check if it's still active
|
|
704
|
+
const slotEnd = new Date(slot.endDt);
|
|
705
|
+
if (slotEnd > now) {
|
|
706
|
+
publishChargingState(true);
|
|
707
|
+
setupSlotEndTimer(slot);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// Setup slot end timer (exact end time)
|
|
713
|
+
function setupSlotEndTimer(slot) {
|
|
714
|
+
const now = new Date();
|
|
715
|
+
const slotEnd = new Date(slot.endDt);
|
|
716
|
+
const msUntilEnd = slotEnd.getTime() - now.getTime();
|
|
717
|
+
|
|
718
|
+
if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
719
|
+
slotEndTimer = setTimeout(() => {
|
|
720
|
+
node.warn(`Charging slot ended at ${slot.endDt}`);
|
|
721
|
+
|
|
722
|
+
// Check if another slot starts immediately (within cached data)
|
|
723
|
+
const now = new Date();
|
|
724
|
+
const immediateNextSlot = cachedSlots.find(s => {
|
|
725
|
+
const start = new Date(s.startDt);
|
|
726
|
+
const end = new Date(s.endDt);
|
|
727
|
+
return start <= now && end > now;
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
if (immediateNextSlot) {
|
|
731
|
+
node.warn("Next slot starting immediately");
|
|
732
|
+
publishChargingState(true);
|
|
733
|
+
setupSlotEndTimer(immediateNextSlot);
|
|
734
|
+
} else {
|
|
735
|
+
publishChargingState(false);
|
|
736
|
+
}
|
|
737
|
+
}, msUntilEnd);
|
|
738
|
+
|
|
739
|
+
const minutesUntil = Math.round(msUntilEnd / 60000);
|
|
740
|
+
node.log(`Slot end timer set for ${minutesUntil} min (${slot.endDt})`);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// Main timer setup - called on each poll
|
|
745
|
+
function setupChargingTimers(slots) {
|
|
746
|
+
// Clear existing timers
|
|
747
|
+
clearChargingTimers();
|
|
748
|
+
|
|
749
|
+
// Cache slots for later use
|
|
750
|
+
cachedSlots = slots;
|
|
751
|
+
|
|
752
|
+
const now = new Date();
|
|
753
|
+
|
|
754
|
+
// Check if currently in a charging slot
|
|
755
|
+
const activeSlot = slots.find(s => {
|
|
756
|
+
const start = new Date(s.startDt);
|
|
757
|
+
const end = new Date(s.endDt);
|
|
758
|
+
return start <= now && end > now;
|
|
759
|
+
});
|
|
760
|
+
|
|
761
|
+
if (activeSlot) {
|
|
762
|
+
// Currently charging
|
|
763
|
+
const newState = true;
|
|
764
|
+
if (chargingNow !== newState) {
|
|
765
|
+
publishChargingState(newState);
|
|
766
|
+
}
|
|
767
|
+
setupSlotEndTimer(activeSlot);
|
|
768
|
+
node.log("Currently charging - end timer set");
|
|
769
|
+
} else {
|
|
770
|
+
// Not currently charging
|
|
771
|
+
const newState = false;
|
|
772
|
+
if (chargingNow !== newState) {
|
|
773
|
+
publishChargingState(newState);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// Find next future slot
|
|
777
|
+
const nextSlot = slots.find(s => new Date(s.startDt) > now);
|
|
778
|
+
|
|
779
|
+
if (nextSlot) {
|
|
780
|
+
setupPreValidationTimer(nextSlot);
|
|
781
|
+
node.log(`Next slot at ${nextSlot.startDt}`);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// 7. Event Listeners
|
|
787
|
+
|
|
788
|
+
// Helper: Publish current state (both pending and confirmed)
|
|
789
|
+
function publishCurrentState() {
|
|
790
|
+
if (enableMqtt && node.broker) {
|
|
791
|
+
const quickState = {
|
|
792
|
+
pending_limit: pendingLimit,
|
|
793
|
+
pending_time: pendingTime,
|
|
794
|
+
confirmed_limit: confirmedLimit,
|
|
795
|
+
confirmed_time: confirmedTime
|
|
796
|
+
};
|
|
797
|
+
node.broker.client.publish(stateTopic, JSON.stringify(quickState), { retain: false });
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// A. Handle Node-RED Input Messages
|
|
802
|
+
node.on('input', function (msg) {
|
|
803
|
+
// Check for control commands
|
|
804
|
+
if (msg.payload && typeof msg.payload === 'object') {
|
|
805
|
+
if (msg.payload.set_limit || msg.payload.set_time) {
|
|
806
|
+
// Use new values if present, otherwise keep existing
|
|
807
|
+
const targetLimit = msg.payload.set_limit || confirmedLimit;
|
|
808
|
+
const targetTime = msg.payload.set_time || confirmedTime;
|
|
809
|
+
setPreferences(targetLimit, targetTime);
|
|
810
|
+
return; // Don't run standard fetch if setting
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
// If just a trigger, run fetch
|
|
814
|
+
fetchData();
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
// B. Handle MQTT Commands (Home Assistant)
|
|
818
|
+
if (enableMqtt && node.broker) {
|
|
819
|
+
node.broker.register(this);
|
|
820
|
+
|
|
821
|
+
// Slider changed - update pending value only
|
|
822
|
+
node.broker.subscribe(cmdTopicLimit, 0, (topic, payload) => {
|
|
823
|
+
const val = parseInt(payload.toString());
|
|
824
|
+
pendingLimit = val;
|
|
825
|
+
publishCurrentState(); // Update display immediately
|
|
826
|
+
node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
|
|
827
|
+
});
|
|
828
|
+
|
|
829
|
+
// Dropdown changed - update pending value only
|
|
830
|
+
node.broker.subscribe(cmdTopicTime, 0, (topic, payload) => {
|
|
831
|
+
const val = payload.toString();
|
|
832
|
+
pendingTime = val;
|
|
833
|
+
publishCurrentState(); // Update display immediately
|
|
834
|
+
node.status({ fill: "yellow", shape: "dot", text: `Pending: ${pendingLimit}% @ ${pendingTime}` });
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
// Button pressed - submit changes to API
|
|
838
|
+
node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
|
|
839
|
+
setPreferences(pendingLimit, pendingTime);
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
setTimeout(announceControls, 2000);
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
// Init
|
|
846
|
+
const intervalId = setInterval(fetchData, refreshRate);
|
|
847
|
+
setTimeout(fetchData, 1000);
|
|
848
|
+
node.on('close', () => {
|
|
849
|
+
clearInterval(intervalId);
|
|
850
|
+
// Clear any pending retry timeouts
|
|
851
|
+
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
852
|
+
retryTimeouts = [];
|
|
853
|
+
// Clear charging timers
|
|
854
|
+
clearChargingTimers();
|
|
855
|
+
if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit);
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
RED.nodes.registerType("octopus-intelligent", OctopusIntelligentNode, {
|
|
860
|
+
credentials: { apiKey: { type: "password" } }
|
|
861
|
+
});
|
|
862
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "node-red-contrib-octopus-intelligent",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Node-RED integration for Octopus Energy Intelligent Octopus Go with Home Assistant MQTT discovery",
|
|
5
|
+
"main": "octopus-intelligent.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "jest",
|
|
8
|
+
"test:watch": "jest --watch",
|
|
9
|
+
"test:coverage": "jest --coverage"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"node-red",
|
|
13
|
+
"octopus-energy",
|
|
14
|
+
"intelligent-octopus",
|
|
15
|
+
"home-assistant",
|
|
16
|
+
"mqtt",
|
|
17
|
+
"ev-charging",
|
|
18
|
+
"smart-charging"
|
|
19
|
+
],
|
|
20
|
+
"author": "Andrew Somerharju Neale",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"node-red": {
|
|
23
|
+
"nodes": {
|
|
24
|
+
"octopus-intelligent": "octopus-intelligent.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"axios": "^1.6.0"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"jest": "^29.7.0",
|
|
32
|
+
"@types/jest": "^29.5.0"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://github.com/ASomerN/node-red-contrib-octopus-intelligent.git"
|
|
37
|
+
},
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/ASomerN/node-red-contrib-octopus-intelligent/issues"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://github.com/ASomerN/node-red-contrib-octopus-intelligent/blob/master/README.md"
|
|
42
|
+
}
|