1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
|
from __future__ import annotations
from collections import abc
from collections.abc import Iterable, Sequence
from dataclasses import field, fields
import enum
from functools import lru_cache
import struct
from typing import Any, Callable, ClassVar, Generic, TypeVar, _GenericAlias
SerializerCallback = Callable[[type, Any], bytes]
DeserializerCallback = Callable[[type, bytes], Any]
T = TypeVar("T")
class u8(int):
pass
class u16(int):
pass
class bu16(int):
pass
class u32(int):
pass
class u64(int):
pass
class u128(int):
pass
def get_origin(tp):
"""
Returns the containing type
get_origin(int) == None
get_origin(Sequence[int]) == collections.abc.Sequence
"""
if isinstance(tp, _GenericAlias):
return tp.__origin__ if tp.__origin__ is not ClassVar else None
if tp is Generic:
return Generic
return None
class TlvParseException(Exception):
"""Raised upon parse error with some TLV"""
pass
class TlvSerializeException(Exception):
"""Raised upon parse error with some TLV"""
pass
def tlv_iterator(encoded_struct: bytes) -> Iterable:
offset = 0
while offset < len(encoded_struct):
type = encoded_struct[offset]
length = encoded_struct[offset + 1]
value = encoded_struct[offset + 2 :][:length]
# If length is 255 the next chunks may be part of same value
# Iterate until the type changes
while length == 255:
peek_offset = offset + 2 + length
if peek_offset >= len(encoded_struct):
# https://github.com/home-assistant/core/issues/100160
# Schlage Encode Plus seems to incorrectly serialize "linked services"
# Recover as gracefully as possible
# If we break here, we'll have all the value that we received, but length might be wrong.
break
if encoded_struct[peek_offset] != type:
break
offset = peek_offset
length = encoded_struct[offset + 1]
value += encoded_struct[offset + 2 :][:length]
yield offset, type, length, value
offset += 2 + length
def tlv_array(encoded_array: bytes, separator: int = 0) -> Iterable[bytes]:
start = 0
for offset, type, length, chunk_value in tlv_iterator(encoded_array):
if type == separator:
yield encoded_array[start:offset]
start = offset + 2
continue
item = encoded_array[start:]
if item:
yield item
def deserialize_u8(value_type: type, value: bytes) -> int:
return int.from_bytes(value, "little")
def deserialize_u16(value_type: type, value: bytes) -> int:
return int.from_bytes(value, "little")
def deserialize_bu16(value_type: type, value: bytes) -> int:
return int.from_bytes(value, "big")
def deserialize_u32(value_type: type, value: bytes) -> int:
return int.from_bytes(value, "little")
def deserialize_u64(value_type: type, value: bytes) -> int:
return int.from_bytes(value, "little")
def deserialize_u128(value_type: type, value: bytes) -> int:
return int.from_bytes(value, "little")
def deserialize_str(value_type: type, value: bytes) -> str:
return value.decode("utf-8")
def deserialize_bytes(value_type: type, value: bytes) -> bytes:
return value
def deserialize_int_enum(value_type: type, value: bytes) -> enum.IntEnum:
int_value = deserialize_u8(value_type, value)
return value_type(int_value)
def deserialize_tlv_struct(value_type: type, value: bytes) -> TLVStruct:
return value_type.decode(value)
def deserialize_typing_sequence(value_type: type, value: bytes) -> Sequence[TLVStruct]:
inner_type = value_type.__args__[0]
results = []
for inner_value in tlv_array(value):
fn = find_deserializer(inner_type)
results.append(fn(inner_type, inner_value))
return results
def serialize_u8(value_type: type, value: int) -> bytes:
return struct.pack("B", value)
def serialize_u16(value_type: type, value: int) -> bytes:
return struct.pack("H", value)
def serialize_bu16(value_type: type, value: int) -> bytes:
return struct.pack(">H", value)
def serialize_u32(value_type: type, value: int) -> bytes:
return struct.pack("I", value)
def serialize_u64(value_type: type, value: int) -> bytes:
return struct.pack("Q", value)
def serialize_u128(value_type: type, value: int) -> bytes:
return value.to_bytes(length=16, byteorder="little")
def serialize_str(value_type: type, value: str) -> bytes:
return value.encode("utf-8")
def serialize_bytes(value_type: type, value: bytes) -> bytes:
return value
def serialize_int_enum(value_type: type, value: enum.IntEnum) -> bytes:
return serialize_u8(value_type, int(value))
def serialize_tlv_struct(value_type: type, value: TLVStruct) -> bytes:
return value.encode()
def serialize_typing_sequence(value_type: type, value: Sequence) -> bytes:
if not value:
return b""
value_iter = iter(value)
result = bytearray()
result.extend(next(value_iter).encode())
for val in value_iter:
result.extend(b"\x00\x00")
result.extend(val.encode())
return bytes(result)
def tlv_entry(type: int, **kwargs):
return field(default=None, metadata={"tlv_type": type, **kwargs})
@lru_cache(maxsize=100)
def find_serializer(py_type: type):
if get_origin(py_type):
superclasses = [get_origin(py_type)]
elif hasattr(py_type, "__mro__"):
superclasses = py_type.__mro__
else:
superclasses = [py_type]
for klass in superclasses:
if klass in SERIALIZERS:
return SERIALIZERS[klass]
raise TlvSerializeException(f"Cannot serialize {py_type} to TLV8")
@lru_cache(maxsize=100)
def find_deserializer(py_type: type):
if get_origin(py_type):
superclasses = [get_origin(py_type)]
elif hasattr(py_type, "__mro__"):
superclasses = py_type.__mro__
else:
superclasses = [py_type]
for klass in superclasses:
if klass in DESERIALIZERS:
return DESERIALIZERS[klass]
raise TlvParseException(f"Cannot deserialize TLV type {type} into {py_type}")
class TLVStruct:
"""
A mixin that adds TLV8 encoding and decoding to dataclasses.
"""
def encode(self) -> bytes:
result = bytearray()
for struct_field in fields(self):
if not struct_field.init:
continue
value = getattr(self, struct_field.name)
if value is None:
continue
tlv_type = struct_field.metadata["tlv_type"]
py_type = struct_field.type
serializer = find_serializer(py_type)
encoded = serializer(py_type, value)
for offset in range(0, len(encoded), 255):
chunk = encoded[offset : offset + 255]
result.append(tlv_type)
result.extend(struct.pack("B", len(chunk)))
result.extend(chunk)
return bytes(result)
@classmethod
@lru_cache(maxsize=None)
def _tlv_types(cls: T) -> dict:
"""Return the TLV types for this class."""
return {
field.metadata["tlv_type"]: field for field in fields(cls) if field.init
}
@classmethod
def decode(cls: T, encoded_struct: bytes) -> T:
kwargs = {}
offset = 0
tlv_types = cls._tlv_types()
for offset, type, length, value in tlv_iterator(encoded_struct):
if type not in tlv_types:
raise TlvParseException(f"Unknown TLV type {type} for {cls}")
py_type = tlv_types[type].type
deserializer = find_deserializer(py_type)
kwargs[tlv_types[type].name] = deserializer(py_type, value)
return cls(**kwargs)
DESERIALIZERS: dict[type, DeserializerCallback] = {
bu16: deserialize_bu16,
u8: deserialize_u8,
u16: deserialize_u16,
u32: deserialize_u32,
u64: deserialize_u64,
u128: deserialize_u128,
str: deserialize_str,
enum.IntEnum: deserialize_int_enum,
TLVStruct: deserialize_tlv_struct,
abc.Sequence: deserialize_typing_sequence,
bytes: deserialize_bytes,
}
SERIALIZERS: dict[type, SerializerCallback] = {
bu16: serialize_bu16,
u8: serialize_u8,
u16: serialize_u16,
u32: serialize_u32,
u64: serialize_u64,
u128: serialize_u128,
str: serialize_str,
enum.IntEnum: serialize_int_enum,
TLVStruct: serialize_tlv_struct,
abc.Sequence: serialize_typing_sequence,
bytes: serialize_bytes,
}
|