Skip to content

Commit

Permalink
fix style errors reported by flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
yankee42 committed Nov 11, 2021
1 parent ef1f2b9 commit be17309
Show file tree
Hide file tree
Showing 24 changed files with 233 additions and 119 deletions.
1 change: 1 addition & 0 deletions packages/helpermodules/compatibility.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from pathlib import Path


def is_ramdisk_in_use() -> bool:
""" prüft, ob die Daten in der Ramdisk liegen (v1.x), sonst wird mit dem Broker (2.x) gearbeitet.
"""
Expand Down
9 changes: 4 additions & 5 deletions packages/helpermodules/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

try:
from . import compatibility
except:
except ImportError:
from helpermodules import compatibility

debug_logger = None
Expand Down Expand Up @@ -66,9 +65,9 @@ def __write_log(self, message: str):
"""
try:
local_time = datetime.now(timezone.utc).astimezone()
myPid = str(os.getpid())
print(local_time.strftime(format="%Y-%m-%d %H:%M:%S") + ": PID: " + myPid + ": " + message)
except:
my_pid = str(os.getpid())
print(local_time.strftime(format="%Y-%m-%d %H:%M:%S") + ": PID: " + my_pid + ": " + message)
except Exception:
traceback.print_exc()

instance = None
Expand Down
18 changes: 11 additions & 7 deletions packages/helpermodules/pub.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,27 @@

import json
import os
from typing import Optional

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish

from . import log

client = None
client = None # type: Optional[mqtt.Client]


def setup_connection():
""" öffnet die Verbindugn zum Broker. Bei Verbindungsabbruch wird automatisch versucht, eine erneute Verbindung herzustellen.
"""Öffnet die Verbindung zum Broker.
Bei Verbindungsabbruch wird automatisch versucht, eine erneute Verbindung herzustellen.
"""
try:
global client
client = mqtt.Client("openWB-python-bulkpublisher-" + str(os.getpid()))
client.connect("localhost", 1886)
client.loop_start()
except Exception as e:
except Exception:
log.MainLogger().exception("Fehler im pub-Modul")


Expand All @@ -39,7 +43,7 @@ def pub(topic, payload):
client.publish(topic, payload, qos=0, retain=True)
else:
client.publish(topic, payload=json.dumps(payload), qos=0, retain=True)
except Exception as e:
except Exception:
log.MainLogger().exception("Fehler im pub-Modul")


Expand All @@ -49,7 +53,7 @@ def delete_connection():
try:
client.loop_stop()
client.disconnect
except Exception as e:
except Exception:
log.MainLogger().exception("Fehler im pub-Modul")


Expand All @@ -68,9 +72,9 @@ def pub_single(topic, payload, hostname="localhost", no_json=False):
Kompabilität mit isss, die ramdisk verwenden.
"""
try:
if no_json == True:
if no_json:
publish.single(topic, payload, hostname=hostname, retain=True)
else:
publish.single(topic, json.dumps(payload), hostname=hostname, retain=True)
except Exception as e:
except Exception:
log.MainLogger().exception("Fehler im pub-Modul")
10 changes: 7 additions & 3 deletions packages/modules/alpha_ess/bat.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from ..common import modbus
from ..common.abstract_component import AbstractBat
from ..common.component_state import BatState
except:
except ImportError:
from helpermodules import log
from modules.common import modbus
from modules.common.abstract_component import AbstractBat
Expand Down Expand Up @@ -43,13 +43,17 @@ def get_values(self) -> BatState:
current = self.client.read_holding_registers(0x0101, modbus.ModbusDataType.INT_16, unit=sdmid)

power = voltage * current * -1 / 100
log.MainLogger().debug("Alpha Ess Leistung[W]: "+str(power)+", Speicher-Register: Spannung[V] "+str(voltage)+" Strom[A] "+str(current))
log.MainLogger().debug(
"Alpha Ess Leistung[W]: %f, Speicher-Register: Spannung[V]: %f, Strom[A]: %f" % (power, voltage, current)
)
time.sleep(0.1)
soc_reg = self.client.read_holding_registers(0x0102, modbus.ModbusDataType.INT_16, unit=sdmid)
soc = int(soc_reg * 0.1)

topic_str = "openWB/set/system/device/" + str(self.device_id)+"/component/"+str(self.data["config"]["id"])+"/"
imported, exported = self.sim_count.sim_count(power, topic=topic_str, data=self.data["simulation"], prefix="speicher")
imported, exported = self.sim_count.sim_count(
power, topic=topic_str, data=self.data["simulation"], prefix="speicher"
)
bat_state = BatState(
power=power,
soc=soc,
Expand Down
6 changes: 3 additions & 3 deletions packages/modules/alpha_ess/counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from ..common.abstract_component import AbstractCounter
from ..common.component_state import CounterState
from ..common.module_error import ModuleError
except:
except ImportError:
from helpermodules import log
from modules.common import modbus
from modules.common.abstract_component import AbstractCounter
Expand Down Expand Up @@ -72,7 +72,7 @@ def __get_values_before_v123(self, unit: int) -> CounterState:
frequency=50
)
return counter_state
except ModuleError as e:
except ModuleError:
raise
except Exception as e:
self.process_error(e)
Expand Down Expand Up @@ -103,7 +103,7 @@ def __get_values_since_v123(self, unit: int) -> CounterState:
frequency=50
)
return counter_state
except ModuleError as e:
except ModuleError:
raise
except Exception as e:
self.process_error(e)
15 changes: 9 additions & 6 deletions packages/modules/alpha_ess/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
""" Modul zum Auslesen von Alpha Ess Speichern, Zählern und Wechselrichtern.
"""
import sys
from typing import List, Union
from typing import List

try:
from ...helpermodules import log
Expand All @@ -11,7 +11,7 @@
from . import bat
from . import counter
from . import inverter
except:
except ImportError:
from helpermodules import log
from modules.common import modbus
from modules.common import abstract_device
Expand Down Expand Up @@ -39,7 +39,7 @@ def __init__(self, device: dict) -> None:
try:
client = modbus.ModbusClient("192.168.193.125", 8899)
super().__init__(device, client)
except Exception as e:
except Exception:
log.MainLogger().exception("Fehler im Modul "+device["name"])

def add_component(self, component_config: dict) -> None:
Expand All @@ -57,7 +57,7 @@ def read_legacy(argv: List[str]) -> None:
version = int(argv[2])
try:
num = int(argv[3])
except:
except ValueError:
num = None

device_config = get_default_config()
Expand All @@ -66,7 +66,10 @@ def read_legacy(argv: List[str]) -> None:
if component_type in COMPONENT_TYPE_TO_MODULE:
component_config = COMPONENT_TYPE_TO_MODULE[component_type].get_default_config()
else:
raise Exception("illegal component type "+component_type+". Allowed values: "+','.join(COMPONENT_TYPE_TO_MODULE.keys()))
raise Exception(
"illegal component type " + component_type + ". Allowed values: " +
','.join(COMPONENT_TYPE_TO_MODULE.keys())
)
component_config["id"] = num
component_config["configuration"]["version"] = version
dev.add_component(component_config)
Expand All @@ -79,5 +82,5 @@ def read_legacy(argv: List[str]) -> None:
if __name__ == "__main__":
try:
read_legacy(sys.argv)
except:
except Exception:
log.MainLogger().exception("Fehler im Alpha Ess Skript")
8 changes: 5 additions & 3 deletions packages/modules/alpha_ess/inverter.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
#!/usr/bin/env python3
import time

try:
from ...helpermodules import log
from ..common import modbus
from ..common.abstract_component import AbstractInverter
from ..common.component_state import InverterState
from ..common.module_error import ModuleError
except:
except ImportError:
from helpermodules import log
from modules.common import modbus
from modules.common.abstract_component import AbstractInverter
Expand Down Expand Up @@ -58,7 +57,10 @@ def __version_factory(self, version: int) -> int:

def __get_power(self, unit: int, reg_p: int) -> int:
try:
powers = [self.client.read_holding_registers(address, modbus.ModbusDataType.INT_32, unit=unit) for address in [reg_p, 0x041F, 0x0423, 0x0427]]
powers = [
self.client.read_holding_registers(address, modbus.ModbusDataType.INT_32, unit=unit)
for address in [reg_p, 0x041F, 0x0423, 0x0427]
]
powers[0] = abs(powers[0])
power = sum(powers) * -1
log.MainLogger().debug("Alpha Ess Leistung: "+str(power)+", WR-Register: " + str(powers))
Expand Down
44 changes: 33 additions & 11 deletions packages/modules/common/abstract_component.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from abc import abstractmethod
from typing import List, Union
from typing import Union
try:
from ...helpermodules import log
from ..common import modbus
Expand All @@ -10,7 +10,7 @@
from ..common import store
from ..common.module_error import ModuleError, ModuleErrorLevel
from component_state import BatState, CounterState, InverterState
except:
except ImportError:
from helpermodules import log
from modules.common import modbus
from modules.common import lovato
Expand All @@ -23,16 +23,23 @@


class AbstractComponent:
def __init__(self, device_id: int, component_config: dict, client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]) -> None:
def __init__(
self,
device_id: int,
component_config: dict,
client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]
) -> None:
try:
self.device_id = device_id
self.client = client
self.data = {"config": component_config,
"simulation": {}}
self.value_store = (store.ValueStoreFactory().get_storage(component_config["type"]))(self.data["config"]["id"])
self.value_store = (store.ValueStoreFactory().get_storage(component_config["type"]))(
self.data["config"]["id"]
)
simcount_factory = simcount.SimCountFactory().get_sim_counter()
self.sim_count = simcount_factory()
except Exception as e:
except Exception:
log.MainLogger().exception("Fehler im Modul "+self.data["config"]["name"])

@abstractmethod
Expand All @@ -50,13 +57,19 @@ def update_values(self) -> Union[BatState, CounterState, InverterState]:
self.process_error(e)
raise ModuleError("", ModuleErrorLevel.ERROR)
else:
ModuleError("Kein Fehler.", ModuleErrorLevel.NO_ERROR).store_error(self.data["config"]["id"], self.data["config"]["type"], self.data["config"]["name"])
ModuleError("Kein Fehler.", ModuleErrorLevel.NO_ERROR).store_error(
self.data["config"]["id"], self.data["config"]["type"], self.data["config"]["name"]
)
return state

def process_error(self, e):
ModuleError(str(type(e))+" "+str(e), ModuleErrorLevel.ERROR).store_error(self.data["config"]["id"], self.data["config"]["type"], self.data["config"]["name"])
ModuleError(str(type(e))+" "+str(e), ModuleErrorLevel.ERROR).store_error(
self.data["config"]["id"], self.data["config"]["type"], self.data["config"]["name"]
)

def kit_version_factory(self, version: int, id: int, tcp_client: modbus.ModbusClient) -> Union[mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]:
def kit_version_factory(self, version: int, id: int, tcp_client: modbus.ModbusClient) -> Union[
mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630
]:
try:
if version == 0:
return mpm3pm.Mpm3pm(id, tcp_client)
Expand All @@ -71,7 +84,10 @@ def kit_version_factory(self, version: int, id: int, tcp_client: modbus.ModbusCl


class AbstractBat(AbstractComponent):
def __init__(self, device_id: int, component_config: dict, client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]) -> None:
def __init__(self,
device_id: int,
component_config: dict,
client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]) -> None:
super().__init__(device_id, component_config, client)

@abstractmethod
Expand All @@ -83,7 +99,10 @@ def update_values(self) -> BatState:


class AbstractCounter(AbstractComponent):
def __init__(self, device_id: int, component_config: dict, client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]) -> None:
def __init__(self,
device_id: int,
component_config: dict,
client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]) -> None:
super().__init__(device_id, component_config, client)

@abstractmethod
Expand All @@ -95,7 +114,10 @@ def update_values(self) -> CounterState:


class AbstractInverter(AbstractComponent):
def __init__(self, device_id: int, component_config: dict, client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]) -> None:
def __init__(self,
device_id: int,
component_config: dict,
client: Union[modbus.ModbusClient, mpm3pm.Mpm3pm, lovato.Lovato, sdm630.Sdm630]) -> None:
super().__init__(device_id, component_config, client)

@abstractmethod
Expand Down
28 changes: 19 additions & 9 deletions packages/modules/common/abstract_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from ...helpermodules import log
from ..common import modbus
from ..common.module_error import ModuleError
except:
except ImportError:
from helpermodules import log
from modules.common import modbus
from modules.common.module_error import ModuleError
Expand All @@ -19,21 +19,25 @@ def __init__(self, device: dict, client: modbus.ModbusClient) -> None:
self.data = {"config": device,
"components": {}}
self.client = client
except:
except Exception:
log.MainLogger().exception("Fehler im Modul "+device["name"])

def instantiate_component(self, component_config: dict, factory) -> None:
try:
self.data["components"]["component"+str(component_config["id"])] = factory(self.data["config"]["id"], component_config, self.client)
except:
self.data["components"]["component"+str(component_config["id"])] = factory(
self.data["config"]["id"], component_config, self.client
)
except Exception:
log.MainLogger().exception("Fehler im Modul "+self.data["config"]["name"])

def component_factory(self, component_type: str):
try:
if component_type in self.COMPONENT_TYPE_TO_CLASS:
return self.COMPONENT_TYPE_TO_CLASS[component_type]
raise Exception("illegal component type "+component_type+". Allowed values: "+','.join(self.COMPONENT_TYPE_TO_CLASS.keys()))
except Exception as e:
raise Exception("illegal component type "+component_type+". Allowed values: "+','.join(
self.COMPONENT_TYPE_TO_CLASS.keys()
))
except Exception:
log.MainLogger().exception("Fehler im Modul "+self.data["config"]["name"])

@abstractmethod
Expand All @@ -47,8 +51,14 @@ def update_values(self):
for component in self.data["components"]:
self.data["components"][component].update_values()
else:
log.MainLogger().warning(self.data["config"]["name"]+": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden.")
log.MainLogger().warning(
self.data["config"]["name"] +
": Es konnten keine Werte gelesen werden, da noch keine Komponenten konfiguriert wurden."
)
except ModuleError:
log.MainLogger().error("Beim Auslesen eines Moduls ist ein Fehler aufgetreten. Auslesen des Devices "+self.data["config"]["name"]+" beendet.")
except:
log.MainLogger().error(
"Beim Auslesen eines Moduls ist ein Fehler aufgetreten. Auslesen des Devices %s beendet." %
self.data["config"]["name"]
)
except Exception:
log.MainLogger().exception("Fehler im Modul "+self.data["config"]["name"])
Loading

0 comments on commit be17309

Please sign in to comment.