From 0aba139aeff8ff80757c5d36502413299a0b449e Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Thu, 11 May 2023 04:18:08 +0300 Subject: mqtt, esp: add new esp8266-based device --- src/home/mqtt/payload/base_payload.py | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) (limited to 'src/home/mqtt/payload/base_payload.py') diff --git a/src/home/mqtt/payload/base_payload.py b/src/home/mqtt/payload/base_payload.py index 108e0c0..1abd898 100644 --- a/src/home/mqtt/payload/base_payload.py +++ b/src/home/mqtt/payload/base_payload.py @@ -5,7 +5,21 @@ import re from typing import Optional, Tuple -class MQTTPayload(abc.ABC): +def pldstr(self) -> str: + attrs = [] + for field in self.__class__.__annotations__: + if hasattr(self, field): + attr = getattr(self, field) + attrs.append(f'{field}={attr}') + if attrs: + attrs_s = ' ' + attrs_s += ', '.join(attrs) + else: + attrs_s = '' + return f'<%s{attrs_s}>' % (self.__class__.__name__,) + + +class MqttPayload(abc.ABC): FORMAT = '' PACKER = {} UNPACKER = {} @@ -70,7 +84,7 @@ class MQTTPayload(abc.ABC): bf_number = -1 i += 1 - if issubclass(field_type, MQTTPayloadCustomField): + if issubclass(field_type, MqttPayloadCustomField): kwargs[field] = field_type.unpack(data[i]) else: kwargs[field] = cls._unpack_field(field, data[i]) @@ -87,15 +101,18 @@ class MQTTPayload(abc.ABC): @classmethod def _unpack_field(cls, name, val): - if isinstance(val, MQTTPayloadCustomField): + if isinstance(val, MqttPayloadCustomField): return if cls.UNPACKER and name in cls.UNPACKER: return cls.UNPACKER[name](val) else: return val + def __str__(self): + return pldstr(self) -class MQTTPayloadCustomField(abc.ABC): + +class MqttPayloadCustomField(abc.ABC): def __init__(self, **kwargs): for field in self.__class__.__annotations__: setattr(self, field, kwargs[field]) @@ -109,6 +126,9 @@ class MQTTPayloadCustomField(abc.ABC): def unpack(cls, *args, **kwargs): pass + def __str__(self): + return pldstr(self) + def bit_field(seq_no: int, total_bits: int, bits: int): return type(f'MQTTPayloadBitField_{seq_no}_{total_bits}_{bits}', (object,), { -- cgit v1.2.3