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.

1739 satır
65KB

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