iobroker.nexowatt-ui 0.7.38 → 0.7.41
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/ems/modules/ai-advisor.js +806 -290
- package/io-package.json +18 -2
- package/main.js +117 -42
- package/package.json +1 -1
- package/www/app.js +147 -25
- package/www/cockpit-shell.js +16 -0
- package/www/ems-apps.html +93 -30
- package/www/ems-apps.js +144 -13
- package/www/evcs-report.js +6 -4
- package/www/evcs.js +22 -9
- package/www/history.js +12 -9
- package/www/index.html +3 -3
- package/www/logic.js +14 -4
- package/www/manifest.webmanifest +1 -1
- package/www/report-common.js +6 -4
- package/www/settings.html +49 -1
- package/www/smarthome.js +12 -4
- package/www/storagefarm.js +8 -4
- package/www/styles.css +27 -0
- package/www/sw.js +1 -1
- package/www/year-report.js +9 -6
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
const { BaseModule } = require('./base');
|
|
@@ -17,8 +18,8 @@ function bool(v, fallback = false) {
|
|
|
17
18
|
if (v === true || v === 1 || v === '1') return true;
|
|
18
19
|
if (v === false || v === 0 || v === '0') return false;
|
|
19
20
|
const s = String(v === null || v === undefined ? '' : v).trim().toLowerCase();
|
|
20
|
-
if (['true', 'on', 'yes', 'ja', 'active', 'an'].includes(s)) return true;
|
|
21
|
-
if (['false', 'off', 'no', 'nein', 'inactive', 'aus'].includes(s)) return false;
|
|
21
|
+
if (['true', 'on', 'yes', 'ja', 'active', 'aktiv', 'an'].includes(s)) return true;
|
|
22
|
+
if (['false', 'off', 'no', 'nein', 'inactive', 'inaktiv', 'aus'].includes(s)) return false;
|
|
22
23
|
return !!fallback;
|
|
23
24
|
}
|
|
24
25
|
|
|
@@ -34,9 +35,11 @@ function round(v, digits = 0) {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
function makeHash(obj) {
|
|
37
|
-
try { return JSON.stringify(obj); } catch { return String(Date.now()); }
|
|
38
|
+
try { return JSON.stringify(obj); } catch (_e) { return String(Date.now()); }
|
|
38
39
|
}
|
|
39
40
|
|
|
41
|
+
function pad2(v) { return String(Math.max(0, Math.round(Number(v) || 0))).padStart(2, '0'); }
|
|
42
|
+
|
|
40
43
|
function formatKw(w) {
|
|
41
44
|
const n = Number(w);
|
|
42
45
|
if (!Number.isFinite(n)) return '—';
|
|
@@ -59,6 +62,93 @@ function formatPrice(eurKwh) {
|
|
|
59
62
|
return n.toFixed(3) + ' €/kWh';
|
|
60
63
|
}
|
|
61
64
|
|
|
65
|
+
function formatPct(v, digits = 0) {
|
|
66
|
+
const n = Number(v);
|
|
67
|
+
if (!Number.isFinite(n)) return '—';
|
|
68
|
+
return n.toFixed(Math.max(0, Math.min(2, Math.round(Number(digits) || 0)))) + ' %';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function formatTemp(v) {
|
|
72
|
+
const n = Number(v);
|
|
73
|
+
if (!Number.isFinite(n)) return '—';
|
|
74
|
+
return n.toFixed(Math.abs(n) < 10 ? 1 : 0) + ' °C';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function textContainsAny(value, needles) {
|
|
78
|
+
const hay = String(value || '').toLowerCase();
|
|
79
|
+
return (Array.isArray(needles) ? needles : []).some((needle) => hay.includes(String(needle).toLowerCase()));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function weatherLine(text, minC, maxC, precipPct) {
|
|
83
|
+
const parts = [];
|
|
84
|
+
if (text) parts.push(String(text));
|
|
85
|
+
if (Number.isFinite(Number(minC)) || Number.isFinite(Number(maxC))) parts.push(`${formatTemp(minC)}–${formatTemp(maxC)}`);
|
|
86
|
+
if (Number.isFinite(Number(precipPct))) parts.push(`Regenrisiko ${formatPct(precipPct)}`);
|
|
87
|
+
return parts.filter(Boolean).join(', ');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function buildWeatherSummary(s) {
|
|
91
|
+
if (!s || !s.weatherEnabled) return 'Wetterprognose deaktiviert.';
|
|
92
|
+
const parts = [];
|
|
93
|
+
const today = [];
|
|
94
|
+
if (s.weatherText) today.push(String(s.weatherText));
|
|
95
|
+
if (finiteNumber(s.weatherTempC)) today.push(formatTemp(s.weatherTempC));
|
|
96
|
+
if (finiteNumber(s.weatherCloudPct)) today.push(`Bewölkung ${formatPct(s.weatherCloudPct)}`);
|
|
97
|
+
if (finiteNumber(s.weatherWindKmh)) today.push(`Wind ${Math.round(s.weatherWindKmh)} km/h`);
|
|
98
|
+
if (today.length) parts.push(`Heute: ${today.join(', ')}`);
|
|
99
|
+
const tomorrow = weatherLine(s.weatherTomorrowText, s.weatherTomorrowMinC, s.weatherTomorrowMaxC, s.weatherTomorrowPrecipPct);
|
|
100
|
+
if (tomorrow) parts.push(`Morgen: ${tomorrow}`);
|
|
101
|
+
return parts.join(' · ') || 'Wetterprognose aktiv.';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isPeakShavingConfigured(config) {
|
|
105
|
+
const cfg = (config && typeof config === 'object') ? config : {};
|
|
106
|
+
if (cfg.enablePeakShaving === true) return true;
|
|
107
|
+
const ps = (cfg.peakShaving && typeof cfg.peakShaving === 'object') ? cfg.peakShaving : {};
|
|
108
|
+
const atypical = (ps.atypical && typeof ps.atypical === 'object') ? ps.atypical : {};
|
|
109
|
+
return ps.enabled === true || atypical.enabled === true;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
const EVCS_MAPPING_FIELDS = [
|
|
114
|
+
'powerId', 'energyTotalId', 'energySessionId', 'statusId', 'activeId', 'modeId', 'onlineId',
|
|
115
|
+
'setCurrentAId', 'setPowerWId', 'enableWriteId', 'lockWriteId', 'rfidReadId', 'vehicleSocId',
|
|
116
|
+
];
|
|
117
|
+
|
|
118
|
+
function evcsRowHasMapping(row) {
|
|
119
|
+
const r = (row && typeof row === 'object') ? row : {};
|
|
120
|
+
return EVCS_MAPPING_FIELDS.some((key) => String(r[key] === null || r[key] === undefined ? '' : r[key]).trim().length > 0);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function inferEvcsAvailable(adapter, settingsCfg) {
|
|
124
|
+
const cfg = (adapter && adapter.config && typeof adapter.config === 'object') ? adapter.config : {};
|
|
125
|
+
const sc = (settingsCfg && typeof settingsCfg === 'object') ? settingsCfg : ((cfg.settingsConfig && typeof cfg.settingsConfig === 'object') ? cfg.settingsConfig : {});
|
|
126
|
+
if (typeof sc.evcsAvailable === 'boolean') return sc.evcsAvailable;
|
|
127
|
+
const lists = [];
|
|
128
|
+
if (Array.isArray(sc.evcsList)) lists.push(sc.evcsList);
|
|
129
|
+
if (Array.isArray(adapter && adapter.evcsList)) lists.push(adapter.evcsList);
|
|
130
|
+
if (Array.isArray(cfg.evcsList)) lists.push(cfg.evcsList);
|
|
131
|
+
if (cfg.chargingManagement && Array.isArray(cfg.chargingManagement.wallboxes)) lists.push(cfg.chargingManagement.wallboxes);
|
|
132
|
+
if (lists.some((list) => list.some(evcsRowHasMapping))) return true;
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function evcsPhrase(hasEvcs, withArticle = true) {
|
|
137
|
+
return hasEvcs ? (withArticle ? 'EV-Laden, Heizstab und andere flexible Lasten' : 'EV-Laden, Heizstab und andere flexible Verbraucher') : (withArticle ? 'Heizstab und andere flexible Lasten' : 'Heizstab und andere flexible Verbraucher');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function buildPeakStateText(s, limitW, usagePct) {
|
|
141
|
+
const statusRaw = String(s && s.peakStatus || '').trim();
|
|
142
|
+
const suffix = statusRaw ? ` · Status ${statusRaw}` : '';
|
|
143
|
+
if (!limitW || !Number.isFinite(Number(limitW)) || Number(limitW) <= 0) {
|
|
144
|
+
return (s && s.peakConfigured ? 'Lastspitzenkappung bereit, aber kein Netzanschlusslimit verfügbar.' : 'Lastspitzenkappung nicht konfiguriert.') + suffix;
|
|
145
|
+
}
|
|
146
|
+
const state = s && s.peakActive
|
|
147
|
+
? 'Lastspitzenkappung aktiv'
|
|
148
|
+
: (s && s.peakConfigured ? 'Lastspitzenkappung bereit' : 'Lastspitzenkappung nicht konfiguriert');
|
|
149
|
+
return `${formatKw(s && s.gridImportW)} von ${formatKw(limitW)} (${formatPct(usagePct)}) · ${state}${suffix}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
62
152
|
function shortIsoWindow(from, to) {
|
|
63
153
|
const f = String(from || '').trim();
|
|
64
154
|
const t = String(to || '').trim();
|
|
@@ -66,7 +156,6 @@ function shortIsoWindow(from, to) {
|
|
|
66
156
|
if (!s) return '';
|
|
67
157
|
const d = new Date(s);
|
|
68
158
|
if (Number.isNaN(d.getTime())) return s;
|
|
69
|
-
const pad2 = (n) => String(n).padStart(2, '0');
|
|
70
159
|
const today = new Date();
|
|
71
160
|
const sameDay = d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate();
|
|
72
161
|
const tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
|
|
@@ -78,12 +167,146 @@ function shortIsoWindow(from, to) {
|
|
|
78
167
|
return fmt(f) || fmt(t) || '';
|
|
79
168
|
}
|
|
80
169
|
|
|
170
|
+
function parseClockMinutes(value, fallback = null) {
|
|
171
|
+
const raw = String(value === null || value === undefined ? '' : value).trim();
|
|
172
|
+
const m = raw.match(/^(\d{1,2})(?::(\d{1,2}))?$/);
|
|
173
|
+
if (!m) return fallback;
|
|
174
|
+
const h = Number(m[1]);
|
|
175
|
+
const min = Number(m[2] || 0);
|
|
176
|
+
if (!Number.isFinite(h) || !Number.isFinite(min) || h < 0 || h > 23 || min < 0 || min > 59) return fallback;
|
|
177
|
+
return h * 60 + min;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function minutesUntilClock(value, now = new Date()) {
|
|
181
|
+
const target = parseClockMinutes(value, null);
|
|
182
|
+
if (target === null) return null;
|
|
183
|
+
const current = now.getHours() * 60 + now.getMinutes();
|
|
184
|
+
let diff = target - current;
|
|
185
|
+
if (diff <= 0) diff += 1440;
|
|
186
|
+
return diff;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function formatClockMinutes(totalMinutes) {
|
|
190
|
+
const n = ((Math.round(Number(totalMinutes) || 0) % 1440) + 1440) % 1440;
|
|
191
|
+
return `${pad2(Math.floor(n / 60))}:${pad2(n % 60)}`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function formatDurationMinutes(minutes) {
|
|
195
|
+
const n = Math.max(0, Math.round(Number(minutes) || 0));
|
|
196
|
+
if (n < 90) return `${n} min`;
|
|
197
|
+
return `${Math.floor(n / 60)} h ${String(n % 60).padStart(2, '0')} min`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function formatClockMs(ms) {
|
|
201
|
+
const n = Number(ms);
|
|
202
|
+
if (!Number.isFinite(n) || n <= 0) return '—';
|
|
203
|
+
const d = new Date(n);
|
|
204
|
+
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function tsToShortWindow(ts) {
|
|
208
|
+
const n = Number(ts);
|
|
209
|
+
if (!Number.isFinite(n) || n <= 0) return '';
|
|
210
|
+
const d = new Date(n);
|
|
211
|
+
const now = new Date();
|
|
212
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
|
213
|
+
const target = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
|
214
|
+
const day = target === today ? 'heute' : (target === today + 86400000 ? 'morgen' : `${pad2(d.getDate())}.${pad2(d.getMonth() + 1)}.`);
|
|
215
|
+
return `${day} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function formatWindowHour(hour) {
|
|
219
|
+
const h = ((Math.round(Number(hour) || 0) % 24) + 24) % 24;
|
|
220
|
+
return `${pad2(h)}:00–${pad2((h + 1) % 24)}:00`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function isInsideClockWindow(nowMs, startValue, endValue) {
|
|
224
|
+
const d = new Date(Number(nowMs) || Date.now());
|
|
225
|
+
const now = d.getHours() * 60 + d.getMinutes();
|
|
226
|
+
const start = parseClockMinutes(startValue, null);
|
|
227
|
+
const end = parseClockMinutes(endValue, null);
|
|
228
|
+
if (start === null || end === null || start === end) return false;
|
|
229
|
+
if (start < end) return now >= start && now < end;
|
|
230
|
+
return now >= start || now < end;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function seasonFromDate(now = new Date()) {
|
|
234
|
+
const month = (now instanceof Date ? now : new Date(now)).getMonth() + 1;
|
|
235
|
+
if (month === 12 || month <= 2) return 'winter';
|
|
236
|
+
if (month >= 3 && month <= 5) return 'spring';
|
|
237
|
+
if (month >= 6 && month <= 8) return 'summer';
|
|
238
|
+
return 'autumn';
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function seasonLabel(season) {
|
|
242
|
+
const s = String(season || '').toLowerCase();
|
|
243
|
+
if (s === 'winter') return 'Winter';
|
|
244
|
+
if (s === 'spring') return 'Frühjahr';
|
|
245
|
+
if (s === 'summer') return 'Sommer';
|
|
246
|
+
if (s === 'autumn') return 'Herbst';
|
|
247
|
+
return 'Saison';
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function normalizeOptimizationMode(value) {
|
|
251
|
+
const s = String(value || 'balanced').trim().toLowerCase();
|
|
252
|
+
if (['cost', 'kosten', 'preis'].includes(s)) return 'cost';
|
|
253
|
+
if (['autarky', 'autarkie', 'self', 'eigenverbrauch'].includes(s)) return 'autarky';
|
|
254
|
+
if (['co2', 'co₂', 'carbon', 'klima'].includes(s)) return 'co2';
|
|
255
|
+
if (['comfort', 'komfort'].includes(s)) return 'comfort';
|
|
256
|
+
if (['peak', 'netz', 'lastspitze'].includes(s)) return 'peak';
|
|
257
|
+
return 'balanced';
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function optimizationModeLabel(mode) {
|
|
261
|
+
const m = normalizeOptimizationMode(mode);
|
|
262
|
+
if (m === 'cost') return 'Kosten';
|
|
263
|
+
if (m === 'autarky') return 'Autarkie';
|
|
264
|
+
if (m === 'co2') return 'CO₂';
|
|
265
|
+
if (m === 'comfort') return 'Komfort';
|
|
266
|
+
if (m === 'peak') return 'Peak-Schutz';
|
|
267
|
+
return 'Balance';
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function average(list, field) {
|
|
271
|
+
const vals = (Array.isArray(list) ? list : []).map((x) => field ? Number(x && x[field]) : Number(x)).filter(Number.isFinite);
|
|
272
|
+
if (!vals.length) return null;
|
|
273
|
+
return vals.reduce((a, b) => a + b, 0) / vals.length;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function percentile(list, field, pct) {
|
|
277
|
+
const vals = (Array.isArray(list) ? list : []).map((x) => field ? Number(x && x[field]) : Number(x)).filter(Number.isFinite).sort((a, b) => a - b);
|
|
278
|
+
if (!vals.length) return null;
|
|
279
|
+
const idx = Math.max(0, Math.min(vals.length - 1, Math.round((vals.length - 1) * (Number(pct) || 0))));
|
|
280
|
+
return vals[idx];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function safeJson(value, fallback) {
|
|
284
|
+
try { return JSON.stringify(value); } catch (_e) { return fallback; }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function toSafeIdPart(value) {
|
|
288
|
+
return String(value === null || value === undefined ? '' : value)
|
|
289
|
+
.trim()
|
|
290
|
+
.toLowerCase()
|
|
291
|
+
.replace(/[^a-z0-9_-]+/g, '_')
|
|
292
|
+
.replace(/^_+|_+$/g, '');
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function priorityText(priorities, options = {}) {
|
|
296
|
+
const labels = { evcs: 'Wallbox', thermal: 'Thermik', heatingRod: 'Heizstab', storage: 'Speicherreserve', generic: 'sonstige Lasten' };
|
|
297
|
+
const hasEvcs = options && options.hasEvcs !== false;
|
|
298
|
+
const entries = Object.keys(labels)
|
|
299
|
+
.filter((key) => hasEvcs || key !== 'evcs')
|
|
300
|
+
.map((key) => ({ key, label: labels[key], value: Number(priorities && priorities[key]) || 0 }))
|
|
301
|
+
.filter((x) => x.value > 0)
|
|
302
|
+
.sort((a, b) => b.value - a.value);
|
|
303
|
+
if (!entries.length) return 'Prioritäten prüfen';
|
|
304
|
+
return entries.slice(0, 5).map((x, i) => `${i + 1}. ${x.label}`).join(' · ');
|
|
305
|
+
}
|
|
306
|
+
|
|
81
307
|
/**
|
|
82
308
|
* KI-Energieberater / AI Advisor.
|
|
83
|
-
*
|
|
84
|
-
* This is intentionally advisory-only in the ioBroker UI adapter. It never writes
|
|
85
|
-
* actuator setpoints and only publishes ranked optimization recommendations for
|
|
86
|
-
* the VIS and later reporting/analytics layers.
|
|
309
|
+
* Advisory-only: no actuator setpoints are written here.
|
|
87
310
|
*/
|
|
88
311
|
class AiAdvisorModule extends BaseModule {
|
|
89
312
|
constructor(adapter, dpRegistry) {
|
|
@@ -92,36 +315,55 @@ class AiAdvisorModule extends BaseModule {
|
|
|
92
315
|
this._lastRunMs = 0;
|
|
93
316
|
this._lastHash = '';
|
|
94
317
|
this._lastDisabledWriteMs = 0;
|
|
318
|
+
this._samples = [];
|
|
319
|
+
this._peakHourBuckets = Array.from({ length: 24 }, () => 0);
|
|
320
|
+
this._forecastChecks = [];
|
|
321
|
+
this._forecastQualityPct = null;
|
|
322
|
+
this._forecastQualityText = '';
|
|
323
|
+
this._lastLearning = { anomaly: false, anomalyText: '', forecastQualityPct: null, peakLearningText: '' };
|
|
324
|
+
this._lastPlan = { mode: 'balanced', items: [], text: '' };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
_cachedValue(id, fallback) {
|
|
328
|
+
try {
|
|
329
|
+
const rec = this.adapter && this.adapter.stateCache ? this.adapter.stateCache[id] : null;
|
|
330
|
+
if (rec && Object.prototype.hasOwnProperty.call(rec, 'value') && rec.value !== undefined && rec.value !== null && String(rec.value).trim() !== '') return rec.value;
|
|
331
|
+
} catch (_e) {}
|
|
332
|
+
return fallback;
|
|
95
333
|
}
|
|
96
334
|
|
|
97
335
|
_cfg() {
|
|
98
|
-
const c = (this.adapter && this.adapter.config && this.adapter.config.aiAdvisor && typeof this.adapter.config.aiAdvisor === 'object')
|
|
99
|
-
? this.adapter.config.aiAdvisor
|
|
100
|
-
: {};
|
|
336
|
+
const c = (this.adapter && this.adapter.config && this.adapter.config.aiAdvisor && typeof this.adapter.config.aiAdvisor === 'object') ? this.adapter.config.aiAdvisor : {};
|
|
101
337
|
const cats = (c.categories && typeof c.categories === 'object') ? c.categories : {};
|
|
338
|
+
const prioCfg = (c.priorities && typeof c.priorities === 'object') ? c.priorities : {};
|
|
102
339
|
const minPriority = String(c.minPriority || 'info').trim().toLowerCase();
|
|
103
|
-
|
|
104
|
-
try {
|
|
105
|
-
const rec = this.adapter && this.adapter.stateCache ? this.adapter.stateCache['settings.aiAdvisorEnabled'] : null;
|
|
106
|
-
customerEnabled = bool(rec && Object.prototype.hasOwnProperty.call(rec, 'value') ? rec.value : true, true);
|
|
107
|
-
} catch (_e) {
|
|
108
|
-
customerEnabled = true;
|
|
109
|
-
}
|
|
340
|
+
const customerEnabled = bool(this._cachedValue('settings.aiAdvisorEnabled', true), true);
|
|
110
341
|
const configuredEnabled = c.enabled !== false;
|
|
111
342
|
const showOnLiveCfg = (c.showInLive !== undefined) ? c.showInLive : c.showOnLive;
|
|
343
|
+
const optimizationMode = normalizeOptimizationMode(this._cachedValue('settings.aiAdvisorMode', this._cachedValue('settings.aiAdvisorOptimizationMode', c.optimizationMode || c.mode || 'balanced')));
|
|
344
|
+
const dailyPlanEnabled = c.dailyPlanEnabled !== false && c.dayPlanEnabled !== false;
|
|
345
|
+
const learningEnabled = c.learningEnabled !== false && c.peakLearningEnabled !== false;
|
|
346
|
+
const seasonLogicEnabled = c.seasonLogicEnabled !== false && c.seasonalStrategyEnabled !== false;
|
|
347
|
+
const priorityStorage = clamp(num(this._cachedValue('settings.aiAdvisorPriorityStorage', c.priorityStorage ?? prioCfg.storage ?? 90), 90), 1, 100);
|
|
348
|
+
const priorityEvcs = clamp(num(this._cachedValue('settings.aiAdvisorPriorityEvcs', c.priorityEvcs ?? prioCfg.evcs ?? 80), 80), 1, 100);
|
|
349
|
+
const priorityThermal = clamp(num(this._cachedValue('settings.aiAdvisorPriorityThermal', c.priorityThermal ?? prioCfg.thermal ?? 60), 60), 1, 100);
|
|
350
|
+
const priorityHeatingRod = clamp(num(this._cachedValue('settings.aiAdvisorPriorityHeatingRod', c.priorityHeatingRod ?? prioCfg.heatingRod ?? 45), 45), 1, 100);
|
|
351
|
+
const priorityGeneric = clamp(num(this._cachedValue('settings.aiAdvisorPriorityGeneric', c.priorityGeneric ?? prioCfg.generic ?? 40), 40), 1, 100);
|
|
112
352
|
return {
|
|
113
353
|
enabled: configuredEnabled && customerEnabled,
|
|
114
354
|
customerEnabled,
|
|
115
355
|
configuredEnabled,
|
|
116
356
|
advisoryOnly: true,
|
|
117
357
|
showInLive: showOnLiveCfg !== false,
|
|
118
|
-
|
|
119
|
-
// Keep legacy/canonical aliases as well so older configs remain valid.
|
|
358
|
+
optimizationMode,
|
|
120
359
|
minIntervalSec: clamp(num(c.minIntervalSec ?? c.intervalSec, 60), 10, 3600),
|
|
121
|
-
maxSuggestions: clamp(num(c.maxSuggestions,
|
|
360
|
+
maxSuggestions: clamp(num(c.maxSuggestions, 6), 1, 10),
|
|
122
361
|
minPriority: ['info', 'warning', 'action', 'critical'].includes(minPriority) ? minPriority : 'info',
|
|
123
362
|
pvSurplusThresholdW: clamp(num(c.pvSurplusThresholdW ?? c.exportHighW, 1500), 0, 1000000),
|
|
124
363
|
highImportThresholdW: clamp(num(c.highImportThresholdW ?? c.importHighW, 3000), 0, 10000000),
|
|
364
|
+
peakNearLimitPct: clamp(num(c.peakNearLimitPct ?? c.peakConnectionUsageWarnPct ?? c.gridConnectionWarnPct, 90), 50, 100),
|
|
365
|
+
peakCriticalLimitPct: clamp(num(c.peakCriticalLimitPct ?? c.peakConnectionUsageCriticalPct ?? c.gridConnectionCriticalPct, 98), 90, 120),
|
|
366
|
+
weatherRainRiskPct: clamp(num(c.weatherRainRiskPct ?? c.weatherRainProbabilityPct, 60), 0, 100),
|
|
125
367
|
lowSocPct: clamp(num(c.lowSocPct, 25), 0, 100),
|
|
126
368
|
highSocPct: clamp(num(c.highSocPct, 85), 0, 100),
|
|
127
369
|
minSocForDischargePct: clamp(num(c.minSocForDischargePct, 35), 0, 100),
|
|
@@ -131,13 +373,50 @@ class AiAdvisorModule extends BaseModule {
|
|
|
131
373
|
expensivePriceMarginEurKwh: clamp(num(c.expensivePriceMarginEurKwh, 0.05), 0, 10),
|
|
132
374
|
staleTimeoutSec: clamp(num(c.staleTimeoutSec, 300), 30, 86400),
|
|
133
375
|
includeInstallerHints: c.includeInstallerHints !== false,
|
|
376
|
+
dailyPlanEnabled,
|
|
377
|
+
dayPlanEnabled: dailyPlanEnabled,
|
|
378
|
+
evGoalPlanningEnabled: c.evGoalPlanningEnabled !== false && c.evGoalEnabled !== false,
|
|
379
|
+
storageStrategyEnabled: c.storageStrategyEnabled !== false,
|
|
380
|
+
learningEnabled,
|
|
381
|
+
peakLearningEnabled: learningEnabled,
|
|
382
|
+
anomalyDetectionEnabled: c.anomalyDetectionEnabled !== false,
|
|
383
|
+
forecastQualityEnabled: c.forecastQualityEnabled !== false,
|
|
384
|
+
seasonLogicEnabled,
|
|
385
|
+
seasonalStrategyEnabled: seasonLogicEnabled,
|
|
386
|
+
comfortHintsEnabled: c.comfortHintsEnabled !== false && c.comfortWindowsEnabled !== false,
|
|
387
|
+
co2HintsEnabled: c.co2HintsEnabled !== false && c.co2Enabled !== false,
|
|
388
|
+
comfortStart: String(this._cachedValue('settings.aiAdvisorComfortStart', c.comfortStart || '06:00') || '06:00'),
|
|
389
|
+
comfortEnd: String(this._cachedValue('settings.aiAdvisorComfortEnd', c.comfortEnd || '22:00') || '22:00'),
|
|
390
|
+
quietHoursStart: String(this._cachedValue('settings.aiAdvisorQuietHoursStart', c.quietHoursStart || '22:00') || '22:00'),
|
|
391
|
+
quietHoursEnd: String(this._cachedValue('settings.aiAdvisorQuietHoursEnd', c.quietHoursEnd || '06:00') || '06:00'),
|
|
392
|
+
evReadyBy: String(this._cachedValue('settings.aiAdvisorEvReadyBy', c.evReadyBy || c.evDepartureTime || '07:00') || '07:00'),
|
|
393
|
+
evTargetSocPct: clamp(num(this._cachedValue('settings.aiAdvisorEvTargetSocPct', c.evTargetSocPct ?? c.defaultEvTargetSocPct ?? 80), 80), 20, 100),
|
|
394
|
+
evBatteryCapacityKwh: clamp(num(c.evBatteryCapacityKwh, 60), 10, 250),
|
|
395
|
+
thermalReadyBy: String(this._cachedValue('settings.aiAdvisorThermalReadyBy', c.thermalReadyBy || c.warmWaterReadyBy || '18:00') || '18:00'),
|
|
396
|
+
anomalyMinSamples: clamp(num(c.anomalyMinSamples, 12), 4, 10000),
|
|
397
|
+
anomalyFactor: clamp(num(c.anomalyFactor ?? c.anomalyMultiplier, 2.2), 1.1, 20),
|
|
398
|
+
anomalyMinImportW: clamp(num(c.anomalyMinImportW ?? c.anomalyHighLoadW, 5000), 0, 100000000),
|
|
399
|
+
anomalyHighLoadW: clamp(num(c.anomalyHighLoadW ?? c.anomalyMinImportW, 5500), 500, 100000000),
|
|
400
|
+
nightBaseLoadW: clamp(num(c.nightBaseLoadW, 900), 100, 100000000),
|
|
401
|
+
evUrgentRemainingMin: clamp(num(c.evUrgentRemainingMin, 90), 15, 1440),
|
|
402
|
+
forecastQualityWarnPct: clamp(num(c.forecastQualityWarnPct, 65), 0, 100),
|
|
403
|
+
co2LowGPerKwh: clamp(num(c.co2LowGPerKwh, 250), 0, 2000),
|
|
404
|
+
co2HighGPerKwh: clamp(num(c.co2HighGPerKwh, 500), 0, 2000),
|
|
405
|
+
priorities: { storage: priorityStorage, evcs: priorityEvcs, thermal: priorityThermal, heatingRod: priorityHeatingRod, generic: priorityGeneric },
|
|
134
406
|
categories: {
|
|
135
407
|
tariff: cats.tariff !== false,
|
|
136
408
|
pv: cats.pv !== false,
|
|
137
409
|
storage: cats.storage !== false,
|
|
138
410
|
evcs: cats.evcs !== false,
|
|
139
411
|
peak: cats.peak !== false,
|
|
412
|
+
weather: cats.weather !== false,
|
|
140
413
|
heating: cats.heating !== false,
|
|
414
|
+
plan: cats.plan !== false && cats.dailyPlan !== false,
|
|
415
|
+
dailyPlan: cats.dailyPlan !== false && cats.plan !== false,
|
|
416
|
+
anomaly: cats.anomaly !== false,
|
|
417
|
+
comfort: cats.comfort !== false,
|
|
418
|
+
learning: cats.learning !== false,
|
|
419
|
+
co2: cats.co2 !== false,
|
|
141
420
|
system: cats.system !== false,
|
|
142
421
|
},
|
|
143
422
|
};
|
|
@@ -151,37 +430,18 @@ class AiAdvisorModule extends BaseModule {
|
|
|
151
430
|
|
|
152
431
|
async _ensureStates() {
|
|
153
432
|
const a = this.adapter;
|
|
154
|
-
await a.setObjectNotExistsAsync('aiAdvisor', {
|
|
155
|
-
|
|
156
|
-
common: { name: 'KI-Energieberater' },
|
|
157
|
-
native: {},
|
|
158
|
-
});
|
|
159
|
-
|
|
160
|
-
await a.setObjectNotExistsAsync('aiAdvisor.suggestions', {
|
|
161
|
-
type: 'channel',
|
|
162
|
-
common: { name: 'KI-Energieberater Vorschläge' },
|
|
163
|
-
native: {},
|
|
164
|
-
});
|
|
165
|
-
|
|
433
|
+
await a.setObjectNotExistsAsync('aiAdvisor', { type: 'channel', common: { name: 'KI-Energieberater' }, native: {} });
|
|
434
|
+
await a.setObjectNotExistsAsync('aiAdvisor.suggestions', { type: 'channel', common: { name: 'KI-Energieberater Vorschläge' }, native: {} });
|
|
166
435
|
const mk = async (id, name, type, role, unit = undefined) => {
|
|
167
436
|
await a.setObjectNotExistsAsync(id, {
|
|
168
437
|
type: 'state',
|
|
169
|
-
common: {
|
|
170
|
-
name,
|
|
171
|
-
type,
|
|
172
|
-
role,
|
|
173
|
-
read: true,
|
|
174
|
-
write: false,
|
|
175
|
-
...(unit ? { unit } : {}),
|
|
176
|
-
},
|
|
438
|
+
common: { name, type, role, read: true, write: false, ...(unit ? { unit } : {}) },
|
|
177
439
|
native: {},
|
|
178
440
|
});
|
|
179
441
|
};
|
|
180
|
-
|
|
181
442
|
await mk('aiAdvisor.enabled', 'KI-Energieberater aktiv', 'boolean', 'indicator');
|
|
182
443
|
await mk('aiAdvisor.advisoryOnly', 'Nur Beratung, keine Schaltentscheidungen', 'boolean', 'indicator');
|
|
183
444
|
await mk('aiAdvisor.showInLive', 'In LIVE anzeigen', 'boolean', 'indicator');
|
|
184
|
-
// Compatibility alias: App-Center and older VIS builds used "showOnLive".
|
|
185
445
|
await mk('aiAdvisor.showOnLive', 'In LIVE anzeigen', 'boolean', 'indicator');
|
|
186
446
|
await mk('aiAdvisor.status', 'Status', 'string', 'text');
|
|
187
447
|
await mk('aiAdvisor.severity', 'Höchste Priorität / Severity', 'string', 'text');
|
|
@@ -189,21 +449,33 @@ class AiAdvisorModule extends BaseModule {
|
|
|
189
449
|
await mk('aiAdvisor.summary', 'Zusammenfassung', 'string', 'text');
|
|
190
450
|
await mk('aiAdvisor.count', 'Anzahl Vorschläge', 'number', 'value');
|
|
191
451
|
await mk('aiAdvisor.score', 'Optimierungs-Score', 'number', 'value', '%');
|
|
452
|
+
await mk('aiAdvisor.peakUsagePct', 'Netzanschluss-Auslastung', 'number', 'value', '%');
|
|
453
|
+
await mk('aiAdvisor.peakStateText', 'Peak-Shaving Status', 'string', 'text');
|
|
454
|
+
await mk('aiAdvisor.gridConnectionLimitW', 'Netzanschlusslimit', 'number', 'value.power', 'W');
|
|
455
|
+
await mk('aiAdvisor.peakWarnThresholdW', 'Peak-Vorwarnschwelle', 'number', 'value.power', 'W');
|
|
456
|
+
await mk('aiAdvisor.weatherSummary', 'Wetter-Prognose Zusammenfassung', 'string', 'text');
|
|
457
|
+
await mk('aiAdvisor.dailyPlanText', 'KI-Tagesfahrplan Text', 'string', 'text');
|
|
458
|
+
await mk('aiAdvisor.dailyPlanJson', 'KI-Tagesfahrplan JSON', 'string', 'json');
|
|
459
|
+
await mk('aiAdvisor.evPlanText', 'EV-Zielplanung Text', 'string', 'text');
|
|
460
|
+
await mk('aiAdvisor.optimizationMode', 'Optimierungsziel', 'string', 'text');
|
|
461
|
+
await mk('aiAdvisor.comfortWindowSummary', 'Komfortfenster Zusammenfassung', 'string', 'text');
|
|
462
|
+
await mk('aiAdvisor.season', 'Saisonlogik', 'string', 'text');
|
|
463
|
+
await mk('aiAdvisor.anomalyText', 'Anomalie-Erkennung Text', 'string', 'text');
|
|
464
|
+
await mk('aiAdvisor.forecastQualityPct', 'Prognosequalität', 'number', 'value', '%');
|
|
465
|
+
await mk('aiAdvisor.forecastQualityText', 'Prognosequalität Text', 'string', 'text');
|
|
466
|
+
await mk('aiAdvisor.peakLearningText', 'Lastspitzen-Lernfunktion Text', 'string', 'text');
|
|
467
|
+
await mk('aiAdvisor.peakLearningJson', 'Lastspitzen-Lernfunktion JSON', 'string', 'json');
|
|
192
468
|
await mk('aiAdvisor.topTitle', 'Top-Vorschlag Titel', 'string', 'text');
|
|
193
469
|
await mk('aiAdvisor.topText', 'Top-Vorschlag Text', 'string', 'text');
|
|
194
470
|
await mk('aiAdvisor.topAction', 'Top-Vorschlag Handlung', 'string', 'text');
|
|
195
471
|
await mk('aiAdvisor.topWindow', 'Top-Vorschlag Zeitfenster', 'string', 'text');
|
|
472
|
+
await mk('aiAdvisor.topCategory', 'Top-Vorschlag Kategorie', 'string', 'text');
|
|
196
473
|
await mk('aiAdvisor.suggestionsJson', 'Vorschläge JSON', 'string', 'json');
|
|
197
474
|
await mk('aiAdvisor.snapshotJson', 'KI-Energieberater Snapshot JSON', 'string', 'json');
|
|
198
475
|
await mk('aiAdvisor.lastUpdate', 'Letzte Aktualisierung', 'number', 'value.time');
|
|
199
476
|
await mk('aiAdvisor.nextUpdate', 'Nächste Aktualisierung', 'number', 'value.time');
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
await a.setObjectNotExistsAsync(`aiAdvisor.suggestions.${i}`, {
|
|
203
|
-
type: 'channel',
|
|
204
|
-
common: { name: `Vorschlag ${i}` },
|
|
205
|
-
native: {},
|
|
206
|
-
});
|
|
477
|
+
for (let i = 1; i <= 8; i++) {
|
|
478
|
+
await a.setObjectNotExistsAsync(`aiAdvisor.suggestions.${i}`, { type: 'channel', common: { name: `Vorschlag ${i}` }, native: {} });
|
|
207
479
|
await mk(`aiAdvisor.suggestions.${i}.title`, `Vorschlag ${i} Titel`, 'string', 'text');
|
|
208
480
|
await mk(`aiAdvisor.suggestions.${i}.text`, `Vorschlag ${i} Text`, 'string', 'text');
|
|
209
481
|
await mk(`aiAdvisor.suggestions.${i}.action`, `Vorschlag ${i} Handlung`, 'string', 'text');
|
|
@@ -256,6 +528,60 @@ class AiAdvisorModule extends BaseModule {
|
|
|
256
528
|
return fallback;
|
|
257
529
|
}
|
|
258
530
|
|
|
531
|
+
_chargingWallboxKeys() {
|
|
532
|
+
const keys = [];
|
|
533
|
+
try {
|
|
534
|
+
const cfg = (this.adapter && this.adapter.config && this.adapter.config.chargingManagement && typeof this.adapter.config.chargingManagement === 'object') ? this.adapter.config.chargingManagement : {};
|
|
535
|
+
const list = Array.isArray(cfg.wallboxes) ? cfg.wallboxes : [];
|
|
536
|
+
for (let i = 0; i < list.length; i++) {
|
|
537
|
+
const wb = list[i] || {};
|
|
538
|
+
const raw = wb.key || wb.id || wb.index || wb.name || `lp${i + 1}`;
|
|
539
|
+
const safe = toSafeIdPart(raw);
|
|
540
|
+
if (safe) keys.push(safe);
|
|
541
|
+
}
|
|
542
|
+
} catch (_e) {}
|
|
543
|
+
for (let i = 1; i <= 8; i++) keys.push(`lp${i}`);
|
|
544
|
+
return Array.from(new Set(keys.filter(Boolean)));
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
async _readEvGoals(evcsAvailable = true) {
|
|
548
|
+
const out = [];
|
|
549
|
+
if (!evcsAvailable) return out;
|
|
550
|
+
const keys = this._chargingWallboxKeys();
|
|
551
|
+
for (const safe of keys) {
|
|
552
|
+
const base = `chargingManagement.wallboxes.${safe}`;
|
|
553
|
+
const goalEnabled = await this._readBool([`${base}.goalEnabled`], false);
|
|
554
|
+
const goalActive = await this._readBool([`${base}.goalActive`], false);
|
|
555
|
+
const vehiclePlugged = await this._readBool([`${base}.vehiclePlugged`], false);
|
|
556
|
+
const goalFinishTs = await this._readNumber([`${base}.goalFinishTs`], 0);
|
|
557
|
+
const goalTargetSocPct = await this._readNumber([`${base}.goalTargetSocPct`], null);
|
|
558
|
+
const goalRemainingMin = await this._readNumber([`${base}.goalRemainingMin`], null);
|
|
559
|
+
const goalDesiredPowerW = await this._readNumber([`${base}.goalDesiredPowerW`], null);
|
|
560
|
+
const goalRequiredPowerW = await this._readNumber([`${base}.goalRequiredPowerW`], null);
|
|
561
|
+
const goalShortfallW = await this._readNumber([`${base}.goalShortfallW`], null);
|
|
562
|
+
const goalStatus = await this._readString([`${base}.goalStatus`], '');
|
|
563
|
+
const chargingPowerW = await this._readNumber([`${base}.actualPowerW`, `${base}.powerW`, `${base}.usedW`], null);
|
|
564
|
+
const hasData = goalEnabled || goalActive || vehiclePlugged || (Number.isFinite(Number(goalFinishTs)) && Number(goalFinishTs) > 0) || (goalStatus && goalStatus !== 'idle');
|
|
565
|
+
if (!hasData) continue;
|
|
566
|
+
out.push({
|
|
567
|
+
id: safe,
|
|
568
|
+
label: safe.toUpperCase(),
|
|
569
|
+
goalEnabled,
|
|
570
|
+
goalActive,
|
|
571
|
+
vehiclePlugged,
|
|
572
|
+
goalFinishTs: Number.isFinite(Number(goalFinishTs)) ? Number(goalFinishTs) : 0,
|
|
573
|
+
goalTargetSocPct: finiteNumber(goalTargetSocPct) ? goalTargetSocPct : null,
|
|
574
|
+
goalRemainingMin: finiteNumber(goalRemainingMin) ? goalRemainingMin : null,
|
|
575
|
+
goalDesiredPowerW: finiteNumber(goalDesiredPowerW) ? goalDesiredPowerW : null,
|
|
576
|
+
goalRequiredPowerW: finiteNumber(goalRequiredPowerW) ? goalRequiredPowerW : null,
|
|
577
|
+
goalShortfallW: finiteNumber(goalShortfallW) ? goalShortfallW : null,
|
|
578
|
+
goalStatus,
|
|
579
|
+
chargingPowerW: finiteNumber(chargingPowerW) ? Math.max(0, chargingPowerW) : null,
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
return out;
|
|
583
|
+
}
|
|
584
|
+
|
|
259
585
|
async _snapshot() {
|
|
260
586
|
const gridRawW = await this._readNumber(['ems.gridPowerRawW', 'grid.powerRawW', 'gridPointPower'], null);
|
|
261
587
|
const gridW = await this._readNumber(['ems.budget.gridW', 'ems.gridPowerW', 'grid.powerW'], gridRawW || 0);
|
|
@@ -263,14 +589,57 @@ class AiAdvisorModule extends BaseModule {
|
|
|
263
589
|
const gridExportW = await this._readNumber(['ems.budget.gridExportW', 'gridSellPower'], Math.max(0, -(num(gridRawW, gridW || 0))));
|
|
264
590
|
const pvPowerW = await this._readNumber(['ems.budget.pvPowerW', 'derived.core.pv.totalW', 'pvPower', 'productionTotal'], 0);
|
|
265
591
|
const pvBudgetW = await this._readNumber(['ems.budget.pvBudgetW', 'ems.budget.remainingPvW'], 0);
|
|
592
|
+
const consumptionTotalW = await this._readNumber(['consumptionTotal', 'ems.budget.consumptionTotalW', 'building.powerW', 'loadPower'], null);
|
|
593
|
+
const productionEnergyKwh = await this._readNumber(['productionEnergyKwh', 'pvEnergyKwh', 'production.energyKwh'], null);
|
|
594
|
+
|
|
595
|
+
const cfgGridConnectionW = num(this.adapter && this.adapter.config && this.adapter.config.installerConfig ? this.adapter.config.installerConfig.gridConnectionPower : 0, 0);
|
|
596
|
+
const gridConnectionLimitW = await this._readNumber(['ems.core.gridConnectionLimitW_cfg', 'installer.gridConnectionPower', 'installerConfig.gridConnectionPower'], cfgGridConnectionW || null);
|
|
597
|
+
const gridImportLimitEffectiveW = await this._readNumber(['ems.core.gridImportLimitW_effective', 'chargingManagement.control.gridImportLimitW_effective'], null);
|
|
598
|
+
const gridImportLimitSource = await this._readString(['ems.core.gridImportLimitW_source'], '');
|
|
266
599
|
|
|
267
600
|
const storageSocPct = await this._readNumber(['storageFarm.totalSoc', 'speicher.regelung.socPct', 'storageSoc'], null);
|
|
268
601
|
const storageChargeW = await this._readNumber(['ems.budget.storageChargeW', 'storageFarm.totalChargePowerW', 'storageChargePower'], 0);
|
|
269
602
|
const storageDischargeW = await this._readNumber(['ems.budget.storageDischargeW', 'storageFarm.totalDischargePowerW', 'storageDischargePower'], 0);
|
|
270
603
|
|
|
271
|
-
|
|
604
|
+
let evcsUsedW = await this._readNumber(['chargingManagement.control.usedW', 'evcs.totalPowerW', 'consumptionEvcs'], 0);
|
|
272
605
|
const thermalUsedW = await this._readNumber(['thermal.summary.budgetUsedW'], 0);
|
|
273
606
|
const heatingRodUsedW = await this._readNumber(['heatingRod.summary.budgetUsedW'], 0);
|
|
607
|
+
let houseLoadW = await this._readNumber(['ems.budget.loadW', 'ems.budget.houseLoadW', 'derived.core.load.totalW', 'buildingConsumptionW', 'consumptionTotal', 'consumptionHouse'], null);
|
|
608
|
+
if (!finiteNumber(houseLoadW)) {
|
|
609
|
+
houseLoadW = Math.max(0, num(pvPowerW, 0) + Math.max(0, num(gridImportW, 0)) + Math.max(0, num(storageDischargeW, 0)) - Math.max(0, num(gridExportW, 0)) - Math.max(0, num(storageChargeW, 0)));
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const aiCfg = (this.adapter && this.adapter.config && this.adapter.config.aiAdvisor && typeof this.adapter.config.aiAdvisor === 'object') ? this.adapter.config.aiAdvisor : {};
|
|
613
|
+
const settingsCfg = (this.adapter && this.adapter.config && this.adapter.config.settingsConfig && typeof this.adapter.config.settingsConfig === 'object') ? this.adapter.config.settingsConfig : {};
|
|
614
|
+
const evcsAvailable = inferEvcsAvailable(this.adapter, settingsCfg);
|
|
615
|
+
if (!evcsAvailable) evcsUsedW = 0;
|
|
616
|
+
const evcsCountRaw = evcsAvailable ? num(settingsCfg.evcsCount ?? this.adapter.evcsCount, Array.isArray(this.adapter && this.adapter.evcsList) ? this.adapter.evcsList.length : 0) : 0;
|
|
617
|
+
const evcsCount = evcsAvailable ? Math.max(0, Math.min(20, Math.round(num(evcsCountRaw, 0)))) : 0;
|
|
618
|
+
let evConnectedCount = 0;
|
|
619
|
+
let evVehicleSocPct = null;
|
|
620
|
+
let evStatusText = '';
|
|
621
|
+
let evMode = '';
|
|
622
|
+
if (evcsAvailable && evcsCount > 0) {
|
|
623
|
+
for (let i = 1; i <= evcsCount; i++) {
|
|
624
|
+
const status = await this._readString([`evcs.${i}.status`], '');
|
|
625
|
+
const active = await this._readBool([`evcs.${i}.active`], false);
|
|
626
|
+
const connectedByStatus = /charging|connected|plug|suspendedev|preparing|laden|verbunden/i.test(status || '');
|
|
627
|
+
if (active || connectedByStatus) evConnectedCount += 1;
|
|
628
|
+
if (!evStatusText && status) evStatusText = status;
|
|
629
|
+
if (!evMode) evMode = await this._readString([`evcs.${i}.mode`], '');
|
|
630
|
+
const soc = await this._readNumber([`evcs.${i}.vehicleSoc`, `evcs.${i}.vehicleSocPct`, `evcs.${i}.socPct`], null);
|
|
631
|
+
if (finiteNumber(soc)) evVehicleSocPct = evVehicleSocPct === null ? soc : Math.min(evVehicleSocPct, soc);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
const connectedCount = evcsAvailable ? await this._readNumber(['chargingManagement.control.connectedCount', 'evcs.connectedCount'], null) : null;
|
|
635
|
+
if (evcsAvailable && finiteNumber(connectedCount) && connectedCount > 0) evConnectedCount = Math.max(evConnectedCount, Math.round(connectedCount));
|
|
636
|
+
const evTargetSocPct = evcsAvailable ? await this._readNumber(['settings.aiAdvisorEvTargetSocPct', 'chargingManagement.targetSocPct', 'evcs.1.targetSoc', 'evcs.1.targetSocPct'], num(aiCfg.evTargetSocPct ?? aiCfg.defaultEvTargetSocPct, 80)) : null;
|
|
637
|
+
const evBatteryCapacityKwh = evcsAvailable ? num(aiCfg.evBatteryCapacityKwh, 60) : null;
|
|
638
|
+
const evReadyBy = evcsAvailable ? await this._readString(['settings.aiAdvisorEvReadyBy', 'chargingManagement.readyBy', 'evcs.1.readyBy', 'evcs.1.departureTime'], String(aiCfg.evReadyBy || aiCfg.evDepartureTime || '07:00')) : '';
|
|
639
|
+
const evMinutesUntilReady = evcsAvailable ? minutesUntilClock(evReadyBy, new Date()) : null;
|
|
640
|
+
const evEnergyNeededKwh = (evcsAvailable && finiteNumber(evVehicleSocPct) && finiteNumber(evTargetSocPct) && finiteNumber(evBatteryCapacityKwh))
|
|
641
|
+
? Math.max(0, (evBatteryCapacityKwh * (Math.min(100, evTargetSocPct) - Math.max(0, evVehicleSocPct))) / 100)
|
|
642
|
+
: null;
|
|
274
643
|
|
|
275
644
|
const tariffActive = await this._readBool(['tarif.aktiv', 'ems.budget.tariff.active'], false);
|
|
276
645
|
const tariffState = await this._readString(['tarif.state', 'ems.budget.tariff.state'], '');
|
|
@@ -281,18 +650,37 @@ class AiAdvisorModule extends BaseModule {
|
|
|
281
650
|
const nextCheapTo = await this._readString(['tarif.naechstesGuensigBis'], '');
|
|
282
651
|
const negativeActive = await this._readBool(['tarif.negativpreisAktiv', 'ems.budget.tariff.negativeActive'], false);
|
|
283
652
|
const gridImportPreferred = await this._readBool(['tarif.netzbezugBevorzugt', 'ems.budget.tariff.gridImportPreferred'], negativeActive);
|
|
653
|
+
const co2IntensityGPerKwh = await this._readNumber(['tarif.co2IntensityGPerKwh', 'grid.co2IntensityGPerKwh', 'co2.gridIntensityGPerKwh'], null);
|
|
284
654
|
|
|
285
655
|
const pvForecastUsable = await this._readBool(['ems.budget.forecast.usable', 'forecast.pv.valid'], false);
|
|
286
656
|
const pvKwh6 = await this._readNumber(['ems.budget.forecast.kwhNext6h', 'forecast.pv.kwhNext6h'], 0);
|
|
287
657
|
const pvKwh12 = await this._readNumber(['ems.budget.forecast.kwhNext12h', 'forecast.pv.kwhNext12h'], 0);
|
|
288
658
|
const pvKwh24 = await this._readNumber(['ems.budget.forecast.kwhNext24h', 'forecast.pv.kwhNext24h'], 0);
|
|
289
659
|
const pvPeak24W = await this._readNumber(['ems.budget.forecast.peakNext24h', 'forecast.pv.peakWNext24h'], 0);
|
|
660
|
+
const forecastQualityPct = await this._readNumber(['ems.budget.forecast.qualityPct', 'forecast.pv.qualityPct', 'forecast.qualityPct'], null);
|
|
661
|
+
const forecastErrorPct = await this._readNumber(['ems.budget.forecast.errorPct', 'forecast.pv.errorPct', 'forecast.errorPct'], null);
|
|
662
|
+
|
|
663
|
+
const weatherEnabled = await this._readBool(['settings.weatherEnabled'], false);
|
|
664
|
+
const weatherTempC = await this._readNumber(['weatherTempC'], null);
|
|
665
|
+
const weatherText = await this._readString(['weatherText'], '');
|
|
666
|
+
const weatherCloudPct = await this._readNumber(['weatherCloudPct'], null);
|
|
667
|
+
const weatherWindKmh = await this._readNumber(['weatherWindKmh'], null);
|
|
668
|
+
const weatherTomorrowMinC = await this._readNumber(['weatherTomorrowMinC'], null);
|
|
669
|
+
const weatherTomorrowMaxC = await this._readNumber(['weatherTomorrowMaxC'], null);
|
|
670
|
+
const weatherTomorrowPrecipPct = await this._readNumber(['weatherTomorrowPrecipPct'], null);
|
|
671
|
+
const weatherTomorrowCode = await this._readNumber(['weatherTomorrowCode'], null);
|
|
672
|
+
const weatherTomorrowText = await this._readString(['weatherTomorrowText'], '');
|
|
290
673
|
|
|
291
674
|
const peakActive = await this._readBool(['peakShaving.control.active'], false);
|
|
292
675
|
const peakLimitW = await this._readNumber(['peakShaving.control.limitW', 'ems.core.gridImportLimitW_effective'], null);
|
|
293
676
|
const peakOverW = await this._readNumber(['peakShaving.control.overW'], 0);
|
|
677
|
+
const peakStatus = await this._readString(['peakShaving.control.status'], '');
|
|
294
678
|
const hlzfActive = await this._readBool(['peakShaving.atypical.activeWindow'], false);
|
|
295
679
|
const para14aActive = await this._readBool(['para14a.active', 'ems.core.para14aActive'], false);
|
|
680
|
+
const peakStatusLower = String(peakStatus || '').toLowerCase();
|
|
681
|
+
const peakConfigured = isPeakShavingConfigured(this.adapter && this.adapter.config)
|
|
682
|
+
|| (finiteNumber(peakLimitW) && peakLimitW > 0 && !['disabled', 'off', 'inactive', 'aus'].includes(peakStatusLower));
|
|
683
|
+
const evGoals = evcsAvailable ? await this._readEvGoals(evcsAvailable) : [];
|
|
296
684
|
|
|
297
685
|
return {
|
|
298
686
|
ts: Date.now(),
|
|
@@ -300,14 +688,31 @@ class AiAdvisorModule extends BaseModule {
|
|
|
300
688
|
gridW,
|
|
301
689
|
gridImportW: Math.max(0, num(gridImportW, 0)),
|
|
302
690
|
gridExportW: Math.max(0, num(gridExportW, 0)),
|
|
691
|
+
gridConnectionLimitW: finiteNumber(gridConnectionLimitW) && gridConnectionLimitW > 0 ? gridConnectionLimitW : null,
|
|
692
|
+
gridImportLimitEffectiveW: finiteNumber(gridImportLimitEffectiveW) && gridImportLimitEffectiveW > 0 ? gridImportLimitEffectiveW : null,
|
|
693
|
+
gridImportLimitSource,
|
|
303
694
|
pvPowerW: Math.max(0, num(pvPowerW, 0)),
|
|
304
695
|
pvBudgetW: Math.max(0, num(pvBudgetW, 0)),
|
|
696
|
+
consumptionTotalW: finiteNumber(consumptionTotalW) ? Math.max(0, num(consumptionTotalW, 0)) : null,
|
|
697
|
+
productionEnergyKwh: finiteNumber(productionEnergyKwh) ? productionEnergyKwh : null,
|
|
305
698
|
storageSocPct: finiteNumber(storageSocPct) ? storageSocPct : null,
|
|
306
699
|
storageChargeW: Math.max(0, num(storageChargeW, 0)),
|
|
307
700
|
storageDischargeW: Math.max(0, num(storageDischargeW, 0)),
|
|
308
|
-
|
|
701
|
+
evcsAvailable,
|
|
702
|
+
evcsCount,
|
|
703
|
+
evcsUsedW: evcsAvailable ? Math.max(0, num(evcsUsedW, 0)) : 0,
|
|
309
704
|
thermalUsedW: Math.max(0, num(thermalUsedW, 0)),
|
|
310
705
|
heatingRodUsedW: Math.max(0, num(heatingRodUsedW, 0)),
|
|
706
|
+
houseLoadW: Math.max(0, num(houseLoadW, 0)),
|
|
707
|
+
evConnectedCount: Math.max(0, Math.round(num(evConnectedCount, 0))),
|
|
708
|
+
evVehicleSocPct: finiteNumber(evVehicleSocPct) ? evVehicleSocPct : null,
|
|
709
|
+
evTargetSocPct: finiteNumber(evTargetSocPct) ? evTargetSocPct : null,
|
|
710
|
+
evBatteryCapacityKwh: finiteNumber(evBatteryCapacityKwh) ? evBatteryCapacityKwh : null,
|
|
711
|
+
evReadyBy,
|
|
712
|
+
evMinutesUntilReady: finiteNumber(evMinutesUntilReady) ? evMinutesUntilReady : null,
|
|
713
|
+
evEnergyNeededKwh: finiteNumber(evEnergyNeededKwh) ? evEnergyNeededKwh : null,
|
|
714
|
+
evStatusText,
|
|
715
|
+
evMode,
|
|
311
716
|
tariffActive,
|
|
312
717
|
tariffState,
|
|
313
718
|
priceNow,
|
|
@@ -317,19 +722,191 @@ class AiAdvisorModule extends BaseModule {
|
|
|
317
722
|
nextCheapTo,
|
|
318
723
|
negativeActive,
|
|
319
724
|
gridImportPreferred,
|
|
725
|
+
co2IntensityGPerKwh: finiteNumber(co2IntensityGPerKwh) ? co2IntensityGPerKwh : null,
|
|
320
726
|
pvForecastUsable,
|
|
321
727
|
pvKwh6: Math.max(0, num(pvKwh6, 0)),
|
|
322
728
|
pvKwh12: Math.max(0, num(pvKwh12, 0)),
|
|
323
729
|
pvKwh24: Math.max(0, num(pvKwh24, 0)),
|
|
324
730
|
pvPeak24W: Math.max(0, num(pvPeak24W, 0)),
|
|
731
|
+
forecastQualityPct: finiteNumber(forecastQualityPct) ? forecastQualityPct : null,
|
|
732
|
+
forecastErrorPct: finiteNumber(forecastErrorPct) ? forecastErrorPct : null,
|
|
733
|
+
weatherEnabled,
|
|
734
|
+
weatherTempC: finiteNumber(weatherTempC) ? weatherTempC : null,
|
|
735
|
+
weatherText,
|
|
736
|
+
weatherCloudPct: finiteNumber(weatherCloudPct) ? weatherCloudPct : null,
|
|
737
|
+
weatherWindKmh: finiteNumber(weatherWindKmh) ? weatherWindKmh : null,
|
|
738
|
+
weatherTomorrowMinC: finiteNumber(weatherTomorrowMinC) ? weatherTomorrowMinC : null,
|
|
739
|
+
weatherTomorrowMaxC: finiteNumber(weatherTomorrowMaxC) ? weatherTomorrowMaxC : null,
|
|
740
|
+
weatherTomorrowPrecipPct: finiteNumber(weatherTomorrowPrecipPct) ? weatherTomorrowPrecipPct : null,
|
|
741
|
+
weatherTomorrowCode: finiteNumber(weatherTomorrowCode) ? weatherTomorrowCode : null,
|
|
742
|
+
weatherTomorrowText,
|
|
325
743
|
peakActive,
|
|
326
|
-
peakLimitW,
|
|
744
|
+
peakLimitW: finiteNumber(peakLimitW) && peakLimitW > 0 ? peakLimitW : null,
|
|
327
745
|
peakOverW: Math.max(0, num(peakOverW, 0)),
|
|
746
|
+
peakStatus,
|
|
747
|
+
peakConfigured,
|
|
328
748
|
hlzfActive,
|
|
329
749
|
para14aActive,
|
|
750
|
+
evGoals,
|
|
330
751
|
};
|
|
331
752
|
}
|
|
332
753
|
|
|
754
|
+
_updateLearning(snapshot, cfg) {
|
|
755
|
+
const s = Object.assign({}, snapshot || {});
|
|
756
|
+
const now = Number(s.ts) || Date.now();
|
|
757
|
+
const d = new Date(now);
|
|
758
|
+
const hour = d.getHours();
|
|
759
|
+
const sample = {
|
|
760
|
+
ts: now,
|
|
761
|
+
hour,
|
|
762
|
+
gridImportW: Math.max(0, Number(s.gridImportW) || 0),
|
|
763
|
+
gridExportW: Math.max(0, Number(s.gridExportW) || 0),
|
|
764
|
+
pvPowerW: Math.max(0, Number(s.pvPowerW) || 0),
|
|
765
|
+
houseLoadW: Math.max(0, Number(s.houseLoadW) || Number(s.consumptionTotalW) || 0),
|
|
766
|
+
};
|
|
767
|
+
const last = this._samples.length ? this._samples[this._samples.length - 1] : null;
|
|
768
|
+
if (!last || now - last.ts >= 30000) this._samples.push(sample);
|
|
769
|
+
const keepFrom = now - 72 * 3600 * 1000;
|
|
770
|
+
this._samples = this._samples.filter((it) => it && it.ts >= keepFrom).slice(-5000);
|
|
771
|
+
|
|
772
|
+
const peakBase = finiteNumber(s.gridConnectionLimitW) && s.gridConnectionLimitW > 0 ? s.gridConnectionLimitW : (finiteNumber(s.peakLimitW) && s.peakLimitW > 0 ? s.peakLimitW : null);
|
|
773
|
+
const peakWarnW = peakBase ? peakBase * ((cfg.peakNearLimitPct || 90) / 100) : null;
|
|
774
|
+
if (cfg.learningEnabled && peakWarnW && sample.gridImportW >= peakWarnW * 0.78) {
|
|
775
|
+
this._peakHourBuckets[hour] = (Number(this._peakHourBuckets[hour]) || 0) + clamp(sample.gridImportW / Math.max(1000, peakWarnW), 0.25, 2.5);
|
|
776
|
+
}
|
|
777
|
+
if (cfg.learningEnabled && (!last || now - last.ts >= 5 * 60000)) this._peakHourBuckets = this._peakHourBuckets.map((v) => Math.max(0, (Number(v) || 0) * 0.997));
|
|
778
|
+
let topHour = -1;
|
|
779
|
+
let topScore = 0;
|
|
780
|
+
this._peakHourBuckets.forEach((v, idx) => { if ((Number(v) || 0) > topScore) { topScore = Number(v) || 0; topHour = idx; } });
|
|
781
|
+
s.peakRiskHour = topHour >= 0 && topScore >= 1.5 ? topHour : null;
|
|
782
|
+
s.peakRiskWindow = s.peakRiskHour !== null ? formatWindowHour(s.peakRiskHour) : '';
|
|
783
|
+
s.peakLearningJson = JSON.stringify({ hours: this._peakHourBuckets.map((v, idx) => ({ hour: idx, score: round(v, 2) || 0 })), topHour: s.peakRiskHour, topWindow: s.peakRiskWindow });
|
|
784
|
+
|
|
785
|
+
const older = this._samples.filter((it) => it && it.ts < now - 10 * 60000);
|
|
786
|
+
const sameHour = older.filter((it) => Math.abs((Number(it.hour) || 0) - hour) <= 1 || Math.abs((Number(it.hour) || 0) - hour) >= 23);
|
|
787
|
+
const baselineSet = sameHour.length >= Math.min(6, older.length) ? sameHour : older;
|
|
788
|
+
const baselineW = average(baselineSet, 'houseLoadW');
|
|
789
|
+
const p95W = percentile(baselineSet, 'houseLoadW', 0.95);
|
|
790
|
+
const flexW = Math.max(0, Number(s.evcsUsedW) || 0) + Math.max(0, Number(s.thermalUsedW) || 0) + Math.max(0, Number(s.heatingRodUsedW) || 0);
|
|
791
|
+
const unexplainedW = Math.max(0, sample.houseLoadW - flexW);
|
|
792
|
+
const quietActive = isInsideClockWindow(now, cfg.quietHoursStart, cfg.quietHoursEnd);
|
|
793
|
+
const anomalyLimitW = Math.max(Number(cfg.anomalyMinImportW) || 0, baselineW ? baselineW * (Number(cfg.anomalyFactor) || 2.2) : 0, p95W ? p95W * 1.25 : 0);
|
|
794
|
+
const enoughSamples = baselineSet.length >= (Number(cfg.anomalyMinSamples) || 12);
|
|
795
|
+
s.anomalyBaselineW = baselineW;
|
|
796
|
+
s.anomalyP95W = p95W;
|
|
797
|
+
s.anomalyDetected = false;
|
|
798
|
+
s.anomalyText = '';
|
|
799
|
+
if (cfg.anomalyDetectionEnabled) {
|
|
800
|
+
if (quietActive && unexplainedW >= cfg.nightBaseLoadW && Math.max(0, Number(s.evcsUsedW) || 0) < 200) {
|
|
801
|
+
s.anomalyDetected = true;
|
|
802
|
+
s.anomalyText = s.evcsAvailable ? `Ungewöhnliche Grundlast im Ruhefenster: etwa ${formatKw(unexplainedW)} ohne erkennbare Wallbox-/Thermiklast.` : `Ungewöhnliche Grundlast im Ruhefenster: etwa ${formatKw(unexplainedW)} ohne erkennbare Thermik-/Heizstablast.`;
|
|
803
|
+
} else if (unexplainedW >= cfg.anomalyHighLoadW) {
|
|
804
|
+
s.anomalyDetected = true;
|
|
805
|
+
s.anomalyText = `Ungewöhnlich hoher Gebäudeverbrauch: etwa ${formatKw(unexplainedW)} nicht durch bekannte flexible Verbraucher erklärt.`;
|
|
806
|
+
} else if (enoughSamples && sample.houseLoadW >= anomalyLimitW && sample.houseLoadW > 0) {
|
|
807
|
+
s.anomalyDetected = true;
|
|
808
|
+
s.anomalyText = `Der Gebäudeverbrauch liegt deutlich über dem gelernten Bereich (${formatKw(sample.houseLoadW)} statt typisch ${baselineW ? formatKw(baselineW) : '—'}).`;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
if (finiteNumber(s.forecastQualityPct)) {
|
|
813
|
+
this._forecastQualityPct = clamp(Number(s.forecastQualityPct), 0, 100);
|
|
814
|
+
this._forecastQualityText = `PV-Prognosequalität ca. ${formatPct(this._forecastQualityPct)}.`;
|
|
815
|
+
} else if (finiteNumber(s.forecastErrorPct)) {
|
|
816
|
+
this._forecastQualityPct = clamp(100 - Math.abs(Number(s.forecastErrorPct)), 0, 100);
|
|
817
|
+
this._forecastQualityText = `PV-Prognosequalität ca. ${formatPct(this._forecastQualityPct)}.`;
|
|
818
|
+
} else if (cfg.forecastQualityEnabled && s.pvForecastUsable && finiteNumber(s.productionEnergyKwh) && s.pvKwh6 > 0.5) {
|
|
819
|
+
const lastCheck = this._forecastChecks.length ? this._forecastChecks[this._forecastChecks.length - 1] : null;
|
|
820
|
+
if (!lastCheck || now - lastCheck.ts >= 60 * 60000) this._forecastChecks.push({ ts: now, forecastKwh6: s.pvKwh6, productionEnergyKwh: s.productionEnergyKwh, resolved: false });
|
|
821
|
+
}
|
|
822
|
+
for (const check of this._forecastChecks) {
|
|
823
|
+
if (!check || check.resolved) continue;
|
|
824
|
+
const age = now - check.ts;
|
|
825
|
+
if (age >= 5.75 * 3600000 && age <= 9 * 3600000 && finiteNumber(s.productionEnergyKwh) && finiteNumber(check.productionEnergyKwh)) {
|
|
826
|
+
const actual = Math.max(0, Number(s.productionEnergyKwh) - Number(check.productionEnergyKwh));
|
|
827
|
+
const forecast = Math.max(0.1, Number(check.forecastKwh6) || 0);
|
|
828
|
+
const errPct = Math.abs(actual - forecast) / forecast * 100;
|
|
829
|
+
const q = clamp(100 - errPct, 0, 100);
|
|
830
|
+
check.resolved = true;
|
|
831
|
+
check.actualKwh = actual;
|
|
832
|
+
check.qualityPct = q;
|
|
833
|
+
check.errPct = errPct;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
this._forecastChecks = this._forecastChecks.filter((it) => it && now - it.ts <= 30 * 3600000).slice(-48);
|
|
837
|
+
const recentResolved = this._forecastChecks.filter((it) => it && it.resolved && finiteNumber(it.qualityPct)).slice(-8);
|
|
838
|
+
if (recentResolved.length) {
|
|
839
|
+
this._forecastQualityPct = round(average(recentResolved, 'qualityPct'), 0);
|
|
840
|
+
const lastQ = recentResolved[recentResolved.length - 1];
|
|
841
|
+
this._forecastQualityText = `PV-Prognosequalität ca. ${formatPct(this._forecastQualityPct)} (letzte Prüfung: Forecast ${formatKwh(lastQ.forecastKwh6)}, Ist ${formatKwh(lastQ.actualKwh)}).`;
|
|
842
|
+
}
|
|
843
|
+
s.forecastQualityPct = this._forecastQualityPct;
|
|
844
|
+
s.forecastQualityText = this._forecastQualityText || (s.pvForecastUsable ? 'PV-Prognose aktiv; Qualität wird nach den ersten Vergleichsfenstern bewertet.' : 'PV-Prognose nicht verfügbar.');
|
|
845
|
+
s.season = seasonFromDate(new Date(now));
|
|
846
|
+
s.seasonLabel = seasonLabel(s.season);
|
|
847
|
+
s.comfortActive = isInsideClockWindow(now, cfg.comfortStart, cfg.comfortEnd);
|
|
848
|
+
s.quietActive = quietActive;
|
|
849
|
+
s.comfortWindow = `${cfg.comfortStart || '06:00'}–${cfg.comfortEnd || '22:00'}`;
|
|
850
|
+
s.quietWindow = `${cfg.quietHoursStart || '22:00'}–${cfg.quietHoursEnd || '06:00'}`;
|
|
851
|
+
s.optimizationMode = cfg.optimizationMode;
|
|
852
|
+
this._lastLearning = {
|
|
853
|
+
anomaly: !!s.anomalyDetected,
|
|
854
|
+
anomalyText: s.anomalyText || '',
|
|
855
|
+
peakLearningText: s.peakRiskWindow ? `Gelerntes Peak-Risiko im Fenster ${s.peakRiskWindow}.` : 'Lernprofil wird aufgebaut.',
|
|
856
|
+
forecastQualityPct: s.forecastQualityPct,
|
|
857
|
+
forecastQualityText: s.forecastQualityText,
|
|
858
|
+
byHour: this._peakHourBuckets.map((v, idx) => ({ hour: idx, score: round(v, 2) || 0 })),
|
|
859
|
+
};
|
|
860
|
+
return s;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
_makeDailyPlan(s, cfg) {
|
|
864
|
+
const items = [];
|
|
865
|
+
const add = (time, title, text, priority, category) => {
|
|
866
|
+
if (!title || !text) return;
|
|
867
|
+
items.push({ time: String(time || ''), title: String(title), text: String(text), priority: Math.round(Number(priority) || 0), category: String(category || 'system') });
|
|
868
|
+
};
|
|
869
|
+
const tariffState = String(s.tariffState || '').toLowerCase();
|
|
870
|
+
const currentCheap = !!(s.negativeActive || s.gridImportPreferred || tariffState.includes('günstig') || tariffState.includes('guenstig') || tariffState.includes('cheap'));
|
|
871
|
+
const currentExpensive = !!(tariffState.includes('teuer') || tariffState.includes('expensive'));
|
|
872
|
+
const surplusW = Math.max(Number(s.gridExportW) || 0, Number(s.pvBudgetW) || 0);
|
|
873
|
+
const hasEvcs = !!s.evcsAvailable && (Number(s.evcsCount) > 0 || Number(s.evConnectedCount) > 0 || Number(s.evcsUsedW) > 100);
|
|
874
|
+
const surplusTargets = hasEvcs ? 'Wallbox, Warmwasser oder andere flexible Verbraucher' : 'Warmwasser, Heizstab oder andere flexible Verbraucher';
|
|
875
|
+
const peakLimit = finiteNumber(s.gridConnectionLimitW) && s.gridConnectionLimitW > 0 ? s.gridConnectionLimitW : (finiteNumber(s.peakLimitW) && s.peakLimitW > 0 ? s.peakLimitW : s.gridImportLimitEffectiveW);
|
|
876
|
+
const peakUsagePct = peakLimit ? (s.gridImportW / peakLimit * 100) : 0;
|
|
877
|
+
if (peakLimit && peakUsagePct >= (cfg.peakNearLimitPct || 90)) add('jetzt', 'Peak-Schutz', `Netzbezug bei ${formatPct(peakUsagePct)}: flexible Lasten nach Priorität reduzieren (${priorityText(cfg.priorities, { hasEvcs })}).`, 95, 'peak');
|
|
878
|
+
if (surplusW >= cfg.pvSurplusThresholdW) add('jetzt', 'PV-Überschuss nutzen', `${formatKw(surplusW)} Überschuss in ${surplusTargets} legen.`, 86, 'pv');
|
|
879
|
+
if (currentCheap) add('jetzt', 'Günstigen Tarif nutzen', `Preisfenster nutzen${finiteNumber(s.priceNow) ? ` (${formatPrice(s.priceNow)})` : ''}, solange Peak-Reserve bleibt.`, 84, 'tariff');
|
|
880
|
+
else if (currentExpensive) add('jetzt vermeiden', 'Teures Tarif-/Lastfenster', hasEvcs ? 'EV-Laden und Heizstab möglichst verschieben; Speicherreserve nur gezielt nutzen.' : 'Heizstab und andere flexible Lasten möglichst verschieben; Speicherreserve nur gezielt nutzen.', 80, 'tariff');
|
|
881
|
+
if (s.nextCheapFrom) add(shortIsoWindow(s.nextCheapFrom, s.nextCheapTo) || 'nächstes Tarif-Fenster', 'Nächstes günstiges Zeitfenster', 'Planbare Lasten in dieses Fenster verschieben.', 68, 'tariff');
|
|
882
|
+
if (s.pvForecastUsable && (s.pvKwh24 > 0 || s.pvPeak24W > 0)) add('Sonnenfenster', 'PV-Prognose einplanen', `${formatKwh(s.pvKwh24)} in 24h erwartet${s.pvPeak24W > 0 ? `, Peak ${formatKw(s.pvPeak24W)}` : ''}. Speicher-Headroom und flexible Lasten darauf abstimmen.`, 70, 'forecast');
|
|
883
|
+
if (hasEvcs && s.evConnectedCount > 0) {
|
|
884
|
+
if (finiteNumber(s.evEnergyNeededKwh) && s.evEnergyNeededKwh > 1) add(`bis ${s.evReadyBy || cfg.evReadyBy}`, 'EV-Ziel erreichen', `${formatKwh(s.evEnergyNeededKwh)} bis Ziel-SoC ${formatPct(s.evTargetSocPct || cfg.evTargetSocPct)} nachladen; PV-/Tariffenster bevorzugen.`, s.evMinutesUntilReady !== null && s.evMinutesUntilReady < 180 ? 90 : 74, 'evcs');
|
|
885
|
+
else add(`bis ${s.evReadyBy || cfg.evReadyBy}`, 'EV-Komfort prüfen', 'Fahrzeug ist verbunden; Ziel-SoC/Abfahrtszeit prüfen, damit PV und Tarif sauber geplant werden können.', 52, 'evcs');
|
|
886
|
+
}
|
|
887
|
+
const activeGoals = hasEvcs ? (Array.isArray(s.evGoals) ? s.evGoals : []).filter((g) => g && (g.goalEnabled || g.goalActive)) : [];
|
|
888
|
+
if (activeGoals.length) {
|
|
889
|
+
const next = activeGoals.slice().sort((a, b) => (Number(a.goalFinishTs || 0) || Infinity) - (Number(b.goalFinishTs || 0) || Infinity))[0];
|
|
890
|
+
add(tsToShortWindow(next.goalFinishTs) || 'EV-Ziel', 'EV-Zielladen absichern', `${next.label}: Ziel ${next.goalTargetSocPct !== null ? `${round(next.goalTargetSocPct, 0)} %` : 'gesetzt'}${next.goalFinishTs ? ` bis ${formatClockMs(next.goalFinishTs)}` : ''}.`, 82, 'evcs');
|
|
891
|
+
}
|
|
892
|
+
if (s.weatherEnabled) {
|
|
893
|
+
const rainy = (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct >= cfg.weatherRainRiskPct) || textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['regen', 'schauer', 'gewitter', 'schnee', 'bedeckt']);
|
|
894
|
+
const sunny = !rainy && (textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['sonnig', 'klar', 'heiter']) || (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct <= 25));
|
|
895
|
+
if (rainy) add('heute / morgen', 'Speicherreserve wettergeführt', 'Schwächeres PV-Fenster erwartet: Speicher nicht unnötig leeren und Komfortlasten auf sichere Fenster legen.', 72, 'weather');
|
|
896
|
+
if (sunny) add('morgen', 'PV-Headroom vorbereiten', 'Gutes PV-Fenster erwartet: unnötige Netzladung vermeiden und Speicherplatz für PV freihalten.', 66, 'weather');
|
|
897
|
+
}
|
|
898
|
+
if (cfg.seasonLogicEnabled) {
|
|
899
|
+
if (s.season === 'winter') add('laufend', 'Winterstrategie', 'Reserve höher gewichten, weil PV-Fenster kürzer und Wärmelasten relevanter sind.', 54, 'storage');
|
|
900
|
+
if (s.season === 'summer') add('tagsüber', 'Sommerstrategie', hasEvcs ? 'PV-Headroom und Eigenverbrauch hoch gewichten; Abendspitzen durch EV/Kühlung vermeiden.' : 'PV-Headroom und Eigenverbrauch hoch gewichten; Abendspitzen durch Kühlung/Heizstab vermeiden.', 54, 'pv');
|
|
901
|
+
}
|
|
902
|
+
if (s.peakRiskWindow) add(s.peakRiskWindow, 'Gelerntes Peak-Fenster entschärfen', 'Große flexible Lasten nicht gleichzeitig starten.', 74, 'learning');
|
|
903
|
+
if (s.anomalyDetected) add('prüfen', 'Anomalie prüfen', s.anomalyText, 88, 'anomaly');
|
|
904
|
+
if (!items.length) add('heute', 'Weiter beobachten', 'Keine starken Optimierungssignale; größere Verbraucher in PV- oder günstige Tarifzeiten legen.', 30, 'system');
|
|
905
|
+
const sorted = items.sort((a, b) => b.priority - a.priority).slice(0, 6);
|
|
906
|
+
const text = `Modus ${optimizationModeLabel(cfg.optimizationMode)}: ` + sorted.slice(0, 4).map((it) => `${it.time}: ${it.title}`).join(' · ');
|
|
907
|
+
return { mode: cfg.optimizationMode, modeLabel: optimizationModeLabel(cfg.optimizationMode), season: s.season, seasonLabel: s.seasonLabel, items: sorted, text };
|
|
908
|
+
}
|
|
909
|
+
|
|
333
910
|
_pushSuggestion(list, item) {
|
|
334
911
|
if (!item || !item.id) return;
|
|
335
912
|
const severityWeight = { critical: 5, warning: 4, success: 3, info: 2, neutral: 1 };
|
|
@@ -352,227 +929,110 @@ class AiAdvisorModule extends BaseModule {
|
|
|
352
929
|
|
|
353
930
|
_buildSuggestions(s, cfg) {
|
|
354
931
|
const out = [];
|
|
932
|
+
s.weatherSummary = s.weatherSummary || buildWeatherSummary(s);
|
|
355
933
|
const tariffState = String(s.tariffState || '').toLowerCase();
|
|
356
934
|
const currentCheap = !!(
|
|
357
|
-
s.negativeActive ||
|
|
358
|
-
s.gridImportPreferred ||
|
|
359
|
-
tariffState.includes('günstig') || tariffState.includes('guenstig') || tariffState.includes('cheap') ||
|
|
935
|
+
s.negativeActive || s.gridImportPreferred || tariffState.includes('günstig') || tariffState.includes('guenstig') || tariffState.includes('cheap') ||
|
|
360
936
|
(finiteNumber(s.priceNow) && finiteNumber(s.priceCheapThreshold) && s.priceNow <= s.priceCheapThreshold) ||
|
|
361
937
|
(finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow <= (s.priceAvg - cfg.cheapPriceMarginEurKwh))
|
|
362
938
|
);
|
|
363
|
-
const currentExpensive = !!(
|
|
364
|
-
tariffState.includes('teuer') || tariffState.includes('expensive') ||
|
|
365
|
-
(finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow >= (s.priceAvg + cfg.expensivePriceMarginEurKwh))
|
|
366
|
-
);
|
|
939
|
+
const currentExpensive = !!(tariffState.includes('teuer') || tariffState.includes('expensive') || (finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow >= (s.priceAvg + cfg.expensivePriceMarginEurKwh)));
|
|
367
940
|
const hasStorage = s.storageSocPct !== null;
|
|
368
941
|
const storageEnough = !hasStorage || s.storageSocPct >= cfg.minSocForDischargePct;
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
});
|
|
386
|
-
} else if (currentCheap) {
|
|
387
|
-
this._pushSuggestion(out, {
|
|
388
|
-
id: 'cheap-tariff-now',
|
|
389
|
-
category: 'tariff',
|
|
390
|
-
severity: 'success',
|
|
391
|
-
priority: 88,
|
|
392
|
-
icon: '💶',
|
|
393
|
-
title: 'Günstiges Tariffenster aktiv',
|
|
394
|
-
text: `Der Strompreis ist günstig${finiteNumber(s.priceNow) ? ` (${formatPrice(s.priceNow)})` : ''}. Verschiebbare Lasten sind jetzt wirtschaftlicher als in teuren Zeiten.`,
|
|
395
|
-
action: 'EV-Laden, Warmwasser/Heizstab oder Speicherladung bevorzugt in dieses Fenster legen.',
|
|
396
|
-
window: 'jetzt',
|
|
397
|
-
impact: 'Energiekosten senken',
|
|
398
|
-
confidence: 82,
|
|
399
|
-
});
|
|
400
|
-
} else if (s.tariffActive && s.nextCheapFrom) {
|
|
401
|
-
this._pushSuggestion(out, {
|
|
402
|
-
id: 'next-cheap-window',
|
|
403
|
-
category: 'tariff',
|
|
404
|
-
severity: 'info',
|
|
405
|
-
priority: 62,
|
|
406
|
-
icon: '⏱️',
|
|
407
|
-
title: 'Nächstes günstiges Zeitfenster vormerken',
|
|
408
|
-
text: `Das nächste günstige Tariffenster liegt bei ${shortIsoWindow(s.nextCheapFrom, s.nextCheapTo) || 'demnächst'}.`,
|
|
409
|
-
action: 'Planbare Verbraucher möglichst in dieses Fenster verschieben.',
|
|
410
|
-
window: shortIsoWindow(s.nextCheapFrom, s.nextCheapTo),
|
|
411
|
-
impact: 'Lastverschiebung',
|
|
412
|
-
confidence: 75,
|
|
413
|
-
});
|
|
414
|
-
}
|
|
942
|
+
const hasEvcs = !!s.evcsAvailable && (Number(s.evcsCount) > 0 || Number(s.evConnectedCount) > 0 || Number(s.evcsUsedW) > 100);
|
|
943
|
+
const evLoadW = hasEvcs ? Math.max(0, Number(s.evcsUsedW) || 0) : 0;
|
|
944
|
+
const hasFlexibleLoad = (evLoadW > 100 || s.thermalUsedW > 100 || s.heatingRodUsedW > 100) || !!(this.adapter && this.adapter.config && ((hasEvcs && this.adapter.config.enableChargingManagement) || this.adapter.config.enableThermalControl || this.adapter.config.enableHeatingRodControl));
|
|
945
|
+
const flexibleLoadLabel = evcsPhrase(hasEvcs, true);
|
|
946
|
+
const flexibleConsumerLabel = evcsPhrase(hasEvcs, false);
|
|
947
|
+
const pvSurplusTargets = hasEvcs ? 'Wallbox, Warmwasser oder andere flexible Verbraucher' : 'Warmwasser, Heizstab oder andere flexible Verbraucher';
|
|
948
|
+
const configuredGridLimitW = finiteNumber(s.gridConnectionLimitW) && s.gridConnectionLimitW > 0 ? s.gridConnectionLimitW : null;
|
|
949
|
+
const effectiveGridLimitW = finiteNumber(s.peakLimitW) && s.peakLimitW > 0 ? s.peakLimitW : (finiteNumber(s.gridImportLimitEffectiveW) && s.gridImportLimitEffectiveW > 0 ? s.gridImportLimitEffectiveW : null);
|
|
950
|
+
const peakReferenceLimitW = configuredGridLimitW || effectiveGridLimitW;
|
|
951
|
+
const peakUsagePct = peakReferenceLimitW ? (s.gridImportW / peakReferenceLimitW * 100) : null;
|
|
952
|
+
const peakWarnThresholdW = peakReferenceLimitW ? (peakReferenceLimitW * (cfg.peakNearLimitPct / 100)) : null;
|
|
953
|
+
const peakNearLimit = peakReferenceLimitW && Number.isFinite(peakUsagePct) && peakUsagePct >= cfg.peakNearLimitPct;
|
|
954
|
+
const peakCriticalLimit = peakReferenceLimitW && Number.isFinite(peakUsagePct) && peakUsagePct >= cfg.peakCriticalLimitPct;
|
|
955
|
+
const peakReadinessText = s.peakActive
|
|
956
|
+
? 'Lastspitzenkappung ist aktiv.'
|
|
957
|
+
: (s.peakConfigured ? 'Lastspitzenkappung ist vorbereitet und wird bei Überschreiten des konfigurierten Limits aktiv.' : 'Lastspitzenkappung ist aktuell nicht konfiguriert – der KI-Berater warnt nur und schaltet nichts automatisch.');
|
|
415
958
|
|
|
416
|
-
if (
|
|
959
|
+
if (s.peakActive || s.hlzfActive || s.peakOverW > 0) {
|
|
960
|
+
const lim = peakReferenceLimitW || s.peakLimitW;
|
|
961
|
+
const pctText = lim ? ` (${formatPct((s.gridImportW / lim) * 100)} von ${formatKw(lim)})` : '';
|
|
417
962
|
this._pushSuggestion(out, {
|
|
418
|
-
id: '
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
title: 'Teures Tariffenster — Verbrauch reduzieren',
|
|
424
|
-
text: `Der Tarif ist aktuell teuer${finiteNumber(s.priceNow) ? ` (${formatPrice(s.priceNow)})` : ''}. Große flexible Verbraucher sollten möglichst warten.`,
|
|
425
|
-
action: storageEnough ? 'Speicherentladung nutzen und EV/Heizstab nach hinten schieben.' : 'EV/Heizstab nach hinten schieben; Speicherreserve ist niedrig.',
|
|
426
|
-
window: 'jetzt vermeiden',
|
|
427
|
-
impact: 'Kosten vermeiden',
|
|
428
|
-
confidence: 82,
|
|
963
|
+
id: 'peak-window-protect', category: 'peak', severity: s.peakOverW > 0 ? 'critical' : 'warning', priority: 98, icon: '⚡',
|
|
964
|
+
title: s.hlzfActive ? 'Hochlastzeitfenster / Lastspitze aktiv' : 'Lastspitzenkappung aktiv',
|
|
965
|
+
text: s.peakOverW > 0 ? `Aktuell liegt der Netzbezug etwa ${formatKw(s.peakOverW)} über dem Limit${pctText}. Lastspitzenkappung ist aktiv.` : `Der Netzbezug wird aktuell durch ${s.hlzfActive ? 'HLZF/§19' : 'Lastspitzenkappung'} begrenzt${pctText || (finiteNumber(s.peakLimitW) ? ` (Limit ${formatKw(s.peakLimitW)})` : '')}.`,
|
|
966
|
+
action: `${flexibleLoadLabel} nach Priorität pausieren/reduzieren (${priorityText(cfg.priorities, { hasEvcs })}), bis der Netzanschluss wieder unter der Grenze liegt.`,
|
|
967
|
+
window: 'jetzt', impact: 'Leistungspreis / Netzanschluss schützen', confidence: 92,
|
|
429
968
|
});
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
if (surplusW >= cfg.pvSurplusThresholdW) {
|
|
969
|
+
} else if (peakNearLimit) {
|
|
970
|
+
const remainingW = Math.max(0, peakReferenceLimitW - s.gridImportW);
|
|
971
|
+
const warnText = peakWarnThresholdW ? `Die Vorwarnschwelle liegt bei ${formatPct(cfg.peakNearLimitPct)} = ${formatKw(peakWarnThresholdW)}.` : '';
|
|
434
972
|
this._pushSuggestion(out, {
|
|
435
|
-
id: '
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
title: 'PV-Überschuss jetzt nutzen',
|
|
441
|
-
text: `Es stehen etwa ${formatKw(surplusW)} PV-/Einspeiseüberschuss zur Verfügung.`,
|
|
442
|
-
action: hasFlexibleLoad ? 'Wallbox, Heizstab oder Wärmelast bevorzugt jetzt starten.' : 'Flexible Verbraucher einplanen oder zusätzliche Verbraucher im App-Center anbinden.',
|
|
443
|
-
window: 'jetzt',
|
|
444
|
-
impact: 'Eigenverbrauch erhöhen',
|
|
445
|
-
confidence: 88,
|
|
973
|
+
id: 'peak-near-grid-connection-limit', category: 'peak', severity: peakCriticalLimit ? 'critical' : 'warning', priority: peakCriticalLimit ? 97 : 92, icon: peakCriticalLimit ? '🛑' : '🚧',
|
|
974
|
+
title: peakCriticalLimit ? 'Netzanschluss am Limit' : `Netzanschluss zu ${formatPct(cfg.peakNearLimitPct)} ausgelastet`,
|
|
975
|
+
text: `Aktuell werden ${formatKw(s.gridImportW)} von ${formatKw(peakReferenceLimitW)} genutzt (${formatPct(peakUsagePct)}). ${warnText} ${peakReadinessText}`.replace(/\s+/g, ' ').trim(),
|
|
976
|
+
action: s.peakConfigured ? `Jetzt optimieren: flexible Lasten nach Priorität reduzieren oder verschieben (${priorityText(cfg.priorities, { hasEvcs })})${hasStorage && storageEnough ? ', Speicherentladung als Stütze prüfen' : ''}. Es bleiben nur etwa ${formatKw(remainingW)} Reserve bis zum Netzanschlusslimit.` : `Peak-Shaving im Installer/App-Center prüfen. Bis dahin flexible Lasten manuell reduzieren oder verschieben${hasStorage && storageEnough ? ' und Speicherstützung prüfen' : ''}. Es bleiben nur etwa ${formatKw(remainingW)} Reserve.`,
|
|
977
|
+
window: 'jetzt', impact: 'Lastspitze vermeiden', confidence: s.peakConfigured ? 90 : 82,
|
|
446
978
|
});
|
|
447
979
|
}
|
|
448
980
|
|
|
449
|
-
if (
|
|
450
|
-
|
|
451
|
-
let title = 'PV-Ertrag vorausplanen';
|
|
452
|
-
let action = `Morgen/innerhalb 24h werden etwa ${formatKwh(s.pvKwh24)} erwartet — flexible Lasten in die PV-Zeit legen.`;
|
|
453
|
-
let severity = 'info';
|
|
454
|
-
if (hasStorage && s.storageSocPct >= cfg.highSocPct) {
|
|
455
|
-
title = 'PV-Speicher-Headroom freihalten';
|
|
456
|
-
action = `Der Speicher ist bei ${round(s.storageSocPct, 0)} %. Bei erwartetem PV-Ertrag von ${formatKwh(s.pvKwh24)} sollte Netzladung vermieden und Platz für PV gelassen werden.`;
|
|
457
|
-
prio = 74;
|
|
458
|
-
} else if (hasStorage && s.storageSocPct <= cfg.lowSocPct) {
|
|
459
|
-
title = 'Speicherreserve und PV-Fenster abstimmen';
|
|
460
|
-
action = `Der Speicher ist niedrig (${round(s.storageSocPct, 0)} %). PV-Ertrag ist angekündigt; Reserve prüfen und größere Verbraucher bis zur PV-Zeit verschieben.`;
|
|
461
|
-
prio = 72;
|
|
462
|
-
severity = 'warning';
|
|
463
|
-
}
|
|
464
|
-
this._pushSuggestion(out, {
|
|
465
|
-
id: 'pv-forecast-plan',
|
|
466
|
-
category: 'forecast',
|
|
467
|
-
severity,
|
|
468
|
-
priority: prio,
|
|
469
|
-
icon: '🔮',
|
|
470
|
-
title,
|
|
471
|
-
text: `PV-Prognose: ${formatKwh(s.pvKwh6)} in 6h, ${formatKwh(s.pvKwh24)} in 24h${s.pvPeak24W > 0 ? `, Peak ${formatKw(s.pvPeak24W)}` : ''}.`,
|
|
472
|
-
action,
|
|
473
|
-
window: 'nächste 24h',
|
|
474
|
-
impact: 'PV-Nutzung planen',
|
|
475
|
-
confidence: 76,
|
|
476
|
-
});
|
|
981
|
+
if (cfg.dailyPlanEnabled && s.dayPlan && Array.isArray(s.dayPlan.items) && s.dayPlan.items.length) {
|
|
982
|
+
this._pushSuggestion(out, { id: 'ai-day-plan', category: 'plan', severity: 'info', priority: (cfg.optimizationMode === 'comfort' ? 82 : 76), icon: '🗓️', title: 'Tagesfahrplan erstellt', text: s.dayPlan.text, action: 'Planbare Verbraucher anhand dieser Reihenfolge einplanen; der Berater schaltet weiterhin nichts automatisch.', window: 'heute', impact: 'Vorausschauende Planung', confidence: 76 });
|
|
477
983
|
}
|
|
478
984
|
|
|
479
|
-
|
|
985
|
+
const activeEvGoals = hasEvcs ? (Array.isArray(s.evGoals) ? s.evGoals : []).filter((g) => g && (g.goalEnabled || g.goalActive)) : [];
|
|
986
|
+
if (hasEvcs && cfg.evGoalPlanningEnabled && (activeEvGoals.length || (s.evConnectedCount > 0 && finiteNumber(s.evEnergyNeededKwh)))) {
|
|
987
|
+
const urgent = activeEvGoals.length ? activeEvGoals.slice().sort((a, b) => (finiteNumber(a.goalRemainingMin) ? a.goalRemainingMin : 999999) - (finiteNumber(b.goalRemainingMin) ? b.goalRemainingMin : 999999))[0] : null;
|
|
988
|
+
const remaining = urgent && finiteNumber(urgent.goalRemainingMin) ? urgent.goalRemainingMin : s.evMinutesUntilReady;
|
|
989
|
+
const shortfall = urgent && finiteNumber(urgent.goalShortfallW) ? Math.max(0, urgent.goalShortfallW) : 0;
|
|
990
|
+
const isUrgent = (remaining !== null && remaining <= cfg.evUrgentRemainingMin) || shortfall > 500;
|
|
480
991
|
this._pushSuggestion(out, {
|
|
481
|
-
id: '
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
icon: '⚡',
|
|
486
|
-
title: s.hlzfActive ? 'Hochlastzeitfenster aktiv' : 'Peak-Shaving aktiv',
|
|
487
|
-
text: s.peakOverW > 0
|
|
488
|
-
? `Aktuell liegt der Netzbezug etwa ${formatKw(s.peakOverW)} über dem Limit.`
|
|
489
|
-
: `Der Netzbezug wird aktuell durch ${s.hlzfActive ? 'HLZF/§19' : 'Peak-Shaving'} begrenzt${finiteNumber(s.peakLimitW) ? ` (Limit ${formatKw(s.peakLimitW)})` : ''}.`,
|
|
490
|
-
action: 'EV-Laden, Heizstab und andere flexible Lasten pausieren oder reduzieren, bis das Fenster vorbei ist.',
|
|
491
|
-
window: 'jetzt',
|
|
492
|
-
impact: 'Leistungspreis / Netzlimit schützen',
|
|
493
|
-
confidence: 90,
|
|
992
|
+
id: 'ev-target-planning', category: 'evcs', severity: isUrgent ? 'warning' : 'info', priority: isUrgent ? 90 : 72, icon: '🚗', title: 'EV-Zielplanung aktiv',
|
|
993
|
+
text: urgent ? `${urgent.label}: Ziel ${urgent.goalTargetSocPct !== null ? `${round(urgent.goalTargetSocPct, 0)} %` : 'gesetzt'}${urgent.goalFinishTs ? ` bis ${tsToShortWindow(urgent.goalFinishTs)}` : ''}${shortfall > 0 ? `, aktuell fehlen ca. ${formatKw(shortfall)} Ladeleistung.` : '.'}` : `${formatKwh(s.evEnergyNeededKwh)} fehlen bis ${formatPct(s.evTargetSocPct || cfg.evTargetSocPct)} Ziel-SoC, bereit bis ${s.evReadyBy || cfg.evReadyBy}${remaining !== null ? ` (${formatDurationMinutes(remaining)})` : ''}.`,
|
|
994
|
+
action: currentCheap || s.negativeActive ? 'Jetzt laden, solange Tarif und Peak-Reserve passen.' : 'PV- und günstige Tariffenster priorisieren; bei knapper Abfahrtszeit Ladeleistung rechtzeitig freigeben.',
|
|
995
|
+
window: urgent && urgent.goalFinishTs ? tsToShortWindow(urgent.goalFinishTs) : `bis ${s.evReadyBy || cfg.evReadyBy}`, impact: 'Mobilität sicherstellen', confidence: urgent ? 82 : 70,
|
|
494
996
|
});
|
|
495
997
|
}
|
|
496
998
|
|
|
497
|
-
if (s.
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
icon: '🚦',
|
|
504
|
-
title: '§14a-Leistungsbegrenzung aktiv',
|
|
505
|
-
text: 'Der Netzbetreiber-/EMS-Deckel für steuerbare Verbraucher ist aktiv.',
|
|
506
|
-
action: 'Komfortverbraucher priorisieren und nicht notwendige Verbraucher verschieben.',
|
|
507
|
-
window: 'jetzt',
|
|
508
|
-
impact: 'Netzvorgabe einhalten',
|
|
509
|
-
confidence: 85,
|
|
510
|
-
});
|
|
999
|
+
if (s.weatherEnabled) {
|
|
1000
|
+
const rainyTomorrow = (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct >= cfg.weatherRainRiskPct) || textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['regen', 'schauer', 'gewitter', 'schnee', 'bedeckt']);
|
|
1001
|
+
const sunnyTomorrow = !rainyTomorrow && (textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['sonnig', 'klar', 'heiter']) || (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct <= 25));
|
|
1002
|
+
if (cfg.storageStrategyEnabled && rainyTomorrow && hasStorage) this._pushSuggestion(out, { id: 'weather-storage-reserve', category: 'weather', severity: s.storageSocPct < cfg.lowSocPct ? 'warning' : 'info', priority: s.storageSocPct < cfg.lowSocPct ? 82 : 68, icon: '🌧️', title: 'Speicherstrategie nach Wetter', text: `Wetter: ${s.weatherSummary}. Für morgen ist ein schwächeres PV-Fenster möglich.`, action: hasEvcs ? 'Speicherreserve nicht unnötig leeren; EV/Warmwasser eher in sichere Tarif- oder PV-Fenster legen.' : 'Speicherreserve nicht unnötig leeren; Warmwasser/Heizstab eher in sichere Tarif- oder PV-Fenster legen.', window: 'heute / morgen', impact: 'Reserve & Autarkie', confidence: 75 });
|
|
1003
|
+
if (cfg.storageStrategyEnabled && sunnyTomorrow && hasStorage) this._pushSuggestion(out, { id: 'weather-pv-headroom', category: 'weather', severity: 'success', priority: 64, icon: '☀️', title: 'PV-Headroom vorbereiten', text: `Wetter: ${s.weatherSummary}. Gutes PV-Fenster wahrscheinlich.`, action: 'Speicher nicht unnötig per Netz füllen; Platz für PV freihalten und flexible Lasten in die Sonne legen.', window: 'morgen', impact: 'Eigenverbrauch erhöhen', confidence: 72 });
|
|
1004
|
+
if (finiteNumber(s.weatherTomorrowMinC) && s.weatherTomorrowMinC <= 3 && hasFlexibleLoad) this._pushSuggestion(out, { id: 'weather-cold-thermal-plan', category: 'weather', severity: 'info', priority: 60, icon: '❄️', title: 'Kalte Nacht einplanen', text: `Die Prognose meldet bis ${formatTemp(s.weatherTomorrowMinC)}. Wärmelasten können später teurer oder peak-relevant werden.`, action: 'Warmwasser, Heizstab oder Wärmepumpe bevorzugt in günstige Tarif- oder PV-Fenster legen, ohne das Peak-Limit zu reißen.', window: 'nächste Nacht', impact: 'Komfort und Peak optimieren', confidence: 68 });
|
|
511
1005
|
}
|
|
512
1006
|
|
|
513
|
-
if (
|
|
514
|
-
this._pushSuggestion(out, {
|
|
515
|
-
|
|
516
|
-
category: 'storage',
|
|
517
|
-
severity: 'warning',
|
|
518
|
-
priority: 78,
|
|
519
|
-
icon: '🔋',
|
|
520
|
-
title: 'Speicherreserve niedrig',
|
|
521
|
-
text: `Der Speicher liegt bei ${round(s.storageSocPct, 0)} %.`,
|
|
522
|
-
action: 'Reservegrenze prüfen; flexible Lasten eher in PV- oder günstige Tariffenster verschieben.',
|
|
523
|
-
window: 'bis Reserve erholt ist',
|
|
524
|
-
impact: 'Reserve schützen',
|
|
525
|
-
confidence: 80,
|
|
526
|
-
});
|
|
1007
|
+
if (cfg.seasonLogicEnabled) {
|
|
1008
|
+
if (s.season === 'winter' && hasStorage) this._pushSuggestion(out, { id: 'season-winter-storage', category: 'storage', severity: 'info', priority: 55, icon: '🧊', title: 'Winterstrategie', text: 'Kürzere PV-Fenster und höhere Wärmelasten: Speicherreserve und Komfortziele höher gewichten.', action: hasEvcs ? 'Abends nicht zu aggressiv entladen und Warmwasser/EV möglichst in sichere Tarif- oder PV-Fenster legen.' : 'Abends nicht zu aggressiv entladen und Warmwasser/Heizstab möglichst in sichere Tarif- oder PV-Fenster legen.', window: 'laufend', impact: 'Reserve & Komfort', confidence: 66 });
|
|
1009
|
+
if (s.season === 'summer') this._pushSuggestion(out, { id: 'season-summer-pv', category: 'pv', severity: 'success', priority: 54, icon: '🌞', title: 'Sommerstrategie', text: 'Lange PV-Fenster: Eigenverbrauch und Speicher-Headroom sind besonders wertvoll.', action: hasEvcs ? 'Große Verbraucher tagsüber staffeln und Abendspitzen durch EV/Kühlung vermeiden.' : 'Große Verbraucher tagsüber staffeln und Abendspitzen durch Kühlung/Heizstab vermeiden.', window: 'tagsüber', impact: 'Eigenverbrauch & Peak', confidence: 66 });
|
|
527
1010
|
}
|
|
528
1011
|
|
|
529
|
-
if (s.
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
category: 'grid',
|
|
533
|
-
severity: 'warning',
|
|
534
|
-
priority: 70,
|
|
535
|
-
icon: '📉',
|
|
536
|
-
title: 'Hoher Netzbezug erkannt',
|
|
537
|
-
text: `Aktuell werden etwa ${formatKw(s.gridImportW)} aus dem Netz bezogen.`,
|
|
538
|
-
action: 'Nicht dringende Verbraucher verschieben; bei Speicher prüfen, ob Entladen freigegeben ist.',
|
|
539
|
-
window: 'jetzt',
|
|
540
|
-
impact: 'Netzbezug senken',
|
|
541
|
-
confidence: 72,
|
|
542
|
-
});
|
|
543
|
-
}
|
|
1012
|
+
if (s.anomalyDetected) this._pushSuggestion(out, { id: 'anomaly-detected', category: 'anomaly', severity: 'warning', priority: 87, icon: '🔎', title: 'Ungewöhnlichen Verbrauch prüfen', text: s.anomalyText, action: 'Geräteliste/SmartHome prüfen und nicht benötigte Verbraucher ausschalten oder in ein passendes Fenster verschieben.', window: 'jetzt prüfen', impact: 'Fehlverbrauch vermeiden', confidence: 74 });
|
|
1013
|
+
if (s.peakRiskWindow && !peakNearLimit) this._pushSuggestion(out, { id: 'peak-learning-risk', category: 'learning', severity: 'info', priority: 68, icon: '📈', title: 'Gelernte Lastspitze beachten', text: `Die Lastspitzen-Lernfunktion markiert ${s.peakRiskWindow} als typisches Peak-Risiko.`, action: `Flexible Verbraucher vorsorglich staffeln: ${priorityText(cfg.priorities, { hasEvcs })}.`, window: s.peakRiskWindow, impact: 'Peak vermeiden', confidence: 70 });
|
|
1014
|
+
if (cfg.forecastQualityEnabled && finiteNumber(s.forecastQualityPct) && s.forecastQualityPct < cfg.forecastQualityWarnPct) this._pushSuggestion(out, { id: 'forecast-quality-low', category: 'forecast', severity: 'info', priority: 57, icon: '🎯', title: 'Prognosequalität vorsichtig bewerten', text: `${s.forecastQualityText} Empfehlungen werden konservativer gewichtet.`, action: 'Bei niedriger Prognosequalität Speicherreserve erhöhen und harte Lastverschiebungen vermeiden.', window: 'laufend', impact: 'Risiko reduzieren', confidence: 70 });
|
|
544
1015
|
|
|
545
|
-
if (cfg.
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
severity: 'info',
|
|
550
|
-
priority: 30,
|
|
551
|
-
icon: '🧭',
|
|
552
|
-
title: 'Dynamischen Tarif anbinden',
|
|
553
|
-
text: 'Für bessere Zeitvorschläge fehlt aktuell ein frisches Preis-/Tarifsignal.',
|
|
554
|
-
action: 'Im App-Center Tarife/Preisprognose zuordnen.',
|
|
555
|
-
window: 'Setup',
|
|
556
|
-
impact: 'KI-Beratung verbessern',
|
|
557
|
-
confidence: 70,
|
|
558
|
-
});
|
|
1016
|
+
if (cfg.optimizationMode === 'co2' && finiteNumber(s.co2IntensityGPerKwh)) {
|
|
1017
|
+
const clean = s.co2IntensityGPerKwh <= cfg.co2LowGPerKwh;
|
|
1018
|
+
const dirty = s.co2IntensityGPerKwh >= cfg.co2HighGPerKwh;
|
|
1019
|
+
if (clean || dirty) this._pushSuggestion(out, { id: clean ? 'co2-clean-window' : 'co2-high-window', category: 'co2', severity: clean ? 'success' : 'info', priority: clean ? 75 : 65, icon: clean ? '🌱' : '🌫️', title: clean ? 'CO₂-günstiges Zeitfenster' : 'CO₂-intensive Netzphase', text: `Aktuelle CO₂-Intensität: ${Math.round(s.co2IntensityGPerKwh)} g/kWh.`, action: clean ? 'Flexible Lasten bevorzugen, solange Peak-Reserve bleibt.' : 'Nicht dringende Netzlasten verschieben; PV/Speicher bevorzugen.', window: 'jetzt', impact: 'CO₂-Optimierung', confidence: 72 });
|
|
559
1020
|
}
|
|
1021
|
+
if (cfg.optimizationMode === 'autarky' && s.gridExportW >= cfg.pvSurplusThresholdW) this._pushSuggestion(out, { id: 'autarky-mode-surplus', category: 'pv', severity: 'success', priority: 75, icon: '🏡', title: 'Autarkie-Modus: Überschuss nutzen', text: `${formatKw(s.gridExportW)} Einspeisung erkannt.`, action: `Eigenverbrauch erhöhen: ${pvSurplusTargets} staffeln.`, window: 'jetzt', impact: 'Autarkie erhöhen', confidence: 78 });
|
|
1022
|
+
if (cfg.optimizationMode === 'peak' && peakReferenceLimitW) this._pushSuggestion(out, { id: 'peak-mode-reserve', category: 'peak', severity: peakNearLimit ? 'warning' : 'info', priority: peakNearLimit ? 90 : 56, icon: '🛡️', title: 'Peak-Schutz-Modus', text: `Netzanschluss-Auslastung aktuell ${formatPct(peakUsagePct || 0)}.`, action: `Lasten konsequent nach Priorität staffeln: ${priorityText(cfg.priorities, { hasEvcs })}.`, window: 'laufend', impact: 'Lastspitzen vermeiden', confidence: 72 });
|
|
560
1023
|
|
|
561
|
-
if (
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
confidence: 70,
|
|
574
|
-
});
|
|
575
|
-
}
|
|
1024
|
+
if (s.negativeActive || s.gridImportPreferred) this._pushSuggestion(out, { id: 'negative-price-window', category: 'tariff', severity: 'success', priority: 88, icon: '€', title: s.negativeActive ? 'Negativpreis-Fenster nutzen' : 'Günstiges Netzladefenster', text: s.negativeActive ? 'Der aktuelle Strompreis ist negativ bzw. sehr günstig.' : 'Der Tarif bevorzugt aktuell Netzbezug.', action: `Flexible Lasten jetzt nutzen${hasStorage ? ', Speicherladung prüfen' : ''}, solange Peak-Reserve bleibt.`, window: 'jetzt', impact: 'Kosten senken', confidence: 86 });
|
|
1025
|
+
else if (currentExpensive && hasFlexibleLoad) this._pushSuggestion(out, { id: 'expensive-price-avoid-loads', category: 'tariff', severity: 'warning', priority: 74, icon: '💸', title: 'Teures Tarif-Fenster', text: finiteNumber(s.priceNow) ? `Aktueller Preis ${formatPrice(s.priceNow)} liegt über dem Vergleichswert.` : 'Der aktuelle Tarifzustand ist teuer.', action: `${flexibleConsumerLabel} verschieben oder reduzieren, wenn Komfortziele es erlauben.`, window: 'jetzt', impact: 'Kosten vermeiden', confidence: 78 });
|
|
1026
|
+
if (s.nextCheapFrom && !currentCheap) this._pushSuggestion(out, { id: 'next-cheap-window', category: 'tariff', severity: 'info', priority: 62, icon: '⏱️', title: 'Nächstes günstiges Zeitfenster', text: `Günstiges Tarif-Fenster: ${shortIsoWindow(s.nextCheapFrom, s.nextCheapTo) || s.nextCheapFrom}.`, action: hasEvcs ? 'Planbare Lasten bis dahin zurückstellen, sofern Komfort und EV-Zielzeiten passen.' : 'Planbare Lasten bis dahin zurückstellen, sofern Komfortziele passen.', window: shortIsoWindow(s.nextCheapFrom, s.nextCheapTo), impact: 'Kosten optimieren', confidence: 72 });
|
|
1027
|
+
if (s.gridExportW >= cfg.pvSurplusThresholdW) this._pushSuggestion(out, { id: 'pv-surplus-use', category: 'pv', severity: 'success', priority: 82, icon: '☀️', title: 'PV-Überschuss verfügbar', text: `Aktuell werden etwa ${formatKw(s.gridExportW)} eingespeist.`, action: `${pvSurplusTargets} einschalten bzw. erhöhen, solange kein Peak-Risiko besteht.`, window: 'jetzt', impact: 'Eigenverbrauch erhöhen', confidence: 82 });
|
|
1028
|
+
if (s.pvForecastUsable && (s.pvKwh24 >= cfg.pvForecastMinKwh || s.pvPeak24W >= cfg.pvPeakMinW)) this._pushSuggestion(out, { id: 'pv-forecast-plan', category: 'forecast', severity: 'info', priority: 66, icon: '🔮', title: 'PV-Prognose einplanen', text: `${formatKwh(s.pvKwh24)} PV-Ertrag in den nächsten 24h erwartet, Peak ca. ${formatKw(s.pvPeak24W)}.`, action: hasStorage ? 'Speicher-Headroom für PV freihalten und flexible Lasten in das Sonnenfenster legen.' : 'Flexible Lasten in das Sonnenfenster legen.', window: 'nächste 24h', impact: 'Autarkie erhöhen', confidence: 75 });
|
|
1029
|
+
if (hasStorage && s.storageSocPct <= cfg.lowSocPct) this._pushSuggestion(out, { id: 'storage-low-reserve', category: 'storage', severity: 'warning', priority: 78, icon: '🔋', title: 'Speicherreserve niedrig', text: `Der Speicher liegt bei ${round(s.storageSocPct, 0)} %.`, action: 'Reservegrenze prüfen; flexible Lasten eher in PV- oder günstige Tariffenster verschieben.', window: 'bis Reserve erholt ist', impact: 'Reserve schützen', confidence: 80 });
|
|
1030
|
+
if (s.gridImportW >= cfg.highImportThresholdW && !currentCheap && !s.negativeActive && !peakNearLimit && !s.peakActive && !(s.peakOverW > 0)) this._pushSuggestion(out, { id: 'high-grid-import', category: 'grid', severity: 'warning', priority: 70, icon: '📉', title: 'Hoher Netzbezug erkannt', text: `Aktuell werden etwa ${formatKw(s.gridImportW)} aus dem Netz bezogen.`, action: 'Nicht dringende Verbraucher verschieben; bei Speicher prüfen, ob Entladen freigegeben ist.', window: 'jetzt', impact: 'Netzbezug senken', confidence: 72 });
|
|
1031
|
+
if (s.para14aActive) this._pushSuggestion(out, { id: 'para14a-active', category: 'grid', severity: 'warning', priority: 84, icon: '🚦', title: '§14a-Leistungsbegrenzung aktiv', text: 'Der Netzbetreiber-/EMS-Deckel für steuerbare Verbraucher ist aktiv.', action: 'Komfortverbraucher priorisieren und nicht notwendige Verbraucher verschieben.', window: 'jetzt', impact: 'Netzvorgabe einhalten', confidence: 85 });
|
|
1032
|
+
if (cfg.comfortHintsEnabled && s.quietActive && (evLoadW + s.thermalUsedW + s.heatingRodUsedW) > 500 && cfg.optimizationMode !== 'comfort') this._pushSuggestion(out, { id: 'comfort-quiet-hours-flex-load', category: 'comfort', severity: 'info', priority: 63, icon: '🌙', title: 'Ruhezeit: flexible Lasten prüfen', text: `Im Ruhefenster ${s.quietWindow} laufen flexible Verbraucher mit etwa ${formatKw(evLoadW + s.thermalUsedW + s.heatingRodUsedW)}.`, action: 'Nur laufen lassen, wenn Komfortziel, Abfahrtszeit oder günstiger Tarif wichtiger ist; sonst in PV-/Tariffenster verschieben.', window: 'jetzt', impact: 'Komfort / Geräusch / Peak', confidence: 70 });
|
|
1033
|
+
if (cfg.includeInstallerHints && !configuredGridLimitW) this._pushSuggestion(out, { id: 'setup-grid-connection-limit', category: 'setup', severity: 'info', priority: 32, icon: '🔌', title: 'Netzanschlussleistung hinterlegen', text: 'Für korrekte Peak-Shaving-Vorwarnungen fehlt die konfigurierte Netzanschlussleistung.', action: 'Im Installer die Netzanschlussleistung eintragen, z. B. 30000 W für einen 30-kW-Anschluss.', window: 'Setup', impact: 'Peak-Beratung verbessern', confidence: 72 });
|
|
1034
|
+
if (cfg.includeInstallerHints && !s.tariffActive && !finiteNumber(s.priceNow)) this._pushSuggestion(out, { id: 'setup-tariff', category: 'setup', severity: 'info', priority: 30, icon: '🧭', title: 'Dynamischen Tarif anbinden', text: 'Für bessere Zeitvorschläge fehlt aktuell ein frisches Preis-/Tarifsignal.', action: 'Im App-Center Tarife/Preisprognose zuordnen.', window: 'Setup', impact: 'KI-Beratung verbessern', confidence: 70 });
|
|
1035
|
+
if (cfg.includeInstallerHints && !s.pvForecastUsable) this._pushSuggestion(out, { id: 'setup-pv-forecast', category: 'setup', severity: 'info', priority: 28, icon: '☀️', title: 'PV-Forecast aktivieren', text: 'Für vorausschauende Empfehlungen fehlt eine nutzbare PV-Prognose.', action: 'PV-Forecast im App-Center einrichten, damit Verbraucher zeitlich besser geplant werden können.', window: 'Setup', impact: 'Prognosequalität erhöhen', confidence: 70 });
|
|
576
1036
|
|
|
577
1037
|
const seen = new Set();
|
|
578
1038
|
const deduped = [];
|
|
@@ -583,7 +1043,6 @@ class AiAdvisorModule extends BaseModule {
|
|
|
583
1043
|
delete clean.rankWeight;
|
|
584
1044
|
deduped.push(clean);
|
|
585
1045
|
}
|
|
586
|
-
|
|
587
1046
|
const minPriorityMap = { info: 0, warning: 60, action: 75, critical: 90 };
|
|
588
1047
|
const minPrio = minPriorityMap[cfg.minPriority] || 0;
|
|
589
1048
|
const categoryAllowed = (item) => {
|
|
@@ -594,43 +1053,37 @@ class AiAdvisorModule extends BaseModule {
|
|
|
594
1053
|
if (cat === 'storage') return cats.storage !== false;
|
|
595
1054
|
if (cat === 'evcs') return cats.evcs !== false;
|
|
596
1055
|
if (cat === 'peak') return cats.peak !== false;
|
|
1056
|
+
if (cat === 'weather') return cats.weather !== false;
|
|
597
1057
|
if (cat === 'heating' || cat === 'thermal') return cats.heating !== false;
|
|
1058
|
+
if (cat === 'dailyplan' || cat === 'daily-plan' || cat === 'plan') return cats.dailyPlan !== false && cats.plan !== false;
|
|
1059
|
+
if (cat === 'anomaly') return cats.anomaly !== false;
|
|
1060
|
+
if (cat === 'comfort') return cats.comfort !== false;
|
|
1061
|
+
if (cat === 'learning') return cats.learning !== false;
|
|
1062
|
+
if (cat === 'co2' || cat === 'co₂') return cats.co2 !== false;
|
|
598
1063
|
if (cat === 'grid' || cat === 'setup' || cat === 'system' || cat === 'general') return cats.system !== false;
|
|
599
1064
|
return true;
|
|
600
1065
|
};
|
|
601
1066
|
let filtered = deduped.filter((item) => categoryAllowed(item) && (Number(item.priority) || 0) >= minPrio);
|
|
602
|
-
|
|
603
1067
|
if (!filtered.length) {
|
|
604
|
-
this._pushSuggestion(filtered, {
|
|
605
|
-
id: 'system-balanced',
|
|
606
|
-
category: 'system',
|
|
607
|
-
severity: 'success',
|
|
608
|
-
priority: 20,
|
|
609
|
-
icon: '✅',
|
|
610
|
-
title: 'System läuft wirtschaftlich unauffällig',
|
|
611
|
-
text: 'Aktuell erkennt der KI-Energieberater keine dringende Optimierung.',
|
|
612
|
-
action: 'Weiter beobachten; größere Verbraucher möglichst in PV- oder günstige Tariffenster legen.',
|
|
613
|
-
window: 'laufend',
|
|
614
|
-
impact: 'Monitoring',
|
|
615
|
-
confidence: 65,
|
|
616
|
-
});
|
|
1068
|
+
this._pushSuggestion(filtered, { id: 'system-balanced', category: 'system', severity: 'success', priority: 20, icon: '✅', title: 'System läuft wirtschaftlich unauffällig', text: 'Aktuell erkennt der KI-Energieberater keine dringende Optimierung.', action: 'Weiter beobachten; größere Verbraucher möglichst in PV- oder günstige Tariffenster legen.', window: 'laufend', impact: 'Monitoring', confidence: 65 });
|
|
617
1069
|
filtered = filtered.filter((item) => categoryAllowed(item));
|
|
618
1070
|
}
|
|
619
|
-
|
|
620
|
-
return filtered.map((item) => { const clean = Object.assign({}, item); delete clean.rankWeight; return clean; }).slice(0, cfg.maxSuggestions);
|
|
1071
|
+
return filtered.slice(0, cfg.maxSuggestions);
|
|
621
1072
|
}
|
|
622
1073
|
|
|
623
1074
|
_score(snapshot, suggestions) {
|
|
624
|
-
let score =
|
|
625
|
-
|
|
626
|
-
if (
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
if (snapshot.
|
|
630
|
-
if (snapshot.gridImportW > 5000) score -= 8;
|
|
1075
|
+
let score = 72;
|
|
1076
|
+
if (suggestions && suggestions.length) score -= Math.min(22, suggestions.reduce((sum, it) => sum + (it.severity === 'critical' ? 8 : it.severity === 'warning' ? 5 : 2), 0));
|
|
1077
|
+
if (snapshot.gridExportW > 1000) score += 3;
|
|
1078
|
+
const peakBase = finiteNumber(snapshot.gridConnectionLimitW) && snapshot.gridConnectionLimitW > 0 ? snapshot.gridConnectionLimitW : snapshot.peakLimitW;
|
|
1079
|
+
if (peakBase && snapshot.gridImportW >= peakBase) score -= 20;
|
|
1080
|
+
else if (peakBase && snapshot.gridImportW >= peakBase * 0.9) score -= 12;
|
|
631
1081
|
if (snapshot.pvForecastUsable) score += 4;
|
|
1082
|
+
if (snapshot.weatherEnabled) score += 2;
|
|
632
1083
|
if (snapshot.tariffActive || finiteNumber(snapshot.priceNow)) score += 4;
|
|
633
1084
|
if (snapshot.storageSocPct !== null && snapshot.storageSocPct < 15) score -= 8;
|
|
1085
|
+
if (snapshot.anomalyDetected) score -= 10;
|
|
1086
|
+
if (finiteNumber(snapshot.forecastQualityPct) && snapshot.forecastQualityPct < 50) score -= 4;
|
|
634
1087
|
return clamp(Math.round(score), 0, 100);
|
|
635
1088
|
}
|
|
636
1089
|
|
|
@@ -642,6 +1095,7 @@ class AiAdvisorModule extends BaseModule {
|
|
|
642
1095
|
async _publishDisabled(cfg, now) {
|
|
643
1096
|
if ((now - (this._lastDisabledWriteMs || 0)) < 60000) return;
|
|
644
1097
|
this._lastDisabledWriteMs = now;
|
|
1098
|
+
const disabledByCustomer = cfg.customerEnabled === false;
|
|
645
1099
|
await this._set('aiAdvisor.enabled', false);
|
|
646
1100
|
await this._set('aiAdvisor.advisoryOnly', true);
|
|
647
1101
|
await this._set('aiAdvisor.showInLive', cfg.showInLive !== false);
|
|
@@ -649,17 +1103,43 @@ class AiAdvisorModule extends BaseModule {
|
|
|
649
1103
|
await this._set('aiAdvisor.status', 'disabled');
|
|
650
1104
|
await this._set('aiAdvisor.severity', 'neutral');
|
|
651
1105
|
await this._set('aiAdvisor.headline', 'KI-Energieberater deaktiviert');
|
|
652
|
-
await this._set('aiAdvisor.summary',
|
|
1106
|
+
await this._set('aiAdvisor.summary', disabledByCustomer ? 'Die beratende KI ist in den Kundeneinstellungen deaktiviert.' : 'Die beratende KI ist im App-Center deaktiviert.');
|
|
653
1107
|
await this._set('aiAdvisor.count', 0);
|
|
654
1108
|
await this._set('aiAdvisor.score', 0);
|
|
1109
|
+
await this._set('aiAdvisor.peakUsagePct', 0);
|
|
1110
|
+
await this._set('aiAdvisor.peakStateText', '');
|
|
1111
|
+
await this._set('aiAdvisor.gridConnectionLimitW', 0);
|
|
1112
|
+
await this._set('aiAdvisor.peakWarnThresholdW', 0);
|
|
1113
|
+
await this._set('aiAdvisor.weatherSummary', '');
|
|
1114
|
+
await this._set('aiAdvisor.dailyPlanText', '');
|
|
1115
|
+
await this._set('aiAdvisor.dailyPlanJson', '[]');
|
|
1116
|
+
await this._set('aiAdvisor.evPlanText', '');
|
|
1117
|
+
await this._set('aiAdvisor.optimizationMode', cfg.optimizationMode || 'balanced');
|
|
1118
|
+
await this._set('aiAdvisor.comfortWindowSummary', '');
|
|
1119
|
+
await this._set('aiAdvisor.season', seasonFromDate(new Date()));
|
|
1120
|
+
await this._set('aiAdvisor.anomalyText', '');
|
|
1121
|
+
await this._set('aiAdvisor.forecastQualityPct', 0);
|
|
1122
|
+
await this._set('aiAdvisor.forecastQualityText', '');
|
|
1123
|
+
await this._set('aiAdvisor.peakLearningText', '');
|
|
1124
|
+
await this._set('aiAdvisor.peakLearningJson', '[]');
|
|
655
1125
|
await this._set('aiAdvisor.topTitle', '');
|
|
656
1126
|
await this._set('aiAdvisor.topText', '');
|
|
657
1127
|
await this._set('aiAdvisor.topAction', '');
|
|
658
1128
|
await this._set('aiAdvisor.topWindow', '');
|
|
1129
|
+
await this._set('aiAdvisor.topCategory', '');
|
|
659
1130
|
await this._set('aiAdvisor.suggestionsJson', '[]');
|
|
660
1131
|
await this._set('aiAdvisor.snapshotJson', JSON.stringify({ ts: now, enabled: false }));
|
|
661
1132
|
await this._set('aiAdvisor.lastUpdate', now);
|
|
662
1133
|
await this._set('aiAdvisor.nextUpdate', now + 60000);
|
|
1134
|
+
for (let i = 1; i <= 8; i++) {
|
|
1135
|
+
await this._set(`aiAdvisor.suggestions.${i}.title`, '');
|
|
1136
|
+
await this._set(`aiAdvisor.suggestions.${i}.text`, '');
|
|
1137
|
+
await this._set(`aiAdvisor.suggestions.${i}.action`, '');
|
|
1138
|
+
await this._set(`aiAdvisor.suggestions.${i}.severity`, '');
|
|
1139
|
+
await this._set(`aiAdvisor.suggestions.${i}.category`, '');
|
|
1140
|
+
await this._set(`aiAdvisor.suggestions.${i}.window`, '');
|
|
1141
|
+
await this._set(`aiAdvisor.suggestions.${i}.impact`, '');
|
|
1142
|
+
}
|
|
663
1143
|
}
|
|
664
1144
|
|
|
665
1145
|
async _publish(snapshot, suggestions, cfg) {
|
|
@@ -669,7 +1149,22 @@ class AiAdvisorModule extends BaseModule {
|
|
|
669
1149
|
const severity = top ? String(top.severity || 'info') : 'neutral';
|
|
670
1150
|
const headline = top ? `${top.icon || '💡'} ${top.title}` : 'KI-Energieberater bereit';
|
|
671
1151
|
const summary = top ? String(top.text || '') : 'Keine aktuellen Hinweise.';
|
|
672
|
-
const jsonSuggestions =
|
|
1152
|
+
const jsonSuggestions = safeJson(suggestions || [], '[]');
|
|
1153
|
+
const peakReferenceLimitW = (finiteNumber(snapshot.gridConnectionLimitW) && snapshot.gridConnectionLimitW > 0)
|
|
1154
|
+
? snapshot.gridConnectionLimitW
|
|
1155
|
+
: ((finiteNumber(snapshot.peakLimitW) && snapshot.peakLimitW > 0) ? snapshot.peakLimitW : ((finiteNumber(snapshot.gridImportLimitEffectiveW) && snapshot.gridImportLimitEffectiveW > 0) ? snapshot.gridImportLimitEffectiveW : null));
|
|
1156
|
+
const peakUsagePct = peakReferenceLimitW ? (snapshot.gridImportW / peakReferenceLimitW * 100) : 0;
|
|
1157
|
+
const peakWarnThresholdW = peakReferenceLimitW ? (peakReferenceLimitW * ((cfg.peakNearLimitPct || 90) / 100)) : 0;
|
|
1158
|
+
const peakStateText = buildPeakStateText(snapshot, peakReferenceLimitW, peakUsagePct);
|
|
1159
|
+
const weatherSummary = buildWeatherSummary(snapshot);
|
|
1160
|
+
const dailyPlan = snapshot.dayPlan || { mode: cfg.optimizationMode, modeLabel: optimizationModeLabel(cfg.optimizationMode), items: [], text: '' };
|
|
1161
|
+
const evPlanText = (snapshot.evcsAvailable && snapshot.evConnectedCount > 0)
|
|
1162
|
+
? (finiteNumber(snapshot.evEnergyNeededKwh) && snapshot.evEnergyNeededKwh > 1
|
|
1163
|
+
? `${formatKwh(snapshot.evEnergyNeededKwh)} bis ${formatPct(snapshot.evTargetSocPct || cfg.evTargetSocPct)} Ziel-SoC nachladen · bereit bis ${snapshot.evReadyBy || cfg.evReadyBy}.`
|
|
1164
|
+
: `Fahrzeug verbunden · Ziel-SoC ${formatPct(snapshot.evTargetSocPct || cfg.evTargetSocPct)} · bereit bis ${snapshot.evReadyBy || cfg.evReadyBy}.`)
|
|
1165
|
+
: 'Kein verbundenes Fahrzeug erkannt.';
|
|
1166
|
+
const comfortWindowSummary = `${cfg.comfortStart || '06:00'}–${cfg.comfortEnd || '22:00'} · Ruhezeit ${cfg.quietHoursStart || '22:00'}–${cfg.quietHoursEnd || '06:00'}`;
|
|
1167
|
+
const learning = this._lastLearning || {};
|
|
673
1168
|
const snap = {
|
|
674
1169
|
ts: now,
|
|
675
1170
|
enabled: true,
|
|
@@ -677,14 +1172,19 @@ class AiAdvisorModule extends BaseModule {
|
|
|
677
1172
|
showInLive: cfg.showInLive !== false,
|
|
678
1173
|
status: 'ok',
|
|
679
1174
|
score,
|
|
1175
|
+
peakUsagePct,
|
|
1176
|
+
peakStateText,
|
|
1177
|
+
weatherSummary,
|
|
1178
|
+
dailyPlan,
|
|
1179
|
+
evPlanText,
|
|
1180
|
+
comfortWindowSummary,
|
|
1181
|
+
learning,
|
|
680
1182
|
severity,
|
|
681
1183
|
top,
|
|
682
1184
|
suggestions,
|
|
683
1185
|
raw: snapshot,
|
|
684
1186
|
};
|
|
685
|
-
const hash = makeHash({ suggestions, score, severity, show: cfg.showInLive });
|
|
686
|
-
|
|
687
|
-
// Even if content is unchanged, refresh timestamps periodically for stale diagnostics.
|
|
1187
|
+
const hash = makeHash({ suggestions, score, severity, show: cfg.showInLive, plan: dailyPlan.text || '', anomaly: learning.anomalyText || '', forecastQuality: learning.forecastQualityPct });
|
|
688
1188
|
const contentChanged = hash !== this._lastHash;
|
|
689
1189
|
this._lastHash = hash;
|
|
690
1190
|
|
|
@@ -698,30 +1198,46 @@ class AiAdvisorModule extends BaseModule {
|
|
|
698
1198
|
await this._set('aiAdvisor.summary', summary);
|
|
699
1199
|
await this._set('aiAdvisor.count', Array.isArray(suggestions) ? suggestions.length : 0);
|
|
700
1200
|
await this._set('aiAdvisor.score', score);
|
|
1201
|
+
await this._set('aiAdvisor.peakUsagePct', round(peakUsagePct, 1) || 0);
|
|
1202
|
+
await this._set('aiAdvisor.peakStateText', peakStateText);
|
|
1203
|
+
await this._set('aiAdvisor.gridConnectionLimitW', peakReferenceLimitW || 0);
|
|
1204
|
+
await this._set('aiAdvisor.peakWarnThresholdW', round(peakWarnThresholdW, 0) || 0);
|
|
1205
|
+
await this._set('aiAdvisor.weatherSummary', weatherSummary);
|
|
1206
|
+
await this._set('aiAdvisor.dailyPlanText', dailyPlan.text || '');
|
|
1207
|
+
await this._set('aiAdvisor.dailyPlanJson', safeJson(dailyPlan.items || [], '[]'));
|
|
1208
|
+
await this._set('aiAdvisor.evPlanText', evPlanText);
|
|
1209
|
+
await this._set('aiAdvisor.optimizationMode', cfg.optimizationMode || 'balanced');
|
|
1210
|
+
await this._set('aiAdvisor.comfortWindowSummary', comfortWindowSummary);
|
|
1211
|
+
await this._set('aiAdvisor.season', snapshot.season || seasonFromDate(new Date()));
|
|
1212
|
+
await this._set('aiAdvisor.anomalyText', snapshot.anomalyText || '');
|
|
1213
|
+
await this._set('aiAdvisor.forecastQualityPct', round(snapshot.forecastQualityPct, 1) || 0);
|
|
1214
|
+
await this._set('aiAdvisor.forecastQualityText', snapshot.forecastQualityText || '');
|
|
1215
|
+
await this._set('aiAdvisor.peakLearningText', learning.peakLearningText || '');
|
|
1216
|
+
await this._set('aiAdvisor.peakLearningJson', snapshot.peakLearningJson || '[]');
|
|
701
1217
|
await this._set('aiAdvisor.topTitle', top ? top.title : '');
|
|
702
1218
|
await this._set('aiAdvisor.topText', top ? top.text : '');
|
|
703
1219
|
await this._set('aiAdvisor.topAction', top ? top.action : '');
|
|
704
1220
|
await this._set('aiAdvisor.topWindow', top ? top.window : '');
|
|
1221
|
+
await this._set('aiAdvisor.topCategory', top ? top.category : '');
|
|
705
1222
|
if (contentChanged) {
|
|
706
1223
|
await this._set('aiAdvisor.suggestionsJson', jsonSuggestions);
|
|
707
1224
|
await this._set('aiAdvisor.snapshotJson', JSON.stringify(snap));
|
|
708
1225
|
} else {
|
|
709
|
-
// keep JSON in stateCache fresh after restarts even if identical writes are skipped by ioBroker internals
|
|
710
1226
|
try { if (typeof this.adapter.updateValue === 'function') this.adapter.updateValue('aiAdvisor.suggestionsJson', jsonSuggestions, now); } catch (_e) {}
|
|
711
1227
|
try { if (typeof this.adapter.updateValue === 'function') this.adapter.updateValue('aiAdvisor.snapshotJson', JSON.stringify(snap), now); } catch (_e) {}
|
|
712
1228
|
}
|
|
713
1229
|
await this._set('aiAdvisor.lastUpdate', now);
|
|
714
1230
|
await this._set('aiAdvisor.nextUpdate', now + Math.round(cfg.minIntervalSec * 1000));
|
|
715
1231
|
|
|
716
|
-
for (let i = 1; i <=
|
|
717
|
-
const
|
|
718
|
-
await this._set(`aiAdvisor.suggestions.${i}.title`,
|
|
719
|
-
await this._set(`aiAdvisor.suggestions.${i}.text`,
|
|
720
|
-
await this._set(`aiAdvisor.suggestions.${i}.action`,
|
|
721
|
-
await this._set(`aiAdvisor.suggestions.${i}.severity`,
|
|
722
|
-
await this._set(`aiAdvisor.suggestions.${i}.category`,
|
|
723
|
-
await this._set(`aiAdvisor.suggestions.${i}.window`,
|
|
724
|
-
await this._set(`aiAdvisor.suggestions.${i}.impact`,
|
|
1232
|
+
for (let i = 1; i <= 8; i++) {
|
|
1233
|
+
const s0 = (Array.isArray(suggestions) && suggestions[i - 1]) ? suggestions[i - 1] : null;
|
|
1234
|
+
await this._set(`aiAdvisor.suggestions.${i}.title`, s0 ? s0.title : '');
|
|
1235
|
+
await this._set(`aiAdvisor.suggestions.${i}.text`, s0 ? s0.text : '');
|
|
1236
|
+
await this._set(`aiAdvisor.suggestions.${i}.action`, s0 ? s0.action : '');
|
|
1237
|
+
await this._set(`aiAdvisor.suggestions.${i}.severity`, s0 ? s0.severity : '');
|
|
1238
|
+
await this._set(`aiAdvisor.suggestions.${i}.category`, s0 ? s0.category : '');
|
|
1239
|
+
await this._set(`aiAdvisor.suggestions.${i}.window`, s0 ? s0.window : '');
|
|
1240
|
+
await this._set(`aiAdvisor.suggestions.${i}.impact`, s0 ? s0.impact : '');
|
|
725
1241
|
}
|
|
726
1242
|
}
|
|
727
1243
|
|
|
@@ -729,17 +1245,17 @@ class AiAdvisorModule extends BaseModule {
|
|
|
729
1245
|
if (!this._inited) await this.init();
|
|
730
1246
|
const cfg = this._cfg();
|
|
731
1247
|
const now = Date.now();
|
|
732
|
-
|
|
733
1248
|
if (!cfg.enabled) {
|
|
734
1249
|
await this._publishDisabled(cfg, now);
|
|
735
1250
|
return;
|
|
736
1251
|
}
|
|
737
|
-
|
|
738
1252
|
const minMs = Math.max(10000, Math.round(cfg.minIntervalSec * 1000));
|
|
739
1253
|
if (this._lastRunMs && (now - this._lastRunMs) < minMs) return;
|
|
740
1254
|
this._lastRunMs = now;
|
|
741
|
-
|
|
742
|
-
|
|
1255
|
+
let snapshot = await this._snapshot();
|
|
1256
|
+
snapshot = this._updateLearning(snapshot, cfg);
|
|
1257
|
+
snapshot.dayPlan = this._makeDailyPlan(snapshot, cfg);
|
|
1258
|
+
this._lastPlan = snapshot.dayPlan;
|
|
743
1259
|
const suggestions = this._buildSuggestions(snapshot, cfg);
|
|
744
1260
|
await this._publish(snapshot, suggestions, cfg);
|
|
745
1261
|
}
|