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.

configuration.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #
  2. # configuration.py
  3. # Apply options from config.ini to the existing Configuration headers
  4. #
  5. import re, shutil, configparser
  6. from pathlib import Path
  7. verbose = 0
  8. def blab(str,level=1):
  9. if verbose >= level: print(f"[config] {str}")
  10. def config_path(cpath):
  11. return Path("Marlin", cpath)
  12. # Apply a single name = on/off ; name = value ; etc.
  13. # TODO: Limit to the given (optional) configuration
  14. def apply_opt(name, val, conf=None):
  15. if name == "lcd": name, val = val, "on"
  16. # Create a regex to match the option and capture parts of the line
  17. regex = re.compile(r'^(\s*)(//\s*)?(#define\s+)(' + name + r'\b)(\s*)(.*?)(\s*)(//.*)?$', re.IGNORECASE)
  18. # Find and enable and/or update all matches
  19. for file in ("Configuration.h", "Configuration_adv.h"):
  20. fullpath = config_path(file)
  21. lines = fullpath.read_text().split('\n')
  22. found = False
  23. for i in range(len(lines)):
  24. line = lines[i]
  25. match = regex.match(line)
  26. if match and match[4].upper() == name.upper():
  27. found = True
  28. # For boolean options un/comment the define
  29. if val in ("on", "", None):
  30. newline = re.sub(r'^(\s*)//+\s*(#define)(\s{1,3})?(\s*)', r'\1\2 \4', line)
  31. elif val == "off":
  32. newline = re.sub(r'^(\s*)(#define)(\s{1,3})?(\s*)', r'\1//\2 \4', line)
  33. else:
  34. # For options with values, enable and set the value
  35. newline = match[1] + match[3] + match[4] + match[5] + val
  36. if match[8]:
  37. sp = match[7] if match[7] else ' '
  38. newline += sp + match[8]
  39. lines[i] = newline
  40. blab(f"Set {name} to {val}")
  41. # If the option was found, write the modified lines
  42. if found:
  43. fullpath.write_text('\n'.join(lines))
  44. break
  45. # If the option didn't appear in either config file, add it
  46. if not found:
  47. # OFF options are added as disabled items so they appear
  48. # in config dumps. Useful for custom settings.
  49. prefix = ""
  50. if val == "off":
  51. prefix, val = "//", "" # Item doesn't appear in config dump
  52. #val = "false" # Item appears in config dump
  53. # Uppercase the option unless already mixed/uppercase
  54. added = name.upper() if name.islower() else name
  55. # Add the provided value after the name
  56. if val != "on" and val != "" and val is not None:
  57. added += " " + val
  58. # Prepend the new option after the first set of #define lines
  59. fullpath = config_path("Configuration.h")
  60. with fullpath.open() as f:
  61. lines = f.readlines()
  62. linenum = 0
  63. gotdef = False
  64. for line in lines:
  65. isdef = line.startswith("#define")
  66. if not gotdef:
  67. gotdef = isdef
  68. elif not isdef:
  69. break
  70. linenum += 1
  71. lines.insert(linenum, f"{prefix}#define {added} // Added by config.ini\n")
  72. fullpath.write_text('\n'.join(lines))
  73. # Fetch configuration files from GitHub given the path.
  74. # Return True if any files were fetched.
  75. def fetch_example(path):
  76. if path.endswith("/"):
  77. path = path[:-1]
  78. url = path.replace("%", "%25").replace(" ", "%20")
  79. if not path.startswith('http'):
  80. url = "https://raw.githubusercontent.com/MarlinFirmware/Configurations/bugfix-2.1.x/config/%s" % url
  81. # Find a suitable fetch command
  82. if shutil.which("curl") is not None:
  83. fetch = "curl -L -s -S -f -o"
  84. elif shutil.which("wget") is not None:
  85. fetch = "wget -q -O"
  86. else:
  87. blab("Couldn't find curl or wget", -1)
  88. return False
  89. import os
  90. # Reset configurations to default
  91. os.system("git reset --hard HEAD")
  92. gotfile = False
  93. # Try to fetch the remote files
  94. for fn in ("Configuration.h", "Configuration_adv.h", "_Bootscreen.h", "_Statusscreen.h"):
  95. if os.system("%s wgot %s/%s >/dev/null 2>&1" % (fetch, url, fn)) == 0:
  96. shutil.move('wgot', config_path(fn))
  97. gotfile = True
  98. if Path('wgot').exists():
  99. shutil.rmtree('wgot')
  100. return gotfile
  101. def section_items(cp, sectkey):
  102. return cp.items(sectkey) if sectkey in cp.sections() else []
  103. # Apply all items from a config section
  104. def apply_ini_by_name(cp, sect):
  105. iniok = True
  106. if sect in ('config:base', 'config:root'):
  107. iniok = False
  108. items = section_items(cp, 'config:base') + section_items(cp, 'config:root')
  109. else:
  110. items = cp.items(sect)
  111. for item in items:
  112. if iniok or not item[0].startswith('ini_'):
  113. apply_opt(item[0], item[1])
  114. # Apply all config sections from a parsed file
  115. def apply_all_sections(cp):
  116. for sect in cp.sections():
  117. if sect.startswith('config:'):
  118. apply_ini_by_name(cp, sect)
  119. # Apply certain config sections from a parsed file
  120. def apply_sections(cp, ckey='all', addbase=False):
  121. blab("[config] apply section key: %s" % ckey)
  122. if ckey == 'all':
  123. apply_all_sections(cp)
  124. else:
  125. # Apply the base/root config.ini settings after external files are done
  126. if addbase or ckey in ('base', 'root'):
  127. apply_ini_by_name(cp, 'config:base')
  128. # Apply historically 'Configuration.h' settings everywhere
  129. if ckey == 'basic':
  130. apply_ini_by_name(cp, 'config:basic')
  131. # Apply historically Configuration_adv.h settings everywhere
  132. # (Some of which rely on defines in 'Conditionals_LCD.h')
  133. elif ckey in ('adv', 'advanced'):
  134. apply_ini_by_name(cp, 'config:advanced')
  135. # Apply a specific config:<name> section directly
  136. elif ckey.startswith('config:'):
  137. apply_ini_by_name(cp, ckey)
  138. # Apply settings from a top level config.ini
  139. def apply_config_ini(cp):
  140. blab("=" * 20 + " Gather 'config.ini' entries...")
  141. # Pre-scan for ini_use_config to get config_keys
  142. base_items = section_items(cp, 'config:base') + section_items(cp, 'config:root')
  143. config_keys = ['base']
  144. for ikey, ival in base_items:
  145. if ikey == 'ini_use_config':
  146. config_keys = [ x.strip() for x in ival.split(',') ]
  147. # For each ini_use_config item perform an action
  148. for ckey in config_keys:
  149. addbase = False
  150. # For a key ending in .ini load and parse another .ini file
  151. if ckey.endswith('.ini'):
  152. sect = 'base'
  153. if '@' in ckey: sect, ckey = ckey.split('@')
  154. other_ini = configparser.ConfigParser()
  155. other_ini.read(config_path(ckey))
  156. apply_sections(other_ini, sect)
  157. # (Allow 'example/' as a shortcut for 'examples/')
  158. elif ckey.startswith('example/'):
  159. ckey = 'examples' + ckey[7:]
  160. # For 'examples/<path>' fetch an example set from GitHub.
  161. # For https?:// do a direct fetch of the URL.
  162. elif ckey.startswith('examples/') or ckey.startswith('http'):
  163. addbase = True
  164. fetch_example(ckey)
  165. # Apply keyed sections after external files are done
  166. apply_sections(cp, 'config:' + ckey, addbase)
  167. if __name__ == "__main__":
  168. #
  169. # From command line use the given file name
  170. #
  171. import sys
  172. args = sys.argv[1:]
  173. if len(args) > 0:
  174. if args[0].endswith('.ini'):
  175. ini_file = args[0]
  176. else:
  177. print("Usage: %s <.ini file>" % sys.argv[0])
  178. else:
  179. ini_file = config_path('config.ini')
  180. if ini_file:
  181. user_ini = configparser.ConfigParser()
  182. user_ini.read(ini_file)
  183. apply_config_ini(user_ini)
  184. else:
  185. #
  186. # From within PlatformIO use the loaded INI file
  187. #
  188. import pioutil
  189. if pioutil.is_pio_build():
  190. Import("env")
  191. try:
  192. verbose = int(env.GetProjectOption('custom_verbose'))
  193. except:
  194. pass
  195. from platformio.project.config import ProjectConfig
  196. apply_config_ini(ProjectConfig())