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.

1086 rindas
41KB

  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. protected:
  827. virtual void Task();
  828. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  829. virtual void disconnect();
  830. virtual void timer_event(USBDriverTimer *whichTimer);
  831. private:
  832. static void rx_callback(const Transfer_t *transfer);
  833. static void tx_callback(const Transfer_t *transfer);
  834. void rx_data(const Transfer_t *transfer);
  835. void tx_data(const Transfer_t *transfer);
  836. void init();
  837. size_t write(const void *data, const size_t size);
  838. int read(void *data, const size_t size);
  839. void transmit();
  840. private:
  841. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  842. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  843. strbuf_t mystring_bufs[1];
  844. //USBDriverTimer txtimer;
  845. USBDriverTimer updatetimer;
  846. Pipe_t *rxpipe;
  847. Pipe_t *txpipe;
  848. bool first_update;
  849. uint8_t txbuffer[240];
  850. uint8_t rxpacket[64];
  851. volatile uint16_t txhead;
  852. volatile uint16_t txtail;
  853. volatile bool txready;
  854. volatile uint8_t rxlen;
  855. volatile bool do_polling;
  856. private:
  857. enum _eventi {
  858. EVENTI_MESSAGE = 0,
  859. EVENTI_CHANNEL,
  860. EVENTI_TOTAL
  861. };
  862. enum _profiles {
  863. PROFILE_HRM = 0,
  864. PROFILE_SPDCAD,
  865. PROFILE_POWER,
  866. PROFILE_STRIDE,
  867. PROFILE_SPEED,
  868. PROFILE_CADENCE,
  869. PROFILE_TOTAL
  870. };
  871. typedef struct {
  872. uint8_t channel;
  873. uint8_t RFFreq;
  874. uint8_t networkNumber;
  875. uint8_t stub;
  876. uint8_t searchTimeout;
  877. uint8_t channelType;
  878. uint8_t deviceType;
  879. uint8_t transType;
  880. uint16_t channelPeriod;
  881. uint16_t searchWaveform;
  882. uint32_t deviceNumber; // deviceId
  883. struct {
  884. uint8_t chanIdOnce;
  885. uint8_t keyAccepted;
  886. uint8_t profileValid;
  887. uint8_t channelStatus;
  888. uint8_t channelStatusOld;
  889. } flags;
  890. } TDCONFIG;
  891. typedef struct {
  892. uint8_t initOnce;
  893. uint8_t key; // key index
  894. int iDevice; // index to the antplus we're interested in, if > one found
  895. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  896. } TLIBANTPLUS;
  897. TLIBANTPLUS ant;
  898. int (*callbackFunc)(uint32_t msg, intptr_t *value1, uint32_t value2);
  899. void (*user_onStatusChange)(int channel, int status);
  900. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  901. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  902. static const uint8_t *getAntKey(const uint8_t keyIdx);
  903. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  904. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  905. static int msgCheckIntegrity(uint8_t *stream, const int len);
  906. static int msgGetLength(uint8_t *stream);
  907. int handleMessages(uint8_t *buffer, int tBytes);
  908. void setCallbackFunc(int (*func)(uint32_t msg, intptr_t *value1, uint32_t value2));
  909. void sendMessage(uint32_t msg, intptr_t *value1, uint32_t value2);
  910. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  911. void message_channel(const int chan, const int eventId,
  912. const uint8_t *payload, const size_t dataLength);
  913. void message_response(const int chan, const int msgId,
  914. const uint8_t *payload, const size_t dataLength);
  915. void message_event(const int channel, const int msgId,
  916. const uint8_t *payload, const size_t dataLength);
  917. int ResetSystem();
  918. int RequestMessage(const int channel, const int message);
  919. int SetNetworkKey(const int netNumber, const uint8_t *key);
  920. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  921. int SetChannelPeriod(const int channel, const int period);
  922. int SetChannelRFFreq(const int channel, const int freq);
  923. int SetSearchWaveform(const int channel, const int wave);
  924. int OpenChannel(const int channel);
  925. int CloseChannel(const int channel);
  926. int AssignChannel(const int channel, const int channelType, const int network);
  927. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  928. const int transmissionType);
  929. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  930. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  931. int SendBroadcastData(const int channel, const uint8_t *data);
  932. int SendAcknowledgedData(const int channel, const uint8_t *data);
  933. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  934. const int TranType, const uint8_t *data);
  935. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  936. const int TranType, const uint8_t *data);
  937. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  938. const int devType, const int TranType, const uint8_t *data);
  939. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  940. const int tranType, const uint8_t *data, const int nunPackets);
  941. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  942. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  943. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  944. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  945. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  946. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  947. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  948. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  949. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  950. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  951. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  952. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  953. };
  954. class MouseController : public USBHIDInput {
  955. public:
  956. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  957. bool available() { return mouseEvent; }
  958. void mouseDataClear();
  959. uint8_t getButtons() { return buttons; }
  960. int getMouseX() { return mouseX; }
  961. int getMouseY() { return mouseY; }
  962. int getWheel() { return wheel; }
  963. int getWheelH() { return wheelH; }
  964. protected:
  965. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  966. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  967. virtual void hid_input_data(uint32_t usage, int32_t value);
  968. virtual void hid_input_end();
  969. virtual void disconnect_collection(Device_t *dev);
  970. private:
  971. uint8_t collections_claimed = 0;
  972. volatile bool mouseEvent = false;
  973. volatile bool hid_input_begin_ = false;
  974. uint8_t buttons = 0;
  975. int mouseX = 0;
  976. int mouseY = 0;
  977. int wheel = 0;
  978. int wheelH = 0;
  979. };
  980. class JoystickController : public USBHIDInput {
  981. public:
  982. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  983. bool available() { return joystickEvent; }
  984. void joystickDataClear();
  985. uint32_t getButtons() { return buttons; }
  986. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  987. protected:
  988. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  989. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  990. virtual void hid_input_data(uint32_t usage, int32_t value);
  991. virtual void hid_input_end();
  992. virtual void disconnect_collection(Device_t *dev);
  993. private:
  994. uint8_t collections_claimed = 0;
  995. bool anychange = false;
  996. volatile bool joystickEvent = false;
  997. uint32_t buttons = 0;
  998. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  999. };
  1000. class KeyboardHIDExtrasController : public USBHIDInput {
  1001. public:
  1002. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  1003. void clear() { event_ = false;}
  1004. bool available() { return event_; }
  1005. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  1006. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  1007. enum {MAX_KEYS_DOWN=4};
  1008. // uint32_t buttons() { return buttons_; }
  1009. protected:
  1010. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  1011. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1012. virtual void hid_input_data(uint32_t usage, int32_t value);
  1013. virtual void hid_input_end();
  1014. virtual void disconnect_collection(Device_t *dev);
  1015. private:
  1016. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  1017. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  1018. uint32_t topusage_ = 0; // What top report am I processing?
  1019. uint8_t collections_claimed_ = 0;
  1020. volatile bool event_ = false;
  1021. volatile bool hid_input_begin_ = false;
  1022. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  1023. uint8_t count_keys_down_ = 0;
  1024. uint16_t keys_down[MAX_KEYS_DOWN];
  1025. };
  1026. #endif