use Enum class for State

This commit is contained in:
Stefan Allius
2024-06-16 17:50:09 +02:00
parent f5e7aa4292
commit e0568291f6
5 changed files with 51 additions and 46 deletions

View File

@@ -4,12 +4,12 @@ import time
from datetime import datetime from datetime import datetime
if __name__ == "app.src.gen3.talent": if __name__ == "app.src.gen3.talent":
from app.src.messages import hex_dump_memory, Message from app.src.messages import hex_dump_memory, Message, State
from app.src.modbus import Modbus from app.src.modbus import Modbus
from app.src.config import Config from app.src.config import Config
from app.src.gen3.infos_g3 import InfosG3 from app.src.gen3.infos_g3 import InfosG3
else: # pragma: no cover else: # pragma: no cover
from messages import hex_dump_memory, Message from messages import hex_dump_memory, Message, State
from modbus import Modbus from modbus import Modbus
from config import Config from config import Config
from gen3.infos_g3 import InfosG3 from gen3.infos_g3 import InfosG3
@@ -71,13 +71,13 @@ class Talent(Message):
Our puplic methods Our puplic methods
''' '''
def close(self) -> None: def close(self) -> None:
logging.debug('Talent.close()') logging.info('Talent.close()')
# we have refernces to methods of this class in self.switch # we have refernces to methods of this class in self.switch
# so we have to erase self.switch, otherwise this instance can't be # so we have to erase self.switch, otherwise this instance can't be
# deallocated by the garbage collector ==> we get a memory leak # deallocated by the garbage collector ==> we get a memory leak
self.switch.clear() self.switch.clear()
self.log_lvl.clear() self.log_lvl.clear()
self.state = self.STATE_CLOSED self.state = State.closed
super().close() super().close()
def __set_serial_no(self, serial_no: str): def __set_serial_no(self, serial_no: str):
@@ -141,7 +141,7 @@ class Talent(Message):
return return
def send_modbus_cb(self, modbus_pdu: bytearray, log_lvl: int, state: str): def send_modbus_cb(self, modbus_pdu: bytearray, log_lvl: int, state: str):
if self.state != self.STATE_UP: if self.state != State.up:
logger.warning(f'[{self.node_id}] ignore MODBUS cmd,' logger.warning(f'[{self.node_id}] ignore MODBUS cmd,'
' cause the state is not UP anymore') ' cause the state is not UP anymore')
return return
@@ -158,7 +158,7 @@ class Talent(Message):
self._send_buffer = bytearray(0) # self._send_buffer[sent:] self._send_buffer = bytearray(0) # self._send_buffer[sent:]
async def send_modbus_cmd(self, func, addr, val, log_lvl) -> None: async def send_modbus_cmd(self, func, addr, val, log_lvl) -> None:
if self.state != self.STATE_UP: if self.state != State.up:
logger.log(log_lvl, f'[{self.node_id}] ignore MODBUS cmd,' logger.log(log_lvl, f'[{self.node_id}] ignore MODBUS cmd,'
' as the state is not UP') ' as the state is not UP')
return return
@@ -371,7 +371,7 @@ class Talent(Message):
self._send_buffer += b'\x01' self._send_buffer += b'\x01'
self.__finish_send_msg() self.__finish_send_msg()
self.__process_data() self.__process_data()
self.state = self.STATE_UP self.state = State.up
elif self.ctrl.is_resp(): elif self.ctrl.is_resp():
return # ignore received response return # ignore received response
@@ -387,7 +387,7 @@ class Talent(Message):
self._send_buffer += b'\x01' self._send_buffer += b'\x01'
self.__finish_send_msg() self.__finish_send_msg()
self.__process_data() self.__process_data()
self.state = self.STATE_UP self.state = State.up
elif self.ctrl.is_resp(): elif self.ctrl.is_resp():
return # ignore received response return # ignore received response

View File

@@ -6,13 +6,13 @@ import asyncio
from datetime import datetime from datetime import datetime
if __name__ == "app.src.gen3plus.solarman_v5": if __name__ == "app.src.gen3plus.solarman_v5":
from app.src.messages import hex_dump_memory, Message from app.src.messages import hex_dump_memory, Message, State
from app.src.modbus import Modbus from app.src.modbus import Modbus
from app.src.config import Config from app.src.config import Config
from app.src.gen3plus.infos_g3p import InfosG3P from app.src.gen3plus.infos_g3p import InfosG3P
from app.src.infos import Register from app.src.infos import Register
else: # pragma: no cover else: # pragma: no cover
from messages import hex_dump_memory, Message from messages import hex_dump_memory, Message, State
from config import Config from config import Config
from modbus import Modbus from modbus import Modbus
from gen3plus.infos_g3p import InfosG3P from gen3plus.infos_g3p import InfosG3P
@@ -135,7 +135,7 @@ class SolarmanV5(Message):
# deallocated by the garbage collector ==> we get a memory leak # deallocated by the garbage collector ==> we get a memory leak
self.switch.clear() self.switch.clear()
self.log_lvl.clear() self.log_lvl.clear()
self.state = self.STATE_CLOSED self.state = State.closed
super().close() super().close()
def __set_serial_no(self, snr: int): def __set_serial_no(self, snr: int):
@@ -345,7 +345,7 @@ class SolarmanV5(Message):
self.__finish_send_msg() self.__finish_send_msg()
def send_modbus_cb(self, pdu: bytearray, log_lvl: int, state: str): def send_modbus_cb(self, pdu: bytearray, log_lvl: int, state: str):
if self.state != self.STATE_UP: if self.state != State.up:
logger.warning(f'[{self.node_id}] ignore MODBUS cmd,' logger.warning(f'[{self.node_id}] ignore MODBUS cmd,'
' cause the state is not UP anymore') ' cause the state is not UP anymore')
return return
@@ -360,7 +360,7 @@ class SolarmanV5(Message):
self._send_buffer = bytearray(0) # self._send_buffer[sent:] self._send_buffer = bytearray(0) # self._send_buffer[sent:]
async def send_modbus_cmd(self, func, addr, val, log_lvl) -> None: async def send_modbus_cmd(self, func, addr, val, log_lvl) -> None:
if self.state != self.STATE_UP: if self.state != State.up:
logger.log(log_lvl, f'[{self.node_id}] ignore MODBUS cmd,' logger.log(log_lvl, f'[{self.node_id}] ignore MODBUS cmd,'
' as the state is not UP') ' as the state is not UP')
return return
@@ -371,7 +371,7 @@ class SolarmanV5(Message):
cmd.startswith(tuple(self.at_acl[connection]['block'])) cmd.startswith(tuple(self.at_acl[connection]['block']))
async def send_at_cmd(self, AT_cmd: str) -> None: async def send_at_cmd(self, AT_cmd: str) -> None:
if self.state != self.STATE_UP: if self.state != State.up:
logger.warning(f'[{self.node_id}] ignore AT+ cmd,' logger.warning(f'[{self.node_id}] ignore AT+ cmd,'
' as the state is not UP') ' as the state is not UP')
return return
@@ -471,7 +471,7 @@ class SolarmanV5(Message):
self.__process_data(ftype) self.__process_data(ftype)
self.__forward_msg() self.__forward_msg()
self.__send_ack_rsp(0x1210, ftype) self.__send_ack_rsp(0x1210, ftype)
self.state = self.STATE_UP self.state = State.up
def msg_sync_start(self): def msg_sync_start(self):
data = self._recv_buffer[self.header_len:] data = self._recv_buffer[self.header_len:]
@@ -567,7 +567,7 @@ class SolarmanV5(Message):
self.__forward_msg() self.__forward_msg()
self.__send_ack_rsp(0x1710, ftype) self.__send_ack_rsp(0x1710, ftype)
self.state = self.STATE_UP self.state = State.up
def msg_sync_end(self): def msg_sync_end(self):
data = self._recv_buffer[self.header_len:] data = self._recv_buffer[self.header_len:]

View File

@@ -1,6 +1,7 @@
import logging import logging
import weakref import weakref
from typing import Callable, Generator from typing import Callable, Generator
from enum import Enum
if __name__ == "app.src.messages": if __name__ == "app.src.messages":
@@ -52,11 +53,14 @@ class IterRegistry(type):
yield obj yield obj
class State(Enum):
init = 0
up = 2
closed = 3
class Message(metaclass=IterRegistry): class Message(metaclass=IterRegistry):
_registry = [] _registry = []
STATE_INIT = 0
STATE_UP = 2
STATE_CLOSED = 3
def __init__(self, server_side: bool, send_modbus_cb: def __init__(self, server_side: bool, send_modbus_cb:
Callable[[bytes, int, str], None], mb_timeout: int): Callable[[bytes, int, str], None], mb_timeout: int):
@@ -78,7 +82,7 @@ class Message(metaclass=IterRegistry):
self._send_buffer = bytearray(0) self._send_buffer = bytearray(0)
self._forward_buffer = bytearray(0) self._forward_buffer = bytearray(0)
self.new_data = {} self.new_data = {}
self.state = self.STATE_INIT self.state = State.init
''' '''
Empty methods, that have to be implemented in any child class which Empty methods, that have to be implemented in any child class which

View File

@@ -1682,21 +1682,21 @@ def test_zombie_conn(ConfigTsunInv1, MsgInverterInd):
m1 = MemoryStream(MsgInverterInd, (0,)) m1 = MemoryStream(MsgInverterInd, (0,))
m2 = MemoryStream(MsgInverterInd, (0,)) m2 = MemoryStream(MsgInverterInd, (0,))
m3 = MemoryStream(MsgInverterInd, (0,)) m3 = MemoryStream(MsgInverterInd, (0,))
assert m1.state == m1.STATE_INIT assert m1.state == m1.State.init
assert m2.state == m2.STATE_INIT assert m2.state == m2.State.init
assert m3.state == m3.STATE_INIT assert m3.state == m3.State.init
m1.read() # read complete msg, and set unique_id m1.read() # read complete msg, and set unique_id
assert m1.state == m1.STATE_INIT assert m1.state == m1.State.init
assert m2.state == m2.STATE_INIT assert m2.state == m2.State.init
assert m3.state == m3.STATE_INIT assert m3.state == m3.State.init
m2.read() # read complete msg, and set unique_id m2.read() # read complete msg, and set unique_id
assert m1.state == m1.STATE_CLOSED assert m1.state == m1.State.closed
assert m2.state == m2.STATE_INIT assert m2.state == m2.State.init
assert m3.state == m3.STATE_INIT assert m3.state == m3.State.init
m3.read() # read complete msg, and set unique_id m3.read() # read complete msg, and set unique_id
assert m1.state == m1.STATE_CLOSED assert m1.state == m1.State.closed
assert m2.state == m2.STATE_CLOSED assert m2.state == m2.State.closed
assert m3.state == m3.STATE_INIT assert m3.state == m3.State.init
m1.close() m1.close()
m2.close() m2.close()
m3.close() m3.close()

View File

@@ -4,6 +4,7 @@ from app.src.gen3.talent import Talent, Control
from app.src.config import Config from app.src.config import Config
from app.src.infos import Infos, Register from app.src.infos import Infos, Register
from app.src.modbus import Modbus from app.src.modbus import Modbus
from app.src.messages import State
pytest_plugins = ('pytest_asyncio',) pytest_plugins = ('pytest_asyncio',)
@@ -909,7 +910,7 @@ def test_msg_modbus_req(ConfigTsunInv1, MsgModbusCmd):
ConfigTsunInv1 ConfigTsunInv1
m = MemoryStream(b'') m = MemoryStream(b'')
m.id_str = b"R170000000000001" m.id_str = b"R170000000000001"
m.state = m.STATE_UP m.state = State.up
c = m.createClientStream(MsgModbusCmd) c = m.createClientStream(MsgModbusCmd)
@@ -1159,7 +1160,7 @@ async def test_msg_build_modbus_req(ConfigTsunInv1, MsgModbusCmd):
assert m._send_buffer == b'' assert m._send_buffer == b''
assert m.writer.sent_pdu == b'' assert m.writer.sent_pdu == b''
m.state = m.STATE_UP m.state = State.up
await m.send_modbus_cmd(Modbus.WRITE_SINGLE_REG, 0x2008, 0, logging.DEBUG) await m.send_modbus_cmd(Modbus.WRITE_SINGLE_REG, 0x2008, 0, logging.DEBUG)
assert 0 == m.send_msg_ofs assert 0 == m.send_msg_ofs
assert m._forward_buffer == b'' assert m._forward_buffer == b''
@@ -1189,21 +1190,21 @@ def test_zombie_conn(ConfigTsunInv1, MsgInverterInd):
m3 = MemoryStream(MsgInverterInd, (0,)) m3 = MemoryStream(MsgInverterInd, (0,))
assert MemoryStream._RefNo == 3 + start_val assert MemoryStream._RefNo == 3 + start_val
assert m3.RefNo == 3 + start_val assert m3.RefNo == 3 + start_val
assert m1.state == m1.STATE_INIT assert m1.state == m1.State.init
assert m2.state == m2.STATE_INIT assert m2.state == m2.State.init
assert m3.state == m3.STATE_INIT assert m3.state == m3.State.init
m1.read() # read complete msg, and set unique_id m1.read() # read complete msg, and set unique_id
assert m1.state == m1.STATE_UP assert m1.state == m1.State.up
assert m2.state == m2.STATE_INIT assert m2.state == m2.State.init
assert m3.state == m3.STATE_INIT assert m3.state == m3.State.init
m2.read() # read complete msg, and set unique_id m2.read() # read complete msg, and set unique_id
assert m1.state == m1.STATE_CLOSED assert m1.state == m1.State.closed
assert m2.state == m2.STATE_UP assert m2.state == m2.State.up
assert m3.state == m3.STATE_INIT assert m3.state == m3.State.init
m3.read() # read complete msg, and set unique_id m3.read() # read complete msg, and set unique_id
assert m1.state == m1.STATE_CLOSED assert m1.state == m1.State.closed
assert m2.state == m2.STATE_CLOSED assert m2.state == m2.State.closed
assert m3.state == m3.STATE_UP assert m3.state == m3.State.up
m1.close() m1.close()
m2.close() m2.close()
m3.close() m3.close()