otatool.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. sys.path.append(PARTTOOL_DIR)
  81. import gen_esp32part as gen
  82. def is_otadata_info_valid(status):
  83. seq = status.seq % (1 << 32)
  84. crc = hex(binascii.crc32(struct.pack('I', seq), 0xFFFFFFFF) % (1 << 32))
  85. return seq < (int('0xFFFFFFFF', 16) % (1 << 32)) and status.crc == crc
  86. partition_table = self.target.partition_table
  87. ota_partitions = list()
  88. for i in range(gen.NUM_PARTITION_SUBTYPE_APP_OTA):
  89. ota_partition = filter(lambda p: p.subtype == (gen.MIN_PARTITION_SUBTYPE_APP_OTA + i), partition_table)
  90. try:
  91. ota_partitions.append(list(ota_partition)[0])
  92. except IndexError:
  93. break
  94. ota_partitions = sorted(ota_partitions, key=lambda p: p.subtype)
  95. if not ota_partitions:
  96. raise Exception('No ota app partitions found')
  97. # Look for the app partition to switch to
  98. ota_partition_next = None
  99. try:
  100. if isinstance(ota_id, int):
  101. ota_partition_next = filter(lambda p: p.subtype - gen.MIN_PARTITION_SUBTYPE_APP_OTA == ota_id, ota_partitions)
  102. else:
  103. ota_partition_next = filter(lambda p: p.name == ota_id, ota_partitions)
  104. ota_partition_next = list(ota_partition_next)[0]
  105. except IndexError:
  106. raise Exception('Partition to switch to not found')
  107. otadata_info = self._get_otadata_info()
  108. # Find the copy to base the computation for ota sequence number on
  109. otadata_compute_base = -1
  110. # Both are valid, take the max as computation base
  111. if is_otadata_info_valid(otadata_info[0]) and is_otadata_info_valid(otadata_info[1]):
  112. if otadata_info[0].seq >= otadata_info[1].seq:
  113. otadata_compute_base = 0
  114. else:
  115. otadata_compute_base = 1
  116. # Only one copy is valid, use that
  117. elif is_otadata_info_valid(otadata_info[0]):
  118. otadata_compute_base = 0
  119. elif is_otadata_info_valid(otadata_info[1]):
  120. otadata_compute_base = 1
  121. # Both are invalid (could be initial state - all 0xFF's)
  122. else:
  123. pass
  124. ota_seq_next = 0
  125. ota_partitions_num = len(ota_partitions)
  126. target_seq = (ota_partition_next.subtype & 0x0F) + 1
  127. # Find the next ota sequence number
  128. if otadata_compute_base == 0 or otadata_compute_base == 1:
  129. base_seq = otadata_info[otadata_compute_base].seq % (1 << 32)
  130. i = 0
  131. while base_seq > target_seq % ota_partitions_num + i * ota_partitions_num:
  132. i += 1
  133. ota_seq_next = target_seq % ota_partitions_num + i * ota_partitions_num
  134. else:
  135. ota_seq_next = target_seq
  136. # Create binary data from computed values
  137. ota_seq_next = struct.pack('I', ota_seq_next)
  138. ota_seq_crc_next = binascii.crc32(ota_seq_next, 0xFFFFFFFF) % (1 << 32)
  139. ota_seq_crc_next = struct.pack('I', ota_seq_crc_next)
  140. temp_file = tempfile.NamedTemporaryFile(delete=False)
  141. temp_file.close()
  142. try:
  143. with open(temp_file.name, 'wb') as otadata_next_file:
  144. start = (1 if otadata_compute_base == 0 else 0) * (self.spi_flash_sec_size >> 1)
  145. otadata_next_file.write(self.otadata)
  146. otadata_next_file.seek(start)
  147. otadata_next_file.write(ota_seq_next)
  148. otadata_next_file.seek(start + 28)
  149. otadata_next_file.write(ota_seq_crc_next)
  150. otadata_next_file.flush()
  151. self.target.write_partition(OtatoolTarget.OTADATA_PARTITION, temp_file.name)
  152. finally:
  153. os.unlink(temp_file.name)
  154. def read_ota_partition(self, ota_id, output):
  155. self.target.read_partition(self._get_partition_id_from_ota_id(ota_id), output)
  156. def write_ota_partition(self, ota_id, input):
  157. self.target.write_partition(self._get_partition_id_from_ota_id(ota_id), input)
  158. def erase_ota_partition(self, ota_id):
  159. self.target.erase_partition(self._get_partition_id_from_ota_id(ota_id))
  160. def _read_otadata(target):
  161. target._check_otadata_partition()
  162. otadata_info = target._get_otadata_info()
  163. print(' {:8s} \t {:8s} | \t {:8s} \t {:8s}'.format('OTA_SEQ', 'CRC', 'OTA_SEQ', 'CRC'))
  164. print('Firmware: 0x{:8x} \t0x{:8x} | \t0x{:8x} \t 0x{:8x}'.format(otadata_info[0].seq, otadata_info[0].crc,
  165. otadata_info[1].seq, otadata_info[1].crc))
  166. def _erase_otadata(target):
  167. target.erase_otadata()
  168. status('Erased ota_data partition contents')
  169. def _switch_ota_partition(target, ota_id):
  170. target.switch_ota_partition(ota_id)
  171. def _read_ota_partition(target, ota_id, output):
  172. target.read_ota_partition(ota_id, output)
  173. status('Read ota partition contents to file {}'.format(output))
  174. def _write_ota_partition(target, ota_id, input):
  175. target.write_ota_partition(ota_id, input)
  176. status('Written contents of file {} to ota partition'.format(input))
  177. def _erase_ota_partition(target, ota_id):
  178. target.erase_ota_partition(ota_id)
  179. status('Erased contents of ota partition')
  180. def main():
  181. if sys.version_info[0] < 3:
  182. print('WARNING: Support for Python 2 is deprecated and will be removed in future versions.', file=sys.stderr)
  183. elif sys.version_info[0] == 3 and sys.version_info[1] < 6:
  184. print('WARNING: Python 3 versions older than 3.6 are not supported.', file=sys.stderr)
  185. global quiet
  186. parser = argparse.ArgumentParser('ESP-IDF OTA Partitions Tool')
  187. parser.add_argument('--quiet', '-q', help='suppress stderr messages', action='store_true')
  188. parser.add_argument('--esptool-args', help='additional main arguments for esptool', nargs='+')
  189. parser.add_argument('--esptool-write-args', help='additional subcommand arguments for esptool write_flash', nargs='+')
  190. parser.add_argument('--esptool-read-args', help='additional subcommand arguments for esptool read_flash', nargs='+')
  191. parser.add_argument('--esptool-erase-args', help='additional subcommand arguments for esptool erase_region', nargs='+')
  192. # There are two possible sources for the partition table: a device attached to the host
  193. # or a partition table CSV/binary file. These sources are mutually exclusive.
  194. parser.add_argument('--port', '-p', help='port where the device to read the partition table from is attached')
  195. parser.add_argument('--baud', '-b', help='baudrate to use', type=int)
  196. parser.add_argument('--partition-table-offset', '-o', help='offset to read the partition table from', type=str)
  197. parser.add_argument('--partition-table-file', '-f', help='file (CSV/binary) to read the partition table from; \
  198. overrides device attached to specified port as the partition table source when defined')
  199. subparsers = parser.add_subparsers(dest='operation', help='run otatool -h for additional help')
  200. spi_flash_sec_size = argparse.ArgumentParser(add_help=False)
  201. spi_flash_sec_size.add_argument('--spi-flash-sec-size', help='value of SPI_FLASH_SEC_SIZE macro', type=str)
  202. # Specify the supported operations
  203. subparsers.add_parser('read_otadata', help='read otadata partition', parents=[spi_flash_sec_size])
  204. subparsers.add_parser('erase_otadata', help='erase otadata partition')
  205. slot_or_name_parser = argparse.ArgumentParser(add_help=False)
  206. slot_or_name_parser_args = slot_or_name_parser.add_mutually_exclusive_group()
  207. slot_or_name_parser_args.add_argument('--slot', help='slot number of the ota partition', type=int)
  208. slot_or_name_parser_args.add_argument('--name', help='name of the ota partition')
  209. subparsers.add_parser('switch_ota_partition', help='switch otadata partition', parents=[slot_or_name_parser, spi_flash_sec_size])
  210. read_ota_partition_subparser = subparsers.add_parser('read_ota_partition', help='read contents of an ota partition', parents=[slot_or_name_parser])
  211. read_ota_partition_subparser.add_argument('--output', help='file to write the contents of the ota partition to')
  212. write_ota_partition_subparser = subparsers.add_parser('write_ota_partition', help='write contents to an ota partition', parents=[slot_or_name_parser])
  213. write_ota_partition_subparser.add_argument('--input', help='file whose contents to write to the ota partition')
  214. subparsers.add_parser('erase_ota_partition', help='erase contents of an ota partition', parents=[slot_or_name_parser])
  215. args = parser.parse_args()
  216. quiet = args.quiet
  217. # No operation specified, display help and exit
  218. if args.operation is None:
  219. if not quiet:
  220. parser.print_help()
  221. sys.exit(1)
  222. target_args = {}
  223. if args.port:
  224. target_args['port'] = args.port
  225. if args.partition_table_file:
  226. target_args['partition_table_file'] = args.partition_table_file
  227. if args.partition_table_offset:
  228. target_args['partition_table_offset'] = int(args.partition_table_offset, 0)
  229. try:
  230. if args.spi_flash_sec_size:
  231. target_args['spi_flash_sec_size'] = int(args.spi_flash_sec_size, 0)
  232. except AttributeError:
  233. pass
  234. if args.esptool_args:
  235. target_args['esptool_args'] = args.esptool_args
  236. if args.esptool_write_args:
  237. target_args['esptool_write_args'] = args.esptool_write_args
  238. if args.esptool_read_args:
  239. target_args['esptool_read_args'] = args.esptool_read_args
  240. if args.esptool_erase_args:
  241. target_args['esptool_erase_args'] = args.esptool_erase_args
  242. if args.baud:
  243. target_args['baud'] = args.baud
  244. target = OtatoolTarget(**target_args)
  245. # Create the operation table and execute the operation
  246. common_args = {'target':target}
  247. ota_id = []
  248. try:
  249. if args.name is not None:
  250. ota_id = ['name']
  251. else:
  252. if args.slot is not None:
  253. ota_id = ['slot']
  254. except AttributeError:
  255. pass
  256. otatool_ops = {
  257. 'read_otadata':(_read_otadata, []),
  258. 'erase_otadata':(_erase_otadata, []),
  259. 'switch_ota_partition':(_switch_ota_partition, ota_id),
  260. 'read_ota_partition':(_read_ota_partition, ['output'] + ota_id),
  261. 'write_ota_partition':(_write_ota_partition, ['input'] + ota_id),
  262. 'erase_ota_partition':(_erase_ota_partition, ota_id)
  263. }
  264. (op, op_args) = otatool_ops[args.operation]
  265. for op_arg in op_args:
  266. common_args.update({op_arg:vars(args)[op_arg]})
  267. try:
  268. common_args['ota_id'] = common_args.pop('name')
  269. except KeyError:
  270. try:
  271. common_args['ota_id'] = common_args.pop('slot')
  272. except KeyError:
  273. pass
  274. if quiet:
  275. # If exceptions occur, suppress and exit quietly
  276. try:
  277. op(**common_args)
  278. except Exception:
  279. sys.exit(2)
  280. else:
  281. op(**common_args)
  282. if __name__ == '__main__':
  283. main()