Applied STATIC_ENDPOINT_CONFIGURATION and FIXED_CONTROL_SIZE tokens to all Device...
[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 /* Discard the unused wValue parameter */
144 Endpoint_Discard_Word();
145
146 /* Discard the unused wIndex parameter */
147 Endpoint_Discard_Word();
148
149 /* Read in the wLength parameter */
150 uint16_t wLength = Endpoint_Read_Word_LE();
151
152 /* Process RNDIS class commands */
153 switch (USB_ControlRequest.bRequest)
154 {
155 case REQ_SendEncapsulatedCommand:
156 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
157 {
158 /* Clear the SETUP packet, ready for data transfer */
159 Endpoint_ClearSETUP();
160
161 /* Read in the RNDIS message into the message buffer */
162 Endpoint_Read_Control_Stream_LE(RNDISMessageBuffer, wLength);
163
164 /* Finalize the stream transfer to clear the last packet from the host */
165 Endpoint_ClearIN();
166
167 /* Process the RNDIS message */
168 ProcessRNDISControlMessage();
169 }
170
171 break;
172 case REQ_GetEncapsulatedResponse:
173 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
174 {
175 /* Check if a response to the last message is ready */
176 if (!(MessageHeader->MessageLength))
177 {
178 /* Set the response to a single 0x00 byte to indicate that no response is ready */
179 RNDISMessageBuffer[0] = 0;
180 MessageHeader->MessageLength = 1;
181 }
182
183 /* Clear the SETUP packet, ready for data transfer */
184 Endpoint_ClearSETUP();
185
186 /* Write the message response data to the endpoint */
187 Endpoint_Write_Control_Stream_LE(RNDISMessageBuffer, MessageHeader->MessageLength);
188
189 /* Finalize the stream transfer to send the last packet or clear the host abort */
190 Endpoint_ClearOUT();
191
192 /* Reset the message header once again after transmission */
193 MessageHeader->MessageLength = 0;
194 }
195
196 break;
197 }
198 }
199
200 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
201 * log to a serial port, or anything else that is suitable for status updates.
202 *
203 * \param CurrentStatus Current status of the system, from the RNDISEthernet_StatusCodes_t enum
204 */
205 void UpdateStatus(uint8_t CurrentStatus)
206 {
207 uint8_t LEDMask = LEDS_NO_LEDS;
208
209 /* Set the LED mask to the appropriate LED mask based on the given status code */
210 switch (CurrentStatus)
211 {
212 case Status_USBNotReady:
213 LEDMask = (LEDS_LED1);
214 break;
215 case Status_USBEnumerating:
216 LEDMask = (LEDS_LED1 | LEDS_LED2);
217 break;
218 case Status_USBReady:
219 LEDMask = (LEDS_LED2 | LEDS_LED4);
220 break;
221 case Status_ProcessingEthernetFrame:
222 LEDMask = (LEDS_LED2 | LEDS_LED3);
223 break;
224 }
225
226 /* Set the board LEDs to the new LED mask */
227 LEDs_SetAllLEDs(LEDMask);
228 }
229
230 /** Task to manage the sending and receiving of encapsulated RNDIS data and notifications. This removes the RNDIS
231 * wrapper from received Ethernet frames and places them in the FrameIN global buffer, or adds the RNDIS wrapper
232 * to a frame in the FrameOUT global before sending the buffer contents to the host.
233 */
234 TASK(RNDIS_Task)
235 {
236 /* Select the notification endpoint */
237 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM);
238
239 /* Check if a message response is ready for the host */
240 if (Endpoint_IsINReady() && ResponseReady)
241 {
242 USB_Notification_t Notification = (USB_Notification_t)
243 {
244 .bmRequestType = (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE),
245 .bNotification = NOTIF_RESPONSE_AVAILABLE,
246 .wValue = 0,
247 .wIndex = 0,
248 .wLength = 0,
249 };
250
251 /* Indicate that a message response is ready for the host */
252 Endpoint_Write_Stream_LE(&Notification, sizeof(Notification));
253
254 /* Finalize the stream transfer to send the last packet */
255 Endpoint_ClearIN();
256
257 /* Indicate a response is no longer ready */
258 ResponseReady = false;
259 }
260
261 /* Don't process the data endpoints until the system is in the data initialized state, and the buffer is free */
262 if ((CurrRNDISState == RNDIS_Data_Initialized) && !(MessageHeader->MessageLength))
263 {
264 /* Create a new packet header for reading/writing */
265 RNDIS_PACKET_MSG_t RNDISPacketHeader;
266
267 /* Select the data OUT endpoint */
268 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
269
270 /* Check if the data OUT endpoint contains data, and that the IN buffer is empty */
271 if (Endpoint_IsOUTReceived() && !(FrameIN.FrameInBuffer))
272 {
273 /* Read in the packet message header */
274 Endpoint_Read_Stream_LE(&RNDISPacketHeader, sizeof(RNDIS_PACKET_MSG_t));
275
276 /* Stall the request if the data is too large */
277 if (RNDISPacketHeader.DataLength > ETHERNET_FRAME_SIZE_MAX)
278 {
279 Endpoint_StallTransaction();
280 return;
281 }
282
283 /* Read in the Ethernet frame into the buffer */
284 Endpoint_Read_Stream_LE(FrameIN.FrameData, RNDISPacketHeader.DataLength);
285
286 /* Finalize the stream transfer to send the last packet */
287 Endpoint_ClearOUT();
288
289 /* Store the size of the Ethernet frame */
290 FrameIN.FrameLength = RNDISPacketHeader.DataLength;
291
292 /* Indicate Ethernet IN buffer full */
293 FrameIN.FrameInBuffer = true;
294 }
295
296 /* Select the data IN endpoint */
297 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
298
299 /* Check if the data IN endpoint is ready for more data, and that the IN buffer is full */
300 if (Endpoint_IsINReady() && FrameOUT.FrameInBuffer)
301 {
302 /* Clear the packet header with all 0s so that the relevant fields can be filled */
303 memset(&RNDISPacketHeader, 0, sizeof(RNDIS_PACKET_MSG_t));
304
305 /* Construct the required packet header fields in the buffer */
306 RNDISPacketHeader.MessageType = REMOTE_NDIS_PACKET_MSG;
307 RNDISPacketHeader.MessageLength = (sizeof(RNDIS_PACKET_MSG_t) + FrameOUT.FrameLength);
308 RNDISPacketHeader.DataOffset = (sizeof(RNDIS_PACKET_MSG_t) - sizeof(RNDIS_Message_Header_t));
309 RNDISPacketHeader.DataLength = FrameOUT.FrameLength;
310
311 /* Send the packet header to the host */
312 Endpoint_Write_Stream_LE(&RNDISPacketHeader, sizeof(RNDIS_PACKET_MSG_t));
313
314 /* Send the Ethernet frame data to the host */
315 Endpoint_Write_Stream_LE(FrameOUT.FrameData, RNDISPacketHeader.DataLength);
316
317 /* Finalize the stream transfer to send the last packet */
318 Endpoint_ClearIN();
319
320 /* Indicate Ethernet OUT buffer no longer full */
321 FrameOUT.FrameInBuffer = false;
322 }
323 }
324 }
325
326 /** Ethernet frame processing task. This task checks to see if a frame has been received, and if so hands off the processing
327 * of the frame to the Ethernet processing routines.
328 */
329 TASK(Ethernet_Task)
330 {
331 /* Task for Ethernet processing. Incoming ethernet frames are loaded into the FrameIN structure, and
332 outgoing frames should be loaded into the FrameOUT structure. Both structures can only hold a single
333 Ethernet frame at a time, so the FrameInBuffer bool is used to indicate when the buffers contain data. */
334
335 /* Check if a frame has been written to the IN frame buffer */
336 if (FrameIN.FrameInBuffer)
337 {
338 /* Indicate packet processing started */
339 UpdateStatus(Status_ProcessingEthernetFrame);
340
341 /* Process the ethernet frame - replace this with your own Ethernet handler code as desired */
342 Ethernet_ProcessPacket();
343
344 /* Indicate packet processing complete */
345 UpdateStatus(Status_USBReady);
346 }
347 }