working enum

This commit is contained in:
2026-07-28 05:02:15 +02:00
parent 70157b8bd9
commit 9ff3ef4521
+25 -3
View File
@@ -2,10 +2,11 @@ import struct
import typing import typing
from typing import get_type_hints, get_origin, get_args from typing import get_type_hints, get_origin, get_args
class PWPError(Exception): class PWPError(Exception):
pass pass
class uint8:
pass
def encode_value(value, typ) -> bytes: def encode_value(value, typ) -> bytes:
origin = get_origin(typ) origin = get_origin(typ)
@@ -61,7 +62,9 @@ def encode_value(value, typ) -> bytes:
if typ is bool: if typ is bool:
return b"\x01" if value else b"\x00" return b"\x01" if value else b"\x00"
# nested PWP class if typ is uint8:
return struct.pack("<B", value)
if hasattr(value, "to_com"): if hasattr(value, "to_com"):
return value.to_com() return value.to_com()
@@ -144,6 +147,9 @@ def decode_value(data: bytes, offset: int, typ):
if typ is bool: if typ is bool:
return data[offset] != 0, offset + 1 return data[offset] != 0, offset + 1
if typ is uint8:
return data[offset], offset + 1
# nested PWP class # nested PWP class
if hasattr(typ, "from_com"): if hasattr(typ, "from_com"):
return typ.from_com(data[offset:]), len(data) return typ.from_com(data[offset:]), len(data)
@@ -163,7 +169,7 @@ def pwp(cls):
return output return output
@classmethod @classmethod
def from_com(cls, data): def from_com(data):
values = {} values = {}
offset = 0 offset = 0
@@ -177,3 +183,19 @@ def pwp(cls):
cls.from_com = from_com cls.from_com = from_com
return cls return cls
def pwp_enum(cls):
for index, (name, value) in enumerate(cls.__dict__.items()):
if isinstance(value, type) and value.__module__ == cls.__module__:
value.__annotations__ = {
"_id": uint8,
**getattr(value, "__annotations__", {})
}
value._id = index
value = pwp(value)
setattr(cls, name, value)
return cls