Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestAndMeasurement.c 14KB

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