Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #ifndef USB_HOST_TEENSY36_
  24. #define USB_HOST_TEENSY36_
  25. #include <stdint.h>
  26. #if !defined(__MK66FX1M0__) && !defined(__IMXRT1052__) && !defined(__IMXRT1062__)
  27. #error "USBHost_t36 only works with Teensy 3.6. Please select it in Tools > Boards"
  28. #endif
  29. #include "utility/imxrt_usbhs.h"
  30. // Dear inquisitive reader, USB is a complex protocol defined with
  31. // very specific terminology. To have any chance of understand this
  32. // source code, you absolutely must have solid knowledge of specific
  33. // USB terms such as host, device, endpoint, pipe, enumeration....
  34. // You really must also have at least a basic knowledge of the
  35. // different USB transfers: control, bulk, interrupt, isochronous.
  36. //
  37. // The USB 2.0 specification explains these in chapter 4 (pages 15
  38. // to 24), and provides more detail in the first part of chapter 5
  39. // (pages 25 to 55). The USB spec is published for free at
  40. // www.usb.org. Here is a convenient link to just the main PDF:
  41. //
  42. // https://www.pjrc.com/teensy/beta/usb20.pdf
  43. //
  44. // This is a huge file, but chapter 4 is short and easy to read.
  45. // If you're not familiar with the USB lingo, please do yourself
  46. // a favor by reading at least chapter 4 to get up to speed on the
  47. // meaning of these important USB concepts and terminology.
  48. //
  49. // If you wish to ask questions (which belong on the forum, not
  50. // github issues) or discuss development of this library, you
  51. // ABSOLUTELY MUST know the basic USB terminology from chapter 4.
  52. // Please repect other people's valuable time & effort by making
  53. // your best effort to read chapter 4 before asking USB questions!
  54. //#define USBHOST_PRINT_DEBUG
  55. /************************************************/
  56. /* Data Types */
  57. /************************************************/
  58. // These 6 types are the key to understanding how this USB Host
  59. // library really works.
  60. // USBHost is a static class controlling the hardware.
  61. // All common USB functionality is implemented here.
  62. class USBHost;
  63. // These 3 structures represent the actual USB entities
  64. // USBHost manipulates. One Device_t is created for
  65. // each active USB device. One Pipe_t is create for
  66. // each endpoint. Transfer_t structures are created
  67. // when any data transfer is added to the EHCI work
  68. // queues, and then returned to the free pool after the
  69. // data transfer completes and the driver has processed
  70. // the results.
  71. typedef struct Device_struct Device_t;
  72. typedef struct Pipe_struct Pipe_t;
  73. typedef struct Transfer_struct Transfer_t;
  74. typedef enum { CLAIM_NO=0, CLAIM_REPORT, CLAIM_INTERFACE} hidclaim_t;
  75. // All USB device drivers inherit use these classes.
  76. // Drivers build user-visible functionality on top
  77. // of these classes, which receive USB events from
  78. // USBHost.
  79. class USBDriver;
  80. class USBDriverTimer;
  81. /************************************************/
  82. /* Added Defines */
  83. /************************************************/
  84. // Keyboard special Keys
  85. #define KEYD_UP 0xDA
  86. #define KEYD_DOWN 0xD9
  87. #define KEYD_LEFT 0xD8
  88. #define KEYD_RIGHT 0xD7
  89. #define KEYD_INSERT 0xD1
  90. #define KEYD_DELETE 0xD4
  91. #define KEYD_PAGE_UP 0xD3
  92. #define KEYD_PAGE_DOWN 0xD6
  93. #define KEYD_HOME 0xD2
  94. #define KEYD_END 0xD5
  95. #define KEYD_F1 0xC2
  96. #define KEYD_F2 0xC3
  97. #define KEYD_F3 0xC4
  98. #define KEYD_F4 0xC5
  99. #define KEYD_F5 0xC6
  100. #define KEYD_F6 0xC7
  101. #define KEYD_F7 0xC8
  102. #define KEYD_F8 0xC9
  103. #define KEYD_F9 0xCA
  104. #define KEYD_F10 0xCB
  105. #define KEYD_F11 0xCC
  106. #define KEYD_F12 0xCD
  107. // USBSerial formats - Lets encode format into bits
  108. // Bits: 0-4 - Number of data bits
  109. // Bits: 5-7 - Parity (0=none, 1=odd, 2 = even)
  110. // bits: 8-9 - Stop bits. 0=1, 1=2
  111. #define USBHOST_SERIAL_7E1 0x047
  112. #define USBHOST_SERIAL_7O1 0x027
  113. #define USBHOST_SERIAL_8N1 0x08
  114. #define USBHOST_SERIAL_8N2 0x108
  115. #define USBHOST_SERIAL_8E1 0x048
  116. #define USBHOST_SERIAL_8O1 0x028
  117. /************************************************/
  118. /* Data Structure Definitions */
  119. /************************************************/
  120. // setup_t holds the 8 byte USB SETUP packet data.
  121. // These unions & structs allow convenient access to
  122. // the setup fields.
  123. typedef union {
  124. struct {
  125. union {
  126. struct {
  127. uint8_t bmRequestType;
  128. uint8_t bRequest;
  129. };
  130. uint16_t wRequestAndType;
  131. };
  132. uint16_t wValue;
  133. uint16_t wIndex;
  134. uint16_t wLength;
  135. };
  136. struct {
  137. uint32_t word1;
  138. uint32_t word2;
  139. };
  140. } setup_t;
  141. typedef struct {
  142. enum {STRING_BUF_SIZE=50};
  143. enum {STR_ID_MAN=0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
  144. uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
  145. uint8_t buffer[STRING_BUF_SIZE];
  146. } strbuf_t;
  147. #define DEVICE_STRUCT_STRING_BUF_SIZE 50
  148. // Device_t holds all the information about a USB device
  149. struct Device_struct {
  150. Pipe_t *control_pipe;
  151. Pipe_t *data_pipes;
  152. Device_t *next;
  153. USBDriver *drivers;
  154. strbuf_t *strbuf;
  155. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  156. uint8_t address;
  157. uint8_t hub_address;
  158. uint8_t hub_port;
  159. uint8_t enum_state;
  160. uint8_t bDeviceClass;
  161. uint8_t bDeviceSubClass;
  162. uint8_t bDeviceProtocol;
  163. uint8_t bmAttributes;
  164. uint8_t bMaxPower;
  165. uint16_t idVendor;
  166. uint16_t idProduct;
  167. uint16_t LanguageID;
  168. };
  169. // Pipe_t holes all information about each USB endpoint/pipe
  170. // The first half is an EHCI QH structure for the pipe.
  171. struct Pipe_struct {
  172. // Queue Head (QH), EHCI page 46-50
  173. struct { // must be aligned to 32 byte boundary
  174. volatile uint32_t horizontal_link;
  175. volatile uint32_t capabilities[2];
  176. volatile uint32_t current;
  177. volatile uint32_t next;
  178. volatile uint32_t alt_next;
  179. volatile uint32_t token;
  180. volatile uint32_t buffer[5];
  181. } qh;
  182. Device_t *device;
  183. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  184. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  185. uint8_t start_mask;
  186. uint8_t complete_mask;
  187. Pipe_t *next;
  188. void (*callback_function)(const Transfer_t *);
  189. uint16_t periodic_interval;
  190. uint16_t periodic_offset;
  191. uint16_t bandwidth_interval;
  192. uint16_t bandwidth_offset;
  193. uint16_t bandwidth_shift;
  194. uint8_t bandwidth_stime;
  195. uint8_t bandwidth_ctime;
  196. uint32_t unused1;
  197. uint32_t unused2;
  198. uint32_t unused3;
  199. uint32_t unused4;
  200. uint32_t unused5;
  201. };
  202. // Transfer_t represents a single transaction on the USB bus.
  203. // The first portion is an EHCI qTD structure. Transfer_t are
  204. // allocated as-needed from a memory pool, loaded with pointers
  205. // to the actual data buffers, linked into a followup list,
  206. // and placed on ECHI Queue Heads. When the ECHI interrupt
  207. // occurs, the followup lists are used to find the Transfer_t
  208. // in memory. Callbacks are made, and then the Transfer_t are
  209. // returned to the memory pool.
  210. struct Transfer_struct {
  211. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  212. struct { // must be aligned to 32 byte boundary
  213. volatile uint32_t next;
  214. volatile uint32_t alt_next;
  215. volatile uint32_t token;
  216. volatile uint32_t buffer[5];
  217. } qtd;
  218. // Linked list of queued, not-yet-completed transfers
  219. Transfer_t *next_followup;
  220. Transfer_t *prev_followup;
  221. Pipe_t *pipe;
  222. // Data to be used by callback function. When a group
  223. // of Transfer_t are created, these fields and the
  224. // interrupt-on-complete bit in the qTD token are only
  225. // set in the last Transfer_t of the list.
  226. void *buffer;
  227. uint32_t length;
  228. setup_t setup;
  229. USBDriver *driver;
  230. };
  231. /************************************************/
  232. /* Main USB EHCI Controller */
  233. /************************************************/
  234. class USBHost {
  235. public:
  236. static void begin();
  237. static void Task();
  238. static void countFree(uint32_t &devices, uint32_t &pipes, uint32_t &trans, uint32_t &strs);
  239. protected:
  240. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  241. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  242. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  243. void *buf, USBDriver *driver);
  244. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  245. uint32_t len, USBDriver *driver);
  246. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  247. static void disconnect_Device(Device_t *dev);
  248. static void enumeration(const Transfer_t *transfer);
  249. static void driver_ready_for_device(USBDriver *driver);
  250. static volatile bool enumeration_busy;
  251. public: // Maybe others may want/need to contribute memory example HID devices may want to add transfers.
  252. static void contribute_Devices(Device_t *devices, uint32_t num);
  253. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  254. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  255. static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
  256. private:
  257. static void isr();
  258. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  259. static void claim_drivers(Device_t *dev);
  260. static uint32_t assign_address(void);
  261. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  262. static void init_Device_Pipe_Transfer_memory(void);
  263. static Device_t * allocate_Device(void);
  264. static void delete_Pipe(Pipe_t *pipe);
  265. static void free_Device(Device_t *q);
  266. static Pipe_t * allocate_Pipe(void);
  267. static void free_Pipe(Pipe_t *q);
  268. static Transfer_t * allocate_Transfer(void);
  269. static void free_Transfer(Transfer_t *q);
  270. static strbuf_t * allocate_string_buffer(void);
  271. static void free_string_buffer(strbuf_t *strbuf);
  272. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  273. uint32_t maxlen, uint32_t interval);
  274. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  275. static bool followup_Transfer(Transfer_t *transfer);
  276. static void followup_Error(void);
  277. protected:
  278. #ifdef USBHOST_PRINT_DEBUG
  279. static void print_(const Transfer_t *transfer);
  280. static void print_(const Transfer_t *first, const Transfer_t *last);
  281. static void print_token(uint32_t token);
  282. static void print_(const Pipe_t *pipe);
  283. static void print_driverlist(const char *name, const USBDriver *driver);
  284. static void print_qh_list(const Pipe_t *list);
  285. static void print_device_descriptor(const uint8_t *p);
  286. static void print_config_descriptor(const uint8_t *p, uint32_t maxlen);
  287. static void print_string_descriptor(const char *name, const uint8_t *p);
  288. static void print_hexbytes(const void *ptr, uint32_t len);
  289. static void print_(const char *s) { Serial.print(s); }
  290. static void print_(int n) { Serial.print(n); }
  291. static void print_(unsigned int n) { Serial.print(n); }
  292. static void print_(long n) { Serial.print(n); }
  293. static void print_(unsigned long n) { Serial.print(n); }
  294. static void println_(const char *s) { Serial.println(s); }
  295. static void println_(int n) { Serial.println(n); }
  296. static void println_(unsigned int n) { Serial.println(n); }
  297. static void println_(long n) { Serial.println(n); }
  298. static void println_(unsigned long n) { Serial.println(n); }
  299. static void println_() { Serial.println(); }
  300. static void print_(uint32_t n, uint8_t b) { Serial.print(n, b); }
  301. static void println_(uint32_t n, uint8_t b) { Serial.println(n, b); }
  302. static void print_(const char *s, int n, uint8_t b = DEC) {
  303. Serial.print(s); Serial.print(n, b); }
  304. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  305. Serial.print(s); Serial.print(n, b); }
  306. static void print_(const char *s, long n, uint8_t b = DEC) {
  307. Serial.print(s); Serial.print(n, b); }
  308. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  309. Serial.print(s); Serial.print(n, b); }
  310. static void println_(const char *s, int n, uint8_t b = DEC) {
  311. Serial.print(s); Serial.println(n, b); }
  312. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  313. Serial.print(s); Serial.println(n, b); }
  314. static void println_(const char *s, long n, uint8_t b = DEC) {
  315. Serial.print(s); Serial.println(n, b); }
  316. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  317. Serial.print(s); Serial.println(n, b); }
  318. friend class USBDriverTimer; // for access to print & println
  319. #else
  320. static void print_(const Transfer_t *transfer) {}
  321. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  322. static void print_token(uint32_t token) {}
  323. static void print_(const Pipe_t *pipe) {}
  324. static void print_driverlist(const char *name, const USBDriver *driver) {}
  325. static void print_qh_list(const Pipe_t *list) {}
  326. static void print_device_descriptor(const uint8_t *p) {}
  327. static void print_config_descriptor(const uint8_t *p, uint32_t maxlen) {}
  328. static void print_string_descriptor(const char *name, const uint8_t *p) {}
  329. static void print_hexbytes(const void *ptr, uint32_t len) {}
  330. static void print_(const char *s) {}
  331. static void print_(int n) {}
  332. static void print_(unsigned int n) {}
  333. static void print_(long n) {}
  334. static void print_(unsigned long n) {}
  335. static void println_(const char *s) {}
  336. static void println_(int n) {}
  337. static void println_(unsigned int n) {}
  338. static void println_(long n) {}
  339. static void println_(unsigned long n) {}
  340. static void println_() {}
  341. static void print_(uint32_t n, uint8_t b) {}
  342. static void println_(uint32_t n, uint8_t b) {}
  343. static void print_(const char *s, int n, uint8_t b = DEC) {}
  344. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  345. static void print_(const char *s, long n, uint8_t b = DEC) {}
  346. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  347. static void println_(const char *s, int n, uint8_t b = DEC) {}
  348. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  349. static void println_(const char *s, long n, uint8_t b = DEC) {}
  350. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  351. #endif
  352. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  353. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  354. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  355. s.word2 = wIndex | (wLength << 16);
  356. }
  357. };
  358. /************************************************/
  359. /* USB Device Driver Common Base Class */
  360. /************************************************/
  361. // All USB device drivers inherit from this base class.
  362. class USBDriver : public USBHost {
  363. public:
  364. operator bool() {
  365. Device_t *dev = *(Device_t * volatile *)&device;
  366. return dev != nullptr;
  367. }
  368. uint16_t idVendor() {
  369. Device_t *dev = *(Device_t * volatile *)&device;
  370. return (dev != nullptr) ? dev->idVendor : 0;
  371. }
  372. uint16_t idProduct() {
  373. Device_t *dev = *(Device_t * volatile *)&device;
  374. return (dev != nullptr) ? dev->idProduct : 0;
  375. }
  376. const uint8_t *manufacturer() {
  377. Device_t *dev = *(Device_t * volatile *)&device;
  378. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  379. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_MAN]];
  380. }
  381. const uint8_t *product() {
  382. Device_t *dev = *(Device_t * volatile *)&device;
  383. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  384. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_PROD]];
  385. }
  386. const uint8_t *serialNumber() {
  387. Device_t *dev = *(Device_t * volatile *)&device;
  388. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  389. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]];
  390. }
  391. protected:
  392. USBDriver() : next(NULL), device(NULL) {}
  393. // Check if a driver wishes to claim a device or interface or group
  394. // of interfaces within a device. When this function returns true,
  395. // the driver is considered bound or loaded for that device. When
  396. // new devices are detected, enumeration.cpp calls this function on
  397. // all unbound driver objects, to give them an opportunity to bind
  398. // to the new device.
  399. // device has its vid&pid, class/subclass fields initialized
  400. // type is 0 for device level, 1 for interface level, 2 for IAD
  401. // descriptors points to the specific descriptor data
  402. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  403. // When an unknown (not chapter 9) control transfer completes, this
  404. // function is called for all drivers bound to the device. Return
  405. // true means this driver originated this control transfer, so no
  406. // more drivers need to be offered an opportunity to process it.
  407. // This function is optional, only needed if the driver uses control
  408. // transfers and wishes to be notified when they complete.
  409. virtual void control(const Transfer_t *transfer) { }
  410. // When any of the USBDriverTimer objects a driver creates generates
  411. // a timer event, this function is called.
  412. virtual void timer_event(USBDriverTimer *whichTimer) { }
  413. // When the user calls USBHost::Task, this Task function for all
  414. // active drivers is called, so they may update state and/or call
  415. // any attached user callback functions.
  416. virtual void Task() { }
  417. // When a device disconnects from the USB, this function is called.
  418. // The driver must free all resources it allocated and update any
  419. // internal state necessary to deal with the possibility of user
  420. // code continuing to call its API. However, pipes and transfers
  421. // are the handled by lower layers, so device drivers do not free
  422. // pipes they created or cancel transfers they had in progress.
  423. virtual void disconnect();
  424. // Drivers are managed by this single-linked list. All inactive
  425. // (not bound to any device) drivers are linked from
  426. // available_drivers in enumeration.cpp. When bound to a device,
  427. // drivers are linked from that Device_t drivers list.
  428. USBDriver *next;
  429. // The device this object instance is bound to. In words, this
  430. // is the specific device this driver is using. When not bound
  431. // to any device, this must be NULL. Drivers may set this to
  432. // any non-NULL value if they are in a state where they do not
  433. // wish to claim any device or interface (eg, if getting data
  434. // from the HID parser).
  435. Device_t *device;
  436. friend class USBHost;
  437. };
  438. // Device drivers may create these timer objects to schedule a timer call
  439. class USBDriverTimer {
  440. public:
  441. USBDriverTimer() { }
  442. USBDriverTimer(USBDriver *d) : driver(d) { }
  443. void init(USBDriver *d) { driver = d; };
  444. void start(uint32_t microseconds);
  445. void stop();
  446. void *pointer;
  447. uint32_t integer;
  448. uint32_t started_micros; // testing only
  449. private:
  450. USBDriver *driver;
  451. uint32_t usec;
  452. USBDriverTimer *next;
  453. USBDriverTimer *prev;
  454. friend class USBHost;
  455. };
  456. // Device drivers may inherit from this base class, if they wish to receive
  457. // HID input data fully decoded by the USBHIDParser driver
  458. class USBHIDParser;
  459. class USBHIDInput {
  460. public:
  461. operator bool() { return (mydevice != nullptr); }
  462. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  463. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  464. const uint8_t *manufacturer()
  465. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  466. const uint8_t *product()
  467. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  468. const uint8_t *serialNumber()
  469. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  470. private:
  471. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  472. virtual bool hid_process_in_data(const Transfer_t *transfer) {return false;}
  473. virtual bool hid_process_out_data(const Transfer_t *transfer) {return false;}
  474. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  475. virtual void hid_input_data(uint32_t usage, int32_t value);
  476. virtual void hid_input_end();
  477. virtual void disconnect_collection(Device_t *dev);
  478. void add_to_list();
  479. USBHIDInput *next;
  480. friend class USBHIDParser;
  481. protected:
  482. Device_t *mydevice = NULL;
  483. };
  484. /************************************************/
  485. /* USB Device Drivers */
  486. /************************************************/
  487. class USBHub : public USBDriver {
  488. public:
  489. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  490. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  491. // Hubs with more more than 7 ports are built from two tiers of hubs
  492. // using 4 or 7 port hub chips. While the USB spec seems to allow
  493. // hubs to have up to 255 ports, in practice all hub chips on the
  494. // market are only 2, 3, 4 or 7 ports.
  495. enum { MAXPORTS = 7 };
  496. typedef uint8_t portbitmask_t;
  497. enum {
  498. PORT_OFF = 0,
  499. PORT_DISCONNECT = 1,
  500. PORT_DEBOUNCE1 = 2,
  501. PORT_DEBOUNCE2 = 3,
  502. PORT_DEBOUNCE3 = 4,
  503. PORT_DEBOUNCE4 = 5,
  504. PORT_DEBOUNCE5 = 6,
  505. PORT_RESET = 7,
  506. PORT_RECOVERY = 8,
  507. PORT_ACTIVE = 9
  508. };
  509. protected:
  510. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  511. virtual void control(const Transfer_t *transfer);
  512. virtual void timer_event(USBDriverTimer *whichTimer);
  513. virtual void disconnect();
  514. void init();
  515. bool can_send_control_now();
  516. void send_poweron(uint32_t port);
  517. void send_getstatus(uint32_t port);
  518. void send_clearstatus_connect(uint32_t port);
  519. void send_clearstatus_enable(uint32_t port);
  520. void send_clearstatus_suspend(uint32_t port);
  521. void send_clearstatus_overcurrent(uint32_t port);
  522. void send_clearstatus_reset(uint32_t port);
  523. void send_setreset(uint32_t port);
  524. void send_setinterface();
  525. static void callback(const Transfer_t *transfer);
  526. void status_change(const Transfer_t *transfer);
  527. void new_port_status(uint32_t port, uint32_t status);
  528. void start_debounce_timer(uint32_t port);
  529. void stop_debounce_timer(uint32_t port);
  530. private:
  531. Device_t mydevices[MAXPORTS];
  532. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  533. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  534. strbuf_t mystring_bufs[1];
  535. USBDriverTimer debouncetimer;
  536. USBDriverTimer resettimer;
  537. setup_t setup;
  538. Pipe_t *changepipe;
  539. Device_t *devicelist[MAXPORTS];
  540. uint32_t changebits;
  541. uint32_t statusbits;
  542. uint8_t hub_desc[16];
  543. uint8_t interface_count;
  544. uint8_t interface_number;
  545. uint8_t altsetting;
  546. uint8_t protocol;
  547. uint8_t endpoint;
  548. uint8_t interval;
  549. uint8_t numports;
  550. uint8_t characteristics;
  551. uint8_t powertime;
  552. uint8_t sending_control_transfer;
  553. uint8_t port_doing_reset;
  554. uint8_t port_doing_reset_speed;
  555. uint8_t portstate[MAXPORTS];
  556. portbitmask_t send_pending_poweron;
  557. portbitmask_t send_pending_getstatus;
  558. portbitmask_t send_pending_clearstatus_connect;
  559. portbitmask_t send_pending_clearstatus_enable;
  560. portbitmask_t send_pending_clearstatus_suspend;
  561. portbitmask_t send_pending_clearstatus_overcurrent;
  562. portbitmask_t send_pending_clearstatus_reset;
  563. portbitmask_t send_pending_setreset;
  564. portbitmask_t debounce_in_use;
  565. static volatile bool reset_busy;
  566. };
  567. //--------------------------------------------------------------------------
  568. class USBHIDParser : public USBDriver {
  569. public:
  570. USBHIDParser(USBHost &host) { init(); }
  571. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  572. bool sendPacket(const uint8_t *buffer, int cb=-1);
  573. void setTXBuffers(uint8_t *buffer1, uint8_t *buffer2, uint8_t cb);
  574. bool sendControlPacket(uint32_t bmRequestType, uint32_t bRequest,
  575. uint32_t wValue, uint32_t wIndex, uint32_t wLength, void *buf);
  576. protected:
  577. enum { TOPUSAGE_LIST_LEN = 4 };
  578. enum { USAGE_LIST_LEN = 24 };
  579. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  580. virtual void control(const Transfer_t *transfer);
  581. virtual void disconnect();
  582. static void in_callback(const Transfer_t *transfer);
  583. static void out_callback(const Transfer_t *transfer);
  584. void in_data(const Transfer_t *transfer);
  585. void out_data(const Transfer_t *transfer);
  586. bool check_if_using_report_id();
  587. void parse();
  588. USBHIDInput * find_driver(uint32_t topusage);
  589. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  590. void init();
  591. // Atempt for RAWhid to take over processing of data
  592. //
  593. uint16_t inSize(void) {return in_size;}
  594. uint16_t outSize(void) {return out_size;}
  595. uint8_t activeSendMask(void) {return txstate;}
  596. private:
  597. Pipe_t *in_pipe;
  598. Pipe_t *out_pipe;
  599. static USBHIDInput *available_hid_drivers_list;
  600. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  601. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  602. uint16_t in_size;
  603. uint16_t out_size;
  604. setup_t setup;
  605. uint8_t descriptor[512];
  606. uint8_t report[64];
  607. uint16_t descsize;
  608. bool use_report_id;
  609. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  610. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  611. strbuf_t mystring_bufs[1];
  612. uint8_t txstate = 0;
  613. uint8_t *tx1 = nullptr;
  614. uint8_t *tx2 = nullptr;
  615. bool hid_driver_claimed_control_ = false;
  616. };
  617. //--------------------------------------------------------------------------
  618. class KeyboardController : public USBDriver , public USBHIDInput {
  619. public:
  620. typedef union {
  621. struct {
  622. uint8_t numLock : 1;
  623. uint8_t capsLock : 1;
  624. uint8_t scrollLock : 1;
  625. uint8_t compose : 1;
  626. uint8_t kana : 1;
  627. uint8_t reserved : 3;
  628. };
  629. uint8_t byte;
  630. } KBDLeds_t;
  631. public:
  632. KeyboardController(USBHost &host) { init(); }
  633. KeyboardController(USBHost *host) { init(); }
  634. // need their own versions as both USBDriver and USBHIDInput provide
  635. uint16_t idVendor();
  636. uint16_t idProduct();
  637. const uint8_t *manufacturer();
  638. const uint8_t *product();
  639. const uint8_t *serialNumber();
  640. // Some methods are in both public classes so we need to figure out which one to use
  641. operator bool() { return (device != nullptr); }
  642. // Main boot keyboard functions.
  643. uint16_t getKey() { return keyCode; }
  644. uint8_t getModifiers() { return modifiers; }
  645. uint8_t getOemKey() { return keyOEM; }
  646. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  647. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  648. void LEDS(uint8_t leds);
  649. uint8_t LEDS() {return leds_.byte;}
  650. void updateLEDS(void);
  651. bool numLock() {return leds_.numLock;}
  652. bool capsLock() {return leds_.capsLock;}
  653. bool scrollLock() {return leds_.scrollLock;}
  654. void numLock(bool f);
  655. void capsLock(bool f);
  656. void scrollLock(bool f);
  657. // Added for extras information.
  658. void attachExtrasPress(void (*f)(uint32_t top, uint16_t code)) { extrasKeyPressedFunction = f; }
  659. void attachExtrasRelease(void (*f)(uint32_t top, uint16_t code)) { extrasKeyReleasedFunction = f; }
  660. void forceBootProtocol();
  661. enum {MAX_KEYS_DOWN=4};
  662. protected:
  663. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  664. virtual void control(const Transfer_t *transfer);
  665. virtual void disconnect();
  666. static void callback(const Transfer_t *transfer);
  667. void new_data(const Transfer_t *transfer);
  668. void init();
  669. protected: // HID functions for extra keyboard data.
  670. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  671. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  672. virtual void hid_input_data(uint32_t usage, int32_t value);
  673. virtual void hid_input_end();
  674. virtual void disconnect_collection(Device_t *dev);
  675. private:
  676. void update();
  677. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  678. void key_press(uint32_t mod, uint32_t key);
  679. void key_release(uint32_t mod, uint32_t key);
  680. void (*keyPressedFunction)(int unicode);
  681. void (*keyReleasedFunction)(int unicode);
  682. Pipe_t *datapipe;
  683. setup_t setup;
  684. uint8_t report[8];
  685. uint16_t keyCode;
  686. uint8_t modifiers;
  687. uint8_t keyOEM;
  688. uint8_t prev_report[8];
  689. KBDLeds_t leds_ = {0};
  690. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  691. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  692. strbuf_t mystring_bufs[1];
  693. // Added to process secondary HID data.
  694. void (*extrasKeyPressedFunction)(uint32_t top, uint16_t code);
  695. void (*extrasKeyReleasedFunction)(uint32_t top, uint16_t code);
  696. uint32_t topusage_ = 0; // What top report am I processing?
  697. uint8_t collections_claimed_ = 0;
  698. volatile bool hid_input_begin_ = false;
  699. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  700. uint8_t count_keys_down_ = 0;
  701. uint16_t keys_down[MAX_KEYS_DOWN];
  702. bool force_boot_protocol; // User or VID/PID said force boot protocol?
  703. bool control_queued;
  704. };
  705. class MouseController : public USBHIDInput {
  706. public:
  707. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  708. bool available() { return mouseEvent; }
  709. void mouseDataClear();
  710. uint8_t getButtons() { return buttons; }
  711. int getMouseX() { return mouseX; }
  712. int getMouseY() { return mouseY; }
  713. int getWheel() { return wheel; }
  714. int getWheelH() { return wheelH; }
  715. protected:
  716. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  717. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  718. virtual void hid_input_data(uint32_t usage, int32_t value);
  719. virtual void hid_input_end();
  720. virtual void disconnect_collection(Device_t *dev);
  721. private:
  722. uint8_t collections_claimed = 0;
  723. volatile bool mouseEvent = false;
  724. volatile bool hid_input_begin_ = false;
  725. uint8_t buttons = 0;
  726. int mouseX = 0;
  727. int mouseY = 0;
  728. int wheel = 0;
  729. int wheelH = 0;
  730. };
  731. //--------------------------------------------------------------------------
  732. class JoystickController : public USBDriver, public USBHIDInput {
  733. public:
  734. JoystickController(USBHost &host) { init(); }
  735. uint16_t idVendor();
  736. uint16_t idProduct();
  737. const uint8_t *manufacturer();
  738. const uint8_t *product();
  739. const uint8_t *serialNumber();
  740. operator bool() { return (((device != nullptr) || (mydevice != nullptr)) && connected_); } // override as in both USBDriver and in USBHIDInput
  741. bool available() { return joystickEvent; }
  742. void joystickDataClear();
  743. uint32_t getButtons() { return buttons; }
  744. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  745. uint64_t axisMask() {return axis_mask_;}
  746. uint64_t axisChangedMask() { return axis_changed_mask_;}
  747. uint64_t axisChangeNotifyMask() {return axis_change_notify_mask_;}
  748. void axisChangeNotifyMask(uint64_t notify_mask) {axis_change_notify_mask_ = notify_mask;}
  749. // set functions functionality depends on underlying joystick.
  750. bool setRumble(uint8_t lValue, uint8_t rValue, uint8_t timeout=0xff);
  751. // setLEDs on PS4(RGB), PS3 simple LED setting (only uses lr)
  752. bool setLEDs(uint8_t lr, uint8_t lg=0, uint8_t lb=0); // sets Leds,
  753. enum { STANDARD_AXIS_COUNT = 10, ADDITIONAL_AXIS_COUNT = 54, TOTAL_AXIS_COUNT = (STANDARD_AXIS_COUNT+ADDITIONAL_AXIS_COUNT) };
  754. typedef enum { UNKNOWN=0, PS3, PS4, XBOXONE, XBOX360} joytype_t;
  755. joytype_t joystickType = UNKNOWN;
  756. protected:
  757. // From USBDriver
  758. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  759. virtual void control(const Transfer_t *transfer);
  760. virtual void disconnect();
  761. // From USBHIDInput
  762. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  763. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  764. virtual void hid_input_data(uint32_t usage, int32_t value);
  765. virtual void hid_input_end();
  766. virtual void disconnect_collection(Device_t *dev);
  767. virtual bool hid_process_out_data(const Transfer_t *transfer);
  768. private:
  769. // Class specific
  770. void init();
  771. USBHIDParser *driver_ = nullptr;
  772. joytype_t mapVIDPIDtoJoystickType(uint16_t idVendor, uint16_t idProduct, bool exclude_hid_devices);
  773. bool transmitPS4UserFeedbackMsg();
  774. bool transmitPS3UserFeedbackMsg();
  775. bool anychange = false;
  776. volatile bool joystickEvent = false;
  777. uint32_t buttons = 0;
  778. int axis[TOTAL_AXIS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  779. uint64_t axis_mask_ = 0; // which axis have valid data
  780. uint64_t axis_changed_mask_ = 0;
  781. uint64_t axis_change_notify_mask_ = 0x3ff; // assume the low 10 values only.
  782. uint16_t additional_axis_usage_page_ = 0;
  783. uint16_t additional_axis_usage_start_ = 0;
  784. uint16_t additional_axis_usage_count_ = 0;
  785. // State values to output to Joystick.
  786. uint8_t rumble_lValue_ = 0;
  787. uint8_t rumble_rValue_ = 0;
  788. uint8_t rumble_timeout_ = 0;
  789. uint8_t leds_[3] = {0,0,0};
  790. uint8_t connected_ = 0; // what type of device if any is connected xbox 360...
  791. // Used by HID code
  792. uint8_t collections_claimed = 0;
  793. // Used by USBDriver code
  794. static void rx_callback(const Transfer_t *transfer);
  795. static void tx_callback(const Transfer_t *transfer);
  796. void rx_data(const Transfer_t *transfer);
  797. void tx_data(const Transfer_t *transfer);
  798. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  799. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  800. strbuf_t mystring_bufs[1];
  801. uint8_t rx_ep_ = 0; // remember which end point this object is...
  802. uint16_t rx_size_ = 0;
  803. uint16_t tx_size_ = 0;
  804. Pipe_t *rxpipe_;
  805. Pipe_t *txpipe_;
  806. uint8_t rxbuf_[64]; // receive circular buffer
  807. uint8_t txbuf_[64]; // buffer to use to send commands to joystick
  808. // Mapping table to say which devices we handle
  809. typedef struct {
  810. uint16_t idVendor;
  811. uint16_t idProduct;
  812. joytype_t joyType;
  813. bool hidDevice;
  814. } product_vendor_mapping_t;
  815. static product_vendor_mapping_t pid_vid_mapping[];
  816. };
  817. //--------------------------------------------------------------------------
  818. class MIDIDevice : public USBDriver {
  819. public:
  820. enum { SYSEX_MAX_LEN = 290 };
  821. // Message type names for compatibility with Arduino MIDI library 4.3.1
  822. enum MidiType {
  823. InvalidType = 0x00, // For notifying errors
  824. NoteOff = 0x80, // Note Off
  825. NoteOn = 0x90, // Note On
  826. AfterTouchPoly = 0xA0, // Polyphonic AfterTouch
  827. ControlChange = 0xB0, // Control Change / Channel Mode
  828. ProgramChange = 0xC0, // Program Change
  829. AfterTouchChannel = 0xD0, // Channel (monophonic) AfterTouch
  830. PitchBend = 0xE0, // Pitch Bend
  831. SystemExclusive = 0xF0, // System Exclusive
  832. TimeCodeQuarterFrame = 0xF1, // System Common - MIDI Time Code Quarter Frame
  833. SongPosition = 0xF2, // System Common - Song Position Pointer
  834. SongSelect = 0xF3, // System Common - Song Select
  835. TuneRequest = 0xF6, // System Common - Tune Request
  836. Clock = 0xF8, // System Real Time - Timing Clock
  837. Start = 0xFA, // System Real Time - Start
  838. Continue = 0xFB, // System Real Time - Continue
  839. Stop = 0xFC, // System Real Time - Stop
  840. ActiveSensing = 0xFE, // System Real Time - Active Sensing
  841. SystemReset = 0xFF, // System Real Time - System Reset
  842. };
  843. MIDIDevice(USBHost &host) { init(); }
  844. MIDIDevice(USBHost *host) { init(); }
  845. void sendNoteOff(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  846. send(0x80, note, velocity, channel, cable);
  847. }
  848. void sendNoteOn(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  849. send(0x90, note, velocity, channel, cable);
  850. }
  851. void sendPolyPressure(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  852. send(0xA0, note, pressure, channel, cable);
  853. }
  854. void sendAfterTouchPoly(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  855. send(0xA0, note, pressure, channel, cable);
  856. }
  857. void sendControlChange(uint8_t control, uint8_t value, uint8_t channel, uint8_t cable=0) {
  858. send(0xB0, control, value, channel, cable);
  859. }
  860. void sendProgramChange(uint8_t program, uint8_t channel, uint8_t cable=0) {
  861. send(0xC0, program, 0, channel, cable);
  862. }
  863. void sendAfterTouch(uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  864. send(0xD0, pressure, 0, channel, cable);
  865. }
  866. void sendPitchBend(int value, uint8_t channel, uint8_t cable=0) {
  867. if (value < -8192) {
  868. value = -8192;
  869. } else if (value > 8191) {
  870. value = 8191;
  871. }
  872. value += 8192;
  873. send(0xE0, value, value >> 7, channel, cable);
  874. }
  875. void sendSysEx(uint32_t length, const uint8_t *data, bool hasTerm=false, uint8_t cable=0) {
  876. //if (cable >= MIDI_NUM_CABLES) return;
  877. if (hasTerm) {
  878. send_sysex_buffer_has_term(data, length, cable);
  879. } else {
  880. send_sysex_add_term_bytes(data, length, cable);
  881. }
  882. }
  883. void sendRealTime(uint8_t type, uint8_t cable=0) {
  884. switch (type) {
  885. case 0xF8: // Clock
  886. case 0xFA: // Start
  887. case 0xFB: // Continue
  888. case 0xFC: // Stop
  889. case 0xFE: // ActiveSensing
  890. case 0xFF: // SystemReset
  891. send(type, 0, 0, 0, cable);
  892. break;
  893. default: // Invalid Real Time marker
  894. break;
  895. }
  896. }
  897. void sendTimeCodeQuarterFrame(uint8_t type, uint8_t value, uint8_t cable=0) {
  898. send(0xF1, ((type & 0x07) << 4) | (value & 0x0F), 0, 0, cable);
  899. }
  900. void sendSongPosition(uint16_t beats, uint8_t cable=0) {
  901. send(0xF2, beats, beats >> 7, 0, cable);
  902. }
  903. void sendSongSelect(uint8_t song, uint8_t cable=0) {
  904. send(0xF3, song, 0, 0, cable);
  905. }
  906. void sendTuneRequest(uint8_t cable=0) {
  907. send(0xF6, 0, 0, 0, cable);
  908. }
  909. void beginRpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  910. sendControlChange(101, number >> 7, channel, cable);
  911. sendControlChange(100, number, channel, cable);
  912. }
  913. void sendRpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  914. sendControlChange(6, value >> 7, channel, cable);
  915. sendControlChange(38, value, channel, cable);
  916. }
  917. void sendRpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  918. sendControlChange(96, amount, channel, cable);
  919. }
  920. void sendRpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  921. sendControlChange(97, amount, channel, cable);
  922. }
  923. void endRpn(uint8_t channel, uint8_t cable=0) {
  924. sendControlChange(101, 0x7F, channel, cable);
  925. sendControlChange(100, 0x7F, channel, cable);
  926. }
  927. void beginNrpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  928. sendControlChange(99, number >> 7, channel, cable);
  929. sendControlChange(98, number, channel, cable);
  930. }
  931. void sendNrpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  932. sendControlChange(6, value >> 7, channel, cable);
  933. sendControlChange(38, value, channel, cable);
  934. }
  935. void sendNrpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  936. sendControlChange(96, amount, channel, cable);
  937. }
  938. void sendNrpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  939. sendControlChange(97, amount, channel, cable);
  940. }
  941. void endNrpn(uint8_t channel, uint8_t cable=0) {
  942. sendControlChange(99, 0x7F, channel, cable);
  943. sendControlChange(98, 0x7F, channel, cable);
  944. }
  945. void send(uint8_t type, uint8_t data1, uint8_t data2, uint8_t channel, uint8_t cable=0) {
  946. //if (cable >= MIDI_NUM_CABLES) return;
  947. if (type < 0xF0) {
  948. if (type < 0x80) return;
  949. type &= 0xF0;
  950. write_packed((type << 8) | (type >> 4) | ((cable & 0x0F) << 4)
  951. | (((channel - 1) & 0x0F) << 8) | ((data1 & 0x7F) << 16)
  952. | ((data2 & 0x7F) << 24));
  953. } else if (type >= 0xF8 || type == 0xF6) {
  954. write_packed((type << 8) | 0x0F | ((cable & 0x0F) << 4));
  955. } else if (type == 0xF1 || type == 0xF3) {
  956. write_packed((type << 8) | 0x02 | ((cable & 0x0F) << 4)
  957. | ((data1 & 0x7F) << 16));
  958. } else if (type == 0xF2) {
  959. write_packed((type << 8) | 0x03 | ((cable & 0x0F) << 4)
  960. | ((data1 & 0x7F) << 16) | ((data2 & 0x7F) << 24));
  961. }
  962. }
  963. void send_now(void) __attribute__((always_inline)) {
  964. }
  965. bool read(uint8_t channel=0);
  966. uint8_t getType(void) {
  967. return msg_type;
  968. };
  969. uint8_t getCable(void) {
  970. return msg_cable;
  971. }
  972. uint8_t getChannel(void) {
  973. return msg_channel;
  974. };
  975. uint8_t getData1(void) {
  976. return msg_data1;
  977. };
  978. uint8_t getData2(void) {
  979. return msg_data2;
  980. };
  981. uint8_t * getSysExArray(void) {
  982. return msg_sysex;
  983. }
  984. uint16_t getSysExArrayLength(void) {
  985. return msg_data2 << 8 | msg_data1;
  986. }
  987. void setHandleNoteOff(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  988. // type: 0x80 NoteOff
  989. handleNoteOff = fptr;
  990. }
  991. void setHandleNoteOn(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  992. // type: 0x90 NoteOn
  993. handleNoteOn = fptr;
  994. }
  995. void setHandleVelocityChange(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  996. // type: 0xA0 AfterTouchPoly
  997. handleVelocityChange = fptr;
  998. }
  999. void setHandleAfterTouchPoly(void (*fptr)(uint8_t channel, uint8_t note, uint8_t pressure)) {
  1000. // type: 0xA0 AfterTouchPoly
  1001. handleVelocityChange = fptr;
  1002. }
  1003. void setHandleControlChange(void (*fptr)(uint8_t channel, uint8_t control, uint8_t value)) {
  1004. // type: 0xB0 ControlChange
  1005. handleControlChange = fptr;
  1006. }
  1007. void setHandleProgramChange(void (*fptr)(uint8_t channel, uint8_t program)) {
  1008. // type: 0xC0 ProgramChange
  1009. handleProgramChange = fptr;
  1010. }
  1011. void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1012. // type: 0xD0 AfterTouchChannel
  1013. handleAfterTouch = fptr;
  1014. }
  1015. void setHandleAfterTouchChannel(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1016. // type: 0xD0 AfterTouchChannel
  1017. handleAfterTouch = fptr;
  1018. }
  1019. void setHandlePitchChange(void (*fptr)(uint8_t channel, int pitch)) {
  1020. // type: 0xE0 PitchBend
  1021. handlePitchChange = fptr;
  1022. }
  1023. void setHandleSysEx(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1024. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1025. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1026. }
  1027. void setHandleSystemExclusive(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1028. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1029. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1030. }
  1031. void setHandleSystemExclusive(void (*fptr)(uint8_t *data, unsigned int size)) {
  1032. // type: 0xF0 SystemExclusive - single call, message larger than buffer is truncated
  1033. handleSysExComplete = fptr;
  1034. }
  1035. void setHandleTimeCodeQuarterFrame(void (*fptr)(uint8_t data)) {
  1036. // type: 0xF1 TimeCodeQuarterFrame
  1037. handleTimeCodeQuarterFrame = fptr;
  1038. }
  1039. void setHandleSongPosition(void (*fptr)(uint16_t beats)) {
  1040. // type: 0xF2 SongPosition
  1041. handleSongPosition = fptr;
  1042. }
  1043. void setHandleSongSelect(void (*fptr)(uint8_t songnumber)) {
  1044. // type: 0xF3 SongSelect
  1045. handleSongSelect = fptr;
  1046. }
  1047. void setHandleTuneRequest(void (*fptr)(void)) {
  1048. // type: 0xF6 TuneRequest
  1049. handleTuneRequest = fptr;
  1050. }
  1051. void setHandleClock(void (*fptr)(void)) {
  1052. // type: 0xF8 Clock
  1053. handleClock = fptr;
  1054. }
  1055. void setHandleStart(void (*fptr)(void)) {
  1056. // type: 0xFA Start
  1057. handleStart = fptr;
  1058. }
  1059. void setHandleContinue(void (*fptr)(void)) {
  1060. // type: 0xFB Continue
  1061. handleContinue = fptr;
  1062. }
  1063. void setHandleStop(void (*fptr)(void)) {
  1064. // type: 0xFC Stop
  1065. handleStop = fptr;
  1066. }
  1067. void setHandleActiveSensing(void (*fptr)(void)) {
  1068. // type: 0xFE ActiveSensing
  1069. handleActiveSensing = fptr;
  1070. }
  1071. void setHandleSystemReset(void (*fptr)(void)) {
  1072. // type: 0xFF SystemReset
  1073. handleSystemReset = fptr;
  1074. }
  1075. void setHandleRealTimeSystem(void (*fptr)(uint8_t realtimebyte)) {
  1076. // type: 0xF8-0xFF - if more specific handler not configured
  1077. handleRealTimeSystem = fptr;
  1078. }
  1079. protected:
  1080. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1081. virtual void disconnect();
  1082. static void rx_callback(const Transfer_t *transfer);
  1083. static void tx_callback(const Transfer_t *transfer);
  1084. void rx_data(const Transfer_t *transfer);
  1085. void tx_data(const Transfer_t *transfer);
  1086. void init();
  1087. void write_packed(uint32_t data);
  1088. void send_sysex_buffer_has_term(const uint8_t *data, uint32_t length, uint8_t cable);
  1089. void send_sysex_add_term_bytes(const uint8_t *data, uint32_t length, uint8_t cable);
  1090. void sysex_byte(uint8_t b);
  1091. private:
  1092. Pipe_t *rxpipe;
  1093. Pipe_t *txpipe;
  1094. enum { MAX_PACKET_SIZE = 64 };
  1095. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1096. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  1097. uint32_t tx_buffer1[MAX_PACKET_SIZE/4];
  1098. uint32_t tx_buffer2[MAX_PACKET_SIZE/4];
  1099. uint16_t rx_size;
  1100. uint16_t tx_size;
  1101. uint32_t rx_queue[RX_QUEUE_SIZE];
  1102. bool rx_packet_queued;
  1103. uint16_t rx_head;
  1104. uint16_t rx_tail;
  1105. volatile uint8_t tx1_count;
  1106. volatile uint8_t tx2_count;
  1107. uint8_t rx_ep;
  1108. uint8_t tx_ep;
  1109. uint8_t rx_ep_type;
  1110. uint8_t tx_ep_type;
  1111. uint8_t msg_cable;
  1112. uint8_t msg_channel;
  1113. uint8_t msg_type;
  1114. uint8_t msg_data1;
  1115. uint8_t msg_data2;
  1116. uint8_t msg_sysex[SYSEX_MAX_LEN];
  1117. uint16_t msg_sysex_len;
  1118. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  1119. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  1120. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  1121. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  1122. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  1123. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  1124. void (*handlePitchChange)(uint8_t ch, int pitch);
  1125. void (*handleSysExPartial)(const uint8_t *data, uint16_t length, uint8_t complete);
  1126. void (*handleSysExComplete)(uint8_t *data, unsigned int size);
  1127. void (*handleTimeCodeQuarterFrame)(uint8_t data);
  1128. void (*handleSongPosition)(uint16_t beats);
  1129. void (*handleSongSelect)(uint8_t songnumber);
  1130. void (*handleTuneRequest)(void);
  1131. void (*handleClock)(void);
  1132. void (*handleStart)(void);
  1133. void (*handleContinue)(void);
  1134. void (*handleStop)(void);
  1135. void (*handleActiveSensing)(void);
  1136. void (*handleSystemReset)(void);
  1137. void (*handleRealTimeSystem)(uint8_t rtb);
  1138. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1139. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1140. strbuf_t mystring_bufs[1];
  1141. };
  1142. //--------------------------------------------------------------------------
  1143. class USBSerial: public USBDriver, public Stream {
  1144. public:
  1145. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  1146. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1147. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  1148. USBSerial(USBHost &host) : txtimer(this) { init(); }
  1149. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  1150. void end(void);
  1151. uint32_t writeTimeout() {return write_timeout_;}
  1152. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  1153. virtual int available(void);
  1154. virtual int peek(void);
  1155. virtual int read(void);
  1156. virtual int availableForWrite();
  1157. virtual size_t write(uint8_t c);
  1158. virtual void flush(void);
  1159. using Print::write;
  1160. protected:
  1161. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1162. virtual void control(const Transfer_t *transfer);
  1163. virtual void disconnect();
  1164. virtual void timer_event(USBDriverTimer *whichTimer);
  1165. private:
  1166. static void rx_callback(const Transfer_t *transfer);
  1167. static void tx_callback(const Transfer_t *transfer);
  1168. void rx_data(const Transfer_t *transfer);
  1169. void tx_data(const Transfer_t *transfer);
  1170. void rx_queue_packets(uint32_t head, uint32_t tail);
  1171. void init();
  1172. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  1173. bool init_buffers(uint32_t rsize, uint32_t tsize);
  1174. void ch341_setBaud(uint8_t byte_index);
  1175. private:
  1176. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1177. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1178. strbuf_t mystring_bufs[1];
  1179. USBDriverTimer txtimer;
  1180. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  1181. setup_t setup;
  1182. uint8_t setupdata[16]; //
  1183. uint32_t baudrate;
  1184. uint32_t format_;
  1185. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  1186. Pipe_t *rxpipe;
  1187. Pipe_t *txpipe;
  1188. uint8_t *rx1; // location for first incoming packet
  1189. uint8_t *rx2; // location for second incoming packet
  1190. uint8_t *rxbuf; // receive circular buffer
  1191. uint8_t *tx1; // location for first outgoing packet
  1192. uint8_t *tx2; // location for second outgoing packet
  1193. uint8_t *txbuf;
  1194. volatile uint16_t rxhead;// receive head
  1195. volatile uint16_t rxtail;// receive tail
  1196. volatile uint16_t txhead;
  1197. volatile uint16_t txtail;
  1198. uint16_t rxsize;// size of receive circular buffer
  1199. uint16_t txsize;// size of transmit circular buffer
  1200. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  1201. volatile uint8_t txstate;
  1202. uint8_t pending_control;
  1203. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  1204. uint8_t pl2303_v1; // Which version do we have
  1205. uint8_t pl2303_v2;
  1206. uint8_t interface;
  1207. bool control_queued; // Is there already a queued control messaged
  1208. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  1209. sertype_t sertype;
  1210. typedef struct {
  1211. uint16_t idVendor;
  1212. uint16_t idProduct;
  1213. sertype_t sertype;
  1214. } product_vendor_mapping_t;
  1215. static product_vendor_mapping_t pid_vid_mapping[];
  1216. };
  1217. //--------------------------------------------------------------------------
  1218. class AntPlus: public USBDriver {
  1219. // Please post any AntPlus feedback or contributions on this forum thread:
  1220. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  1221. public:
  1222. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  1223. void begin(const uint8_t key=0);
  1224. void onStatusChange(void (*function)(int channel, int status)) {
  1225. user_onStatusChange = function;
  1226. }
  1227. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  1228. user_onDeviceID = function;
  1229. }
  1230. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  1231. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  1232. memset(&hrm, 0, sizeof(hrm));
  1233. user_onHeartRateMonitor = f;
  1234. }
  1235. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  1236. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  1237. memset(&spdcad, 0, sizeof(spdcad));
  1238. user_onSpeedCadence = f;
  1239. }
  1240. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  1241. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  1242. memset(&spd, 0, sizeof(spd));
  1243. user_onSpeed = f;
  1244. }
  1245. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  1246. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  1247. memset(&cad, 0, sizeof(cad));
  1248. user_onCadence = f;
  1249. }
  1250. void setWheelCircumference(float meters) {
  1251. wheelCircumference = meters * 1000.0f;
  1252. }
  1253. protected:
  1254. virtual void Task();
  1255. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1256. virtual void disconnect();
  1257. virtual void timer_event(USBDriverTimer *whichTimer);
  1258. private:
  1259. static void rx_callback(const Transfer_t *transfer);
  1260. static void tx_callback(const Transfer_t *transfer);
  1261. void rx_data(const Transfer_t *transfer);
  1262. void tx_data(const Transfer_t *transfer);
  1263. void init();
  1264. size_t write(const void *data, const size_t size);
  1265. int read(void *data, const size_t size);
  1266. void transmit();
  1267. private:
  1268. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1269. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1270. strbuf_t mystring_bufs[1];
  1271. //USBDriverTimer txtimer;
  1272. USBDriverTimer updatetimer;
  1273. Pipe_t *rxpipe;
  1274. Pipe_t *txpipe;
  1275. bool first_update;
  1276. uint8_t txbuffer[240];
  1277. uint8_t rxpacket[64];
  1278. volatile uint16_t txhead;
  1279. volatile uint16_t txtail;
  1280. volatile bool txready;
  1281. volatile uint8_t rxlen;
  1282. volatile bool do_polling;
  1283. private:
  1284. enum _eventi {
  1285. EVENTI_MESSAGE = 0,
  1286. EVENTI_CHANNEL,
  1287. EVENTI_TOTAL
  1288. };
  1289. enum _profiles {
  1290. PROFILE_HRM = 0,
  1291. PROFILE_SPDCAD,
  1292. PROFILE_POWER,
  1293. PROFILE_STRIDE,
  1294. PROFILE_SPEED,
  1295. PROFILE_CADENCE,
  1296. PROFILE_TOTAL
  1297. };
  1298. typedef struct {
  1299. uint8_t channel;
  1300. uint8_t RFFreq;
  1301. uint8_t networkNumber;
  1302. uint8_t stub;
  1303. uint8_t searchTimeout;
  1304. uint8_t channelType;
  1305. uint8_t deviceType;
  1306. uint8_t transType;
  1307. uint16_t channelPeriod;
  1308. uint16_t searchWaveform;
  1309. uint32_t deviceNumber; // deviceId
  1310. struct {
  1311. uint8_t chanIdOnce;
  1312. uint8_t keyAccepted;
  1313. uint8_t profileValid;
  1314. uint8_t channelStatus;
  1315. uint8_t channelStatusOld;
  1316. } flags;
  1317. } TDCONFIG;
  1318. struct {
  1319. uint8_t initOnce;
  1320. uint8_t key; // key index
  1321. int iDevice; // index to the antplus we're interested in, if > one found
  1322. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1323. } ant;
  1324. void (*user_onStatusChange)(int channel, int status);
  1325. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1326. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1327. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1328. void (*user_onSpeed)(float speed, float distance);
  1329. void (*user_onCadence)(float cadence);
  1330. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1331. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1332. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1333. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1334. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1335. static int msgGetLength(uint8_t *stream);
  1336. int handleMessages(uint8_t *buffer, int tBytes);
  1337. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1338. void message_channel(const int chan, const int eventId,
  1339. const uint8_t *payload, const size_t dataLength);
  1340. void message_response(const int chan, const int msgId,
  1341. const uint8_t *payload, const size_t dataLength);
  1342. void message_event(const int channel, const int msgId,
  1343. const uint8_t *payload, const size_t dataLength);
  1344. int ResetSystem();
  1345. int RequestMessage(const int channel, const int message);
  1346. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1347. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1348. int SetChannelPeriod(const int channel, const int period);
  1349. int SetChannelRFFreq(const int channel, const int freq);
  1350. int SetSearchWaveform(const int channel, const int wave);
  1351. int OpenChannel(const int channel);
  1352. int CloseChannel(const int channel);
  1353. int AssignChannel(const int channel, const int channelType, const int network);
  1354. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1355. const int transmissionType);
  1356. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1357. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1358. int SendBroadcastData(const int channel, const uint8_t *data);
  1359. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1360. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1361. const int TranType, const uint8_t *data);
  1362. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1363. const int TranType, const uint8_t *data);
  1364. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1365. const int devType, const int TranType, const uint8_t *data);
  1366. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1367. const int tranType, const uint8_t *data, const int nunPackets);
  1368. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1369. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1370. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1371. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1372. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1373. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1374. struct {
  1375. struct {
  1376. uint8_t bpm;
  1377. uint8_t sequence;
  1378. uint16_t time;
  1379. } previous;
  1380. } hrm;
  1381. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1382. struct {
  1383. struct {
  1384. uint16_t cadenceTime;
  1385. uint16_t cadenceCt;
  1386. uint16_t speedTime;
  1387. uint16_t speedCt;
  1388. } previous;
  1389. float distance;
  1390. } spdcad;
  1391. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1392. /* struct {
  1393. struct {
  1394. uint8_t sequence;
  1395. uint16_t pedalPowerContribution;
  1396. uint8_t pedalPower;
  1397. uint8_t instantCadence;
  1398. uint16_t sumPower;
  1399. uint16_t instantPower;
  1400. } current;
  1401. struct {
  1402. uint16_t stub;
  1403. } previous;
  1404. } pwr; */
  1405. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1406. /* struct {
  1407. struct {
  1408. uint16_t speed;
  1409. uint16_t cadence;
  1410. uint8_t strides;
  1411. } current;
  1412. struct {
  1413. uint8_t strides;
  1414. uint16_t speed;
  1415. uint16_t cadence;
  1416. } previous;
  1417. } stride; */
  1418. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1419. struct {
  1420. struct {
  1421. uint16_t speedTime;
  1422. uint16_t speedCt;
  1423. } previous;
  1424. float distance;
  1425. } spd;
  1426. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1427. struct {
  1428. struct {
  1429. uint16_t cadenceTime;
  1430. uint16_t cadenceCt;
  1431. } previous;
  1432. } cad;
  1433. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1434. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1435. };
  1436. //--------------------------------------------------------------------------
  1437. class RawHIDController : public USBHIDInput {
  1438. public:
  1439. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1440. uint32_t usage(void) {return usage_;}
  1441. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1442. bool sendPacket(const uint8_t *buffer);
  1443. protected:
  1444. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1445. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1446. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1447. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1448. virtual void hid_input_data(uint32_t usage, int32_t value);
  1449. virtual void hid_input_end();
  1450. virtual void disconnect_collection(Device_t *dev);
  1451. private:
  1452. void init();
  1453. USBHIDParser *driver_;
  1454. enum { MAX_PACKET_SIZE = 64 };
  1455. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1456. uint8_t collections_claimed = 0;
  1457. //volatile bool hid_input_begin_ = false;
  1458. uint32_t fixed_usage_;
  1459. uint32_t usage_ = 0;
  1460. // See if we can contribute transfers
  1461. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1462. };
  1463. #endif