-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathch559update.py
365 lines (269 loc) · 9.29 KB
/
ch559update.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import argparse
import serial
import logging
import time
PACKET_HEADER = [0x57, 0xab]
DETECT_CMD = [
0xa1, 0x12, 0x00, 0x59, 0x11, 0x4d, 0x43, 0x55, 0x20, 0x49, 0x53, 0x50,
0x20, 0x26, 0x20, 0x57, 0x43, 0x48, 0x2e, 0x43, 0x4e
]
RESET_CMD = [0xa2, 0x01, 0x00, 0x01]
KEY_CMD = [0xa3, 0x22, 0x00] + [0x00] * 0x22
ERASE_CMD = [0xa4, 0x01, 0x00, 0x00]
WRITE_CMD = [0xa5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
VERIFY_CMD = [0xa6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
READ_CFG_CMD = [0xa7, 0x02, 0x00, 0x1f, 0x00]
WRITE_CFG_CMD = [
0xa8, 0x0e, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00,
0x00, 0xff, 0x4e, 0x00, 0x00
]
PAGE_MAX = 60
def __dumpHex(arg):
return ' '.join([format(h, '02x') for h in arg])
def __convertPayload(payload, chksum, devid):
for idx in range(len(payload)):
if idx % 8 == 0x07:
payload[idx] = (payload[idx] ^ ((chksum + devid) & 0xFF)) & 0xFF
else:
payload[idx] = (payload[idx] ^ chksum) & 0xFF
def __appendHeader(packet):
return PACKET_HEADER + packet
def __appendChecksum(packet):
s = (0x55 + 0xab + sum(packet)) & 255
return packet + [s]
def __makeFlashCmd(cmdheader, address, remain, payload, chksum, devid):
cmd = cmdheader
cmd[1] = len(payload) + 5
cmd[3] = address & 0xff
cmd[4] = (address >> 8) & 0xff
cmd[7] = remain & 0xff
__convertPayload(payload, chksum, devid)
cmd = cmd + payload
cmd = __appendChecksum(cmd)
return __appendHeader(cmd)
def __makeFlashWriteCmd(address, remain, payload, chksum, devid):
return __makeFlashCmd(WRITE_CMD, address, remain, payload, chksum, devid)
def __makeVerifyCmd(address, remain, payload, chksum, devid):
return __makeFlashCmd(VERIFY_CMD, address, remain, payload, chksum, devid)
def __makeEraseCmd(byte_len):
cmd = ERASE_CMD
page_len = math.floor((byte_len + 1024 - 1) / 1024)
if page_len > PAGE_MAX:
raise Exception(f'File size is too large({byte_len}>{1024*PAGE_MAX}).')
cmd[3] = page_len
cmd = __appendChecksum(cmd)
return __appendHeader(cmd)
def __makeDetectCmd():
cmd = DETECT_CMD
cmd = __appendChecksum(cmd)
return __appendHeader(cmd)
def __makeResetCmd():
cmd = RESET_CMD
cmd = __appendChecksum(cmd)
return __appendHeader(cmd)
def __makeReadCfgCmd():
cmd = READ_CFG_CMD
cmd = __appendChecksum(cmd)
return __appendHeader(cmd)
def __makeWriteCfgCmd(changeBootpin):
cmd = WRITE_CFG_CMD
if changeBootpin:
cmd[9] = 0x01
cmd = __appendChecksum(cmd)
return __appendHeader(cmd)
def __makeSendKeyCmd():
cmd = KEY_CMD
cmd = __appendChecksum(cmd)
return __appendHeader(cmd)
def __splitToChunk(binfile, size):
for idx in range(0, len(binfile), size):
yield binfile[idx:idx + size]
def __flashBinFile(binfile, com, checksum, devid):
chunks = __splitToChunk(binfile, 56)
addr = 0
remains = len(binfile)
for chunk in chunks:
if len(chunk) < 56:
chunk.extend([0xFF] * (56 - len(chunk)))
cmd = __makeFlashWriteCmd(addr, remains, chunk, checksum, devid)
addr = addr + len(chunk)
remains = remains - len(chunk)
com.write(cmd)
logging.debug('send:' + __dumpHex(cmd))
ret = com.read(size=9)
if len(ret) != 9 or ret[6] != 0:
raise Exception(f'Flash failed at address {addr}')
logging.debug('receive:' + __dumpHex(ret))
print('.', end='', flush=True)
def __verifyBinFile(binfile, com, checksum, devid):
chunks = __splitToChunk(binfile, 56)
addr = 0
remains = len(binfile)
for chunk in chunks:
if len(chunk) < 56:
chunk.extend([0xFF] * (56 - len(chunk)))
cmd = __makeVerifyCmd(addr, remains, chunk, checksum, devid)
addr = addr + len(chunk)
remains = remains - len(chunk)
com.write(cmd)
logging.debug('send:' + __dumpHex(cmd))
ret = com.read(size=9)
if ret[6] != 0:
raise Exception(
f'verify failed at address {addr - len(chunk)} to {addr}')
logging.debug('receive:' + __dumpHex(ret))
print('.', end='', flush=True)
def __detectCh559(com):
if not com.isOpen():
raise
cmd = __makeDetectCmd()
ret = com.write(cmd)
logging.debug('send:' + __dumpHex(cmd))
ret = com.read(size=9)
if len(ret) < 9 or ret[5] != 0:
raise Exception('CH559 is not found.')
logging.debug('receive:' + __dumpHex(ret))
def __getCfg(com):
if not com.isOpen():
raise
cmd = __makeReadCfgCmd()
ret = com.write(cmd)
logging.debug('send:' + __dumpHex(cmd))
ret = com.read(size=33)
if (ret[5] != 0):
return None
logging.debug('receive:' + __dumpHex(ret))
version = f'ver{ret[21]}.{ret[22]}{ret[23]}'
checksum = sum(ret[24:28]) & 0xff
return {'version': version, 'checksum': checksum, 'bootpin': ret[12]}
def __setCfg(com, changeBootpin):
if not com.isOpen():
raise
cmd = __makeWriteCfgCmd(changeBootpin)
ret = com.write(cmd)
logging.debug('send:' + __dumpHex(cmd))
ret = com.read(size=9)
if (ret[5] != 0):
return None
logging.debug('receive:' + __dumpHex(ret))
def __sendKey(com):
if not com.isOpen():
raise
cmd = __makeSendKeyCmd()
logging.debug('send:' + __dumpHex(cmd))
ret = com.write(cmd)
ret = com.read(size=9)
if (ret[5] != 0):
raise
logging.debug('receive:' + __dumpHex(ret))
def __eraseChip(com, filesize):
cmd = __makeEraseCmd(filesize)
ret = com.write(cmd)
logging.debug('send:' + __dumpHex(cmd))
ret = com.read(size=9)
if (ret[5] != 0):
raise
logging.debug('receive:' + __dumpHex(ret))
def __restartUserCode(com):
cmd = __makeResetCmd()
ret = com.write(cmd)
logging.debug('send:' + __dumpHex(cmd))
ret = com.read(size=9)
logging.debug('receive:' + __dumpHex(ret))
def __ch559erase(args, com):
if com is None:
print('No COM port')
return
__detectCh559(com)
cfg = __getCfg(com)
print('Chip erase start...')
__eraseChip(com, PAGE_MAX * 1024)
print('Chip erase complete.')
def __ch559flash(args, com):
if com is None:
print('No COM port')
return
try:
__detectCh559(com)
except:
com.reset_output_buffer()
com.reset_input_buffer()
time.sleep(1)
__detectCh559(com)
cfg = __getCfg(com)
if args.bootpin_change:
print('change boot pin to 5.1')
__setCfg(com, args.bootpin_change)
if args.file != '':
with open(args.file, 'rb') as f:
binfile = list(f.read())
print('Chip erase start...')
__eraseChip(com, len(binfile))
print('Chip erase complete.')
__sendKey(com)
print('Flash start...')
__flashBinFile(binfile, com, cfg['checksum'], 0x59)
print('')
print('Flash complete.')
__sendKey(com)
# print(f'checksum:{cfg['checksum']}')
print('Verify start...')
__verifyBinFile(binfile, com, cfg['checksum'], 0x59)
print('')
print('Verify complete.')
def __ch559verify(args, com):
if com is None:
print('No COM port')
return
__detectCh559(com)
cfg = __getCfg(com)
print('config:')
print(cfg)
if args.file != '':
__sendKey(com)
with open(args.file, 'rb') as f:
binfile = list(f.read())
print('Verify start...')
__verifyBinFile(binfile, com, cfg['checksum'], 0x59)
print('')
print('Verify complete.')
def __ch559update():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=str, default='')
parser.add_argument('-p', '--port', type=str, default='')
parser.add_argument('-r', '--reset', action='store_true')
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-b', '--bootpin_change', action='store_true')
subparsers = parser.add_subparsers()
parser_flash = subparsers.add_parser('flash',
parents=[parser],
add_help=False)
parser_flash.set_defaults(handler=__ch559flash)
parser_verify = subparsers.add_parser('verify',
parents=[parser],
add_help=False)
parser_verify.set_defaults(handler=__ch559verify)
parser_erase = subparsers.add_parser('erase',
parents=[parser],
add_help=False)
parser_erase.set_defaults(handler=__ch559erase)
args = parser.parse_args()
com = None
if args.port != '':
com = serial.Serial(port=args.port, baudrate=57600, timeout=5)
if args.verbose:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s %(message)s')
else:
logging.basicConfig(level=logging.INFO)
if hasattr(args, 'handler'):
args.handler(args, com)
if args.reset and args.port != '':
print('Reset target...')
__restartUserCode(com)
print('Reset complete.')
if __name__ == '__main__':
__ch559update()