usbd_cdc_interface.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * Taken from ST Cube library and heavily modified. See below for original
  5. * copyright header.
  6. */
  7. /**
  8. ******************************************************************************
  9. * @file USB_Device/CDC_Standalone/Src/usbd_cdc_interface.c
  10. * @author MCD Application Team
  11. * @version V1.0.1
  12. * @date 26-February-2014
  13. * @brief Source file for USBD CDC interface
  14. ******************************************************************************
  15. * @attention
  16. *
  17. * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
  18. *
  19. * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
  20. * You may not use this file except in compliance with the License.
  21. * You may obtain a copy of the License at:
  22. *
  23. * http://www.st.com/software_license_agreement_liberty_v2
  24. *
  25. * Unless required by applicable law or agreed to in writing, software
  26. * distributed under the License is distributed on an "AS IS" BASIS,
  27. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28. * See the License for the specific language governing permissions and
  29. * limitations under the License.
  30. *
  31. ******************************************************************************
  32. */
  33. /* Includes ------------------------------------------------------------------*/
  34. #include <stdbool.h>
  35. #include <stdint.h>
  36. #include "usbd_cdc_msc_hid.h"
  37. #include "usbd_cdc_interface.h"
  38. #include "pendsv.h"
  39. #include "py/obj.h"
  40. #include "lib/utils/interrupt_char.h"
  41. #include "irq.h"
  42. #if MICROPY_HW_ENABLE_USB
  43. // CDC control commands
  44. #define CDC_SEND_ENCAPSULATED_COMMAND 0x00
  45. #define CDC_GET_ENCAPSULATED_RESPONSE 0x01
  46. #define CDC_SET_COMM_FEATURE 0x02
  47. #define CDC_GET_COMM_FEATURE 0x03
  48. #define CDC_CLEAR_COMM_FEATURE 0x04
  49. #define CDC_SET_LINE_CODING 0x20
  50. #define CDC_GET_LINE_CODING 0x21
  51. #define CDC_SET_CONTROL_LINE_STATE 0x22
  52. #define CDC_SEND_BREAK 0x23
  53. uint8_t *usbd_cdc_init(usbd_cdc_state_t *cdc_in) {
  54. usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
  55. // Reset all the CDC state
  56. // Note: we don't reset tx_buf_ptr_in in order to allow the output buffer to
  57. // be filled (by usbd_cdc_tx_always) before the USB device is connected.
  58. cdc->rx_buf_put = 0;
  59. cdc->rx_buf_get = 0;
  60. cdc->tx_buf_ptr_out = 0;
  61. cdc->tx_buf_ptr_out_shadow = 0;
  62. cdc->tx_buf_ptr_wait_count = 0;
  63. cdc->tx_need_empty_packet = 0;
  64. cdc->dev_is_connected = 0;
  65. #if MICROPY_HW_USB_ENABLE_CDC2
  66. cdc->attached_to_repl = &cdc->base == cdc->base.usbd->cdc;
  67. #else
  68. cdc->attached_to_repl = 1;
  69. #endif
  70. // Return the buffer to place the first USB OUT packet
  71. return cdc->rx_packet_buf;
  72. }
  73. // Manage the CDC class requests
  74. // cmd: command code
  75. // pbuf: buffer containing command data (request parameters)
  76. // length: number of data to be sent (in bytes)
  77. // Returns USBD_OK if all operations are OK else USBD_FAIL
  78. int8_t usbd_cdc_control(usbd_cdc_state_t *cdc_in, uint8_t cmd, uint8_t* pbuf, uint16_t length) {
  79. usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
  80. switch (cmd) {
  81. case CDC_SEND_ENCAPSULATED_COMMAND:
  82. /* Add your code here */
  83. break;
  84. case CDC_GET_ENCAPSULATED_RESPONSE:
  85. /* Add your code here */
  86. break;
  87. case CDC_SET_COMM_FEATURE:
  88. /* Add your code here */
  89. break;
  90. case CDC_GET_COMM_FEATURE:
  91. /* Add your code here */
  92. break;
  93. case CDC_CLEAR_COMM_FEATURE:
  94. /* Add your code here */
  95. break;
  96. case CDC_SET_LINE_CODING:
  97. #if 0
  98. LineCoding.bitrate = (uint32_t)(pbuf[0] | (pbuf[1] << 8) |\
  99. (pbuf[2] << 16) | (pbuf[3] << 24));
  100. LineCoding.format = pbuf[4];
  101. LineCoding.paritytype = pbuf[5];
  102. LineCoding.datatype = pbuf[6];
  103. /* Set the new configuration */
  104. #endif
  105. break;
  106. case CDC_GET_LINE_CODING:
  107. /* Add your code here */
  108. pbuf[0] = (uint8_t)(115200);
  109. pbuf[1] = (uint8_t)(115200 >> 8);
  110. pbuf[2] = (uint8_t)(115200 >> 16);
  111. pbuf[3] = (uint8_t)(115200 >> 24);
  112. pbuf[4] = 0; // stop bits (1)
  113. pbuf[5] = 0; // parity (none)
  114. pbuf[6] = 8; // number of bits (8)
  115. break;
  116. case CDC_SET_CONTROL_LINE_STATE:
  117. cdc->dev_is_connected = length & 1; // wValue is passed in Len (bit of a hack)
  118. break;
  119. case CDC_SEND_BREAK:
  120. /* Add your code here */
  121. break;
  122. default:
  123. break;
  124. }
  125. return USBD_OK;
  126. }
  127. // This function is called to process outgoing data. We hook directly into the
  128. // SOF (start of frame) callback so that it is called exactly at the time it is
  129. // needed (reducing latency), and often enough (increasing bandwidth).
  130. static void usbd_cdc_sof(PCD_HandleTypeDef *hpcd, usbd_cdc_itf_t *cdc) {
  131. if (cdc == NULL || !cdc->dev_is_connected) {
  132. // CDC device is not connected to a host, so we are unable to send any data
  133. return;
  134. }
  135. if (cdc->tx_buf_ptr_out == cdc->tx_buf_ptr_in && !cdc->tx_need_empty_packet) {
  136. // No outstanding data to send
  137. return;
  138. }
  139. if (cdc->tx_buf_ptr_out != cdc->tx_buf_ptr_out_shadow) {
  140. // We have sent data and are waiting for the low-level USB driver to
  141. // finish sending it over the USB in-endpoint.
  142. // SOF occurs every 1ms, so we have a 500 * 1ms = 500ms timeout
  143. // We have a relatively large timeout because the USB host may be busy
  144. // doing other things and we must give it a chance to read our data.
  145. if (cdc->tx_buf_ptr_wait_count < 500) {
  146. USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
  147. if (USBx_INEP(cdc->base.in_ep & 0x7f)->DIEPTSIZ & USB_OTG_DIEPTSIZ_XFRSIZ) {
  148. // USB in-endpoint is still reading the data
  149. cdc->tx_buf_ptr_wait_count++;
  150. return;
  151. }
  152. }
  153. cdc->tx_buf_ptr_out = cdc->tx_buf_ptr_out_shadow;
  154. }
  155. if (cdc->tx_buf_ptr_out_shadow != cdc->tx_buf_ptr_in || cdc->tx_need_empty_packet) {
  156. uint32_t buffptr;
  157. uint32_t buffsize;
  158. if (cdc->tx_buf_ptr_out_shadow > cdc->tx_buf_ptr_in) { // rollback
  159. buffsize = USBD_CDC_TX_DATA_SIZE - cdc->tx_buf_ptr_out_shadow;
  160. } else {
  161. buffsize = cdc->tx_buf_ptr_in - cdc->tx_buf_ptr_out_shadow;
  162. }
  163. buffptr = cdc->tx_buf_ptr_out_shadow;
  164. if (USBD_CDC_TransmitPacket(&cdc->base, buffsize, &cdc->tx_buf[buffptr]) == USBD_OK) {
  165. cdc->tx_buf_ptr_out_shadow += buffsize;
  166. if (cdc->tx_buf_ptr_out_shadow == USBD_CDC_TX_DATA_SIZE) {
  167. cdc->tx_buf_ptr_out_shadow = 0;
  168. }
  169. cdc->tx_buf_ptr_wait_count = 0;
  170. // According to the USB specification, a packet size of 64 bytes (CDC_DATA_FS_MAX_PACKET_SIZE)
  171. // gets held at the USB host until the next packet is sent. This is because a
  172. // packet of maximum size is considered to be part of a longer chunk of data, and
  173. // the host waits for all data to arrive (ie, waits for a packet < max packet size).
  174. // To flush a packet of exactly max packet size, we need to send a zero-size packet.
  175. // See eg http://www.cypress.com/?id=4&rID=92719
  176. cdc->tx_need_empty_packet = (buffsize > 0 && buffsize % usbd_cdc_max_packet(cdc->base.usbd->pdev) == 0 && cdc->tx_buf_ptr_out_shadow == cdc->tx_buf_ptr_in);
  177. }
  178. }
  179. }
  180. void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) {
  181. usbd_cdc_msc_hid_state_t *usbd = ((USBD_HandleTypeDef*)hpcd->pData)->pClassData;
  182. usbd_cdc_sof(hpcd, (usbd_cdc_itf_t*)usbd->cdc);
  183. #if MICROPY_HW_USB_ENABLE_CDC2
  184. usbd_cdc_sof(hpcd, (usbd_cdc_itf_t*)usbd->cdc2);
  185. #endif
  186. }
  187. // Data received over USB OUT endpoint is processed here.
  188. // len: number of bytes received into the buffer we passed to USBD_CDC_ReceivePacket
  189. // Returns USBD_OK if all operations are OK else USBD_FAIL
  190. int8_t usbd_cdc_receive(usbd_cdc_state_t *cdc_in, size_t len) {
  191. usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in;
  192. // copy the incoming data into the circular buffer
  193. for (const uint8_t *src = cdc->rx_packet_buf, *top = cdc->rx_packet_buf + len; src < top; ++src) {
  194. if (cdc->attached_to_repl && mp_interrupt_char != -1 && *src == mp_interrupt_char) {
  195. pendsv_kbd_intr();
  196. } else {
  197. uint16_t next_put = (cdc->rx_buf_put + 1) & (USBD_CDC_RX_DATA_SIZE - 1);
  198. if (next_put == cdc->rx_buf_get) {
  199. // overflow, we just discard the rest of the chars
  200. break;
  201. }
  202. cdc->rx_user_buf[cdc->rx_buf_put] = *src;
  203. cdc->rx_buf_put = next_put;
  204. }
  205. }
  206. // initiate next USB packet transfer
  207. USBD_CDC_ReceivePacket(&cdc->base, cdc->rx_packet_buf);
  208. return USBD_OK;
  209. }
  210. int usbd_cdc_tx_half_empty(usbd_cdc_itf_t *cdc) {
  211. int32_t tx_waiting = (int32_t)cdc->tx_buf_ptr_in - (int32_t)cdc->tx_buf_ptr_out;
  212. if (tx_waiting < 0) {
  213. tx_waiting += USBD_CDC_TX_DATA_SIZE;
  214. }
  215. return tx_waiting <= USBD_CDC_TX_DATA_SIZE / 2;
  216. }
  217. // timout in milliseconds.
  218. // Returns number of bytes written to the device.
  219. int usbd_cdc_tx(usbd_cdc_itf_t *cdc, const uint8_t *buf, uint32_t len, uint32_t timeout) {
  220. for (uint32_t i = 0; i < len; i++) {
  221. // Wait until the device is connected and the buffer has space, with a given timeout
  222. uint32_t start = HAL_GetTick();
  223. while (!cdc->dev_is_connected || ((cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1)) == cdc->tx_buf_ptr_out) {
  224. // Wraparound of tick is taken care of by 2's complement arithmetic.
  225. if (HAL_GetTick() - start >= timeout) {
  226. // timeout
  227. return i;
  228. }
  229. if (query_irq() == IRQ_STATE_DISABLED) {
  230. // IRQs disabled so buffer will never be drained; return immediately
  231. return i;
  232. }
  233. __WFI(); // enter sleep mode, waiting for interrupt
  234. }
  235. // Write data to device buffer
  236. cdc->tx_buf[cdc->tx_buf_ptr_in] = buf[i];
  237. cdc->tx_buf_ptr_in = (cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1);
  238. }
  239. // Success, return number of bytes read
  240. return len;
  241. }
  242. // Always write all of the data to the device tx buffer, even if the
  243. // device is not connected, or if the buffer is full. Has a small timeout
  244. // to wait for the buffer to be drained, in the case the device is connected.
  245. void usbd_cdc_tx_always(usbd_cdc_itf_t *cdc, const uint8_t *buf, uint32_t len) {
  246. for (int i = 0; i < len; i++) {
  247. // If the CDC device is not connected to the host then we don't have anyone to receive our data.
  248. // The device may become connected in the future, so we should at least try to fill the buffer
  249. // and hope that it doesn't overflow by the time the device connects.
  250. // If the device is not connected then we should go ahead and fill the buffer straight away,
  251. // ignoring overflow. Otherwise, we should make sure that we have enough room in the buffer.
  252. if (cdc->dev_is_connected) {
  253. // If the buffer is full, wait until it gets drained, with a timeout of 500ms
  254. // (wraparound of tick is taken care of by 2's complement arithmetic).
  255. uint32_t start = HAL_GetTick();
  256. while (((cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1)) == cdc->tx_buf_ptr_out && HAL_GetTick() - start <= 500) {
  257. if (query_irq() == IRQ_STATE_DISABLED) {
  258. // IRQs disabled so buffer will never be drained; exit loop
  259. break;
  260. }
  261. __WFI(); // enter sleep mode, waiting for interrupt
  262. }
  263. // Some unused code that makes sure the low-level USB buffer is drained.
  264. // Waiting for low-level is handled in HAL_PCD_SOFCallback.
  265. /*
  266. start = HAL_GetTick();
  267. PCD_HandleTypeDef *hpcd = hUSBDDevice.pData;
  268. if (hpcd->IN_ep[0x83 & 0x7f].is_in) {
  269. //volatile uint32_t *xfer_count = &hpcd->IN_ep[0x83 & 0x7f].xfer_count;
  270. //volatile uint32_t *xfer_len = &hpcd->IN_ep[0x83 & 0x7f].xfer_len;
  271. USB_OTG_GlobalTypeDef *USBx = hpcd->Instance;
  272. while (
  273. // *xfer_count < *xfer_len // using this works
  274. // (USBx_INEP(3)->DIEPTSIZ & USB_OTG_DIEPTSIZ_XFRSIZ) // using this works
  275. && HAL_GetTick() - start <= 2000) {
  276. __WFI(); // enter sleep mode, waiting for interrupt
  277. }
  278. }
  279. */
  280. }
  281. cdc->tx_buf[cdc->tx_buf_ptr_in] = buf[i];
  282. cdc->tx_buf_ptr_in = (cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1);
  283. }
  284. }
  285. // Returns number of bytes in the rx buffer.
  286. int usbd_cdc_rx_num(usbd_cdc_itf_t *cdc) {
  287. int32_t rx_waiting = (int32_t)cdc->rx_buf_put - (int32_t)cdc->rx_buf_get;
  288. if (rx_waiting < 0) {
  289. rx_waiting += USBD_CDC_RX_DATA_SIZE;
  290. }
  291. return rx_waiting;
  292. }
  293. // timout in milliseconds.
  294. // Returns number of bytes read from the device.
  295. int usbd_cdc_rx(usbd_cdc_itf_t *cdc, uint8_t *buf, uint32_t len, uint32_t timeout) {
  296. // loop to read bytes
  297. for (uint32_t i = 0; i < len; i++) {
  298. // Wait until we have at least 1 byte to read
  299. uint32_t start = HAL_GetTick();
  300. while (cdc->rx_buf_put == cdc->rx_buf_get) {
  301. // Wraparound of tick is taken care of by 2's complement arithmetic.
  302. if (HAL_GetTick() - start >= timeout) {
  303. // timeout
  304. return i;
  305. }
  306. if (query_irq() == IRQ_STATE_DISABLED) {
  307. // IRQs disabled so buffer will never be filled; return immediately
  308. return i;
  309. }
  310. __WFI(); // enter sleep mode, waiting for interrupt
  311. }
  312. // Copy byte from device to user buffer
  313. buf[i] = cdc->rx_user_buf[cdc->rx_buf_get];
  314. cdc->rx_buf_get = (cdc->rx_buf_get + 1) & (USBD_CDC_RX_DATA_SIZE - 1);
  315. }
  316. // Success, return number of bytes read
  317. return len;
  318. }
  319. #endif