iobroker.nexowatt-ui 0.7.26 → 0.7.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ems/engine.js CHANGED
@@ -594,8 +594,9 @@ class EmsEngine {
594
594
  adapter.config._chargingHasAnySetpoint = !!anyControl;
595
595
  adapter.config.chargingManagement = chargingCfg;
596
596
 
597
- // If PeakShaving is enabled but no gridPointPowerId is set, default to internal derived net grid power
598
- if (adapter.config.enablePeakShaving) {
597
+ // If PeakShaving/Atypical HLZF is enabled but no gridPointPowerId is set, default to internal derived net grid power
598
+ const peakRuntimeEnabled = !!adapter.config.enablePeakShaving || !!(adapter.config.peakShaving && adapter.config.peakShaving.atypical && adapter.config.peakShaving.atypical.enabled);
599
+ if (peakRuntimeEnabled) {
599
600
  adapter.config.peakShaving = adapter.config.peakShaving || {};
600
601
  const gp = typeof adapter.config.peakShaving.gridPointPowerId === 'string' ? adapter.config.peakShaving.gridPointPowerId.trim() : '';
601
602
  if (!gp && this._gridPowerId) {
@@ -109,7 +109,7 @@ class ModuleManager {
109
109
  this.modules.push({
110
110
  key: 'peakShaving',
111
111
  instance: new PeakShavingModule(this.adapter, this.dp),
112
- enabledFn: () => !!this.adapter.config.enablePeakShaving,
112
+ enabledFn: () => !!this.adapter.config.enablePeakShaving || !!(this.adapter.config.peakShaving && this.adapter.config.peakShaving.atypical && this.adapter.config.peakShaving.atypical.enabled),
113
113
  });
114
114
 
115
115
  // §14a EnWG (steuerbare Verbrauchseinrichtungen)
@@ -383,6 +383,7 @@ class ChargingManagementModule extends BaseModule {
383
383
  this._pvStartReadySinceMs = new Map(); // safeKey -> ms since PV-only start conditions are continuously satisfied
384
384
  this._pvBelowMinSinceMs = new Map(); // safeKey -> ms since a running PV-only session is continuously below the technical minimum
385
385
  this._pvMinRunUntilMs = new Map(); // safeKey -> ms until a freshly started PV-only session should be kept stable
386
+ this._pvStartCooldownUntilMs = new Map(); // safeKey -> ms until a failed PV-only start may be retried
386
387
  }
387
388
 
388
389
  /**
@@ -1265,6 +1266,7 @@ class ChargingManagementModule extends BaseModule {
1265
1266
  const pvConnectorStopDelayMs = clamp(num(cfg.pvConnectorStopDelaySec, Math.max(num(cfg.pvStopDelaySec, 30), 45)), 0, 3600) * 1000;
1266
1267
  const pvMinRunMs = clamp(num(cfg.pvMinRunSec, 45), 0, 3600) * 1000;
1267
1268
  const pvRunDeficitToleranceW = clamp(num(cfg.pvRunDeficitToleranceW, 600), 0, 1e12);
1269
+ const pvStartRetryCooldownMs = clamp(num(cfg.pvStartRetryCooldownSec, num(cfg.pvRestartCooldownSec, 180)), 0, 3600) * 1000;
1268
1270
  const pvRampUpAperTick = clamp(num(cfg.pvRampUpAperTick, 0.5), 0, 1e6);
1269
1271
  const pvRampUpWPerTick = clamp(num(cfg.pvRampUpWPerTick, 350), 0, 1e12);
1270
1272
 
@@ -1872,13 +1874,16 @@ class ChargingManagementModule extends BaseModule {
1872
1874
 
1873
1875
  let pvStartupHoldUntilMs = this._pvStartupUntilMs.get(safe) || 0;
1874
1876
  let pvMinRunUntilMs = this._pvMinRunUntilMs.get(safe) || 0;
1877
+ let pvStartCooldownUntilMs = this._pvStartCooldownUntilMs.get(safe) || 0;
1875
1878
  if (!enabled || !online || vehiclePlugged === false) {
1876
1879
  this._pvStartupUntilMs.delete(safe);
1877
1880
  this._pvStartReadySinceMs.delete(safe);
1878
1881
  this._pvBelowMinSinceMs.delete(safe);
1879
1882
  this._pvMinRunUntilMs.delete(safe);
1883
+ this._pvStartCooldownUntilMs.delete(safe);
1880
1884
  pvStartupHoldUntilMs = 0;
1881
1885
  pvMinRunUntilMs = 0;
1886
+ pvStartCooldownUntilMs = 0;
1882
1887
  } else {
1883
1888
  if (pvStartupHoldUntilMs > 0 && now >= pvStartupHoldUntilMs) {
1884
1889
  this._pvStartupUntilMs.delete(safe);
@@ -1888,6 +1893,10 @@ class ChargingManagementModule extends BaseModule {
1888
1893
  this._pvMinRunUntilMs.delete(safe);
1889
1894
  pvMinRunUntilMs = 0;
1890
1895
  }
1896
+ if (pvStartCooldownUntilMs > 0 && now >= pvStartCooldownUntilMs) {
1897
+ this._pvStartCooldownUntilMs.delete(safe);
1898
+ pvStartCooldownUntilMs = 0;
1899
+ }
1891
1900
  }
1892
1901
 
1893
1902
  try {
@@ -2070,6 +2079,7 @@ class ChargingManagementModule extends BaseModule {
2070
2079
  actualPowerW: pWNum,
2071
2080
  pvStartupHoldUntilMs,
2072
2081
  pvMinRunUntilMs,
2082
+ pvStartCooldownUntilMs,
2073
2083
  userMode,
2074
2084
  evcsIndex: (Number.isFinite(evcsIndex) && evcsIndex > 0) ? Math.round(evcsIndex) : 0,
2075
2085
  vehiclePlugged,
@@ -2815,7 +2825,10 @@ class ChargingManagementModule extends BaseModule {
2815
2825
  // PV - (Verbrauch ohne EV) - Speicherladung
2816
2826
  // Bei aktiver EV-Priorität wird PV-Speicherladung, die gerade den Überschuss bindet,
2817
2827
  // nicht abgezogen. Diese Leistung soll zuerst der Wallbox angeboten werden.
2818
- const baseLoadNoEvW = Math.max(0, loadTotalDirectW - pvEvcsActualW);
2828
+ const evcsForLoadW = (pvEvcsUsedW > pvEvcsActualW && loadTotalDirectW >= (pvEvcsUsedW - 100))
2829
+ ? pvEvcsUsedW
2830
+ : pvEvcsActualW;
2831
+ const baseLoadNoEvW = Math.max(0, loadTotalDirectW - evcsForLoadW);
2819
2832
  const storageChargeBlockingPvW = Math.max(0, storageChargeNowW - evPriorityStorageYieldW);
2820
2833
  pvSurplusNoEvW = Math.max(0, pvDirectW - baseLoadNoEvW - storageChargeBlockingPvW);
2821
2834
  gridImportNoEvW = Math.max(0, baseLoadNoEvW + storageChargeBlockingPvW - pvDirectW);
@@ -4109,6 +4122,9 @@ if (components.length) {
4109
4122
  const actualOrCmdActive = !!w.charging || actualNowW >= activityThresholdW || prevCmdWasActive;
4110
4123
  const startupHoldActive = isPvManaged && Number.isFinite(Number(w.pvStartupHoldUntilMs)) && Number(w.pvStartupHoldUntilMs) > now;
4111
4124
  const minRunActive = isPvOnly && Number.isFinite(Number(w.pvMinRunUntilMs)) && Number(w.pvMinRunUntilMs) > now;
4125
+ const startCooldownActive = isPvOnly && !actualOrCmdActive
4126
+ && Number.isFinite(Number(w.pvStartCooldownUntilMs))
4127
+ && Number(w.pvStartCooldownUntilMs) > now;
4112
4128
  const pvTechnicalMinW = (w.chargerType === 'AC' && Number(w.phases || 0) === 3)
4113
4129
  ? Math.max(0, Math.max(num(w.minPW, 0), acMinPower3pW))
4114
4130
  : Math.max(0, num(w.minPW, 0));
@@ -4335,7 +4351,15 @@ if (components.length) {
4335
4351
  this._pvStartReadySinceMs.delete(startReadyKey);
4336
4352
  this._pvBelowMinSinceMs.delete(startReadyKey);
4337
4353
  } else {
4338
- if (!actualOrCmdActive) {
4354
+ if (startCooldownActive) {
4355
+ this._pvStartReadySinceMs.delete(startReadyKey);
4356
+ startReadySince = 0;
4357
+ if (targetW > 0) {
4358
+ targetW = 0;
4359
+ targetA = 0;
4360
+ reason = ReasonCodes.NO_PV_SURPLUS;
4361
+ }
4362
+ } else if (!actualOrCmdActive) {
4339
4363
  if (needStartW <= 0 || startReadyBudgetW >= needStartW) {
4340
4364
  if (!startReadySince) {
4341
4365
  startReadySince = now;
@@ -4396,6 +4420,7 @@ if (components.length) {
4396
4420
  this._pvStartReadySinceMs.delete(String(w.safe || ''));
4397
4421
  this._pvBelowMinSinceMs.delete(String(w.safe || ''));
4398
4422
  if (!isPvManaged) this._pvMinRunUntilMs.delete(String(w.safe || ''));
4423
+ if (!isPvManaged) this._pvStartCooldownUntilMs.delete(String(w.safe || ''));
4399
4424
  }
4400
4425
 
4401
4426
  // Convert to A for AC current-based control
@@ -4616,6 +4641,34 @@ if (components.length) {
4616
4641
  this._lastCmdTargetW.set(w.safe, cmdW);
4617
4642
  this._lastCmdTargetA.set(w.safe, cmdA);
4618
4643
 
4644
+ // If a PV-only start attempt collapses before the wallbox reports real power,
4645
+ // wait briefly before trying again. This prevents repeated short start pulses
4646
+ // while still allowing the same PV window to recover after a few minutes.
4647
+ try {
4648
+ if (isPvOnly && actualNowW >= activityThresholdW) {
4649
+ this._pvStartCooldownUntilMs.delete(w.safe);
4650
+ } else if (isPvOnly
4651
+ && pvStartRetryCooldownMs > 0
4652
+ && prevCmdWasActive
4653
+ && cmdW < activityThresholdW
4654
+ && actualNowW < activityThresholdW
4655
+ && w.charging !== true
4656
+ && w.enabled
4657
+ && w.online
4658
+ && w.vehiclePlugged !== false
4659
+ && (reason === ReasonCodes.NO_PV_SURPLUS || reason === ReasonCodes.BELOW_MIN || limiter === 'pv')) {
4660
+ this._pvStartCooldownUntilMs.set(w.safe, now + pvStartRetryCooldownMs);
4661
+ this._pvStartReadySinceMs.delete(w.safe);
4662
+ this._pvBelowMinSinceMs.delete(w.safe);
4663
+ this._pvStartupUntilMs.delete(w.safe);
4664
+ this._pvMinRunUntilMs.delete(w.safe);
4665
+ } else if (!isPvOnly || w.vehiclePlugged === false || !w.enabled || !w.online) {
4666
+ this._pvStartCooldownUntilMs.delete(w.safe);
4667
+ }
4668
+ } catch {
4669
+ // ignore
4670
+ }
4671
+
4619
4672
  // PV-Start Einschwingzeit + Mindestlaufzeit:
4620
4673
  // Einige Wallboxen/Fahrzeuge übernehmen nach der Freigabe die neue Leistung verzögert.
4621
4674
  // Damit wir direkt nach dem Start nicht wieder auf 0 regeln, halten wir eine kurze
@@ -4898,4 +4951,4 @@ if (components.length) {
4898
4951
  }
4899
4952
  }
4900
4953
 
4901
- module.exports = { ChargingManagementModule };
4954
+ module.exports = { ChargingManagementModule };
@@ -25,6 +25,15 @@ function isFiniteNumber(v) {
25
25
  return typeof v === 'number' && Number.isFinite(v);
26
26
  }
27
27
 
28
+ function isPeakShavingRuntimeEnabled(config) {
29
+ const cfg = (config && typeof config === 'object') ? config : {};
30
+ if (cfg.enablePeakShaving === true) return true;
31
+ const ps = (cfg.peakShaving && typeof cfg.peakShaving === 'object') ? cfg.peakShaving : {};
32
+ const atypical = (ps.atypical && typeof ps.atypical === 'object') ? ps.atypical : {};
33
+ return atypical.enabled === true;
34
+ }
35
+
36
+
28
37
  async function readStateNumber(adapter, id, fallback = null) {
29
38
  try {
30
39
  const st = await adapter.getStateAsync(id);
@@ -732,7 +741,7 @@ class CoreLimitsModule extends BaseModule {
732
741
  if (base > 0) gridImportLimitW_physical = Math.max(0, base - gridSafetyMarginW);
733
742
  }
734
743
 
735
- const peakEnabledCfg = !!cfg.enablePeakShaving;
744
+ const peakEnabledCfg = isPeakShavingRuntimeEnabled(cfg);
736
745
  const peakShavingLimitW_raw = await readStateNumber(this.adapter, 'peakShaving.control.limitW', null);
737
746
  const gridImportLimitW_peakShaving = (peakEnabledCfg && typeof peakShavingLimitW_raw === 'number' && Number.isFinite(peakShavingLimitW_raw) && peakShavingLimitW_raw > 0)
738
747
  ? peakShavingLimitW_raw
@@ -64,6 +64,118 @@ function clamp(n, min, max) {
64
64
  return n;
65
65
  }
66
66
 
67
+ const ATYPICAL_THRESHOLD_PERCENT_BY_VOLTAGE_LEVEL = Object.freeze({
68
+ // §19 Abs. 2 S. 1 StromNEV / BNetzA-Leitfaden: Erheblichkeitsschwellen je Entnahmeebene.
69
+ HOS: 5,
70
+ HOSHS: 10,
71
+ HS: 10,
72
+ HSMS: 20,
73
+ MS: 20,
74
+ MSNS: 30,
75
+ NS: 30,
76
+ });
77
+
78
+ function normalizeVoltageLevelKey(v) {
79
+ return String(v || '')
80
+ .normalize('NFD')
81
+ .replace(/[\u0300-\u036f]/g, '')
82
+ .toUpperCase()
83
+ .replace(/[^A-Z0-9]+/g, '');
84
+ }
85
+
86
+ function atypicalThresholdPercent(voltageLevel, fallback = 20) {
87
+ const key = normalizeVoltageLevelKey(voltageLevel);
88
+ if (Object.prototype.hasOwnProperty.call(ATYPICAL_THRESHOLD_PERCENT_BY_VOLTAGE_LEVEL, key)) {
89
+ return ATYPICAL_THRESHOLD_PERCENT_BY_VOLTAGE_LEVEL[key];
90
+ }
91
+ return fallback;
92
+ }
93
+
94
+ function isPeakShavingRuntimeEnabled(config) {
95
+ const cfg = (config && typeof config === 'object') ? config : {};
96
+ if (cfg.enablePeakShaving === true) return true;
97
+ const ps = (cfg.peakShaving && typeof cfg.peakShaving === 'object') ? cfg.peakShaving : {};
98
+ const atypical = (ps.atypical && typeof ps.atypical === 'object') ? ps.atypical : {};
99
+ return atypical.enabled === true;
100
+ }
101
+
102
+ function parseHmToMinutes(value) {
103
+ const s = String(value || '').trim();
104
+ const m = s.match(/^(\d{1,2}):(\d{2})$/);
105
+ if (!m) return null;
106
+ const h = Number(m[1]);
107
+ const min = Number(m[2]);
108
+ if (!Number.isInteger(h) || !Number.isInteger(min) || h < 0 || h > 23 || min < 0 || min > 59) return null;
109
+ return h * 60 + min;
110
+ }
111
+
112
+ function localYmd(date) {
113
+ const d = (date instanceof Date) ? date : new Date(date);
114
+ if (!(d instanceof Date) || Number.isNaN(d.getTime())) return '';
115
+ const y = String(d.getFullYear()).padStart(4, '0');
116
+ const m = String(d.getMonth() + 1).padStart(2, '0');
117
+ const day = String(d.getDate()).padStart(2, '0');
118
+ return `${y}-${m}-${day}`;
119
+ }
120
+
121
+ function normalizeYmd(value) {
122
+ if (value instanceof Date) return localYmd(value);
123
+ const s = String(value || '').trim();
124
+ if (!s) return '';
125
+ const m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
126
+ if (m) {
127
+ return `${String(m[1]).padStart(4, '0')}-${String(m[2]).padStart(2, '0')}-${String(m[3]).padStart(2, '0')}`;
128
+ }
129
+ const d = new Date(s);
130
+ return Number.isNaN(d.getTime()) ? '' : localYmd(d);
131
+ }
132
+
133
+ function asArray(value) {
134
+ if (Array.isArray(value)) return value;
135
+ if (typeof value === 'string') return value.split(/[,;\n]+/).map(s => s.trim()).filter(Boolean);
136
+ if (value === null || value === undefined || value === '') return [];
137
+ return [value];
138
+ }
139
+
140
+ function toNumberArray(value) {
141
+ const out = [];
142
+ const seen = new Set();
143
+ for (const item of asArray(value)) {
144
+ const n = Number(item);
145
+ if (!Number.isFinite(n)) continue;
146
+ const r = Math.round(n);
147
+ if (seen.has(r)) continue;
148
+ seen.add(r);
149
+ out.push(r);
150
+ }
151
+ return out;
152
+ }
153
+
154
+ function toDateSet(value) {
155
+ const set = new Set();
156
+ for (const item of asArray(value)) {
157
+ let raw = item;
158
+ if (item && typeof item === 'object' && !(item instanceof Date)) {
159
+ raw = item.date || item.day || item.ymd || item.value || '';
160
+ }
161
+ const ymd = normalizeYmd(raw);
162
+ if (ymd) set.add(ymd);
163
+ }
164
+ return set;
165
+ }
166
+
167
+ function isoWeekday(date) {
168
+ const js = date.getDay();
169
+ return js === 0 ? 7 : js;
170
+ }
171
+
172
+ function isChristmasNewYearPeriod(date) {
173
+ const month = date.getMonth() + 1;
174
+ const day = date.getDate();
175
+ return (month === 12 && day >= 24) || (month === 1 && day <= 1);
176
+ }
177
+
178
+
67
179
  class PeakShavingModule extends BaseModule {
68
180
  constructor(adapter, dpRegistry) {
69
181
  super(adapter, dpRegistry);
@@ -83,7 +195,7 @@ class PeakShavingModule extends BaseModule {
83
195
  }
84
196
 
85
197
  _isEnabled() {
86
- return !!this.adapter.config.enablePeakShaving;
198
+ return isPeakShavingRuntimeEnabled(this.adapter && this.adapter.config);
87
199
  }
88
200
 
89
201
  async init() {
@@ -96,7 +208,7 @@ class PeakShavingModule extends BaseModule {
96
208
  native: {},
97
209
  });
98
210
 
99
- for (const ch of ['measure', 'calc', 'control', 'dynamic', 'actuators']) {
211
+ for (const ch of ['measure', 'calc', 'control', 'dynamic', 'actuators', 'atypical']) {
100
212
  await this.adapter.setObjectNotExistsAsync(`peakShaving.${ch}`, {
101
213
  type: 'channel',
102
214
  common: { name: ch },
@@ -137,6 +249,224 @@ class PeakShavingModule extends BaseModule {
137
249
 
138
250
  await mk('peakShaving.calc.avgPowerW', 'Average power (W)', 'number', 'value.power');
139
251
  await mk('peakShaving.calc.samples', 'Samples', 'number', 'value');
252
+
253
+ await mk('peakShaving.atypical.enabled', 'Atypische Spitzenkappung aktiviert', 'boolean', 'indicator');
254
+ await mk('peakShaving.atypical.enforce', 'Atypische Spitzenkappung erzwingen', 'boolean', 'indicator');
255
+ await mk('peakShaving.atypical.activeWindow', 'Aktives Hochlastzeitfenster', 'boolean', 'indicator');
256
+ await mk('peakShaving.atypical.status', 'Atypische Spitzenkappung Status', 'string', 'text');
257
+ await mk('peakShaving.atypical.windowLabel', 'Aktuelles Hochlastzeitfenster', 'string', 'text');
258
+ await mk('peakShaving.atypical.voltageLevel', 'Entnahmeebene', 'string', 'text');
259
+ await mk('peakShaving.atypical.thresholdPercent', 'Erheblichkeitsschwelle (%)', 'number', 'value');
260
+ await mk('peakShaving.atypical.minShiftW', 'Mindestverlagerung (W)', 'number', 'value.power');
261
+ await mk('peakShaving.atypical.pAbsRefW', 'Referenz-Jahreshöchstlast P_abs_ref (W)', 'number', 'value.power');
262
+ await mk('peakShaving.atypical.targetLimitW', 'HLZF-Ziellast (W)', 'number', 'value.power');
263
+ await mk('peakShaving.atypical.effectiveLimitW', 'Wirksames HLZF-Limit nach Hybrid-Minimum (W)', 'number', 'value.power');
264
+ await mk('peakShaving.atypical.deltaW', 'Verlagerung gegenüber P_abs_ref (W)', 'number', 'value.power');
265
+ await mk('peakShaving.atypical.deltaPercent', 'Verlagerung gegenüber P_abs_ref (%)', 'number', 'value');
266
+ await mk('peakShaving.atypical.eligiblePotential', '§19-Potenzial erfüllt Zielparameter', 'boolean', 'indicator');
267
+ await mk('peakShaving.atypical.binding', 'Bindendes Limit / Quelle', 'string', 'text');
268
+ await mk('peakShaving.atypical.snapshotJson', 'Atypische Spitzenkappung Snapshot (JSON)', 'string', 'text');
269
+ }
270
+
271
+
272
+ _atypicalSeasonMonths(season) {
273
+ const s = String(season || '').trim().toLowerCase();
274
+ if (!s) return [];
275
+ if (['winter', 'win', 'w'].includes(s)) return [1, 2, 12];
276
+ if (['sommer', 'summer', 'sum', 's'].includes(s)) return [6, 7, 8];
277
+ if (['uebergang', 'übergang', 'transition', 'spring-autumn', 'fruehjahr-herbst', 'frühjahr-herbst'].includes(s)) return [3, 4, 5, 9, 10, 11];
278
+ return [];
279
+ }
280
+
281
+ _atypicalWindowLabel(win) {
282
+ if (win && typeof win === 'object') {
283
+ const explicit = String(win.label || win.name || win.id || '').trim();
284
+ if (explicit) return explicit;
285
+ const from = String(win.from || win.start || win.startTime || win.fromTime || '').trim();
286
+ const to = String(win.to || win.end || win.endTime || win.toTime || '').trim();
287
+ if (from || to) return `${from || '?'}-${to || '?'}`;
288
+ }
289
+ return '';
290
+ }
291
+
292
+ _atypicalWindowMatches(win, nowDate) {
293
+ if (!win || typeof win !== 'object') return false;
294
+ if (win.enabled === false || win.active === false) return false;
295
+
296
+ const ymd = localYmd(nowDate);
297
+ const validFrom = normalizeYmd(win.validFrom || win.validFromDate || win.fromDate || '');
298
+ const validTo = normalizeYmd(win.validTo || win.validToDate || win.toDate || '');
299
+ if (validFrom && ymd < validFrom) return false;
300
+ if (validTo && ymd > validTo) return false;
301
+
302
+ const month = nowDate.getMonth() + 1;
303
+ const months = toNumberArray(win.months || win.month || []);
304
+ if (months.length && !months.includes(month)) return false;
305
+ if (!months.length) {
306
+ const seasonMonths = this._atypicalSeasonMonths(win.season || win.jahreszeit || '');
307
+ if (seasonMonths.length && !seasonMonths.includes(month)) return false;
308
+ }
309
+
310
+ const weekdays = toNumberArray(win.weekdays || win.days || win.weekday || []);
311
+ if (weekdays.length) {
312
+ const iso = isoWeekday(nowDate); // 1=Mon ... 7=Sun
313
+ const js = nowDate.getDay(); // 0=Sun ... 6=Sat
314
+ if (!weekdays.includes(iso) && !weekdays.includes(js)) return false;
315
+ }
316
+
317
+ const fromMin = parseHmToMinutes(win.from || win.start || win.startTime || win.fromTime);
318
+ const toMin = parseHmToMinutes(win.to || win.end || win.endTime || win.toTime);
319
+ if (fromMin === null || toMin === null || fromMin === toMin) return false;
320
+
321
+ const nowMin = nowDate.getHours() * 60 + nowDate.getMinutes();
322
+ if (toMin > fromMin) return nowMin >= fromMin && nowMin < toMin;
323
+ // Overnight windows are not typical for HLZF, but supporting them keeps the parser robust.
324
+ return nowMin >= fromMin || nowMin < toMin;
325
+ }
326
+
327
+ _evaluateAtypicalSchedule(atypicalCfg, now) {
328
+ const cfg = (atypicalCfg && typeof atypicalCfg === 'object') ? atypicalCfg : {};
329
+ const enabled = !!cfg.enabled;
330
+ const date = new Date(now || Date.now());
331
+ const ymd = localYmd(date);
332
+ if (!enabled) return { enabled: false, active: false, reason: 'disabled', ymd, windowLabel: '' };
333
+
334
+ const includeWeekends = cfg.includeWeekends === true;
335
+ if (!includeWeekends && isoWeekday(date) >= 6) {
336
+ return { enabled: true, active: false, reason: 'weekend', ymd, windowLabel: '' };
337
+ }
338
+
339
+ const excludeChristmasNewYear = cfg.excludeChristmasNewYear !== false;
340
+ if (excludeChristmasNewYear && isChristmasNewYearPeriod(date)) {
341
+ return { enabled: true, active: false, reason: 'christmas-new-year-period', ymd, windowLabel: '' };
342
+ }
343
+
344
+ const holidaySet = toDateSet(cfg.holidays || cfg.holidayDates || []);
345
+ const bridgeDaySet = toDateSet(cfg.bridgeDays || cfg.bridgeDayDates || []);
346
+ const exceptionSet = toDateSet(cfg.calendarExceptions || cfg.exceptions || []);
347
+ if (holidaySet.has(ymd)) return { enabled: true, active: false, reason: 'holiday', ymd, windowLabel: '' };
348
+ if (bridgeDaySet.has(ymd)) return { enabled: true, active: false, reason: 'bridge-day', ymd, windowLabel: '' };
349
+ if (exceptionSet.has(ymd)) return { enabled: true, active: false, reason: 'calendar-exception', ymd, windowLabel: '' };
350
+
351
+ const windows = Array.isArray(cfg.highLoadWindows)
352
+ ? cfg.highLoadWindows
353
+ : (Array.isArray(cfg.windows) ? cfg.windows : []);
354
+ if (!windows.length) return { enabled: true, active: false, reason: 'no-high-load-windows', ymd, windowLabel: '' };
355
+
356
+ for (const win of windows) {
357
+ if (this._atypicalWindowMatches(win, date)) {
358
+ return {
359
+ enabled: true,
360
+ active: true,
361
+ reason: 'active-high-load-window',
362
+ ymd,
363
+ windowLabel: this._atypicalWindowLabel(win),
364
+ window: win,
365
+ };
366
+ }
367
+ }
368
+
369
+ return { enabled: true, active: false, reason: 'outside-high-load-window', ymd, windowLabel: '' };
370
+ }
371
+
372
+ _calculateAtypicalTarget(atypicalCfg) {
373
+ const cfg = (atypicalCfg && typeof atypicalCfg === 'object') ? atypicalCfg : {};
374
+ const voltageLevel = String(
375
+ cfg.voltageLevel ||
376
+ this.adapter?.config?.installerConfig?.voltageLevel ||
377
+ this.adapter?.config?.settingsConfig?.voltageLevel ||
378
+ 'MS'
379
+ );
380
+ const fallbackThreshold = atypicalThresholdPercent(voltageLevel, 20);
381
+ let thresholdPercent = clamp(num(cfg.thresholdPercent, fallbackThreshold), 0, 100);
382
+ if (typeof thresholdPercent !== 'number') thresholdPercent = fallbackThreshold;
383
+
384
+ let minShiftW = clamp(num(cfg.minShiftW, 100000), 0, 1e12);
385
+ if (typeof minShiftW !== 'number') minShiftW = 100000;
386
+
387
+ const pAbsRefW = Math.max(0, num(
388
+ cfg.annualPeakReferenceW ?? cfg.pAbsRefW ?? cfg.pAbsMaxW ?? cfg.referencePeakW ?? cfg.referencePeakPowerW,
389
+ 0
390
+ ) || 0);
391
+ const explicitTargetW = num(cfg.targetLimitW ?? cfg.hlzfTargetW ?? cfg.highLoadLimitW ?? cfg.capW, null);
392
+ const marginW = Math.max(0, num(cfg.safetyMarginW, 0) || 0);
393
+
394
+ let rawTargetW = 0;
395
+ let targetSource = '';
396
+ if (typeof explicitTargetW === 'number' && explicitTargetW > 0) {
397
+ rawTargetW = explicitTargetW;
398
+ targetSource = 'explicit';
399
+ } else if (pAbsRefW > 0) {
400
+ const byPercentW = pAbsRefW * Math.max(0, 1 - (thresholdPercent / 100));
401
+ const byShiftW = Math.max(0, pAbsRefW - minShiftW);
402
+ rawTargetW = Math.min(byPercentW, byShiftW);
403
+ targetSource = 'derived-from-annual-peak';
404
+ }
405
+
406
+ const targetLimitW = rawTargetW > 0 ? Math.max(0, rawTargetW - marginW) : 0;
407
+ const deltaW = (pAbsRefW > 0 && rawTargetW > 0) ? Math.max(0, pAbsRefW - rawTargetW) : 0;
408
+ const deltaPercent = pAbsRefW > 0 ? (deltaW / pAbsRefW * 100) : 0;
409
+ const thresholdOk = pAbsRefW > 0 && deltaPercent + 1e-9 >= thresholdPercent;
410
+ const minShiftOk = pAbsRefW > 0 && deltaW + 1e-9 >= minShiftW;
411
+ const eligiblePotential = rawTargetW > 0 && thresholdOk && minShiftOk;
412
+
413
+ let reason = 'ok';
414
+ if (!(rawTargetW > 0)) reason = 'missing-target-or-reference-peak';
415
+ else if (targetSource === 'explicit' && !(pAbsRefW > 0)) reason = 'explicit-target-without-reference-peak';
416
+ else if (!eligiblePotential && pAbsRefW > 0) reason = 'threshold-or-min-shift-not-met';
417
+
418
+ return {
419
+ voltageLevel,
420
+ thresholdPercent,
421
+ minShiftW,
422
+ pAbsRefW,
423
+ rawTargetW,
424
+ marginW,
425
+ targetLimitW,
426
+ targetSource,
427
+ deltaW,
428
+ deltaPercent,
429
+ thresholdOk,
430
+ minShiftOk,
431
+ eligiblePotential,
432
+ reason,
433
+ };
434
+ }
435
+
436
+ async _publishAtypicalDiagnostics(ctx) {
437
+ const c = (ctx && typeof ctx === 'object') ? ctx : {};
438
+ const schedule = (c.schedule && typeof c.schedule === 'object') ? c.schedule : {};
439
+ const target = (c.target && typeof c.target === 'object') ? c.target : {};
440
+ const set = async (id, val) => {
441
+ try { await this.adapter.setStateAsync(id, val, true); } catch { /* diagnostics only */ }
442
+ };
443
+
444
+ await set('peakShaving.atypical.enabled', !!c.enabled);
445
+ await set('peakShaving.atypical.enforce', !!c.enforce);
446
+ await set('peakShaving.atypical.activeWindow', !!schedule.active);
447
+ await set('peakShaving.atypical.status', String(schedule.reason || target.reason || ''));
448
+ await set('peakShaving.atypical.windowLabel', String(schedule.windowLabel || ''));
449
+ await set('peakShaving.atypical.voltageLevel', String(target.voltageLevel || ''));
450
+ await set('peakShaving.atypical.thresholdPercent', Number.isFinite(Number(target.thresholdPercent)) ? Number(target.thresholdPercent) : 0);
451
+ await set('peakShaving.atypical.minShiftW', Number.isFinite(Number(target.minShiftW)) ? Math.round(Number(target.minShiftW)) : 0);
452
+ await set('peakShaving.atypical.pAbsRefW', Number.isFinite(Number(target.pAbsRefW)) ? Math.round(Number(target.pAbsRefW)) : 0);
453
+ await set('peakShaving.atypical.targetLimitW', Number.isFinite(Number(target.targetLimitW)) ? Math.round(Number(target.targetLimitW)) : 0);
454
+ await set('peakShaving.atypical.effectiveLimitW', Number.isFinite(Number(c.effectiveLimitW)) ? Math.round(Number(c.effectiveLimitW)) : 0);
455
+ await set('peakShaving.atypical.deltaW', Number.isFinite(Number(target.deltaW)) ? Math.round(Number(target.deltaW)) : 0);
456
+ await set('peakShaving.atypical.deltaPercent', Number.isFinite(Number(target.deltaPercent)) ? Math.round(Number(target.deltaPercent) * 100) / 100 : 0);
457
+ await set('peakShaving.atypical.eligiblePotential', !!target.eligiblePotential);
458
+ await set('peakShaving.atypical.binding', String(c.binding || ''));
459
+ await set('peakShaving.atypical.snapshotJson', JSON.stringify({
460
+ ts: Date.now(),
461
+ mode: String(c.mode || ''),
462
+ enabled: !!c.enabled,
463
+ enforce: !!c.enforce,
464
+ schedule,
465
+ target,
466
+ limitCandidateW: Number.isFinite(Number(c.limitCandidateW)) ? Math.round(Number(c.limitCandidateW)) : 0,
467
+ effectiveLimitW: Number.isFinite(Number(c.effectiveLimitW)) ? Math.round(Number(c.effectiveLimitW)) : 0,
468
+ binding: String(c.binding || ''),
469
+ }));
140
470
  }
141
471
 
142
472
  async tick() {
@@ -169,6 +499,28 @@ class PeakShavingModule extends BaseModule {
169
499
  const hysteresisA = clamp(num(cfg.hysteresisA, 1), 0, 100);
170
500
  const voltageV = clamp(num(cfg.voltageV, 230), 50, 400);
171
501
 
502
+
503
+ // Atypische Netznutzung / HLZF-Spitzenkappung (§19 Abs. 2 S. 1 StromNEV)
504
+ // strategyMode steuert die UI-Auswahl:
505
+ // - standard: nur klassische Lastspitzenkappung
506
+ // - atypical: nur HLZF-Cap innerhalb aktiver Hochlastzeitfenster
507
+ // - hybrid: klassisch + HLZF, es bindet immer das strengere Limit
508
+ // - monitor: HLZF-Diagnose ohne Peak-Shaving-Setpoint aus diesem Modul
509
+ const atypicalCfg = (cfg.atypical && typeof cfg.atypical === 'object') ? cfg.atypical : {};
510
+ let strategyMode = String(cfg.strategyMode || cfg.strategy || '').trim().toLowerCase();
511
+ if (!['standard', 'atypical', 'hybrid', 'monitor'].includes(strategyMode)) {
512
+ const legacyMode = String(atypicalCfg.mode || '').trim().toLowerCase();
513
+ strategyMode = atypicalCfg.enabled ? (legacyMode === 'monitor' ? 'monitor' : 'hybrid') : 'standard';
514
+ }
515
+ const standardLimitEnabled = strategyMode === 'standard' || strategyMode === 'hybrid';
516
+ const atypicalRuntimeEnabled = !!atypicalCfg.enabled && (strategyMode === 'atypical' || strategyMode === 'hybrid' || strategyMode === 'monitor');
517
+ const atypicalMode = strategyMode === 'monitor' ? 'monitor' : String(atypicalCfg.mode || (strategyMode === 'atypical' ? 'enforce' : 'hybrid')).trim().toLowerCase(); // monitor|enforce|hybrid
518
+ const atypicalEnforce = atypicalRuntimeEnabled && atypicalMode !== 'monitor' && atypicalCfg.enforce !== false;
519
+ const atypicalSchedule = this._evaluateAtypicalSchedule({ ...atypicalCfg, enabled: atypicalRuntimeEnabled }, now);
520
+ const atypicalTarget = this._calculateAtypicalTarget(atypicalCfg);
521
+ const atypicalLimitCandidateW = (atypicalSchedule.active && atypicalEnforce && atypicalTarget.targetLimitW > 0) ? atypicalTarget.targetLimitW : 0;
522
+ const atypicalWantsPowerLimit = atypicalLimitCandidateW > 0;
523
+
172
524
  // Bind datapoints from config (manufacturer-independent)
173
525
  if (cfg.gridPointPowerId) {
174
526
  // IMPORTANT: enable alive-prefix heartbeat. Many meters/adapters are event-driven
@@ -201,7 +553,7 @@ class PeakShavingModule extends BaseModule {
201
553
  let staleTimeoutSec = num(cfg.staleTimeoutSec, 300);
202
554
  staleTimeoutSec = clamp(staleTimeoutSec, 1, 3600);
203
555
  const staleMaxAgeMs = staleTimeoutSec * 1000;
204
- const wantsPowerLimit = typeof plantLimitW === 'number' && plantLimitW > 0;
556
+ const wantsPowerLimit = (standardLimitEnabled && typeof plantLimitW === 'number' && plantLimitW > 0) || atypicalWantsPowerLimit;
205
557
  const wantsPhaseLimit = (phaseMode === 'info' || phaseMode === 'enforce') && typeof maxPhaseA === 'number' && maxPhaseA > 0;
206
558
  let staleMeter = false;
207
559
  const staleKeys = [];
@@ -266,18 +618,37 @@ class PeakShavingModule extends BaseModule {
266
618
  let limitW = 0;
267
619
  let allowedPowerW = null;
268
620
  let reserveW = num(cfg.reserveW, 0);
621
+ let limitSource = '';
269
622
 
270
- if (mode === 'dynamic') {
623
+ if (standardLimitEnabled && mode === 'dynamic') {
271
624
  allowedPowerW = this.dp.getNumber('ps.allowedPowerW', null);
272
625
  // Central plant limit is a hard cap (if configured). If not configured, allow dynamic DP only.
273
626
  const baseMax = (typeof plantLimitW === 'number' && plantLimitW > 0) ? plantLimitW : Number.POSITIVE_INFINITY;
274
627
  const allowed = (typeof allowedPowerW === 'number' && allowedPowerW > 0) ? allowedPowerW : Number.POSITIVE_INFINITY;
275
628
  limitW = Math.min(baseMax, allowed) - Math.max(0, reserveW);
276
629
  if (!Number.isFinite(limitW)) limitW = 0;
277
- } else {
630
+ if (limitW > 0) limitSource = (Number.isFinite(baseMax) && Number.isFinite(allowed)) ? 'standard+dynamic' : (Number.isFinite(allowed) ? 'dynamic' : 'standard');
631
+ } else if (standardLimitEnabled) {
278
632
  // static: fester Grenzwert, aber Reserve ebenfalls abziehen (Reserve ist keine dynamic-only Funktion)
279
633
  const base = (typeof plantLimitW === 'number' && plantLimitW > 0) ? plantLimitW : 0;
280
634
  limitW = Math.max(0, base - Math.max(0, reserveW));
635
+ if (limitW > 0) limitSource = 'standard';
636
+ } else {
637
+ // Atypisch-only/Monitor: kein permanenter Standard-Cap außerhalb der HLZF.
638
+ limitW = 0;
639
+ limitSource = '';
640
+ }
641
+
642
+ if (atypicalWantsPowerLimit) {
643
+ if (limitW > 0) {
644
+ if (atypicalLimitCandidateW <= limitW + 0.001) {
645
+ limitSource = limitSource ? `atypical+${limitSource}` : 'atypical';
646
+ }
647
+ limitW = Math.min(limitW, atypicalLimitCandidateW);
648
+ } else {
649
+ limitW = atypicalLimitCandidateW;
650
+ limitSource = 'atypical';
651
+ }
281
652
  }
282
653
 
283
654
  // GridConstraints (RLM): zusätzliche dynamische Obergrenze für den Netzbezug
@@ -287,7 +658,13 @@ class PeakShavingModule extends BaseModule {
287
658
  const st = await this.adapter.getStateAsync('gridConstraints.rlm.capNowW');
288
659
  const cap = (st && typeof st.val === 'number') ? st.val : Number(st && st.val);
289
660
  if (Number.isFinite(cap) && cap > 0) {
661
+ const beforeLimitW = limitW;
290
662
  limitW = (limitW > 0) ? Math.min(limitW, cap) : cap;
663
+ if (limitW > 0 && (!(beforeLimitW > 0) || cap <= beforeLimitW + 0.001)) {
664
+ limitSource = limitSource
665
+ ? `gridConstraints+${limitSource}`
666
+ : 'gridConstraints';
667
+ }
291
668
  }
292
669
  } catch {
293
670
  // ignore
@@ -300,6 +677,17 @@ class PeakShavingModule extends BaseModule {
300
677
  limitW = Math.max(0, limitW - Math.max(0, safetyMarginW));
301
678
  }
302
679
 
680
+ await this._publishAtypicalDiagnostics({
681
+ enabled: !!atypicalRuntimeEnabled,
682
+ mode: atypicalMode,
683
+ enforce: atypicalEnforce,
684
+ schedule: atypicalSchedule,
685
+ target: atypicalTarget,
686
+ limitCandidateW: atypicalLimitCandidateW,
687
+ effectiveLimitW: atypicalWantsPowerLimit ? limitW : 0,
688
+ binding: atypicalWantsPowerLimit ? (limitSource || 'atypical') : '',
689
+ });
690
+
303
691
  // Phase analysis
304
692
  const l1 = useAverage ? this._winL1.mean() : l1Raw;
305
693
  const l2 = useAverage ? this._winL2.mean() : l2Raw;
@@ -488,7 +876,7 @@ class PeakShavingModule extends BaseModule {
488
876
  const lvl = (diagCfg.logLevel === 'info' || diagCfg.logLevel === 'debug') ? diagCfg.logLevel : 'debug';
489
877
  const fn = (this.adapter && this.adapter.log && typeof this.adapter.log[lvl] === 'function') ? this.adapter.log[lvl] : this.adapter.log.debug;
490
878
  try {
491
- fn.call(this.adapter.log, `[Lastspitzenkappung] Modus=${mode} aktiv=${active} status=${status} Grund=${reason} (${reasonToGerman(reason)}) MesswertAlt=${staleMeter ? 1 : 0} FastTrip=${fastTripViolation ? 1 : 0} Safety=${Math.round(Number(safetyMarginW || 0))}W Limit=${Math.round(Number(limitW || 0))}W Roh=${Math.round(Number(gridPowerRaw || 0))}W MW=${Math.round(Number(avgPower || 0))}W Trip=${Math.round(Number(tripPower || 0))}W Eff=${Math.round(Number(effPower || 0))}W Über=${Math.round(Number(overW || 0))}W VerfCtl=${Math.round(Number(availableForControlledW || 0))}W BedarfRed=${Math.round(Number(requiredReductionW || 0))}W`);
879
+ fn.call(this.adapter.log, `[Lastspitzenkappung] Modus=${mode} aktiv=${active} status=${status} Grund=${reason} (${reasonToGerman(reason)}) MesswertAlt=${staleMeter ? 1 : 0} FastTrip=${fastTripViolation ? 1 : 0} Safety=${Math.round(Number(safetyMarginW || 0))}W Limit=${Math.round(Number(limitW || 0))}W Quelle=${limitSource || 'none'} Atypisch=${atypicalSchedule.active ? 1 : 0} AtypischLimit=${Math.round(Number(atypicalLimitCandidateW || 0))}W Roh=${Math.round(Number(gridPowerRaw || 0))}W MW=${Math.round(Number(avgPower || 0))}W Trip=${Math.round(Number(tripPower || 0))}W Eff=${Math.round(Number(effPower || 0))}W Über=${Math.round(Number(overW || 0))}W VerfCtl=${Math.round(Number(availableForControlledW || 0))}W BedarfRed=${Math.round(Number(requiredReductionW || 0))}W`);
492
880
  } catch {
493
881
  // ignore
494
882
  }