node-red-contrib-octopus-intelligent 1.2.1 → 1.3.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.
- package/CHANGELOG.md +91 -0
- package/README.md +614 -227
- package/examples/ha-dashboard.yaml +470 -0
- package/lib/api-metrics.js +31 -0
- package/lib/auth.js +20 -0
- package/lib/categories/account.js +30 -0
- package/lib/categories/applicable-rates.js +91 -0
- package/lib/categories/completed-dispatches.js +35 -0
- package/lib/categories/electricity.js +132 -0
- package/lib/categories/flex-planned-dispatches.js +36 -0
- package/lib/categories/free-electricity.js +61 -0
- package/lib/categories/gas.js +94 -0
- package/lib/categories/home-mini.js +37 -0
- package/lib/categories/intelligent.js +124 -0
- package/lib/categories/octoplus.js +32 -0
- package/lib/categories/saving-sessions.js +50 -0
- package/lib/categories/wheel-of-fortune.js +49 -0
- package/lib/discovery.js +85 -0
- package/lib/graphql.js +44 -0
- package/lib/payload.js +76 -0
- package/lib/scheduler.js +33 -0
- package/lib/timezone.js +49 -0
- package/octopus-intelligent.html +71 -4
- package/octopus-intelligent.js +583 -369
- package/package.json +2 -1
package/octopus-intelligent.js
CHANGED
|
@@ -1,34 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
resolve({ data: JSON.parse(raw), status: res.statusCode, headers: res.headers });
|
|
22
|
-
} catch (e) {
|
|
23
|
-
reject(new Error("Failed to parse API response: " + e.message));
|
|
24
|
-
}
|
|
25
|
-
});
|
|
26
|
-
});
|
|
27
|
-
req.on("error", reject);
|
|
28
|
-
req.write(payload);
|
|
29
|
-
req.end();
|
|
30
|
-
});
|
|
31
|
-
}
|
|
1
|
+
'use strict';
|
|
2
|
+
const { graphqlPost } = require('./lib/graphql');
|
|
3
|
+
const { convertToTimezone, resolveTimezone } = require('./lib/timezone');
|
|
4
|
+
const { createApiMetrics } = require('./lib/api-metrics');
|
|
5
|
+
const intelligentCategory = require('./lib/categories/intelligent');
|
|
6
|
+
const { buildDefaultPayload } = require('./lib/payload');
|
|
7
|
+
const { createScheduler } = require('./lib/scheduler');
|
|
8
|
+
const { discoverProducts } = require('./lib/discovery');
|
|
9
|
+
const { mergePayload } = require('./lib/payload');
|
|
10
|
+
const electricityCategory = require('./lib/categories/electricity');
|
|
11
|
+
const gasCategory = require('./lib/categories/gas');
|
|
12
|
+
const wheelOfFortuneCategory = require('./lib/categories/wheel-of-fortune');
|
|
13
|
+
const homeMiniCategory = require('./lib/categories/home-mini');
|
|
14
|
+
const completedDispatchesCategory = require('./lib/categories/completed-dispatches');
|
|
15
|
+
const accountCategory = require('./lib/categories/account');
|
|
16
|
+
const octoplusCategory = require('./lib/categories/octoplus');
|
|
17
|
+
const flexPlannedDispatchesCategory = require('./lib/categories/flex-planned-dispatches');
|
|
18
|
+
const applicableRatesCategory = require('./lib/categories/applicable-rates');
|
|
19
|
+
const savingSessionsCategory = require('./lib/categories/saving-sessions');
|
|
20
|
+
const freeElectricityCategory = require('./lib/categories/free-electricity');
|
|
32
21
|
|
|
33
22
|
module.exports = function (RED) {
|
|
34
23
|
function OctopusIntelligentNode(config) {
|
|
@@ -65,118 +54,165 @@ module.exports = function (RED) {
|
|
|
65
54
|
];
|
|
66
55
|
|
|
67
56
|
// 3. Sensor Definitions (Read-Only)
|
|
57
|
+
// category: undefined = main, 'config' = Configuration, 'diagnostic' = Diagnostics
|
|
68
58
|
const sensors = [
|
|
69
|
-
//
|
|
70
|
-
{ id:
|
|
71
|
-
{ id:
|
|
72
|
-
{ id:
|
|
73
|
-
{ id:
|
|
74
|
-
|
|
75
|
-
{ id:
|
|
76
|
-
{ id:
|
|
77
|
-
{ id:
|
|
78
|
-
{ id:
|
|
79
|
-
{ id:
|
|
80
|
-
{ id:
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
{ id:
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
{ id:
|
|
93
|
-
{ id:
|
|
94
|
-
{ id:
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
{ id:
|
|
98
|
-
{ id:
|
|
99
|
-
{ id:
|
|
100
|
-
{ id:
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
{ id:
|
|
104
|
-
{ id:
|
|
105
|
-
{ id:
|
|
106
|
-
{ id:
|
|
107
|
-
|
|
108
|
-
{ id:
|
|
109
|
-
{ id:
|
|
110
|
-
{ id:
|
|
111
|
-
{ id:
|
|
112
|
-
{ id:
|
|
113
|
-
{ id:
|
|
114
|
-
|
|
115
|
-
{ id:
|
|
116
|
-
{ id:
|
|
117
|
-
//
|
|
118
|
-
{ id:
|
|
119
|
-
{ id:
|
|
59
|
+
// --- EV Charging (main) ---
|
|
60
|
+
{ id: 'next_charge', name: 'Next Charge Time', class: 'timestamp', icon: 'mdi:timer', val: 'next_start' },
|
|
61
|
+
{ id: 'total_energy', name: 'Total Planned Energy', unit: 'kWh', class: 'energy', val: 'total_energy' },
|
|
62
|
+
{ id: 'next_kwh', name: 'Next Slot Energy', unit: 'kWh', class: 'energy', val: 'next_kwh' },
|
|
63
|
+
{ id: 'source', name: 'Charge Source', icon: 'mdi:help-circle', val: 'next_source' },
|
|
64
|
+
{ id: 'slot1_start', name: 'Slot 1 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot1_start' },
|
|
65
|
+
{ id: 'slot1_end', name: 'Slot 1 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot1_end' },
|
|
66
|
+
{ id: 'slot2_start', name: 'Slot 2 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot2_start' },
|
|
67
|
+
{ id: 'slot2_end', name: 'Slot 2 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot2_end' },
|
|
68
|
+
{ id: 'slot3_start', name: 'Slot 3 Start', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot3_start' },
|
|
69
|
+
{ id: 'slot3_end', name: 'Slot 3 End', class: 'timestamp', icon: 'mdi:timer-outline', val: 'slot3_end' },
|
|
70
|
+
{ id: 'window_start', name: 'Overall Window Start', class: 'timestamp', icon: 'mdi:timer-play', val: 'window_start' },
|
|
71
|
+
{ id: 'window_end', name: 'Overall Window End', class: 'timestamp', icon: 'mdi:timer-stop', val: 'window_end' },
|
|
72
|
+
|
|
73
|
+
// --- EV Charging (diagnostic) ---
|
|
74
|
+
{ id: 'next_poll', name: 'Next Poll Time', class: 'timestamp', icon: 'mdi:clock-outline', val: 'next_poll', category: 'diagnostic' },
|
|
75
|
+
{ id: 'refresh_available_at', name: 'Refresh Available At', class: 'timestamp', icon: 'mdi:timer-sand', val: 'refresh_available_at', category: 'diagnostic' },
|
|
76
|
+
{ id: 'api_requests_hour', name: 'API Requests (Last Hour)', icon: 'mdi:api', val: 'api_requests_hour', category: 'diagnostic' },
|
|
77
|
+
{ id: 'api_complexity_hour', name: 'API Complexity (Last Hour)', icon: 'mdi:chart-line', val: 'api_complexity_hour', category: 'diagnostic' },
|
|
78
|
+
{ id: 'api_complexity_percent', name: 'API Complexity Usage', unit: '%', icon: 'mdi:percent', val: 'api_complexity_percent', category: 'diagnostic' },
|
|
79
|
+
|
|
80
|
+
// --- Raw timestamps (diagnostic) ---
|
|
81
|
+
{ id: 'next_charge_raw', name: 'Next Charge Time (Raw)', icon: 'mdi:timer', val: 'next_start_raw', category: 'diagnostic' },
|
|
82
|
+
{ id: 'next_poll_raw', name: 'Next Poll Time (Raw)', icon: 'mdi:clock-outline', val: 'next_poll_raw', category: 'diagnostic' },
|
|
83
|
+
{ id: 'slot1_start_raw', name: 'Slot 1 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot1_start_raw', category: 'diagnostic' },
|
|
84
|
+
{ id: 'slot1_end_raw', name: 'Slot 1 End (Raw)', icon: 'mdi:timer-outline', val: 'slot1_end_raw', category: 'diagnostic' },
|
|
85
|
+
{ id: 'slot2_start_raw', name: 'Slot 2 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot2_start_raw', category: 'diagnostic' },
|
|
86
|
+
{ id: 'slot2_end_raw', name: 'Slot 2 End (Raw)', icon: 'mdi:timer-outline', val: 'slot2_end_raw', category: 'diagnostic' },
|
|
87
|
+
{ id: 'slot3_start_raw', name: 'Slot 3 Start (Raw)', icon: 'mdi:timer-outline', val: 'slot3_start_raw', category: 'diagnostic' },
|
|
88
|
+
{ id: 'slot3_end_raw', name: 'Slot 3 End (Raw)', icon: 'mdi:timer-outline', val: 'slot3_end_raw', category: 'diagnostic' },
|
|
89
|
+
{ id: 'window_start_raw', name: 'Overall Window Start (Raw)', icon: 'mdi:timer-play', val: 'window_start_raw', category: 'diagnostic' },
|
|
90
|
+
{ id: 'window_end_raw', name: 'Overall Window End (Raw)', icon: 'mdi:timer-stop', val: 'window_end_raw', category: 'diagnostic' },
|
|
91
|
+
|
|
92
|
+
// --- Locale timestamps (diagnostic) ---
|
|
93
|
+
{ id: 'next_charge_locale', name: 'Next Charge Time (Locale)', icon: 'mdi:timer', val: 'next_start_locale', category: 'diagnostic' },
|
|
94
|
+
{ id: 'slot1_start_locale', name: 'Slot 1 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot1_start_locale', category: 'diagnostic' },
|
|
95
|
+
{ id: 'slot1_end_locale', name: 'Slot 1 End (Locale)', icon: 'mdi:timer-outline', val: 'slot1_end_locale', category: 'diagnostic' },
|
|
96
|
+
{ id: 'slot2_start_locale', name: 'Slot 2 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot2_start_locale', category: 'diagnostic' },
|
|
97
|
+
{ id: 'slot2_end_locale', name: 'Slot 2 End (Locale)', icon: 'mdi:timer-outline', val: 'slot2_end_locale', category: 'diagnostic' },
|
|
98
|
+
{ id: 'slot3_start_locale', name: 'Slot 3 Start (Locale)', icon: 'mdi:timer-outline', val: 'slot3_start_locale', category: 'diagnostic' },
|
|
99
|
+
{ id: 'slot3_end_locale', name: 'Slot 3 End (Locale)', icon: 'mdi:timer-outline', val: 'slot3_end_locale', category: 'diagnostic' },
|
|
100
|
+
{ id: 'window_start_locale', name: 'Overall Window Start (Locale)', icon: 'mdi:timer-play', val: 'window_start_locale', category: 'diagnostic' },
|
|
101
|
+
{ id: 'window_end_locale', name: 'Overall Window End (Locale)', icon: 'mdi:timer-stop', val: 'window_end_locale', category: 'diagnostic' },
|
|
102
|
+
{ id: 'timezone_detected', name: 'Timezone Detected', icon: 'mdi:earth', val: 'timezone_detected', category: 'diagnostic' },
|
|
103
|
+
{ id: 'timezone_applied', name: 'Timezone Applied', icon: 'mdi:earth-plus', val: 'timezone_applied', category: 'diagnostic' },
|
|
104
|
+
// --- Electricity (main) ---
|
|
105
|
+
{ id: 'electricity_standing_charge', name: 'Electricity Standing Charge', unit: 'p/day', icon: 'mdi:cash', val: 'electricity_standing_charge' },
|
|
106
|
+
{ id: 'electricity_consumption_kwh', name: 'Electricity Consumption', unit: 'kWh', class: 'energy', val: 'electricity_consumption_kwh' },
|
|
107
|
+
// --- Electricity (config) ---
|
|
108
|
+
{ id: 'electricity_unit_rate', name: 'Electricity Unit Rate', unit: 'p/kWh', icon: 'mdi:flash', val: 'electricity_unit_rate' },
|
|
109
|
+
{ id: 'electricity_tariff_code', name: 'Electricity Tariff Code', icon: 'mdi:tag', val: 'electricity_tariff_code' },
|
|
110
|
+
{ id: 'electricity_valid_from', name: 'Electricity Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'electricity_valid_from' },
|
|
111
|
+
{ id: 'electricity_valid_to', name: 'Electricity Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'electricity_valid_to' },
|
|
112
|
+
// --- Electricity (diagnostic) ---
|
|
113
|
+
{ id: 'electricity_consumption_from', name: 'Electricity Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_consumption_from', category: 'diagnostic' },
|
|
114
|
+
{ id: 'electricity_consumption_to', name: 'Electricity Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_consumption_to', category: 'diagnostic' },
|
|
115
|
+
{ id: 'electricity_rates_error', name: 'Electricity Rates Error', icon: 'mdi:alert-circle', val: 'electricity_rates_error', category: 'diagnostic' },
|
|
116
|
+
{ id: 'electricity_consumption_error', name: 'Electricity Consumption Error', icon: 'mdi:alert-circle', val: 'electricity_consumption_error', category: 'diagnostic' },
|
|
117
|
+
|
|
118
|
+
// --- Electricity Export (main) ---
|
|
119
|
+
{ id: 'electricity_export_consumption_kwh', name: 'Electricity Export Consumption', unit: 'kWh', class: 'energy', val: 'electricity_export_consumption_kwh' },
|
|
120
|
+
{ id: 'electricity_export_rate_current_pence', name: 'Current Electricity Export Rate', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_current_pence' },
|
|
121
|
+
{ id: 'electricity_export_rate_current_gbp', name: 'Electricity Export Rate', unit: 'GBP/kWh', icon: 'mdi:cash-clock', stateClass: 'measurement', val: 'electricity_export_rate_current_gbp' },
|
|
122
|
+
// --- Electricity Export (config) ---
|
|
123
|
+
// Solar/export users have a second agreement with productCode containing "OUTGOING".
|
|
124
|
+
// unit_rate is null for half-hourly export tariffs (e.g. Agile Outgoing) — current
|
|
125
|
+
// half-hourly export rate comes from electricity_export_rate_current_pence.
|
|
126
|
+
{ id: 'electricity_export_unit_rate', name: 'Electricity Export Unit Rate', unit: 'p/kWh', icon: 'mdi:transmission-tower-export', val: 'electricity_export_unit_rate' },
|
|
127
|
+
{ id: 'electricity_export_standing_charge',name: 'Electricity Export Standing Charge',unit: 'p/day', icon: 'mdi:cash', val: 'electricity_export_standing_charge' },
|
|
128
|
+
{ id: 'electricity_export_tariff_code', name: 'Electricity Export Tariff Code', icon: 'mdi:tag', val: 'electricity_export_tariff_code' },
|
|
129
|
+
{ id: 'electricity_export_valid_from', name: 'Electricity Export Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'electricity_export_valid_from' },
|
|
130
|
+
{ id: 'electricity_export_valid_to', name: 'Electricity Export Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'electricity_export_valid_to' },
|
|
131
|
+
// --- Electricity Export (diagnostic) ---
|
|
132
|
+
{ id: 'electricity_export_consumption_from', name: 'Electricity Export Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_consumption_from', category: 'diagnostic' },
|
|
133
|
+
{ id: 'electricity_export_consumption_to', name: 'Electricity Export Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_consumption_to', category: 'diagnostic' },
|
|
134
|
+
{ id: 'electricity_export_rate_count', name: 'Electricity Export Rate Slots', icon: 'mdi:format-list-numbered', val: 'electricity_export_rate_count', category: 'diagnostic' },
|
|
135
|
+
{ id: 'electricity_export_rate_prev_pence', name: 'Electricity Export Rate Prev', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_prev_pence', category: 'diagnostic' },
|
|
136
|
+
{ id: 'electricity_export_rate_prev_to', name: 'Electricity Export Rate Prev Ends', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_rate_prev_to', category: 'diagnostic' },
|
|
137
|
+
{ id: 'electricity_export_rate_next_pence', name: 'Electricity Export Rate Next', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'electricity_export_rate_next_pence', category: 'diagnostic' },
|
|
138
|
+
{ id: 'electricity_export_rate_next_from', name: 'Electricity Export Rate Next From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'electricity_export_rate_next_from', category: 'diagnostic' },
|
|
139
|
+
{ id: 'electricity_export_rate_error', name: 'Electricity Export Rate Error', icon: 'mdi:alert-circle', val: 'electricity_export_rate_error', category: 'diagnostic' },
|
|
140
|
+
|
|
141
|
+
// --- Gas (main) ---
|
|
142
|
+
{ id: 'gas_standing_charge', name: 'Gas Standing Charge', unit: 'p/day', icon: 'mdi:cash', val: 'gas_standing_charge' },
|
|
143
|
+
{ id: 'gas_consumption_kwh', name: 'Gas Consumption', unit: 'kWh', class: 'energy', val: 'gas_consumption_kwh' },
|
|
144
|
+
// --- Gas (config) ---
|
|
145
|
+
{ id: 'gas_unit_rate', name: 'Gas Unit Rate', unit: 'p/kWh', icon: 'mdi:fire', val: 'gas_unit_rate' },
|
|
146
|
+
{ id: 'gas_tariff_code', name: 'Gas Tariff Code', icon: 'mdi:tag', val: 'gas_tariff_code' },
|
|
147
|
+
{ id: 'gas_valid_from', name: 'Gas Tariff Valid From', class: 'timestamp', icon: 'mdi:calendar-start', val: 'gas_valid_from' },
|
|
148
|
+
{ id: 'gas_valid_to', name: 'Gas Tariff Valid To', class: 'timestamp', icon: 'mdi:calendar-end', val: 'gas_valid_to' },
|
|
149
|
+
// --- Gas (diagnostic) ---
|
|
150
|
+
{ id: 'gas_consumption_from', name: 'Gas Consumption From', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'gas_consumption_from', category: 'diagnostic' },
|
|
151
|
+
{ id: 'gas_consumption_to', name: 'Gas Consumption To', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'gas_consumption_to', category: 'diagnostic' },
|
|
152
|
+
{ id: 'gas_rates_error', name: 'Gas Rates Error', icon: 'mdi:alert-circle', val: 'gas_rates_error', category: 'diagnostic' },
|
|
153
|
+
{ id: 'gas_consumption_error', name: 'Gas Consumption Error', icon: 'mdi:alert-circle', val: 'gas_consumption_error', category: 'diagnostic' },
|
|
154
|
+
|
|
155
|
+
// --- Applicable Rates (main) ---
|
|
156
|
+
{ id: 'applicable_rates_current_pence', name: 'Current Electricity Rate', unit: 'p/kWh', icon: 'mdi:cash-clock', val: 'applicable_rates_current_pence' },
|
|
157
|
+
{ id: 'applicable_rates_current_gbp', name: 'Electricity Rate', unit: 'GBP/kWh', icon: 'mdi:cash-clock', stateClass: 'measurement', val: 'applicable_rates_current_gbp' },
|
|
158
|
+
// --- Applicable Rates (diagnostic) ---
|
|
159
|
+
{ id: 'applicable_rates_count', name: 'Applicable Rates Slots', icon: 'mdi:format-list-numbered', val: 'applicable_rates_count', category: 'diagnostic' },
|
|
160
|
+
{ id: 'applicable_rates_error', name: 'Applicable Rates Error', icon: 'mdi:alert-circle', val: 'applicable_rates_error', category: 'diagnostic' },
|
|
161
|
+
|
|
162
|
+
// --- Account (main) ---
|
|
163
|
+
{ id: 'account_balance_pounds', name: 'Account Balance', unit: '£', icon: 'mdi:cash-multiple', val: 'account_balance_pounds' },
|
|
164
|
+
// --- Account (diagnostic) ---
|
|
165
|
+
{ id: 'account_balance_pence', name: 'Account Balance (Pence)', unit: 'p', icon: 'mdi:cash', val: 'account_balance_pence', category: 'diagnostic' },
|
|
166
|
+
{ id: 'account_error', name: 'Account Error', icon: 'mdi:alert-circle', val: 'account_error', category: 'diagnostic' },
|
|
167
|
+
|
|
168
|
+
// --- Octoplus (config) ---
|
|
169
|
+
// octoplus_enrolled and octoplus_loyalty_points_user are booleans — published as
|
|
170
|
+
// binary_sensor entities further down. Leaving them out of this array.
|
|
171
|
+
{ id: 'octoplus_enrollment_status', name: 'Octoplus Status', icon: 'mdi:star-circle-outline', val: 'octoplus_enrollment_status' },
|
|
172
|
+
// --- Octoplus (diagnostic) ---
|
|
173
|
+
{ id: 'octoplus_error', name: 'Octoplus Error', icon: 'mdi:alert-circle', val: 'octoplus_error', category: 'diagnostic' },
|
|
174
|
+
|
|
175
|
+
// --- Wheel of Fortune (main) ---
|
|
176
|
+
{ id: 'wheel_of_fortune_electricity_spins', name: 'WoF Electricity Spins', icon: 'mdi:star-circle', val: 'wheel_of_fortune_electricity_spins' },
|
|
177
|
+
{ id: 'wheel_of_fortune_gas_spins', name: 'WoF Gas Spins', icon: 'mdi:star-circle', val: 'wheel_of_fortune_gas_spins' },
|
|
178
|
+
// --- Wheel of Fortune (diagnostic) ---
|
|
179
|
+
{ id: 'wheel_of_fortune_electricity_max', name: 'WoF Electricity Max', icon: 'mdi:star-outline', val: 'wheel_of_fortune_electricity_max', category: 'diagnostic' },
|
|
180
|
+
{ id: 'wheel_of_fortune_electricity_used', name: 'WoF Electricity Used', icon: 'mdi:star-outline', val: 'wheel_of_fortune_electricity_used', category: 'diagnostic' },
|
|
181
|
+
{ id: 'wheel_of_fortune_gas_max', name: 'WoF Gas Max', icon: 'mdi:star-outline', val: 'wheel_of_fortune_gas_max', category: 'diagnostic' },
|
|
182
|
+
{ id: 'wheel_of_fortune_gas_used', name: 'WoF Gas Used', icon: 'mdi:star-outline', val: 'wheel_of_fortune_gas_used', category: 'diagnostic' },
|
|
183
|
+
{ id: 'wheel_of_fortune_error', name: 'WoF Error', icon: 'mdi:alert-circle', val: 'wheel_of_fortune_error', category: 'diagnostic' },
|
|
184
|
+
|
|
185
|
+
// --- Home Mini (main) ---
|
|
186
|
+
{ id: 'mini_demand_kw', name: 'Home Mini Demand', unit: 'kW', class: 'power', icon: 'mdi:home-lightning-bolt', val: 'mini_demand_kw' },
|
|
187
|
+
{ id: 'mini_consumption_delta_kwh', name: 'Home Mini Period Consumption', unit: 'kWh', class: 'energy', icon: 'mdi:home-lightning-bolt', val: 'mini_consumption_delta_kwh' },
|
|
188
|
+
// --- Home Mini (diagnostic) ---
|
|
189
|
+
{ id: 'mini_read_at', name: 'Home Mini Reading Time', class: 'timestamp', icon: 'mdi:clock-outline', val: 'mini_read_at', category: 'diagnostic' },
|
|
190
|
+
{ id: 'home_mini_error', name: 'Home Mini Error', icon: 'mdi:alert-circle', val: 'home_mini_error', category: 'diagnostic' },
|
|
191
|
+
|
|
192
|
+
// --- Saving Sessions (main) ---
|
|
193
|
+
{ id: 'saving_session_joined', name: 'Saving Session Joined', icon: 'mdi:lightning-bolt-circle', val: 'saving_session_joined' },
|
|
194
|
+
{ id: 'saving_session_points', name: 'Octopus Points', icon: 'mdi:star', val: 'saving_session_points' },
|
|
195
|
+
// --- Saving Sessions (config) ---
|
|
196
|
+
{ id: 'saving_session_start', name: 'Saving Session Start', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'saving_session_start' },
|
|
197
|
+
{ id: 'saving_session_end', name: 'Saving Session End', class: 'timestamp', icon: 'mdi:calendar-clock', val: 'saving_session_end' },
|
|
198
|
+
// --- Saving Sessions (diagnostic) ---
|
|
199
|
+
{ id: 'saving_sessions_error', name: 'Saving Sessions Error', icon: 'mdi:alert-circle', val: 'saving_sessions_error', category: 'diagnostic' },
|
|
200
|
+
|
|
201
|
+
// --- Free Electricity (config) ---
|
|
202
|
+
{ id: 'free_electricity_start', name: 'Free Electricity Start', class: 'timestamp', icon: 'mdi:flash-circle', val: 'free_electricity_start' },
|
|
203
|
+
{ id: 'free_electricity_end', name: 'Free Electricity End', class: 'timestamp', icon: 'mdi:flash-circle', val: 'free_electricity_end' },
|
|
204
|
+
// --- Free Electricity (diagnostic) ---
|
|
205
|
+
{ id: 'free_electricity_error', name: 'Free Electricity Error', icon: 'mdi:alert-circle', val: 'free_electricity_error', category: 'diagnostic' },
|
|
206
|
+
|
|
207
|
+
// --- Dispatches (main) ---
|
|
208
|
+
{ id: 'completed_dispatches_count', name: 'Completed Dispatches', icon: 'mdi:history', val: 'completed_dispatches_count' },
|
|
209
|
+
{ id: 'flex_planned_dispatches_count', name: 'Flex Planned Dispatches', icon: 'mdi:lightning-bolt-circle', val: 'flex_planned_dispatches_count' },
|
|
210
|
+
// --- Dispatches (diagnostic) ---
|
|
211
|
+
{ id: 'completed_dispatches_error', name: 'Completed Dispatches Error', icon: 'mdi:alert-circle', val: 'completed_dispatches_error', category: 'diagnostic' },
|
|
212
|
+
{ id: 'flex_planned_dispatches_error', name: 'Flex Planned Dispatches Error', icon: 'mdi:alert-circle', val: 'flex_planned_dispatches_error', category: 'diagnostic' },
|
|
213
|
+
{ id: 'intelligent_error', name: 'Intelligent Error', icon: 'mdi:alert-circle', val: 'intelligent_error', category: 'diagnostic' },
|
|
120
214
|
];
|
|
121
215
|
|
|
122
|
-
// 3. Timezone Helpers
|
|
123
|
-
function convertToTimezone(dateStr, tz) {
|
|
124
|
-
if (!dateStr || typeof dateStr !== 'string') return dateStr;
|
|
125
|
-
try {
|
|
126
|
-
const date = new Date(dateStr.replace(' ', 'T'));
|
|
127
|
-
if (isNaN(date.getTime())) return dateStr;
|
|
128
|
-
|
|
129
|
-
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
130
|
-
timeZone: tz,
|
|
131
|
-
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
132
|
-
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
|
133
|
-
hour12: false, hourCycle: 'h23'
|
|
134
|
-
}).formatToParts(date);
|
|
135
|
-
|
|
136
|
-
const get = (type) => (parts.find(p => p.type === type) || {}).value || '00';
|
|
137
|
-
const y = get('year');
|
|
138
|
-
const mo = get('month');
|
|
139
|
-
const d = get('day');
|
|
140
|
-
const h = get('hour');
|
|
141
|
-
const mi = get('minute');
|
|
142
|
-
const s = get('second');
|
|
143
|
-
|
|
144
|
-
const localAsUtc = Date.UTC(
|
|
145
|
-
parseInt(y, 10), parseInt(mo, 10) - 1, parseInt(d, 10),
|
|
146
|
-
parseInt(h, 10), parseInt(mi, 10), parseInt(s, 10)
|
|
147
|
-
);
|
|
148
|
-
const offsetMins = Math.round((localAsUtc - date.getTime()) / 60000);
|
|
149
|
-
const sign = offsetMins >= 0 ? '+' : '-';
|
|
150
|
-
const absMin = Math.abs(offsetMins);
|
|
151
|
-
const offsetStr = `${sign}${String(Math.floor(absMin / 60)).padStart(2, '0')}:${String(absMin % 60).padStart(2, '0')}`;
|
|
152
|
-
|
|
153
|
-
return `${y}-${mo}-${d} ${h}:${mi}:${s}${offsetStr}`;
|
|
154
|
-
} catch (e) {
|
|
155
|
-
node.warn(`Invalid timezone: ${tz}, falling back to auto-detected`);
|
|
156
|
-
return dateStr;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function resolveTimezone(nd) {
|
|
161
|
-
try {
|
|
162
|
-
const persisted = nd.context().get('timezone');
|
|
163
|
-
if (persisted && typeof persisted === 'string' && persisted.trim().length > 0) {
|
|
164
|
-
return persisted.trim();
|
|
165
|
-
}
|
|
166
|
-
} catch (e) {}
|
|
167
|
-
|
|
168
|
-
const override = nd.timezoneOverride;
|
|
169
|
-
if (override && typeof override === 'string' && override.trim().length > 0) {
|
|
170
|
-
return override.trim();
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
try {
|
|
174
|
-
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
175
|
-
} catch (e) {
|
|
176
|
-
return 'UTC';
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
216
|
// 4. Helper: Announce Controls (Write-Enabled)
|
|
181
217
|
function announceControls() {
|
|
182
218
|
if (!enableMqtt || !node.broker) return;
|
|
@@ -187,7 +223,7 @@ module.exports = function (RED) {
|
|
|
187
223
|
name: "Octopus Intelligent",
|
|
188
224
|
manufacturer: "Octopus Energy",
|
|
189
225
|
model: "Intelligent Octopus Go",
|
|
190
|
-
sw_version: "
|
|
226
|
+
sw_version: "2.0.0",
|
|
191
227
|
suggested_area: "Energy",
|
|
192
228
|
configuration_url: "https://octopus.energy/intelligent/"
|
|
193
229
|
};
|
|
@@ -278,6 +314,76 @@ module.exports = function (RED) {
|
|
|
278
314
|
};
|
|
279
315
|
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_charging_now/config`, JSON.stringify(chargingNowBinarySensor), { retain: true });
|
|
280
316
|
|
|
317
|
+
// G2. Saving Session Available Binary Sensor
|
|
318
|
+
const savingSessionBinarySensor = {
|
|
319
|
+
name: "Octopus Saving Session Available",
|
|
320
|
+
unique_id: `${uniqueIdPrefix}_saving_session_available`,
|
|
321
|
+
state_topic: stateTopic,
|
|
322
|
+
value_template: "{{ value_json.saving_session_available }}",
|
|
323
|
+
payload_on: "True",
|
|
324
|
+
payload_off: "False",
|
|
325
|
+
icon: "mdi:lightning-bolt-circle",
|
|
326
|
+
device: device
|
|
327
|
+
};
|
|
328
|
+
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_saving_session_available/config`, JSON.stringify(savingSessionBinarySensor), { retain: true });
|
|
329
|
+
|
|
330
|
+
// G3. Free Electricity Active Binary Sensor
|
|
331
|
+
const freeElectricityActiveSensor = {
|
|
332
|
+
name: "Octopus Free Electricity Active",
|
|
333
|
+
unique_id: `${uniqueIdPrefix}_free_electricity_active`,
|
|
334
|
+
state_topic: stateTopic,
|
|
335
|
+
value_template: "{{ value_json.free_electricity_active }}",
|
|
336
|
+
payload_on: "True",
|
|
337
|
+
payload_off: "False",
|
|
338
|
+
icon: "mdi:flash-circle",
|
|
339
|
+
device: device
|
|
340
|
+
};
|
|
341
|
+
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_active/config`, JSON.stringify(freeElectricityActiveSensor), { retain: true });
|
|
342
|
+
|
|
343
|
+
// G4. Free Electricity Available Binary Sensor
|
|
344
|
+
const freeElectricityAvailableSensor = {
|
|
345
|
+
name: "Octopus Free Electricity Available",
|
|
346
|
+
unique_id: `${uniqueIdPrefix}_free_electricity_available`,
|
|
347
|
+
state_topic: stateTopic,
|
|
348
|
+
value_template: "{{ value_json.free_electricity_available }}",
|
|
349
|
+
payload_on: "True",
|
|
350
|
+
payload_off: "False",
|
|
351
|
+
icon: "mdi:flash-circle-outline",
|
|
352
|
+
device: device
|
|
353
|
+
};
|
|
354
|
+
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_free_electricity_available/config`, JSON.stringify(freeElectricityAvailableSensor), { retain: true });
|
|
355
|
+
|
|
356
|
+
// G5. Octoplus Enrolled Binary Sensor
|
|
357
|
+
// Published as binary_sensor (not sensor) because the value is a boolean —
|
|
358
|
+
// HA's sensor domain rejects booleans without a device_class, leaving the
|
|
359
|
+
// entity unregistered.
|
|
360
|
+
const octoplusEnrolledBinarySensor = {
|
|
361
|
+
name: "Octopus Octoplus Enrolled",
|
|
362
|
+
unique_id: `${uniqueIdPrefix}_octoplus_enrolled`,
|
|
363
|
+
state_topic: stateTopic,
|
|
364
|
+
value_template: "{{ value_json.octoplus_enrolled }}",
|
|
365
|
+
payload_on: "True",
|
|
366
|
+
payload_off: "False",
|
|
367
|
+
icon: "mdi:star-circle",
|
|
368
|
+
entity_category: "config",
|
|
369
|
+
device: device
|
|
370
|
+
};
|
|
371
|
+
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_enrolled/config`, JSON.stringify(octoplusEnrolledBinarySensor), { retain: true });
|
|
372
|
+
|
|
373
|
+
// G6. Octoplus Loyalty Points (boolean) Binary Sensor
|
|
374
|
+
const octoplusLoyaltyBinarySensor = {
|
|
375
|
+
name: "Octopus Octoplus Loyalty Points",
|
|
376
|
+
unique_id: `${uniqueIdPrefix}_octoplus_loyalty_points_user`,
|
|
377
|
+
state_topic: stateTopic,
|
|
378
|
+
value_template: "{{ value_json.octoplus_loyalty_points_user }}",
|
|
379
|
+
payload_on: "True",
|
|
380
|
+
payload_off: "False",
|
|
381
|
+
icon: "mdi:star",
|
|
382
|
+
entity_category: "config",
|
|
383
|
+
device: device
|
|
384
|
+
};
|
|
385
|
+
node.broker.client.publish(`${mqttPrefix}/binary_sensor/${uniqueIdPrefix}_octoplus_loyalty_points_user/config`, JSON.stringify(octoplusLoyaltyBinarySensor), { retain: true });
|
|
386
|
+
|
|
281
387
|
// H. Announce Read-Only Sensors
|
|
282
388
|
sensors.forEach(sensor => {
|
|
283
389
|
const payload = {
|
|
@@ -289,14 +395,11 @@ module.exports = function (RED) {
|
|
|
289
395
|
};
|
|
290
396
|
if (sensor.class) payload.device_class = sensor.class;
|
|
291
397
|
if (sensor.unit) payload.unit_of_measurement = sensor.unit;
|
|
398
|
+
if (sensor.stateClass) payload.state_class = sensor.stateClass;
|
|
292
399
|
if (sensor.icon) payload.icon = sensor.icon;
|
|
293
400
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
sensor.id === 'refresh_available_at' ||
|
|
297
|
-
sensor.id.startsWith('api_') ||
|
|
298
|
-
sensor.id.startsWith('timezone_')) {
|
|
299
|
-
payload.entity_category = "diagnostic";
|
|
401
|
+
if (sensor.category) {
|
|
402
|
+
payload.entity_category = sensor.category;
|
|
300
403
|
}
|
|
301
404
|
|
|
302
405
|
node.broker.client.publish(`${mqttPrefix}/sensor/${uniqueIdPrefix}_${sensor.id}/config`, JSON.stringify(payload), { retain: true });
|
|
@@ -379,14 +482,14 @@ module.exports = function (RED) {
|
|
|
379
482
|
// Polling metrics
|
|
380
483
|
let nextPollTime = null; // ISO timestamp of next scheduled poll
|
|
381
484
|
let pollIntervalHandle = null; // Reference to setInterval handle
|
|
382
|
-
|
|
485
|
+
const metrics = createApiMetrics();
|
|
383
486
|
|
|
384
487
|
// API Complexity Tracking
|
|
385
488
|
// Octopus Energy API does not return actual complexity values in headers or extensions,
|
|
386
489
|
// so we use estimated complexity based on query types:
|
|
387
490
|
// - Regular poll (auth + data query): ~300
|
|
388
491
|
// - Mutation (auth + setPreferences): ~250
|
|
389
|
-
// - Pre-validation (auth +
|
|
492
|
+
// - Pre-validation (auth + flexPlannedDispatches only): ~200
|
|
390
493
|
|
|
391
494
|
// Smart charging state (fetched once at startup)
|
|
392
495
|
let krakenflexDeviceId = null;
|
|
@@ -394,7 +497,201 @@ module.exports = function (RED) {
|
|
|
394
497
|
let smartChargingRetryTimeouts = [];
|
|
395
498
|
|
|
396
499
|
// Last known full state - prevents sensors going unknown when controls change
|
|
397
|
-
let lastKnownState = buildDefaultPayload();
|
|
500
|
+
let lastKnownState = buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
|
|
501
|
+
|
|
502
|
+
// V2 category registry — populated after discovery
|
|
503
|
+
let categories = [];
|
|
504
|
+
|
|
505
|
+
async function initCategories(discovered) {
|
|
506
|
+
categories = [];
|
|
507
|
+
|
|
508
|
+
const electricityEnabled = config.electricityEnabled !== false;
|
|
509
|
+
const gasEnabled = config.gasEnabled !== false;
|
|
510
|
+
|
|
511
|
+
if (discovered.hasElectricity && electricityEnabled) {
|
|
512
|
+
const ratesMs = (config.electricityRatesInterval || 60) * 60 * 1000;
|
|
513
|
+
const consumptionMs = (config.electricityConsumptionInterval || 60) * 60 * 1000;
|
|
514
|
+
categories.push({
|
|
515
|
+
id: 'electricity_rates',
|
|
516
|
+
enabled: true,
|
|
517
|
+
intervalMs: ratesMs,
|
|
518
|
+
lastPolled: 0,
|
|
519
|
+
queryFn: () => electricityCategory.buildRatesQuery(account),
|
|
520
|
+
parseFn: d => electricityCategory.parseRatesResponse(d)
|
|
521
|
+
});
|
|
522
|
+
categories.push({
|
|
523
|
+
id: 'electricity_consumption',
|
|
524
|
+
enabled: true,
|
|
525
|
+
intervalMs: consumptionMs,
|
|
526
|
+
lastPolled: 0,
|
|
527
|
+
queryFn: () => electricityCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
528
|
+
parseFn: d => electricityCategory.parseConsumptionResponse(d, discovered.electricityMpan, discovered.electricityExportMpan)
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (discovered.hasGas && gasEnabled) {
|
|
533
|
+
const ratesMs = (config.gasRatesInterval || 60) * 60 * 1000;
|
|
534
|
+
const consumptionMs = (config.gasConsumptionInterval || 60) * 60 * 1000;
|
|
535
|
+
categories.push({
|
|
536
|
+
id: 'gas_rates',
|
|
537
|
+
enabled: true,
|
|
538
|
+
intervalMs: ratesMs,
|
|
539
|
+
lastPolled: 0,
|
|
540
|
+
queryFn: () => gasCategory.buildRatesQuery(account),
|
|
541
|
+
parseFn: d => gasCategory.parseRatesResponse(d)
|
|
542
|
+
});
|
|
543
|
+
categories.push({
|
|
544
|
+
id: 'gas_consumption',
|
|
545
|
+
enabled: true,
|
|
546
|
+
intervalMs: consumptionMs,
|
|
547
|
+
lastPolled: 0,
|
|
548
|
+
queryFn: () => gasCategory.buildConsumptionQuery(account, config.timezoneOverride || 'UTC'),
|
|
549
|
+
parseFn: d => gasCategory.parseConsumptionResponse(d)
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
categories.push({
|
|
554
|
+
id: 'wheel_of_fortune',
|
|
555
|
+
enabled: config.enableWheelOfFortune || false,
|
|
556
|
+
intervalMs: (config.wheelOfFortuneInterval || 60) * 60 * 1000,
|
|
557
|
+
lastPolled: 0,
|
|
558
|
+
queryFn: () => wheelOfFortuneCategory.buildQuery(account),
|
|
559
|
+
parseFn: d => wheelOfFortuneCategory.parseResponse(d)
|
|
560
|
+
});
|
|
561
|
+
if (discovered.smartMeterDeviceId) {
|
|
562
|
+
categories.push({
|
|
563
|
+
id: 'home_mini',
|
|
564
|
+
enabled: config.enableHomeMini || false,
|
|
565
|
+
intervalMs: (config.homeMiniInterval || 1) * 60 * 1000,
|
|
566
|
+
lastPolled: 0,
|
|
567
|
+
queryFn: () => homeMiniCategory.buildQuery(discovered.smartMeterDeviceId),
|
|
568
|
+
parseFn: d => homeMiniCategory.parseResponse(d)
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
categories.push({
|
|
572
|
+
id: 'saving_sessions',
|
|
573
|
+
enabled: true,
|
|
574
|
+
intervalMs: (config.savingSessionsInterval || 60) * 60 * 1000,
|
|
575
|
+
lastPolled: 0,
|
|
576
|
+
queryFn: () => savingSessionsCategory.buildQuery(account),
|
|
577
|
+
parseFn: d => savingSessionsCategory.parseResponse(d)
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
if (discovered.hasIntelligent) {
|
|
581
|
+
categories.push({
|
|
582
|
+
id: 'completed_dispatches',
|
|
583
|
+
enabled: true,
|
|
584
|
+
intervalMs: 60 * 60 * 1000,
|
|
585
|
+
lastPolled: 0,
|
|
586
|
+
queryFn: () => completedDispatchesCategory.buildQuery(account),
|
|
587
|
+
parseFn: d => completedDispatchesCategory.parseResponse(d)
|
|
588
|
+
});
|
|
589
|
+
if (discovered.deviceId) {
|
|
590
|
+
categories.push({
|
|
591
|
+
id: 'flex_planned_dispatches',
|
|
592
|
+
enabled: true,
|
|
593
|
+
intervalMs: (config.refreshInterval || 5) * 60 * 1000,
|
|
594
|
+
lastPolled: 0,
|
|
595
|
+
queryFn: () => flexPlannedDispatchesCategory.buildQuery(discovered.deviceId),
|
|
596
|
+
parseFn: d => flexPlannedDispatchesCategory.parseResponse(d)
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
if (discovered.hasElectricity && discovered.electricityMpan) {
|
|
602
|
+
categories.push({
|
|
603
|
+
id: 'applicable_rates',
|
|
604
|
+
enabled: true,
|
|
605
|
+
intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
|
|
606
|
+
lastPolled: 0,
|
|
607
|
+
queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityMpan),
|
|
608
|
+
parseFn: d => applicableRatesCategory.parseResponse(d)
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// Export applicable rates — second query with the export MPAN. Same parser,
|
|
613
|
+
// different field prefix so the output keys don't collide with import.
|
|
614
|
+
if (discovered.hasElectricity && discovered.electricityExportMpan) {
|
|
615
|
+
categories.push({
|
|
616
|
+
id: 'applicable_rates_export',
|
|
617
|
+
enabled: true,
|
|
618
|
+
intervalMs: (config.electricityRatesInterval || 60) * 60 * 1000,
|
|
619
|
+
lastPolled: 0,
|
|
620
|
+
queryFn: () => applicableRatesCategory.buildQuery(account, discovered.electricityExportMpan),
|
|
621
|
+
parseFn: d => applicableRatesCategory.parseResponse(d, { fieldPrefix: 'electricity_export_rate' })
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
if (discovered.hasElectricity && discovered.electricityMpan) {
|
|
626
|
+
categories.push({
|
|
627
|
+
id: 'free_electricity',
|
|
628
|
+
enabled: true,
|
|
629
|
+
intervalMs: 30 * 60 * 1000, // 30 minutes
|
|
630
|
+
lastPolled: 0,
|
|
631
|
+
queryFn: () => freeElectricityCategory.buildQuery(account, discovered.electricityMpan),
|
|
632
|
+
parseFn: d => freeElectricityCategory.parseResponse(d)
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
categories.push({
|
|
637
|
+
id: 'account',
|
|
638
|
+
enabled: true,
|
|
639
|
+
intervalMs: 60 * 60 * 1000,
|
|
640
|
+
lastPolled: 0,
|
|
641
|
+
queryFn: () => accountCategory.buildQuery(account),
|
|
642
|
+
parseFn: d => accountCategory.parseResponse(d)
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
categories.push({
|
|
646
|
+
id: 'octoplus',
|
|
647
|
+
enabled: true,
|
|
648
|
+
intervalMs: 60 * 60 * 1000,
|
|
649
|
+
lastPolled: 0,
|
|
650
|
+
queryFn: () => octoplusCategory.buildQuery(account),
|
|
651
|
+
parseFn: d => octoplusCategory.parseResponse(d)
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async function pollDueCategories() {
|
|
656
|
+
const { isDue } = require('./lib/scheduler');
|
|
657
|
+
const due = categories.filter(c => c.enabled && isDue(c));
|
|
658
|
+
if (due.length === 0) return;
|
|
659
|
+
|
|
660
|
+
let token;
|
|
661
|
+
try {
|
|
662
|
+
const response = await graphqlPost({
|
|
663
|
+
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
664
|
+
variables: { input: { APIKey: apiKey } }
|
|
665
|
+
});
|
|
666
|
+
if (!response.data.data || !response.data.data.obtainKrakenToken) {
|
|
667
|
+
throw new Error('Auth response missing token');
|
|
668
|
+
}
|
|
669
|
+
token = response.data.data.obtainKrakenToken.token;
|
|
670
|
+
} catch (e) {
|
|
671
|
+
node.warn(`V2 category poll: auth failed: ${e.message}`);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
for (const cat of due) {
|
|
676
|
+
try {
|
|
677
|
+
const { query, variables, hostname } = cat.queryFn();
|
|
678
|
+
const response = await graphqlPost({ query, variables }, token, hostname);
|
|
679
|
+
if (response.data.errors) throw new Error(JSON.stringify(response.data.errors));
|
|
680
|
+
if (!response.data.data) throw new Error('Response missing data');
|
|
681
|
+
const parsed = cat.parseFn(response.data.data);
|
|
682
|
+
lastKnownState = mergePayload(lastKnownState, parsed);
|
|
683
|
+
cat.lastPolled = Date.now();
|
|
684
|
+
} catch (e) {
|
|
685
|
+
cat.enabled = false;
|
|
686
|
+
node.warn(`V2 category ${cat.id} failed (disabled until redeploy): ${e.message}`);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
if (enableMqtt && node.broker && node.broker.client) {
|
|
691
|
+
node.broker.client.publish(stateTopic, JSON.stringify(lastKnownState), { retain: true });
|
|
692
|
+
}
|
|
693
|
+
node.send({ payload: lastKnownState });
|
|
694
|
+
}
|
|
398
695
|
|
|
399
696
|
async function setPreferences(newLimit, newTime) {
|
|
400
697
|
// Validation
|
|
@@ -475,7 +772,7 @@ module.exports = function (RED) {
|
|
|
475
772
|
|
|
476
773
|
// Record mutation API usage (auth + mutation = ~250 complexity)
|
|
477
774
|
const ESTIMATED_MUTATION_COMPLEXITY = 250;
|
|
478
|
-
recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
775
|
+
metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
479
776
|
|
|
480
777
|
// C. Start exponential backoff validation
|
|
481
778
|
expectedLimit = limit;
|
|
@@ -577,7 +874,7 @@ module.exports = function (RED) {
|
|
|
577
874
|
|
|
578
875
|
// Record mutation API usage (auth + mutation = ~250 complexity)
|
|
579
876
|
const ESTIMATED_MUTATION_COMPLEXITY = 250;
|
|
580
|
-
recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
877
|
+
metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
581
878
|
|
|
582
879
|
// Optimistically update cached state
|
|
583
880
|
const expectedSuspended = !enable;
|
|
@@ -643,7 +940,7 @@ module.exports = function (RED) {
|
|
|
643
940
|
|
|
644
941
|
// Record verification API usage (auth + device query = ~200 complexity)
|
|
645
942
|
const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
|
|
646
|
-
recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
|
|
943
|
+
metrics.recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
|
|
647
944
|
|
|
648
945
|
const actualSuspended = evDevice.status.isSuspended;
|
|
649
946
|
if (actualSuspended === expectedSuspended) {
|
|
@@ -668,7 +965,7 @@ module.exports = function (RED) {
|
|
|
668
965
|
async function fetchData(validationMode = false) {
|
|
669
966
|
// Estimated complexity per poll:
|
|
670
967
|
// - Auth mutation: ~100 complexity
|
|
671
|
-
// - Data query (
|
|
968
|
+
// - Data query (devices + flexPlannedDispatches — two sequential calls): ~400 complexity
|
|
672
969
|
// - Total: ~300 complexity per poll
|
|
673
970
|
const ESTIMATED_POLL_COMPLEXITY = 300;
|
|
674
971
|
|
|
@@ -687,7 +984,7 @@ module.exports = function (RED) {
|
|
|
687
984
|
debugInfo.step = "validation";
|
|
688
985
|
node.status({ fill: "red", shape: "ring", text: "Config Missing" });
|
|
689
986
|
node.send({
|
|
690
|
-
payload:
|
|
987
|
+
payload: getDefaultPayload(),
|
|
691
988
|
debug: debugInfo
|
|
692
989
|
});
|
|
693
990
|
return { validated: false };
|
|
@@ -730,76 +1027,100 @@ module.exports = function (RED) {
|
|
|
730
1027
|
debugInfo.apiCalls[0].tokenObtained = !!token;
|
|
731
1028
|
debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
|
|
732
1029
|
|
|
733
|
-
// STEP
|
|
734
|
-
debugInfo.step = "
|
|
1030
|
+
// STEP 2a: Fetch devices (preferences + device ID)
|
|
1031
|
+
debugInfo.step = "fetching_devices";
|
|
735
1032
|
node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
|
|
736
1033
|
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
const masterQuery = `
|
|
740
|
-
query getData($account: String!) {
|
|
741
|
-
plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } }
|
|
742
|
-
vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
|
|
743
|
-
}`;
|
|
744
|
-
|
|
745
|
-
const dataResponse = await graphqlPost({
|
|
746
|
-
query: masterQuery,
|
|
747
|
-
variables: { account: account }
|
|
748
|
-
}, token);
|
|
1034
|
+
const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
|
|
1035
|
+
const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
|
|
749
1036
|
|
|
750
1037
|
debugInfo.apiCalls.push({
|
|
751
1038
|
step: 2,
|
|
752
|
-
name: "
|
|
1039
|
+
name: "devices_query",
|
|
753
1040
|
url: "https://api.octopus.energy/v1/graphql/",
|
|
754
1041
|
accountNumber: account,
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
1042
|
+
statusCode: devicesResponse.status,
|
|
1043
|
+
hasErrors: !!(devicesResponse.data.errors),
|
|
1044
|
+
errors: devicesResponse.data.errors || null,
|
|
1045
|
+
hasData: !!(devicesResponse.data.data),
|
|
1046
|
+
responseHeaders: devicesResponse.headers || {}
|
|
1047
|
+
});
|
|
1048
|
+
|
|
1049
|
+
if (devicesResponse.data.errors) {
|
|
1050
|
+
throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
|
|
1051
|
+
}
|
|
1052
|
+
if (!devicesResponse.data.data) {
|
|
1053
|
+
throw new Error(`Devices response missing data. Response: ${JSON.stringify(devicesResponse.data)}`);
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
const devicesData = devicesResponse.data.data;
|
|
1057
|
+
const evDevice = intelligentCategory.extractEvDevice(devicesData.devices);
|
|
1058
|
+
if (!evDevice) {
|
|
1059
|
+
throw new Error('No ELECTRIC_VEHICLES device found on account');
|
|
1060
|
+
}
|
|
1061
|
+
krakenflexDeviceId = evDevice.id;
|
|
1062
|
+
|
|
1063
|
+
// STEP 2b: Fetch planned dispatches using device ID
|
|
1064
|
+
debugInfo.step = "fetching_dispatches";
|
|
1065
|
+
const { query: dispatchQuery, variables: dispatchVars } = intelligentCategory.buildDispatchQuery(evDevice.id);
|
|
1066
|
+
const dispatchResponse = await graphqlPost({ query: dispatchQuery, variables: dispatchVars }, token);
|
|
1067
|
+
|
|
1068
|
+
debugInfo.apiCalls.push({
|
|
1069
|
+
step: 3,
|
|
1070
|
+
name: "dispatches_query",
|
|
1071
|
+
url: "https://api.octopus.energy/v1/graphql/",
|
|
1072
|
+
deviceId: evDevice.id,
|
|
1073
|
+
statusCode: dispatchResponse.status,
|
|
1074
|
+
hasErrors: !!(dispatchResponse.data.errors),
|
|
1075
|
+
errors: dispatchResponse.data.errors || null,
|
|
1076
|
+
hasData: !!(dispatchResponse.data.data),
|
|
1077
|
+
responseHeaders: dispatchResponse.headers || {}
|
|
762
1078
|
});
|
|
763
1079
|
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
throw new Error(`Data query failed: ${JSON.stringify(dataResponse.data.errors)}`);
|
|
1080
|
+
if (dispatchResponse.data.errors) {
|
|
1081
|
+
throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
|
|
767
1082
|
}
|
|
768
|
-
if (!
|
|
769
|
-
throw new Error(`
|
|
1083
|
+
if (!dispatchResponse.data.data) {
|
|
1084
|
+
throw new Error(`Dispatches response missing data. Response: ${JSON.stringify(dispatchResponse.data)}`);
|
|
770
1085
|
}
|
|
771
1086
|
|
|
772
1087
|
// STEP 3: Extract and Process
|
|
773
1088
|
debugInfo.step = "processing";
|
|
774
|
-
const data =
|
|
775
|
-
|
|
776
|
-
|
|
1089
|
+
const data = {
|
|
1090
|
+
devices: devicesData.devices,
|
|
1091
|
+
flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || []
|
|
1092
|
+
};
|
|
1093
|
+
const slots = data.flexPlannedDispatches;
|
|
777
1094
|
|
|
778
|
-
// Check for GraphQL extensions
|
|
1095
|
+
// Check for GraphQL extensions on the dispatches response
|
|
779
1096
|
let actualComplexity = null;
|
|
780
|
-
if (
|
|
781
|
-
debugInfo.apiCalls[
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
dataResponse.data.extensions.cost ||
|
|
1097
|
+
if (dispatchResponse.data.extensions) {
|
|
1098
|
+
debugInfo.apiCalls[2].extensions = dispatchResponse.data.extensions;
|
|
1099
|
+
actualComplexity = dispatchResponse.data.extensions.complexity ||
|
|
1100
|
+
dispatchResponse.data.extensions.cost ||
|
|
785
1101
|
null;
|
|
786
1102
|
}
|
|
787
1103
|
|
|
788
1104
|
// Record poll with estimated or actual complexity
|
|
789
|
-
recordPoll(actualComplexity || ESTIMATED_POLL_COMPLEXITY);
|
|
790
|
-
|
|
791
|
-
debugInfo.apiCalls[
|
|
792
|
-
debugInfo.apiCalls[
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
source: s.meta?.source
|
|
1105
|
+
metrics.recordPoll(actualComplexity || ESTIMATED_POLL_COMPLEXITY);
|
|
1106
|
+
|
|
1107
|
+
debugInfo.apiCalls[2].slotsFound = slots.length;
|
|
1108
|
+
debugInfo.apiCalls[2].slotDetails = slots.map(s => ({
|
|
1109
|
+
start: s.start,
|
|
1110
|
+
end: s.end,
|
|
1111
|
+
kwh: s.energyAddedKwh,
|
|
1112
|
+
type: s.type
|
|
798
1113
|
}));
|
|
799
1114
|
|
|
800
|
-
//
|
|
801
|
-
|
|
802
|
-
|
|
1115
|
+
// Parse response via intelligent category module
|
|
1116
|
+
const appliedTz = resolveTimezone(node);
|
|
1117
|
+
const serverTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch(e) { return 'UTC'; } })();
|
|
1118
|
+
const catResult = intelligentCategory.parseResponse(data, { tz: appliedTz, serverTz });
|
|
1119
|
+
const { _activeSlots, ...catPublic } = catResult;
|
|
1120
|
+
|
|
1121
|
+
// Update Confirmed State (from catResult)
|
|
1122
|
+
confirmedLimit = catResult.confirmed_limit ?? confirmedLimit;
|
|
1123
|
+
confirmedTime = catResult.confirmed_time || confirmedTime;
|
|
803
1124
|
|
|
804
1125
|
// On successful fetch, sync pending to confirmed if not in validation mode
|
|
805
1126
|
if (!validationMode) {
|
|
@@ -807,20 +1128,11 @@ module.exports = function (RED) {
|
|
|
807
1128
|
pendingTime = confirmedTime;
|
|
808
1129
|
}
|
|
809
1130
|
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
// Include active slots (endDt in future) and future slots
|
|
813
|
-
const activeAndFutureSlots = slots.filter(s => new Date(s.endDt) > now);
|
|
814
|
-
const nextSlot = activeAndFutureSlots[0] || null;
|
|
815
|
-
|
|
816
|
-
// Total energy for all active/future slots
|
|
817
|
-
const totalEnergy = activeAndFutureSlots.reduce((sum, s) => sum + (s.deltaKwh || 0), 0);
|
|
818
|
-
|
|
819
|
-
debugInfo.apiCalls[1].activeAndFutureSlots = activeAndFutureSlots.length;
|
|
820
|
-
debugInfo.processingTime = now.toISOString();
|
|
1131
|
+
debugInfo.apiCalls[1].activeAndFutureSlots = _activeSlots.length;
|
|
1132
|
+
debugInfo.processingTime = new Date().toISOString();
|
|
821
1133
|
|
|
822
1134
|
// Setup charging timers (always update charging state)
|
|
823
|
-
setupChargingTimers(
|
|
1135
|
+
setupChargingTimers(_activeSlots);
|
|
824
1136
|
|
|
825
1137
|
// Start reconciliation loop on first successful data fetch (only in non-validation mode)
|
|
826
1138
|
if (!validationMode && !stateCheckInterval) {
|
|
@@ -831,68 +1143,24 @@ module.exports = function (RED) {
|
|
|
831
1143
|
updateNextPollTime();
|
|
832
1144
|
|
|
833
1145
|
// Get API metrics for inclusion in payload
|
|
834
|
-
const apiMetrics =
|
|
1146
|
+
const apiMetrics = metrics.getMetrics();
|
|
835
1147
|
|
|
836
|
-
// Build Payload
|
|
837
|
-
const
|
|
838
|
-
|
|
839
|
-
const statusPayload = {
|
|
840
|
-
next_start: nextSlot ? convertToTimezone(nextSlot.startDt, appliedTz) : null,
|
|
841
|
-
total_energy: parseFloat(totalEnergy.toFixed(2)),
|
|
842
|
-
next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
|
|
843
|
-
next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
|
|
844
|
-
// Confirmed values (from API)
|
|
845
|
-
confirmed_limit: confirmedLimit,
|
|
846
|
-
confirmed_time: confirmedTime,
|
|
847
|
-
// Pending values (user's current selections)
|
|
1148
|
+
// Build Payload — merge catResult into lastKnownState, then add orchestrator-owned fields
|
|
1149
|
+
const statusPayload = Object.assign({}, lastKnownState, catPublic, {
|
|
1150
|
+
// Orchestrator-owned state fields (not in intelligentCategory)
|
|
848
1151
|
pending_limit: pendingLimit,
|
|
849
1152
|
pending_time: pendingTime,
|
|
850
|
-
// Charging Now state
|
|
851
1153
|
charging_now: chargingNow,
|
|
852
|
-
// Next poll time
|
|
853
1154
|
next_poll: nextPollTime,
|
|
854
1155
|
next_poll_raw: nextPollTime,
|
|
855
|
-
// Refresh available timestamp (null = ready, ISO timestamp = counting down)
|
|
856
1156
|
refresh_available_at: getRefreshAvailableAt(),
|
|
857
|
-
// API complexity metrics
|
|
858
1157
|
api_requests_hour: apiMetrics.requests_last_hour,
|
|
859
1158
|
api_complexity_hour: apiMetrics.complexity_last_hour,
|
|
860
1159
|
api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
|
|
861
|
-
// Individual slots (first 3 active/future) — timezone-converted (appliedTz)
|
|
862
|
-
slot1_start: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
|
|
863
|
-
slot1_end: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, appliedTz) : null,
|
|
864
|
-
slot2_start: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, appliedTz) : null,
|
|
865
|
-
slot2_end: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, appliedTz) : null,
|
|
866
|
-
slot3_start: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, appliedTz) : null,
|
|
867
|
-
slot3_end: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, appliedTz) : null,
|
|
868
|
-
// Overall window (first start to last end) — timezone-converted (appliedTz)
|
|
869
|
-
window_start: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
|
|
870
|
-
window_end: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, appliedTz) : null,
|
|
871
|
-
// Raw timestamp strings (exact API output)
|
|
872
|
-
next_start_raw: nextSlot ? nextSlot.startDt : null,
|
|
873
|
-
slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
|
|
874
|
-
slot1_end_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
|
|
875
|
-
slot2_start_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
|
|
876
|
-
slot2_end_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
|
|
877
|
-
slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
|
|
878
|
-
slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
|
|
879
|
-
window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
|
|
880
|
-
window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
|
|
881
|
-
// Timezone metadata
|
|
882
1160
|
timezone_detected: serverTz,
|
|
883
1161
|
timezone_applied: appliedTz,
|
|
884
|
-
// Locale timestamps — always server auto-detected timezone (never overridden)
|
|
885
|
-
next_start_locale: nextSlot ? convertToTimezone(nextSlot.startDt, serverTz) : null,
|
|
886
|
-
slot1_start_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
|
|
887
|
-
slot1_end_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, serverTz) : null,
|
|
888
|
-
slot2_start_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, serverTz) : null,
|
|
889
|
-
slot2_end_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, serverTz) : null,
|
|
890
|
-
slot3_start_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, serverTz) : null,
|
|
891
|
-
slot3_end_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, serverTz) : null,
|
|
892
|
-
window_start_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
|
|
893
|
-
window_end_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, serverTz) : null,
|
|
894
1162
|
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
|
|
895
|
-
};
|
|
1163
|
+
});
|
|
896
1164
|
|
|
897
1165
|
// Success!
|
|
898
1166
|
debugInfo.success = true;
|
|
@@ -975,7 +1243,7 @@ module.exports = function (RED) {
|
|
|
975
1243
|
|
|
976
1244
|
// Send default payload with debug info
|
|
977
1245
|
node.send({
|
|
978
|
-
payload:
|
|
1246
|
+
payload: getDefaultPayload(),
|
|
979
1247
|
debug: debugInfo
|
|
980
1248
|
});
|
|
981
1249
|
}
|
|
@@ -985,55 +1253,9 @@ module.exports = function (RED) {
|
|
|
985
1253
|
}
|
|
986
1254
|
}
|
|
987
1255
|
|
|
988
|
-
// Helper: Build default payload when errors occur
|
|
989
|
-
function
|
|
990
|
-
return {
|
|
991
|
-
next_start: null,
|
|
992
|
-
total_energy: 0,
|
|
993
|
-
next_kwh: "0",
|
|
994
|
-
next_source: "unknown",
|
|
995
|
-
confirmed_limit: confirmedLimit,
|
|
996
|
-
confirmed_time: confirmedTime,
|
|
997
|
-
pending_limit: pendingLimit,
|
|
998
|
-
pending_time: pendingTime,
|
|
999
|
-
charging_now: chargingNow,
|
|
1000
|
-
refresh_available_at: null,
|
|
1001
|
-
api_requests_hour: 0,
|
|
1002
|
-
api_complexity_hour: 0,
|
|
1003
|
-
api_complexity_percent: 0,
|
|
1004
|
-
slot1_start: null,
|
|
1005
|
-
slot1_end: null,
|
|
1006
|
-
slot2_start: null,
|
|
1007
|
-
slot2_end: null,
|
|
1008
|
-
slot3_start: null,
|
|
1009
|
-
slot3_end: null,
|
|
1010
|
-
window_start: null,
|
|
1011
|
-
window_end: null,
|
|
1012
|
-
// Raw timestamp strings
|
|
1013
|
-
next_start_raw: null,
|
|
1014
|
-
slot1_start_raw: null,
|
|
1015
|
-
slot1_end_raw: null,
|
|
1016
|
-
slot2_start_raw: null,
|
|
1017
|
-
slot2_end_raw: null,
|
|
1018
|
-
slot3_start_raw: null,
|
|
1019
|
-
slot3_end_raw: null,
|
|
1020
|
-
window_start_raw: null,
|
|
1021
|
-
window_end_raw: null,
|
|
1022
|
-
// Timezone metadata
|
|
1023
|
-
timezone_detected: null,
|
|
1024
|
-
timezone_applied: null,
|
|
1025
|
-
// Locale timestamps
|
|
1026
|
-
next_start_locale: null,
|
|
1027
|
-
slot1_start_locale: null,
|
|
1028
|
-
slot1_end_locale: null,
|
|
1029
|
-
slot2_start_locale: null,
|
|
1030
|
-
slot2_end_locale: null,
|
|
1031
|
-
slot3_start_locale: null,
|
|
1032
|
-
slot3_end_locale: null,
|
|
1033
|
-
window_start_locale: null,
|
|
1034
|
-
window_end_locale: null,
|
|
1035
|
-
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
|
|
1036
|
-
};
|
|
1256
|
+
// Helper: Build default payload when errors occur — delegates to lib/payload.js
|
|
1257
|
+
function getDefaultPayload() {
|
|
1258
|
+
return buildDefaultPayload({ confirmedLimit, confirmedTime, pendingLimit, pendingTime, chargingNow, smartChargingSuspended });
|
|
1037
1259
|
}
|
|
1038
1260
|
|
|
1039
1261
|
// Helper: Fetch device ID and initial smart charging state (called once at startup)
|
|
@@ -1086,8 +1308,8 @@ module.exports = function (RED) {
|
|
|
1086
1308
|
|
|
1087
1309
|
// Check if we should be charging RIGHT NOW based on cached slots
|
|
1088
1310
|
const shouldBeCharging = cachedSlots.some(slot => {
|
|
1089
|
-
const start = new Date(slot.
|
|
1090
|
-
const end = new Date(slot.
|
|
1311
|
+
const start = new Date(slot.start);
|
|
1312
|
+
const end = new Date(slot.end);
|
|
1091
1313
|
return start <= now && end > now;
|
|
1092
1314
|
});
|
|
1093
1315
|
|
|
@@ -1175,35 +1397,6 @@ module.exports = function (RED) {
|
|
|
1175
1397
|
nextPollTime = new Date(Date.now() + refreshRate).toISOString();
|
|
1176
1398
|
}
|
|
1177
1399
|
|
|
1178
|
-
function recordPoll(complexity = null) {
|
|
1179
|
-
const now = Date.now();
|
|
1180
|
-
pollHistory.push({
|
|
1181
|
-
timestamp: now,
|
|
1182
|
-
complexity: complexity || null
|
|
1183
|
-
});
|
|
1184
|
-
|
|
1185
|
-
// Remove entries older than 60 minutes
|
|
1186
|
-
const sixtyMinAgo = now - (60 * 60 * 1000);
|
|
1187
|
-
pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
|
|
1188
|
-
}
|
|
1189
|
-
|
|
1190
|
-
function getApiMetrics() {
|
|
1191
|
-
// Clean up old entries first
|
|
1192
|
-
const now = Date.now();
|
|
1193
|
-
const sixtyMinAgo = now - (60 * 60 * 1000);
|
|
1194
|
-
pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
|
|
1195
|
-
|
|
1196
|
-
const requestCount = pollHistory.length;
|
|
1197
|
-
const totalComplexity = pollHistory.reduce((sum, entry) => sum + (entry.complexity || 0), 0);
|
|
1198
|
-
const percentUsed = requestCount > 0 && totalComplexity > 0 ? (totalComplexity / 50000) * 100 : 0;
|
|
1199
|
-
|
|
1200
|
-
return {
|
|
1201
|
-
requests_last_hour: requestCount,
|
|
1202
|
-
complexity_last_hour: totalComplexity,
|
|
1203
|
-
complexity_percent: percentUsed.toFixed(1)
|
|
1204
|
-
};
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
1400
|
// Publish charging state to MQTT and Node-RED
|
|
1208
1401
|
function publishChargingState(state) {
|
|
1209
1402
|
chargingNow = state;
|
|
@@ -1242,7 +1435,7 @@ module.exports = function (RED) {
|
|
|
1242
1435
|
// Setup pre-validation timer (30s before slot starts)
|
|
1243
1436
|
function setupPreValidationTimer(nextSlot) {
|
|
1244
1437
|
const now = new Date();
|
|
1245
|
-
const slotStart = new Date(nextSlot.
|
|
1438
|
+
const slotStart = new Date(nextSlot.start);
|
|
1246
1439
|
const preValidationTime = slotStart.getTime() - 30000; // 30s before
|
|
1247
1440
|
const msUntilPreValidation = preValidationTime - now.getTime();
|
|
1248
1441
|
|
|
@@ -1250,7 +1443,10 @@ module.exports = function (RED) {
|
|
|
1250
1443
|
preValidationTimer = setTimeout(async () => {
|
|
1251
1444
|
node.warn("Pre-validating slot data (30s before start)");
|
|
1252
1445
|
try {
|
|
1253
|
-
|
|
1446
|
+
if (!krakenflexDeviceId) {
|
|
1447
|
+
throw new Error("Device ID not available for pre-validation");
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1254
1450
|
const authResponse = await graphqlPost({
|
|
1255
1451
|
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
1256
1452
|
variables: { input: { APIKey: apiKey } }
|
|
@@ -1262,25 +1458,23 @@ module.exports = function (RED) {
|
|
|
1262
1458
|
|
|
1263
1459
|
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
1264
1460
|
|
|
1265
|
-
const
|
|
1266
|
-
|
|
1267
|
-
variables: { account: account }
|
|
1268
|
-
}, token);
|
|
1461
|
+
const { query: dq, variables: dv } = intelligentCategory.buildDispatchQuery(krakenflexDeviceId);
|
|
1462
|
+
const dataResponse = await graphqlPost({ query: dq, variables: dv }, token);
|
|
1269
1463
|
|
|
1270
|
-
if (dataResponse.data.data && dataResponse.data.data.
|
|
1271
|
-
cachedSlots = dataResponse.data.data.
|
|
1464
|
+
if (dataResponse.data.data && dataResponse.data.data.flexPlannedDispatches) {
|
|
1465
|
+
cachedSlots = dataResponse.data.data.flexPlannedDispatches;
|
|
1272
1466
|
|
|
1273
1467
|
// Record pre-validation API usage (auth + simple query = ~200 complexity)
|
|
1274
1468
|
const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
|
|
1275
|
-
recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
|
|
1469
|
+
metrics.recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
|
|
1276
1470
|
|
|
1277
1471
|
// Check if slot still exists (within 1 minute tolerance)
|
|
1278
1472
|
const stillExists = cachedSlots.find(s =>
|
|
1279
|
-
Math.abs(new Date(s.
|
|
1473
|
+
Math.abs(new Date(s.start).getTime() - slotStart.getTime()) < 60000
|
|
1280
1474
|
);
|
|
1281
1475
|
|
|
1282
1476
|
if (stillExists) {
|
|
1283
|
-
node.warn(`Slot confirmed at ${stillExists.
|
|
1477
|
+
node.warn(`Slot confirmed at ${stillExists.start}`);
|
|
1284
1478
|
setupSlotStartTimer(stillExists);
|
|
1285
1479
|
} else {
|
|
1286
1480
|
node.warn("Slot was cancelled or modified - not setting start timer");
|
|
@@ -1301,21 +1495,21 @@ module.exports = function (RED) {
|
|
|
1301
1495
|
// Setup slot start timer (exact start time)
|
|
1302
1496
|
function setupSlotStartTimer(slot) {
|
|
1303
1497
|
const now = new Date();
|
|
1304
|
-
const slotStart = new Date(slot.
|
|
1498
|
+
const slotStart = new Date(slot.start);
|
|
1305
1499
|
const msUntilStart = slotStart.getTime() - now.getTime();
|
|
1306
1500
|
|
|
1307
1501
|
if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
1308
1502
|
slotStartTimer = setTimeout(() => {
|
|
1309
1503
|
publishChargingState(true);
|
|
1310
|
-
node.warn(`Charging slot started at ${slot.
|
|
1504
|
+
node.warn(`Charging slot started at ${slot.start}`);
|
|
1311
1505
|
setupSlotEndTimer(slot);
|
|
1312
1506
|
}, msUntilStart);
|
|
1313
1507
|
|
|
1314
1508
|
const secondsUntil = Math.round(msUntilStart / 1000);
|
|
1315
|
-
node.log(`Slot start timer set for ${secondsUntil}s (${slot.
|
|
1509
|
+
node.log(`Slot start timer set for ${secondsUntil}s (${slot.start})`);
|
|
1316
1510
|
} else if (msUntilStart <= 0) {
|
|
1317
1511
|
// Slot already started, check if it's still active
|
|
1318
|
-
const slotEnd = new Date(slot.
|
|
1512
|
+
const slotEnd = new Date(slot.end);
|
|
1319
1513
|
if (slotEnd > now) {
|
|
1320
1514
|
publishChargingState(true);
|
|
1321
1515
|
setupSlotEndTimer(slot);
|
|
@@ -1326,18 +1520,18 @@ module.exports = function (RED) {
|
|
|
1326
1520
|
// Setup slot end timer (exact end time)
|
|
1327
1521
|
function setupSlotEndTimer(slot) {
|
|
1328
1522
|
const now = new Date();
|
|
1329
|
-
const slotEnd = new Date(slot.
|
|
1523
|
+
const slotEnd = new Date(slot.end);
|
|
1330
1524
|
const msUntilEnd = slotEnd.getTime() - now.getTime();
|
|
1331
1525
|
|
|
1332
1526
|
if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
1333
1527
|
slotEndTimer = setTimeout(() => {
|
|
1334
|
-
node.warn(`Charging slot ended at ${slot.
|
|
1528
|
+
node.warn(`Charging slot ended at ${slot.end}`);
|
|
1335
1529
|
|
|
1336
1530
|
// Check if another slot starts immediately (within cached data)
|
|
1337
1531
|
const now = new Date();
|
|
1338
1532
|
const immediateNextSlot = cachedSlots.find(s => {
|
|
1339
|
-
const start = new Date(s.
|
|
1340
|
-
const end = new Date(s.
|
|
1533
|
+
const start = new Date(s.start);
|
|
1534
|
+
const end = new Date(s.end);
|
|
1341
1535
|
return start <= now && end > now;
|
|
1342
1536
|
});
|
|
1343
1537
|
|
|
@@ -1351,7 +1545,7 @@ module.exports = function (RED) {
|
|
|
1351
1545
|
}, msUntilEnd);
|
|
1352
1546
|
|
|
1353
1547
|
const minutesUntil = Math.round(msUntilEnd / 60000);
|
|
1354
|
-
node.log(`Slot end timer set for ${minutesUntil} min (${slot.
|
|
1548
|
+
node.log(`Slot end timer set for ${minutesUntil} min (${slot.end})`);
|
|
1355
1549
|
}
|
|
1356
1550
|
}
|
|
1357
1551
|
|
|
@@ -1367,8 +1561,8 @@ module.exports = function (RED) {
|
|
|
1367
1561
|
|
|
1368
1562
|
// Check if currently in a charging slot
|
|
1369
1563
|
const activeSlot = slots.find(s => {
|
|
1370
|
-
const start = new Date(s.
|
|
1371
|
-
const end = new Date(s.
|
|
1564
|
+
const start = new Date(s.start);
|
|
1565
|
+
const end = new Date(s.end);
|
|
1372
1566
|
return start <= now && end > now;
|
|
1373
1567
|
});
|
|
1374
1568
|
|
|
@@ -1388,11 +1582,11 @@ module.exports = function (RED) {
|
|
|
1388
1582
|
}
|
|
1389
1583
|
|
|
1390
1584
|
// Find next future slot
|
|
1391
|
-
const nextSlot = slots.find(s => new Date(s.
|
|
1585
|
+
const nextSlot = slots.find(s => new Date(s.start) > now);
|
|
1392
1586
|
|
|
1393
1587
|
if (nextSlot) {
|
|
1394
1588
|
setupPreValidationTimer(nextSlot);
|
|
1395
|
-
node.log(`Next slot at ${nextSlot.
|
|
1589
|
+
node.log(`Next slot at ${nextSlot.start}`);
|
|
1396
1590
|
}
|
|
1397
1591
|
}
|
|
1398
1592
|
}
|
|
@@ -1555,6 +1749,25 @@ module.exports = function (RED) {
|
|
|
1555
1749
|
updateNextPollTime(); // Set initial next poll time
|
|
1556
1750
|
setTimeout(fetchData, 1000);
|
|
1557
1751
|
setTimeout(fetchDeviceId, 1500);
|
|
1752
|
+
|
|
1753
|
+
// V2 category discovery and scheduler
|
|
1754
|
+
setTimeout(async () => {
|
|
1755
|
+
try {
|
|
1756
|
+
const discovered = await discoverProducts(apiKey, account);
|
|
1757
|
+
if (discovered.deviceSuspended !== null && discovered.deviceSuspended !== undefined) {
|
|
1758
|
+
smartChargingSuspended = discovered.deviceSuspended;
|
|
1759
|
+
lastKnownState = mergePayload(lastKnownState, { smart_charging: !discovered.deviceSuspended });
|
|
1760
|
+
}
|
|
1761
|
+
await initCategories(discovered);
|
|
1762
|
+
node.log(`V2 discovery: electricity=${discovered.hasElectricity}, gas=${discovered.hasGas}, intelligent=${discovered.hasIntelligent}, suspended=${discovered.deviceSuspended}`);
|
|
1763
|
+
const v2Scheduler = createScheduler(pollDueCategories);
|
|
1764
|
+
v2Scheduler.start();
|
|
1765
|
+
node._v2Scheduler = v2Scheduler;
|
|
1766
|
+
} catch (e) {
|
|
1767
|
+
node.warn(`V2 discovery failed: ${e.message}. New categories unavailable.`);
|
|
1768
|
+
}
|
|
1769
|
+
}, 2000);
|
|
1770
|
+
|
|
1558
1771
|
node.on('close', () => {
|
|
1559
1772
|
clearInterval(pollIntervalHandle);
|
|
1560
1773
|
// Clear any pending retry timeouts
|
|
@@ -1570,6 +1783,7 @@ module.exports = function (RED) {
|
|
|
1570
1783
|
clearTimeout(cooldownExpiryTimer);
|
|
1571
1784
|
cooldownExpiryTimer = null;
|
|
1572
1785
|
}
|
|
1786
|
+
if (node._v2Scheduler) node._v2Scheduler.stop();
|
|
1573
1787
|
if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging);
|
|
1574
1788
|
});
|
|
1575
1789
|
}
|