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.

734 lines
27 KiB

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