Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1161 rinda
43KB

  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. // All USB device drivers inherit use these classes.
  74. // Drivers build user-visible functionality on top
  75. // of these classes, which receive USB events from
  76. // USBHost.
  77. class USBDriver;
  78. class USBDriverTimer;
  79. /************************************************/
  80. /* Added Defines */
  81. /************************************************/
  82. #define KEYD_UP 0xDA
  83. #define KEYD_DOWN 0xD9
  84. #define KEYD_LEFT 0xD8
  85. #define KEYD_RIGHT 0xD7
  86. #define KEYD_INSERT 0xD1
  87. #define KEYD_DELETE 0xD4
  88. #define KEYD_PAGE_UP 0xD3
  89. #define KEYD_PAGE_DOWN 0xD6
  90. #define KEYD_HOME 0xD2
  91. #define KEYD_END 0xD5
  92. #define KEYD_F1 0xC2
  93. #define KEYD_F2 0xC3
  94. #define KEYD_F3 0xC4
  95. #define KEYD_F4 0xC5
  96. #define KEYD_F5 0xC6
  97. #define KEYD_F6 0xC7
  98. #define KEYD_F7 0xC8
  99. #define KEYD_F8 0xC9
  100. #define KEYD_F9 0xCA
  101. #define KEYD_F10 0xCB
  102. #define KEYD_F11 0xCC
  103. #define KEYD_F12 0xCD
  104. /************************************************/
  105. /* Data Structure Definitions */
  106. /************************************************/
  107. // setup_t holds the 8 byte USB SETUP packet data.
  108. // These unions & structs allow convenient access to
  109. // the setup fields.
  110. typedef union {
  111. struct {
  112. union {
  113. struct {
  114. uint8_t bmRequestType;
  115. uint8_t bRequest;
  116. };
  117. uint16_t wRequestAndType;
  118. };
  119. uint16_t wValue;
  120. uint16_t wIndex;
  121. uint16_t wLength;
  122. };
  123. struct {
  124. uint32_t word1;
  125. uint32_t word2;
  126. };
  127. } setup_t;
  128. typedef struct {
  129. enum {STRING_BUF_SIZE=50};
  130. enum {STR_ID_MAN=0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
  131. uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
  132. uint8_t buffer[STRING_BUF_SIZE];
  133. } strbuf_t;
  134. #define DEVICE_STRUCT_STRING_BUF_SIZE 50
  135. // Device_t holds all the information about a USB device
  136. struct Device_struct {
  137. Pipe_t *control_pipe;
  138. Pipe_t *data_pipes;
  139. Device_t *next;
  140. USBDriver *drivers;
  141. strbuf_t *strbuf;
  142. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  143. uint8_t address;
  144. uint8_t hub_address;
  145. uint8_t hub_port;
  146. uint8_t enum_state;
  147. uint8_t bDeviceClass;
  148. uint8_t bDeviceSubClass;
  149. uint8_t bDeviceProtocol;
  150. uint8_t bmAttributes;
  151. uint8_t bMaxPower;
  152. uint16_t idVendor;
  153. uint16_t idProduct;
  154. uint16_t LanguageID;
  155. };
  156. // Pipe_t holes all information about each USB endpoint/pipe
  157. // The first half is an EHCI QH structure for the pipe.
  158. struct Pipe_struct {
  159. // Queue Head (QH), EHCI page 46-50
  160. struct { // must be aligned to 32 byte boundary
  161. volatile uint32_t horizontal_link;
  162. volatile uint32_t capabilities[2];
  163. volatile uint32_t current;
  164. volatile uint32_t next;
  165. volatile uint32_t alt_next;
  166. volatile uint32_t token;
  167. volatile uint32_t buffer[5];
  168. } qh;
  169. Device_t *device;
  170. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  171. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  172. uint8_t start_mask;
  173. uint8_t complete_mask;
  174. Pipe_t *next;
  175. void (*callback_function)(const Transfer_t *);
  176. uint16_t periodic_interval;
  177. uint16_t periodic_offset;
  178. uint32_t unused1;
  179. uint32_t unused2;
  180. uint32_t unused3;
  181. uint32_t unused4;
  182. uint32_t unused5;
  183. uint32_t unused6;
  184. uint32_t unused7;
  185. };
  186. // Transfer_t represents a single transaction on the USB bus.
  187. // The first portion is an EHCI qTD structure. Transfer_t are
  188. // allocated as-needed from a memory pool, loaded with pointers
  189. // to the actual data buffers, linked into a followup list,
  190. // and placed on ECHI Queue Heads. When the ECHI interrupt
  191. // occurs, the followup lists are used to find the Transfer_t
  192. // in memory. Callbacks are made, and then the Transfer_t are
  193. // returned to the memory pool.
  194. struct Transfer_struct {
  195. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  196. struct { // must be aligned to 32 byte boundary
  197. volatile uint32_t next;
  198. volatile uint32_t alt_next;
  199. volatile uint32_t token;
  200. volatile uint32_t buffer[5];
  201. } qtd;
  202. // Linked list of queued, not-yet-completed transfers
  203. Transfer_t *next_followup;
  204. Transfer_t *prev_followup;
  205. Pipe_t *pipe;
  206. // Data to be used by callback function. When a group
  207. // of Transfer_t are created, these fields and the
  208. // interrupt-on-complete bit in the qTD token are only
  209. // set in the last Transfer_t of the list.
  210. void *buffer;
  211. uint32_t length;
  212. setup_t setup;
  213. USBDriver *driver;
  214. };
  215. /************************************************/
  216. /* Main USB EHCI Controller */
  217. /************************************************/
  218. class USBHost {
  219. public:
  220. static void begin();
  221. static void Task();
  222. protected:
  223. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  224. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  225. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  226. void *buf, USBDriver *driver);
  227. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  228. uint32_t len, USBDriver *driver);
  229. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  230. static void disconnect_Device(Device_t *dev);
  231. static void enumeration(const Transfer_t *transfer);
  232. static void driver_ready_for_device(USBDriver *driver);
  233. static void contribute_Devices(Device_t *devices, uint32_t num);
  234. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  235. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  236. static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
  237. static volatile bool enumeration_busy;
  238. private:
  239. static void isr();
  240. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  241. static void claim_drivers(Device_t *dev);
  242. static uint32_t assign_address(void);
  243. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  244. static void init_Device_Pipe_Transfer_memory(void);
  245. static Device_t * allocate_Device(void);
  246. static void delete_Pipe(Pipe_t *pipe);
  247. static void free_Device(Device_t *q);
  248. static Pipe_t * allocate_Pipe(void);
  249. static void free_Pipe(Pipe_t *q);
  250. static Transfer_t * allocate_Transfer(void);
  251. static void free_Transfer(Transfer_t *q);
  252. static strbuf_t * allocate_string_buffer(void);
  253. static void free_string_buffer(strbuf_t *strbuf);
  254. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  255. uint32_t maxlen, uint32_t interval);
  256. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  257. static bool followup_Transfer(Transfer_t *transfer);
  258. static void followup_Error(void);
  259. protected:
  260. #ifdef USBHOST_PRINT_DEBUG
  261. static void print_(const Transfer_t *transfer);
  262. static void print_(const Transfer_t *first, const Transfer_t *last);
  263. static void print_token(uint32_t token);
  264. static void print_(const Pipe_t *pipe);
  265. static void print_driverlist(const char *name, const USBDriver *driver);
  266. static void print_qh_list(const Pipe_t *list);
  267. static void print_hexbytes(const void *ptr, uint32_t len);
  268. static void print_(const char *s) { Serial.print(s); }
  269. static void print_(int n) { Serial.print(n); }
  270. static void print_(unsigned int n) { Serial.print(n); }
  271. static void print_(long n) { Serial.print(n); }
  272. static void print_(unsigned long n) { Serial.print(n); }
  273. static void println_(const char *s) { Serial.println(s); }
  274. static void println_(int n) { Serial.println(n); }
  275. static void println_(unsigned int n) { Serial.println(n); }
  276. static void println_(long n) { Serial.println(n); }
  277. static void println_(unsigned long n) { Serial.println(n); }
  278. static void println_() { Serial.println(); }
  279. static void print_(uint32_t n, uint8_t b) { Serial.print(n, b); }
  280. static void println_(uint32_t n, uint8_t b) { Serial.println(n, b); }
  281. static void print_(const char *s, int n, uint8_t b = DEC) {
  282. Serial.print(s); Serial.print(n, b); }
  283. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  284. Serial.print(s); Serial.print(n, b); }
  285. static void print_(const char *s, long n, uint8_t b = DEC) {
  286. Serial.print(s); Serial.print(n, b); }
  287. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  288. Serial.print(s); Serial.print(n, b); }
  289. static void println_(const char *s, int n, uint8_t b = DEC) {
  290. Serial.print(s); Serial.println(n, b); }
  291. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  292. Serial.print(s); Serial.println(n, b); }
  293. static void println_(const char *s, long n, uint8_t b = DEC) {
  294. Serial.print(s); Serial.println(n, b); }
  295. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  296. Serial.print(s); Serial.println(n, b); }
  297. friend class USBDriverTimer; // for access to print & println
  298. #else
  299. static void print_(const Transfer_t *transfer) {}
  300. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  301. static void print_token(uint32_t token) {}
  302. static void print_(const Pipe_t *pipe) {}
  303. static void print_driverlist(const char *name, const USBDriver *driver) {}
  304. static void print_qh_list(const Pipe_t *list) {}
  305. static void print_hexbytes(const void *ptr, uint32_t len) {}
  306. static void print_(const char *s) {}
  307. static void print_(int n) {}
  308. static void print_(unsigned int n) {}
  309. static void print_(long n) {}
  310. static void print_(unsigned long n) {}
  311. static void println_(const char *s) {}
  312. static void println_(int n) {}
  313. static void println_(unsigned int n) {}
  314. static void println_(long n) {}
  315. static void println_(unsigned long n) {}
  316. static void println_() {}
  317. static void print_(uint32_t n, uint8_t b) {}
  318. static void println_(uint32_t n, uint8_t b) {}
  319. static void print_(const char *s, int n, uint8_t b = DEC) {}
  320. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  321. static void print_(const char *s, long n, uint8_t b = DEC) {}
  322. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  323. static void println_(const char *s, int n, uint8_t b = DEC) {}
  324. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  325. static void println_(const char *s, long n, uint8_t b = DEC) {}
  326. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  327. #endif
  328. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  329. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  330. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  331. s.word2 = wIndex | (wLength << 16);
  332. }
  333. };
  334. /************************************************/
  335. /* USB Device Driver Common Base Class */
  336. /************************************************/
  337. // All USB device drivers inherit from this base class.
  338. class USBDriver : public USBHost {
  339. public:
  340. operator bool() { return (device != nullptr); }
  341. uint16_t idVendor() { return (device != nullptr) ? device->idVendor : 0; }
  342. uint16_t idProduct() { return (device != nullptr) ? device->idProduct : 0; }
  343. const uint8_t *manufacturer()
  344. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  345. const uint8_t *product()
  346. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  347. const uint8_t *serialNumber()
  348. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  349. // TODO: user-level functions
  350. // check if device is bound/active/online
  351. // query vid, pid
  352. // query string: manufacturer, product, serial number
  353. protected:
  354. USBDriver() : next(NULL), device(NULL) {}
  355. // Check if a driver wishes to claim a device or interface or group
  356. // of interfaces within a device. When this function returns true,
  357. // the driver is considered bound or loaded for that device. When
  358. // new devices are detected, enumeration.cpp calls this function on
  359. // all unbound driver objects, to give them an opportunity to bind
  360. // to the new device.
  361. // device has its vid&pid, class/subclass fields initialized
  362. // type is 0 for device level, 1 for interface level, 2 for IAD
  363. // descriptors points to the specific descriptor data
  364. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  365. // When an unknown (not chapter 9) control transfer completes, this
  366. // function is called for all drivers bound to the device. Return
  367. // true means this driver originated this control transfer, so no
  368. // more drivers need to be offered an opportunity to process it.
  369. // This function is optional, only needed if the driver uses control
  370. // transfers and wishes to be notified when they complete.
  371. virtual void control(const Transfer_t *transfer) { }
  372. // When any of the USBDriverTimer objects a driver creates generates
  373. // a timer event, this function is called.
  374. virtual void timer_event(USBDriverTimer *whichTimer) { }
  375. // When the user calls USBHost::Task, this Task function for all
  376. // active drivers is called, so they may update state and/or call
  377. // any attached user callback functions.
  378. virtual void Task() { }
  379. // When a device disconnects from the USB, this function is called.
  380. // The driver must free all resources it allocated and update any
  381. // internal state necessary to deal with the possibility of user
  382. // code continuing to call its API. However, pipes and transfers
  383. // are the handled by lower layers, so device drivers do not free
  384. // pipes they created or cancel transfers they had in progress.
  385. virtual void disconnect();
  386. // Drivers are managed by this single-linked list. All inactive
  387. // (not bound to any device) drivers are linked from
  388. // available_drivers in enumeration.cpp. When bound to a device,
  389. // drivers are linked from that Device_t drivers list.
  390. USBDriver *next;
  391. // The device this object instance is bound to. In words, this
  392. // is the specific device this driver is using. When not bound
  393. // to any device, this must be NULL. Drivers may set this to
  394. // any non-NULL value if they are in a state where they do not
  395. // wish to claim any device or interface (eg, if getting data
  396. // from the HID parser).
  397. Device_t *device;
  398. friend class USBHost;
  399. };
  400. // Device drivers may create these timer objects to schedule a timer call
  401. class USBDriverTimer {
  402. public:
  403. USBDriverTimer() { }
  404. USBDriverTimer(USBDriver *d) : driver(d) { }
  405. void init(USBDriver *d) { driver = d; };
  406. void start(uint32_t microseconds);
  407. void stop();
  408. void *pointer;
  409. uint32_t integer;
  410. uint32_t started_micros; // testing only
  411. private:
  412. USBDriver *driver;
  413. uint32_t usec;
  414. USBDriverTimer *next;
  415. USBDriverTimer *prev;
  416. friend class USBHost;
  417. };
  418. // Device drivers may inherit from this base class, if they wish to receive
  419. // HID input data fully decoded by the USBHIDParser driver
  420. class USBHIDInput {
  421. public:
  422. operator bool() { return (mydevice != nullptr); }
  423. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  424. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  425. const uint8_t *manufacturer()
  426. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  427. const uint8_t *product()
  428. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  429. const uint8_t *serialNumber()
  430. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  431. private:
  432. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  433. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  434. virtual void hid_input_data(uint32_t usage, int32_t value);
  435. virtual void hid_input_end();
  436. virtual void disconnect_collection(Device_t *dev);
  437. void add_to_list();
  438. USBHIDInput *next;
  439. friend class USBHIDParser;
  440. protected:
  441. Device_t *mydevice = NULL;
  442. };
  443. /************************************************/
  444. /* USB Device Drivers */
  445. /************************************************/
  446. class USBHub : public USBDriver {
  447. public:
  448. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  449. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  450. // Hubs with more more than 7 ports are built from two tiers of hubs
  451. // using 4 or 7 port hub chips. While the USB spec seems to allow
  452. // hubs to have up to 255 ports, in practice all hub chips on the
  453. // market are only 2, 3, 4 or 7 ports.
  454. enum { MAXPORTS = 7 };
  455. typedef uint8_t portbitmask_t;
  456. enum {
  457. PORT_OFF = 0,
  458. PORT_DISCONNECT = 1,
  459. PORT_DEBOUNCE1 = 2,
  460. PORT_DEBOUNCE2 = 3,
  461. PORT_DEBOUNCE3 = 4,
  462. PORT_DEBOUNCE4 = 5,
  463. PORT_DEBOUNCE5 = 6,
  464. PORT_RESET = 7,
  465. PORT_RECOVERY = 8,
  466. PORT_ACTIVE = 9
  467. };
  468. protected:
  469. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  470. virtual void control(const Transfer_t *transfer);
  471. virtual void timer_event(USBDriverTimer *whichTimer);
  472. virtual void disconnect();
  473. void init();
  474. bool can_send_control_now();
  475. void send_poweron(uint32_t port);
  476. void send_getstatus(uint32_t port);
  477. void send_clearstatus_connect(uint32_t port);
  478. void send_clearstatus_enable(uint32_t port);
  479. void send_clearstatus_suspend(uint32_t port);
  480. void send_clearstatus_overcurrent(uint32_t port);
  481. void send_clearstatus_reset(uint32_t port);
  482. void send_setreset(uint32_t port);
  483. static void callback(const Transfer_t *transfer);
  484. void status_change(const Transfer_t *transfer);
  485. void new_port_status(uint32_t port, uint32_t status);
  486. void start_debounce_timer(uint32_t port);
  487. void stop_debounce_timer(uint32_t port);
  488. private:
  489. Device_t mydevices[MAXPORTS];
  490. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  491. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  492. strbuf_t mystring_bufs[1];
  493. USBDriverTimer debouncetimer;
  494. USBDriverTimer resettimer;
  495. setup_t setup;
  496. Pipe_t *changepipe;
  497. Device_t *devicelist[MAXPORTS];
  498. uint32_t changebits;
  499. uint32_t statusbits;
  500. uint8_t hub_desc[16];
  501. uint8_t endpoint;
  502. uint8_t interval;
  503. uint8_t numports;
  504. uint8_t characteristics;
  505. uint8_t powertime;
  506. uint8_t sending_control_transfer;
  507. uint8_t port_doing_reset;
  508. uint8_t port_doing_reset_speed;
  509. uint8_t portstate[MAXPORTS];
  510. portbitmask_t send_pending_poweron;
  511. portbitmask_t send_pending_getstatus;
  512. portbitmask_t send_pending_clearstatus_connect;
  513. portbitmask_t send_pending_clearstatus_enable;
  514. portbitmask_t send_pending_clearstatus_suspend;
  515. portbitmask_t send_pending_clearstatus_overcurrent;
  516. portbitmask_t send_pending_clearstatus_reset;
  517. portbitmask_t send_pending_setreset;
  518. portbitmask_t debounce_in_use;
  519. static volatile bool reset_busy;
  520. };
  521. class USBHIDParser : public USBDriver {
  522. public:
  523. USBHIDParser(USBHost &host) { init(); }
  524. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  525. protected:
  526. enum { TOPUSAGE_LIST_LEN = 4 };
  527. enum { USAGE_LIST_LEN = 24 };
  528. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  529. virtual void control(const Transfer_t *transfer);
  530. virtual void disconnect();
  531. static void in_callback(const Transfer_t *transfer);
  532. static void out_callback(const Transfer_t *transfer);
  533. void in_data(const Transfer_t *transfer);
  534. void out_data(const Transfer_t *transfer);
  535. bool check_if_using_report_id();
  536. void parse();
  537. USBHIDInput * find_driver(uint32_t topusage);
  538. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  539. void init();
  540. private:
  541. Pipe_t *in_pipe;
  542. Pipe_t *out_pipe;
  543. static USBHIDInput *available_hid_drivers_list;
  544. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  545. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  546. uint16_t in_size;
  547. uint16_t out_size;
  548. setup_t setup;
  549. uint8_t descriptor[512];
  550. uint8_t report[64];
  551. uint16_t descsize;
  552. bool use_report_id;
  553. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  554. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  555. strbuf_t mystring_bufs[1];
  556. };
  557. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  558. public:
  559. typedef union {
  560. struct {
  561. uint8_t numLock : 1;
  562. uint8_t capsLock : 1;
  563. uint8_t scrollLock : 1;
  564. uint8_t compose : 1;
  565. uint8_t kana : 1;
  566. uint8_t reserved : 3;
  567. };
  568. uint8_t byte;
  569. } KBDLeds_t;
  570. public:
  571. KeyboardController(USBHost &host) { init(); }
  572. KeyboardController(USBHost *host) { init(); }
  573. int available();
  574. int read();
  575. uint16_t getKey() { return keyCode; }
  576. uint8_t getModifiers() { return modifiers; }
  577. uint8_t getOemKey() { return keyOEM; }
  578. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  579. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  580. void LEDS(uint8_t leds);
  581. uint8_t LEDS() {return leds_.byte;}
  582. void updateLEDS(void);
  583. bool numLock() {return leds_.numLock;}
  584. bool capsLock() {return leds_.capsLock;}
  585. bool scrollLock() {return leds_.scrollLock;}
  586. void numLock(bool f);
  587. void capsLock(bool f);
  588. void scrollLock(bool f);
  589. protected:
  590. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  591. virtual void control(const Transfer_t *transfer);
  592. virtual void disconnect();
  593. static void callback(const Transfer_t *transfer);
  594. void new_data(const Transfer_t *transfer);
  595. void init();
  596. private:
  597. void update();
  598. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  599. void key_press(uint32_t mod, uint32_t key);
  600. void key_release(uint32_t mod, uint32_t key);
  601. void (*keyPressedFunction)(int unicode);
  602. void (*keyReleasedFunction)(int unicode);
  603. Pipe_t *datapipe;
  604. setup_t setup;
  605. uint8_t report[8];
  606. uint16_t keyCode;
  607. uint8_t modifiers;
  608. uint8_t keyOEM;
  609. uint8_t prev_report[8];
  610. KBDLeds_t leds_ = {0};
  611. bool update_leds_ = false;
  612. bool processing_new_data_ = false;
  613. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  614. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  615. strbuf_t mystring_bufs[1];
  616. };
  617. class MIDIDevice : public USBDriver {
  618. public:
  619. enum { SYSEX_MAX_LEN = 60 };
  620. MIDIDevice(USBHost &host) { init(); }
  621. MIDIDevice(USBHost *host) { init(); }
  622. bool read(uint8_t channel=0, uint8_t cable=0);
  623. uint8_t getType(void) {
  624. return msg_type;
  625. };
  626. uint8_t getChannel(void) {
  627. return msg_channel;
  628. };
  629. uint8_t getData1(void) {
  630. return msg_data1;
  631. };
  632. uint8_t getData2(void) {
  633. return msg_data2;
  634. };
  635. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  636. handleNoteOff = f;
  637. };
  638. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  639. handleNoteOn = f;
  640. };
  641. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  642. handleVelocityChange = f;
  643. };
  644. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  645. handleControlChange = f;
  646. };
  647. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  648. handleProgramChange = f;
  649. };
  650. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  651. handleAfterTouch = f;
  652. };
  653. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  654. handlePitchChange = f;
  655. };
  656. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  657. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  658. }
  659. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  660. handleRealTimeSystem = f;
  661. };
  662. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  663. handleTimeCodeQuarterFrame = f;
  664. };
  665. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  666. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  667. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  668. }
  669. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  670. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  671. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  672. }
  673. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  674. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  675. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  676. }
  677. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  678. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  679. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  680. }
  681. void sendProgramChange(uint32_t program, uint32_t channel) {
  682. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  683. | ((program & 0x7F) << 16));
  684. }
  685. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  686. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  687. | ((pressure & 0x7F) << 16));
  688. }
  689. void sendPitchBend(uint32_t value, uint32_t channel) {
  690. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  691. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  692. }
  693. void sendSysEx(uint32_t length, const void *data);
  694. void sendRealTime(uint32_t type) {
  695. switch (type) {
  696. case 0xF8: // Clock
  697. case 0xFA: // Start
  698. case 0xFC: // Stop
  699. case 0xFB: // Continue
  700. case 0xFE: // ActiveSensing
  701. case 0xFF: // SystemReset
  702. write_packed((type << 8) | 0x0F);
  703. break;
  704. default: // Invalid Real Time marker
  705. break;
  706. }
  707. }
  708. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  709. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  710. sendTimeCodeQuarterFrame(data);
  711. }
  712. void sendTimeCodeQuarterFrame(uint32_t data) {
  713. write_packed(0xF108 | ((data & 0x7F) << 16));
  714. }
  715. protected:
  716. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  717. virtual void disconnect();
  718. static void rx_callback(const Transfer_t *transfer);
  719. static void tx_callback(const Transfer_t *transfer);
  720. void rx_data(const Transfer_t *transfer);
  721. void tx_data(const Transfer_t *transfer);
  722. void init();
  723. void write_packed(uint32_t data);
  724. void sysex_byte(uint8_t b);
  725. private:
  726. Pipe_t *rxpipe;
  727. Pipe_t *txpipe;
  728. enum { MAX_PACKET_SIZE = 64 };
  729. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  730. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  731. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  732. uint16_t rx_size;
  733. uint16_t tx_size;
  734. uint32_t rx_queue[RX_QUEUE_SIZE];
  735. bool rx_packet_queued;
  736. uint16_t rx_head;
  737. uint16_t rx_tail;
  738. uint8_t rx_ep;
  739. uint8_t tx_ep;
  740. uint8_t msg_channel;
  741. uint8_t msg_type;
  742. uint8_t msg_data1;
  743. uint8_t msg_data2;
  744. uint8_t msg_sysex[SYSEX_MAX_LEN];
  745. uint8_t msg_sysex_len;
  746. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  747. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  748. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  749. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  750. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  751. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  752. void (*handlePitchChange)(uint8_t ch, int pitch);
  753. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  754. void (*handleRealTimeSystem)(uint8_t rtb);
  755. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  756. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  757. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  758. strbuf_t mystring_bufs[1];
  759. };
  760. class USBSerial: public USBDriver, public Stream {
  761. public:
  762. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  763. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  764. USBSerial(USBHost &host) : txtimer(this) { init(); }
  765. void begin(uint32_t baud, uint32_t format=0);
  766. void end(void);
  767. virtual int available(void);
  768. virtual int peek(void);
  769. virtual int read(void);
  770. virtual int availableForWrite();
  771. virtual size_t write(uint8_t c);
  772. using Print::write;
  773. protected:
  774. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  775. virtual void control(const Transfer_t *transfer);
  776. virtual void disconnect();
  777. virtual void timer_event(USBDriverTimer *whichTimer);
  778. private:
  779. static void rx_callback(const Transfer_t *transfer);
  780. static void tx_callback(const Transfer_t *transfer);
  781. void rx_data(const Transfer_t *transfer);
  782. void tx_data(const Transfer_t *transfer);
  783. void rx_queue_packets(uint32_t head, uint32_t tail);
  784. void init();
  785. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  786. bool init_buffers(uint32_t rsize, uint32_t tsize);
  787. private:
  788. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  789. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  790. strbuf_t mystring_bufs[1];
  791. USBDriverTimer txtimer;
  792. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  793. setup_t setup;
  794. uint8_t setupdata[8];
  795. uint32_t baudrate;
  796. Pipe_t *rxpipe;
  797. Pipe_t *txpipe;
  798. uint8_t *rx1; // location for first incoming packet
  799. uint8_t *rx2; // location for second incoming packet
  800. uint8_t *rxbuf; // receive circular buffer
  801. uint8_t *tx1; // location for first outgoing packet
  802. uint8_t *tx2; // location for second outgoing packet
  803. uint8_t *txbuf;
  804. volatile uint16_t rxhead;// receive head
  805. volatile uint16_t rxtail;// receive tail
  806. volatile uint16_t txhead;
  807. volatile uint16_t txtail;
  808. uint16_t rxsize;// size of receive circular buffer
  809. uint16_t txsize;// size of transmit circular buffer
  810. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  811. volatile uint8_t txstate;
  812. uint8_t pending_control;
  813. bool control_queued;
  814. enum { CDCACM, FTDI, PL2303, CH341 } sertype;
  815. };
  816. class AntPlus: public USBDriver {
  817. public:
  818. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  819. void begin(const uint8_t key=0);
  820. void onStatusChange(void (*function)(int channel, int status)) {
  821. user_onStatusChange = function;
  822. }
  823. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  824. user_onDeviceID = function;
  825. }
  826. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  827. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  828. memset(&hrm, 0, sizeof(hrm));
  829. user_onHeartRateMonitor = f;
  830. }
  831. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  832. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  833. memset(&spdcad, 0, sizeof(spdcad));
  834. user_onSpeedCadence = f;
  835. }
  836. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  837. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  838. memset(&spd, 0, sizeof(spd));
  839. user_onSpeed = f;
  840. }
  841. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  842. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  843. memset(&cad, 0, sizeof(cad));
  844. user_onCadence = f;
  845. }
  846. void setWheelCircumference(float meters) {
  847. wheelCircumference = meters * 1000.0f;
  848. }
  849. protected:
  850. virtual void Task();
  851. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  852. virtual void disconnect();
  853. virtual void timer_event(USBDriverTimer *whichTimer);
  854. private:
  855. static void rx_callback(const Transfer_t *transfer);
  856. static void tx_callback(const Transfer_t *transfer);
  857. void rx_data(const Transfer_t *transfer);
  858. void tx_data(const Transfer_t *transfer);
  859. void init();
  860. size_t write(const void *data, const size_t size);
  861. int read(void *data, const size_t size);
  862. void transmit();
  863. private:
  864. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  865. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  866. strbuf_t mystring_bufs[1];
  867. //USBDriverTimer txtimer;
  868. USBDriverTimer updatetimer;
  869. Pipe_t *rxpipe;
  870. Pipe_t *txpipe;
  871. bool first_update;
  872. uint8_t txbuffer[240];
  873. uint8_t rxpacket[64];
  874. volatile uint16_t txhead;
  875. volatile uint16_t txtail;
  876. volatile bool txready;
  877. volatile uint8_t rxlen;
  878. volatile bool do_polling;
  879. private:
  880. enum _eventi {
  881. EVENTI_MESSAGE = 0,
  882. EVENTI_CHANNEL,
  883. EVENTI_TOTAL
  884. };
  885. enum _profiles {
  886. PROFILE_HRM = 0,
  887. PROFILE_SPDCAD,
  888. PROFILE_POWER,
  889. PROFILE_STRIDE,
  890. PROFILE_SPEED,
  891. PROFILE_CADENCE,
  892. PROFILE_TOTAL
  893. };
  894. typedef struct {
  895. uint8_t channel;
  896. uint8_t RFFreq;
  897. uint8_t networkNumber;
  898. uint8_t stub;
  899. uint8_t searchTimeout;
  900. uint8_t channelType;
  901. uint8_t deviceType;
  902. uint8_t transType;
  903. uint16_t channelPeriod;
  904. uint16_t searchWaveform;
  905. uint32_t deviceNumber; // deviceId
  906. struct {
  907. uint8_t chanIdOnce;
  908. uint8_t keyAccepted;
  909. uint8_t profileValid;
  910. uint8_t channelStatus;
  911. uint8_t channelStatusOld;
  912. } flags;
  913. } TDCONFIG;
  914. struct {
  915. uint8_t initOnce;
  916. uint8_t key; // key index
  917. int iDevice; // index to the antplus we're interested in, if > one found
  918. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  919. } ant;
  920. void (*user_onStatusChange)(int channel, int status);
  921. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  922. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  923. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  924. void (*user_onSpeed)(float speed, float distance);
  925. void (*user_onCadence)(float cadence);
  926. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  927. static const uint8_t *getAntKey(const uint8_t keyIdx);
  928. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  929. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  930. static int msgCheckIntegrity(uint8_t *stream, const int len);
  931. static int msgGetLength(uint8_t *stream);
  932. int handleMessages(uint8_t *buffer, int tBytes);
  933. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  934. void message_channel(const int chan, const int eventId,
  935. const uint8_t *payload, const size_t dataLength);
  936. void message_response(const int chan, const int msgId,
  937. const uint8_t *payload, const size_t dataLength);
  938. void message_event(const int channel, const int msgId,
  939. const uint8_t *payload, const size_t dataLength);
  940. int ResetSystem();
  941. int RequestMessage(const int channel, const int message);
  942. int SetNetworkKey(const int netNumber, const uint8_t *key);
  943. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  944. int SetChannelPeriod(const int channel, const int period);
  945. int SetChannelRFFreq(const int channel, const int freq);
  946. int SetSearchWaveform(const int channel, const int wave);
  947. int OpenChannel(const int channel);
  948. int CloseChannel(const int channel);
  949. int AssignChannel(const int channel, const int channelType, const int network);
  950. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  951. const int transmissionType);
  952. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  953. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  954. int SendBroadcastData(const int channel, const uint8_t *data);
  955. int SendAcknowledgedData(const int channel, const uint8_t *data);
  956. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  957. const int TranType, const uint8_t *data);
  958. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  959. const int TranType, const uint8_t *data);
  960. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  961. const int devType, const int TranType, const uint8_t *data);
  962. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  963. const int tranType, const uint8_t *data, const int nunPackets);
  964. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  965. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  966. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  967. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  968. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  969. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  970. struct {
  971. struct {
  972. uint8_t bpm;
  973. uint8_t sequence;
  974. uint16_t time;
  975. } previous;
  976. } hrm;
  977. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  978. struct {
  979. struct {
  980. uint16_t cadenceTime;
  981. uint16_t cadenceCt;
  982. uint16_t speedTime;
  983. uint16_t speedCt;
  984. } previous;
  985. float distance;
  986. } spdcad;
  987. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  988. /* struct {
  989. struct {
  990. uint8_t sequence;
  991. uint16_t pedalPowerContribution;
  992. uint8_t pedalPower;
  993. uint8_t instantCadence;
  994. uint16_t sumPower;
  995. uint16_t instantPower;
  996. } current;
  997. struct {
  998. uint16_t stub;
  999. } previous;
  1000. } pwr; */
  1001. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1002. /* struct {
  1003. struct {
  1004. uint16_t speed;
  1005. uint16_t cadence;
  1006. uint8_t strides;
  1007. } current;
  1008. struct {
  1009. uint8_t strides;
  1010. uint16_t speed;
  1011. uint16_t cadence;
  1012. } previous;
  1013. } stride; */
  1014. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1015. struct {
  1016. struct {
  1017. uint16_t speedTime;
  1018. uint16_t speedCt;
  1019. } previous;
  1020. float distance;
  1021. } spd;
  1022. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1023. struct {
  1024. struct {
  1025. uint16_t cadenceTime;
  1026. uint16_t cadenceCt;
  1027. } previous;
  1028. } cad;
  1029. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1030. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1031. };
  1032. class MouseController : public USBHIDInput {
  1033. public:
  1034. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  1035. bool available() { return mouseEvent; }
  1036. void mouseDataClear();
  1037. uint8_t getButtons() { return buttons; }
  1038. int getMouseX() { return mouseX; }
  1039. int getMouseY() { return mouseY; }
  1040. int getWheel() { return wheel; }
  1041. int getWheelH() { return wheelH; }
  1042. protected:
  1043. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  1044. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1045. virtual void hid_input_data(uint32_t usage, int32_t value);
  1046. virtual void hid_input_end();
  1047. virtual void disconnect_collection(Device_t *dev);
  1048. private:
  1049. uint8_t collections_claimed = 0;
  1050. volatile bool mouseEvent = false;
  1051. volatile bool hid_input_begin_ = false;
  1052. uint8_t buttons = 0;
  1053. int mouseX = 0;
  1054. int mouseY = 0;
  1055. int wheel = 0;
  1056. int wheelH = 0;
  1057. };
  1058. class JoystickController : public USBHIDInput {
  1059. public:
  1060. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  1061. bool available() { return joystickEvent; }
  1062. void joystickDataClear();
  1063. uint32_t getButtons() { return buttons; }
  1064. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  1065. protected:
  1066. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  1067. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1068. virtual void hid_input_data(uint32_t usage, int32_t value);
  1069. virtual void hid_input_end();
  1070. virtual void disconnect_collection(Device_t *dev);
  1071. private:
  1072. uint8_t collections_claimed = 0;
  1073. bool anychange = false;
  1074. volatile bool joystickEvent = false;
  1075. uint32_t buttons = 0;
  1076. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  1077. };
  1078. class KeyboardHIDExtrasController : public USBHIDInput {
  1079. public:
  1080. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  1081. void clear() { event_ = false;}
  1082. bool available() { return event_; }
  1083. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  1084. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  1085. enum {MAX_KEYS_DOWN=4};
  1086. // uint32_t buttons() { return buttons_; }
  1087. protected:
  1088. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  1089. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1090. virtual void hid_input_data(uint32_t usage, int32_t value);
  1091. virtual void hid_input_end();
  1092. virtual void disconnect_collection(Device_t *dev);
  1093. private:
  1094. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  1095. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  1096. uint32_t topusage_ = 0; // What top report am I processing?
  1097. uint8_t collections_claimed_ = 0;
  1098. volatile bool event_ = false;
  1099. volatile bool hid_input_begin_ = false;
  1100. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  1101. uint8_t count_keys_down_ = 0;
  1102. uint16_t keys_down[MAX_KEYS_DOWN];
  1103. };
  1104. #endif