Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / scripts / flashing / nrfconnect_firmware_utils.py
1 #!/usr/bin/env python3
2 # Copyright (c) 2020-2021 Project CHIP Authors
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 """Flash an NRF5 device.
16
17 This is layered so that a caller can perform individual operations
18 through an `Flasher` instance, or operations according to a command line.
19 For `Flasher`, see the class documentation. For the parse_command()
20 interface or standalone execution:
21
22 usage: nrfconnect_firmware_utils.py [-h] [--verbose] [--erase]
23                                     [--application FILE]
24                                     [--verify_application] [--reset]
25                                     [--skip_reset] [--nrfjprog FILE]
26                                     [--snr SERIAL] [--family FAMILY]
27
28 Flash NRF5 device
29
30 optional arguments:
31   -h, --help            show this help message and exit
32
33 configuration:
34   --verbose, -v         Report more verbosely
35   --nrfjprog FILE       File name of the nrfjprog executable
36   --snr SERIAL, --serial SERIAL, -s SERIAL
37                         Serial number of device to flash
38   --family FAMILY       NRF5 device family
39
40 operations:
41   --erase               Erase device
42   --application FILE    Flash an image
43   --verify_application, --verify-application
44                         Verify the image after flashing
45   --reset               Reset device after flashing
46   --skip_reset, --skip-reset
47                         Do not reset device after flashing
48 """
49
50 import errno
51 import os
52 import sys
53
54 import firmware_utils
55
56 # Additional options that can be use to configure an `Flasher`
57 # object (as dictionary keys) and/or passed as command line options.
58 NRF5_OPTIONS = {
59     # Configuration options define properties used in flashing operations.
60     'configuration': {
61         # Tool configuration options.
62         'nrfjprog': {
63             'help': 'File name of the nrfjprog executable',
64             'default': 'nrfjprog',
65             'argparse': {
66                 'metavar': 'FILE'
67             },
68             'command': [
69                 '{nrfjprog}',
70                 {'optional': 'family'},
71                 {'optional': 'snr'},
72                 ()
73             ],
74             'verify': ['{nrfjprog}', '--version'],
75             'error':
76                 """\
77                 Unable to execute {nrfjprog}.
78
79                 Please ensure that this tool is installed and
80                 available. See the NRF5 example README for
81                 installation instructions.
82
83                 """,
84         },
85         'snr': {
86             'help': 'Serial number of device to flash',
87             'default': None,
88             'alias': ['--serial', '-s'],
89             'argparse': {
90                 'metavar': 'SERIAL'
91             },
92         },
93
94         # Device configuration options.
95         'family': {
96             'help': 'NRF5 device family',
97             'default': None,
98             'argparse': {
99                 'metavar': 'FAMILY'
100             },
101         },
102     },
103 }
104
105
106 class Flasher(firmware_utils.Flasher):
107     """Manage nrf5 flashing."""
108
109     def __init__(self, **options):
110         super().__init__(platform='NRF5', module=__name__, **options)
111         self.define_options(NRF5_OPTIONS)
112
113     def erase(self):
114         """Perform nrfjprog --eraseall"""
115         return self.run_tool('nrfjprog', ['--eraseall'], name='Erase all')
116
117     def verify(self, image):
118         """Verify image."""
119         return self.run_tool('nrfjprog',
120                              ['--quiet', '--verify', image],
121                              name='Verify',
122                              pass_message='Verified',
123                              fail_message='Not verified',
124                              fail_level=2)
125
126     def flash(self, image):
127         """Flash image."""
128         return self.run_tool('nrfjprog',
129                              ['--program', image, '--sectoranduicrerase'],
130                              name='Flash')
131
132     def reset(self):
133         """Reset the device."""
134         return self.run_tool('nrfjprog', ['--pinresetenable'], name='Enable pin reset')
135         return self.run_tool('nrfjprog', ['--pinreset'], name='Apply pin reset')
136
137     def actions(self):
138         """Perform actions on the device according to self.option."""
139         self.log(3, 'Options:', self.option)
140
141         if self.option.erase:
142             if self.erase().err:
143                 return self
144
145         application = self.optional_file(self.option.application)
146         if application:
147             if self.flash(application).err:
148                 return self
149             if self.option.verify_application:
150                 if self.verify(application).err:
151                     return self
152             if self.option.reset is None:
153                 self.option.reset = True
154
155         if self.option.reset:
156             if self.reset().err:
157                 return self
158
159         return self
160
161 ### Mobly integration
162 class Nrf5Platform:
163   def __init__(self, flasher_args):
164       self.flasher = Flasher(**flasher_args)
165
166   def flash(self):
167       self.flasher.flash_command([os.getcwd()])
168
169 def verify_platform_args(platform_args):
170     required_args = ['application']
171     for r in required_args:
172         if not r in platform_args:
173             raise ValueError("Required argument %s missing" % r)
174
175 def create_platform(platform_args):
176     verify_platform_args(platform_args[0])
177     return Nrf5Platform(platform_args[0])
178
179 ### End of Mobly integration
180
181 if __name__ == '__main__':
182     sys.exit(Flasher().flash_command(sys.argv))