__main__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # Copyright (c) 2015, Nordic Semiconductor
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are met:
  6. #
  7. # * Redistributions of source code must retain the above copyright notice, this
  8. # list of conditions and the following disclaimer.
  9. #
  10. # * Redistributions in binary form must reproduce the above copyright notice,
  11. # this list of conditions and the following disclaimer in the documentation
  12. # and/or other materials provided with the distribution.
  13. #
  14. # * Neither the name of Nordic Semiconductor ASA nor the names of its
  15. # contributors may be used to endorse or promote products derived from
  16. # this software without specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  19. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  22. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  24. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  26. # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. """nrfutil command line tool."""
  29. import logging
  30. import os
  31. import click
  32. import sys
  33. import traceback
  34. from nordicsemi.dfu.dfu import Dfu
  35. from nordicsemi.dfu.dfu_transport import DfuEvent
  36. from nordicsemi.dfu.dfu_transport_serial import DfuTransportSerial
  37. from nordicsemi.dfu.dfu_transport_mesh import DfuTransportMesh
  38. from nordicsemi.dfu.package import Package
  39. from nordicsemi import version as nrfutil_version
  40. from nordicsemi.dfu.signing import Signing
  41. from nordicsemi.dfu.util import query_func
  42. class nRFException(Exception):
  43. pass
  44. def int_as_text_to_int(value):
  45. try:
  46. if value[:2].lower() == '0x':
  47. return int(value[2:], 16)
  48. elif value[:1] == '0':
  49. return int(value, 8)
  50. return int(value, 10)
  51. except ValueError:
  52. raise nRFException('%s is not a valid integer' % value)
  53. class BasedIntOrNoneParamType(click.ParamType):
  54. name = 'Int or None'
  55. def convert(self, value, param, ctx):
  56. try:
  57. if value.lower() == 'none':
  58. return 'none'
  59. return int_as_text_to_int(value)
  60. except nRFException:
  61. self.fail('%s is not a valid integer' % value, param, ctx)
  62. BASED_INT_OR_NONE = BasedIntOrNoneParamType()
  63. class TextOrNoneParamType(click.ParamType):
  64. name = 'Text or None'
  65. def convert(self, value, param, ctx):
  66. return value
  67. TEXT_OR_NONE = TextOrNoneParamType()
  68. @click.group()
  69. @click.option('--verbose',
  70. help='Show verbose information',
  71. is_flag=True)
  72. def cli(verbose):
  73. if verbose:
  74. logging.basicConfig(format='%(message)s', level=logging.INFO)
  75. else:
  76. logging.basicConfig(format='%(message)s')
  77. @cli.command()
  78. def version():
  79. """Displays nrf utility version."""
  80. click.echo("nrfutil version {}".format(nrfutil_version.NRFUTIL_VERSION))
  81. @cli.command(short_help='Generate keys for signing or generate public keys')
  82. @click.argument('key_file', required=True)
  83. @click.option('--gen-key',
  84. help='generate signing key and store at given path (pem-file)',
  85. type=click.BOOL,
  86. is_flag=True)
  87. @click.option('--show-vk',
  88. help='Show the verification keys for DFU Signing (hex|code|pem)',
  89. type=click.STRING)
  90. def keys(key_file,
  91. gen_key,
  92. show_vk):
  93. """
  94. This set of commands support creation of signing key (private) and showing the verification key (public)
  95. from a previously loaded signing key. Signing key is stored in PEM format
  96. """
  97. if not gen_key and show_vk is None:
  98. raise nRFException("Use either gen-key or show-vk.")
  99. signer = Signing()
  100. if gen_key:
  101. if os.path.exists(key_file):
  102. if not query_func("File found at %s. Do you want to overwrite the file?" % key_file):
  103. click.echo('Key generation aborted')
  104. return
  105. signer.gen_key(key_file)
  106. click.echo("Generated key at: %s" % key_file)
  107. elif show_vk:
  108. if not os.path.isfile(key_file):
  109. raise nRFException("No key file to load at: %s" % key_file)
  110. signer.load_key(key_file)
  111. click.echo(signer.get_vk(show_vk))
  112. @cli.group()
  113. def dfu():
  114. """
  115. This set of commands support Nordic DFU OTA package generation for distribution to
  116. applications and serial DFU.
  117. """
  118. pass
  119. @dfu.command(short_help='Generate a package for distribution to Apps supporting Nordic DFU OTA')
  120. @click.argument('zipfile',
  121. required=True,
  122. type=click.Path())
  123. @click.option('--application',
  124. help='The application firmware file',
  125. type=click.STRING)
  126. @click.option('--company-id',
  127. help='Company ID for mesh-application. Must either be a Bluetooth SIG assigned company ID '
  128. '(see https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers '
  129. 'for more information), or a random number between 65535 and 4294967295. If a random number '
  130. 'is chosen, it is recommended to not use the \"lazy\" approach of selecting an easy number, '
  131. 'as this increases the risk of namespace collisions for the app-IDs. It is also recommended to '
  132. 'use the same company-ID for all your applications.',
  133. type=BASED_INT_OR_NONE)
  134. @click.option('--application-id',
  135. help='Mesh application ID, default: 0x0000',
  136. type=BASED_INT_OR_NONE,
  137. default=str(Package.DEFAULT_MESH_APP_ID))
  138. @click.option('--application-version',
  139. help='Application version, default: 0xFFFFFFFF',
  140. type=BASED_INT_OR_NONE,
  141. default=str(Package.DEFAULT_APP_VERSION))
  142. @click.option('--bootloader-id',
  143. help='Mesh bootloader id, default: 0xFF00',
  144. type=BASED_INT_OR_NONE,
  145. default=str(Package.DEFAULT_MESH_BOOTLOADER_ID))
  146. @click.option('--bootloader',
  147. help='The bootloader firmware file',
  148. type=click.STRING)
  149. @click.option('--dev-revision',
  150. help='Device revision, default: 0xFFFF',
  151. type=BASED_INT_OR_NONE,
  152. default=str(Package.DEFAULT_DEV_REV))
  153. @click.option('--dev-type',
  154. help='Device type, default: 0xFFFF',
  155. type=BASED_INT_OR_NONE,
  156. default=str(Package.DEFAULT_DEV_TYPE))
  157. @click.option('--dfu-ver',
  158. help='DFU packet version to use, default: 0.5',
  159. type=click.FLOAT,
  160. default=Package.DEFAULT_DFU_VER)
  161. @click.option('--sd-req',
  162. help='SoftDevice requirement. A list of SoftDevice versions (1 or more)'
  163. 'of which one is required to be present on the target device.'
  164. 'Example: --sd-req 0x4F,0x5A. Default: 0xFFFE.',
  165. type=TEXT_OR_NONE,
  166. default=str(Package.DEFAULT_SD_REQ[0]))
  167. @click.option('--softdevice',
  168. help='The SoftDevice firmware file',
  169. type=click.STRING)
  170. @click.option('--key-file',
  171. help='Signing key (pem fomat)',
  172. type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False))
  173. @click.option('--mesh',
  174. help='Generate a package targeting Mesh-DFU',
  175. type=click.BOOL,
  176. is_flag=True)
  177. def genpkg(zipfile,
  178. application,
  179. company_id,
  180. application_id,
  181. application_version,
  182. bootloader_id,
  183. bootloader,
  184. dev_revision,
  185. dev_type,
  186. dfu_ver,
  187. sd_req,
  188. softdevice,
  189. key_file,
  190. mesh):
  191. """
  192. Generate a zipfile package for distribution to Apps supporting Nordic DFU OTA.
  193. The application, bootloader and softdevice files are converted to .bin if it is a .hex file.
  194. For more information on the generated init packet see:
  195. http://developer.nordicsemi.com/nRF51_SDK/doc/7.2.0/s110/html/a00065.html
  196. """
  197. zipfile_path = zipfile
  198. if company_id == 'none':
  199. company_id = None
  200. if application_id == 'none':
  201. application_id = None
  202. if application_version == 'none':
  203. application_version = None
  204. if dev_revision == 'none':
  205. dev_revision = None
  206. if dev_type == 'none':
  207. dev_type = None
  208. if bootloader_id == 'none':
  209. bootloader_id = None
  210. sd_req_list = None
  211. if sd_req.lower() == 'none':
  212. sd_req_list = []
  213. elif sd_req:
  214. try:
  215. # This will parse any string starting with 0x as base 16.
  216. sd_req_list = sd_req.split(',')
  217. sd_req_list = map(int_as_text_to_int, sd_req_list)
  218. except ValueError:
  219. raise nRFException("Could not parse value for --sd-req. "
  220. "Hex values should be prefixed with 0x.")
  221. if key_file and dfu_ver < 0.8:
  222. click.echo("Key file was given, setting DFU version to 0.8")
  223. package = Package(dev_type,
  224. dev_revision,
  225. company_id,
  226. application_id,
  227. application_version,
  228. bootloader_id,
  229. sd_req_list,
  230. application,
  231. bootloader,
  232. softdevice,
  233. dfu_ver,
  234. key_file,
  235. mesh)
  236. package.generate_package(zipfile_path)
  237. log_message = "Zip created at {0}".format(zipfile_path)
  238. click.echo(log_message)
  239. global_bar = None
  240. def update_progress(progress=0, done=False, log_message=""):
  241. del done, log_message # Unused parameters
  242. if global_bar:
  243. global_bar.update(max(1, progress))
  244. @dfu.command(short_help="Program a device with bootloader that support serial DFU")
  245. @click.option('-pkg', '--package',
  246. help='DFU package filename',
  247. type=click.Path(exists=True, resolve_path=True, file_okay=True, dir_okay=False),
  248. required=True)
  249. @click.option('-p', '--port',
  250. help='Serial port COM Port to which the device is connected',
  251. type=click.STRING,
  252. required=True)
  253. @click.option('-b', '--baudrate',
  254. help='Desired baud rate 38400/96000/115200/230400/250000/460800/921600/1000000 (default: 38400). '
  255. 'Note: Physical serial ports (e.g. COM1) typically do not support baud rates > 115200',
  256. type=click.INT,
  257. default=DfuTransportSerial.DEFAULT_BAUD_RATE)
  258. @click.option('-fc', '--flowcontrol',
  259. help='Enable flow control, default: disabled',
  260. type=click.BOOL,
  261. is_flag=True)
  262. @click.option('-i', '--interval',
  263. help='Desired interval between data packets in milliseconds. Default: 500. Only applies to Mesh-DFU. '
  264. 'Note: It is recommended to keep the interval above 200ms to avoid buffer overflow, and below '
  265. '2 seconds to avoid timeout.',
  266. type=click.INT,
  267. default=1000 * DfuTransportMesh.SEND_DATA_PACKET_WAIT_TIME)
  268. @click.option('-m', '--mesh',
  269. help='Use mesh serial mode',
  270. type=click.BOOL,
  271. is_flag=True)
  272. def serial(package, port, baudrate, flowcontrol, interval, mesh):
  273. """Program a device with bootloader that support serial DFU"""
  274. if mesh:
  275. serial_backend = DfuTransportMesh(port, baudrate, flowcontrol, interval=interval / 1000.0)
  276. serial_backend.register_events_callback(DfuEvent.PROGRESS_EVENT, update_progress)
  277. else:
  278. serial_backend = DfuTransportSerial(port, baudrate, flowcontrol)
  279. serial_backend.register_events_callback(DfuEvent.PROGRESS_EVENT, update_progress)
  280. dfu = Dfu(package, dfu_transport=serial_backend)
  281. click.echo("Upgrading target on {1} with DFU package {0}. Flow control is {2}."
  282. .format(package, port, "enabled" if flowcontrol else "disabled"))
  283. try:
  284. with click.progressbar(length=100) as bar:
  285. global global_bar
  286. global_bar = bar
  287. dfu.dfu_send_images()
  288. except Exception as e:
  289. click.echo("")
  290. click.echo("Failed to upgrade target. Error is: {0}".format(e.message))
  291. click.echo("")
  292. click.echo("Possible causes:")
  293. click.echo("- bootloader, SoftDevice or application on target "
  294. "does not match the requirements in the DFU package.")
  295. click.echo("- baud rate or flow control is not the same as in the target bootloader.")
  296. click.echo("- target is not in DFU mode. If using the SDK examples, "
  297. "press Button 4 and RESET and release both to enter DFU mode.")
  298. click.echo("- if the error is ERROR_BUSY at the beginning of the DFU process,"
  299. "increase the value of PAGE_ERASE_TIME_MAX by few milliseconds. ")
  300. #click.echo("Trace:\r\n{0}".format(traceback.print_exc()))
  301. exit(-1)
  302. finally:
  303. serial_backend.close()
  304. click.echo("Device programmed.")
  305. exit(0)
  306. if __name__ == '__main__':
  307. cli()