config_h.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. """Used by the make system to generate info_config.h from info.json.
  2. """
  3. from pathlib import Path
  4. from dotty_dict import dotty
  5. from argcomplete.completers import FilesCompleter
  6. from milc import cli
  7. from qmk.info import info_json
  8. from qmk.json_schema import json_load
  9. from qmk.keyboard import keyboard_completer, keyboard_folder
  10. from qmk.commands import dump_lines, parse_configurator_json
  11. from qmk.path import normpath, FileType
  12. from qmk.constants import GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE
  13. def generate_flag(define, value=None):
  14. # TODO: Change behavior to always use is_keymap logic for keyboard level config
  15. is_keymap = cli.args.filename
  16. if is_keymap:
  17. return f'\n#define {define}' if value else f'\n#undef {define}'
  18. return f'\n#define {define}' if value else ''
  19. def generate_define(define, value=None):
  20. is_keymap = cli.args.filename
  21. value = f' {value}' if value is not None else ''
  22. if is_keymap:
  23. return f"""
  24. #undef {define}
  25. #define {define}{value}"""
  26. return f"""
  27. #ifndef {define}
  28. # define {define}{value}
  29. #endif // {define}"""
  30. def direct_pins(direct_pins, postfix):
  31. """Return the config.h lines that set the direct pins.
  32. """
  33. rows = []
  34. for row in direct_pins:
  35. cols = ','.join(map(str, [col or 'NO_PIN' for col in row]))
  36. rows.append('{' + cols + '}')
  37. return generate_define(f'DIRECT_PINS{postfix}', f'{{ {", ".join(rows)} }}')
  38. def pin_array(define, pins, postfix):
  39. """Return the config.h lines that set a pin array.
  40. """
  41. pin_array = ', '.join(map(str, [pin or 'NO_PIN' for pin in pins]))
  42. return generate_define(f'{define}_PINS{postfix}', f'{{ {pin_array} }}')
  43. def matrix_pins(matrix_pins, postfix=''):
  44. """Add the matrix config to the config.h.
  45. """
  46. pins = []
  47. if 'direct' in matrix_pins:
  48. pins.append(direct_pins(matrix_pins['direct'], postfix))
  49. if 'cols' in matrix_pins:
  50. pins.append(pin_array('MATRIX_COL', matrix_pins['cols'], postfix))
  51. if 'rows' in matrix_pins:
  52. pins.append(pin_array('MATRIX_ROW', matrix_pins['rows'], postfix))
  53. return '\n'.join(pins)
  54. def generate_matrix_size(kb_info_json, config_h_lines):
  55. """Add the matrix size to the config.h.
  56. """
  57. if 'matrix_size' in kb_info_json:
  58. config_h_lines.append(generate_define('MATRIX_COLS', kb_info_json['matrix_size']['cols']))
  59. config_h_lines.append(generate_define('MATRIX_ROWS', kb_info_json['matrix_size']['rows']))
  60. def generate_config_items(kb_info_json, config_h_lines):
  61. """Iterate through the info_config map to generate basic config values.
  62. """
  63. info_config_map = json_load(Path('data/mappings/info_config.hjson'))
  64. for config_key, info_dict in info_config_map.items():
  65. info_key = info_dict['info_key']
  66. key_type = info_dict.get('value_type', 'raw')
  67. to_c = info_dict.get('to_c', True)
  68. if not to_c:
  69. continue
  70. try:
  71. config_value = kb_info_json[info_key]
  72. except KeyError, IndexError:
  73. continue
  74. if key_type.startswith('array.array'):
  75. config_h_lines.append(generate_define(config_key, f'{{ {", ".join(["{" + ",".join(list(map(str, x))) + "}" for x in config_value])} }}'))
  76. elif key_type.startswith('array'):
  77. config_h_lines.append(generate_define(config_key, f'{{ {", ".join(map(str, config_value))} }}'))
  78. elif key_type == 'bool':
  79. config_h_lines.append(generate_define(config_key, 'true' if config_value else 'false'))
  80. elif key_type == 'flag':
  81. config_h_lines.append(generate_flag(config_key, config_value))
  82. elif key_type == 'mapping':
  83. for key, value in config_value.items():
  84. config_h_lines.append(generate_define(key, value))
  85. elif key_type == 'str':
  86. escaped_str = config_value.replace('\\', '\\\\').replace('"', '\\"')
  87. config_h_lines.append(generate_define(config_key, f'"{escaped_str}"'))
  88. elif key_type == 'bcd_version':
  89. (major, minor, revision) = config_value.split('.')
  90. config_h_lines.append(generate_define(config_key, f'0x{major.zfill(2)}{minor}{revision}'))
  91. else:
  92. config_h_lines.append(generate_define(config_key, config_value))
  93. def generate_encoder_config(encoder_json, config_h_lines, postfix=''):
  94. """Generate the config.h lines for encoders."""
  95. a_pads = []
  96. b_pads = []
  97. resolutions = []
  98. for encoder in encoder_json.get("rotary", []):
  99. a_pads.append(encoder["pin_a"])
  100. b_pads.append(encoder["pin_b"])
  101. resolutions.append(encoder.get("resolution", None))
  102. config_h_lines.append(generate_define(f'ENCODER_A_PINS{postfix}', f'{{ {", ".join(a_pads)} }}'))
  103. config_h_lines.append(generate_define(f'ENCODER_B_PINS{postfix}', f'{{ {", ".join(b_pads)} }}'))
  104. if len(resolutions) == 0 or all(r is None for r in resolutions):
  105. cli.log.debug(f"Skipping ENCODER_RESOLUTION{postfix} configuration")
  106. return
  107. resolutions = [4 if r is None else r for r in resolutions]
  108. if len(set(resolutions)) == 1:
  109. config_h_lines.append(generate_define(f'ENCODER_RESOLUTION{postfix}', resolutions[0]))
  110. else:
  111. config_h_lines.append(generate_define(f'ENCODER_RESOLUTIONS{postfix}', f'{{ {", ".join(map(str,resolutions))} }}'))
  112. def generate_split_config(kb_info_json, config_h_lines):
  113. """Generate the config.h lines for split boards."""
  114. if 'handedness' in kb_info_json['split']:
  115. # TODO: change SPLIT_HAND_MATRIX_GRID to require brackets
  116. handedness = kb_info_json['split']['handedness']
  117. if 'matrix_grid' in handedness:
  118. config_h_lines.append(generate_define('SPLIT_HAND_MATRIX_GRID', ', '.join(handedness['matrix_grid'])))
  119. if 'protocol' in kb_info_json['split'].get('transport', {}):
  120. if kb_info_json['split']['transport']['protocol'] == 'i2c':
  121. config_h_lines.append(generate_define('USE_I2C'))
  122. if 'right' in kb_info_json['split'].get('matrix_pins', {}):
  123. config_h_lines.append(matrix_pins(kb_info_json['split']['matrix_pins']['right'], '_RIGHT'))
  124. if 'right' in kb_info_json['split'].get('encoder', {}):
  125. generate_encoder_config(kb_info_json['split']['encoder']['right'], config_h_lines, '_RIGHT')
  126. def generate_led_animations_config(feature, led_feature_json, config_h_lines, enable_prefix, animation_prefix):
  127. if 'animation' in led_feature_json.get('default', {}):
  128. config_h_lines.append(generate_define(f'{feature.upper()}_DEFAULT_MODE', f'{animation_prefix}{led_feature_json["default"]["animation"].upper()}'))
  129. for animation in led_feature_json.get('animations', {}):
  130. config_h_lines.append(generate_flag(f'{enable_prefix}{animation.upper()}', led_feature_json['animations'][animation]))
  131. @cli.argument('filename', nargs='?', arg_only=True, type=FileType('r'), completer=FilesCompleter('.json'), help='A configurator export JSON to be compiled and flashed or a pre-compiled binary firmware file (bin/hex) to be flashed.')
  132. @cli.argument('-o', '--output', arg_only=True, type=normpath, help='File to write to')
  133. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  134. @cli.argument('-kb', '--keyboard', arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate config.h for.')
  135. @cli.subcommand('Used by the make system to generate info_config.h from info.json', hidden=True)
  136. def generate_config_h(cli):
  137. """Generates the info_config.h file.
  138. """
  139. # Determine our keyboard/keymap
  140. if cli.args.filename:
  141. user_keymap = parse_configurator_json(cli.args.filename)
  142. kb_info_json = dotty(user_keymap.get('config', {}))
  143. elif cli.args.keyboard:
  144. kb_info_json = dotty(info_json(cli.args.keyboard))
  145. else:
  146. cli.log.error('You must supply a configurator export or `--keyboard`.')
  147. cli.subcommands['generate-config-h'].print_help()
  148. return False
  149. # Build the info_config.h file.
  150. config_h_lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE, '#pragma once']
  151. generate_config_items(kb_info_json, config_h_lines)
  152. generate_matrix_size(kb_info_json, config_h_lines)
  153. if 'matrix_pins' in kb_info_json:
  154. config_h_lines.append(matrix_pins(kb_info_json['matrix_pins']))
  155. if 'encoder' in kb_info_json:
  156. generate_encoder_config(kb_info_json['encoder'], config_h_lines)
  157. if 'split' in kb_info_json:
  158. generate_split_config(kb_info_json, config_h_lines)
  159. if 'led_matrix' in kb_info_json:
  160. generate_led_animations_config('led_matrix', kb_info_json['led_matrix'], config_h_lines, 'ENABLE_LED_MATRIX_', 'LED_MATRIX_')
  161. if 'rgb_matrix' in kb_info_json:
  162. generate_led_animations_config('rgb_matrix', kb_info_json['rgb_matrix'], config_h_lines, 'ENABLE_RGB_MATRIX_', 'RGB_MATRIX_')
  163. if 'rgblight' in kb_info_json:
  164. generate_led_animations_config('rgblight', kb_info_json['rgblight'], config_h_lines, 'RGBLIGHT_EFFECT_', 'RGBLIGHT_MODE_')
  165. # Show the results
  166. dump_lines(cli.args.output, config_h_lines, cli.args.quiet)