XPLAINBridge.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2018.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2018 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * Main source file for the XPLAINBridge project. This file contains the main tasks of
  29. * the project and is responsible for the initial application hardware configuration.
  30. */
  31. #include "XPLAINBridge.h"
  32. /** Current firmware mode, making the device behave as either a programmer or a USART bridge */
  33. bool CurrentFirmwareMode = MODE_USART_BRIDGE;
  34. /** LUFA CDC Class driver interface configuration and state information. This structure is
  35. * passed to all CDC Class driver functions, so that multiple instances of the same class
  36. * within a device can be differentiated from one another.
  37. */
  38. USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
  39. {
  40. .Config =
  41. {
  42. .ControlInterfaceNumber = INTERFACE_ID_CDC_CCI,
  43. .DataINEndpoint =
  44. {
  45. .Address = CDC_TX_EPADDR,
  46. .Size = CDC_TXRX_EPSIZE,
  47. .Banks = 1,
  48. },
  49. .DataOUTEndpoint =
  50. {
  51. .Address = CDC_RX_EPADDR,
  52. .Size = CDC_TXRX_EPSIZE,
  53. .Banks = 1,
  54. },
  55. .NotificationEndpoint =
  56. {
  57. .Address = CDC_NOTIFICATION_EPADDR,
  58. .Size = CDC_NOTIFICATION_EPSIZE,
  59. .Banks = 1,
  60. },
  61. },
  62. };
  63. /** Circular buffer to hold data from the host before it is sent to the device via the serial port. */
  64. RingBuffer_t USBtoUART_Buffer;
  65. /** Underlying data buffer for \ref USBtoUART_Buffer, where the stored bytes are located. */
  66. static uint8_t USBtoUART_Buffer_Data[128];
  67. /** Circular buffer to hold data from the serial port before it is sent to the host. */
  68. RingBuffer_t UARTtoUSB_Buffer;
  69. /** Underlying data buffer for \ref UARTtoUSB_Buffer, where the stored bytes are located. */
  70. static uint8_t UARTtoUSB_Buffer_Data[128];
  71. /** Main program entry point. This routine contains the overall program flow, including initial
  72. * setup of all components and the main program loop.
  73. */
  74. int main(void)
  75. {
  76. SetupHardware();
  77. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  78. GlobalInterruptEnable();
  79. for (;;)
  80. {
  81. if (CurrentFirmwareMode == MODE_USART_BRIDGE)
  82. UARTBridge_Task();
  83. else
  84. AVRISP_Task();
  85. USB_USBTask();
  86. }
  87. }
  88. void AVRISP_Task(void)
  89. {
  90. /* Must be in the configured state for the AVRISP code to process data */
  91. if (USB_DeviceState != DEVICE_STATE_Configured)
  92. return;
  93. V2Params_UpdateParamValues();
  94. Endpoint_SelectEndpoint(AVRISP_DATA_OUT_EPADDR);
  95. /* Check to see if a V2 Protocol command has been received */
  96. if (Endpoint_IsOUTReceived())
  97. {
  98. LEDs_SetAllLEDs(LEDMASK_BUSY);
  99. /* Pass off processing of the V2 Protocol command to the V2 Protocol handler */
  100. V2Protocol_ProcessCommand();
  101. LEDs_SetAllLEDs(LEDMASK_USB_READY);
  102. }
  103. }
  104. void UARTBridge_Task(void)
  105. {
  106. /* Must be in the configured state for the USART Bridge code to process data */
  107. if (USB_DeviceState != DEVICE_STATE_Configured)
  108. return;
  109. /* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
  110. if (!(RingBuffer_IsFull(&USBtoUART_Buffer)))
  111. {
  112. int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
  113. /* Read bytes from the USB OUT endpoint into the UART transmit buffer */
  114. if (!(ReceivedByte < 0))
  115. RingBuffer_Insert(&USBtoUART_Buffer, ReceivedByte);
  116. }
  117. /* Check if the UART receive buffer flush timer has expired or buffer is nearly full */
  118. uint16_t BufferCount = RingBuffer_GetCount(&UARTtoUSB_Buffer);
  119. if ((TIFR0 & (1 << TOV0)) || (BufferCount > 200))
  120. {
  121. /* Clear flush timer expiry flag */
  122. TIFR0 |= (1 << TOV0);
  123. /* Read bytes from the USART receive buffer into the USB IN endpoint */
  124. while (BufferCount--)
  125. {
  126. /* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
  127. if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
  128. RingBuffer_Peek(&UARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
  129. {
  130. break;
  131. }
  132. /* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
  133. RingBuffer_Remove(&UARTtoUSB_Buffer);
  134. }
  135. }
  136. CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
  137. }
  138. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  139. void SetupHardware(void)
  140. {
  141. #if (ARCH == ARCH_AVR8)
  142. /* Disable watchdog if enabled by bootloader/fuses */
  143. MCUSR &= ~(1 << WDRF);
  144. wdt_disable();
  145. /* Disable clock division */
  146. clock_prescale_set(clock_div_1);
  147. #endif
  148. /* Disable JTAG debugging */
  149. MCUCR |= (1 << JTD);
  150. MCUCR |= (1 << JTD);
  151. /* Enable pull-up on the JTAG TDI pin so we can use it to select the mode */
  152. PORTF |= (1 << 7);
  153. Delay_MS(10);
  154. /* Select the firmware mode based on the JTD pin's value */
  155. CurrentFirmwareMode = (PINF & (1 << 7)) ? MODE_USART_BRIDGE : MODE_PDI_PROGRAMMER;
  156. /* Re-enable JTAG debugging */
  157. MCUCR &= ~(1 << JTD);
  158. MCUCR &= ~(1 << JTD);
  159. /* Hardware Initialization */
  160. SoftUART_Init();
  161. LEDs_Init();
  162. #if defined(RESET_TOGGLES_LIBUSB_COMPAT)
  163. UpdateCurrentCompatibilityMode();
  164. #endif
  165. /* USB Stack Initialization */
  166. USB_Init();
  167. }
  168. /** Event handler for the library USB Configuration Changed event. */
  169. void EVENT_USB_Device_ConfigurationChanged(void)
  170. {
  171. bool ConfigSuccess = true;
  172. /* Configure the device endpoints according to the selected mode */
  173. if (CurrentFirmwareMode == MODE_USART_BRIDGE)
  174. {
  175. ConfigSuccess &= CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);
  176. /* Configure the UART flush timer - run at Fcpu/1024 for maximum interval before overflow */
  177. TCCR0B = ((1 << CS02) | (1 << CS00));
  178. /* Initialize ring buffers used to hold serial data between USB and software UART interfaces */
  179. RingBuffer_InitBuffer(&USBtoUART_Buffer, USBtoUART_Buffer_Data, sizeof(USBtoUART_Buffer_Data));
  180. RingBuffer_InitBuffer(&UARTtoUSB_Buffer, UARTtoUSB_Buffer_Data, sizeof(UARTtoUSB_Buffer_Data));
  181. /* Start the software USART */
  182. SoftUART_Init();
  183. }
  184. else
  185. {
  186. ConfigSuccess &= Endpoint_ConfigureEndpoint(AVRISP_DATA_OUT_EPADDR, EP_TYPE_BULK, AVRISP_DATA_EPSIZE, 1);
  187. if ((AVRISP_DATA_IN_EPADDR & ENDPOINT_EPNUM_MASK) != (AVRISP_DATA_OUT_EPADDR & ENDPOINT_EPNUM_MASK))
  188. ConfigSuccess &= Endpoint_ConfigureEndpoint(AVRISP_DATA_IN_EPADDR, EP_TYPE_BULK, AVRISP_DATA_EPSIZE, 1);
  189. /* Configure the V2 protocol packet handler */
  190. V2Protocol_Init();
  191. }
  192. LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
  193. }
  194. /** Event handler for the library USB Control Request reception event. */
  195. void EVENT_USB_Device_ControlRequest(void)
  196. {
  197. if (CurrentFirmwareMode == MODE_USART_BRIDGE)
  198. CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
  199. }
  200. /** Event handler for the library USB Connection event. */
  201. void EVENT_USB_Device_Connect(void)
  202. {
  203. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  204. }
  205. /** Event handler for the library USB Disconnection event. */
  206. void EVENT_USB_Device_Disconnect(void)
  207. {
  208. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  209. }
  210. /** Event handler for the CDC Class driver Line Encoding Changed event.
  211. *
  212. * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced
  213. */
  214. void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
  215. {
  216. /* Change the software UART's baud rate to match the new baud rate */
  217. SoftUART_SetBaud(CDCInterfaceInfo->State.LineEncoding.BaudRateBPS);
  218. }
  219. /** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
  220. * documentation) by the application code so that the address and size of a requested descriptor can be given
  221. * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
  222. * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
  223. * USB host.
  224. *
  225. * \param[in] wValue Descriptor type and index to retrieve
  226. * \param[in] wIndex Sub-index to retrieve (such as a localized string language)
  227. * \param[out] DescriptorAddress Address of the retrieved descriptor
  228. *
  229. * \return Length of the retrieved descriptor in bytes, or NO_DESCRIPTOR if the descriptor was not found
  230. */
  231. uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
  232. const uint16_t wIndex,
  233. const void** const DescriptorAddress)
  234. {
  235. /* Return the correct descriptors based on the selected mode */
  236. if (CurrentFirmwareMode == MODE_USART_BRIDGE)
  237. return USART_GetDescriptor(wValue, wIndex, DescriptorAddress);
  238. else
  239. return AVRISP_GetDescriptor(wValue, wIndex, DescriptorAddress);
  240. }