node-red-contrib-octopus-intelligent 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/README.md +619 -222
- 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 +123 -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 +628 -386
- 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
|
|
@@ -436,19 +733,32 @@ module.exports = function (RED) {
|
|
|
436
733
|
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
437
734
|
|
|
438
735
|
// B. Send Mutation
|
|
736
|
+
if (!krakenflexDeviceId) {
|
|
737
|
+
throw new Error('Device ID not available — cannot set preferences');
|
|
738
|
+
}
|
|
739
|
+
|
|
439
740
|
const mutation = `
|
|
440
|
-
mutation setPreferences($input:
|
|
441
|
-
|
|
741
|
+
mutation setPreferences($input: SmartFlexDevicePreferencesInput!) {
|
|
742
|
+
setDevicePreferences(input: $input) { __typename }
|
|
442
743
|
}`;
|
|
443
744
|
|
|
745
|
+
const DAYS = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'];
|
|
746
|
+
function buildDevicePreferencesInput(deviceId, socLimit, readyTime) {
|
|
747
|
+
return {
|
|
748
|
+
deviceId,
|
|
749
|
+
mode: 'CHARGE',
|
|
750
|
+
unit: 'PERCENTAGE',
|
|
751
|
+
schedules: DAYS.map(dayOfWeek => ({
|
|
752
|
+
dayOfWeek,
|
|
753
|
+
time: readyTime + ':00',
|
|
754
|
+
min: 0,
|
|
755
|
+
max: socLimit
|
|
756
|
+
}))
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
|
|
444
760
|
const variables = {
|
|
445
|
-
input:
|
|
446
|
-
accountNumber: account,
|
|
447
|
-
weekdayTargetSoc: limit,
|
|
448
|
-
weekendTargetSoc: limit,
|
|
449
|
-
weekdayTargetTime: time,
|
|
450
|
-
weekendTargetTime: time
|
|
451
|
-
}
|
|
761
|
+
input: buildDevicePreferencesInput(krakenflexDeviceId, limit, time)
|
|
452
762
|
};
|
|
453
763
|
|
|
454
764
|
const mutationResponse = await graphqlPost({
|
|
@@ -462,7 +772,7 @@ module.exports = function (RED) {
|
|
|
462
772
|
|
|
463
773
|
// Record mutation API usage (auth + mutation = ~250 complexity)
|
|
464
774
|
const ESTIMATED_MUTATION_COMPLEXITY = 250;
|
|
465
|
-
recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
775
|
+
metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
466
776
|
|
|
467
777
|
// C. Start exponential backoff validation
|
|
468
778
|
expectedLimit = limit;
|
|
@@ -564,7 +874,7 @@ module.exports = function (RED) {
|
|
|
564
874
|
|
|
565
875
|
// Record mutation API usage (auth + mutation = ~250 complexity)
|
|
566
876
|
const ESTIMATED_MUTATION_COMPLEXITY = 250;
|
|
567
|
-
recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
877
|
+
metrics.recordPoll(ESTIMATED_MUTATION_COMPLEXITY);
|
|
568
878
|
|
|
569
879
|
// Optimistically update cached state
|
|
570
880
|
const expectedSuspended = !enable;
|
|
@@ -613,26 +923,33 @@ module.exports = function (RED) {
|
|
|
613
923
|
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
614
924
|
|
|
615
925
|
const deviceResponse = await graphqlPost({
|
|
616
|
-
query: `query
|
|
926
|
+
query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
|
|
617
927
|
variables: { accountNumber: account }
|
|
618
928
|
}, token);
|
|
619
929
|
|
|
620
|
-
if (deviceResponse.data.errors || !deviceResponse.data.data
|
|
930
|
+
if (deviceResponse.data.errors || !deviceResponse.data.data) {
|
|
931
|
+
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
const evDevice = (deviceResponse.data.data.devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES');
|
|
936
|
+
if (!evDevice) {
|
|
621
937
|
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
622
938
|
return;
|
|
623
939
|
}
|
|
624
940
|
|
|
625
941
|
// Record verification API usage (auth + device query = ~200 complexity)
|
|
626
942
|
const ESTIMATED_VERIFICATION_COMPLEXITY = 200;
|
|
627
|
-
recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
|
|
943
|
+
metrics.recordPoll(ESTIMATED_VERIFICATION_COMPLEXITY);
|
|
628
944
|
|
|
629
|
-
const actualSuspended =
|
|
945
|
+
const actualSuspended = evDevice.status.isSuspended;
|
|
630
946
|
if (actualSuspended === expectedSuspended) {
|
|
631
947
|
// Confirmed — clear remaining retries
|
|
632
948
|
smartChargingSuspended = actualSuspended;
|
|
633
949
|
smartChargingRetryTimeouts.forEach(t => clearTimeout(t));
|
|
634
950
|
smartChargingRetryTimeouts = [];
|
|
635
951
|
node.log(`Smart charging confirmed: suspended=${actualSuspended}`);
|
|
952
|
+
node.status({ fill: "green", shape: "dot", text: actualSuspended ? "Smart charging suspended" : "Smart charging enabled" });
|
|
636
953
|
} else {
|
|
637
954
|
scheduleSmartChargingVerification(expectedSuspended, intervals, index + 1);
|
|
638
955
|
}
|
|
@@ -648,7 +965,7 @@ module.exports = function (RED) {
|
|
|
648
965
|
async function fetchData(validationMode = false) {
|
|
649
966
|
// Estimated complexity per poll:
|
|
650
967
|
// - Auth mutation: ~100 complexity
|
|
651
|
-
// - Data query (
|
|
968
|
+
// - Data query (devices + flexPlannedDispatches — two sequential calls): ~400 complexity
|
|
652
969
|
// - Total: ~300 complexity per poll
|
|
653
970
|
const ESTIMATED_POLL_COMPLEXITY = 300;
|
|
654
971
|
|
|
@@ -667,7 +984,7 @@ module.exports = function (RED) {
|
|
|
667
984
|
debugInfo.step = "validation";
|
|
668
985
|
node.status({ fill: "red", shape: "ring", text: "Config Missing" });
|
|
669
986
|
node.send({
|
|
670
|
-
payload:
|
|
987
|
+
payload: getDefaultPayload(),
|
|
671
988
|
debug: debugInfo
|
|
672
989
|
});
|
|
673
990
|
return { validated: false };
|
|
@@ -710,76 +1027,100 @@ module.exports = function (RED) {
|
|
|
710
1027
|
debugInfo.apiCalls[0].tokenObtained = !!token;
|
|
711
1028
|
debugInfo.apiCalls[0].tokenPrefix = token ? token.substring(0, 20) + "..." : null;
|
|
712
1029
|
|
|
713
|
-
// STEP
|
|
714
|
-
debugInfo.step = "
|
|
1030
|
+
// STEP 2a: Fetch devices (preferences + device ID)
|
|
1031
|
+
debugInfo.step = "fetching_devices";
|
|
715
1032
|
node.status({ fill: "yellow", shape: "ring", text: "Fetching data..." });
|
|
716
1033
|
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
const masterQuery = `
|
|
720
|
-
query getData($account: String!) {
|
|
721
|
-
plannedDispatches(accountNumber: $account) { startDt endDt deltaKwh meta { source } }
|
|
722
|
-
vehicleChargingPreferences(accountNumber: $account) { weekdayTargetSoc weekdayTargetTime }
|
|
723
|
-
}`;
|
|
724
|
-
|
|
725
|
-
const dataResponse = await graphqlPost({
|
|
726
|
-
query: masterQuery,
|
|
727
|
-
variables: { account: account }
|
|
728
|
-
}, token);
|
|
1034
|
+
const { query: devicesQuery, variables: devicesVars } = intelligentCategory.buildDevicesQuery(account);
|
|
1035
|
+
const devicesResponse = await graphqlPost({ query: devicesQuery, variables: devicesVars }, token);
|
|
729
1036
|
|
|
730
1037
|
debugInfo.apiCalls.push({
|
|
731
1038
|
step: 2,
|
|
732
|
-
name: "
|
|
1039
|
+
name: "devices_query",
|
|
733
1040
|
url: "https://api.octopus.energy/v1/graphql/",
|
|
734
1041
|
accountNumber: account,
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
// Capture response headers for rate limit analysis
|
|
741
|
-
responseHeaders: dataResponse.headers || {}
|
|
1042
|
+
statusCode: devicesResponse.status,
|
|
1043
|
+
hasErrors: !!(devicesResponse.data.errors),
|
|
1044
|
+
errors: devicesResponse.data.errors || null,
|
|
1045
|
+
hasData: !!(devicesResponse.data.data),
|
|
1046
|
+
responseHeaders: devicesResponse.headers || {}
|
|
742
1047
|
});
|
|
743
1048
|
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
throw new Error(`Data query failed: ${JSON.stringify(dataResponse.data.errors)}`);
|
|
1049
|
+
if (devicesResponse.data.errors) {
|
|
1050
|
+
throw new Error(`Devices query failed: ${JSON.stringify(devicesResponse.data.errors)}`);
|
|
747
1051
|
}
|
|
748
|
-
if (!
|
|
749
|
-
throw new Error(`
|
|
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 || {}
|
|
1078
|
+
});
|
|
1079
|
+
|
|
1080
|
+
if (dispatchResponse.data.errors) {
|
|
1081
|
+
throw new Error(`Dispatches query failed: ${JSON.stringify(dispatchResponse.data.errors)}`);
|
|
1082
|
+
}
|
|
1083
|
+
if (!dispatchResponse.data.data) {
|
|
1084
|
+
throw new Error(`Dispatches response missing data. Response: ${JSON.stringify(dispatchResponse.data)}`);
|
|
750
1085
|
}
|
|
751
1086
|
|
|
752
1087
|
// STEP 3: Extract and Process
|
|
753
1088
|
debugInfo.step = "processing";
|
|
754
|
-
const data =
|
|
755
|
-
|
|
756
|
-
|
|
1089
|
+
const data = {
|
|
1090
|
+
devices: devicesData.devices,
|
|
1091
|
+
flexPlannedDispatches: dispatchResponse.data.data.flexPlannedDispatches || []
|
|
1092
|
+
};
|
|
1093
|
+
const slots = data.flexPlannedDispatches;
|
|
757
1094
|
|
|
758
|
-
// Check for GraphQL extensions
|
|
1095
|
+
// Check for GraphQL extensions on the dispatches response
|
|
759
1096
|
let actualComplexity = null;
|
|
760
|
-
if (
|
|
761
|
-
debugInfo.apiCalls[
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
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 ||
|
|
765
1101
|
null;
|
|
766
1102
|
}
|
|
767
1103
|
|
|
768
1104
|
// Record poll with estimated or actual complexity
|
|
769
|
-
recordPoll(actualComplexity || ESTIMATED_POLL_COMPLEXITY);
|
|
770
|
-
|
|
771
|
-
debugInfo.apiCalls[
|
|
772
|
-
debugInfo.apiCalls[
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
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
|
|
778
1113
|
}));
|
|
779
1114
|
|
|
780
|
-
//
|
|
781
|
-
|
|
782
|
-
|
|
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;
|
|
783
1124
|
|
|
784
1125
|
// On successful fetch, sync pending to confirmed if not in validation mode
|
|
785
1126
|
if (!validationMode) {
|
|
@@ -787,20 +1128,11 @@ module.exports = function (RED) {
|
|
|
787
1128
|
pendingTime = confirmedTime;
|
|
788
1129
|
}
|
|
789
1130
|
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
// Include active slots (endDt in future) and future slots
|
|
793
|
-
const activeAndFutureSlots = slots.filter(s => new Date(s.endDt) > now);
|
|
794
|
-
const nextSlot = activeAndFutureSlots[0] || null;
|
|
795
|
-
|
|
796
|
-
// Total energy for all active/future slots
|
|
797
|
-
const totalEnergy = activeAndFutureSlots.reduce((sum, s) => sum + (s.deltaKwh || 0), 0);
|
|
798
|
-
|
|
799
|
-
debugInfo.apiCalls[1].activeAndFutureSlots = activeAndFutureSlots.length;
|
|
800
|
-
debugInfo.processingTime = now.toISOString();
|
|
1131
|
+
debugInfo.apiCalls[1].activeAndFutureSlots = _activeSlots.length;
|
|
1132
|
+
debugInfo.processingTime = new Date().toISOString();
|
|
801
1133
|
|
|
802
1134
|
// Setup charging timers (always update charging state)
|
|
803
|
-
setupChargingTimers(
|
|
1135
|
+
setupChargingTimers(_activeSlots);
|
|
804
1136
|
|
|
805
1137
|
// Start reconciliation loop on first successful data fetch (only in non-validation mode)
|
|
806
1138
|
if (!validationMode && !stateCheckInterval) {
|
|
@@ -811,68 +1143,24 @@ module.exports = function (RED) {
|
|
|
811
1143
|
updateNextPollTime();
|
|
812
1144
|
|
|
813
1145
|
// Get API metrics for inclusion in payload
|
|
814
|
-
const apiMetrics =
|
|
1146
|
+
const apiMetrics = metrics.getMetrics();
|
|
815
1147
|
|
|
816
|
-
// Build Payload
|
|
817
|
-
const
|
|
818
|
-
|
|
819
|
-
const statusPayload = {
|
|
820
|
-
next_start: nextSlot ? convertToTimezone(nextSlot.startDt, appliedTz) : null,
|
|
821
|
-
total_energy: parseFloat(totalEnergy.toFixed(2)),
|
|
822
|
-
next_kwh: nextSlot ? nextSlot.deltaKwh.toFixed(2) : "0",
|
|
823
|
-
next_source: nextSlot && nextSlot.meta ? nextSlot.meta.source : "unknown",
|
|
824
|
-
// Confirmed values (from API)
|
|
825
|
-
confirmed_limit: confirmedLimit,
|
|
826
|
-
confirmed_time: confirmedTime,
|
|
827
|
-
// 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)
|
|
828
1151
|
pending_limit: pendingLimit,
|
|
829
1152
|
pending_time: pendingTime,
|
|
830
|
-
// Charging Now state
|
|
831
1153
|
charging_now: chargingNow,
|
|
832
|
-
// Next poll time
|
|
833
1154
|
next_poll: nextPollTime,
|
|
834
1155
|
next_poll_raw: nextPollTime,
|
|
835
|
-
// Refresh available timestamp (null = ready, ISO timestamp = counting down)
|
|
836
1156
|
refresh_available_at: getRefreshAvailableAt(),
|
|
837
|
-
// API complexity metrics
|
|
838
1157
|
api_requests_hour: apiMetrics.requests_last_hour,
|
|
839
1158
|
api_complexity_hour: apiMetrics.complexity_last_hour,
|
|
840
1159
|
api_complexity_percent: parseFloat(apiMetrics.complexity_percent),
|
|
841
|
-
// Individual slots (first 3 active/future) — timezone-converted (appliedTz)
|
|
842
|
-
slot1_start: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
|
|
843
|
-
slot1_end: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, appliedTz) : null,
|
|
844
|
-
slot2_start: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, appliedTz) : null,
|
|
845
|
-
slot2_end: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, appliedTz) : null,
|
|
846
|
-
slot3_start: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, appliedTz) : null,
|
|
847
|
-
slot3_end: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, appliedTz) : null,
|
|
848
|
-
// Overall window (first start to last end) — timezone-converted (appliedTz)
|
|
849
|
-
window_start: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, appliedTz) : null,
|
|
850
|
-
window_end: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, appliedTz) : null,
|
|
851
|
-
// Raw timestamp strings (exact API output)
|
|
852
|
-
next_start_raw: nextSlot ? nextSlot.startDt : null,
|
|
853
|
-
slot1_start_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].startDt : null,
|
|
854
|
-
slot1_end_raw: activeAndFutureSlots[0] ? activeAndFutureSlots[0].endDt : null,
|
|
855
|
-
slot2_start_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].startDt : null,
|
|
856
|
-
slot2_end_raw: activeAndFutureSlots[1] ? activeAndFutureSlots[1].endDt : null,
|
|
857
|
-
slot3_start_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].startDt : null,
|
|
858
|
-
slot3_end_raw: activeAndFutureSlots[2] ? activeAndFutureSlots[2].endDt : null,
|
|
859
|
-
window_start_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[0].startDt : null,
|
|
860
|
-
window_end_raw: activeAndFutureSlots.length > 0 ? activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt : null,
|
|
861
|
-
// Timezone metadata
|
|
862
1160
|
timezone_detected: serverTz,
|
|
863
1161
|
timezone_applied: appliedTz,
|
|
864
|
-
// Locale timestamps — always server auto-detected timezone (never overridden)
|
|
865
|
-
next_start_locale: nextSlot ? convertToTimezone(nextSlot.startDt, serverTz) : null,
|
|
866
|
-
slot1_start_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
|
|
867
|
-
slot1_end_locale: activeAndFutureSlots[0] ? convertToTimezone(activeAndFutureSlots[0].endDt, serverTz) : null,
|
|
868
|
-
slot2_start_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].startDt, serverTz) : null,
|
|
869
|
-
slot2_end_locale: activeAndFutureSlots[1] ? convertToTimezone(activeAndFutureSlots[1].endDt, serverTz) : null,
|
|
870
|
-
slot3_start_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].startDt, serverTz) : null,
|
|
871
|
-
slot3_end_locale: activeAndFutureSlots[2] ? convertToTimezone(activeAndFutureSlots[2].endDt, serverTz) : null,
|
|
872
|
-
window_start_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[0].startDt, serverTz) : null,
|
|
873
|
-
window_end_locale: activeAndFutureSlots.length > 0 ? convertToTimezone(activeAndFutureSlots[activeAndFutureSlots.length - 1].endDt, serverTz) : null,
|
|
874
1162
|
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
|
|
875
|
-
};
|
|
1163
|
+
});
|
|
876
1164
|
|
|
877
1165
|
// Success!
|
|
878
1166
|
debugInfo.success = true;
|
|
@@ -955,7 +1243,7 @@ module.exports = function (RED) {
|
|
|
955
1243
|
|
|
956
1244
|
// Send default payload with debug info
|
|
957
1245
|
node.send({
|
|
958
|
-
payload:
|
|
1246
|
+
payload: getDefaultPayload(),
|
|
959
1247
|
debug: debugInfo
|
|
960
1248
|
});
|
|
961
1249
|
}
|
|
@@ -965,55 +1253,9 @@ module.exports = function (RED) {
|
|
|
965
1253
|
}
|
|
966
1254
|
}
|
|
967
1255
|
|
|
968
|
-
// Helper: Build default payload when errors occur
|
|
969
|
-
function
|
|
970
|
-
return {
|
|
971
|
-
next_start: null,
|
|
972
|
-
total_energy: 0,
|
|
973
|
-
next_kwh: "0",
|
|
974
|
-
next_source: "unknown",
|
|
975
|
-
confirmed_limit: confirmedLimit,
|
|
976
|
-
confirmed_time: confirmedTime,
|
|
977
|
-
pending_limit: pendingLimit,
|
|
978
|
-
pending_time: pendingTime,
|
|
979
|
-
charging_now: chargingNow,
|
|
980
|
-
refresh_available_at: null,
|
|
981
|
-
api_requests_hour: 0,
|
|
982
|
-
api_complexity_hour: 0,
|
|
983
|
-
api_complexity_percent: 0,
|
|
984
|
-
slot1_start: null,
|
|
985
|
-
slot1_end: null,
|
|
986
|
-
slot2_start: null,
|
|
987
|
-
slot2_end: null,
|
|
988
|
-
slot3_start: null,
|
|
989
|
-
slot3_end: null,
|
|
990
|
-
window_start: null,
|
|
991
|
-
window_end: null,
|
|
992
|
-
// Raw timestamp strings
|
|
993
|
-
next_start_raw: null,
|
|
994
|
-
slot1_start_raw: null,
|
|
995
|
-
slot1_end_raw: null,
|
|
996
|
-
slot2_start_raw: null,
|
|
997
|
-
slot2_end_raw: null,
|
|
998
|
-
slot3_start_raw: null,
|
|
999
|
-
slot3_end_raw: null,
|
|
1000
|
-
window_start_raw: null,
|
|
1001
|
-
window_end_raw: null,
|
|
1002
|
-
// Timezone metadata
|
|
1003
|
-
timezone_detected: null,
|
|
1004
|
-
timezone_applied: null,
|
|
1005
|
-
// Locale timestamps
|
|
1006
|
-
next_start_locale: null,
|
|
1007
|
-
slot1_start_locale: null,
|
|
1008
|
-
slot1_end_locale: null,
|
|
1009
|
-
slot2_start_locale: null,
|
|
1010
|
-
slot2_end_locale: null,
|
|
1011
|
-
slot3_start_locale: null,
|
|
1012
|
-
slot3_end_locale: null,
|
|
1013
|
-
window_start_locale: null,
|
|
1014
|
-
window_end_locale: null,
|
|
1015
|
-
smart_charging: smartChargingSuspended === null ? null : !smartChargingSuspended
|
|
1016
|
-
};
|
|
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 });
|
|
1017
1259
|
}
|
|
1018
1260
|
|
|
1019
1261
|
// Helper: Fetch device ID and initial smart charging state (called once at startup)
|
|
@@ -1029,17 +1271,25 @@ module.exports = function (RED) {
|
|
|
1029
1271
|
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
1030
1272
|
|
|
1031
1273
|
const deviceResponse = await graphqlPost({
|
|
1032
|
-
query: `query
|
|
1274
|
+
query: `query getDevices($accountNumber: String!) { devices(accountNumber: $accountNumber) { id deviceType status { isSuspended } } }`,
|
|
1033
1275
|
variables: { accountNumber: account }
|
|
1034
1276
|
}, token);
|
|
1035
1277
|
|
|
1036
|
-
if (deviceResponse.data.errors || !deviceResponse.data.data
|
|
1278
|
+
if (deviceResponse.data.errors || !deviceResponse.data.data) {
|
|
1037
1279
|
throw new Error(`Device fetch failed: ${JSON.stringify(deviceResponse.data.errors)}`);
|
|
1038
1280
|
}
|
|
1039
1281
|
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1282
|
+
function extractEvDevice(devices) {
|
|
1283
|
+
return (devices || []).find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
const evDevice = extractEvDevice(deviceResponse.data.data.devices);
|
|
1287
|
+
if (!evDevice) {
|
|
1288
|
+
throw new Error('No ELECTRIC_VEHICLES device found on account');
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
krakenflexDeviceId = evDevice.id;
|
|
1292
|
+
smartChargingSuspended = evDevice.status.isSuspended;
|
|
1043
1293
|
node.log(`Device ID cached: ${krakenflexDeviceId}, suspended: ${smartChargingSuspended}`);
|
|
1044
1294
|
} catch (e) {
|
|
1045
1295
|
node.warn(`Failed to fetch device ID at startup: ${e.message}. Smart charging toggle unavailable.`);
|
|
@@ -1058,8 +1308,8 @@ module.exports = function (RED) {
|
|
|
1058
1308
|
|
|
1059
1309
|
// Check if we should be charging RIGHT NOW based on cached slots
|
|
1060
1310
|
const shouldBeCharging = cachedSlots.some(slot => {
|
|
1061
|
-
const start = new Date(slot.
|
|
1062
|
-
const end = new Date(slot.
|
|
1311
|
+
const start = new Date(slot.start);
|
|
1312
|
+
const end = new Date(slot.end);
|
|
1063
1313
|
return start <= now && end > now;
|
|
1064
1314
|
});
|
|
1065
1315
|
|
|
@@ -1147,35 +1397,6 @@ module.exports = function (RED) {
|
|
|
1147
1397
|
nextPollTime = new Date(Date.now() + refreshRate).toISOString();
|
|
1148
1398
|
}
|
|
1149
1399
|
|
|
1150
|
-
function recordPoll(complexity = null) {
|
|
1151
|
-
const now = Date.now();
|
|
1152
|
-
pollHistory.push({
|
|
1153
|
-
timestamp: now,
|
|
1154
|
-
complexity: complexity || null
|
|
1155
|
-
});
|
|
1156
|
-
|
|
1157
|
-
// Remove entries older than 60 minutes
|
|
1158
|
-
const sixtyMinAgo = now - (60 * 60 * 1000);
|
|
1159
|
-
pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
function getApiMetrics() {
|
|
1163
|
-
// Clean up old entries first
|
|
1164
|
-
const now = Date.now();
|
|
1165
|
-
const sixtyMinAgo = now - (60 * 60 * 1000);
|
|
1166
|
-
pollHistory = pollHistory.filter(entry => entry.timestamp > sixtyMinAgo);
|
|
1167
|
-
|
|
1168
|
-
const requestCount = pollHistory.length;
|
|
1169
|
-
const totalComplexity = pollHistory.reduce((sum, entry) => sum + (entry.complexity || 0), 0);
|
|
1170
|
-
const percentUsed = requestCount > 0 && totalComplexity > 0 ? (totalComplexity / 50000) * 100 : 0;
|
|
1171
|
-
|
|
1172
|
-
return {
|
|
1173
|
-
requests_last_hour: requestCount,
|
|
1174
|
-
complexity_last_hour: totalComplexity,
|
|
1175
|
-
complexity_percent: percentUsed.toFixed(1)
|
|
1176
|
-
};
|
|
1177
|
-
}
|
|
1178
|
-
|
|
1179
1400
|
// Publish charging state to MQTT and Node-RED
|
|
1180
1401
|
function publishChargingState(state) {
|
|
1181
1402
|
chargingNow = state;
|
|
@@ -1214,7 +1435,7 @@ module.exports = function (RED) {
|
|
|
1214
1435
|
// Setup pre-validation timer (30s before slot starts)
|
|
1215
1436
|
function setupPreValidationTimer(nextSlot) {
|
|
1216
1437
|
const now = new Date();
|
|
1217
|
-
const slotStart = new Date(nextSlot.
|
|
1438
|
+
const slotStart = new Date(nextSlot.start);
|
|
1218
1439
|
const preValidationTime = slotStart.getTime() - 30000; // 30s before
|
|
1219
1440
|
const msUntilPreValidation = preValidationTime - now.getTime();
|
|
1220
1441
|
|
|
@@ -1222,7 +1443,10 @@ module.exports = function (RED) {
|
|
|
1222
1443
|
preValidationTimer = setTimeout(async () => {
|
|
1223
1444
|
node.warn("Pre-validating slot data (30s before start)");
|
|
1224
1445
|
try {
|
|
1225
|
-
|
|
1446
|
+
if (!krakenflexDeviceId) {
|
|
1447
|
+
throw new Error("Device ID not available for pre-validation");
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1226
1450
|
const authResponse = await graphqlPost({
|
|
1227
1451
|
query: `mutation obtainToken($input: ObtainJSONWebTokenInput!) { obtainKrakenToken(input: $input) { token } }`,
|
|
1228
1452
|
variables: { input: { APIKey: apiKey } }
|
|
@@ -1234,25 +1458,23 @@ module.exports = function (RED) {
|
|
|
1234
1458
|
|
|
1235
1459
|
const token = authResponse.data.data.obtainKrakenToken.token;
|
|
1236
1460
|
|
|
1237
|
-
const
|
|
1238
|
-
|
|
1239
|
-
variables: { account: account }
|
|
1240
|
-
}, token);
|
|
1461
|
+
const { query: dq, variables: dv } = intelligentCategory.buildDispatchQuery(krakenflexDeviceId);
|
|
1462
|
+
const dataResponse = await graphqlPost({ query: dq, variables: dv }, token);
|
|
1241
1463
|
|
|
1242
|
-
if (dataResponse.data.data && dataResponse.data.data.
|
|
1243
|
-
cachedSlots = dataResponse.data.data.
|
|
1464
|
+
if (dataResponse.data.data && dataResponse.data.data.flexPlannedDispatches) {
|
|
1465
|
+
cachedSlots = dataResponse.data.data.flexPlannedDispatches;
|
|
1244
1466
|
|
|
1245
1467
|
// Record pre-validation API usage (auth + simple query = ~200 complexity)
|
|
1246
1468
|
const ESTIMATED_PREVALIDATION_COMPLEXITY = 200;
|
|
1247
|
-
recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
|
|
1469
|
+
metrics.recordPoll(ESTIMATED_PREVALIDATION_COMPLEXITY);
|
|
1248
1470
|
|
|
1249
1471
|
// Check if slot still exists (within 1 minute tolerance)
|
|
1250
1472
|
const stillExists = cachedSlots.find(s =>
|
|
1251
|
-
Math.abs(new Date(s.
|
|
1473
|
+
Math.abs(new Date(s.start).getTime() - slotStart.getTime()) < 60000
|
|
1252
1474
|
);
|
|
1253
1475
|
|
|
1254
1476
|
if (stillExists) {
|
|
1255
|
-
node.warn(`Slot confirmed at ${stillExists.
|
|
1477
|
+
node.warn(`Slot confirmed at ${stillExists.start}`);
|
|
1256
1478
|
setupSlotStartTimer(stillExists);
|
|
1257
1479
|
} else {
|
|
1258
1480
|
node.warn("Slot was cancelled or modified - not setting start timer");
|
|
@@ -1273,21 +1495,21 @@ module.exports = function (RED) {
|
|
|
1273
1495
|
// Setup slot start timer (exact start time)
|
|
1274
1496
|
function setupSlotStartTimer(slot) {
|
|
1275
1497
|
const now = new Date();
|
|
1276
|
-
const slotStart = new Date(slot.
|
|
1498
|
+
const slotStart = new Date(slot.start);
|
|
1277
1499
|
const msUntilStart = slotStart.getTime() - now.getTime();
|
|
1278
1500
|
|
|
1279
1501
|
if (msUntilStart > 0 && msUntilStart < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
1280
1502
|
slotStartTimer = setTimeout(() => {
|
|
1281
1503
|
publishChargingState(true);
|
|
1282
|
-
node.warn(`Charging slot started at ${slot.
|
|
1504
|
+
node.warn(`Charging slot started at ${slot.start}`);
|
|
1283
1505
|
setupSlotEndTimer(slot);
|
|
1284
1506
|
}, msUntilStart);
|
|
1285
1507
|
|
|
1286
1508
|
const secondsUntil = Math.round(msUntilStart / 1000);
|
|
1287
|
-
node.log(`Slot start timer set for ${secondsUntil}s (${slot.
|
|
1509
|
+
node.log(`Slot start timer set for ${secondsUntil}s (${slot.start})`);
|
|
1288
1510
|
} else if (msUntilStart <= 0) {
|
|
1289
1511
|
// Slot already started, check if it's still active
|
|
1290
|
-
const slotEnd = new Date(slot.
|
|
1512
|
+
const slotEnd = new Date(slot.end);
|
|
1291
1513
|
if (slotEnd > now) {
|
|
1292
1514
|
publishChargingState(true);
|
|
1293
1515
|
setupSlotEndTimer(slot);
|
|
@@ -1298,18 +1520,18 @@ module.exports = function (RED) {
|
|
|
1298
1520
|
// Setup slot end timer (exact end time)
|
|
1299
1521
|
function setupSlotEndTimer(slot) {
|
|
1300
1522
|
const now = new Date();
|
|
1301
|
-
const slotEnd = new Date(slot.
|
|
1523
|
+
const slotEnd = new Date(slot.end);
|
|
1302
1524
|
const msUntilEnd = slotEnd.getTime() - now.getTime();
|
|
1303
1525
|
|
|
1304
1526
|
if (msUntilEnd > 0 && msUntilEnd < 24 * 60 * 60 * 1000) { // Within 24 hours
|
|
1305
1527
|
slotEndTimer = setTimeout(() => {
|
|
1306
|
-
node.warn(`Charging slot ended at ${slot.
|
|
1528
|
+
node.warn(`Charging slot ended at ${slot.end}`);
|
|
1307
1529
|
|
|
1308
1530
|
// Check if another slot starts immediately (within cached data)
|
|
1309
1531
|
const now = new Date();
|
|
1310
1532
|
const immediateNextSlot = cachedSlots.find(s => {
|
|
1311
|
-
const start = new Date(s.
|
|
1312
|
-
const end = new Date(s.
|
|
1533
|
+
const start = new Date(s.start);
|
|
1534
|
+
const end = new Date(s.end);
|
|
1313
1535
|
return start <= now && end > now;
|
|
1314
1536
|
});
|
|
1315
1537
|
|
|
@@ -1323,7 +1545,7 @@ module.exports = function (RED) {
|
|
|
1323
1545
|
}, msUntilEnd);
|
|
1324
1546
|
|
|
1325
1547
|
const minutesUntil = Math.round(msUntilEnd / 60000);
|
|
1326
|
-
node.log(`Slot end timer set for ${minutesUntil} min (${slot.
|
|
1548
|
+
node.log(`Slot end timer set for ${minutesUntil} min (${slot.end})`);
|
|
1327
1549
|
}
|
|
1328
1550
|
}
|
|
1329
1551
|
|
|
@@ -1339,8 +1561,8 @@ module.exports = function (RED) {
|
|
|
1339
1561
|
|
|
1340
1562
|
// Check if currently in a charging slot
|
|
1341
1563
|
const activeSlot = slots.find(s => {
|
|
1342
|
-
const start = new Date(s.
|
|
1343
|
-
const end = new Date(s.
|
|
1564
|
+
const start = new Date(s.start);
|
|
1565
|
+
const end = new Date(s.end);
|
|
1344
1566
|
return start <= now && end > now;
|
|
1345
1567
|
});
|
|
1346
1568
|
|
|
@@ -1360,11 +1582,11 @@ module.exports = function (RED) {
|
|
|
1360
1582
|
}
|
|
1361
1583
|
|
|
1362
1584
|
// Find next future slot
|
|
1363
|
-
const nextSlot = slots.find(s => new Date(s.
|
|
1585
|
+
const nextSlot = slots.find(s => new Date(s.start) > now);
|
|
1364
1586
|
|
|
1365
1587
|
if (nextSlot) {
|
|
1366
1588
|
setupPreValidationTimer(nextSlot);
|
|
1367
|
-
node.log(`Next slot at ${nextSlot.
|
|
1589
|
+
node.log(`Next slot at ${nextSlot.start}`);
|
|
1368
1590
|
}
|
|
1369
1591
|
}
|
|
1370
1592
|
}
|
|
@@ -1527,6 +1749,25 @@ module.exports = function (RED) {
|
|
|
1527
1749
|
updateNextPollTime(); // Set initial next poll time
|
|
1528
1750
|
setTimeout(fetchData, 1000);
|
|
1529
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
|
+
|
|
1530
1771
|
node.on('close', () => {
|
|
1531
1772
|
clearInterval(pollIntervalHandle);
|
|
1532
1773
|
// Clear any pending retry timeouts
|
|
@@ -1542,6 +1783,7 @@ module.exports = function (RED) {
|
|
|
1542
1783
|
clearTimeout(cooldownExpiryTimer);
|
|
1543
1784
|
cooldownExpiryTimer = null;
|
|
1544
1785
|
}
|
|
1786
|
+
if (node._v2Scheduler) node._v2Scheduler.stop();
|
|
1545
1787
|
if (node.broker) node.broker.unsubscribe(cmdTopicLimit, cmdTopicTime, cmdTopicSubmit, cmdTopicRefresh, cmdTopicTimezone, cmdTopicSmartCharging);
|
|
1546
1788
|
});
|
|
1547
1789
|
}
|