iobroker.nexowatt-ui 0.7.25 → 0.7.26

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
@@ -660,6 +660,16 @@ class EmsEngine {
660
660
  adapter.config.storage.datapoints = adapter.config.storage.datapoints || {};
661
661
  const curBP = (typeof adapter.config.storage.datapoints.batteryPowerObjectId === 'string') ? adapter.config.storage.datapoints.batteryPowerObjectId.trim() : '';
662
662
  if (!curBP) adapter.config.storage.datapoints.batteryPowerObjectId = batPowerId;
663
+
664
+ // Keep the embedded EMS sign convention in sync with the Energiefluss signed battery mapping.
665
+ // Convention after normalization: -W = charge, +W = discharge.
666
+ // If the user enabled the Batterie-Vorzeichen inversion in the flow settings and the
667
+ // storage module is using this VIS datapoint, apply the same inversion to st.batteryPowerW.
668
+ const usesVisBatteryPower = !curBP || curBP === batPowerId;
669
+ const invBat = !!(adapter.config && adapter.config.settings && adapter.config.settings.flowInvertBattery);
670
+ if (usesVisBatteryPower && adapter.config.storage.datapoints.batteryPowerInvert === undefined) {
671
+ adapter.config.storage.datapoints.batteryPowerInvert = invBat;
672
+ }
663
673
  }
664
674
  } catch (_e) {
665
675
  // ignore
@@ -564,7 +564,13 @@ class CoreLimitsModule extends BaseModule {
564
564
  let storageDischargeW = Math.max(0, this._readCacheNumberMax(['storageFarm.totalDischargePowerW', 'storageDischargePower'], 0) || 0);
565
565
  const batteryPowerW = this._readCacheNumber(['batteryPower'], null);
566
566
  if (isFiniteNumber(batteryPowerW)) {
567
- const signed = Math.round(batteryPowerW);
567
+ const flowBatteryMapped = !!(cfg.datapoints && String(cfg.datapoints.batteryPower || '').trim());
568
+ const farmActive = !!this._readCacheNumber(['storageFarm.enabled'], 0);
569
+ // Apply the VIS inversion only to a raw mapped batteryPower datapoint.
570
+ // If batteryPower was mirrored from the already-normalized storage pair/farm,
571
+ // flipping it here again would swap charge/discharge twice.
572
+ const invBattery = flowBatteryMapped && !farmActive && !!(cfg.settings && cfg.settings.flowInvertBattery);
573
+ const signed = Math.round(invBattery ? -batteryPowerW : batteryPowerW);
568
574
  if (signed < -25) {
569
575
  storageChargeW = Math.max(storageChargeW, Math.abs(signed));
570
576
  storageDischargeW = 0;
@@ -619,7 +619,13 @@ class HeatingRodControlModule extends BaseModule {
619
619
 
620
620
  const batteryPowerW = this._readNumberAny(['batteryPower'], staleMs, null);
621
621
  if (typeof batteryPowerW === 'number' && Number.isFinite(batteryPowerW)) {
622
- const signedW = Math.round(batteryPowerW);
622
+ const cfg = (this.adapter && this.adapter.config) ? this.adapter.config : {};
623
+ const flowBatteryMapped = !!(cfg.datapoints && String(cfg.datapoints.batteryPower || '').trim());
624
+ const farmActive = !!this._readCacheNumber('storageFarm.enabled', 0);
625
+ // Apply the VIS inversion only to a raw mapped batteryPower datapoint.
626
+ // Mirrored batteryPower values are already normalized by the main flow engine.
627
+ const invBattery = flowBatteryMapped && !farmActive && !!(cfg.settings && cfg.settings.flowInvertBattery);
628
+ const signedW = Math.round(invBattery ? -batteryPowerW : batteryPowerW);
623
629
  const noiseW = 25;
624
630
  // batteryPower is the canonical direction signal in this adapter:
625
631
  // +W = discharge, -W = charge. Prefer that direction over separate
package/io-package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "nexowatt-ui",
4
- "version": "0.7.25",
4
+ "version": "0.7.26",
5
5
  "news": {
6
+ "0.7.26": {
7
+ "en": "Battery power sign handling fixed: signed storage power is normalized like grid power, battery sign inversion is applied before charge/discharge splitting, stale battery values are guarded, and VIS/status/EMS modules now use one consistent charge/discharge direction.",
8
+ "de": "Batterie-Leistung mit Vorzeichen korrigiert: signed Speicherleistung wird wie der NVP normalisiert, die Batterie-Vorzeichen-Invertierung greift vor der Aufteilung in Laden/Entladen, veraltete Batterie-Werte werden abgesichert und VIS/Status/EMS-Module verwenden jetzt eine einheitliche Lade-/Entlade-Richtung."
9
+ },
6
10
  "0.7.25": {
7
11
  "en": "License page speed fix: UUID is now read from the adapter runtime endpoint first without waiting for ioBroker Admin socket fallbacks. Admin fallbacks are skipped when runtime already delivered UUID and status, reducing long waits before the UUID appears.",
8
12
  "de": "Lizenzseiten-Speed-Fix: Die UUID wird jetzt zuerst direkt über den Adapter-Runtime-Endpunkt gelesen, ohne vorher auf ioBroker-Admin-Socket-Fallbacks zu warten. Admin-Fallbacks werden übersprungen, wenn Runtime bereits UUID und Status geliefert hat. Dadurch erscheint die UUID deutlich schneller."
@@ -1915,8 +1919,12 @@
1915
1919
  }
1916
1920
  },
1917
1921
  "instanceObjects": [],
1918
- "version": "0.7.25",
1922
+ "version": "0.7.26",
1919
1923
  "news": {
1924
+ "0.7.26": {
1925
+ "en": "Battery power sign handling fixed: signed storage power is normalized like grid power, battery sign inversion is applied before charge/discharge splitting, stale battery values are guarded, and VIS/status/EMS modules now use one consistent charge/discharge direction.",
1926
+ "de": "Batterie-Leistung mit Vorzeichen korrigiert: signed Speicherleistung wird wie der NVP normalisiert, die Batterie-Vorzeichen-Invertierung greift vor der Aufteilung in Laden/Entladen, veraltete Batterie-Werte werden abgesichert und VIS/Status/EMS-Module verwenden jetzt eine einheitliche Lade-/Entlade-Richtung."
1927
+ },
1920
1928
  "0.7.25": {
1921
1929
  "en": "License page speed fix: UUID is now read from the adapter runtime endpoint first without waiting for ioBroker Admin socket fallbacks. Admin fallbacks are skipped when runtime already delivered UUID and status, reducing long waits before the UUID appears.",
1922
1930
  "de": "Lizenzseiten-Speed-Fix: Die UUID wird jetzt zuerst direkt über den Adapter-Runtime-Endpunkt gelesen, ohne vorher auf ioBroker-Admin-Socket-Fallbacks zu warten. Admin-Fallbacks werden übersprungen, wenn Runtime bereits UUID und Status geliefert hat. Dadurch erscheint die UUID deutlich schneller."
package/main.js CHANGED
@@ -59,6 +59,9 @@ class NexoWattVis extends utils.Adapter {
59
59
  });
60
60
 
61
61
  this.stateCache = {};
62
+ // Public values may be normalized for UI/module safety (e.g. charge/discharge magnitudes).
63
+ // Keep the original signed input values as well so signed battery fallbacks can be split correctly.
64
+ this._nwRawValueCache = {};
62
65
  this.sseClients = new Set();
63
66
  // Batch SSE updates to prevent UI freezes on frequent state updates
64
67
  this._ssePendingPayload = {};
@@ -4152,10 +4155,10 @@ try {
4152
4155
  // SoC: Für die aktive Farm-Anzeige bevorzugen wir den frischen Online-SoC.
4153
4156
  // Der stabile Gesamt-SoC bleibt weiterhin unter storageFarm.totalSoc verfügbar.
4154
4157
  const activeSoc = socSourcesOnline > 0 ? totalSocOnline : totalSoc;
4155
- this.updateValue('storageSoc', Math.round(activeSoc * 10) / 10, now);
4156
- this.updateValue('storageChargePower', Math.round(totalCharge), now);
4157
- this.updateValue('storageDischargePower', Math.round(totalDischarge), now);
4158
- this.updateValue('batteryPower', Math.round(totalDischarge - totalCharge), now);
4158
+ this.updateValue('storageSoc', Math.round(activeSoc * 10) / 10, now, { raw: false });
4159
+ this.updateValue('storageChargePower', Math.round(totalCharge), now, { raw: false });
4160
+ this.updateValue('storageDischargePower', Math.round(totalDischarge), now, { raw: false });
4161
+ this.updateValue('batteryPower', Math.round(totalDischarge - totalCharge), now, { raw: false });
4159
4162
 
4160
4163
  // PV (DC) Farm‑Summe nur als Fallback, wenn kein PV‑DP gemappt ist
4161
4164
  if (typeof this._nwHasMappedDatapoint === 'function') {
@@ -16858,6 +16861,213 @@ Technische Details: system.adapter.${c.inst}.alive=false`,
16858
16861
  }
16859
16862
  }
16860
16863
 
16864
+ _nwGetCacheAgeMs(key, now = Date.now()) {
16865
+ try {
16866
+ const rec = this.stateCache && this.stateCache[key];
16867
+ if (!rec) return null;
16868
+ const ts = Number(rec.ts);
16869
+ if (!Number.isFinite(ts) || ts <= 0) return null;
16870
+ return Math.max(0, Number(now) - ts);
16871
+ } catch (_e) {
16872
+ return null;
16873
+ }
16874
+ }
16875
+
16876
+ _nwGetNumberFromCacheFresh(key, maxAgeMs = null, fallback = null, now = Date.now()) {
16877
+ try {
16878
+ const rec = this.stateCache && this.stateCache[key];
16879
+ if (!rec) return fallback;
16880
+ const n = Number(rec.value);
16881
+ if (!Number.isFinite(n)) return fallback;
16882
+ const maxAge = Number(maxAgeMs);
16883
+ if (Number.isFinite(maxAge) && maxAge > 0) {
16884
+ const age = this._nwGetCacheAgeMs(key, now);
16885
+ if (age !== null && age > maxAge) return fallback;
16886
+ }
16887
+ return n;
16888
+ } catch (_e) {
16889
+ return fallback;
16890
+ }
16891
+ }
16892
+
16893
+ _nwGetRawNumberFromCache(key, maxAgeMs = null, fallback = null, now = Date.now()) {
16894
+ try {
16895
+ const rec = (this._nwRawValueCache && this._nwRawValueCache[key]) || (this.stateCache && this.stateCache[key]);
16896
+ if (!rec) return fallback;
16897
+ const n = Number(rec.value);
16898
+ if (!Number.isFinite(n)) return fallback;
16899
+ const maxAge = Number(maxAgeMs);
16900
+ if (Number.isFinite(maxAge) && maxAge > 0) {
16901
+ const ts = Number(rec.ts);
16902
+ if (Number.isFinite(ts) && ts > 0 && Math.max(0, Number(now) - ts) > maxAge) return fallback;
16903
+ }
16904
+ return n;
16905
+ } catch (_e) {
16906
+ return fallback;
16907
+ }
16908
+ }
16909
+
16910
+ _nwLiveInputMaxAgeMs() {
16911
+ try {
16912
+ const fromState = Number(this.stateCache && this.stateCache['settings.deviceStaleTimeoutSec'] ? this.stateCache['settings.deviceStaleTimeoutSec'].value : NaN);
16913
+ const fromCfg = Number(this.config && this.config.settings ? this.config.settings.deviceStaleTimeoutSec : NaN);
16914
+ const sec = Number.isFinite(fromState) && fromState > 0 ? fromState : (Number.isFinite(fromCfg) && fromCfg > 0 ? fromCfg : 300);
16915
+ return Math.max(10_000, Math.round(sec * 1000));
16916
+ } catch (_e) {
16917
+ return 300_000;
16918
+ }
16919
+ }
16920
+
16921
+ _nwIsBatterySignInverted() {
16922
+ try {
16923
+ if (typeof this._notifyGetSettingBool === 'function') {
16924
+ return this._notifyGetSettingBool('flowInvertBattery', !!(this.config && this.config.settings && this.config.settings.flowInvertBattery));
16925
+ }
16926
+ } catch (_e) {}
16927
+ try {
16928
+ return !!(this.config && this.config.settings && this.config.settings.flowInvertBattery);
16929
+ } catch (_e2) {
16930
+ return false;
16931
+ }
16932
+ }
16933
+
16934
+ _nwResolveBatteryFlowFromCache(opts = {}) {
16935
+ const now = Number.isFinite(Number(opts.now)) ? Number(opts.now) : Date.now();
16936
+ const maxAgeMs = opts.maxAgeMs === undefined ? this._nwLiveInputMaxAgeMs() : opts.maxAgeMs;
16937
+ const deadbandW = Number.isFinite(Number(opts.deadbandW)) ? Math.max(0, Number(opts.deadbandW)) : 25;
16938
+
16939
+ const dps = (this.config && this.config.datapoints && typeof this.config.datapoints === 'object') ? this.config.datapoints : {};
16940
+ const idOf = (key) => String(dps[key] || '').trim();
16941
+ const chargeMapped = !!idOf('storageChargePower');
16942
+ const dischargeMapped = !!idOf('storageDischargePower');
16943
+ const batteryMapped = !!idOf('batteryPower');
16944
+ const sameChargeDischargeId = !!(chargeMapped && dischargeMapped && idOf('storageChargePower') === idOf('storageDischargePower'));
16945
+ const inv = this._nwIsBatterySignInverted();
16946
+
16947
+ const fresh = (key, onlyIfMapped) => {
16948
+ if (onlyIfMapped && !idOf(key)) return null;
16949
+ return this._nwGetNumberFromCacheFresh(key, maxAgeMs, null, now);
16950
+ };
16951
+ const rawFresh = (key, onlyIfMapped) => {
16952
+ if (onlyIfMapped && !idOf(key)) return null;
16953
+ return this._nwGetRawNumberFromCache(key, maxAgeMs, null, now);
16954
+ };
16955
+
16956
+ const fromSigned = (signedRaw, src, opts2 = {}) => {
16957
+ let signed = Number(signedRaw);
16958
+ if (!Number.isFinite(signed)) signed = 0;
16959
+ if (inv) signed = -signed;
16960
+ if (Math.abs(signed) <= deadbandW) signed = 0;
16961
+ const chargeW = signed < 0 ? Math.abs(signed) : 0;
16962
+ const dischargeW = signed > 0 ? signed : 0;
16963
+ return {
16964
+ chargeW: Math.round(chargeW),
16965
+ dischargeW: Math.round(dischargeW),
16966
+ signedW: Math.round(signed),
16967
+ src,
16968
+ inverted: inv,
16969
+ fromSigned: true,
16970
+ mirror: opts2.mirror !== false,
16971
+ staleMs: {
16972
+ batteryPower: this._nwGetCacheAgeMs('batteryPower', now),
16973
+ storageChargePower: this._nwGetCacheAgeMs('storageChargePower', now),
16974
+ storageDischargePower: this._nwGetCacheAgeMs('storageDischargePower', now),
16975
+ },
16976
+ };
16977
+ };
16978
+
16979
+ // Speicherfarm already provides normalized charge/discharge totals. Keep it authoritative
16980
+ // unless a signed single battery datapoint is explicitly mapped for a non-farm setup.
16981
+ const sfEnabled = !!(this.stateCache && this.stateCache['storageFarm.enabled'] && this.stateCache['storageFarm.enabled'].value);
16982
+ if (sfEnabled) {
16983
+ const farmCharge = fresh('storageFarm.totalChargePowerW', false);
16984
+ const farmDischarge = fresh('storageFarm.totalDischargePowerW', false);
16985
+ if (farmCharge !== null || farmDischarge !== null) {
16986
+ let c = Math.max(0, Math.abs(Number(farmCharge || 0)));
16987
+ let d = Math.max(0, Math.abs(Number(farmDischarge || 0)));
16988
+ if (inv) { const t = c; c = d; d = t; }
16989
+ return {
16990
+ chargeW: Math.round(c),
16991
+ dischargeW: Math.round(d),
16992
+ signedW: Math.round(d - c),
16993
+ src: inv ? 'storageFarm(inv)' : 'storageFarm',
16994
+ inverted: inv,
16995
+ fromSigned: false,
16996
+ mirror: true,
16997
+ staleMs: {
16998
+ farmCharge: this._nwGetCacheAgeMs('storageFarm.totalChargePowerW', now),
16999
+ farmDischarge: this._nwGetCacheAgeMs('storageFarm.totalDischargePowerW', now),
17000
+ },
17001
+ };
17002
+ }
17003
+ }
17004
+
17005
+ const batterySigned = batteryMapped ? rawFresh('batteryPower', true) : null;
17006
+ const chargeRaw = chargeMapped ? rawFresh('storageChargePower', true) : null;
17007
+ const dischargeRaw = dischargeMapped ? rawFresh('storageDischargePower', true) : null;
17008
+
17009
+ // If charge/discharge were both mapped to the same signed datapoint, keep the sign.
17010
+ // updateValue() normalizes their public state values to magnitudes, so the private raw cache is used here.
17011
+ if (sameChargeDischargeId && chargeRaw !== null) {
17012
+ return fromSigned(chargeRaw, 'sameChargeDischargeSigned', { mirror: true });
17013
+ }
17014
+
17015
+ // Canonical single signed DP fallback: exactly like NVP signed handling.
17016
+ // Use it when no separate channels are mapped, when separate channels are missing/stale,
17017
+ // or when stale/legacy mirrored values would otherwise show both directions at once.
17018
+ const separateAvailable = (chargeRaw !== null || dischargeRaw !== null);
17019
+ const publicCharge = chargeMapped ? fresh('storageChargePower', true) : null;
17020
+ const publicDischarge = dischargeMapped ? fresh('storageDischargePower', true) : null;
17021
+ const bothPublicDirections = (Number(publicCharge || 0) > deadbandW && Number(publicDischarge || 0) > deadbandW);
17022
+ const bothEqualish = bothPublicDirections && Math.abs(Math.abs(Number(publicCharge || 0)) - Math.abs(Number(publicDischarge || 0))) <= Math.max(2, deadbandW);
17023
+
17024
+ if (batterySigned !== null && (!separateAvailable || bothEqualish || (!chargeMapped && !dischargeMapped))) {
17025
+ return fromSigned(batterySigned, bothEqualish ? 'batterySignedOverrideDual' : 'batterySigned', { mirror: true });
17026
+ }
17027
+
17028
+ if (separateAvailable) {
17029
+ let c = chargeRaw !== null ? Math.abs(Number(chargeRaw)) : 0;
17030
+ let d = dischargeRaw !== null ? Math.abs(Number(dischargeRaw)) : 0;
17031
+ if (!Number.isFinite(c)) c = 0;
17032
+ if (!Number.isFinite(d)) d = 0;
17033
+ if (c <= deadbandW) c = 0;
17034
+ if (d <= deadbandW) d = 0;
17035
+ if (inv) { const t = c; c = d; d = t; }
17036
+ return {
17037
+ chargeW: Math.round(c),
17038
+ dischargeW: Math.round(d),
17039
+ signedW: Math.round(d - c),
17040
+ src: inv ? 'chargeDischarge(inv)' : 'chargeDischarge',
17041
+ inverted: inv,
17042
+ fromSigned: false,
17043
+ mirror: sameChargeDischargeId || !chargeMapped || !dischargeMapped,
17044
+ staleMs: {
17045
+ storageChargePower: this._nwGetCacheAgeMs('storageChargePower', now),
17046
+ storageDischargePower: this._nwGetCacheAgeMs('storageDischargePower', now),
17047
+ },
17048
+ };
17049
+ }
17050
+
17051
+ if (batterySigned !== null) {
17052
+ return fromSigned(batterySigned, 'batterySigned', { mirror: true });
17053
+ }
17054
+
17055
+ return {
17056
+ chargeW: 0,
17057
+ dischargeW: 0,
17058
+ signedW: 0,
17059
+ src: (batteryMapped || chargeMapped || dischargeMapped) ? 'stale-or-missing' : 'missing',
17060
+ inverted: inv,
17061
+ fromSigned: false,
17062
+ mirror: (!chargeMapped || !dischargeMapped),
17063
+ staleMs: {
17064
+ batteryPower: this._nwGetCacheAgeMs('batteryPower', now),
17065
+ storageChargePower: this._nwGetCacheAgeMs('storageChargePower', now),
17066
+ storageDischargePower: this._nwGetCacheAgeMs('storageDischargePower', now),
17067
+ },
17068
+ };
17069
+ }
17070
+
16861
17071
  _nwResolveGridImportExportFromCache() {
16862
17072
  const gridBuyMapped = this._nwHasMappedDatapoint('gridBuyPower');
16863
17073
  const gridSellMapped = this._nwHasMappedDatapoint('gridSellPower');
@@ -17040,8 +17250,9 @@ Technische Details: system.adapter.${c.inst}.alive=false`,
17040
17250
  } = this._nwResolveGridImportExportFromCache();
17041
17251
  const pvW = this._nwGetNumberFromCache('pvPower');
17042
17252
  const loadW = this._nwGetNumberFromCache('consumptionTotal');
17043
- let chgW = this._nwGetNumberFromCache('storageChargePower');
17044
- let dchgW = this._nwGetNumberFromCache('storageDischargePower');
17253
+ const storageFlowHist = this._nwResolveBatteryFlowFromCache({ now });
17254
+ let chgW = Number(storageFlowHist.chargeW);
17255
+ let dchgW = Number(storageFlowHist.dischargeW);
17045
17256
  let soc = this._nwGetNumberFromCache('storageSoc');
17046
17257
  const evW = this._nwGetNumberFromCache('evcs.totalPowerW');
17047
17258
 
@@ -17071,15 +17282,10 @@ Technische Details: system.adapter.${c.inst}.alive=false`,
17071
17282
  }
17072
17283
  }
17073
17284
 
17074
- // In StorageFarm mode, prefer the aggregated farm totals for charge/discharge/SoC.
17075
- // This avoids race conditions with legacy single-storage datapoint mappings that may
17076
- // still update the generic cache keys.
17285
+ // In StorageFarm mode the storageFlow resolver already prefers the aggregated farm
17286
+ // charge/discharge totals. Keep the farm SoC preference here for history/export.
17077
17287
  if (sfEnabled) {
17078
- const chgFarmW = this._nwGetNumberFromCache('storageFarm.totalChargePowerW');
17079
- const dchgFarmW = this._nwGetNumberFromCache('storageFarm.totalDischargePowerW');
17080
17288
  const socFarm = this._nwGetNumberFromCache('storageFarm.totalSoc');
17081
- if (Number.isFinite(chgFarmW)) chgW = chgFarmW;
17082
- if (Number.isFinite(dchgFarmW)) dchgW = dchgFarmW;
17083
17289
  if (Number.isFinite(socFarm)) soc = socFarm;
17084
17290
  }
17085
17291
 
@@ -17951,40 +18157,15 @@ Technische Details: system.adapter.${c.inst}.alive=false`,
17951
18157
  } = this._nwResolveGridImportExportFromCache();
17952
18158
 
17953
18159
  // --- Storage ---
17954
- let chargeRaw = this._nwGetNumberFromCache('storageChargePower');
17955
- let dischargeRaw = this._nwGetNumberFromCache('storageDischargePower');
17956
- const batteryRaw = this._nwGetNumberFromCache('batteryPower');
17957
-
17958
- let storageSrc = 'chargeDischarge';
17959
- if (chargeRaw === null && dischargeRaw === null) {
17960
- if (batteryRaw !== null) {
17961
- const signed = Number(batteryRaw);
17962
- if (Number.isFinite(signed)) {
17963
- if (signed >= 0) {
17964
- dischargeRaw = signed;
17965
- chargeRaw = 0;
17966
- } else {
17967
- chargeRaw = -signed;
17968
- dischargeRaw = 0;
17969
- }
17970
- storageSrc = 'batterySigned';
17971
- } else {
17972
- chargeRaw = 0;
17973
- dischargeRaw = 0;
17974
- storageSrc = 'missing';
17975
- }
17976
- } else {
17977
- chargeRaw = 0;
17978
- dischargeRaw = 0;
17979
- storageSrc = 'missing';
17980
- }
17981
- } else {
17982
- if (chargeRaw === null) chargeRaw = 0;
17983
- if (dischargeRaw === null) dischargeRaw = 0;
17984
- }
17985
-
17986
- const chargeW = Math.max(0, Math.abs(chargeRaw ?? 0));
17987
- const dischargeW = Math.max(0, Math.abs(dischargeRaw ?? 0));
18160
+ // Normalize storage power centrally:
18161
+ // batteryPower (signed) convention: -W = charge, +W = discharge
18162
+ // settings.flowInvertBattery flips that signed value before splitting.
18163
+ // Separate charge/discharge datapoints remain supported, but stale/legacy mirrored
18164
+ // values must not make the UI or derived balance show both directions at once.
18165
+ const storageFlow = this._nwResolveBatteryFlowFromCache({ now: ts });
18166
+ const chargeW = Math.max(0, Number(storageFlow.chargeW) || 0);
18167
+ const dischargeW = Math.max(0, Number(storageFlow.dischargeW) || 0);
18168
+ const storageSrc = storageFlow.src || 'missing';
17988
18169
  const gridBuyRound = Math.round(gridBuyW);
17989
18170
  const gridSellRound = Math.round(gridSellW);
17990
18171
 
@@ -18300,6 +18481,30 @@ Technische Details: system.adapter.${c.inst}.alive=false`,
18300
18481
  this.updateValue('pvPower', pvTotalRound, ts);
18301
18482
  }
18302
18483
  }
18484
+
18485
+ // 4) If storage is resolved from a signed fallback (or farm/auto values), mirror the
18486
+ // normalized pair into the public keys. This is the battery equivalent of the NVP
18487
+ // import/export fallback and keeps tiles, history and downstream modules aligned.
18488
+ try {
18489
+ const dps = (this.config && this.config.datapoints) || {};
18490
+ const chargeMapped = !!String(dps.storageChargePower || '').trim();
18491
+ const dischargeMapped = !!String(dps.storageDischargePower || '').trim();
18492
+ const samePair = chargeMapped && dischargeMapped && String(dps.storageChargePower || '').trim() === String(dps.storageDischargePower || '').trim();
18493
+ const shouldMirrorStorage = !!(storageFlow && (storageFlow.mirror || samePair || !chargeMapped || !dischargeMapped));
18494
+ const chargeRound = Math.round(chargeW);
18495
+ const dischargeRound = Math.round(dischargeW);
18496
+ if (shouldMirrorStorage) {
18497
+ const curC = Number(this.stateCache?.storageChargePower?.value);
18498
+ const curD = Number(this.stateCache?.storageDischargePower?.value);
18499
+ if (!Number.isFinite(curC) || curC !== chargeRound) this.updateValue('storageChargePower', chargeRound, ts, { raw: false });
18500
+ if (!Number.isFinite(curD) || curD !== dischargeRound) this.updateValue('storageDischargePower', dischargeRound, ts, { raw: false });
18501
+ }
18502
+ if (!this._nwHasMappedDatapoint('batteryPower')) {
18503
+ const signedRound = Math.round(dischargeW - chargeW);
18504
+ const curB = Number(this.stateCache?.batteryPower?.value);
18505
+ if (!Number.isFinite(curB) || curB !== signedRound) this.updateValue('batteryPower', signedRound, ts, { raw: false });
18506
+ }
18507
+ } catch (_eStorageMirror) {}
18303
18508
  }
18304
18509
 
18305
18510
  _nwHasMappedDatapoint(key) {
@@ -18569,10 +18774,21 @@ Technische Details: system.adapter.${c.inst}.alive=false`,
18569
18774
 
18570
18775
 
18571
18776
 
18572
- updateValue(key, value, ts) {
18777
+ updateValue(key, value, ts, opts = {}) {
18778
+ const rawValue = value;
18779
+ try {
18780
+ const keepRaw = !(opts && opts.raw === false);
18781
+ if (keepRaw) {
18782
+ if (!this._nwRawValueCache || typeof this._nwRawValueCache !== 'object') this._nwRawValueCache = {};
18783
+ this._nwRawValueCache[key] = { value: rawValue, ts };
18784
+ }
18785
+ } catch (_e0) {}
18786
+
18573
18787
  // Some devices provide charging/discharging power as signed values
18574
18788
  // (e.g. charging power can be negative). In NexoWatt we treat
18575
- // charge/discharge as positive magnitudes for UI/Historie.
18789
+ // public charge/discharge states as positive magnitudes for UI/Historie.
18790
+ // The raw signed value remains available in _nwRawValueCache so a single
18791
+ // signed battery datapoint cannot accidentally fill charge AND discharge.
18576
18792
  if (
18577
18793
  typeof value === 'number' &&
18578
18794
  !isNaN(value) &&
@@ -18638,6 +18854,7 @@ Technische Details: system.adapter.${c.inst}.alive=false`,
18638
18854
  key === 'gridBuyPower' || key === 'gridSellPower' || key === 'gridPointPower' ||
18639
18855
  key === 'pvPower' || key === 'productionTotal' ||
18640
18856
  key === 'storageChargePower' || key === 'storageDischargePower' || key === 'batteryPower' ||
18857
+ key === 'settings.flowInvertBattery' || key === 'settings.deviceStaleTimeoutSec' ||
18641
18858
  /^producer\d+Power$/.test(key) || /^consumer\d+Power$/.test(key) ||
18642
18859
  /^evcs\.\d+\.powerW$/.test(key) || key === 'evcs.totalPowerW' ||
18643
18860
  key.startsWith('storageFarm.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.nexowatt-ui",
3
- "version": "0.7.25",
3
+ "version": "0.7.26",
4
4
  "description": "Responsive NexoWatt EMS visualization adapter.",
5
5
  "author": "NexoWatt",
6
6
  "license": "Proprietary License (NPL) v1.0",
package/www/app.js CHANGED
@@ -1684,8 +1684,9 @@ function computeDerived() {
1684
1684
  // derive some percentages if not provided
1685
1685
  const pv = pick('pvPower', 'productionTotal');
1686
1686
  const load = pick('consumptionTotal');
1687
- const charge = pick('storageChargePower');
1688
- const discharge = pick('storageDischargePower');
1687
+ const batteryFlow = getNormalizedBatteryFlow();
1688
+ const charge = Number(batteryFlow.chargeW) || 0;
1689
+ const discharge = Number(batteryFlow.dischargeW) || 0;
1689
1690
 
1690
1691
  const gridMeta = getGridImportExport((k) => get(k));
1691
1692
  const rawBuy = gridMeta.rawBuy;
@@ -1793,6 +1794,117 @@ function getGridImportExport(read) {
1793
1794
  };
1794
1795
  }
1795
1796
 
1797
+ function getStateAgeMs(key) {
1798
+ try {
1799
+ const rec = state && state[key];
1800
+ const ts = Number(rec && rec.ts);
1801
+ if (!Number.isFinite(ts) || ts <= 0) return null;
1802
+ return Math.max(0, Date.now() - ts);
1803
+ } catch (_e) {
1804
+ return null;
1805
+ }
1806
+ }
1807
+
1808
+ function getFlowFreshMaxAgeMs() {
1809
+ try {
1810
+ const stateVal = coerceNumber(state && state['settings.deviceStaleTimeoutSec'] && state['settings.deviceStaleTimeoutSec'].value);
1811
+ const cfgVal = coerceNumber(window.__nwCfg && window.__nwCfg.settings && window.__nwCfg.settings.deviceStaleTimeoutSec);
1812
+ const sec = stateVal != null && stateVal > 0 ? stateVal : (cfgVal != null && cfgVal > 0 ? cfgVal : 300);
1813
+ return Math.max(10000, Math.round(sec * 1000));
1814
+ } catch (_e) {
1815
+ return 300000;
1816
+ }
1817
+ }
1818
+
1819
+ function getFreshFlowNumber(key, opts = {}) {
1820
+ if (opts.onlyIfMapped && !isMappedDatapoint(key)) return null;
1821
+ const rec = state && state[key];
1822
+ if (!rec) return null;
1823
+ const n = coerceNumber(rec.value);
1824
+ if (n === null) return null;
1825
+ const maxAgeMs = opts.maxAgeMs === undefined ? getFlowFreshMaxAgeMs() : opts.maxAgeMs;
1826
+ const age = getStateAgeMs(key);
1827
+ if (Number.isFinite(Number(maxAgeMs)) && Number(maxAgeMs) > 0 && age !== null && age > Number(maxAgeMs)) return null;
1828
+ return n;
1829
+ }
1830
+
1831
+ function getConfiguredDatapointId(key) {
1832
+ try {
1833
+ const cfg = window.__nwCfg || {};
1834
+ const dps = cfg && cfg.datapoints && typeof cfg.datapoints === 'object' ? cfg.datapoints : {};
1835
+ return String(dps[key] || '').trim();
1836
+ } catch (_e) {
1837
+ return '';
1838
+ }
1839
+ }
1840
+
1841
+ function getNormalizedBatteryFlow() {
1842
+ const deadbandW = 25;
1843
+ const inv = !!(state && state['settings.flowInvertBattery'] && state['settings.flowInvertBattery'].value);
1844
+ const chargeId = getConfiguredDatapointId('storageChargePower');
1845
+ const dischargeId = getConfiguredDatapointId('storageDischargePower');
1846
+ const batteryId = getConfiguredDatapointId('batteryPower');
1847
+ const chargeMapped = !!chargeId;
1848
+ const dischargeMapped = !!dischargeId;
1849
+ const batteryMapped = !!batteryId;
1850
+ const samePair = !!(chargeMapped && dischargeMapped && chargeId === dischargeId);
1851
+
1852
+ const fromSigned = (raw, src) => {
1853
+ let signed = Number(raw);
1854
+ if (!Number.isFinite(signed)) signed = 0;
1855
+ if (inv) signed = -signed;
1856
+ if (Math.abs(signed) <= deadbandW) signed = 0;
1857
+ return {
1858
+ chargeW: signed < 0 ? Math.abs(signed) : 0,
1859
+ dischargeW: signed > 0 ? signed : 0,
1860
+ signedW: signed,
1861
+ src,
1862
+ inverted: inv,
1863
+ };
1864
+ };
1865
+
1866
+ const sfEnabled = !!(state && state['storageFarm.enabled'] && state['storageFarm.enabled'].value);
1867
+ if (sfEnabled) {
1868
+ const fc = getFreshFlowNumber('storageFarm.totalChargePowerW');
1869
+ const fd = getFreshFlowNumber('storageFarm.totalDischargePowerW');
1870
+ if (fc !== null || fd !== null) {
1871
+ let c = Math.max(0, Math.abs(Number(fc || 0)));
1872
+ let d = Math.max(0, Math.abs(Number(fd || 0)));
1873
+ if (inv) { const t = c; c = d; d = t; }
1874
+ if (c <= deadbandW) c = 0;
1875
+ if (d <= deadbandW) d = 0;
1876
+ return { chargeW: c, dischargeW: d, signedW: d - c, src: inv ? 'storageFarm(inv)' : 'storageFarm', inverted: inv };
1877
+ }
1878
+ }
1879
+
1880
+ const signedBattery = batteryMapped ? getFreshFlowNumber('batteryPower') : null;
1881
+ const charge = chargeMapped ? getFreshFlowNumber('storageChargePower') : null;
1882
+ const discharge = dischargeMapped ? getFreshFlowNumber('storageDischargePower') : null;
1883
+
1884
+ if (samePair && signedBattery !== null) return fromSigned(signedBattery, 'batterySignedForSamePair');
1885
+
1886
+ const separateAvailable = (charge !== null || discharge !== null);
1887
+ const bothDirections = Math.abs(Number(charge || 0)) > deadbandW && Math.abs(Number(discharge || 0)) > deadbandW;
1888
+ const bothEqualish = bothDirections && Math.abs(Math.abs(Number(charge || 0)) - Math.abs(Number(discharge || 0))) <= Math.max(2, deadbandW);
1889
+
1890
+ if (signedBattery !== null && (!separateAvailable || bothEqualish || (!chargeMapped && !dischargeMapped))) {
1891
+ return fromSigned(signedBattery, bothEqualish ? 'batterySignedOverrideDual' : 'batterySigned');
1892
+ }
1893
+
1894
+ if (separateAvailable) {
1895
+ let c = Math.max(0, Math.abs(Number(charge || 0)));
1896
+ let d = Math.max(0, Math.abs(Number(discharge || 0)));
1897
+ if (c <= deadbandW) c = 0;
1898
+ if (d <= deadbandW) d = 0;
1899
+ if (inv) { const t = c; c = d; d = t; }
1900
+ return { chargeW: c, dischargeW: d, signedW: d - c, src: inv ? 'chargeDischarge(inv)' : 'chargeDischarge', inverted: inv };
1901
+ }
1902
+
1903
+ if (signedBattery !== null) return fromSigned(signedBattery, 'batterySigned');
1904
+
1905
+ return { chargeW: 0, dischargeW: 0, signedW: 0, src: (batteryMapped || chargeMapped || dischargeMapped) ? 'stale-or-missing' : 'missing', inverted: inv };
1906
+ }
1907
+
1796
1908
  function render() {
1797
1909
  const s = state;
1798
1910
 
@@ -1825,17 +1937,14 @@ function render() {
1825
1937
 
1826
1938
  const load = d('consumptionTotal');
1827
1939
  const { buy, sell } = getGridImportExport(d);
1828
- let charge = d('storageChargePower');
1829
- let discharge = d('storageDischargePower');
1940
+ const batteryFlow = getNormalizedBatteryFlow();
1941
+ let charge = Number(batteryFlow.chargeW) || 0;
1942
+ let discharge = Number(batteryFlow.dischargeW) || 0;
1830
1943
  let soc = d('storageSoc');
1831
1944
 
1832
1945
  if (sfEnabled) {
1833
- const c = d('storageFarm.totalChargePowerW');
1834
- const dch = d('storageFarm.totalDischargePowerW');
1835
1946
  const socAvg = d('storageFarm.totalSoc');
1836
1947
  const socMedian = d('storageFarm.medianSoc');
1837
- if (c != null && !isNaN(Number(c))) charge = c;
1838
- if (dch != null && !isNaN(Number(dch))) discharge = dch;
1839
1948
  // Im Farm‑Modus bevorzugen wir den Durchschnitt (Ø), Median bleibt als Fallback.
1840
1949
  if (socAvg != null && !isNaN(Number(socAvg))) soc = socAvg;
1841
1950
  else if (socMedian != null && !isNaN(Number(socMedian))) soc = socMedian;
@@ -2069,6 +2178,7 @@ let cfgReloadPending = false;
2069
2178
 
2070
2179
  const applyConfigSnapshot = (nextCfg) => {
2071
2180
  cfg = nextCfg || {};
2181
+ try { window.__nwCfg = cfg || {}; } catch (_e) { window.__nwCfg = {}; }
2072
2182
  try { units = cfg.units || units; } catch (_e) {}
2073
2183
 
2074
2184
  // App-Center config
@@ -3683,8 +3793,9 @@ render = function(){
3683
3793
  const pv = +(d('pvPower') ?? 0);
3684
3794
  const load = +(d('consumptionTotal') ?? 0);
3685
3795
  const { buy } = getGridImportExport(d);
3686
- const chg = +(d('storageChargePower') ?? 0);
3687
- const dchg = +(d('storageDischargePower') ?? 0);
3796
+ const batteryFlow = getNormalizedBatteryFlow();
3797
+ const chg = Number(batteryFlow.chargeW) || 0;
3798
+ const dchg = Number(batteryFlow.dischargeW) || 0;
3688
3799
  const soc = d('storageSoc');
3689
3800
  const cap = +(d('storageCapacityKwh') ?? 0);
3690
3801
 
@@ -3730,8 +3841,9 @@ render = function(){
3730
3841
  const pv = +(d('pvPower') ?? 0);
3731
3842
  const load = +(d('consumptionTotal') ?? 0);
3732
3843
  const { buy, sell } = getGridImportExport(d);
3733
- const charge = +(d('storageChargePower') ?? 0);
3734
- const discharge = +(d('storageDischargePower') ?? 0);
3844
+ const batteryFlow = getNormalizedBatteryFlow();
3845
+ const charge = Number(batteryFlow.chargeW) || 0;
3846
+ const discharge = Number(batteryFlow.dischargeW) || 0;
3735
3847
  const soc = d('storageSoc');
3736
3848
  const cap = +(d('storageCapacityKwh') ?? 0);
3737
3849
 
@@ -3785,8 +3897,9 @@ render = function(){
3785
3897
  const pv = +(d('pvPower') ?? 0);
3786
3898
  const load = +(d('consumptionTotal') ?? 0);
3787
3899
  const { buy } = getGridImportExport(d);
3788
- const chg = +(d('storageChargePower') ?? 0);
3789
- const dchg = +(d('storageDischargePower') ?? 0);
3900
+ const batteryFlow = getNormalizedBatteryFlow();
3901
+ const chg = Number(batteryFlow.chargeW) || 0;
3902
+ const dchg = Number(batteryFlow.dischargeW) || 0;
3790
3903
  const soc = d('storageSoc');
3791
3904
  const cap = +(d('storageCapacityKwh') ?? 0);
3792
3905
 
@@ -3832,8 +3945,9 @@ render = function(){
3832
3945
  const pv = +(d('pvPower') ?? 0);
3833
3946
  const load = +(d('consumptionTotal') ?? 0);
3834
3947
  const { buy, sell } = getGridImportExport(d);
3835
- const charge = +(d('storageChargePower') ?? 0);
3836
- const discharge = +(d('storageDischargePower') ?? 0);
3948
+ const batteryFlow = getNormalizedBatteryFlow();
3949
+ const charge = Number(batteryFlow.chargeW) || 0;
3950
+ const discharge = Number(batteryFlow.dischargeW) || 0;
3837
3951
  const soc = d('storageSoc');
3838
3952
  const cap = +(d('storageCapacityKwh') ?? 0);
3839
3953
 
@@ -5564,26 +5678,25 @@ function updateEnergyWeb() {
5564
5678
  let { buy, sell } = getGridImportExport(d);
5565
5679
  let load = +(d('consumptionTotal') ?? 0);
5566
5680
  let c2 = +(d('evcs.totalPowerW') ?? d('consumptionEvcs') ?? 0); // Wallbox (sum)
5567
- let batCharge = +(d('storageChargePower') ?? 0);
5568
- let batDischarge = +(d('storageDischargePower') ?? 0);
5569
- const batSingle = d('batteryPower'); // optional fallback
5681
+
5682
+ // Batterie: zentral normalisieren wie den NVP.
5683
+ // Signed batteryPower-Konvention: -W = Laden, +W = Entladen;
5684
+ // die Option "Batterie-Vorzeichen invertieren" wird vor dem Split angewendet.
5685
+ const batteryFlow = getNormalizedBatteryFlow();
5686
+ let batCharge = Number(batteryFlow.chargeW) || 0;
5687
+ let batDischarge = Number(batteryFlow.dischargeW) || 0;
5570
5688
  let soc = d('storageSoc');
5571
5689
 
5572
5690
  if (sfEnabled) {
5573
- const c = d('storageFarm.totalChargePowerW');
5574
- const dch = d('storageFarm.totalDischargePowerW');
5575
5691
  const socAvg = d('storageFarm.totalSoc');
5576
5692
  const socMedian = d('storageFarm.medianSoc');
5577
- if (c != null && !isNaN(Number(c))) batCharge = +c;
5578
- if (dch != null && !isNaN(Number(dch))) batDischarge = +dch;
5579
5693
  // Im Farm‑Modus bevorzugen wir den Durchschnitt (Ø), Median bleibt als Fallback.
5580
5694
  if (socAvg != null && !isNaN(Number(socAvg))) soc = socAvg;
5581
5695
  else if (socMedian != null && !isNaN(Number(socMedian))) soc = socMedian;
5582
5696
  }
5583
5697
 
5584
- // Invert toggles (remain verfügbar)
5698
+ // Invert toggles (Batterie ist bereits im Normalizer enthalten)
5585
5699
  const invPv = !!(s['settings.flowInvertPv']?.value);
5586
- const invBat = !!(s['settings.flowInvertBattery']?.value);
5587
5700
  const invGrid = !!(s['settings.flowInvertGrid']?.value);
5588
5701
  const invEv = !!(s['settings.flowInvertEv']?.value);
5589
5702
  const subEvFromLoad = (s['settings.flowSubtractEvFromBuilding']?.value ?? true) ? true : false;
@@ -5594,19 +5707,6 @@ function updateEnergyWeb() {
5594
5707
  if (!evAvail) c2 = 0;
5595
5708
  if (invGrid) { const t=buy; buy = sell; sell = t; } // swap semantics if inverted grid
5596
5709
 
5597
- if (invBat) { const t=batCharge; batCharge = batDischarge; batDischarge = t; }
5598
-
5599
- // Normalize battery flow signs: some systems report negative for charge/discharge
5600
- if (batCharge < 0 && batDischarge <= 0) { batCharge = Math.abs(batCharge); }
5601
- if (batDischarge < 0 && batCharge <= 0) { batDischarge = Math.abs(batDischarge); }
5602
-
5603
- // Fallback: if both battery flows are zero AND a single DP exists, infer direction from its sign
5604
- if ((batCharge===0 && batDischarge===0) && batSingle !== undefined && batSingle !== null && !isNaN(Number(batSingle))) {
5605
- const bp = Number(batSingle);
5606
- if (bp < 0) { batCharge = Math.abs(bp); batDischarge = 0; }
5607
- else { batDischarge = Math.abs(bp); batCharge = 0; }
5608
- }
5609
-
5610
5710
  // Optionale Extra-Kreise aktualisieren (Rückgabe = Summe der optionalen Verbraucher)
5611
5711
  const extrasConsumersSum = updateEnergyWebExtras(d);
5612
5712