iobroker.nexowatt-ui 0.7.38 → 0.7.40
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 +760 -288
- package/io-package.json +10 -2
- package/main.js +44 -2
- package/package.json +1 -1
- package/www/app.js +6 -0
- package/www/ems-apps.html +91 -28
- package/www/ems-apps.js +127 -5
- package/www/manifest.webmanifest +1 -1
- package/www/settings.html +49 -1
- package/www/styles.css +27 -0
- package/www/sw.js +1 -1
|
@@ -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,65 @@ 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
|
+
function buildPeakStateText(s, limitW, usagePct) {
|
|
113
|
+
const statusRaw = String(s && s.peakStatus || '').trim();
|
|
114
|
+
const suffix = statusRaw ? ` · Status ${statusRaw}` : '';
|
|
115
|
+
if (!limitW || !Number.isFinite(Number(limitW)) || Number(limitW) <= 0) {
|
|
116
|
+
return (s && s.peakConfigured ? 'Lastspitzenkappung bereit, aber kein Netzanschlusslimit verfügbar.' : 'Lastspitzenkappung nicht konfiguriert.') + suffix;
|
|
117
|
+
}
|
|
118
|
+
const state = s && s.peakActive
|
|
119
|
+
? 'Lastspitzenkappung aktiv'
|
|
120
|
+
: (s && s.peakConfigured ? 'Lastspitzenkappung bereit' : 'Lastspitzenkappung nicht konfiguriert');
|
|
121
|
+
return `${formatKw(s && s.gridImportW)} von ${formatKw(limitW)} (${formatPct(usagePct)}) · ${state}${suffix}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
62
124
|
function shortIsoWindow(from, to) {
|
|
63
125
|
const f = String(from || '').trim();
|
|
64
126
|
const t = String(to || '').trim();
|
|
@@ -66,7 +128,6 @@ function shortIsoWindow(from, to) {
|
|
|
66
128
|
if (!s) return '';
|
|
67
129
|
const d = new Date(s);
|
|
68
130
|
if (Number.isNaN(d.getTime())) return s;
|
|
69
|
-
const pad2 = (n) => String(n).padStart(2, '0');
|
|
70
131
|
const today = new Date();
|
|
71
132
|
const sameDay = d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate();
|
|
72
133
|
const tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
|
|
@@ -78,12 +139,144 @@ function shortIsoWindow(from, to) {
|
|
|
78
139
|
return fmt(f) || fmt(t) || '';
|
|
79
140
|
}
|
|
80
141
|
|
|
142
|
+
function parseClockMinutes(value, fallback = null) {
|
|
143
|
+
const raw = String(value === null || value === undefined ? '' : value).trim();
|
|
144
|
+
const m = raw.match(/^(\d{1,2})(?::(\d{1,2}))?$/);
|
|
145
|
+
if (!m) return fallback;
|
|
146
|
+
const h = Number(m[1]);
|
|
147
|
+
const min = Number(m[2] || 0);
|
|
148
|
+
if (!Number.isFinite(h) || !Number.isFinite(min) || h < 0 || h > 23 || min < 0 || min > 59) return fallback;
|
|
149
|
+
return h * 60 + min;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function minutesUntilClock(value, now = new Date()) {
|
|
153
|
+
const target = parseClockMinutes(value, null);
|
|
154
|
+
if (target === null) return null;
|
|
155
|
+
const current = now.getHours() * 60 + now.getMinutes();
|
|
156
|
+
let diff = target - current;
|
|
157
|
+
if (diff <= 0) diff += 1440;
|
|
158
|
+
return diff;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function formatClockMinutes(totalMinutes) {
|
|
162
|
+
const n = ((Math.round(Number(totalMinutes) || 0) % 1440) + 1440) % 1440;
|
|
163
|
+
return `${pad2(Math.floor(n / 60))}:${pad2(n % 60)}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function formatDurationMinutes(minutes) {
|
|
167
|
+
const n = Math.max(0, Math.round(Number(minutes) || 0));
|
|
168
|
+
if (n < 90) return `${n} min`;
|
|
169
|
+
return `${Math.floor(n / 60)} h ${String(n % 60).padStart(2, '0')} min`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function formatClockMs(ms) {
|
|
173
|
+
const n = Number(ms);
|
|
174
|
+
if (!Number.isFinite(n) || n <= 0) return '—';
|
|
175
|
+
const d = new Date(n);
|
|
176
|
+
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function tsToShortWindow(ts) {
|
|
180
|
+
const n = Number(ts);
|
|
181
|
+
if (!Number.isFinite(n) || n <= 0) return '';
|
|
182
|
+
const d = new Date(n);
|
|
183
|
+
const now = new Date();
|
|
184
|
+
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
|
185
|
+
const target = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
|
186
|
+
const day = target === today ? 'heute' : (target === today + 86400000 ? 'morgen' : `${pad2(d.getDate())}.${pad2(d.getMonth() + 1)}.`);
|
|
187
|
+
return `${day} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function formatWindowHour(hour) {
|
|
191
|
+
const h = ((Math.round(Number(hour) || 0) % 24) + 24) % 24;
|
|
192
|
+
return `${pad2(h)}:00–${pad2((h + 1) % 24)}:00`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function isInsideClockWindow(nowMs, startValue, endValue) {
|
|
196
|
+
const d = new Date(Number(nowMs) || Date.now());
|
|
197
|
+
const now = d.getHours() * 60 + d.getMinutes();
|
|
198
|
+
const start = parseClockMinutes(startValue, null);
|
|
199
|
+
const end = parseClockMinutes(endValue, null);
|
|
200
|
+
if (start === null || end === null || start === end) return false;
|
|
201
|
+
if (start < end) return now >= start && now < end;
|
|
202
|
+
return now >= start || now < end;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function seasonFromDate(now = new Date()) {
|
|
206
|
+
const month = (now instanceof Date ? now : new Date(now)).getMonth() + 1;
|
|
207
|
+
if (month === 12 || month <= 2) return 'winter';
|
|
208
|
+
if (month >= 3 && month <= 5) return 'spring';
|
|
209
|
+
if (month >= 6 && month <= 8) return 'summer';
|
|
210
|
+
return 'autumn';
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function seasonLabel(season) {
|
|
214
|
+
const s = String(season || '').toLowerCase();
|
|
215
|
+
if (s === 'winter') return 'Winter';
|
|
216
|
+
if (s === 'spring') return 'Frühjahr';
|
|
217
|
+
if (s === 'summer') return 'Sommer';
|
|
218
|
+
if (s === 'autumn') return 'Herbst';
|
|
219
|
+
return 'Saison';
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function normalizeOptimizationMode(value) {
|
|
223
|
+
const s = String(value || 'balanced').trim().toLowerCase();
|
|
224
|
+
if (['cost', 'kosten', 'preis'].includes(s)) return 'cost';
|
|
225
|
+
if (['autarky', 'autarkie', 'self', 'eigenverbrauch'].includes(s)) return 'autarky';
|
|
226
|
+
if (['co2', 'co₂', 'carbon', 'klima'].includes(s)) return 'co2';
|
|
227
|
+
if (['comfort', 'komfort'].includes(s)) return 'comfort';
|
|
228
|
+
if (['peak', 'netz', 'lastspitze'].includes(s)) return 'peak';
|
|
229
|
+
return 'balanced';
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function optimizationModeLabel(mode) {
|
|
233
|
+
const m = normalizeOptimizationMode(mode);
|
|
234
|
+
if (m === 'cost') return 'Kosten';
|
|
235
|
+
if (m === 'autarky') return 'Autarkie';
|
|
236
|
+
if (m === 'co2') return 'CO₂';
|
|
237
|
+
if (m === 'comfort') return 'Komfort';
|
|
238
|
+
if (m === 'peak') return 'Peak-Schutz';
|
|
239
|
+
return 'Balance';
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function average(list, field) {
|
|
243
|
+
const vals = (Array.isArray(list) ? list : []).map((x) => field ? Number(x && x[field]) : Number(x)).filter(Number.isFinite);
|
|
244
|
+
if (!vals.length) return null;
|
|
245
|
+
return vals.reduce((a, b) => a + b, 0) / vals.length;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function percentile(list, field, pct) {
|
|
249
|
+
const vals = (Array.isArray(list) ? list : []).map((x) => field ? Number(x && x[field]) : Number(x)).filter(Number.isFinite).sort((a, b) => a - b);
|
|
250
|
+
if (!vals.length) return null;
|
|
251
|
+
const idx = Math.max(0, Math.min(vals.length - 1, Math.round((vals.length - 1) * (Number(pct) || 0))));
|
|
252
|
+
return vals[idx];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function safeJson(value, fallback) {
|
|
256
|
+
try { return JSON.stringify(value); } catch (_e) { return fallback; }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function toSafeIdPart(value) {
|
|
260
|
+
return String(value === null || value === undefined ? '' : value)
|
|
261
|
+
.trim()
|
|
262
|
+
.toLowerCase()
|
|
263
|
+
.replace(/[^a-z0-9_-]+/g, '_')
|
|
264
|
+
.replace(/^_+|_+$/g, '');
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function priorityText(priorities) {
|
|
268
|
+
const labels = { evcs: 'Wallbox', thermal: 'Thermik', heatingRod: 'Heizstab', storage: 'Speicherreserve', generic: 'sonstige Lasten' };
|
|
269
|
+
const entries = Object.keys(labels)
|
|
270
|
+
.map((key) => ({ key, label: labels[key], value: Number(priorities && priorities[key]) || 0 }))
|
|
271
|
+
.filter((x) => x.value > 0)
|
|
272
|
+
.sort((a, b) => b.value - a.value);
|
|
273
|
+
if (!entries.length) return 'Prioritäten prüfen';
|
|
274
|
+
return entries.slice(0, 5).map((x, i) => `${i + 1}. ${x.label}`).join(' · ');
|
|
275
|
+
}
|
|
276
|
+
|
|
81
277
|
/**
|
|
82
278
|
* 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.
|
|
279
|
+
* Advisory-only: no actuator setpoints are written here.
|
|
87
280
|
*/
|
|
88
281
|
class AiAdvisorModule extends BaseModule {
|
|
89
282
|
constructor(adapter, dpRegistry) {
|
|
@@ -92,36 +285,55 @@ class AiAdvisorModule extends BaseModule {
|
|
|
92
285
|
this._lastRunMs = 0;
|
|
93
286
|
this._lastHash = '';
|
|
94
287
|
this._lastDisabledWriteMs = 0;
|
|
288
|
+
this._samples = [];
|
|
289
|
+
this._peakHourBuckets = Array.from({ length: 24 }, () => 0);
|
|
290
|
+
this._forecastChecks = [];
|
|
291
|
+
this._forecastQualityPct = null;
|
|
292
|
+
this._forecastQualityText = '';
|
|
293
|
+
this._lastLearning = { anomaly: false, anomalyText: '', forecastQualityPct: null, peakLearningText: '' };
|
|
294
|
+
this._lastPlan = { mode: 'balanced', items: [], text: '' };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
_cachedValue(id, fallback) {
|
|
298
|
+
try {
|
|
299
|
+
const rec = this.adapter && this.adapter.stateCache ? this.adapter.stateCache[id] : null;
|
|
300
|
+
if (rec && Object.prototype.hasOwnProperty.call(rec, 'value') && rec.value !== undefined && rec.value !== null && String(rec.value).trim() !== '') return rec.value;
|
|
301
|
+
} catch (_e) {}
|
|
302
|
+
return fallback;
|
|
95
303
|
}
|
|
96
304
|
|
|
97
305
|
_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
|
-
: {};
|
|
306
|
+
const c = (this.adapter && this.adapter.config && this.adapter.config.aiAdvisor && typeof this.adapter.config.aiAdvisor === 'object') ? this.adapter.config.aiAdvisor : {};
|
|
101
307
|
const cats = (c.categories && typeof c.categories === 'object') ? c.categories : {};
|
|
308
|
+
const prioCfg = (c.priorities && typeof c.priorities === 'object') ? c.priorities : {};
|
|
102
309
|
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
|
-
}
|
|
310
|
+
const customerEnabled = bool(this._cachedValue('settings.aiAdvisorEnabled', true), true);
|
|
110
311
|
const configuredEnabled = c.enabled !== false;
|
|
111
312
|
const showOnLiveCfg = (c.showInLive !== undefined) ? c.showInLive : c.showOnLive;
|
|
313
|
+
const optimizationMode = normalizeOptimizationMode(this._cachedValue('settings.aiAdvisorMode', this._cachedValue('settings.aiAdvisorOptimizationMode', c.optimizationMode || c.mode || 'balanced')));
|
|
314
|
+
const dailyPlanEnabled = c.dailyPlanEnabled !== false && c.dayPlanEnabled !== false;
|
|
315
|
+
const learningEnabled = c.learningEnabled !== false && c.peakLearningEnabled !== false;
|
|
316
|
+
const seasonLogicEnabled = c.seasonLogicEnabled !== false && c.seasonalStrategyEnabled !== false;
|
|
317
|
+
const priorityStorage = clamp(num(this._cachedValue('settings.aiAdvisorPriorityStorage', c.priorityStorage ?? prioCfg.storage ?? 90), 90), 1, 100);
|
|
318
|
+
const priorityEvcs = clamp(num(this._cachedValue('settings.aiAdvisorPriorityEvcs', c.priorityEvcs ?? prioCfg.evcs ?? 80), 80), 1, 100);
|
|
319
|
+
const priorityThermal = clamp(num(this._cachedValue('settings.aiAdvisorPriorityThermal', c.priorityThermal ?? prioCfg.thermal ?? 60), 60), 1, 100);
|
|
320
|
+
const priorityHeatingRod = clamp(num(this._cachedValue('settings.aiAdvisorPriorityHeatingRod', c.priorityHeatingRod ?? prioCfg.heatingRod ?? 45), 45), 1, 100);
|
|
321
|
+
const priorityGeneric = clamp(num(this._cachedValue('settings.aiAdvisorPriorityGeneric', c.priorityGeneric ?? prioCfg.generic ?? 40), 40), 1, 100);
|
|
112
322
|
return {
|
|
113
323
|
enabled: configuredEnabled && customerEnabled,
|
|
114
324
|
customerEnabled,
|
|
115
325
|
configuredEnabled,
|
|
116
326
|
advisoryOnly: true,
|
|
117
327
|
showInLive: showOnLiveCfg !== false,
|
|
118
|
-
|
|
119
|
-
// Keep legacy/canonical aliases as well so older configs remain valid.
|
|
328
|
+
optimizationMode,
|
|
120
329
|
minIntervalSec: clamp(num(c.minIntervalSec ?? c.intervalSec, 60), 10, 3600),
|
|
121
|
-
maxSuggestions: clamp(num(c.maxSuggestions,
|
|
330
|
+
maxSuggestions: clamp(num(c.maxSuggestions, 6), 1, 10),
|
|
122
331
|
minPriority: ['info', 'warning', 'action', 'critical'].includes(minPriority) ? minPriority : 'info',
|
|
123
332
|
pvSurplusThresholdW: clamp(num(c.pvSurplusThresholdW ?? c.exportHighW, 1500), 0, 1000000),
|
|
124
333
|
highImportThresholdW: clamp(num(c.highImportThresholdW ?? c.importHighW, 3000), 0, 10000000),
|
|
334
|
+
peakNearLimitPct: clamp(num(c.peakNearLimitPct ?? c.peakConnectionUsageWarnPct ?? c.gridConnectionWarnPct, 90), 50, 100),
|
|
335
|
+
peakCriticalLimitPct: clamp(num(c.peakCriticalLimitPct ?? c.peakConnectionUsageCriticalPct ?? c.gridConnectionCriticalPct, 98), 90, 120),
|
|
336
|
+
weatherRainRiskPct: clamp(num(c.weatherRainRiskPct ?? c.weatherRainProbabilityPct, 60), 0, 100),
|
|
125
337
|
lowSocPct: clamp(num(c.lowSocPct, 25), 0, 100),
|
|
126
338
|
highSocPct: clamp(num(c.highSocPct, 85), 0, 100),
|
|
127
339
|
minSocForDischargePct: clamp(num(c.minSocForDischargePct, 35), 0, 100),
|
|
@@ -131,13 +343,50 @@ class AiAdvisorModule extends BaseModule {
|
|
|
131
343
|
expensivePriceMarginEurKwh: clamp(num(c.expensivePriceMarginEurKwh, 0.05), 0, 10),
|
|
132
344
|
staleTimeoutSec: clamp(num(c.staleTimeoutSec, 300), 30, 86400),
|
|
133
345
|
includeInstallerHints: c.includeInstallerHints !== false,
|
|
346
|
+
dailyPlanEnabled,
|
|
347
|
+
dayPlanEnabled: dailyPlanEnabled,
|
|
348
|
+
evGoalPlanningEnabled: c.evGoalPlanningEnabled !== false && c.evGoalEnabled !== false,
|
|
349
|
+
storageStrategyEnabled: c.storageStrategyEnabled !== false,
|
|
350
|
+
learningEnabled,
|
|
351
|
+
peakLearningEnabled: learningEnabled,
|
|
352
|
+
anomalyDetectionEnabled: c.anomalyDetectionEnabled !== false,
|
|
353
|
+
forecastQualityEnabled: c.forecastQualityEnabled !== false,
|
|
354
|
+
seasonLogicEnabled,
|
|
355
|
+
seasonalStrategyEnabled: seasonLogicEnabled,
|
|
356
|
+
comfortHintsEnabled: c.comfortHintsEnabled !== false && c.comfortWindowsEnabled !== false,
|
|
357
|
+
co2HintsEnabled: c.co2HintsEnabled !== false && c.co2Enabled !== false,
|
|
358
|
+
comfortStart: String(this._cachedValue('settings.aiAdvisorComfortStart', c.comfortStart || '06:00') || '06:00'),
|
|
359
|
+
comfortEnd: String(this._cachedValue('settings.aiAdvisorComfortEnd', c.comfortEnd || '22:00') || '22:00'),
|
|
360
|
+
quietHoursStart: String(this._cachedValue('settings.aiAdvisorQuietHoursStart', c.quietHoursStart || '22:00') || '22:00'),
|
|
361
|
+
quietHoursEnd: String(this._cachedValue('settings.aiAdvisorQuietHoursEnd', c.quietHoursEnd || '06:00') || '06:00'),
|
|
362
|
+
evReadyBy: String(this._cachedValue('settings.aiAdvisorEvReadyBy', c.evReadyBy || c.evDepartureTime || '07:00') || '07:00'),
|
|
363
|
+
evTargetSocPct: clamp(num(this._cachedValue('settings.aiAdvisorEvTargetSocPct', c.evTargetSocPct ?? c.defaultEvTargetSocPct ?? 80), 80), 20, 100),
|
|
364
|
+
evBatteryCapacityKwh: clamp(num(c.evBatteryCapacityKwh, 60), 10, 250),
|
|
365
|
+
thermalReadyBy: String(this._cachedValue('settings.aiAdvisorThermalReadyBy', c.thermalReadyBy || c.warmWaterReadyBy || '18:00') || '18:00'),
|
|
366
|
+
anomalyMinSamples: clamp(num(c.anomalyMinSamples, 12), 4, 10000),
|
|
367
|
+
anomalyFactor: clamp(num(c.anomalyFactor ?? c.anomalyMultiplier, 2.2), 1.1, 20),
|
|
368
|
+
anomalyMinImportW: clamp(num(c.anomalyMinImportW ?? c.anomalyHighLoadW, 5000), 0, 100000000),
|
|
369
|
+
anomalyHighLoadW: clamp(num(c.anomalyHighLoadW ?? c.anomalyMinImportW, 5500), 500, 100000000),
|
|
370
|
+
nightBaseLoadW: clamp(num(c.nightBaseLoadW, 900), 100, 100000000),
|
|
371
|
+
evUrgentRemainingMin: clamp(num(c.evUrgentRemainingMin, 90), 15, 1440),
|
|
372
|
+
forecastQualityWarnPct: clamp(num(c.forecastQualityWarnPct, 65), 0, 100),
|
|
373
|
+
co2LowGPerKwh: clamp(num(c.co2LowGPerKwh, 250), 0, 2000),
|
|
374
|
+
co2HighGPerKwh: clamp(num(c.co2HighGPerKwh, 500), 0, 2000),
|
|
375
|
+
priorities: { storage: priorityStorage, evcs: priorityEvcs, thermal: priorityThermal, heatingRod: priorityHeatingRod, generic: priorityGeneric },
|
|
134
376
|
categories: {
|
|
135
377
|
tariff: cats.tariff !== false,
|
|
136
378
|
pv: cats.pv !== false,
|
|
137
379
|
storage: cats.storage !== false,
|
|
138
380
|
evcs: cats.evcs !== false,
|
|
139
381
|
peak: cats.peak !== false,
|
|
382
|
+
weather: cats.weather !== false,
|
|
140
383
|
heating: cats.heating !== false,
|
|
384
|
+
plan: cats.plan !== false && cats.dailyPlan !== false,
|
|
385
|
+
dailyPlan: cats.dailyPlan !== false && cats.plan !== false,
|
|
386
|
+
anomaly: cats.anomaly !== false,
|
|
387
|
+
comfort: cats.comfort !== false,
|
|
388
|
+
learning: cats.learning !== false,
|
|
389
|
+
co2: cats.co2 !== false,
|
|
141
390
|
system: cats.system !== false,
|
|
142
391
|
},
|
|
143
392
|
};
|
|
@@ -151,37 +400,18 @@ class AiAdvisorModule extends BaseModule {
|
|
|
151
400
|
|
|
152
401
|
async _ensureStates() {
|
|
153
402
|
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
|
-
|
|
403
|
+
await a.setObjectNotExistsAsync('aiAdvisor', { type: 'channel', common: { name: 'KI-Energieberater' }, native: {} });
|
|
404
|
+
await a.setObjectNotExistsAsync('aiAdvisor.suggestions', { type: 'channel', common: { name: 'KI-Energieberater Vorschläge' }, native: {} });
|
|
166
405
|
const mk = async (id, name, type, role, unit = undefined) => {
|
|
167
406
|
await a.setObjectNotExistsAsync(id, {
|
|
168
407
|
type: 'state',
|
|
169
|
-
common: {
|
|
170
|
-
name,
|
|
171
|
-
type,
|
|
172
|
-
role,
|
|
173
|
-
read: true,
|
|
174
|
-
write: false,
|
|
175
|
-
...(unit ? { unit } : {}),
|
|
176
|
-
},
|
|
408
|
+
common: { name, type, role, read: true, write: false, ...(unit ? { unit } : {}) },
|
|
177
409
|
native: {},
|
|
178
410
|
});
|
|
179
411
|
};
|
|
180
|
-
|
|
181
412
|
await mk('aiAdvisor.enabled', 'KI-Energieberater aktiv', 'boolean', 'indicator');
|
|
182
413
|
await mk('aiAdvisor.advisoryOnly', 'Nur Beratung, keine Schaltentscheidungen', 'boolean', 'indicator');
|
|
183
414
|
await mk('aiAdvisor.showInLive', 'In LIVE anzeigen', 'boolean', 'indicator');
|
|
184
|
-
// Compatibility alias: App-Center and older VIS builds used "showOnLive".
|
|
185
415
|
await mk('aiAdvisor.showOnLive', 'In LIVE anzeigen', 'boolean', 'indicator');
|
|
186
416
|
await mk('aiAdvisor.status', 'Status', 'string', 'text');
|
|
187
417
|
await mk('aiAdvisor.severity', 'Höchste Priorität / Severity', 'string', 'text');
|
|
@@ -189,21 +419,33 @@ class AiAdvisorModule extends BaseModule {
|
|
|
189
419
|
await mk('aiAdvisor.summary', 'Zusammenfassung', 'string', 'text');
|
|
190
420
|
await mk('aiAdvisor.count', 'Anzahl Vorschläge', 'number', 'value');
|
|
191
421
|
await mk('aiAdvisor.score', 'Optimierungs-Score', 'number', 'value', '%');
|
|
422
|
+
await mk('aiAdvisor.peakUsagePct', 'Netzanschluss-Auslastung', 'number', 'value', '%');
|
|
423
|
+
await mk('aiAdvisor.peakStateText', 'Peak-Shaving Status', 'string', 'text');
|
|
424
|
+
await mk('aiAdvisor.gridConnectionLimitW', 'Netzanschlusslimit', 'number', 'value.power', 'W');
|
|
425
|
+
await mk('aiAdvisor.peakWarnThresholdW', 'Peak-Vorwarnschwelle', 'number', 'value.power', 'W');
|
|
426
|
+
await mk('aiAdvisor.weatherSummary', 'Wetter-Prognose Zusammenfassung', 'string', 'text');
|
|
427
|
+
await mk('aiAdvisor.dailyPlanText', 'KI-Tagesfahrplan Text', 'string', 'text');
|
|
428
|
+
await mk('aiAdvisor.dailyPlanJson', 'KI-Tagesfahrplan JSON', 'string', 'json');
|
|
429
|
+
await mk('aiAdvisor.evPlanText', 'EV-Zielplanung Text', 'string', 'text');
|
|
430
|
+
await mk('aiAdvisor.optimizationMode', 'Optimierungsziel', 'string', 'text');
|
|
431
|
+
await mk('aiAdvisor.comfortWindowSummary', 'Komfortfenster Zusammenfassung', 'string', 'text');
|
|
432
|
+
await mk('aiAdvisor.season', 'Saisonlogik', 'string', 'text');
|
|
433
|
+
await mk('aiAdvisor.anomalyText', 'Anomalie-Erkennung Text', 'string', 'text');
|
|
434
|
+
await mk('aiAdvisor.forecastQualityPct', 'Prognosequalität', 'number', 'value', '%');
|
|
435
|
+
await mk('aiAdvisor.forecastQualityText', 'Prognosequalität Text', 'string', 'text');
|
|
436
|
+
await mk('aiAdvisor.peakLearningText', 'Lastspitzen-Lernfunktion Text', 'string', 'text');
|
|
437
|
+
await mk('aiAdvisor.peakLearningJson', 'Lastspitzen-Lernfunktion JSON', 'string', 'json');
|
|
192
438
|
await mk('aiAdvisor.topTitle', 'Top-Vorschlag Titel', 'string', 'text');
|
|
193
439
|
await mk('aiAdvisor.topText', 'Top-Vorschlag Text', 'string', 'text');
|
|
194
440
|
await mk('aiAdvisor.topAction', 'Top-Vorschlag Handlung', 'string', 'text');
|
|
195
441
|
await mk('aiAdvisor.topWindow', 'Top-Vorschlag Zeitfenster', 'string', 'text');
|
|
442
|
+
await mk('aiAdvisor.topCategory', 'Top-Vorschlag Kategorie', 'string', 'text');
|
|
196
443
|
await mk('aiAdvisor.suggestionsJson', 'Vorschläge JSON', 'string', 'json');
|
|
197
444
|
await mk('aiAdvisor.snapshotJson', 'KI-Energieberater Snapshot JSON', 'string', 'json');
|
|
198
445
|
await mk('aiAdvisor.lastUpdate', 'Letzte Aktualisierung', 'number', 'value.time');
|
|
199
446
|
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
|
-
});
|
|
447
|
+
for (let i = 1; i <= 8; i++) {
|
|
448
|
+
await a.setObjectNotExistsAsync(`aiAdvisor.suggestions.${i}`, { type: 'channel', common: { name: `Vorschlag ${i}` }, native: {} });
|
|
207
449
|
await mk(`aiAdvisor.suggestions.${i}.title`, `Vorschlag ${i} Titel`, 'string', 'text');
|
|
208
450
|
await mk(`aiAdvisor.suggestions.${i}.text`, `Vorschlag ${i} Text`, 'string', 'text');
|
|
209
451
|
await mk(`aiAdvisor.suggestions.${i}.action`, `Vorschlag ${i} Handlung`, 'string', 'text');
|
|
@@ -256,6 +498,59 @@ class AiAdvisorModule extends BaseModule {
|
|
|
256
498
|
return fallback;
|
|
257
499
|
}
|
|
258
500
|
|
|
501
|
+
_chargingWallboxKeys() {
|
|
502
|
+
const keys = [];
|
|
503
|
+
try {
|
|
504
|
+
const cfg = (this.adapter && this.adapter.config && this.adapter.config.chargingManagement && typeof this.adapter.config.chargingManagement === 'object') ? this.adapter.config.chargingManagement : {};
|
|
505
|
+
const list = Array.isArray(cfg.wallboxes) ? cfg.wallboxes : [];
|
|
506
|
+
for (let i = 0; i < list.length; i++) {
|
|
507
|
+
const wb = list[i] || {};
|
|
508
|
+
const raw = wb.key || wb.id || wb.index || wb.name || `lp${i + 1}`;
|
|
509
|
+
const safe = toSafeIdPart(raw);
|
|
510
|
+
if (safe) keys.push(safe);
|
|
511
|
+
}
|
|
512
|
+
} catch (_e) {}
|
|
513
|
+
for (let i = 1; i <= 8; i++) keys.push(`lp${i}`);
|
|
514
|
+
return Array.from(new Set(keys.filter(Boolean)));
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async _readEvGoals() {
|
|
518
|
+
const out = [];
|
|
519
|
+
const keys = this._chargingWallboxKeys();
|
|
520
|
+
for (const safe of keys) {
|
|
521
|
+
const base = `chargingManagement.wallboxes.${safe}`;
|
|
522
|
+
const goalEnabled = await this._readBool([`${base}.goalEnabled`], false);
|
|
523
|
+
const goalActive = await this._readBool([`${base}.goalActive`], false);
|
|
524
|
+
const vehiclePlugged = await this._readBool([`${base}.vehiclePlugged`], false);
|
|
525
|
+
const goalFinishTs = await this._readNumber([`${base}.goalFinishTs`], 0);
|
|
526
|
+
const goalTargetSocPct = await this._readNumber([`${base}.goalTargetSocPct`], null);
|
|
527
|
+
const goalRemainingMin = await this._readNumber([`${base}.goalRemainingMin`], null);
|
|
528
|
+
const goalDesiredPowerW = await this._readNumber([`${base}.goalDesiredPowerW`], null);
|
|
529
|
+
const goalRequiredPowerW = await this._readNumber([`${base}.goalRequiredPowerW`], null);
|
|
530
|
+
const goalShortfallW = await this._readNumber([`${base}.goalShortfallW`], null);
|
|
531
|
+
const goalStatus = await this._readString([`${base}.goalStatus`], '');
|
|
532
|
+
const chargingPowerW = await this._readNumber([`${base}.actualPowerW`, `${base}.powerW`, `${base}.usedW`], null);
|
|
533
|
+
const hasData = goalEnabled || goalActive || vehiclePlugged || (Number.isFinite(Number(goalFinishTs)) && Number(goalFinishTs) > 0) || (goalStatus && goalStatus !== 'idle');
|
|
534
|
+
if (!hasData) continue;
|
|
535
|
+
out.push({
|
|
536
|
+
id: safe,
|
|
537
|
+
label: safe.toUpperCase(),
|
|
538
|
+
goalEnabled,
|
|
539
|
+
goalActive,
|
|
540
|
+
vehiclePlugged,
|
|
541
|
+
goalFinishTs: Number.isFinite(Number(goalFinishTs)) ? Number(goalFinishTs) : 0,
|
|
542
|
+
goalTargetSocPct: finiteNumber(goalTargetSocPct) ? goalTargetSocPct : null,
|
|
543
|
+
goalRemainingMin: finiteNumber(goalRemainingMin) ? goalRemainingMin : null,
|
|
544
|
+
goalDesiredPowerW: finiteNumber(goalDesiredPowerW) ? goalDesiredPowerW : null,
|
|
545
|
+
goalRequiredPowerW: finiteNumber(goalRequiredPowerW) ? goalRequiredPowerW : null,
|
|
546
|
+
goalShortfallW: finiteNumber(goalShortfallW) ? goalShortfallW : null,
|
|
547
|
+
goalStatus,
|
|
548
|
+
chargingPowerW: finiteNumber(chargingPowerW) ? Math.max(0, chargingPowerW) : null,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
return out;
|
|
552
|
+
}
|
|
553
|
+
|
|
259
554
|
async _snapshot() {
|
|
260
555
|
const gridRawW = await this._readNumber(['ems.gridPowerRawW', 'grid.powerRawW', 'gridPointPower'], null);
|
|
261
556
|
const gridW = await this._readNumber(['ems.budget.gridW', 'ems.gridPowerW', 'grid.powerW'], gridRawW || 0);
|
|
@@ -263,6 +558,13 @@ class AiAdvisorModule extends BaseModule {
|
|
|
263
558
|
const gridExportW = await this._readNumber(['ems.budget.gridExportW', 'gridSellPower'], Math.max(0, -(num(gridRawW, gridW || 0))));
|
|
264
559
|
const pvPowerW = await this._readNumber(['ems.budget.pvPowerW', 'derived.core.pv.totalW', 'pvPower', 'productionTotal'], 0);
|
|
265
560
|
const pvBudgetW = await this._readNumber(['ems.budget.pvBudgetW', 'ems.budget.remainingPvW'], 0);
|
|
561
|
+
const consumptionTotalW = await this._readNumber(['consumptionTotal', 'ems.budget.consumptionTotalW', 'building.powerW', 'loadPower'], null);
|
|
562
|
+
const productionEnergyKwh = await this._readNumber(['productionEnergyKwh', 'pvEnergyKwh', 'production.energyKwh'], null);
|
|
563
|
+
|
|
564
|
+
const cfgGridConnectionW = num(this.adapter && this.adapter.config && this.adapter.config.installerConfig ? this.adapter.config.installerConfig.gridConnectionPower : 0, 0);
|
|
565
|
+
const gridConnectionLimitW = await this._readNumber(['ems.core.gridConnectionLimitW_cfg', 'installer.gridConnectionPower', 'installerConfig.gridConnectionPower'], cfgGridConnectionW || null);
|
|
566
|
+
const gridImportLimitEffectiveW = await this._readNumber(['ems.core.gridImportLimitW_effective', 'chargingManagement.control.gridImportLimitW_effective'], null);
|
|
567
|
+
const gridImportLimitSource = await this._readString(['ems.core.gridImportLimitW_source'], '');
|
|
266
568
|
|
|
267
569
|
const storageSocPct = await this._readNumber(['storageFarm.totalSoc', 'speicher.regelung.socPct', 'storageSoc'], null);
|
|
268
570
|
const storageChargeW = await this._readNumber(['ems.budget.storageChargeW', 'storageFarm.totalChargePowerW', 'storageChargePower'], 0);
|
|
@@ -271,6 +573,38 @@ class AiAdvisorModule extends BaseModule {
|
|
|
271
573
|
const evcsUsedW = await this._readNumber(['chargingManagement.control.usedW', 'evcs.totalPowerW', 'consumptionEvcs'], 0);
|
|
272
574
|
const thermalUsedW = await this._readNumber(['thermal.summary.budgetUsedW'], 0);
|
|
273
575
|
const heatingRodUsedW = await this._readNumber(['heatingRod.summary.budgetUsedW'], 0);
|
|
576
|
+
let houseLoadW = await this._readNumber(['ems.budget.loadW', 'ems.budget.houseLoadW', 'derived.core.load.totalW', 'buildingConsumptionW', 'consumptionTotal', 'consumptionHouse'], null);
|
|
577
|
+
if (!finiteNumber(houseLoadW)) {
|
|
578
|
+
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)));
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const aiCfg = (this.adapter && this.adapter.config && this.adapter.config.aiAdvisor && typeof this.adapter.config.aiAdvisor === 'object') ? this.adapter.config.aiAdvisor : {};
|
|
582
|
+
const settingsCfg = (this.adapter && this.adapter.config && this.adapter.config.settingsConfig && typeof this.adapter.config.settingsConfig === 'object') ? this.adapter.config.settingsConfig : {};
|
|
583
|
+
const evcsCountRaw = num(settingsCfg.evcsCount ?? this.adapter.evcsCount, Array.isArray(this.adapter && this.adapter.evcsList) ? this.adapter.evcsList.length : 0);
|
|
584
|
+
const evcsCount = Math.max(0, Math.min(20, Math.round(num(evcsCountRaw, 0))));
|
|
585
|
+
let evConnectedCount = 0;
|
|
586
|
+
let evVehicleSocPct = null;
|
|
587
|
+
let evStatusText = '';
|
|
588
|
+
let evMode = '';
|
|
589
|
+
for (let i = 1; i <= Math.max(1, evcsCount || 1); i++) {
|
|
590
|
+
const status = await this._readString([`evcs.${i}.status`], '');
|
|
591
|
+
const active = await this._readBool([`evcs.${i}.active`], false);
|
|
592
|
+
const connectedByStatus = /charging|connected|plug|suspendedev|preparing|laden|verbunden/i.test(status || '');
|
|
593
|
+
if (active || connectedByStatus) evConnectedCount += 1;
|
|
594
|
+
if (!evStatusText && status) evStatusText = status;
|
|
595
|
+
if (!evMode) evMode = await this._readString([`evcs.${i}.mode`], '');
|
|
596
|
+
const soc = await this._readNumber([`evcs.${i}.vehicleSoc`, `evcs.${i}.vehicleSocPct`, `evcs.${i}.socPct`], null);
|
|
597
|
+
if (finiteNumber(soc)) evVehicleSocPct = evVehicleSocPct === null ? soc : Math.min(evVehicleSocPct, soc);
|
|
598
|
+
}
|
|
599
|
+
const connectedCount = await this._readNumber(['chargingManagement.control.connectedCount', 'evcs.connectedCount'], null);
|
|
600
|
+
if (finiteNumber(connectedCount) && connectedCount > 0) evConnectedCount = Math.max(evConnectedCount, Math.round(connectedCount));
|
|
601
|
+
const evTargetSocPct = await this._readNumber(['settings.aiAdvisorEvTargetSocPct', 'chargingManagement.targetSocPct', 'evcs.1.targetSoc', 'evcs.1.targetSocPct'], num(aiCfg.evTargetSocPct ?? aiCfg.defaultEvTargetSocPct, 80));
|
|
602
|
+
const evBatteryCapacityKwh = num(aiCfg.evBatteryCapacityKwh, 60);
|
|
603
|
+
const evReadyBy = await this._readString(['settings.aiAdvisorEvReadyBy', 'chargingManagement.readyBy', 'evcs.1.readyBy', 'evcs.1.departureTime'], String(aiCfg.evReadyBy || aiCfg.evDepartureTime || '07:00'));
|
|
604
|
+
const evMinutesUntilReady = minutesUntilClock(evReadyBy, new Date());
|
|
605
|
+
const evEnergyNeededKwh = (finiteNumber(evVehicleSocPct) && finiteNumber(evTargetSocPct) && finiteNumber(evBatteryCapacityKwh))
|
|
606
|
+
? Math.max(0, (evBatteryCapacityKwh * (Math.min(100, evTargetSocPct) - Math.max(0, evVehicleSocPct))) / 100)
|
|
607
|
+
: null;
|
|
274
608
|
|
|
275
609
|
const tariffActive = await this._readBool(['tarif.aktiv', 'ems.budget.tariff.active'], false);
|
|
276
610
|
const tariffState = await this._readString(['tarif.state', 'ems.budget.tariff.state'], '');
|
|
@@ -281,18 +615,37 @@ class AiAdvisorModule extends BaseModule {
|
|
|
281
615
|
const nextCheapTo = await this._readString(['tarif.naechstesGuensigBis'], '');
|
|
282
616
|
const negativeActive = await this._readBool(['tarif.negativpreisAktiv', 'ems.budget.tariff.negativeActive'], false);
|
|
283
617
|
const gridImportPreferred = await this._readBool(['tarif.netzbezugBevorzugt', 'ems.budget.tariff.gridImportPreferred'], negativeActive);
|
|
618
|
+
const co2IntensityGPerKwh = await this._readNumber(['tarif.co2IntensityGPerKwh', 'grid.co2IntensityGPerKwh', 'co2.gridIntensityGPerKwh'], null);
|
|
284
619
|
|
|
285
620
|
const pvForecastUsable = await this._readBool(['ems.budget.forecast.usable', 'forecast.pv.valid'], false);
|
|
286
621
|
const pvKwh6 = await this._readNumber(['ems.budget.forecast.kwhNext6h', 'forecast.pv.kwhNext6h'], 0);
|
|
287
622
|
const pvKwh12 = await this._readNumber(['ems.budget.forecast.kwhNext12h', 'forecast.pv.kwhNext12h'], 0);
|
|
288
623
|
const pvKwh24 = await this._readNumber(['ems.budget.forecast.kwhNext24h', 'forecast.pv.kwhNext24h'], 0);
|
|
289
624
|
const pvPeak24W = await this._readNumber(['ems.budget.forecast.peakNext24h', 'forecast.pv.peakWNext24h'], 0);
|
|
625
|
+
const forecastQualityPct = await this._readNumber(['ems.budget.forecast.qualityPct', 'forecast.pv.qualityPct', 'forecast.qualityPct'], null);
|
|
626
|
+
const forecastErrorPct = await this._readNumber(['ems.budget.forecast.errorPct', 'forecast.pv.errorPct', 'forecast.errorPct'], null);
|
|
627
|
+
|
|
628
|
+
const weatherEnabled = await this._readBool(['settings.weatherEnabled'], false);
|
|
629
|
+
const weatherTempC = await this._readNumber(['weatherTempC'], null);
|
|
630
|
+
const weatherText = await this._readString(['weatherText'], '');
|
|
631
|
+
const weatherCloudPct = await this._readNumber(['weatherCloudPct'], null);
|
|
632
|
+
const weatherWindKmh = await this._readNumber(['weatherWindKmh'], null);
|
|
633
|
+
const weatherTomorrowMinC = await this._readNumber(['weatherTomorrowMinC'], null);
|
|
634
|
+
const weatherTomorrowMaxC = await this._readNumber(['weatherTomorrowMaxC'], null);
|
|
635
|
+
const weatherTomorrowPrecipPct = await this._readNumber(['weatherTomorrowPrecipPct'], null);
|
|
636
|
+
const weatherTomorrowCode = await this._readNumber(['weatherTomorrowCode'], null);
|
|
637
|
+
const weatherTomorrowText = await this._readString(['weatherTomorrowText'], '');
|
|
290
638
|
|
|
291
639
|
const peakActive = await this._readBool(['peakShaving.control.active'], false);
|
|
292
640
|
const peakLimitW = await this._readNumber(['peakShaving.control.limitW', 'ems.core.gridImportLimitW_effective'], null);
|
|
293
641
|
const peakOverW = await this._readNumber(['peakShaving.control.overW'], 0);
|
|
642
|
+
const peakStatus = await this._readString(['peakShaving.control.status'], '');
|
|
294
643
|
const hlzfActive = await this._readBool(['peakShaving.atypical.activeWindow'], false);
|
|
295
644
|
const para14aActive = await this._readBool(['para14a.active', 'ems.core.para14aActive'], false);
|
|
645
|
+
const peakStatusLower = String(peakStatus || '').toLowerCase();
|
|
646
|
+
const peakConfigured = isPeakShavingConfigured(this.adapter && this.adapter.config)
|
|
647
|
+
|| (finiteNumber(peakLimitW) && peakLimitW > 0 && !['disabled', 'off', 'inactive', 'aus'].includes(peakStatusLower));
|
|
648
|
+
const evGoals = await this._readEvGoals();
|
|
296
649
|
|
|
297
650
|
return {
|
|
298
651
|
ts: Date.now(),
|
|
@@ -300,14 +653,29 @@ class AiAdvisorModule extends BaseModule {
|
|
|
300
653
|
gridW,
|
|
301
654
|
gridImportW: Math.max(0, num(gridImportW, 0)),
|
|
302
655
|
gridExportW: Math.max(0, num(gridExportW, 0)),
|
|
656
|
+
gridConnectionLimitW: finiteNumber(gridConnectionLimitW) && gridConnectionLimitW > 0 ? gridConnectionLimitW : null,
|
|
657
|
+
gridImportLimitEffectiveW: finiteNumber(gridImportLimitEffectiveW) && gridImportLimitEffectiveW > 0 ? gridImportLimitEffectiveW : null,
|
|
658
|
+
gridImportLimitSource,
|
|
303
659
|
pvPowerW: Math.max(0, num(pvPowerW, 0)),
|
|
304
660
|
pvBudgetW: Math.max(0, num(pvBudgetW, 0)),
|
|
661
|
+
consumptionTotalW: finiteNumber(consumptionTotalW) ? Math.max(0, num(consumptionTotalW, 0)) : null,
|
|
662
|
+
productionEnergyKwh: finiteNumber(productionEnergyKwh) ? productionEnergyKwh : null,
|
|
305
663
|
storageSocPct: finiteNumber(storageSocPct) ? storageSocPct : null,
|
|
306
664
|
storageChargeW: Math.max(0, num(storageChargeW, 0)),
|
|
307
665
|
storageDischargeW: Math.max(0, num(storageDischargeW, 0)),
|
|
308
666
|
evcsUsedW: Math.max(0, num(evcsUsedW, 0)),
|
|
309
667
|
thermalUsedW: Math.max(0, num(thermalUsedW, 0)),
|
|
310
668
|
heatingRodUsedW: Math.max(0, num(heatingRodUsedW, 0)),
|
|
669
|
+
houseLoadW: Math.max(0, num(houseLoadW, 0)),
|
|
670
|
+
evConnectedCount: Math.max(0, Math.round(num(evConnectedCount, 0))),
|
|
671
|
+
evVehicleSocPct: finiteNumber(evVehicleSocPct) ? evVehicleSocPct : null,
|
|
672
|
+
evTargetSocPct: finiteNumber(evTargetSocPct) ? evTargetSocPct : null,
|
|
673
|
+
evBatteryCapacityKwh: finiteNumber(evBatteryCapacityKwh) ? evBatteryCapacityKwh : null,
|
|
674
|
+
evReadyBy,
|
|
675
|
+
evMinutesUntilReady: finiteNumber(evMinutesUntilReady) ? evMinutesUntilReady : null,
|
|
676
|
+
evEnergyNeededKwh: finiteNumber(evEnergyNeededKwh) ? evEnergyNeededKwh : null,
|
|
677
|
+
evStatusText,
|
|
678
|
+
evMode,
|
|
311
679
|
tariffActive,
|
|
312
680
|
tariffState,
|
|
313
681
|
priceNow,
|
|
@@ -317,17 +685,187 @@ class AiAdvisorModule extends BaseModule {
|
|
|
317
685
|
nextCheapTo,
|
|
318
686
|
negativeActive,
|
|
319
687
|
gridImportPreferred,
|
|
688
|
+
co2IntensityGPerKwh: finiteNumber(co2IntensityGPerKwh) ? co2IntensityGPerKwh : null,
|
|
320
689
|
pvForecastUsable,
|
|
321
690
|
pvKwh6: Math.max(0, num(pvKwh6, 0)),
|
|
322
691
|
pvKwh12: Math.max(0, num(pvKwh12, 0)),
|
|
323
692
|
pvKwh24: Math.max(0, num(pvKwh24, 0)),
|
|
324
693
|
pvPeak24W: Math.max(0, num(pvPeak24W, 0)),
|
|
694
|
+
forecastQualityPct: finiteNumber(forecastQualityPct) ? forecastQualityPct : null,
|
|
695
|
+
forecastErrorPct: finiteNumber(forecastErrorPct) ? forecastErrorPct : null,
|
|
696
|
+
weatherEnabled,
|
|
697
|
+
weatherTempC: finiteNumber(weatherTempC) ? weatherTempC : null,
|
|
698
|
+
weatherText,
|
|
699
|
+
weatherCloudPct: finiteNumber(weatherCloudPct) ? weatherCloudPct : null,
|
|
700
|
+
weatherWindKmh: finiteNumber(weatherWindKmh) ? weatherWindKmh : null,
|
|
701
|
+
weatherTomorrowMinC: finiteNumber(weatherTomorrowMinC) ? weatherTomorrowMinC : null,
|
|
702
|
+
weatherTomorrowMaxC: finiteNumber(weatherTomorrowMaxC) ? weatherTomorrowMaxC : null,
|
|
703
|
+
weatherTomorrowPrecipPct: finiteNumber(weatherTomorrowPrecipPct) ? weatherTomorrowPrecipPct : null,
|
|
704
|
+
weatherTomorrowCode: finiteNumber(weatherTomorrowCode) ? weatherTomorrowCode : null,
|
|
705
|
+
weatherTomorrowText,
|
|
325
706
|
peakActive,
|
|
326
|
-
peakLimitW,
|
|
707
|
+
peakLimitW: finiteNumber(peakLimitW) && peakLimitW > 0 ? peakLimitW : null,
|
|
327
708
|
peakOverW: Math.max(0, num(peakOverW, 0)),
|
|
709
|
+
peakStatus,
|
|
710
|
+
peakConfigured,
|
|
328
711
|
hlzfActive,
|
|
329
712
|
para14aActive,
|
|
713
|
+
evGoals,
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
_updateLearning(snapshot, cfg) {
|
|
718
|
+
const s = Object.assign({}, snapshot || {});
|
|
719
|
+
const now = Number(s.ts) || Date.now();
|
|
720
|
+
const d = new Date(now);
|
|
721
|
+
const hour = d.getHours();
|
|
722
|
+
const sample = {
|
|
723
|
+
ts: now,
|
|
724
|
+
hour,
|
|
725
|
+
gridImportW: Math.max(0, Number(s.gridImportW) || 0),
|
|
726
|
+
gridExportW: Math.max(0, Number(s.gridExportW) || 0),
|
|
727
|
+
pvPowerW: Math.max(0, Number(s.pvPowerW) || 0),
|
|
728
|
+
houseLoadW: Math.max(0, Number(s.houseLoadW) || Number(s.consumptionTotalW) || 0),
|
|
729
|
+
};
|
|
730
|
+
const last = this._samples.length ? this._samples[this._samples.length - 1] : null;
|
|
731
|
+
if (!last || now - last.ts >= 30000) this._samples.push(sample);
|
|
732
|
+
const keepFrom = now - 72 * 3600 * 1000;
|
|
733
|
+
this._samples = this._samples.filter((it) => it && it.ts >= keepFrom).slice(-5000);
|
|
734
|
+
|
|
735
|
+
const peakBase = finiteNumber(s.gridConnectionLimitW) && s.gridConnectionLimitW > 0 ? s.gridConnectionLimitW : (finiteNumber(s.peakLimitW) && s.peakLimitW > 0 ? s.peakLimitW : null);
|
|
736
|
+
const peakWarnW = peakBase ? peakBase * ((cfg.peakNearLimitPct || 90) / 100) : null;
|
|
737
|
+
if (cfg.learningEnabled && peakWarnW && sample.gridImportW >= peakWarnW * 0.78) {
|
|
738
|
+
this._peakHourBuckets[hour] = (Number(this._peakHourBuckets[hour]) || 0) + clamp(sample.gridImportW / Math.max(1000, peakWarnW), 0.25, 2.5);
|
|
739
|
+
}
|
|
740
|
+
if (cfg.learningEnabled && (!last || now - last.ts >= 5 * 60000)) this._peakHourBuckets = this._peakHourBuckets.map((v) => Math.max(0, (Number(v) || 0) * 0.997));
|
|
741
|
+
let topHour = -1;
|
|
742
|
+
let topScore = 0;
|
|
743
|
+
this._peakHourBuckets.forEach((v, idx) => { if ((Number(v) || 0) > topScore) { topScore = Number(v) || 0; topHour = idx; } });
|
|
744
|
+
s.peakRiskHour = topHour >= 0 && topScore >= 1.5 ? topHour : null;
|
|
745
|
+
s.peakRiskWindow = s.peakRiskHour !== null ? formatWindowHour(s.peakRiskHour) : '';
|
|
746
|
+
s.peakLearningJson = JSON.stringify({ hours: this._peakHourBuckets.map((v, idx) => ({ hour: idx, score: round(v, 2) || 0 })), topHour: s.peakRiskHour, topWindow: s.peakRiskWindow });
|
|
747
|
+
|
|
748
|
+
const older = this._samples.filter((it) => it && it.ts < now - 10 * 60000);
|
|
749
|
+
const sameHour = older.filter((it) => Math.abs((Number(it.hour) || 0) - hour) <= 1 || Math.abs((Number(it.hour) || 0) - hour) >= 23);
|
|
750
|
+
const baselineSet = sameHour.length >= Math.min(6, older.length) ? sameHour : older;
|
|
751
|
+
const baselineW = average(baselineSet, 'houseLoadW');
|
|
752
|
+
const p95W = percentile(baselineSet, 'houseLoadW', 0.95);
|
|
753
|
+
const flexW = Math.max(0, Number(s.evcsUsedW) || 0) + Math.max(0, Number(s.thermalUsedW) || 0) + Math.max(0, Number(s.heatingRodUsedW) || 0);
|
|
754
|
+
const unexplainedW = Math.max(0, sample.houseLoadW - flexW);
|
|
755
|
+
const quietActive = isInsideClockWindow(now, cfg.quietHoursStart, cfg.quietHoursEnd);
|
|
756
|
+
const anomalyLimitW = Math.max(Number(cfg.anomalyMinImportW) || 0, baselineW ? baselineW * (Number(cfg.anomalyFactor) || 2.2) : 0, p95W ? p95W * 1.25 : 0);
|
|
757
|
+
const enoughSamples = baselineSet.length >= (Number(cfg.anomalyMinSamples) || 12);
|
|
758
|
+
s.anomalyBaselineW = baselineW;
|
|
759
|
+
s.anomalyP95W = p95W;
|
|
760
|
+
s.anomalyDetected = false;
|
|
761
|
+
s.anomalyText = '';
|
|
762
|
+
if (cfg.anomalyDetectionEnabled) {
|
|
763
|
+
if (quietActive && unexplainedW >= cfg.nightBaseLoadW && Math.max(0, Number(s.evcsUsedW) || 0) < 200) {
|
|
764
|
+
s.anomalyDetected = true;
|
|
765
|
+
s.anomalyText = `Ungewöhnliche Grundlast im Ruhefenster: etwa ${formatKw(unexplainedW)} ohne erkennbare Wallbox-/Thermiklast.`;
|
|
766
|
+
} else if (unexplainedW >= cfg.anomalyHighLoadW) {
|
|
767
|
+
s.anomalyDetected = true;
|
|
768
|
+
s.anomalyText = `Ungewöhnlich hoher Gebäudeverbrauch: etwa ${formatKw(unexplainedW)} nicht durch bekannte flexible Verbraucher erklärt.`;
|
|
769
|
+
} else if (enoughSamples && sample.houseLoadW >= anomalyLimitW && sample.houseLoadW > 0) {
|
|
770
|
+
s.anomalyDetected = true;
|
|
771
|
+
s.anomalyText = `Der Gebäudeverbrauch liegt deutlich über dem gelernten Bereich (${formatKw(sample.houseLoadW)} statt typisch ${baselineW ? formatKw(baselineW) : '—'}).`;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
if (finiteNumber(s.forecastQualityPct)) {
|
|
776
|
+
this._forecastQualityPct = clamp(Number(s.forecastQualityPct), 0, 100);
|
|
777
|
+
this._forecastQualityText = `PV-Prognosequalität ca. ${formatPct(this._forecastQualityPct)}.`;
|
|
778
|
+
} else if (finiteNumber(s.forecastErrorPct)) {
|
|
779
|
+
this._forecastQualityPct = clamp(100 - Math.abs(Number(s.forecastErrorPct)), 0, 100);
|
|
780
|
+
this._forecastQualityText = `PV-Prognosequalität ca. ${formatPct(this._forecastQualityPct)}.`;
|
|
781
|
+
} else if (cfg.forecastQualityEnabled && s.pvForecastUsable && finiteNumber(s.productionEnergyKwh) && s.pvKwh6 > 0.5) {
|
|
782
|
+
const lastCheck = this._forecastChecks.length ? this._forecastChecks[this._forecastChecks.length - 1] : null;
|
|
783
|
+
if (!lastCheck || now - lastCheck.ts >= 60 * 60000) this._forecastChecks.push({ ts: now, forecastKwh6: s.pvKwh6, productionEnergyKwh: s.productionEnergyKwh, resolved: false });
|
|
784
|
+
}
|
|
785
|
+
for (const check of this._forecastChecks) {
|
|
786
|
+
if (!check || check.resolved) continue;
|
|
787
|
+
const age = now - check.ts;
|
|
788
|
+
if (age >= 5.75 * 3600000 && age <= 9 * 3600000 && finiteNumber(s.productionEnergyKwh) && finiteNumber(check.productionEnergyKwh)) {
|
|
789
|
+
const actual = Math.max(0, Number(s.productionEnergyKwh) - Number(check.productionEnergyKwh));
|
|
790
|
+
const forecast = Math.max(0.1, Number(check.forecastKwh6) || 0);
|
|
791
|
+
const errPct = Math.abs(actual - forecast) / forecast * 100;
|
|
792
|
+
const q = clamp(100 - errPct, 0, 100);
|
|
793
|
+
check.resolved = true;
|
|
794
|
+
check.actualKwh = actual;
|
|
795
|
+
check.qualityPct = q;
|
|
796
|
+
check.errPct = errPct;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
this._forecastChecks = this._forecastChecks.filter((it) => it && now - it.ts <= 30 * 3600000).slice(-48);
|
|
800
|
+
const recentResolved = this._forecastChecks.filter((it) => it && it.resolved && finiteNumber(it.qualityPct)).slice(-8);
|
|
801
|
+
if (recentResolved.length) {
|
|
802
|
+
this._forecastQualityPct = round(average(recentResolved, 'qualityPct'), 0);
|
|
803
|
+
const lastQ = recentResolved[recentResolved.length - 1];
|
|
804
|
+
this._forecastQualityText = `PV-Prognosequalität ca. ${formatPct(this._forecastQualityPct)} (letzte Prüfung: Forecast ${formatKwh(lastQ.forecastKwh6)}, Ist ${formatKwh(lastQ.actualKwh)}).`;
|
|
805
|
+
}
|
|
806
|
+
s.forecastQualityPct = this._forecastQualityPct;
|
|
807
|
+
s.forecastQualityText = this._forecastQualityText || (s.pvForecastUsable ? 'PV-Prognose aktiv; Qualität wird nach den ersten Vergleichsfenstern bewertet.' : 'PV-Prognose nicht verfügbar.');
|
|
808
|
+
s.season = seasonFromDate(new Date(now));
|
|
809
|
+
s.seasonLabel = seasonLabel(s.season);
|
|
810
|
+
s.comfortActive = isInsideClockWindow(now, cfg.comfortStart, cfg.comfortEnd);
|
|
811
|
+
s.quietActive = quietActive;
|
|
812
|
+
s.comfortWindow = `${cfg.comfortStart || '06:00'}–${cfg.comfortEnd || '22:00'}`;
|
|
813
|
+
s.quietWindow = `${cfg.quietHoursStart || '22:00'}–${cfg.quietHoursEnd || '06:00'}`;
|
|
814
|
+
s.optimizationMode = cfg.optimizationMode;
|
|
815
|
+
this._lastLearning = {
|
|
816
|
+
anomaly: !!s.anomalyDetected,
|
|
817
|
+
anomalyText: s.anomalyText || '',
|
|
818
|
+
peakLearningText: s.peakRiskWindow ? `Gelerntes Peak-Risiko im Fenster ${s.peakRiskWindow}.` : 'Lernprofil wird aufgebaut.',
|
|
819
|
+
forecastQualityPct: s.forecastQualityPct,
|
|
820
|
+
forecastQualityText: s.forecastQualityText,
|
|
821
|
+
byHour: this._peakHourBuckets.map((v, idx) => ({ hour: idx, score: round(v, 2) || 0 })),
|
|
330
822
|
};
|
|
823
|
+
return s;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
_makeDailyPlan(s, cfg) {
|
|
827
|
+
const items = [];
|
|
828
|
+
const add = (time, title, text, priority, category) => {
|
|
829
|
+
if (!title || !text) return;
|
|
830
|
+
items.push({ time: String(time || ''), title: String(title), text: String(text), priority: Math.round(Number(priority) || 0), category: String(category || 'system') });
|
|
831
|
+
};
|
|
832
|
+
const tariffState = String(s.tariffState || '').toLowerCase();
|
|
833
|
+
const currentCheap = !!(s.negativeActive || s.gridImportPreferred || tariffState.includes('günstig') || tariffState.includes('guenstig') || tariffState.includes('cheap'));
|
|
834
|
+
const currentExpensive = !!(tariffState.includes('teuer') || tariffState.includes('expensive'));
|
|
835
|
+
const surplusW = Math.max(Number(s.gridExportW) || 0, Number(s.pvBudgetW) || 0);
|
|
836
|
+
const peakLimit = finiteNumber(s.gridConnectionLimitW) && s.gridConnectionLimitW > 0 ? s.gridConnectionLimitW : (finiteNumber(s.peakLimitW) && s.peakLimitW > 0 ? s.peakLimitW : s.gridImportLimitEffectiveW);
|
|
837
|
+
const peakUsagePct = peakLimit ? (s.gridImportW / peakLimit * 100) : 0;
|
|
838
|
+
if (peakLimit && peakUsagePct >= (cfg.peakNearLimitPct || 90)) add('jetzt', 'Peak-Schutz', `Netzbezug bei ${formatPct(peakUsagePct)}: flexible Lasten nach Priorität reduzieren (${priorityText(cfg.priorities)}).`, 95, 'peak');
|
|
839
|
+
if (surplusW >= cfg.pvSurplusThresholdW) add('jetzt', 'PV-Überschuss nutzen', `${formatKw(surplusW)} Überschuss in Wallbox, Warmwasser oder andere flexible Verbraucher legen.`, 86, 'pv');
|
|
840
|
+
if (currentCheap) add('jetzt', 'Günstigen Tarif nutzen', `Preisfenster nutzen${finiteNumber(s.priceNow) ? ` (${formatPrice(s.priceNow)})` : ''}, solange Peak-Reserve bleibt.`, 84, 'tariff');
|
|
841
|
+
else if (currentExpensive) add('jetzt vermeiden', 'Teures Tarif-/Lastfenster', 'EV-Laden und Heizstab möglichst verschieben; Speicherreserve nur gezielt nutzen.', 80, 'tariff');
|
|
842
|
+
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');
|
|
843
|
+
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');
|
|
844
|
+
if (s.evConnectedCount > 0) {
|
|
845
|
+
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');
|
|
846
|
+
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');
|
|
847
|
+
}
|
|
848
|
+
const activeGoals = (Array.isArray(s.evGoals) ? s.evGoals : []).filter((g) => g && (g.goalEnabled || g.goalActive));
|
|
849
|
+
if (activeGoals.length) {
|
|
850
|
+
const next = activeGoals.slice().sort((a, b) => (Number(a.goalFinishTs || 0) || Infinity) - (Number(b.goalFinishTs || 0) || Infinity))[0];
|
|
851
|
+
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');
|
|
852
|
+
}
|
|
853
|
+
if (s.weatherEnabled) {
|
|
854
|
+
const rainy = (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct >= cfg.weatherRainRiskPct) || textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['regen', 'schauer', 'gewitter', 'schnee', 'bedeckt']);
|
|
855
|
+
const sunny = !rainy && (textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['sonnig', 'klar', 'heiter']) || (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct <= 25));
|
|
856
|
+
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');
|
|
857
|
+
if (sunny) add('morgen', 'PV-Headroom vorbereiten', 'Gutes PV-Fenster erwartet: unnötige Netzladung vermeiden und Speicherplatz für PV freihalten.', 66, 'weather');
|
|
858
|
+
}
|
|
859
|
+
if (cfg.seasonLogicEnabled) {
|
|
860
|
+
if (s.season === 'winter') add('laufend', 'Winterstrategie', 'Reserve höher gewichten, weil PV-Fenster kürzer und Wärmelasten relevanter sind.', 54, 'storage');
|
|
861
|
+
if (s.season === 'summer') add('tagsüber', 'Sommerstrategie', 'PV-Headroom und Eigenverbrauch hoch gewichten; Abendspitzen durch EV/Kühlung vermeiden.', 54, 'pv');
|
|
862
|
+
}
|
|
863
|
+
if (s.peakRiskWindow) add(s.peakRiskWindow, 'Gelerntes Peak-Fenster entschärfen', 'Große flexible Lasten nicht gleichzeitig starten.', 74, 'learning');
|
|
864
|
+
if (s.anomalyDetected) add('prüfen', 'Anomalie prüfen', s.anomalyText, 88, 'anomaly');
|
|
865
|
+
if (!items.length) add('heute', 'Weiter beobachten', 'Keine starken Optimierungssignale; größere Verbraucher in PV- oder günstige Tarifzeiten legen.', 30, 'system');
|
|
866
|
+
const sorted = items.sort((a, b) => b.priority - a.priority).slice(0, 6);
|
|
867
|
+
const text = `Modus ${optimizationModeLabel(cfg.optimizationMode)}: ` + sorted.slice(0, 4).map((it) => `${it.time}: ${it.title}`).join(' · ');
|
|
868
|
+
return { mode: cfg.optimizationMode, modeLabel: optimizationModeLabel(cfg.optimizationMode), season: s.season, seasonLabel: s.seasonLabel, items: sorted, text };
|
|
331
869
|
}
|
|
332
870
|
|
|
333
871
|
_pushSuggestion(list, item) {
|
|
@@ -352,227 +890,105 @@ class AiAdvisorModule extends BaseModule {
|
|
|
352
890
|
|
|
353
891
|
_buildSuggestions(s, cfg) {
|
|
354
892
|
const out = [];
|
|
893
|
+
s.weatherSummary = s.weatherSummary || buildWeatherSummary(s);
|
|
355
894
|
const tariffState = String(s.tariffState || '').toLowerCase();
|
|
356
895
|
const currentCheap = !!(
|
|
357
|
-
s.negativeActive ||
|
|
358
|
-
s.gridImportPreferred ||
|
|
359
|
-
tariffState.includes('günstig') || tariffState.includes('guenstig') || tariffState.includes('cheap') ||
|
|
896
|
+
s.negativeActive || s.gridImportPreferred || tariffState.includes('günstig') || tariffState.includes('guenstig') || tariffState.includes('cheap') ||
|
|
360
897
|
(finiteNumber(s.priceNow) && finiteNumber(s.priceCheapThreshold) && s.priceNow <= s.priceCheapThreshold) ||
|
|
361
898
|
(finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow <= (s.priceAvg - cfg.cheapPriceMarginEurKwh))
|
|
362
899
|
);
|
|
363
|
-
const currentExpensive = !!(
|
|
364
|
-
tariffState.includes('teuer') || tariffState.includes('expensive') ||
|
|
365
|
-
(finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow >= (s.priceAvg + cfg.expensivePriceMarginEurKwh))
|
|
366
|
-
);
|
|
900
|
+
const currentExpensive = !!(tariffState.includes('teuer') || tariffState.includes('expensive') || (finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow >= (s.priceAvg + cfg.expensivePriceMarginEurKwh)));
|
|
367
901
|
const hasStorage = s.storageSocPct !== null;
|
|
368
902
|
const storageEnough = !hasStorage || s.storageSocPct >= cfg.minSocForDischargePct;
|
|
369
|
-
const hasFlexibleLoad = (s.evcsUsedW > 100 || s.thermalUsedW > 100 || s.heatingRodUsedW > 100)
|
|
370
|
-
|
|
903
|
+
const hasFlexibleLoad = (s.evcsUsedW > 100 || s.thermalUsedW > 100 || s.heatingRodUsedW > 100) || !!(this.adapter && this.adapter.config && (this.adapter.config.enableChargingManagement || this.adapter.config.enableThermalControl || this.adapter.config.enableHeatingRodControl));
|
|
904
|
+
const configuredGridLimitW = finiteNumber(s.gridConnectionLimitW) && s.gridConnectionLimitW > 0 ? s.gridConnectionLimitW : null;
|
|
905
|
+
const effectiveGridLimitW = finiteNumber(s.peakLimitW) && s.peakLimitW > 0 ? s.peakLimitW : (finiteNumber(s.gridImportLimitEffectiveW) && s.gridImportLimitEffectiveW > 0 ? s.gridImportLimitEffectiveW : null);
|
|
906
|
+
const peakReferenceLimitW = configuredGridLimitW || effectiveGridLimitW;
|
|
907
|
+
const peakUsagePct = peakReferenceLimitW ? (s.gridImportW / peakReferenceLimitW * 100) : null;
|
|
908
|
+
const peakWarnThresholdW = peakReferenceLimitW ? (peakReferenceLimitW * (cfg.peakNearLimitPct / 100)) : null;
|
|
909
|
+
const peakNearLimit = peakReferenceLimitW && Number.isFinite(peakUsagePct) && peakUsagePct >= cfg.peakNearLimitPct;
|
|
910
|
+
const peakCriticalLimit = peakReferenceLimitW && Number.isFinite(peakUsagePct) && peakUsagePct >= cfg.peakCriticalLimitPct;
|
|
911
|
+
const peakReadinessText = s.peakActive
|
|
912
|
+
? 'Lastspitzenkappung ist aktiv.'
|
|
913
|
+
: (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.');
|
|
371
914
|
|
|
372
|
-
if (s.
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
category: 'tariff',
|
|
376
|
-
severity: 'success',
|
|
377
|
-
priority: 98,
|
|
378
|
-
icon: '🟢',
|
|
379
|
-
title: 'Negativpreis-Fenster nutzen',
|
|
380
|
-
text: `Der Tarif bevorzugt aktuell Netzbezug${finiteNumber(s.priceNow) ? ` (${formatPrice(s.priceNow)})` : ''}. Flexible Verbraucher können jetzt wirtschaftlich laufen, solange Netz- und Peak-Limits eingehalten werden.`,
|
|
381
|
-
action: 'Wallbox, Speicher-Netzladung oder Wärmelast jetzt freigeben, falls der Nutzer das möchte.',
|
|
382
|
-
window: 'jetzt',
|
|
383
|
-
impact: 'Kostenoptimierung',
|
|
384
|
-
confidence: 90,
|
|
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
|
-
}
|
|
415
|
-
|
|
416
|
-
if (currentExpensive) {
|
|
915
|
+
if (s.peakActive || s.hlzfActive || s.peakOverW > 0) {
|
|
916
|
+
const lim = peakReferenceLimitW || s.peakLimitW;
|
|
917
|
+
const pctText = lim ? ` (${formatPct((s.gridImportW / lim) * 100)} von ${formatKw(lim)})` : '';
|
|
417
918
|
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,
|
|
919
|
+
id: 'peak-window-protect', category: 'peak', severity: s.peakOverW > 0 ? 'critical' : 'warning', priority: 98, icon: '⚡',
|
|
920
|
+
title: s.hlzfActive ? 'Hochlastzeitfenster / Lastspitze aktiv' : 'Lastspitzenkappung aktiv',
|
|
921
|
+
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)})` : '')}.`,
|
|
922
|
+
action: `EV-Laden, Heizstab und andere flexible Lasten nach Priorität pausieren/reduzieren (${priorityText(cfg.priorities)}), bis der Netzanschluss wieder unter der Grenze liegt.`,
|
|
923
|
+
window: 'jetzt', impact: 'Leistungspreis / Netzanschluss schützen', confidence: 92,
|
|
429
924
|
});
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
if (surplusW >= cfg.pvSurplusThresholdW) {
|
|
925
|
+
} else if (peakNearLimit) {
|
|
926
|
+
const remainingW = Math.max(0, peakReferenceLimitW - s.gridImportW);
|
|
927
|
+
const warnText = peakWarnThresholdW ? `Die Vorwarnschwelle liegt bei ${formatPct(cfg.peakNearLimitPct)} = ${formatKw(peakWarnThresholdW)}.` : '';
|
|
434
928
|
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,
|
|
929
|
+
id: 'peak-near-grid-connection-limit', category: 'peak', severity: peakCriticalLimit ? 'critical' : 'warning', priority: peakCriticalLimit ? 97 : 92, icon: peakCriticalLimit ? '🛑' : '🚧',
|
|
930
|
+
title: peakCriticalLimit ? 'Netzanschluss am Limit' : `Netzanschluss zu ${formatPct(cfg.peakNearLimitPct)} ausgelastet`,
|
|
931
|
+
text: `Aktuell werden ${formatKw(s.gridImportW)} von ${formatKw(peakReferenceLimitW)} genutzt (${formatPct(peakUsagePct)}). ${warnText} ${peakReadinessText}`.replace(/\s+/g, ' ').trim(),
|
|
932
|
+
action: s.peakConfigured ? `Jetzt optimieren: flexible Lasten nach Priorität reduzieren oder verschieben (${priorityText(cfg.priorities)})${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.`,
|
|
933
|
+
window: 'jetzt', impact: 'Lastspitze vermeiden', confidence: s.peakConfigured ? 90 : 82,
|
|
446
934
|
});
|
|
447
935
|
}
|
|
448
936
|
|
|
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
|
-
});
|
|
937
|
+
if (cfg.dailyPlanEnabled && s.dayPlan && Array.isArray(s.dayPlan.items) && s.dayPlan.items.length) {
|
|
938
|
+
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
939
|
}
|
|
478
940
|
|
|
479
|
-
|
|
941
|
+
const activeEvGoals = (Array.isArray(s.evGoals) ? s.evGoals : []).filter((g) => g && (g.goalEnabled || g.goalActive));
|
|
942
|
+
if (cfg.evGoalPlanningEnabled && (activeEvGoals.length || (s.evConnectedCount > 0 && finiteNumber(s.evEnergyNeededKwh)))) {
|
|
943
|
+
const urgent = activeEvGoals.length ? activeEvGoals.slice().sort((a, b) => (finiteNumber(a.goalRemainingMin) ? a.goalRemainingMin : 999999) - (finiteNumber(b.goalRemainingMin) ? b.goalRemainingMin : 999999))[0] : null;
|
|
944
|
+
const remaining = urgent && finiteNumber(urgent.goalRemainingMin) ? urgent.goalRemainingMin : s.evMinutesUntilReady;
|
|
945
|
+
const shortfall = urgent && finiteNumber(urgent.goalShortfallW) ? Math.max(0, urgent.goalShortfallW) : 0;
|
|
946
|
+
const isUrgent = (remaining !== null && remaining <= cfg.evUrgentRemainingMin) || shortfall > 500;
|
|
480
947
|
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,
|
|
948
|
+
id: 'ev-target-planning', category: 'evcs', severity: isUrgent ? 'warning' : 'info', priority: isUrgent ? 90 : 72, icon: '🚗', title: 'EV-Zielplanung aktiv',
|
|
949
|
+
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)})` : ''}.`,
|
|
950
|
+
action: currentCheap || s.negativeActive ? 'Jetzt laden, solange Tarif und Peak-Reserve passen.' : 'PV- und günstige Tariffenster priorisieren; bei knapper Abfahrtszeit Ladeleistung rechtzeitig freigeben.',
|
|
951
|
+
window: urgent && urgent.goalFinishTs ? tsToShortWindow(urgent.goalFinishTs) : `bis ${s.evReadyBy || cfg.evReadyBy}`, impact: 'Mobilität sicherstellen', confidence: urgent ? 82 : 70,
|
|
494
952
|
});
|
|
495
953
|
}
|
|
496
954
|
|
|
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
|
-
});
|
|
955
|
+
if (s.weatherEnabled) {
|
|
956
|
+
const rainyTomorrow = (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct >= cfg.weatherRainRiskPct) || textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['regen', 'schauer', 'gewitter', 'schnee', 'bedeckt']);
|
|
957
|
+
const sunnyTomorrow = !rainyTomorrow && (textContainsAny(`${s.weatherTomorrowText || ''} ${s.weatherText || ''}`, ['sonnig', 'klar', 'heiter']) || (finiteNumber(s.weatherTomorrowPrecipPct) && s.weatherTomorrowPrecipPct <= 25));
|
|
958
|
+
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: 'Speicherreserve nicht unnötig leeren; EV/Warmwasser eher in sichere Tarif- oder PV-Fenster legen.', window: 'heute / morgen', impact: 'Reserve & Autarkie', confidence: 75 });
|
|
959
|
+
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 });
|
|
960
|
+
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
961
|
}
|
|
512
962
|
|
|
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
|
-
});
|
|
963
|
+
if (cfg.seasonLogicEnabled) {
|
|
964
|
+
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: 'Abends nicht zu aggressiv entladen und Warmwasser/EV möglichst in sichere Tarif- oder PV-Fenster legen.', window: 'laufend', impact: 'Reserve & Komfort', confidence: 66 });
|
|
965
|
+
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: 'Große Verbraucher tagsüber staffeln und Abendspitzen durch EV/Kühlung vermeiden.', window: 'tagsüber', impact: 'Eigenverbrauch & Peak', confidence: 66 });
|
|
527
966
|
}
|
|
528
967
|
|
|
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
|
-
}
|
|
968
|
+
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 });
|
|
969
|
+
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)}.`, window: s.peakRiskWindow, impact: 'Peak vermeiden', confidence: 70 });
|
|
970
|
+
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
971
|
|
|
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
|
-
});
|
|
972
|
+
if (cfg.optimizationMode === 'co2' && finiteNumber(s.co2IntensityGPerKwh)) {
|
|
973
|
+
const clean = s.co2IntensityGPerKwh <= cfg.co2LowGPerKwh;
|
|
974
|
+
const dirty = s.co2IntensityGPerKwh >= cfg.co2HighGPerKwh;
|
|
975
|
+
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
976
|
}
|
|
977
|
+
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: Wallbox, Warmwasser oder steuerbare Lasten staffeln.', window: 'jetzt', impact: 'Autarkie erhöhen', confidence: 78 });
|
|
978
|
+
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)}.`, window: 'laufend', impact: 'Lastspitzen vermeiden', confidence: 72 });
|
|
560
979
|
|
|
561
|
-
if (
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
confidence: 70,
|
|
574
|
-
});
|
|
575
|
-
}
|
|
980
|
+
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 });
|
|
981
|
+
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: 'EV-Laden, Heizstab und andere flexible Verbraucher verschieben oder reduzieren, wenn Komfortziele es erlauben.', window: 'jetzt', impact: 'Kosten vermeiden', confidence: 78 });
|
|
982
|
+
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: 'Planbare Lasten bis dahin zurückstellen, sofern Komfort und EV-Zielzeiten passen.', window: shortIsoWindow(s.nextCheapFrom, s.nextCheapTo), impact: 'Kosten optimieren', confidence: 72 });
|
|
983
|
+
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: 'Wallbox, Warmwasser oder andere flexible Verbraucher einschalten bzw. erhöhen, solange kein Peak-Risiko besteht.', window: 'jetzt', impact: 'Eigenverbrauch erhöhen', confidence: 82 });
|
|
984
|
+
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 });
|
|
985
|
+
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 });
|
|
986
|
+
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 });
|
|
987
|
+
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 });
|
|
988
|
+
if (cfg.comfortHintsEnabled && s.quietActive && (s.evcsUsedW + 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(s.evcsUsedW + 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 });
|
|
989
|
+
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 });
|
|
990
|
+
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 });
|
|
991
|
+
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
992
|
|
|
577
993
|
const seen = new Set();
|
|
578
994
|
const deduped = [];
|
|
@@ -583,7 +999,6 @@ class AiAdvisorModule extends BaseModule {
|
|
|
583
999
|
delete clean.rankWeight;
|
|
584
1000
|
deduped.push(clean);
|
|
585
1001
|
}
|
|
586
|
-
|
|
587
1002
|
const minPriorityMap = { info: 0, warning: 60, action: 75, critical: 90 };
|
|
588
1003
|
const minPrio = minPriorityMap[cfg.minPriority] || 0;
|
|
589
1004
|
const categoryAllowed = (item) => {
|
|
@@ -594,43 +1009,37 @@ class AiAdvisorModule extends BaseModule {
|
|
|
594
1009
|
if (cat === 'storage') return cats.storage !== false;
|
|
595
1010
|
if (cat === 'evcs') return cats.evcs !== false;
|
|
596
1011
|
if (cat === 'peak') return cats.peak !== false;
|
|
1012
|
+
if (cat === 'weather') return cats.weather !== false;
|
|
597
1013
|
if (cat === 'heating' || cat === 'thermal') return cats.heating !== false;
|
|
1014
|
+
if (cat === 'dailyplan' || cat === 'daily-plan' || cat === 'plan') return cats.dailyPlan !== false && cats.plan !== false;
|
|
1015
|
+
if (cat === 'anomaly') return cats.anomaly !== false;
|
|
1016
|
+
if (cat === 'comfort') return cats.comfort !== false;
|
|
1017
|
+
if (cat === 'learning') return cats.learning !== false;
|
|
1018
|
+
if (cat === 'co2' || cat === 'co₂') return cats.co2 !== false;
|
|
598
1019
|
if (cat === 'grid' || cat === 'setup' || cat === 'system' || cat === 'general') return cats.system !== false;
|
|
599
1020
|
return true;
|
|
600
1021
|
};
|
|
601
1022
|
let filtered = deduped.filter((item) => categoryAllowed(item) && (Number(item.priority) || 0) >= minPrio);
|
|
602
|
-
|
|
603
1023
|
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
|
-
});
|
|
1024
|
+
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
1025
|
filtered = filtered.filter((item) => categoryAllowed(item));
|
|
618
1026
|
}
|
|
619
|
-
|
|
620
|
-
return filtered.map((item) => { const clean = Object.assign({}, item); delete clean.rankWeight; return clean; }).slice(0, cfg.maxSuggestions);
|
|
1027
|
+
return filtered.slice(0, cfg.maxSuggestions);
|
|
621
1028
|
}
|
|
622
1029
|
|
|
623
1030
|
_score(snapshot, suggestions) {
|
|
624
|
-
let score =
|
|
625
|
-
|
|
626
|
-
if (
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
if (snapshot.
|
|
630
|
-
if (snapshot.gridImportW > 5000) score -= 8;
|
|
1031
|
+
let score = 72;
|
|
1032
|
+
if (suggestions && suggestions.length) score -= Math.min(22, suggestions.reduce((sum, it) => sum + (it.severity === 'critical' ? 8 : it.severity === 'warning' ? 5 : 2), 0));
|
|
1033
|
+
if (snapshot.gridExportW > 1000) score += 3;
|
|
1034
|
+
const peakBase = finiteNumber(snapshot.gridConnectionLimitW) && snapshot.gridConnectionLimitW > 0 ? snapshot.gridConnectionLimitW : snapshot.peakLimitW;
|
|
1035
|
+
if (peakBase && snapshot.gridImportW >= peakBase) score -= 20;
|
|
1036
|
+
else if (peakBase && snapshot.gridImportW >= peakBase * 0.9) score -= 12;
|
|
631
1037
|
if (snapshot.pvForecastUsable) score += 4;
|
|
1038
|
+
if (snapshot.weatherEnabled) score += 2;
|
|
632
1039
|
if (snapshot.tariffActive || finiteNumber(snapshot.priceNow)) score += 4;
|
|
633
1040
|
if (snapshot.storageSocPct !== null && snapshot.storageSocPct < 15) score -= 8;
|
|
1041
|
+
if (snapshot.anomalyDetected) score -= 10;
|
|
1042
|
+
if (finiteNumber(snapshot.forecastQualityPct) && snapshot.forecastQualityPct < 50) score -= 4;
|
|
634
1043
|
return clamp(Math.round(score), 0, 100);
|
|
635
1044
|
}
|
|
636
1045
|
|
|
@@ -642,6 +1051,7 @@ class AiAdvisorModule extends BaseModule {
|
|
|
642
1051
|
async _publishDisabled(cfg, now) {
|
|
643
1052
|
if ((now - (this._lastDisabledWriteMs || 0)) < 60000) return;
|
|
644
1053
|
this._lastDisabledWriteMs = now;
|
|
1054
|
+
const disabledByCustomer = cfg.customerEnabled === false;
|
|
645
1055
|
await this._set('aiAdvisor.enabled', false);
|
|
646
1056
|
await this._set('aiAdvisor.advisoryOnly', true);
|
|
647
1057
|
await this._set('aiAdvisor.showInLive', cfg.showInLive !== false);
|
|
@@ -649,17 +1059,43 @@ class AiAdvisorModule extends BaseModule {
|
|
|
649
1059
|
await this._set('aiAdvisor.status', 'disabled');
|
|
650
1060
|
await this._set('aiAdvisor.severity', 'neutral');
|
|
651
1061
|
await this._set('aiAdvisor.headline', 'KI-Energieberater deaktiviert');
|
|
652
|
-
await this._set('aiAdvisor.summary',
|
|
1062
|
+
await this._set('aiAdvisor.summary', disabledByCustomer ? 'Die beratende KI ist in den Kundeneinstellungen deaktiviert.' : 'Die beratende KI ist im App-Center deaktiviert.');
|
|
653
1063
|
await this._set('aiAdvisor.count', 0);
|
|
654
1064
|
await this._set('aiAdvisor.score', 0);
|
|
1065
|
+
await this._set('aiAdvisor.peakUsagePct', 0);
|
|
1066
|
+
await this._set('aiAdvisor.peakStateText', '');
|
|
1067
|
+
await this._set('aiAdvisor.gridConnectionLimitW', 0);
|
|
1068
|
+
await this._set('aiAdvisor.peakWarnThresholdW', 0);
|
|
1069
|
+
await this._set('aiAdvisor.weatherSummary', '');
|
|
1070
|
+
await this._set('aiAdvisor.dailyPlanText', '');
|
|
1071
|
+
await this._set('aiAdvisor.dailyPlanJson', '[]');
|
|
1072
|
+
await this._set('aiAdvisor.evPlanText', '');
|
|
1073
|
+
await this._set('aiAdvisor.optimizationMode', cfg.optimizationMode || 'balanced');
|
|
1074
|
+
await this._set('aiAdvisor.comfortWindowSummary', '');
|
|
1075
|
+
await this._set('aiAdvisor.season', seasonFromDate(new Date()));
|
|
1076
|
+
await this._set('aiAdvisor.anomalyText', '');
|
|
1077
|
+
await this._set('aiAdvisor.forecastQualityPct', 0);
|
|
1078
|
+
await this._set('aiAdvisor.forecastQualityText', '');
|
|
1079
|
+
await this._set('aiAdvisor.peakLearningText', '');
|
|
1080
|
+
await this._set('aiAdvisor.peakLearningJson', '[]');
|
|
655
1081
|
await this._set('aiAdvisor.topTitle', '');
|
|
656
1082
|
await this._set('aiAdvisor.topText', '');
|
|
657
1083
|
await this._set('aiAdvisor.topAction', '');
|
|
658
1084
|
await this._set('aiAdvisor.topWindow', '');
|
|
1085
|
+
await this._set('aiAdvisor.topCategory', '');
|
|
659
1086
|
await this._set('aiAdvisor.suggestionsJson', '[]');
|
|
660
1087
|
await this._set('aiAdvisor.snapshotJson', JSON.stringify({ ts: now, enabled: false }));
|
|
661
1088
|
await this._set('aiAdvisor.lastUpdate', now);
|
|
662
1089
|
await this._set('aiAdvisor.nextUpdate', now + 60000);
|
|
1090
|
+
for (let i = 1; i <= 8; i++) {
|
|
1091
|
+
await this._set(`aiAdvisor.suggestions.${i}.title`, '');
|
|
1092
|
+
await this._set(`aiAdvisor.suggestions.${i}.text`, '');
|
|
1093
|
+
await this._set(`aiAdvisor.suggestions.${i}.action`, '');
|
|
1094
|
+
await this._set(`aiAdvisor.suggestions.${i}.severity`, '');
|
|
1095
|
+
await this._set(`aiAdvisor.suggestions.${i}.category`, '');
|
|
1096
|
+
await this._set(`aiAdvisor.suggestions.${i}.window`, '');
|
|
1097
|
+
await this._set(`aiAdvisor.suggestions.${i}.impact`, '');
|
|
1098
|
+
}
|
|
663
1099
|
}
|
|
664
1100
|
|
|
665
1101
|
async _publish(snapshot, suggestions, cfg) {
|
|
@@ -669,7 +1105,22 @@ class AiAdvisorModule extends BaseModule {
|
|
|
669
1105
|
const severity = top ? String(top.severity || 'info') : 'neutral';
|
|
670
1106
|
const headline = top ? `${top.icon || '💡'} ${top.title}` : 'KI-Energieberater bereit';
|
|
671
1107
|
const summary = top ? String(top.text || '') : 'Keine aktuellen Hinweise.';
|
|
672
|
-
const jsonSuggestions =
|
|
1108
|
+
const jsonSuggestions = safeJson(suggestions || [], '[]');
|
|
1109
|
+
const peakReferenceLimitW = (finiteNumber(snapshot.gridConnectionLimitW) && snapshot.gridConnectionLimitW > 0)
|
|
1110
|
+
? snapshot.gridConnectionLimitW
|
|
1111
|
+
: ((finiteNumber(snapshot.peakLimitW) && snapshot.peakLimitW > 0) ? snapshot.peakLimitW : ((finiteNumber(snapshot.gridImportLimitEffectiveW) && snapshot.gridImportLimitEffectiveW > 0) ? snapshot.gridImportLimitEffectiveW : null));
|
|
1112
|
+
const peakUsagePct = peakReferenceLimitW ? (snapshot.gridImportW / peakReferenceLimitW * 100) : 0;
|
|
1113
|
+
const peakWarnThresholdW = peakReferenceLimitW ? (peakReferenceLimitW * ((cfg.peakNearLimitPct || 90) / 100)) : 0;
|
|
1114
|
+
const peakStateText = buildPeakStateText(snapshot, peakReferenceLimitW, peakUsagePct);
|
|
1115
|
+
const weatherSummary = buildWeatherSummary(snapshot);
|
|
1116
|
+
const dailyPlan = snapshot.dayPlan || { mode: cfg.optimizationMode, modeLabel: optimizationModeLabel(cfg.optimizationMode), items: [], text: '' };
|
|
1117
|
+
const evPlanText = (snapshot.evConnectedCount > 0)
|
|
1118
|
+
? (finiteNumber(snapshot.evEnergyNeededKwh) && snapshot.evEnergyNeededKwh > 1
|
|
1119
|
+
? `${formatKwh(snapshot.evEnergyNeededKwh)} bis ${formatPct(snapshot.evTargetSocPct || cfg.evTargetSocPct)} Ziel-SoC nachladen · bereit bis ${snapshot.evReadyBy || cfg.evReadyBy}.`
|
|
1120
|
+
: `Fahrzeug verbunden · Ziel-SoC ${formatPct(snapshot.evTargetSocPct || cfg.evTargetSocPct)} · bereit bis ${snapshot.evReadyBy || cfg.evReadyBy}.`)
|
|
1121
|
+
: 'Kein verbundenes Fahrzeug erkannt.';
|
|
1122
|
+
const comfortWindowSummary = `${cfg.comfortStart || '06:00'}–${cfg.comfortEnd || '22:00'} · Ruhezeit ${cfg.quietHoursStart || '22:00'}–${cfg.quietHoursEnd || '06:00'}`;
|
|
1123
|
+
const learning = this._lastLearning || {};
|
|
673
1124
|
const snap = {
|
|
674
1125
|
ts: now,
|
|
675
1126
|
enabled: true,
|
|
@@ -677,14 +1128,19 @@ class AiAdvisorModule extends BaseModule {
|
|
|
677
1128
|
showInLive: cfg.showInLive !== false,
|
|
678
1129
|
status: 'ok',
|
|
679
1130
|
score,
|
|
1131
|
+
peakUsagePct,
|
|
1132
|
+
peakStateText,
|
|
1133
|
+
weatherSummary,
|
|
1134
|
+
dailyPlan,
|
|
1135
|
+
evPlanText,
|
|
1136
|
+
comfortWindowSummary,
|
|
1137
|
+
learning,
|
|
680
1138
|
severity,
|
|
681
1139
|
top,
|
|
682
1140
|
suggestions,
|
|
683
1141
|
raw: snapshot,
|
|
684
1142
|
};
|
|
685
|
-
const hash = makeHash({ suggestions, score, severity, show: cfg.showInLive });
|
|
686
|
-
|
|
687
|
-
// Even if content is unchanged, refresh timestamps periodically for stale diagnostics.
|
|
1143
|
+
const hash = makeHash({ suggestions, score, severity, show: cfg.showInLive, plan: dailyPlan.text || '', anomaly: learning.anomalyText || '', forecastQuality: learning.forecastQualityPct });
|
|
688
1144
|
const contentChanged = hash !== this._lastHash;
|
|
689
1145
|
this._lastHash = hash;
|
|
690
1146
|
|
|
@@ -698,30 +1154,46 @@ class AiAdvisorModule extends BaseModule {
|
|
|
698
1154
|
await this._set('aiAdvisor.summary', summary);
|
|
699
1155
|
await this._set('aiAdvisor.count', Array.isArray(suggestions) ? suggestions.length : 0);
|
|
700
1156
|
await this._set('aiAdvisor.score', score);
|
|
1157
|
+
await this._set('aiAdvisor.peakUsagePct', round(peakUsagePct, 1) || 0);
|
|
1158
|
+
await this._set('aiAdvisor.peakStateText', peakStateText);
|
|
1159
|
+
await this._set('aiAdvisor.gridConnectionLimitW', peakReferenceLimitW || 0);
|
|
1160
|
+
await this._set('aiAdvisor.peakWarnThresholdW', round(peakWarnThresholdW, 0) || 0);
|
|
1161
|
+
await this._set('aiAdvisor.weatherSummary', weatherSummary);
|
|
1162
|
+
await this._set('aiAdvisor.dailyPlanText', dailyPlan.text || '');
|
|
1163
|
+
await this._set('aiAdvisor.dailyPlanJson', safeJson(dailyPlan.items || [], '[]'));
|
|
1164
|
+
await this._set('aiAdvisor.evPlanText', evPlanText);
|
|
1165
|
+
await this._set('aiAdvisor.optimizationMode', cfg.optimizationMode || 'balanced');
|
|
1166
|
+
await this._set('aiAdvisor.comfortWindowSummary', comfortWindowSummary);
|
|
1167
|
+
await this._set('aiAdvisor.season', snapshot.season || seasonFromDate(new Date()));
|
|
1168
|
+
await this._set('aiAdvisor.anomalyText', snapshot.anomalyText || '');
|
|
1169
|
+
await this._set('aiAdvisor.forecastQualityPct', round(snapshot.forecastQualityPct, 1) || 0);
|
|
1170
|
+
await this._set('aiAdvisor.forecastQualityText', snapshot.forecastQualityText || '');
|
|
1171
|
+
await this._set('aiAdvisor.peakLearningText', learning.peakLearningText || '');
|
|
1172
|
+
await this._set('aiAdvisor.peakLearningJson', snapshot.peakLearningJson || '[]');
|
|
701
1173
|
await this._set('aiAdvisor.topTitle', top ? top.title : '');
|
|
702
1174
|
await this._set('aiAdvisor.topText', top ? top.text : '');
|
|
703
1175
|
await this._set('aiAdvisor.topAction', top ? top.action : '');
|
|
704
1176
|
await this._set('aiAdvisor.topWindow', top ? top.window : '');
|
|
1177
|
+
await this._set('aiAdvisor.topCategory', top ? top.category : '');
|
|
705
1178
|
if (contentChanged) {
|
|
706
1179
|
await this._set('aiAdvisor.suggestionsJson', jsonSuggestions);
|
|
707
1180
|
await this._set('aiAdvisor.snapshotJson', JSON.stringify(snap));
|
|
708
1181
|
} else {
|
|
709
|
-
// keep JSON in stateCache fresh after restarts even if identical writes are skipped by ioBroker internals
|
|
710
1182
|
try { if (typeof this.adapter.updateValue === 'function') this.adapter.updateValue('aiAdvisor.suggestionsJson', jsonSuggestions, now); } catch (_e) {}
|
|
711
1183
|
try { if (typeof this.adapter.updateValue === 'function') this.adapter.updateValue('aiAdvisor.snapshotJson', JSON.stringify(snap), now); } catch (_e) {}
|
|
712
1184
|
}
|
|
713
1185
|
await this._set('aiAdvisor.lastUpdate', now);
|
|
714
1186
|
await this._set('aiAdvisor.nextUpdate', now + Math.round(cfg.minIntervalSec * 1000));
|
|
715
1187
|
|
|
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`,
|
|
1188
|
+
for (let i = 1; i <= 8; i++) {
|
|
1189
|
+
const s0 = (Array.isArray(suggestions) && suggestions[i - 1]) ? suggestions[i - 1] : null;
|
|
1190
|
+
await this._set(`aiAdvisor.suggestions.${i}.title`, s0 ? s0.title : '');
|
|
1191
|
+
await this._set(`aiAdvisor.suggestions.${i}.text`, s0 ? s0.text : '');
|
|
1192
|
+
await this._set(`aiAdvisor.suggestions.${i}.action`, s0 ? s0.action : '');
|
|
1193
|
+
await this._set(`aiAdvisor.suggestions.${i}.severity`, s0 ? s0.severity : '');
|
|
1194
|
+
await this._set(`aiAdvisor.suggestions.${i}.category`, s0 ? s0.category : '');
|
|
1195
|
+
await this._set(`aiAdvisor.suggestions.${i}.window`, s0 ? s0.window : '');
|
|
1196
|
+
await this._set(`aiAdvisor.suggestions.${i}.impact`, s0 ? s0.impact : '');
|
|
725
1197
|
}
|
|
726
1198
|
}
|
|
727
1199
|
|
|
@@ -729,17 +1201,17 @@ class AiAdvisorModule extends BaseModule {
|
|
|
729
1201
|
if (!this._inited) await this.init();
|
|
730
1202
|
const cfg = this._cfg();
|
|
731
1203
|
const now = Date.now();
|
|
732
|
-
|
|
733
1204
|
if (!cfg.enabled) {
|
|
734
1205
|
await this._publishDisabled(cfg, now);
|
|
735
1206
|
return;
|
|
736
1207
|
}
|
|
737
|
-
|
|
738
1208
|
const minMs = Math.max(10000, Math.round(cfg.minIntervalSec * 1000));
|
|
739
1209
|
if (this._lastRunMs && (now - this._lastRunMs) < minMs) return;
|
|
740
1210
|
this._lastRunMs = now;
|
|
741
|
-
|
|
742
|
-
|
|
1211
|
+
let snapshot = await this._snapshot();
|
|
1212
|
+
snapshot = this._updateLearning(snapshot, cfg);
|
|
1213
|
+
snapshot.dayPlan = this._makeDailyPlan(snapshot, cfg);
|
|
1214
|
+
this._lastPlan = snapshot.dayPlan;
|
|
743
1215
|
const suggestions = this._buildSuggestions(snapshot, cfg);
|
|
744
1216
|
await this._publish(snapshot, suggestions, cfg);
|
|
745
1217
|
}
|