usbcas.c 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 (lines & CDC_CONTROL_LINE_IN_DCD)
  84. PORTB &= ~(1U << 0);
  85. else
  86. PORTB |= (1U << 0);
  87. if (forced || CDCInterfaceInfo->State.ControlLineStates.DeviceToHost != lines) {
  88. CDCInterfaceInfo->State.ControlLineStates.DeviceToHost = lines;
  89. CDC_Device_SendControlLineStateChange(CDCInterfaceInfo);
  90. }
  91. }
  92. /** Main program entry point. This routine contains the overall program flow, including initial
  93. * setup of all components and the main program loop.
  94. */
  95. int main(void)
  96. {
  97. int8_t hinybble = -1;
  98. SetupHardware();
  99. RingBuffer_InitBuffer(&USBtoCAS_Buffer, USBtoCAS_Buffer_Data, sizeof(USBtoCAS_Buffer_Data));
  100. RingBuffer_InitBuffer(&CAStoUSB_Buffer, CAStoUSB_Buffer_Data, sizeof(CAStoUSB_Buffer_Data));
  101. GlobalInterruptEnable();
  102. for (;;)
  103. {
  104. /* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
  105. if (!(RingBuffer_IsFull(&USBtoCAS_Buffer)))
  106. {
  107. int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
  108. /* Store received byte into the USART transmit buffer */
  109. if (!(ReceivedByte < 0))
  110. RingBuffer_Insert(&USBtoCAS_Buffer, ReceivedByte);
  111. }
  112. uint16_t BufferCount = RingBuffer_GetCount(&CAStoUSB_Buffer);
  113. if (BufferCount)
  114. {
  115. Endpoint_SelectEndpoint(VirtualSerial_CDC_Interface.Config.DataINEndpoint.Address);
  116. /* Check if a packet is already enqueued to the host - if so, we shouldn't try to send more data
  117. * until it completes as there is a chance nothing is listening and a lengthy timeout could occur */
  118. if (Endpoint_IsINReady())
  119. {
  120. /* Never send more than one bank size less one byte to the host at a time, so that we don't block
  121. * while a Zero Length Packet (ZLP) to terminate the transfer is sent if the host isn't listening */
  122. uint8_t BytesToSend = MIN(BufferCount, (CDC_TXRX_EPSIZE - 1));
  123. /* Read bytes from the USART receive buffer into the USB IN endpoint */
  124. while (BytesToSend--)
  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(&CAStoUSB_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(&CAStoUSB_Buffer);
  134. }
  135. }
  136. }
  137. /* Transmit the next data nybble if we can */
  138. if (fmtx_send_ready()) {
  139. if (hinybble >= 0) {
  140. /* Send high nybble of previous data */
  141. fmtx_send_nybble(hinybble);
  142. hinybble = -1;
  143. } else if (!RingBuffer_IsEmpty(&USBtoCAS_Buffer)) {
  144. /* Send low nybble of new data */
  145. hinybble = fmtx_send_nybble(RingBuffer_Remove(&USBtoCAS_Buffer));
  146. }
  147. }
  148. /* Update modem flags if needed */
  149. update_modem_status(&VirtualSerial_CDC_Interface, false);
  150. CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
  151. USB_USBTask();
  152. }
  153. }
  154. static uint32_t current_baudrate = CAS_BAUDRATE_ABC80;
  155. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  156. void SetupHardware(void)
  157. {
  158. #if (ARCH == ARCH_AVR8)
  159. /* Disable watchdog if enabled by bootloader/fuses */
  160. MCUSR &= ~(1 << WDRF);
  161. wdt_disable();
  162. /* Disable clock division */
  163. clock_prescale_set(clock_div_1);
  164. #endif
  165. /* Hardware Initialization */
  166. USB_Init();
  167. /* PORTB: PB0 - RXLED, PB4 - Relay, PB5 - relay out */
  168. PORTB = (1 << 0) | (1 << 4);
  169. DDRB = ~(1 << 4);
  170. /* Initialize transmitter (and receiver) */
  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. #if 0
  195. /** ISR to manage the reception of data from the serial port, placing received bytes into a circular buffer
  196. * for later transmission to the host.
  197. */
  198. ISR(USART1_RX_vect, ISR_BLOCK)
  199. {
  200. uint8_t ReceivedByte = UDR1;
  201. if ((USB_DeviceState == DEVICE_STATE_Configured) &&
  202. !(RingBuffer_IsFull(&CAStoUSB_Buffer)))
  203. RingBuffer_Insert(&CAStoUSB_Buffer, ReceivedByte);
  204. }
  205. #endif
  206. /** Event handler for the CDC Class driver Line Encoding Changed event.
  207. *
  208. * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced
  209. */
  210. void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
  211. {
  212. uint32_t baudrate = CDCInterfaceInfo->State.LineEncoding.BaudRateBPS;
  213. /* Hack to map ABC80 standard speed to a common baud rate */
  214. if (baudrate == CAS_BAUDRATE_ABC80_FAKE)
  215. baudrate = CAS_BAUDRATE_ABC80;
  216. if (baudrate != current_baudrate) {
  217. current_baudrate = baudrate;
  218. fmtx_drain();
  219. fmtx_init_speed(baudrate);
  220. }
  221. }
  222. /*
  223. * Control lines changed
  224. */
  225. void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
  226. {
  227. /* Indicate the DTR line via RXLED for now */
  228. #if 0
  229. if (CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
  230. PORTB &= ~(1U << 0);
  231. else
  232. PORTB |= (1U << 0);
  233. #endif
  234. }