ob.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #!/usr/bin/env python3
  2. import logging
  3. import argparse
  4. import subprocess
  5. import sys
  6. import os
  7. class Main:
  8. def __init__(self):
  9. # command args
  10. self.parser = argparse.ArgumentParser()
  11. self.parser.add_argument("-d", "--debug", action="store_true", help="Debug")
  12. self.subparsers = self.parser.add_subparsers(help="sub-command help")
  13. self.parser_check = self.subparsers.add_parser(
  14. "check", help="Check Option Bytes"
  15. )
  16. self.parser_check.set_defaults(func=self.check)
  17. self.parser_set = self.subparsers.add_parser("set", help="Set Option Bytes")
  18. self.parser_set.set_defaults(func=self.set)
  19. # logging
  20. self.logger = logging.getLogger()
  21. # OB
  22. self.ob = {}
  23. def __call__(self):
  24. self.args = self.parser.parse_args()
  25. if "func" not in self.args:
  26. self.parser.error("Choose something to do")
  27. # configure log output
  28. self.log_level = logging.DEBUG if self.args.debug else logging.INFO
  29. self.logger.setLevel(self.log_level)
  30. self.handler = logging.StreamHandler(sys.stdout)
  31. self.handler.setLevel(self.log_level)
  32. self.formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
  33. self.handler.setFormatter(self.formatter)
  34. self.logger.addHandler(self.handler)
  35. # execute requested function
  36. self.loadOB()
  37. self.args.func()
  38. def loadOB(self):
  39. self.logger.info(f"Loading Option Bytes data")
  40. file_path = os.path.join(os.path.dirname(sys.argv[0]), "ob.data")
  41. file = open(file_path, "r")
  42. for line in file.readlines():
  43. k, v, o = line.split(":")
  44. self.ob[k.strip()] = v.strip(), o.strip()
  45. def check(self):
  46. self.logger.info(f"Checking Option Bytes")
  47. try:
  48. output = subprocess.check_output(
  49. ["STM32_Programmer_CLI", "-q", "-c port=swd", "-ob displ"]
  50. )
  51. assert output
  52. except Exception as e:
  53. self.logger.error(f"Failed to call STM32_Programmer_CLI")
  54. self.logger.exception(e)
  55. return
  56. ob_correct = True
  57. for line in output.decode().split("\n"):
  58. line = line.strip()
  59. if not ":" in line:
  60. self.logger.debug(f"Skipping line: {line}")
  61. continue
  62. key, data = line.split(":", 1)
  63. key = key.strip()
  64. data = data.strip()
  65. if not key in self.ob.keys():
  66. self.logger.debug(f"Skipping key: {key}")
  67. continue
  68. self.logger.debug(f"Processing key: {key} {data}")
  69. value, comment = data.split(" ", 1)
  70. value = value.strip()
  71. comment = comment.strip()
  72. if self.ob[key][0] != value:
  73. self.logger.error(
  74. f"Invalid OB: {key} {value}, expected: {self.ob[key][0]}"
  75. )
  76. ob_correct = False
  77. if ob_correct:
  78. self.logger.info(f"OB Check OK")
  79. else:
  80. self.logger.error(f"OB Check FAIL")
  81. exit(255)
  82. def set(self):
  83. self.logger.info(f"Setting Option Bytes")
  84. options = []
  85. for key, (value, attr) in self.ob.items():
  86. if "w" in attr:
  87. options.append(f"{key}={value}")
  88. try:
  89. output = subprocess.check_output(
  90. [
  91. "STM32_Programmer_CLI",
  92. "-q",
  93. "-c port=swd",
  94. f"-ob {' '.join(options)}",
  95. ]
  96. )
  97. assert output
  98. self.logger.info(f"Success")
  99. except Exception as e:
  100. self.logger.error(f"Failed to call STM32_Programmer_CLI")
  101. self.logger.exception(e)
  102. return
  103. if __name__ == "__main__":
  104. Main()()