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

USBHost_t36.h 64KB

8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  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 = NULL;
  480. friend class USBHIDParser;
  481. protected:
  482. Device_t *mydevice = NULL;
  483. };
  484. // Device drivers may inherit from this base class, if they wish to receive
  485. // HID input like data from Bluetooth HID device.
  486. class BluetoothController;
  487. class BTHIDInput {
  488. public:
  489. operator bool() { return (btdevice != nullptr); }
  490. uint16_t idVendor() { return (btdevice != nullptr) ? btdevice->idVendor : 0; }
  491. uint16_t idProduct() { return (btdevice != nullptr) ? btdevice->idProduct : 0; }
  492. const uint8_t *manufacturer()
  493. { return ((btdevice == nullptr) || (btdevice->strbuf == nullptr)) ? nullptr : &btdevice->strbuf->buffer[btdevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  494. const uint8_t *product()
  495. { return ((btdevice == nullptr) || (btdevice->strbuf == nullptr)) ? nullptr : &btdevice->strbuf->buffer[btdevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  496. const uint8_t *serialNumber()
  497. { return ((btdevice == nullptr) || (btdevice->strbuf == nullptr)) ? nullptr : &btdevice->strbuf->buffer[btdevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  498. private:
  499. virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class) {return false;}
  500. virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length) {return false;}
  501. virtual void release_bluetooth() {};
  502. void add_to_list();
  503. BTHIDInput *next = NULL;
  504. friend class BluetoothController;
  505. protected:
  506. Device_t *btdevice = NULL;
  507. };
  508. /************************************************/
  509. /* USB Device Drivers */
  510. /************************************************/
  511. class USBHub : public USBDriver {
  512. public:
  513. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  514. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  515. // Hubs with more more than 7 ports are built from two tiers of hubs
  516. // using 4 or 7 port hub chips. While the USB spec seems to allow
  517. // hubs to have up to 255 ports, in practice all hub chips on the
  518. // market are only 2, 3, 4 or 7 ports.
  519. enum { MAXPORTS = 7 };
  520. typedef uint8_t portbitmask_t;
  521. enum {
  522. PORT_OFF = 0,
  523. PORT_DISCONNECT = 1,
  524. PORT_DEBOUNCE1 = 2,
  525. PORT_DEBOUNCE2 = 3,
  526. PORT_DEBOUNCE3 = 4,
  527. PORT_DEBOUNCE4 = 5,
  528. PORT_DEBOUNCE5 = 6,
  529. PORT_RESET = 7,
  530. PORT_RECOVERY = 8,
  531. PORT_ACTIVE = 9
  532. };
  533. protected:
  534. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  535. virtual void control(const Transfer_t *transfer);
  536. virtual void timer_event(USBDriverTimer *whichTimer);
  537. virtual void disconnect();
  538. void init();
  539. bool can_send_control_now();
  540. void send_poweron(uint32_t port);
  541. void send_getstatus(uint32_t port);
  542. void send_clearstatus_connect(uint32_t port);
  543. void send_clearstatus_enable(uint32_t port);
  544. void send_clearstatus_suspend(uint32_t port);
  545. void send_clearstatus_overcurrent(uint32_t port);
  546. void send_clearstatus_reset(uint32_t port);
  547. void send_setreset(uint32_t port);
  548. void send_setinterface();
  549. static void callback(const Transfer_t *transfer);
  550. void status_change(const Transfer_t *transfer);
  551. void new_port_status(uint32_t port, uint32_t status);
  552. void start_debounce_timer(uint32_t port);
  553. void stop_debounce_timer(uint32_t port);
  554. private:
  555. Device_t mydevices[MAXPORTS];
  556. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  557. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  558. strbuf_t mystring_bufs[1];
  559. USBDriverTimer debouncetimer;
  560. USBDriverTimer resettimer;
  561. setup_t setup;
  562. Pipe_t *changepipe;
  563. Device_t *devicelist[MAXPORTS];
  564. uint32_t changebits;
  565. uint32_t statusbits;
  566. uint8_t hub_desc[16];
  567. uint8_t interface_count;
  568. uint8_t interface_number;
  569. uint8_t altsetting;
  570. uint8_t protocol;
  571. uint8_t endpoint;
  572. uint8_t interval;
  573. uint8_t numports;
  574. uint8_t characteristics;
  575. uint8_t powertime;
  576. uint8_t sending_control_transfer;
  577. uint8_t port_doing_reset;
  578. uint8_t port_doing_reset_speed;
  579. uint8_t portstate[MAXPORTS];
  580. portbitmask_t send_pending_poweron;
  581. portbitmask_t send_pending_getstatus;
  582. portbitmask_t send_pending_clearstatus_connect;
  583. portbitmask_t send_pending_clearstatus_enable;
  584. portbitmask_t send_pending_clearstatus_suspend;
  585. portbitmask_t send_pending_clearstatus_overcurrent;
  586. portbitmask_t send_pending_clearstatus_reset;
  587. portbitmask_t send_pending_setreset;
  588. portbitmask_t debounce_in_use;
  589. static volatile bool reset_busy;
  590. };
  591. //--------------------------------------------------------------------------
  592. class USBHIDParser : public USBDriver {
  593. public:
  594. USBHIDParser(USBHost &host) { init(); }
  595. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  596. bool sendPacket(const uint8_t *buffer, int cb=-1);
  597. void setTXBuffers(uint8_t *buffer1, uint8_t *buffer2, uint8_t cb);
  598. bool sendControlPacket(uint32_t bmRequestType, uint32_t bRequest,
  599. uint32_t wValue, uint32_t wIndex, uint32_t wLength, void *buf);
  600. protected:
  601. enum { TOPUSAGE_LIST_LEN = 4 };
  602. enum { USAGE_LIST_LEN = 24 };
  603. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  604. virtual void control(const Transfer_t *transfer);
  605. virtual void disconnect();
  606. static void in_callback(const Transfer_t *transfer);
  607. static void out_callback(const Transfer_t *transfer);
  608. void in_data(const Transfer_t *transfer);
  609. void out_data(const Transfer_t *transfer);
  610. bool check_if_using_report_id();
  611. void parse();
  612. USBHIDInput * find_driver(uint32_t topusage);
  613. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  614. void init();
  615. // Atempt for RAWhid to take over processing of data
  616. //
  617. uint16_t inSize(void) {return in_size;}
  618. uint16_t outSize(void) {return out_size;}
  619. uint8_t activeSendMask(void) {return txstate;}
  620. private:
  621. Pipe_t *in_pipe;
  622. Pipe_t *out_pipe;
  623. static USBHIDInput *available_hid_drivers_list;
  624. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  625. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  626. uint16_t in_size;
  627. uint16_t out_size;
  628. setup_t setup;
  629. uint8_t descriptor[512];
  630. uint8_t report[64];
  631. uint16_t descsize;
  632. bool use_report_id;
  633. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  634. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  635. strbuf_t mystring_bufs[1];
  636. uint8_t txstate = 0;
  637. uint8_t *tx1 = nullptr;
  638. uint8_t *tx2 = nullptr;
  639. bool hid_driver_claimed_control_ = false;
  640. };
  641. //--------------------------------------------------------------------------
  642. class KeyboardController : public USBDriver , public USBHIDInput, public BTHIDInput {
  643. public:
  644. typedef union {
  645. struct {
  646. uint8_t numLock : 1;
  647. uint8_t capsLock : 1;
  648. uint8_t scrollLock : 1;
  649. uint8_t compose : 1;
  650. uint8_t kana : 1;
  651. uint8_t reserved : 3;
  652. };
  653. uint8_t byte;
  654. } KBDLeds_t;
  655. public:
  656. KeyboardController(USBHost &host) { init(); }
  657. KeyboardController(USBHost *host) { init(); }
  658. // need their own versions as both USBDriver and USBHIDInput provide
  659. uint16_t idVendor();
  660. uint16_t idProduct();
  661. const uint8_t *manufacturer();
  662. const uint8_t *product();
  663. const uint8_t *serialNumber();
  664. operator bool() { return ((device != nullptr) || (btdevice != nullptr)); }
  665. // Main boot keyboard functions.
  666. uint16_t getKey() { return keyCode; }
  667. uint8_t getModifiers() { return modifiers; }
  668. uint8_t getOemKey() { return keyOEM; }
  669. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  670. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  671. void LEDS(uint8_t leds);
  672. uint8_t LEDS() {return leds_.byte;}
  673. void updateLEDS(void);
  674. bool numLock() {return leds_.numLock;}
  675. bool capsLock() {return leds_.capsLock;}
  676. bool scrollLock() {return leds_.scrollLock;}
  677. void numLock(bool f);
  678. void capsLock(bool f);
  679. void scrollLock(bool f);
  680. // Added for extras information.
  681. void attachExtrasPress(void (*f)(uint32_t top, uint16_t code)) { extrasKeyPressedFunction = f; }
  682. void attachExtrasRelease(void (*f)(uint32_t top, uint16_t code)) { extrasKeyReleasedFunction = f; }
  683. void forceBootProtocol();
  684. enum {MAX_KEYS_DOWN=4};
  685. protected:
  686. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  687. virtual void control(const Transfer_t *transfer);
  688. virtual void disconnect();
  689. static void callback(const Transfer_t *transfer);
  690. void new_data(const Transfer_t *transfer);
  691. void init();
  692. // Bluetooth data
  693. virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class);
  694. virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length);
  695. virtual void release_bluetooth();
  696. protected: // HID functions for extra keyboard data.
  697. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  698. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  699. virtual void hid_input_data(uint32_t usage, int32_t value);
  700. virtual void hid_input_end();
  701. virtual void disconnect_collection(Device_t *dev);
  702. private:
  703. void update();
  704. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  705. void key_press(uint32_t mod, uint32_t key);
  706. void key_release(uint32_t mod, uint32_t key);
  707. void (*keyPressedFunction)(int unicode);
  708. void (*keyReleasedFunction)(int unicode);
  709. Pipe_t *datapipe;
  710. setup_t setup;
  711. uint8_t report[8];
  712. uint16_t keyCode;
  713. uint8_t modifiers;
  714. uint8_t keyOEM;
  715. uint8_t prev_report[8];
  716. KBDLeds_t leds_ = {0};
  717. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  718. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  719. strbuf_t mystring_bufs[1];
  720. // Added to process secondary HID data.
  721. void (*extrasKeyPressedFunction)(uint32_t top, uint16_t code);
  722. void (*extrasKeyReleasedFunction)(uint32_t top, uint16_t code);
  723. uint32_t topusage_ = 0; // What top report am I processing?
  724. uint8_t collections_claimed_ = 0;
  725. volatile bool hid_input_begin_ = false;
  726. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  727. uint8_t count_keys_down_ = 0;
  728. uint16_t keys_down[MAX_KEYS_DOWN];
  729. bool force_boot_protocol; // User or VID/PID said force boot protocol?
  730. bool control_queued;
  731. };
  732. class MouseController : public USBHIDInput {
  733. public:
  734. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  735. bool available() { return mouseEvent; }
  736. void mouseDataClear();
  737. uint8_t getButtons() { return buttons; }
  738. int getMouseX() { return mouseX; }
  739. int getMouseY() { return mouseY; }
  740. int getWheel() { return wheel; }
  741. int getWheelH() { return wheelH; }
  742. protected:
  743. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  744. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  745. virtual void hid_input_data(uint32_t usage, int32_t value);
  746. virtual void hid_input_end();
  747. virtual void disconnect_collection(Device_t *dev);
  748. private:
  749. uint8_t collections_claimed = 0;
  750. volatile bool mouseEvent = false;
  751. volatile bool hid_input_begin_ = false;
  752. uint8_t buttons = 0;
  753. int mouseX = 0;
  754. int mouseY = 0;
  755. int wheel = 0;
  756. int wheelH = 0;
  757. };
  758. //--------------------------------------------------------------------------
  759. class JoystickController : public USBDriver, public USBHIDInput, public BTHIDInput {
  760. public:
  761. JoystickController(USBHost &host) { init(); }
  762. uint16_t idVendor();
  763. uint16_t idProduct();
  764. const uint8_t *manufacturer();
  765. const uint8_t *product();
  766. const uint8_t *serialNumber();
  767. operator bool() { return (((device != nullptr) || (mydevice != nullptr)) && connected_); } // override as in both USBDriver and in USBHIDInput
  768. bool available() { return joystickEvent; }
  769. void joystickDataClear();
  770. uint32_t getButtons() { return buttons; }
  771. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  772. uint64_t axisMask() {return axis_mask_;}
  773. uint64_t axisChangedMask() { return axis_changed_mask_;}
  774. uint64_t axisChangeNotifyMask() {return axis_change_notify_mask_;}
  775. void axisChangeNotifyMask(uint64_t notify_mask) {axis_change_notify_mask_ = notify_mask;}
  776. // set functions functionality depends on underlying joystick.
  777. bool setRumble(uint8_t lValue, uint8_t rValue, uint8_t timeout=0xff);
  778. // setLEDs on PS4(RGB), PS3 simple LED setting (only uses lr)
  779. bool setLEDs(uint8_t lr, uint8_t lg=0, uint8_t lb=0); // sets Leds,
  780. enum { STANDARD_AXIS_COUNT = 10, ADDITIONAL_AXIS_COUNT = 54, TOTAL_AXIS_COUNT = (STANDARD_AXIS_COUNT+ADDITIONAL_AXIS_COUNT) };
  781. typedef enum { UNKNOWN=0, PS3, PS4, XBOXONE, XBOX360} joytype_t;
  782. joytype_t joystickType = UNKNOWN;
  783. protected:
  784. // From USBDriver
  785. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  786. virtual void control(const Transfer_t *transfer);
  787. virtual void disconnect();
  788. // From USBHIDInput
  789. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  790. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  791. virtual void hid_input_data(uint32_t usage, int32_t value);
  792. virtual void hid_input_end();
  793. virtual void disconnect_collection(Device_t *dev);
  794. virtual bool hid_process_out_data(const Transfer_t *transfer);
  795. // Bluetooth data
  796. virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class);
  797. virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length);
  798. virtual void release_bluetooth();
  799. private:
  800. // Class specific
  801. void init();
  802. USBHIDParser *driver_ = nullptr;
  803. joytype_t mapVIDPIDtoJoystickType(uint16_t idVendor, uint16_t idProduct, bool exclude_hid_devices);
  804. bool transmitPS4UserFeedbackMsg();
  805. bool transmitPS3UserFeedbackMsg();
  806. bool anychange = false;
  807. volatile bool joystickEvent = false;
  808. uint32_t buttons = 0;
  809. int axis[TOTAL_AXIS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  810. uint64_t axis_mask_ = 0; // which axis have valid data
  811. uint64_t axis_changed_mask_ = 0;
  812. uint64_t axis_change_notify_mask_ = 0x3ff; // assume the low 10 values only.
  813. uint16_t additional_axis_usage_page_ = 0;
  814. uint16_t additional_axis_usage_start_ = 0;
  815. uint16_t additional_axis_usage_count_ = 0;
  816. // State values to output to Joystick.
  817. uint8_t rumble_lValue_ = 0;
  818. uint8_t rumble_rValue_ = 0;
  819. uint8_t rumble_timeout_ = 0;
  820. uint8_t leds_[3] = {0,0,0};
  821. uint8_t connected_ = 0; // what type of device if any is connected xbox 360...
  822. // Used by HID code
  823. uint8_t collections_claimed = 0;
  824. // Used by USBDriver code
  825. static void rx_callback(const Transfer_t *transfer);
  826. static void tx_callback(const Transfer_t *transfer);
  827. void rx_data(const Transfer_t *transfer);
  828. void tx_data(const Transfer_t *transfer);
  829. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  830. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  831. strbuf_t mystring_bufs[1];
  832. uint8_t rx_ep_ = 0; // remember which end point this object is...
  833. uint16_t rx_size_ = 0;
  834. uint16_t tx_size_ = 0;
  835. Pipe_t *rxpipe_;
  836. Pipe_t *txpipe_;
  837. uint8_t rxbuf_[64]; // receive circular buffer
  838. uint8_t txbuf_[64]; // buffer to use to send commands to joystick
  839. // Mapping table to say which devices we handle
  840. typedef struct {
  841. uint16_t idVendor;
  842. uint16_t idProduct;
  843. joytype_t joyType;
  844. bool hidDevice;
  845. } product_vendor_mapping_t;
  846. static product_vendor_mapping_t pid_vid_mapping[];
  847. };
  848. //--------------------------------------------------------------------------
  849. class MIDIDevice : public USBDriver {
  850. public:
  851. enum { SYSEX_MAX_LEN = 290 };
  852. // Message type names for compatibility with Arduino MIDI library 4.3.1
  853. enum MidiType {
  854. InvalidType = 0x00, // For notifying errors
  855. NoteOff = 0x80, // Note Off
  856. NoteOn = 0x90, // Note On
  857. AfterTouchPoly = 0xA0, // Polyphonic AfterTouch
  858. ControlChange = 0xB0, // Control Change / Channel Mode
  859. ProgramChange = 0xC0, // Program Change
  860. AfterTouchChannel = 0xD0, // Channel (monophonic) AfterTouch
  861. PitchBend = 0xE0, // Pitch Bend
  862. SystemExclusive = 0xF0, // System Exclusive
  863. TimeCodeQuarterFrame = 0xF1, // System Common - MIDI Time Code Quarter Frame
  864. SongPosition = 0xF2, // System Common - Song Position Pointer
  865. SongSelect = 0xF3, // System Common - Song Select
  866. TuneRequest = 0xF6, // System Common - Tune Request
  867. Clock = 0xF8, // System Real Time - Timing Clock
  868. Start = 0xFA, // System Real Time - Start
  869. Continue = 0xFB, // System Real Time - Continue
  870. Stop = 0xFC, // System Real Time - Stop
  871. ActiveSensing = 0xFE, // System Real Time - Active Sensing
  872. SystemReset = 0xFF, // System Real Time - System Reset
  873. };
  874. MIDIDevice(USBHost &host) { init(); }
  875. MIDIDevice(USBHost *host) { init(); }
  876. void sendNoteOff(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  877. send(0x80, note, velocity, channel, cable);
  878. }
  879. void sendNoteOn(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  880. send(0x90, note, velocity, channel, cable);
  881. }
  882. void sendPolyPressure(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  883. send(0xA0, note, pressure, channel, cable);
  884. }
  885. void sendAfterTouchPoly(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  886. send(0xA0, note, pressure, channel, cable);
  887. }
  888. void sendControlChange(uint8_t control, uint8_t value, uint8_t channel, uint8_t cable=0) {
  889. send(0xB0, control, value, channel, cable);
  890. }
  891. void sendProgramChange(uint8_t program, uint8_t channel, uint8_t cable=0) {
  892. send(0xC0, program, 0, channel, cable);
  893. }
  894. void sendAfterTouch(uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  895. send(0xD0, pressure, 0, channel, cable);
  896. }
  897. void sendPitchBend(int value, uint8_t channel, uint8_t cable=0) {
  898. if (value < -8192) {
  899. value = -8192;
  900. } else if (value > 8191) {
  901. value = 8191;
  902. }
  903. value += 8192;
  904. send(0xE0, value, value >> 7, channel, cable);
  905. }
  906. void sendSysEx(uint32_t length, const uint8_t *data, bool hasTerm=false, uint8_t cable=0) {
  907. //if (cable >= MIDI_NUM_CABLES) return;
  908. if (hasTerm) {
  909. send_sysex_buffer_has_term(data, length, cable);
  910. } else {
  911. send_sysex_add_term_bytes(data, length, cable);
  912. }
  913. }
  914. void sendRealTime(uint8_t type, uint8_t cable=0) {
  915. switch (type) {
  916. case 0xF8: // Clock
  917. case 0xFA: // Start
  918. case 0xFB: // Continue
  919. case 0xFC: // Stop
  920. case 0xFE: // ActiveSensing
  921. case 0xFF: // SystemReset
  922. send(type, 0, 0, 0, cable);
  923. break;
  924. default: // Invalid Real Time marker
  925. break;
  926. }
  927. }
  928. void sendTimeCodeQuarterFrame(uint8_t type, uint8_t value, uint8_t cable=0) {
  929. send(0xF1, ((type & 0x07) << 4) | (value & 0x0F), 0, 0, cable);
  930. }
  931. void sendSongPosition(uint16_t beats, uint8_t cable=0) {
  932. send(0xF2, beats, beats >> 7, 0, cable);
  933. }
  934. void sendSongSelect(uint8_t song, uint8_t cable=0) {
  935. send(0xF3, song, 0, 0, cable);
  936. }
  937. void sendTuneRequest(uint8_t cable=0) {
  938. send(0xF6, 0, 0, 0, cable);
  939. }
  940. void beginRpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  941. sendControlChange(101, number >> 7, channel, cable);
  942. sendControlChange(100, number, channel, cable);
  943. }
  944. void sendRpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  945. sendControlChange(6, value >> 7, channel, cable);
  946. sendControlChange(38, value, channel, cable);
  947. }
  948. void sendRpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  949. sendControlChange(96, amount, channel, cable);
  950. }
  951. void sendRpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  952. sendControlChange(97, amount, channel, cable);
  953. }
  954. void endRpn(uint8_t channel, uint8_t cable=0) {
  955. sendControlChange(101, 0x7F, channel, cable);
  956. sendControlChange(100, 0x7F, channel, cable);
  957. }
  958. void beginNrpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  959. sendControlChange(99, number >> 7, channel, cable);
  960. sendControlChange(98, number, channel, cable);
  961. }
  962. void sendNrpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  963. sendControlChange(6, value >> 7, channel, cable);
  964. sendControlChange(38, value, channel, cable);
  965. }
  966. void sendNrpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  967. sendControlChange(96, amount, channel, cable);
  968. }
  969. void sendNrpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  970. sendControlChange(97, amount, channel, cable);
  971. }
  972. void endNrpn(uint8_t channel, uint8_t cable=0) {
  973. sendControlChange(99, 0x7F, channel, cable);
  974. sendControlChange(98, 0x7F, channel, cable);
  975. }
  976. void send(uint8_t type, uint8_t data1, uint8_t data2, uint8_t channel, uint8_t cable=0) {
  977. //if (cable >= MIDI_NUM_CABLES) return;
  978. if (type < 0xF0) {
  979. if (type < 0x80) return;
  980. type &= 0xF0;
  981. write_packed((type << 8) | (type >> 4) | ((cable & 0x0F) << 4)
  982. | (((channel - 1) & 0x0F) << 8) | ((data1 & 0x7F) << 16)
  983. | ((data2 & 0x7F) << 24));
  984. } else if (type >= 0xF8 || type == 0xF6) {
  985. write_packed((type << 8) | 0x0F | ((cable & 0x0F) << 4));
  986. } else if (type == 0xF1 || type == 0xF3) {
  987. write_packed((type << 8) | 0x02 | ((cable & 0x0F) << 4)
  988. | ((data1 & 0x7F) << 16));
  989. } else if (type == 0xF2) {
  990. write_packed((type << 8) | 0x03 | ((cable & 0x0F) << 4)
  991. | ((data1 & 0x7F) << 16) | ((data2 & 0x7F) << 24));
  992. }
  993. }
  994. void send_now(void) __attribute__((always_inline)) {
  995. }
  996. bool read(uint8_t channel=0);
  997. uint8_t getType(void) {
  998. return msg_type;
  999. };
  1000. uint8_t getCable(void) {
  1001. return msg_cable;
  1002. }
  1003. uint8_t getChannel(void) {
  1004. return msg_channel;
  1005. };
  1006. uint8_t getData1(void) {
  1007. return msg_data1;
  1008. };
  1009. uint8_t getData2(void) {
  1010. return msg_data2;
  1011. };
  1012. uint8_t * getSysExArray(void) {
  1013. return msg_sysex;
  1014. }
  1015. uint16_t getSysExArrayLength(void) {
  1016. return msg_data2 << 8 | msg_data1;
  1017. }
  1018. void setHandleNoteOff(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1019. // type: 0x80 NoteOff
  1020. handleNoteOff = fptr;
  1021. }
  1022. void setHandleNoteOn(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1023. // type: 0x90 NoteOn
  1024. handleNoteOn = fptr;
  1025. }
  1026. void setHandleVelocityChange(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1027. // type: 0xA0 AfterTouchPoly
  1028. handleVelocityChange = fptr;
  1029. }
  1030. void setHandleAfterTouchPoly(void (*fptr)(uint8_t channel, uint8_t note, uint8_t pressure)) {
  1031. // type: 0xA0 AfterTouchPoly
  1032. handleVelocityChange = fptr;
  1033. }
  1034. void setHandleControlChange(void (*fptr)(uint8_t channel, uint8_t control, uint8_t value)) {
  1035. // type: 0xB0 ControlChange
  1036. handleControlChange = fptr;
  1037. }
  1038. void setHandleProgramChange(void (*fptr)(uint8_t channel, uint8_t program)) {
  1039. // type: 0xC0 ProgramChange
  1040. handleProgramChange = fptr;
  1041. }
  1042. void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1043. // type: 0xD0 AfterTouchChannel
  1044. handleAfterTouch = fptr;
  1045. }
  1046. void setHandleAfterTouchChannel(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1047. // type: 0xD0 AfterTouchChannel
  1048. handleAfterTouch = fptr;
  1049. }
  1050. void setHandlePitchChange(void (*fptr)(uint8_t channel, int pitch)) {
  1051. // type: 0xE0 PitchBend
  1052. handlePitchChange = fptr;
  1053. }
  1054. void setHandleSysEx(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1055. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1056. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1057. }
  1058. void setHandleSystemExclusive(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1059. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1060. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1061. }
  1062. void setHandleSystemExclusive(void (*fptr)(uint8_t *data, unsigned int size)) {
  1063. // type: 0xF0 SystemExclusive - single call, message larger than buffer is truncated
  1064. handleSysExComplete = fptr;
  1065. }
  1066. void setHandleTimeCodeQuarterFrame(void (*fptr)(uint8_t data)) {
  1067. // type: 0xF1 TimeCodeQuarterFrame
  1068. handleTimeCodeQuarterFrame = fptr;
  1069. }
  1070. void setHandleSongPosition(void (*fptr)(uint16_t beats)) {
  1071. // type: 0xF2 SongPosition
  1072. handleSongPosition = fptr;
  1073. }
  1074. void setHandleSongSelect(void (*fptr)(uint8_t songnumber)) {
  1075. // type: 0xF3 SongSelect
  1076. handleSongSelect = fptr;
  1077. }
  1078. void setHandleTuneRequest(void (*fptr)(void)) {
  1079. // type: 0xF6 TuneRequest
  1080. handleTuneRequest = fptr;
  1081. }
  1082. void setHandleClock(void (*fptr)(void)) {
  1083. // type: 0xF8 Clock
  1084. handleClock = fptr;
  1085. }
  1086. void setHandleStart(void (*fptr)(void)) {
  1087. // type: 0xFA Start
  1088. handleStart = fptr;
  1089. }
  1090. void setHandleContinue(void (*fptr)(void)) {
  1091. // type: 0xFB Continue
  1092. handleContinue = fptr;
  1093. }
  1094. void setHandleStop(void (*fptr)(void)) {
  1095. // type: 0xFC Stop
  1096. handleStop = fptr;
  1097. }
  1098. void setHandleActiveSensing(void (*fptr)(void)) {
  1099. // type: 0xFE ActiveSensing
  1100. handleActiveSensing = fptr;
  1101. }
  1102. void setHandleSystemReset(void (*fptr)(void)) {
  1103. // type: 0xFF SystemReset
  1104. handleSystemReset = fptr;
  1105. }
  1106. void setHandleRealTimeSystem(void (*fptr)(uint8_t realtimebyte)) {
  1107. // type: 0xF8-0xFF - if more specific handler not configured
  1108. handleRealTimeSystem = fptr;
  1109. }
  1110. protected:
  1111. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1112. virtual void disconnect();
  1113. static void rx_callback(const Transfer_t *transfer);
  1114. static void tx_callback(const Transfer_t *transfer);
  1115. void rx_data(const Transfer_t *transfer);
  1116. void tx_data(const Transfer_t *transfer);
  1117. void init();
  1118. void write_packed(uint32_t data);
  1119. void send_sysex_buffer_has_term(const uint8_t *data, uint32_t length, uint8_t cable);
  1120. void send_sysex_add_term_bytes(const uint8_t *data, uint32_t length, uint8_t cable);
  1121. void sysex_byte(uint8_t b);
  1122. private:
  1123. Pipe_t *rxpipe;
  1124. Pipe_t *txpipe;
  1125. enum { MAX_PACKET_SIZE = 64 };
  1126. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1127. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  1128. uint32_t tx_buffer1[MAX_PACKET_SIZE/4];
  1129. uint32_t tx_buffer2[MAX_PACKET_SIZE/4];
  1130. uint16_t rx_size;
  1131. uint16_t tx_size;
  1132. uint32_t rx_queue[RX_QUEUE_SIZE];
  1133. bool rx_packet_queued;
  1134. uint16_t rx_head;
  1135. uint16_t rx_tail;
  1136. volatile uint8_t tx1_count;
  1137. volatile uint8_t tx2_count;
  1138. uint8_t rx_ep;
  1139. uint8_t tx_ep;
  1140. uint8_t rx_ep_type;
  1141. uint8_t tx_ep_type;
  1142. uint8_t msg_cable;
  1143. uint8_t msg_channel;
  1144. uint8_t msg_type;
  1145. uint8_t msg_data1;
  1146. uint8_t msg_data2;
  1147. uint8_t msg_sysex[SYSEX_MAX_LEN];
  1148. uint16_t msg_sysex_len;
  1149. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  1150. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  1151. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  1152. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  1153. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  1154. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  1155. void (*handlePitchChange)(uint8_t ch, int pitch);
  1156. void (*handleSysExPartial)(const uint8_t *data, uint16_t length, uint8_t complete);
  1157. void (*handleSysExComplete)(uint8_t *data, unsigned int size);
  1158. void (*handleTimeCodeQuarterFrame)(uint8_t data);
  1159. void (*handleSongPosition)(uint16_t beats);
  1160. void (*handleSongSelect)(uint8_t songnumber);
  1161. void (*handleTuneRequest)(void);
  1162. void (*handleClock)(void);
  1163. void (*handleStart)(void);
  1164. void (*handleContinue)(void);
  1165. void (*handleStop)(void);
  1166. void (*handleActiveSensing)(void);
  1167. void (*handleSystemReset)(void);
  1168. void (*handleRealTimeSystem)(uint8_t rtb);
  1169. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1170. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1171. strbuf_t mystring_bufs[1];
  1172. };
  1173. //--------------------------------------------------------------------------
  1174. class USBSerial: public USBDriver, public Stream {
  1175. public:
  1176. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  1177. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1178. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  1179. USBSerial(USBHost &host) : txtimer(this) { init(); }
  1180. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  1181. void end(void);
  1182. uint32_t writeTimeout() {return write_timeout_;}
  1183. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  1184. virtual int available(void);
  1185. virtual int peek(void);
  1186. virtual int read(void);
  1187. virtual int availableForWrite();
  1188. virtual size_t write(uint8_t c);
  1189. virtual void flush(void);
  1190. using Print::write;
  1191. protected:
  1192. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1193. virtual void control(const Transfer_t *transfer);
  1194. virtual void disconnect();
  1195. virtual void timer_event(USBDriverTimer *whichTimer);
  1196. private:
  1197. static void rx_callback(const Transfer_t *transfer);
  1198. static void tx_callback(const Transfer_t *transfer);
  1199. void rx_data(const Transfer_t *transfer);
  1200. void tx_data(const Transfer_t *transfer);
  1201. void rx_queue_packets(uint32_t head, uint32_t tail);
  1202. void init();
  1203. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  1204. bool init_buffers(uint32_t rsize, uint32_t tsize);
  1205. void ch341_setBaud(uint8_t byte_index);
  1206. private:
  1207. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1208. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1209. strbuf_t mystring_bufs[1];
  1210. USBDriverTimer txtimer;
  1211. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  1212. setup_t setup;
  1213. uint8_t setupdata[16]; //
  1214. uint32_t baudrate;
  1215. uint32_t format_;
  1216. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  1217. Pipe_t *rxpipe;
  1218. Pipe_t *txpipe;
  1219. uint8_t *rx1; // location for first incoming packet
  1220. uint8_t *rx2; // location for second incoming packet
  1221. uint8_t *rxbuf; // receive circular buffer
  1222. uint8_t *tx1; // location for first outgoing packet
  1223. uint8_t *tx2; // location for second outgoing packet
  1224. uint8_t *txbuf;
  1225. volatile uint16_t rxhead;// receive head
  1226. volatile uint16_t rxtail;// receive tail
  1227. volatile uint16_t txhead;
  1228. volatile uint16_t txtail;
  1229. uint16_t rxsize;// size of receive circular buffer
  1230. uint16_t txsize;// size of transmit circular buffer
  1231. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  1232. volatile uint8_t txstate;
  1233. uint8_t pending_control;
  1234. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  1235. uint8_t pl2303_v1; // Which version do we have
  1236. uint8_t pl2303_v2;
  1237. uint8_t interface;
  1238. bool control_queued; // Is there already a queued control messaged
  1239. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  1240. sertype_t sertype;
  1241. typedef struct {
  1242. uint16_t idVendor;
  1243. uint16_t idProduct;
  1244. sertype_t sertype;
  1245. } product_vendor_mapping_t;
  1246. static product_vendor_mapping_t pid_vid_mapping[];
  1247. };
  1248. //--------------------------------------------------------------------------
  1249. class AntPlus: public USBDriver {
  1250. // Please post any AntPlus feedback or contributions on this forum thread:
  1251. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  1252. public:
  1253. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  1254. void begin(const uint8_t key=0);
  1255. void onStatusChange(void (*function)(int channel, int status)) {
  1256. user_onStatusChange = function;
  1257. }
  1258. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  1259. user_onDeviceID = function;
  1260. }
  1261. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  1262. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  1263. memset(&hrm, 0, sizeof(hrm));
  1264. user_onHeartRateMonitor = f;
  1265. }
  1266. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  1267. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  1268. memset(&spdcad, 0, sizeof(spdcad));
  1269. user_onSpeedCadence = f;
  1270. }
  1271. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  1272. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  1273. memset(&spd, 0, sizeof(spd));
  1274. user_onSpeed = f;
  1275. }
  1276. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  1277. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  1278. memset(&cad, 0, sizeof(cad));
  1279. user_onCadence = f;
  1280. }
  1281. void setWheelCircumference(float meters) {
  1282. wheelCircumference = meters * 1000.0f;
  1283. }
  1284. protected:
  1285. virtual void Task();
  1286. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1287. virtual void disconnect();
  1288. virtual void timer_event(USBDriverTimer *whichTimer);
  1289. private:
  1290. static void rx_callback(const Transfer_t *transfer);
  1291. static void tx_callback(const Transfer_t *transfer);
  1292. void rx_data(const Transfer_t *transfer);
  1293. void tx_data(const Transfer_t *transfer);
  1294. void init();
  1295. size_t write(const void *data, const size_t size);
  1296. int read(void *data, const size_t size);
  1297. void transmit();
  1298. private:
  1299. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1300. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1301. strbuf_t mystring_bufs[1];
  1302. //USBDriverTimer txtimer;
  1303. USBDriverTimer updatetimer;
  1304. Pipe_t *rxpipe;
  1305. Pipe_t *txpipe;
  1306. bool first_update;
  1307. uint8_t txbuffer[240];
  1308. uint8_t rxpacket[64];
  1309. volatile uint16_t txhead;
  1310. volatile uint16_t txtail;
  1311. volatile bool txready;
  1312. volatile uint8_t rxlen;
  1313. volatile bool do_polling;
  1314. private:
  1315. enum _eventi {
  1316. EVENTI_MESSAGE = 0,
  1317. EVENTI_CHANNEL,
  1318. EVENTI_TOTAL
  1319. };
  1320. enum _profiles {
  1321. PROFILE_HRM = 0,
  1322. PROFILE_SPDCAD,
  1323. PROFILE_POWER,
  1324. PROFILE_STRIDE,
  1325. PROFILE_SPEED,
  1326. PROFILE_CADENCE,
  1327. PROFILE_TOTAL
  1328. };
  1329. typedef struct {
  1330. uint8_t channel;
  1331. uint8_t RFFreq;
  1332. uint8_t networkNumber;
  1333. uint8_t stub;
  1334. uint8_t searchTimeout;
  1335. uint8_t channelType;
  1336. uint8_t deviceType;
  1337. uint8_t transType;
  1338. uint16_t channelPeriod;
  1339. uint16_t searchWaveform;
  1340. uint32_t deviceNumber; // deviceId
  1341. struct {
  1342. uint8_t chanIdOnce;
  1343. uint8_t keyAccepted;
  1344. uint8_t profileValid;
  1345. uint8_t channelStatus;
  1346. uint8_t channelStatusOld;
  1347. } flags;
  1348. } TDCONFIG;
  1349. struct {
  1350. uint8_t initOnce;
  1351. uint8_t key; // key index
  1352. int iDevice; // index to the antplus we're interested in, if > one found
  1353. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1354. } ant;
  1355. void (*user_onStatusChange)(int channel, int status);
  1356. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1357. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1358. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1359. void (*user_onSpeed)(float speed, float distance);
  1360. void (*user_onCadence)(float cadence);
  1361. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1362. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1363. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1364. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1365. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1366. static int msgGetLength(uint8_t *stream);
  1367. int handleMessages(uint8_t *buffer, int tBytes);
  1368. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1369. void message_channel(const int chan, const int eventId,
  1370. const uint8_t *payload, const size_t dataLength);
  1371. void message_response(const int chan, const int msgId,
  1372. const uint8_t *payload, const size_t dataLength);
  1373. void message_event(const int channel, const int msgId,
  1374. const uint8_t *payload, const size_t dataLength);
  1375. int ResetSystem();
  1376. int RequestMessage(const int channel, const int message);
  1377. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1378. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1379. int SetChannelPeriod(const int channel, const int period);
  1380. int SetChannelRFFreq(const int channel, const int freq);
  1381. int SetSearchWaveform(const int channel, const int wave);
  1382. int OpenChannel(const int channel);
  1383. int CloseChannel(const int channel);
  1384. int AssignChannel(const int channel, const int channelType, const int network);
  1385. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1386. const int transmissionType);
  1387. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1388. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1389. int SendBroadcastData(const int channel, const uint8_t *data);
  1390. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1391. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1392. const int TranType, const uint8_t *data);
  1393. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1394. const int TranType, const uint8_t *data);
  1395. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1396. const int devType, const int TranType, const uint8_t *data);
  1397. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1398. const int tranType, const uint8_t *data, const int nunPackets);
  1399. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1400. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1401. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1402. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1403. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1404. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1405. struct {
  1406. struct {
  1407. uint8_t bpm;
  1408. uint8_t sequence;
  1409. uint16_t time;
  1410. } previous;
  1411. } hrm;
  1412. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1413. struct {
  1414. struct {
  1415. uint16_t cadenceTime;
  1416. uint16_t cadenceCt;
  1417. uint16_t speedTime;
  1418. uint16_t speedCt;
  1419. } previous;
  1420. float distance;
  1421. } spdcad;
  1422. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1423. /* struct {
  1424. struct {
  1425. uint8_t sequence;
  1426. uint16_t pedalPowerContribution;
  1427. uint8_t pedalPower;
  1428. uint8_t instantCadence;
  1429. uint16_t sumPower;
  1430. uint16_t instantPower;
  1431. } current;
  1432. struct {
  1433. uint16_t stub;
  1434. } previous;
  1435. } pwr; */
  1436. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1437. /* struct {
  1438. struct {
  1439. uint16_t speed;
  1440. uint16_t cadence;
  1441. uint8_t strides;
  1442. } current;
  1443. struct {
  1444. uint8_t strides;
  1445. uint16_t speed;
  1446. uint16_t cadence;
  1447. } previous;
  1448. } stride; */
  1449. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1450. struct {
  1451. struct {
  1452. uint16_t speedTime;
  1453. uint16_t speedCt;
  1454. } previous;
  1455. float distance;
  1456. } spd;
  1457. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1458. struct {
  1459. struct {
  1460. uint16_t cadenceTime;
  1461. uint16_t cadenceCt;
  1462. } previous;
  1463. } cad;
  1464. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1465. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1466. };
  1467. //--------------------------------------------------------------------------
  1468. class RawHIDController : public USBHIDInput {
  1469. public:
  1470. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1471. uint32_t usage(void) {return usage_;}
  1472. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1473. bool sendPacket(const uint8_t *buffer);
  1474. protected:
  1475. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1476. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1477. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1478. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1479. virtual void hid_input_data(uint32_t usage, int32_t value);
  1480. virtual void hid_input_end();
  1481. virtual void disconnect_collection(Device_t *dev);
  1482. private:
  1483. void init();
  1484. USBHIDParser *driver_;
  1485. enum { MAX_PACKET_SIZE = 64 };
  1486. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1487. uint8_t collections_claimed = 0;
  1488. //volatile bool hid_input_begin_ = false;
  1489. uint32_t fixed_usage_;
  1490. uint32_t usage_ = 0;
  1491. // See if we can contribute transfers
  1492. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1493. };
  1494. //--------------------------------------------------------------------------
  1495. class BluetoothController: public USBDriver {
  1496. public:
  1497. BluetoothController(USBHost &host, bool pair = false, const char *pin = "0000") : do_pair_device_(pair), pair_pincode_(pin)
  1498. { init(); }
  1499. enum {MAX_ENDPOINTS=4, NUM_SERVICES=4, }; // Max number of Bluetooth services - if you need more than 4 simply increase this number
  1500. enum {BT_CLASS_DEVICE= 0x0804}; // Toy - Robot
  1501. static void driver_ready_for_bluetooth(BTHIDInput *driver);
  1502. protected:
  1503. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1504. virtual void control(const Transfer_t *transfer);
  1505. virtual void disconnect();
  1506. //virtual void timer_event(USBDriverTimer *whichTimer);
  1507. BTHIDInput * find_driver(uint32_t device_type);
  1508. private:
  1509. static void rx_callback(const Transfer_t *transfer);
  1510. static void rx2_callback(const Transfer_t *transfer);
  1511. static void tx_callback(const Transfer_t *transfer);
  1512. void rx_data(const Transfer_t *transfer);
  1513. void rx2_data(const Transfer_t *transfer);
  1514. void tx_data(const Transfer_t *transfer);
  1515. void init();
  1516. // HCI support functions...
  1517. void sendHCICommand(uint16_t hciCommand, uint16_t cParams, const uint8_t* data);
  1518. //void sendHCIReadLocalSupportedFeatures();
  1519. void inline sendHCI_INQUIRY();
  1520. void inline sendHCIInquiryCancel();
  1521. void inline sendHCICreateConnection();
  1522. void inline sendHCIAuthenticationRequested();
  1523. void inline sendHCIAcceptConnectionRequest();
  1524. void inline sendHCILinkKeyNegativeReply();
  1525. void inline sendHCIPinCodeReply();
  1526. void inline sendResetHCI();
  1527. void inline sendHDCWriteClassOfDev();
  1528. void inline sendHCIReadBDAddr();
  1529. void inline sendHCIReadLocalVersionInfo();
  1530. void inline sendHCIWriteScanEnable(uint8_t scan_op);
  1531. void inline sendHCIRemoteNameRequest();
  1532. void inline sendHCIRemoteVersionInfoRequest();
  1533. void handle_hci_command_complete();
  1534. void handle_hci_command_status();
  1535. void handle_hci_inquiry_result();
  1536. void handle_hci_inquiry_complete();
  1537. void handle_hci_incoming_connect();
  1538. void handle_hci_connection_complete();
  1539. void handle_hci_disconnect_complete();
  1540. void handle_hci_authentication_complete();
  1541. void handle_hci_remote_name_complete();
  1542. void handle_hci_remote_version_information_complete();
  1543. void handle_hci_pin_code_request();
  1544. void handle_hci_link_key_notification();
  1545. void handle_hci_link_key_request();
  1546. void queue_next_hci_command();
  1547. void sendl2cap_ConnectionResponse(uint16_t handle, uint8_t rxid, uint16_t dcid, uint16_t scid, uint8_t result);
  1548. void sendl2cap_ConnectionRequest(uint16_t handle, uint8_t rxid, uint16_t scid, uint16_t psm);
  1549. void sendl2cap_ConfigRequest(uint16_t handle, uint8_t rxid, uint16_t dcid);
  1550. void sendl2cap_ConfigResponse(uint16_t handle, uint8_t rxid, uint16_t scid);
  1551. void sendL2CapCommand(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00);
  1552. void process_l2cap_connection_request(uint8_t *data);
  1553. void process_l2cap_connection_response(uint8_t *data);
  1554. void process_l2cap_config_request(uint8_t *data);
  1555. void process_l2cap_config_response(uint8_t *data);
  1556. void process_l2cap_command_reject(uint8_t *data);
  1557. void process_l2cap_disconnect_request(uint8_t *data);
  1558. void setHIDProtocol(uint8_t protocol);
  1559. void handleHIDTHDRData(uint8_t *buffer); // Pass the whole buffer...
  1560. static BTHIDInput *available_bthid_drivers_list;
  1561. setup_t setup;
  1562. Pipe_t mypipes[4] __attribute__ ((aligned(32)));
  1563. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1564. strbuf_t mystring_bufs[2]; // 2 string buffers - one for our device - one for remote device...
  1565. uint16_t pending_control_ = 0;
  1566. uint16_t pending_control_tx_ = 0;
  1567. uint16_t rx_size_ = 0;
  1568. uint16_t rx2_size_ = 0;
  1569. uint16_t tx_size_ = 0;
  1570. Pipe_t *rxpipe_;
  1571. Pipe_t *rx2pipe_;
  1572. Pipe_t *txpipe_;
  1573. uint8_t rxbuf_[256]; // used to receive data from RX, which may come with several packets...
  1574. uint8_t rx_packet_data_remaining=0; // how much data remaining
  1575. uint8_t rx2buf_[64]; // receive buffer from Bulk end point
  1576. uint8_t txbuf_[256]; // buffer to use to send commands to bluetooth
  1577. uint8_t hciVersion; // what version of HCI do we have?
  1578. bool do_pair_device_; // Should we do a pair for a new device?
  1579. const char *pair_pincode_; // What pin code to use for the pairing
  1580. uint8_t my_bdaddr[6]; // The bluetooth dongles Bluetooth address.
  1581. uint8_t features[8]; // remember our local features.
  1582. BTHIDInput * device_driver_ = nullptr;;
  1583. uint8_t device_bdaddr_[6];// remember devices address
  1584. uint8_t device_ps_repetion_mode_ ; // mode
  1585. uint8_t device_clock_offset_[2];
  1586. uint32_t device_class_; // class of device.
  1587. uint16_t device_connection_handle_; // handle to connection
  1588. uint16_t connection_rxid_ = 0;
  1589. uint16_t control_dcid_ = 0x70;
  1590. uint16_t interrupt_dcid_ = 0x71;
  1591. uint16_t interrupt_scid_;
  1592. uint16_t control_scid_;
  1593. uint8_t remote_ver_;
  1594. uint16_t remote_man_;
  1595. uint8_t remote_subv_;
  1596. };
  1597. #endif