Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1306 Zeilen
47KB

  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. // Some methods are in both public classes so we need to figure out which one to use
  602. operator bool() { return (device != nullptr); }
  603. // Main boot keyboard functions.
  604. uint16_t getKey() { return keyCode; }
  605. uint8_t getModifiers() { return modifiers; }
  606. uint8_t getOemKey() { return keyOEM; }
  607. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  608. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  609. void LEDS(uint8_t leds);
  610. uint8_t LEDS() {return leds_.byte;}
  611. void updateLEDS(void);
  612. bool numLock() {return leds_.numLock;}
  613. bool capsLock() {return leds_.capsLock;}
  614. bool scrollLock() {return leds_.scrollLock;}
  615. void numLock(bool f);
  616. void capsLock(bool f);
  617. void scrollLock(bool f);
  618. // Added for extras information.
  619. void attachExtrasPress(void (*f)(uint32_t top, uint16_t code)) { extrasKeyPressedFunction = f; }
  620. void attachExtrasRelease(void (*f)(uint32_t top, uint16_t code)) { extrasKeyReleasedFunction = f; }
  621. enum {MAX_KEYS_DOWN=4};
  622. protected:
  623. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  624. virtual void control(const Transfer_t *transfer);
  625. virtual void disconnect();
  626. static void callback(const Transfer_t *transfer);
  627. void new_data(const Transfer_t *transfer);
  628. void init();
  629. protected: // HID functions for extra keyboard data.
  630. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  631. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  632. virtual void hid_input_data(uint32_t usage, int32_t value);
  633. virtual void hid_input_end();
  634. virtual void disconnect_collection(Device_t *dev);
  635. private:
  636. void update();
  637. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  638. void key_press(uint32_t mod, uint32_t key);
  639. void key_release(uint32_t mod, uint32_t key);
  640. void (*keyPressedFunction)(int unicode);
  641. void (*keyReleasedFunction)(int unicode);
  642. Pipe_t *datapipe;
  643. setup_t setup;
  644. uint8_t report[8];
  645. uint16_t keyCode;
  646. uint8_t modifiers;
  647. uint8_t keyOEM;
  648. uint8_t prev_report[8];
  649. KBDLeds_t leds_ = {0};
  650. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  651. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  652. strbuf_t mystring_bufs[1];
  653. // Added to process secondary HID data.
  654. void (*extrasKeyPressedFunction)(uint32_t top, uint16_t code);
  655. void (*extrasKeyReleasedFunction)(uint32_t top, uint16_t code);
  656. uint32_t topusage_ = 0; // What top report am I processing?
  657. uint8_t collections_claimed_ = 0;
  658. volatile bool hid_input_begin_ = false;
  659. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  660. uint8_t count_keys_down_ = 0;
  661. uint16_t keys_down[MAX_KEYS_DOWN];
  662. };
  663. class MouseController : public USBHIDInput {
  664. public:
  665. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  666. bool available() { return mouseEvent; }
  667. void mouseDataClear();
  668. uint8_t getButtons() { return buttons; }
  669. int getMouseX() { return mouseX; }
  670. int getMouseY() { return mouseY; }
  671. int getWheel() { return wheel; }
  672. int getWheelH() { return wheelH; }
  673. protected:
  674. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  675. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  676. virtual void hid_input_data(uint32_t usage, int32_t value);
  677. virtual void hid_input_end();
  678. virtual void disconnect_collection(Device_t *dev);
  679. private:
  680. uint8_t collections_claimed = 0;
  681. volatile bool mouseEvent = false;
  682. volatile bool hid_input_begin_ = false;
  683. uint8_t buttons = 0;
  684. int mouseX = 0;
  685. int mouseY = 0;
  686. int wheel = 0;
  687. int wheelH = 0;
  688. };
  689. //--------------------------------------------------------------------------
  690. class JoystickController : public USBDriver, public USBHIDInput {
  691. public:
  692. JoystickController(USBHost &host) { init(); }
  693. uint16_t idVendor();
  694. uint16_t idProduct();
  695. const uint8_t *manufacturer();
  696. const uint8_t *product();
  697. const uint8_t *serialNumber();
  698. operator bool() { return ((device != nullptr) || (mydevice != nullptr)); } // override as in both USBDriver and in USBHIDInput
  699. bool available() { return joystickEvent; }
  700. void joystickDataClear();
  701. uint32_t getButtons() { return buttons; }
  702. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  703. uint32_t axisMask() {return axis_mask_;}
  704. enum { AXIS_COUNT = 10 };
  705. protected:
  706. // From USBDriver
  707. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  708. virtual void control(const Transfer_t *transfer);
  709. virtual void disconnect();
  710. // From USBHIDInput
  711. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  712. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  713. virtual void hid_input_data(uint32_t usage, int32_t value);
  714. virtual void hid_input_end();
  715. virtual void disconnect_collection(Device_t *dev);
  716. private:
  717. // Class specific
  718. void init();
  719. bool anychange = false;
  720. volatile bool joystickEvent = false;
  721. uint32_t buttons = 0;
  722. int axis[AXIS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  723. uint32_t axis_mask_ = 0; // which axis have valid data
  724. // Used by HID code
  725. uint8_t collections_claimed = 0;
  726. // Used by USBDriver code
  727. static void rx_callback(const Transfer_t *transfer);
  728. static void tx_callback(const Transfer_t *transfer);
  729. void rx_data(const Transfer_t *transfer);
  730. void tx_data(const Transfer_t *transfer);
  731. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  732. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  733. strbuf_t mystring_bufs[1];
  734. uint16_t rx_size_ = 0;
  735. uint16_t tx_size_ = 0;
  736. Pipe_t *rxpipe_;
  737. Pipe_t *txpipe_;
  738. uint8_t rxbuf_[64]; // receive circular buffer
  739. // Mapping table to say which devices we handle
  740. typedef struct {
  741. uint16_t idVendor;
  742. uint16_t idProduct;
  743. } product_vendor_mapping_t;
  744. static product_vendor_mapping_t pid_vid_mapping[];
  745. };
  746. //--------------------------------------------------------------------------
  747. class MIDIDevice : public USBDriver {
  748. public:
  749. enum { SYSEX_MAX_LEN = 60 };
  750. MIDIDevice(USBHost &host) { init(); }
  751. MIDIDevice(USBHost *host) { init(); }
  752. bool read(uint8_t channel=0, uint8_t cable=0);
  753. uint8_t getType(void) {
  754. return msg_type;
  755. };
  756. uint8_t getChannel(void) {
  757. return msg_channel;
  758. };
  759. uint8_t getData1(void) {
  760. return msg_data1;
  761. };
  762. uint8_t getData2(void) {
  763. return msg_data2;
  764. };
  765. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  766. handleNoteOff = f;
  767. };
  768. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  769. handleNoteOn = f;
  770. };
  771. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  772. handleVelocityChange = f;
  773. };
  774. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  775. handleControlChange = f;
  776. };
  777. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  778. handleProgramChange = f;
  779. };
  780. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  781. handleAfterTouch = f;
  782. };
  783. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  784. handlePitchChange = f;
  785. };
  786. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  787. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  788. }
  789. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  790. handleRealTimeSystem = f;
  791. };
  792. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  793. handleTimeCodeQuarterFrame = f;
  794. };
  795. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  796. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  797. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  798. }
  799. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  800. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  801. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  802. }
  803. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  804. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  805. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  806. }
  807. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  808. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  809. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  810. }
  811. void sendProgramChange(uint32_t program, uint32_t channel) {
  812. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  813. | ((program & 0x7F) << 16));
  814. }
  815. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  816. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  817. | ((pressure & 0x7F) << 16));
  818. }
  819. void sendPitchBend(uint32_t value, uint32_t channel) {
  820. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  821. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  822. }
  823. void sendSysEx(uint32_t length, const void *data);
  824. void sendRealTime(uint32_t type) {
  825. switch (type) {
  826. case 0xF8: // Clock
  827. case 0xFA: // Start
  828. case 0xFC: // Stop
  829. case 0xFB: // Continue
  830. case 0xFE: // ActiveSensing
  831. case 0xFF: // SystemReset
  832. write_packed((type << 8) | 0x0F);
  833. break;
  834. default: // Invalid Real Time marker
  835. break;
  836. }
  837. }
  838. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  839. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  840. sendTimeCodeQuarterFrame(data);
  841. }
  842. void sendTimeCodeQuarterFrame(uint32_t data) {
  843. write_packed(0xF108 | ((data & 0x7F) << 16));
  844. }
  845. protected:
  846. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  847. virtual void disconnect();
  848. static void rx_callback(const Transfer_t *transfer);
  849. static void tx_callback(const Transfer_t *transfer);
  850. void rx_data(const Transfer_t *transfer);
  851. void tx_data(const Transfer_t *transfer);
  852. void init();
  853. void write_packed(uint32_t data);
  854. void sysex_byte(uint8_t b);
  855. private:
  856. Pipe_t *rxpipe;
  857. Pipe_t *txpipe;
  858. enum { MAX_PACKET_SIZE = 64 };
  859. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  860. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  861. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  862. uint16_t rx_size;
  863. uint16_t tx_size;
  864. uint32_t rx_queue[RX_QUEUE_SIZE];
  865. bool rx_packet_queued;
  866. uint16_t rx_head;
  867. uint16_t rx_tail;
  868. uint8_t rx_ep;
  869. uint8_t tx_ep;
  870. uint8_t msg_channel;
  871. uint8_t msg_type;
  872. uint8_t msg_data1;
  873. uint8_t msg_data2;
  874. uint8_t msg_sysex[SYSEX_MAX_LEN];
  875. uint8_t msg_sysex_len;
  876. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  877. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  878. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  879. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  880. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  881. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  882. void (*handlePitchChange)(uint8_t ch, int pitch);
  883. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  884. void (*handleRealTimeSystem)(uint8_t rtb);
  885. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  886. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  887. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  888. strbuf_t mystring_bufs[1];
  889. };
  890. //--------------------------------------------------------------------------
  891. class USBSerial: public USBDriver, public Stream {
  892. public:
  893. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  894. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  895. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  896. USBSerial(USBHost &host) : txtimer(this) { init(); }
  897. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  898. void end(void);
  899. uint32_t writeTimeout() {return write_timeout_;}
  900. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  901. virtual int available(void);
  902. virtual int peek(void);
  903. virtual int read(void);
  904. virtual int availableForWrite();
  905. virtual size_t write(uint8_t c);
  906. virtual void flush(void);
  907. using Print::write;
  908. protected:
  909. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  910. virtual void control(const Transfer_t *transfer);
  911. virtual void disconnect();
  912. virtual void timer_event(USBDriverTimer *whichTimer);
  913. private:
  914. static void rx_callback(const Transfer_t *transfer);
  915. static void tx_callback(const Transfer_t *transfer);
  916. void rx_data(const Transfer_t *transfer);
  917. void tx_data(const Transfer_t *transfer);
  918. void rx_queue_packets(uint32_t head, uint32_t tail);
  919. void init();
  920. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  921. bool init_buffers(uint32_t rsize, uint32_t tsize);
  922. void ch341_setBaud(uint8_t byte_index);
  923. private:
  924. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  925. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  926. strbuf_t mystring_bufs[1];
  927. USBDriverTimer txtimer;
  928. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  929. setup_t setup;
  930. uint8_t setupdata[16]; //
  931. uint32_t baudrate;
  932. uint32_t format_;
  933. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  934. Pipe_t *rxpipe;
  935. Pipe_t *txpipe;
  936. uint8_t *rx1; // location for first incoming packet
  937. uint8_t *rx2; // location for second incoming packet
  938. uint8_t *rxbuf; // receive circular buffer
  939. uint8_t *tx1; // location for first outgoing packet
  940. uint8_t *tx2; // location for second outgoing packet
  941. uint8_t *txbuf;
  942. volatile uint16_t rxhead;// receive head
  943. volatile uint16_t rxtail;// receive tail
  944. volatile uint16_t txhead;
  945. volatile uint16_t txtail;
  946. uint16_t rxsize;// size of receive circular buffer
  947. uint16_t txsize;// size of transmit circular buffer
  948. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  949. volatile uint8_t txstate;
  950. uint8_t pending_control;
  951. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  952. uint8_t pl2303_v1; // Which version do we have
  953. uint8_t pl2303_v2;
  954. uint8_t interface;
  955. bool control_queued;
  956. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  957. sertype_t sertype;
  958. typedef struct {
  959. uint16_t idVendor;
  960. uint16_t idProduct;
  961. sertype_t sertype;
  962. } product_vendor_mapping_t;
  963. static product_vendor_mapping_t pid_vid_mapping[];
  964. };
  965. //--------------------------------------------------------------------------
  966. class AntPlus: public USBDriver {
  967. // Please post any AntPlus feedback or contributions on this forum thread:
  968. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  969. public:
  970. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  971. void begin(const uint8_t key=0);
  972. void onStatusChange(void (*function)(int channel, int status)) {
  973. user_onStatusChange = function;
  974. }
  975. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  976. user_onDeviceID = function;
  977. }
  978. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  979. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  980. memset(&hrm, 0, sizeof(hrm));
  981. user_onHeartRateMonitor = f;
  982. }
  983. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  984. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  985. memset(&spdcad, 0, sizeof(spdcad));
  986. user_onSpeedCadence = f;
  987. }
  988. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  989. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  990. memset(&spd, 0, sizeof(spd));
  991. user_onSpeed = f;
  992. }
  993. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  994. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  995. memset(&cad, 0, sizeof(cad));
  996. user_onCadence = f;
  997. }
  998. void setWheelCircumference(float meters) {
  999. wheelCircumference = meters * 1000.0f;
  1000. }
  1001. protected:
  1002. virtual void Task();
  1003. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1004. virtual void disconnect();
  1005. virtual void timer_event(USBDriverTimer *whichTimer);
  1006. private:
  1007. static void rx_callback(const Transfer_t *transfer);
  1008. static void tx_callback(const Transfer_t *transfer);
  1009. void rx_data(const Transfer_t *transfer);
  1010. void tx_data(const Transfer_t *transfer);
  1011. void init();
  1012. size_t write(const void *data, const size_t size);
  1013. int read(void *data, const size_t size);
  1014. void transmit();
  1015. private:
  1016. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1017. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1018. strbuf_t mystring_bufs[1];
  1019. //USBDriverTimer txtimer;
  1020. USBDriverTimer updatetimer;
  1021. Pipe_t *rxpipe;
  1022. Pipe_t *txpipe;
  1023. bool first_update;
  1024. uint8_t txbuffer[240];
  1025. uint8_t rxpacket[64];
  1026. volatile uint16_t txhead;
  1027. volatile uint16_t txtail;
  1028. volatile bool txready;
  1029. volatile uint8_t rxlen;
  1030. volatile bool do_polling;
  1031. private:
  1032. enum _eventi {
  1033. EVENTI_MESSAGE = 0,
  1034. EVENTI_CHANNEL,
  1035. EVENTI_TOTAL
  1036. };
  1037. enum _profiles {
  1038. PROFILE_HRM = 0,
  1039. PROFILE_SPDCAD,
  1040. PROFILE_POWER,
  1041. PROFILE_STRIDE,
  1042. PROFILE_SPEED,
  1043. PROFILE_CADENCE,
  1044. PROFILE_TOTAL
  1045. };
  1046. typedef struct {
  1047. uint8_t channel;
  1048. uint8_t RFFreq;
  1049. uint8_t networkNumber;
  1050. uint8_t stub;
  1051. uint8_t searchTimeout;
  1052. uint8_t channelType;
  1053. uint8_t deviceType;
  1054. uint8_t transType;
  1055. uint16_t channelPeriod;
  1056. uint16_t searchWaveform;
  1057. uint32_t deviceNumber; // deviceId
  1058. struct {
  1059. uint8_t chanIdOnce;
  1060. uint8_t keyAccepted;
  1061. uint8_t profileValid;
  1062. uint8_t channelStatus;
  1063. uint8_t channelStatusOld;
  1064. } flags;
  1065. } TDCONFIG;
  1066. struct {
  1067. uint8_t initOnce;
  1068. uint8_t key; // key index
  1069. int iDevice; // index to the antplus we're interested in, if > one found
  1070. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1071. } ant;
  1072. void (*user_onStatusChange)(int channel, int status);
  1073. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1074. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1075. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1076. void (*user_onSpeed)(float speed, float distance);
  1077. void (*user_onCadence)(float cadence);
  1078. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1079. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1080. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1081. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1082. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1083. static int msgGetLength(uint8_t *stream);
  1084. int handleMessages(uint8_t *buffer, int tBytes);
  1085. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1086. void message_channel(const int chan, const int eventId,
  1087. const uint8_t *payload, const size_t dataLength);
  1088. void message_response(const int chan, const int msgId,
  1089. const uint8_t *payload, const size_t dataLength);
  1090. void message_event(const int channel, const int msgId,
  1091. const uint8_t *payload, const size_t dataLength);
  1092. int ResetSystem();
  1093. int RequestMessage(const int channel, const int message);
  1094. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1095. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1096. int SetChannelPeriod(const int channel, const int period);
  1097. int SetChannelRFFreq(const int channel, const int freq);
  1098. int SetSearchWaveform(const int channel, const int wave);
  1099. int OpenChannel(const int channel);
  1100. int CloseChannel(const int channel);
  1101. int AssignChannel(const int channel, const int channelType, const int network);
  1102. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1103. const int transmissionType);
  1104. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1105. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1106. int SendBroadcastData(const int channel, const uint8_t *data);
  1107. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1108. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1109. const int TranType, const uint8_t *data);
  1110. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1111. const int TranType, const uint8_t *data);
  1112. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1113. const int devType, const int TranType, const uint8_t *data);
  1114. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1115. const int tranType, const uint8_t *data, const int nunPackets);
  1116. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1117. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1118. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1119. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1120. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1121. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1122. struct {
  1123. struct {
  1124. uint8_t bpm;
  1125. uint8_t sequence;
  1126. uint16_t time;
  1127. } previous;
  1128. } hrm;
  1129. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1130. struct {
  1131. struct {
  1132. uint16_t cadenceTime;
  1133. uint16_t cadenceCt;
  1134. uint16_t speedTime;
  1135. uint16_t speedCt;
  1136. } previous;
  1137. float distance;
  1138. } spdcad;
  1139. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1140. /* struct {
  1141. struct {
  1142. uint8_t sequence;
  1143. uint16_t pedalPowerContribution;
  1144. uint8_t pedalPower;
  1145. uint8_t instantCadence;
  1146. uint16_t sumPower;
  1147. uint16_t instantPower;
  1148. } current;
  1149. struct {
  1150. uint16_t stub;
  1151. } previous;
  1152. } pwr; */
  1153. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1154. /* struct {
  1155. struct {
  1156. uint16_t speed;
  1157. uint16_t cadence;
  1158. uint8_t strides;
  1159. } current;
  1160. struct {
  1161. uint8_t strides;
  1162. uint16_t speed;
  1163. uint16_t cadence;
  1164. } previous;
  1165. } stride; */
  1166. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1167. struct {
  1168. struct {
  1169. uint16_t speedTime;
  1170. uint16_t speedCt;
  1171. } previous;
  1172. float distance;
  1173. } spd;
  1174. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1175. struct {
  1176. struct {
  1177. uint16_t cadenceTime;
  1178. uint16_t cadenceCt;
  1179. } previous;
  1180. } cad;
  1181. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1182. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1183. };
  1184. //--------------------------------------------------------------------------
  1185. class RawHIDController : public USBHIDInput {
  1186. public:
  1187. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1188. uint32_t usage(void) {return usage_;}
  1189. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1190. bool sendPacket(const uint8_t *buffer);
  1191. protected:
  1192. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1193. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1194. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1195. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1196. virtual void hid_input_data(uint32_t usage, int32_t value);
  1197. virtual void hid_input_end();
  1198. virtual void disconnect_collection(Device_t *dev);
  1199. private:
  1200. void init();
  1201. USBHIDParser *driver_;
  1202. enum { MAX_PACKET_SIZE = 64 };
  1203. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1204. uint8_t collections_claimed = 0;
  1205. //volatile bool hid_input_begin_ = false;
  1206. uint32_t fixed_usage_;
  1207. uint32_t usage_ = 0;
  1208. // See if we can contribute transfers
  1209. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1210. };
  1211. #endif