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