-
Notifications
You must be signed in to change notification settings - Fork 0
/
updater.py
executable file
·1654 lines (1464 loc) · 72.3 KB
/
updater.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2016-2020, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
from __future__ import print_function
import argparse
import base64
import binascii
from io import BytesIO, StringIO
import json
import os
import re
import struct
import sys
import tarfile
import time
from traceback import print_exc
import serial.tools.list_ports
from esptool import ESP32ROM
import esptool
from pypic import Pypic
try:
import humanfriendly
humanfriendly_available = True
except:
humanfriendly_available = False
DEBUG = False
FLASH_MODE = 'dio'
FLASH_FREQ = '80m'
DEFAULT_BAUD_RATE = 115200
FAST_BAUD_RATE = 921600
MAXPICREAD_BAUD_RATE = 230400
LORA_REGIONS = ["EU868", "US915", "AS923", "AU915", "IN865"]
PIC_BOARDS = ["04D8:F013", "04D8:F012", "04D8:EF98", "04D8:EF38", "04D8:ED14"]
PARTITIONS = { 'secureboot' : ["0x0", "0x8000"],
'bootloader' : ["0x1000", "0x7000"],
'partitions' : ["0x8000", "0x1000"],
'nvs' : ["0x9000", "0x7000"],
'factory' : ["0x10000", "0x180000"],
'otadata' : ["0x190000", "0x1000"],
'ota_0' : ["0x1a0000", "0x180000"],
'fs' : ["0x380000", "0x7F000"],
'config' : ["0x3FF000", "0x1000"],
'fs1' : ["0x400000", "0x400000"],
'all' : ["0x0" , "0x800000"]}
PARTITIONS_NEW = {
"factory" : ["0x10000", "0x1AE000"],
'otadata' : ["0x1BE000", "0x1000"],
"ota_0" : ["0x1a0000", "0x1AE000"]
}
# HERE_PATH = os.path.dirname(os.path.realpath(__file__))
# Beware not all regions are support in firmware yet!
# AS band on 923MHz
LORAMAC_REGION_AS923 = 0
# Australian band on 915MHz
LORAMAC_REGION_AU915 = 1
# Chinese band on 470MHz
LORAMAC_REGION_CN470 = 2
# Chinese band on 779MHz
LORAMAC_REGION_CN779 = 3
# European band on 433MHz
LORAMAC_REGION_EU433 = 4
# European band on 868MHz
LORAMAC_REGION_EU868 = 5
# South korean band on 920MHz
LORAMAC_REGION_KR920 = 6
# India band on 865MHz
LORAMAC_REGION_IN865 = 7
# North american band on 915MHz
LORAMAC_REGION_US915 = 8
# North american band on 915MHz with a maximum of 16 channels
LORAMAC_REGION_US915_HYBRID = 9
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
sys.stderr.flush()
def print_exception(e):
if DEBUG:
try:
if sys.version_info[0] < 3:
print_exc(e)
else:
print_exc()
except Exception as ex:
print_debug('Exception: {}'.format(e))
print_debug('Exception exception: {}'.format(ex))
def print_debug(msg, show=DEBUG):
if show:
eprint(msg)
size_table = [
(1024 ** 3, ' gb'),
(1024 ** 2, ' mb'),
(1024 ** 1, ' kb'),
(1024 ** 0, ' bytes'),
]
def hr_size(size):
if humanfriendly_available:
return humanfriendly.format_size(size, binary=True)
else:
for factor, suffix in size_table:
if size >= factor:
break
try:
amount = int(size / factor)
except Exception as e:
print_exception(e)
return str(amount) + " bytes"
if isinstance(suffix, tuple):
singular, multiple = suffix
if amount == 1:
suffix = singular
else:
suffix = multiple
return str(amount) + suffix
class Args(object):
pass
def load_tar(fileobj, prog, secure=False):
script = None
legacy = False
try:
tar = tarfile.open(mode="r", fileobj=fileobj)
except Exception as e:
print_exception(e)
return e
try:
fsize = prog.int_flash_size()
if fsize == 0x800000:
try:
if secure:
script_file = json.loads(tar.extractfile("script_8MB_enc").read().decode('UTF-8'))
else:
script_file = json.loads(tar.extractfile("script_8MB").read().decode('UTF-8'))
except:
print_debug("Error Loading script_8MB ... defaulting to legacy script2!", True)
legacy = True
elif fsize == 0x400000:
try:
if secure:
script_file = json.load(tar.extractfile("script_4MB_enc").read().decode('UTF-8'))
else:
script_file = json.load(tar.extractfile("script_4MB").read().decode('UTF-8'))
except Exception as e:
print_exception(e)
print_debug("Error Loading script_4MB ... defaulting to legacy script2!", True)
legacy = True
else:
return RuntimeError("Cannot detect flash size! .. Aborting")
if legacy:
script_file = json.loads(tar.extractfile("script2").read().decode('UTF-8'))
version = script_file.get('version')
if version is not None:
print_debug('Script Version: {}'.format(version), True)
partitions = script_file.get('partitions')
if partitions is not None:
PARTITIONS.update(partitions)
else:
raise ValueError('version not found in script2')
try:
script = script_file.get('script')
except Exception as e:
print_exception(e)
if script is None:
raise ValueError('script not found in script2')
except RuntimeError as e:
print_exception(e)
return e
except:
try:
script = json.loads(tar.extractfile("script").read().decode('UTF-8'))
except Exception as e:
script = e
print_exception(e)
raise ValueError("Your board is not supported by this firmware package")
try:
for i in range(len(script)):
if script[i][0] == 'w' or script[i][0] == 'o':
script[i][0] = script[i][0] + ":" + script[i][2]
script[i][2] = tar.extractfile(script[i][2]).read()
except Exception as e:
script = e
print_exception(e)
tar.close()
return script
class NPyProgrammer(object):
def __init__(self, port, baudrate, continuation=False, pypic=False, debug=False, reset=False, resultUpdateList=None, connect_read=False):
self.__debug = debug
self.__current_baudrate = self.__baudrate = baudrate
self.__pypic = pypic
self.__resultUpdateList = resultUpdateList
self.__flash_size = 'detect'
self.__progress_fs = None
if re.match('^com[0-9].*', port, re.I):
self.esp_port = port.lower()
else:
self.esp_port = port
print_debug("Connecting to ESP32 with baudrate: %d" % self.__baudrate, self.__debug)
if continuation == False:
if (self.__pypic):
self.enter_pycom_programming_mode()
self.esp = ESP32ROM(self.esp_port, DEFAULT_BAUD_RATE)
if not self.__pypic:
self.esp.connect()
else:
self.esp.connect(mode='no_reset')
self.esp = self.esp.run_stub()
if connect_read and pypic:
self.__current_baudrate = self.get_baudrate(True)
self.esp.change_baud(self.__current_baudrate, self.__resultUpdateList)
elif self.__current_baudrate != 115200:
self.esp.change_baud(self.__baudrate, self.__resultUpdateList)
else:
esp = ESP32ROM(self.esp_port, self.__baudrate)
self.esp = esp.STUB_CLASS(esp) # enable the stub functions
def is_pypic(self):
return self.__pypic
def get_resultUpdateList(self):
return self.__resultUpdateList
def get_baudrate(self, read=False):
if self.__pypic and read and self.__baudrate > MAXPICREAD_BAUD_RATE:
return MAXPICREAD_BAUD_RATE
else:
return self.__baudrate
def set_baudrate(self, read=False):
if self.__current_baudrate != self.get_baudrate(read):
try:
self.__current_baudrate = self.get_baudrate(read)
self.esp.change_baud(self.__current_baudrate, self.__resultUpdateList)
except Exception as e:
print_exception(e)
def read(self, offset, size):
self.set_baudrate(True)
ret_val = self.esp.read_flash(offset, size, resultUpdateList=self.__resultUpdateList, partition=self.partition_name(offset))
self.set_baudrate(False)
return ret_val
def check_partition(self, partition):
if PARTITIONS.get(partition) is None:
return False
else:
return True
def partition_name(self, offset):
if offset > 0:
for partition in PARTITIONS.keys():
if int(PARTITIONS.get(partition)[0], 16) == offset:
return partition
return str(offset)
def int_flash_size(self):
args = Args()
args.flash_size = self.__flash_size
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = True
args.verify = False
args.no_stub = False
if args.flash_size == 'detect':
esptool.detect_flash_size(self.esp, args)
self.__flash_size = args.flash_size
str_flash_size = args.flash_size
try:
int_flash_size = int(str_flash_size.replace('MB', '')) * 0x100000
except:
int_flash_size = (4 * 0x100000) if args.flash_size != '8MB' else (8 * 0x100000)
return int_flash_size
def erase(self, offset, section_size, ui_label=None, updateList=False):
msg = "Erasing %s at address 0x%08X" % (hr_size(section_size), int(offset))
if ui_label is None:
print(msg)
else:
ui_label.setText(msg)
if updateList and self.__resultUpdateList is not None:
self.__resultUpdateList.append("Erased %s at address 0x%08X" % (hr_size(section_size), offset))
MAX_SECTION_SIZE = 0x380000
offset = int((offset // 4096) * 4096)
iterations = int((section_size + MAX_SECTION_SIZE - 1) // MAX_SECTION_SIZE)
for x in range(iterations):
s = min(section_size, MAX_SECTION_SIZE)
s = int(((s + 4095) // 4096) * 4096)
# We'll give it 3 attempts, if it still fails we lost the connection
try:
self.esp.erase_region(offset, s, progress_fs=self.__progress_fs)
except Exception as e:
try:
self.esp.erase_region(offset, s, progress_fs=self.__progress_fs)
except:
try:
self.esp.erase_region(offset, s, progress_fs=self.__progress_fs)
except:
print_exception(e)
raise e
offset += s
def erase_all(self, ui_label=None):
args = Args()
args.flash_size = self.__flash_size
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = True
args.verify = False
args.no_stub = False
if args.flash_size == 'detect':
esptool.detect_flash_size(self.esp, args)
self.__flash_size = args.flash_size
self.set_baudrate(False)
if ui_label is not None:
ui_label.setText("Erasing entire flash... this may take a while")
if self.__resultUpdateList is not None:
self.__resultUpdateList.append("Erasing entire flash")
ret_val = self.esp.erase_flash()
return ret_val
def write(self, offset, contents, compress=True, flash_size='detect', std_out=None, ui_label=None, file_name=None, updateList=True, progress_fs=None):
if progress_fs is not None:
self.__progress_fs = progress_fs
args = Args()
args.flash_size = self.__flash_size if flash_size == 'detect' else flash_size
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = compress
args.verify = False
args.no_stub = False
if args.flash_size == 'detect':
esptool.detect_flash_size(self.esp, args)
self.__flash_size = args.flash_size
self.set_baudrate(False)
fmap = BytesIO(contents)
args.addr_filename = [[offset, fmap]]
if std_out is not None:
sys.stdout = std_out
first_exception = None
for x in range(0, 3):
try:
esptool.write_flash(self.esp, args, ui_label=ui_label, file_name=file_name, resultUpdateList=self.__resultUpdateList if updateList else None, partition=self.partition_name(offset), progress_fs=self.__progress_fs)
fmap.close()
return
except AttributeError as ae:
print_exc(ae)
raise RuntimeError('Content at offset 0x%x does not fit available flash size of %s' % (offset, args.flash_size))
except Exception as e:
print_debug("Exception in write: {}".format(e), self.__debug)
if x == 0:
first_exception = e
fmap.close()
if first_exception is not None:
raise first_exception
def detect_flash_size(self):
args = Args()
args.flash_size = 'detect'
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = True
args.verify = False
args.no_stub = False
esptool.detect_flash_size(self.esp, args)
return args.flash_size
def write_script(self, offset, contents, config_block, overwrite=False, size=None, ui_label=None, file_name=None):
if overwrite or size is None:
self.write(offset, contents, ui_label=ui_label, file_name=file_name)
else:
if (len(contents) > size):
print_debug("Truncating this instruction by %s as it finishes outside specified partition size!" % hr_size(len(contents) - size), self.__debug)
contents = contents[:size]
args = Args()
args.flash_size = self.__flash_size
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = True
args.verify = False
args.no_stub = False
if args.flash_size == 'detect':
esptool.detect_flash_size(self.esp, args)
self.__flash_size = args.flash_size
finish_addr = offset + len(contents)
str_flash_size = args.flash_size
try:
int_flash_size = int(str_flash_size.replace('MB', '')) * 0x100000
except:
int_flash_size = (4 * 0x100000) if args.flash_size != '8MB' else (8 * 0x100000)
cb_start = int(PARTITIONS.get('config')[0], 16)
cb_len = int(PARTITIONS.get('config')[1], 16)
cb_end = cb_start + cb_len
if finish_addr > int_flash_size:
print_debug("Truncating this instruction by %s as it finishes outside available flash memory!" % ((hr_size(finish_addr - int_flash_size))), self.__debug)
contents = contents[:int_flash_size - offset]
finish_addr = offset + len(contents)
if offset >= int_flash_size:
print_debug("Ignoring this instruction as it starts outside available flash memory!", self.__debug)
elif offset < cb_end and finish_addr > cb_start:
if offset >= cb_start and finish_addr <= cb_end:
print_debug("Offset[0x%X] until finish_addr[0x%X] would only write within the CB! Skipping..." % (offset, finish_addr), self.__debug)
else:
print_debug("Offset[0x%X] + Content[%s] would overwrite CB! It ends at: 0x%X" % (offset, hr_size(len(contents)), finish_addr), self.__debug)
if config_block is None:
print_debug("I need to read the config block because I didn't receive it as a parameter", self.__debug)
config_block = self.read(cb_start, cb_len)
if offset < cb_start and finish_addr > cb_end:
self.write(offset, contents[0:cb_start - offset] + config_block + contents[cb_start - offset:], flash_size=args.flash_size, ui_label=ui_label)
elif offset <= cb_start and finish_addr <= cb_end:
self.write(offset, contents[0:cb_start - offset] + config_block, flash_size=args.flash_size, ui_label=ui_label)
elif offset > cb_start and finish_addr > cb_end:
self.write(offset, config_block + contents[cb_start - offset:], flash_size=args.flash_size, ui_label=ui_label)
else:
raise RuntimeError("I am unable to protect the config block from being overwritten.")
else:
print_debug("Offset[0x%X] + Content[%s] finish at: 0x%X" % (offset, hr_size(len(contents)), finish_addr), self.__debug)
self.write(offset, contents.ljust(size, b'\xFF'), flash_size=args.flash_size, ui_label=ui_label, file_name=file_name)
def write_remote(self, contents):
cb_start = int(PARTITIONS.get('config')[0], 16)
cb_len = int(PARTITIONS.get('config')[1], 16)
config_block = self.read(cb_start, cb_len)
self.write(cb_start, contents[0:52] + config_block[52:])
def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui_label=None, progress_fs=None, erase_nvs=False):
self.__progress_fs = progress_fs
if script is None:
raise ValueError('Invalid or no script file in firmware package!')
if DEBUG:
for instruction in script:
print_debug('Instruction: {} {}'.format(instruction[0], instruction[1]))
ota_updated = False
ota = None
img_size = 0xffffffff
no_erase = False
for instruction in script:
if instruction[1] == 'fs' or instruction[1] == 'fs1':
erase_fs = (instruction[0] == 'e')
elif instruction[1] == 'nvs':
erase_nvs = (instruction[0] == 'e')
elif instruction[1] == 'all':
erase_fs = False
erase_nvs = False
no_erase = not (instruction[0] == 'e')
start_time = time.time()
total_size = 0
for instruction in script:
if instruction[0] == 'e':
if no_erase:
print_debug("Ignoring erase instruction %s as entire flash partition is being written." % instruction[1], self.__debug)
continue
if instruction[1] == 'fs' or instruction[1] == 'fs1':
continue
if instruction[1] == 'all':
self.erase_all(ui_label=ui_label)
ota_updated = True
continue
if check_partition(instruction[1]):
instruction1 = int(PARTITIONS.get(instruction[1])[0], 16)
instruction2 = int(PARTITIONS.get(instruction[1])[1], 16)
elif instruction[1] == 'nvs':
instruction1 = int(PARTITIONS.get('nvs')[0], 16)
instruction2 = int(PARTITIONS.get('nvs')[1], 16)
elif instruction[1] == 'cb' or instruction[1] == 'config':
instruction1 = int(PARTITIONS.get('config')[0], 16)
instruction2 = int(PARTITIONS.get('config')[1], 16)
elif instruction[1] == 'ota' or instruction[1] == 'otadata':
instruction1 = int(PARTITIONS.get('otadata')[0], 16)
instruction2 = int(PARTITIONS.get('otadata')[1], 16)
ota_updated = True
else:
instruction1 = int(instruction[1], 16)
instruction2 = int(instruction[2], 16)
if instruction1 <= int(PARTITIONS.get('otadata')[0], 16) and instruction1 + instruction2 >= int(PARTITIONS.get('otadata')[0], 16) + int(PARTITIONS.get('otadata')[1], 16):
ota_updated = True
if ota_updated:
print_debug("OTA partition has been erased.", self.__debug)
total_size += instruction2
self.erase(instruction1, instruction2, ui_label=ui_label)
if total_size > 0 and self.__resultUpdateList is not None:
if humanfriendly_available:
self.__resultUpdateList.append('Erased {} in {}'.format(humanfriendly.format_size(total_size, binary=True), humanfriendly.format_timespan(time.time() - start_time)))
else:
self.__resultUpdateList.append('Erased {} in {0:.2f} seconds'.format(hr_size(total_size), time.time() - start_time))
if erase_fs:
self.erase_fs(chip_id, ui_label=ui_label)
if erase_nvs:
self.erase(int(PARTITIONS.get('nvs')[0], 16), int(PARTITIONS.get('nvs')[1], 16), ui_label=ui_label, updateList = True)
for instruction in script:
if instruction[0].split(':', 2)[0] == 'w' or instruction[0].split(':', 2)[0] == 'o':
file_name = instruction[0].split(':', 2)[-1]
print_debug(("Writing %s " + ("to partition %s" if check_partition(instruction[1]) else "at offset %s")) % (file_name, instruction[1]), self.__debug)
psize = None
instruction1 = instruction[1]
if instruction[1] == 'fs' or instruction[1] == 'fs1':
erase_fs = False
if instruction[1] == 'otadata':
ota_updated = True
if check_partition(instruction[1]):
if instruction[1] == "ota_0":
ota = True
img_size = len(instruction[2])
elif instruction[1] == "factory":
if ota is None:
ota = False
img_size = len(instruction[2])
psize = int(PARTITIONS.get(instruction[1])[1], 16)
if instruction[1] == "all":
psize = self.int_flash_size()
instruction1 = PARTITIONS.get(instruction[1])[0]
elif instruction[1] == 'cb':
instruction1 = PARTITIONS.get('config')[0]
psize = int(PARTITIONS.get('config')[1], 16)
elif instruction[1] == 'ota':
ota_updated = True
instruction1 = PARTITIONS.get('otadata')[0]
psize = int(PARTITIONS.get('otadata')[1], 16)
try:
int_instr1 = int(instruction1, 16)
except ValueError:
raise ValueError('Invalid partition or memory region %s' % str(instruction1))
self.write_script(int_instr1, instruction[2], config_block, instruction[0].split(':', 2)[0] == 'o', size=psize, ui_label=ui_label, file_name=file_name)
if (int_instr1 <= int(PARTITIONS.get('otadata')[0], 16)) and (int_instr1 + (len(instruction[2]) if psize is None else psize) >= int(PARTITIONS.get('otadata')[0], 16) + int(PARTITIONS.get('otadata')[1], 16)):
ota_updated = True
print_debug("OTA partition has been written.", self.__debug)
elif instruction[0] != 'e':
raise ValueError('Invalid script command %s' % instruction[0].split(':', 2)[0])
if ota is not None and not ota_updated:
self.set_ota(ota, img_size, ui_label=ui_label)
def set_ota(self, ota, image_size, ui_label=None):
ota_signature = b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
crc32_header = b'\xff\xff\xff\xff'
if ota:
ota_data = struct.pack('<5I16s', 1, 0, 0, image_size, 0, ota_signature)
ota_crc32 = (binascii.crc32(crc32_header + ota_data) % (1 << 32))
ota_part = struct.pack('<36sI', ota_data, ota_crc32)
if ui_label is not None:
ui_label.setText("Setting otadata partition to boot from ota_0")
if self.__resultUpdateList is not None:
self.__resultUpdateList.append("Booting from partition: <b>ota_0</b>")
print_debug("Setting otadata partition to boot from ota_0", self.__debug)
self.write(int(PARTITIONS.get('otadata')[0], 16), ota_part.ljust(int(PARTITIONS.get('otadata')[1], 16), b'\xff'))
else:
ota_data = struct.pack('<5I16s', 0, 1, 0, image_size, 0, ota_signature)
ota_crc32 = (binascii.crc32(crc32_header + ota_data) % (1 << 32))
ota_part = struct.pack('<36sI', ota_data, ota_crc32)
if ui_label is not None:
ui_label.setText("Setting otadata partition to boot from factory partition")
if self.__resultUpdateList is not None:
self.__resultUpdateList.append("Booting from partition: <b>factory</b>")
print_debug("Setting otadata partition to boot from factory", self.__debug)
self.write(int(PARTITIONS.get('otadata')[0], 16), ota_part.ljust(int(PARTITIONS.get('otadata')[1], 16), b'\xff'))
def erase_sytem_mem(self):
# Erase first 3.5Mb (this way fs and MAC address will be untouched)
self.erase(0, 0x3100000)
def erase_fs(self, chip_id=None, ui_label=None, progress_fs=None):
self.__progress_fs = progress_fs
start_time = time.time()
print_debug('self.int_flash_size() = {}'.format(self.int_flash_size()))
print_debug('chip_id = {}'.format(chip_id))
if self.int_flash_size() == 0x800000:
print_debug("Erasing 8MB device flash fs", self.__debug)
# self.erase(int(PARTITIONS.get('fs')[0], 16), int(PARTITIONS.get('fs')[1], 16), ui_label=ui_label, updateList=False)
section_size = int(PARTITIONS.get('fs1')[1], 16) / 8
for x in range(0, 8):
self.erase(int(PARTITIONS.get('fs1')[0], 16) + (x * section_size), section_size, ui_label=ui_label, updateList=False)
if self.__resultUpdateList is not None:
if humanfriendly_available:
self.__resultUpdateList.append("Erased {} flash fs in {}".format(humanfriendly.format_size(int(PARTITIONS.get('fs1')[1], 16), binary=True), humanfriendly.format_timespan(time.time() - start_time)))
else:
self.__resultUpdateList.append("Erased {} flash fs in {0:.2f} seconds".format(hr_size(int(PARTITIONS.get('fs1')[1], 16)), time.time() - start_time))
else:
print_debug("Erasing 4MB device flash fs", self.__debug)
self.erase(int(PARTITIONS.get('fs')[0], 16), int(PARTITIONS.get('fs')[1], 16), ui_label=ui_label, updateList=False)
if self.__resultUpdateList is not None:
if humanfriendly_available:
self.__resultUpdateList.append("Erased {} flash fs in {}".format(humanfriendly.format_size(int(PARTITIONS.get('fs')[1], 16), binary=True), humanfriendly.format_timespan(time.time() - start_time)))
else:
self.__resultUpdateList.append("Erased {} flash fs in {0:.2f} seconds".format(hr_size(int(PARTITIONS.get('fs')[1], 16)), time.time() - start_time))
def get_chip_id(self):
try:
return self.esp.get_chip_description()
except Exception as e:
try:
return self.esp.get_chip_description()
except:
print_exception(e)
raise e
def flash_bin(self, dest_and_file_pairs, ui_label=None, file_name=None, progress_fs=None):
args = Args()
args.flash_size = self.__flash_size
args.flash_mode = FLASH_MODE
args.flash_freq = FLASH_FREQ
args.compress = True
args.verify = True
if args.flash_size == 'detect':
esptool.detect_flash_size(self.esp, args)
self.__flash_size = args.flash_size
dest_and_file = list(dest_and_file_pairs)
for i, el in enumerate(dest_and_file):
dest_and_file[i][1] = open(el[1], "rb")
args.addr_filename = dest_and_file
esptool.write_flash(self.esp, args, ui_label=ui_label, file_name=file_name, resultUpdateList=self.__resultUpdateList, progress_fs=progress_fs)
def set_wifi_config(self, config_block, wifi_ssid=None, wifi_pwd=None, wifi_on_boot=None):
config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00')
if wifi_on_boot is not None:
if wifi_on_boot == True:
wob = b'\xbb'
else:
wob = b'\xba'
else:
if sys.version_info[0] < 3:
wob = config_block[53]
else:
wob = config_block[53].to_bytes(1, byteorder='little')
if wifi_ssid is not None:
ssid = wifi_ssid.encode().ljust(33, b'\x00')
else:
ssid = config_block[54:87]
if wifi_pwd is not None:
pwd = wifi_pwd.encode().ljust(65, b'\x00')
else:
pwd = config_block[87:152]
new_config_block = config_block[0:53] \
+wob \
+ssid \
+pwd \
+config_block[152:]
return self.set_pybytes_config(new_config_block, force_update=True)
def set_lte_config(self, config_block, carrier=None, apn=None, lte_type=None, cid=None, band=None, reset=None):
config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00')
if carrier is not None:
cb_carrier = str(carrier[0:128]).ljust(129, b'\x00')
else:
cb_carrier = config_block[634:763]
if apn is not None:
cb_apn = str(apn[0:128]).ljust(129, b'\x00')
else:
cb_apn = config_block[763:892]
if lte_type is not None:
cb_lte_type = str(lte_type[0:16]).ljust(17, b'\x00')
else:
cb_lte_type = config_block[892:909]
if cid is not None:
cb_cid = struct.pack('>B', int(cid))
else:
cb_cid = config_block[909]
if band is not None:
cb_band = struct.pack('>B', int(band))
else:
cb_band = config_block[910]
if reset is not None:
cb_reset = struct.pack('>B', int(reset == 'True'))
else:
cb_reset = config_block[911]
new_config_block = config_block[0:634] \
+cb_carrier \
+cb_apn \
+cb_lte_type \
+cb_cid \
+cb_band \
+cb_reset \
+config_block[912:]
return self.set_pybytes_config(new_config_block, force_update=True)
def set_pycom_config(self, config_block, boot_fs_type=None):
print_debug('This is set_pycom_config with boot_fs_type={} [{}]'.format(boot_fs_type, type(boot_fs_type)))
config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00')
if boot_fs_type is None:
print_debug('Not doing anything because boot_fs_type is None')
return config_block
if DEBUG:
self.print_cb(config_block)
if boot_fs_type is not None:
if str(boot_fs_type) == 'LittleFS' or boot_fs_type == 1 or str(boot_fs_type) == '1':
fs = b'\x01'
else:
fs = b'\x00'
new_config_block = config_block[0:533] \
+fs \
+config_block[534:]
if DEBUG:
self.print_cb(config_block)
if self.__resultUpdateList is not None:
self.__resultUpdateList.append('File system type set to <b>{}</b>'.format('LittleFS' if (boot_fs_type == 'LittleFS' or boot_fs_type == 1 or boot_fs_type == '1') else 'FatFS'))
return self.set_pybytes_config(new_config_block, force_update=True)
def print_cb(self, config_block):
if DEBUG:
for x in range(0, 30):
print(binascii.hexlify(config_block[x * 32:x * 32 + 32]).decode('UTF-8'))
def set_pybytes_config(self, config_block, userid=None, device_token=None, mqttServiceAddress=None, network_preferences=None, extra_preferences=None, force_update=None, auto_start=None):
config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00')
if device_token is not None:
token = str(device_token)[0:39].ljust(40, b'\x00')
else:
token = config_block[162:202]
if mqttServiceAddress is not None:
address = str(mqttServiceAddress)[0:39].ljust(40, b'\x00')
else:
address = config_block[202:242]
if userid is not None:
uid = str(userid)[0:99].ljust(100, b'\x00')
else:
uid = config_block[242:342]
if network_preferences is not None:
nwp = str(network_preferences)[0:54].ljust(55, b'\x00')
else:
nwp = config_block[342:397]
if extra_preferences is not None:
ep = str(extra_preferences)[0:99].ljust(100, b'\x00')
else:
ep = config_block[397:497]
if force_update is not None:
if force_update:
fu = b'\x01'
else:
fu = b'\x00'
else:
if sys.version_info[0] < 3:
fu = config_block[497]
else:
fu = config_block[497].to_bytes(1, byteorder='little')
if auto_start is not None:
if auto_start:
asf = b'\x01'
else:
asf = b'\x00'
else:
if sys.version_info[0] < 3:
asf = config_block[498]
else:
asf = config_block[498].to_bytes(1, byteorder='little')
new_config_block = config_block[0:162] \
+token \
+address \
+uid \
+nwp \
+ep \
+fu \
+asf \
+config_block[499:]
# self.print_cb(new_config_block)
return new_config_block
def str2region(self, lora_region_str):
if lora_region_str is not None:
return {
'EU868' : LORAMAC_REGION_EU868,
'US915' : LORAMAC_REGION_US915,
'AU915' : LORAMAC_REGION_AU915,
'AS923' : LORAMAC_REGION_AS923
}.get(lora_region_str, 0xff)
else:
return 0xff
def region2str(self, lora_region_int):
if lora_region_int is not None:
return {
LORAMAC_REGION_EU868 : 'EU868',
LORAMAC_REGION_US915 : 'US915',
LORAMAC_REGION_AU915 : 'AU915',
LORAMAC_REGION_AS923 : 'AS923'
}.get(lora_region_int, 'NONE')
else:
return None
def set_lpwan_config(self, config_block, lora_region=None):
config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00')
if lora_region is not None:
if sys.version_info[0] < 3:
region = chr(self.str2region(lora_region))
else:
region = self.str2region(lora_region).to_bytes(1, byteorder='little')
else:
if sys.version_info[0] < 3:
region = config_block[52]
else:
region = config_block[52].to_bytes(1, byteorder='little')
new_config_block = config_block[0:52] \
+region \
+config_block[53:]
return new_config_block
def set_sigfox_config(self, config_block, sid=None, pac=None, pubkey=None, privkey=None):
config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00')
if sid is not None:
if not len(sid)==8:
raise ValueError('ID must be 8 HEX characters')
sigid = bytearray.fromhex(sid).ljust(4, b'\x00')
else:
sigid = config_block[8:12]
if pac is not None:
if not len(pac)==16:
raise ValueError('PAC must be 16 HEX characters')
spac = bytearray.fromhex(pac).ljust(8, b'\x00')
else:
spac = config_block[12:20]
if privkey is not None:
if not len(privkey)==32:
raise ValueError('private key must be 32 HEX characters')
sprivkey = bytearray.fromhex(privkey).ljust(16, b'\x00')
else:
sprivkey = config_block[20:36]
if pubkey is not None:
if not len(pubkey)==32:
raise ValueError('public key must be 32 HEX characters')
spubkey = bytearray.fromhex(pubkey).ljust(16, b'\x00')
else:
spubkey = config_block[36:52]
new_config_block = config_block[0:8] \
+sigid \
+spac \
+ sprivkey \
+ spubkey \
+config_block[52:]
return new_config_block
def read_mac(self):
# returns a tuple with (wifi_mac, bluetooth_mac)
return self.esp.read_mac()
def reset_pycom_module(self):
pic = Pypic(self.esp_port)
if pic.isdetected():
pic.reset_pycom_module()
pic.close()
def exit_pycom_programming_mode(self, reset=True):
if not self.__pypic:
self.esp.hard_reset()
time.sleep(.5)
del self.esp
if (self.__pypic):
pic = Pypic(self.esp_port)
if pic.isdetected():
pic.exit_pycom_programming_mode(reset)
pic.close()
def enter_pycom_programming_mode(self):
pic = Pypic(self.esp_port)
if pic.isdetected():
print("Product ID: %d HW Version: %d FW Version: 0.0.%d" % (pic.read_product_id(), pic.read_hw_version(), pic.read_fw_version()))
pic.enter_pycom_programming_mode()
pic.close()
def check_usbid(port):
for n, (portname, desc, hwid) in enumerate(sorted(serial.tools.list_ports.comports(), reverse=True)):
if (portname.replace("/dev/tty.", "/dev/cu.").upper() == str(port).replace("/dev/tty.", "/dev/cu.").upper()):
for usbid in PIC_BOARDS:
if usbid in hwid:
return True
else:
return False
raise ValueError('Invalid serial port %s! Use list command to show valid ports.' % port)
def list_usbid():
for n, (portname, desc, hwid) in enumerate(sorted(serial.tools.list_ports.comports(), reverse=True)):
print("%s [%s] [%s]" % (portname, desc, hwid))
def check_partition(partition):
if PARTITIONS.get(partition) is None:
return False
else:
return True
def check_lora_region(region):
if region in LORA_REGIONS:
return True
else:
return False
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected [yes, true, 1 or no, false, 0]')
def process_arguments():
cmd_parser = argparse.ArgumentParser(description='Update your Pycom device with the specified firmware image file\n\nFor more details please see https://docs.pycom.io/chapter/advance/cli.html')
cmd_parser.add_argument('-v', '--verbose', action='store_true', help='show verbose output from esptool')
cmd_parser.add_argument('-d', '--debug', action='store_true', help='show debuggin output from fwtool')
cmd_parser.add_argument('-q', '--quiet', action='store_true', help='suppress success messages')
cmd_parser.add_argument('-p', '--port', default=None, help='the serial port to use')
cmd_parser.add_argument('-s', '--speed', default=None, type=int, help='baudrate')
cmd_parser.add_argument('-c', '--continuation', action='store_true', help='continue previous connection')
cmd_parser.add_argument('-x', '--noexit', action='store_true', help='do not exit firmware update mode')
cmd_parser.add_argument('--ftdi', action='store_true', help='force running in ftdi mode')
cmd_parser.add_argument('--pic', action='store_true', help='force running in pic mode')
cmd_parser.add_argument('-r', '--reset', action='store_true', help='use Espressif reset mode')
subparsers = cmd_parser.add_subparsers(dest='command')
subparsers.add_parser('list', help='Get list of available COM ports')
subparsers.add_parser('chip_id', help='Show ESP32 chip_id')
subparsers.add_parser('wmac', help='Show WiFi MAC')
subparsers.add_parser('smac', help='Show LPWAN MAC')
subparsers.add_parser('exit', help='Exit firmware update mode')
if DEBUG: