refactored
This commit is contained in:
+28
-40
@@ -1,8 +1,6 @@
|
||||
import struct
|
||||
|
||||
from msg_container import MsgContainer
|
||||
from msg_sink import MsgSink
|
||||
|
||||
UBX_SYNC_WORD = b'\xb5\x62'
|
||||
|
||||
def checksum(data: bytes) -> bytes:
|
||||
ck_a = 0
|
||||
@@ -22,59 +20,49 @@ def frame_create(_class: int, _id: int, _data: bytes) -> bytes:
|
||||
|
||||
return _sync + _hdr + _data + _check
|
||||
|
||||
class Hdr:
|
||||
def __init__(self, _class: int, _id: int, _length: int):
|
||||
self.mclass = _class
|
||||
self.mid = _id
|
||||
self.length = _length
|
||||
|
||||
|
||||
def frame_parse_hdr(frame: bytes) -> Hdr|None:
|
||||
hdr = Hdr(0,0,0)
|
||||
|
||||
if len(frame) < 4:
|
||||
return None
|
||||
|
||||
hdr.mclass = struct.unpack('B', frame[0:1])[0]
|
||||
hdr.mid = struct.unpack('B', frame[1:2])[0]
|
||||
hdr.length = struct.unpack('<H', frame[2:4])[0]
|
||||
|
||||
return hdr
|
||||
|
||||
def frame_parse(frame: bytes):
|
||||
_class = 0
|
||||
_id = 0
|
||||
_data = None
|
||||
_hdr = Hdr(0,0,0)
|
||||
|
||||
while True:
|
||||
hdr = frame[0:2]
|
||||
if hdr != b'\xb5\x62':
|
||||
_hdr = frame_parse_hdr(frame[0:4])
|
||||
if _hdr is None:
|
||||
break
|
||||
|
||||
_class = struct.unpack('B', frame[2:3])[0]
|
||||
_id = struct.unpack('B', frame[3:4])[0]
|
||||
_length = struct.unpack('<H', frame[4:6])[0]
|
||||
if (6+_length+2) != len(frame):
|
||||
if (4+_hdr.length+2) != len(frame):
|
||||
break
|
||||
|
||||
_check_soll = frame[-2:]
|
||||
_check_ist = checksum(frame[2:-2])
|
||||
_check_ist = checksum(frame[0:-2])
|
||||
if _check_soll != _check_ist:
|
||||
break
|
||||
|
||||
_data = frame[6:-2]
|
||||
_data = frame[4:-2]
|
||||
break
|
||||
|
||||
return _data, _class, _id
|
||||
|
||||
class UbxReceiver(MsgSink):
|
||||
def __init__(self, name: str, mid: int, mclass: int):
|
||||
MsgSink.__init__(self)
|
||||
self.name = name
|
||||
self.mid = mid
|
||||
self.mclass = mclass
|
||||
|
||||
def on_recv(self, msg: MsgContainer):
|
||||
data, mclass, mid = frame_parse(msg.data)
|
||||
print(f"{mclass}:{mid}:{data}")
|
||||
|
||||
|
||||
def is_msg(self, msg: MsgContainer):
|
||||
data, mclass, mid = frame_parse(msg.data)
|
||||
if data is None:
|
||||
return False
|
||||
|
||||
if mclass != self.mclass:
|
||||
return False
|
||||
|
||||
if mid != self.mid:
|
||||
return False
|
||||
|
||||
return True
|
||||
return _data, _hdr
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = frame_create(1, 2, b'Hallo')
|
||||
print(result)
|
||||
payload, msg_class, msg_id = frame_parse(result)
|
||||
payload, hdr = frame_parse(result)
|
||||
print(payload)
|
||||
|
||||
Reference in New Issue
Block a user