iobroker.nexowatt-ui 0.7.37 → 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.
@@ -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,25 +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();
310
+ const customerEnabled = bool(this._cachedValue('settings.aiAdvisorEnabled', true), true);
311
+ const configuredEnabled = c.enabled !== false;
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);
103
322
  return {
104
- enabled: c.enabled !== false,
323
+ enabled: configuredEnabled && customerEnabled,
324
+ customerEnabled,
325
+ configuredEnabled,
105
326
  advisoryOnly: true,
106
- showInLive: c.showInLive !== false,
107
- // App-Center writes intervalSec/exportHighW/importHighW/pvForecastHighW.
108
- // Keep legacy/canonical aliases as well so older configs remain valid.
327
+ showInLive: showOnLiveCfg !== false,
328
+ optimizationMode,
109
329
  minIntervalSec: clamp(num(c.minIntervalSec ?? c.intervalSec, 60), 10, 3600),
110
- maxSuggestions: clamp(num(c.maxSuggestions, 4), 1, 8),
330
+ maxSuggestions: clamp(num(c.maxSuggestions, 6), 1, 10),
111
331
  minPriority: ['info', 'warning', 'action', 'critical'].includes(minPriority) ? minPriority : 'info',
112
332
  pvSurplusThresholdW: clamp(num(c.pvSurplusThresholdW ?? c.exportHighW, 1500), 0, 1000000),
113
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),
114
337
  lowSocPct: clamp(num(c.lowSocPct, 25), 0, 100),
115
338
  highSocPct: clamp(num(c.highSocPct, 85), 0, 100),
116
339
  minSocForDischargePct: clamp(num(c.minSocForDischargePct, 35), 0, 100),
@@ -120,13 +343,50 @@ class AiAdvisorModule extends BaseModule {
120
343
  expensivePriceMarginEurKwh: clamp(num(c.expensivePriceMarginEurKwh, 0.05), 0, 10),
121
344
  staleTimeoutSec: clamp(num(c.staleTimeoutSec, 300), 30, 86400),
122
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 },
123
376
  categories: {
124
377
  tariff: cats.tariff !== false,
125
378
  pv: cats.pv !== false,
126
379
  storage: cats.storage !== false,
127
380
  evcs: cats.evcs !== false,
128
381
  peak: cats.peak !== false,
382
+ weather: cats.weather !== false,
129
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,
130
390
  system: cats.system !== false,
131
391
  },
132
392
  };
@@ -140,57 +400,52 @@ class AiAdvisorModule extends BaseModule {
140
400
 
141
401
  async _ensureStates() {
142
402
  const a = this.adapter;
143
- await a.setObjectNotExistsAsync('aiAdvisor', {
144
- type: 'channel',
145
- common: { name: 'KI-Energieberater' },
146
- native: {},
147
- });
148
-
149
- await a.setObjectNotExistsAsync('aiAdvisor.suggestions', {
150
- type: 'channel',
151
- common: { name: 'KI-Energieberater Vorschläge' },
152
- native: {},
153
- });
154
-
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: {} });
155
405
  const mk = async (id, name, type, role, unit = undefined) => {
156
406
  await a.setObjectNotExistsAsync(id, {
157
407
  type: 'state',
158
- common: {
159
- name,
160
- type,
161
- role,
162
- read: true,
163
- write: false,
164
- ...(unit ? { unit } : {}),
165
- },
408
+ common: { name, type, role, read: true, write: false, ...(unit ? { unit } : {}) },
166
409
  native: {},
167
410
  });
168
411
  };
169
-
170
412
  await mk('aiAdvisor.enabled', 'KI-Energieberater aktiv', 'boolean', 'indicator');
171
413
  await mk('aiAdvisor.advisoryOnly', 'Nur Beratung, keine Schaltentscheidungen', 'boolean', 'indicator');
172
414
  await mk('aiAdvisor.showInLive', 'In LIVE anzeigen', 'boolean', 'indicator');
415
+ await mk('aiAdvisor.showOnLive', 'In LIVE anzeigen', 'boolean', 'indicator');
173
416
  await mk('aiAdvisor.status', 'Status', 'string', 'text');
174
417
  await mk('aiAdvisor.severity', 'Höchste Priorität / Severity', 'string', 'text');
175
418
  await mk('aiAdvisor.headline', 'Kurz-Hinweis', 'string', 'text');
176
419
  await mk('aiAdvisor.summary', 'Zusammenfassung', 'string', 'text');
177
420
  await mk('aiAdvisor.count', 'Anzahl Vorschläge', 'number', 'value');
178
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');
179
438
  await mk('aiAdvisor.topTitle', 'Top-Vorschlag Titel', 'string', 'text');
180
439
  await mk('aiAdvisor.topText', 'Top-Vorschlag Text', 'string', 'text');
181
440
  await mk('aiAdvisor.topAction', 'Top-Vorschlag Handlung', 'string', 'text');
182
441
  await mk('aiAdvisor.topWindow', 'Top-Vorschlag Zeitfenster', 'string', 'text');
442
+ await mk('aiAdvisor.topCategory', 'Top-Vorschlag Kategorie', 'string', 'text');
183
443
  await mk('aiAdvisor.suggestionsJson', 'Vorschläge JSON', 'string', 'json');
184
444
  await mk('aiAdvisor.snapshotJson', 'KI-Energieberater Snapshot JSON', 'string', 'json');
185
445
  await mk('aiAdvisor.lastUpdate', 'Letzte Aktualisierung', 'number', 'value.time');
186
446
  await mk('aiAdvisor.nextUpdate', 'Nächste Aktualisierung', 'number', 'value.time');
187
-
188
- for (let i = 1; i <= 5; i++) {
189
- await a.setObjectNotExistsAsync(`aiAdvisor.suggestions.${i}`, {
190
- type: 'channel',
191
- common: { name: `Vorschlag ${i}` },
192
- native: {},
193
- });
447
+ for (let i = 1; i <= 8; i++) {
448
+ await a.setObjectNotExistsAsync(`aiAdvisor.suggestions.${i}`, { type: 'channel', common: { name: `Vorschlag ${i}` }, native: {} });
194
449
  await mk(`aiAdvisor.suggestions.${i}.title`, `Vorschlag ${i} Titel`, 'string', 'text');
195
450
  await mk(`aiAdvisor.suggestions.${i}.text`, `Vorschlag ${i} Text`, 'string', 'text');
196
451
  await mk(`aiAdvisor.suggestions.${i}.action`, `Vorschlag ${i} Handlung`, 'string', 'text');
@@ -243,6 +498,59 @@ class AiAdvisorModule extends BaseModule {
243
498
  return fallback;
244
499
  }
245
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
+
246
554
  async _snapshot() {
247
555
  const gridRawW = await this._readNumber(['ems.gridPowerRawW', 'grid.powerRawW', 'gridPointPower'], null);
248
556
  const gridW = await this._readNumber(['ems.budget.gridW', 'ems.gridPowerW', 'grid.powerW'], gridRawW || 0);
@@ -250,6 +558,13 @@ class AiAdvisorModule extends BaseModule {
250
558
  const gridExportW = await this._readNumber(['ems.budget.gridExportW', 'gridSellPower'], Math.max(0, -(num(gridRawW, gridW || 0))));
251
559
  const pvPowerW = await this._readNumber(['ems.budget.pvPowerW', 'derived.core.pv.totalW', 'pvPower', 'productionTotal'], 0);
252
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'], '');
253
568
 
254
569
  const storageSocPct = await this._readNumber(['storageFarm.totalSoc', 'speicher.regelung.socPct', 'storageSoc'], null);
255
570
  const storageChargeW = await this._readNumber(['ems.budget.storageChargeW', 'storageFarm.totalChargePowerW', 'storageChargePower'], 0);
@@ -258,6 +573,38 @@ class AiAdvisorModule extends BaseModule {
258
573
  const evcsUsedW = await this._readNumber(['chargingManagement.control.usedW', 'evcs.totalPowerW', 'consumptionEvcs'], 0);
259
574
  const thermalUsedW = await this._readNumber(['thermal.summary.budgetUsedW'], 0);
260
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;
261
608
 
262
609
  const tariffActive = await this._readBool(['tarif.aktiv', 'ems.budget.tariff.active'], false);
263
610
  const tariffState = await this._readString(['tarif.state', 'ems.budget.tariff.state'], '');
@@ -268,18 +615,37 @@ class AiAdvisorModule extends BaseModule {
268
615
  const nextCheapTo = await this._readString(['tarif.naechstesGuensigBis'], '');
269
616
  const negativeActive = await this._readBool(['tarif.negativpreisAktiv', 'ems.budget.tariff.negativeActive'], false);
270
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);
271
619
 
272
620
  const pvForecastUsable = await this._readBool(['ems.budget.forecast.usable', 'forecast.pv.valid'], false);
273
621
  const pvKwh6 = await this._readNumber(['ems.budget.forecast.kwhNext6h', 'forecast.pv.kwhNext6h'], 0);
274
622
  const pvKwh12 = await this._readNumber(['ems.budget.forecast.kwhNext12h', 'forecast.pv.kwhNext12h'], 0);
275
623
  const pvKwh24 = await this._readNumber(['ems.budget.forecast.kwhNext24h', 'forecast.pv.kwhNext24h'], 0);
276
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'], '');
277
638
 
278
639
  const peakActive = await this._readBool(['peakShaving.control.active'], false);
279
640
  const peakLimitW = await this._readNumber(['peakShaving.control.limitW', 'ems.core.gridImportLimitW_effective'], null);
280
641
  const peakOverW = await this._readNumber(['peakShaving.control.overW'], 0);
642
+ const peakStatus = await this._readString(['peakShaving.control.status'], '');
281
643
  const hlzfActive = await this._readBool(['peakShaving.atypical.activeWindow'], false);
282
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();
283
649
 
284
650
  return {
285
651
  ts: Date.now(),
@@ -287,14 +653,29 @@ class AiAdvisorModule extends BaseModule {
287
653
  gridW,
288
654
  gridImportW: Math.max(0, num(gridImportW, 0)),
289
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,
290
659
  pvPowerW: Math.max(0, num(pvPowerW, 0)),
291
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,
292
663
  storageSocPct: finiteNumber(storageSocPct) ? storageSocPct : null,
293
664
  storageChargeW: Math.max(0, num(storageChargeW, 0)),
294
665
  storageDischargeW: Math.max(0, num(storageDischargeW, 0)),
295
666
  evcsUsedW: Math.max(0, num(evcsUsedW, 0)),
296
667
  thermalUsedW: Math.max(0, num(thermalUsedW, 0)),
297
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,
298
679
  tariffActive,
299
680
  tariffState,
300
681
  priceNow,
@@ -304,17 +685,187 @@ class AiAdvisorModule extends BaseModule {
304
685
  nextCheapTo,
305
686
  negativeActive,
306
687
  gridImportPreferred,
688
+ co2IntensityGPerKwh: finiteNumber(co2IntensityGPerKwh) ? co2IntensityGPerKwh : null,
307
689
  pvForecastUsable,
308
690
  pvKwh6: Math.max(0, num(pvKwh6, 0)),
309
691
  pvKwh12: Math.max(0, num(pvKwh12, 0)),
310
692
  pvKwh24: Math.max(0, num(pvKwh24, 0)),
311
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,
312
706
  peakActive,
313
- peakLimitW,
707
+ peakLimitW: finiteNumber(peakLimitW) && peakLimitW > 0 ? peakLimitW : null,
314
708
  peakOverW: Math.max(0, num(peakOverW, 0)),
709
+ peakStatus,
710
+ peakConfigured,
315
711
  hlzfActive,
316
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 })),
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') });
317
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 };
318
869
  }
319
870
 
320
871
  _pushSuggestion(list, item) {
@@ -339,227 +890,105 @@ class AiAdvisorModule extends BaseModule {
339
890
 
340
891
  _buildSuggestions(s, cfg) {
341
892
  const out = [];
893
+ s.weatherSummary = s.weatherSummary || buildWeatherSummary(s);
342
894
  const tariffState = String(s.tariffState || '').toLowerCase();
343
895
  const currentCheap = !!(
344
- s.negativeActive ||
345
- s.gridImportPreferred ||
346
- 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') ||
347
897
  (finiteNumber(s.priceNow) && finiteNumber(s.priceCheapThreshold) && s.priceNow <= s.priceCheapThreshold) ||
348
898
  (finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow <= (s.priceAvg - cfg.cheapPriceMarginEurKwh))
349
899
  );
350
- const currentExpensive = !!(
351
- tariffState.includes('teuer') || tariffState.includes('expensive') ||
352
- (finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow >= (s.priceAvg + cfg.expensivePriceMarginEurKwh))
353
- );
900
+ const currentExpensive = !!(tariffState.includes('teuer') || tariffState.includes('expensive') || (finiteNumber(s.priceNow) && finiteNumber(s.priceAvg) && s.priceNow >= (s.priceAvg + cfg.expensivePriceMarginEurKwh)));
354
901
  const hasStorage = s.storageSocPct !== null;
355
902
  const storageEnough = !hasStorage || s.storageSocPct >= cfg.minSocForDischargePct;
356
- const hasFlexibleLoad = (s.evcsUsedW > 100 || s.thermalUsedW > 100 || s.heatingRodUsedW > 100)
357
- || !!(this.adapter && this.adapter.config && (this.adapter.config.enableChargingManagement || this.adapter.config.enableThermalControl || this.adapter.config.enableHeatingRodControl));
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.');
358
914
 
359
- if (s.negativeActive || s.gridImportPreferred) {
360
- this._pushSuggestion(out, {
361
- id: 'negative-price-window',
362
- category: 'tariff',
363
- severity: 'success',
364
- priority: 98,
365
- icon: '🟢',
366
- title: 'Negativpreis-Fenster nutzen',
367
- 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.`,
368
- action: 'Wallbox, Speicher-Netzladung oder Wärmelast jetzt freigeben, falls der Nutzer das möchte.',
369
- window: 'jetzt',
370
- impact: 'Kostenoptimierung',
371
- confidence: 90,
372
- });
373
- } else if (currentCheap) {
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)})` : '';
374
918
  this._pushSuggestion(out, {
375
- id: 'cheap-tariff-now',
376
- category: 'tariff',
377
- severity: 'success',
378
- priority: 88,
379
- icon: '💶',
380
- title: 'Günstiges Tariffenster aktiv',
381
- text: `Der Strompreis ist günstig${finiteNumber(s.priceNow) ? ` (${formatPrice(s.priceNow)})` : ''}. Verschiebbare Lasten sind jetzt wirtschaftlicher als in teuren Zeiten.`,
382
- action: 'EV-Laden, Warmwasser/Heizstab oder Speicherladung bevorzugt in dieses Fenster legen.',
383
- window: 'jetzt',
384
- impact: 'Energiekosten senken',
385
- 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,
386
924
  });
387
- } else if (s.tariffActive && s.nextCheapFrom) {
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)}.` : '';
388
928
  this._pushSuggestion(out, {
389
- id: 'next-cheap-window',
390
- category: 'tariff',
391
- severity: 'info',
392
- priority: 62,
393
- icon: '⏱️',
394
- title: 'Nächstes günstiges Zeitfenster vormerken',
395
- text: `Das nächste günstige Tariffenster liegt bei ${shortIsoWindow(s.nextCheapFrom, s.nextCheapTo) || 'demnächst'}.`,
396
- action: 'Planbare Verbraucher möglichst in dieses Fenster verschieben.',
397
- window: shortIsoWindow(s.nextCheapFrom, s.nextCheapTo),
398
- impact: 'Lastverschiebung',
399
- confidence: 75,
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,
400
934
  });
401
935
  }
402
936
 
403
- if (currentExpensive) {
404
- this._pushSuggestion(out, {
405
- id: 'expensive-tariff-reduce-load',
406
- category: 'tariff',
407
- severity: 'warning',
408
- priority: storageEnough ? 90 : 82,
409
- icon: '🟠',
410
- title: 'Teures Tariffenster — Verbrauch reduzieren',
411
- text: `Der Tarif ist aktuell teuer${finiteNumber(s.priceNow) ? ` (${formatPrice(s.priceNow)})` : ''}. Große flexible Verbraucher sollten möglichst warten.`,
412
- action: storageEnough ? 'Speicherentladung nutzen und EV/Heizstab nach hinten schieben.' : 'EV/Heizstab nach hinten schieben; Speicherreserve ist niedrig.',
413
- window: 'jetzt vermeiden',
414
- impact: 'Kosten vermeiden',
415
- confidence: 82,
416
- });
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 });
417
939
  }
418
940
 
419
- const surplusW = Math.max(s.gridExportW, s.pvBudgetW);
420
- if (surplusW >= cfg.pvSurplusThresholdW) {
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;
421
947
  this._pushSuggestion(out, {
422
- id: 'pv-surplus-use-now',
423
- category: 'pv',
424
- severity: 'success',
425
- priority: 86,
426
- icon: '☀️',
427
- title: 'PV-Überschuss jetzt nutzen',
428
- text: `Es stehen etwa ${formatKw(surplusW)} PV-/Einspeiseüberschuss zur Verfügung.`,
429
- action: hasFlexibleLoad ? 'Wallbox, Heizstab oder Wärmelast bevorzugt jetzt starten.' : 'Flexible Verbraucher einplanen oder zusätzliche Verbraucher im App-Center anbinden.',
430
- window: 'jetzt',
431
- impact: 'Eigenverbrauch erhöhen',
432
- confidence: 88,
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,
433
952
  });
434
953
  }
435
954
 
436
- if (s.pvForecastUsable && (s.pvKwh24 >= cfg.pvForecastMinKwh || s.pvPeak24W >= cfg.pvPeakMinW)) {
437
- let prio = 58;
438
- let title = 'PV-Ertrag vorausplanen';
439
- let action = `Morgen/innerhalb 24h werden etwa ${formatKwh(s.pvKwh24)} erwartet — flexible Lasten in die PV-Zeit legen.`;
440
- let severity = 'info';
441
- if (hasStorage && s.storageSocPct >= cfg.highSocPct) {
442
- title = 'PV-Speicher-Headroom freihalten';
443
- 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.`;
444
- prio = 74;
445
- } else if (hasStorage && s.storageSocPct <= cfg.lowSocPct) {
446
- title = 'Speicherreserve und PV-Fenster abstimmen';
447
- 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.`;
448
- prio = 72;
449
- severity = 'warning';
450
- }
451
- this._pushSuggestion(out, {
452
- id: 'pv-forecast-plan',
453
- category: 'forecast',
454
- severity,
455
- priority: prio,
456
- icon: '🔮',
457
- title,
458
- text: `PV-Prognose: ${formatKwh(s.pvKwh6)} in 6h, ${formatKwh(s.pvKwh24)} in 24h${s.pvPeak24W > 0 ? `, Peak ${formatKw(s.pvPeak24W)}` : ''}.`,
459
- action,
460
- window: 'nächste 24h',
461
- impact: 'PV-Nutzung planen',
462
- confidence: 76,
463
- });
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 });
464
961
  }
465
962
 
466
- if (s.peakActive || s.hlzfActive || s.peakOverW > 0) {
467
- this._pushSuggestion(out, {
468
- id: 'peak-window-protect',
469
- category: 'peak',
470
- severity: s.peakOverW > 0 ? 'critical' : 'warning',
471
- priority: 96,
472
- icon: '⚡',
473
- title: s.hlzfActive ? 'Hochlastzeitfenster aktiv' : 'Peak-Shaving aktiv',
474
- text: s.peakOverW > 0
475
- ? `Aktuell liegt der Netzbezug etwa ${formatKw(s.peakOverW)} über dem Limit.`
476
- : `Der Netzbezug wird aktuell durch ${s.hlzfActive ? 'HLZF/§19' : 'Peak-Shaving'} begrenzt${finiteNumber(s.peakLimitW) ? ` (Limit ${formatKw(s.peakLimitW)})` : ''}.`,
477
- action: 'EV-Laden, Heizstab und andere flexible Lasten pausieren oder reduzieren, bis das Fenster vorbei ist.',
478
- window: 'jetzt',
479
- impact: 'Leistungspreis / Netzlimit schützen',
480
- confidence: 90,
481
- });
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 });
482
966
  }
483
967
 
484
- if (s.para14aActive) {
485
- this._pushSuggestion(out, {
486
- id: 'para14a-active',
487
- category: 'grid',
488
- severity: 'warning',
489
- priority: 84,
490
- icon: '🚦',
491
- title: '§14a-Leistungsbegrenzung aktiv',
492
- text: 'Der Netzbetreiber-/EMS-Deckel für steuerbare Verbraucher ist aktiv.',
493
- action: 'Komfortverbraucher priorisieren und nicht notwendige Verbraucher verschieben.',
494
- window: 'jetzt',
495
- impact: 'Netzvorgabe einhalten',
496
- confidence: 85,
497
- });
498
- }
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 });
499
971
 
500
- if (hasStorage && s.storageSocPct <= cfg.lowSocPct) {
501
- this._pushSuggestion(out, {
502
- id: 'storage-low-reserve',
503
- category: 'storage',
504
- severity: 'warning',
505
- priority: 78,
506
- icon: '🔋',
507
- title: 'Speicherreserve niedrig',
508
- text: `Der Speicher liegt bei ${round(s.storageSocPct, 0)} %.`,
509
- action: 'Reservegrenze prüfen; flexible Lasten eher in PV- oder günstige Tariffenster verschieben.',
510
- window: 'bis Reserve erholt ist',
511
- impact: 'Reserve schützen',
512
- confidence: 80,
513
- });
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 });
514
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 });
515
979
 
516
- if (s.gridImportW >= cfg.highImportThresholdW && !currentCheap && !s.negativeActive) {
517
- this._pushSuggestion(out, {
518
- id: 'high-grid-import',
519
- category: 'grid',
520
- severity: 'warning',
521
- priority: 70,
522
- icon: '📉',
523
- title: 'Hoher Netzbezug erkannt',
524
- text: `Aktuell werden etwa ${formatKw(s.gridImportW)} aus dem Netz bezogen.`,
525
- action: 'Nicht dringende Verbraucher verschieben; bei Speicher prüfen, ob Entladen freigegeben ist.',
526
- window: 'jetzt',
527
- impact: 'Netzbezug senken',
528
- confidence: 72,
529
- });
530
- }
531
-
532
- if (cfg.includeInstallerHints && !s.tariffActive && !finiteNumber(s.priceNow)) {
533
- this._pushSuggestion(out, {
534
- id: 'setup-tariff',
535
- category: 'setup',
536
- severity: 'info',
537
- priority: 30,
538
- icon: '🧭',
539
- title: 'Dynamischen Tarif anbinden',
540
- text: 'Für bessere Zeitvorschläge fehlt aktuell ein frisches Preis-/Tarifsignal.',
541
- action: 'Im App-Center Tarife/Preisprognose zuordnen.',
542
- window: 'Setup',
543
- impact: 'KI-Beratung verbessern',
544
- confidence: 70,
545
- });
546
- }
547
-
548
- if (cfg.includeInstallerHints && !s.pvForecastUsable) {
549
- this._pushSuggestion(out, {
550
- id: 'setup-pv-forecast',
551
- category: 'setup',
552
- severity: 'info',
553
- priority: 28,
554
- icon: '☀️',
555
- title: 'PV-Forecast aktivieren',
556
- text: 'Für vorausschauende Empfehlungen fehlt eine nutzbare PV-Prognose.',
557
- action: 'PV-Forecast im App-Center einrichten, damit Verbraucher zeitlich besser geplant werden können.',
558
- window: 'Setup',
559
- impact: 'Prognosequalität erhöhen',
560
- confidence: 70,
561
- });
562
- }
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 });
563
992
 
564
993
  const seen = new Set();
565
994
  const deduped = [];
@@ -570,7 +999,6 @@ class AiAdvisorModule extends BaseModule {
570
999
  delete clean.rankWeight;
571
1000
  deduped.push(clean);
572
1001
  }
573
-
574
1002
  const minPriorityMap = { info: 0, warning: 60, action: 75, critical: 90 };
575
1003
  const minPrio = minPriorityMap[cfg.minPriority] || 0;
576
1004
  const categoryAllowed = (item) => {
@@ -581,43 +1009,37 @@ class AiAdvisorModule extends BaseModule {
581
1009
  if (cat === 'storage') return cats.storage !== false;
582
1010
  if (cat === 'evcs') return cats.evcs !== false;
583
1011
  if (cat === 'peak') return cats.peak !== false;
1012
+ if (cat === 'weather') return cats.weather !== false;
584
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;
585
1019
  if (cat === 'grid' || cat === 'setup' || cat === 'system' || cat === 'general') return cats.system !== false;
586
1020
  return true;
587
1021
  };
588
1022
  let filtered = deduped.filter((item) => categoryAllowed(item) && (Number(item.priority) || 0) >= minPrio);
589
-
590
1023
  if (!filtered.length) {
591
- this._pushSuggestion(filtered, {
592
- id: 'system-balanced',
593
- category: 'system',
594
- severity: 'success',
595
- priority: 20,
596
- icon: '✅',
597
- title: 'System läuft wirtschaftlich unauffällig',
598
- text: 'Aktuell erkennt der KI-Energieberater keine dringende Optimierung.',
599
- action: 'Weiter beobachten; größere Verbraucher möglichst in PV- oder günstige Tariffenster legen.',
600
- window: 'laufend',
601
- impact: 'Monitoring',
602
- confidence: 65,
603
- });
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 });
604
1025
  filtered = filtered.filter((item) => categoryAllowed(item));
605
1026
  }
606
-
607
- 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);
608
1028
  }
609
1029
 
610
1030
  _score(snapshot, suggestions) {
611
- let score = 78;
612
- const maxSeverity = (suggestions || [])[0] ? String(suggestions[0].severity || '') : '';
613
- if (maxSeverity === 'critical') score -= 28;
614
- else if (maxSeverity === 'warning') score -= 15;
615
- else if (maxSeverity === 'success') score += 8;
616
- if (snapshot.gridExportW > 2500) score -= 5;
617
- 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;
618
1037
  if (snapshot.pvForecastUsable) score += 4;
1038
+ if (snapshot.weatherEnabled) score += 2;
619
1039
  if (snapshot.tariffActive || finiteNumber(snapshot.priceNow)) score += 4;
620
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;
621
1043
  return clamp(Math.round(score), 0, 100);
622
1044
  }
623
1045
 
@@ -629,23 +1051,51 @@ class AiAdvisorModule extends BaseModule {
629
1051
  async _publishDisabled(cfg, now) {
630
1052
  if ((now - (this._lastDisabledWriteMs || 0)) < 60000) return;
631
1053
  this._lastDisabledWriteMs = now;
1054
+ const disabledByCustomer = cfg.customerEnabled === false;
632
1055
  await this._set('aiAdvisor.enabled', false);
633
1056
  await this._set('aiAdvisor.advisoryOnly', true);
634
1057
  await this._set('aiAdvisor.showInLive', cfg.showInLive !== false);
1058
+ await this._set('aiAdvisor.showOnLive', cfg.showInLive !== false);
635
1059
  await this._set('aiAdvisor.status', 'disabled');
636
1060
  await this._set('aiAdvisor.severity', 'neutral');
637
1061
  await this._set('aiAdvisor.headline', 'KI-Energieberater deaktiviert');
638
- await this._set('aiAdvisor.summary', 'Die beratende KI ist im App-Center deaktiviert.');
1062
+ await this._set('aiAdvisor.summary', disabledByCustomer ? 'Die beratende KI ist in den Kundeneinstellungen deaktiviert.' : 'Die beratende KI ist im App-Center deaktiviert.');
639
1063
  await this._set('aiAdvisor.count', 0);
640
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', '[]');
641
1081
  await this._set('aiAdvisor.topTitle', '');
642
1082
  await this._set('aiAdvisor.topText', '');
643
1083
  await this._set('aiAdvisor.topAction', '');
644
1084
  await this._set('aiAdvisor.topWindow', '');
1085
+ await this._set('aiAdvisor.topCategory', '');
645
1086
  await this._set('aiAdvisor.suggestionsJson', '[]');
646
1087
  await this._set('aiAdvisor.snapshotJson', JSON.stringify({ ts: now, enabled: false }));
647
1088
  await this._set('aiAdvisor.lastUpdate', now);
648
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
+ }
649
1099
  }
650
1100
 
651
1101
  async _publish(snapshot, suggestions, cfg) {
@@ -655,7 +1105,22 @@ class AiAdvisorModule extends BaseModule {
655
1105
  const severity = top ? String(top.severity || 'info') : 'neutral';
656
1106
  const headline = top ? `${top.icon || '💡'} ${top.title}` : 'KI-Energieberater bereit';
657
1107
  const summary = top ? String(top.text || '') : 'Keine aktuellen Hinweise.';
658
- const jsonSuggestions = JSON.stringify(suggestions || []);
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 || {};
659
1124
  const snap = {
660
1125
  ts: now,
661
1126
  enabled: true,
@@ -663,50 +1128,72 @@ class AiAdvisorModule extends BaseModule {
663
1128
  showInLive: cfg.showInLive !== false,
664
1129
  status: 'ok',
665
1130
  score,
1131
+ peakUsagePct,
1132
+ peakStateText,
1133
+ weatherSummary,
1134
+ dailyPlan,
1135
+ evPlanText,
1136
+ comfortWindowSummary,
1137
+ learning,
666
1138
  severity,
667
1139
  top,
668
1140
  suggestions,
669
1141
  raw: snapshot,
670
1142
  };
671
- const hash = makeHash({ suggestions, score, severity, show: cfg.showInLive });
672
-
673
- // 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 });
674
1144
  const contentChanged = hash !== this._lastHash;
675
1145
  this._lastHash = hash;
676
1146
 
677
1147
  await this._set('aiAdvisor.enabled', true);
678
1148
  await this._set('aiAdvisor.advisoryOnly', true);
679
1149
  await this._set('aiAdvisor.showInLive', cfg.showInLive !== false);
1150
+ await this._set('aiAdvisor.showOnLive', cfg.showInLive !== false);
680
1151
  await this._set('aiAdvisor.status', 'ok');
681
1152
  await this._set('aiAdvisor.severity', severity);
682
1153
  await this._set('aiAdvisor.headline', headline);
683
1154
  await this._set('aiAdvisor.summary', summary);
684
1155
  await this._set('aiAdvisor.count', Array.isArray(suggestions) ? suggestions.length : 0);
685
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 || '[]');
686
1173
  await this._set('aiAdvisor.topTitle', top ? top.title : '');
687
1174
  await this._set('aiAdvisor.topText', top ? top.text : '');
688
1175
  await this._set('aiAdvisor.topAction', top ? top.action : '');
689
1176
  await this._set('aiAdvisor.topWindow', top ? top.window : '');
1177
+ await this._set('aiAdvisor.topCategory', top ? top.category : '');
690
1178
  if (contentChanged) {
691
1179
  await this._set('aiAdvisor.suggestionsJson', jsonSuggestions);
692
1180
  await this._set('aiAdvisor.snapshotJson', JSON.stringify(snap));
693
1181
  } else {
694
- // keep JSON in stateCache fresh after restarts even if identical writes are skipped by ioBroker internals
695
1182
  try { if (typeof this.adapter.updateValue === 'function') this.adapter.updateValue('aiAdvisor.suggestionsJson', jsonSuggestions, now); } catch (_e) {}
696
1183
  try { if (typeof this.adapter.updateValue === 'function') this.adapter.updateValue('aiAdvisor.snapshotJson', JSON.stringify(snap), now); } catch (_e) {}
697
1184
  }
698
1185
  await this._set('aiAdvisor.lastUpdate', now);
699
1186
  await this._set('aiAdvisor.nextUpdate', now + Math.round(cfg.minIntervalSec * 1000));
700
1187
 
701
- for (let i = 1; i <= 5; i++) {
702
- const s = (Array.isArray(suggestions) && suggestions[i - 1]) ? suggestions[i - 1] : null;
703
- await this._set(`aiAdvisor.suggestions.${i}.title`, s ? s.title : '');
704
- await this._set(`aiAdvisor.suggestions.${i}.text`, s ? s.text : '');
705
- await this._set(`aiAdvisor.suggestions.${i}.action`, s ? s.action : '');
706
- await this._set(`aiAdvisor.suggestions.${i}.severity`, s ? s.severity : '');
707
- await this._set(`aiAdvisor.suggestions.${i}.category`, s ? s.category : '');
708
- await this._set(`aiAdvisor.suggestions.${i}.window`, s ? s.window : '');
709
- await this._set(`aiAdvisor.suggestions.${i}.impact`, s ? s.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 : '');
710
1197
  }
711
1198
  }
712
1199
 
@@ -714,17 +1201,17 @@ class AiAdvisorModule extends BaseModule {
714
1201
  if (!this._inited) await this.init();
715
1202
  const cfg = this._cfg();
716
1203
  const now = Date.now();
717
-
718
1204
  if (!cfg.enabled) {
719
1205
  await this._publishDisabled(cfg, now);
720
1206
  return;
721
1207
  }
722
-
723
1208
  const minMs = Math.max(10000, Math.round(cfg.minIntervalSec * 1000));
724
1209
  if (this._lastRunMs && (now - this._lastRunMs) < minMs) return;
725
1210
  this._lastRunMs = now;
726
-
727
- const snapshot = await this._snapshot();
1211
+ let snapshot = await this._snapshot();
1212
+ snapshot = this._updateLearning(snapshot, cfg);
1213
+ snapshot.dayPlan = this._makeDailyPlan(snapshot, cfg);
1214
+ this._lastPlan = snapshot.dayPlan;
728
1215
  const suggestions = this._buildSuggestions(snapshot, cfg);
729
1216
  await this._publish(snapshot, suggestions, cfg);
730
1217
  }