PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1906 linhas
70KB

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