3 Copyright (C) Dean Camera, 2015.
5 dean [at] fourwalledcubicle [dot] com
10 Copyright 2015 Dean Camera (dean [at] fourwalledcubicle [dot] com)
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.
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
31 #include "TestAndMeasurement.h"
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.
37 TMC_Capabilities_t Capabilities
=
39 .Status
= TMC_STATUS_SUCCESS
,
40 .TMCVersion
= VERSION_BCD(1.00),
46 .PulseIndicateSupported
= false,
51 .SupportsAbortINOnMatch
= false,
55 /** Current TMC control request that is being processed */
56 static uint8_t RequestInProgress
= 0;
58 /** Stream callback abort flag for bulk IN data */
59 static bool IsTMCBulkINReset
= false;
61 /** Stream callback abort flag for bulk OUT data */
62 static bool IsTMCBulkOUTReset
= false;
64 /** Last used tag value for data transfers */
65 static uint8_t CurrentTransferTag
= 0;
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;
70 /** Buffer to hold the next message to sent to the TMC host */
71 static uint8_t NextResponseBuffer
[64];
73 /** Indicates the length of the next response to send */
74 static uint8_t NextResponseLen
;
76 /** Main program entry point. This routine contains the overall program flow, including initial
77 * setup of all components and the main program loop.
83 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
84 GlobalInterruptEnable();
93 /** Configures the board hardware and chip peripherals for the demo's functionality. */
94 void SetupHardware(void)
96 #if (ARCH == ARCH_AVR8)
97 /* Disable watchdog if enabled by bootloader/fuses */
98 MCUSR
&= ~(1 << WDRF
);
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
);
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
);
112 PMIC
.CTRL
= PMIC_LOLVLEN_bm
| PMIC_MEDLVLEN_bm
| PMIC_HILVLEN_bm
;
115 /* Hardware Initialization */
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.
123 void EVENT_USB_Device_Connect(void)
125 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
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.
131 void EVENT_USB_Device_Disconnect(void)
133 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
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.
139 void EVENT_USB_Device_ConfigurationChanged(void)
141 bool ConfigSuccess
= true;
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);
148 /* Indicate endpoint configuration success or failure */
149 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY
: LEDMASK_USB_ERROR
);
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
156 void EVENT_USB_Device_ControlRequest(void)
158 uint8_t TMCRequestStatus
= TMC_STATUS_SUCCESS
;
160 /* Process TMC specific control requests */
161 switch (USB_ControlRequest
.bRequest
)
163 case Req_InitiateAbortBulkOut
:
164 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_ENDPOINT
))
166 /* Check that no split transaction is already in progress and the data transfer tag is valid */
167 if (RequestInProgress
!= 0)
169 TMCRequestStatus
= TMC_STATUS_SPLIT_IN_PROGRESS
;
171 else if (USB_ControlRequest
.wValue
!= CurrentTransferTag
)
173 TMCRequestStatus
= TMC_STATUS_TRANSFER_NOT_IN_PROGRESS
;
177 /* Indicate that all in-progress/pending data OUT requests should be aborted */
178 IsTMCBulkOUTReset
= true;
180 /* Save the split request for later checking when a new request is received */
181 RequestInProgress
= Req_InitiateAbortBulkOut
;
184 Endpoint_ClearSETUP();
186 /* Write the request response byte */
187 Endpoint_Write_8(TMCRequestStatus
);
190 Endpoint_ClearStatusStage();
194 case Req_CheckAbortBulkOutStatus
:
195 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_ENDPOINT
))
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
;
203 RequestInProgress
= 0;
205 Endpoint_ClearSETUP();
207 /* Write the request response bytes */
208 Endpoint_Write_8(TMCRequestStatus
);
209 Endpoint_Write_16_LE(0);
210 Endpoint_Write_32_LE(LastTransferLength
);
213 Endpoint_ClearStatusStage();
217 case Req_InitiateAbortBulkIn
:
218 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_ENDPOINT
))
220 /* Check that no split transaction is already in progress and the data transfer tag is valid */
221 if (RequestInProgress
!= 0)
223 TMCRequestStatus
= TMC_STATUS_SPLIT_IN_PROGRESS
;
225 else if (USB_ControlRequest
.wValue
!= CurrentTransferTag
)
227 TMCRequestStatus
= TMC_STATUS_TRANSFER_NOT_IN_PROGRESS
;
231 /* Indicate that all in-progress/pending data IN requests should be aborted */
232 IsTMCBulkINReset
= true;
234 /* Save the split request for later checking when a new request is received */
235 RequestInProgress
= Req_InitiateAbortBulkIn
;
238 Endpoint_ClearSETUP();
240 /* Write the request response bytes */
241 Endpoint_Write_8(TMCRequestStatus
);
242 Endpoint_Write_8(CurrentTransferTag
);
245 Endpoint_ClearStatusStage();
249 case Req_CheckAbortBulkInStatus
:
250 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_ENDPOINT
))
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
;
258 RequestInProgress
= 0;
260 Endpoint_ClearSETUP();
262 /* Write the request response bytes */
263 Endpoint_Write_8(TMCRequestStatus
);
264 Endpoint_Write_16_LE(0);
265 Endpoint_Write_32_LE(LastTransferLength
);
268 Endpoint_ClearStatusStage();
272 case Req_InitiateClear
:
273 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
275 /* Check that no split transaction is already in progress */
276 if (RequestInProgress
!= 0)
278 Endpoint_Write_8(TMC_STATUS_SPLIT_IN_PROGRESS
);
282 /* Indicate that all in-progress/pending data IN and OUT requests should be aborted */
283 IsTMCBulkINReset
= true;
284 IsTMCBulkOUTReset
= true;
286 /* Save the split request for later checking when a new request is received */
287 RequestInProgress
= Req_InitiateClear
;
290 Endpoint_ClearSETUP();
292 /* Write the request response byte */
293 Endpoint_Write_8(TMCRequestStatus
);
296 Endpoint_ClearStatusStage();
300 case Req_CheckClearStatus
:
301 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
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
;
309 RequestInProgress
= 0;
311 Endpoint_ClearSETUP();
313 /* Write the request response bytes */
314 Endpoint_Write_8(TMCRequestStatus
);
318 Endpoint_ClearStatusStage();
322 case Req_GetCapabilities
:
323 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
325 Endpoint_ClearSETUP();
327 /* Write the device capabilities to the control endpoint */
328 Endpoint_Write_Control_Stream_LE(&Capabilities
, sizeof(TMC_Capabilities_t
));
336 void ProcessSentMessage(uint8_t* const Data
, const uint8_t Length
)
338 if (strncmp((char*)Data
, "*IDN?", 5) == 0)
339 strcpy((char*)NextResponseBuffer
, "LUFA TMC DEMO");
341 NextResponseLen
= strlen((char*)NextResponseBuffer
);
344 uint8_t GetNextMessage(uint8_t* const Data
)
346 strcpy((char*)NextResponseBuffer
, "LUFA TMC DEMO");
348 NextResponseLen
= strlen((char*)NextResponseBuffer
);
350 uint8_t DataLen
= MIN(NextResponseLen
, 64);
352 strlcpy((char*)Data
, (char*)NextResponseBuffer
, DataLen
);
357 /** Function to manage TMC data transmission and reception to and from the host. */
360 /* Device must be connected and configured for the task to run */
361 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
364 TMC_MessageHeader_t MessageHeader
;
365 uint8_t MessagePayload
[128];
367 /* Try to read in a TMC message from the interface, process if one is available */
368 if (ReadTMCHeader(&MessageHeader
))
371 LEDs_SetAllLEDs(LEDMASK_USB_BUSY
);
373 switch (MessageHeader
.MessageID
)
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
)
380 if (IsTMCBulkOUTReset
)
386 ProcessSentMessage(MessagePayload
, LastTransferLength
);
388 case TMC_MESSAGEID_DEV_DEP_MSG_IN
:
391 MessageHeader
.TransferSize
= GetNextMessage(MessagePayload
);
392 MessageHeader
.MessageIDSpecific
.DeviceOUT
.LastMessageTransaction
= true;
393 WriteTMCHeader(&MessageHeader
);
395 LastTransferLength
= 0;
396 while (Endpoint_Write_Stream_LE(MessagePayload
, MessageHeader
.TransferSize
, &LastTransferLength
) ==
397 ENDPOINT_RWSTREAM_IncompleteTransfer
)
399 if (IsTMCBulkINReset
)
406 Endpoint_StallTransaction();
410 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
413 /* All pending data has been processed - reset the data abort flags */
414 IsTMCBulkINReset
= false;
415 IsTMCBulkOUTReset
= false;
418 /** Attempts to read in the TMC message header from the TMC interface.
420 * \param[out] MessageHeader Pointer to a location where the read header (if any) should be stored
422 * \return Boolean \c true if a header was read, \c false otherwise
424 bool ReadTMCHeader(TMC_MessageHeader_t
* const MessageHeader
)
426 uint16_t BytesTransferred
;
429 /* Select the Data Out endpoint */
430 Endpoint_SelectEndpoint(TMC_OUT_EPADDR
);
432 /* Abort if no command has been sent from the host */
433 if (!(Endpoint_IsOUTReceived()))
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
)
441 if (IsTMCBulkOUTReset
)
445 /* Store the new command tag value for later use */
446 CurrentTransferTag
= MessageHeader
->Tag
;
448 /* Indicate if the command has been aborted or not */
449 return (!(IsTMCBulkOUTReset
) && (ErrorCode
== ENDPOINT_RWSTREAM_NoError
));
452 bool WriteTMCHeader(TMC_MessageHeader_t
* const MessageHeader
)
454 uint16_t BytesTransferred
;
457 /* Set the message tag of the command header */
458 MessageHeader
->Tag
= CurrentTransferTag
;
459 MessageHeader
->InverseTag
= ~CurrentTransferTag
;
461 /* Select the Data In endpoint */
462 Endpoint_SelectEndpoint(TMC_IN_EPADDR
);
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
)
469 if (IsTMCBulkINReset
)
473 /* Indicate if the command has been aborted or not */
474 return (!(IsTMCBulkINReset
) && (ErrorCode
== ENDPOINT_RWSTREAM_NoError
));