+# packet received from mcu
+def unpack_header(data):
+ header = data[0:4]
+ fmt_header = '<BBBB'
+ SOD, LNH, LNL, RES = struct.unpack(fmt_header, header)
+ if (SOD != 0x81):
+ raise Exception(f'Wrong start of packet data received')
+ pkt_len = (LNH << 0x8 | LNL) - 1
+ if (RES & 0x80):
+ raise Exception(f'MCU encountered error {RES & 0x7F}')
+ fmt_message = '<' + str(pkt_len) + 's'
+ raw = struct.unpack_from(fmt_message, data, 4)[0]
+ message = ['0x{:02X}'.format(byte) for byte in raw]
+ fmt_footer = '<BB'
+ SUM, ETX = struct.unpack_from(fmt_footer, data, 4 + pkt_len)
+ lnh, lnl, local_sum = calc_sum(RES, message)
+ if (SUM != local_sum):
+ raise Exception(f'Sum calculation mismatch, read {local_sum} instead of {SUM}')
+ if (ETX != 0x03):
+ raise Exception(f'Packet ETX error')
+ return message