iobroker.sun2000 2.3.3 → 2.3.5

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/README.md CHANGED
@@ -65,6 +65,16 @@ browse in the [wiki](https://github.com/bolliy/ioBroker.sun2000/wiki)
65
65
  Placeholder for the next version (at the beginning of the line):
66
66
  ### **WORK IN PROGRESS**
67
67
  -->
68
+ ### 2.3.5 (2025-11-17)
69
+ * dependency and configuration updates
70
+ * Battery status check was suspended in inverter control [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)
71
+ * Emma: dynamic detection of sun2000 inverters and integration of devices such as sun2000
72
+ * allow Modbus ID 0 when using the sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)
73
+
74
+ ### 2.3.4 (2025-11-01)
75
+ * dependency and configuration updates
76
+ * new state `collected.dailyExternalYield` Riemann sum of `collected.externalPower`
77
+
68
78
  ### 2.3.3 (2025-10-31)
69
79
  * Improved verification of the adapter configuration
70
80
  * new state `inverter.x.derived.dailyActiveEnergy` Inverter daily active energy, which is determined via the Riemann sum of `inverter.x.activePower`
package/io-package.json CHANGED
@@ -1,8 +1,34 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "sun2000",
4
- "version": "2.3.3",
4
+ "version": "2.3.5",
5
5
  "news": {
6
+ "2.3.5": {
7
+ "en": "dependency and configuration updates\nBattery status check was suspended in inverter control [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)\nEmma: dynamic detection of sun2000 inverters and integration of devices such as sun2000\nallow Modbus ID 0 when using the sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
8
+ "de": "abhängigkeits- und konfigurationsupdates\nDie Batteriestatusprüfung wurde in der Wechselrichtersteuerung [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220) ausgesetzt\nEmma: dynamische Erkennung von Wechselrichtern von Sun2000 und Integration von Geräten wie sun2000\nerlauben Sie Modbus ID 0 bei Verwendung des sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
9
+ "ru": "обновления зависимостей и конфигурации\nПроверка состояния батареи была приостановлена в инверторном управлении [#220] (https://github.com/bolliy/ioBroker.sun2000/issues/220)\nЭмма: динамическое обнаружение инверторов Sun2000 и интеграция таких устройств, как Sun2000\nразрешить Modbus ID 0 при использовании sDongle [#218] (https://github.com/bolliy/ioBroker.sun2000/issues/118)",
10
+ "pt": "atualizações de dependência e configuração\nA verificação do estado da bateria foi suspensa no controle do inversor [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)\nEmma: detecção dinâmica de inversores sun2000 e integração de dispositivos como sun2000\npermitir Modbus ID 0 ao usar o sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
11
+ "nl": "afhankelijkheid en configuratie-updates\nDe controle van de status van de batterij werd opgeschort bij controle van de inverter [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)\nEmma: dynamische detectie van zonne2000 omvormers en integratie van apparaten zoals sun2000\nmodbus ID 0 toestaan bij gebruik van sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
12
+ "fr": "mises à jour de la dépendance et de la configuration\nLe contrôle de l'état de la batterie a été suspendu dans le contrôle de l'onduleur [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)\nEmma : détection dynamique des onduleurs Sun2000 et intégration de dispositifs tels que Sun2000\npermettre Modbus ID 0 lors de l'utilisation de sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
13
+ "it": "aggiornamenti di dipendenza e configurazione\nIl controllo dello stato della batteria è stato sospeso nel controllo dell'inverter [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)\nEmma: rilevazione dinamica degli inverter Sun2000 e integrazione di dispositivi come sun2000\nconsentire Modbus ID 0 quando si utilizza lo sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
14
+ "es": "actualizaciones de dependencia y configuración\nSe suspendió el control del estado de la batería [#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)\nEmma: detección dinámica de inversores de sol2000 e integración de dispositivos como el sol2000\npermitir Modbus ID 0 al utilizar el sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
15
+ "pl": "aktualizacje zależności i konfiguracji\nKontrola stanu baterii została zawieszona w kontrolach inwertera [# 220] (https: / / github.com / bolliy / ioBroker.sun2000 / issues / 220)\nEmma: dynamiczna detekcja inwerterów sun2000 i integracja urządzeń takich jak sun2000\nw przypadku stosowania sDongle [# 218] (https: / / github.com / bolliy / ioBroker.sun2000 / issues / 118)",
16
+ "uk": "оновлення залежності та конфігурації\nПеревірка стану акумулятора була припинена в інверторному режимі [#220] (https://github.com/bolliy/ioBroker.sun2000/issues/220)\nЕмма: динамічне виявлення інверторів сонця2000 та інтеграції пристроїв, таких як сонце2000\nдозволити Modbus ID 0 при використанні sDongle [#218](https://github.com/bolliy/ioBroker.sun2000/issues/118)",
17
+ "zh-cn": "依赖和配置更新\n在反转控制中暂停了电池状态检查[#220](https://github.com/bolliy/ioBroker.sun2000/issues/220)\n艾玛:对太阳2000反转器的动态检测和太阳2000等设备的集成\n允许在使用 sDongle [# 218] 时使用 Modbus ID (https:// github.com/ bolliy/ioBroker.sun2000/issues/118) "
18
+ },
19
+ "2.3.4": {
20
+ "en": "dependency and configuration updates\nnew state `collected.dailyExternalYield` Riemann sum of `collected.externalPower`",
21
+ "de": "abhängigkeits- und konfigurationsupdates\nneuer Zustand `collect.dailyExternalYield` Riemann Summe von `collected.externalPower `",
22
+ "ru": "обновления зависимостей и конфигурации\nновый государственный «коллектив.dailyExternalYield» Riemann sum of 'collected.externalPower пункт",
23
+ "pt": "atualizações de dependência e configuração\nnovo estado «colected.dailyEnergieYield» Riemann soma de `colected.externalPower `",
24
+ "nl": "afhankelijkheid en configuratie-updates\nnieuwe staat Riemann som van gecollecteerd.externe kracht Wat",
25
+ "fr": "mises à jour de la dépendance et de la configuration\nnouvel état `collected.dailyExternalYield` Riemann somme de `collected.externalPower \"",
26
+ "it": "aggiornamenti di dipendenza e configurazione\nnuovo stato `colletto.dailyExternalYield` Riemann somma di `colletto.Power esterno #",
27
+ "es": "actualizaciones de dependencia y configuración\nnuevo estado `colected.dailyExternalYield` Riemann sum of `collected.externalPower `",
28
+ "pl": "aktualizacje zależności i konfiguracji\nnowy stan \"collected.dailyExternalYield\" Riemann sum of 'collected.externalPower'",
29
+ "uk": "оновлення залежності та конфігурації\nновий стан `collected.dailyExternalYield` Сума Riemann `collected.externalPower й",
30
+ "zh-cn": "依赖和配置更新\n新国家`收集.每日外部耶尔德' 收集的里曼总和。 `"
31
+ },
6
32
  "2.3.3": {
7
33
  "en": "Improved verification of the adapter configuration\nnew state `inverter.x.derived.dailyActiveEnergy` Inverter daily active energy, which is determined via the Riemann sum of `inverter.x.activePower`\nstate `collected.dailyInputYield` was redisigned based on inverter.[0..n-1].derived.dailyActiveEnergy",
8
34
  "de": "Verbesserte Überprüfung der Adapterkonfiguration\n`inverter.x.derived.dailyActiveEnergy` Inverter tägliche aktive Energie, die über die Riemann Summe von `inverter.x.activePower bestimmt wird `\nstate `collected.dailyInputYield` wurde basierend auf Inverter zurückgeteilt. [0.n-1].derived.dailyActiveEnergy",
@@ -67,32 +93,6 @@
67
93
  "pl": "inverter control: add same state for startup and shutdown an inverter [# 199] (https: / / github.com / bolliy / ioBroker.sun2000 / issues / 199)\nfix: Nazwa statusu urządzenia została poprawiona [# 202] (https: / / github.com / bolliy / ioBroker.sun2000 / pull / 202)\ndodać nieudokumentowany status urządzenia \"Wyłączenie: koniec procesu rozładowania ESS\"\nemma control: New state 'emma.control.battery.ESSControlMode'. Można teraz skonfigurować EMMA z TOU- mode (Time of Use), aby naładować baterię z siatki. [# 200] (https: / / github.com / bolliy / ioBroker.sun2000 / discussions / 200)\njeśli zainstalowana jest Emma, niektóre stany sterujące inwertera są wyłączone (tylko do odczytu). Głównie dla ustawień siatki.\nusunięto zdepregatowane stany kontrolne.\na workaround for issue [# 582] (https: / / github.com / yaacov / node- modbus- serial / issues / 582) of node- modbus- serial został wdrożony.",
68
94
  "uk": "контроль інвертора: додати однаковий стан для запуску та відключення інвертора [#199](https://github.com/bolliy/ioBroker.sun2000/issues/199)\nвиправлено: Назва стану пристрою було виправлено [#202] (https://github.com/bolliy/ioBroker.sun2000/pull/202)\nдодати недокументований статус пристрою `Пошук: кінець процесу розряду ESS\nемма управління: новий стан ` emma.control.battery.ESSControlMode`. Ви можете налаштувати EMMA з TOU-mode (Time of Use) для зарядки акумулятора з сітки. [#200](https://github.com/bolliy/ioBroker.sun2000/discussions/200)\nякщо встановлений Емма, деактивуються деякі стани управління інвертором (прочитати тільки). В основному для налаштування сітки.\nвилучені стани керування.\n[#582](https://github.com/yaacov/node-modbus-serial/issues/582) вузла-modbus-serial.",
69
95
  "zh-cn": "反转器控制:为启动和关闭添加相同状态的反转器[199](https://github.com/bolliy/ioBroker.sun2000/issues/199)\n固定: 设备状态名称已更正 [# 202] (https://github.com/bolliy/ioBroker.sun2000/pul/202)\n添加无文件设备状态“关闭:ESS放电过程结束”\nemma控制:新状态`emma.control.battery.ESS Control Mode'. 您现在可以用 TOU- mode( 使用时间) 配置 EMMA 从电网中充电 。 [# 200] (https://github.com/bolliy/ioBroker.sun2000/discussions/200)\n如果安装了Emma,反转器的某些控制状态就会失效(只读). 主要用于网格设置.\n贬值的控制状态已被取消.\n已落实了节点-modbus-serial[#582](https://github.com/yaacov/node-modbus-serial/issues/582)的工作."
70
- },
71
- "2.2.0": {
72
- "en": "dependency and configuration updates\nnew state `meter.derived.signConventionForPowerFeed-in` sign of meter.activePower that is currently being fed into the power grid\nnew state `meter.derived.feed-inPower` electric power that is supplied to a grid (\"fed in\")",
73
- "de": "abhängigkeits- und konfigurationsupdates\nneuer Zustand `meter.derived.signConventionForPowerFeed-in` Zeichen von meter.active Strom, der derzeit in das Stromnetz eingespeist wird\nneue Zustand `meter.derived.feed-inPower` elektrische Leistung, die einem Netz zugeführt wird (\"fed in\")",
74
- "ru": "обновления зависимостей и конфигурации\nновый государственный знак «meter.derived.signConventionForPowerFeed-in» Мощность, которая в настоящее время подается в электросеть\nэлектрическая мощность нового состояния «meter.derived.feed-inPower», которая подается в сеть («питается в»)",
75
- "pt": "atualizações de dependência e configuração\nnovo estado `meter.derived.signConventionForPowerFeed-in` sinal do medidor.active Energia que está sendo alimentada na rede de energia\nnovo estado `meter.derived.feed-inPower` energia elétrica que é fornecida a uma grade (\"feed in\")",
76
- "nl": "afhankelijkheid en configuratie-updates\nnieuwe staat Energie die momenteel wordt gevoed in het elektriciteitsnet\nnieuwe toestand ",
77
- "fr": "mises à jour de la dépendance et de la configuration\nnouvel état `meter.derived.signConventionForPowerFeed-in` signe de meter.active Puissance qui est actuellement introduite dans le réseau électrique\nnouvel état `meter.derived.feed-inPower` électricité qui est fourni à un réseau (\"feed in\")",
78
- "it": "aggiornamenti di dipendenza e configurazione\nnuovo stato `meter.derived.signConventionForPowerFeed-in` segno di metro.active Potenza che sta attualmente alimentando nella rete elettrica\nnuovo stato `meter.derived.feed-inPower` potere elettrico che viene fornito a una griglia (\"fed in\")",
79
- "es": "actualizaciones de dependencia y configuración\nnuevo estado `meter.derived.signConventionForPowerFeed-in` signo de medidor.active Potencia que actualmente está siendo alimentada en la red eléctrica\nnuevo estado `meter.derived.feed-inPower` energía eléctrica que se suministra a una red (\"fed in\")",
80
- "pl": "aktualizacje zależności i konfiguracji\nnowy stan 'meter.derived.signConventionForPowerFeed- in' znak meter.active Energia zasilana obecnie do sieci energetycznej\nnowy stan 'meter.derived.feed-inPower' energia elektryczna, która jest dostarczana do sieci (\"karmiona w\")",
81
- "uk": "оновлення залежності та конфігурації\nновий стан `meter.derived.signConventionForPowerFeed-in` знак лічильника.active Потужність, яка в даний час вдається в електромережу\nновий стан `meter.derived.feed-inPower` електрична потужність, яка подається в сітку (\"fed in\")",
82
- "zh-cn": "依赖和配置更新\n新的状态“ 公尺” 。 生成。 签署 Convention ForPowerFeed- in' sign of meter. 活动 目前输入电网的电力\n新状态“ met. entered. feed-inpower” 供电给电网(“ feeded in”)"
83
- },
84
- "2.1.1": {
85
- "en": "dependency and configuration updates\nfix: adjust event value limits based on usableSurplus parameters\nfix: swap register values for power consumption in Emma driver #190\nemma: improve power calculation with exponential moving average in EmmaCharger\nupdate surplus power state definitions and deprecate old identifiers",
86
- "de": "abhängigkeits- und konfigurationsupdates\nfix: Event-Wert-Grenze basierend auf nutzbar Überschüssige Parameter\nfix: Swap-Registerwerte für den Stromverbrauch in Emma Treiber #190\nemma: Leistungsberechnung mit exponentiellem Bewegungsmittel in EmmaCharger verbessern\naktualisierung der überschussstrom-zustandsdefinitionen und abschreibung alter kennungen",
87
- "ru": "обновления зависимостей и конфигурации\nисправление: корректировка предельных значений событий на основе пригодных для использования Дополнительные параметры\nисправление: значения регистра свопов для энергопотребления в драйвере Emma #190\nemma: улучшите расчет мощности с экспоненциальной скользящей средней в EmmaCharger\nобновить определения состояния избыточной мощности и обесценить старые идентификаторы",
88
- "pt": "atualizações de dependência e configuração\ncorreção: ajustar os limites do valor do evento com base no utilizável Parâmetros do excedente\ncorreção: valores de registro de swap para consumo de energia em Emma driver #190\nemma: melhorar o cálculo de potência com média móvel exponencial em EmmaCharger\natualizar definições de estado de potência excedente e depreciar identificadores antigos",
89
- "nl": "afhankelijkheid en configuratie-updates\nfix: aanpassen gebeurtenis waarde limieten op basis van bruikbaar Overschotparameters\nfix: swap register waarden voor energieverbruik in Emma driver #190\nemma: verbeteren van de stroomberekening met exponentieel bewegend gemiddelde in EmmaCharger\nde definitie van overtollige vermogenstoestand bij te werken en oude identificatienummers te schrappen",
90
- "fr": "mises à jour de la dépendance et de la configuration\nfix: ajuster les limites de valeur d'événement en fonction de la valeur utilisable Paramètres excédentaires\nfix: valeurs de registre d'échange pour la consommation d'énergie en Emma driver #190\nemma: améliorer le calcul de la puissance avec la moyenne mobile exponentielle en EmmaCharger\nmettre à jour les définitions de l'état de puissance excédentaire et supprimer les anciens identifiants",
91
- "it": "aggiornamenti di dipendenza e configurazione\ncorrezione: regolare i limiti del valore dell'evento in base all'utilizzabile Parametri in eccesso\ncorrezione: swap valori di registro per il consumo di energia in Emma driver #190\nemma: migliorare il calcolo di potenza con una media mobile esponenziale in EmmaCharger\naggiornare le definizioni di stato di potenza eccedente e deprecare vecchi identificatori",
92
- "es": "actualizaciones de dependencia y configuración\nfijación: ajustar los límites de valor de evento basados en utilizables Parámetros adicionales\nfijado: cambiar los valores de registro para el consumo de energía en el controlador Emma #190\nemma: mejorar el cálculo de potencia con promedio de movimiento exponencial en EmmaCharger\nactualizar las definiciones de estado de excedente de energía y depreparar identificadores antiguos",
93
- "pl": "aktualizacje zależności i konfiguracji\nfix: dostosować wartości graniczne dla zdarzeń w oparciu o wartość użytkową Parametry nadwyżki\nfix: wartości rejestru swap dla zużycia energii w sterowniku Emma # 190\nemma: ulepszenie obliczania mocy przy zastosowaniu wykładniczej średniej ruchomej w EmmaCharger\naktualizacja definicji nadwyżek energii elektrycznej i deprecjacja starych identyfikatorów",
94
- "uk": "оновлення залежності та конфігурації\nвиправити: регулювати ліміти значення події на основі Параметри Surplus\nвиправити: значення swap для споживання енергії в машині Емма #190\nемма: поліпшення розрахунку потужності з постійним рухомим середнім в ЕммаКхаргер\nоновлення надлишок визначення стану живлення та депресувати старі ідентифікатори",
95
- "zh-cn": "依赖和配置更新\n固定:根据可用值调整事件值限制 盈余参数\n修补: Emma 驱动器中用电量的交换记录值 # 190\nemma: 改进电量计算, 以 Emmacourer 中的指数移动平均值\n更新剩余电源状态定义并折旧旧标识符"
96
96
  }
97
97
  },
98
98
  "titleLang": {
@@ -233,14 +233,14 @@
233
233
  "native": {
234
234
  "address": "",
235
235
  "port": 502,
236
- "modbusIds": "1",
236
+ "modbusIds": "",
237
237
  "updateInterval": 20,
238
238
  "sd_active": false,
239
239
  "sDongleId": "100",
240
240
  "timeout": 10000,
241
241
  "delay": 0,
242
242
  "connectDelay": 5000,
243
- "autoAdjust": true,
243
+ "autoAdjust": false,
244
244
  "ms_active": false,
245
245
  "ms_address": "0.0.0.0",
246
246
  "ms_port": 502,
@@ -750,6 +750,7 @@ class ServiceQueueMap {
750
750
  this._eventMap.delete(event.id); //forget the event
751
751
  continue;
752
752
  }
753
+ /*
753
754
  const BatStatus = this.inverterInfo.instance.stateCache.get(`${this.inverterInfo.path}.battery.runningStatus`)?.value ?? -1;
754
755
  if (BatStatus !== 2 && BatStatus !== 1 && BatStatus !== -1) {
755
756
  this.log.warn(
@@ -758,6 +759,7 @@ class ServiceQueueMap {
758
759
  this._eventMap.delete(event.id); //forget the event
759
760
  continue;
760
761
  }
762
+ */
761
763
  }
762
764
  if (service.state.type === 'number') {
763
765
  if (!this.isNumber(event)) {
@@ -570,7 +570,7 @@ class Emma extends DriverBase {
570
570
  this.log.debug('### PostHook for Emma - identify Subdevices charger');
571
571
  this.identifySubdevices('charger', this.modbusId)
572
572
  .then(ret => {
573
- this.log.debug(`### PostHook identification for Emmachargers - ret: ${JSON.stringify(ret)}`);
573
+ this.log.debug(`### PostHook identification for Emma chargers - ret: ${JSON.stringify(ret)}`);
574
574
  for (const [i, charger] of ret.entries()) {
575
575
  const device = {
576
576
  index: i,
@@ -588,8 +588,23 @@ class Emma extends DriverBase {
588
588
  this.identifySubdevices('sun2000', this.modbusId)
589
589
  .then(ret => {
590
590
  this.log.debug(`### PostHook indentification for Inverter Sun2000 - ret: ${JSON.stringify(ret)}`);
591
- for (const [, inverter] of ret.entries()) {
591
+ //check if inverter sun2000 already exists
592
+ const inverterExist = this.adapter.devices.findIndex(x => x.driverClass === driverClasses.inverter);
593
+ for (const [i, inverter] of ret.entries()) {
592
594
  this.log.info(`${this._name} identify subdevice an inverter sun2000: OID=${inverter.obj_id}, modbus id: ${inverter.slave_id}`);
595
+ //unless inverters are configured, add them
596
+ if (inverterExist === -1) {
597
+ const device = {
598
+ index: i,
599
+ duration: 5000,
600
+ modbusId: inverter.slave_id,
601
+ driverClass: driverClasses.inverter,
602
+ meter: false,
603
+ };
604
+ this.adapter.devices.push(device);
605
+ this.adapter.initDevicePath(device);
606
+ this.log.info(`Inverter sun2000 with modbus id ${inverter.slave_id} added.`);
607
+ }
593
608
  }
594
609
  })
595
610
  .catch(err => {
@@ -96,15 +96,13 @@ class InverterSun2000 extends DriverBase {
96
96
  this.solarSum = new RiemannSum();
97
97
  this.adapter.getState(`${this.deviceInfo.path}.derived.dailySolarYield`, (err, state) => {
98
98
  if (!err && state) {
99
- this.solarSum.setStart(state.val, state.ts);
99
+ this.solarSum.setStart(state?.val, state?.ts);
100
100
  }
101
101
  });
102
-
103
- //
104
102
  this.activePowerSum = new RiemannSum();
105
103
  this.adapter.getState(`${this.deviceInfo.path}.derived.dailyActiveEnergy`, (err, state) => {
106
104
  if (!err && state) {
107
- this.activePowerSum.setStart(state.val, state.ts);
105
+ this.activePowerSum.setStart(state?.val, state?.ts);
108
106
  }
109
107
  });
110
108
 
@@ -1521,7 +1519,8 @@ class InverterSun2000 extends DriverBase {
1521
1519
  const charge = this.stateCache.get(`${path}battery.currentDayChargeCapacity`)?.value ?? 0;
1522
1520
  //let inputYield = this.stateCache.get(`${path}dailyEnergyYield`)?.value ?? 0 * 0.97 + charge - disCharge;
1523
1521
  const activeEnergy = this.stateCache.get(`${path}derived.dailyActiveEnergy`)?.value ?? 0;
1524
- let inYield = activeEnergy + (charge - disCharge) * 0.97; //efficiency loss of battery 3%
1522
+ //let inYield = activeEnergy + (charge - disCharge) * 0.97; //efficiency loss of battery 3%
1523
+ let inYield = activeEnergy + charge * 0.97 - disCharge * 1.03; //efficiency loss of battery 3%
1525
1524
  if (inYield < 0) {
1526
1525
  inYield = 0;
1527
1526
  }
@@ -97,11 +97,17 @@ class ModbusConnect extends DeviceInterface {
97
97
  close() {
98
98
  return new Promise(resolve => {
99
99
  if (this.client) {
100
- this.client.close(() => {
100
+ try {
101
+ this.client.close(() => {
102
+ resolve({});
103
+ });
104
+ //workaround for issue https://github.com/yaacov/node-modbus-serial/issues/582 with node-modbus-serial
101
105
  resolve({});
102
- });
103
- //workaround for issue https://github.com/yaacov/node-modbus-serial/issues/582 with node-modbus-serial
104
- resolve({});
106
+ } catch (err) {
107
+ this.log.warn(`Could not close Modbus connection: ${err.message}`);
108
+ resolve({});
109
+ //reject();
110
+ }
105
111
  } else {
106
112
  resolve({});
107
113
  }
@@ -112,9 +118,15 @@ class ModbusConnect extends DeviceInterface {
112
118
  _destroy() {
113
119
  return new Promise(resolve => {
114
120
  if (this.client) {
115
- this.client.destroy(() => {
121
+ try {
122
+ this.client.destroy(() => {
123
+ resolve({});
124
+ });
125
+ } catch (err) {
126
+ this.log.warn(`Could not destroy Modbus connection: ${err.message}`);
116
127
  resolve({});
117
- });
128
+ //reject();
129
+ }
118
130
  } else {
119
131
  resolve({});
120
132
  }
@@ -140,8 +152,6 @@ class ModbusConnect extends DeviceInterface {
140
152
  if (err.modbusCode === undefined) {
141
153
  this._adjustDelay(err, false);
142
154
  await this.close();
143
- //await this._destroy();
144
- //await this.closing();
145
155
  await this._create();
146
156
  if (err.errno === 'ECONNREFUSED') {
147
157
  this.log.warn('Has another device interrupted the modbus connection?');
@@ -150,8 +160,6 @@ class ModbusConnect extends DeviceInterface {
150
160
  } else {
151
161
  if (err.modbusCode === 0) {
152
162
  await this.close();
153
- //await this._destroy();
154
- //await this.closing();
155
163
  this._adjustDelay(err, false);
156
164
  await this._create();
157
165
  }
package/lib/register.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { deviceType, driverClasses, dataRefreshRate } = require(`${__dirname}/types.js`);
4
- const { StateMap } = require(`${__dirname}/tools.js`);
4
+ const { RiemannSum, StateMap } = require(`${__dirname}/tools.js`);
5
5
  const getDriverHandler = require(`${__dirname}/drivers/index.js`);
6
6
 
7
7
  class Registers {
@@ -9,6 +9,8 @@ class Registers {
9
9
  this.adapter = adapterInstance;
10
10
  this.stateCache = new StateMap();
11
11
 
12
+ this.externalSum = new RiemannSum();
13
+
12
14
  for (const device of this.adapter.devices) {
13
15
  //DriverInfo Instance or Sdongle
14
16
  const handler = getDriverHandler(device.driverClass);
@@ -153,6 +155,7 @@ class Registers {
153
155
  const feedinPower = this.stateCache.get('meter.derived.feed-inPower')?.value ?? 0;
154
156
 
155
157
  const extPower = this.adapter.control.get('externalPower')?.value ?? 0;
158
+ this.externalSum.add(extPower); //riemann Sum
156
159
 
157
160
  //Zu geringe Erzeugerenegie
158
161
  let houseConsum = actPower - feedinPower + extPower;
@@ -234,6 +237,14 @@ class Registers {
234
237
  },
235
238
  { id: 'collected.SOC', name: 'State of battery capacity', type: 'number', unit: '%', role: 'value.battery', desc: 'SOC' },
236
239
  { id: 'collected.ratedCapacity', name: 'Rated of battery capacity', type: 'number', unit: 'Wh', role: 'value.capacity' },
240
+ {
241
+ id: 'collected.dailyExternalYield',
242
+ name: 'daily external yield',
243
+ type: 'number',
244
+ unit: 'kWh',
245
+ role: 'value.power.consumption',
246
+ desc: 'Riemann sum of external power',
247
+ },
237
248
  /*
238
249
  {
239
250
  id: 'collected.dailyActiveEnergy',
@@ -281,8 +292,9 @@ class Registers {
281
292
  }
282
293
  }
283
294
  //this.stateCache.set('collected.dailyActiveEnergy', activeEnergy, { type: 'number' });
295
+ this.stateCache.set('collected.dailyExternalYield', this.externalSum.sum, { type: 'number' }); //of externalPower
284
296
  this.stateCache.set('collected.dailyEnergyYield', outYield, { type: 'number' });
285
- this.stateCache.set('collected.dailyInputYield', inYield, { type: 'number' }); //deprecated
297
+ this.stateCache.set('collected.dailyInputYield', inYield, { type: 'number' });
286
298
  this.stateCache.set('collected.dailySolarYield', solarYield, { type: 'number' });
287
299
  this.stateCache.set('collected.accumulatedEnergyYield', enYield, { type: 'number' });
288
300
  const sign = this.stateCache.get('meter.derived.signConventionForPowerFeed-in')?.value ?? 1;
@@ -315,7 +327,10 @@ class Registers {
315
327
  //new computation of consumption today
316
328
  this.stateCache.set(
317
329
  'collected.consumptionToday',
318
- activeEnergy + this.stateCache.get('collected.gridImportToday')?.value - this.stateCache.get('collected.gridExportToday')?.value,
330
+ activeEnergy +
331
+ this.externalSum.sum +
332
+ this.stateCache.get('collected.gridImportToday')?.value -
333
+ this.stateCache.get('collected.gridExportToday')?.value,
319
334
  { type: 'number' },
320
335
  );
321
336
  //compute battery
@@ -433,7 +448,9 @@ class Registers {
433
448
  this.stateCache.set('collected.gridImportStart', state?.val, { type: 'number', stored: true });
434
449
  state = await this.adapter.getState('collected.consumptionStart');
435
450
  this.stateCache.set('collected.consumptionStart', state?.val, { type: 'number', stored: true });
436
- //this.stateCache.set('collected.consumptionStart', 100000, { type: 'number', stored: true });
451
+ state = await this.adapter.getState('collected.dailyExternalYield');
452
+ this.stateCache.set('collected.dailyExternalYield', state?.val, { type: 'number', stored: true });
453
+ this.externalSum.setStart(state?.val, state?.ts);
437
454
  }
438
455
 
439
456
  //state
@@ -502,6 +519,8 @@ class Registers {
502
519
  this.stateCache.set('collected.gridExportStart', this.stateCache.get('meter.positiveActiveEnergy')?.value ?? 0, { type: 'number' });
503
520
  this.stateCache.set('collected.gridImportStart', this.stateCache.get('meter.reverseActiveEnergy')?.value ?? 0, { type: 'number' });
504
521
  }
522
+ this.externalSum.reset(); //reset for next day
523
+ this.stateCache.set('collected.dailyExternalYield', 0, { type: 'number' });
505
524
  // copy consumption Sum to Start for the next day
506
525
  this.stateCache.set('collected.consumptionStart', this.stateCache.get('collected.consumptionSum')?.value ?? 0, { type: 'number' });
507
526
  for (const device of this.adapter.devices) {
package/lib/tools.js CHANGED
@@ -202,8 +202,12 @@ class RiemannSum {
202
202
  }
203
203
 
204
204
  setStart(sum, ts) {
205
- this._sum = sum;
206
- this._lastDate = new Date(ts);
205
+ if (!isNaN(sum)) {
206
+ this._sum = sum;
207
+ this._lastDate = new Date(ts);
208
+ } else {
209
+ this.reset();
210
+ }
207
211
  }
208
212
  }
209
213
 
package/main.js CHANGED
@@ -386,14 +386,13 @@ class Sun2000 extends utils.Adapter {
386
386
  this.settings.modbusDelay = this.config.delay; //ms
387
387
  this.settings.modbusConnectDelay = this.config.connectDelay; //ms
388
388
  this.settings.modbusAdjust = this.config.autoAdjust;
389
- this.settings.modbusIds = this.config.modbusIds.split(',').map(n => {
390
- return Number(n);
391
- });
392
- /*
393
- this.settings.chargerIds = this.config.chargerIds.split(',').map(n => {
394
- return Number(n);
395
- });
396
- */
389
+ if (this.config.modbusIds !== '') {
390
+ this.settings.modbusIds = this.config.modbusIds.split(',').map(n => {
391
+ return Number(n);
392
+ });
393
+ } else {
394
+ this.settings.modbusIds = [];
395
+ }
397
396
  //SmartDongle
398
397
  this.settings.sd.active = this.config.sd_active;
399
398
  // eslint-disable-next-line no-constant-binary-expression
@@ -419,27 +418,34 @@ class Sun2000 extends utils.Adapter {
419
418
  if (this.settings.modbusAdjust) {
420
419
  await this.setState('info.JSONhealth', { val: '{message: "Adjust modbus settings"}', ack: true });
421
420
  } else {
422
- await this.setState('info.JSONhealth', { val: '{message : "Information is collected"}', ack: true });
421
+ await this.setState('info.JSONhealth', { val: '{message : "Information is collected..."}', ack: true });
423
422
  }
424
- //future: if (this.settings.integration !== 2 && (this.settings.modbusIds.length === 0 || this.settings.modbusIds.length > 5)) {
425
- if (this.settings.modbusIds.length === 0 || this.settings.modbusIds.length > 5) {
426
- this.adapterDisable(`*** Adapter deactivated, inverter modbus Ids is invalid! ***`);
423
+ //validate modbus Ids
424
+ if (this.settings.modbusIds.length > 5) {
425
+ this.adapterDisable(`*** Adapter deactivated, Only a maximum of 5 inverters are allowed! ***`);
426
+ return;
427
+ }
428
+ if (this.settings.integration !== 2 && this.settings.modbusIds.length === 0) {
429
+ this.adapterDisable(`*** Adapter deactivated, inverter Modbus IDs must be entered! ***`);
427
430
  return;
428
431
  }
429
432
  //ES6 use a for (const [index, item] of array.entries()) of loop
430
433
  for (const [i, id] of this.settings.modbusIds.entries()) {
431
434
  //Inverter
432
- if (id < 1 || id >= 250) {
435
+ if (id >= 250) {
433
436
  this.adapterDisable(`*** Adapter deactivated, inverter modbus Id ${id} is not permitted! ***`);
434
437
  return;
435
438
  }
436
- this.devices.push({
437
- index: i,
438
- duration: 5000,
439
- modbusId: id,
440
- driverClass: driverClasses.inverter,
441
- meter: i == 0 && this.settings.integration === 0,
442
- });
439
+ //inverter modbus id 0 does not exist with emma
440
+ if (this.settings.integration !== 2 || id > 0) {
441
+ this.devices.push({
442
+ index: i,
443
+ duration: 5000,
444
+ modbusId: id,
445
+ driverClass: driverClasses.inverter,
446
+ meter: i == 0 && this.settings.integration === 0,
447
+ });
448
+ }
443
449
  }
444
450
 
445
451
  //SDongle
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.sun2000",
3
- "version": "2.3.3",
3
+ "version": "2.3.5",
4
4
  "description": "sun2000",
5
5
  "author": {
6
6
  "name": "bolliy",
@@ -33,18 +33,16 @@
33
33
  "tcp-port-used": "^1.0.2"
34
34
  },
35
35
  "devDependencies": {
36
- "@alcalzone/release-script": "^3.8.0",
37
- "@alcalzone/release-script-plugin-iobroker": "^3.7.2",
38
- "@alcalzone/release-script-plugin-license": "^3.7.0",
39
- "@alcalzone/release-script-plugin-manual-review": "^3.7.0",
40
- "@eslint/eslintrc": "^3.3.1",
41
- "@eslint/js": "^9.36.0",
36
+ "@alcalzone/release-script": "^5.0.0",
37
+ "@alcalzone/release-script-plugin-iobroker": "^4.0.0",
38
+ "@alcalzone/release-script-plugin-license": "^4.0.0",
39
+ "@alcalzone/release-script-plugin-manual-review": "^4.0.0",
42
40
  "@iobroker/adapter-dev": "^1.5.0",
43
41
  "@iobroker/eslint-config": "^2.2.0",
44
- "@iobroker/testing": "^5.1.1",
42
+ "@iobroker/testing": "^5.2.2",
45
43
  "@tsconfig/node20": "^20.1.6",
46
- "@types/node": "^24.6.2",
47
- "globals": "^16.4.0",
44
+ "@types/node": "^24.10.1",
45
+ "globals": "^16.5.0",
48
46
  "typescript": "~5.9.3"
49
47
  },
50
48
  "main": "main.js",