You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1259 line
46KB

  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 != nullptr); }
  354. uint16_t idVendor() { return (device != nullptr) ? device->idVendor : 0; }
  355. uint16_t idProduct() { return (device != nullptr) ? device->idProduct : 0; }
  356. const uint8_t *manufacturer()
  357. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  358. const uint8_t *product()
  359. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  360. const uint8_t *serialNumber()
  361. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  362. // TODO: user-level functions
  363. // check if device is bound/active/online
  364. // query vid, pid
  365. // query string: manufacturer, product, serial number
  366. protected:
  367. USBDriver() : next(NULL), device(NULL) {}
  368. // Check if a driver wishes to claim a device or interface or group
  369. // of interfaces within a device. When this function returns true,
  370. // the driver is considered bound or loaded for that device. When
  371. // new devices are detected, enumeration.cpp calls this function on
  372. // all unbound driver objects, to give them an opportunity to bind
  373. // to the new device.
  374. // device has its vid&pid, class/subclass fields initialized
  375. // type is 0 for device level, 1 for interface level, 2 for IAD
  376. // descriptors points to the specific descriptor data
  377. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  378. // When an unknown (not chapter 9) control transfer completes, this
  379. // function is called for all drivers bound to the device. Return
  380. // true means this driver originated this control transfer, so no
  381. // more drivers need to be offered an opportunity to process it.
  382. // This function is optional, only needed if the driver uses control
  383. // transfers and wishes to be notified when they complete.
  384. virtual void control(const Transfer_t *transfer) { }
  385. // When any of the USBDriverTimer objects a driver creates generates
  386. // a timer event, this function is called.
  387. virtual void timer_event(USBDriverTimer *whichTimer) { }
  388. // When the user calls USBHost::Task, this Task function for all
  389. // active drivers is called, so they may update state and/or call
  390. // any attached user callback functions.
  391. virtual void Task() { }
  392. // When a device disconnects from the USB, this function is called.
  393. // The driver must free all resources it allocated and update any
  394. // internal state necessary to deal with the possibility of user
  395. // code continuing to call its API. However, pipes and transfers
  396. // are the handled by lower layers, so device drivers do not free
  397. // pipes they created or cancel transfers they had in progress.
  398. virtual void disconnect();
  399. // Drivers are managed by this single-linked list. All inactive
  400. // (not bound to any device) drivers are linked from
  401. // available_drivers in enumeration.cpp. When bound to a device,
  402. // drivers are linked from that Device_t drivers list.
  403. USBDriver *next;
  404. // The device this object instance is bound to. In words, this
  405. // is the specific device this driver is using. When not bound
  406. // to any device, this must be NULL. Drivers may set this to
  407. // any non-NULL value if they are in a state where they do not
  408. // wish to claim any device or interface (eg, if getting data
  409. // from the HID parser).
  410. Device_t *device;
  411. friend class USBHost;
  412. };
  413. // Device drivers may create these timer objects to schedule a timer call
  414. class USBDriverTimer {
  415. public:
  416. USBDriverTimer() { }
  417. USBDriverTimer(USBDriver *d) : driver(d) { }
  418. void init(USBDriver *d) { driver = d; };
  419. void start(uint32_t microseconds);
  420. void stop();
  421. void *pointer;
  422. uint32_t integer;
  423. uint32_t started_micros; // testing only
  424. private:
  425. USBDriver *driver;
  426. uint32_t usec;
  427. USBDriverTimer *next;
  428. USBDriverTimer *prev;
  429. friend class USBHost;
  430. };
  431. // Device drivers may inherit from this base class, if they wish to receive
  432. // HID input data fully decoded by the USBHIDParser driver
  433. class USBHIDParser;
  434. class USBHIDInput {
  435. public:
  436. operator bool() { return (mydevice != nullptr); }
  437. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  438. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  439. const uint8_t *manufacturer()
  440. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  441. const uint8_t *product()
  442. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  443. const uint8_t *serialNumber()
  444. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  445. private:
  446. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  447. virtual bool hid_process_in_data(const Transfer_t *transfer) {return false;}
  448. virtual bool hid_process_out_data(const Transfer_t *transfer) {return false;}
  449. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  450. virtual void hid_input_data(uint32_t usage, int32_t value);
  451. virtual void hid_input_end();
  452. virtual void disconnect_collection(Device_t *dev);
  453. void add_to_list();
  454. USBHIDInput *next;
  455. friend class USBHIDParser;
  456. protected:
  457. Device_t *mydevice = NULL;
  458. };
  459. /************************************************/
  460. /* USB Device Drivers */
  461. /************************************************/
  462. class USBHub : public USBDriver {
  463. public:
  464. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  465. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  466. // Hubs with more more than 7 ports are built from two tiers of hubs
  467. // using 4 or 7 port hub chips. While the USB spec seems to allow
  468. // hubs to have up to 255 ports, in practice all hub chips on the
  469. // market are only 2, 3, 4 or 7 ports.
  470. enum { MAXPORTS = 7 };
  471. typedef uint8_t portbitmask_t;
  472. enum {
  473. PORT_OFF = 0,
  474. PORT_DISCONNECT = 1,
  475. PORT_DEBOUNCE1 = 2,
  476. PORT_DEBOUNCE2 = 3,
  477. PORT_DEBOUNCE3 = 4,
  478. PORT_DEBOUNCE4 = 5,
  479. PORT_DEBOUNCE5 = 6,
  480. PORT_RESET = 7,
  481. PORT_RECOVERY = 8,
  482. PORT_ACTIVE = 9
  483. };
  484. protected:
  485. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  486. virtual void control(const Transfer_t *transfer);
  487. virtual void timer_event(USBDriverTimer *whichTimer);
  488. virtual void disconnect();
  489. void init();
  490. bool can_send_control_now();
  491. void send_poweron(uint32_t port);
  492. void send_getstatus(uint32_t port);
  493. void send_clearstatus_connect(uint32_t port);
  494. void send_clearstatus_enable(uint32_t port);
  495. void send_clearstatus_suspend(uint32_t port);
  496. void send_clearstatus_overcurrent(uint32_t port);
  497. void send_clearstatus_reset(uint32_t port);
  498. void send_setreset(uint32_t port);
  499. static void callback(const Transfer_t *transfer);
  500. void status_change(const Transfer_t *transfer);
  501. void new_port_status(uint32_t port, uint32_t status);
  502. void start_debounce_timer(uint32_t port);
  503. void stop_debounce_timer(uint32_t port);
  504. private:
  505. Device_t mydevices[MAXPORTS];
  506. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  507. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  508. strbuf_t mystring_bufs[1];
  509. USBDriverTimer debouncetimer;
  510. USBDriverTimer resettimer;
  511. setup_t setup;
  512. Pipe_t *changepipe;
  513. Device_t *devicelist[MAXPORTS];
  514. uint32_t changebits;
  515. uint32_t statusbits;
  516. uint8_t hub_desc[16];
  517. uint8_t endpoint;
  518. uint8_t interval;
  519. uint8_t numports;
  520. uint8_t characteristics;
  521. uint8_t powertime;
  522. uint8_t sending_control_transfer;
  523. uint8_t port_doing_reset;
  524. uint8_t port_doing_reset_speed;
  525. uint8_t portstate[MAXPORTS];
  526. portbitmask_t send_pending_poweron;
  527. portbitmask_t send_pending_getstatus;
  528. portbitmask_t send_pending_clearstatus_connect;
  529. portbitmask_t send_pending_clearstatus_enable;
  530. portbitmask_t send_pending_clearstatus_suspend;
  531. portbitmask_t send_pending_clearstatus_overcurrent;
  532. portbitmask_t send_pending_clearstatus_reset;
  533. portbitmask_t send_pending_setreset;
  534. portbitmask_t debounce_in_use;
  535. static volatile bool reset_busy;
  536. };
  537. //--------------------------------------------------------------------------
  538. class USBHIDParser : public USBDriver {
  539. public:
  540. USBHIDParser(USBHost &host) { init(); }
  541. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  542. bool sendPacket(const uint8_t *buffer);
  543. protected:
  544. enum { TOPUSAGE_LIST_LEN = 4 };
  545. enum { USAGE_LIST_LEN = 24 };
  546. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  547. virtual void control(const Transfer_t *transfer);
  548. virtual void disconnect();
  549. static void in_callback(const Transfer_t *transfer);
  550. static void out_callback(const Transfer_t *transfer);
  551. void in_data(const Transfer_t *transfer);
  552. void out_data(const Transfer_t *transfer);
  553. bool check_if_using_report_id();
  554. void parse();
  555. USBHIDInput * find_driver(uint32_t topusage);
  556. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  557. void init();
  558. // Atempt for RAWhid to take over processing of data
  559. //
  560. uint16_t inSize(void) {return in_size;}
  561. uint16_t outSize(void) {return out_size;}
  562. uint8_t activeSendMask(void) {return txstate;}
  563. private:
  564. Pipe_t *in_pipe;
  565. Pipe_t *out_pipe;
  566. static USBHIDInput *available_hid_drivers_list;
  567. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  568. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  569. uint16_t in_size;
  570. uint16_t out_size;
  571. setup_t setup;
  572. uint8_t descriptor[512];
  573. uint8_t report[64];
  574. uint16_t descsize;
  575. bool use_report_id;
  576. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  577. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  578. strbuf_t mystring_bufs[1];
  579. uint8_t txstate = 0;
  580. uint8_t *tx1 = nullptr;
  581. uint8_t *tx2 = nullptr;
  582. bool hid_driver_claimed_control_ = false;
  583. };
  584. //--------------------------------------------------------------------------
  585. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  586. public:
  587. typedef union {
  588. struct {
  589. uint8_t numLock : 1;
  590. uint8_t capsLock : 1;
  591. uint8_t scrollLock : 1;
  592. uint8_t compose : 1;
  593. uint8_t kana : 1;
  594. uint8_t reserved : 3;
  595. };
  596. uint8_t byte;
  597. } KBDLeds_t;
  598. public:
  599. KeyboardController(USBHost &host) { init(); }
  600. KeyboardController(USBHost *host) { init(); }
  601. int available();
  602. int read();
  603. uint16_t getKey() { return keyCode; }
  604. uint8_t getModifiers() { return modifiers; }
  605. uint8_t getOemKey() { return keyOEM; }
  606. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  607. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  608. void LEDS(uint8_t leds);
  609. uint8_t LEDS() {return leds_.byte;}
  610. void updateLEDS(void);
  611. bool numLock() {return leds_.numLock;}
  612. bool capsLock() {return leds_.capsLock;}
  613. bool scrollLock() {return leds_.scrollLock;}
  614. void numLock(bool f);
  615. void capsLock(bool f);
  616. void scrollLock(bool f);
  617. protected:
  618. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  619. virtual void control(const Transfer_t *transfer);
  620. virtual void disconnect();
  621. static void callback(const Transfer_t *transfer);
  622. void new_data(const Transfer_t *transfer);
  623. void init();
  624. private:
  625. void update();
  626. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  627. void key_press(uint32_t mod, uint32_t key);
  628. void key_release(uint32_t mod, uint32_t key);
  629. void (*keyPressedFunction)(int unicode);
  630. void (*keyReleasedFunction)(int unicode);
  631. Pipe_t *datapipe;
  632. setup_t setup;
  633. uint8_t report[8];
  634. uint16_t keyCode;
  635. uint8_t modifiers;
  636. uint8_t keyOEM;
  637. uint8_t prev_report[8];
  638. KBDLeds_t leds_ = {0};
  639. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  640. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  641. strbuf_t mystring_bufs[1];
  642. };
  643. //--------------------------------------------------------------------------
  644. class KeyboardHIDExtrasController : public USBHIDInput {
  645. public:
  646. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  647. void clear() { event_ = false;}
  648. bool available() { return event_; }
  649. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  650. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  651. enum {MAX_KEYS_DOWN=4};
  652. // uint32_t buttons() { return buttons_; }
  653. protected:
  654. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  655. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  656. virtual void hid_input_data(uint32_t usage, int32_t value);
  657. virtual void hid_input_end();
  658. virtual void disconnect_collection(Device_t *dev);
  659. private:
  660. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  661. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  662. uint32_t topusage_ = 0; // What top report am I processing?
  663. uint8_t collections_claimed_ = 0;
  664. volatile bool event_ = false;
  665. volatile bool hid_input_begin_ = false;
  666. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  667. uint8_t count_keys_down_ = 0;
  668. uint16_t keys_down[MAX_KEYS_DOWN];
  669. };
  670. //--------------------------------------------------------------------------
  671. class MouseController : public USBHIDInput {
  672. public:
  673. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  674. bool available() { return mouseEvent; }
  675. void mouseDataClear();
  676. uint8_t getButtons() { return buttons; }
  677. int getMouseX() { return mouseX; }
  678. int getMouseY() { return mouseY; }
  679. int getWheel() { return wheel; }
  680. int getWheelH() { return wheelH; }
  681. protected:
  682. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  683. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  684. virtual void hid_input_data(uint32_t usage, int32_t value);
  685. virtual void hid_input_end();
  686. virtual void disconnect_collection(Device_t *dev);
  687. private:
  688. uint8_t collections_claimed = 0;
  689. volatile bool mouseEvent = false;
  690. volatile bool hid_input_begin_ = false;
  691. uint8_t buttons = 0;
  692. int mouseX = 0;
  693. int mouseY = 0;
  694. int wheel = 0;
  695. int wheelH = 0;
  696. };
  697. //--------------------------------------------------------------------------
  698. class JoystickController : public USBHIDInput {
  699. public:
  700. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  701. bool available() { return joystickEvent; }
  702. void joystickDataClear();
  703. uint32_t getButtons() { return buttons; }
  704. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  705. protected:
  706. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  707. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  708. virtual void hid_input_data(uint32_t usage, int32_t value);
  709. virtual void hid_input_end();
  710. virtual void disconnect_collection(Device_t *dev);
  711. private:
  712. uint8_t collections_claimed = 0;
  713. bool anychange = false;
  714. volatile bool joystickEvent = false;
  715. uint32_t buttons = 0;
  716. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  717. };
  718. //--------------------------------------------------------------------------
  719. class MIDIDevice : public USBDriver {
  720. public:
  721. enum { SYSEX_MAX_LEN = 60 };
  722. MIDIDevice(USBHost &host) { init(); }
  723. MIDIDevice(USBHost *host) { init(); }
  724. bool read(uint8_t channel=0, uint8_t cable=0);
  725. uint8_t getType(void) {
  726. return msg_type;
  727. };
  728. uint8_t getChannel(void) {
  729. return msg_channel;
  730. };
  731. uint8_t getData1(void) {
  732. return msg_data1;
  733. };
  734. uint8_t getData2(void) {
  735. return msg_data2;
  736. };
  737. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  738. handleNoteOff = f;
  739. };
  740. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  741. handleNoteOn = f;
  742. };
  743. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  744. handleVelocityChange = f;
  745. };
  746. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  747. handleControlChange = f;
  748. };
  749. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  750. handleProgramChange = f;
  751. };
  752. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  753. handleAfterTouch = f;
  754. };
  755. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  756. handlePitchChange = f;
  757. };
  758. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  759. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  760. }
  761. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  762. handleRealTimeSystem = f;
  763. };
  764. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  765. handleTimeCodeQuarterFrame = f;
  766. };
  767. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  768. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  769. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  770. }
  771. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  772. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  773. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  774. }
  775. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  776. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  777. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  778. }
  779. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  780. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  781. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  782. }
  783. void sendProgramChange(uint32_t program, uint32_t channel) {
  784. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  785. | ((program & 0x7F) << 16));
  786. }
  787. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  788. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  789. | ((pressure & 0x7F) << 16));
  790. }
  791. void sendPitchBend(uint32_t value, uint32_t channel) {
  792. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  793. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  794. }
  795. void sendSysEx(uint32_t length, const void *data);
  796. void sendRealTime(uint32_t type) {
  797. switch (type) {
  798. case 0xF8: // Clock
  799. case 0xFA: // Start
  800. case 0xFC: // Stop
  801. case 0xFB: // Continue
  802. case 0xFE: // ActiveSensing
  803. case 0xFF: // SystemReset
  804. write_packed((type << 8) | 0x0F);
  805. break;
  806. default: // Invalid Real Time marker
  807. break;
  808. }
  809. }
  810. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  811. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  812. sendTimeCodeQuarterFrame(data);
  813. }
  814. void sendTimeCodeQuarterFrame(uint32_t data) {
  815. write_packed(0xF108 | ((data & 0x7F) << 16));
  816. }
  817. protected:
  818. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  819. virtual void disconnect();
  820. static void rx_callback(const Transfer_t *transfer);
  821. static void tx_callback(const Transfer_t *transfer);
  822. void rx_data(const Transfer_t *transfer);
  823. void tx_data(const Transfer_t *transfer);
  824. void init();
  825. void write_packed(uint32_t data);
  826. void sysex_byte(uint8_t b);
  827. private:
  828. Pipe_t *rxpipe;
  829. Pipe_t *txpipe;
  830. enum { MAX_PACKET_SIZE = 64 };
  831. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  832. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  833. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  834. uint16_t rx_size;
  835. uint16_t tx_size;
  836. uint32_t rx_queue[RX_QUEUE_SIZE];
  837. bool rx_packet_queued;
  838. uint16_t rx_head;
  839. uint16_t rx_tail;
  840. uint8_t rx_ep;
  841. uint8_t tx_ep;
  842. uint8_t msg_channel;
  843. uint8_t msg_type;
  844. uint8_t msg_data1;
  845. uint8_t msg_data2;
  846. uint8_t msg_sysex[SYSEX_MAX_LEN];
  847. uint8_t msg_sysex_len;
  848. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  849. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  850. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  851. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  852. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  853. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  854. void (*handlePitchChange)(uint8_t ch, int pitch);
  855. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  856. void (*handleRealTimeSystem)(uint8_t rtb);
  857. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  858. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  859. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  860. strbuf_t mystring_bufs[1];
  861. };
  862. //--------------------------------------------------------------------------
  863. class USBSerial: public USBDriver, public Stream {
  864. public:
  865. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  866. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  867. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  868. USBSerial(USBHost &host) : txtimer(this) { init(); }
  869. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  870. void end(void);
  871. uint32_t writeTimeout() {return write_timeout_;}
  872. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  873. virtual int available(void);
  874. virtual int peek(void);
  875. virtual int read(void);
  876. virtual int availableForWrite();
  877. virtual size_t write(uint8_t c);
  878. virtual void flush(void);
  879. using Print::write;
  880. protected:
  881. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  882. virtual void control(const Transfer_t *transfer);
  883. virtual void disconnect();
  884. virtual void timer_event(USBDriverTimer *whichTimer);
  885. private:
  886. static void rx_callback(const Transfer_t *transfer);
  887. static void tx_callback(const Transfer_t *transfer);
  888. void rx_data(const Transfer_t *transfer);
  889. void tx_data(const Transfer_t *transfer);
  890. void rx_queue_packets(uint32_t head, uint32_t tail);
  891. void init();
  892. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  893. bool init_buffers(uint32_t rsize, uint32_t tsize);
  894. void ch341_setBaud(uint8_t byte_index);
  895. private:
  896. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  897. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  898. strbuf_t mystring_bufs[1];
  899. USBDriverTimer txtimer;
  900. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  901. setup_t setup;
  902. uint8_t setupdata[16]; //
  903. uint32_t baudrate;
  904. uint32_t format_;
  905. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  906. Pipe_t *rxpipe;
  907. Pipe_t *txpipe;
  908. uint8_t *rx1; // location for first incoming packet
  909. uint8_t *rx2; // location for second incoming packet
  910. uint8_t *rxbuf; // receive circular buffer
  911. uint8_t *tx1; // location for first outgoing packet
  912. uint8_t *tx2; // location for second outgoing packet
  913. uint8_t *txbuf;
  914. volatile uint16_t rxhead;// receive head
  915. volatile uint16_t rxtail;// receive tail
  916. volatile uint16_t txhead;
  917. volatile uint16_t txtail;
  918. uint16_t rxsize;// size of receive circular buffer
  919. uint16_t txsize;// size of transmit circular buffer
  920. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  921. volatile uint8_t txstate;
  922. uint8_t pending_control;
  923. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  924. uint8_t pl2303_v1; // Which version do we have
  925. uint8_t pl2303_v2;
  926. uint8_t interface;
  927. bool control_queued;
  928. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  929. sertype_t sertype;
  930. typedef struct {
  931. uint16_t idVendor;
  932. uint16_t idProduct;
  933. sertype_t sertype;
  934. } product_vendor_mapping_t;
  935. static product_vendor_mapping_t pid_vid_mapping[];
  936. };
  937. //--------------------------------------------------------------------------
  938. class AntPlus: public USBDriver {
  939. // Please post any AntPlus feedback or contributions on this forum thread:
  940. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  941. public:
  942. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  943. void begin(const uint8_t key=0);
  944. void onStatusChange(void (*function)(int channel, int status)) {
  945. user_onStatusChange = function;
  946. }
  947. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  948. user_onDeviceID = function;
  949. }
  950. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  951. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  952. memset(&hrm, 0, sizeof(hrm));
  953. user_onHeartRateMonitor = f;
  954. }
  955. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  956. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  957. memset(&spdcad, 0, sizeof(spdcad));
  958. user_onSpeedCadence = f;
  959. }
  960. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  961. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  962. memset(&spd, 0, sizeof(spd));
  963. user_onSpeed = f;
  964. }
  965. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  966. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  967. memset(&cad, 0, sizeof(cad));
  968. user_onCadence = f;
  969. }
  970. void setWheelCircumference(float meters) {
  971. wheelCircumference = meters * 1000.0f;
  972. }
  973. protected:
  974. virtual void Task();
  975. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  976. virtual void disconnect();
  977. virtual void timer_event(USBDriverTimer *whichTimer);
  978. private:
  979. static void rx_callback(const Transfer_t *transfer);
  980. static void tx_callback(const Transfer_t *transfer);
  981. void rx_data(const Transfer_t *transfer);
  982. void tx_data(const Transfer_t *transfer);
  983. void init();
  984. size_t write(const void *data, const size_t size);
  985. int read(void *data, const size_t size);
  986. void transmit();
  987. private:
  988. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  989. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  990. strbuf_t mystring_bufs[1];
  991. //USBDriverTimer txtimer;
  992. USBDriverTimer updatetimer;
  993. Pipe_t *rxpipe;
  994. Pipe_t *txpipe;
  995. bool first_update;
  996. uint8_t txbuffer[240];
  997. uint8_t rxpacket[64];
  998. volatile uint16_t txhead;
  999. volatile uint16_t txtail;
  1000. volatile bool txready;
  1001. volatile uint8_t rxlen;
  1002. volatile bool do_polling;
  1003. private:
  1004. enum _eventi {
  1005. EVENTI_MESSAGE = 0,
  1006. EVENTI_CHANNEL,
  1007. EVENTI_TOTAL
  1008. };
  1009. enum _profiles {
  1010. PROFILE_HRM = 0,
  1011. PROFILE_SPDCAD,
  1012. PROFILE_POWER,
  1013. PROFILE_STRIDE,
  1014. PROFILE_SPEED,
  1015. PROFILE_CADENCE,
  1016. PROFILE_TOTAL
  1017. };
  1018. typedef struct {
  1019. uint8_t channel;
  1020. uint8_t RFFreq;
  1021. uint8_t networkNumber;
  1022. uint8_t stub;
  1023. uint8_t searchTimeout;
  1024. uint8_t channelType;
  1025. uint8_t deviceType;
  1026. uint8_t transType;
  1027. uint16_t channelPeriod;
  1028. uint16_t searchWaveform;
  1029. uint32_t deviceNumber; // deviceId
  1030. struct {
  1031. uint8_t chanIdOnce;
  1032. uint8_t keyAccepted;
  1033. uint8_t profileValid;
  1034. uint8_t channelStatus;
  1035. uint8_t channelStatusOld;
  1036. } flags;
  1037. } TDCONFIG;
  1038. struct {
  1039. uint8_t initOnce;
  1040. uint8_t key; // key index
  1041. int iDevice; // index to the antplus we're interested in, if > one found
  1042. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1043. } ant;
  1044. void (*user_onStatusChange)(int channel, int status);
  1045. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1046. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1047. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1048. void (*user_onSpeed)(float speed, float distance);
  1049. void (*user_onCadence)(float cadence);
  1050. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1051. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1052. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1053. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1054. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1055. static int msgGetLength(uint8_t *stream);
  1056. int handleMessages(uint8_t *buffer, int tBytes);
  1057. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1058. void message_channel(const int chan, const int eventId,
  1059. const uint8_t *payload, const size_t dataLength);
  1060. void message_response(const int chan, const int msgId,
  1061. const uint8_t *payload, const size_t dataLength);
  1062. void message_event(const int channel, const int msgId,
  1063. const uint8_t *payload, const size_t dataLength);
  1064. int ResetSystem();
  1065. int RequestMessage(const int channel, const int message);
  1066. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1067. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1068. int SetChannelPeriod(const int channel, const int period);
  1069. int SetChannelRFFreq(const int channel, const int freq);
  1070. int SetSearchWaveform(const int channel, const int wave);
  1071. int OpenChannel(const int channel);
  1072. int CloseChannel(const int channel);
  1073. int AssignChannel(const int channel, const int channelType, const int network);
  1074. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1075. const int transmissionType);
  1076. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1077. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1078. int SendBroadcastData(const int channel, const uint8_t *data);
  1079. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1080. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1081. const int TranType, const uint8_t *data);
  1082. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1083. const int TranType, const uint8_t *data);
  1084. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1085. const int devType, const int TranType, const uint8_t *data);
  1086. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1087. const int tranType, const uint8_t *data, const int nunPackets);
  1088. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1089. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1090. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1091. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1092. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1093. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1094. struct {
  1095. struct {
  1096. uint8_t bpm;
  1097. uint8_t sequence;
  1098. uint16_t time;
  1099. } previous;
  1100. } hrm;
  1101. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1102. struct {
  1103. struct {
  1104. uint16_t cadenceTime;
  1105. uint16_t cadenceCt;
  1106. uint16_t speedTime;
  1107. uint16_t speedCt;
  1108. } previous;
  1109. float distance;
  1110. } spdcad;
  1111. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1112. /* struct {
  1113. struct {
  1114. uint8_t sequence;
  1115. uint16_t pedalPowerContribution;
  1116. uint8_t pedalPower;
  1117. uint8_t instantCadence;
  1118. uint16_t sumPower;
  1119. uint16_t instantPower;
  1120. } current;
  1121. struct {
  1122. uint16_t stub;
  1123. } previous;
  1124. } pwr; */
  1125. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1126. /* struct {
  1127. struct {
  1128. uint16_t speed;
  1129. uint16_t cadence;
  1130. uint8_t strides;
  1131. } current;
  1132. struct {
  1133. uint8_t strides;
  1134. uint16_t speed;
  1135. uint16_t cadence;
  1136. } previous;
  1137. } stride; */
  1138. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1139. struct {
  1140. struct {
  1141. uint16_t speedTime;
  1142. uint16_t speedCt;
  1143. } previous;
  1144. float distance;
  1145. } spd;
  1146. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1147. struct {
  1148. struct {
  1149. uint16_t cadenceTime;
  1150. uint16_t cadenceCt;
  1151. } previous;
  1152. } cad;
  1153. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1154. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1155. };
  1156. //--------------------------------------------------------------------------
  1157. class RawHIDController : public USBHIDInput {
  1158. public:
  1159. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1160. uint32_t usage(void) {return usage_;}
  1161. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1162. bool sendPacket(const uint8_t *buffer);
  1163. protected:
  1164. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1165. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1166. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1167. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1168. virtual void hid_input_data(uint32_t usage, int32_t value);
  1169. virtual void hid_input_end();
  1170. virtual void disconnect_collection(Device_t *dev);
  1171. private:
  1172. void init();
  1173. USBHIDParser *driver_;
  1174. enum { MAX_PACKET_SIZE = 64 };
  1175. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1176. uint8_t collections_claimed = 0;
  1177. //volatile bool hid_input_begin_ = false;
  1178. uint32_t fixed_usage_;
  1179. uint32_t usage_ = 0;
  1180. // See if we can contribute transfers
  1181. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1182. };
  1183. #endif