Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1319 lines
48KB

  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #ifndef USB_HOST_TEENSY36_
  24. #define USB_HOST_TEENSY36_
  25. #include <stdint.h>
  26. #if !defined(__MK66FX1M0__)
  27. #error "USBHost_t36 only works with Teensy 3.6. Please select it in Tools > Boards"
  28. #endif
  29. // Dear inquisitive reader, USB is a complex protocol defined with
  30. // very specific terminology. To have any chance of understand this
  31. // source code, you absolutely must have solid knowledge of specific
  32. // USB terms such as host, device, endpoint, pipe, enumeration....
  33. // You really must also have at least a basic knowledge of the
  34. // different USB transfers: control, bulk, interrupt, isochronous.
  35. //
  36. // The USB 2.0 specification explains these in chapter 4 (pages 15
  37. // to 24), and provides more detail in the first part of chapter 5
  38. // (pages 25 to 55). The USB spec is published for free at
  39. // www.usb.org. Here is a convenient link to just the main PDF:
  40. //
  41. // https://www.pjrc.com/teensy/beta/usb20.pdf
  42. //
  43. // This is a huge file, but chapter 4 is short and easy to read.
  44. // If you're not familiar with the USB lingo, please do yourself
  45. // a favor by reading at least chapter 4 to get up to speed on the
  46. // meaning of these important USB concepts and terminology.
  47. //
  48. // If you wish to ask questions (which belong on the forum, not
  49. // github issues) or discuss development of this library, you
  50. // ABSOLUTELY MUST know the basic USB terminology from chapter 4.
  51. // Please repect other people's valuable time & effort by making
  52. // your best effort to read chapter 4 before asking USB questions!
  53. //#define USBHOST_PRINT_DEBUG
  54. /************************************************/
  55. /* Data Types */
  56. /************************************************/
  57. // These 6 types are the key to understanding how this USB Host
  58. // library really works.
  59. // USBHost is a static class controlling the hardware.
  60. // All common USB functionality is implemented here.
  61. class USBHost;
  62. // These 3 structures represent the actual USB entities
  63. // USBHost manipulates. One Device_t is created for
  64. // each active USB device. One Pipe_t is create for
  65. // each endpoint. Transfer_t structures are created
  66. // when any data transfer is added to the EHCI work
  67. // queues, and then returned to the free pool after the
  68. // data transfer completes and the driver has processed
  69. // the results.
  70. typedef struct Device_struct Device_t;
  71. typedef struct Pipe_struct Pipe_t;
  72. typedef struct Transfer_struct Transfer_t;
  73. typedef enum { CLAIM_NO=0, CLAIM_REPORT, CLAIM_INTERFACE} hidclaim_t;
  74. // All USB device drivers inherit use these classes.
  75. // Drivers build user-visible functionality on top
  76. // of these classes, which receive USB events from
  77. // USBHost.
  78. class USBDriver;
  79. class USBDriverTimer;
  80. /************************************************/
  81. /* Added Defines */
  82. /************************************************/
  83. // Keyboard special Keys
  84. #define KEYD_UP 0xDA
  85. #define KEYD_DOWN 0xD9
  86. #define KEYD_LEFT 0xD8
  87. #define KEYD_RIGHT 0xD7
  88. #define KEYD_INSERT 0xD1
  89. #define KEYD_DELETE 0xD4
  90. #define KEYD_PAGE_UP 0xD3
  91. #define KEYD_PAGE_DOWN 0xD6
  92. #define KEYD_HOME 0xD2
  93. #define KEYD_END 0xD5
  94. #define KEYD_F1 0xC2
  95. #define KEYD_F2 0xC3
  96. #define KEYD_F3 0xC4
  97. #define KEYD_F4 0xC5
  98. #define KEYD_F5 0xC6
  99. #define KEYD_F6 0xC7
  100. #define KEYD_F7 0xC8
  101. #define KEYD_F8 0xC9
  102. #define KEYD_F9 0xCA
  103. #define KEYD_F10 0xCB
  104. #define KEYD_F11 0xCC
  105. #define KEYD_F12 0xCD
  106. // USBSerial formats - Lets encode format into bits
  107. // Bits: 0-4 - Number of data bits
  108. // Bits: 5-7 - Parity (0=none, 1=odd, 2 = even)
  109. // bits: 8-9 - Stop bits. 0=1, 1=2
  110. #define USBHOST_SERIAL_7E1 0x047
  111. #define USBHOST_SERIAL_7O1 0x027
  112. #define USBHOST_SERIAL_8N1 0x08
  113. #define USBHOST_SERIAL_8N2 0x108
  114. #define USBHOST_SERIAL_8E1 0x048
  115. #define USBHOST_SERIAL_8O1 0x028
  116. /************************************************/
  117. /* Data Structure Definitions */
  118. /************************************************/
  119. // setup_t holds the 8 byte USB SETUP packet data.
  120. // These unions & structs allow convenient access to
  121. // the setup fields.
  122. typedef union {
  123. struct {
  124. union {
  125. struct {
  126. uint8_t bmRequestType;
  127. uint8_t bRequest;
  128. };
  129. uint16_t wRequestAndType;
  130. };
  131. uint16_t wValue;
  132. uint16_t wIndex;
  133. uint16_t wLength;
  134. };
  135. struct {
  136. uint32_t word1;
  137. uint32_t word2;
  138. };
  139. } setup_t;
  140. typedef struct {
  141. enum {STRING_BUF_SIZE=50};
  142. enum {STR_ID_MAN=0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
  143. uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
  144. uint8_t buffer[STRING_BUF_SIZE];
  145. } strbuf_t;
  146. #define DEVICE_STRUCT_STRING_BUF_SIZE 50
  147. // Device_t holds all the information about a USB device
  148. struct Device_struct {
  149. Pipe_t *control_pipe;
  150. Pipe_t *data_pipes;
  151. Device_t *next;
  152. USBDriver *drivers;
  153. strbuf_t *strbuf;
  154. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  155. uint8_t address;
  156. uint8_t hub_address;
  157. uint8_t hub_port;
  158. uint8_t enum_state;
  159. uint8_t bDeviceClass;
  160. uint8_t bDeviceSubClass;
  161. uint8_t bDeviceProtocol;
  162. uint8_t bmAttributes;
  163. uint8_t bMaxPower;
  164. uint16_t idVendor;
  165. uint16_t idProduct;
  166. uint16_t LanguageID;
  167. };
  168. // Pipe_t holes all information about each USB endpoint/pipe
  169. // The first half is an EHCI QH structure for the pipe.
  170. struct Pipe_struct {
  171. // Queue Head (QH), EHCI page 46-50
  172. struct { // must be aligned to 32 byte boundary
  173. volatile uint32_t horizontal_link;
  174. volatile uint32_t capabilities[2];
  175. volatile uint32_t current;
  176. volatile uint32_t next;
  177. volatile uint32_t alt_next;
  178. volatile uint32_t token;
  179. volatile uint32_t buffer[5];
  180. } qh;
  181. Device_t *device;
  182. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  183. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  184. uint8_t start_mask;
  185. uint8_t complete_mask;
  186. Pipe_t *next;
  187. void (*callback_function)(const Transfer_t *);
  188. uint16_t periodic_interval;
  189. uint16_t periodic_offset;
  190. uint32_t unused1;
  191. uint32_t unused2;
  192. uint32_t unused3;
  193. uint32_t unused4;
  194. uint32_t unused5;
  195. uint32_t unused6;
  196. uint32_t unused7;
  197. };
  198. // Transfer_t represents a single transaction on the USB bus.
  199. // The first portion is an EHCI qTD structure. Transfer_t are
  200. // allocated as-needed from a memory pool, loaded with pointers
  201. // to the actual data buffers, linked into a followup list,
  202. // and placed on ECHI Queue Heads. When the ECHI interrupt
  203. // occurs, the followup lists are used to find the Transfer_t
  204. // in memory. Callbacks are made, and then the Transfer_t are
  205. // returned to the memory pool.
  206. struct Transfer_struct {
  207. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  208. struct { // must be aligned to 32 byte boundary
  209. volatile uint32_t next;
  210. volatile uint32_t alt_next;
  211. volatile uint32_t token;
  212. volatile uint32_t buffer[5];
  213. } qtd;
  214. // Linked list of queued, not-yet-completed transfers
  215. Transfer_t *next_followup;
  216. Transfer_t *prev_followup;
  217. Pipe_t *pipe;
  218. // Data to be used by callback function. When a group
  219. // of Transfer_t are created, these fields and the
  220. // interrupt-on-complete bit in the qTD token are only
  221. // set in the last Transfer_t of the list.
  222. void *buffer;
  223. uint32_t length;
  224. setup_t setup;
  225. USBDriver *driver;
  226. };
  227. /************************************************/
  228. /* Main USB EHCI Controller */
  229. /************************************************/
  230. class USBHost {
  231. public:
  232. static void begin();
  233. static void Task();
  234. protected:
  235. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  236. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  237. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  238. void *buf, USBDriver *driver);
  239. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  240. uint32_t len, USBDriver *driver);
  241. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  242. static void disconnect_Device(Device_t *dev);
  243. static void enumeration(const Transfer_t *transfer);
  244. static void driver_ready_for_device(USBDriver *driver);
  245. static volatile bool enumeration_busy;
  246. public: // Maybe others may want/need to contribute memory example HID devices may want to add transfers.
  247. static void contribute_Devices(Device_t *devices, uint32_t num);
  248. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  249. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  250. static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
  251. private:
  252. static void isr();
  253. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  254. static void claim_drivers(Device_t *dev);
  255. static uint32_t assign_address(void);
  256. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  257. static void init_Device_Pipe_Transfer_memory(void);
  258. static Device_t * allocate_Device(void);
  259. static void delete_Pipe(Pipe_t *pipe);
  260. static void free_Device(Device_t *q);
  261. static Pipe_t * allocate_Pipe(void);
  262. static void free_Pipe(Pipe_t *q);
  263. static Transfer_t * allocate_Transfer(void);
  264. static void free_Transfer(Transfer_t *q);
  265. static strbuf_t * allocate_string_buffer(void);
  266. static void free_string_buffer(strbuf_t *strbuf);
  267. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  268. uint32_t maxlen, uint32_t interval);
  269. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  270. static bool followup_Transfer(Transfer_t *transfer);
  271. static void followup_Error(void);
  272. protected:
  273. #ifdef USBHOST_PRINT_DEBUG
  274. static void print_(const Transfer_t *transfer);
  275. static void print_(const Transfer_t *first, const Transfer_t *last);
  276. static void print_token(uint32_t token);
  277. static void print_(const Pipe_t *pipe);
  278. static void print_driverlist(const char *name, const USBDriver *driver);
  279. static void print_qh_list(const Pipe_t *list);
  280. static void print_hexbytes(const void *ptr, uint32_t len);
  281. static void print_(const char *s) { Serial.print(s); }
  282. static void print_(int n) { Serial.print(n); }
  283. static void print_(unsigned int n) { Serial.print(n); }
  284. static void print_(long n) { Serial.print(n); }
  285. static void print_(unsigned long n) { Serial.print(n); }
  286. static void println_(const char *s) { Serial.println(s); }
  287. static void println_(int n) { Serial.println(n); }
  288. static void println_(unsigned int n) { Serial.println(n); }
  289. static void println_(long n) { Serial.println(n); }
  290. static void println_(unsigned long n) { Serial.println(n); }
  291. static void println_() { Serial.println(); }
  292. static void print_(uint32_t n, uint8_t b) { Serial.print(n, b); }
  293. static void println_(uint32_t n, uint8_t b) { Serial.println(n, b); }
  294. static void print_(const char *s, int n, uint8_t b = DEC) {
  295. Serial.print(s); Serial.print(n, b); }
  296. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  297. Serial.print(s); Serial.print(n, b); }
  298. static void print_(const char *s, long n, uint8_t b = DEC) {
  299. Serial.print(s); Serial.print(n, b); }
  300. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  301. Serial.print(s); Serial.print(n, b); }
  302. static void println_(const char *s, int n, uint8_t b = DEC) {
  303. Serial.print(s); Serial.println(n, b); }
  304. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  305. Serial.print(s); Serial.println(n, b); }
  306. static void println_(const char *s, long n, uint8_t b = DEC) {
  307. Serial.print(s); Serial.println(n, b); }
  308. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  309. Serial.print(s); Serial.println(n, b); }
  310. friend class USBDriverTimer; // for access to print & println
  311. #else
  312. static void print_(const Transfer_t *transfer) {}
  313. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  314. static void print_token(uint32_t token) {}
  315. static void print_(const Pipe_t *pipe) {}
  316. static void print_driverlist(const char *name, const USBDriver *driver) {}
  317. static void print_qh_list(const Pipe_t *list) {}
  318. static void print_hexbytes(const void *ptr, uint32_t len) {}
  319. static void print_(const char *s) {}
  320. static void print_(int n) {}
  321. static void print_(unsigned int n) {}
  322. static void print_(long n) {}
  323. static void print_(unsigned long n) {}
  324. static void println_(const char *s) {}
  325. static void println_(int n) {}
  326. static void println_(unsigned int n) {}
  327. static void println_(long n) {}
  328. static void println_(unsigned long n) {}
  329. static void println_() {}
  330. static void print_(uint32_t n, uint8_t b) {}
  331. static void println_(uint32_t n, uint8_t b) {}
  332. static void print_(const char *s, int n, uint8_t b = DEC) {}
  333. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  334. static void print_(const char *s, long n, uint8_t b = DEC) {}
  335. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  336. static void println_(const char *s, int n, uint8_t b = DEC) {}
  337. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  338. static void println_(const char *s, long n, uint8_t b = DEC) {}
  339. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  340. #endif
  341. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  342. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  343. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  344. s.word2 = wIndex | (wLength << 16);
  345. }
  346. };
  347. /************************************************/
  348. /* USB Device Driver Common Base Class */
  349. /************************************************/
  350. // All USB device drivers inherit from this base class.
  351. class USBDriver : public USBHost {
  352. public:
  353. //operator bool() { return (*(Device_t * volatile *)&device != nullptr); }
  354. operator bool() {
  355. Device_t *dev = *(Device_t * volatile *)&device;
  356. return dev != nullptr;
  357. }
  358. uint16_t idVendor() {
  359. Device_t *dev = *(Device_t * volatile *)&device;
  360. return (device != nullptr) ? device->idVendor : 0;
  361. }
  362. uint16_t idProduct() {
  363. Device_t *dev = *(Device_t * volatile *)&device;
  364. return (device != nullptr) ? device->idProduct : 0;
  365. }
  366. const uint8_t *manufacturer() {
  367. Device_t *dev = *(Device_t * volatile *)&device;
  368. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  369. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_MAN]];
  370. }
  371. const uint8_t *product() {
  372. Device_t *dev = *(Device_t * volatile *)&device;
  373. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  374. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_PROD]];
  375. }
  376. const uint8_t *serialNumber() {
  377. Device_t *dev = *(Device_t * volatile *)&device;
  378. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  379. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]];
  380. }
  381. protected:
  382. USBDriver() : next(NULL), device(NULL) {}
  383. // Check if a driver wishes to claim a device or interface or group
  384. // of interfaces within a device. When this function returns true,
  385. // the driver is considered bound or loaded for that device. When
  386. // new devices are detected, enumeration.cpp calls this function on
  387. // all unbound driver objects, to give them an opportunity to bind
  388. // to the new device.
  389. // device has its vid&pid, class/subclass fields initialized
  390. // type is 0 for device level, 1 for interface level, 2 for IAD
  391. // descriptors points to the specific descriptor data
  392. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  393. // When an unknown (not chapter 9) control transfer completes, this
  394. // function is called for all drivers bound to the device. Return
  395. // true means this driver originated this control transfer, so no
  396. // more drivers need to be offered an opportunity to process it.
  397. // This function is optional, only needed if the driver uses control
  398. // transfers and wishes to be notified when they complete.
  399. virtual void control(const Transfer_t *transfer) { }
  400. // When any of the USBDriverTimer objects a driver creates generates
  401. // a timer event, this function is called.
  402. virtual void timer_event(USBDriverTimer *whichTimer) { }
  403. // When the user calls USBHost::Task, this Task function for all
  404. // active drivers is called, so they may update state and/or call
  405. // any attached user callback functions.
  406. virtual void Task() { }
  407. // When a device disconnects from the USB, this function is called.
  408. // The driver must free all resources it allocated and update any
  409. // internal state necessary to deal with the possibility of user
  410. // code continuing to call its API. However, pipes and transfers
  411. // are the handled by lower layers, so device drivers do not free
  412. // pipes they created or cancel transfers they had in progress.
  413. virtual void disconnect();
  414. // Drivers are managed by this single-linked list. All inactive
  415. // (not bound to any device) drivers are linked from
  416. // available_drivers in enumeration.cpp. When bound to a device,
  417. // drivers are linked from that Device_t drivers list.
  418. USBDriver *next;
  419. // The device this object instance is bound to. In words, this
  420. // is the specific device this driver is using. When not bound
  421. // to any device, this must be NULL. Drivers may set this to
  422. // any non-NULL value if they are in a state where they do not
  423. // wish to claim any device or interface (eg, if getting data
  424. // from the HID parser).
  425. Device_t *device;
  426. friend class USBHost;
  427. };
  428. // Device drivers may create these timer objects to schedule a timer call
  429. class USBDriverTimer {
  430. public:
  431. USBDriverTimer() { }
  432. USBDriverTimer(USBDriver *d) : driver(d) { }
  433. void init(USBDriver *d) { driver = d; };
  434. void start(uint32_t microseconds);
  435. void stop();
  436. void *pointer;
  437. uint32_t integer;
  438. uint32_t started_micros; // testing only
  439. private:
  440. USBDriver *driver;
  441. uint32_t usec;
  442. USBDriverTimer *next;
  443. USBDriverTimer *prev;
  444. friend class USBHost;
  445. };
  446. // Device drivers may inherit from this base class, if they wish to receive
  447. // HID input data fully decoded by the USBHIDParser driver
  448. class USBHIDParser;
  449. class USBHIDInput {
  450. public:
  451. operator bool() { return (mydevice != nullptr); }
  452. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  453. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  454. const uint8_t *manufacturer()
  455. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  456. const uint8_t *product()
  457. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  458. const uint8_t *serialNumber()
  459. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  460. private:
  461. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  462. virtual bool hid_process_in_data(const Transfer_t *transfer) {return false;}
  463. virtual bool hid_process_out_data(const Transfer_t *transfer) {return false;}
  464. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  465. virtual void hid_input_data(uint32_t usage, int32_t value);
  466. virtual void hid_input_end();
  467. virtual void disconnect_collection(Device_t *dev);
  468. void add_to_list();
  469. USBHIDInput *next;
  470. friend class USBHIDParser;
  471. protected:
  472. Device_t *mydevice = NULL;
  473. };
  474. /************************************************/
  475. /* USB Device Drivers */
  476. /************************************************/
  477. class USBHub : public USBDriver {
  478. public:
  479. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  480. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  481. // Hubs with more more than 7 ports are built from two tiers of hubs
  482. // using 4 or 7 port hub chips. While the USB spec seems to allow
  483. // hubs to have up to 255 ports, in practice all hub chips on the
  484. // market are only 2, 3, 4 or 7 ports.
  485. enum { MAXPORTS = 7 };
  486. typedef uint8_t portbitmask_t;
  487. enum {
  488. PORT_OFF = 0,
  489. PORT_DISCONNECT = 1,
  490. PORT_DEBOUNCE1 = 2,
  491. PORT_DEBOUNCE2 = 3,
  492. PORT_DEBOUNCE3 = 4,
  493. PORT_DEBOUNCE4 = 5,
  494. PORT_DEBOUNCE5 = 6,
  495. PORT_RESET = 7,
  496. PORT_RECOVERY = 8,
  497. PORT_ACTIVE = 9
  498. };
  499. protected:
  500. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  501. virtual void control(const Transfer_t *transfer);
  502. virtual void timer_event(USBDriverTimer *whichTimer);
  503. virtual void disconnect();
  504. void init();
  505. bool can_send_control_now();
  506. void send_poweron(uint32_t port);
  507. void send_getstatus(uint32_t port);
  508. void send_clearstatus_connect(uint32_t port);
  509. void send_clearstatus_enable(uint32_t port);
  510. void send_clearstatus_suspend(uint32_t port);
  511. void send_clearstatus_overcurrent(uint32_t port);
  512. void send_clearstatus_reset(uint32_t port);
  513. void send_setreset(uint32_t port);
  514. static void callback(const Transfer_t *transfer);
  515. void status_change(const Transfer_t *transfer);
  516. void new_port_status(uint32_t port, uint32_t status);
  517. void start_debounce_timer(uint32_t port);
  518. void stop_debounce_timer(uint32_t port);
  519. private:
  520. Device_t mydevices[MAXPORTS];
  521. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  522. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  523. strbuf_t mystring_bufs[1];
  524. USBDriverTimer debouncetimer;
  525. USBDriverTimer resettimer;
  526. setup_t setup;
  527. Pipe_t *changepipe;
  528. Device_t *devicelist[MAXPORTS];
  529. uint32_t changebits;
  530. uint32_t statusbits;
  531. uint8_t hub_desc[16];
  532. uint8_t endpoint;
  533. uint8_t interval;
  534. uint8_t numports;
  535. uint8_t characteristics;
  536. uint8_t powertime;
  537. uint8_t sending_control_transfer;
  538. uint8_t port_doing_reset;
  539. uint8_t port_doing_reset_speed;
  540. uint8_t portstate[MAXPORTS];
  541. portbitmask_t send_pending_poweron;
  542. portbitmask_t send_pending_getstatus;
  543. portbitmask_t send_pending_clearstatus_connect;
  544. portbitmask_t send_pending_clearstatus_enable;
  545. portbitmask_t send_pending_clearstatus_suspend;
  546. portbitmask_t send_pending_clearstatus_overcurrent;
  547. portbitmask_t send_pending_clearstatus_reset;
  548. portbitmask_t send_pending_setreset;
  549. portbitmask_t debounce_in_use;
  550. static volatile bool reset_busy;
  551. };
  552. //--------------------------------------------------------------------------
  553. class USBHIDParser : public USBDriver {
  554. public:
  555. USBHIDParser(USBHost &host) { init(); }
  556. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  557. bool sendPacket(const uint8_t *buffer);
  558. protected:
  559. enum { TOPUSAGE_LIST_LEN = 4 };
  560. enum { USAGE_LIST_LEN = 24 };
  561. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  562. virtual void control(const Transfer_t *transfer);
  563. virtual void disconnect();
  564. static void in_callback(const Transfer_t *transfer);
  565. static void out_callback(const Transfer_t *transfer);
  566. void in_data(const Transfer_t *transfer);
  567. void out_data(const Transfer_t *transfer);
  568. bool check_if_using_report_id();
  569. void parse();
  570. USBHIDInput * find_driver(uint32_t topusage);
  571. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  572. void init();
  573. // Atempt for RAWhid to take over processing of data
  574. //
  575. uint16_t inSize(void) {return in_size;}
  576. uint16_t outSize(void) {return out_size;}
  577. uint8_t activeSendMask(void) {return txstate;}
  578. private:
  579. Pipe_t *in_pipe;
  580. Pipe_t *out_pipe;
  581. static USBHIDInput *available_hid_drivers_list;
  582. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  583. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  584. uint16_t in_size;
  585. uint16_t out_size;
  586. setup_t setup;
  587. uint8_t descriptor[512];
  588. uint8_t report[64];
  589. uint16_t descsize;
  590. bool use_report_id;
  591. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  592. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  593. strbuf_t mystring_bufs[1];
  594. uint8_t txstate = 0;
  595. uint8_t *tx1 = nullptr;
  596. uint8_t *tx2 = nullptr;
  597. bool hid_driver_claimed_control_ = false;
  598. };
  599. //--------------------------------------------------------------------------
  600. class KeyboardController : public USBDriver , public USBHIDInput {
  601. public:
  602. typedef union {
  603. struct {
  604. uint8_t numLock : 1;
  605. uint8_t capsLock : 1;
  606. uint8_t scrollLock : 1;
  607. uint8_t compose : 1;
  608. uint8_t kana : 1;
  609. uint8_t reserved : 3;
  610. };
  611. uint8_t byte;
  612. } KBDLeds_t;
  613. public:
  614. KeyboardController(USBHost &host) { init(); }
  615. KeyboardController(USBHost *host) { init(); }
  616. // Some methods are in both public classes so we need to figure out which one to use
  617. operator bool() { return (device != nullptr); }
  618. // Main boot keyboard functions.
  619. uint16_t getKey() { return keyCode; }
  620. uint8_t getModifiers() { return modifiers; }
  621. uint8_t getOemKey() { return keyOEM; }
  622. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  623. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  624. void LEDS(uint8_t leds);
  625. uint8_t LEDS() {return leds_.byte;}
  626. void updateLEDS(void);
  627. bool numLock() {return leds_.numLock;}
  628. bool capsLock() {return leds_.capsLock;}
  629. bool scrollLock() {return leds_.scrollLock;}
  630. void numLock(bool f);
  631. void capsLock(bool f);
  632. void scrollLock(bool f);
  633. // Added for extras information.
  634. void attachExtrasPress(void (*f)(uint32_t top, uint16_t code)) { extrasKeyPressedFunction = f; }
  635. void attachExtrasRelease(void (*f)(uint32_t top, uint16_t code)) { extrasKeyReleasedFunction = f; }
  636. enum {MAX_KEYS_DOWN=4};
  637. protected:
  638. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  639. virtual void control(const Transfer_t *transfer);
  640. virtual void disconnect();
  641. static void callback(const Transfer_t *transfer);
  642. void new_data(const Transfer_t *transfer);
  643. void init();
  644. protected: // HID functions for extra keyboard data.
  645. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  646. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  647. virtual void hid_input_data(uint32_t usage, int32_t value);
  648. virtual void hid_input_end();
  649. virtual void disconnect_collection(Device_t *dev);
  650. private:
  651. void update();
  652. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  653. void key_press(uint32_t mod, uint32_t key);
  654. void key_release(uint32_t mod, uint32_t key);
  655. void (*keyPressedFunction)(int unicode);
  656. void (*keyReleasedFunction)(int unicode);
  657. Pipe_t *datapipe;
  658. setup_t setup;
  659. uint8_t report[8];
  660. uint16_t keyCode;
  661. uint8_t modifiers;
  662. uint8_t keyOEM;
  663. uint8_t prev_report[8];
  664. KBDLeds_t leds_ = {0};
  665. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  666. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  667. strbuf_t mystring_bufs[1];
  668. // Added to process secondary HID data.
  669. void (*extrasKeyPressedFunction)(uint32_t top, uint16_t code);
  670. void (*extrasKeyReleasedFunction)(uint32_t top, uint16_t code);
  671. uint32_t topusage_ = 0; // What top report am I processing?
  672. uint8_t collections_claimed_ = 0;
  673. volatile bool hid_input_begin_ = false;
  674. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  675. uint8_t count_keys_down_ = 0;
  676. uint16_t keys_down[MAX_KEYS_DOWN];
  677. };
  678. class MouseController : public USBHIDInput {
  679. public:
  680. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  681. bool available() { return mouseEvent; }
  682. void mouseDataClear();
  683. uint8_t getButtons() { return buttons; }
  684. int getMouseX() { return mouseX; }
  685. int getMouseY() { return mouseY; }
  686. int getWheel() { return wheel; }
  687. int getWheelH() { return wheelH; }
  688. protected:
  689. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  690. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  691. virtual void hid_input_data(uint32_t usage, int32_t value);
  692. virtual void hid_input_end();
  693. virtual void disconnect_collection(Device_t *dev);
  694. private:
  695. uint8_t collections_claimed = 0;
  696. volatile bool mouseEvent = false;
  697. volatile bool hid_input_begin_ = false;
  698. uint8_t buttons = 0;
  699. int mouseX = 0;
  700. int mouseY = 0;
  701. int wheel = 0;
  702. int wheelH = 0;
  703. };
  704. //--------------------------------------------------------------------------
  705. class JoystickController : public USBDriver, public USBHIDInput {
  706. public:
  707. JoystickController(USBHost &host) { init(); }
  708. uint16_t idVendor();
  709. uint16_t idProduct();
  710. const uint8_t *manufacturer();
  711. const uint8_t *product();
  712. const uint8_t *serialNumber();
  713. operator bool() { return ((device != nullptr) || (mydevice != nullptr)); } // override as in both USBDriver and in USBHIDInput
  714. bool available() { return joystickEvent; }
  715. void joystickDataClear();
  716. uint32_t getButtons() { return buttons; }
  717. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  718. uint32_t axisMask() {return axis_mask_;}
  719. enum { AXIS_COUNT = 10 };
  720. protected:
  721. // From USBDriver
  722. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  723. virtual void control(const Transfer_t *transfer);
  724. virtual void disconnect();
  725. // From USBHIDInput
  726. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  727. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  728. virtual void hid_input_data(uint32_t usage, int32_t value);
  729. virtual void hid_input_end();
  730. virtual void disconnect_collection(Device_t *dev);
  731. private:
  732. // Class specific
  733. void init();
  734. bool anychange = false;
  735. volatile bool joystickEvent = false;
  736. uint32_t buttons = 0;
  737. int axis[AXIS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  738. uint32_t axis_mask_ = 0; // which axis have valid data
  739. // Used by HID code
  740. uint8_t collections_claimed = 0;
  741. // Used by USBDriver code
  742. static void rx_callback(const Transfer_t *transfer);
  743. static void tx_callback(const Transfer_t *transfer);
  744. void rx_data(const Transfer_t *transfer);
  745. void tx_data(const Transfer_t *transfer);
  746. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  747. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  748. strbuf_t mystring_bufs[1];
  749. uint16_t rx_size_ = 0;
  750. uint16_t tx_size_ = 0;
  751. Pipe_t *rxpipe_;
  752. Pipe_t *txpipe_;
  753. uint8_t rxbuf_[64]; // receive circular buffer
  754. // Mapping table to say which devices we handle
  755. typedef struct {
  756. uint16_t idVendor;
  757. uint16_t idProduct;
  758. } product_vendor_mapping_t;
  759. static product_vendor_mapping_t pid_vid_mapping[];
  760. };
  761. //--------------------------------------------------------------------------
  762. class MIDIDevice : public USBDriver {
  763. public:
  764. enum { SYSEX_MAX_LEN = 60 };
  765. MIDIDevice(USBHost &host) { init(); }
  766. MIDIDevice(USBHost *host) { init(); }
  767. bool read(uint8_t channel=0, uint8_t cable=0);
  768. uint8_t getType(void) {
  769. return msg_type;
  770. };
  771. uint8_t getChannel(void) {
  772. return msg_channel;
  773. };
  774. uint8_t getData1(void) {
  775. return msg_data1;
  776. };
  777. uint8_t getData2(void) {
  778. return msg_data2;
  779. };
  780. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  781. handleNoteOff = f;
  782. };
  783. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  784. handleNoteOn = f;
  785. };
  786. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  787. handleVelocityChange = f;
  788. };
  789. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  790. handleControlChange = f;
  791. };
  792. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  793. handleProgramChange = f;
  794. };
  795. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  796. handleAfterTouch = f;
  797. };
  798. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  799. handlePitchChange = f;
  800. };
  801. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  802. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  803. }
  804. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  805. handleRealTimeSystem = f;
  806. };
  807. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  808. handleTimeCodeQuarterFrame = f;
  809. };
  810. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  811. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  812. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  813. }
  814. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  815. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  816. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  817. }
  818. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  819. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  820. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  821. }
  822. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  823. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  824. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  825. }
  826. void sendProgramChange(uint32_t program, uint32_t channel) {
  827. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  828. | ((program & 0x7F) << 16));
  829. }
  830. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  831. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  832. | ((pressure & 0x7F) << 16));
  833. }
  834. void sendPitchBend(uint32_t value, uint32_t channel) {
  835. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  836. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  837. }
  838. void sendSysEx(uint32_t length, const void *data);
  839. void sendRealTime(uint32_t type) {
  840. switch (type) {
  841. case 0xF8: // Clock
  842. case 0xFA: // Start
  843. case 0xFC: // Stop
  844. case 0xFB: // Continue
  845. case 0xFE: // ActiveSensing
  846. case 0xFF: // SystemReset
  847. write_packed((type << 8) | 0x0F);
  848. break;
  849. default: // Invalid Real Time marker
  850. break;
  851. }
  852. }
  853. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  854. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  855. sendTimeCodeQuarterFrame(data);
  856. }
  857. void sendTimeCodeQuarterFrame(uint32_t data) {
  858. write_packed(0xF108 | ((data & 0x7F) << 16));
  859. }
  860. protected:
  861. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  862. virtual void disconnect();
  863. static void rx_callback(const Transfer_t *transfer);
  864. static void tx_callback(const Transfer_t *transfer);
  865. void rx_data(const Transfer_t *transfer);
  866. void tx_data(const Transfer_t *transfer);
  867. void init();
  868. void write_packed(uint32_t data);
  869. void sysex_byte(uint8_t b);
  870. private:
  871. Pipe_t *rxpipe;
  872. Pipe_t *txpipe;
  873. enum { MAX_PACKET_SIZE = 64 };
  874. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  875. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  876. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  877. uint16_t rx_size;
  878. uint16_t tx_size;
  879. uint32_t rx_queue[RX_QUEUE_SIZE];
  880. bool rx_packet_queued;
  881. uint16_t rx_head;
  882. uint16_t rx_tail;
  883. uint8_t rx_ep;
  884. uint8_t tx_ep;
  885. uint8_t msg_channel;
  886. uint8_t msg_type;
  887. uint8_t msg_data1;
  888. uint8_t msg_data2;
  889. uint8_t msg_sysex[SYSEX_MAX_LEN];
  890. uint8_t msg_sysex_len;
  891. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  892. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  893. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  894. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  895. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  896. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  897. void (*handlePitchChange)(uint8_t ch, int pitch);
  898. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  899. void (*handleRealTimeSystem)(uint8_t rtb);
  900. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  901. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  902. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  903. strbuf_t mystring_bufs[1];
  904. };
  905. //--------------------------------------------------------------------------
  906. class USBSerial: public USBDriver, public Stream {
  907. public:
  908. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  909. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  910. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  911. USBSerial(USBHost &host) : txtimer(this) { init(); }
  912. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  913. void end(void);
  914. uint32_t writeTimeout() {return write_timeout_;}
  915. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  916. virtual int available(void);
  917. virtual int peek(void);
  918. virtual int read(void);
  919. virtual int availableForWrite();
  920. virtual size_t write(uint8_t c);
  921. virtual void flush(void);
  922. using Print::write;
  923. protected:
  924. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  925. virtual void control(const Transfer_t *transfer);
  926. virtual void disconnect();
  927. virtual void timer_event(USBDriverTimer *whichTimer);
  928. private:
  929. static void rx_callback(const Transfer_t *transfer);
  930. static void tx_callback(const Transfer_t *transfer);
  931. void rx_data(const Transfer_t *transfer);
  932. void tx_data(const Transfer_t *transfer);
  933. void rx_queue_packets(uint32_t head, uint32_t tail);
  934. void init();
  935. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  936. bool init_buffers(uint32_t rsize, uint32_t tsize);
  937. void ch341_setBaud(uint8_t byte_index);
  938. private:
  939. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  940. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  941. strbuf_t mystring_bufs[1];
  942. USBDriverTimer txtimer;
  943. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  944. setup_t setup;
  945. uint8_t setupdata[16]; //
  946. uint32_t baudrate;
  947. uint32_t format_;
  948. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  949. Pipe_t *rxpipe;
  950. Pipe_t *txpipe;
  951. uint8_t *rx1; // location for first incoming packet
  952. uint8_t *rx2; // location for second incoming packet
  953. uint8_t *rxbuf; // receive circular buffer
  954. uint8_t *tx1; // location for first outgoing packet
  955. uint8_t *tx2; // location for second outgoing packet
  956. uint8_t *txbuf;
  957. volatile uint16_t rxhead;// receive head
  958. volatile uint16_t rxtail;// receive tail
  959. volatile uint16_t txhead;
  960. volatile uint16_t txtail;
  961. uint16_t rxsize;// size of receive circular buffer
  962. uint16_t txsize;// size of transmit circular buffer
  963. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  964. volatile uint8_t txstate;
  965. uint8_t pending_control;
  966. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  967. uint8_t pl2303_v1; // Which version do we have
  968. uint8_t pl2303_v2;
  969. uint8_t interface;
  970. bool control_queued;
  971. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  972. sertype_t sertype;
  973. typedef struct {
  974. uint16_t idVendor;
  975. uint16_t idProduct;
  976. sertype_t sertype;
  977. } product_vendor_mapping_t;
  978. static product_vendor_mapping_t pid_vid_mapping[];
  979. };
  980. //--------------------------------------------------------------------------
  981. class AntPlus: public USBDriver {
  982. // Please post any AntPlus feedback or contributions on this forum thread:
  983. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  984. public:
  985. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  986. void begin(const uint8_t key=0);
  987. void onStatusChange(void (*function)(int channel, int status)) {
  988. user_onStatusChange = function;
  989. }
  990. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  991. user_onDeviceID = function;
  992. }
  993. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  994. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  995. memset(&hrm, 0, sizeof(hrm));
  996. user_onHeartRateMonitor = f;
  997. }
  998. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  999. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  1000. memset(&spdcad, 0, sizeof(spdcad));
  1001. user_onSpeedCadence = f;
  1002. }
  1003. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  1004. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  1005. memset(&spd, 0, sizeof(spd));
  1006. user_onSpeed = f;
  1007. }
  1008. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  1009. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  1010. memset(&cad, 0, sizeof(cad));
  1011. user_onCadence = f;
  1012. }
  1013. void setWheelCircumference(float meters) {
  1014. wheelCircumference = meters * 1000.0f;
  1015. }
  1016. protected:
  1017. virtual void Task();
  1018. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1019. virtual void disconnect();
  1020. virtual void timer_event(USBDriverTimer *whichTimer);
  1021. private:
  1022. static void rx_callback(const Transfer_t *transfer);
  1023. static void tx_callback(const Transfer_t *transfer);
  1024. void rx_data(const Transfer_t *transfer);
  1025. void tx_data(const Transfer_t *transfer);
  1026. void init();
  1027. size_t write(const void *data, const size_t size);
  1028. int read(void *data, const size_t size);
  1029. void transmit();
  1030. private:
  1031. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1032. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1033. strbuf_t mystring_bufs[1];
  1034. //USBDriverTimer txtimer;
  1035. USBDriverTimer updatetimer;
  1036. Pipe_t *rxpipe;
  1037. Pipe_t *txpipe;
  1038. bool first_update;
  1039. uint8_t txbuffer[240];
  1040. uint8_t rxpacket[64];
  1041. volatile uint16_t txhead;
  1042. volatile uint16_t txtail;
  1043. volatile bool txready;
  1044. volatile uint8_t rxlen;
  1045. volatile bool do_polling;
  1046. private:
  1047. enum _eventi {
  1048. EVENTI_MESSAGE = 0,
  1049. EVENTI_CHANNEL,
  1050. EVENTI_TOTAL
  1051. };
  1052. enum _profiles {
  1053. PROFILE_HRM = 0,
  1054. PROFILE_SPDCAD,
  1055. PROFILE_POWER,
  1056. PROFILE_STRIDE,
  1057. PROFILE_SPEED,
  1058. PROFILE_CADENCE,
  1059. PROFILE_TOTAL
  1060. };
  1061. typedef struct {
  1062. uint8_t channel;
  1063. uint8_t RFFreq;
  1064. uint8_t networkNumber;
  1065. uint8_t stub;
  1066. uint8_t searchTimeout;
  1067. uint8_t channelType;
  1068. uint8_t deviceType;
  1069. uint8_t transType;
  1070. uint16_t channelPeriod;
  1071. uint16_t searchWaveform;
  1072. uint32_t deviceNumber; // deviceId
  1073. struct {
  1074. uint8_t chanIdOnce;
  1075. uint8_t keyAccepted;
  1076. uint8_t profileValid;
  1077. uint8_t channelStatus;
  1078. uint8_t channelStatusOld;
  1079. } flags;
  1080. } TDCONFIG;
  1081. struct {
  1082. uint8_t initOnce;
  1083. uint8_t key; // key index
  1084. int iDevice; // index to the antplus we're interested in, if > one found
  1085. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1086. } ant;
  1087. void (*user_onStatusChange)(int channel, int status);
  1088. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1089. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1090. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1091. void (*user_onSpeed)(float speed, float distance);
  1092. void (*user_onCadence)(float cadence);
  1093. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1094. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1095. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1096. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1097. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1098. static int msgGetLength(uint8_t *stream);
  1099. int handleMessages(uint8_t *buffer, int tBytes);
  1100. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1101. void message_channel(const int chan, const int eventId,
  1102. const uint8_t *payload, const size_t dataLength);
  1103. void message_response(const int chan, const int msgId,
  1104. const uint8_t *payload, const size_t dataLength);
  1105. void message_event(const int channel, const int msgId,
  1106. const uint8_t *payload, const size_t dataLength);
  1107. int ResetSystem();
  1108. int RequestMessage(const int channel, const int message);
  1109. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1110. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1111. int SetChannelPeriod(const int channel, const int period);
  1112. int SetChannelRFFreq(const int channel, const int freq);
  1113. int SetSearchWaveform(const int channel, const int wave);
  1114. int OpenChannel(const int channel);
  1115. int CloseChannel(const int channel);
  1116. int AssignChannel(const int channel, const int channelType, const int network);
  1117. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1118. const int transmissionType);
  1119. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1120. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1121. int SendBroadcastData(const int channel, const uint8_t *data);
  1122. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1123. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1124. const int TranType, const uint8_t *data);
  1125. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1126. const int TranType, const uint8_t *data);
  1127. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1128. const int devType, const int TranType, const uint8_t *data);
  1129. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1130. const int tranType, const uint8_t *data, const int nunPackets);
  1131. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1132. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1133. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1134. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1135. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1136. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1137. struct {
  1138. struct {
  1139. uint8_t bpm;
  1140. uint8_t sequence;
  1141. uint16_t time;
  1142. } previous;
  1143. } hrm;
  1144. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1145. struct {
  1146. struct {
  1147. uint16_t cadenceTime;
  1148. uint16_t cadenceCt;
  1149. uint16_t speedTime;
  1150. uint16_t speedCt;
  1151. } previous;
  1152. float distance;
  1153. } spdcad;
  1154. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1155. /* struct {
  1156. struct {
  1157. uint8_t sequence;
  1158. uint16_t pedalPowerContribution;
  1159. uint8_t pedalPower;
  1160. uint8_t instantCadence;
  1161. uint16_t sumPower;
  1162. uint16_t instantPower;
  1163. } current;
  1164. struct {
  1165. uint16_t stub;
  1166. } previous;
  1167. } pwr; */
  1168. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1169. /* struct {
  1170. struct {
  1171. uint16_t speed;
  1172. uint16_t cadence;
  1173. uint8_t strides;
  1174. } current;
  1175. struct {
  1176. uint8_t strides;
  1177. uint16_t speed;
  1178. uint16_t cadence;
  1179. } previous;
  1180. } stride; */
  1181. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1182. struct {
  1183. struct {
  1184. uint16_t speedTime;
  1185. uint16_t speedCt;
  1186. } previous;
  1187. float distance;
  1188. } spd;
  1189. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1190. struct {
  1191. struct {
  1192. uint16_t cadenceTime;
  1193. uint16_t cadenceCt;
  1194. } previous;
  1195. } cad;
  1196. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1197. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1198. };
  1199. //--------------------------------------------------------------------------
  1200. class RawHIDController : public USBHIDInput {
  1201. public:
  1202. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1203. uint32_t usage(void) {return usage_;}
  1204. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1205. bool sendPacket(const uint8_t *buffer);
  1206. protected:
  1207. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1208. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1209. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1210. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1211. virtual void hid_input_data(uint32_t usage, int32_t value);
  1212. virtual void hid_input_end();
  1213. virtual void disconnect_collection(Device_t *dev);
  1214. private:
  1215. void init();
  1216. USBHIDParser *driver_;
  1217. enum { MAX_PACKET_SIZE = 64 };
  1218. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1219. uint8_t collections_claimed = 0;
  1220. //volatile bool hid_input_begin_ = false;
  1221. uint32_t fixed_usage_;
  1222. uint32_t usage_ = 0;
  1223. // See if we can contribute transfers
  1224. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1225. };
  1226. #endif