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