]> git.gir.st - tmk_keyboard.git/blob - protocol/lufa/LUFA-git/Demos/Device/Incomplete/TestAndMeasurement/TestAndMeasurement.c
Squashed 'tmk_core/' changes from caca2c0..dc0e46e
[tmk_keyboard.git] / protocol / lufa / LUFA-git / Demos / Device / Incomplete / TestAndMeasurement / TestAndMeasurement.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2014.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2014 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 #if (ARCH == ARCH_AVR8)
97 /* Disable watchdog if enabled by bootloader/fuses */
98 MCUSR &= ~(1 << WDRF);
99 wdt_disable();
100
101 /* Disable clock division */
102 clock_prescale_set(clock_div_1);
103 #elif (ARCH == ARCH_XMEGA)
104 /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
105 XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
106 XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
107
108 /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
109 XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
110 XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
111
112 PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
113 #endif
114
115 /* Hardware Initialization */
116 LEDs_Init();
117 USB_Init();
118 }
119
120 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
121 * starts the library USB task to begin the enumeration and USB management process.
122 */
123 void EVENT_USB_Device_Connect(void)
124 {
125 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
126 }
127
128 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
129 * the status LEDs and stops the USB management and CDC management tasks.
130 */
131 void EVENT_USB_Device_Disconnect(void)
132 {
133 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
134 }
135
136 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
137 * of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
138 */
139 void EVENT_USB_Device_ConfigurationChanged(void)
140 {
141 bool ConfigSuccess = true;
142
143 /* Setup TMC In, Out and Notification Endpoints */
144 ConfigSuccess &= Endpoint_ConfigureEndpoint(TMC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, TMC_IO_EPSIZE, 1);
145 ConfigSuccess &= Endpoint_ConfigureEndpoint(TMC_IN_EPADDR, EP_TYPE_BULK, TMC_IO_EPSIZE, 1);
146 ConfigSuccess &= Endpoint_ConfigureEndpoint(TMC_OUT_EPADDR, EP_TYPE_BULK, TMC_IO_EPSIZE, 1);
147
148 /* Indicate endpoint configuration success or failure */
149 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
150 }
151
152 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
153 * the device from the USB host before passing along unhandled control requests to the library for processing
154 * internally.
155 */
156 void EVENT_USB_Device_ControlRequest(void)
157 {
158 uint8_t TMCRequestStatus = TMC_STATUS_SUCCESS;
159
160 /* Process TMC specific control requests */
161 switch (USB_ControlRequest.bRequest)
162 {
163 case Req_InitiateAbortBulkOut:
164 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
165 {
166 /* Check that no split transaction is already in progress and the data transfer tag is valid */
167 if (RequestInProgress != 0)
168 {
169 TMCRequestStatus = TMC_STATUS_SPLIT_IN_PROGRESS;
170 }
171 else if (USB_ControlRequest.wValue != CurrentTransferTag)
172 {
173 TMCRequestStatus = TMC_STATUS_TRANSFER_NOT_IN_PROGRESS;
174 }
175 else
176 {
177 /* Indicate that all in-progress/pending data OUT requests should be aborted */
178 IsTMCBulkOUTReset = true;
179
180 /* Save the split request for later checking when a new request is received */
181 RequestInProgress = Req_InitiateAbortBulkOut;
182 }
183
184 Endpoint_ClearSETUP();
185
186 /* Write the request response byte */
187 Endpoint_Write_8(TMCRequestStatus);
188
189 Endpoint_ClearIN();
190 Endpoint_ClearStatusStage();
191 }
192
193 break;
194 case Req_CheckAbortBulkOutStatus:
195 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
196 {
197 /* Check that an ABORT BULK OUT transaction has been requested and that the request has completed */
198 if (RequestInProgress != Req_InitiateAbortBulkOut)
199 TMCRequestStatus = TMC_STATUS_SPLIT_NOT_IN_PROGRESS;
200 else if (IsTMCBulkOUTReset)
201 TMCRequestStatus = TMC_STATUS_PENDING;
202 else
203 RequestInProgress = 0;
204
205 Endpoint_ClearSETUP();
206
207 /* Write the request response bytes */
208 Endpoint_Write_8(TMCRequestStatus);
209 Endpoint_Write_16_LE(0);
210 Endpoint_Write_32_LE(LastTransferLength);
211
212 Endpoint_ClearIN();
213 Endpoint_ClearStatusStage();
214 }
215
216 break;
217 case Req_InitiateAbortBulkIn:
218 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
219 {
220 /* Check that no split transaction is already in progress and the data transfer tag is valid */
221 if (RequestInProgress != 0)
222 {
223 TMCRequestStatus = TMC_STATUS_SPLIT_IN_PROGRESS;
224 }
225 else if (USB_ControlRequest.wValue != CurrentTransferTag)
226 {
227 TMCRequestStatus = TMC_STATUS_TRANSFER_NOT_IN_PROGRESS;
228 }
229 else
230 {
231 /* Indicate that all in-progress/pending data IN requests should be aborted */
232 IsTMCBulkINReset = true;
233
234 /* Save the split request for later checking when a new request is received */
235 RequestInProgress = Req_InitiateAbortBulkIn;
236 }
237
238 Endpoint_ClearSETUP();
239
240 /* Write the request response bytes */
241 Endpoint_Write_8(TMCRequestStatus);
242 Endpoint_Write_8(CurrentTransferTag);
243
244 Endpoint_ClearIN();
245 Endpoint_ClearStatusStage();
246 }
247
248 break;
249 case Req_CheckAbortBulkInStatus:
250 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_ENDPOINT))
251 {
252 /* Check that an ABORT BULK IN transaction has been requested and that the request has completed */
253 if (RequestInProgress != Req_InitiateAbortBulkIn)
254 TMCRequestStatus = TMC_STATUS_SPLIT_NOT_IN_PROGRESS;
255 else if (IsTMCBulkINReset)
256 TMCRequestStatus = TMC_STATUS_PENDING;
257 else
258 RequestInProgress = 0;
259
260 Endpoint_ClearSETUP();
261
262 /* Write the request response bytes */
263 Endpoint_Write_8(TMCRequestStatus);
264 Endpoint_Write_16_LE(0);
265 Endpoint_Write_32_LE(LastTransferLength);
266
267 Endpoint_ClearIN();
268 Endpoint_ClearStatusStage();
269 }
270
271 break;
272 case Req_InitiateClear:
273 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
274 {
275 /* Check that no split transaction is already in progress */
276 if (RequestInProgress != 0)
277 {
278 Endpoint_Write_8(TMC_STATUS_SPLIT_IN_PROGRESS);
279 }
280 else
281 {
282 /* Indicate that all in-progress/pending data IN and OUT requests should be aborted */
283 IsTMCBulkINReset = true;
284 IsTMCBulkOUTReset = true;
285
286 /* Save the split request for later checking when a new request is received */
287 RequestInProgress = Req_InitiateClear;
288 }
289
290 Endpoint_ClearSETUP();
291
292 /* Write the request response byte */
293 Endpoint_Write_8(TMCRequestStatus);
294
295 Endpoint_ClearIN();
296 Endpoint_ClearStatusStage();
297 }
298
299 break;
300 case Req_CheckClearStatus:
301 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
302 {
303 /* Check that a CLEAR transaction has been requested and that the request has completed */
304 if (RequestInProgress != Req_InitiateClear)
305 TMCRequestStatus = TMC_STATUS_SPLIT_NOT_IN_PROGRESS;
306 else if (IsTMCBulkINReset || IsTMCBulkOUTReset)
307 TMCRequestStatus = TMC_STATUS_PENDING;
308 else
309 RequestInProgress = 0;
310
311 Endpoint_ClearSETUP();
312
313 /* Write the request response bytes */
314 Endpoint_Write_8(TMCRequestStatus);
315 Endpoint_Write_8(0);
316
317 Endpoint_ClearIN();
318 Endpoint_ClearStatusStage();
319 }
320
321 break;
322 case Req_GetCapabilities:
323 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
324 {
325 Endpoint_ClearSETUP();
326
327 /* Write the device capabilities to the control endpoint */
328 Endpoint_Write_Control_Stream_LE(&Capabilities, sizeof(TMC_Capabilities_t));
329 Endpoint_ClearOUT();
330 }
331
332 break;
333 }
334 }
335
336 void ProcessSentMessage(uint8_t* const Data, const uint8_t Length)
337 {
338 if (strncmp((char*)Data, "*IDN?", 5) == 0)
339 strcpy((char*)NextResponseBuffer, "LUFA TMC DEMO");
340
341 NextResponseLen = strlen((char*)NextResponseBuffer);
342 }
343
344 uint8_t GetNextMessage(uint8_t* const Data)
345 {
346 strcpy((char*)NextResponseBuffer, "LUFA TMC DEMO");
347
348 NextResponseLen = strlen((char*)NextResponseBuffer);
349 // ---
350 uint8_t DataLen = MIN(NextResponseLen, 64);
351
352 strlcpy((char*)Data, (char*)NextResponseBuffer, DataLen);
353
354 return DataLen;
355 }
356
357 /** Function to manage TMC data transmission and reception to and from the host. */
358 void TMC_Task(void)
359 {
360 /* Device must be connected and configured for the task to run */
361 if (USB_DeviceState != DEVICE_STATE_Configured)
362 return;
363
364 TMC_MessageHeader_t MessageHeader;
365 uint8_t MessagePayload[128];
366
367 /* Try to read in a TMC message from the interface, process if one is available */
368 if (ReadTMCHeader(&MessageHeader))
369 {
370 /* Indicate busy */
371 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
372
373 switch (MessageHeader.MessageID)
374 {
375 case TMC_MESSAGEID_DEV_DEP_MSG_OUT:
376 LastTransferLength = 0;
377 while (Endpoint_Read_Stream_LE(MessagePayload, MIN(MessageHeader.TransferSize, sizeof(MessagePayload)), &LastTransferLength) ==
378 ENDPOINT_RWSTREAM_IncompleteTransfer)
379 {
380 if (IsTMCBulkOUTReset)
381 break;
382 }
383
384 Endpoint_ClearOUT();
385
386 ProcessSentMessage(MessagePayload, LastTransferLength);
387 break;
388 case TMC_MESSAGEID_DEV_DEP_MSG_IN:
389 Endpoint_ClearOUT();
390
391 MessageHeader.TransferSize = GetNextMessage(MessagePayload);
392 MessageHeader.MessageIDSpecific.DeviceOUT.LastMessageTransaction = true;
393 WriteTMCHeader(&MessageHeader);
394
395 LastTransferLength = 0;
396 while (Endpoint_Write_Stream_LE(MessagePayload, MessageHeader.TransferSize, &LastTransferLength) ==
397 ENDPOINT_RWSTREAM_IncompleteTransfer)
398 {
399 if (IsTMCBulkINReset)
400 break;
401 }
402
403 Endpoint_ClearIN();
404 break;
405 default:
406 Endpoint_StallTransaction();
407 break;
408 }
409
410 LEDs_SetAllLEDs(LEDMASK_USB_READY);
411 }
412
413 /* All pending data has been processed - reset the data abort flags */
414 IsTMCBulkINReset = false;
415 IsTMCBulkOUTReset = false;
416 }
417
418 /** Attempts to read in the TMC message header from the TMC interface.
419 *
420 * \param[out] MessageHeader Pointer to a location where the read header (if any) should be stored
421 *
422 * \return Boolean \c true if a header was read, \c false otherwise
423 */
424 bool ReadTMCHeader(TMC_MessageHeader_t* const MessageHeader)
425 {
426 uint16_t BytesTransferred;
427 uint8_t ErrorCode;
428
429 /* Select the Data Out endpoint */
430 Endpoint_SelectEndpoint(TMC_OUT_EPADDR);
431
432 /* Abort if no command has been sent from the host */
433 if (!(Endpoint_IsOUTReceived()))
434 return false;
435
436 /* Read in the header of the command from the host */
437 BytesTransferred = 0;
438 while ((ErrorCode = Endpoint_Read_Stream_LE(MessageHeader, sizeof(TMC_MessageHeader_t), &BytesTransferred)) ==
439 ENDPOINT_RWSTREAM_IncompleteTransfer)
440 {
441 if (IsTMCBulkOUTReset)
442 break;
443 }
444
445 /* Store the new command tag value for later use */
446 CurrentTransferTag = MessageHeader->Tag;
447
448 /* Indicate if the command has been aborted or not */
449 return (!(IsTMCBulkOUTReset) && (ErrorCode == ENDPOINT_RWSTREAM_NoError));
450 }
451
452 bool WriteTMCHeader(TMC_MessageHeader_t* const MessageHeader)
453 {
454 uint16_t BytesTransferred;
455 uint8_t ErrorCode;
456
457 /* Set the message tag of the command header */
458 MessageHeader->Tag = CurrentTransferTag;
459 MessageHeader->InverseTag = ~CurrentTransferTag;
460
461 /* Select the Data In endpoint */
462 Endpoint_SelectEndpoint(TMC_IN_EPADDR);
463
464 /* Send the command header to the host */
465 BytesTransferred = 0;
466 while ((ErrorCode = Endpoint_Write_Stream_LE(MessageHeader, sizeof(TMC_MessageHeader_t), &BytesTransferred)) ==
467 ENDPOINT_RWSTREAM_IncompleteTransfer)
468 {
469 if (IsTMCBulkINReset)
470 break;
471 }
472
473 /* Indicate if the command has been aborted or not */
474 return (!(IsTMCBulkINReset) && (ErrorCode == ENDPOINT_RWSTREAM_NoError));
475 }
476
Imprint / Impressum