def main(): COMPONENTS_PATH = os.path.expandvars( os.path.join("$IDF_PATH", "components")) PARTTOOL_DIR = os.path.join(COMPONENTS_PATH, "partition_table") sys.path.append(PARTTOOL_DIR) from parttool import PartitionName, PartitionType, ParttoolTarget from gen_empty_partition import generate_blanked_file parser = argparse.ArgumentParser("ESP-IDF Partitions Tool Example") parser.add_argument( "--port", "-p", help="port where the device to perform operations on is connected") parser.add_argument("--binary", "-b", help="path to built example binary", default=os.path.join("build", "parttool.bin")) args = parser.parse_args() target = ParttoolTarget(args.port) # Read app partition and save the contents to a file. The app partition is identified # using type-subtype combination print("Checking if device app binary matches built binary") factory = PartitionType("app", "factory") target.read_partition(factory, "app.bin") assert_file_same(args.binary, "app.bin", "Device app binary does not match built binary") # Retrieve info on data storage partition, this time identifying it by name. storage = PartitionName("storage") storage_info = target.get_partition_info(storage) print("Found data partition at offset 0x{:x} with size 0x{:x}".format( storage_info.offset, storage_info.size)) # Create a file whose contents will be written to the storage partition with open("write.bin", "wb") as f: # Create a file to write to the data partition with randomly generated content f.write(os.urandom(storage_info.size)) # Write the contents of the created file to storage partition print("Writing to data partition") target.write_partition(storage, "write.bin") # Read back the contents of the storage partition print("Reading data partition") target.read_partition(storage, "read.bin") assert_file_same( "write.bin", "read.bin", "Read contents of storage partition does not match source file contents" ) # Erase contents of the storage partition print("Erasing data partition") target.erase_partition(storage) # Read back the erased data partition print("Reading data partition") target.read_partition(storage, "read.bin") # Generate a file of all 0xFF generate_blanked_file(storage_info.size, "blank.bin") assert_file_same("blank.bin", "read.bin", "Contents of storage partition not fully erased") # Example end and cleanup print("\nPartition tool operations performed successfully!") clean_files = ["app.bin", "read.bin", "blank.bin", "write.bin"] for clean_file in clean_files: os.unlink(clean_file)
class OtatoolTarget(): OTADATA_PARTITION = PartitionType("data", "ota") def __init__(self, port=None, partition_table_offset=PARTITION_TABLE_OFFSET, partition_table_file=None, spi_flash_sec_size=SPI_FLASH_SEC_SIZE): self.target = ParttoolTarget(port, partition_table_offset, partition_table_file) self.spi_flash_sec_size = spi_flash_sec_size temp_file = tempfile.NamedTemporaryFile(delete=False) temp_file.close() try: self.target.read_partition(OtatoolTarget.OTADATA_PARTITION, temp_file.name) with open(temp_file.name, "rb") as f: self.otadata = f.read() except Exception: self.otadata = None finally: os.unlink(temp_file.name) def _check_otadata_partition(self): if not self.otadata: raise Exception("No otadata partition found") def erase_otadata(self): self._check_otadata_partition() self.target.erase_partition(OtatoolTarget.OTADATA_PARTITION) def _get_otadata_info(self): info = [] otadata_info = collections.namedtuple("otadata_info", "seq crc") for i in range(2): start = i * (self.spi_flash_sec_size >> 1) seq = bytearray(self.otadata[start:start + 4]) crc = bytearray(self.otadata[start + 28:start + 32]) seq = struct.unpack('>I', seq) crc = struct.unpack('>I', crc) info.append(otadata_info(seq[0], crc[0])) return info def _get_partition_id_from_ota_id(self, ota_id): if isinstance(ota_id, int): return PartitionType("app", "ota_" + str(ota_id)) else: return PartitionName(ota_id) def switch_ota_partition(self, ota_id): self._check_otadata_partition() sys.path.append(PARTTOOL_DIR) import gen_esp32part as gen def is_otadata_info_valid(status): seq = status.seq % (1 << 32) crc = hex(binascii.crc32(struct.pack("I", seq), 0xFFFFFFFF) % (1 << 32)) return seq < (int('0xFFFFFFFF', 16) % (1 << 32)) and status.crc == crc partition_table = self.target.partition_table ota_partitions = list() for i in range(gen.NUM_PARTITION_SUBTYPE_APP_OTA): ota_partition = filter(lambda p: p.subtype == (gen.MIN_PARTITION_SUBTYPE_APP_OTA + i), partition_table) try: ota_partitions.append(list(ota_partition)[0]) except IndexError: break ota_partitions = sorted(ota_partitions, key=lambda p: p.subtype) if not ota_partitions: raise Exception("No ota app partitions found") # Look for the app partition to switch to ota_partition_next = None try: if isinstance(ota_id, int): ota_partition_next = filter(lambda p: p.subtype - gen.MIN_PARTITION_SUBTYPE_APP_OTA == ota_id, ota_partitions) else: ota_partition_next = filter(lambda p: p.name == ota_id, ota_partitions) ota_partition_next = list(ota_partition_next)[0] except IndexError: raise Exception("Partition to switch to not found") otadata_info = self._get_otadata_info() # Find the copy to base the computation for ota sequence number on otadata_compute_base = -1 # Both are valid, take the max as computation base if is_otadata_info_valid(otadata_info[0]) and is_otadata_info_valid(otadata_info[1]): if otadata_info[0].seq >= otadata_info[1].seq: otadata_compute_base = 0 else: otadata_compute_base = 1 # Only one copy is valid, use that elif is_otadata_info_valid(otadata_info[0]): otadata_compute_base = 0 elif is_otadata_info_valid(otadata_info[1]): otadata_compute_base = 1 # Both are invalid (could be initial state - all 0xFF's) else: pass ota_seq_next = 0 ota_partitions_num = len(ota_partitions) target_seq = (ota_partition_next.subtype & 0x0F) + 1 # Find the next ota sequence number if otadata_compute_base == 0 or otadata_compute_base == 1: base_seq = otadata_info[otadata_compute_base].seq % (1 << 32) i = 0 while base_seq > target_seq % ota_partitions_num + i * ota_partitions_num: i += 1 ota_seq_next = target_seq % ota_partitions_num + i * ota_partitions_num else: ota_seq_next = target_seq # Create binary data from computed values ota_seq_next = struct.pack("I", ota_seq_next) ota_seq_crc_next = binascii.crc32(ota_seq_next, 0xFFFFFFFF) % (1 << 32) ota_seq_crc_next = struct.pack("I", ota_seq_crc_next) temp_file = tempfile.NamedTemporaryFile(delete=False) temp_file.close() try: with open(temp_file.name, "wb") as otadata_next_file: start = (1 if otadata_compute_base == 0 else 0) * (self.spi_flash_sec_size >> 1) otadata_next_file.write(self.otadata) otadata_next_file.seek(start) otadata_next_file.write(ota_seq_next) otadata_next_file.seek(start + 28) otadata_next_file.write(ota_seq_crc_next) otadata_next_file.flush() self.target.write_partition(OtatoolTarget.OTADATA_PARTITION, temp_file.name) finally: os.unlink(temp_file.name) def read_ota_partition(self, ota_id, output): self.target.read_partition(self._get_partition_id_from_ota_id(ota_id), output) def write_ota_partition(self, ota_id, input): self.target.write_partition(self._get_partition_id_from_ota_id(ota_id), input) def erase_ota_partition(self, ota_id): self.target.erase_partition(self._get_partition_id_from_ota_id(ota_id))
def main(): COMPONENTS_PATH = os.path.expandvars( os.path.join('$IDF_PATH', 'components')) PARTTOOL_DIR = os.path.join(COMPONENTS_PATH, 'partition_table') sys.path.append(PARTTOOL_DIR) from gen_empty_partition import generate_blanked_file from parttool import PartitionName, PartitionType, ParttoolTarget parser = argparse.ArgumentParser('ESP-IDF Partitions Tool Example') parser.add_argument( '--port', '-p', help='port where the device to perform operations on is connected') parser.add_argument('--binary', '-b', help='path to built example binary', default=os.path.join('build', 'parttool.bin')) args = parser.parse_args() target = ParttoolTarget(args.port) # Read app partition and save the contents to a file. The app partition is identified # using type-subtype combination print('Checking if device app binary matches built binary') factory = PartitionType('app', 'factory') target.read_partition(factory, 'app.bin') assert_file_same(args.binary, 'app.bin', 'Device app binary does not match built binary') # Retrieve info on data storage partition, this time identifying it by name. storage = PartitionName('storage') storage_info = target.get_partition_info(storage) print('Found data partition at offset 0x{:x} with size 0x{:x}'.format( storage_info.offset, storage_info.size)) # Create a file whose contents will be written to the storage partition with open('write.bin', 'wb') as f: # Create a file to write to the data partition with randomly generated content f.write(os.urandom(storage_info.size)) # Write the contents of the created file to storage partition print('Writing to data partition') target.write_partition(storage, 'write.bin') # Read back the contents of the storage partition print('Reading data partition') target.read_partition(storage, 'read.bin') assert_file_same( 'write.bin', 'read.bin', 'Read contents of storage partition does not match source file contents' ) # Erase contents of the storage partition print('Erasing data partition') target.erase_partition(storage) # Read back the erased data partition print('Reading data partition') target.read_partition(storage, 'read.bin') # Generate a file of all 0xFF generate_blanked_file(storage_info.size, 'blank.bin') assert_file_same('blank.bin', 'read.bin', 'Contents of storage partition not fully erased') # Example end and cleanup print('\nPartition tool operations performed successfully!') clean_files = ['app.bin', 'read.bin', 'blank.bin', 'write.bin'] for clean_file in clean_files: os.unlink(clean_file)