Minor documentation improvements.
[pub/USBasp.git] / Demos / Device / Incomplete / TestAndMeasurement / TestAndMeasurement.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2012.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all 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 disclaims 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 #include "TestAndMeasurement.h"
32
33 /** Contains the (usually static) capabilities of the TMC device. This table is requested by the
34 * host upon enumeration to give it information on what features of the Test and Measurement USB
35 * Class the device supports.
36 */
37 TMC_Capabilities_t Capabilities =
38 {
39 .Status = TMC_STATUS_SUCCESS,
40 .TMCVersion = VERSION_BCD(1.00),
41
42 .Interface =
43 {
44 .ListenOnly = false,
45 .TalkOnly = false,
46 .PulseIndicateSupported = false,
47 },
48
49 .Device =
50 {
51 .SupportsAbortINOnMatch = false,
52 },
53 };
54
55 /** Current TMC control request that is being processed */
56 static uint8_t RequestInProgress = 0;
57
58 /** Stream callback abort flag for bulk IN data */
59 static bool IsTMCBulkINReset = false;
60
61 /** Stream callback abort flag for bulk OUT data */
62 static bool IsTMCBulkOUTReset = false;
63
64 /** Last used tag value for data transfers */
65 static uint8_t CurrentTransferTag = 0;
66
67 /** Length of last data transfer, for reporting to the host in case an in-progress transfer is aborted */
68 static uint16_t LastTransferLength = 0;
69
70 /** Buffer to hold the next message to sent to the TMC host */
71 static uint8_t NextResponseBuffer[64];
72
73 /** Indicates the length of the next response to send */
74 static uint8_t NextResponseLen;
75
76 /** Main program entry point. This routine contains the overall program flow, including initial
77 * setup of all components and the main program loop.
78 */
79 int main(void)
80 {
81 SetupHardware();
82
83 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
84 GlobalInterruptEnable();
85
86 for (;;)
87 {
88 TMC_Task();
89 USB_USBTask();
90 }
91 }
92
93 /** Configures the board hardware and chip peripherals for the demo's functionality. */
94 void SetupHardware(void)
95 {
96 /* Disable watchdog if enabled by bootloader/fuses */
97 MCUSR &= ~(1 << WDRF);
98 wdt_disable();
99
100 /* Disable clock division */
101 clock_prescale_set(clock_div_1);
102
103 /* Hardware Initialization */
104 LEDs_Init();
105 USB_Init();
106 }
107
108 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
109 * starts the library USB task to begin the enumeration and USB management process.
110 */
111 void EVENT_USB_Device_Connect(void)
112 {
113 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
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 void EVENT_USB_Device_Disconnect(void)
120 {
121 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
122 }
123
124 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
125 * of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
126 */
127 void EVENT_USB_Device_ConfigurationChanged(void)
128 {
129 bool ConfigSuccess = true;
130
131 /* Setup TMC In, Out and Notification Endpoints */
132 ConfigSuccess &= Endpoint_ConfigureEndpoint(TMC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, TMC_IO_EPSIZE, 1);
133 ConfigSuccess &= Endpoint_ConfigureEndpoint(TMC_IN_EPADDR, EP_TYPE_BULK, TMC_IO_EPSIZE, 1);
134 ConfigSuccess &= Endpoint_ConfigureEndpoint(TMC_OUT_EPADDR, EP_TYPE_BULK, TMC_IO_EPSIZE, 1);
135
136 /* Indicate endpoint configuration success or failure */
137 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
138 }
139
140 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
141 * the device from the USB host before passing along unhandled control requests to the library for processing
142 * internally.
143 */
144 void EVENT_USB_Device_ControlRequest(void)
145 {
146 uint8_t TMCRequestStatus = TMC_STATUS_SUCCESS;
147
148 /* Process TMC specific control requests */
149 switch (USB_ControlRequest.bRequest)
150 {
151 case Req_InitiateAbortBulkOut:
152 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
153 {
154 /* Check that no split transaction is already in progress and the data transfer tag is valid */
155 if (RequestInProgress != 0)
156 {
157 TMCRequestStatus = TMC_STATUS_SPLIT_IN_PROGRESS;
158 }
159 else if (USB_ControlRequest.wValue != CurrentTransferTag)
160 {
161 TMCRequestStatus = TMC_STATUS_TRANSFER_NOT_IN_PROGRESS;
162 }
163 else
164 {
165 /* Indicate that all in-progress/pending data OUT requests should be aborted */
166 IsTMCBulkOUTReset = true;
167
168 /* Save the split request for later checking when a new request is received */
169 RequestInProgress = Req_InitiateAbortBulkOut;
170 }
171
172 Endpoint_ClearSETUP();
173
174 /* Write the request response byte */
175 Endpoint_Write_8(TMCRequestStatus);
176
177 Endpoint_ClearIN();
178 Endpoint_ClearStatusStage();
179 }
180
181 break;
182 case Req_CheckAbortBulkOutStatus:
183 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
184 {
185 /* Check that an ABORT BULK OUT transaction has been requested and that the request has completed */
186 if (RequestInProgress != Req_InitiateAbortBulkOut)
187 TMCRequestStatus = TMC_STATUS_SPLIT_NOT_IN_PROGRESS;
188 else if (IsTMCBulkOUTReset)
189 TMCRequestStatus = TMC_STATUS_PENDING;
190 else
191 RequestInProgress = 0;
192
193 Endpoint_ClearSETUP();
194
195 /* Write the request response bytes */
196 Endpoint_Write_8(TMCRequestStatus);
197 Endpoint_Write_16_LE(0);
198 Endpoint_Write_32_LE(LastTransferLength);
199
200 Endpoint_ClearIN();
201 Endpoint_ClearStatusStage();
202 }
203
204 break;
205 case Req_InitiateAbortBulkIn:
206 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
207 {
208 /* Check that no split transaction is already in progress and the data transfer tag is valid */
209 if (RequestInProgress != 0)
210 {
211 TMCRequestStatus = TMC_STATUS_SPLIT_IN_PROGRESS;
212 }
213 else if (USB_ControlRequest.wValue != CurrentTransferTag)
214 {
215 TMCRequestStatus = TMC_STATUS_TRANSFER_NOT_IN_PROGRESS;
216 }
217 else
218 {
219 /* Indicate that all in-progress/pending data IN requests should be aborted */
220 IsTMCBulkINReset = true;
221
222 /* Save the split request for later checking when a new request is received */
223 RequestInProgress = Req_InitiateAbortBulkIn;
224 }
225
226 Endpoint_ClearSETUP();
227
228 /* Write the request response bytes */
229 Endpoint_Write_8(TMCRequestStatus);
230 Endpoint_Write_8(CurrentTransferTag);
231
232 Endpoint_ClearIN();
233 Endpoint_ClearStatusStage();
234 }
235
236 break;
237 case Req_CheckAbortBulkInStatus:
238 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
239 {
240 /* Check that an ABORT BULK IN transaction has been requested and that the request has completed */
241 if (RequestInProgress != Req_InitiateAbortBulkIn)
242 TMCRequestStatus = TMC_STATUS_SPLIT_NOT_IN_PROGRESS;
243 else if (IsTMCBulkINReset)
244 TMCRequestStatus = TMC_STATUS_PENDING;
245 else
246 RequestInProgress = 0;
247
248 Endpoint_ClearSETUP();
249
250 /* Write the request response bytes */
251 Endpoint_Write_8(TMCRequestStatus);
252 Endpoint_Write_16_LE(0);
253 Endpoint_Write_32_LE(LastTransferLength);
254
255 Endpoint_ClearIN();
256 Endpoint_ClearStatusStage();
257 }
258
259 break;
260 case Req_InitiateClear:
261 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
262 {
263 /* Check that no split transaction is already in progress */
264 if (RequestInProgress != 0)
265 {
266 Endpoint_Write_8(TMC_STATUS_SPLIT_IN_PROGRESS);
267 }
268 else
269 {
270 /* Indicate that all in-progress/pending data IN and OUT requests should be aborted */
271 IsTMCBulkINReset = true;
272 IsTMCBulkOUTReset = true;
273
274 /* Save the split request for later checking when a new request is received */
275 RequestInProgress = Req_InitiateClear;
276 }
277
278 Endpoint_ClearSETUP();
279
280 /* Write the request response byte */
281 Endpoint_Write_8(TMCRequestStatus);
282
283 Endpoint_ClearIN();
284 Endpoint_ClearStatusStage();
285 }
286
287 break;
288 case Req_CheckClearStatus:
289 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
290 {
291 /* Check that a CLEAR transaction has been requested and that the request has completed */
292 if (RequestInProgress != Req_InitiateClear)
293 TMCRequestStatus = TMC_STATUS_SPLIT_NOT_IN_PROGRESS;
294 else if (IsTMCBulkINReset || IsTMCBulkOUTReset)
295 TMCRequestStatus = TMC_STATUS_PENDING;
296 else
297 RequestInProgress = 0;
298
299 Endpoint_ClearSETUP();
300
301 /* Write the request response bytes */
302 Endpoint_Write_8(TMCRequestStatus);
303 Endpoint_Write_8(0);
304
305 Endpoint_ClearIN();
306 Endpoint_ClearStatusStage();
307 }
308
309 break;
310 case Req_GetCapabilities:
311 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
312 {
313 Endpoint_ClearSETUP();
314
315 /* Write the device capabilities to the control endpoint */
316 Endpoint_Write_Control_Stream_LE(&Capabilities, sizeof(TMC_Capabilities_t));
317 Endpoint_ClearOUT();
318 }
319
320 break;
321 }
322 }
323
324 void ProcessSentMessage(uint8_t* const Data, const uint8_t Length)
325 {
326 if (strncmp((char*)Data, "*IDN?", 5) == 0)
327 strcpy((char*)NextResponseBuffer, "LUFA TMC DEMO");
328
329 NextResponseLen = strlen((char*)NextResponseBuffer);
330 }
331
332 uint8_t GetNextMessage(uint8_t* const Data)
333 {
334 strcpy((char*)NextResponseBuffer, "LUFA TMC DEMO");
335
336 NextResponseLen = strlen((char*)NextResponseBuffer);
337 // ---
338 uint8_t DataLen = MIN(NextResponseLen, 64);
339
340 strlcpy((char*)Data, (char*)NextResponseBuffer, DataLen);
341
342 return DataLen;
343 }
344
345 /** Function to manage TMC data transmission and reception to and from the host. */
346 void TMC_Task(void)
347 {
348 /* Device must be connected and configured for the task to run */
349 if (USB_DeviceState != DEVICE_STATE_Configured)
350 return;
351
352 TMC_MessageHeader_t MessageHeader;
353 uint8_t MessagePayload[128];
354
355 /* Try to read in a TMC message from the interface, process if one is available */
356 if (ReadTMCHeader(&MessageHeader))
357 {
358 /* Indicate busy */
359 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
360
361 switch (MessageHeader.MessageID)
362 {
363 case TMC_MESSAGEID_DEV_DEP_MSG_OUT:
364 LastTransferLength = 0;
365 while (Endpoint_Read_Stream_LE(MessagePayload, MIN(MessageHeader.TransferSize, sizeof(MessagePayload)), &LastTransferLength) ==
366 ENDPOINT_RWSTREAM_IncompleteTransfer)
367 {
368 if (IsTMCBulkOUTReset)
369 break;
370 }
371
372 Endpoint_ClearOUT();
373
374 ProcessSentMessage(MessagePayload, LastTransferLength);
375 break;
376 case TMC_MESSAGEID_DEV_DEP_MSG_IN:
377 Endpoint_ClearOUT();
378
379 MessageHeader.TransferSize = GetNextMessage(MessagePayload);
380 MessageHeader.MessageIDSpecific.DeviceOUT.LastMessageTransaction = true;
381 WriteTMCHeader(&MessageHeader);
382
383 LastTransferLength = 0;
384 while (Endpoint_Write_Stream_LE(MessagePayload, MessageHeader.TransferSize, &LastTransferLength) ==
385 ENDPOINT_RWSTREAM_IncompleteTransfer)
386 {
387 if (IsTMCBulkINReset)
388 break;
389 }
390
391 Endpoint_ClearIN();
392 break;
393 default:
394 Endpoint_StallTransaction();
395 break;
396 }
397
398 LEDs_SetAllLEDs(LEDMASK_USB_READY);
399 }
400
401 /* All pending data has been processed - reset the data abort flags */
402 IsTMCBulkINReset = false;
403 IsTMCBulkOUTReset = false;
404 }
405
406 /** Attempts to read in the TMC message header from the TMC interface.
407 *
408 * \param[out] MessageHeader Pointer to a location where the read header (if any) should be stored
409 *
410 * \return Boolean true if a header was read, false otherwise
411 */
412 bool ReadTMCHeader(TMC_MessageHeader_t* const MessageHeader)
413 {
414 uint16_t BytesTransferred;
415 uint8_t ErrorCode;
416
417 /* Select the Data Out endpoint */
418 Endpoint_SelectEndpoint(TMC_OUT_EPADDR);
419
420 /* Abort if no command has been sent from the host */
421 if (!(Endpoint_IsOUTReceived()))
422 return false;
423
424 /* Read in the header of the command from the host */
425 BytesTransferred = 0;
426 while ((ErrorCode = Endpoint_Read_Stream_LE(MessageHeader, sizeof(TMC_MessageHeader_t), &BytesTransferred)) ==
427 ENDPOINT_RWSTREAM_IncompleteTransfer)
428 {
429 if (IsTMCBulkOUTReset)
430 break;
431 }
432
433 /* Store the new command tag value for later use */
434 CurrentTransferTag = MessageHeader->Tag;
435
436 /* Indicate if the command has been aborted or not */
437 return (!(IsTMCBulkOUTReset) && (ErrorCode == ENDPOINT_RWSTREAM_NoError));
438 }
439
440 bool WriteTMCHeader(TMC_MessageHeader_t* const MessageHeader)
441 {
442 uint16_t BytesTransferred;
443 uint8_t ErrorCode;
444
445 /* Set the message tag of the command header */
446 MessageHeader->Tag = CurrentTransferTag;
447 MessageHeader->InverseTag = ~CurrentTransferTag;
448
449 /* Select the Data In endpoint */
450 Endpoint_SelectEndpoint(TMC_IN_EPADDR);
451
452 /* Send the command header to the host */
453 BytesTransferred = 0;
454 while ((ErrorCode = Endpoint_Write_Stream_LE(MessageHeader, sizeof(TMC_MessageHeader_t), &BytesTransferred)) ==
455 ENDPOINT_RWSTREAM_IncompleteTransfer)
456 {
457 if (IsTMCBulkINReset)
458 break;
459 }
460
461 /* Indicate if the command has been aborted or not */
462 return (!(IsTMCBulkINReset) && (ErrorCode == ENDPOINT_RWSTREAM_NoError));
463 }
464