usbcas.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2021.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2021 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 USBtoSerial project. This file contains the main tasks of
  29. * the project and is responsible for the initial application hardware configuration.
  30. */
  31. #include "usbcas.h"
  32. /** Circular buffer to hold data from the host before it is sent to the device via the serial port. */
  33. static RingBuffer_t USBtoCAS_Buffer;
  34. /** Underlying data buffer for \ref USBtoCAS_Buffer, where the stored bytes are located. */
  35. static uint8_t USBtoCAS_Buffer_Data[128];
  36. /** Circular buffer to hold data from the serial port before it is sent to the host. */
  37. static RingBuffer_t CAStoUSB_Buffer;
  38. /** Underlying data buffer for \ref CAStoUSB_Buffer, where the stored bytes are located. */
  39. static uint8_t CAStoUSB_Buffer_Data[128];
  40. /** LUFA CDC Class driver interface configuration and state information. This structure is
  41. * passed to all CDC Class driver functions, so that multiple instances of the same class
  42. * within a device can be differentiated from one another.
  43. */
  44. USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
  45. {
  46. .Config =
  47. {
  48. .ControlInterfaceNumber = INTERFACE_ID_CDC_CCI,
  49. .DataINEndpoint =
  50. {
  51. .Address = CDC_TX_EPADDR,
  52. .Size = CDC_TXRX_EPSIZE,
  53. .Banks = 1,
  54. },
  55. .DataOUTEndpoint =
  56. {
  57. .Address = CDC_RX_EPADDR,
  58. .Size = CDC_TXRX_EPSIZE,
  59. .Banks = 1,
  60. },
  61. .NotificationEndpoint =
  62. {
  63. .Address = CDC_NOTIFICATION_EPADDR,
  64. .Size = CDC_NOTIFICATION_EPSIZE,
  65. .Banks = 1,
  66. },
  67. },
  68. };
  69. /*
  70. * Transmit an FM-modulated signal using the USART in SPI master mode.
  71. * As per ABC standard, this signal is transmitted LSB first.
  72. */
  73. #include "usbcas.h"
  74. /*
  75. * Probe for modem control status bits and send them if changed,
  76. * or if forced...
  77. */
  78. static void update_modem_status(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo, bool forced)
  79. {
  80. uint16_t lines = CDC_CONTROL_LINE_IN_DSR;
  81. if (!(PINB & (1 << 4))) /* Cassette relay active */
  82. lines |= CDC_CONTROL_LINE_IN_DCD;
  83. #if 0
  84. if (lines & CDC_CONTROL_LINE_IN_DCD)
  85. PORTB &= ~(1U << 0);
  86. else
  87. PORTB |= (1U << 0);
  88. #endif
  89. if (forced || CDCInterfaceInfo->State.ControlLineStates.DeviceToHost != lines) {
  90. CDCInterfaceInfo->State.ControlLineStates.DeviceToHost = lines;
  91. CDC_Device_SendControlLineStateChange(CDCInterfaceInfo);
  92. }
  93. }
  94. /* This is called in the main loop, but also any time we are waiting on something... */
  95. void do_usb_task(void)
  96. {
  97. /* Update modem flags if needed */
  98. update_modem_status(&VirtualSerial_CDC_Interface, false);
  99. CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
  100. USB_USBTask();
  101. }
  102. /** Main program entry point. This routine contains the overall program flow, including initial
  103. * setup of all components and the main program loop.
  104. */
  105. int main(void)
  106. {
  107. SetupHardware();
  108. RingBuffer_InitBuffer(&USBtoCAS_Buffer, USBtoCAS_Buffer_Data, sizeof(USBtoCAS_Buffer_Data));
  109. RingBuffer_InitBuffer(&CAStoUSB_Buffer, CAStoUSB_Buffer_Data, sizeof(CAStoUSB_Buffer_Data));
  110. GlobalInterruptEnable();
  111. for (;;)
  112. {
  113. /* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
  114. if (!(RingBuffer_IsFull(&USBtoCAS_Buffer)))
  115. {
  116. int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
  117. /* Store received byte into the USART transmit buffer */
  118. if (!(ReceivedByte < 0)) {
  119. RingBuffer_Insert(&USBtoCAS_Buffer, ReceivedByte);
  120. fmtx_enable(); /* Enable TX interrupt routine if disabled */
  121. }
  122. }
  123. uint16_t BufferCount = RingBuffer_GetCount(&CAStoUSB_Buffer);
  124. if (BufferCount)
  125. {
  126. Endpoint_SelectEndpoint(VirtualSerial_CDC_Interface.Config.DataINEndpoint.Address);
  127. /* Check if a packet is already enqueued to the host - if so, we shouldn't try to send more data
  128. * until it completes as there is a chance nothing is listening and a lengthy timeout could occur */
  129. if (Endpoint_IsINReady())
  130. {
  131. /* Never send more than one bank size less one byte to the host at a time, so that we don't block
  132. * while a Zero Length Packet (ZLP) to terminate the transfer is sent if the host isn't listening */
  133. uint8_t BytesToSend = MIN(BufferCount, (CDC_TXRX_EPSIZE - 1));
  134. /* Read bytes from the USART receive buffer into the USB IN endpoint */
  135. while (BytesToSend--)
  136. {
  137. /* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
  138. if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
  139. RingBuffer_Peek(&CAStoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
  140. {
  141. break;
  142. }
  143. /* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
  144. RingBuffer_Remove(&CAStoUSB_Buffer);
  145. }
  146. }
  147. }
  148. do_usb_task();
  149. }
  150. }
  151. static uint32_t current_baudrate;
  152. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  153. void SetupHardware(void)
  154. {
  155. #if (ARCH == ARCH_AVR8)
  156. /* Disable watchdog if enabled by bootloader/fuses */
  157. MCUSR &= ~(1 << WDRF);
  158. wdt_disable();
  159. /* Disable clock division */
  160. clock_prescale_set(clock_div_1);
  161. #endif
  162. /* Hardware Initialization */
  163. USB_Init();
  164. /* PORTB: PB0 - RXLED, PB4 - Relay (pullup), PB5 - relay out */
  165. PORTB |= (1 << 0) | (1 << 4);
  166. DDRB = (DDRB & ~((1 << 4))) | ((1 << 0) | (1 << 5));
  167. /* Initialize receiver and transmitter */
  168. fmrx_init();
  169. current_baudrate = fmtx_real_baudrate(0);
  170. fmrx_set_speed(current_baudrate);
  171. fmtx_init_speed(current_baudrate);
  172. }
  173. /** Event handler for the library USB Connection event. */
  174. void EVENT_USB_Device_Connect(void)
  175. {
  176. }
  177. /** Event handler for the library USB Disconnection event. */
  178. void EVENT_USB_Device_Disconnect(void)
  179. {
  180. }
  181. /** Event handler for the library USB Configuration Changed event. */
  182. void EVENT_USB_Device_ConfigurationChanged(void)
  183. {
  184. bool success = true;
  185. success &= CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);
  186. if (success)
  187. update_modem_status(&VirtualSerial_CDC_Interface, true);
  188. }
  189. /** Event handler for the library USB Control Request reception event. */
  190. void EVENT_USB_Device_ControlRequest(void)
  191. {
  192. CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
  193. }
  194. /*
  195. * Called from the demodulation ISR to push a new byte into the buffer
  196. */
  197. void fmrx_recv_byte(uint8_t byte)
  198. {
  199. if (USB_DeviceState == DEVICE_STATE_Configured &&
  200. !RingBuffer_IsFull(&CAStoUSB_Buffer))
  201. RingBuffer_Insert(&CAStoUSB_Buffer, byte);
  202. }
  203. /*
  204. * Called from the transmit register empty ISR to fetch a new byte;
  205. * returns -1 if the ring buffer is empty.
  206. */
  207. int fmtx_next_byte(void)
  208. {
  209. if (USB_DeviceState != DEVICE_STATE_Configured ||
  210. RingBuffer_IsEmpty(&USBtoCAS_Buffer))
  211. return -1;
  212. return RingBuffer_Remove(&USBtoCAS_Buffer);
  213. }
  214. /** Event handler for the CDC Class driver Line Encoding Changed event.
  215. *
  216. * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced
  217. */
  218. void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
  219. {
  220. uint32_t baudrate = CDCInterfaceInfo->State.LineEncoding.BaudRateBPS;
  221. if (baudrate == 9600)
  222. baudrate = CAS_BAUDRATE_ABC80;
  223. baudrate = fmtx_real_baudrate(baudrate);
  224. if (1 || baudrate != current_baudrate) {
  225. current_baudrate = baudrate;
  226. fmtx_drain();
  227. fmrx_set_speed(current_baudrate);
  228. fmtx_init_speed(current_baudrate);
  229. }
  230. }
  231. /*
  232. * Control lines changed
  233. */
  234. void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
  235. {
  236. /* Indicate the DTR line via RXLED for now */
  237. #if 0
  238. if (CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
  239. PORTB &= ~(1U << 0);
  240. else
  241. PORTB |= (1U << 0);
  242. #endif
  243. }