Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

USBHost_t36.h 59KB

7 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  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 MIDIDeviceBase : 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. MIDIDeviceBase(USBHost &host, uint32_t *rx, uint32_t *tx1, uint32_t *tx2,
  844. uint16_t bufsize, uint32_t *rqueue, uint16_t qsize) :
  845. rx_buffer(rx), tx_buffer1(tx1), tx_buffer2(tx2),
  846. rx_queue(rqueue), max_packet_size(bufsize), rx_queue_size(qsize) {
  847. init();
  848. }
  849. void sendNoteOff(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  850. send(0x80, note, velocity, channel, cable);
  851. }
  852. void sendNoteOn(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  853. send(0x90, note, velocity, channel, cable);
  854. }
  855. void sendPolyPressure(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  856. send(0xA0, note, pressure, channel, cable);
  857. }
  858. void sendAfterTouchPoly(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  859. send(0xA0, note, pressure, channel, cable);
  860. }
  861. void sendControlChange(uint8_t control, uint8_t value, uint8_t channel, uint8_t cable=0) {
  862. send(0xB0, control, value, channel, cable);
  863. }
  864. void sendProgramChange(uint8_t program, uint8_t channel, uint8_t cable=0) {
  865. send(0xC0, program, 0, channel, cable);
  866. }
  867. void sendAfterTouch(uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  868. send(0xD0, pressure, 0, channel, cable);
  869. }
  870. void sendPitchBend(int value, uint8_t channel, uint8_t cable=0) {
  871. if (value < -8192) {
  872. value = -8192;
  873. } else if (value > 8191) {
  874. value = 8191;
  875. }
  876. value += 8192;
  877. send(0xE0, value, value >> 7, channel, cable);
  878. }
  879. void sendSysEx(uint32_t length, const uint8_t *data, bool hasTerm=false, uint8_t cable=0) {
  880. //if (cable >= MIDI_NUM_CABLES) return;
  881. if (hasTerm) {
  882. send_sysex_buffer_has_term(data, length, cable);
  883. } else {
  884. send_sysex_add_term_bytes(data, length, cable);
  885. }
  886. }
  887. void sendRealTime(uint8_t type, uint8_t cable=0) {
  888. switch (type) {
  889. case 0xF8: // Clock
  890. case 0xFA: // Start
  891. case 0xFB: // Continue
  892. case 0xFC: // Stop
  893. case 0xFE: // ActiveSensing
  894. case 0xFF: // SystemReset
  895. send(type, 0, 0, 0, cable);
  896. break;
  897. default: // Invalid Real Time marker
  898. break;
  899. }
  900. }
  901. void sendTimeCodeQuarterFrame(uint8_t type, uint8_t value, uint8_t cable=0) {
  902. send(0xF1, ((type & 0x07) << 4) | (value & 0x0F), 0, 0, cable);
  903. }
  904. void sendSongPosition(uint16_t beats, uint8_t cable=0) {
  905. send(0xF2, beats, beats >> 7, 0, cable);
  906. }
  907. void sendSongSelect(uint8_t song, uint8_t cable=0) {
  908. send(0xF3, song, 0, 0, cable);
  909. }
  910. void sendTuneRequest(uint8_t cable=0) {
  911. send(0xF6, 0, 0, 0, cable);
  912. }
  913. void beginRpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  914. sendControlChange(101, number >> 7, channel, cable);
  915. sendControlChange(100, number, channel, cable);
  916. }
  917. void sendRpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  918. sendControlChange(6, value >> 7, channel, cable);
  919. sendControlChange(38, value, channel, cable);
  920. }
  921. void sendRpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  922. sendControlChange(96, amount, channel, cable);
  923. }
  924. void sendRpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  925. sendControlChange(97, amount, channel, cable);
  926. }
  927. void endRpn(uint8_t channel, uint8_t cable=0) {
  928. sendControlChange(101, 0x7F, channel, cable);
  929. sendControlChange(100, 0x7F, channel, cable);
  930. }
  931. void beginNrpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  932. sendControlChange(99, number >> 7, channel, cable);
  933. sendControlChange(98, number, channel, cable);
  934. }
  935. void sendNrpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  936. sendControlChange(6, value >> 7, channel, cable);
  937. sendControlChange(38, value, channel, cable);
  938. }
  939. void sendNrpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  940. sendControlChange(96, amount, channel, cable);
  941. }
  942. void sendNrpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  943. sendControlChange(97, amount, channel, cable);
  944. }
  945. void endNrpn(uint8_t channel, uint8_t cable=0) {
  946. sendControlChange(99, 0x7F, channel, cable);
  947. sendControlChange(98, 0x7F, channel, cable);
  948. }
  949. void send(uint8_t type, uint8_t data1, uint8_t data2, uint8_t channel, uint8_t cable=0) {
  950. //if (cable >= MIDI_NUM_CABLES) return;
  951. if (type < 0xF0) {
  952. if (type < 0x80) return;
  953. type &= 0xF0;
  954. write_packed((type << 8) | (type >> 4) | ((cable & 0x0F) << 4)
  955. | (((channel - 1) & 0x0F) << 8) | ((data1 & 0x7F) << 16)
  956. | ((data2 & 0x7F) << 24));
  957. } else if (type >= 0xF8 || type == 0xF6) {
  958. write_packed((type << 8) | 0x0F | ((cable & 0x0F) << 4));
  959. } else if (type == 0xF1 || type == 0xF3) {
  960. write_packed((type << 8) | 0x02 | ((cable & 0x0F) << 4)
  961. | ((data1 & 0x7F) << 16));
  962. } else if (type == 0xF2) {
  963. write_packed((type << 8) | 0x03 | ((cable & 0x0F) << 4)
  964. | ((data1 & 0x7F) << 16) | ((data2 & 0x7F) << 24));
  965. }
  966. }
  967. void send_now(void) __attribute__((always_inline)) {
  968. }
  969. bool read(uint8_t channel=0);
  970. uint8_t getType(void) {
  971. return msg_type;
  972. };
  973. uint8_t getCable(void) {
  974. return msg_cable;
  975. }
  976. uint8_t getChannel(void) {
  977. return msg_channel;
  978. };
  979. uint8_t getData1(void) {
  980. return msg_data1;
  981. };
  982. uint8_t getData2(void) {
  983. return msg_data2;
  984. };
  985. uint8_t * getSysExArray(void) {
  986. return msg_sysex;
  987. }
  988. uint16_t getSysExArrayLength(void) {
  989. return msg_data2 << 8 | msg_data1;
  990. }
  991. void setHandleNoteOff(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  992. // type: 0x80 NoteOff
  993. handleNoteOff = fptr;
  994. }
  995. void setHandleNoteOn(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  996. // type: 0x90 NoteOn
  997. handleNoteOn = fptr;
  998. }
  999. void setHandleVelocityChange(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1000. // type: 0xA0 AfterTouchPoly
  1001. handleVelocityChange = fptr;
  1002. }
  1003. void setHandleAfterTouchPoly(void (*fptr)(uint8_t channel, uint8_t note, uint8_t pressure)) {
  1004. // type: 0xA0 AfterTouchPoly
  1005. handleVelocityChange = fptr;
  1006. }
  1007. void setHandleControlChange(void (*fptr)(uint8_t channel, uint8_t control, uint8_t value)) {
  1008. // type: 0xB0 ControlChange
  1009. handleControlChange = fptr;
  1010. }
  1011. void setHandleProgramChange(void (*fptr)(uint8_t channel, uint8_t program)) {
  1012. // type: 0xC0 ProgramChange
  1013. handleProgramChange = fptr;
  1014. }
  1015. void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1016. // type: 0xD0 AfterTouchChannel
  1017. handleAfterTouch = fptr;
  1018. }
  1019. void setHandleAfterTouchChannel(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1020. // type: 0xD0 AfterTouchChannel
  1021. handleAfterTouch = fptr;
  1022. }
  1023. void setHandlePitchChange(void (*fptr)(uint8_t channel, int pitch)) {
  1024. // type: 0xE0 PitchBend
  1025. handlePitchChange = fptr;
  1026. }
  1027. void setHandleSysEx(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)(const uint8_t *data, uint16_t length, bool complete)) {
  1032. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1033. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1034. }
  1035. void setHandleSystemExclusive(void (*fptr)(uint8_t *data, unsigned int size)) {
  1036. // type: 0xF0 SystemExclusive - single call, message larger than buffer is truncated
  1037. handleSysExComplete = fptr;
  1038. }
  1039. void setHandleTimeCodeQuarterFrame(void (*fptr)(uint8_t data)) {
  1040. // type: 0xF1 TimeCodeQuarterFrame
  1041. handleTimeCodeQuarterFrame = fptr;
  1042. }
  1043. void setHandleSongPosition(void (*fptr)(uint16_t beats)) {
  1044. // type: 0xF2 SongPosition
  1045. handleSongPosition = fptr;
  1046. }
  1047. void setHandleSongSelect(void (*fptr)(uint8_t songnumber)) {
  1048. // type: 0xF3 SongSelect
  1049. handleSongSelect = fptr;
  1050. }
  1051. void setHandleTuneRequest(void (*fptr)(void)) {
  1052. // type: 0xF6 TuneRequest
  1053. handleTuneRequest = fptr;
  1054. }
  1055. void setHandleClock(void (*fptr)(void)) {
  1056. // type: 0xF8 Clock
  1057. handleClock = fptr;
  1058. }
  1059. void setHandleStart(void (*fptr)(void)) {
  1060. // type: 0xFA Start
  1061. handleStart = fptr;
  1062. }
  1063. void setHandleContinue(void (*fptr)(void)) {
  1064. // type: 0xFB Continue
  1065. handleContinue = fptr;
  1066. }
  1067. void setHandleStop(void (*fptr)(void)) {
  1068. // type: 0xFC Stop
  1069. handleStop = fptr;
  1070. }
  1071. void setHandleActiveSensing(void (*fptr)(void)) {
  1072. // type: 0xFE ActiveSensing
  1073. handleActiveSensing = fptr;
  1074. }
  1075. void setHandleSystemReset(void (*fptr)(void)) {
  1076. // type: 0xFF SystemReset
  1077. handleSystemReset = fptr;
  1078. }
  1079. void setHandleRealTimeSystem(void (*fptr)(uint8_t realtimebyte)) {
  1080. // type: 0xF8-0xFF - if more specific handler not configured
  1081. handleRealTimeSystem = fptr;
  1082. }
  1083. protected:
  1084. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1085. virtual void disconnect();
  1086. static void rx_callback(const Transfer_t *transfer);
  1087. static void tx_callback(const Transfer_t *transfer);
  1088. void rx_data(const Transfer_t *transfer);
  1089. void tx_data(const Transfer_t *transfer);
  1090. void init();
  1091. void write_packed(uint32_t data);
  1092. void send_sysex_buffer_has_term(const uint8_t *data, uint32_t length, uint8_t cable);
  1093. void send_sysex_add_term_bytes(const uint8_t *data, uint32_t length, uint8_t cable);
  1094. void sysex_byte(uint8_t b);
  1095. private:
  1096. Pipe_t *rxpipe;
  1097. Pipe_t *txpipe;
  1098. //enum { MAX_PACKET_SIZE = 64 };
  1099. //enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1100. //uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  1101. //uint32_t tx_buffer1[MAX_PACKET_SIZE/4];
  1102. //uint32_t tx_buffer2[MAX_PACKET_SIZE/4];
  1103. uint32_t * const rx_buffer;
  1104. uint32_t * const tx_buffer1;
  1105. uint32_t * const tx_buffer2;
  1106. uint16_t rx_size;
  1107. uint16_t tx_size;
  1108. //uint32_t rx_queue[RX_QUEUE_SIZE];
  1109. uint32_t * const rx_queue;
  1110. bool rx_packet_queued;
  1111. const uint16_t max_packet_size;
  1112. const uint16_t rx_queue_size;
  1113. uint16_t rx_head;
  1114. uint16_t rx_tail;
  1115. volatile uint8_t tx1_count;
  1116. volatile uint8_t tx2_count;
  1117. uint8_t rx_ep;
  1118. uint8_t tx_ep;
  1119. uint8_t rx_ep_type;
  1120. uint8_t tx_ep_type;
  1121. uint8_t msg_cable;
  1122. uint8_t msg_channel;
  1123. uint8_t msg_type;
  1124. uint8_t msg_data1;
  1125. uint8_t msg_data2;
  1126. uint8_t msg_sysex[SYSEX_MAX_LEN];
  1127. uint16_t msg_sysex_len;
  1128. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  1129. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  1130. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  1131. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  1132. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  1133. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  1134. void (*handlePitchChange)(uint8_t ch, int pitch);
  1135. void (*handleSysExPartial)(const uint8_t *data, uint16_t length, uint8_t complete);
  1136. void (*handleSysExComplete)(uint8_t *data, unsigned int size);
  1137. void (*handleTimeCodeQuarterFrame)(uint8_t data);
  1138. void (*handleSongPosition)(uint16_t beats);
  1139. void (*handleSongSelect)(uint8_t songnumber);
  1140. void (*handleTuneRequest)(void);
  1141. void (*handleClock)(void);
  1142. void (*handleStart)(void);
  1143. void (*handleContinue)(void);
  1144. void (*handleStop)(void);
  1145. void (*handleActiveSensing)(void);
  1146. void (*handleSystemReset)(void);
  1147. void (*handleRealTimeSystem)(uint8_t rtb);
  1148. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1149. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1150. strbuf_t mystring_bufs[1];
  1151. };
  1152. class MIDIDevice : public MIDIDeviceBase {
  1153. public:
  1154. MIDIDevice(USBHost &host) :
  1155. MIDIDeviceBase(host, rx, tx1, tx2, MAX_PACKET_SIZE, queue, RX_QUEUE_SIZE) {};
  1156. // MIDIDevice(USBHost *host) : ....
  1157. private:
  1158. enum { MAX_PACKET_SIZE = 64 };
  1159. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1160. uint32_t rx[MAX_PACKET_SIZE/4];
  1161. uint32_t tx1[MAX_PACKET_SIZE/4];
  1162. uint32_t tx2[MAX_PACKET_SIZE/4];
  1163. uint32_t queue[RX_QUEUE_SIZE];
  1164. };
  1165. class MIDIDevice_BigBuffer : public MIDIDeviceBase {
  1166. public:
  1167. MIDIDevice_BigBuffer(USBHost &host) :
  1168. MIDIDeviceBase(host, rx, tx1, tx2, MAX_PACKET_SIZE, queue, RX_QUEUE_SIZE) {};
  1169. // MIDIDevice(USBHost *host) : ....
  1170. private:
  1171. enum { MAX_PACKET_SIZE = 512 };
  1172. enum { RX_QUEUE_SIZE = 400 }; // must be more than MAX_PACKET_SIZE/4
  1173. uint32_t rx[MAX_PACKET_SIZE/4];
  1174. uint32_t tx1[MAX_PACKET_SIZE/4];
  1175. uint32_t tx2[MAX_PACKET_SIZE/4];
  1176. uint32_t queue[RX_QUEUE_SIZE];
  1177. };
  1178. //--------------------------------------------------------------------------
  1179. class USBSerial: public USBDriver, public Stream {
  1180. public:
  1181. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  1182. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1183. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  1184. USBSerial(USBHost &host) : txtimer(this) { init(); }
  1185. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  1186. void end(void);
  1187. uint32_t writeTimeout() {return write_timeout_;}
  1188. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  1189. virtual int available(void);
  1190. virtual int peek(void);
  1191. virtual int read(void);
  1192. virtual int availableForWrite();
  1193. virtual size_t write(uint8_t c);
  1194. virtual void flush(void);
  1195. using Print::write;
  1196. protected:
  1197. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1198. virtual void control(const Transfer_t *transfer);
  1199. virtual void disconnect();
  1200. virtual void timer_event(USBDriverTimer *whichTimer);
  1201. private:
  1202. static void rx_callback(const Transfer_t *transfer);
  1203. static void tx_callback(const Transfer_t *transfer);
  1204. void rx_data(const Transfer_t *transfer);
  1205. void tx_data(const Transfer_t *transfer);
  1206. void rx_queue_packets(uint32_t head, uint32_t tail);
  1207. void init();
  1208. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  1209. bool init_buffers(uint32_t rsize, uint32_t tsize);
  1210. void ch341_setBaud(uint8_t byte_index);
  1211. private:
  1212. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1213. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1214. strbuf_t mystring_bufs[1];
  1215. USBDriverTimer txtimer;
  1216. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  1217. setup_t setup;
  1218. uint8_t setupdata[16]; //
  1219. uint32_t baudrate;
  1220. uint32_t format_;
  1221. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  1222. Pipe_t *rxpipe;
  1223. Pipe_t *txpipe;
  1224. uint8_t *rx1; // location for first incoming packet
  1225. uint8_t *rx2; // location for second incoming packet
  1226. uint8_t *rxbuf; // receive circular buffer
  1227. uint8_t *tx1; // location for first outgoing packet
  1228. uint8_t *tx2; // location for second outgoing packet
  1229. uint8_t *txbuf;
  1230. volatile uint16_t rxhead;// receive head
  1231. volatile uint16_t rxtail;// receive tail
  1232. volatile uint16_t txhead;
  1233. volatile uint16_t txtail;
  1234. uint16_t rxsize;// size of receive circular buffer
  1235. uint16_t txsize;// size of transmit circular buffer
  1236. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  1237. volatile uint8_t txstate;
  1238. uint8_t pending_control;
  1239. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  1240. uint8_t pl2303_v1; // Which version do we have
  1241. uint8_t pl2303_v2;
  1242. uint8_t interface;
  1243. bool control_queued; // Is there already a queued control messaged
  1244. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  1245. sertype_t sertype;
  1246. typedef struct {
  1247. uint16_t idVendor;
  1248. uint16_t idProduct;
  1249. sertype_t sertype;
  1250. } product_vendor_mapping_t;
  1251. static product_vendor_mapping_t pid_vid_mapping[];
  1252. };
  1253. //--------------------------------------------------------------------------
  1254. class AntPlus: public USBDriver {
  1255. // Please post any AntPlus feedback or contributions on this forum thread:
  1256. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  1257. public:
  1258. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  1259. void begin(const uint8_t key=0);
  1260. void onStatusChange(void (*function)(int channel, int status)) {
  1261. user_onStatusChange = function;
  1262. }
  1263. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  1264. user_onDeviceID = function;
  1265. }
  1266. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  1267. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  1268. memset(&hrm, 0, sizeof(hrm));
  1269. user_onHeartRateMonitor = f;
  1270. }
  1271. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  1272. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  1273. memset(&spdcad, 0, sizeof(spdcad));
  1274. user_onSpeedCadence = f;
  1275. }
  1276. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  1277. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  1278. memset(&spd, 0, sizeof(spd));
  1279. user_onSpeed = f;
  1280. }
  1281. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  1282. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  1283. memset(&cad, 0, sizeof(cad));
  1284. user_onCadence = f;
  1285. }
  1286. void setWheelCircumference(float meters) {
  1287. wheelCircumference = meters * 1000.0f;
  1288. }
  1289. protected:
  1290. virtual void Task();
  1291. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1292. virtual void disconnect();
  1293. virtual void timer_event(USBDriverTimer *whichTimer);
  1294. private:
  1295. static void rx_callback(const Transfer_t *transfer);
  1296. static void tx_callback(const Transfer_t *transfer);
  1297. void rx_data(const Transfer_t *transfer);
  1298. void tx_data(const Transfer_t *transfer);
  1299. void init();
  1300. size_t write(const void *data, const size_t size);
  1301. int read(void *data, const size_t size);
  1302. void transmit();
  1303. private:
  1304. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1305. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1306. strbuf_t mystring_bufs[1];
  1307. //USBDriverTimer txtimer;
  1308. USBDriverTimer updatetimer;
  1309. Pipe_t *rxpipe;
  1310. Pipe_t *txpipe;
  1311. bool first_update;
  1312. uint8_t txbuffer[240];
  1313. uint8_t rxpacket[64];
  1314. volatile uint16_t txhead;
  1315. volatile uint16_t txtail;
  1316. volatile bool txready;
  1317. volatile uint8_t rxlen;
  1318. volatile bool do_polling;
  1319. private:
  1320. enum _eventi {
  1321. EVENTI_MESSAGE = 0,
  1322. EVENTI_CHANNEL,
  1323. EVENTI_TOTAL
  1324. };
  1325. enum _profiles {
  1326. PROFILE_HRM = 0,
  1327. PROFILE_SPDCAD,
  1328. PROFILE_POWER,
  1329. PROFILE_STRIDE,
  1330. PROFILE_SPEED,
  1331. PROFILE_CADENCE,
  1332. PROFILE_TOTAL
  1333. };
  1334. typedef struct {
  1335. uint8_t channel;
  1336. uint8_t RFFreq;
  1337. uint8_t networkNumber;
  1338. uint8_t stub;
  1339. uint8_t searchTimeout;
  1340. uint8_t channelType;
  1341. uint8_t deviceType;
  1342. uint8_t transType;
  1343. uint16_t channelPeriod;
  1344. uint16_t searchWaveform;
  1345. uint32_t deviceNumber; // deviceId
  1346. struct {
  1347. uint8_t chanIdOnce;
  1348. uint8_t keyAccepted;
  1349. uint8_t profileValid;
  1350. uint8_t channelStatus;
  1351. uint8_t channelStatusOld;
  1352. } flags;
  1353. } TDCONFIG;
  1354. struct {
  1355. uint8_t initOnce;
  1356. uint8_t key; // key index
  1357. int iDevice; // index to the antplus we're interested in, if > one found
  1358. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1359. } ant;
  1360. void (*user_onStatusChange)(int channel, int status);
  1361. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1362. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1363. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1364. void (*user_onSpeed)(float speed, float distance);
  1365. void (*user_onCadence)(float cadence);
  1366. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1367. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1368. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1369. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1370. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1371. static int msgGetLength(uint8_t *stream);
  1372. int handleMessages(uint8_t *buffer, int tBytes);
  1373. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1374. void message_channel(const int chan, const int eventId,
  1375. const uint8_t *payload, const size_t dataLength);
  1376. void message_response(const int chan, const int msgId,
  1377. const uint8_t *payload, const size_t dataLength);
  1378. void message_event(const int channel, const int msgId,
  1379. const uint8_t *payload, const size_t dataLength);
  1380. int ResetSystem();
  1381. int RequestMessage(const int channel, const int message);
  1382. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1383. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1384. int SetChannelPeriod(const int channel, const int period);
  1385. int SetChannelRFFreq(const int channel, const int freq);
  1386. int SetSearchWaveform(const int channel, const int wave);
  1387. int OpenChannel(const int channel);
  1388. int CloseChannel(const int channel);
  1389. int AssignChannel(const int channel, const int channelType, const int network);
  1390. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1391. const int transmissionType);
  1392. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1393. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1394. int SendBroadcastData(const int channel, const uint8_t *data);
  1395. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1396. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1397. const int TranType, const uint8_t *data);
  1398. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1399. const int TranType, const uint8_t *data);
  1400. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1401. const int devType, const int TranType, const uint8_t *data);
  1402. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1403. const int tranType, const uint8_t *data, const int nunPackets);
  1404. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1405. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1406. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1407. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1408. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1409. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1410. struct {
  1411. struct {
  1412. uint8_t bpm;
  1413. uint8_t sequence;
  1414. uint16_t time;
  1415. } previous;
  1416. } hrm;
  1417. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1418. struct {
  1419. struct {
  1420. uint16_t cadenceTime;
  1421. uint16_t cadenceCt;
  1422. uint16_t speedTime;
  1423. uint16_t speedCt;
  1424. } previous;
  1425. float distance;
  1426. } spdcad;
  1427. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1428. /* struct {
  1429. struct {
  1430. uint8_t sequence;
  1431. uint16_t pedalPowerContribution;
  1432. uint8_t pedalPower;
  1433. uint8_t instantCadence;
  1434. uint16_t sumPower;
  1435. uint16_t instantPower;
  1436. } current;
  1437. struct {
  1438. uint16_t stub;
  1439. } previous;
  1440. } pwr; */
  1441. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1442. /* struct {
  1443. struct {
  1444. uint16_t speed;
  1445. uint16_t cadence;
  1446. uint8_t strides;
  1447. } current;
  1448. struct {
  1449. uint8_t strides;
  1450. uint16_t speed;
  1451. uint16_t cadence;
  1452. } previous;
  1453. } stride; */
  1454. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1455. struct {
  1456. struct {
  1457. uint16_t speedTime;
  1458. uint16_t speedCt;
  1459. } previous;
  1460. float distance;
  1461. } spd;
  1462. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1463. struct {
  1464. struct {
  1465. uint16_t cadenceTime;
  1466. uint16_t cadenceCt;
  1467. } previous;
  1468. } cad;
  1469. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1470. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1471. };
  1472. //--------------------------------------------------------------------------
  1473. class RawHIDController : public USBHIDInput {
  1474. public:
  1475. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1476. uint32_t usage(void) {return usage_;}
  1477. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1478. bool sendPacket(const uint8_t *buffer);
  1479. protected:
  1480. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1481. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1482. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1483. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1484. virtual void hid_input_data(uint32_t usage, int32_t value);
  1485. virtual void hid_input_end();
  1486. virtual void disconnect_collection(Device_t *dev);
  1487. private:
  1488. void init();
  1489. USBHIDParser *driver_;
  1490. enum { MAX_PACKET_SIZE = 64 };
  1491. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1492. uint8_t collections_claimed = 0;
  1493. //volatile bool hid_input_begin_ = false;
  1494. uint32_t fixed_usage_;
  1495. uint32_t usage_ = 0;
  1496. // See if we can contribute transfers
  1497. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1498. };
  1499. #endif