Applied STATIC_ENDPOINT_CONFIGURATION and FIXED_CONTROL_SIZE tokens to all Device...
[pub/USBasp.git] / Demos / Device / 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 /* Scheduler Task List */
40 TASK_LIST
41 {
42 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
43 { .Task = CDC_Task , .TaskStatus = TASK_STOP },
44 };
45
46 /* Globals: */
47 /** Contains the current baud rate and other settings of the virtual serial port. While this demo does not use
48 * the physical USART and thus does not use these settings, they must still be retained and returned to the host
49 * upon request or the host will assume the device is non-functional.
50 *
51 * These values are set by the host via a class-specific request, however they are not required to be used accurately.
52 * It is possible to completely ignore these value or use other settings as the host is completely unaware of the physical
53 * serial link characteristics and instead sends and receives data in endpoint streams.
54 */
55 CDC_Line_Coding_t LineCoding = { .BaudRateBPS = 9600,
56 .CharFormat = OneStopBit,
57 .ParityType = Parity_None,
58 .DataBits = 8 };
59
60 /** String to print through the virtual serial port when the joystick is pressed upwards. */
61 char JoystickUpString[] = "Joystick Up\r\n";
62
63 /** String to print through the virtual serial port when the joystick is pressed downward. */
64 char JoystickDownString[] = "Joystick Down\r\n";
65
66 /** String to print through the virtual serial port when the joystick is pressed left. */
67 char JoystickLeftString[] = "Joystick Left\r\n";
68
69 /** String to print through the virtual serial port when the joystick is pressed right. */
70 char JoystickRightString[] = "Joystick Right\r\n";
71
72 /** String to print through the virtual serial port when the joystick is pressed inwards. */
73 char JoystickPressedString[] = "Joystick Pressed\r\n";
74
75 /** Main program entry point. This routine configures the hardware required by the application, then
76 * starts the scheduler to run the application tasks.
77 */
78 int main(void)
79 {
80 /* Disable watchdog if enabled by bootloader/fuses */
81 MCUSR &= ~(1 << WDRF);
82 wdt_disable();
83
84 /* Disable clock division */
85 clock_prescale_set(clock_div_1);
86
87 /* Hardware Initialization */
88 Joystick_Init();
89 LEDs_Init();
90
91 /* Indicate USB not ready */
92 UpdateStatus(Status_USBNotReady);
93
94 /* Initialize Scheduler so that it can be used */
95 Scheduler_Init();
96
97 /* Initialize USB Subsystem */
98 USB_Init();
99
100 /* Scheduling - routine never returns, so put this last in the main function */
101 Scheduler_Start();
102 }
103
104 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
105 * starts the library USB task to begin the enumeration and USB management process.
106 */
107 EVENT_HANDLER(USB_Connect)
108 {
109 /* Start USB management task */
110 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
111
112 /* Indicate USB enumerating */
113 UpdateStatus(Status_USBEnumerating);
114 }
115
116 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
117 * the status LEDs and stops the USB management and CDC management tasks.
118 */
119 EVENT_HANDLER(USB_Disconnect)
120 {
121 /* Stop running CDC and USB management tasks */
122 Scheduler_SetTaskMode(CDC_Task, TASK_STOP);
123 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
124
125 /* Indicate USB not ready */
126 UpdateStatus(Status_USBNotReady);
127 }
128
129 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
130 * of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
131 */
132 EVENT_HANDLER(USB_ConfigurationChanged)
133 {
134 /* Setup CDC Notification, Rx and Tx Endpoints */
135 Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
136 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
137 ENDPOINT_BANK_SINGLE);
138
139 Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
140 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
141 ENDPOINT_BANK_SINGLE);
142
143 Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
144 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
145 ENDPOINT_BANK_SINGLE);
146
147 /* Indicate USB connected and ready */
148 UpdateStatus(Status_USBReady);
149
150 /* Start CDC task */
151 Scheduler_SetTaskMode(CDC_Task, TASK_RUN);
152 }
153
154 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
155 * control requests that are not handled internally by the USB library (including the CDC control commands,
156 * which are all issued via the control endpoint), so that they can be handled appropriately for the application.
157 */
158 EVENT_HANDLER(USB_UnhandledControlPacket)
159 {
160 uint8_t* LineCodingData = (uint8_t*)&LineCoding;
161
162 /* Process CDC specific control requests */
163 switch (USB_ControlRequest.bRequest)
164 {
165 case REQ_GetLineEncoding:
166 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
167 {
168 /* Acknowledge the SETUP packet, ready for data transfer */
169 Endpoint_ClearSETUP();
170
171 /* Write the line coding data to the control endpoint */
172 Endpoint_Write_Control_Stream_LE(LineCodingData, sizeof(CDC_Line_Coding_t));
173
174 /* Finalize the stream transfer to send the last packet or clear the host abort */
175 Endpoint_ClearOUT();
176 }
177
178 break;
179 case REQ_SetLineEncoding:
180 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
181 {
182 /* Acknowledge the SETUP packet, ready for data transfer */
183 Endpoint_ClearSETUP();
184
185 /* Read the line coding data in from the host into the global struct */
186 Endpoint_Read_Control_Stream_LE(LineCodingData, sizeof(CDC_Line_Coding_t));
187
188 /* Finalize the stream transfer to clear the last packet from the host */
189 Endpoint_ClearIN();
190 }
191
192 break;
193 case REQ_SetControlLineState:
194 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
195 {
196 /* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake
197 lines. The mask is read in from the wValue parameter in USB_ControlRequest, and can be masked against the
198 CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code:
199 */
200
201 /* Acknowledge the SETUP packet, ready for data transfer */
202 Endpoint_ClearSETUP();
203
204 /* Acknowledge status stage */
205 while (!(Endpoint_IsINReady()));
206 Endpoint_ClearIN();
207 }
208
209 break;
210 }
211 }
212
213 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
214 * log to a serial port, or anything else that is suitable for status updates.
215 *
216 * \param CurrentStatus Current status of the system, from the CDC_StatusCodes_t enum
217 */
218 void UpdateStatus(uint8_t CurrentStatus)
219 {
220 uint8_t LEDMask = LEDS_NO_LEDS;
221
222 /* Set the LED mask to the appropriate LED mask based on the given status code */
223 switch (CurrentStatus)
224 {
225 case Status_USBNotReady:
226 LEDMask = (LEDS_LED1);
227 break;
228 case Status_USBEnumerating:
229 LEDMask = (LEDS_LED1 | LEDS_LED2);
230 break;
231 case Status_USBReady:
232 LEDMask = (LEDS_LED2 | LEDS_LED4);
233 break;
234 }
235
236 /* Set the board LEDs to the new LED mask */
237 LEDs_SetAllLEDs(LEDMask);
238 }
239
240 /** Function to manage CDC data transmission and reception to and from the host. */
241 TASK(CDC_Task)
242 {
243 char* ReportString = NULL;
244 uint8_t JoyStatus_LCL = Joystick_GetStatus();
245 static bool ActionSent = false;
246
247 #if 0
248 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232
249 handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code:
250 */
251 USB_Notification_Header_t Notification = (USB_Notification_Header_t)
252 {
253 .NotificationType = (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE),
254 .Notification = NOTIF_SerialState,
255 .wValue = 0,
256 .wIndex = 0,
257 .wLength = sizeof(uint16_t),
258 };
259
260 uint16_t LineStateMask;
261
262 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host
263
264 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM);
265 Endpoint_Write_Stream_LE(&Notification, sizeof(Notification));
266 Endpoint_Write_Stream_LE(&LineStateMask, sizeof(LineStateMask));
267 Endpoint_ClearIN();
268 #endif
269
270 /* Determine if a joystick action has occurred */
271 if (JoyStatus_LCL & JOY_UP)
272 ReportString = JoystickUpString;
273 else if (JoyStatus_LCL & JOY_DOWN)
274 ReportString = JoystickDownString;
275 else if (JoyStatus_LCL & JOY_LEFT)
276 ReportString = JoystickLeftString;
277 else if (JoyStatus_LCL & JOY_RIGHT)
278 ReportString = JoystickRightString;
279 else if (JoyStatus_LCL & JOY_PRESS)
280 ReportString = JoystickPressedString;
281
282 /* Flag management - Only allow one string to be sent per action */
283 if (ReportString == NULL)
284 {
285 ActionSent = false;
286 }
287 else if (ActionSent == false)
288 {
289 ActionSent = true;
290
291 /* Select the Serial Tx Endpoint */
292 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
293
294 /* Write the String to the Endpoint */
295 Endpoint_Write_Stream_LE(ReportString, strlen(ReportString));
296
297 /* Remember if the packet to send completely fills the endpoint */
298 bool IsFull = (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE);
299
300 /* Finalize the stream transfer to send the last packet */
301 Endpoint_ClearIN();
302
303 /* If the last packet filled the endpoint, send an empty packet to release the buffer on
304 * the receiver (otherwise all data will be cached until a non-full packet is received) */
305 if (IsFull)
306 {
307 /* Wait until the endpoint is ready for another packet */
308 while (!(Endpoint_IsINReady()));
309
310 /* Send an empty packet to ensure that the host does not buffer data sent to it */
311 Endpoint_ClearIN();
312 }
313 }
314
315 /* Select the Serial Rx Endpoint */
316 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
317
318 /* Throw away any received data from the host */
319 if (Endpoint_IsOUTReceived())
320 Endpoint_ClearOUT();
321 }