My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

common-dependencies.py 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #
  2. # common-dependencies.py
  3. # Convenience script to check dependencies and add libs and sources for Marlin Enabled Features
  4. #
  5. import subprocess,os,re
  6. PIO_VERSION_MIN = (5, 0, 3)
  7. try:
  8. from platformio import VERSION as PIO_VERSION
  9. weights = (1000, 100, 1)
  10. version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)])
  11. version_cur = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION)])
  12. if version_cur < version_min:
  13. print()
  14. print("**************************************************")
  15. print("****** An update to PlatformIO is ******")
  16. print("****** required to build Marlin Firmware. ******")
  17. print("****** ******")
  18. print("****** Minimum version: ", PIO_VERSION_MIN, " ******")
  19. print("****** Current Version: ", PIO_VERSION, " ******")
  20. print("****** ******")
  21. print("****** Update PlatformIO and try again. ******")
  22. print("**************************************************")
  23. print()
  24. exit(1)
  25. except SystemExit:
  26. exit(1)
  27. except:
  28. print("Can't detect PlatformIO Version")
  29. from platformio.package.meta import PackageSpec
  30. from platformio.project.config import ProjectConfig
  31. Import("env")
  32. #print(env.Dump())
  33. try:
  34. verbose = int(env.GetProjectOption('custom_verbose'))
  35. except:
  36. verbose = 0
  37. def blab(str,level=1):
  38. if verbose >= level:
  39. print("[deps] %s" % str)
  40. FEATURE_CONFIG = {}
  41. def add_to_feat_cnf(feature, flines):
  42. try:
  43. feat = FEATURE_CONFIG[feature]
  44. except:
  45. FEATURE_CONFIG[feature] = {}
  46. # Get a reference to the FEATURE_CONFIG under construction
  47. feat = FEATURE_CONFIG[feature]
  48. # Split up passed lines on commas or newlines and iterate
  49. # Add common options to the features config under construction
  50. # For lib_deps replace a previous instance of the same library
  51. atoms = re.sub(r',\\s*', '\n', flines).strip().split('\n')
  52. for line in atoms:
  53. parts = line.split('=')
  54. name = parts.pop(0)
  55. if name in ['build_flags', 'extra_scripts', 'src_filter', 'lib_ignore']:
  56. feat[name] = '='.join(parts)
  57. blab("[%s] %s=%s" % (feature, name, feat[name]), 3)
  58. else:
  59. for dep in re.split(r",\s*", line):
  60. lib_name = re.sub(r'@([~^]|[<>]=?)?[\d.]+', '', dep.strip()).split('=').pop(0)
  61. lib_re = re.compile('(?!^' + lib_name + '\\b)')
  62. feat['lib_deps'] = list(filter(lib_re.match, feat['lib_deps'])) + [dep]
  63. blab("[%s] lib_deps = %s" % (feature, dep), 3)
  64. def load_config():
  65. blab("========== Gather [features] entries...")
  66. items = ProjectConfig().items('features')
  67. for key in items:
  68. feature = key[0].upper()
  69. if not feature in FEATURE_CONFIG:
  70. FEATURE_CONFIG[feature] = { 'lib_deps': [] }
  71. add_to_feat_cnf(feature, key[1])
  72. # Add options matching custom_marlin.MY_OPTION to the pile
  73. blab("========== Gather custom_marlin entries...")
  74. all_opts = env.GetProjectOptions()
  75. for n in all_opts:
  76. key = n[0]
  77. mat = re.match(r'custom_marlin\.(.+)', key)
  78. if mat:
  79. try:
  80. val = env.GetProjectOption(key)
  81. except:
  82. val = None
  83. if val:
  84. opt = mat.group(1).upper()
  85. blab("%s.custom_marlin.%s = '%s'" % ( env['PIOENV'], opt, val ))
  86. add_to_feat_cnf(opt, val)
  87. def get_all_known_libs():
  88. known_libs = []
  89. for feature in FEATURE_CONFIG:
  90. feat = FEATURE_CONFIG[feature]
  91. if not 'lib_deps' in feat:
  92. continue
  93. for dep in feat['lib_deps']:
  94. known_libs.append(PackageSpec(dep).name)
  95. return known_libs
  96. def get_all_env_libs():
  97. env_libs = []
  98. lib_deps = env.GetProjectOption('lib_deps')
  99. for dep in lib_deps:
  100. env_libs.append(PackageSpec(dep).name)
  101. return env_libs
  102. def set_env_field(field, value):
  103. proj = env.GetProjectConfig()
  104. proj.set("env:" + env['PIOENV'], field, value)
  105. # All unused libs should be ignored so that if a library
  106. # exists in .pio/lib_deps it will not break compilation.
  107. def force_ignore_unused_libs():
  108. env_libs = get_all_env_libs()
  109. known_libs = get_all_known_libs()
  110. diff = (list(set(known_libs) - set(env_libs)))
  111. lib_ignore = env.GetProjectOption('lib_ignore') + diff
  112. blab("Ignore libraries: %s" % lib_ignore)
  113. set_env_field('lib_ignore', lib_ignore)
  114. def apply_features_config():
  115. load_config()
  116. blab("========== Apply enabled features...")
  117. for feature in FEATURE_CONFIG:
  118. if not env.MarlinFeatureIsEnabled(feature):
  119. continue
  120. feat = FEATURE_CONFIG[feature]
  121. if 'lib_deps' in feat and len(feat['lib_deps']):
  122. blab("========== Adding lib_deps for %s... " % feature, 2)
  123. # feat to add
  124. deps_to_add = {}
  125. for dep in feat['lib_deps']:
  126. deps_to_add[PackageSpec(dep).name] = dep
  127. blab("==================== %s... " % dep, 2)
  128. # Does the env already have the dependency?
  129. deps = env.GetProjectOption('lib_deps')
  130. for dep in deps:
  131. name = PackageSpec(dep).name
  132. if name in deps_to_add:
  133. del deps_to_add[name]
  134. # Are there any libraries that should be ignored?
  135. lib_ignore = env.GetProjectOption('lib_ignore')
  136. for dep in deps:
  137. name = PackageSpec(dep).name
  138. if name in deps_to_add:
  139. del deps_to_add[name]
  140. # Is there anything left?
  141. if len(deps_to_add) > 0:
  142. # Only add the missing dependencies
  143. set_env_field('lib_deps', deps + list(deps_to_add.values()))
  144. if 'build_flags' in feat:
  145. f = feat['build_flags']
  146. blab("========== Adding build_flags for %s: %s" % (feature, f), 2)
  147. new_flags = env.GetProjectOption('build_flags') + [ f ]
  148. env.Replace(BUILD_FLAGS=new_flags)
  149. if 'extra_scripts' in feat:
  150. blab("Running extra_scripts for %s... " % feature, 2)
  151. env.SConscript(feat['extra_scripts'], exports="env")
  152. if 'src_filter' in feat:
  153. blab("========== Adding src_filter for %s... " % feature, 2)
  154. src_filter = ' '.join(env.GetProjectOption('src_filter'))
  155. # first we need to remove the references to the same folder
  156. my_srcs = re.findall(r'[+-](<.*?>)', feat['src_filter'])
  157. cur_srcs = re.findall(r'[+-](<.*?>)', src_filter)
  158. for d in my_srcs:
  159. if d in cur_srcs:
  160. src_filter = re.sub(r'[+-]' + d, '', src_filter)
  161. src_filter = feat['src_filter'] + ' ' + src_filter
  162. set_env_field('src_filter', [src_filter])
  163. env.Replace(SRC_FILTER=src_filter)
  164. if 'lib_ignore' in feat:
  165. blab("========== Adding lib_ignore for %s... " % feature, 2)
  166. lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']]
  167. set_env_field('lib_ignore', lib_ignore)
  168. #
  169. # Find a compiler, considering the OS
  170. #
  171. ENV_BUILD_PATH = os.path.join(env.Dictionary('PROJECT_BUILD_DIR'), env['PIOENV'])
  172. GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path")
  173. def search_compiler():
  174. try:
  175. filepath = env.GetProjectOption('custom_gcc')
  176. blab("Getting compiler from env")
  177. return filepath
  178. except:
  179. pass
  180. if os.path.exists(GCC_PATH_CACHE):
  181. with open(GCC_PATH_CACHE, 'r') as f:
  182. return f.read()
  183. # Find the current platform compiler by searching the $PATH
  184. # which will be in a platformio toolchain bin folder
  185. path_regex = re.escape(env['PROJECT_PACKAGES_DIR'])
  186. gcc = "g++"
  187. if env['PLATFORM'] == 'win32':
  188. path_separator = ';'
  189. path_regex += r'.*\\bin'
  190. gcc += ".exe"
  191. else:
  192. path_separator = ':'
  193. path_regex += r'/.+/bin'
  194. # Search for the compiler
  195. for pathdir in env['ENV']['PATH'].split(path_separator):
  196. if not re.search(path_regex, pathdir, re.IGNORECASE):
  197. continue
  198. for filepath in os.listdir(pathdir):
  199. if not filepath.endswith(gcc):
  200. continue
  201. # Use entire path to not rely on env PATH
  202. filepath = os.path.sep.join([pathdir, filepath])
  203. # Cache the g++ path to no search always
  204. if os.path.exists(ENV_BUILD_PATH):
  205. with open(GCC_PATH_CACHE, 'w+') as f:
  206. f.write(filepath)
  207. return filepath
  208. filepath = env.get('CXX')
  209. blab("Couldn't find a compiler! Fallback to %s" % filepath)
  210. return filepath
  211. #
  212. # Use the compiler to get a list of all enabled features
  213. #
  214. def load_marlin_features():
  215. if 'MARLIN_FEATURES' in env:
  216. return
  217. # Process defines
  218. build_flags = env.get('BUILD_FLAGS')
  219. build_flags = env.ParseFlagsExtended(build_flags)
  220. cxx = search_compiler()
  221. cmd = ['"' + cxx + '"']
  222. # Build flags from board.json
  223. #if 'BOARD' in env:
  224. # cmd += [env.BoardConfig().get("build.extra_flags")]
  225. for s in build_flags['CPPDEFINES']:
  226. if isinstance(s, tuple):
  227. cmd += ['-D' + s[0] + '=' + str(s[1])]
  228. else:
  229. cmd += ['-D' + s]
  230. cmd += ['-D__MARLIN_DEPS__ -w -dM -E -x c++ buildroot/share/PlatformIO/scripts/common-dependencies.h']
  231. cmd = ' '.join(cmd)
  232. blab(cmd, 4)
  233. define_list = subprocess.check_output(cmd, shell=True).splitlines()
  234. marlin_features = {}
  235. for define in define_list:
  236. feature = define[8:].strip().decode().split(' ')
  237. feature, definition = feature[0], ' '.join(feature[1:])
  238. marlin_features[feature] = definition
  239. env['MARLIN_FEATURES'] = marlin_features
  240. #
  241. # Return True if a matching feature is enabled
  242. #
  243. def MarlinFeatureIsEnabled(env, feature):
  244. load_marlin_features()
  245. r = re.compile('^' + feature + '$')
  246. found = list(filter(r.match, env['MARLIN_FEATURES']))
  247. # Defines could still be 'false' or '0', so check
  248. some_on = False
  249. if len(found):
  250. for f in found:
  251. val = env['MARLIN_FEATURES'][f]
  252. if val in [ '', '1', 'true' ]:
  253. some_on = True
  254. elif val in env['MARLIN_FEATURES']:
  255. some_on = env.MarlinFeatureIsEnabled(val)
  256. return some_on
  257. #
  258. # Add a method for other PIO scripts to query enabled features
  259. #
  260. env.AddMethod(MarlinFeatureIsEnabled)
  261. #
  262. # Add dependencies for enabled Marlin features
  263. #
  264. apply_features_config()
  265. force_ignore_unused_libs()