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.

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