forked from NordicSemiconductor/pc-nrfutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__main__.py
executable file
·1457 lines (1272 loc) · 58 KB
/
__main__.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
#
# Copyright (c) 2016 Nordic Semiconductor ASA
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# 3. Neither the name of Nordic Semiconductor ASA nor the names of other
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# 4. This software must only be used in or with a processor manufactured by Nordic
# Semiconductor ASA, or in or with a processor manufactured by a third party that
# is used in combination with a processor manufactured by Nordic Semiconductor.
#
# 5. Any software provided in binary or object form under this license must not be
# reverse engineered, decompiled, modified and/or disassembled.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import ipaddress
import signal
"""nrfutil command line tool."""
import os
import sys
import click
import time
import logging
import subprocess
import re
sys.path.append(os.getcwd())
from nordicsemi.dfu.bl_dfu_sett import BLDFUSettings
from nordicsemi.dfu.dfu import Dfu
from nordicsemi.dfu.dfu_transport import DfuEvent, TRANSPORT_LOGGING_LEVEL
from nordicsemi.dfu.dfu_transport_serial import DfuTransportSerial
from nordicsemi.dfu.package import Package
from nordicsemi import version as nrfutil_version
from nordicsemi.dfu.signing import Signing
from nordicsemi.dfu.util import query_func
from nordicsemi.zigbee.prod_config import ProductionConfig, ProductionConfigWrongException, ProductionConfigTooLargeException
from pc_ble_driver_py.exceptions import NordicSemiException, NotImplementedException
from nordicsemi.lister.device_lister import DeviceLister
logger = logging.getLogger(__name__)
def ble_driver_init(conn_ic_id):
global BLEDriver, Flasher, DfuTransportBle
from pc_ble_driver_py import config
config.__conn_ic_id__ = conn_ic_id
from pc_ble_driver_py.ble_driver import BLEDriver, Flasher
from nordicsemi.dfu.dfu_transport_ble import DfuTransportBle
def display_sec_warning():
default_key_warning = """
|===============================================================|
|## ## ### ######## ## ## #### ## ## ###### |
|## ## ## ## ## ## ## ### ## ## ### ## ## ## |
|## ## ## ## ## ## ## #### ## ## #### ## ## |
|## ## ## ## ## ######## ## ## ## ## ## ## ## ## ####|
|## ## ## ######### ## ## ## #### ## ## #### ## ## |
|## ## ## ## ## ## ## ## ### ## ## ### ## ## |
| ### ### ## ## ## ## ## ## #### ## ## ###### |
|===============================================================|
|The security key you provided is insecure, as it part of a |
|known set of keys that have been widely distributed. Do NOT use|
|it in your final product or your DFU procedure may be |
|compromised and at risk of malicious attacks. |
|===============================================================|
"""
click.echo("{}".format(default_key_warning))
def display_nokey_warning():
default_nokey_warning = """
|===============================================================|
|## ## ### ######## ## ## #### ## ## ###### |
|## ## ## ## ## ## ## ### ## ## ### ## ## ## |
|## ## ## ## ## ## ## #### ## ## #### ## ## |
|## ## ## ## ## ######## ## ## ## ## ## ## ## ## ####|
|## ## ## ######### ## ## ## #### ## ## #### ## ## |
|## ## ## ## ## ## ## ## ### ## ## ### ## ## |
| ### ### ## ## ## ## ## ## #### ## ## ###### |
|===============================================================|
|You are not providing a signature key, which means the DFU |
|files will not be signed, and are vulnerable to tampering. |
|This is only compatible with a signature-less bootloader and is|
|not suitable for production environments. |
|===============================================================|
"""
click.echo("{}".format(default_nokey_warning))
def display_debug_warning():
debug_warning = """
|===============================================================|
|## ## ### ######## ## ## #### ## ## ###### |
|## ## ## ## ## ## ## ### ## ## ### ## ## ## |
|## ## ## ## ## ## ## #### ## ## #### ## ## |
|## ## ## ## ## ######## ## ## ## ## ## ## ## ## ####|
|## ## ## ######### ## ## ## #### ## ## #### ## ## |
|## ## ## ## ## ## ## ## ### ## ## ### ## ## |
| ### ### ## ## ## ## ## ## #### ## ## ###### |
|===============================================================|
|You are generating a package with the debug bit enabled in the |
|init packet. This is only compatible with a debug bootloader |
|and is not suitable for production. |
|===============================================================|
"""
click.echo("{}".format(debug_warning))
def display_settings_backup_warning():
debug_warning = """
Note: Generating a DFU settings page with backup page included.
This is only required for bootloaders from nRF5 SDK 15.1 and newer.
If you want to skip backup page generation, use --no-backup option."""
click.echo("{}".format(debug_warning))
def int_as_text_to_int(value):
try:
if value[:2].lower() == '0x':
return int(value[2:], 16)
elif value[:1] == '0':
return int(value, 8)
return int(value, 10)
except ValueError:
raise NordicSemiException('%s is not a valid integer' % value)
def pause():
while True:
try:
raw_input()
except (KeyboardInterrupt, EOFError):
break
class BasedIntOrNoneParamType(click.ParamType):
name = 'Integer'
def convert(self, value, param, ctx):
try:
if value.lower() == 'none':
return 'none'
return int_as_text_to_int(value)
except NordicSemiException:
self.fail('%s is not a valid integer' % value, param, ctx)
BASED_INT_OR_NONE = BasedIntOrNoneParamType()
class BasedIntParamType(BasedIntOrNoneParamType):
name = 'Integer'
BASED_INT= BasedIntParamType()
class TextOrNoneParamType(click.ParamType):
name = 'Text'
def convert(self, value, param, ctx):
return value
TEXT_OR_NONE = TextOrNoneParamType()
BOOT_VALIDATION_ARGS =\
[
'NO_VALIDATION',
'VALIDATE_GENERATED_CRC',
'VALIDATE_GENERATED_SHA256',
'VALIDATE_ECDSA_P256_SHA256',
]
DEFAULT_BOOT_VALIDATION = 'VALIDATE_GENERATED_CRC'
class OptionRequiredIf(click.Option):
def full_process_value(self, ctx, value):
value = super(OptionRequiredIf, self).full_process_value(ctx, value)
if ('serial_number' not in ctx.params or not ctx.params['serial_number']) and value is None:
msg = 'Required if "-snr" / "--serial-number" is not defined.'
raise click.MissingParameter(ctx=ctx, param=self, message=msg)
return value
@click.group()
@click.option('-v', '--verbose',
help='Increase verbosity of output. Can be specified more than once (up to -v -v -v -v).',
count=True)
@click.option('-o', '--output',
help='Log output to file',
metavar='<filename>')
def cli(verbose, output):
#click.echo('verbosity: %s' % verbose)
if verbose == 0:
log_level = logging.ERROR
elif verbose == 1:
log_level = logging.WARNING
elif verbose == 2:
log_level = logging.INFO
elif verbose == 3:
log_level = logging.DEBUG
else:
# Custom level, logs all the bytes sent/received over the wire/air
log_level = TRANSPORT_LOGGING_LEVEL
logging.basicConfig(format='%(asctime)s %(message)s', level=log_level)
if (output):
root = logging.getLogger('')
fh = logging.FileHandler(output)
fh.setLevel(log_level)
fh.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
root.addHandler(fh)
@cli.command()
def version():
"""Display nrfutil version."""
click.echo("nrfutil version {}".format(nrfutil_version.NRFUTIL_VERSION))
logger.info("PyPi URL: https://pypi.python.org/pypi/nrfutil")
logger.debug("GitHub URL: https://github.com/NordicSemiconductor/pc-nrfutil")
@cli.group(short_help='Generate and display Bootloader DFU settings.')
def settings():
"""
This set of commands supports creating and displaying bootloader settings.
"""
pass
@settings.command(short_help='Generate a .hex file with Bootloader DFU settings.')
@click.argument('hex_file', required=True, type=click.Path())
@click.option('--family',
help='nRF IC family: NRF51 or NRF52 or NRF52QFAB or NRF52810 or NRF52840',
type=click.Choice(['NRF51', 'NRF52', 'NRF52QFAB', 'NRF52810', 'NRF52840']))
@click.option('--application',
help='The application firmware file. This can be omitted if'
'the target IC does not contain an application in flash.'
'Requires --application-version or --application-version-string.',
type=click.STRING)
@click.option('--application-version',
help='The application version.',
type=BASED_INT_OR_NONE)
@click.option('--application-version-string',
help='The application version string, e.g "2.7.31".',
type=click.STRING)
@click.option('--bootloader-version',
help='The bootloader version.',
type=BASED_INT_OR_NONE)
@click.option('--bl-settings-version',
help='The Bootloader settings version.'
'Defined in nrf_dfu_types.h, the following apply to released SDKs:'
'\n|SDK12.0.0 - SDK15.2.0|1|'
'\n|SDK15.3.0 - |2|',
type=BASED_INT_OR_NONE)
@click.option('--start-address',
help='Custom start address for the settings page. If not specified, '
'then the last page of the flash is used.',
type=BASED_INT_OR_NONE)
@click.option('--no-backup',
help='Do not overwrite DFU settings backup page. If not specified, '
'than the resulting .hex file will contain a copy of DFU settings, '
'that will overwrite contents of DFU settings backup page.',
type=click.BOOL,
is_flag=True,
required=False)
@click.option('--backup-address',
help='Address of the DFU settings backup page inside flash. '
'By default, the backup page address is placed one page below DFU settings. '
'The value is precalculated based on configured settings address '
'(<DFU_settings_addrsss> - 0x1000).',
type=BASED_INT_OR_NONE)
@click.option('--app-boot-validation',
help='The method of boot validation for application. Choose from:\n%s' % ('\n'.join(BOOT_VALIDATION_ARGS),),
required=False,
type=click.STRING)
@click.option('--sd-boot-validation',
help='The method of boot validation for Softdevice. Choose from:\n%s' % ('\n'.join(BOOT_VALIDATION_ARGS),),
required=False,
type=click.STRING)
@click.option('--softdevice',
help='The SoftDevice firmware file. Must be given if SD Boot Validation is used.',
required=False,
type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False))
@click.option('--key-file',
help='The private (signing) key in PEM fomat. Needed for ECDSA Boot Validation.',
required=False,
type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False))
def generate(hex_file,
family,
application,
application_version,
application_version_string,
bootloader_version,
bl_settings_version,
start_address,
no_backup,
backup_address,
app_boot_validation,
sd_boot_validation,
softdevice,
key_file):
# Initial consistency checks
if family is None:
click.echo("Error: IC Family required.")
return
# The user can specify the application version with two different
# formats. As an integer, e.g. 102130, or as a string
# "10.21.30". Internally we convert to integer.
if application_version_string:
application_version_internal = convert_version_string_to_int(application_version_string)
else:
application_version_internal = application_version
if application is not None:
if not os.path.isfile(application):
click.echo("Error: Application file not found.")
return
if application_version_internal is None:
click.echo("Error: Application version required.")
return
if bootloader_version is None:
click.echo("Error: Bootloader version required.")
return
if bl_settings_version is None:
click.echo("Error: Bootloader DFU settings version required.")
return
if (no_backup is not None) and (backup_address is not None):
click.echo("Error: Bootloader DFU settings backup page cannot be specified if backup is disabled.")
return
if no_backup is None:
no_backup = False
if no_backup is False:
display_settings_backup_warning()
if (start_address is not None) and (backup_address is None):
click.echo("WARNING: Using default offset in order to calculate bootloader settings backup page")
if sd_boot_validation and (sd_boot_validation not in BOOT_VALIDATION_ARGS):
click.echo("Error: --sd_boot_validation called with invalid argument. Must be one of:\n%s" % ("\n".join(BOOT_VALIDATION_ARGS)))
return
if app_boot_validation and (app_boot_validation not in BOOT_VALIDATION_ARGS):
click.echo("Error: --app_boot_validation called with invalid argument. Must be one of:\n%s" % ("\n".join(BOOT_VALIDATION_ARGS)))
return
if bl_settings_version == 1 and (app_boot_validation or sd_boot_validation):
click.echo("Error: Bootloader settings version 1 does not support boot validation.")
return
if (app_boot_validation == 'VALIDATE_ECDSA_P256_SHA256' and key_file is None) or \
(sd_boot_validation == 'VALIDATE_ECDSA_P256_SHA256' and key_file is None):
click.echo("Error: Key file must be given when 'VALIDATE_ECDSA_P256_SHA256' boot validation is used")
return
if app_boot_validation and not application:
click.echo("Error: --application hex file must be set when using --app_boot_validation")
return
if sd_boot_validation and not softdevice:
click.echo("Error: --softdevice hex file must be set when using --sd_boot_validation")
return
# Default boot validation cases
if app_boot_validation is None and application is not None and bl_settings_version == 2:
app_boot_validation = DEFAULT_BOOT_VALIDATION
if sd_boot_validation is None and softdevice is not None and bl_settings_version == 2:
sd_boot_validation = DEFAULT_BOOT_VALIDATION
sett = BLDFUSettings()
sett.generate(arch=family, app_file=application, app_ver=application_version_internal, bl_ver=bootloader_version,
bl_sett_ver=bl_settings_version, custom_bl_sett_addr=start_address, no_backup=no_backup,
backup_address=backup_address, app_boot_validation_type=app_boot_validation,
sd_boot_validation_type=sd_boot_validation, sd_file=softdevice, key_file=key_file)
sett.tohexfile(hex_file)
click.echo("\nGenerated Bootloader DFU settings .hex file and stored it in: {}".format(hex_file))
click.echo("{0}".format(str(sett)))
@settings.command(short_help='Display the contents of a .hex file with Bootloader DFU settings.')
@click.argument('hex_file', required=True, type=click.Path())
def display(hex_file):
sett = BLDFUSettings()
try:
sett.fromhexfile(hex_file)
except NordicSemiException as err:
click.echo(err)
return
click.echo("{0}".format(str(sett)))
@cli.group(short_help='Generate and display private and public keys.')
def keys():
"""
This set of commands supports creating and displaying a private (signing) key
as well as displaying the public (verification) key derived from a private key.
Private keys are stored in PEM format.
"""
pass
@keys.command(short_help='Generate a private key and store it in a file in PEM format.')
@click.argument('key_file', required=True, type=click.Path())
def generate(key_file):
signer = Signing()
if os.path.exists(key_file):
if not query_func("File found at %s. Do you want to overwrite the file?" % key_file):
click.echo('Key generation aborted.')
return
signer.gen_key(key_file)
click.echo("Generated private key and stored it in: %s" % key_file)
@keys.command(short_help='Display the private key that is stored in a file in PEM format or a public key derived from it.')
@click.argument('key_file', required=True, type=click.Path())
@click.option('--key',
help='(pk|sk) Display the public key (pk) or the private key (sk).',
type=click.STRING)
@click.option('--format',
help='(hex|code|pem) Display the key in hexadecimal format (hex), C code (code), or PEM (pem) format.',
type=click.STRING)
@click.option('--out_file',
help='If provided, save the output in file out_file.',
type=click.STRING)
def display(key_file, key, format, out_file):
signer = Signing()
if not os.path.isfile(key_file):
raise NordicSemiException("File not found: %s" % key_file)
default_key = signer.load_key(key_file)
if default_key:
display_sec_warning()
if not key:
click.echo("You must specify a key with --key (pk|sk).")
return
if key != "pk" and key != "sk":
click.echo("Invalid key type. Valid types are (pk|sk).")
return
if not format:
click.echo("You must specify a format with --format (hex|code|pem).")
return
if format != "hex" and format != "code" and format != "pem" and format != "dbgcode":
click.echo("Invalid format. Valid formats are (hex|code|pem).")
return
if format == "dbgcode":
format = "code"
dbg = True
else:
dbg = False
if format == "code" and key == "sk":
click.echo("Displaying the private key as code is not available.")
return
if key == "pk":
kstr = signer.get_vk(format, dbg)
elif key == "sk":
kstr = "\nWARNING: Security risk! Do not share the private key.\n\n"
kstr = kstr + signer.get_sk(format, dbg)
if not out_file:
click.echo(kstr)
else:
with open(out_file, "w") as kfile:
kfile.write(kstr)
@cli.group(short_help='Display or generate a DFU package (zip file).')
def pkg():
"""
This set of commands supports Nordic DFU package generation.
"""
pass
@pkg.command(short_help='Generate a zip file for performing DFU.')
@click.argument('zipfile',
required=True,
type=click.Path())
@click.option('--debug-mode',
help='Debug mode switch, enables version check skipping.',
type=click.BOOL,
default=False,
is_flag=True)
@click.option('--application',
help='The application firmware file.',
type=click.STRING)
@click.option('--application-version',
help='The application version.',
type=BASED_INT_OR_NONE)
@click.option('--application-version-string',
help='The application version string, e.g "2.7.31".',
type=click.STRING)
@click.option('--bootloader',
help='The bootloader firmware file.',
type=click.STRING)
@click.option('--bootloader-version',
help='The bootloader version.',
type=BASED_INT_OR_NONE)
@click.option('--hw-version',
help='The hardware version.',
required=False,
type=BASED_INT)
@click.option('--sd-req',
help='The SoftDevice requirements. A comma-separated list of SoftDevice firmware IDs '
'(1 or more) of which one must be present on the target device. Each item on the '
'list must be a two- or four-digit hex number prefixed with \"0x\" (e.g. \"0x12\", '
'\"0x1234\").\n'
'A non-exhaustive list of well-known values to use with this option follows:'
'\n|s112_nrf52_6.0.0|0xA7|'
'\n|s112_nrf52_6.1.0|0xB0|'
'\n|s112_nrf52_6.1.1|0xB8|'
'\n|s130_nrf51_1.0.0|0x67|'
'\n|s130_nrf51_2.0.0|0x80|'
'\n|s132_nrf52_2.0.0|0x81|'
'\n|s130_nrf51_2.0.1|0x87|'
'\n|s132_nrf52_2.0.1|0x88|'
'\n|s132_nrf52_3.0.0|0x8C|'
'\n|s132_nrf52_3.1.0|0x91|'
'\n|s132_nrf52_4.0.0|0x95|'
'\n|s132_nrf52_4.0.2|0x98|'
'\n|s132_nrf52_4.0.3|0x99|'
'\n|s132_nrf52_4.0.4|0x9E|'
'\n|s132_nrf52_4.0.5|0x9F|'
'\n|s132_nrf52_5.0.0|0x9D|'
'\n|s132_nrf52_5.1.0|0xA5|'
'\n|s132_nrf52_6.0.0|0xA8|'
'\n|s132_nrf52_6.1.0|0xAF|'
'\n|s132_nrf52_6.1.1|0xB7|'
'\n|s140_nrf52_6.0.0|0xA9|'
'\n|s140_nrf52_6.1.0|0xAE|'
'\n|s140_nrf52_6.1.1|0xB6|',
type=click.STRING,
required=False,
multiple=True)
@click.option('--sd-id',
help='The new SoftDevice ID to be used as --sd-req for the Application update in case the ZIP '
'contains a SoftDevice and an Application.',
type=click.STRING,
multiple=True)
@click.option('--softdevice',
help='The SoftDevice firmware file.',
type=click.STRING)
@click.option('--sd-boot-validation',
help='The method of boot validation for Softdevice. Choose from:\n%s' % ('\n'.join(BOOT_VALIDATION_ARGS),),
required=False,
type=click.STRING)
@click.option('--app-boot-validation',
help='The method of boot validation for application. Choose from:\n%s' % ('\n'.join(BOOT_VALIDATION_ARGS),),
required=False,
type=click.STRING)
@click.option('--key-file',
help='The private (signing) key in PEM fomat.',
required=False,
type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False))
@click.option('--external-app',
help='Indicates that the FW upgrade is intended to be passed through '
'(not applied on the receiving device)',
type=click.BOOL, is_flag=True, default=False)
@click.option('--zigbee',
help='Create an image and distribution package for Zigbee DFU server.',
required=False,
type=click.BOOL)
@click.option('--zigbee-manufacturer-id',
help='Manufacturer ID to be used in Zigbee OTA header.',
required=False,
type=BASED_INT)
@click.option('--zigbee-image-type',
help='Image type to be used in Zigbee OTA header.',
required=False,
type=BASED_INT)
@click.option('--zigbee-comment',
help='Firmware comment to be used in Zigbee OTA header.',
required=False,
type=click.STRING)
@click.option('--zigbee-ota-hw-version',
help='The zigbee OTA hw version.',
required=False,
type=BASED_INT_OR_NONE)
@click.option('--zigbee-ota-fw-version',
help='The zigbee OTA fw version.',
required=False,
type=BASED_INT_OR_NONE)
def generate(zipfile,
debug_mode,
application,
application_version,
application_version_string,
bootloader,
bootloader_version,
hw_version,
sd_req,
sd_id,
softdevice,
sd_boot_validation,
app_boot_validation,
key_file,
external_app,
zigbee,
zigbee_manufacturer_id,
zigbee_image_type,
zigbee_comment,
zigbee_ota_hw_version,
zigbee_ota_fw_version):
"""
Generate a zip package for distribution to apps that support Nordic DFU OTA.
The application, bootloader, and SoftDevice files are converted to .bin if supplied as .hex files.
For more information on the generated package, see:
http://developer.nordicsemi.com/nRF5_SDK/doc/
The following combinations are supported by this command:
* BL only: Supported.
* SD only: Supported (SD of same Major Version).
* APP only: Supported (external or internal).
* BL + SD: Supported.
* BL + APP: Not supported (use two packages instead).
* BL + SD + APP: Supported.
* SD + APP: Supported (SD of same Major Version).
"""
zipfile_path = zipfile
# Check combinations
if bootloader is not None and application is not None and softdevice is None:
click.echo("Error: Invalid combination: use two .zip packages instead.")
return
if debug_mode is None:
debug_mode = False
# The user can specify the application version with two different
# formats. As an integer, e.g. 102130, or as a string
# "10.21.30". Internally we convert to integer.
if application_version_string:
application_version_internal = convert_version_string_to_int(application_version_string)
else:
application_version_internal = application_version
if application_version_internal == 'none':
application_version_internal = None
if bootloader_version == 'none':
bootloader_version = None
if hw_version == 'none':
hw_version = None
if external_app is None:
external_app = False
if zigbee_ota_hw_version == 'none':
zigbee_ota_hw_version = None
if zigbee_ota_fw_version == 'none':
zigbee_ota_fw_version = None
# Convert multiple value into a single instance
if len(sd_req) > 1:
click.echo("Please specify SoftDevice requirements as a comma-separated list: --sd-req 0xXXXX,0xYYYY,...")
return
elif len(sd_req) == 0:
sd_req = None
else:
sd_req = sd_req[0]
if sd_req == 'none':
sd_req = None
if len(sd_id) > 1:
click.echo("Please specify SoftDevice requirements as a comma-separated list: --sd-id 0xXXXX,0xYYYY,...")
return
elif len(sd_id) == 0:
sd_id = None
else:
sd_id = sd_id[0]
if sd_id == 'none':
sd_id = None
# Initial consistency checks
if application_version_internal is not None and application is None:
click.echo("Error: Application version with no image.")
return
if bootloader_version is not None and bootloader is None:
click.echo("Error: Bootloader version with no image.")
return
if debug_mode:
display_debug_warning()
# Default to no version checking
if application_version_internal is None:
application_version_internal=Package.DEFAULT_APP_VERSION
if bootloader_version is None:
bootloader_version=Package.DEFAULT_BL_VERSION
if hw_version is None:
hw_version=Package.DEFAULT_HW_VERSION
if sd_req is None:
# Use string as this will be mapped into an int below
sd_req=str(Package.DEFAULT_SD_REQ[0])
# Version checks
if hw_version is None:
click.echo("Error: --hw-version required.")
return
if sd_req is None and external_app is False:
click.echo("Error: --sd-req required.")
return
if application is not None and application_version_internal is None:
click.echo('Error: --application-version or --application-version-string'
' required with application image.')
return
if bootloader is not None and bootloader_version is None:
click.echo("Error: --bootloader-version required with bootloader image.")
return
# Zigbee only allows App, SoftDevice (minor), bootloader or Softdevice+bootloader
if zigbee:
if sum(bool(x) for x in [application, softdevice, bootloader]) != 1:
click.echo('Error: Provide either --application, --softdevice, or --bootloader'
' for Zigbee package generation (not a combination).')
if application is not None and softdevice is not None and sd_id is None:
click.echo("Error: --sd-id required with softdevice and application images.")
return
if application is None and external_app is True:
click.echo("Error: --external-app requires an application.")
return
if application is not None and softdevice is not None and external_app is True:
click.echo("Error: --external-app is only possible for application only DFU packages.")
return
if application is not None and bootloader is not None and external_app is True:
click.echo("Error: --external-app is only possible for application only DFU packages.")
return
if zigbee and zigbee_ota_hw_version is None:
click.echo("Error: --zigbee-ota-hw-version is required.")
return
if zigbee and zigbee_ota_fw_version is None:
zigbee_ota_fw_version = 0
sd_req_list = []
if sd_req is not None:
try:
# This will parse any string starting with 0x as base 16.
sd_req_list = sd_req.split(',')
sd_req_list = map(int_as_text_to_int, sd_req_list)
except ValueError:
raise NordicSemiException("Could not parse value for --sd-req. "
"Hex values should be prefixed with 0x.")
sd_id_list = []
if sd_id is not None:
try:
# This will parse any string starting with 0x as base 16.
sd_id_list = sd_id.split(',')
sd_id_list = map(int_as_text_to_int, sd_id_list)
# Copy all IDs from sd_id_list to sd_req_list, without duplicates.
# This ensures that the softdevice update can be repeated in case
# SD+(BL)+App update terminates during application update after the
# softdevice was already updated (with new ID). Such update would
# have to be repeated and the softdevice would have to be sent again,
# this time updating itself.
sd_req_list += set(sd_id_list) - set(sd_req_list)
except ValueError:
raise NordicSemiException("Could not parse value for --sd-id. "
"Hex values should be prefixed with 0x.")
else:
sd_id_list = sd_req_list
if key_file is None:
display_nokey_warning()
else:
signer = Signing()
default_key = signer.load_key(key_file)
if default_key:
display_sec_warning()
if sd_boot_validation and (sd_boot_validation not in BOOT_VALIDATION_ARGS):
click.echo("Error: --sd_boot_validation called with invalid argument. Must be one of:\n%s" % ("\n".join(BOOT_VALIDATION_ARGS)))
return
if app_boot_validation and (app_boot_validation not in BOOT_VALIDATION_ARGS):
click.echo("Error: --app_boot_validation called with invalid argument. Must be one of:\n%s" % ("\n".join(BOOT_VALIDATION_ARGS)))
return
if zigbee_comment is None:
zigbee_comment = ''
elif any(ord(char) > 127 for char in zigbee_comment): # Check if all the characters belong to the ASCII range
click.echo('Warning: Non-ASCII characters in the comment are not allowed. Discarding comment.')
zigbee_comment = ''
elif len(zigbee_comment) > 30:
click.echo('Warning: truncating the comment to 30 bytes.')
zigbee_comment = zigbee_comment[:30]
if zigbee_manufacturer_id is None:
zigbee_manufacturer_id = 0xFFFF
if zigbee_image_type is None:
zigbee_image_type = 0xFFFF
# Set the external_app to false in --zigbee is set
inner_external_app = external_app
if zigbee:
inner_external_app = False
# Generate a DFU package. If --zigbee is set this is the inner DFU package
# which will be used as a binary input to the outter DFU package
package = Package(debug_mode,
hw_version,
application_version_internal,
bootloader_version,
sd_req_list,
sd_id_list,
application,
bootloader,
softdevice,
sd_boot_validation,
app_boot_validation,
key_file,
inner_external_app,
zigbee,
zigbee_manufacturer_id,
zigbee_image_type,
zigbee_comment)
package.generate_package(zipfile_path)
if zigbee:
from shutil import copyfile
from os import remove
log_message = "Zigbee update created at {0}".format(package.zigbee_ota_file.filename)
click.echo(log_message)
# Taking the inner Zigbee package as input for the outer DFU package
binfile = package.zigbee_ota_file.filename.replace(".zigbee", ".bin")
copyfile(package.zigbee_ota_file.filename, binfile)
# Create the outer Zigbee DFU package.
package = Package(debug_mode,
zigbee_ota_hw_version,
zigbee_ota_fw_version,
None,
[0xFFFE],
[0xFFFE],
binfile,
None,
None,
None,
None,
key_file,
True)
package.generate_package(zipfile_path)
remove(binfile)
log_message = "Zip created at {0}".format(zipfile_path)
click.echo(log_message)
@pkg.command(short_help='Display the contents of a .zip package file.')
@click.argument('zip_file', required=True, type=click.Path())
def display(zip_file):
package = Package()
package.parse_package(zip_file, preserve_work_dir=True)
click.echo("{0}".format(str(package)))
global_bar = None
def update_progress(progress=0):
if global_bar:
global_bar.update(progress)
@cli.group(short_help='Perform a Device Firmware Update over serial, BLE, Thread, Zigbee or ANT transport given a DFU package (zip file).')
def dfu():
"""
This set of commands supports Device Firmware Upgrade procedures over both BLE and serial transports.
"""
pass
def do_serial(package, port, connect_delay, flow_control, packet_receipt_notification, baud_rate, serial_number, ping,
timeout):
if flow_control is None:
flow_control = DfuTransportSerial.DEFAULT_FLOW_CONTROL
if packet_receipt_notification is None:
packet_receipt_notification = DfuTransportSerial.DEFAULT_PRN
if baud_rate is None:
baud_rate = DfuTransportSerial.DEFAULT_BAUD_RATE
if ping is None:
ping = False
if port is None:
device_lister = DeviceLister()
device = device_lister.get_device(serial_number=serial_number)
if device is None:
raise NordicSemiException("A device with serial number %s is not connected." % serial_number)
port = device.get_first_available_com_port()
logger.info("Resolved serial number {} to port {}".format(serial_number, port))
if timeout is None:
timeout = DfuTransportSerial.DEFAULT_TIMEOUT
logger.info("Using board at serial port: {}".format(port))
serial_backend = DfuTransportSerial(com_port=str(port), baud_rate=baud_rate,
flow_control=flow_control, prn=packet_receipt_notification, do_ping=ping,
timeout=timeout)
serial_backend.register_events_callback(DfuEvent.PROGRESS_EVENT, update_progress)
dfu = Dfu(zip_file_path = package, dfu_transport = serial_backend, connect_delay = connect_delay)
if logger.getEffectiveLevel() > logging.INFO:
with click.progressbar(length=dfu.dfu_get_total_size()) as bar:
global global_bar
global_bar = bar
dfu.dfu_send_images()
else:
dfu.dfu_send_images()
click.echo("Device programmed.")
@dfu.command(short_help='Update the firmware on a device over a USB serial connection. The DFU '
'target must be a chip with USB pins (i.e. nRF52840) and provide a USB ACM '
'CDC serial interface.')
@click.option('-pkg', '--package',
help='Filename of the DFU package.',
type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False),
required=True)
@click.option('-p', '--port',
help='Serial port address to which the device is connected. (e.g. COM1 in windows systems, /dev/ttyACM0 in linux/mac)',
type=click.STRING,
cls = OptionRequiredIf)
@click.option('-cd', '--connect-delay',
help='Delay in seconds before each connection to the target device during DFU. Default is 3.',
type=click.INT,
required=False)
@click.option('-fc', '--flow-control',
help='To enable flow control set this flag to 1',
type=click.BOOL,
required=False)
@click.option('-prn', '--packet-receipt-notification',
help='Set the packet receipt notification value',
type=click.INT,
required=False)
@click.option('-b', '--baud-rate',
help='Set the baud rate',
type=click.INT,
required=False)
@click.option('-snr', '--serial-number',
help='Serial number of the device. Ignored if --port is set.',
type=click.STRING,
required=False)
@click.option('-t', '--timeout',
help='Set the timeout in seconds for board to respond (default: 30 seconds)',
type=click.INT,
required=False)
def usb_serial(package, port, connect_delay, flow_control, packet_receipt_notification, baud_rate, serial_number,
timeout):
"""Perform a Device Firmware Update on a device with a bootloader that supports USB serial DFU."""
do_serial(package, port, connect_delay, flow_control, packet_receipt_notification, baud_rate, serial_number, False,
timeout)