1 # Copyright (C) Robin Krens - 2024
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 # Commands send to boot firmware
49 # used for init sequence
55 "0xF0", "0xF1", "0xF2", "0xF3",
56 "0xE4", "0xE5", "0xE6", "0xE7",
57 "0xD8", "0xD9", "0xDA", "0xDB",
58 "0xCC", "0xCD", "0xCE", "0xCF"
61 def calc_sum(cmd, data):
63 lnh = (data_len + 1 & 0xFF00) >> 8
64 lnl = data_len + 1 & 0x00FF
66 for i in range(data_len):
67 if isinstance(data[i], str):
68 res += int(data[i], 16)
69 elif isinstance(data[i], int):
73 res = ~(res - 1) & 0xFF # two's complement
74 return (lnh, lnl, res)
77 # format of data packet is [SOD|LNH|LNL|COM|byte_data|SUM|ETX]
78 def pack_command(cmd, data):
82 if isinstance(data, str):
83 byte_data = bytes(data.encode('utf-8'))
85 byte_data = bytes([int(x, 16) for x in data])
87 LNH, LNL, SUM = calc_sum(int(cmd), data)
91 fmt = fmt_header + str(len(data)) + 's' + fmt_footer
92 pack = struct.pack(fmt, SOD, LNH, LNL, COM, byte_data, SUM, ETX)
93 print(fmt, pack, len(pack))
96 # format of data packet is [SOD|LNH|LNL|RES|DAT|SUM|ETX]
97 def pack_pkt(res, data, ack=False):
98 SOD = 0x01 # TODO: check if 0x81 header needed
101 if (len(data) > 1024):
102 raise Exception(f'Data packet too large, data length is {len(data)} (>1024)')
103 LNH, LNL, SUM = calc_sum(int(res), data)
104 if not isinstance(data, bytes):
105 DAT = bytes([int(x, 16) for x in data])
112 fmt = fmt_header + str(len(data)) + 's' + fmt_footer
113 pack = struct.pack(fmt, SOD, LNH, LNL, RES, DAT, SUM, ETX)
116 # packet received from mcu
117 def unpack_pkt(data):
120 SOD, LNH, LNL, RES = struct.unpack(fmt_header, header)
122 raise Exception('Wrong start of packet data received')
123 pkt_len = (LNH << 0x8 | LNL) - 1
124 fmt_message = '<' + str(pkt_len) + 's'
125 raw = struct.unpack_from(fmt_message, data, 4)[0]
126 message = ['0x{:02X}'.format(byte) for byte in raw]
128 raise ValueError(f'MCU encountered error {message[0]}')
130 SUM, ETX = struct.unpack_from(fmt_footer, data, 4 + pkt_len)
131 lnh, lnl, local_sum = calc_sum(RES, message)
132 if (SUM != local_sum):
133 raise Exception(f'Sum calculation mismatch, read {SUM} instead of {local_sum}')
135 raise Exception('Packet ETX error')