usb_descriptors.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2020 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <string.h>
  15. #include "esp32s2/rom/usb/usb_common.h"
  16. #include "soc/soc.h"
  17. #include "soc/efuse_reg.h"
  18. /* USB CDC descriptor.
  19. * Note that we aren't using the one in ROM since it doesn't
  20. * set "serial" to the MAC address.
  21. * However overriding the descriptor is cheap - we can reuse most
  22. * of its components from ROM.
  23. */
  24. /* This is not const, since the MAC address is only known at run time */
  25. static struct string_descriptor s_str_serial_descr = {
  26. .bLength = 2 + 2 * 17,
  27. .bDescriptorType = 0x03,
  28. .bString={'0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0', ':', '0', '0'}
  29. };
  30. static const struct rom_usb_descriptors s_acm_usb_descriptors_override = {
  31. .device_descr = &general_device_descr,
  32. .config_descr = { &acm_config_descr },
  33. .string_count = 4,
  34. .string0_descr = &string0_descr,
  35. .string_descrs = {
  36. &str_manu_descr,
  37. &str_prod_descr,
  38. &s_str_serial_descr
  39. }
  40. };
  41. static inline uint16_t nibble_to_hex_u16(uint8_t b)
  42. {
  43. if (b < 0xa) {
  44. return '0' + b;
  45. } else {
  46. return 'a' + b - 0xa;
  47. }
  48. }
  49. void rom_usb_cdc_set_descriptor_patch(void)
  50. {
  51. /* Get the MAC address */
  52. const uint32_t mac0 = REG_GET_FIELD(EFUSE_RD_MAC_SPI_SYS_0_REG, EFUSE_MAC_0);
  53. const uint32_t mac1 = REG_GET_FIELD(EFUSE_RD_MAC_SPI_SYS_1_REG, EFUSE_MAC_1);
  54. uint8_t mac_bytes[6];
  55. memcpy(mac_bytes, &mac0, 4);
  56. memcpy(mac_bytes + 4, &mac1, 2);
  57. /* Convert to UTF16 string */
  58. uint16_t* dst = s_str_serial_descr.bString;
  59. for (int i = 0; i < 6; ++i) {
  60. uint8_t b = mac_bytes[5 - i]; /* printing from the MSB */
  61. *dst++ = nibble_to_hex_u16(b >> 4);
  62. *dst++ = nibble_to_hex_u16(b & 0xf);
  63. dst++;
  64. }
  65. /* Override the pointer to descriptors structure */
  66. rom_usb_curr_desc = &s_acm_usb_descriptors_override;
  67. }