| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- #include "Com_usb_cdc.h"
- #include <stdio.h>
- #include <string.h>
- #include "FreeRTOS.h"
- #include "task.h"
- #include "stream_buffer.h"
- #include "queue.h"
- #include "usbd_cdc_if.h"
- StreamBufferHandle_t xUsbTxStream = NULL;
- StreamBufferHandle_t xUsbRxStream = NULL;
- TaskHandle_t xUsbSendTaskHandle = NULL;
- /**
- * @brief USB CDC 发送任务
- * 从 TX 流缓冲取出数据,串行调用 CDC_Transmit_FS 发送。
- * 单发任务保证 CDC 端点不会并发访问。
- *
- * 任务A printf → fputc ─┐
- * 任务B printf → fputc ─┼→ TX stream buffer(环形) → [usbSendTask 单发任务] → CDC_Transmit_FS()
- * 任务C printf → fputc ─┘
- */
- static void Task_Usb_Send(void *argument)
- {
- (void)argument;
- uint8_t buf[64];
- size_t got = 0;
- for (;;)
- {
- got = xStreamBufferReceive(xUsbTxStream, buf, sizeof(buf), portMAX_DELAY);
- if (got > 0)
- {
- uint32_t sent = 0;
- while (sent < got)
- {
- uint16_t chunk = (uint16_t)(got - sent);
- if (CDC_Transmit_FS(&buf[sent], chunk) == USBD_OK)
- {
- sent += chunk;
- }
- else
- {
- /* 端点忙,稍后重试 */
- vTaskDelay(pdMS_TO_TICKS(1));
- }
- }
- }
- }
- }
- /**
- * @brief 初始化 USB CDC 通信层:创建流缓冲与发送任务
- */
- void Com_usb_cdc_init(void)
- {
- if (xUsbTxStream == NULL)
- {
- xUsbTxStream = xStreamBufferCreate(COM_USB_TX_BUFFER_SIZE, 1);
- }
- if (xUsbRxStream == NULL)
- {
- xUsbRxStream = xStreamBufferCreate(COM_USB_RX_BUFFER_SIZE, 1);
- }
- if (xUsbSendTaskHandle == NULL)
- {
- xTaskCreate(Task_Usb_Send, "usbSendTask", COM_USB_SEND_TASK_STACK,
- NULL, COM_USB_SEND_TASK_PRIORITY, &xUsbSendTaskHandle);
- }
- }
- /**
- * @brief printf 重定向:把字符写入 TX 流缓冲(多任务安全)
- */
- int fputc(int ch, FILE *f)
- {
- (void)f;
- if (xUsbTxStream != NULL)
- {
- xStreamBufferSend(xUsbTxStream, (uint8_t *)&ch, 1, 0);
- }
- return ch;
- }
- /**
- * @brief CDC 接收回调桥接:把收到的数据存入 RX 流缓冲
- */
- void Com_usb_cdc_rx_handler(uint8_t *buf, uint32_t len)
- {
- if (xUsbRxStream != NULL)
- {
- xStreamBufferSendFromISR(xUsbRxStream, buf, len, NULL);
- }
- }
- /**
- * @brief 读取应用层接收到的数据(非阻塞)
- */
- uint32_t Com_usb_cdc_read(uint8_t *buf, uint32_t len)
- {
- if (xUsbRxStream == NULL || buf == NULL)
- {
- return 0;
- }
- return (uint32_t)xStreamBufferReceive(xUsbRxStream, buf, len, 0);
- }
- /**
- * @brief 查询当前可读字节数
- */
- uint32_t Com_usb_cdc_bytes_available(void)
- {
- if (xUsbRxStream == NULL)
- {
- return 0;
- }
- return (uint32_t)xStreamBufferBytesAvailable(xUsbRxStream);
- }
|