node-red-contrib-octopus-intelligent 1.0.5 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,474 +0,0 @@
1
- /**
2
- * Reconciliation Loop Tests
3
- *
4
- * Tests that verify the 10-second reconciliation loop correctly detects
5
- * charging state changes and triggers both MQTT updates and Node-RED messages.
6
- *
7
- * Simulates time passing from before a slot starts to when it becomes active,
8
- * proving the reconciliation loop catches the transition.
9
- */
10
-
11
- const { createMockBroker, createMockNode } = require('../test-mocks');
12
-
13
- describe('Reconciliation Loop - Time-Based State Detection', () => {
14
- let mockBroker;
15
- let mockNode;
16
- let chargingNow;
17
- let cachedSlots;
18
- let stateCheckInterval;
19
- let sentMessages;
20
-
21
- beforeEach(() => {
22
- jest.clearAllMocks();
23
- jest.useFakeTimers();
24
-
25
- mockBroker = createMockBroker();
26
- mockNode = createMockNode();
27
-
28
- // Initialize state
29
- chargingNow = false;
30
- cachedSlots = [];
31
- stateCheckInterval = null;
32
- sentMessages = [];
33
- });
34
-
35
- afterEach(() => {
36
- if (stateCheckInterval) {
37
- clearInterval(stateCheckInterval);
38
- }
39
- jest.useRealTimers();
40
- });
41
-
42
- // ==========================================================================
43
- // Helper Functions
44
- // ==========================================================================
45
-
46
- function publishChargingState(state) {
47
- chargingNow = state;
48
-
49
- const enableMqtt = true;
50
- const stateTopic = 'nodered_octopus/A-TEST1234/status';
51
-
52
- if (enableMqtt && mockBroker) {
53
- const payload = state ? "ON" : "OFF";
54
- mockBroker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
55
- }
56
- }
57
-
58
- function sendNodeRedMessage(state) {
59
- const message = {
60
- payload: {
61
- charging_now: state,
62
- timestamp: new Date().toISOString()
63
- },
64
- debug: {
65
- trigger: 'reconciliation',
66
- state_change: true
67
- }
68
- };
69
- sentMessages.push(message);
70
- mockNode.send(message);
71
- }
72
-
73
- function reconcileChargingState() {
74
- if (!cachedSlots || cachedSlots.length === 0) return;
75
-
76
- const now = new Date();
77
-
78
- const shouldBeCharging = cachedSlots.some(slot => {
79
- const start = new Date(slot.startDt);
80
- const end = new Date(slot.endDt);
81
- return start <= now && end > now;
82
- });
83
-
84
- if (shouldBeCharging !== chargingNow) {
85
- mockNode.warn(`State reconciliation: Correcting chargingNow from ${chargingNow} to ${shouldBeCharging}`);
86
- publishChargingState(shouldBeCharging);
87
- sendNodeRedMessage(shouldBeCharging);
88
- }
89
- }
90
-
91
- function startStateReconciliation() {
92
- if (stateCheckInterval) {
93
- clearInterval(stateCheckInterval);
94
- }
95
-
96
- stateCheckInterval = setInterval(() => {
97
- reconcileChargingState();
98
- }, 10000);
99
-
100
- mockNode.log("State reconciliation loop started (every 10s)");
101
- }
102
-
103
- // ==========================================================================
104
- // Test Suite 1: Future Slot Becomes Active
105
- // ==========================================================================
106
-
107
- describe('Future Slot Becomes Active', () => {
108
- /**
109
- * @test Reconciliation detects slot becoming active
110
- * @scenario Start with future slot, wait for it to become active
111
- * @given Slot: 02:00 - 03:00, Current time: 01:50
112
- * @expect At 02:00, reconciliation detects change and updates state
113
- */
114
- test('should detect when future slot becomes active and trigger updates', () => {
115
- // Arrange: Set initial time BEFORE slot starts
116
- const initialTime = new Date('2025-12-10T01:50:00Z');
117
- jest.setSystemTime(initialTime);
118
-
119
- // Slot starts at 02:00 (10 minutes from now)
120
- cachedSlots = [
121
- {
122
- startDt: '2025-12-10 02:00:00+00:00',
123
- endDt: '2025-12-10 03:00:00+00:00',
124
- deltaKwh: -5,
125
- meta: { source: 'smart-charge' }
126
- }
127
- ];
128
-
129
- chargingNow = false;
130
-
131
- // Start reconciliation loop
132
- startStateReconciliation();
133
-
134
- // Verify initial state
135
- expect(chargingNow).toBe(false);
136
- expect(stateCheckInterval).not.toBeNull();
137
- expect(mockNode.log).toHaveBeenCalledWith("State reconciliation loop started (every 10s)");
138
-
139
- // Clear any initial MQTT publishes
140
- mockBroker.getPublished().length = 0;
141
- sentMessages.length = 0;
142
- mockNode.getSent().length = 0;
143
-
144
- // Act: Advance time by 5 minutes (still before slot)
145
- // 01:50 → 01:55
146
- jest.advanceTimersByTime(5 * 60 * 1000);
147
-
148
- // Reconciliation should have run (after 5 min = 30 ticks of 10s)
149
- // but state should still be false
150
- expect(chargingNow).toBe(false);
151
- expect(mockBroker.getPublished().length).toBe(0); // No MQTT updates
152
- expect(sentMessages.length).toBe(0); // No Node-RED messages
153
-
154
- // Act: Advance time to EXACTLY when slot starts
155
- // 01:55 → 02:00 (5 more minutes)
156
- jest.advanceTimersByTime(5 * 60 * 1000);
157
-
158
- // NOW we're in the slot! Next reconciliation tick should detect it
159
- // Advance by 10 seconds to trigger reconciliation
160
- jest.advanceTimersByTime(10000);
161
-
162
- // Assert: State should be updated
163
- expect(chargingNow).toBe(true);
164
-
165
- // Verify MQTT update
166
- const mqttPublished = mockBroker.getPublished();
167
- expect(mqttPublished.length).toBeGreaterThan(0);
168
- const chargingNowUpdate = mqttPublished.find(p => p.topic.endsWith('/charging_now'));
169
- expect(chargingNowUpdate).toBeDefined();
170
- expect(chargingNowUpdate.payload).toBe('ON');
171
-
172
- // Verify Node-RED message sent
173
- expect(sentMessages.length).toBe(1);
174
- expect(sentMessages[0].payload.charging_now).toBe(true);
175
- expect(sentMessages[0].debug.trigger).toBe('reconciliation');
176
-
177
- // Verify warning was logged
178
- expect(mockNode.warn).toHaveBeenCalledWith(
179
- expect.stringContaining('State reconciliation: Correcting chargingNow from false to true')
180
- );
181
- });
182
-
183
- /**
184
- * @test Reconciliation continues to run every 10 seconds
185
- * @scenario Verify multiple reconciliation ticks occur
186
- */
187
- test('should run reconciliation every 10 seconds consistently', () => {
188
- const initialTime = new Date('2025-12-10T01:00:00Z');
189
- jest.setSystemTime(initialTime);
190
-
191
- cachedSlots = [
192
- {
193
- startDt: '2025-12-10 02:00:00+00:00',
194
- endDt: '2025-12-10 03:00:00+00:00',
195
- deltaKwh: -5,
196
- meta: { source: 'smart-charge' }
197
- }
198
- ];
199
-
200
- chargingNow = false;
201
-
202
- // Spy on reconciliation function
203
- const reconcileSpy = jest.fn(reconcileChargingState);
204
- stateCheckInterval = setInterval(reconcileSpy, 10000);
205
-
206
- // Advance time by 1 minute (6 ticks)
207
- jest.advanceTimersByTime(60000);
208
-
209
- // Should have run 6 times
210
- expect(reconcileSpy).toHaveBeenCalledTimes(6);
211
-
212
- // Advance another 30 seconds (3 more ticks)
213
- jest.advanceTimersByTime(30000);
214
-
215
- // Should have run 9 times total
216
- expect(reconcileSpy).toHaveBeenCalledTimes(9);
217
- });
218
- });
219
-
220
- // ==========================================================================
221
- // Test Suite 2: Active Slot Becomes Inactive
222
- // ==========================================================================
223
-
224
- describe('Active Slot Becomes Inactive', () => {
225
- /**
226
- * @test Reconciliation detects slot ending
227
- * @scenario Start IN active slot, wait for it to end
228
- * @given Slot: 02:00 - 03:00, Current time: 02:55
229
- * @expect At 03:00, reconciliation detects change and updates state
230
- */
231
- test('should detect when active slot ends and trigger updates', () => {
232
- // Arrange: Set time INSIDE active slot (5 min before end)
233
- const initialTime = new Date('2025-12-10T02:55:00Z');
234
- jest.setSystemTime(initialTime);
235
-
236
- cachedSlots = [
237
- {
238
- startDt: '2025-12-10 02:00:00+00:00',
239
- endDt: '2025-12-10 03:00:00+00:00',
240
- deltaKwh: -5,
241
- meta: { source: 'smart-charge' }
242
- }
243
- ];
244
-
245
- chargingNow = true; // Currently charging
246
-
247
- startStateReconciliation();
248
-
249
- // Clear initial state
250
- mockBroker.getPublished().length = 0;
251
- sentMessages.length = 0;
252
-
253
- // Act: Advance to JUST BEFORE slot ends
254
- // 02:55 → 02:59 (4 minutes)
255
- jest.advanceTimersByTime(4 * 60 * 1000);
256
-
257
- // Still in slot
258
- expect(chargingNow).toBe(true);
259
- expect(sentMessages.length).toBe(0);
260
-
261
- // Act: Advance to AFTER slot ends
262
- // 02:59 → 03:01 (2 minutes)
263
- jest.advanceTimersByTime(2 * 60 * 1000);
264
-
265
- // Trigger reconciliation
266
- jest.advanceTimersByTime(10000);
267
-
268
- // Assert: State should be updated to NOT charging
269
- expect(chargingNow).toBe(false);
270
-
271
- // Verify MQTT update
272
- const mqttPublished = mockBroker.getPublished();
273
- const chargingNowUpdate = mqttPublished.find(p => p.topic.endsWith('/charging_now'));
274
- expect(chargingNowUpdate).toBeDefined();
275
- expect(chargingNowUpdate.payload).toBe('OFF');
276
-
277
- // Verify Node-RED message sent
278
- expect(sentMessages.length).toBe(1);
279
- expect(sentMessages[0].payload.charging_now).toBe(false);
280
-
281
- // Verify warning was logged
282
- expect(mockNode.warn).toHaveBeenCalledWith(
283
- expect.stringContaining('State reconciliation: Correcting chargingNow from true to false')
284
- );
285
- });
286
- });
287
-
288
- // ==========================================================================
289
- // Test Suite 3: Multiple Slots Transition
290
- // ==========================================================================
291
-
292
- describe('Multiple Slots Transition', () => {
293
- /**
294
- * @test Reconciliation handles transition between slots
295
- * @scenario Two slots with gap between them
296
- * @expect State transitions: false → true → false → true
297
- */
298
- test('should detect transitions through multiple slot boundaries', () => {
299
- // Arrange: Time before first slot
300
- const initialTime = new Date('2025-12-10T01:50:00Z');
301
- jest.setSystemTime(initialTime);
302
-
303
- cachedSlots = [
304
- {
305
- startDt: '2025-12-10 02:00:00+00:00', // Slot 1: 02:00-02:30
306
- endDt: '2025-12-10 02:30:00+00:00',
307
- deltaKwh: -3,
308
- meta: { source: 'smart-charge' }
309
- },
310
- {
311
- startDt: '2025-12-10 03:00:00+00:00', // Slot 2: 03:00-03:30
312
- endDt: '2025-12-10 03:30:00+00:00',
313
- deltaKwh: -3,
314
- meta: { source: 'smart-charge' }
315
- }
316
- ];
317
-
318
- chargingNow = false;
319
- startStateReconciliation();
320
-
321
- const stateChanges = [];
322
-
323
- // Capture state changes
324
- const originalPublish = publishChargingState;
325
- publishChargingState = (state) => {
326
- stateChanges.push({ time: new Date().toISOString(), state });
327
- originalPublish(state);
328
- };
329
-
330
- // Reset
331
- mockBroker.getPublished().length = 0;
332
- sentMessages.length = 0;
333
-
334
- // Timeline simulation:
335
- // 01:50 → 02:00 (10 min) - Enter slot 1
336
- jest.advanceTimersByTime(10 * 60 * 1000);
337
- jest.advanceTimersByTime(10000); // Trigger reconciliation
338
- expect(chargingNow).toBe(true); // Should be charging
339
-
340
- // 02:00 → 02:30 (30 min) - Exit slot 1
341
- jest.advanceTimersByTime(30 * 60 * 1000);
342
- jest.advanceTimersByTime(10000);
343
- expect(chargingNow).toBe(false); // Should NOT be charging
344
-
345
- // 02:30 → 03:00 (30 min) - Enter slot 2
346
- jest.advanceTimersByTime(30 * 60 * 1000);
347
- jest.advanceTimersByTime(10000);
348
- expect(chargingNow).toBe(true); // Should be charging again
349
-
350
- // Verify we had 3 state changes
351
- expect(stateChanges.length).toBe(3);
352
- expect(stateChanges[0].state).toBe(true); // Entered slot 1
353
- expect(stateChanges[1].state).toBe(false); // Exited slot 1
354
- expect(stateChanges[2].state).toBe(true); // Entered slot 2
355
- });
356
- });
357
-
358
- // ==========================================================================
359
- // Test Suite 4: No False Positives
360
- // ==========================================================================
361
-
362
- describe('No False Positives', () => {
363
- /**
364
- * @test Reconciliation doesn't trigger when state is correct
365
- * @scenario State matches reality throughout
366
- * @expect No updates triggered
367
- */
368
- test('should NOT trigger updates when state is already correct', () => {
369
- const initialTime = new Date('2025-12-10T02:30:00Z');
370
- jest.setSystemTime(initialTime);
371
-
372
- cachedSlots = [
373
- {
374
- startDt: '2025-12-10 02:00:00+00:00',
375
- endDt: '2025-12-10 03:00:00+00:00',
376
- deltaKwh: -5,
377
- meta: { source: 'smart-charge' }
378
- }
379
- ];
380
-
381
- chargingNow = true; // Correctly set to true (we're in slot)
382
-
383
- startStateReconciliation();
384
-
385
- // Clear initial state
386
- mockBroker.getPublished().length = 0;
387
- sentMessages.length = 0;
388
- mockNode.warn.mockClear();
389
-
390
- // Advance time by 20 minutes (still in slot)
391
- // This triggers 120 reconciliation ticks
392
- jest.advanceTimersByTime(20 * 60 * 1000);
393
-
394
- // State should still be true (unchanged)
395
- expect(chargingNow).toBe(true);
396
-
397
- // NO MQTT updates should have happened
398
- expect(mockBroker.getPublished().length).toBe(0);
399
-
400
- // NO Node-RED messages should have been sent
401
- expect(sentMessages.length).toBe(0);
402
-
403
- // NO warnings should have been logged
404
- expect(mockNode.warn).not.toHaveBeenCalled();
405
- });
406
- });
407
-
408
- // ==========================================================================
409
- // Test Suite 5: Integration - Complete Charging Session
410
- // ==========================================================================
411
-
412
- describe('Complete Charging Session', () => {
413
- /**
414
- * @test Full charging session simulation
415
- * @scenario Simulate realistic charging session timeline
416
- */
417
- test('should correctly track state through complete charging session', () => {
418
- // Start before car is plugged in
419
- const initialTime = new Date('2025-12-10T01:00:00Z');
420
- jest.setSystemTime(initialTime);
421
-
422
- // No slots initially
423
- cachedSlots = [];
424
- chargingNow = false;
425
-
426
- startStateReconciliation();
427
-
428
- const timeline = [];
429
-
430
- // 01:00 - No slots, not charging
431
- jest.advanceTimersByTime(10000);
432
- timeline.push({ time: '01:00', charging: chargingNow, slots: cachedSlots.length });
433
-
434
- // 01:30 - Car plugged in, API returns slots (simulated by updating cachedSlots)
435
- jest.setSystemTime(new Date('2025-12-10T01:30:00Z'));
436
- cachedSlots = [
437
- {
438
- startDt: '2025-12-10 02:00:00+00:00',
439
- endDt: '2025-12-10 03:00:00+00:00',
440
- deltaKwh: -15,
441
- meta: { source: 'smart-charge' }
442
- }
443
- ];
444
- jest.advanceTimersByTime(10000);
445
- timeline.push({ time: '01:30', charging: chargingNow, slots: cachedSlots.length });
446
- expect(chargingNow).toBe(false); // Still before slot
447
-
448
- // 02:00 - Slot starts, reconciliation detects it
449
- jest.setSystemTime(new Date('2025-12-10T02:00:00Z'));
450
- jest.advanceTimersByTime(10000);
451
- timeline.push({ time: '02:00', charging: chargingNow, slots: cachedSlots.length });
452
- expect(chargingNow).toBe(true); // NOW charging!
453
-
454
- // 02:30 - Still charging
455
- jest.setSystemTime(new Date('2025-12-10T02:30:00Z'));
456
- jest.advanceTimersByTime(10000);
457
- timeline.push({ time: '02:30', charging: chargingNow, slots: cachedSlots.length });
458
- expect(chargingNow).toBe(true);
459
-
460
- // 03:00 - Slot ends, reconciliation detects it
461
- jest.setSystemTime(new Date('2025-12-10T03:00:00Z'));
462
- jest.advanceTimersByTime(10000);
463
- timeline.push({ time: '03:00', charging: chargingNow, slots: cachedSlots.length });
464
- expect(chargingNow).toBe(false); // Stopped charging
465
-
466
- // Verify timeline
467
- expect(timeline[0].charging).toBe(false); // Before slot
468
- expect(timeline[1].charging).toBe(false); // Car plugged in but before slot
469
- expect(timeline[2].charging).toBe(true); // Charging started
470
- expect(timeline[3].charging).toBe(true); // Still charging
471
- expect(timeline[4].charging).toBe(false); // Charging stopped
472
- });
473
- });
474
- });
@@ -1,64 +0,0 @@
1
- # Images Needed for Documentation
2
-
3
- Place the following screenshot images in this directory to enhance the README and Node-RED help documentation.
4
-
5
- ## Captured Images ✅
6
-
7
- | Description | Image Name | Status | Version |
8
- |-------------|------------|--------|---------|
9
- | Node-RED flow: Shows basic monitoring, set preferences, and preset buttons all in one comprehensive flow | `examples/basic-monitoring-flow.png` | ✅ Captured | v1.0.1+ |
10
- | Node-RED flow: Complete MQTT integration with broker config | `examples/mqtt-integration-flow.png` | ✅ Captured | v1.0.1+ |
11
- | Home Assistant: Device page showing all v1.0.4 entities including refresh button and API monitoring | `examples/homeassistant-device-v1.0.4.png` | ✅ Captured | v1.0.4 |
12
-
13
- **Legacy Images (Outdated):**
14
- - `examples/homeassistant-device.png` - v1.0.1 screenshot (missing v1.0.4 features) - Kept for reference
15
-
16
- **Total: 3 current images + 1 legacy = All requirements covered!**
17
-
18
- ## Image Guidelines
19
-
20
- - **Format:** PNG preferred (better for screenshots)
21
- - **Size:** Keep under 500KB per image (compress if needed using TinyPNG or similar)
22
- - **Resolution:** 1920x1080 or similar HD resolution
23
- - **Content:** Ensure no sensitive data visible (account numbers, API keys, real addresses)
24
- - **Theme:** Light theme preferred for consistency (easier to see in documentation)
25
-
26
- ## How to Capture Node-RED Flows
27
-
28
- 1. Import/create the example flow
29
- 2. Arrange nodes neatly in editor
30
- 3. Take screenshot of flow area
31
- 4. Crop to show just the flow (remove unnecessary UI)
32
- 5. Save with appropriate filename in `images/examples/` folder
33
-
34
- ## How to Capture Home Assistant Screenshots
35
-
36
- 1. Navigate to Settings → Devices & Services → MQTT
37
- 2. Click "Octopus Intelligent" device
38
- 3. Expand all sections (Controls, Sensors, Diagnostics)
39
- 4. Ensure sensors show actual values (not "unavailable")
40
- 5. For v1.0.4 screenshots, ensure these are visible:
41
- - Controls: "Octopus Refresh API" button
42
- - Diagnostics: "Refresh Available At", "API Requests", "API Complexity" sensors
43
- 6. Screenshot entire device page
44
- 7. Crop to remove unnecessary UI chrome
45
- 8. Save with versioned filename (e.g., `homeassistant-device-v1.0.4.png`)
46
-
47
- ## Usage in Documentation
48
-
49
- ### In README.md:
50
- ```markdown
51
- ![Basic Monitoring Flow](images/examples/basic-monitoring-flow.png)
52
- ```
53
-
54
- ### In octopus-intelligent.html:
55
- ```html
56
- <img src="https://raw.githubusercontent.com/ASomerN/node-red-contrib-octopus-intelligent/master/images/homeassistant-device.png" alt="Home Assistant Device" style="max-width: 100%;">
57
- ```
58
-
59
- ## Notes
60
-
61
- - Images will be committed to git and hosted on GitHub
62
- - GitHub raw URLs allow direct embedding in Node-RED help panel
63
- - Keep images focused and cropped to relevant content
64
- - All images are excluded from npm package (kept in git only for documentation)