Files
bproto/template/python/static/bproto_base.py
2025-04-14 14:43:03 +02:00

68 lines
1.6 KiB
Python

import abc
class bproto_Package(abc.ABC):
@abc.abstractmethod
def to_bytes(self) -> bytes:
raise NotImplementedError()
@abc.abstractmethod
def from_bytes(self, data: bytes):
raise NotImplementedError()
class bproto_Bitfield(abc.ABC):
@abc.abstractmethod
def to_bytes(self) -> bytes:
pass
@abc.abstractmethod
def from_bytes(self, data: bytes):
pass
def __str__(self):
return self.__repr__()
def crc16_calc_inital(data: bytearray) -> int:
"""CRC-16/CITT-FALSE
from https://stackoverflow.com/questions/35205702/calculating-crc16-in-python
Args:
data (bytearray): protocol hash
Returns:
bytes: initals for crc16_calc_with_initial
"""
crc = 0xFFFF
for i in range(0, len(data)):
crc ^= data[i] << 8
for j in range(0, 8):
if (crc & 0x8000) > 0:
crc = (crc << 1) ^ 0x1021
else:
crc = crc << 1
return crc
def calc_crc_sum(data: bytearray, inital: int) -> bytes:
"""CRC-16/CITT-FALSE
form https://stackoverflow.com/questions/35205702/calculating-crc16-in-python
Args:
data (bytearray): protocol data
inital (int): Inital calculated from protocol hash
Returns:
bytes: 2 byte CRC Checksum
"""
crc = inital
for i in range(0, len(data)):
crc ^= data[i] << 8
for j in range(0, 8):
if (crc & 0x8000) > 0:
crc = (crc << 1) ^ 0x1021
else:
crc = crc << 1
return crc & 0xFFFF