cube.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import logging
  2. import subprocess
  3. class CubeProgrammer:
  4. """STM32 Cube Programmer cli wrapper"""
  5. def __init__(self, port, params=[]):
  6. self.port = port
  7. self.params = params
  8. # logging
  9. self.logger = logging.getLogger()
  10. def _execute(self, args):
  11. try:
  12. output = subprocess.check_output(
  13. [
  14. "STM32_Programmer_CLI",
  15. "-q",
  16. f"-c port={self.port}",
  17. *self.params,
  18. *args,
  19. ]
  20. )
  21. except subprocess.CalledProcessError as e:
  22. if e.output:
  23. print("Process output:\n", e.output.decode())
  24. print("Process return code:", e.returncode)
  25. raise e
  26. assert output
  27. return output.decode()
  28. def getVersion(self):
  29. output = self._execute(["--version"])
  30. def checkOptionBytes(self, option_bytes):
  31. output = self._execute(["-ob displ"])
  32. ob_correct = True
  33. for line in output.split("\n"):
  34. line = line.strip()
  35. if not ":" in line:
  36. self.logger.debug(f"Skipping line: {line}")
  37. continue
  38. key, data = line.split(":", 1)
  39. key = key.strip()
  40. data = data.strip()
  41. if not key in option_bytes.keys():
  42. self.logger.debug(f"Skipping key: {key}")
  43. continue
  44. self.logger.debug(f"Processing key: {key} {data}")
  45. value, comment = data.split(" ", 1)
  46. value = value.strip()
  47. comment = comment.strip()
  48. if option_bytes[key][0] != value:
  49. self.logger.error(
  50. f"Invalid OB: {key} {value}, expected: {option_bytes[key][0]}"
  51. )
  52. ob_correct = False
  53. return ob_correct
  54. def setOptionBytes(self, option_bytes):
  55. options = []
  56. for key, (value, attr) in option_bytes.items():
  57. if "w" in attr:
  58. options.append(f"{key}={value}")
  59. self._execute(["-ob", *options])
  60. return True
  61. def flashBin(self, address, filename):
  62. self._execute(
  63. [
  64. "-d",
  65. filename,
  66. f"{address}",
  67. ]
  68. )
  69. def flashCore2(self, address, filename):
  70. self._execute(
  71. [
  72. "-fwupgrade",
  73. filename,
  74. f"{address}",
  75. ]
  76. )
  77. def deleteCore2RadioStack(self):
  78. self._execute(["-fwdelete"])
  79. def resetTarget(self):
  80. self._execute([])