Fixed bug in RNDISEthernet and DualCDC demos not using the correct USB_ControlRequest...
[pub/USBasp.git] / Demos / Device / RNDISEthernet / RNDISEthernet.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 RNDISEthernet demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
35 */
36
37 #include "RNDISEthernet.h"
38
39 /* Scheduler Task List */
40 TASK_LIST
41 {
42 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
43 { .Task = Ethernet_Task , .TaskStatus = TASK_STOP },
44 { .Task = TCP_Task , .TaskStatus = TASK_STOP },
45 { .Task = RNDIS_Task , .TaskStatus = TASK_STOP },
46 };
47
48 /** Main program entry point. This routine configures the hardware required by the application, then
49 * starts the scheduler to run the USB management task.
50 */
51 int main(void)
52 {
53 /* Disable watchdog if enabled by bootloader/fuses */
54 MCUSR &= ~(1 << WDRF);
55 wdt_disable();
56
57 /* Disable clock division */
58 clock_prescale_set(clock_div_1);
59
60 /* Hardware Initialization */
61 LEDs_Init();
62 SerialStream_Init(9600, false);
63
64 /* Webserver Initialization */
65 TCP_Init();
66 Webserver_Init();
67
68 printf_P(PSTR("\r\n\r\n****** RNDIS Demo running. ******\r\n"));
69
70 /* Indicate USB not ready */
71 UpdateStatus(Status_USBNotReady);
72
73 /* Initialize Scheduler so that it can be used */
74 Scheduler_Init();
75
76 /* Initialize USB Subsystem */
77 USB_Init();
78
79 /* Scheduling - routine never returns, so put this last in the main function */
80 Scheduler_Start();
81 }
82
83 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
84 * starts the library USB task to begin the enumeration and USB management process.
85 */
86 EVENT_HANDLER(USB_Connect)
87 {
88 /* Start USB management task */
89 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
90
91 /* Indicate USB enumerating */
92 UpdateStatus(Status_USBEnumerating);
93 }
94
95 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
96 * the status LEDs and stops all the relevant tasks.
97 */
98 EVENT_HANDLER(USB_Disconnect)
99 {
100 /* Stop running TCP/IP and USB management tasks */
101 Scheduler_SetTaskMode(RNDIS_Task, TASK_STOP);
102 Scheduler_SetTaskMode(Ethernet_Task, TASK_STOP);
103 Scheduler_SetTaskMode(TCP_Task, TASK_STOP);
104 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
105
106 /* Indicate USB not ready */
107 UpdateStatus(Status_USBNotReady);
108 }
109
110 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
111 * of the USB device after enumeration, and configures the RNDIS device endpoints and starts the relevant tasks.
112 */
113 EVENT_HANDLER(USB_ConfigurationChanged)
114 {
115 /* Setup CDC Notification, Rx and Tx Endpoints */
116 Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
117 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
118 ENDPOINT_BANK_SINGLE);
119
120 Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
121 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
122 ENDPOINT_BANK_SINGLE);
123
124 Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
125 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
126 ENDPOINT_BANK_SINGLE);
127
128 /* Indicate USB connected and ready */
129 UpdateStatus(Status_USBReady);
130
131 /* Start TCP/IP tasks */
132 Scheduler_SetTaskMode(RNDIS_Task, TASK_RUN);
133 Scheduler_SetTaskMode(Ethernet_Task, TASK_RUN);
134 Scheduler_SetTaskMode(TCP_Task, TASK_RUN);
135 }
136
137 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
138 * control requests that are not handled internally by the USB library (including the RNDIS control commands,
139 * which set up the USB RNDIS network adapter), so that they can be handled appropriately for the application.
140 */
141 EVENT_HANDLER(USB_UnhandledControlPacket)
142 {
143 /* Process RNDIS class commands */
144 switch (USB_ControlRequest.bRequest)
145 {
146 case REQ_SendEncapsulatedCommand:
147 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
148 {
149 /* Clear the SETUP packet, ready for data transfer */
150 Endpoint_ClearSETUP();
151
152 /* Read in the RNDIS message into the message buffer */
153 Endpoint_Read_Control_Stream_LE(RNDISMessageBuffer, USB_ControlRequest.wLength);
154
155 /* Finalize the stream transfer to clear the last packet from the host */
156 Endpoint_ClearIN();
157
158 /* Process the RNDIS message */
159 ProcessRNDISControlMessage();
160 }
161
162 break;
163 case REQ_GetEncapsulatedResponse:
164 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
165 {
166 /* Clear the SETUP packet, ready for data transfer */
167 Endpoint_ClearSETUP();
168
169 /* Check if a response to the last message is ready */
170 if (!(MessageHeader->MessageLength))
171 {
172 /* Set the response to a single 0x00 byte to indicate that no response is ready */
173 RNDISMessageBuffer[0] = 0;
174 MessageHeader->MessageLength = 1;
175 }
176
177 /* Write the message response data to the endpoint */
178 Endpoint_Write_Control_Stream_LE(RNDISMessageBuffer, MessageHeader->MessageLength);
179
180 /* Finalize the stream transfer to send the last packet or clear the host abort */
181 Endpoint_ClearOUT();
182
183 /* Reset the message header once again after transmission */
184 MessageHeader->MessageLength = 0;
185 }
186
187 break;
188 }
189 }
190
191 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
192 * log to a serial port, or anything else that is suitable for status updates.
193 *
194 * \param CurrentStatus Current status of the system, from the RNDISEthernet_StatusCodes_t enum
195 */
196 void UpdateStatus(uint8_t CurrentStatus)
197 {
198 uint8_t LEDMask = LEDS_NO_LEDS;
199
200 /* Set the LED mask to the appropriate LED mask based on the given status code */
201 switch (CurrentStatus)
202 {
203 case Status_USBNotReady:
204 LEDMask = (LEDS_LED1);
205 break;
206 case Status_USBEnumerating:
207 LEDMask = (LEDS_LED1 | LEDS_LED2);
208 break;
209 case Status_USBReady:
210 LEDMask = (LEDS_LED2 | LEDS_LED4);
211 break;
212 case Status_ProcessingEthernetFrame:
213 LEDMask = (LEDS_LED2 | LEDS_LED3);
214 break;
215 }
216
217 /* Set the board LEDs to the new LED mask */
218 LEDs_SetAllLEDs(LEDMask);
219 }
220
221 /** Task to manage the sending and receiving of encapsulated RNDIS data and notifications. This removes the RNDIS
222 * wrapper from received Ethernet frames and places them in the FrameIN global buffer, or adds the RNDIS wrapper
223 * to a frame in the FrameOUT global before sending the buffer contents to the host.
224 */
225 TASK(RNDIS_Task)
226 {
227 /* Select the notification endpoint */
228 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM);
229
230 /* Check if a message response is ready for the host */
231 if (Endpoint_IsINReady() && ResponseReady)
232 {
233 USB_Notification_t Notification = (USB_Notification_t)
234 {
235 .bmRequestType = (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE),
236 .bNotification = NOTIF_RESPONSE_AVAILABLE,
237 .wValue = 0,
238 .wIndex = 0,
239 .wLength = 0,
240 };
241
242 /* Indicate that a message response is ready for the host */
243 Endpoint_Write_Stream_LE(&Notification, sizeof(Notification));
244
245 /* Finalize the stream transfer to send the last packet */
246 Endpoint_ClearIN();
247
248 /* Indicate a response is no longer ready */
249 ResponseReady = false;
250 }
251
252 /* Don't process the data endpoints until the system is in the data initialized state, and the buffer is free */
253 if ((CurrRNDISState == RNDIS_Data_Initialized) && !(MessageHeader->MessageLength))
254 {
255 /* Create a new packet header for reading/writing */
256 RNDIS_PACKET_MSG_t RNDISPacketHeader;
257
258 /* Select the data OUT endpoint */
259 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
260
261 /* Check if the data OUT endpoint contains data, and that the IN buffer is empty */
262 if (Endpoint_IsOUTReceived() && !(FrameIN.FrameInBuffer))
263 {
264 /* Read in the packet message header */
265 Endpoint_Read_Stream_LE(&RNDISPacketHeader, sizeof(RNDIS_PACKET_MSG_t));
266
267 /* Stall the request if the data is too large */
268 if (RNDISPacketHeader.DataLength > ETHERNET_FRAME_SIZE_MAX)
269 {
270 Endpoint_StallTransaction();
271 return;
272 }
273
274 /* Read in the Ethernet frame into the buffer */
275 Endpoint_Read_Stream_LE(FrameIN.FrameData, RNDISPacketHeader.DataLength);
276
277 /* Finalize the stream transfer to send the last packet */
278 Endpoint_ClearOUT();
279
280 /* Store the size of the Ethernet frame */
281 FrameIN.FrameLength = RNDISPacketHeader.DataLength;
282
283 /* Indicate Ethernet IN buffer full */
284 FrameIN.FrameInBuffer = true;
285 }
286
287 /* Select the data IN endpoint */
288 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
289
290 /* Check if the data IN endpoint is ready for more data, and that the IN buffer is full */
291 if (Endpoint_IsINReady() && FrameOUT.FrameInBuffer)
292 {
293 /* Clear the packet header with all 0s so that the relevant fields can be filled */
294 memset(&RNDISPacketHeader, 0, sizeof(RNDIS_PACKET_MSG_t));
295
296 /* Construct the required packet header fields in the buffer */
297 RNDISPacketHeader.MessageType = REMOTE_NDIS_PACKET_MSG;
298 RNDISPacketHeader.MessageLength = (sizeof(RNDIS_PACKET_MSG_t) + FrameOUT.FrameLength);
299 RNDISPacketHeader.DataOffset = (sizeof(RNDIS_PACKET_MSG_t) - sizeof(RNDIS_Message_Header_t));
300 RNDISPacketHeader.DataLength = FrameOUT.FrameLength;
301
302 /* Send the packet header to the host */
303 Endpoint_Write_Stream_LE(&RNDISPacketHeader, sizeof(RNDIS_PACKET_MSG_t));
304
305 /* Send the Ethernet frame data to the host */
306 Endpoint_Write_Stream_LE(FrameOUT.FrameData, RNDISPacketHeader.DataLength);
307
308 /* Finalize the stream transfer to send the last packet */
309 Endpoint_ClearIN();
310
311 /* Indicate Ethernet OUT buffer no longer full */
312 FrameOUT.FrameInBuffer = false;
313 }
314 }
315 }
316
317 /** Ethernet frame processing task. This task checks to see if a frame has been received, and if so hands off the processing
318 * of the frame to the Ethernet processing routines.
319 */
320 TASK(Ethernet_Task)
321 {
322 /* Task for Ethernet processing. Incoming ethernet frames are loaded into the FrameIN structure, and
323 outgoing frames should be loaded into the FrameOUT structure. Both structures can only hold a single
324 Ethernet frame at a time, so the FrameInBuffer bool is used to indicate when the buffers contain data. */
325
326 /* Check if a frame has been written to the IN frame buffer */
327 if (FrameIN.FrameInBuffer)
328 {
329 /* Indicate packet processing started */
330 UpdateStatus(Status_ProcessingEthernetFrame);
331
332 /* Process the ethernet frame - replace this with your own Ethernet handler code as desired */
333 Ethernet_ProcessPacket();
334
335 /* Indicate packet processing complete */
336 UpdateStatus(Status_USBReady);
337 }
338 }