From df0e21120005fe9a7514018817300178c2f0eeea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Mo=C3=9Fner?= <46440437+matzempc@users.noreply.github.com> Date: Thu, 12 May 2022 20:07:39 +0200 Subject: [PATCH 1/9] goecheck: avoid resetting current when llsoll(s1) is zero This happens for example when charge point is disabled and therefore goe api is triggered every cycle though it isn't needed --- goecheck.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/goecheck.sh b/goecheck.sh index 53b4dcbbd..bfb8f0329 100644 --- a/goecheck.sh +++ b/goecheck.sh @@ -20,7 +20,7 @@ goecheck(){ fwv=$(echo $output | jq -r '.fwv' | grep -Po "[1-9]\d{1,2}") oldcurrent=$(echo $output | jq -r '.amp') current=$(= 40)) ; then curl --silent --connect-timeout $goetimeoutlp1 -s http://$goeiplp1/mqtt?payload=amx=$current > /dev/null else @@ -48,7 +48,7 @@ goecheck(){ fwv=$(echo $output | jq -r '.fwv' | grep -Po "[1-9]\d{1,2}") oldcurrent=$(echo $output | jq -r '.amp') current=$(= 40)) ; then curl --silent --connect-timeout $goetimeoutlp2 -s http://$goeiplp2/mqtt?payload=amx=$current > /dev/null else From b993bf234950f7eb7db4c91d587a72a1e8765e51 Mon Sep 17 00:00:00 2001 From: okaegi Date: Thu, 19 May 2022 18:29:01 +0200 Subject: [PATCH 2/9] Smartmq.... MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Setzt als Defaiut Smartmq wenn von stanle auf nightly gewechselt wird. Updated Überschuss für Status bild Bringt eine Warnung das Mitte Juni 2022 der jetzige Smarthomehandler ersetzt wird --- runs/initRamdisk.sh | 2 +- runs/smarthomemq.py | 2 ++ web/settings/smarthomeconfig.php | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/runs/initRamdisk.sh b/runs/initRamdisk.sh index 62519da83..1bfc064bd 100644 --- a/runs/initRamdisk.sh +++ b/runs/initRamdisk.sh @@ -611,7 +611,7 @@ initRamdisk(){ ra='^-?[0-9]+$' smartmqtemp=$(timeout 1 mosquitto_sub -t openWB/config/get/SmartHome/smartmq) if ! [[ $smartmqtemp =~ $ra ]] ; then - smartmqtemp="0" + smartmqtemp="1" fi echo $smartmqtemp > $RamdiskPath/smartmq diff --git a/runs/smarthomemq.py b/runs/smarthomemq.py index 4f61956f7..202afcbd2 100644 --- a/runs/smarthomemq.py +++ b/runs/smarthomemq.py @@ -227,6 +227,8 @@ def getdevicevalues(): mqtt_all['openWB/SmartHome/Status/wattschalt'] = totalwatt mqtt_all['openWB/SmartHome/Status/wattnichtschalt'] = totalwattot mqtt_all['openWB/SmartHome/Status/wattnichtHaus'] = totalminhaus + mqtt_all['openWB/SmartHome/Status/uberschuss'] = uberschuss + mqtt_all['openWB/SmartHome/Status/uberschussoffset'] = uberschussoffset sendmq(mqtt_all) diff --git a/web/settings/smarthomeconfig.php b/web/settings/smarthomeconfig.php index fd3950500..65a7ce7e6 100644 --- a/web/settings/smarthomeconfig.php +++ b/web/settings/smarthomeconfig.php @@ -794,13 +794,14 @@
- +
+ Smartmq bietet derweilen die gleichen und mehr Funktionen wie der Smarthomehandler an. Smartmq wird Mitte Juni 2022 den Smarthomehandler komplett ersetzen. Dann wird der obige Parameter fix auf Ja gesetzt und kann nicht mehr geändert werden.
From 54fe1698c90fa0eaaae1ed6fe315746d6c33c15b Mon Sep 17 00:00:00 2001 From: LKuemmel Date: Mon, 23 May 2022 13:05:20 +0200 Subject: [PATCH 3/9] changes from core --- packages/helpermodules/log.py | 39 +++++++++++ packages/modules/alpha_ess/bat.py | 7 +- packages/modules/alpha_ess/counter.py | 3 - packages/modules/alpha_ess/device.py | 32 +++++---- packages/modules/alpha_ess/inverter.py | 4 -- packages/modules/batterx/counter.py | 8 ++- packages/modules/batterx/device.py | 12 ++-- packages/modules/batterx/inverter.py | 3 - packages/modules/carlo_gavazzi/counter.py | 6 +- packages/modules/carlo_gavazzi/device.py | 24 ++++--- .../modules/common/abstract_chargepoint.py | 23 +++++++ packages/modules/common/abstract_soc.py | 11 +++ packages/modules/common/component_context.py | 12 +++- packages/modules/common/component_state.py | 68 +++++++++++++------ .../modules/common/component_state_test.py | 8 +++ packages/modules/common/component_type.py | 32 +++++++++ packages/modules/common/fault_state.py | 34 ++++------ packages/modules/common/modbus.py | 6 +- packages/modules/common/powerwall.py | 2 +- packages/modules/common/req.py | 5 +- packages/modules/common/simcount.py | 52 +++++++------- packages/modules/common/store/__init__.py | 1 + packages/modules/common/store/_api.py | 2 +- packages/modules/common/store/_broker.py | 9 +-- packages/modules/common/store/_car.py | 17 +---- packages/modules/common/store/_chargepoint.py | 25 +++++++ packages/modules/common/store/_counter.py | 2 +- packages/modules/discovergy/api_test.py | 0 packages/modules/discovergy/device.py | 8 +-- packages/modules/fronius/bat.py | 4 -- packages/modules/fronius/counter_s0.py | 5 -- packages/modules/fronius/counter_sm.py | 11 ++- packages/modules/fronius/device.py | 24 ++++--- packages/modules/fronius/inverter.py | 3 - packages/modules/good_we/bat.py | 3 - packages/modules/good_we/counter.py | 3 - packages/modules/good_we/device.py | 26 +++---- packages/modules/good_we/inverter.py | 3 - packages/modules/http/api.py | 6 +- packages/modules/http/bat.py | 3 - packages/modules/http/counter.py | 3 - packages/modules/http/device.py | 25 +++---- packages/modules/http/inverter.py | 4 +- packages/modules/huawei/bat.py | 3 - packages/modules/huawei/counter.py | 2 - packages/modules/huawei/device.py | 28 ++++---- packages/modules/huawei/inverter.py | 2 - packages/modules/janitza/counter.py | 3 - packages/modules/janitza/device.py | 24 ++++--- packages/modules/json/bat.py | 2 - packages/modules/json/counter.py | 2 - packages/modules/json/device.py | 22 +++--- packages/modules/json/inverter.py | 2 - packages/modules/openwb_bat_kit/device.py | 24 +++---- packages/modules/openwb_flex/bat.py | 3 - packages/modules/openwb_flex/counter.py | 5 +- packages/modules/openwb_flex/device.py | 32 +++++---- packages/modules/openwb_flex/inverter.py | 2 - packages/modules/powerdog/counter.py | 9 +-- packages/modules/powerdog/device.py | 48 ++++++------- packages/modules/powerdog/inverter.py | 5 +- packages/modules/saxpower/bat.py | 2 - packages/modules/saxpower/device.py | 24 ++++--- packages/modules/siemens/bat.py | 2 - packages/modules/siemens/counter.py | 3 - packages/modules/siemens/device.py | 24 ++++--- packages/modules/siemens/inverter.py | 2 - packages/modules/sma_modbus_tcp/device.py | 12 ++-- .../sma_modbus_tcp/inverter_modbus_tcp.py | 7 +- .../modules/sma_modbus_tcp/inverter_webbox.py | 6 -- packages/modules/sma_shm/device.py | 14 ++-- packages/modules/sma_shm/utils.py | 2 +- packages/modules/solax/bat.py | 2 - packages/modules/solax/counter.py | 7 +- packages/modules/solax/device.py | 26 +++---- packages/modules/solax/inverter.py | 5 +- packages/modules/sonnenbatterie/bat.py | 13 ++-- packages/modules/sonnenbatterie/counter.py | 17 +++-- packages/modules/sonnenbatterie/device.py | 26 +++---- packages/modules/sonnenbatterie/inverter.py | 15 ++-- packages/modules/studer/bat.py | 2 - packages/modules/studer/device.py | 22 +++--- packages/modules/studer/inverter.py | 2 - packages/modules/sungrow/bat.py | 2 - packages/modules/sungrow/counter.py | 7 +- packages/modules/sungrow/device.py | 22 +++--- packages/modules/sungrow/inverter.py | 2 - packages/modules/sunny_island/bat.py | 2 - packages/modules/sunny_island/device.py | 26 +++---- packages/modules/sunways/device.py | 26 +++---- packages/modules/sunways/inverter.py | 5 +- packages/modules/tesla/counter.py | 8 ++- packages/modules/tesla/device.py | 28 ++++---- packages/modules/victron/bat.py | 2 - packages/modules/victron/counter.py | 3 - packages/modules/victron/device.py | 30 ++++---- packages/modules/victron/inverter.py | 9 +-- 97 files changed, 654 insertions(+), 549 deletions(-) create mode 100644 packages/modules/common/abstract_chargepoint.py create mode 100644 packages/modules/common/abstract_soc.py create mode 100644 packages/modules/common/component_state_test.py create mode 100644 packages/modules/common/component_type.py create mode 100644 packages/modules/common/store/_chargepoint.py mode change 100755 => 100644 packages/modules/discovergy/api_test.py diff --git a/packages/helpermodules/log.py b/packages/helpermodules/log.py index 0f1d9255a..aa4d044b3 100644 --- a/packages/helpermodules/log.py +++ b/packages/helpermodules/log.py @@ -1,6 +1,7 @@ import logging import os import sys +from pathlib import Path def get_log_level_from_environment(): @@ -13,7 +14,20 @@ def get_log_level_from_environment(): return logging.DEBUG +def filter_soc_neg(record) -> bool: + if "soc" in record.threadName: + return False + return True + + +def filter_soc_pos(record) -> bool: + if "soc" in record.threadName: + return True + return False + + def setup_logging_stdout(): + format_str_short = '%(asctime)s - %(message)s' root_logger = logging.getLogger() # Only do something if logging is not yet initialized. # It may not be initialized if this function is called multiple times or of logging is set up while unit testing @@ -24,6 +38,31 @@ def setup_logging_stdout(): ) root_logger.addHandler(handler) root_logger.setLevel(get_log_level_from_environment()) + logging.getLogger().handlers[0].addFilter(filter_soc_neg) + + mqtt_log = logging.getLogger("mqtt") + mqtt_log.propagate = False + mqtt_file_handler = logging.FileHandler(str(Path(__file__).resolve().parents[2] / 'ramdisk' / ('mqtt.log'))) + mqtt_file_handler.setFormatter(logging.Formatter(format_str_short)) + mqtt_log.addHandler(mqtt_file_handler) + + soc_log = logging.getLogger("soc") + soc_log.propagate = True + soc_file_handler = logging.FileHandler(str(Path(__file__).resolve().parents[2] / 'ramdisk' / ('soc.log'))) + soc_file_handler.setFormatter(logging.Formatter( + u"%(asctime)s: PID: %(process)d: %(name)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")) + soc_file_handler.addFilter(filter_soc_pos) + soc_log.addHandler(soc_file_handler) + + urllib3_log = logging.getLogger("urllib3.connectionpool") + urllib3_log.propagate = True + urllib3_file_handler = logging.FileHandler(str(Path(__file__).resolve().parents[2] / 'ramdisk' / ('soc.log'))) + urllib3_file_handler.setFormatter(logging.Formatter( + u"%(asctime)s: PID: %(process)d: %(name)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")) + urllib3_file_handler.addFilter(filter_soc_pos) + urllib3_log.addHandler(urllib3_file_handler) + + logging.getLogger("pymodbus").setLevel(logging.WARNING) class MainLogger: diff --git a/packages/modules/alpha_ess/bat.py b/packages/modules/alpha_ess/bat.py index 551536f33..cfdda9f91 100644 --- a/packages/modules/alpha_ess/bat.py +++ b/packages/modules/alpha_ess/bat.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 +import logging import time from typing import Dict -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -10,6 +10,8 @@ from modules.common.fault_state import ComponentInfo from modules.common.store import get_bat_value_store +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -34,7 +36,6 @@ def __init__(self, device_id: int, self.component_info = ComponentInfo.from_component_config(component_config) def update(self, unit_id: int) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") # keine Unterschiede zwischen den Versionen with self.__tcp_client: @@ -44,7 +45,7 @@ def update(self, unit_id: int) -> None: current = self.__tcp_client.read_holding_registers(0x0101, ModbusDataType.INT_16, unit=unit_id) power = voltage * current * -1 / 100 - log.MainLogger().debug( + log.debug( "Alpha Ess Leistung[W]: %f, Speicher-Register: Spannung[V]: %f, Strom[A]: %f" % (power, voltage, current) ) diff --git a/packages/modules/alpha_ess/counter.py b/packages/modules/alpha_ess/counter.py index 017212f03..315e426b9 100644 --- a/packages/modules/alpha_ess/counter.py +++ b/packages/modules/alpha_ess/counter.py @@ -2,7 +2,6 @@ import time from typing import Callable, Dict -from helpermodules import log from modules.common import modbus from modules.common.component_state import CounterState from modules.common.fault_state import ComponentInfo @@ -31,8 +30,6 @@ def __init__(self, device_id: int, self.__device_config = device_config def update(self, unit_id: int): - log.MainLogger().debug( - "Komponente "+self.component_config["name"]+" auslesen.") time.sleep(0.1) factory_method = self.__get_values_factory() counter_state = factory_method(unit_id) diff --git a/packages/modules/alpha_ess/device.py b/packages/modules/alpha_ess/device.py index 329c3a1e4..2d24c8c8e 100644 --- a/packages/modules/alpha_ess/device.py +++ b/packages/modules/alpha_ess/device.py @@ -1,16 +1,18 @@ #!/usr/bin/env python3 """ Modul zum Auslesen von Alpha Ess Speichern, Zählern und Wechselrichtern. """ +import logging from typing import Dict, Union, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args -from modules.alpha_ess import bat -from modules.alpha_ess import counter -from modules.alpha_ess import inverter from modules.common import modbus from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext +from modules.alpha_ess import bat +from modules.alpha_ess import counter +from modules.alpha_ess import inverter + +log = logging.getLogger(__name__) def get_default_config() -> dict: @@ -38,7 +40,7 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, alpha_ess_component_classes] + self.components = {} # type: Dict[str, alpha_ess_component_classes] try: if device_config["configuration"]["source"] == 0: self.client = modbus.ModbusClient("192.168.193.125", 8899) @@ -46,12 +48,12 @@ def __init__(self, device_config: dict) -> None: self.client = modbus.ModbusClient(device_config["configuration"]["ip_address"], 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client, @@ -63,14 +65,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update(unit_id=default_unit_id) + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update(unit_id=default_unit_id) else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -98,8 +100,8 @@ def read_legacy(component_type: str, source: int, version: int, ip_address: str, component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('alpha_ess Version: ' + str(version)) - log.MainLogger().debug('alpha_ess IP-Adresse: ' + str(ip_address)) + log.debug('alpha_ess Version: ' + str(version)) + log.debug('alpha_ess IP-Adresse: ' + str(ip_address)) dev.update() diff --git a/packages/modules/alpha_ess/inverter.py b/packages/modules/alpha_ess/inverter.py index 51504fc3e..6608b3583 100644 --- a/packages/modules/alpha_ess/inverter.py +++ b/packages/modules/alpha_ess/inverter.py @@ -1,7 +1,5 @@ #!/usr/bin/env python3 - from typing import Dict -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import InverterState @@ -34,7 +32,6 @@ def __init__(self, device_id: int, self.__device_config = device_config def update(self, unit_id: int) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") reg_p = self.__version_factory() power = self.__get_power(unit_id, reg_p) @@ -63,5 +60,4 @@ def __get_power(self, unit: int, reg_p: int) -> Number: ] powers[0] = abs(powers[0]) power = sum(powers) * -1 - log.MainLogger().debug("Alpha Ess Leistung: "+str(power)+", WR-Register: " + str(powers)) return power diff --git a/packages/modules/batterx/counter.py b/packages/modules/batterx/counter.py index 50615779a..ba77fed11 100644 --- a/packages/modules/batterx/counter.py +++ b/packages/modules/batterx/counter.py @@ -1,10 +1,13 @@ #!/usr/bin/env python3 +import logging from typing import Dict, List + from modules.common.store import get_counter_value_store from modules.common.fault_state import ComponentInfo from modules.common.component_state import CounterState from modules.common import simcount -from helpermodules import log + +log = logging.getLogger(__name__) def get_default_config() -> dict: @@ -26,7 +29,6 @@ def __init__(self, device_id: int, component_config: dict) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self, resp: Dict) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") power = resp["2913"]["0"] frequency = resp["2914"]["0"] / 100 powers = self.__parse_list_values(resp, 2897) @@ -35,7 +37,7 @@ def update(self, resp: Dict) -> None: try: power_factors = self.__parse_list_values(resp, 2881) except KeyError: - log.MainLogger().debug( + log.debug( "Powerfaktor sollte laut Doku enthalten sein, ID 2881 kann aber nicht ermittelt werden.") power_factors = None topic_str = "openWB/set/system/device/{}/component/{}/".format( diff --git a/packages/modules/batterx/device.py b/packages/modules/batterx/device.py index e4dca658d..9af2179c6 100644 --- a/packages/modules/batterx/device.py +++ b/packages/modules/batterx/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Optional, Union, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common.abstract_device import AbstractDevice from modules.common.component_context import MultiComponentUpdateContext @@ -10,6 +10,8 @@ from modules.batterx import inverter from modules.common import req +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -38,7 +40,7 @@ def __init__(self, device_config: dict) -> None: try: self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] @@ -52,7 +54,7 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) + log.debug("Start device reading " + str(self._components)) if self._components: with MultiComponentUpdateContext(self._components): resp_json = req.get_http_session().get( @@ -61,7 +63,7 @@ def update(self) -> None: for component in self._components: self._components[component].update(resp_json) else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -83,7 +85,7 @@ def read_legacy( if bat == "speicher_batterx": dev = _add_component(dev, "bat", None) - log.MainLogger().debug('BatterX IP-Adresse: ' + ip_address) + log.debug('BatterX IP-Adresse: ' + ip_address) dev.update() diff --git a/packages/modules/batterx/inverter.py b/packages/modules/batterx/inverter.py index 9e5c7813d..141b0fef4 100644 --- a/packages/modules/batterx/inverter.py +++ b/packages/modules/batterx/inverter.py @@ -2,7 +2,6 @@ from typing import Dict -from helpermodules import log from modules.common import simcount from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo @@ -28,8 +27,6 @@ def __init__(self, device_id: int, component_config: dict) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self, resp: Dict) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") - power = resp["1634"]["0"] * -1 topic = "openWB/set/system/device/" + str(self.__device_id)+"/component/" + str(self.component_config["id"])+"/" diff --git a/packages/modules/carlo_gavazzi/counter.py b/packages/modules/carlo_gavazzi/counter.py index 64e029435..d0c7233f2 100644 --- a/packages/modules/carlo_gavazzi/counter.py +++ b/packages/modules/carlo_gavazzi/counter.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 from pymodbus.constants import Endian -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -31,15 +30,13 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo def update(self): unit = 1 - log.MainLogger().debug( - "Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: voltages = [val / 10 for val in self.__tcp_client.read_input_registers( 0x00, [ModbusDataType.INT_32] * 3, wordorder=Endian.Little, unit=unit)] powers = [val / 10 for val in self.__tcp_client.read_input_registers( 0x12, [ModbusDataType.INT_32] * 3, wordorder=Endian.Little, unit=unit)] power = sum(powers) - currents = [abs(val / 1000) for val in self.__tcp_client.read_input_registers( + currents = [(val / 1000) for val in self.__tcp_client.read_input_registers( 0x0C, [ModbusDataType.INT_32] * 3, wordorder=Endian.Little, unit=unit)] frequency = self.__tcp_client.read_input_registers(0x33, ModbusDataType.INT_16, unit=unit) / 10 if frequency > 100: @@ -62,5 +59,4 @@ def update(self): power=power, frequency=frequency ) - log.MainLogger().debug("Carlo Gavazzi Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/carlo_gavazzi/device.py b/packages/modules/carlo_gavazzi/device.py index 7f1478821..f6fb0430d 100644 --- a/packages/modules/carlo_gavazzi/device.py +++ b/packages/modules/carlo_gavazzi/device.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.carlo_gavazzi import counter from modules.common import modbus from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -26,18 +28,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, counter.CarloGavazziCounter] + self.components = {} # type: Dict[str, counter.CarloGavazziCounter] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client) else: raise Exception( @@ -46,14 +48,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -76,7 +78,7 @@ def read_legacy(component_type: str, ip_address: str, num: Optional[int] = None) component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('carlo gavazzi IP-Adresse: ' + str(ip_address)) + log.debug('carlo gavazzi IP-Adresse: ' + str(ip_address)) dev.update() diff --git a/packages/modules/common/abstract_chargepoint.py b/packages/modules/common/abstract_chargepoint.py new file mode 100644 index 000000000..215c0c3b8 --- /dev/null +++ b/packages/modules/common/abstract_chargepoint.py @@ -0,0 +1,23 @@ +from abc import abstractmethod + + +class AbstractChargepoint: + @abstractmethod + def __init__(self, config: dict) -> None: + pass + + @abstractmethod + def set_current(self, current: float) -> None: + pass + + @abstractmethod + def get_values(self) -> None: + pass + + @abstractmethod + def switch_phases(self, phases_to_use: int, duration: int) -> None: + pass + + @abstractmethod + def interrupt_cp(self, duration: int) -> None: + pass diff --git a/packages/modules/common/abstract_soc.py b/packages/modules/common/abstract_soc.py new file mode 100644 index 000000000..a0b94f0e9 --- /dev/null +++ b/packages/modules/common/abstract_soc.py @@ -0,0 +1,11 @@ +from abc import abstractmethod + + +class AbstractSoc: + @abstractmethod + def __init__(self, soc_config: dict) -> None: + pass + + @abstractmethod + def update(self, chargepoint_state) -> None: + pass diff --git a/packages/modules/common/component_context.py b/packages/modules/common/component_context.py index ecb854a24..2e481151b 100644 --- a/packages/modules/common/component_context.py +++ b/packages/modules/common/component_context.py @@ -1,14 +1,17 @@ +import logging import threading from typing import Optional, List, Union, Any, Dict from modules.common.fault_state import ComponentInfo, FaultState +log = logging.getLogger("soc."+__name__) + class SingleComponentUpdateContext: """ Wenn die Werte der Komponenten nicht miteinander verrechnet werden, sollen, auch wenn bei einer Komponente ein Fehler auftritt, alle anderen dennnoch ausgelesen werden. WR-Werte dienen nur statistischen Zwecken, ohne EVU-Werte ist aber keine Regelung möglich. Ein nicht antwortender WR soll dann nicht die Regelung verhindern. - for component in self._components: + for component in self.components: with SingleComponentUpdateContext(component): component.update() """ @@ -17,6 +20,7 @@ def __init__(self, component_info: ComponentInfo): self.__component_info = component_info def __enter__(self): + log.debug("Update Komponente ['"+self.__component_info.name+"']") return None def __exit__(self, exception_type, exception, exception_traceback) -> bool: @@ -28,8 +32,8 @@ class MultiComponentUpdateContext: """ Wenn die Werte der Komponenten miteinander verrechnet werden, muss, wenn bei einer Komponente ein Fehler auftritt, für alle Komponenten der Fehlerzustand gesetzt werden, da aufgrund der Abhängigkeiten für alle Module keine Werte ermittelt werden können. - with MultiComponentUpdateContext(self._components): - for component in self._components: + with MultiComponentUpdateContext(self.components): + for component in self.components: component.update() """ __thread_local = threading.local() @@ -43,6 +47,8 @@ def __enter__(self): if hasattr(self.__thread_local, "active_context"): raise Exception("Nesting MultiComponentUpdateContext is not supported") MultiComponentUpdateContext.__thread_local.active_context = self + log.debug("Update Komponenten " + + str([component.component_info.name for component in self.__device_components])) return None def __exit__(self, exception_type, exception, exception_traceback) -> bool: diff --git a/packages/modules/common/component_state.py b/packages/modules/common/component_state.py index bb571971e..7a3d1c6a7 100644 --- a/packages/modules/common/component_state.py +++ b/packages/modules/common/component_state.py @@ -1,4 +1,4 @@ -from typing import List +from typing import Dict, List, Optional from helpermodules.auto_str import auto_str @@ -31,10 +31,10 @@ def __init__( imported: float = 0, exported: float = 0, power: float = 0, - voltages: List[float] = None, - currents: List[float] = None, - powers: List[float] = None, - power_factors: List[float] = None, + voltages: Optional[List[float]] = None, + currents: Optional[List[float]] = None, + powers: Optional[List[float]] = None, + power_factors: Optional[List[float]] = None, frequency: float = 50, ): """Args: @@ -48,22 +48,21 @@ def __init__( frequency: actual grid frequency in Hz """ if voltages is None: - voltages = [230]*3 + voltages = [230.0]*3 self.voltages = voltages if powers is None: if currents is None: - powers = [0]*3 + powers = [0.0]*3 else: powers = [currents[i]*voltages[i] for i in range(0, 3)] self.powers = powers - if currents is None: - if powers: - currents = [powers[i]/voltages[i] for i in range(0, 3)] - else: - currents = [0]*3 + if currents is None and powers: + currents = [powers[i]/voltages[i] for i in range(0, 3)] + if currents and powers: + currents = [currents[i]*-1 if powers[i] < 0 and currents[i] > 0 else currents[i] for i in range(0, 3)] self.currents = currents if power_factors is None: - power_factors = [0]*3 + power_factors = [0.0]*3 self.power_factors = power_factors self.imported = imported self.exported = exported @@ -77,7 +76,7 @@ def __init__( self, counter: float, power: float, - currents: List[float] = None, + currents: Optional[List[float]] = None, ): """Args: counter: total energy in Wh @@ -85,7 +84,7 @@ def __init__( currents: actual currents for 3 phases in A """ if currents is None: - currents = [0]*3 + currents = [0.0]*3 self.currents = currents self.power = power self.counter = counter @@ -93,11 +92,42 @@ def __init__( @auto_str class CarState: - def __init__( - self, - soc: float, - ): + def __init__(self, soc: float, range: Optional[float] = None, soc_timestamp: str = ""): """Args: soc: actual state of charge in percent + range: actual range in km + soc_timestamp: timestamp of last request in %m/%d/%Y, %H:%M:%S """ self.soc = soc + self.range = range + self.soc_timestamp = soc_timestamp + + +class ChargepointState: + def __init__(self, + imported: float = 0, + exported: float = 0, + power: float = 0, + voltages: Optional[List[float]] = None, + currents: Optional[List[float]] = None, + power_factors: Optional[List[float]] = None, + phases_in_use: int = 1, + charge_state: bool = False, + plug_state: bool = False, + read_tag: Optional[Dict[str, str]] = None): + if voltages is None: + voltages = [0.0]*3 + self.voltages = voltages + if currents is None: + currents = [0.0]*3 + self.currents = currents + if power_factors is None: + power_factors = [0.0]*3 + self.power_factors = power_factors + self.imported = imported + self.exported = exported + self.power = power + self.phases_in_use = phases_in_use + self.charge_state = charge_state + self.plug_state = plug_state + self.read_tag = read_tag diff --git a/packages/modules/common/component_state_test.py b/packages/modules/common/component_state_test.py new file mode 100644 index 000000000..842bf2993 --- /dev/null +++ b/packages/modules/common/component_state_test.py @@ -0,0 +1,8 @@ +from modules.common.component_state import CounterState + +counter_state = CounterState(currents=[-5, -5, 5], powers=[-1150, -1150, 1150]) + + +def test_current_sign(): + assert vars(CounterState(currents=[-5, -5, 5], powers=[-1150, -1150, 1150])) == vars(counter_state) + assert vars(CounterState(currents=[5, 5, 5], powers=[-1150, -1150, 1150])) == vars(counter_state) diff --git a/packages/modules/common/component_type.py b/packages/modules/common/component_type.py new file mode 100644 index 000000000..05eae75e8 --- /dev/null +++ b/packages/modules/common/component_type.py @@ -0,0 +1,32 @@ +from enum import Enum + + +class ComponentType(Enum): + BAT = "bat" + CHARGEPOINT = "cp" + COUNTER = "counter" + INVERTER = "inverter" + + +def special_to_general_type_mapping(component_type: str) -> ComponentType: + if "bat" in component_type: + return ComponentType.BAT + elif "counter" in component_type: + return ComponentType.COUNTER + elif "inverter" in component_type: + return ComponentType.INVERTER + elif "cp" in component_type: + return ComponentType.CHARGEPOINT + else: + raise TypeError("Typ "+component_type+" konnte keinem bekannten Komponenten-Typ zugeordnet werden.") + + +def type_to_topic_mapping(component_type: str) -> str: + if "bat" in component_type: + return "bat" + elif "counter" in component_type: + return "counter" + elif "inverter" in component_type: + return "pv" + else: + return component_type diff --git a/packages/modules/common/fault_state.py b/packages/modules/common/fault_state.py index c897cc602..c67342373 100644 --- a/packages/modules/common/fault_state.py +++ b/packages/modules/common/fault_state.py @@ -1,11 +1,15 @@ -from enum import Enum +from enum import IntEnum +import logging import traceback from typing import Optional -from helpermodules import compatibility, exceptions, log, pub +from helpermodules import compatibility, exceptions, pub +from modules.common import component_type +log = logging.getLogger("soc."+__name__) -class FaultStateLevel(Enum): + +class FaultStateLevel(IntEnum): NO_ERROR = 0 WARNING = 1 ERROR = 2 @@ -29,14 +33,14 @@ def __init__(self, fault_str: str, fault_state: FaultStateLevel) -> None: def store_error(self, component_info: ComponentInfo) -> None: try: - if self.fault_state is not FaultStateLevel.NO_ERROR: - log.MainLogger().error(component_info.name + ": FaultState " + - str(self.fault_state) + ", FaultStr " + - self.fault_str + ", Traceback: \n" + - traceback.format_exc()) + if self.fault_state != FaultStateLevel.NO_ERROR: + log.error(component_info.name + ": FaultState " + + str(self.fault_state) + ", FaultStr " + + self.fault_str + ", Traceback: \n" + + traceback.format_exc()) ramdisk = compatibility.is_ramdisk_in_use() if ramdisk: - topic = self.__type_topic_mapping_comp(component_info.type) + topic = component_type.type_to_topic_mapping(component_info.type) prefix = "openWB/set/" + topic + "/" if component_info.id is not None: if topic == "lp": @@ -48,21 +52,13 @@ def store_error(self, component_info: ComponentInfo) -> None: pub.pub_single(prefix + "aultStr", self.fault_str) pub.pub_single(prefix + "aultState", self.fault_state.value) else: - topic = self.__type_topic_mapping(component_info.type) + topic = component_type.type_to_topic_mapping(component_info.type) pub.Pub().pub( "openWB/set/" + topic + "/" + str(component_info.id) + "/get/fault_str", self.fault_str) pub.Pub().pub( "openWB/set/" + topic + "/" + str(component_info.id) + "/get/fault_state", self.fault_state.value) except Exception: - log.MainLogger().exception("Fehler im Modul fault_state") - - def __type_topic_mapping(self, component_type: str) -> str: - if "counter" in component_type: - return "counter" - elif "inverter" in component_type: - return "pv" - else: - return component_type + log.exception("Fehler im Modul fault_state") def __type_topic_mapping_comp(self, component_type: str) -> str: if "bat" in component_type: diff --git a/packages/modules/common/modbus.py b/packages/modules/common/modbus.py index 8a0ade710..129117723 100644 --- a/packages/modules/common/modbus.py +++ b/packages/modules/common/modbus.py @@ -4,6 +4,7 @@ Das Modul baut eine Modbus-TCP-Verbindung auf. Es gibt verschiedene Funktionen, um die gelesenen Register zu formatieren. """ +import logging import struct from enum import Enum from typing import Callable, Iterable, Union, overload, List @@ -14,9 +15,10 @@ from pymodbus.payload import BinaryPayloadDecoder from urllib3.util import parse_url -from helpermodules import log from modules.common.fault_state import FaultState +log = logging.getLogger(__name__) + class ModbusDataType(Enum): UINT_8 = 8, "decode_8bit_uint" @@ -59,7 +61,7 @@ def __exit__(self, klass, value, traceback): def close_connection(self) -> None: try: - log.MainLogger().debug("Close Modbus TCP connection") + log.debug("Close Modbus TCP connection") self.delegate.close() except Exception as e: raise FaultState.error(__name__+" "+str(type(e))+" " + diff --git a/packages/modules/common/powerwall.py b/packages/modules/common/powerwall.py index d492bf0d5..b4f13c76a 100644 --- a/packages/modules/common/powerwall.py +++ b/packages/modules/common/powerwall.py @@ -10,7 +10,7 @@ from modules.common.store import RAMDISK_PATH COOKIE_FILE = RAMDISK_PATH / "powerwall_cookie.txt" -log = logging.getLogger("Powerwall") +log = logging.getLogger(__name__) class PowerwallHttpClient: diff --git a/packages/modules/common/req.py b/packages/modules/common/req.py index db76b886a..529823cda 100644 --- a/packages/modules/common/req.py +++ b/packages/modules/common/req.py @@ -1,11 +1,12 @@ +import logging from requests import Session -from helpermodules import log +log = logging.getLogger("soc."+__name__) def get_http_session() -> Session: session = Session() session.hooks['response'].append(lambda r, *args, **kwargs: r.raise_for_status()) - session.hooks['response'].append(lambda r, *args, **kwargs: log.MainLogger().debug("Get-Response: " + r.text)) + session.hooks['response'].append(lambda r, *args, **kwargs: log.debug("Get-Response: " + r.text)) return session diff --git a/packages/modules/common/simcount.py b/packages/modules/common/simcount.py index ba3754390..d50148ba2 100644 --- a/packages/modules/common/simcount.py +++ b/packages/modules/common/simcount.py @@ -1,17 +1,19 @@ """ Sim Count Berechnet die importierte und exportierte Leistung, wenn der Zähler / PV-Modul / Speicher diese nicht liefert. """ +import logging import os import paho.mqtt.client as mqtt import time import typing from helpermodules import compatibility -from helpermodules import log from helpermodules import pub from helpermodules.cli import run_using_positional_cli_args from modules.common.fault_state import FaultState +log = logging.getLogger(__name__) + def process_error(e): raise FaultState.error(__name__+" "+str(type(e))+" "+str(e)) from e @@ -97,15 +99,15 @@ def sim_count( # runs/simcount.py speichert das Zwischenergebnis des Exports negativ ab. counter_export_present = counter_export_present * -1 counter_export_previous = counter_export_present - log.MainLogger().debug("simcount Zwischenergebnisse letzte Berechnung: Import: " + - str(counter_import_previous) + " Export: " + str(counter_export_previous) + - " Leistung: " + str(power_previous)) + log.debug("simcount Zwischenergebnisse letzte Berechnung: Import: " + + str(counter_import_previous) + " Export: " + str(counter_export_previous) + + " Leistung: " + str(power_previous)) start_new = False write_ramdisk_file(prefix+'sec0', "%22.6f" % timestamp_present) write_ramdisk_file(prefix+'wh0', int(power_present)) if start_new: - log.MainLogger().debug("Neue Simulation starten.") + log.debug("Neue Simulation starten.") if prefix == "bezug": imported = get_existing_imports_exports('bezugkwh') exported = get_existing_imports_exports('einspeisungkwh') @@ -123,19 +125,19 @@ def sim_count( seconds_since_previous, power_previous, power_present) counter_export_present = counter_export_present + imp_exp[1] counter_import_present = counter_import_present + imp_exp[0] - log.MainLogger().debug( + log.debug( "simcount aufsummierte Energie: Bezug[Ws]: " + str(counter_import_present) + ", Einspeisung[Ws]: " + str(counter_export_present) ) energy_positive_kWh = counter_import_present / 3600 energy_negative_kWh = counter_export_present / 3600 - log.MainLogger().info( + log.info( "simcount Ergebnis: Bezug[Wh]: " + str(energy_positive_kWh) + ", Einspeisung[Wh]: " + str(energy_negative_kWh) ) topic = get_topic(prefix) - log.MainLogger().debug( + log.debug( "simcount Zwischenergebnisse aktuelle Berechnung: Import: " + str(counter_import_present) + " Export: " + str(counter_export_present) + " Leistung: " + str(power_present) ) @@ -154,7 +156,7 @@ def sim_count( def get_existing_imports_exports(file: str) -> float: if os.path.isfile('/var/www/html/openWB/ramdisk/'+file): value = float(read_ramdisk_file(file)) - log.MainLogger().info("Es wurde ein vorhandener Zählerstand in "+file+" gefunden: "+str(value)+"Wh") + log.info("Es wurde ein vorhandener Zählerstand in "+file+" gefunden: "+str(value)+"Wh") else: value = 0 return value @@ -179,13 +181,13 @@ def restore_value(self, value: str, prefix: str) -> float: try: result = float(self.temp) if value == "watt0pos": - log.MainLogger().info( + log.info( "loadvars read openWB/"+get_topic(self.prefix)+"/WHImported_temp from mosquito "+str(self.temp)) else: - log.MainLogger().info( + log.info( "loadvars read openWB/"+get_topic(self.prefix)+"/WHExport_temp from mosquito "+str(self.temp)) except ValueError: - log.MainLogger().info("Keine Werte auf dem Broker gefunden.") + log.info("Keine Werte auf dem Broker gefunden.") if prefix == "bezug": file = "bezugkwh" if value == "watt0pos" else "einspeisungkwh" elif prefix == "pv": @@ -197,7 +199,7 @@ def restore_value(self, value: str, prefix: str) -> float: self.temp = str(result) write_ramdisk_file(prefix+value, self.temp) except Exception: - log.MainLogger().exception("Fehler in der Restore-Klasse") + log.exception("Fehler in der Restore-Klasse") finally: return result @@ -211,7 +213,7 @@ def __on_connect(self, client, userdata, flags, rc): else: client.subscribe("openWB/"+topic+"/WHExport_temp", 2) except Exception: - log.MainLogger().exception("Fehler in der Restore-Klasse") + log.exception("Fehler in der Restore-Klasse") def __on_message(self, client, userdata, msg): """ wartet auf eingehende Topics. @@ -228,7 +230,7 @@ def __getserial(self): return line[10:26] return "0000000000000000" except Exception: - log.MainLogger().exception("Fehler in der Restore-Klasse") + log.exception("Fehler in der Restore-Klasse") class SimCount: @@ -263,7 +265,7 @@ def sim_count( counter_export_present = int(data["present_exported"]) else: counter_export_present = 0 - log.MainLogger().debug( + log.debug( "Fortsetzen der Simulation: Importzähler: " + str(counter_import_present)+"Ws, Export-Zähler: " + str(counter_export_present) + "Ws" ) @@ -272,28 +274,29 @@ def sim_count( pub.Pub().pub(topic+"simulation/power_present", power_present) if start_new: - log.MainLogger().debug("Neue Simulation") + log.debug("Neue Simulation") pub.Pub().pub(topic+"simulation/present_imported", 0) pub.Pub().pub(topic+"simulation/present_exported", 0) return 0, 0 else: # timestamp_previous = timestamp_previous + 1 # do not increment time if calculating areas! seconds_since_previous = timestamp_present - timestamp_previous - imp_exp = calculate_import_export(seconds_since_previous, power_previous, power_present) + imp_exp = calculate_import_export( + seconds_since_previous, power_previous, power_present) counter_export_present = counter_export_present + imp_exp[1] counter_import_present = counter_import_present + imp_exp[0] - log.MainLogger().debug( + log.debug( "simcount aufsummierte Energie: Bezug[Ws]: " + str(counter_import_present) + ", Einspeisung[Ws]: " + str(counter_export_present) ) energy_positive_kWh = counter_import_present / 3600 energy_negative_kWh = counter_export_present / 3600 - log.MainLogger().info( + log.info( "simcount Ergebnis: Bezug[Wh]: " + str(energy_positive_kWh) + ", Einspeisung[Wh]: " + str(energy_negative_kWh) ) - log.MainLogger().debug( + log.debug( "simcount Zwischenergebnisse aktuelle Berechnung: Import: " + str(counter_import_present) + " Export: " + str(counter_export_present) + " Power: " + str(power_present) ) @@ -311,7 +314,7 @@ def calculate_import_export( seconds_since_previous: Number, power1: Number, power2: Number ) -> typing.Tuple[Number, Number]: try: - log.MainLogger().debug( + log.debug( "simcount Berechnungsgrundlage: vergangene Zeit [s]" + str(seconds_since_previous) + ", vorherige Leistung[W]: " + str(power1) + ", aktuelle Leistung[W]: " + str(power2) ) @@ -323,12 +326,13 @@ def calculate_import_export( def energy_function(seconds): return .5 * gradient * seconds ** 2 + power_low * seconds energy_total = energy_function(seconds_since_previous) - log.MainLogger().debug("simcount Gesamtenergie im Zeitintervall: "+str(energy_total)) + log.debug("simcount Gesamtenergie im Zeitintervall: "+str(energy_total)) if power_low < 0 < power_high: # Berechnung der Fläche im vierten Quadranten -> Export power_zero_seconds = -power_low / gradient energy_exported = energy_function(power_zero_seconds) - log.MainLogger().debug("simcount exportierte Energie im Zeitintervall: "+str(energy_exported)) + log.debug( + "simcount exportierte Energie im Zeitintervall: "+str(energy_exported)) # Betragsmäßige Gesamtfläche: oberhalb der x-Achse = Import, unterhalb der x-Achse: Export return energy_total - energy_exported, energy_exported * -1 return (energy_total, 0) if energy_total >= 0 else (0, -energy_total) diff --git a/packages/modules/common/store/__init__.py b/packages/modules/common/store/__init__.py index 2c394a514..be1c60814 100644 --- a/packages/modules/common/store/__init__.py +++ b/packages/modules/common/store/__init__.py @@ -1,6 +1,7 @@ from modules.common.store._api import ValueStore from modules.common.store._battery import get_bat_value_store from modules.common.store._car import get_car_value_store +from modules.common.store._chargepoint import get_chargepoint_value_store from modules.common.store._counter import get_counter_value_store from modules.common.store._inverter import get_inverter_value_store from modules.common.store.ramdisk.io import ramdisk_write, ramdisk_read, ramdisk_read_float, ramdisk_read_int, \ diff --git a/packages/modules/common/store/_api.py b/packages/modules/common/store/_api.py index 263aa2f84..b1db71197 100644 --- a/packages/modules/common/store/_api.py +++ b/packages/modules/common/store/_api.py @@ -3,7 +3,7 @@ from typing import Generic, TypeVar T = TypeVar("T") -log = logging.getLogger("ValueStore") +log = logging.getLogger("soc."+__name__) class ValueStore(Generic[T]): diff --git a/packages/modules/common/store/_broker.py b/packages/modules/common/store/_broker.py index b055ccb4f..03ca98642 100644 --- a/packages/modules/common/store/_broker.py +++ b/packages/modules/common/store/_broker.py @@ -7,9 +7,10 @@ def pub_to_broker(topic: str, value, digits: Union[int, None] = None) -> None: rounding = get_rounding_function_by_digits(digits) try: - if isinstance(value, list): - Pub().pub(topic, [rounding(v) for v in value]) - else: - Pub().pub(topic, rounding(value)) + if value is not None: + if isinstance(value, list): + Pub().pub(topic, [rounding(v) for v in value]) + else: + Pub().pub(topic, rounding(value)) except Exception as e: process_error(e) diff --git a/packages/modules/common/store/_car.py b/packages/modules/common/store/_car.py index 08e3187d0..faa0e0b17 100644 --- a/packages/modules/common/store/_car.py +++ b/packages/modules/common/store/_car.py @@ -1,7 +1,6 @@ -from helpermodules import compatibility from modules.common.component_state import CarState from modules.common.store import ValueStore -from modules.common.store._broker import pub_to_broker +from modules.common.store._api import LoggingValueStore from modules.common.store.ramdisk import files @@ -10,18 +9,8 @@ def __init__(self, charge_point: int): self.file = files.charge_points[charge_point - 1].soc def set(self, state: CarState) -> None: - self.file.write(state.soc) - - -class CarValueStoreBroker(ValueStore[CarState]): - def __init__(self, vehicle_id: int): - self.topic = "openWB/set/ev/{}/get/counter".format(vehicle_id) - - def set(self, state: CarState) -> None: - pub_to_broker(self.topic, state.soc) + self.file.write(int(state.soc)) def get_car_value_store(id: int) -> ValueStore[CarState]: - if compatibility.is_ramdisk_in_use(): - return CarValueStoreRamdisk(id) - return CarValueStoreBroker(id) + return LoggingValueStore(CarValueStoreRamdisk(id)) diff --git a/packages/modules/common/store/_chargepoint.py b/packages/modules/common/store/_chargepoint.py new file mode 100644 index 000000000..7f43575eb --- /dev/null +++ b/packages/modules/common/store/_chargepoint.py @@ -0,0 +1,25 @@ +from modules.common.component_state import ChargepointState +from modules.common.store import ValueStore +from modules.common.store._broker import pub_to_broker + + +class ChargepointValueStoreBroker(ValueStore[ChargepointState]): + def __init__(self, cp_id: int): + self.num = cp_id + + def set(self, state: ChargepointState) -> None: + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/voltages", state.voltages, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/currents", state.currents, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/power_factors", state.power_factors, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/imported", state.imported, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/exported", state.exported, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/power", state.power, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/phases_in_use", state.phases_in_use, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/charge_state", state.charge_state, 2) + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/plug_state", state.plug_state, 2) + if state.read_tag: + pub_to_broker("openWB/set/chargepoint/" + str(self.num) + "/get/read_tag", state.read_tag, 2) + + +def get_chargepoint_value_store(id: int) -> ValueStore[ChargepointState]: + return ChargepointValueStoreBroker(id) diff --git a/packages/modules/common/store/_counter.py b/packages/modules/common/store/_counter.py index 92245390b..e8afa14c3 100644 --- a/packages/modules/common/store/_counter.py +++ b/packages/modules/common/store/_counter.py @@ -17,7 +17,7 @@ def set(self, counter_state: CounterState): files.evu.power_factors.write(counter_state.power_factors) files.evu.energy_import.write(counter_state.imported) files.evu.energy_export.write(counter_state.exported) - files.evu.power_import.write(counter_state.power) + files.evu.power_import.write(int(counter_state.power)) files.evu.frequency.write(counter_state.frequency) except Exception as e: process_error(e) diff --git a/packages/modules/discovergy/api_test.py b/packages/modules/discovergy/api_test.py old mode 100755 new mode 100644 diff --git a/packages/modules/discovergy/device.py b/packages/modules/discovergy/device.py index 42157e488..924c0bf5a 100644 --- a/packages/modules/discovergy/device.py +++ b/packages/modules/discovergy/device.py @@ -27,7 +27,7 @@ def get_default_config(id: int = 0, **configuration) -> dict: "inverter": inverter.create_component } -log = logging.getLogger("Discovergy") +log = logging.getLogger(__name__) class Device(AbstractDevice): @@ -35,7 +35,7 @@ def __init__(self, device_config: dict) -> None: settings = device_config["configuration"] self.__session = get_http_session() self.__session.auth = (settings["user"], settings["password"]) - self._components = [] # type: List[DiscovergyComponent] + self.components = [] # type: List[DiscovergyComponent] def add_component(self, component_config: dict) -> None: try: @@ -44,10 +44,10 @@ def add_component(self, component_config: dict) -> None: raise Exception( "Unknown component type <%s>, known types are: <%s>", e, ','.join(component_registry.keys()) ) - self._components.append(factory(component_config)) + self.components.append(factory(component_config)) def update(self) -> None: - for component in self._components: + for component in self.components: with SingleComponentUpdateContext(component.component_info): component.update(self.__session) diff --git a/packages/modules/fronius/bat.py b/packages/modules/fronius/bat.py index 6305282ec..6632771fd 100644 --- a/packages/modules/fronius/bat.py +++ b/packages/modules/fronius/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import req from modules.common import simcount from modules.common.component_state import BatState @@ -30,7 +29,6 @@ def __init__(self, device_id: int, component_config: dict, device_config: Froniu self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") meter_id = str(self.component_config["configuration"]["meter_id"]) resp_json = req.get_http_session().get( @@ -64,6 +62,4 @@ def update(self) -> None: imported=imported, exported=exported ) - - log.MainLogger().debug("Fronius Battery Leistung[W]: " + str(bat_state.power)) self.__store.set(bat_state) diff --git a/packages/modules/fronius/counter_s0.py b/packages/modules/fronius/counter_s0.py index 9df3e7eee..f65247952 100644 --- a/packages/modules/fronius/counter_s0.py +++ b/packages/modules/fronius/counter_s0.py @@ -5,7 +5,6 @@ from modules.common import req from modules.common import simcount from modules.fronius.abstract_config import FroniusConfiguration -from helpermodules import log def get_default_config() -> dict: @@ -28,8 +27,6 @@ def __init__(self, device_id: int, component_config: dict, device_config: Froniu self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") - session = req.get_http_session() response = session.get( 'http://'+self.device_config.ip_address+'/solar_api/v1/GetPowerFlowRealtimeData.fcgi', @@ -52,6 +49,4 @@ def update(self) -> None: exported=exported, power=power ) - - log.MainLogger().debug("Fronius S0 Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/fronius/counter_sm.py b/packages/modules/fronius/counter_sm.py index 59c49e199..19d4758e4 100644 --- a/packages/modules/fronius/counter_sm.py +++ b/packages/modules/fronius/counter_sm.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 +import logging from requests import Session from typing import Tuple -from helpermodules import log from modules.common import req from modules.common import simcount from modules.common.component_state import CounterState @@ -10,6 +10,8 @@ from modules.common.store import get_counter_value_store from modules.fronius.abstract_config import FroniusConfiguration, MeterLocation +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -34,7 +36,6 @@ def __init__(self, device_id: int, component_config: dict, device_config: Froniu self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") session = req.get_http_session() variant = self.component_config["configuration"]["variant"] @@ -54,8 +55,6 @@ def update(self) -> None: data=self.simulation, prefix="bezug" ) - - log.MainLogger().debug("Fronius SM Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) def __update_variant_0_1(self, session: Session) -> CounterState: @@ -81,7 +80,7 @@ def __update_variant_0_1(self, session: Session) -> CounterState: response_json_id = response.json()["Body"]["Data"] meter_location = MeterLocation.get(response_json_id["Meter_Location_Current"]) - log.MainLogger().debug("Einbauort: "+str(meter_location)) + log.debug("Einbauort: "+str(meter_location)) powers = [response_json_id["PowerReal_P_Phase_"+str(num)] for num in range(1, 4)] if meter_location == MeterLocation.load: @@ -117,7 +116,7 @@ def __update_variant_2(self, session: Session) -> CounterState: response_json_id = dict(response.json()["Body"]["Data"]).get(meter_id) meter_location = MeterLocation.get(response_json_id["SMARTMETER_VALUE_LOCATION_U16"]) - log.MainLogger().debug("Einbauort: "+str(meter_location)) + log.debug("Einbauort: "+str(meter_location)) powers = [response_json_id["SMARTMETER_POWERACTIVE_MEAN_0"+str(num)+"_F64"] for num in range(1, 4)] if meter_location == MeterLocation.load: diff --git a/packages/modules/fronius/device.py b/packages/modules/fronius/device.py index 1746e9488..de0d56a5a 100644 --- a/packages/modules/fronius/device.py +++ b/packages/modules/fronius/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Optional, Union, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common.store import get_inverter_value_store from modules.common.abstract_device import AbstractDevice @@ -12,6 +12,8 @@ from modules.fronius import inverter from modules.fronius.abstract_config import Fronius +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -37,18 +39,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, fronius_component_classes] + self.components = {} # type: Dict[str, fronius_component_classes] try: self.config = device_config \ if isinstance(device_config, Fronius) \ else Fronius.from_dict(device_config) except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( self.config.id, component_config, self.config.configuration) else: raise Exception( @@ -57,13 +59,13 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - with MultiComponentUpdateContext(self._components): - for component in self._components: - self._components[component].update() + log.debug("Start device reading " + str(self.components)) + if self.components: + with MultiComponentUpdateContext(self.components): + for component in self.components: + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.config.name + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -101,7 +103,7 @@ def read_legacy( component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Fronius IP-Adresse: ' + ip_address) + log.debug('Fronius IP-Adresse: ' + ip_address) if component_type == "bat" or "counter" in component_type: dev.update() diff --git a/packages/modules/fronius/inverter.py b/packages/modules/fronius/inverter.py index 1ec736c5e..e1cd6a86d 100644 --- a/packages/modules/fronius/inverter.py +++ b/packages/modules/fronius/inverter.py @@ -1,8 +1,6 @@ #!/usr/bin/env python3 - import requests -from helpermodules import log from modules.common import req from modules.common import simcount from modules.common.component_state import InverterState @@ -31,7 +29,6 @@ def __init__(self, device_id: int, component_config: dict, device_config: Froniu self.component_info = ComponentInfo.from_component_config(component_config) def read_power(self) -> float: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") # Rückgabewert ist die aktuelle Wirkleistung in [W]. try: params = ( diff --git a/packages/modules/good_we/bat.py b/packages/modules/good_we/bat.py index c9a4d233e..4e5f6b6ed 100644 --- a/packages/modules/good_we/bat.py +++ b/packages/modules/good_we/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules.log import MainLogger from modules.common import modbus from modules.common.component_state import BatState from modules.common.modbus import ModbusDataType @@ -25,8 +24,6 @@ def __init__(self, modbus_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") - with self.__tcp_client: power = self.__tcp_client.read_holding_registers(35183, ModbusDataType.INT_16, unit=self.__modbus_id)*-1 soc = self.__tcp_client.read_holding_registers(37007, ModbusDataType.UINT_16, unit=self.__modbus_id) diff --git a/packages/modules/good_we/counter.py b/packages/modules/good_we/counter.py index bb2016e47..00ef5c1ab 100644 --- a/packages/modules/good_we/counter.py +++ b/packages/modules/good_we/counter.py @@ -1,6 +1,4 @@ #!/usr/bin/env python3 - -from helpermodules.log import MainLogger from modules.common import modbus from modules.common.component_state import CounterState from modules.common.fault_state import ComponentInfo @@ -26,7 +24,6 @@ def __init__(self, modbus_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power_factors = [ val / 1000 for val in self.__tcp_client.read_holding_registers(36010, diff --git a/packages/modules/good_we/device.py b/packages/modules/good_we/device.py index 59adf1d1a..b269b3b31 100644 --- a/packages/modules/good_we/device.py +++ b/packages/modules/good_we/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, List, Union, Optional -from helpermodules.log import MainLogger from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -10,6 +10,8 @@ from modules.good_we import counter from modules.good_we import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -35,18 +37,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, good_we_component_classes] + self.components = {} # type: Dict[str, good_we_component_classes] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["configuration"]["id"], component_config, self.client)) else: raise Exception( @@ -55,14 +57,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -88,8 +90,8 @@ def read_legacy(component_type: str, ip_address: str, id: int, num: Optional[int component_config["id"] = num dev.add_component(component_config) - MainLogger().debug('GoodWe IP-Adresse: ' + ip_address) - MainLogger().debug('GoodWe ID: ' + str(id)) + log.debug('GoodWe IP-Adresse: ' + ip_address) + log.debug('GoodWe ID: ' + str(id)) dev.update() dev.client.close_connection() diff --git a/packages/modules/good_we/inverter.py b/packages/modules/good_we/inverter.py index 60fcf2ba8..519eb062d 100644 --- a/packages/modules/good_we/inverter.py +++ b/packages/modules/good_we/inverter.py @@ -1,6 +1,4 @@ #!/usr/bin/env python3 - -from helpermodules.log import MainLogger from modules.common import modbus from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo @@ -26,7 +24,6 @@ def __init__(self, modbus_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = sum([self.__tcp_client.read_holding_registers(reg, ModbusDataType.UINT_32, unit=self.__modbus_id) for reg in [35105, 35109, 35113, 35117]]) * -1 diff --git a/packages/modules/http/api.py b/packages/modules/http/api.py index 850fb6da9..ca54032fd 100644 --- a/packages/modules/http/api.py +++ b/packages/modules/http/api.py @@ -1,9 +1,11 @@ import functools +import logging from typing import Callable, Optional -from helpermodules import log from modules.common import req +log = logging.getLogger(__name__) + def request_value(url: str) -> Optional[float]: if "none" == url: @@ -11,7 +13,7 @@ def request_value(url: str) -> Optional[float]: else: response = req.get_http_session().get(url, timeout=5) response.encoding = 'utf-8' - log.MainLogger().debug("Antwort auf "+str(url)+" "+str(response.text)) + log.debug("Antwort auf "+str(url)+" "+str(response.text)) return float(response.text.replace("\n", "")) diff --git a/packages/modules/http/bat.py b/packages/modules/http/bat.py index 9a9962a9e..50f36a815 100644 --- a/packages/modules/http/bat.py +++ b/packages/modules/http/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import simcount from modules.common.component_state import BatState from modules.common.fault_state import ComponentInfo @@ -36,8 +35,6 @@ def __init__(self, device_id: int, component_config: dict, domain: str) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") - imported = self.__get_imported() exported = self.__get_exported() power = self.__get_power() diff --git a/packages/modules/http/counter.py b/packages/modules/http/counter.py index e94708b80..16fca0a1b 100644 --- a/packages/modules/http/counter.py +++ b/packages/modules/http/counter.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import simcount from modules.common.component_state import CounterState from modules.common.fault_state import ComponentInfo @@ -42,8 +41,6 @@ def __init__(self, device_id: int, component_config: dict, domain: str) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") - imported = self.__get_imported() exported = self.__get_exported() power = self.__get_power() diff --git a/packages/modules/http/device.py b/packages/modules/http/device.py index 8a34b6546..b846f9f8e 100644 --- a/packages/modules/http/device.py +++ b/packages/modules/http/device.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 +import logging import re from typing import Dict, Union, List from urllib3.util import parse_url -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext @@ -12,6 +12,8 @@ from modules.http import counter from modules.http import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -37,7 +39,7 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, http_component_classes] + self.components = {} # type: Dict[str, http_component_classes] try: self.device_config = device_config port = self.device_config["configuration"]["port"] @@ -46,13 +48,12 @@ def __init__(self, device_config: dict) -> None: if port is not None: self.domain = self.domain + ":" + str(port) except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - - self._components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.domain) else: raise Exception( @@ -61,14 +62,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -96,7 +97,7 @@ def create_paths_dict(**kwargs): def run_device_legacy(device_config: dict, component_config: dict): device = Device(device_config) device.add_component(component_config) - log.MainLogger().debug( + log.debug( 'Http Konfiguration: ' + str(device_config["configuration"]) + str(component_config["configuration"]) ) device.update() diff --git a/packages/modules/http/inverter.py b/packages/modules/http/inverter.py index 5a80a0740..f782b5ac4 100644 --- a/packages/modules/http/inverter.py +++ b/packages/modules/http/inverter.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -from helpermodules import log, compatibility +from helpermodules import compatibility from modules.common import simcount from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo @@ -33,8 +33,6 @@ def __init__(self, device_id: int, component_config: dict, domain: str) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") - power = (-self.__get_power() if compatibility.is_ramdisk_in_use() else self.__get_power()) counter = self.__get_counter() if counter is None: diff --git a/packages/modules/huawei/bat.py b/packages/modules/huawei/bat.py index ac0b1e405..ab1676f94 100644 --- a/packages/modules/huawei/bat.py +++ b/packages/modules/huawei/bat.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import time -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -31,8 +30,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") - time.sleep(0.1) power = self.__tcp_client.read_holding_registers(37765, ModbusDataType.INT_32, unit=self.__modbus_id) time.sleep(0.1) diff --git a/packages/modules/huawei/counter.py b/packages/modules/huawei/counter.py index f29a6b70a..196ecf2df 100644 --- a/packages/modules/huawei/counter.py +++ b/packages/modules/huawei/counter.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import time -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -31,7 +30,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") time.sleep(0.1) power = self.__tcp_client.read_holding_registers(37113, ModbusDataType.INT_32, unit=self.__modbus_id) * -1 time.sleep(0.1) diff --git a/packages/modules/huawei/device.py b/packages/modules/huawei/device.py index 1bac4bf99..9f24d0bbe 100644 --- a/packages/modules/huawei/device.py +++ b/packages/modules/huawei/device.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 +import logging import time from typing import Dict, Union, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -11,6 +11,8 @@ from modules.huawei import counter from modules.huawei import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -35,7 +37,7 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, huawei_component_classes] + self.components = {} # type: Dict[str, huawei_component_classes] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) @@ -43,12 +45,12 @@ def __init__(self, device_config: dict) -> None: time.sleep(7) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+component_type] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+component_type] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client, self.device_config["configuration"]["modbus_id"])) @@ -59,14 +61,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -84,7 +86,7 @@ def read_legacy(ip_address: str, modbus_id: int, read_counter: str = "False", re components_to_read.append("counter") if read_battery.lower() == "true": components_to_read.append("bat") - log.MainLogger().debug("components to read: " + str(components_to_read)) + log.debug("components to read: " + str(components_to_read)) device_config = get_default_config() device_config["configuration"]["ip_address"] = ip_address @@ -105,8 +107,8 @@ def read_legacy(ip_address: str, modbus_id: int, read_counter: str = "False", re component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Huawei IP-Adresse: ' + ip_address) - log.MainLogger().debug('Huawei Modbus-ID: ' + str(modbus_id)) + log.debug('Huawei IP-Adresse: ' + ip_address) + log.debug('Huawei Modbus-ID: ' + str(modbus_id)) dev.update() diff --git a/packages/modules/huawei/inverter.py b/packages/modules/huawei/inverter.py index 5f31240da..89e532ecf 100644 --- a/packages/modules/huawei/inverter.py +++ b/packages/modules/huawei/inverter.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import time -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import InverterState @@ -31,7 +30,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") time.sleep(0.1) power = self.__tcp_client.read_holding_registers(32064, ModbusDataType.INT_32, unit=self.__modbus_id) * -1 diff --git a/packages/modules/janitza/counter.py b/packages/modules/janitza/counter.py index d90354db7..4f504f167 100644 --- a/packages/modules/janitza/counter.py +++ b/packages/modules/janitza/counter.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -28,7 +27,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_holding_registers(19026, ModbusDataType.FLOAT_32, unit=1) @@ -47,5 +45,4 @@ def update(self): exported=exported, power=power ) - log.MainLogger().debug("Janitza Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/janitza/device.py b/packages/modules/janitza/device.py index e802a05ab..b6db799fb 100644 --- a/packages/modules/janitza/device.py +++ b/packages/modules/janitza/device.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext from modules.janitza import counter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -26,18 +28,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, counter.JanitzaCounter] + self.components = {} # type: Dict[str, counter.JanitzaCounter] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client)) else: raise Exception( @@ -46,14 +48,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -76,7 +78,7 @@ def read_legacy(component_type: str, ip_address: str, num: Optional[int] = None) component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Janitza IP-Adresse: ' + ip_address) + log.debug('Janitza IP-Adresse: ' + ip_address) dev.update() diff --git a/packages/modules/json/bat.py b/packages/modules/json/bat.py index ddcea78ab..8f5cc0b54 100644 --- a/packages/modules/json/bat.py +++ b/packages/modules/json/bat.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import jq -from helpermodules import log from modules.common import simcount from modules.common.component_state import BatState from modules.common.fault_state import ComponentInfo @@ -32,7 +31,6 @@ def __init__(self, device_id: int, component_config: dict) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self, response) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") config = self.component_config["configuration"] power = jq.compile(config["jq_power"]).input(response).first() diff --git a/packages/modules/json/counter.py b/packages/modules/json/counter.py index 267e54ab3..29dde4b8f 100644 --- a/packages/modules/json/counter.py +++ b/packages/modules/json/counter.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import jq -from helpermodules import log from modules.common import simcount from modules.common.component_state import CounterState from modules.common.fault_state import ComponentInfo @@ -31,7 +30,6 @@ def __init__(self, device_id: int, component_config: dict) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self, response): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") config = self.component_config["configuration"] power = jq.compile(config["jq_power"]).input(response).first() diff --git a/packages/modules/json/device.py b/packages/modules/json/device.py index 08f4e9b02..8f916ce4b 100644 --- a/packages/modules/json/device.py +++ b/packages/modules/json/device.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 +import logging from typing import Dict, List, Union, Optional from urllib3.util import parse_url -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import req from modules.common.abstract_device import AbstractDevice @@ -11,6 +11,8 @@ from modules.json import counter from modules.json import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -36,7 +38,7 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, json_component_classes] + self.components = {} # type: Dict[str, json_component_classes] try: self.device_config = device_config port = self.device_config["configuration"]["port"] @@ -44,12 +46,12 @@ def __init__(self, device_config: dict) -> None: "://" + self.device_config["configuration"]["domain"] + \ ":" + str(port) if port else "" except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config) else: raise Exception( @@ -58,14 +60,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - with MultiComponentUpdateContext(self._components): + log.debug("Start device reading " + str(self.components)) + if self.components: + with MultiComponentUpdateContext(self.components): response = req.get_http_session().get(self.domain, timeout=5) - for component in self._components: - self._components[component].update(response.json()) + for component in self.components: + self.components[component].update(response.json()) else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) diff --git a/packages/modules/json/inverter.py b/packages/modules/json/inverter.py index 02590f415..1adccaaae 100644 --- a/packages/modules/json/inverter.py +++ b/packages/modules/json/inverter.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import jq -from helpermodules import log from modules.common import simcount from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo @@ -30,7 +29,6 @@ def __init__(self, device_id: int, component_config: dict) -> None: self.component_info = ComponentInfo.from_component_config(component_config) def update(self, response) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") config = self.component_config["configuration"] power = float(jq.compile(config["jq_power"]).input(response).first()) diff --git a/packages/modules/openwb_bat_kit/device.py b/packages/modules/openwb_bat_kit/device.py index ddf0a6f4f..01c831580 100644 --- a/packages/modules/openwb_bat_kit/device.py +++ b/packages/modules/openwb_bat_kit/device.py @@ -1,11 +1,11 @@ import logging -from typing import Dict, Optional, List -from helpermodules.cli import run_using_positional_cli_args -from modules.common.abstract_device import AbstractDevice -from modules.common.component_context import SingleComponentUpdateContext -from modules.openwb_bat_kit import bat from modules.common import modbus +from modules.openwb_bat_kit import bat +from modules.common.component_context import SingleComponentUpdateContext +from modules.common.abstract_device import AbstractDevice +from helpermodules.cli import run_using_positional_cli_args +from typing import Dict, Optional, List log = logging.getLogger(__name__) @@ -22,25 +22,25 @@ def get_default_config() -> dict: class Device(AbstractDevice): def __init__(self, device_config: dict) -> None: self.device_config = device_config - self._components = {} # type: Dict[str, bat.BatKit] + self.components = {} # type: Dict[str, bat.BatKit] self.client = modbus.ModbusClient("192.168.193.19", 8899) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type == "bat": - self._components["component"+str(component_config["id"])] = bat.BatKit( + self.components["component"+str(component_config["id"])] = bat.BatKit( self.device_config["id"], component_config, self.client) else: raise Exception( "illegal component type " + component_type) def update(self) -> None: - log.debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: log.warning( self.device_config["name"] + diff --git a/packages/modules/openwb_flex/bat.py b/packages/modules/openwb_flex/bat.py index 4db191d5c..703d1b07c 100644 --- a/packages/modules/openwb_flex/bat.py +++ b/packages/modules/openwb_flex/bat.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -39,7 +38,6 @@ def __init__(self, device_id: int, component_config: dict, self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Start kit reading") # TCP-Verbindung schließen möglichst bevor etwas anderes gemacht wird, um im Fehlerfall zu verhindern, # dass offene Verbindungen den Modbus-Adapter blockieren. with self.__tcp_client: @@ -63,5 +61,4 @@ def update(self): exported=exported, power=power ) - log.MainLogger().debug("Speicher-Kit Leistung[W]: " + str(bat_state.power)) self.__store.set(bat_state) diff --git a/packages/modules/openwb_flex/counter.py b/packages/modules/openwb_flex/counter.py index be192b6cf..62734657e 100644 --- a/packages/modules/openwb_flex/counter.py +++ b/packages/modules/openwb_flex/counter.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -39,7 +38,6 @@ def __init__(self, device_id: int, component_config: dict, self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Start kit reading") # TCP-Verbindung schließen möglichst bevor etwas anderes gemacht wird, um im Fehlerfall zu verhindern, # dass offene Verbindungen den Modbus-Adapter blockieren. with self.__tcp_client: @@ -52,7 +50,7 @@ def update(self): imported = self.__client.get_imported() exported = self.__client.get_exported() else: - currents = list(map(abs, self.__client.get_currents())) + currents = self.__client.get_currents() if isinstance(self.__client, Mpm3pm): currents = [powers[i] / voltages[i] for i in range(3)] @@ -78,5 +76,4 @@ def update(self): power=power, frequency=frequency ) - log.MainLogger().debug("EVU-Kit Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/openwb_flex/device.py b/packages/modules/openwb_flex/device.py index f972ee394..87d9829c4 100644 --- a/packages/modules/openwb_flex/device.py +++ b/packages/modules/openwb_flex/device.py @@ -1,6 +1,6 @@ +import logging from typing import Dict, Union, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -9,6 +9,8 @@ from modules.openwb_flex import counter from modules.openwb_flex import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -30,19 +32,19 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, Union[counter.EvuKitFlex, inverter.PvKitFlex]] + self.components = {} # type: Dict[str, Union[counter.EvuKitFlex, inverter.PvKitFlex]] try: self.device_config = device_config ip_address = device_config["configuration"]["ip_address"] port = device_config["configuration"]["port"] self.client = modbus.ModbusClient(ip_address, port) except Exception: - log.MainLogger().exception("Fehler im Modul " + device_config["name"]) + log.exception("Fehler im Modul " + device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client)) else: raise Exception("illegal component type " + component_type + @@ -50,14 +52,14 @@ def add_component(self, component_config: dict) -> None: ','.join(self.COMPONENT_TYPE_TO_CLASS.keys())) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -71,7 +73,7 @@ def read_legacy(component_type: str, version: int, ip_address: str, port: int, i "counter": counter, "inverter": inverter } - log.MainLogger().debug('Start reading flex') + log.debug('Start reading flex') device_config = get_default_config() device_config["configuration"]["ip_address"] = ip_address device_config["configuration"]["port"] = port @@ -89,10 +91,10 @@ def read_legacy(component_type: str, version: int, ip_address: str, port: int, i component_config["configuration"]["id"] = id dev.add_component(component_config) - log.MainLogger().debug('openWB flex Version: ' + str(version)) - log.MainLogger().debug('openWB flex-Kit IP-Adresse: ' + ip_address) - log.MainLogger().debug('openWB flex-Kit Port: ' + str(port)) - log.MainLogger().debug('openWB flex-Kit ID: ' + str(id)) + log.debug('openWB flex Version: ' + str(version)) + log.debug('openWB flex-Kit IP-Adresse: ' + ip_address) + log.debug('openWB flex-Kit Port: ' + str(port)) + log.debug('openWB flex-Kit ID: ' + str(id)) dev.update() diff --git a/packages/modules/openwb_flex/inverter.py b/packages/modules/openwb_flex/inverter.py index 564cc9f79..999576bde 100644 --- a/packages/modules/openwb_flex/inverter.py +++ b/packages/modules/openwb_flex/inverter.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import InverterState @@ -57,7 +56,6 @@ def update(self) -> None: else: counter = self.__client.get_exported() - log.MainLogger().debug("PV-Kit Leistung[W]: "+str(power)) inverter_state = InverterState( power=power, counter=counter, diff --git a/packages/modules/powerdog/counter.py b/packages/modules/powerdog/counter.py index 3d5d95330..a8e5921b9 100644 --- a/packages/modules/powerdog/counter.py +++ b/packages/modules/powerdog/counter.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -from helpermodules import log +import logging + from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -7,6 +8,8 @@ from modules.common.modbus import ModbusDataType from modules.common.store import get_counter_value_store +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -28,10 +31,9 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: home_consumption = self.__tcp_client.read_input_registers(40026, ModbusDataType.INT_32, unit=1) - log.MainLogger().debug("Powerdog Hausverbrauch[W]: " + str(home_consumption)) + log.debug("Powerdog Hausverbrauch[W]: " + str(home_consumption)) return home_consumption def set_counter_state(self, power: float) -> None: @@ -49,5 +51,4 @@ def set_counter_state(self, power: float) -> None: exported=exported, power=power ) - log.MainLogger().debug("Powerdog Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/powerdog/device.py b/packages/modules/powerdog/device.py index 90415716e..d7c701296 100644 --- a/packages/modules/powerdog/device.py +++ b/packages/modules/powerdog/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Union, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -9,6 +9,8 @@ from modules.powerdog import counter from modules.powerdog import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -34,18 +36,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, Union[counter.PowerdogCounter, inverter.PowerdogInverter]] + self.components = {} # type: Dict[str, Union[counter.PowerdogCounter, inverter.PowerdogInverter]] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = ( + self.components["component"+str(component_config["id"])] = ( self.COMPONENT_TYPE_TO_CLASS[component_type](self.device_config["id"], component_config, self.client)) else: raise Exception( @@ -54,32 +56,32 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if len(self._components) == 1: - for component in self._components: - if isinstance(self._components[component], inverter.PowerdogInverter): - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + log.debug("Start device reading " + str(self.components)) + if len(self.components) == 1: + for component in self.components: + if isinstance(self.components[component], inverter.PowerdogInverter): + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: raise Exception( "Wenn ein EVU-Zähler konfiguriert wurde, muss immer auch ein WR konfiguriert sein.") - elif len(self._components) == 2: - with MultiComponentUpdateContext(self._components): - for component in self._components: - if isinstance(self._components[component], counter.PowerdogCounter): - home_consumption = self._components[component].update() - elif isinstance(self._components[component], inverter.PowerdogInverter): - inverter_power = self._components[component].update() + elif len(self.components) == 2: + with MultiComponentUpdateContext(self.components): + for component in self.components: + if isinstance(self.components[component], counter.PowerdogCounter): + home_consumption = self.components[component].update() + elif isinstance(self.components[component], inverter.PowerdogInverter): + inverter_power = self.components[component].update() else: raise Exception( - "illegal component type " + self._components[component].component_config["type"] + + "illegal component type " + self.components[component].component_config["type"] + ". Allowed values: " + ','.join(COMPONENT_TYPE_TO_MODULE.keys())) counter_power = home_consumption + inverter_power - for component in self._components: - if isinstance(self._components[component], counter.PowerdogCounter): - self._components[component].set_counter_state(counter_power) + for component in self.components: + if isinstance(self.components[component], counter.PowerdogCounter): + self.components[component].set_counter_state(counter_power) else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine oder zu viele Komponenten konfiguriert wurden." ) @@ -105,7 +107,7 @@ def read_legacy(component_type: str, ip_address: str, num: Optional[int] = None) inverter_config["id"] = 1 dev.add_component(inverter_config) - log.MainLogger().debug('Powerdog IP-Adresse: ' + ip_address) + log.debug('Powerdog IP-Adresse: ' + ip_address) dev.update() diff --git a/packages/modules/powerdog/inverter.py b/packages/modules/powerdog/inverter.py index 21008b8d0..558b165cb 100644 --- a/packages/modules/powerdog/inverter.py +++ b/packages/modules/powerdog/inverter.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 +import logging -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import InverterState @@ -8,6 +8,8 @@ from modules.common.modbus import ModbusDataType from modules.common.store import get_inverter_value_store +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -29,7 +31,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> float: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_input_registers(40002, ModbusDataType.INT_32, unit=1) * -1 diff --git a/packages/modules/saxpower/bat.py b/packages/modules/saxpower/bat.py index cc9393ef6..8e6170ea9 100644 --- a/packages/modules/saxpower/bat.py +++ b/packages/modules/saxpower/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -28,7 +27,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: # Die beiden Register müssen zwingend zusammen ausgelesen werden, sonst scheitert die zweite Abfrage. soc, power = self.__tcp_client.read_holding_registers(46, [ModbusDataType.INT_16]*2, unit=64) diff --git a/packages/modules/saxpower/device.py b/packages/modules/saxpower/device.py index bb9074c10..e1f18c1c9 100644 --- a/packages/modules/saxpower/device.py +++ b/packages/modules/saxpower/device.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 +import logging from typing import Dict, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext from modules.saxpower import bat +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -26,18 +28,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, bat.SaxpowerBat] + self.components = {} # type: Dict[str, bat.SaxpowerBat] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 3600) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client)) else: raise Exception( @@ -46,14 +48,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -76,7 +78,7 @@ def read_legacy(component_type: str, ip_address: str) -> None: component_config["id"] = None dev.add_component(component_config) - log.MainLogger().debug('Saxpower IP-Adresse: ' + ip_address) + log.debug('Saxpower IP-Adresse: ' + ip_address) dev.update() diff --git a/packages/modules/siemens/bat.py b/packages/modules/siemens/bat.py index 5daf550df..045a290a5 100644 --- a/packages/modules/siemens/bat.py +++ b/packages/modules/siemens/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -28,7 +27,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_holding_registers(6, ModbusDataType.INT_32, unit=1) * -1 soc = int(self.__tcp_client.read_holding_registers(8, ModbusDataType.INT_32, unit=1)) diff --git a/packages/modules/siemens/counter.py b/packages/modules/siemens/counter.py index d47877e50..7e38e987d 100644 --- a/packages/modules/siemens/counter.py +++ b/packages/modules/siemens/counter.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -28,7 +27,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_holding_registers(14, ModbusDataType.INT_32, unit=1) @@ -48,5 +46,4 @@ def update(self): exported=exported, power=power ) - log.MainLogger().debug("Siemens Zähler Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/siemens/device.py b/packages/modules/siemens/device.py index 41503ee25..8d864f9d9 100644 --- a/packages/modules/siemens/device.py +++ b/packages/modules/siemens/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Union, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -10,6 +10,8 @@ from modules.siemens import counter from modules.siemens import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -33,17 +35,17 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, siemens_component_classes] + self.components = {} # type: Dict[str, siemens_component_classes] try: self.client = modbus.ModbusClient(device_config["configuration"]["ip_address"], 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client)) else: raise Exception( @@ -52,14 +54,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading" + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading" + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -84,7 +86,7 @@ def read_legacy(component_type: str, ip_address: str, num: Optional[int] = None) component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Siemens IP-Adresse: ' + ip_address) + log.debug('Siemens IP-Adresse: ' + ip_address) dev.update() diff --git a/packages/modules/siemens/inverter.py b/packages/modules/siemens/inverter.py index 28840817a..6772321c1 100644 --- a/packages/modules/siemens/inverter.py +++ b/packages/modules/siemens/inverter.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import InverterState @@ -29,7 +28,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_holding_registers(16, ModbusDataType.INT_32, unit=1) * -1 diff --git a/packages/modules/sma_modbus_tcp/device.py b/packages/modules/sma_modbus_tcp/device.py index d68419a19..e623c950f 100644 --- a/packages/modules/sma_modbus_tcp/device.py +++ b/packages/modules/sma_modbus_tcp/device.py @@ -13,7 +13,7 @@ from modules.common.store import get_inverter_value_store -log = logging.getLogger("SMA Inverter") +log = logging.getLogger(__name__) def get_default_config() -> dict: @@ -40,7 +40,7 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, sma_modbus_tcp_component_classes] + self.components = {} # type: Dict[str, sma_modbus_tcp_component_classes] try: self.device_config = device_config except Exception: @@ -49,7 +49,7 @@ def __init__(self, device_config: dict) -> None: def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], self.device_config["configuration"]["ip"], component_config)) @@ -60,9 +60,9 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components.values(): + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components.values(): # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. with SingleComponentUpdateContext(component.component_info): component.update() diff --git a/packages/modules/sma_modbus_tcp/inverter_modbus_tcp.py b/packages/modules/sma_modbus_tcp/inverter_modbus_tcp.py index 82f235aa9..8657d3e2c 100644 --- a/packages/modules/sma_modbus_tcp/inverter_modbus_tcp.py +++ b/packages/modules/sma_modbus_tcp/inverter_modbus_tcp.py @@ -20,7 +20,7 @@ def get_default_config() -> dict: } -log = logging.getLogger("SMA ModbusTCP") +log = logging.getLogger(__name__) class SmaModbusTcpInverter: @@ -38,14 +38,13 @@ def update(self) -> None: self.__store.set(self.read_inverter_state()) def read_inverter_state(self) -> InverterState: - log.debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: - if self.component_config["configuration"]["version"] == SmaInverterVersion.default: + if self.component_config["configuration"]["version"] == SmaInverterVersion.default.value: # AC Wirkleistung über alle Phasen (W) [Pac] power = self.__tcp_client.read_holding_registers(30775, ModbusDataType.INT_32, unit=3) # Gesamtertrag (Wh) [E-Total] energy = self.__tcp_client.read_holding_registers(30529, ModbusDataType.UINT_32, unit=3) - elif self.component_config["configuration"]["version"] == SmaInverterVersion.core2: + elif self.component_config["configuration"]["version"] == SmaInverterVersion.core2.value: # AC Wirkleistung über alle Phasen (W) [Pac] power = self.__tcp_client.read_holding_registers(40084, ModbusDataType.INT_16, unit=1) * 10 # Gesamtertrag (Wh) [E-Total] SF=2! diff --git a/packages/modules/sma_modbus_tcp/inverter_webbox.py b/packages/modules/sma_modbus_tcp/inverter_webbox.py index 51b89a6e5..749471182 100644 --- a/packages/modules/sma_modbus_tcp/inverter_webbox.py +++ b/packages/modules/sma_modbus_tcp/inverter_webbox.py @@ -1,6 +1,4 @@ #!/usr/bin/env python3 -import logging - from modules.common import req from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo @@ -16,9 +14,6 @@ def get_default_config() -> dict: } -log = logging.getLogger("SMA Webbox") - - class SmaWebboxInverter: def __init__(self, device_id: int, device_address: str, component_config: dict) -> None: self.__device_address = device_address @@ -30,7 +25,6 @@ def update(self) -> None: self.__store.set(self.read_inverter_state()) def read_inverter_state(self) -> InverterState: - log.debug("Komponente "+self.component_config["name"]+" auslesen.") data = {'RPC': '{"version": "1.0","proc": "GetPlantOverview","id": "1","format": "JSON"}'} response = req.get_http_session().post( 'http://' + self.__device_address + '/rpc', data=data, timeout=3).json() diff --git a/packages/modules/sma_shm/device.py b/packages/modules/sma_shm/device.py index 3b644fde7..987c9e9d5 100644 --- a/packages/modules/sma_shm/device.py +++ b/packages/modules/sma_shm/device.py @@ -2,7 +2,7 @@ import logging import socket import time -from typing import List, Callable, Iterator +from typing import Dict, List, Callable, Iterator from helpermodules.cli import run_using_positional_cli_args from modules.common.abstract_device import AbstractDevice @@ -23,7 +23,7 @@ def get_default_config() -> dict: } -log = logging.getLogger("SMA Speedwire") +log = logging.getLogger(__name__) timeout_seconds = 5 @@ -34,7 +34,7 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = [] # type: List[SpeedwireComponent] + self.components = {} # type: Dict[str, SpeedwireComponent] self.device_config = device_config def add_component(self, component_config: dict) -> None: @@ -44,12 +44,12 @@ def add_component(self, component_config: dict) -> None: raise Exception( "Unknown component type <%s>, known types are: <%s>", e, ','.join(self.COMPONENT_FACTORIES.keys()) ) - self._components.append(factory(component_config)) + self.components["component"+str(component_config["id"])] = factory(component_config) def update(self) -> None: log.debug("Beginning update") - with MultiComponentUpdateContext(self._components): - if not self._components: + with MultiComponentUpdateContext(self.components): + if not self.components: raise FaultState.warning("Keine Komponenten konfiguriert") with SpeedwireListener(timeout_seconds) as speedwire: @@ -59,7 +59,7 @@ def update(self) -> None: def __read_speedwire(self, speedwire: Iterator[dict]): stop_time = time.time() + timeout_seconds - components_todo = self._components + components_todo = self.components.values() try: for sma_data in speedwire: components_todo = [component for component in components_todo if not component.read_datagram(sma_data)] diff --git a/packages/modules/sma_shm/utils.py b/packages/modules/sma_shm/utils.py index 81aaf6fa2..50def421f 100644 --- a/packages/modules/sma_shm/utils.py +++ b/packages/modules/sma_shm/utils.py @@ -6,7 +6,7 @@ from modules.common.store import ValueStore T = TypeVar("T") -log = logging.getLogger("SMA Speedwire") +log = logging.getLogger(__name__) def _create_serial_matcher(serial: Optional[int]) -> Callable[[dict], bool]: diff --git a/packages/modules/solax/bat.py b/packages/modules/solax/bat.py index eedf626cb..4a4aa7839 100644 --- a/packages/modules/solax/bat.py +++ b/packages/modules/solax/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -29,7 +28,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_input_registers(22, ModbusDataType.INT_16, unit=self.__modbus_id) soc = self.__tcp_client.read_input_registers(28, ModbusDataType.UINT_16, unit=self.__modbus_id) diff --git a/packages/modules/solax/counter.py b/packages/modules/solax/counter.py index 056cef908..2346f7a26 100644 --- a/packages/modules/solax/counter.py +++ b/packages/modules/solax/counter.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 -from helpermodules import log +from pymodbus.constants import Endian + from modules.common import modbus from modules.common.component_state import CounterState from modules.common.fault_state import ComponentInfo -from modules.common.modbus import ModbusDataType, Endian +from modules.common.modbus import ModbusDataType from modules.common.store import get_counter_value_store @@ -25,7 +26,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_input_registers(70, ModbusDataType.INT_32, wordorder=Endian.Little, unit=self.__modbus_id) * -1 @@ -48,5 +48,4 @@ def update(self): powers=powers, frequency=frequency ) - log.MainLogger().debug("Solax Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/solax/device.py b/packages/modules/solax/device.py index fedb1a3e7..e91cb4058 100644 --- a/packages/modules/solax/device.py +++ b/packages/modules/solax/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -10,6 +10,8 @@ from modules.solax import counter from modules.solax import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -31,18 +33,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, counter.SolaxCounter] + self.components = {} # type: Dict[str, counter.SolaxCounter] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client, self.device_config["configuration"]["modbus_id"])) else: @@ -52,14 +54,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden.") @@ -84,8 +86,8 @@ def read_legacy(component_type: str, ip_address: str, modbus_id: int, num: Optio component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Solax IP-Adresse: ' + ip_address) - log.MainLogger().debug('Solax ID: ' + str(modbus_id)) + log.debug('Solax IP-Adresse: ' + ip_address) + log.debug('Solax ID: ' + str(modbus_id)) dev.update() diff --git a/packages/modules/solax/inverter.py b/packages/modules/solax/inverter.py index 5cafb5efc..9cf15d7e1 100644 --- a/packages/modules/solax/inverter.py +++ b/packages/modules/solax/inverter.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 +from pymodbus.constants import Endian -from helpermodules import log from modules.common import modbus from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo -from modules.common.modbus import ModbusDataType, Endian +from modules.common.modbus import ModbusDataType from modules.common.store import get_inverter_value_store @@ -26,7 +26,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power_temp = self.__tcp_client.read_input_registers(10, [ModbusDataType.UINT_16] * 2, unit=self.__modbus_id) power = sum(power_temp) * -1 diff --git a/packages/modules/sonnenbatterie/bat.py b/packages/modules/sonnenbatterie/bat.py index 1f76b1aff..c8e36618b 100644 --- a/packages/modules/sonnenbatterie/bat.py +++ b/packages/modules/sonnenbatterie/bat.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 +import logging import requests -from helpermodules import log from modules.common import simcount from modules.common.component_state import BatState from modules.common.fault_state import ComponentInfo from modules.common.store import get_bat_value_store from modules.common.fault_state import FaultState +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -91,9 +93,9 @@ def __update_variant_1(self) -> BatState: ''' battery_state = self.__read_variant_1() battery_power = -battery_state["Pac_total_W"] - log.MainLogger().debug('Speicher Leistung: ' + str(battery_power)) + log.debug('Speicher Leistung: ' + str(battery_power)) battery_soc = battery_state["USOC"] - log.MainLogger().debug('Speicher SoC: ' + str(battery_soc)) + log.debug('Speicher SoC: ' + str(battery_soc)) topic_str = "openWB/set/system/device/" + str( self.__device_id)+"/component/"+str(self.component_config["id"])+"/" imported, exported = self.__sim_count.sim_count( @@ -124,9 +126,7 @@ def __update_variant_2(self) -> BatState: ) def update(self) -> None: - log.MainLogger().debug("Komponente '" + str(self.component_config["id"]) + "' " - + self.component_config["name"] + " wird auslesen.") - log.MainLogger().debug("Variante: " + str(self.__device_variant)) + log.debug("Variante: " + str(self.__device_variant)) if self.__device_variant == 0: state = self.__update_variant_0() elif self.__device_variant == 1: @@ -136,4 +136,3 @@ def update(self) -> None: else: raise FaultState.error("Unbekannte Variante: " + str(self.__device_variant)) self.__store.set(state) - log.MainLogger().debug("Komponente "+self.component_config["name"]+" wurde erfolgreich auslesen.") diff --git a/packages/modules/sonnenbatterie/counter.py b/packages/modules/sonnenbatterie/counter.py index 5855d1275..e5068c719 100644 --- a/packages/modules/sonnenbatterie/counter.py +++ b/packages/modules/sonnenbatterie/counter.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 +import logging import requests -from helpermodules import log from modules.common import simcount from modules.common.component_state import CounterState from modules.common.fault_state import ComponentInfo from modules.common.store import get_counter_value_store from modules.common.fault_state import FaultState +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -74,12 +76,12 @@ def __update_variant_1(self) -> CounterState: ''' counter_state = self.__read_variant_1() grid_power = -counter_state["GridFeedIn_W"] - log.MainLogger().debug('EVU Leistung: ' + str(grid_power)) + log.debug('EVU Leistung: ' + str(grid_power)) # Es wird nur eine Spannung ausgegeben grid_voltage = counter_state["Uac"] - log.MainLogger().debug('EVU Spannung: ' + str(grid_voltage)) + log.debug('EVU Spannung: ' + str(grid_voltage)) grid_frequency = counter_state["Fac"] - log.MainLogger().debug('EVU Netzfrequenz: ' + str(grid_frequency)) + log.debug('EVU Netzfrequenz: ' + str(grid_frequency)) topic_str = "openWB/set/system/device/" + str( self.__device_id)+"/component/"+str(self.component_config["id"])+"/" imported, exported = self.__sim_count.sim_count( @@ -116,11 +118,9 @@ def __update_variant_2(self) -> CounterState: ) def update(self) -> None: - log.MainLogger().debug("Komponente '" + str(self.component_config["id"]) + "' " - + self.component_config["name"] + " wird auslesen.") - log.MainLogger().debug("Variante: " + str(self.__device_variant)) + log.debug("Variante: " + str(self.__device_variant)) if self.__device_variant == 0: - log.MainLogger().debug("Die Variante '0' bietet keine EVU Daten!") + log.debug("Die Variante '0' bietet keine EVU Daten!") elif self.__device_variant == 1: state = self.__update_variant_1() elif self.__device_variant == 2: @@ -128,4 +128,3 @@ def update(self) -> None: else: raise FaultState.error("Unbekannte Variante: " + str(self.__device_variant)) self.__store.set(state) - log.MainLogger().debug("Komponente "+self.component_config["name"]+" wurde erfolgreich auslesen.") diff --git a/packages/modules/sonnenbatterie/device.py b/packages/modules/sonnenbatterie/device.py index ba58e97d5..55c2131f0 100644 --- a/packages/modules/sonnenbatterie/device.py +++ b/packages/modules/sonnenbatterie/device.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 """ Modul zum Auslesen von sonnenBatterie Speichern. """ +import logging from typing import Dict, Union, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.sonnenbatterie import bat from modules.sonnenbatterie import counter @@ -11,6 +11,8 @@ from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -39,16 +41,16 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, sonnenbatterie_component_classes] + self.components = {} # type: Dict[str, sonnenbatterie_component_classes] try: self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], self.device_config["configuration"]["ip"], self.device_config["configuration"]["variant"], @@ -60,14 +62,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -92,8 +94,8 @@ def read_legacy(component_type: str, address: str, variant: int, num: Optional[i ) component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('SonnenBatterie address: ' + address) - log.MainLogger().debug('SonnenBatterie variant: ' + str(variant)) + log.debug('SonnenBatterie address: ' + address) + log.debug('SonnenBatterie variant: ' + str(variant)) dev.update() diff --git a/packages/modules/sonnenbatterie/inverter.py b/packages/modules/sonnenbatterie/inverter.py index 64f5ed63a..b680d33ac 100644 --- a/packages/modules/sonnenbatterie/inverter.py +++ b/packages/modules/sonnenbatterie/inverter.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 +import logging import requests -from helpermodules import log from modules.common import simcount from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo from modules.common.store import get_inverter_value_store from modules.common.fault_state import FaultState +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -74,7 +76,7 @@ def __update_variant_1(self) -> InverterState: ''' inverter_state = self.__read_variant_1() pv_power = -inverter_state["Production_W"] - log.MainLogger().debug('Speicher PV Leistung: ' + str(pv_power)) + log.debug('Speicher PV Leistung: ' + str(pv_power)) topic_str = "openWB/set/system/device/" + str( self.__device_id)+"/component/"+str(self.component_config["id"])+"/" _, exported = self.__sim_count.sim_count( @@ -94,7 +96,7 @@ def __read_variant_2_element(self, element: str) -> str: def __update_variant_2(self) -> InverterState: # Auslesen einer Sonnenbatterie Eco 6 über die integrierte REST-API des Batteriesystems pv_power = -int(float(self.__read_variant_2_element("M03"))) - log.MainLogger().debug('Speicher PV Leistung: ' + str(pv_power)) + log.debug('Speicher PV Leistung: ' + str(pv_power)) topic_str = "openWB/set/system/device/" + str( self.__device_id)+"/component/"+str(self.component_config["id"])+"/" _, exported = self.__sim_count.sim_count( @@ -106,11 +108,9 @@ def __update_variant_2(self) -> InverterState: ) def update(self) -> None: - log.MainLogger().debug("Komponente '" + str(self.component_config["id"]) + "' " - + self.component_config["name"] + " wird auslesen.") - log.MainLogger().debug("Variante: " + str(self.__device_variant)) + log.debug("Variante: " + str(self.__device_variant)) if self.__device_variant == 0: - log.MainLogger().debug("Die Variante '0' bietet keine PV Daten!") + log.debug("Die Variante '0' bietet keine PV Daten!") elif self.__device_variant == 1: state = self.__update_variant_1() elif self.__device_variant == 2: @@ -118,4 +118,3 @@ def update(self) -> None: else: raise FaultState.error("Unbekannte Variante: " + str(self.__device_variant)) self.__store.set(state) - log.MainLogger().debug("Komponente "+self.component_config["name"]+" wurde erfolgreich auslesen.") diff --git a/packages/modules/studer/bat.py b/packages/modules/studer/bat.py index 9ccabce3e..1c21705f9 100644 --- a/packages/modules/studer/bat.py +++ b/packages/modules/studer/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common.component_state import BatState from modules.common.modbus import ModbusDataType @@ -24,7 +23,6 @@ def __init__(self, component_config: dict, tcp_client: modbus.ModbusClient) -> N self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") unit = 60 with self.__tcp_client: power = self.__tcp_client.read_input_registers(6, ModbusDataType.FLOAT_32, unit=unit) diff --git a/packages/modules/studer/device.py b/packages/modules/studer/device.py index 3936d9893..d88dffda3 100644 --- a/packages/modules/studer/device.py +++ b/packages/modules/studer/device.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 """ Modul zum Auslesen von Alpha Ess Speichern, Zählern und Wechselrichtern. """ +import logging from typing import Dict, List, Union, Optional -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -11,6 +11,8 @@ from modules.studer import bat from modules.studer import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -33,18 +35,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, studer_component_classes] + self.components = {} # type: Dict[str, studer_component_classes] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( component_config, self.client)) else: raise Exception( @@ -53,14 +55,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) diff --git a/packages/modules/studer/inverter.py b/packages/modules/studer/inverter.py index 503bedb80..5400910fd 100644 --- a/packages/modules/studer/inverter.py +++ b/packages/modules/studer/inverter.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo, FaultState @@ -28,7 +27,6 @@ def __init__(self, component_config: dict, tcp_client: modbus.ModbusClient) -> N self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") vc_count = self.component_config["configuration"]["vc_count"] vc_type = self.component_config["configuration"]["vc_type"] diff --git a/packages/modules/sungrow/bat.py b/packages/modules/sungrow/bat.py index 0ab5fede8..9f32223f2 100644 --- a/packages/modules/sungrow/bat.py +++ b/packages/modules/sungrow/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -28,7 +27,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") unit = 1 with self.__tcp_client: soc = int(self.__tcp_client.read_input_registers(13022, ModbusDataType.INT_16, unit=unit) / 10) diff --git a/packages/modules/sungrow/counter.py b/packages/modules/sungrow/counter.py index 38043a4b4..ebc0e9a27 100644 --- a/packages/modules/sungrow/counter.py +++ b/packages/modules/sungrow/counter.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -30,7 +29,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") unit = 1 with self.__tcp_client: if self.component_config["configuration"]["version"] == 1: @@ -44,7 +42,7 @@ def update(self): # powers = self.__tcp_client.read_input_registers(5084, [ModbusDataType.UINT_16] * 3, # wordorder=Endian.Little, unit=unit) # powers = [power / 10 for power in powers] - # log.MainLogger().info("power: " + str(power) + " powers?: " + str(powers)) + # log.info("power: " + str(power) + " powers?: " + str(powers)) else: power = self.__tcp_client.read_input_registers(13009, ModbusDataType.INT_32, wordorder=Endian.Little, unit=unit) * -1 @@ -56,7 +54,7 @@ def update(self): # powers = self.__tcp_client.read_input_registers(5084, [ModbusDataType.INT_16] * 3, # wordorder=Endian.Little, unit=unit) # powers = [power / 10 for power in powers] - # log.MainLogger().info("power: " + str(power) + " powers?: " + str(powers)) + # log.info("power: " + str(power) + " powers?: " + str(powers)) topic_str = "openWB/set/system/device/{}/component/{}/".format(self.__device_id, self.component_config["id"]) imported, exported = self.__sim_count.sim_count( @@ -73,5 +71,4 @@ def update(self): voltages=voltages, frequency=frequency ) - log.MainLogger().debug("Sungrow Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/sungrow/device.py b/packages/modules/sungrow/device.py index 87651ae46..fae5dd9f9 100644 --- a/packages/modules/sungrow/device.py +++ b/packages/modules/sungrow/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, List, Union, Optional -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -10,6 +10,8 @@ from modules.sungrow import counter from modules.sungrow import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -33,18 +35,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, sungrow_component_classes] + self.components = {} # type: Dict[str, sungrow_component_classes] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( self.device_config["id"], component_config, self.client)) else: raise Exception( @@ -53,14 +55,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) diff --git a/packages/modules/sungrow/inverter.py b/packages/modules/sungrow/inverter.py index e88751ec9..764d5ff5c 100644 --- a/packages/modules/sungrow/inverter.py +++ b/packages/modules/sungrow/inverter.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import InverterState @@ -29,7 +28,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") with self.__tcp_client: power = self.__tcp_client.read_input_registers(5016, ModbusDataType.UINT_32, wordorder=Endian.Little, unit=1) * -1 diff --git a/packages/modules/sunny_island/bat.py b/packages/modules/sunny_island/bat.py index 5999195aa..7530163ef 100644 --- a/packages/modules/sunny_island/bat.py +++ b/packages/modules/sunny_island/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common.component_state import BatState from modules.common.modbus import ModbusDataType @@ -24,7 +23,6 @@ def __init__(self, component_config: dict, tcp_client: modbus.ModbusClient) -> N self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") unit = 3 with self.__tcp_client: soc = self.__tcp_client.read_holding_registers(30845, ModbusDataType.INT_32, unit=unit) diff --git a/packages/modules/sunny_island/device.py b/packages/modules/sunny_island/device.py index ef2a586d2..6fcc6a7a7 100644 --- a/packages/modules/sunny_island/device.py +++ b/packages/modules/sunny_island/device.py @@ -1,15 +1,15 @@ #!/usr/bin/env python3 -""" Modul zum Auslesen von Alpha Ess Speichern, Zählern und Wechselrichtern. -""" +import logging from typing import Dict, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext from modules.sunny_island import bat +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -28,18 +28,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, bat.SunnyIslandBat] + self.components = {} # type: Dict[str, bat.SunnyIslandBat] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = (self.COMPONENT_TYPE_TO_CLASS[component_type]( component_config, self.client)) else: raise Exception( @@ -48,14 +48,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -78,7 +78,7 @@ def read_legacy(component_type: str, ip_address: str, num: Optional[int] = None) component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Sunny Island IP-Adresse: ' + ip_address) + log.debug('Sunny Island IP-Adresse: ' + ip_address) dev.update() diff --git a/packages/modules/sunways/device.py b/packages/modules/sunways/device.py index 70b926b41..6c3ce01da 100644 --- a/packages/modules/sunways/device.py +++ b/packages/modules/sunways/device.py @@ -1,12 +1,14 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext from modules.sunways import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -26,16 +28,16 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, inverter.SunwaysInverter] + self.components = {} # type: Dict[str, inverter.SunwaysInverter] try: self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( + self.components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( component_config, self.device_config["configuration"]["ip_address"], self.device_config["configuration"]["password"]) @@ -46,14 +48,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine oder zu viele Komponenten konfiguriert wurden." ) @@ -78,8 +80,8 @@ def read_legacy(component_type: str, ip_address: str, password: str, num: Option component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Sunways IP-Adresse: ' + ip_address) - log.MainLogger().debug('Sunways Passwort: ' + password) + log.debug('Sunways IP-Adresse: ' + ip_address) + log.debug('Sunways Passwort: ' + password) dev.update() diff --git a/packages/modules/sunways/inverter.py b/packages/modules/sunways/inverter.py index 79c23c38a..4da593c69 100644 --- a/packages/modules/sunways/inverter.py +++ b/packages/modules/sunways/inverter.py @@ -1,11 +1,9 @@ #!/usr/bin/env python3 - from requests.auth import HTTPDigestAuth -from helpermodules import log +from modules.common import req from modules.common.component_state import InverterState from modules.common.fault_state import ComponentInfo -from modules.common import req from modules.common.store import get_inverter_value_store """Example Output for ajax.txt @@ -33,7 +31,6 @@ def __init__(self, component_config: dict, ip_address: str, password: str) -> No self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") params = ( ('CAN', '1'), ('HASH', '00200403'), diff --git a/packages/modules/tesla/counter.py b/packages/modules/tesla/counter.py index ef22044d0..07ce69468 100644 --- a/packages/modules/tesla/counter.py +++ b/packages/modules/tesla/counter.py @@ -1,12 +1,14 @@ #!/usr/bin/env python3 +import logging from requests import HTTPError -from helpermodules import log from modules.common.component_state import CounterState from modules.common.fault_state import ComponentInfo from modules.common.store import get_counter_value_store from modules.tesla.http_client import PowerwallHttpClient +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -26,7 +28,7 @@ def __init__(self, component_config: dict) -> None: def update(self, client: PowerwallHttpClient, aggregate): # read firmware version status = client.get_json("/api/status") - log.MainLogger().debug('Firmware: ' + status["version"]) + log.debug('Firmware: ' + status["version"]) try: # read additional info if firmware supports meters_site = client.get_json("/api/meters/site") @@ -39,7 +41,7 @@ def update(self, client: PowerwallHttpClient, aggregate): powers=[meters_site[0]["Cached_readings"]["real_power_" + phase] for phase in ["a", "b", "c"]] ) except (KeyError, HTTPError): - log.MainLogger().debug( + log.debug( "Firmware seems not to provide detailed phase measurements. Fallback to total power only.") powerwall_state = CounterState( imported=aggregate["site"]["energy_imported"], diff --git a/packages/modules/tesla/device.py b/packages/modules/tesla/device.py index 309bdc83c..137321282 100644 --- a/packages/modules/tesla/device.py +++ b/packages/modules/tesla/device.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 import json +import logging import requests from json import JSONDecodeError from requests import HTTPError from typing import Callable, Dict, Union, Optional, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common.abstract_device import AbstractDevice from modules.common.component_context import MultiComponentUpdateContext @@ -16,6 +16,8 @@ from modules.tesla import inverter from modules.tesla.http_client import PowerwallHttpClient +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -92,7 +94,7 @@ def __init__(self, device_config: dict) -> None: if isinstance(device_config, Tesla) \ else Tesla.from_dict(device_config) except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] @@ -106,7 +108,7 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Beginning update") + log.debug("Beginning update") cookies = None address = self.config.configuration.ip_address email = self.config.configuration.email @@ -115,9 +117,9 @@ def update(self) -> None: try: cookies = json.loads(COOKIE_FILE.read_text()) except FileNotFoundError: - log.MainLogger().debug("Cookie-File <%s> does not exist. It will be created.", COOKIE_FILE) - except JSONDecodeError as e: - log.MainLogger().warning("Could not parse Cookie-File "+str(COOKIE_FILE)+". It will be re-created.", e) + log.debug("Cookie-File <%s> does not exist. It will be created.", COOKIE_FILE) + except JSONDecodeError: + log.warning("Could not parse Cookie-File "+str(COOKIE_FILE)+". It will be re-created.", exc_info=True) session = get_http_session() if cookies is None: @@ -129,10 +131,10 @@ def update(self) -> None: except HTTPError as e: if e.response.status_code != 401 and e.response.status_code != 403: raise e - log.MainLogger().warning( + log.warning( "Login to powerwall with existing cookie failed. Will retry with new cookie...") self.__authenticate_and_update(session, address, email, password, self.__update_components) - log.MainLogger().debug("Update completed successfully") + log.debug("Update completed successfully") def __update_components(self, client: PowerwallHttpClient): if self._components: @@ -141,7 +143,7 @@ def __update_components(self, client: PowerwallHttpClient): aggregate = client.get_json("/api/meters/aggregates") self._components[component].update(client, aggregate) else: - log.MainLogger().warning( + log.warning( self.config.name + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -156,7 +158,7 @@ def __authenticate(self, session: requests.Session, url: str, email: str, passwo verify=False, timeout=5 ) - log.MainLogger().debug("Authentication endpoint send cookies %s", str(response.cookies)) + log.debug("Authentication endpoint send cookies %s", str(response.cookies)) return {"AuthCookie": response.cookies["AuthCookie"], "UserRecord": response.cookies["UserRecord"]} def __authenticate_and_update(self, @@ -197,9 +199,9 @@ def read_legacy(component_type: str, component_config["id"] = num dev.add_component(component_config) - log.MainLogger().debug('Tesla Powerwall IP-Adresse: ' + address) - log.MainLogger().debug('Tesla Powerwall Mail-Adresse: ' + email) - log.MainLogger().debug('Tesla Powerwall Passwort: ' + password) + log.debug('Tesla Powerwall IP-Adresse: ' + address) + log.debug('Tesla Powerwall Mail-Adresse: ' + email) + log.debug('Tesla Powerwall Passwort: ' + password) dev.update() diff --git a/packages/modules/victron/bat.py b/packages/modules/victron/bat.py index bbf0e348a..3a807571e 100644 --- a/packages/modules/victron/bat.py +++ b/packages/modules/victron/bat.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import BatState @@ -30,7 +29,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") modbus_id = self.component_config["configuration"]["modbus_id"] with self.__tcp_client: power = self.__tcp_client.read_holding_registers(842, ModbusDataType.INT_16, unit=modbus_id) diff --git a/packages/modules/victron/counter.py b/packages/modules/victron/counter.py index 263d36060..7e719ef44 100644 --- a/packages/modules/victron/counter.py +++ b/packages/modules/victron/counter.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import CounterState @@ -31,7 +30,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self): - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") unit = self.component_config["configuration"]["modbus_id"] energy_meter = self.component_config["configuration"]["energy_meter"] with self.__tcp_client: @@ -74,5 +72,4 @@ def update(self): exported=exported, power=power ) - log.MainLogger().debug("Victron Leistung[W]: " + str(counter_state.power)) self.__store.set(counter_state) diff --git a/packages/modules/victron/device.py b/packages/modules/victron/device.py index 89ddc2057..0ff97f60e 100644 --- a/packages/modules/victron/device.py +++ b/packages/modules/victron/device.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 +import logging from typing import Dict, Optional, Union, List -from helpermodules import log from helpermodules.cli import run_using_positional_cli_args from modules.common import modbus from modules.common.abstract_device import AbstractDevice @@ -10,6 +10,8 @@ from modules.victron import counter from modules.victron import inverter +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -30,18 +32,18 @@ class Device(AbstractDevice): } def __init__(self, device_config: dict) -> None: - self._components = {} # type: Dict[str, Union[bat.VictronBat, counter.VictronCounter]] + self.components = {} # type: Dict[str, Union[bat.VictronBat, counter.VictronCounter]] try: ip_address = device_config["configuration"]["ip_address"] self.client = modbus.ModbusClient(ip_address, 502) self.device_config = device_config except Exception: - log.MainLogger().exception("Fehler im Modul "+device_config["name"]) + log.exception("Fehler im Modul "+device_config["name"]) def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: - self._components["component"+str(component_config["id"])] = ( + self.components["component"+str(component_config["id"])] = ( self.COMPONENT_TYPE_TO_CLASS[component_type](self.device_config["id"], component_config, self.client)) else: raise Exception( @@ -50,14 +52,14 @@ def add_component(self, component_config: dict) -> None: ) def update(self) -> None: - log.MainLogger().debug("Start device reading " + str(self._components)) - if self._components: - for component in self._components: + log.debug("Start device reading " + str(self.components)) + if self.components: + for component in self.components: # Auch wenn bei einer Komponente ein Fehler auftritt, sollen alle anderen noch ausgelesen werden. - with SingleComponentUpdateContext(self._components[component].component_info): - self._components[component].update() + with SingleComponentUpdateContext(self.components[component].component_info): + self.components[component].update() else: - log.MainLogger().warning( + log.warning( self.device_config["name"] + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -95,10 +97,10 @@ def read_legacy( component_config["configuration"]["modbus_id"] = modbus_id dev.add_component(component_config) - log.MainLogger().debug('Victron IP-Adresse: ' + ip_address) - log.MainLogger().debug('Victron Energy Meter: ' + str(bool(energy_meter))) - log.MainLogger().debug('Victron Modbus-ID: ' + str(modbus_id)) - log.MainLogger().debug('Victron MPPT: ' + str(mppt)) + log.debug('Victron IP-Adresse: ' + ip_address) + log.debug('Victron Energy Meter: ' + str(bool(energy_meter))) + log.debug('Victron Modbus-ID: ' + str(modbus_id)) + log.debug('Victron MPPT: ' + str(mppt)) dev.update() diff --git a/packages/modules/victron/inverter.py b/packages/modules/victron/inverter.py index f09cd75db..d97833562 100644 --- a/packages/modules/victron/inverter.py +++ b/packages/modules/victron/inverter.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 +import logging -from helpermodules import log from modules.common import modbus from modules.common import simcount from modules.common.component_state import InverterState @@ -8,6 +8,8 @@ from modules.common.modbus import ModbusDataType from modules.common.store import get_inverter_value_store +log = logging.getLogger(__name__) + def get_default_config() -> dict: return { @@ -32,7 +34,6 @@ def __init__(self, device_id: int, component_config: dict, tcp_client: modbus.Mo self.component_info = ComponentInfo.from_component_config(component_config) def update(self) -> None: - log.MainLogger().debug("Komponente "+self.component_config["name"]+" auslesen.") modbus_id = self.component_config["configuration"]["modbus_id"] with self.__tcp_client: if self.component_config["configuration"]["mppt"]: @@ -41,8 +42,8 @@ def update(self) -> None: except Exception as e: if "GatewayPathUnavailable" in str(e): power = 0 - log.MainLogger().debug(self.component_config["name"] + - ": Reg 789 konnte nicht gelesen werden, Power auf 0 gesetzt.") + log.debug(self.component_config["name"] + + ": Reg 789 konnte nicht gelesen werden, Power auf 0 gesetzt.") else: raise else: From 9a977210676cc68a668ec54d52aa03ba1e0b4c75 Mon Sep 17 00:00:00 2001 From: LKuemmel Date: Wed, 25 May 2022 12:40:28 +0200 Subject: [PATCH 4/9] use url for json and http --- packages/modules/http/api.py | 6 +-- packages/modules/http/bat.py | 18 ++++---- packages/modules/http/counter.py | 22 +++++----- packages/modules/http/device.py | 73 ++++++++++++++++++++++--------- packages/modules/http/inverter.py | 10 ++--- packages/modules/json/device.py | 68 ++++++++++++++++++++-------- 6 files changed, 131 insertions(+), 66 deletions(-) diff --git a/packages/modules/http/api.py b/packages/modules/http/api.py index ca54032fd..eec748d1b 100644 --- a/packages/modules/http/api.py +++ b/packages/modules/http/api.py @@ -17,8 +17,8 @@ def request_value(url: str) -> Optional[float]: return float(response.text.replace("\n", "")) -def create_request_function(domain: str, path: str) -> Callable[[], Optional[float]]: - if path == "none": +def create_request_function(url: str, path: str) -> Callable[[], Optional[float]]: + if path == "none" or path is None: return lambda: 0 else: - return functools.partial(request_value, domain + path) + return functools.partial(request_value, url + path) diff --git a/packages/modules/http/bat.py b/packages/modules/http/bat.py index 50f36a815..3573ea05b 100644 --- a/packages/modules/http/bat.py +++ b/packages/modules/http/bat.py @@ -12,20 +12,20 @@ def get_default_config() -> dict: "id": 0, "type": "bat", "configuration": { - "power_path": "", - "imported_path": "none", - "exported_path": "none", - "soc_path": "" + "power_path": None, + "imported_path": None, + "exported_path": None, + "soc_path": None } } class HttpBat: - def __init__(self, device_id: int, component_config: dict, domain: str) -> None: - self.__get_power = create_request_function(domain, component_config["configuration"]["power_path"]) - self.__get_imported = create_request_function(domain, component_config["configuration"]["imported_path"]) - self.__get_exported = create_request_function(domain, component_config["configuration"]["exported_path"]) - self.__get_soc = create_request_function(domain, component_config["configuration"]["soc_path"]) + def __init__(self, device_id: int, component_config: dict, url: str) -> None: + self.__get_power = create_request_function(url, component_config["configuration"]["power_path"]) + self.__get_imported = create_request_function(url, component_config["configuration"]["imported_path"]) + self.__get_exported = create_request_function(url, component_config["configuration"]["exported_path"]) + self.__get_soc = create_request_function(url, component_config["configuration"]["soc_path"]) self.__device_id = device_id self.component_config = component_config diff --git a/packages/modules/http/counter.py b/packages/modules/http/counter.py index 16fca0a1b..fbb739230 100644 --- a/packages/modules/http/counter.py +++ b/packages/modules/http/counter.py @@ -12,23 +12,23 @@ def get_default_config() -> dict: "id": 0, "type": "counter", "configuration": { - "power_path": "", - "imported_path": "none", - "exported_path": "none", - "current_l1_path": "none", - "current_l2_path": "none", - "current_l3_path": "none", + "power_path": None, + "imported_path": None, + "exported_path": None, + "current_l1_path": None, + "current_l2_path": None, + "current_l3_path": None, } } class HttpCounter: - def __init__(self, device_id: int, component_config: dict, domain: str) -> None: - self.__get_power = create_request_function(domain, component_config["configuration"]["power_path"]) - self.__get_imported = create_request_function(domain, component_config["configuration"]["imported_path"]) - self.__get_exported = create_request_function(domain, component_config["configuration"]["exported_path"]) + def __init__(self, device_id: int, component_config: dict, url: str) -> None: + self.__get_power = create_request_function(url, component_config["configuration"]["power_path"]) + self.__get_imported = create_request_function(url, component_config["configuration"]["imported_path"]) + self.__get_exported = create_request_function(url, component_config["configuration"]["exported_path"]) self.__get_currents = [ - create_request_function(domain, + create_request_function(url, component_config["configuration"]["current_l" + str(i) + "_path"]) for i in range(1, 4) ] diff --git a/packages/modules/http/device.py b/packages/modules/http/device.py index b846f9f8e..3af141443 100644 --- a/packages/modules/http/device.py +++ b/packages/modules/http/device.py @@ -3,8 +3,6 @@ import re from typing import Dict, Union, List -from urllib3.util import parse_url - from helpermodules.cli import run_using_positional_cli_args from modules.common.abstract_device import AbstractDevice from modules.common.component_context import SingleComponentUpdateContext @@ -21,13 +19,52 @@ def get_default_config() -> dict: "type": "http", "id": 0, "configuration": { - "protocol": "http", - "domain": None, - "port": 80 + "url": None } } +class HttpConfiguration: + def __init__(self, url: str): + self.url = url + + @staticmethod + def from_dict(device_config: dict): + keys = ["url"] + try: + values = [device_config[key] for key in keys] + except KeyError as e: + raise Exception( + "Illegal configuration <{}>: Expected object with properties: {}".format(device_config, keys) + ) from e + return HttpConfiguration(*values) + + +class Http: + def __init__(self, name: str, type: str, id: int, configuration: HttpConfiguration) -> None: + self.name = name + self.type = type + self.id = id + self.configuration = configuration + + @staticmethod + def from_dict(device_config: dict): + keys = ["name", "type", "id", "configuration"] + try: + values = [device_config[key] for key in keys] + values = [] + for key in keys: + if isinstance(device_config[key], Dict): + values.append(HttpConfiguration.from_dict(device_config[key])) + else: + values.append(device_config[key]) + except KeyError as e: + raise Exception( + "Illegal configuration <{}>: Expected object with properties: {}".format(device_config, keys) + ) from e + return Http(*values) + + http_component_classes = Union[bat.HttpBat, counter.HttpCounter, inverter.HttpInverter] @@ -41,12 +78,9 @@ class Device(AbstractDevice): def __init__(self, device_config: dict) -> None: self.components = {} # type: Dict[str, http_component_classes] try: - self.device_config = device_config - port = self.device_config["configuration"]["port"] - self.domain = self.device_config["configuration"]["protocol"] + \ - "://" + self.device_config["configuration"]["domain"] - if port is not None: - self.domain = self.domain + ":" + str(port) + self.device_config = device_config \ + if isinstance(device_config, Http) \ + else Http.from_dict(device_config) except Exception: log.exception("Fehler im Modul "+device_config["name"]) @@ -54,7 +88,7 @@ def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: self.components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( - self.device_config["id"], component_config, self.domain) + self.device_config.id, component_config, self.device_config.configuration.url) else: raise Exception( "illegal component type " + component_type + ". Allowed values: " + @@ -70,7 +104,7 @@ def update(self) -> None: self.components[component].update() else: log.warning( - self.device_config["name"] + + self.device_config.name + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) @@ -104,14 +138,13 @@ def run_device_legacy(device_config: dict, component_config: dict): def create_legacy_device_config(url: str): - parsed_url = parse_url(url) + regex = re.compile("^(https?://[^/]+)(.*)") + match = regex.search(url) + if match is None: + raise Exception("Invalid URL <" + url + ">: Absolute HTTP or HTTPS URL required") + host_scheme = match.group(1) device_config = get_default_config() - device_config["configuration"]["protocol"] = parsed_url.scheme - device_config["configuration"]["domain"] = parsed_url.hostname - if parsed_url.port is not None: - device_config["configuration"]["port"] = int(parsed_url.port) - else: - device_config["configuration"]["port"] = None + device_config["configuration"]["url"] = host_scheme return device_config diff --git a/packages/modules/http/inverter.py b/packages/modules/http/inverter.py index f782b5ac4..d94b6b09a 100644 --- a/packages/modules/http/inverter.py +++ b/packages/modules/http/inverter.py @@ -14,16 +14,16 @@ def get_default_config() -> dict: "id": 0, "type": "inverter", "configuration": { - "power_path": "", - "counter_path": "none", + "power_path": None, + "counter_path": None } } class HttpInverter: - def __init__(self, device_id: int, component_config: dict, domain: str) -> None: - self.__get_power = create_request_function(domain, component_config["configuration"]["power_path"]) - self.__get_counter = create_request_function(domain, component_config["configuration"]["counter_path"]) + def __init__(self, device_id: int, component_config: dict, url: str) -> None: + self.__get_power = create_request_function(url, component_config["configuration"]["power_path"]) + self.__get_counter = create_request_function(url, component_config["configuration"]["counter_path"]) self.__device_id = device_id self.component_config = component_config diff --git a/packages/modules/json/device.py b/packages/modules/json/device.py index 8f916ce4b..545134771 100644 --- a/packages/modules/json/device.py +++ b/packages/modules/json/device.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 import logging from typing import Dict, List, Union, Optional -from urllib3.util import parse_url from helpermodules.cli import run_using_positional_cli_args from modules.common import req @@ -20,13 +19,52 @@ def get_default_config() -> dict: "type": "json", "id": 0, "configuration": { - "protocol": "http", - "domain": None, - "port": 80 + "url": None } } +class JsonConfiguration: + def __init__(self, url: str): + self.url = url + + @staticmethod + def from_dict(device_config: dict): + keys = ["url"] + try: + values = [device_config[key] for key in keys] + except KeyError as e: + raise Exception( + "Illegal configuration <{}>: Expected object with properties: {}".format(device_config, keys) + ) from e + return JsonConfiguration(*values) + + +class Json: + def __init__(self, name: str, type: str, id: int, configuration: JsonConfiguration) -> None: + self.name = name + self.type = type + self.id = id + self.configuration = configuration + + @staticmethod + def from_dict(device_config: dict): + keys = ["name", "type", "id", "configuration"] + try: + values = [device_config[key] for key in keys] + values = [] + for key in keys: + if isinstance(device_config[key], Dict): + values.append(JsonConfiguration.from_dict(device_config[key])) + else: + values.append(device_config[key]) + except KeyError as e: + raise Exception( + "Illegal configuration <{}>: Expected object with properties: {}".format(device_config, keys) + ) from e + return Json(*values) + + json_component_classes = Union[bat.JsonBat, counter.JsonCounter, inverter.JsonInverter] @@ -40,11 +78,9 @@ class Device(AbstractDevice): def __init__(self, device_config: dict) -> None: self.components = {} # type: Dict[str, json_component_classes] try: - self.device_config = device_config - port = self.device_config["configuration"]["port"] - self.domain = self.device_config["configuration"]["protocol"] + \ - "://" + self.device_config["configuration"]["domain"] + \ - ":" + str(port) if port else "" + self.device_config = device_config \ + if isinstance(device_config, Json) \ + else Json.from_dict(device_config) except Exception: log.exception("Fehler im Modul "+device_config["name"]) @@ -52,7 +88,7 @@ def add_component(self, component_config: dict) -> None: component_type = component_config["type"] if component_type in self.COMPONENT_TYPE_TO_CLASS: self.components["component"+str(component_config["id"])] = self.COMPONENT_TYPE_TO_CLASS[component_type]( - self.device_config["id"], component_config) + self.device_config.id, component_config) else: raise Exception( "illegal component type " + component_type + ". Allowed values: " + @@ -63,26 +99,22 @@ def update(self) -> None: log.debug("Start device reading " + str(self.components)) if self.components: with MultiComponentUpdateContext(self.components): - response = req.get_http_session().get(self.domain, timeout=5) + response = req.get_http_session().get(self.device_config.configuration.url, timeout=5) for component in self.components: self.components[component].update(response.json()) else: log.warning( - self.device_config["name"] + + self.device_config.name + ": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden." ) -def read_legacy(ip_address: str, component_config: dict, num: Optional[int] = None, **kwargs) -> None: +def read_legacy(url: str, component_config: dict, num: Optional[int] = None, **kwargs) -> None: component_config["configuration"].update(kwargs) component_config["id"] = num - parsed_url = parse_url(ip_address) device_config = get_default_config() - device_config["configuration"]["protocol"] = parsed_url.scheme - device_config["configuration"]["domain"] = parsed_url.hostname - device_config["configuration"]["port"] = int(parsed_url.port) - + device_config["configuration"]["url"] = url dev = Device(device_config) dev.add_component(component_config) dev.update() From 37c73b6c905f8efb71d63ccbe60b1558c9e40031 Mon Sep 17 00:00:00 2001 From: LKuemmel Date: Wed, 25 May 2022 16:32:46 +0200 Subject: [PATCH 5/9] fix second fronius inverter --- packages/modules/fronius/device.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/modules/fronius/device.py b/packages/modules/fronius/device.py index de0d56a5a..74776a46f 100644 --- a/packages/modules/fronius/device.py +++ b/packages/modules/fronius/device.py @@ -109,12 +109,11 @@ def read_legacy( dev.update() elif component_type == "inverter" and num: inverter1 = inverter.FroniusInverter(num, component_config, dev.config.configuration) - if ip_address2 != "none": - device_config["configuration"]["ip_address"] = ip_address2 - inverter2 = inverter.FroniusInverter(num, component_config, dev.config.configuration) with SingleComponentUpdateContext(inverter1.component_info): total_power = inverter1.read_power() if ip_address2 != "none": + dev.config.configuration.ip_address = ip_address2 + inverter2 = inverter.FroniusInverter(num, component_config, dev.config.configuration) total_power += inverter2.read_power() get_inverter_value_store(num).set(inverter1.fill_inverter_state(total_power)) else: From 39234dce3e5e75e758b183218721949974512eb2 Mon Sep 17 00:00:00 2001 From: Penny <89247538+hhoefling@users.noreply.github.com> Date: Wed, 25 May 2022 17:36:54 +0200 Subject: [PATCH 6/9] Update minundpv.sh --- minundpv.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/minundpv.sh b/minundpv.sh index f133bdc3a..b346a59c6 100644 --- a/minundpv.sh +++ b/minundpv.sh @@ -7,7 +7,7 @@ minundpvlademodus(){ if [[ $u1p3paktiv == "1" ]]; then u1p3pstat=$( Date: Fri, 27 May 2022 08:53:27 +0200 Subject: [PATCH 7/9] bump version 1.9.267 --- web/version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/version b/web/version index 589bada37..33e46aca8 100644 --- a/web/version +++ b/web/version @@ -1 +1 @@ -1.9.266 +1.9.267 From 4cd204127517da0a10959c224e8ac52937d7b8a0 Mon Sep 17 00:00:00 2001 From: Flock82 <81387035+Flock82@users.noreply.github.com> Date: Fri, 27 May 2022 22:27:16 +0200 Subject: [PATCH 8/9] [BMW/Mini] - New User-Agent --- modules/soc_i3/i3soc.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/soc_i3/i3soc.py b/modules/soc_i3/i3soc.py index e82fd6728..b404b7248 100644 --- a/modules/soc_i3/i3soc.py +++ b/modules/soc_i3/i3soc.py @@ -174,7 +174,8 @@ def requestData(token: str, vin: str) -> dict: url = 'https://' + api_server + '/eadrax-vcs/v1/vehicles?apptimezone=0&appDateTime=' + str(int(time.time())) + '&tireGuardMode=ENABLED' headers = { - 'x-user-agent': 'android(v1.07_20200330);' + brand + ';1.7.0(11152)', + 'User-Agent': 'Dart/2.14 (dart:io)', + 'x-user-agent': 'android(SP1A.210812.016.C1);' + brand + ';2.5.2(14945);row', 'Authorization': (token["token_type"] + " " + token["access_token"])} body = getHTTP(url, headers) response = json.loads(body) From 272ae942843143993111ba82142d51fe6e617cbc Mon Sep 17 00:00:00 2001 From: benderl Date: Fri, 27 May 2022 23:14:10 +0200 Subject: [PATCH 9/9] Bump Version 1.9.268 --- web/version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/version b/web/version index 33e46aca8..95a18d5c7 100644 --- a/web/version +++ b/web/version @@ -1 +1 @@ -1.9.267 +1.9.268