otp.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. #!/usr/bin/env python3
  2. import logging
  3. import argparse
  4. import subprocess
  5. import os
  6. import sys
  7. import re
  8. import struct
  9. import datetime
  10. OTP_MAGIC = 0xBABE
  11. OTP_VERSION = 0x01
  12. OTP_RESERVED = 0x00
  13. OTP_COLORS = {
  14. "unknown": 0x00,
  15. "black": 0x01,
  16. "white": 0x02,
  17. }
  18. OTP_REGIONS = {
  19. "unknown": 0x00,
  20. "europe": 0x01,
  21. "usa": 0x02,
  22. }
  23. BOARD_RESERVED = 0x0000
  24. class Main:
  25. def __init__(self):
  26. # command args
  27. self.parser = argparse.ArgumentParser()
  28. self.parser.add_argument("-d", "--debug", action="store_true", help="Debug")
  29. self.subparsers = self.parser.add_subparsers(help="sub-command help")
  30. # Generate
  31. self.parser_generate = self.subparsers.add_parser(
  32. "generate", help="Generate OTP binary"
  33. )
  34. self._add_args(self.parser_generate)
  35. self.parser_generate.add_argument("file", help="Output file")
  36. self.parser_generate.set_defaults(func=self.generate)
  37. # Flash
  38. self.parser_flash = self.subparsers.add_parser(
  39. "flash", help="Flash OTP to device"
  40. )
  41. self._add_args(self.parser_flash)
  42. self.parser_flash.add_argument(
  43. "--port", type=str, help="Port to connect: swd or usb1", default="swd"
  44. )
  45. self.parser_flash.set_defaults(func=self.flash)
  46. # logging
  47. self.logger = logging.getLogger()
  48. self.timestamp = datetime.datetime.now().timestamp()
  49. def __call__(self):
  50. self.args = self.parser.parse_args()
  51. if "func" not in self.args:
  52. self.parser.error("Choose something to do")
  53. # configure log output
  54. self.log_level = logging.DEBUG if self.args.debug else logging.INFO
  55. self.logger.setLevel(self.log_level)
  56. self.handler = logging.StreamHandler(sys.stdout)
  57. self.handler.setLevel(self.log_level)
  58. self.formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
  59. self.handler.setFormatter(self.formatter)
  60. self.logger.addHandler(self.handler)
  61. # execute requested function
  62. self.args.func()
  63. def _add_args(self, parser):
  64. parser.add_argument("--version", type=int, help="Version", default=10)
  65. parser.add_argument("--firmware", type=int, help="Firmware", default=6)
  66. parser.add_argument("--body", type=int, help="Body", default=8)
  67. parser.add_argument("--connect", type=int, help="Connect", default=5)
  68. parser.add_argument("--color", type=str, help="Color", default="unknown")
  69. parser.add_argument("--region", type=str, help="Region", default="unknown")
  70. parser.add_argument("--name", type=str, help="Name", required=True)
  71. def _process_args(self):
  72. if self.args.color not in OTP_COLORS:
  73. self.parser.error(f"Invalid color. Use one of {OTP_COLORS.keys()}")
  74. self.args.color = OTP_COLORS[self.args.color]
  75. if self.args.region not in OTP_REGIONS:
  76. self.parser.error(f"Invalid region. Use one of {OTP_REGIONS.keys()}")
  77. self.args.region = OTP_REGIONS[self.args.region]
  78. if len(self.args.name) > 8:
  79. self.parser.error("Name is too long. Max 8 symbols.")
  80. if re.match(r"[a-zA-Z0-9]+", self.args.name) is None:
  81. self.parser.error(
  82. "Name contains incorrect symbols. Only a-zA-Z0-9 allowed."
  83. )
  84. def _pack_struct(self):
  85. return struct.pack(
  86. "<" "HBBL" "BBBBBBH" "8s",
  87. OTP_MAGIC,
  88. OTP_VERSION,
  89. OTP_RESERVED,
  90. int(self.timestamp),
  91. self.args.version,
  92. self.args.firmware,
  93. self.args.body,
  94. self.args.connect,
  95. self.args.color,
  96. self.args.region,
  97. BOARD_RESERVED,
  98. self.args.name.encode("ascii"),
  99. )
  100. def generate(self):
  101. self.logger.debug(f"Generating OTP")
  102. self._process_args()
  103. data = self._pack_struct()
  104. open(self.args.file, "wb").write(data)
  105. def flash(self):
  106. self.logger.debug(f"Flashing OTP")
  107. self._process_args()
  108. data = self._pack_struct()
  109. filename = f"otp_{self.args.name}_{self.timestamp}.bin"
  110. open(filename, "wb").write(data)
  111. try:
  112. output = subprocess.check_output(
  113. [
  114. "STM32_Programmer_CLI",
  115. "-q",
  116. "-c",
  117. f"port={self.args.port}",
  118. "-d",
  119. filename,
  120. "0x1FFF7000",
  121. ]
  122. )
  123. assert output
  124. self.logger.info(f"Success")
  125. except subprocess.CalledProcessError as e:
  126. self.logger.error(e.output.decode())
  127. self.logger.error(f"Failed to call STM32_Programmer_CLI")
  128. return
  129. except Exception as e:
  130. self.logger.error(f"Failed to call STM32_Programmer_CLI")
  131. self.logger.exception(e)
  132. return
  133. # reboot
  134. subprocess.check_output(
  135. [
  136. "STM32_Programmer_CLI",
  137. "-q",
  138. "-c",
  139. f"port={self.args.port}",
  140. ]
  141. )
  142. os.remove(filename)
  143. if __name__ == "__main__":
  144. Main()()