Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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