From 82d932fe182d4cc069ba58a374b42fbd382fe78d Mon Sep 17 00:00:00 2001 From: Venelin Efremov Date: Mon, 18 Feb 2019 03:43:52 -0800 Subject: [PATCH] Check if the last packet we tried to transfer is taking too long --- cores/arduino/USBSerial.cpp | 4 ++-- cores/arduino/stm32/usb/cdc/usbd_cdc_if.c | 20 +++++++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/cores/arduino/USBSerial.cpp b/cores/arduino/USBSerial.cpp index 09502925e3..291f411fd5 100644 --- a/cores/arduino/USBSerial.cpp +++ b/cores/arduino/USBSerial.cpp @@ -84,10 +84,10 @@ size_t USBSerial::write(const uint8_t *buffer, size_t size) // After storing data, start transmitting process CDC_continue_transmit(); } else if (!CDC_connected()) { - return size - rest; + break; } } - return size; + return size - rest; } int USBSerial::available(void) diff --git a/cores/arduino/stm32/usb/cdc/usbd_cdc_if.c b/cores/arduino/stm32/usb/cdc/usbd_cdc_if.c index e06b4b076c..9f6a805aeb 100644 --- a/cores/arduino/stm32/usb/cdc/usbd_cdc_if.c +++ b/cores/arduino/stm32/usb/cdc/usbd_cdc_if.c @@ -32,6 +32,15 @@ #define CDC_MAX_PACKET_SIZE USB_MAX_EP0_SIZE #endif +/* + * The value USB_CDC_TRANSMIT_TIMEOUT is defined in terms of HAL_GetTick() units. + * Typically it is 1ms value. The timeout determines when we would consider the + * host "too slow" and threat the USB CDC port as disconnected. + */ +#ifndef +#define USB_CDC_TRANSMIT_TIMEOUT 3 +#endif + /* USBD_CDC Private Variables */ /* USB Device Core CDC handle declaration */ USBD_HandleTypeDef hUSBD_Device_CDC; @@ -43,6 +52,7 @@ CDC_TransmitQueue_TypeDef TransmitQueue; CDC_ReceiveQueue_TypeDef ReceiveQueue; __IO uint32_t lineState = 0; __IO bool receivePended = true; +static uint32_t transmitStart = 0; /** USBD_CDC Private Function Prototypes */ @@ -212,6 +222,7 @@ static int8_t USBD_CDC_Receive(uint8_t *Buf, uint32_t *Len) static int8_t USBD_CDC_Transferred(void) { + transmitStart = 0; CDC_TransmitQueue_CommitRead(&TransmitQueue); CDC_continue_transmit(); return (USBD_OK); @@ -247,7 +258,13 @@ void CDC_deInit(void) bool CDC_connected() { - return hUSBD_Device_CDC.dev_state == USBD_STATE_CONFIGURED && lineState; + uint32_t transmitTime = 0; + if (transmitStart) { + transmitTime = HAL_GetTick() - transmitStart; + } + return hUSBD_Device_CDC.dev_state == USBD_STATE_CONFIGURED + && transmitTime < USB_CDC_TRANSMIT_TIMEOUT + && lineState; } void CDC_continue_transmit(void) @@ -266,6 +283,7 @@ void CDC_continue_transmit(void) if (hcdc->TxState == 0U) { buffer = CDC_TransmitQueue_ReadBlock(&TransmitQueue, &size); if (size > 0) { + transmitStart = HAL_GetTick(); USBD_CDC_SetTxBuffer(&hUSBD_Device_CDC, buffer, size); /* * size never exceed PMA buffer and USBD_CDC_TransmitPacket make full