32
32
from machine import UART
33
33
from micropython import const
34
34
from time import sleep
35
+ import binascii
35
36
36
37
_CMD_SYNC = const (0x08 )
37
38
_CMD_CHANGE_BAUDRATE = const (0x0F )
@@ -76,6 +77,13 @@ def __init__(
76
77
self .reset_pin = Pin (reset , Pin .OUT )
77
78
self .gpio0_pin = Pin (gpio0 , Pin .OUT )
78
79
self .set_baudrate (self .uart_baudrate )
80
+ self .md5sum = None
81
+ try :
82
+ import hashlib
83
+
84
+ self .md5sum = hashlib .md5 ()
85
+ except ImportError :
86
+ pass
79
87
80
88
def _log (self , data , out = True ):
81
89
if self .log :
@@ -266,8 +274,11 @@ def flash_write_file(self, path, blksize=0x1000):
266
274
subseq = 0
267
275
for i in range (total_blocks ):
268
276
buf = f .read (blksize )
277
+ # Update digest
278
+ if self .md5sum is not None :
279
+ self .md5sum .update (buf )
280
+ # The last data block should be padded to the block size with 0xFF bytes.
269
281
if len (buf ) < blksize :
270
- # The last data block should be padded to the block size with 0xFF bytes.
271
282
buf += b"\xFF " * (blksize - len (buf ))
272
283
checksum = self .checksum (buf )
273
284
if seq % erase_blocks == 0 :
@@ -288,15 +299,22 @@ def flash_write_file(self, path, blksize=0x1000):
288
299
289
300
print ("Flash write finished" )
290
301
291
- def flash_verify_file (self , path , md5sum , offset = 0 ):
302
+ def flash_verify_file (self , path , digest = None , offset = 0 ):
303
+ if digest is None :
304
+ if self .md5sum is None :
305
+ raise Exception (f"MD5 checksum missing." )
306
+ digest = binascii .hexlify (self .md5sum .digest ())
307
+
292
308
size = os .stat (path )[6 ]
293
309
val , data = self .command (_CMD_SPI_FLASH_MD5 , struct .pack ("<IIII" , offset , size , 0 , 0 ))
294
- print (f"Flash verify file MD5 { md5sum } " )
295
- print (f"Flash verify flash MD5 { bytes (data [0 :32 ])} " )
296
- if md5sum == data [0 :32 ]:
297
- print ("Firmware write verified" )
310
+
311
+ print (f"Flash verify: File MD5 { digest } " )
312
+ print (f"Flash verify: Flash MD5 { bytes (data [0 :32 ])} " )
313
+
314
+ if digest == data [0 :32 ]:
315
+ print ("Firmware verified." )
298
316
else :
299
- raise Exception (f"Firmware verification failed" )
317
+ raise Exception (f"Firmware verification failed. " )
300
318
301
319
def reboot (self ):
302
320
payload = struct .pack ("<I" , 0 )
0 commit comments