1#!/usr/bin/env bash
2#
3# Demonstrates command-line interface of Partition Tool, parttool.py
4#
5#
6# $1 - serial port where target device to operate on is connnected to, by default the first found valid serial port
7# $2 - path to this example's built binary file (parttool.bin), by default $PWD/build/parttool.bin
8PORT=$1
9PARTTOOL_PY="python $IDF_PATH/components/partition_table/parttool.py -q"
10
11if [[ "$PORT" != "" ]]; then
12    PARTTOOL_PY="$PARTTOOL_PY --port $PORT"
13fi
14
15GEN_EMPTY_PARTITION_PY="python $IDF_PATH/components/partition_table/gen_empty_partition.py"
16
17BINARY=$2
18
19if [[ "$BINARY" == "" ]]; then
20    BINARY=build/parttool.bin
21fi
22
23function assert_file_same()
24{
25    sz_a=$(stat -c %s $1)
26    sz_b=$(stat -c %s $2)
27    sz=$((sz_a < sz_b ? sz_a : sz_b))
28    res=$(cmp -s -n $sz $1 $2) ||
29        (echo "!!!!!!!!!!!!!!!!!!!"
30        echo "FAILURE: $3"
31        echo "!!!!!!!!!!!!!!!!!!!")
32}
33
34# Read app partition and save the contents to a file. The app partition is identified
35# using type-subtype combination
36echo "Checking if device app binary matches built binary"
37$PARTTOOL_PY read_partition --partition-type=app --partition-subtype=factory --output=app.bin
38assert_file_same app.bin $BINARY "Device app binary does not match built binary"
39
40# Retrieve info on data storage partition, this time identifying it by name.
41offset=$($PARTTOOL_PY get_partition_info --partition-name=storage --info offset)
42size=$($PARTTOOL_PY get_partition_info --partition-name=storage  --info size)
43echo "Found data partition at offset $offset with size $size"
44
45# Create a file whose contents will be written to the storage partition
46head -c $(($size)) /dev/urandom > write.bin
47
48# Write the contents of the created file to storage partition
49echo "Writing to data partition"
50$PARTTOOL_PY write_partition --partition-name=storage --input write.bin
51
52# Read back the contents of the storage partition
53echo "Reading data partition"
54$PARTTOOL_PY read_partition --partition-name=storage --output read.bin
55
56assert_file_same write.bin read.bin "Read contents of storage partition does not match source file contents"
57
58# Erase contents of the storage partition
59echo "Erasing data partition"
60$PARTTOOL_PY erase_partition --partition-name=storage
61
62# Read back the erased data partition
63echo "Reading data partition"
64$PARTTOOL_PY read_partition --partition-name=storage --output read.bin
65
66# Generate a file of all 0xFF
67$GEN_EMPTY_PARTITION_PY $(($size)) blank.bin
68
69assert_file_same read.bin blank.bin "Contents of storage partition not fully erased"
70
71# Example end and cleanup
72printf "\nPartition tool operations performed successfully\n"
73rm -rf app.bin read.bin blank.bin write.bin
74