My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

signature.py 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #
  2. # signature.py
  3. #
  4. import subprocess,re,json,hashlib
  5. import schema
  6. from pathlib import Path
  7. #
  8. # Return all macro names in a header as an array, so we can take
  9. # the intersection with the preprocessor output, giving a decent
  10. # reflection of all enabled options that (probably) came from the
  11. # configuration files. We end up with the actual configured state,
  12. # better than what the config files say. You can then use the
  13. # resulting config.ini to produce more exact configuration files.
  14. #
  15. def extract_defines(filepath):
  16. f = open(filepath, encoding="utf8").read().split("\n")
  17. a = []
  18. for line in f:
  19. sline = line.strip()
  20. if sline[:7] == "#define":
  21. # Extract the key here (we don't care about the value)
  22. kv = sline[8:].strip().split()
  23. a.append(kv[0])
  24. return a
  25. # Compute the SHA256 hash of a file
  26. def get_file_sha256sum(filepath):
  27. sha256_hash = hashlib.sha256()
  28. with open(filepath,"rb") as f:
  29. # Read and update hash string value in blocks of 4K
  30. for byte_block in iter(lambda: f.read(4096),b""):
  31. sha256_hash.update(byte_block)
  32. return sha256_hash.hexdigest()
  33. #
  34. # Compress a JSON file into a zip file
  35. #
  36. import zipfile
  37. def compress_file(filepath, outputbase):
  38. with zipfile.ZipFile(outputbase + '.zip', 'w', compression=zipfile.ZIP_BZIP2, compresslevel=9) as zipf:
  39. zipf.write(filepath, compress_type=zipfile.ZIP_BZIP2, compresslevel=9)
  40. #
  41. # Compute the build signature. The idea is to extract all defines in the configuration headers
  42. # to build a unique reversible signature from this build so it can be included in the binary
  43. # We can reverse the signature to get a 1:1 equivalent configuration file
  44. #
  45. def compute_build_signature(env):
  46. if 'BUILD_SIGNATURE' in env:
  47. return
  48. # Definitions from these files will be kept
  49. files_to_keep = [ 'Marlin/Configuration.h', 'Marlin/Configuration_adv.h' ]
  50. build_path = Path(env['PROJECT_BUILD_DIR'], env['PIOENV'])
  51. # Check if we can skip processing
  52. hashes = ''
  53. for header in files_to_keep:
  54. hashes += get_file_sha256sum(header)[0:10]
  55. marlin_json = build_path / 'marlin_config.json'
  56. marlin_zip = build_path / 'mc'
  57. # Read existing config file
  58. try:
  59. with marlin_json.open() as infile:
  60. conf = json.load(infile)
  61. if conf['__INITIAL_HASH'] == hashes:
  62. # Same configuration, skip recomputing the building signature
  63. compress_file(marlin_json, marlin_zip)
  64. return
  65. except:
  66. pass
  67. # Get enabled config options based on preprocessor
  68. from preprocessor import run_preprocessor
  69. complete_cfg = run_preprocessor(env)
  70. # Dumb #define extraction from the configuration files
  71. conf_defines = {}
  72. all_defines = []
  73. for header in files_to_keep:
  74. defines = extract_defines(header)
  75. # To filter only the define we want
  76. all_defines += defines
  77. # To remember from which file it cames from
  78. conf_defines[header.split('/')[-1]] = defines
  79. r = re.compile(r"\(+(\s*-*\s*_.*)\)+")
  80. # First step is to collect all valid macros
  81. defines = {}
  82. for line in complete_cfg:
  83. # Split the define from the value
  84. key_val = line[8:].strip().decode().split(' ')
  85. key, value = key_val[0], ' '.join(key_val[1:])
  86. # Ignore values starting with two underscore, since it's low level
  87. if len(key) > 2 and key[0:2] == "__" :
  88. continue
  89. # Ignore values containing a parenthesis (likely a function macro)
  90. if '(' in key and ')' in key:
  91. continue
  92. # Then filter dumb values
  93. if r.match(value):
  94. continue
  95. defines[key] = value if len(value) else ""
  96. #
  97. # Continue to gather data for CONFIGURATION_EMBEDDING or CONFIG_DUMP
  98. #
  99. if not ('CONFIGURATION_EMBEDDING' in defines or 'CONFIG_DUMP' in defines):
  100. return
  101. # Second step is to filter useless macro
  102. resolved_defines = {}
  103. for key in defines:
  104. # Remove all boards now
  105. if key.startswith("BOARD_") and key != "BOARD_INFO_NAME":
  106. continue
  107. # Remove all keys ending by "_NAME" as it does not make a difference to the configuration
  108. if key.endswith("_NAME") and key != "CUSTOM_MACHINE_NAME":
  109. continue
  110. # Remove all keys ending by "_T_DECLARED" as it's a copy of extraneous system stuff
  111. if key.endswith("_T_DECLARED"):
  112. continue
  113. # Remove keys that are not in the #define list in the Configuration list
  114. if key not in all_defines + [ 'DETAILED_BUILD_VERSION', 'STRING_DISTRIBUTION_DATE' ]:
  115. continue
  116. # Don't be that smart guy here
  117. resolved_defines[key] = defines[key]
  118. # Generate a build signature now
  119. # We are making an object that's a bit more complex than a basic dictionary here
  120. data = {}
  121. data['__INITIAL_HASH'] = hashes
  122. # First create a key for each header here
  123. for header in conf_defines:
  124. data[header] = {}
  125. # Then populate the object where each key is going to (that's a O(N^2) algorithm here...)
  126. for key in resolved_defines:
  127. for header in conf_defines:
  128. if key in conf_defines[header]:
  129. data[header][key] = resolved_defines[key]
  130. # Every python needs this toy
  131. def tryint(key):
  132. try:
  133. return int(defines[key])
  134. except:
  135. return 0
  136. config_dump = tryint('CONFIG_DUMP')
  137. #
  138. # Produce an INI file if CONFIG_DUMP == 2
  139. #
  140. if config_dump == 2:
  141. print("Generating config.ini ...")
  142. ignore = ('CONFIGURATION_H_VERSION', 'CONFIGURATION_ADV_H_VERSION', 'CONFIG_DUMP')
  143. filegrp = { 'Configuration.h':'config:basic', 'Configuration_adv.h':'config:advanced' }
  144. config_ini = build_path / 'config.ini'
  145. with config_ini.open('w') as outfile:
  146. outfile.write('#\n# Marlin Firmware\n# config.ini - Options to apply before the build\n#\n')
  147. # Loop through the data array of arrays
  148. for header in data:
  149. if header.startswith('__'):
  150. continue
  151. outfile.write('\n[' + filegrp[header] + ']\n')
  152. for key in sorted(data[header]):
  153. if key not in ignore:
  154. val = 'on' if data[header][key] == '' else data[header][key]
  155. outfile.write('{0:40}{1}'.format(key.lower(), ' = ' + val) + '\n')
  156. #
  157. # Produce a schema.json file if CONFIG_DUMP == 3
  158. #
  159. if config_dump >= 3:
  160. try:
  161. conf_schema = schema.extract()
  162. except Exception as exc:
  163. print("Error: " + str(exc))
  164. conf_schema = None
  165. if conf_schema:
  166. #
  167. # Produce a schema.json file if CONFIG_DUMP == 3
  168. #
  169. if config_dump in (3, 13):
  170. print("Generating schema.json ...")
  171. schema.dump_json(conf_schema, build_path / 'schema.json')
  172. if config_dump == 13:
  173. schema.group_options(conf_schema)
  174. schema.dump_json(conf_schema, build_path / 'schema_grouped.json')
  175. #
  176. # Produce a schema.yml file if CONFIG_DUMP == 4
  177. #
  178. elif config_dump == 4:
  179. print("Generating schema.yml ...")
  180. try:
  181. import yaml
  182. except ImportError:
  183. env.Execute(env.VerboseAction(
  184. '$PYTHONEXE -m pip install "pyyaml"',
  185. "Installing YAML for schema.yml export",
  186. ))
  187. import yaml
  188. schema.dump_yaml(conf_schema, build_path / 'schema.yml')
  189. # Append the source code version and date
  190. data['VERSION'] = {}
  191. data['VERSION']['DETAILED_BUILD_VERSION'] = resolved_defines['DETAILED_BUILD_VERSION']
  192. data['VERSION']['STRING_DISTRIBUTION_DATE'] = resolved_defines['STRING_DISTRIBUTION_DATE']
  193. try:
  194. curver = subprocess.check_output(["git", "describe", "--match=NeVeRmAtCh", "--always"]).strip()
  195. data['VERSION']['GIT_REF'] = curver.decode()
  196. except:
  197. pass
  198. #
  199. # Produce a JSON file for CONFIGURATION_EMBEDDING or CONFIG_DUMP == 1
  200. #
  201. if config_dump == 1 or 'CONFIGURATION_EMBEDDING' in defines:
  202. with marlin_json.open('w') as outfile:
  203. json.dump(data, outfile, separators=(',', ':'))
  204. #
  205. # The rest only applies to CONFIGURATION_EMBEDDING
  206. #
  207. if not 'CONFIGURATION_EMBEDDING' in defines:
  208. return
  209. # Compress the JSON file as much as we can
  210. compress_file(marlin_json, marlin_zip)
  211. # Generate a C source file for storing this array
  212. with open('Marlin/src/mczip.h','wb') as result_file:
  213. result_file.write(
  214. b'#ifndef NO_CONFIGURATION_EMBEDDING_WARNING\n'
  215. + b' #warning "Generated file \'mc.zip\' is embedded (Define NO_CONFIGURATION_EMBEDDING_WARNING to suppress this warning.)"\n'
  216. + b'#endif\n'
  217. + b'const unsigned char mc_zip[] PROGMEM = {\n '
  218. )
  219. count = 0
  220. for b in (build_path / 'mc.zip').open('rb').read():
  221. result_file.write(b' 0x%02X,' % b)
  222. count += 1
  223. if count % 16 == 0:
  224. result_file.write(b'\n ')
  225. if count % 16:
  226. result_file.write(b'\n')
  227. result_file.write(b'};\n')