node-red-contrib-octopus-intelligent 1.0.3 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +72 -0
- package/README.md +480 -432
- package/__tests__/README.md +220 -0
- package/__tests__/TEST-SUMMARY.md +194 -0
- package/__tests__/charging-now-validation.test.js +495 -0
- package/__tests__/charging-timers.test.js +601 -0
- package/__tests__/data-processing.test.js +478 -0
- package/__tests__/mqtt-refresh-cooldown.test.js +420 -0
- package/__tests__/reconciliation-loop.test.js +474 -0
- package/images/IMAGES_NEEDED.md +64 -0
- package/images/examples/basic-monitoring-flow.png +0 -0
- package/images/examples/homeassistant-device-v1.0.4.png +0 -0
- package/images/examples/homeassistant-device.png +0 -0
- package/images/examples/mqtt-integration-flow.png +0 -0
- package/octopus-intelligent.js +271 -22
- package/package.json +12 -1
- package/test-mocks.js +1038 -0
- package/NodeRed_Global_Setter.js +0 -76
- package/RELEASE.md +0 -140
package/octopus-intelligent.js
CHANGED
|
@@ -21,6 +21,7 @@ module.exports = function (RED) {
|
|
|
21
21
|
const cmdTopicLimit = `nodered_octopus/${account}/set_limit`;
|
|
22
22
|
const cmdTopicTime = `nodered_octopus/${account}/set_time`;
|
|
23
23
|
const cmdTopicSubmit = `nodered_octopus/${account}/submit_changes`;
|
|
24
|
+
const cmdTopicRefresh = `nodered_octopus/${account}/refresh`;
|
|
24
25
|
|
|
25
26
|
// 2. Constants & Validation
|
|
26
27
|
const TIME_OPTIONS = [
|
|
@@ -48,8 +49,20 @@ module.exports = function (RED) {
|
|
|
48
49
|
{ id: "window_start", name: "Overall Window Start", class: "timestamp", icon: "mdi:timer-play", val: "window_start" },
|
|
49
50
|
{ id: "window_end", name: "Overall Window End", class: "timestamp", icon: "mdi:timer-stop", val: "window_end" },
|
|
50
51
|
|
|
51
|
-
//
|
|
52
|
+
// v1.0.4: Next poll timer
|
|
53
|
+
{ id: "next_poll", name: "Next Poll Time", class: "timestamp", icon: "mdi:clock-outline", val: "next_poll" },
|
|
54
|
+
|
|
55
|
+
// v1.0.4: Refresh available timestamp (diagnostic) - for Home Assistant countdown
|
|
56
|
+
{ id: "refresh_available_at", name: "Refresh Available At", class: "timestamp", icon: "mdi:timer-sand", val: "refresh_available_at" },
|
|
57
|
+
|
|
58
|
+
// v1.0.4: API complexity tracking (diagnostic)
|
|
59
|
+
{ id: "api_requests_hour", name: "API Requests (Last Hour)", icon: "mdi:api", val: "api_requests_hour" },
|
|
60
|
+
{ id: "api_complexity_hour", name: "API Complexity (Last Hour)", icon: "mdi:chart-line", val: "api_complexity_hour" },
|
|
61
|
+
{ id: "api_complexity_percent", name: "API Complexity Usage", icon: "mdi:percent", unit: "%", val: "api_complexity_percent" },
|
|
62
|
+
|
|
63
|
+
// Raw timestamp strings (show exact API timestamp) - marked as diagnostic
|
|
52
64
|
{ id: "next_charge_raw", name: "Next Charge Time (Raw)", icon: "mdi:timer", val: "next_start_raw" },
|
|
65
|
+
{ id: "next_poll_raw", name: "Next Poll Time (Raw)", icon: "mdi:clock-outline", val: "next_poll_raw" },
|
|
53
66
|
{ id: "slot1_start_raw", name: "Slot 1 Start (Raw)", icon: "mdi:timer-outline", val: "slot1_start_raw" },
|
|
54
67
|
{ id: "slot1_end_raw", name: "Slot 1 End (Raw)", icon: "mdi:timer-outline", val: "slot1_end_raw" },
|
|
55
68
|
{ id: "slot2_start_raw", name: "Slot 2 Start (Raw)", icon: "mdi:timer-outline", val: "slot2_start_raw" },
|
|
@@ -114,7 +127,19 @@ module.exports = function (RED) {
|
|
|
114
127
|
};
|
|
115
128
|
node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_submit/config`, JSON.stringify(buttonConfig), { retain: true });
|
|
116
129
|
|
|
117
|
-
// D.
|
|
130
|
+
// D. Refresh Button
|
|
131
|
+
const refreshButtonConfig = {
|
|
132
|
+
name: "Octopus Refresh API",
|
|
133
|
+
unique_id: `${uniqueIdPrefix}_refresh_button`,
|
|
134
|
+
command_topic: cmdTopicRefresh,
|
|
135
|
+
payload_press: "REFRESH",
|
|
136
|
+
icon: "mdi:refresh",
|
|
137
|
+
device_class: "restart",
|
|
138
|
+
device: device
|
|
139
|
+
};
|
|
140
|
+
node.broker.client.publish(`${mqttPrefix}/button/${uniqueIdPrefix}_refresh/config`, JSON.stringify(refreshButtonConfig), { retain: true });
|
|
141
|
+
|
|
142
|
+
// E. Add sensors for confirmed values (read-only display)
|
|
118
143
|
const confirmedLimitSensor = {
|
|
119
144
|
name: "Octopus Confirmed Charge Limit",
|
|
120
145
|
unique_id: `${uniqueIdPrefix}_confirmed_limit`,
|
|
@@ -136,7 +161,7 @@ module.exports = function (RED) {
|
|
|
136
161
|
};
|
|
137
162
|
node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_confirmed_time/config`, JSON.stringify(confirmedTimeSensor), { retain: true });
|
|
138
163
|
|
|
139
|
-
//
|
|
164
|
+
// G. Charging Now Binary Sensor (main sensor for automations)
|
|
140
165
|
const chargingNowBinarySensor = {
|
|
141
166
|
name: "Octopus Charging Now",
|
|
142
167
|
unique_id: `${uniqueIdPrefix}_charging_now`,
|
|
@@ -149,7 +174,7 @@ module.exports = function (RED) {
|
|
|
149
174
|
};
|
|
150
175
|
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
|
|
151
176
|
|
|
152
|
-
//
|
|
177
|
+
// H. Announce Read-Only Sensors
|
|
153
178
|
sensors.forEach(sensor => {
|
|
154
179
|
const payload = {
|
|
155
180
|
name: `Octopus ${sensor.name}`,
|
|
@@ -162,8 +187,10 @@ module.exports = function (RED) {
|
|
|
162
187
|
if (sensor.unit) payload.unit_of_measurement = sensor.unit;
|
|
163
188
|
if (sensor.icon) payload.icon = sensor.icon;
|
|
164
189
|
|
|
165
|
-
// Mark raw sensors as diagnostic (moves to Diagnostics section)
|
|
166
|
-
if (sensor.id.includes('_raw')
|
|
190
|
+
// Mark raw sensors, refresh timestamp, and API metrics as diagnostic (moves to Diagnostics section)
|
|
191
|
+
if (sensor.id.includes('_raw') ||
|
|
192
|
+
sensor.id === 'refresh_available_at' ||
|
|
193
|
+
sensor.id.startsWith('api_')) {
|
|
167
194
|
payload.entity_category = "diagnostic";
|
|
168
195
|
}
|
|
169
196
|
|
|
@@ -174,6 +201,7 @@ module.exports = function (RED) {
|
|
|
174
201
|
node.broker.client.subscribe(cmdTopicLimit);
|
|
175
202
|
node.broker.client.subscribe(cmdTopicTime);
|
|
176
203
|
node.broker.client.subscribe(cmdTopicSubmit);
|
|
204
|
+
node.broker.client.subscribe(cmdTopicRefresh);
|
|
177
205
|
}
|
|
178
206
|
|
|
179
207
|
// 5. Helper: Set Preferences (The Mutation)
|
|
@@ -194,6 +222,24 @@ module.exports = function (RED) {
|
|
|
194
222
|
let slotEndTimer = null; // Fires at exact slot end
|
|
195
223
|
let cachedSlots = []; // Fresh slot data from pre-validation
|
|
196
224
|
let stateCheckInterval = null; // Reconciliation loop (every 10s)
|
|
225
|
+
let lastSentChargingState = null; // Track last sent state to avoid duplicates
|
|
226
|
+
|
|
227
|
+
// Manual refresh rate limiting (only for MQTT button, not Node-RED input)
|
|
228
|
+
let lastManualRefresh = 0; // Timestamp of last manual refresh
|
|
229
|
+
const MANUAL_REFRESH_COOLDOWN = 30000; // 30 seconds in milliseconds
|
|
230
|
+
let cooldownExpiryTimer = null; // Timer to clear cooldown state at expiry
|
|
231
|
+
|
|
232
|
+
// Polling metrics
|
|
233
|
+
let nextPollTime = null; // ISO timestamp of next scheduled poll
|
|
234
|
+
let pollIntervalHandle = null; // Reference to setInterval handle
|
|
235
|
+
let pollHistory = []; // Array of {timestamp, complexity} for last 60 min
|
|
236
|
+
|
|
237
|
+
// API Complexity Tracking
|
|
238
|
+
// Octopus Energy API does not return actual complexity values in headers or extensions,
|
|
239
|
+
// so we use estimated complexity based on query types:
|
|
240
|
+
// - Regular poll (auth + data query): ~300
|
|
241
|
+
// - Mutation (auth + setPreferences): ~250
|
|
242
|
+
// - Pre-validation (auth + plannedDispatches only): ~200
|
|
197
243
|
|
|
198
244
|
// Last known full state - prevents sensors going unknown when controls change
|
|
199
245
|
let lastKnownState = buildDefaultPayload();
|
|
@@ -262,6 +308,10 @@ module.exports = function (RED) {
|
|
|
262
308
|
throw new Error(`Mutation failed: ${JSON.stringify(mutationResponse.data.errors)}`);
|
|
263
309
|
}
|
|
264
310
|
|
|
311
|
+
// Record mutation API usage (auth + mutation = ~250 complexity)
|
|
312
|
+
const ESTIMATED_MUTATION_COMPLEXITY = 250;
|
|
313
|
+
recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
314
|
+
|
|
265
315
|
// C. Start exponential backoff validation
|
|
266
316
|
expectedLimit = limit;
|
|
267
317
|
expectedTime = time;
|
|
@@ -327,6 +377,12 @@ module.exports = function (RED) {
|
|
|
327
377
|
|
|
328
378
|
// 6. Logic: Fetch Data (Read)
|
|
329
379
|
async function fetchData(validationMode = false) {
|
|
380
|
+
// Estimated complexity per poll:
|
|
381
|
+
// - Auth mutation: ~100 complexity
|
|
382
|
+
// - Data query (plannedDispatches + vehicleChargingPreferences): ~200 complexity
|
|
383
|
+
// - Total: ~300 complexity per poll
|
|
384
|
+
const ESTIMATED_POLL_COMPLEXITY = 300;
|
|
385
|
+
|
|
330
386
|
// Debug object to track API calls
|
|
331
387
|
const debugInfo = {
|
|
332
388
|
timestamp: new Date().toISOString(),
|
|
@@ -389,6 +445,8 @@ module.exports = function (RED) {
|
|
|
389
445
|
debugInfo.step = "fetching_data";
|
|
390
446
|
node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
|
|
391
447
|
|
|
448
|
+
// Note: rateLimitInfo query may not be available on all API versions
|
|
449
|
+
// If it fails, we'll use fallback estimated complexity
|
|
392
450
|
const masterQuery = `
|
|
393
451
|
query getData($account: String!) {
|
|
394
452
|
plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } }
|
|
@@ -409,7 +467,9 @@ module.exports = function (RED) {
|
|
|
409
467
|
statusCode: dataResponse.status,
|
|
410
468
|
hasErrors: !!(dataResponse.data.errors),
|
|
411
469
|
errors: dataResponse.data.errors || null,
|
|
412
|
-
hasData: !!(dataResponse.data.data)
|
|
470
|
+
hasData: !!(dataResponse.data.data),
|
|
471
|
+
// Capture response headers for rate limit analysis
|
|
472
|
+
responseHeaders: dataResponse.headers || {}
|
|
413
473
|
});
|
|
414
474
|
|
|
415
475
|
// Validate data response
|
|
@@ -426,6 +486,19 @@ module.exports = function (RED) {
|
|
|
426
486
|
const slots = data.plannedDispatches || [];
|
|
427
487
|
const prefs = data.vehicleChargingPreferences || {};
|
|
428
488
|
|
|
489
|
+
// Check for GraphQL extensions (may contain complexity/rate limit info)
|
|
490
|
+
let actualComplexity = null;
|
|
491
|
+
if (dataResponse.data.extensions) {
|
|
492
|
+
debugInfo.apiCalls[1].extensions = dataResponse.data.extensions;
|
|
493
|
+
// Try to extract complexity if available
|
|
494
|
+
actualComplexity = dataResponse.data.extensions.complexity ||
|
|
495
|
+
dataResponse.data.extensions.cost ||
|
|
496
|
+
null;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// Record poll with estimated or actual complexity
|
|
500
|
+
recordPoll(actualComplexity || ESTIMATED_POLL_COMPLEXITY);
|
|
501
|
+
|
|
429
502
|
debugInfo.apiCalls[1].slotsFound = slots.length;
|
|
430
503
|
debugInfo.apiCalls[1].preferencesFound = !!(prefs.weekdayTargetSoc);
|
|
431
504
|
debugInfo.apiCalls[1].slotDetails = slots.map(s => ({
|
|
@@ -457,15 +530,20 @@ module.exports = function (RED) {
|
|
|
457
530
|
debugInfo.apiCalls[1].activeAndFutureSlots = activeAndFutureSlots.length;
|
|
458
531
|
debugInfo.processingTime = now.toISOString();
|
|
459
532
|
|
|
460
|
-
// Setup charging timers (
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
}
|
|
533
|
+
// Setup charging timers (always update charging state)
|
|
534
|
+
setupChargingTimers(activeAndFutureSlots);
|
|
535
|
+
|
|
536
|
+
// Start reconciliation loop on first successful data fetch (only in non-validation mode)
|
|
537
|
+
if (!validationMode && !stateCheckInterval) {
|
|
538
|
+
startStateReconciliation();
|
|
467
539
|
}
|
|
468
540
|
|
|
541
|
+
// Update next poll time after successful fetch
|
|
542
|
+
updateNextPollTime();
|
|
543
|
+
|
|
544
|
+
// Get API metrics for inclusion in payload
|
|
545
|
+
const apiMetrics = getApiMetrics();
|
|
546
|
+
|
|
469
547
|
// Build Payload
|
|
470
548
|
const statusPayload = {
|
|
471
549
|
next_start: nextSlot ? nextSlot.startDt : null,
|
|
@@ -480,6 +558,15 @@ module.exports = function (RED) {
|
|
|
480
558
|
pending_time: pendingTime,
|
|
481
559
|
// Charging Now state
|
|
482
560
|
charging_now: chargingNow,
|
|
561
|
+
// Next poll time
|
|
562
|
+
next_poll: nextPollTime,
|
|
563
|
+
next_poll_raw: nextPollTime,
|
|
564
|
+
// Refresh available timestamp (null = ready, ISO timestamp = counting down)
|
|
565
|
+
refresh_available_at: getRefreshAvailableAt(),
|
|
566
|
+
// API complexity metrics
|
|
567
|
+
api_requests_hour: apiMetrics.requests_last_hour,
|
|
568
|
+
api_complexity_hour: apiMetrics.complexity_last_hour,
|
|
569
|
+
api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
|
|
483
570
|
// Individual slots (first 3 active/future) - formatted timestamps
|
|
484
571
|
slot1_start: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
|
|
485
572
|
slot1_end: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
|
|
@@ -518,6 +605,16 @@ module.exports = function (RED) {
|
|
|
518
605
|
debugInfo.validated = isValidated;
|
|
519
606
|
}
|
|
520
607
|
|
|
608
|
+
// Add API usage metrics to debug info (already fetched above)
|
|
609
|
+
debugInfo.api_usage = {
|
|
610
|
+
requests_last_hour: apiMetrics.requests_last_hour,
|
|
611
|
+
complexity_last_hour: apiMetrics.complexity_last_hour,
|
|
612
|
+
complexity_percent_used: apiMetrics.complexity_percent,
|
|
613
|
+
api_limit_hourly: 50000,
|
|
614
|
+
request_complexity: actualComplexity || ESTIMATED_POLL_COMPLEXITY,
|
|
615
|
+
complexity_source: actualComplexity ? "api" : "estimated"
|
|
616
|
+
};
|
|
617
|
+
|
|
521
618
|
// Store this as the last known full state
|
|
522
619
|
lastKnownState = statusPayload;
|
|
523
620
|
|
|
@@ -527,6 +624,9 @@ module.exports = function (RED) {
|
|
|
527
624
|
debug: debugInfo
|
|
528
625
|
});
|
|
529
626
|
|
|
627
|
+
// Update last sent charging state to prevent duplicate messages
|
|
628
|
+
lastSentChargingState = chargingNow;
|
|
629
|
+
|
|
530
630
|
if (enableMqtt && node.broker) {
|
|
531
631
|
node.broker.client.publish(stateTopic, JSON.stringify(statusPayload), { retain: true });
|
|
532
632
|
// Also publish charging_now state to binary sensor topic
|
|
@@ -592,6 +692,10 @@ module.exports = function (RED) {
|
|
|
592
692
|
pending_limit: pendingLimit,
|
|
593
693
|
pending_time: pendingTime,
|
|
594
694
|
charging_now: chargingNow,
|
|
695
|
+
refresh_available_at: null,
|
|
696
|
+
api_requests_hour: 0,
|
|
697
|
+
api_complexity_hour: 0,
|
|
698
|
+
api_complexity_percent: 0,
|
|
595
699
|
slot1_start: null,
|
|
596
700
|
slot1_end: null,
|
|
597
701
|
slot2_start: null,
|
|
@@ -670,13 +774,110 @@ module.exports = function (RED) {
|
|
|
670
774
|
}
|
|
671
775
|
}
|
|
672
776
|
|
|
673
|
-
//
|
|
777
|
+
// Manual refresh rate limiting helpers
|
|
778
|
+
function canManualRefresh() {
|
|
779
|
+
const now = Date.now();
|
|
780
|
+
const timeSinceLastRefresh = now - lastManualRefresh;
|
|
781
|
+
return lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function getSecondsUntilNextRefresh() {
|
|
785
|
+
const now = Date.now();
|
|
786
|
+
const timeSinceLastRefresh = now - lastManualRefresh;
|
|
787
|
+
const timeRemaining = MANUAL_REFRESH_COOLDOWN - timeSinceLastRefresh;
|
|
788
|
+
return Math.max(0, Math.ceil(timeRemaining / 1000));
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function getRefreshAvailableAt() {
|
|
792
|
+
const now = Date.now();
|
|
793
|
+
const timeSinceLastRefresh = now - lastManualRefresh;
|
|
794
|
+
|
|
795
|
+
// If never refreshed OR cooldown expired, ready now
|
|
796
|
+
if (lastManualRefresh === 0 || timeSinceLastRefresh >= MANUAL_REFRESH_COOLDOWN) {
|
|
797
|
+
return null; // Ready - no cooldown
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// Cooldown active - return timestamp when it expires
|
|
801
|
+
return new Date(lastManualRefresh + MANUAL_REFRESH_COOLDOWN).toISOString();
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function publishRefreshCooldownState() {
|
|
805
|
+
if (enableMqtt && node.broker) {
|
|
806
|
+
const fullState = {
|
|
807
|
+
...lastKnownState,
|
|
808
|
+
refresh_available_at: getRefreshAvailableAt()
|
|
809
|
+
};
|
|
810
|
+
node.broker.client.publish(stateTopic, JSON.stringify(fullState), { retain: true });
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
// Polling metrics helpers
|
|
815
|
+
function updateNextPollTime() {
|
|
816
|
+
nextPollTime = new Date(Date.now() + refreshRate).toISOString();
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
function recordPoll(complexity = null) {
|
|
820
|
+
const now = Date.now();
|
|
821
|
+
pollHistory.push({
|
|
822
|
+
timestamp: now,
|
|
823
|
+
complexity: complexity || null
|
|
824
|
+
});
|
|
825
|
+
|
|
826
|
+
// Remove entries older than 60 minutes
|
|
827
|
+
const sixtyMinAgo = now - (60 * 60 * 1000);
|
|
828
|
+
pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function getApiMetrics() {
|
|
832
|
+
// Clean up old entries first
|
|
833
|
+
const now = Date.now();
|
|
834
|
+
const sixtyMinAgo = now - (60 * 60 * 1000);
|
|
835
|
+
pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
|
|
836
|
+
|
|
837
|
+
const requestCount = pollHistory.length;
|
|
838
|
+
const totalComplexity = pollHistory.reduce((sum, entry) => sum + (entry.complexity || 0), 0);
|
|
839
|
+
const percentUsed = requestCount > 0 && totalComplexity > 0 ? (totalComplexity / 50000) * 100 : 0;
|
|
840
|
+
|
|
841
|
+
return {
|
|
842
|
+
requests_last_hour: requestCount,
|
|
843
|
+
complexity_last_hour: totalComplexity,
|
|
844
|
+
complexity_percent: percentUsed.toFixed(1)
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// Publish charging state to MQTT and Node-RED
|
|
674
849
|
function publishChargingState(state) {
|
|
675
850
|
chargingNow = state;
|
|
851
|
+
|
|
852
|
+
// Update MQTT
|
|
676
853
|
if (enableMqtt && node.broker) {
|
|
677
854
|
const payload = state ? "ON" : "OFF";
|
|
678
855
|
node.broker.client.publish(`${stateTopic}/charging_now`, payload, { retain: true });
|
|
679
856
|
}
|
|
857
|
+
|
|
858
|
+
// Output message to Node-RED flow if state actually changed
|
|
859
|
+
if (lastSentChargingState !== state) {
|
|
860
|
+
lastSentChargingState = state;
|
|
861
|
+
|
|
862
|
+
// Merge updated charging_now into last known full state
|
|
863
|
+
const outputPayload = {
|
|
864
|
+
...lastKnownState,
|
|
865
|
+
charging_now: state
|
|
866
|
+
};
|
|
867
|
+
|
|
868
|
+
node.send({
|
|
869
|
+
payload: outputPayload,
|
|
870
|
+
debug: {
|
|
871
|
+
timestamp: new Date().toISOString(),
|
|
872
|
+
trigger: 'charging_state_change',
|
|
873
|
+
success: true,
|
|
874
|
+
previous_state: !state,
|
|
875
|
+
new_state: state
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
|
|
879
|
+
node.log(`Charging state changed: ${!state} → ${state}, message sent`);
|
|
880
|
+
}
|
|
680
881
|
}
|
|
681
882
|
|
|
682
883
|
// Setup pre-validation timer (30s before slot starts)
|
|
@@ -710,6 +911,10 @@ module.exports = function (RED) {
|
|
|
710
911
|
if (dataResponse.data.data && dataResponse.data.data.plannedDispatches) {
|
|
711
912
|
cachedSlots = dataResponse.data.data.plannedDispatches;
|
|
712
913
|
|
|
914
|
+
// Record pre-validation API usage (auth + simple query = ~200 complexity)
|
|
915
|
+
const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
|
|
916
|
+
recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
|
|
917
|
+
|
|
713
918
|
// Check if slot still exists (within 1 minute tolerance)
|
|
714
919
|
const stillExists = cachedSlots.find(s =>
|
|
715
920
|
Math.abs(new Date(s.startDt).getTime() - slotStart.getTime()) < 60000
|
|
@@ -851,9 +1056,9 @@ module.exports = function (RED) {
|
|
|
851
1056
|
}
|
|
852
1057
|
}
|
|
853
1058
|
|
|
854
|
-
// A. Handle Node-RED Input Messages
|
|
1059
|
+
// A. Handle Node-RED Input Messages (NO rate limiting - programmers control this)
|
|
855
1060
|
node.on('input', function (msg) {
|
|
856
|
-
// Check for control commands
|
|
1061
|
+
// Check for control commands (preference updates)
|
|
857
1062
|
if (msg.payload && typeof msg.payload === 'object') {
|
|
858
1063
|
if (msg.payload.set_limit || msg.payload.set_time) {
|
|
859
1064
|
// Use new values if present, otherwise keep existing
|
|
@@ -863,7 +1068,12 @@ module.exports = function (RED) {
|
|
|
863
1068
|
return; // Don't run standard fetch if setting
|
|
864
1069
|
}
|
|
865
1070
|
}
|
|
866
|
-
|
|
1071
|
+
|
|
1072
|
+
// Manual refresh request from Node-RED - NO rate limiting
|
|
1073
|
+
// (Programmers can control rate limiting in their flows if needed)
|
|
1074
|
+
// Update timestamp so HA sees cooldown, but don't block the refresh
|
|
1075
|
+
lastManualRefresh = Date.now();
|
|
1076
|
+
node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
|
|
867
1077
|
fetchData();
|
|
868
1078
|
});
|
|
869
1079
|
|
|
@@ -891,21 +1101,60 @@ module.exports = function (RED) {
|
|
|
891
1101
|
node.broker.subscribe(cmdTopicSubmit, 0, (topic, payload) => {
|
|
892
1102
|
setPreferences(pendingLimit, pendingTime);
|
|
893
1103
|
});
|
|
894
|
-
|
|
1104
|
+
|
|
1105
|
+
// Refresh button pressed - MQTT has hardcoded 30s rate limiting
|
|
1106
|
+
node.broker.subscribe(cmdTopicRefresh, 0, (topic, payload) => {
|
|
1107
|
+
// Check rate limit (only for MQTT button)
|
|
1108
|
+
if (!canManualRefresh()) {
|
|
1109
|
+
const secondsRemaining = getSecondsUntilNextRefresh();
|
|
1110
|
+
node.status({
|
|
1111
|
+
fill: "red",
|
|
1112
|
+
shape: "dot",
|
|
1113
|
+
text: `Cooldown: ${secondsRemaining}s`
|
|
1114
|
+
});
|
|
1115
|
+
node.warn(`MQTT refresh blocked. Please wait ${secondsRemaining} seconds.`);
|
|
1116
|
+
return; // Block the refresh
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// Refresh allowed - set cooldown timestamp
|
|
1120
|
+
lastManualRefresh = Date.now();
|
|
1121
|
+
|
|
1122
|
+
// Publish immediate update with countdown timestamp
|
|
1123
|
+
publishRefreshCooldownState();
|
|
1124
|
+
|
|
1125
|
+
// Schedule cleanup at exactly 30 seconds to clear countdown
|
|
1126
|
+
if (cooldownExpiryTimer) clearTimeout(cooldownExpiryTimer);
|
|
1127
|
+
cooldownExpiryTimer = setTimeout(() => {
|
|
1128
|
+
// Cooldown expired - publish null to clear countdown in HA
|
|
1129
|
+
publishRefreshCooldownState();
|
|
1130
|
+
cooldownExpiryTimer = null;
|
|
1131
|
+
}, MANUAL_REFRESH_COOLDOWN);
|
|
1132
|
+
|
|
1133
|
+
// Trigger the actual refresh
|
|
1134
|
+
node.status({ fill: "yellow", shape: "ring", text: "Manual refresh..." });
|
|
1135
|
+
fetchData();
|
|
1136
|
+
});
|
|
1137
|
+
|
|
895
1138
|
setTimeout(announceControls, 2000);
|
|
896
1139
|
}
|
|
897
1140
|
|
|
898
1141
|
// Init
|
|
899
|
-
|
|
1142
|
+
pollIntervalHandle = setInterval(fetchData, refreshRate);
|
|
1143
|
+
updateNextPollTime(); // Set initial next poll time
|
|
900
1144
|
setTimeout(fetchData, 1000);
|
|
901
1145
|
node.on('close', () => {
|
|
902
|
-
clearInterval(
|
|
1146
|
+
clearInterval(pollIntervalHandle);
|
|
903
1147
|
// Clear any pending retry timeouts
|
|
904
1148
|
retryTimeouts.forEach(timeout => clearTimeout(timeout));
|
|
905
1149
|
retryTimeouts = [];
|
|
906
1150
|
// Clear charging timers
|
|
907
1151
|
clearChargingTimers();
|
|
908
|
-
|
|
1152
|
+
// Clear cooldown expiry timer
|
|
1153
|
+
if (cooldownExpiryTimer) {
|
|
1154
|
+
clearTimeout(cooldownExpiryTimer);
|
|
1155
|
+
cooldownExpiryTimer = null;
|
|
1156
|
+
}
|
|
1157
|
+
if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh);
|
|
909
1158
|
});
|
|
910
1159
|
}
|
|
911
1160
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-red-contrib-octopus-intelligent",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "Node-RED integration for Octopus Energy Intelligent Octopus Go with Home Assistant MQTT discovery",
|
|
5
5
|
"main": "octopus-intelligent.js",
|
|
6
6
|
"scripts": {
|
|
@@ -19,6 +19,17 @@
|
|
|
19
19
|
],
|
|
20
20
|
"author": "Andrew Somerharju Neale",
|
|
21
21
|
"license": "MIT",
|
|
22
|
+
"files": [
|
|
23
|
+
"octopus-intelligent.js",
|
|
24
|
+
"octopus-intelligent.html",
|
|
25
|
+
"README.md",
|
|
26
|
+
"CHANGELOG.md",
|
|
27
|
+
"LICENSE",
|
|
28
|
+
"examples/",
|
|
29
|
+
"images/",
|
|
30
|
+
"__tests__/",
|
|
31
|
+
"test-mocks.js"
|
|
32
|
+
],
|
|
22
33
|
"node-red": {
|
|
23
34
|
"version": ">=2.0.0",
|
|
24
35
|
"nodes": {
|