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_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_config = info_dict.get('to_config', True)
  62. if not to_config:
  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. if config_value:
  74. config_h_lines.append(generate_define(config_key))
  75. elif key_type == 'mapping':
  76. for key, value in config_value.items():
  77. config_h_lines.append(generate_define(key, value))
  78. elif key_type == 'str':
  79. escaped_str = config_value.replace('\\', '\\\\').replace('"', '\\"')
  80. config_h_lines.append(generate_define(config_key, f'"{escaped_str}"'))
  81. elif key_type == 'bcd_version':
  82. (major, minor, revision) = config_value.split('.')
  83. config_h_lines.append(generate_define(config_key, f'0x{major.zfill(2)}{minor}{revision}'))
  84. else:
  85. config_h_lines.append(generate_define(config_key, config_value))
  86. def generate_encoder_config(encoder_json, config_h_lines, postfix=''):
  87. """Generate the config.h lines for encoders."""
  88. a_pads = []
  89. b_pads = []
  90. resolutions = []
  91. for encoder in encoder_json.get("rotary", []):
  92. a_pads.append(encoder["pin_a"])
  93. b_pads.append(encoder["pin_b"])
  94. resolutions.append(encoder.get("resolution", None))
  95. config_h_lines.append(generate_define(f'ENCODERS_PAD_A{postfix}', f'{{ {", ".join(a_pads)} }}'))
  96. config_h_lines.append(generate_define(f'ENCODERS_PAD_B{postfix}', f'{{ {", ".join(b_pads)} }}'))
  97. if None in resolutions:
  98. cli.log.debug(f"Unable to generate ENCODER_RESOLUTION{postfix} configuration")
  99. elif len(resolutions) == 0:
  100. cli.log.debug(f"Skipping ENCODER_RESOLUTION{postfix} configuration")
  101. elif len(set(resolutions)) == 1:
  102. config_h_lines.append(generate_define(f'ENCODER_RESOLUTION{postfix}', resolutions[0]))
  103. else:
  104. config_h_lines.append(generate_define(f'ENCODER_RESOLUTIONS{postfix}', f'{{ {", ".join(map(str,resolutions))} }}'))
  105. def generate_split_config(kb_info_json, config_h_lines):
  106. """Generate the config.h lines for split boards."""
  107. if 'primary' in kb_info_json['split']:
  108. if kb_info_json['split']['primary'] in ('left', 'right'):
  109. config_h_lines.append('')
  110. config_h_lines.append('#ifndef MASTER_LEFT')
  111. config_h_lines.append('# ifndef MASTER_RIGHT')
  112. if kb_info_json['split']['primary'] == 'left':
  113. config_h_lines.append('# define MASTER_LEFT')
  114. elif kb_info_json['split']['primary'] == 'right':
  115. config_h_lines.append('# define MASTER_RIGHT')
  116. config_h_lines.append('# endif // MASTER_RIGHT')
  117. config_h_lines.append('#endif // MASTER_LEFT')
  118. elif kb_info_json['split']['primary'] == 'pin':
  119. config_h_lines.append(generate_define('SPLIT_HAND_PIN'))
  120. elif kb_info_json['split']['primary'] == 'matrix_grid':
  121. config_h_lines.append(generate_define('SPLIT_HAND_MATRIX_GRID', f'{{ {",".join(kb_info_json["split"]["matrix_grid"])} }}'))
  122. elif kb_info_json['split']['primary'] == 'eeprom':
  123. config_h_lines.append(generate_define('EE_HANDS'))
  124. if 'protocol' in kb_info_json['split'].get('transport', {}):
  125. if kb_info_json['split']['transport']['protocol'] == 'i2c':
  126. config_h_lines.append(generate_define('USE_I2C'))
  127. if 'right' in kb_info_json['split'].get('matrix_pins', {}):
  128. config_h_lines.append(matrix_pins(kb_info_json['split']['matrix_pins']['right'], '_RIGHT'))
  129. if 'right' in kb_info_json['split'].get('encoder', {}):
  130. generate_encoder_config(kb_info_json['split']['encoder']['right'], config_h_lines, '_RIGHT')
  131. def generate_led_animations_config(led_feature_json, config_h_lines, prefix):
  132. for animation in led_feature_json.get('animations', {}):
  133. if led_feature_json['animations'][animation]:
  134. config_h_lines.append(generate_define(f'{prefix}{animation.upper()}'))
  135. @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.')
  136. @cli.argument('-o', '--output', arg_only=True, type=normpath, help='File to write to')
  137. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  138. @cli.argument('-kb', '--keyboard', arg_only=True, type=keyboard_folder, completer=keyboard_completer, help='Keyboard to generate config.h for.')
  139. @cli.subcommand('Used by the make system to generate info_config.h from info.json', hidden=True)
  140. def generate_config_h(cli):
  141. """Generates the info_config.h file.
  142. """
  143. # Determine our keyboard/keymap
  144. if cli.args.filename:
  145. user_keymap = parse_configurator_json(cli.args.filename)
  146. kb_info_json = dotty(user_keymap.get('config', {}))
  147. elif cli.args.keyboard:
  148. kb_info_json = dotty(info_json(cli.args.keyboard))
  149. else:
  150. cli.log.error('You must supply a configurator export or `--keyboard`.')
  151. cli.subcommands['generate-config-h'].print_help()
  152. return False
  153. # Build the info_config.h file.
  154. config_h_lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE, '#pragma once']
  155. generate_config_items(kb_info_json, config_h_lines)
  156. generate_matrix_size(kb_info_json, config_h_lines)
  157. if 'matrix_pins' in kb_info_json:
  158. config_h_lines.append(matrix_pins(kb_info_json['matrix_pins']))
  159. if 'encoder' in kb_info_json:
  160. generate_encoder_config(kb_info_json['encoder'], config_h_lines)
  161. if 'split' in kb_info_json:
  162. generate_split_config(kb_info_json, config_h_lines)
  163. if 'led_matrix' in kb_info_json:
  164. generate_led_animations_config(kb_info_json['led_matrix'], config_h_lines, 'ENABLE_LED_MATRIX_')
  165. if 'rgb_matrix' in kb_info_json:
  166. generate_led_animations_config(kb_info_json['rgb_matrix'], config_h_lines, 'ENABLE_RGB_MATRIX_')
  167. if 'rgblight' in kb_info_json:
  168. generate_led_animations_config(kb_info_json['rgblight'], config_h_lines, 'RGBLIGHT_EFFECT_')
  169. # Show the results
  170. dump_lines(cli.args.output, config_h_lines, cli.args.quiet)