forked from tomzbj/zboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iap.py
281 lines (248 loc) · 7.44 KB
/
iap.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
import serial
import time
#import threading
#import random
import zlib
import os
import sys
import bincopy
from tkinter.filedialog import *
VIEWCFG = False
#VIEWCFG = True
class Cli:
def __init__(self, ser):
self.ser = ser
def CalcLRC(self, msg):
# 计算LRC校验和
# LRC为除LRC外所有字节之和取1补码; 带LRC的字节串按字节求和后低字节为零
lrc = 0
for c in msg:
lrc += c
lrc = lrc % 256
lrc = 256 - lrc
if lrc == 256:
lrc = 0
return lrc
def GetMaxAppSize(self):
# 0x80 读取APP可写入的区域大小
cmd = b'\x80\x00\x80'
ret = self.SendCmd(cmd)
return int.from_bytes(ret, byteorder='little')
def GetAppSize(self):
# 0x82 读取APP区域实际大小, 向上取整到2字节
cmd = b'\x82\x00\x7e'
ret = self.SendCmd(cmd)
return int.from_bytes(ret, byteorder='little')
def SendCmd(self, cmd):
if VIEWCFG == True:
print("CMD: ", end="")
count = 0
for i in cmd:
print("%02x " % i, end="")
count += 1
if count > 16:
break
print()
self.ser.write(cmd)
timeout = time.time() + 1.5
while self.ser.in_waiting == 0 and time.time() < timeout:
time.sleep(0.02)
time.sleep(0.02)
ret = self.ser.read_all()
if VIEWCFG == True:
print("RET: ", ret)
return ret
def ReadImage(self, bin_size):
# 0x81 读取APP区域 81 00 size(4字节) pos(4字节) 校验(1字节)
size = 256
pos = 0
ret = b''
count = 0
while bin_size > 0:
if bin_size < size:
size = bin_size
msg = b'\x81\x00' + size.to_bytes(4, byteorder='little')
msg += pos.to_bytes(4, byteorder='little')
msg += self.CalcLRC(msg).to_bytes(1, byteorder='little')
ret += self.SendCmd(msg)
bin_size -= size
pos += size
count += 1
print(count)
return ret
def EraseImage(self, size):
# 0xc0 擦除APP区域
msg = b'\xc0\x00'
msg += self.CalcLRC(msg).to_bytes(1, byteorder='little')
ret = self.SendCmd(msg)
return ret
def ReadCRC32(self, size):
# 0x83 计算APP区域CRC32校验值
msg = b'\x83\x00'
msg += self.CalcLRC(msg).to_bytes(1, byteorder='little')
while True:
ret = self.SendCmd(msg)
if ret != b'':
break
return ret
def WriteImage(self, img):
# 0xc1 写入APP区域 c1 00 size(2字节) pos(4字节) content(最多1024字节) 校验(1字节) (需要预先擦除)
size = 512
count = 0
pos = 0
totalsize = len(img)
while len(img) % 4 != 0:
img += b'\xff'
while len(img) > 0: # transfer
sys.stdout.flush()
perc = (1 - len(img) / totalsize) * 100
sys.stdout.write('%.0f%% ' % perc)
sys.stdout.flush()
sys.stdout.write('\r')
sys.stdout.flush()
pb = img[0:size]
msg = b'\xc1\x00' + len(pb).to_bytes(2, byteorder='little') + pos.to_bytes(4, byteorder='little') + pb
msg += self.CalcLRC(msg).to_bytes(1, byteorder='little')
count += 1
if pb != (b'\xff' * size): # 全0xff则跳过
while True:
ret = self.SendCmd(msg)
if ret == b'\x00':
break
img = img[size:]
pos += len(pb)
if img == (b'\xff' * len(img)): # 全0xff则跳过剩余部分
break
print('100%')
def WriteAppValidFlag(self):
# 0xc2 写APP有效标记(CRC32校验值)到FLASH末尾
msg = b'\xc2\x00'
msg += self.CalcLRC(msg).to_bytes(1, byteorder='little')
self.SendCmd(msg)
def JumpToApp(self):
# 0x40 跳转至APP区域
msg = b'\xd0\x00'
msg += self.CalcLRC(msg).to_bytes(1, byteorder='little')
self.SendCmd(msg)
def JumpToBootloader(self):
# 0x42 跳转至BOOTLOADER区域
msg = b'## reboot'
# msg += self.CalcLRC(msg).to_bytes(1, byteorder='little')
ret = self.SendCmd(msg)
return ret
def FlashOpFromCmdLine(port, baudrate, file):
ser = serial.Serial(port, baudrate, timeout=0.2)
"""
try:
f = open(file, mode='rb')
except:
print("Failed to open binary file.")
exit()
img = f.read()
f.close()
"""
try:
f = bincopy.BinFile(file)
except:
print("Failed to open ihex file.")
exit()
img = f.as_binary()
orig_len = len(img)
a = Cli(ser)
print('Jumping to bootloader...')
sys.stdout.flush()
a.JumpToBootloader()
time.sleep(0.1)
print('Erasing...')
sys.stdout.flush()
a.EraseImage(len(img))
time.sleep(0.5)
print('Writing...')
sys.stdout.flush()
a.WriteImage(img)
print('Verifying...')
sys.stdout.flush()
img = img[:orig_len]
crc = int.from_bytes(a.ReadCRC32(len(img)), byteorder='little')
crc2 = zlib.crc32(img)
print('Written %d bytes.' % len(img))
print('Original crc32: %08x' % crc2)
print('Written crc32: %08x' % crc)
sys.stdout.flush()
if crc == crc2:
a.JumpToApp()
print('ok')
sys.stdout.flush()
else:
# f = open('dump_img.bin', mode='wb')
# f.write(img)
pass
ser.close()
def ReadImage(port, baudrate):
ser = serial.Serial(port, baudrate, timeout=0.1)
a = Cli(ser)
size = a.GetAppSize()
print(size)
img = a.ReadImage(size)
print(len(img))
path = asksaveasfilename()
f = open(path, mode='wb')
f.write(img)
f.close()
ser.close()
def scan():
'''scan for available ports '''
ports = []
baudrates = [500000]
for i in range(32):
try:
port = 'COM' + str(i + 1)
s = serial.Serial(port)
ports.append(port)
s.close()
except serial.SerialException:
pass
print(ports)
for port in ports:
for baudrate in baudrates:
try:
ser = serial.Serial(port, baudrate, timeout=0.05)
except:
continue
a = Cli(ser)
for i in range(3):
ret = a.SendCmd(b'## test')
if ret != b'':
return port, baudrate
ser.close()
return None, None
def test(port, baudrate):
ser = serial.Serial(port, baudrate, timeout=0.2)
"""
try:
f = open(file, mode='rb')
except:
print("Failed to open binary file.")
exit()
img = f.read()
f.close()
"""
a = Cli(ser)
cmd = b'\x81\x00\x00\x01\x00\x38\x46'
ret = a.SendCmd(cmd)
for i in ret:
print("%02x" % i, end=" ")
if __name__ == '__main__':
# 以下用于单元测试
# print(sys.argv)
port, baudrate = scan()
if port == None:
print('Serial port not deteced.')
exit()
if len(sys.argv) != 2:
print('Usage: iap_test.py xxx.bin')
exit()
file = sys.argv[1]
# test(port, baudrate)
FlashOpFromCmdLine(port, baudrate, file)
# ReadImage(port, baudrate)