9ee744ea044c4cba351cb49ed12680a748cf1605
[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 LineEncoding = { .BaudRateBPS = 0,
49 .CharFormat = OneStopBit,
50 .ParityType = Parity_None,
51 .DataBits = 8 };
52
53 #if 0
54 /* NOTE: Here you can set up a standard stream using the created virtual serial port, so that the standard stream functions in
55 * <stdio.h> can be used on the virtual serial port (e.g. fprintf(&USBSerial, "Test"); to print a string).
56 */
57
58 static int CDC_putchar(char c, FILE *stream)
59 {
60 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
61
62 if (!(LineEncoding.BaudRateBPS))
63 return -1;
64
65 while (!(Endpoint_IsReadWriteAllowed()))
66 {
67 if (USB_DeviceState != DEVICE_STATE_Configured)
68 return -1;
69 }
70
71 Endpoint_Write_Byte(c);
72 Endpoint_ClearIN();
73
74 return 0;
75 }
76
77 static int CDC_getchar(FILE *stream)
78 {
79 int c;
80
81 if (!(LineEncoding.BaudRateBPS))
82 return -1;
83
84 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
85
86 for (;;)
87 {
88 while (!(Endpoint_IsReadWriteAllowed()))
89 {
90 if (USB_DeviceState != DEVICE_STATE_Configured)
91 return -1;
92 }
93
94 if (!(Endpoint_BytesInEndpoint()))
95 {
96 Endpoint_ClearOUT();
97 }
98 else
99 {
100 c = Endpoint_Read_Byte();
101 break;
102 }
103 }
104
105 return c;
106 }
107
108 static FILE USBSerial = FDEV_SETUP_STREAM(CDC_putchar, CDC_getchar, _FDEV_SETUP_RW);
109 #endif
110
111 /** Main program entry point. This routine contains the overall program flow, including initial
112 * setup of all components and the main program loop.
113 */
114 int main(void)
115 {
116 SetupHardware();
117
118 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
119
120 for (;;)
121 {
122 CDC_Task();
123 USB_USBTask();
124 }
125 }
126
127 /** Configures the board hardware and chip peripherals for the demo's functionality. */
128 void SetupHardware(void)
129 {
130 /* Disable watchdog if enabled by bootloader/fuses */
131 MCUSR &= ~(1 << WDRF);
132 wdt_disable();
133
134 /* Disable clock division */
135 clock_prescale_set(clock_div_1);
136
137 /* Hardware Initialization */
138 Joystick_Init();
139 LEDs_Init();
140 USB_Init();
141 }
142
143 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
144 * starts the library USB task to begin the enumeration and USB management process.
145 */
146 void EVENT_USB_Device_Connect(void)
147 {
148 /* Indicate USB enumerating */
149 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
150 }
151
152 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
153 * the status LEDs and stops the USB management and CDC management tasks.
154 */
155 void EVENT_USB_Device_Disconnect(void)
156 {
157 /* Indicate USB not ready */
158 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
159 }
160
161 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
162 * of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
163 */
164 void EVENT_USB_Device_ConfigurationChanged(void)
165 {
166 /* Indicate USB connected and ready */
167 LEDs_SetAllLEDs(LEDMASK_USB_READY);
168
169 /* Setup CDC Notification, Rx and Tx Endpoints */
170 if (!(Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
171 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
172 ENDPOINT_BANK_SINGLE)))
173 {
174 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
175 }
176
177 if (!(Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
178 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
179 ENDPOINT_BANK_SINGLE)))
180 {
181 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
182 }
183
184 if (!(Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
185 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
186 ENDPOINT_BANK_SINGLE)))
187 {
188 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
189 }
190
191 /* Reset line encoding baud rate so that the host knows to send new values */
192 LineEncoding.BaudRateBPS = 0;
193 }
194
195 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific
196 * control requests that are not handled internally by the USB library (including the CDC control commands,
197 * which are all issued via the control endpoint), so that they can be handled appropriately for the application.
198 */
199 void EVENT_USB_Device_UnhandledControlRequest(void)
200 {
201 /* Process CDC specific control requests */
202 switch (USB_ControlRequest.bRequest)
203 {
204 case REQ_GetLineEncoding:
205 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
206 {
207 /* Acknowledge the SETUP packet, ready for data transfer */
208 Endpoint_ClearSETUP();
209
210 /* Write the line coding data to the control endpoint */
211 Endpoint_Write_Control_Stream_LE(&LineEncoding, sizeof(CDC_Line_Coding_t));
212
213 /* Finalize the stream transfer to send the last packet or clear the host abort */
214 Endpoint_ClearOUT();
215 }
216
217 break;
218 case REQ_SetLineEncoding:
219 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
220 {
221 /* Acknowledge the SETUP packet, ready for data transfer */
222 Endpoint_ClearSETUP();
223
224 /* Read the line coding data in from the host into the global struct */
225 Endpoint_Read_Control_Stream_LE(&LineEncoding, sizeof(CDC_Line_Coding_t));
226
227 /* Finalize the stream transfer to clear the last packet from the host */
228 Endpoint_ClearIN();
229 }
230
231 break;
232 case REQ_SetControlLineState:
233 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
234 {
235 /* Acknowledge the SETUP packet, ready for data transfer */
236 Endpoint_ClearSETUP();
237
238 /* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake
239 lines. The mask is read in from the wValue parameter in USB_ControlRequest, and can be masked against the
240 CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code:
241 */
242
243 Endpoint_ClearStatusStage();
244 }
245
246 break;
247 }
248 }
249
250 /** Function to manage CDC data transmission and reception to and from the host. */
251 void CDC_Task(void)
252 {
253 char* ReportString = NULL;
254 uint8_t JoyStatus_LCL = Joystick_GetStatus();
255 static bool ActionSent = false;
256 char* JoystickStrings[] =
257 {
258 "Joystick Up\r\n",
259 "Joystick Down\r\n",
260 "Joystick Left\r\n",
261 "Joystick Right\r\n",
262 "Joystick Pressed\r\n",
263 };
264
265 /* Device must be connected and configured for the task to run */
266 if (USB_DeviceState != DEVICE_STATE_Configured)
267 return;
268
269 #if 0
270 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232
271 * handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code:
272 */
273 USB_Notification_Header_t Notification = (USB_Notification_Header_t)
274 {
275 .NotificationType = (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE),
276 .Notification = NOTIF_SerialState,
277 .wValue = 0,
278 .wIndex = 0,
279 .wLength = sizeof(uint16_t),
280 };
281
282 uint16_t LineStateMask;
283
284 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host
285
286 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM);
287 Endpoint_Write_Stream_LE(&Notification, sizeof(Notification));
288 Endpoint_Write_Stream_LE(&LineStateMask, sizeof(LineStateMask));
289 Endpoint_ClearIN();
290 #endif
291
292 /* Determine if a joystick action has occurred */
293 if (JoyStatus_LCL & JOY_UP)
294 ReportString = JoystickStrings[0];
295 else if (JoyStatus_LCL & JOY_DOWN)
296 ReportString = JoystickStrings[1];
297 else if (JoyStatus_LCL & JOY_LEFT)
298 ReportString = JoystickStrings[2];
299 else if (JoyStatus_LCL & JOY_RIGHT)
300 ReportString = JoystickStrings[3];
301 else if (JoyStatus_LCL & JOY_PRESS)
302 ReportString = JoystickStrings[4];
303
304 /* Flag management - Only allow one string to be sent per action */
305 if (ReportString == NULL)
306 {
307 ActionSent = false;
308 }
309 else if ((ActionSent == false) && LineEncoding.BaudRateBPS)
310 {
311 ActionSent = true;
312
313 /* Select the Serial Tx Endpoint */
314 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
315
316 /* Write the String to the Endpoint */
317 Endpoint_Write_Stream_LE(ReportString, strlen(ReportString));
318
319 /* Remember if the packet to send completely fills the endpoint */
320 bool IsFull = (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE);
321
322 /* Finalize the stream transfer to send the last packet */
323 Endpoint_ClearIN();
324
325 /* If the last packet filled the endpoint, send an empty packet to release the buffer on
326 * the receiver (otherwise all data will be cached until a non-full packet is received) */
327 if (IsFull)
328 {
329 /* Wait until the endpoint is ready for another packet */
330 while (!(Endpoint_IsINReady()))
331 {
332 if (USB_DeviceState == DEVICE_STATE_Unattached)
333 return;
334 }
335
336 /* Send an empty packet to ensure that the host does not buffer data sent to it */
337 Endpoint_ClearIN();
338 }
339 }
340
341 /* Select the Serial Rx Endpoint */
342 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
343
344 /* Throw away any received data from the host */
345 if (Endpoint_IsOUTReceived())
346 Endpoint_ClearOUT();
347 }