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.

common-dependencies.py 9.2KB

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