marlin.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #
  2. # marlin.py
  3. # Helper module with some commonly-used functions
  4. #
  5. import shutil
  6. from pathlib import Path
  7. from SCons.Script import DefaultEnvironment
  8. env = DefaultEnvironment()
  9. def copytree(src, dst, symlinks=False, ignore=None):
  10. for item in src.iterdir():
  11. if item.is_dir():
  12. shutil.copytree(item, dst / item.name, symlinks, ignore)
  13. else:
  14. shutil.copy2(item, dst / item.name)
  15. def replace_define(field, value):
  16. envdefs = env['CPPDEFINES'].copy()
  17. for define in envdefs:
  18. if define[0] == field:
  19. env['CPPDEFINES'].remove(define)
  20. env['CPPDEFINES'].append((field, value))
  21. # Relocate the firmware to a new address, such as "0x08005000"
  22. def relocate_firmware(address):
  23. replace_define("VECT_TAB_ADDR", address)
  24. # Relocate the vector table with a new offset
  25. def relocate_vtab(address):
  26. replace_define("VECT_TAB_OFFSET", address)
  27. # Replace the existing -Wl,-T with the given ldscript path
  28. def custom_ld_script(ldname):
  29. apath = str(Path("buildroot/share/PlatformIO/ldscripts", ldname).resolve())
  30. for i, flag in enumerate(env["LINKFLAGS"]):
  31. if "-Wl,-T" in flag:
  32. env["LINKFLAGS"][i] = "-Wl,-T" + apath
  33. elif flag == "-T":
  34. env["LINKFLAGS"][i + 1] = apath
  35. # Encrypt ${PROGNAME}.bin and save it with a new name. This applies (mostly) to MKS boards
  36. # This PostAction is set up by offset_and_rename.py for envs with 'build.encrypt_mks'.
  37. def encrypt_mks(source, target, env, new_name):
  38. import sys
  39. key = [0xA3, 0xBD, 0xAD, 0x0D, 0x41, 0x11, 0xBB, 0x8D, 0xDC, 0x80, 0x2D, 0xD0, 0xD2, 0xC4, 0x9B, 0x1E, 0x26, 0xEB, 0xE3, 0x33, 0x4A, 0x15, 0xE4, 0x0A, 0xB3, 0xB1, 0x3C, 0x93, 0xBB, 0xAF, 0xF7, 0x3E]
  40. # If FIRMWARE_BIN is defined by config, override all
  41. mf = env["MARLIN_FEATURES"]
  42. if "FIRMWARE_BIN" in mf: new_name = mf["FIRMWARE_BIN"]
  43. fwpath = Path(target[0].path)
  44. fwfile = fwpath.open("rb")
  45. enfile = Path(target[0].dir.path, new_name).open("wb")
  46. length = fwpath.stat().st_size
  47. position = 0
  48. try:
  49. while position < length:
  50. byte = fwfile.read(1)
  51. if 320 <= position < 31040:
  52. byte = chr(ord(byte) ^ key[position & 31])
  53. if sys.version_info[0] > 2:
  54. byte = bytes(byte, 'latin1')
  55. enfile.write(byte)
  56. position += 1
  57. finally:
  58. fwfile.close()
  59. enfile.close()
  60. fwpath.unlink()
  61. def add_post_action(action):
  62. env.AddPostAction(str(Path("$BUILD_DIR", "${PROGNAME}.bin")), action);