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

1727 lines
64KB

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