Fix issue with CDC device demos causing broken communications when the device tries...
[pub/USBasp.git] / Demos / Device / LowLevel / CDC / CDC.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /** \file
32 *
33 * Main source file for the CDC demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #include "CDC.h"
38
39 /* Globals: */
40 /** Contains the current baud rate and other settings of the virtual serial port. While this demo does not use
41 * the physical USART and thus does not use these settings, they must still be retained and returned to the host
42 * upon request or the host will assume the device is non-functional.
43 *
44 * These values are set by the host via a class-specific request, however they are not required to be used accurately.
45 * It is possible to completely ignore these value or use other settings as the host is completely unaware of the physical
46 * serial link characteristics and instead sends and receives data in endpoint streams.
47 */
48 CDC_Line_Coding_t LineCoding = { .BaudRateBPS = 9600,
49 .CharFormat = OneStopBit,
50 .ParityType = Parity_None,
51 .DataBits = 8 };
52
53 /** Indicates if the host has set the device line encoding. Until the line encoding is set by the host, the device should
54 * not attempt to send any bytes.
55 */
56 bool LineEncodingSet = false;
57
58
59 #if 0
60 /* NOTE: Here you can set up a standard stream using the created virtual serial port, so that the standard stream functions in
61 * <stdio.h> can be used on the virtual serial port (e.g. fprintf(&USBSerial, "Test"); to print a string).
62 */
63
64 static int CDC_putchar(char c, FILE *stream)
65 {
66 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
67
68 if (!(LineEncodingSet))
69 return -1;
70
71 while (!(Endpoint_IsReadWriteAllowed()))
72 {
73 if (USB_DeviceState != DEVICE_STATE_Configured)
74 return -1;
75 }
76
77 Endpoint_Write_Byte(c);
78 Endpoint_ClearIN();
79
80 return 0;
81 }
82
83 static int CDC_getchar(FILE *stream)
84 {
85 int c;
86
87 if (!(LineEncodingSet))
88 return -1;
89
90 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
91
92 for (;;)
93 {
94 while (!(Endpoint_IsReadWriteAllowed()))
95 {
96 if (USB_DeviceState != DEVICE_STATE_Configured)
97 return -1;
98 }
99
100 if (!(Endpoint_BytesInEndpoint()))
101 {
102 Endpoint_ClearOUT();
103 }
104 else
105 {
106 c = Endpoint_Read_Byte();
107 break;
108 }
109 }
110
111 return c;
112 }
113
114 static FILE USBSerial = FDEV_SETUP_STREAM(CDC_putchar, CDC_getchar, _FDEV_SETUP_RW);
115 #endif
116
117 /** Main program entry point. This routine contains the overall program flow, including initial
118 * setup of all components and the main program loop.
119 */
120 int main(void)
121 {
122 SetupHardware();
123
124 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
125
126 for (;;)
127 {
128 CDC_Task();
129 USB_USBTask();
130 }
131 }
132
133 /** Configures the board hardware and chip peripherals for the demo's functionality. */
134 void SetupHardware(void)
135 {
136 /* Disable watchdog if enabled by bootloader/fuses */
137 MCUSR &= ~(1 << WDRF);
138 wdt_disable();
139
140 /* Disable clock division */
141 clock_prescale_set(clock_div_1);
142
143 /* Hardware Initialization */
144 Joystick_Init();
145 LEDs_Init();
146 USB_Init();
147 }
148
149 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
150 * starts the library USB task to begin the enumeration and USB management process.
151 */
152 void EVENT_USB_Connect(void)
153 {
154 /* Indicate USB enumerating */
155 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
156 }
157
158 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
159 * the status LEDs and stops the USB management and CDC management tasks.
160 */
161 void EVENT_USB_Disconnect(void)
162 {
163 /* Indicate USB not ready */
164 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
165 }
166
167 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
168 * of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
169 */
170 void EVENT_USB_ConfigurationChanged(void)
171 {
172 /* Indicate USB connected and ready */
173 LEDs_SetAllLEDs(LEDMASK_USB_READY);
174
175 /* Setup CDC Notification, Rx and Tx Endpoints */
176 if (!(Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
177 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
178 ENDPOINT_BANK_SINGLE)))
179 {
180 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
181 }
182
183 if (!(Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
184 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
185 ENDPOINT_BANK_SINGLE)))
186 {
187 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
188 }
189
190 if (!(Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
191 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
192 ENDPOINT_BANK_SINGLE)))
193 {
194 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
195 }
196 }
197
198 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
199 * control requests that are not handled internally by the USB library (including the CDC control commands,
200 * which are all issued via the control endpoint), so that they can be handled appropriately for the application.
201 */
202 void EVENT_USB_UnhandledControlPacket(void)
203 {
204 uint8_t* LineCodingData = (uint8_t*)&LineCoding;
205
206 /* Process CDC specific control requests */
207 switch (USB_ControlRequest.bRequest)
208 {
209 case REQ_GetLineEncoding:
210 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
211 {
212 /* Acknowledge the SETUP packet, ready for data transfer */
213 Endpoint_ClearSETUP();
214
215 /* Write the line coding data to the control endpoint */
216 Endpoint_Write_Control_Stream_LE(LineCodingData, sizeof(CDC_Line_Coding_t));
217
218 /* Finalize the stream transfer to send the last packet or clear the host abort */
219 Endpoint_ClearOUT();
220 }
221
222 break;
223 case REQ_SetLineEncoding:
224 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
225 {
226 /* Acknowledge the SETUP packet, ready for data transfer */
227 Endpoint_ClearSETUP();
228
229 /* Read the line coding data in from the host into the global struct */
230 Endpoint_Read_Control_Stream_LE(LineCodingData, sizeof(CDC_Line_Coding_t));
231
232 /* Indicate that the line encoding has been set, and the device may now send data */
233 LineEncodingSet = true;
234
235 /* Finalize the stream transfer to clear the last packet from the host */
236 Endpoint_ClearIN();
237 }
238
239 break;
240 case REQ_SetControlLineState:
241 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
242 {
243 /* Acknowledge the SETUP packet, ready for data transfer */
244 Endpoint_ClearSETUP();
245
246 /* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake
247 lines. The mask is read in from the wValue parameter in USB_ControlRequest, and can be masked against the
248 CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code:
249 */
250
251 Endpoint_ClearStatusStage();
252 }
253
254 break;
255 }
256 }
257
258 /** Function to manage CDC data transmission and reception to and from the host. */
259 void CDC_Task(void)
260 {
261 char* ReportString = NULL;
262 uint8_t JoyStatus_LCL = Joystick_GetStatus();
263 static bool ActionSent = false;
264 char* JoystickStrings[] =
265 {
266 "Joystick Up\r\n",
267 "Joystick Down\r\n",
268 "Joystick Left\r\n",
269 "Joystick Right\r\n",
270 "Joystick Pressed\r\n",
271 };
272
273 /* Device must be connected and configured for the task to run */
274 if (USB_DeviceState != DEVICE_STATE_Configured)
275 return;
276
277 #if 0
278 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232
279 * handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code:
280 */
281 USB_Notification_Header_t Notification = (USB_Notification_Header_t)
282 {
283 .NotificationType = (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE),
284 .Notification = NOTIF_SerialState,
285 .wValue = 0,
286 .wIndex = 0,
287 .wLength = sizeof(uint16_t),
288 };
289
290 uint16_t LineStateMask;
291
292 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host
293
294 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM);
295 Endpoint_Write_Stream_LE(&Notification, sizeof(Notification));
296 Endpoint_Write_Stream_LE(&LineStateMask, sizeof(LineStateMask));
297 Endpoint_ClearIN();
298 #endif
299
300 /* Determine if a joystick action has occurred */
301 if (JoyStatus_LCL & JOY_UP)
302 ReportString = JoystickStrings[0];
303 else if (JoyStatus_LCL & JOY_DOWN)
304 ReportString = JoystickStrings[1];
305 else if (JoyStatus_LCL & JOY_LEFT)
306 ReportString = JoystickStrings[2];
307 else if (JoyStatus_LCL & JOY_RIGHT)
308 ReportString = JoystickStrings[3];
309 else if (JoyStatus_LCL & JOY_PRESS)
310 ReportString = JoystickStrings[4];
311
312 /* Flag management - Only allow one string to be sent per action */
313 if (ReportString == NULL)
314 {
315 ActionSent = false;
316 }
317 else if ((ActionSent == false) && LineEncodingSet)
318 {
319 ActionSent = true;
320
321 /* Select the Serial Tx Endpoint */
322 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
323
324 /* Write the String to the Endpoint */
325 Endpoint_Write_Stream_LE(ReportString, strlen(ReportString));
326
327 /* Remember if the packet to send completely fills the endpoint */
328 bool IsFull = (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE);
329
330 /* Finalize the stream transfer to send the last packet */
331 Endpoint_ClearIN();
332
333 /* If the last packet filled the endpoint, send an empty packet to release the buffer on
334 * the receiver (otherwise all data will be cached until a non-full packet is received) */
335 if (IsFull)
336 {
337 /* Wait until the endpoint is ready for another packet */
338 while (!(Endpoint_IsINReady()))
339 {
340 if (USB_DeviceState == DEVICE_STATE_Unattached)
341 return;
342 }
343
344 /* Send an empty packet to ensure that the host does not buffer data sent to it */
345 Endpoint_ClearIN();
346 }
347 }
348
349 /* Select the Serial Rx Endpoint */
350 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
351
352 /* Throw away any received data from the host */
353 if (Endpoint_IsOUTReceived())
354 Endpoint_ClearOUT();
355 }