sercomm-pid.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. import argparse
  10. import binascii
  11. import struct
  12. PID_SIZE = 0x70
  13. PADDING = 0x30
  14. PADDING_TAIL = 0x0
  15. def auto_int(x):
  16. return int(x, 0)
  17. def create_pid_file(args):
  18. pid_file = open(args.pid_file, "wb")
  19. buf = get_pid(args)
  20. pid_file.write(buf)
  21. pid_file.close()
  22. def get_pid(args):
  23. buf = bytearray([PADDING] * PID_SIZE)
  24. if not args.hw_id:
  25. enc = args.hw_version.rjust(14, '0').encode('ascii')
  26. struct.pack_into('>14s', buf, 0x0, enc)
  27. else:
  28. enc = args.hw_version.rjust(8, '0').encode('ascii')
  29. struct.pack_into('>8s', buf, 0x0, enc)
  30. enc = binascii.hexlify(args.hw_id.encode()).upper()
  31. struct.pack_into('>6s', buf, 0x8, enc)
  32. enc = args.sw_version.rjust(4, '0').encode('ascii')
  33. struct.pack_into('>4s', buf, 0x64, enc)
  34. if (args.extra_padd_size):
  35. tail = bytearray([PADDING_TAIL] * args.extra_padd_size)
  36. if (args.extra_padd_byte):
  37. struct.pack_into ('<i', tail, 0x0,
  38. args.extra_padd_byte)
  39. elif not args.hw_id:
  40. tail[0] = 0x0D
  41. tail[1] = 0x0A
  42. buf += tail
  43. return buf
  44. def main():
  45. global args
  46. parser = argparse.ArgumentParser(description='This script \
  47. generates firmware PID for the Sercomm-based devices')
  48. parser.add_argument('--hw-version',
  49. dest='hw_version',
  50. action='store',
  51. type=str,
  52. help='Sercomm hardware version')
  53. parser.add_argument('--hw-id',
  54. dest='hw_id',
  55. action='store',
  56. type=str,
  57. help='Sercomm hardware ID')
  58. parser.add_argument('--sw-version',
  59. dest='sw_version',
  60. action='store',
  61. type=str,
  62. help='Sercomm software version')
  63. parser.add_argument('--pid-file',
  64. dest='pid_file',
  65. action='store',
  66. type=str,
  67. help='Output PID file')
  68. parser.add_argument('--extra-padding-size',
  69. dest='extra_padd_size',
  70. action='store',
  71. type=auto_int,
  72. help='Size of extra NULL padding at the end of the file \
  73. (optional)')
  74. parser.add_argument('--extra-padding-first-byte',
  75. dest='extra_padd_byte',
  76. action='store',
  77. type=auto_int,
  78. help='First byte of extra padding (optional)')
  79. args = parser.parse_args()
  80. if ((not args.hw_version) or
  81. (not args.sw_version) or
  82. (not args.pid_file)):
  83. parser.print_help()
  84. exit()
  85. create_pid_file(args)
  86. main()