scripts/download.pl: generilize and simplify download tool check
[openwrt/openwrt.git] / scripts / sercomm-pid.py
1 #!/usr/bin/env python3
2 """
3 # SPDX-License-Identifier: GPL-2.0-or-later
4 #
5 # sercomm-pid.py: Creates Sercomm device PID
6 #
7 # Copyright © 2022 Mikhail Zhilkin
8 """
9
10 import argparse
11 import binascii
12 import struct
13
14 PID_SIZE = 0x70
15 PADDING = 0x30
16 PADDING_TAIL = 0x0
17
18 def auto_int(x):
19 return int(x, 0)
20
21 def create_pid_file(args):
22 pid_file = open(args.pid_file, "wb")
23 buf = get_pid(args)
24 pid_file.write(buf)
25 pid_file.close()
26
27 def get_pid(args):
28 buf = bytearray([PADDING] * PID_SIZE)
29
30 enc = args.hw_version.rjust(8, '0').encode('ascii')
31 struct.pack_into('>8s', buf, 0x0, enc)
32
33 enc = binascii.hexlify(args.hw_id.encode())
34 struct.pack_into('>6s', buf, 0x8, enc)
35
36 enc = args.sw_version.rjust(4, '0').encode('ascii')
37 struct.pack_into('>4s', buf, 0x64, enc)
38
39 if (args.extra_padd_size):
40 tail = bytearray([PADDING_TAIL] * args.extra_padd_size)
41 if (args.extra_padd_byte):
42 struct.pack_into ('<i', tail, 0x0,
43 args.extra_padd_byte)
44 buf += tail
45
46 return buf
47
48 def main():
49 global args
50
51 parser = argparse.ArgumentParser(description='This script \
52 generates firmware PID for the Sercomm-based devices')
53
54 parser.add_argument('--hw-version',
55 dest='hw_version',
56 action='store',
57 type=str,
58 help='Sercomm hardware version')
59
60 parser.add_argument('--hw-id',
61 dest='hw_id',
62 action='store',
63 type=str,
64 help='Sercomm hardware ID')
65
66 parser.add_argument('--sw-version',
67 dest='sw_version',
68 action='store',
69 type=str,
70 help='Sercomm software version')
71
72 parser.add_argument('--pid-file',
73 dest='pid_file',
74 action='store',
75 type=str,
76 help='Output PID file')
77
78 parser.add_argument('--extra-padding-size',
79 dest='extra_padd_size',
80 action='store',
81 type=auto_int,
82 help='Size of extra NULL padding at the end of the file \
83 (optional)')
84
85 parser.add_argument('--extra-padding-first-byte',
86 dest='extra_padd_byte',
87 action='store',
88 type=auto_int,
89 help='First byte of extra padding (optional)')
90
91 args = parser.parse_args()
92
93 if ((not args.hw_version) or
94 (not args.hw_id) or
95 (not args.sw_version) or
96 (not args.pid_file)):
97 parser.print_help()
98 exit()
99
100 create_pid_file(args)
101
102 main()