usb_descriptors.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include "esp32s2/rom/usb/usb_common.h"
  8. #include "soc/soc.h"
  9. #include "hal/efuse_hal.h"
  10. /* USB CDC descriptor.
  11. * Note that we aren't using the one in ROM since it doesn't
  12. * set "serial" to the MAC address.
  13. * However overriding the descriptor is cheap - we can reuse most
  14. * of its components from ROM.
  15. */
  16. /* This is not const, since the MAC address is only known at run time */
  17. static struct string_descriptor s_str_serial_descr = {
  18. .bLength = 2 + 2 * 17,
  19. .bDescriptorType = 0x03,
  20. .bString={'0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0'}
  21. };
  22. static const struct rom_usb_descriptors s_acm_usb_descriptors_override = {
  23. .device_descr = &general_device_descr,
  24. .config_descr = { &acm_config_descr },
  25. .string_count = 4,
  26. .string0_descr = &string0_descr,
  27. .string_descrs = {
  28. &str_manu_descr,
  29. &str_prod_descr,
  30. &s_str_serial_descr
  31. }
  32. };
  33. static inline uint16_t nibble_to_hex_u16(uint8_t b)
  34. {
  35. if (b < 0xa) {
  36. return '0' + b;
  37. } else {
  38. return 'a' + b - 0xa;
  39. }
  40. }
  41. void rom_usb_cdc_set_descriptor_patch(void)
  42. {
  43. uint8_t mac_bytes[6];
  44. efuse_hal_get_mac(mac_bytes);
  45. /* Convert to UTF16 string */
  46. #pragma GCC diagnostic push
  47. #if __GNUC__ >= 9
  48. #pragma GCC diagnostic ignored "-Waddress-of-packed-member"
  49. #endif
  50. uint16_t* dst = s_str_serial_descr.bString;
  51. for (int i = 0; i < 6; ++i) {
  52. uint8_t b = mac_bytes[5 - i]; /* printing from the MSB */
  53. *dst++ = nibble_to_hex_u16(b >> 4);
  54. *dst++ = nibble_to_hex_u16(b & 0xf);
  55. dst++;
  56. }
  57. #pragma GCC diagnostic pop
  58. /* Override the pointer to descriptors structure */
  59. rom_usb_curr_desc = &s_acm_usb_descriptors_override;
  60. }