info.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. """Functions that help us generate and use info.json files.
  2. """
  3. from functools import lru_cache
  4. from pathlib import Path
  5. import jsonschema
  6. from milc import cli
  7. from qmk.constants import CHIBIOS_PROCESSORS, LUFA_PROCESSORS, VUSB_PROCESSORS
  8. from qmk.json_schema import validate
  9. from qmk.keymap import list_keymaps
  10. from qmk.metadata import basic_info_json, info_log_error
  11. @lru_cache(maxsize=None)
  12. def _valid_community_layout(layout):
  13. """Validate that a declared community list exists
  14. """
  15. return (Path('layouts/default') / layout).exists()
  16. @lru_cache(maxsize=None)
  17. def info_json(keyboard):
  18. """Generate the info.json data for a specific keyboard.
  19. """
  20. info_data = basic_info_json(keyboard)
  21. # Populate the list of JSON keymaps
  22. for keymap in list_keymaps(keyboard, c=False, fullpath=True):
  23. info_data['keymaps'][keymap.name] = {'url': f'https://raw.githubusercontent.com/qmk/qmk_firmware/master/{keymap}/keymap.json'}
  24. # Populate layout data
  25. layouts, aliases = _search_keyboard_h(keyboard)
  26. if aliases:
  27. info_data['layout_aliases'] = aliases
  28. for layout_name, layout_json in layouts.items():
  29. if not layout_name.startswith('LAYOUT_kc'):
  30. layout_json['c_macro'] = True
  31. info_data['layouts'][layout_name] = layout_json
  32. # Merge in the data from info.json, config.h, and rules.mk
  33. info_data = merge_info_jsons(keyboard, info_data)
  34. info_data = _extract_rules_mk(info_data)
  35. info_data = _extract_config_h(info_data)
  36. # Ensure that we have matrix row and column counts
  37. info_data = _matrix_size(info_data)
  38. # Validate against the jsonschema
  39. try:
  40. validate(info_data, 'qmk.api.keyboard.v1')
  41. except jsonschema.ValidationError as e:
  42. json_path = '.'.join([str(p) for p in e.absolute_path])
  43. cli.log.error('Invalid API data: %s: %s: %s', keyboard, json_path, e.message)
  44. exit(1)
  45. # Make sure we have at least one layout
  46. if not info_data.get('layouts'):
  47. _find_missing_layouts(info_data, keyboard)
  48. if not info_data.get('layouts'):
  49. info_log_error(info_data, 'No LAYOUTs defined! Need at least one layout defined in the keyboard.h or info.json.')
  50. # Filter out any non-existing community layouts
  51. for layout in info_data.get('community_layouts', []):
  52. if not _valid_community_layout(layout):
  53. # Ignore layout from future checks
  54. info_data['community_layouts'].remove(layout)
  55. info_log_error(info_data, 'Claims to support a community layout that does not exist: %s' % (layout))
  56. # Make sure we supply layout macros for the community layouts we claim to support
  57. for layout in info_data.get('community_layouts', []):
  58. layout_name = 'LAYOUT_' + layout
  59. if layout_name not in info_data.get('layouts', {}) and layout_name not in info_data.get('layout_aliases', {}):
  60. info_log_error(info_data, 'Claims to support community layout %s but no %s() macro found' % (layout, layout_name))
  61. # Check that the reported matrix size is consistent with the actual matrix size
  62. _check_matrix(info_data)
  63. return info_data
  64. def _extract_features(info_data, rules):
  65. """Find all the features enabled in rules.mk.
  66. """
  67. # Special handling for bootmagic which also supports a "lite" mode.
  68. if rules.get('BOOTMAGIC_ENABLE') == 'lite':
  69. rules['BOOTMAGIC_LITE_ENABLE'] = 'on'
  70. del rules['BOOTMAGIC_ENABLE']
  71. if rules.get('BOOTMAGIC_ENABLE') == 'full':
  72. rules['BOOTMAGIC_ENABLE'] = 'on'
  73. # Skip non-boolean features we haven't implemented special handling for
  74. for feature in 'HAPTIC_ENABLE', 'QWIIC_ENABLE':
  75. if rules.get(feature):
  76. del rules[feature]
  77. # Process the rest of the rules as booleans
  78. for key, value in rules.items():
  79. if key.endswith('_ENABLE'):
  80. key = '_'.join(key.split('_')[:-1]).lower()
  81. value = True if value.lower() in true_values else False if value.lower() in false_values else value
  82. if 'config_h_features' not in info_data:
  83. info_data['config_h_features'] = {}
  84. if 'features' not in info_data:
  85. info_data['features'] = {}
  86. if key in info_data['features']:
  87. _log_warning(info_data, 'Feature %s is specified in both info.json and rules.mk, the rules.mk value wins.' % (key,))
  88. info_data['features'][key] = value
  89. info_data['config_h_features'][key] = value
  90. return info_data
  91. def _pin_name(pin):
  92. """Returns the proper representation for a pin.
  93. """
  94. pin = pin.strip()
  95. if not pin:
  96. return None
  97. elif pin.isdigit():
  98. return int(pin)
  99. elif pin == 'NO_PIN':
  100. return None
  101. return pin
  102. def _extract_pins(pins):
  103. """Returns a list of pins from a comma separated string of pins.
  104. """
  105. return [_pin_name(pin) for pin in pins.split(',')]
  106. def _extract_direct_matrix(direct_pins):
  107. """
  108. """
  109. direct_pin_array = []
  110. while direct_pins[-1] != '}':
  111. direct_pins = direct_pins[:-1]
  112. for row in direct_pins.split('},{'):
  113. if row.startswith('{'):
  114. row = row[1:]
  115. if row.endswith('}'):
  116. row = row[:-1]
  117. direct_pin_array.append([])
  118. for pin in row.split(','):
  119. if pin == 'NO_PIN':
  120. pin = None
  121. direct_pin_array[-1].append(pin)
  122. return direct_pin_array
  123. def _extract_audio(info_data, config_c):
  124. """Populate data about the audio configuration
  125. """
  126. audio_pins = []
  127. for pin in 'B5', 'B6', 'B7', 'C4', 'C5', 'C6':
  128. if config_c.get(f'{pin}_AUDIO'):
  129. audio_pins.append(pin)
  130. if audio_pins:
  131. info_data['audio'] = {'pins': audio_pins}
  132. def _extract_split_main(info_data, config_c):
  133. """Populate data about the split configuration
  134. """
  135. # Figure out how the main half is determined
  136. if config_c.get('SPLIT_HAND_PIN') is True:
  137. if 'split' not in info_data:
  138. info_data['split'] = {}
  139. if 'main' in info_data['split']:
  140. _log_warning(info_data, 'Split main hand is specified in both config.h (SPLIT_HAND_PIN) and info.json (split.main) (Value: %s), the config.h value wins.' % info_data['split']['main'])
  141. info_data['split']['main'] = 'pin'
  142. if config_c.get('SPLIT_HAND_MATRIX_GRID'):
  143. if 'split' not in info_data:
  144. info_data['split'] = {}
  145. if 'main' in info_data['split']:
  146. _log_warning(info_data, 'Split main hand is specified in both config.h (SPLIT_HAND_MATRIX_GRID) and info.json (split.main) (Value: %s), the config.h value wins.' % info_data['split']['main'])
  147. info_data['split']['main'] = 'matrix_grid'
  148. info_data['split']['matrix_grid'] = _extract_pins(config_c['SPLIT_HAND_MATRIX_GRID'])
  149. if config_c.get('EE_HANDS') is True:
  150. if 'split' not in info_data:
  151. info_data['split'] = {}
  152. if 'main' in info_data['split']:
  153. _log_warning(info_data, 'Split main hand is specified in both config.h (EE_HANDS) and info.json (split.main) (Value: %s), the config.h value wins.' % info_data['split']['main'])
  154. info_data['split']['main'] = 'eeprom'
  155. if config_c.get('MASTER_RIGHT') is True:
  156. if 'split' not in info_data:
  157. info_data['split'] = {}
  158. if 'main' in info_data['split']:
  159. _log_warning(info_data, 'Split main hand is specified in both config.h (MASTER_RIGHT) and info.json (split.main) (Value: %s), the config.h value wins.' % info_data['split']['main'])
  160. info_data['split']['main'] = 'right'
  161. if config_c.get('MASTER_LEFT') is True:
  162. if 'split' not in info_data:
  163. info_data['split'] = {}
  164. if 'main' in info_data['split']:
  165. _log_warning(info_data, 'Split main hand is specified in both config.h (MASTER_LEFT) and info.json (split.main) (Value: %s), the config.h value wins.' % info_data['split']['main'])
  166. info_data['split']['main'] = 'left'
  167. def _extract_split_transport(info_data, config_c):
  168. # Figure out the transport method
  169. if config_c.get('USE_I2C') is True:
  170. if 'split' not in info_data:
  171. info_data['split'] = {}
  172. if 'transport' not in info_data['split']:
  173. info_data['split']['transport'] = {}
  174. if 'protocol' in info_data['split']['transport']:
  175. _log_warning(info_data, 'Split transport is specified in both config.h (USE_I2C) and info.json (split.transport.protocol) (Value: %s), the config.h value wins.' % info_data['split']['transport'])
  176. info_data['split']['transport']['protocol'] = 'i2c'
  177. elif 'protocol' not in info_data.get('split', {}).get('transport', {}):
  178. if 'split' not in info_data:
  179. info_data['split'] = {}
  180. if 'transport' not in info_data['split']:
  181. info_data['split']['transport'] = {}
  182. info_data['split']['transport']['protocol'] = 'serial'
  183. def _extract_split_right_pins(info_data, config_c):
  184. # Figure out the right half matrix pins
  185. row_pins = config_c.get('MATRIX_ROW_PINS_RIGHT', '').replace('{', '').replace('}', '').strip()
  186. col_pins = config_c.get('MATRIX_COL_PINS_RIGHT', '').replace('{', '').replace('}', '').strip()
  187. unused_pin_text = config_c.get('UNUSED_PINS_RIGHT')
  188. unused_pins = unused_pin_text.replace('{', '').replace('}', '').strip() if isinstance(unused_pin_text, str) else None
  189. direct_pins = config_c.get('DIRECT_PINS_RIGHT', '').replace(' ', '')[1:-1]
  190. if row_pins and col_pins:
  191. if info_data.get('split', {}).get('matrix_pins', {}).get('right') in info_data:
  192. _log_warning(info_data, 'Right hand matrix data is specified in both info.json and config.h, the config.h values win.')
  193. if 'split' not in info_data:
  194. info_data['split'] = {}
  195. if 'matrix_pins' not in info_data['split']:
  196. info_data['split']['matrix_pins'] = {}
  197. if 'right' not in info_data['split']['matrix_pins']:
  198. info_data['split']['matrix_pins']['right'] = {}
  199. info_data['split']['matrix_pins']['right'] = {
  200. 'cols': _extract_pins(col_pins),
  201. 'rows': _extract_pins(row_pins),
  202. }
  203. if direct_pins:
  204. if info_data.get('split', {}).get('matrix_pins', {}).get('right', {}):
  205. _log_warning(info_data, 'Right hand matrix data is specified in both info.json and config.h, the config.h values win.')
  206. if 'split' not in info_data:
  207. info_data['split'] = {}
  208. if 'matrix_pins' not in info_data['split']:
  209. info_data['split']['matrix_pins'] = {}
  210. if 'right' not in info_data['split']['matrix_pins']:
  211. info_data['split']['matrix_pins']['right'] = {}
  212. info_data['split']['matrix_pins']['right']['direct'] = _extract_direct_matrix(direct_pins)
  213. if unused_pins:
  214. if 'split' not in info_data:
  215. info_data['split'] = {}
  216. if 'matrix_pins' not in info_data['split']:
  217. info_data['split']['matrix_pins'] = {}
  218. if 'right' not in info_data['split']['matrix_pins']:
  219. info_data['split']['matrix_pins']['right'] = {}
  220. info_data['split']['matrix_pins']['right']['unused'] = _extract_pins(unused_pins)
  221. def _extract_matrix_info(info_data, config_c):
  222. """Populate the matrix information.
  223. """
  224. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  225. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  226. unused_pin_text = config_c.get('UNUSED_PINS')
  227. unused_pins = unused_pin_text.replace('{', '').replace('}', '').strip() if isinstance(unused_pin_text, str) else None
  228. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  229. info_snippet = {}
  230. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  231. if 'matrix_size' in info_data:
  232. _log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  233. info_data['matrix_size'] = {
  234. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  235. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  236. }
  237. if row_pins and col_pins:
  238. if 'matrix_pins' in info_data and 'cols' in info_data['matrix_pins'] and 'rows' in info_data['matrix_pins']:
  239. _log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  240. info_snippet['cols'] = _extract_pins(col_pins)
  241. info_snippet['rows'] = _extract_pins(row_pins)
  242. if direct_pins:
  243. if 'matrix_pins' in info_data and 'direct' in info_data['matrix_pins']:
  244. _log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  245. info_snippet['direct'] = _extract_direct_matrix(direct_pins)
  246. if unused_pins:
  247. if 'matrix_pins' not in info_data:
  248. info_data['matrix_pins'] = {}
  249. info_snippet['unused'] = _extract_pins(unused_pins)
  250. if config_c.get('CUSTOM_MATRIX', 'no') != 'no':
  251. if 'matrix_pins' in info_data and 'custom' in info_data['matrix_pins']:
  252. _log_warning(info_data, 'Custom Matrix is specified in both info.json and config.h, the config.h values win.')
  253. info_snippet['custom'] = True
  254. if config_c['CUSTOM_MATRIX'] == 'lite':
  255. info_snippet['custom_lite'] = True
  256. if info_snippet:
  257. info_data['matrix_pins'] = info_snippet
  258. return info_data
  259. def _extract_config_h(info_data):
  260. """Pull some keyboard information from existing config.h files
  261. """
  262. config_c = config_h(info_data['keyboard_folder'])
  263. # Pull in data from the json map
  264. dotty_info = dotty(info_data)
  265. info_config_map = json_load(Path('data/mappings/info_config.json'))
  266. for config_key, info_dict in info_config_map.items():
  267. info_key = info_dict['info_key']
  268. key_type = info_dict.get('value_type', 'str')
  269. try:
  270. if config_key in config_c and info_dict.get('to_json', True):
  271. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  272. _log_warning(info_data, '%s in config.h is overwriting %s in info.json' % (config_key, info_key))
  273. if key_type.startswith('array'):
  274. if '.' in key_type:
  275. key_type, array_type = key_type.split('.', 1)
  276. else:
  277. array_type = None
  278. config_value = config_c[config_key].replace('{', '').replace('}', '').strip()
  279. if array_type == 'int':
  280. dotty_info[info_key] = list(map(int, config_value.split(',')))
  281. else:
  282. dotty_info[info_key] = config_value.split(',')
  283. elif key_type == 'bool':
  284. dotty_info[info_key] = config_c[config_key] in true_values
  285. elif key_type == 'hex':
  286. dotty_info[info_key] = '0x' + config_c[config_key][2:].upper()
  287. elif key_type == 'list':
  288. dotty_info[info_key] = config_c[config_key].split()
  289. elif key_type == 'int':
  290. dotty_info[info_key] = int(config_c[config_key])
  291. else:
  292. dotty_info[info_key] = config_c[config_key]
  293. except Exception as e:
  294. _log_warning(info_data, f'{config_key}->{info_key}: {e}')
  295. info_data.update(dotty_info)
  296. # Pull data that easily can't be mapped in json
  297. _extract_matrix_info(info_data, config_c)
  298. _extract_audio(info_data, config_c)
  299. _extract_split_main(info_data, config_c)
  300. _extract_split_transport(info_data, config_c)
  301. _extract_split_right_pins(info_data, config_c)
  302. return info_data
  303. def _extract_rules_mk(info_data):
  304. """Pull some keyboard information from existing rules.mk files
  305. """
  306. rules = rules_mk(info_data['keyboard_folder'])
  307. info_data['processor'] = rules.get('MCU', info_data.get('processor', 'atmega32u4'))
  308. if info_data['processor'] in CHIBIOS_PROCESSORS:
  309. arm_processor_rules(info_data, rules)
  310. elif info_data['processor'] in LUFA_PROCESSORS + VUSB_PROCESSORS:
  311. avr_processor_rules(info_data, rules)
  312. else:
  313. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], info_data['processor']))
  314. unknown_processor_rules(info_data, rules)
  315. # Pull in data from the json map
  316. dotty_info = dotty(info_data)
  317. info_rules_map = json_load(Path('data/mappings/info_rules.json'))
  318. for rules_key, info_dict in info_rules_map.items():
  319. info_key = info_dict['info_key']
  320. key_type = info_dict.get('value_type', 'str')
  321. try:
  322. if rules_key in rules and info_dict.get('to_json', True):
  323. if dotty_info.get(info_key) and info_dict.get('warn_duplicate', True):
  324. _log_warning(info_data, '%s in rules.mk is overwriting %s in info.json' % (rules_key, info_key))
  325. if key_type.startswith('array'):
  326. if '.' in key_type:
  327. key_type, array_type = key_type.split('.', 1)
  328. else:
  329. array_type = None
  330. rules_value = rules[rules_key].replace('{', '').replace('}', '').strip()
  331. if array_type == 'int':
  332. dotty_info[info_key] = list(map(int, rules_value.split(',')))
  333. else:
  334. dotty_info[info_key] = rules_value.split(',')
  335. elif key_type == 'list':
  336. dotty_info[info_key] = rules[rules_key].split()
  337. elif key_type == 'bool':
  338. dotty_info[info_key] = rules[rules_key] in true_values
  339. elif key_type == 'hex':
  340. dotty_info[info_key] = '0x' + rules[rules_key][2:].upper()
  341. elif key_type == 'int':
  342. dotty_info[info_key] = int(rules[rules_key])
  343. else:
  344. dotty_info[info_key] = rules[rules_key]
  345. except Exception as e:
  346. _log_warning(info_data, f'{rules_key}->{info_key}: {e}')
  347. info_data.update(dotty_info)
  348. # Merge in config values that can't be easily mapped
  349. _extract_features(info_data, rules)
  350. return info_data
  351. def _matrix_size(info_data):
  352. """Add info_data['matrix_size'] if it doesn't exist.
  353. """
  354. if 'matrix_size' not in info_data and 'matrix_pins' in info_data:
  355. info_data['matrix_size'] = {}
  356. if 'direct' in info_data['matrix_pins']:
  357. info_data['matrix_size']['cols'] = len(info_data['matrix_pins']['direct'][0])
  358. info_data['matrix_size']['rows'] = len(info_data['matrix_pins']['direct'])
  359. elif 'cols' in info_data['matrix_pins'] and 'rows' in info_data['matrix_pins']:
  360. info_data['matrix_size']['cols'] = len(info_data['matrix_pins']['cols'])
  361. info_data['matrix_size']['rows'] = len(info_data['matrix_pins']['rows'])
  362. return info_data
  363. def _check_matrix(info_data):
  364. """Check the matrix to ensure that row/column count is consistent.
  365. """
  366. if 'matrix_pins' in info_data and 'matrix_size' in info_data:
  367. actual_col_count = info_data['matrix_size'].get('cols', 0)
  368. actual_row_count = info_data['matrix_size'].get('rows', 0)
  369. col_count = row_count = 0
  370. if 'direct' in info_data['matrix_pins']:
  371. col_count = len(info_data['matrix_pins']['direct'][0])
  372. row_count = len(info_data['matrix_pins']['direct'])
  373. elif 'cols' in info_data['matrix_pins'] and 'rows' in info_data['matrix_pins']:
  374. col_count = len(info_data['matrix_pins']['cols'])
  375. row_count = len(info_data['matrix_pins']['rows'])
  376. if col_count != actual_col_count and col_count != (actual_col_count / 2):
  377. # FIXME: once we can we should detect if split is enabled to do the actual_col_count/2 check.
  378. info_log_error(info_data, f'MATRIX_COLS is inconsistent with the size of MATRIX_COL_PINS: {col_count} != {actual_col_count}')
  379. if row_count != actual_row_count and row_count != (actual_row_count / 2):
  380. # FIXME: once we can we should detect if split is enabled to do the actual_row_count/2 check.
  381. info_log_error(info_data, f'MATRIX_ROWS is inconsistent with the size of MATRIX_ROW_PINS: {row_count} != {actual_row_count}')
  382. def _search_keyboard_h(keyboard):
  383. keyboard = Path(keyboard)
  384. current_path = Path('keyboards/')
  385. aliases = {}
  386. layouts = {}
  387. for directory in keyboard.parts:
  388. current_path = current_path / directory
  389. keyboard_h = '%s.h' % (directory,)
  390. keyboard_h_path = current_path / keyboard_h
  391. if keyboard_h_path.exists():
  392. new_layouts, new_aliases = find_layouts(keyboard_h_path)
  393. layouts.update(new_layouts)
  394. for alias, alias_text in new_aliases.items():
  395. if alias_text in layouts:
  396. aliases[alias] = alias_text
  397. return layouts, aliases
  398. def _find_missing_layouts(info_data, keyboard):
  399. """Looks for layout macros when they aren't found other places.
  400. If we don't find any layouts from info.json or keyboard.h we widen our search. This is error prone which is why we want to encourage people to follow the standard above.
  401. """
  402. _log_warning(info_data, '%s: Falling back to searching for KEYMAP/LAYOUT macros.' % (keyboard))
  403. for file in glob('keyboards/%s/*.h' % keyboard):
  404. these_layouts, these_aliases = find_layouts(file)
  405. if these_layouts:
  406. for layout_name, layout_json in these_layouts.items():
  407. if not layout_name.startswith('LAYOUT_kc'):
  408. layout_json['c_macro'] = True
  409. info_data['layouts'][layout_name] = layout_json
  410. for alias, alias_text in these_aliases.items():
  411. if alias_text in these_layouts:
  412. if 'layout_aliases' not in info_data:
  413. info_data['layout_aliases'] = {}
  414. info_data['layout_aliases'][alias] = alias_text
  415. def arm_processor_rules(info_data, rules):
  416. """Setup the default info for an ARM board.
  417. """
  418. info_data['processor_type'] = 'arm'
  419. info_data['protocol'] = 'ChibiOS'
  420. if 'bootloader' not in info_data:
  421. if 'STM32' in info_data['processor']:
  422. info_data['bootloader'] = 'stm32-dfu'
  423. else:
  424. info_data['bootloader'] = 'unknown'
  425. if 'STM32' in info_data['processor']:
  426. info_data['platform'] = 'STM32'
  427. elif 'MCU_SERIES' in rules:
  428. info_data['platform'] = rules['MCU_SERIES']
  429. elif 'ARM_ATSAM' in rules:
  430. info_data['platform'] = 'ARM_ATSAM'
  431. return info_data
  432. def avr_processor_rules(info_data, rules):
  433. """Setup the default info for an AVR board.
  434. """
  435. info_data['processor_type'] = 'avr'
  436. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  437. info_data['protocol'] = 'V-USB' if rules.get('MCU') in VUSB_PROCESSORS else 'LUFA'
  438. if 'bootloader' not in info_data:
  439. info_data['bootloader'] = 'atmel-dfu'
  440. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  441. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  442. return info_data
  443. def unknown_processor_rules(info_data, rules):
  444. """Setup the default keyboard info for unknown boards.
  445. """
  446. info_data['bootloader'] = 'unknown'
  447. info_data['platform'] = 'unknown'
  448. info_data['processor'] = 'unknown'
  449. info_data['processor_type'] = 'unknown'
  450. info_data['protocol'] = 'unknown'
  451. return info_data
  452. def merge_info_jsons(keyboard, info_data):
  453. """Return a merged copy of all the info.json files for a keyboard.
  454. """
  455. for info_file in find_info_json(keyboard):
  456. # Load and validate the JSON data
  457. new_info_data = json_load(info_file)
  458. if not isinstance(new_info_data, dict):
  459. info_log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  460. continue
  461. try:
  462. validate(new_info_data, 'qmk.keyboard.v1')
  463. except jsonschema.ValidationError as e:
  464. json_path = '.'.join([str(p) for p in e.absolute_path])
  465. cli.log.error('Not including data from file: %s', info_file)
  466. cli.log.error('\t%s: %s', json_path, e.message)
  467. continue
  468. # Merge layout data in
  469. if 'layout_aliases' in new_info_data:
  470. info_data['layout_aliases'] = {**info_data.get('layout_aliases', {}), **new_info_data['layout_aliases']}
  471. del new_info_data['layout_aliases']
  472. for layout_name, layout in new_info_data.get('layouts', {}).items():
  473. if layout_name in info_data.get('layout_aliases', {}):
  474. _log_warning(info_data, f"info.json uses alias name {layout_name} instead of {info_data['layout_aliases'][layout_name]}")
  475. layout_name = info_data['layout_aliases'][layout_name]
  476. if layout_name in info_data['layouts']:
  477. if len(info_data['layouts'][layout_name]['layout']) != len(layout['layout']):
  478. msg = '%s: %s: Number of elements in info.json does not match! info.json:%s != %s:%s'
  479. info_log_error(info_data, msg % (info_data['keyboard_folder'], layout_name, len(layout['layout']), layout_name, len(info_data['layouts'][layout_name]['layout'])))
  480. else:
  481. for new_key, existing_key in zip(layout['layout'], info_data['layouts'][layout_name]['layout']):
  482. existing_key.update(new_key)
  483. else:
  484. layout['c_macro'] = False
  485. info_data['layouts'][layout_name] = layout
  486. # Update info_data with the new data
  487. if 'layouts' in new_info_data:
  488. del new_info_data['layouts']
  489. deep_update(info_data, new_info_data)
  490. return info_data
  491. def find_info_json(keyboard):
  492. """Finds all the info.json files associated with a keyboard.
  493. """
  494. # Find the most specific first
  495. base_path = Path('keyboards')
  496. keyboard_path = base_path / keyboard
  497. keyboard_parent = keyboard_path.parent
  498. info_jsons = [keyboard_path / 'info.json']
  499. # Add DEFAULT_FOLDER before parents, if present
  500. rules = rules_mk(keyboard)
  501. if 'DEFAULT_FOLDER' in rules:
  502. info_jsons.append(Path(rules['DEFAULT_FOLDER']) / 'info.json')
  503. # Add in parent folders for least specific
  504. for _ in range(5):
  505. info_jsons.append(keyboard_parent / 'info.json')
  506. if keyboard_parent.parent == base_path:
  507. break
  508. keyboard_parent = keyboard_parent.parent
  509. return info_data