-
Notifications
You must be signed in to change notification settings - Fork 5
/
mcu_util.py
391 lines (352 loc) · 13.3 KB
/
mcu_util.py
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/usr/bin/env python3
###########################################################
# MCU Update script for Creality K1 / K1C / K1 MAX printers
###########################################################
# Pure python implementation
# v0.1
# (c) 2024 CryoZ
###########################################################
from binascii import hexlify
from io import BufferedReader
from os import SEEK_END
from pathlib import Path
import argparse
import sys
import serial
# Compute simple CRC
def crc(data: bytes):
x = 0
for i in data:
x = (x + i) & 0xff
return x ^ 0xff
# Debug output
def debug(msg: str, verbose: bool):
if not verbose:
return
print(msg)
# Handshake stage:
# bootloader waiting 15 secs after startup for handshake, then launch app
# if app corrupted by crc16 - bootloader waiting for handshake forever
# ALL stages requred passing handshake stage ONCE
# send: 0x75, receive ack: 0x75
def _handshake(ser: serial.Serial, v: bool):
result = None
try:
if not ser.is_open:
debug(f'open port {ser.name}', v)
ser.open()
debug('send handshake', v)
if ser.write(bytes([0x75])) == 0:
print('Cannot write data!')
return 0
r = ser.read(1)
if len(r) > 0:
debug(f'rcv data {hexlify(r)}', v)
if r[0] == 0x75:
debug('handshake confirmed', v)
return 1
except serial.SerialTimeoutException:
print(f'Timeout serial {ser.name}')
result = 0
except serial.SerialException as e:
print(f'Error opening serial {ser.name} with error {e}')
result = 0
return result
# Version stage:
# bootloader checks for crc16 of app, if passed - combine hw version string (in bootloader area) and fw version string (in fw area)
# if crc16 not passed - sending 25 bytes of 0x00
# send 00ff (ff - crc), receive string (25 bytes+crc) of combined hw version and fw version
def _get_version(ser: serial.Serial, v: bool):
result = None
try:
if not ser.is_open:
debug(f'open port {ser.name}', v)
ser.open()
debug('send version request', v)
if ser.write(bytes([0x00, 0xff])) == 0:
print('Cannot write data!')
return None
r = ser.read(26)
if len(r) > 0:
debug(f'rcv data {hexlify(r)}', v)
if len(r) == 26 and r[25] == crc(r[:-1]):
debug(f'version received! {r[:-1]}', v)
result = bytes(r[:-1]).decode(encoding='latin')
except serial.SerialTimeoutException:
print(f'Timeout serial {ser.name}')
except serial.SerialException as e:
print(f'Error opening serial {ser.name} with error {e}')
return result
# Get sector size stage
# mostly = 1, multiplier for receive buffer of firmware
# send 03fc (fc - crc), receive sector size (1 byte+crc)
def _get_sector_size(ser: serial.Serial, v: bool):
result = None
try:
if not ser.is_open:
debug(f'open port {ser.name}', v)
ser.open()
debug('send sectorsize request', v)
if ser.write(bytes([0x03, 0xfc])) == 0:
print('Cannot write data!')
return None
r = ser.read(2)
if len(r) > 0:
debug(f'rcv data {hexlify(r)}', v)
if len(r) == 2 and r[-1] == crc(r[:-1]):
debug(f'sector size received! {r[0]}', v)
result = r[0]
except serial.SerialTimeoutException:
print(f'Timeout serial {ser.name}')
except serial.SerialException as e:
print(f'Error opening serial {ser.name} with error {e}')
return result
# App start stage
# bootloader check crc16 of fw in flash, if succeded - passes program flow to fw entrypoint
# send 02fd (fd - crc), receive ack 0x75
def _app_start(ser: serial.Serial, v: bool):
result = None
try:
if not ser.is_open:
debug(f'open port {ser.name}', v)
ser.open()
debug('send app_start request', v)
if ser.write(bytes([0x02, 0xfd])) == 0:
print('Cannot write data!')
return None
r = ser.read(2)
if len(r) > 0:
debug(f'rcv data {hexlify(r)}', v)
if r[0] == 0x75 and r[-1] == crc(r[:-1]):
debug('app started!', v)
result = 1
else:
debug('app start failed!', v)
result = 0
except serial.SerialTimeoutException:
print(f'Timeout serial {ser.name}')
except serial.SerialException as e:
print(f'Error opening serial {ser.name} with error {e}')
return result
# Flash FW stage
# receive fw by chunks, size of chunks = sector size << 16, to ram, then writes to flash.
# 1) update request: send 0xfe (fe - crc), receive ack 0x75
# 2) send fw size: send dword of size with leading crc, receive ack 0x75
# 3) send chunks by chunk-size, receive statuses:
# 0x75 - chunk succeded
# 0x20 - all firmware flashed
# 0x21 - error in write ram->rom stage
# 0x1f - bad crc of received data
def _flash_fw(ser: serial.Serial, v: bool, ss: int, f: BufferedReader):
def fw_status_check(r):
debug(f'[flash_update] rcv data {hexlify(r)}', v)
if len(r) == 0:
debug('[flash_update] no rcv data', v)
return 2
if r[0] == 0x75:
debug('[flash_update] chunk flashed', v)
return 4
if r[0] == 0x1f:
debug('[flash_update] bad crc received', v)
return 3
if r[0] == 0x21:
debug('[flash_update] flash write error', v)
return 0
if r[0] == 0x20:
debug('[flash_update] [3] flash completed', v)
return 1
result = 0
buffer_size = ss * 1024
buffer_send = bytearray(buffer_size + 1)
f.seek(0, SEEK_END)
size = f.tell()
f.seek(0)
try:
if not ser.is_open:
debug(f'open port {ser.name}', v)
ser.open()
debug('send update request', v)
if ser.write(bytes([0x01, 0xfe])) == 0:
print('Cannot write data!')
return 0
r = ser.read(2)
if len(r) > 0:
debug(f'[flash_update] [1] rcv data {hexlify(r)}', v)
if r[0] == 0x75 and r[-1] == crc(r[:-1]):
debug('[flash_update] [1] update request confirmed!', v)
bsize = bytearray()
bsize.extend(size.to_bytes(4, 'little'))
bsize.append(crc(bsize))
if ser.write(bsize) == 5:
r = ser.read(2)
if len(r) > 0:
debug(f'[flash_update] [2] rcv data {hexlify(r)}', v)
if len(r) == 2 and r[-1] == crc(r[:-1]):
if r[0] == 0x75:
debug('[flash_update] [2] FW size confirmed!', v)
for _ in range(size // buffer_size):
buffer_send[:-1] = f.read(buffer_size)
buffer_send[-1] = crc(buffer_send[:-1])
if ser.write(buffer_send) == 0:
debug('[flash_update] [3] cannot send data!', v)
return 2
r = ser.read(2)
if len(r) == 2 and r[-1] == crc(r[:-1]):
x = fw_status_check(r)
if x > 3:
continue
else:
return 0
else:
return 0
size_remainder = size % buffer_size
if size_remainder > 0:
buffer_send[:size_remainder] = f.read(size_remainder)
buffer_send[size_remainder] = crc(buffer_send[:size_remainder])
if ser.write(buffer_send[:size_remainder + 1]) == 0:
debug('[flash_update] [4] cannot send data!', v)
return 2
r = ser.read(2)
if len(r) == 2 and r[-1] == crc(r[:-1]):
return fw_status_check(r)
else:
return 0
else:
return x
else:
return 0
else:
debug('update request failed!', v)
result = 2
except serial.SerialTimeoutException:
print(f'Timeout serial {ser.name}')
except serial.SerialException as e:
print(f'Error opening serial {ser.name} with error {e}')
return result
def open_port(port):
ser = None
try:
ser = serial.Serial(port, baudrate=115200, timeout=2.0)
except serial.SerialException as e:
print(f'Error opening serial {port} with error {e}')
return ser
def handshake(args):
ser = open_port(args.port)
v = args.verbose
result = 0
if ser:
try:
try:
handshake_check = _handshake(ser, v)
if handshake_check is not None and handshake_check:
return 1
except Exception as e:
print(f'Exception! Port {args.port} with error {str(e)}')
result = 0
finally:
ser.close()
else:
print(f'Cannot open port {args.port}')
return result
def get_version(args):
ser = open_port(args.port)
v = args.verbose
result = 0
if ser:
try:
try:
ver = _get_version(ser, v)
if ver is not None:
print(f'FW Version: {ver}')
return 1
except Exception as e:
print(f'Exception! Port {args.port} with error {str(e)}')
result = 0
finally:
ser.close()
else:
print(f'Cannot open port {args.port}')
return result
def app_start(args):
ser = open_port(args.port)
v = args.verbose
if ser:
try:
try:
for retries in range(3):
res = _app_start(ser, v)
if res is not None:
if res == 1:
debug('App started', v)
return 0
else:
debug(f'App start failed, retry #{retries+1}', v)
debug('App start failed after 3 retries', v)
return 1
except Exception as e:
print(f'Exception! Port {args.port} with error {str(e)}')
finally:
ser.close()
else:
print(f'Cannot open port {args.port}')
def update(args):
file = Path(args.file)
if not file.is_file():
print(f'File {args.file} is not exists')
return 1
ser = open_port(args.port)
v = args.verbose
if ser:
try:
try:
with open(file, 'rb') as f:
ss = _get_sector_size(ser, v)
if ss is None:
debug('Cannot get sector size', v)
else:
for retries in range(3):
res = _flash_fw(ser, v, ss, f)
if res is not None:
if res == 1:
debug('Firmware updated successfully', v)
return 0
else:
debug(f'FW flash failed, retry #{retries+1}', v)
debug('FW Update failed after 3 retries', v)
return 1
except Exception as e:
print(f'Exception! Port {args.port} with error {str(e)}')
finally:
ser.close()
else:
print(f'Cannot open port {args.port}')
return 0
parser = argparse.ArgumentParser(description='Creality K1 MCU Flasher')
parser.add_argument('-v', '--verbose', action='store_true', help='Debug output')
parser.add_argument('-c', '--handshake', action='store_true', help='Attempt handshake before operation')
parser.add_argument('-i', '--port', type=str, help='serial device', required=True)
parser.add_argument('-f', '--file', type=str, help='firmware file')
parser.add_argument('-u', '--update', action='store_true', help='Update firmware from file')
parser.add_argument('-s', '--appstart', action='store_true', help='Attempt to start fw')
parser.add_argument('-g', '--version', action='store_true', help='Get version')
# General workflow with bootloader operations:
# 1. handshake
# 2. get version
# 3. get sector size
# 4. fw update
# 4.1 update request
# 4.2 send fw size
# 4.3 send fw
# 5. app start
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])
exit_code = 0
if args.handshake:
exit_code = handshake(args)
if args.version:
exit_code = get_version(args)
if args.update:
exit_code = update(args)
exit_code = app_start(args)
if args.appstart:
exit_code = app_start(args)
sys.exit(exit_code)