1# Reads the USB VID and PID from the file specified by sys.argv[1] and then 2# inserts those values into the template file specified by sys.argv[2], 3# printing the result to stdout 4 5from __future__ import print_function 6 7import sys 8import re 9import string 10 11config_prefix = "MICROPY_HW_USB_" 12needed_keys = ("USB_PID_CDC_MSC", "USB_PID_CDC_HID", "USB_PID_CDC", "USB_VID") 13 14 15def parse_usb_ids(filename): 16 rv = dict() 17 for line in open(filename).readlines(): 18 line = line.rstrip("\r\n") 19 match = re.match("^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$", line) 20 if match and match.group(1).startswith(config_prefix): 21 key = match.group(1).replace(config_prefix, "USB_") 22 val = match.group(2) 23 # print("key =", key, "val =", val) 24 if key in needed_keys: 25 rv[key] = val 26 for k in needed_keys: 27 if k not in rv: 28 raise Exception("Unable to parse %s from %s" % (k, filename)) 29 return rv 30 31 32if __name__ == "__main__": 33 usb_ids_file = sys.argv[1] 34 template_file = sys.argv[2] 35 replacements = parse_usb_ids(usb_ids_file) 36 for line in open(template_file, "r").readlines(): 37 print(string.Template(line).safe_substitute(replacements), end="") 38