otatool.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. #!/usr/bin/env python
  2. #
  3. # otatool is used to perform ota-level operations - flashing ota partition
  4. # erasing ota partition and switching ota partition
  5. #
  6. # Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http:#www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. from __future__ import division, print_function
  20. import argparse
  21. import binascii
  22. import collections
  23. import os
  24. import struct
  25. import sys
  26. import tempfile
  27. try:
  28. from parttool import PARTITION_TABLE_OFFSET, PartitionName, PartitionType, ParttoolTarget
  29. except ImportError:
  30. COMPONENTS_PATH = os.path.expandvars(os.path.join('$IDF_PATH', 'components'))
  31. PARTTOOL_DIR = os.path.join(COMPONENTS_PATH, 'partition_table')
  32. sys.path.append(PARTTOOL_DIR)
  33. from parttool import PARTITION_TABLE_OFFSET, PartitionName, PartitionType, ParttoolTarget
  34. __version__ = '2.0'
  35. SPI_FLASH_SEC_SIZE = 0x2000
  36. quiet = False
  37. def status(msg):
  38. if not quiet:
  39. print(msg)
  40. class OtatoolTarget():
  41. OTADATA_PARTITION = PartitionType('data', 'ota')
  42. def __init__(self, port=None, baud=None, partition_table_offset=PARTITION_TABLE_OFFSET, partition_table_file=None,
  43. spi_flash_sec_size=SPI_FLASH_SEC_SIZE, esptool_args=[], esptool_write_args=[],
  44. esptool_read_args=[], esptool_erase_args=[]):
  45. self.target = ParttoolTarget(port, baud, partition_table_offset, partition_table_file, esptool_args,
  46. esptool_write_args, esptool_read_args, esptool_erase_args)
  47. self.spi_flash_sec_size = spi_flash_sec_size
  48. temp_file = tempfile.NamedTemporaryFile(delete=False)
  49. temp_file.close()
  50. try:
  51. self.target.read_partition(OtatoolTarget.OTADATA_PARTITION, temp_file.name)
  52. with open(temp_file.name, 'rb') as f:
  53. self.otadata = f.read()
  54. finally:
  55. os.unlink(temp_file.name)
  56. def _check_otadata_partition(self):
  57. if not self.otadata:
  58. raise Exception('No otadata partition found')
  59. def erase_otadata(self):
  60. self._check_otadata_partition()
  61. self.target.erase_partition(OtatoolTarget.OTADATA_PARTITION)
  62. def _get_otadata_info(self):
  63. info = []
  64. otadata_info = collections.namedtuple('otadata_info', 'seq crc')
  65. for i in range(2):
  66. start = i * (self.spi_flash_sec_size >> 1)
  67. seq = bytearray(self.otadata[start:start + 4])
  68. crc = bytearray(self.otadata[start + 28:start + 32])
  69. seq = struct.unpack('I', seq)
  70. crc = struct.unpack('I', crc)
  71. info.append(otadata_info(seq[0], crc[0]))
  72. return info
  73. def _get_partition_id_from_ota_id(self, ota_id):
  74. if isinstance(ota_id, int):
  75. return PartitionType('app', 'ota_' + str(ota_id))
  76. else:
  77. return PartitionName(ota_id)
  78. def switch_ota_partition(self, ota_id):
  79. self._check_otadata_partition()
  80. import gen_esp32part as gen
  81. def is_otadata_info_valid(status):
  82. seq = status.seq % (1 << 32)
  83. crc = binascii.crc32(struct.pack('I', seq), 0xFFFFFFFF) % (1 << 32)
  84. return seq < (int('0xFFFFFFFF', 16) % (1 << 32)) and status.crc == crc
  85. partition_table = self.target.partition_table
  86. ota_partitions = list()
  87. for i in range(gen.NUM_PARTITION_SUBTYPE_APP_OTA):
  88. ota_partition = filter(lambda p: p.subtype == (gen.MIN_PARTITION_SUBTYPE_APP_OTA + i), partition_table)
  89. try:
  90. ota_partitions.append(list(ota_partition)[0])
  91. except IndexError:
  92. break
  93. ota_partitions = sorted(ota_partitions, key=lambda p: p.subtype)
  94. if not ota_partitions:
  95. raise Exception('No ota app partitions found')
  96. # Look for the app partition to switch to
  97. ota_partition_next = None
  98. try:
  99. if isinstance(ota_id, int):
  100. ota_partition_next = filter(lambda p: p.subtype - gen.MIN_PARTITION_SUBTYPE_APP_OTA == ota_id, ota_partitions)
  101. else:
  102. ota_partition_next = filter(lambda p: p.name == ota_id, ota_partitions)
  103. ota_partition_next = list(ota_partition_next)[0]
  104. except IndexError:
  105. raise Exception('Partition to switch to not found')
  106. otadata_info = self._get_otadata_info()
  107. # Find the copy to base the computation for ota sequence number on
  108. otadata_compute_base = -1
  109. # Both are valid, take the max as computation base
  110. if is_otadata_info_valid(otadata_info[0]) and is_otadata_info_valid(otadata_info[1]):
  111. if otadata_info[0].seq >= otadata_info[1].seq:
  112. otadata_compute_base = 0
  113. else:
  114. otadata_compute_base = 1
  115. # Only one copy is valid, use that
  116. elif is_otadata_info_valid(otadata_info[0]):
  117. otadata_compute_base = 0
  118. elif is_otadata_info_valid(otadata_info[1]):
  119. otadata_compute_base = 1
  120. # Both are invalid (could be initial state - all 0xFF's)
  121. else:
  122. pass
  123. ota_seq_next = 0
  124. ota_partitions_num = len(ota_partitions)
  125. target_seq = (ota_partition_next.subtype & 0x0F) + 1
  126. # Find the next ota sequence number
  127. if otadata_compute_base == 0 or otadata_compute_base == 1:
  128. base_seq = otadata_info[otadata_compute_base].seq % (1 << 32)
  129. i = 0
  130. while base_seq > target_seq % ota_partitions_num + i * ota_partitions_num:
  131. i += 1
  132. ota_seq_next = target_seq % ota_partitions_num + i * ota_partitions_num
  133. else:
  134. ota_seq_next = target_seq
  135. # Create binary data from computed values
  136. ota_seq_next = struct.pack('I', ota_seq_next)
  137. ota_seq_crc_next = binascii.crc32(ota_seq_next, 0xFFFFFFFF) % (1 << 32)
  138. ota_seq_crc_next = struct.pack('I', ota_seq_crc_next)
  139. temp_file = tempfile.NamedTemporaryFile(delete=False)
  140. temp_file.close()
  141. try:
  142. with open(temp_file.name, 'wb') as otadata_next_file:
  143. start = (1 if otadata_compute_base == 0 else 0) * (self.spi_flash_sec_size >> 1)
  144. otadata_next_file.write(self.otadata)
  145. otadata_next_file.seek(start)
  146. otadata_next_file.write(ota_seq_next)
  147. otadata_next_file.seek(start + 28)
  148. otadata_next_file.write(ota_seq_crc_next)
  149. otadata_next_file.flush()
  150. self.target.write_partition(OtatoolTarget.OTADATA_PARTITION, temp_file.name)
  151. finally:
  152. os.unlink(temp_file.name)
  153. def read_ota_partition(self, ota_id, output):
  154. self.target.read_partition(self._get_partition_id_from_ota_id(ota_id), output)
  155. def write_ota_partition(self, ota_id, input):
  156. self.target.write_partition(self._get_partition_id_from_ota_id(ota_id), input)
  157. def erase_ota_partition(self, ota_id):
  158. self.target.erase_partition(self._get_partition_id_from_ota_id(ota_id))
  159. def _read_otadata(target):
  160. target._check_otadata_partition()
  161. otadata_info = target._get_otadata_info()
  162. print(' {:8s} \t {:8s} | \t {:8s} \t {:8s}'.format('OTA_SEQ', 'CRC', 'OTA_SEQ', 'CRC'))
  163. print('Firmware: 0x{:08x} \t0x{:08x} | \t0x{:08x} \t 0x{:08x}'.format(otadata_info[0].seq, otadata_info[0].crc,
  164. otadata_info[1].seq, otadata_info[1].crc))
  165. def _erase_otadata(target):
  166. target.erase_otadata()
  167. status('Erased ota_data partition contents')
  168. def _switch_ota_partition(target, ota_id):
  169. target.switch_ota_partition(ota_id)
  170. def _read_ota_partition(target, ota_id, output):
  171. target.read_ota_partition(ota_id, output)
  172. status('Read ota partition contents to file {}'.format(output))
  173. def _write_ota_partition(target, ota_id, input):
  174. target.write_ota_partition(ota_id, input)
  175. status('Written contents of file {} to ota partition'.format(input))
  176. def _erase_ota_partition(target, ota_id):
  177. target.erase_ota_partition(ota_id)
  178. status('Erased contents of ota partition')
  179. def main():
  180. if sys.version_info[0] < 3:
  181. print('WARNING: Support for Python 2 is deprecated and will be removed in future versions.', file=sys.stderr)
  182. elif sys.version_info[0] == 3 and sys.version_info[1] < 6:
  183. print('WARNING: Python 3 versions older than 3.6 are not supported.', file=sys.stderr)
  184. global quiet
  185. parser = argparse.ArgumentParser('ESP-IDF OTA Partitions Tool')
  186. parser.add_argument('--quiet', '-q', help='suppress stderr messages', action='store_true')
  187. parser.add_argument('--esptool-args', help='additional main arguments for esptool', nargs='+')
  188. parser.add_argument('--esptool-write-args', help='additional subcommand arguments for esptool write_flash', nargs='+')
  189. parser.add_argument('--esptool-read-args', help='additional subcommand arguments for esptool read_flash', nargs='+')
  190. parser.add_argument('--esptool-erase-args', help='additional subcommand arguments for esptool erase_region', nargs='+')
  191. # There are two possible sources for the partition table: a device attached to the host
  192. # or a partition table CSV/binary file. These sources are mutually exclusive.
  193. parser.add_argument('--port', '-p', help='port where the device to read the partition table from is attached')
  194. parser.add_argument('--baud', '-b', help='baudrate to use', type=int)
  195. parser.add_argument('--partition-table-offset', '-o', help='offset to read the partition table from', type=str)
  196. parser.add_argument('--partition-table-file', '-f', help='file (CSV/binary) to read the partition table from; \
  197. overrides device attached to specified port as the partition table source when defined')
  198. subparsers = parser.add_subparsers(dest='operation', help='run otatool -h for additional help')
  199. spi_flash_sec_size = argparse.ArgumentParser(add_help=False)
  200. spi_flash_sec_size.add_argument('--spi-flash-sec-size', help='value of SPI_FLASH_SEC_SIZE macro', type=str)
  201. # Specify the supported operations
  202. subparsers.add_parser('read_otadata', help='read otadata partition', parents=[spi_flash_sec_size])
  203. subparsers.add_parser('erase_otadata', help='erase otadata partition')
  204. slot_or_name_parser = argparse.ArgumentParser(add_help=False)
  205. slot_or_name_parser_args = slot_or_name_parser.add_mutually_exclusive_group()
  206. slot_or_name_parser_args.add_argument('--slot', help='slot number of the ota partition', type=int)
  207. slot_or_name_parser_args.add_argument('--name', help='name of the ota partition')
  208. subparsers.add_parser('switch_ota_partition', help='switch otadata partition', parents=[slot_or_name_parser, spi_flash_sec_size])
  209. read_ota_partition_subparser = subparsers.add_parser('read_ota_partition', help='read contents of an ota partition', parents=[slot_or_name_parser])
  210. read_ota_partition_subparser.add_argument('--output', help='file to write the contents of the ota partition to', required=True)
  211. write_ota_partition_subparser = subparsers.add_parser('write_ota_partition', help='write contents to an ota partition', parents=[slot_or_name_parser])
  212. write_ota_partition_subparser.add_argument('--input', help='file whose contents to write to the ota partition')
  213. subparsers.add_parser('erase_ota_partition', help='erase contents of an ota partition', parents=[slot_or_name_parser])
  214. args = parser.parse_args()
  215. quiet = args.quiet
  216. # No operation specified, display help and exit
  217. if args.operation is None:
  218. if not quiet:
  219. parser.print_help()
  220. sys.exit(1)
  221. target_args = {}
  222. if args.port:
  223. target_args['port'] = args.port
  224. if args.partition_table_file:
  225. target_args['partition_table_file'] = args.partition_table_file
  226. if args.partition_table_offset:
  227. target_args['partition_table_offset'] = int(args.partition_table_offset, 0)
  228. try:
  229. if args.spi_flash_sec_size:
  230. target_args['spi_flash_sec_size'] = int(args.spi_flash_sec_size, 0)
  231. except AttributeError:
  232. pass
  233. if args.esptool_args:
  234. target_args['esptool_args'] = args.esptool_args
  235. if args.esptool_write_args:
  236. target_args['esptool_write_args'] = args.esptool_write_args
  237. if args.esptool_read_args:
  238. target_args['esptool_read_args'] = args.esptool_read_args
  239. if args.esptool_erase_args:
  240. target_args['esptool_erase_args'] = args.esptool_erase_args
  241. if args.baud:
  242. target_args['baud'] = args.baud
  243. target = OtatoolTarget(**target_args)
  244. # Create the operation table and execute the operation
  245. common_args = {'target':target}
  246. ota_id = []
  247. try:
  248. if args.name is not None:
  249. ota_id = ['name']
  250. else:
  251. if args.slot is not None:
  252. ota_id = ['slot']
  253. except AttributeError:
  254. pass
  255. otatool_ops = {
  256. 'read_otadata':(_read_otadata, []),
  257. 'erase_otadata':(_erase_otadata, []),
  258. 'switch_ota_partition':(_switch_ota_partition, ota_id),
  259. 'read_ota_partition':(_read_ota_partition, ['output'] + ota_id),
  260. 'write_ota_partition':(_write_ota_partition, ['input'] + ota_id),
  261. 'erase_ota_partition':(_erase_ota_partition, ota_id)
  262. }
  263. (op, op_args) = otatool_ops[args.operation]
  264. for op_arg in op_args:
  265. common_args.update({op_arg:vars(args)[op_arg]})
  266. try:
  267. common_args['ota_id'] = common_args.pop('name')
  268. except KeyError:
  269. try:
  270. common_args['ota_id'] = common_args.pop('slot')
  271. except KeyError:
  272. pass
  273. if quiet:
  274. # If exceptions occur, suppress and exit quietly
  275. try:
  276. op(**common_args)
  277. except Exception:
  278. sys.exit(2)
  279. else:
  280. op(**common_args)
  281. if __name__ == '__main__':
  282. main()