api-hal-vcp.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <api-hal-vcp.h>
  2. #include <usbd_cdc_if.h>
  3. #include <flipper_v2.h>
  4. #include <stream_buffer.h>
  5. #define API_HAL_VCP_RX_BUFFER_SIZE 600
  6. typedef struct {
  7. StreamBufferHandle_t rx_stream;
  8. osSemaphoreId_t tx_semaphore;
  9. volatile bool alive;
  10. volatile bool underrun;
  11. } ApiHalVcp;
  12. ApiHalVcp api_hal_vcp;
  13. static const uint8_t ascii_soh = 0x01;
  14. static const uint8_t ascii_eot = 0x04;
  15. void _api_hal_vcp_init();
  16. void _api_hal_vcp_deinit();
  17. void _api_hal_vcp_control_line(uint8_t state);
  18. void _api_hal_vcp_rx_callback(const uint8_t* buffer, size_t size);
  19. void _api_hal_vcp_tx_complete(size_t size);
  20. void api_hal_vcp_init() {
  21. api_hal_vcp.rx_stream = xStreamBufferCreate(API_HAL_VCP_RX_BUFFER_SIZE, 1);
  22. api_hal_vcp.tx_semaphore = osSemaphoreNew(1, 1, NULL);
  23. api_hal_vcp.alive = false;
  24. api_hal_vcp.underrun = false;
  25. }
  26. void _api_hal_vcp_init() {
  27. osSemaphoreRelease(api_hal_vcp.tx_semaphore);
  28. }
  29. void _api_hal_vcp_deinit() {
  30. api_hal_vcp.alive = false;
  31. osSemaphoreRelease(api_hal_vcp.tx_semaphore);
  32. }
  33. void _api_hal_vcp_control_line(uint8_t state) {
  34. // bit 0: DTR state, bit 1: RTS state
  35. // bool dtr = state & 0b01;
  36. bool rts = state & 0b10;
  37. if (rts) {
  38. api_hal_vcp.alive = true;
  39. _api_hal_vcp_rx_callback(&ascii_soh, 1); // SOH
  40. } else {
  41. api_hal_vcp.alive = false;
  42. _api_hal_vcp_rx_callback(&ascii_eot, 1); // EOT
  43. }
  44. osSemaphoreRelease(api_hal_vcp.tx_semaphore);
  45. }
  46. void _api_hal_vcp_rx_callback(const uint8_t* buffer, size_t size) {
  47. BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  48. size_t ret = xStreamBufferSendFromISR(api_hal_vcp.rx_stream, buffer, size, &xHigherPriorityTaskWoken);
  49. if (ret != size) {
  50. api_hal_vcp.underrun = true;
  51. }
  52. portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
  53. }
  54. void _api_hal_vcp_tx_complete(size_t size) {
  55. osSemaphoreRelease(api_hal_vcp.tx_semaphore);
  56. }
  57. size_t api_hal_vcp_rx(uint8_t* buffer, size_t size) {
  58. return xStreamBufferReceive(api_hal_vcp.rx_stream, buffer, size, portMAX_DELAY);
  59. }
  60. void api_hal_vcp_tx(uint8_t* buffer, size_t size) {
  61. while (size > 0 && api_hal_vcp.alive) {
  62. furi_check(osSemaphoreAcquire(api_hal_vcp.tx_semaphore, osWaitForever) == osOK);
  63. size_t batch_size = size;
  64. if (batch_size > APP_TX_DATA_SIZE) {
  65. batch_size = APP_TX_DATA_SIZE;
  66. }
  67. if (CDC_Transmit_FS(buffer, batch_size) == USBD_OK) {
  68. size -= batch_size;
  69. buffer += batch_size;
  70. } else {
  71. // Shouldn't be there
  72. osDelay(100);
  73. }
  74. }
  75. }