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

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