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 64KB

8 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  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 || (btdevice != 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. BluetoothController *btdriver_ = nullptr;
  804. joytype_t mapVIDPIDtoJoystickType(uint16_t idVendor, uint16_t idProduct, bool exclude_hid_devices);
  805. bool transmitPS4UserFeedbackMsg();
  806. bool transmitPS3UserFeedbackMsg();
  807. bool anychange = false;
  808. volatile bool joystickEvent = false;
  809. uint32_t buttons = 0;
  810. int axis[TOTAL_AXIS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  811. uint64_t axis_mask_ = 0; // which axis have valid data
  812. uint64_t axis_changed_mask_ = 0;
  813. uint64_t axis_change_notify_mask_ = 0x3ff; // assume the low 10 values only.
  814. uint16_t additional_axis_usage_page_ = 0;
  815. uint16_t additional_axis_usage_start_ = 0;
  816. uint16_t additional_axis_usage_count_ = 0;
  817. // State values to output to Joystick.
  818. uint8_t rumble_lValue_ = 0;
  819. uint8_t rumble_rValue_ = 0;
  820. uint8_t rumble_timeout_ = 0;
  821. uint8_t leds_[3] = {0,0,0};
  822. uint8_t connected_ = 0; // what type of device if any is connected xbox 360...
  823. // Used by HID code
  824. uint8_t collections_claimed = 0;
  825. // Used by USBDriver code
  826. static void rx_callback(const Transfer_t *transfer);
  827. static void tx_callback(const Transfer_t *transfer);
  828. void rx_data(const Transfer_t *transfer);
  829. void tx_data(const Transfer_t *transfer);
  830. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  831. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  832. strbuf_t mystring_bufs[1];
  833. uint8_t rx_ep_ = 0; // remember which end point this object is...
  834. uint16_t rx_size_ = 0;
  835. uint16_t tx_size_ = 0;
  836. Pipe_t *rxpipe_;
  837. Pipe_t *txpipe_;
  838. uint8_t rxbuf_[64]; // receive circular buffer
  839. uint8_t txbuf_[64]; // buffer to use to send commands to joystick
  840. // Mapping table to say which devices we handle
  841. typedef struct {
  842. uint16_t idVendor;
  843. uint16_t idProduct;
  844. joytype_t joyType;
  845. bool hidDevice;
  846. } product_vendor_mapping_t;
  847. static product_vendor_mapping_t pid_vid_mapping[];
  848. };
  849. //--------------------------------------------------------------------------
  850. class MIDIDevice : public USBDriver {
  851. public:
  852. enum { SYSEX_MAX_LEN = 290 };
  853. // Message type names for compatibility with Arduino MIDI library 4.3.1
  854. enum MidiType {
  855. InvalidType = 0x00, // For notifying errors
  856. NoteOff = 0x80, // Note Off
  857. NoteOn = 0x90, // Note On
  858. AfterTouchPoly = 0xA0, // Polyphonic AfterTouch
  859. ControlChange = 0xB0, // Control Change / Channel Mode
  860. ProgramChange = 0xC0, // Program Change
  861. AfterTouchChannel = 0xD0, // Channel (monophonic) AfterTouch
  862. PitchBend = 0xE0, // Pitch Bend
  863. SystemExclusive = 0xF0, // System Exclusive
  864. TimeCodeQuarterFrame = 0xF1, // System Common - MIDI Time Code Quarter Frame
  865. SongPosition = 0xF2, // System Common - Song Position Pointer
  866. SongSelect = 0xF3, // System Common - Song Select
  867. TuneRequest = 0xF6, // System Common - Tune Request
  868. Clock = 0xF8, // System Real Time - Timing Clock
  869. Start = 0xFA, // System Real Time - Start
  870. Continue = 0xFB, // System Real Time - Continue
  871. Stop = 0xFC, // System Real Time - Stop
  872. ActiveSensing = 0xFE, // System Real Time - Active Sensing
  873. SystemReset = 0xFF, // System Real Time - System Reset
  874. };
  875. MIDIDevice(USBHost &host) { init(); }
  876. MIDIDevice(USBHost *host) { init(); }
  877. void sendNoteOff(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  878. send(0x80, note, velocity, channel, cable);
  879. }
  880. void sendNoteOn(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  881. send(0x90, note, velocity, channel, cable);
  882. }
  883. void sendPolyPressure(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  884. send(0xA0, note, pressure, channel, cable);
  885. }
  886. void sendAfterTouchPoly(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  887. send(0xA0, note, pressure, channel, cable);
  888. }
  889. void sendControlChange(uint8_t control, uint8_t value, uint8_t channel, uint8_t cable=0) {
  890. send(0xB0, control, value, channel, cable);
  891. }
  892. void sendProgramChange(uint8_t program, uint8_t channel, uint8_t cable=0) {
  893. send(0xC0, program, 0, channel, cable);
  894. }
  895. void sendAfterTouch(uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  896. send(0xD0, pressure, 0, channel, cable);
  897. }
  898. void sendPitchBend(int value, uint8_t channel, uint8_t cable=0) {
  899. if (value < -8192) {
  900. value = -8192;
  901. } else if (value > 8191) {
  902. value = 8191;
  903. }
  904. value += 8192;
  905. send(0xE0, value, value >> 7, channel, cable);
  906. }
  907. void sendSysEx(uint32_t length, const uint8_t *data, bool hasTerm=false, uint8_t cable=0) {
  908. //if (cable >= MIDI_NUM_CABLES) return;
  909. if (hasTerm) {
  910. send_sysex_buffer_has_term(data, length, cable);
  911. } else {
  912. send_sysex_add_term_bytes(data, length, cable);
  913. }
  914. }
  915. void sendRealTime(uint8_t type, uint8_t cable=0) {
  916. switch (type) {
  917. case 0xF8: // Clock
  918. case 0xFA: // Start
  919. case 0xFB: // Continue
  920. case 0xFC: // Stop
  921. case 0xFE: // ActiveSensing
  922. case 0xFF: // SystemReset
  923. send(type, 0, 0, 0, cable);
  924. break;
  925. default: // Invalid Real Time marker
  926. break;
  927. }
  928. }
  929. void sendTimeCodeQuarterFrame(uint8_t type, uint8_t value, uint8_t cable=0) {
  930. send(0xF1, ((type & 0x07) << 4) | (value & 0x0F), 0, 0, cable);
  931. }
  932. void sendSongPosition(uint16_t beats, uint8_t cable=0) {
  933. send(0xF2, beats, beats >> 7, 0, cable);
  934. }
  935. void sendSongSelect(uint8_t song, uint8_t cable=0) {
  936. send(0xF3, song, 0, 0, cable);
  937. }
  938. void sendTuneRequest(uint8_t cable=0) {
  939. send(0xF6, 0, 0, 0, cable);
  940. }
  941. void beginRpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  942. sendControlChange(101, number >> 7, channel, cable);
  943. sendControlChange(100, number, channel, cable);
  944. }
  945. void sendRpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  946. sendControlChange(6, value >> 7, channel, cable);
  947. sendControlChange(38, value, channel, cable);
  948. }
  949. void sendRpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  950. sendControlChange(96, amount, channel, cable);
  951. }
  952. void sendRpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  953. sendControlChange(97, amount, channel, cable);
  954. }
  955. void endRpn(uint8_t channel, uint8_t cable=0) {
  956. sendControlChange(101, 0x7F, channel, cable);
  957. sendControlChange(100, 0x7F, channel, cable);
  958. }
  959. void beginNrpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  960. sendControlChange(99, number >> 7, channel, cable);
  961. sendControlChange(98, number, channel, cable);
  962. }
  963. void sendNrpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  964. sendControlChange(6, value >> 7, channel, cable);
  965. sendControlChange(38, value, channel, cable);
  966. }
  967. void sendNrpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  968. sendControlChange(96, amount, channel, cable);
  969. }
  970. void sendNrpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  971. sendControlChange(97, amount, channel, cable);
  972. }
  973. void endNrpn(uint8_t channel, uint8_t cable=0) {
  974. sendControlChange(99, 0x7F, channel, cable);
  975. sendControlChange(98, 0x7F, channel, cable);
  976. }
  977. void send(uint8_t type, uint8_t data1, uint8_t data2, uint8_t channel, uint8_t cable=0) {
  978. //if (cable >= MIDI_NUM_CABLES) return;
  979. if (type < 0xF0) {
  980. if (type < 0x80) return;
  981. type &= 0xF0;
  982. write_packed((type << 8) | (type >> 4) | ((cable & 0x0F) << 4)
  983. | (((channel - 1) & 0x0F) << 8) | ((data1 & 0x7F) << 16)
  984. | ((data2 & 0x7F) << 24));
  985. } else if (type >= 0xF8 || type == 0xF6) {
  986. write_packed((type << 8) | 0x0F | ((cable & 0x0F) << 4));
  987. } else if (type == 0xF1 || type == 0xF3) {
  988. write_packed((type << 8) | 0x02 | ((cable & 0x0F) << 4)
  989. | ((data1 & 0x7F) << 16));
  990. } else if (type == 0xF2) {
  991. write_packed((type << 8) | 0x03 | ((cable & 0x0F) << 4)
  992. | ((data1 & 0x7F) << 16) | ((data2 & 0x7F) << 24));
  993. }
  994. }
  995. void send_now(void) __attribute__((always_inline)) {
  996. }
  997. bool read(uint8_t channel=0);
  998. uint8_t getType(void) {
  999. return msg_type;
  1000. };
  1001. uint8_t getCable(void) {
  1002. return msg_cable;
  1003. }
  1004. uint8_t getChannel(void) {
  1005. return msg_channel;
  1006. };
  1007. uint8_t getData1(void) {
  1008. return msg_data1;
  1009. };
  1010. uint8_t getData2(void) {
  1011. return msg_data2;
  1012. };
  1013. uint8_t * getSysExArray(void) {
  1014. return msg_sysex;
  1015. }
  1016. uint16_t getSysExArrayLength(void) {
  1017. return msg_data2 << 8 | msg_data1;
  1018. }
  1019. void setHandleNoteOff(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1020. // type: 0x80 NoteOff
  1021. handleNoteOff = fptr;
  1022. }
  1023. void setHandleNoteOn(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1024. // type: 0x90 NoteOn
  1025. handleNoteOn = fptr;
  1026. }
  1027. void setHandleVelocityChange(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1028. // type: 0xA0 AfterTouchPoly
  1029. handleVelocityChange = fptr;
  1030. }
  1031. void setHandleAfterTouchPoly(void (*fptr)(uint8_t channel, uint8_t note, uint8_t pressure)) {
  1032. // type: 0xA0 AfterTouchPoly
  1033. handleVelocityChange = fptr;
  1034. }
  1035. void setHandleControlChange(void (*fptr)(uint8_t channel, uint8_t control, uint8_t value)) {
  1036. // type: 0xB0 ControlChange
  1037. handleControlChange = fptr;
  1038. }
  1039. void setHandleProgramChange(void (*fptr)(uint8_t channel, uint8_t program)) {
  1040. // type: 0xC0 ProgramChange
  1041. handleProgramChange = fptr;
  1042. }
  1043. void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1044. // type: 0xD0 AfterTouchChannel
  1045. handleAfterTouch = fptr;
  1046. }
  1047. void setHandleAfterTouchChannel(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1048. // type: 0xD0 AfterTouchChannel
  1049. handleAfterTouch = fptr;
  1050. }
  1051. void setHandlePitchChange(void (*fptr)(uint8_t channel, int pitch)) {
  1052. // type: 0xE0 PitchBend
  1053. handlePitchChange = fptr;
  1054. }
  1055. void setHandleSysEx(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1056. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1057. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1058. }
  1059. void setHandleSystemExclusive(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1060. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1061. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1062. }
  1063. void setHandleSystemExclusive(void (*fptr)(uint8_t *data, unsigned int size)) {
  1064. // type: 0xF0 SystemExclusive - single call, message larger than buffer is truncated
  1065. handleSysExComplete = fptr;
  1066. }
  1067. void setHandleTimeCodeQuarterFrame(void (*fptr)(uint8_t data)) {
  1068. // type: 0xF1 TimeCodeQuarterFrame
  1069. handleTimeCodeQuarterFrame = fptr;
  1070. }
  1071. void setHandleSongPosition(void (*fptr)(uint16_t beats)) {
  1072. // type: 0xF2 SongPosition
  1073. handleSongPosition = fptr;
  1074. }
  1075. void setHandleSongSelect(void (*fptr)(uint8_t songnumber)) {
  1076. // type: 0xF3 SongSelect
  1077. handleSongSelect = fptr;
  1078. }
  1079. void setHandleTuneRequest(void (*fptr)(void)) {
  1080. // type: 0xF6 TuneRequest
  1081. handleTuneRequest = fptr;
  1082. }
  1083. void setHandleClock(void (*fptr)(void)) {
  1084. // type: 0xF8 Clock
  1085. handleClock = fptr;
  1086. }
  1087. void setHandleStart(void (*fptr)(void)) {
  1088. // type: 0xFA Start
  1089. handleStart = fptr;
  1090. }
  1091. void setHandleContinue(void (*fptr)(void)) {
  1092. // type: 0xFB Continue
  1093. handleContinue = fptr;
  1094. }
  1095. void setHandleStop(void (*fptr)(void)) {
  1096. // type: 0xFC Stop
  1097. handleStop = fptr;
  1098. }
  1099. void setHandleActiveSensing(void (*fptr)(void)) {
  1100. // type: 0xFE ActiveSensing
  1101. handleActiveSensing = fptr;
  1102. }
  1103. void setHandleSystemReset(void (*fptr)(void)) {
  1104. // type: 0xFF SystemReset
  1105. handleSystemReset = fptr;
  1106. }
  1107. void setHandleRealTimeSystem(void (*fptr)(uint8_t realtimebyte)) {
  1108. // type: 0xF8-0xFF - if more specific handler not configured
  1109. handleRealTimeSystem = fptr;
  1110. }
  1111. protected:
  1112. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1113. virtual void disconnect();
  1114. static void rx_callback(const Transfer_t *transfer);
  1115. static void tx_callback(const Transfer_t *transfer);
  1116. void rx_data(const Transfer_t *transfer);
  1117. void tx_data(const Transfer_t *transfer);
  1118. void init();
  1119. void write_packed(uint32_t data);
  1120. void send_sysex_buffer_has_term(const uint8_t *data, uint32_t length, uint8_t cable);
  1121. void send_sysex_add_term_bytes(const uint8_t *data, uint32_t length, uint8_t cable);
  1122. void sysex_byte(uint8_t b);
  1123. private:
  1124. Pipe_t *rxpipe;
  1125. Pipe_t *txpipe;
  1126. enum { MAX_PACKET_SIZE = 64 };
  1127. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1128. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  1129. uint32_t tx_buffer1[MAX_PACKET_SIZE/4];
  1130. uint32_t tx_buffer2[MAX_PACKET_SIZE/4];
  1131. uint16_t rx_size;
  1132. uint16_t tx_size;
  1133. uint32_t rx_queue[RX_QUEUE_SIZE];
  1134. bool rx_packet_queued;
  1135. uint16_t rx_head;
  1136. uint16_t rx_tail;
  1137. volatile uint8_t tx1_count;
  1138. volatile uint8_t tx2_count;
  1139. uint8_t rx_ep;
  1140. uint8_t tx_ep;
  1141. uint8_t rx_ep_type;
  1142. uint8_t tx_ep_type;
  1143. uint8_t msg_cable;
  1144. uint8_t msg_channel;
  1145. uint8_t msg_type;
  1146. uint8_t msg_data1;
  1147. uint8_t msg_data2;
  1148. uint8_t msg_sysex[SYSEX_MAX_LEN];
  1149. uint16_t msg_sysex_len;
  1150. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  1151. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  1152. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  1153. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  1154. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  1155. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  1156. void (*handlePitchChange)(uint8_t ch, int pitch);
  1157. void (*handleSysExPartial)(const uint8_t *data, uint16_t length, uint8_t complete);
  1158. void (*handleSysExComplete)(uint8_t *data, unsigned int size);
  1159. void (*handleTimeCodeQuarterFrame)(uint8_t data);
  1160. void (*handleSongPosition)(uint16_t beats);
  1161. void (*handleSongSelect)(uint8_t songnumber);
  1162. void (*handleTuneRequest)(void);
  1163. void (*handleClock)(void);
  1164. void (*handleStart)(void);
  1165. void (*handleContinue)(void);
  1166. void (*handleStop)(void);
  1167. void (*handleActiveSensing)(void);
  1168. void (*handleSystemReset)(void);
  1169. void (*handleRealTimeSystem)(uint8_t rtb);
  1170. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1171. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1172. strbuf_t mystring_bufs[1];
  1173. };
  1174. //--------------------------------------------------------------------------
  1175. class USBSerial: public USBDriver, public Stream {
  1176. public:
  1177. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  1178. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1179. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  1180. USBSerial(USBHost &host) : txtimer(this) { init(); }
  1181. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  1182. void end(void);
  1183. uint32_t writeTimeout() {return write_timeout_;}
  1184. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  1185. virtual int available(void);
  1186. virtual int peek(void);
  1187. virtual int read(void);
  1188. virtual int availableForWrite();
  1189. virtual size_t write(uint8_t c);
  1190. virtual void flush(void);
  1191. using Print::write;
  1192. protected:
  1193. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1194. virtual void control(const Transfer_t *transfer);
  1195. virtual void disconnect();
  1196. virtual void timer_event(USBDriverTimer *whichTimer);
  1197. private:
  1198. static void rx_callback(const Transfer_t *transfer);
  1199. static void tx_callback(const Transfer_t *transfer);
  1200. void rx_data(const Transfer_t *transfer);
  1201. void tx_data(const Transfer_t *transfer);
  1202. void rx_queue_packets(uint32_t head, uint32_t tail);
  1203. void init();
  1204. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  1205. bool init_buffers(uint32_t rsize, uint32_t tsize);
  1206. void ch341_setBaud(uint8_t byte_index);
  1207. private:
  1208. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1209. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1210. strbuf_t mystring_bufs[1];
  1211. USBDriverTimer txtimer;
  1212. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  1213. setup_t setup;
  1214. uint8_t setupdata[16]; //
  1215. uint32_t baudrate;
  1216. uint32_t format_;
  1217. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  1218. Pipe_t *rxpipe;
  1219. Pipe_t *txpipe;
  1220. uint8_t *rx1; // location for first incoming packet
  1221. uint8_t *rx2; // location for second incoming packet
  1222. uint8_t *rxbuf; // receive circular buffer
  1223. uint8_t *tx1; // location for first outgoing packet
  1224. uint8_t *tx2; // location for second outgoing packet
  1225. uint8_t *txbuf;
  1226. volatile uint16_t rxhead;// receive head
  1227. volatile uint16_t rxtail;// receive tail
  1228. volatile uint16_t txhead;
  1229. volatile uint16_t txtail;
  1230. uint16_t rxsize;// size of receive circular buffer
  1231. uint16_t txsize;// size of transmit circular buffer
  1232. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  1233. volatile uint8_t txstate;
  1234. uint8_t pending_control;
  1235. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  1236. uint8_t pl2303_v1; // Which version do we have
  1237. uint8_t pl2303_v2;
  1238. uint8_t interface;
  1239. bool control_queued; // Is there already a queued control messaged
  1240. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  1241. sertype_t sertype;
  1242. typedef struct {
  1243. uint16_t idVendor;
  1244. uint16_t idProduct;
  1245. sertype_t sertype;
  1246. } product_vendor_mapping_t;
  1247. static product_vendor_mapping_t pid_vid_mapping[];
  1248. };
  1249. //--------------------------------------------------------------------------
  1250. class AntPlus: public USBDriver {
  1251. // Please post any AntPlus feedback or contributions on this forum thread:
  1252. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  1253. public:
  1254. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  1255. void begin(const uint8_t key=0);
  1256. void onStatusChange(void (*function)(int channel, int status)) {
  1257. user_onStatusChange = function;
  1258. }
  1259. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  1260. user_onDeviceID = function;
  1261. }
  1262. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  1263. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  1264. memset(&hrm, 0, sizeof(hrm));
  1265. user_onHeartRateMonitor = f;
  1266. }
  1267. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  1268. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  1269. memset(&spdcad, 0, sizeof(spdcad));
  1270. user_onSpeedCadence = f;
  1271. }
  1272. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  1273. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  1274. memset(&spd, 0, sizeof(spd));
  1275. user_onSpeed = f;
  1276. }
  1277. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  1278. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  1279. memset(&cad, 0, sizeof(cad));
  1280. user_onCadence = f;
  1281. }
  1282. void setWheelCircumference(float meters) {
  1283. wheelCircumference = meters * 1000.0f;
  1284. }
  1285. protected:
  1286. virtual void Task();
  1287. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1288. virtual void disconnect();
  1289. virtual void timer_event(USBDriverTimer *whichTimer);
  1290. private:
  1291. static void rx_callback(const Transfer_t *transfer);
  1292. static void tx_callback(const Transfer_t *transfer);
  1293. void rx_data(const Transfer_t *transfer);
  1294. void tx_data(const Transfer_t *transfer);
  1295. void init();
  1296. size_t write(const void *data, const size_t size);
  1297. int read(void *data, const size_t size);
  1298. void transmit();
  1299. private:
  1300. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1301. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1302. strbuf_t mystring_bufs[1];
  1303. //USBDriverTimer txtimer;
  1304. USBDriverTimer updatetimer;
  1305. Pipe_t *rxpipe;
  1306. Pipe_t *txpipe;
  1307. bool first_update;
  1308. uint8_t txbuffer[240];
  1309. uint8_t rxpacket[64];
  1310. volatile uint16_t txhead;
  1311. volatile uint16_t txtail;
  1312. volatile bool txready;
  1313. volatile uint8_t rxlen;
  1314. volatile bool do_polling;
  1315. private:
  1316. enum _eventi {
  1317. EVENTI_MESSAGE = 0,
  1318. EVENTI_CHANNEL,
  1319. EVENTI_TOTAL
  1320. };
  1321. enum _profiles {
  1322. PROFILE_HRM = 0,
  1323. PROFILE_SPDCAD,
  1324. PROFILE_POWER,
  1325. PROFILE_STRIDE,
  1326. PROFILE_SPEED,
  1327. PROFILE_CADENCE,
  1328. PROFILE_TOTAL
  1329. };
  1330. typedef struct {
  1331. uint8_t channel;
  1332. uint8_t RFFreq;
  1333. uint8_t networkNumber;
  1334. uint8_t stub;
  1335. uint8_t searchTimeout;
  1336. uint8_t channelType;
  1337. uint8_t deviceType;
  1338. uint8_t transType;
  1339. uint16_t channelPeriod;
  1340. uint16_t searchWaveform;
  1341. uint32_t deviceNumber; // deviceId
  1342. struct {
  1343. uint8_t chanIdOnce;
  1344. uint8_t keyAccepted;
  1345. uint8_t profileValid;
  1346. uint8_t channelStatus;
  1347. uint8_t channelStatusOld;
  1348. } flags;
  1349. } TDCONFIG;
  1350. struct {
  1351. uint8_t initOnce;
  1352. uint8_t key; // key index
  1353. int iDevice; // index to the antplus we're interested in, if > one found
  1354. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1355. } ant;
  1356. void (*user_onStatusChange)(int channel, int status);
  1357. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1358. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1359. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1360. void (*user_onSpeed)(float speed, float distance);
  1361. void (*user_onCadence)(float cadence);
  1362. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1363. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1364. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1365. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1366. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1367. static int msgGetLength(uint8_t *stream);
  1368. int handleMessages(uint8_t *buffer, int tBytes);
  1369. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1370. void message_channel(const int chan, const int eventId,
  1371. const uint8_t *payload, const size_t dataLength);
  1372. void message_response(const int chan, const int msgId,
  1373. const uint8_t *payload, const size_t dataLength);
  1374. void message_event(const int channel, const int msgId,
  1375. const uint8_t *payload, const size_t dataLength);
  1376. int ResetSystem();
  1377. int RequestMessage(const int channel, const int message);
  1378. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1379. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1380. int SetChannelPeriod(const int channel, const int period);
  1381. int SetChannelRFFreq(const int channel, const int freq);
  1382. int SetSearchWaveform(const int channel, const int wave);
  1383. int OpenChannel(const int channel);
  1384. int CloseChannel(const int channel);
  1385. int AssignChannel(const int channel, const int channelType, const int network);
  1386. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1387. const int transmissionType);
  1388. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1389. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1390. int SendBroadcastData(const int channel, const uint8_t *data);
  1391. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1392. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1393. const int TranType, const uint8_t *data);
  1394. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1395. const int TranType, const uint8_t *data);
  1396. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1397. const int devType, const int TranType, const uint8_t *data);
  1398. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1399. const int tranType, const uint8_t *data, const int nunPackets);
  1400. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1401. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1402. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1403. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1404. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1405. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1406. struct {
  1407. struct {
  1408. uint8_t bpm;
  1409. uint8_t sequence;
  1410. uint16_t time;
  1411. } previous;
  1412. } hrm;
  1413. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1414. struct {
  1415. struct {
  1416. uint16_t cadenceTime;
  1417. uint16_t cadenceCt;
  1418. uint16_t speedTime;
  1419. uint16_t speedCt;
  1420. } previous;
  1421. float distance;
  1422. } spdcad;
  1423. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1424. /* struct {
  1425. struct {
  1426. uint8_t sequence;
  1427. uint16_t pedalPowerContribution;
  1428. uint8_t pedalPower;
  1429. uint8_t instantCadence;
  1430. uint16_t sumPower;
  1431. uint16_t instantPower;
  1432. } current;
  1433. struct {
  1434. uint16_t stub;
  1435. } previous;
  1436. } pwr; */
  1437. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1438. /* struct {
  1439. struct {
  1440. uint16_t speed;
  1441. uint16_t cadence;
  1442. uint8_t strides;
  1443. } current;
  1444. struct {
  1445. uint8_t strides;
  1446. uint16_t speed;
  1447. uint16_t cadence;
  1448. } previous;
  1449. } stride; */
  1450. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1451. struct {
  1452. struct {
  1453. uint16_t speedTime;
  1454. uint16_t speedCt;
  1455. } previous;
  1456. float distance;
  1457. } spd;
  1458. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1459. struct {
  1460. struct {
  1461. uint16_t cadenceTime;
  1462. uint16_t cadenceCt;
  1463. } previous;
  1464. } cad;
  1465. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1466. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1467. };
  1468. //--------------------------------------------------------------------------
  1469. class RawHIDController : public USBHIDInput {
  1470. public:
  1471. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1472. uint32_t usage(void) {return usage_;}
  1473. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1474. bool sendPacket(const uint8_t *buffer);
  1475. protected:
  1476. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1477. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1478. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1479. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1480. virtual void hid_input_data(uint32_t usage, int32_t value);
  1481. virtual void hid_input_end();
  1482. virtual void disconnect_collection(Device_t *dev);
  1483. private:
  1484. void init();
  1485. USBHIDParser *driver_;
  1486. enum { MAX_PACKET_SIZE = 64 };
  1487. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1488. uint8_t collections_claimed = 0;
  1489. //volatile bool hid_input_begin_ = false;
  1490. uint32_t fixed_usage_;
  1491. uint32_t usage_ = 0;
  1492. // See if we can contribute transfers
  1493. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1494. };
  1495. //--------------------------------------------------------------------------
  1496. class BluetoothController: public USBDriver {
  1497. public:
  1498. BluetoothController(USBHost &host, bool pair = false, const char *pin = "0000") : do_pair_device_(pair), pair_pincode_(pin)
  1499. { init(); }
  1500. enum {MAX_ENDPOINTS=4, NUM_SERVICES=4, }; // Max number of Bluetooth services - if you need more than 4 simply increase this number
  1501. enum {BT_CLASS_DEVICE= 0x0804}; // Toy - Robot
  1502. static void driver_ready_for_bluetooth(BTHIDInput *driver);
  1503. // BUGBUG version to allow some of the controlled objects to call?
  1504. void sendL2CapCommand(uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00) {
  1505. sendL2CapCommand (device_connection_handle_, data, nbytes, channelLow, channelHigh);
  1506. }
  1507. protected:
  1508. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1509. virtual void control(const Transfer_t *transfer);
  1510. virtual void disconnect();
  1511. //virtual void timer_event(USBDriverTimer *whichTimer);
  1512. BTHIDInput * find_driver(uint32_t device_type);
  1513. private:
  1514. friend class BTHIDInput;
  1515. static void rx_callback(const Transfer_t *transfer);
  1516. static void rx2_callback(const Transfer_t *transfer);
  1517. static void tx_callback(const Transfer_t *transfer);
  1518. void rx_data(const Transfer_t *transfer);
  1519. void rx2_data(const Transfer_t *transfer);
  1520. void tx_data(const Transfer_t *transfer);
  1521. void init();
  1522. // HCI support functions...
  1523. void sendHCICommand(uint16_t hciCommand, uint16_t cParams, const uint8_t* data);
  1524. //void sendHCIReadLocalSupportedFeatures();
  1525. void inline sendHCI_INQUIRY();
  1526. void inline sendHCIInquiryCancel();
  1527. void inline sendHCICreateConnection();
  1528. void inline sendHCIAuthenticationRequested();
  1529. void inline sendHCIAcceptConnectionRequest();
  1530. void inline sendHCILinkKeyNegativeReply();
  1531. void inline sendHCIPinCodeReply();
  1532. void inline sendResetHCI();
  1533. void inline sendHDCWriteClassOfDev();
  1534. void inline sendHCIReadBDAddr();
  1535. void inline sendHCIReadLocalVersionInfo();
  1536. void inline sendHCIWriteScanEnable(uint8_t scan_op);
  1537. void inline sendHCIRemoteNameRequest();
  1538. void inline sendHCIRemoteVersionInfoRequest();
  1539. void handle_hci_command_complete();
  1540. void handle_hci_command_status();
  1541. void handle_hci_inquiry_result();
  1542. void handle_hci_inquiry_complete();
  1543. void handle_hci_incoming_connect();
  1544. void handle_hci_connection_complete();
  1545. void handle_hci_disconnect_complete();
  1546. void handle_hci_authentication_complete();
  1547. void handle_hci_remote_name_complete();
  1548. void handle_hci_remote_version_information_complete();
  1549. void handle_hci_pin_code_request();
  1550. void handle_hci_link_key_notification();
  1551. void handle_hci_link_key_request();
  1552. void queue_next_hci_command();
  1553. void sendl2cap_ConnectionResponse(uint16_t handle, uint8_t rxid, uint16_t dcid, uint16_t scid, uint8_t result);
  1554. void sendl2cap_ConnectionRequest(uint16_t handle, uint8_t rxid, uint16_t scid, uint16_t psm);
  1555. void sendl2cap_ConfigRequest(uint16_t handle, uint8_t rxid, uint16_t dcid);
  1556. void sendl2cap_ConfigResponse(uint16_t handle, uint8_t rxid, uint16_t scid);
  1557. void sendL2CapCommand(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00);
  1558. void process_l2cap_connection_request(uint8_t *data);
  1559. void process_l2cap_connection_response(uint8_t *data);
  1560. void process_l2cap_config_request(uint8_t *data);
  1561. void process_l2cap_config_response(uint8_t *data);
  1562. void process_l2cap_command_reject(uint8_t *data);
  1563. void process_l2cap_disconnect_request(uint8_t *data);
  1564. void setHIDProtocol(uint8_t protocol);
  1565. void handleHIDTHDRData(uint8_t *buffer); // Pass the whole buffer...
  1566. static BTHIDInput *available_bthid_drivers_list;
  1567. setup_t setup;
  1568. Pipe_t mypipes[4] __attribute__ ((aligned(32)));
  1569. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1570. strbuf_t mystring_bufs[2]; // 2 string buffers - one for our device - one for remote device...
  1571. uint16_t pending_control_ = 0;
  1572. uint16_t pending_control_tx_ = 0;
  1573. uint16_t rx_size_ = 0;
  1574. uint16_t rx2_size_ = 0;
  1575. uint16_t tx_size_ = 0;
  1576. Pipe_t *rxpipe_;
  1577. Pipe_t *rx2pipe_;
  1578. Pipe_t *txpipe_;
  1579. uint8_t rxbuf_[256]; // used to receive data from RX, which may come with several packets...
  1580. uint8_t rx_packet_data_remaining=0; // how much data remaining
  1581. uint8_t rx2buf_[64]; // receive buffer from Bulk end point
  1582. uint8_t txbuf_[256]; // buffer to use to send commands to bluetooth
  1583. uint8_t hciVersion; // what version of HCI do we have?
  1584. bool do_pair_device_; // Should we do a pair for a new device?
  1585. const char *pair_pincode_; // What pin code to use for the pairing
  1586. uint8_t my_bdaddr[6]; // The bluetooth dongles Bluetooth address.
  1587. uint8_t features[8]; // remember our local features.
  1588. BTHIDInput * device_driver_ = nullptr;;
  1589. uint8_t device_bdaddr_[6];// remember devices address
  1590. uint8_t device_ps_repetion_mode_ ; // mode
  1591. uint8_t device_clock_offset_[2];
  1592. uint32_t device_class_; // class of device.
  1593. uint16_t device_connection_handle_; // handle to connection
  1594. uint16_t connection_rxid_ = 0;
  1595. uint16_t control_dcid_ = 0x70;
  1596. uint16_t interrupt_dcid_ = 0x71;
  1597. uint16_t interrupt_scid_;
  1598. uint16_t control_scid_;
  1599. uint8_t remote_ver_;
  1600. uint16_t remote_man_;
  1601. uint8_t remote_subv_;
  1602. };
  1603. #endif