config_h.py 8.7 KB

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