rt_usbd_msc.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2026, sakumisu
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include "usbd_core.h"
  7. #include "usbd_msc.h"
  8. #include <rtthread.h>
  9. #include <rtdevice.h>
  10. #ifndef CONFIG_USBDEV_MSC_THREAD
  11. #error "Please enable CONFIG_USBDEV_MSC_THREAD, move msc read & write from isr to thread"
  12. #endif
  13. #ifndef CONFIG_USBDEV_MSC_BLOCK_DEV_NAME
  14. #define CONFIG_USBDEV_MSC_BLOCK_DEV_NAME "sd0"
  15. #endif
  16. static rt_device_t blk_dev = RT_NULL;
  17. static struct rt_device_blk_geometry geometry = { 0 };
  18. static struct usbd_interface msc_intf;
  19. void usbd_msc_get_cap(uint8_t busid, uint8_t lun, uint32_t *block_num, uint32_t *block_size)
  20. {
  21. rt_device_control(blk_dev, RT_DEVICE_CTRL_BLK_GETGEOME, &geometry);
  22. *block_num = geometry.sector_count;
  23. *block_size = geometry.bytes_per_sector;
  24. }
  25. int usbd_msc_sector_read(uint8_t busid, uint8_t lun, uint32_t sector, uint8_t *buffer, uint32_t length)
  26. {
  27. rt_device_read(blk_dev, sector, buffer, length / geometry.bytes_per_sector);
  28. return 0;
  29. }
  30. int usbd_msc_sector_write(uint8_t busid, uint8_t lun, uint32_t sector, uint8_t *buffer, uint32_t length)
  31. {
  32. rt_device_write(blk_dev, sector, buffer, length / geometry.bytes_per_sector);
  33. return 0;
  34. }
  35. void usbd_msc_blkdev_init(uint8_t busid, uint8_t in_ep, uint8_t out_ep)
  36. {
  37. rt_err_t res;
  38. blk_dev = rt_device_find(CONFIG_USBDEV_MSC_BLOCK_DEV_NAME);
  39. RT_ASSERT(blk_dev);
  40. res = rt_device_open(blk_dev, RT_DEVICE_OFLAG_RDWR);
  41. RT_ASSERT(res == RT_EOK);
  42. usbd_add_interface(busid, usbd_msc_init_intf(busid, &msc_intf, out_ep, in_ep));
  43. }