選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

851 行
31KB

  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. // Device_t holds all the information about a USB device
  129. struct Device_struct {
  130. Pipe_t *control_pipe;
  131. Pipe_t *data_pipes;
  132. Device_t *next;
  133. USBDriver *drivers;
  134. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  135. uint8_t address;
  136. uint8_t hub_address;
  137. uint8_t hub_port;
  138. uint8_t enum_state;
  139. uint8_t bDeviceClass;
  140. uint8_t bDeviceSubClass;
  141. uint8_t bDeviceProtocol;
  142. uint8_t bmAttributes;
  143. uint8_t bMaxPower;
  144. uint16_t idVendor;
  145. uint16_t idProduct;
  146. uint16_t LanguageID;
  147. };
  148. // Pipe_t holes all information about each USB endpoint/pipe
  149. // The first half is an EHCI QH structure for the pipe.
  150. struct Pipe_struct {
  151. // Queue Head (QH), EHCI page 46-50
  152. struct { // must be aligned to 32 byte boundary
  153. volatile uint32_t horizontal_link;
  154. volatile uint32_t capabilities[2];
  155. volatile uint32_t current;
  156. volatile uint32_t next;
  157. volatile uint32_t alt_next;
  158. volatile uint32_t token;
  159. volatile uint32_t buffer[5];
  160. } qh;
  161. Device_t *device;
  162. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  163. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  164. uint8_t start_mask;
  165. uint8_t complete_mask;
  166. Pipe_t *next;
  167. void (*callback_function)(const Transfer_t *);
  168. uint16_t periodic_interval;
  169. uint16_t periodic_offset;
  170. uint32_t unused1;
  171. uint32_t unused2;
  172. uint32_t unused3;
  173. uint32_t unused4;
  174. uint32_t unused5;
  175. uint32_t unused6;
  176. uint32_t unused7;
  177. };
  178. // Transfer_t represents a single transaction on the USB bus.
  179. // The first portion is an EHCI qTD structure. Transfer_t are
  180. // allocated as-needed from a memory pool, loaded with pointers
  181. // to the actual data buffers, linked into a followup list,
  182. // and placed on ECHI Queue Heads. When the ECHI interrupt
  183. // occurs, the followup lists are used to find the Transfer_t
  184. // in memory. Callbacks are made, and then the Transfer_t are
  185. // returned to the memory pool.
  186. struct Transfer_struct {
  187. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  188. struct { // must be aligned to 32 byte boundary
  189. volatile uint32_t next;
  190. volatile uint32_t alt_next;
  191. volatile uint32_t token;
  192. volatile uint32_t buffer[5];
  193. } qtd;
  194. // Linked list of queued, not-yet-completed transfers
  195. Transfer_t *next_followup;
  196. Transfer_t *prev_followup;
  197. Pipe_t *pipe;
  198. // Data to be used by callback function. When a group
  199. // of Transfer_t are created, these fields and the
  200. // interrupt-on-complete bit in the qTD token are only
  201. // set in the last Transfer_t of the list.
  202. void *buffer;
  203. uint32_t length;
  204. setup_t setup;
  205. USBDriver *driver;
  206. };
  207. /************************************************/
  208. /* Main USB EHCI Controller */
  209. /************************************************/
  210. class USBHost {
  211. public:
  212. static void begin();
  213. static void Task();
  214. protected:
  215. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  216. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  217. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  218. void *buf, USBDriver *driver);
  219. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  220. uint32_t len, USBDriver *driver);
  221. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  222. static void disconnect_Device(Device_t *dev);
  223. static void enumeration(const Transfer_t *transfer);
  224. static void driver_ready_for_device(USBDriver *driver);
  225. static void contribute_Devices(Device_t *devices, uint32_t num);
  226. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  227. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  228. static volatile bool enumeration_busy;
  229. private:
  230. static void isr();
  231. static void claim_drivers(Device_t *dev);
  232. static uint32_t assign_address(void);
  233. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  234. static void init_Device_Pipe_Transfer_memory(void);
  235. static Device_t * allocate_Device(void);
  236. static void delete_Pipe(Pipe_t *pipe);
  237. static void free_Device(Device_t *q);
  238. static Pipe_t * allocate_Pipe(void);
  239. static void free_Pipe(Pipe_t *q);
  240. static Transfer_t * allocate_Transfer(void);
  241. static void free_Transfer(Transfer_t *q);
  242. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  243. uint32_t maxlen, uint32_t interval);
  244. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  245. static bool followup_Transfer(Transfer_t *transfer);
  246. static void followup_Error(void);
  247. protected:
  248. #ifdef USBHOST_PRINT_DEBUG
  249. static void print(const Transfer_t *transfer);
  250. static void print(const Transfer_t *first, const Transfer_t *last);
  251. static void print_token(uint32_t token);
  252. static void print(const Pipe_t *pipe);
  253. static void print_driverlist(const char *name, const USBDriver *driver);
  254. static void print_qh_list(const Pipe_t *list);
  255. static void print_hexbytes(const void *ptr, uint32_t len);
  256. static void print(const char *s) { Serial.print(s); }
  257. static void print(int n) { Serial.print(n); }
  258. static void print(unsigned int n) { Serial.print(n); }
  259. static void print(long n) { Serial.print(n); }
  260. static void print(unsigned long n) { Serial.print(n); }
  261. static void println(const char *s) { Serial.println(s); }
  262. static void println(int n) { Serial.println(n); }
  263. static void println(unsigned int n) { Serial.println(n); }
  264. static void println(long n) { Serial.println(n); }
  265. static void println(unsigned long n) { Serial.println(n); }
  266. static void println() { Serial.println(); }
  267. static void print(uint32_t n, uint8_t b) { Serial.print(n, b); }
  268. static void println(uint32_t n, uint8_t b) { Serial.println(n, b); }
  269. static void print(const char *s, int n, uint8_t b = DEC) {
  270. Serial.print(s); Serial.print(n, b); }
  271. static void print(const char *s, unsigned int n, uint8_t b = DEC) {
  272. Serial.print(s); Serial.print(n, b); }
  273. static void print(const char *s, long n, uint8_t b = DEC) {
  274. Serial.print(s); Serial.print(n, b); }
  275. static void print(const char *s, unsigned long n, uint8_t b = DEC) {
  276. Serial.print(s); Serial.print(n, b); }
  277. static void println(const char *s, int n, uint8_t b = DEC) {
  278. Serial.print(s); Serial.println(n, b); }
  279. static void println(const char *s, unsigned int n, uint8_t b = DEC) {
  280. Serial.print(s); Serial.println(n, b); }
  281. static void println(const char *s, long n, uint8_t b = DEC) {
  282. Serial.print(s); Serial.println(n, b); }
  283. static void println(const char *s, unsigned long n, uint8_t b = DEC) {
  284. Serial.print(s); Serial.println(n, b); }
  285. #else
  286. static void print(const Transfer_t *transfer) {}
  287. static void print(const Transfer_t *first, const Transfer_t *last) {}
  288. static void print_token(uint32_t token) {}
  289. static void print(const Pipe_t *pipe) {}
  290. static void print_driverlist(const char *name, const USBDriver *driver) {}
  291. static void print_qh_list(const Pipe_t *list) {}
  292. static void print_hexbytes(const void *ptr, uint32_t len) {}
  293. static void print(const char *s) {}
  294. static void print(int n) {}
  295. static void print(unsigned int n) {}
  296. static void print(long n) {}
  297. static void print(unsigned long n) {}
  298. static void println(const char *s) {}
  299. static void println(int n) {}
  300. static void println(unsigned int n) {}
  301. static void println(long n) {}
  302. static void println(unsigned long n) {}
  303. static void println() {}
  304. static void print(uint32_t n, uint8_t b) {}
  305. static void println(uint32_t n, uint8_t b) {}
  306. static void print(const char *s, int n, uint8_t b = DEC) {}
  307. static void print(const char *s, unsigned int n, uint8_t b = DEC) {}
  308. static void print(const char *s, long n, uint8_t b = DEC) {}
  309. static void print(const char *s, unsigned long n, uint8_t b = DEC) {}
  310. static void println(const char *s, int n, uint8_t b = DEC) {}
  311. static void println(const char *s, unsigned int n, uint8_t b = DEC) {}
  312. static void println(const char *s, long n, uint8_t b = DEC) {}
  313. static void println(const char *s, unsigned long n, uint8_t b = DEC) {}
  314. #endif
  315. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  316. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  317. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  318. s.word2 = wIndex | (wLength << 16);
  319. }
  320. };
  321. /************************************************/
  322. /* USB Device Driver Common Base Class */
  323. /************************************************/
  324. // All USB device drivers inherit from this base class.
  325. class USBDriver : public USBHost {
  326. public:
  327. operator bool() { return (device != nullptr); }
  328. uint16_t idVendor() { return (device != nullptr) ? device->idVendor : 0; }
  329. uint16_t idProduct() { return (device != nullptr) ? device->idProduct : 0; }
  330. // TODO: user-level functions
  331. // check if device is bound/active/online
  332. // query vid, pid
  333. // query string: manufacturer, product, serial number
  334. protected:
  335. USBDriver() : next(NULL), device(NULL) {}
  336. // Check if a driver wishes to claim a device or interface or group
  337. // of interfaces within a device. When this function returns true,
  338. // the driver is considered bound or loaded for that device. When
  339. // new devices are detected, enumeration.cpp calls this function on
  340. // all unbound driver objects, to give them an opportunity to bind
  341. // to the new device.
  342. // device has its vid&pid, class/subclass fields initialized
  343. // type is 0 for device level, 1 for interface level, 2 for IAD
  344. // descriptors points to the specific descriptor data
  345. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  346. // When an unknown (not chapter 9) control transfer completes, this
  347. // function is called for all drivers bound to the device. Return
  348. // true means this driver originated this control transfer, so no
  349. // more drivers need to be offered an opportunity to process it.
  350. // This function is optional, only needed if the driver uses control
  351. // transfers and wishes to be notified when they complete.
  352. virtual void control(const Transfer_t *transfer) { }
  353. // When any of the USBDriverTimer objects a driver creates generates
  354. // a timer event, this function is called.
  355. virtual void timer_event(USBDriverTimer *whichTimer) { }
  356. // When the user calls USBHost::Task, this Task function for all
  357. // active drivers is called, so they may update state and/or call
  358. // any attached user callback functions.
  359. virtual void Task() { }
  360. // When a device disconnects from the USB, this function is called.
  361. // The driver must free all resources it allocated and update any
  362. // internal state necessary to deal with the possibility of user
  363. // code continuing to call its API. However, pipes and transfers
  364. // are the handled by lower layers, so device drivers do not free
  365. // pipes they created or cancel transfers they had in progress.
  366. virtual void disconnect();
  367. // Drivers are managed by this single-linked list. All inactive
  368. // (not bound to any device) drivers are linked from
  369. // available_drivers in enumeration.cpp. When bound to a device,
  370. // drivers are linked from that Device_t drivers list.
  371. USBDriver *next;
  372. // The device this object instance is bound to. In words, this
  373. // is the specific device this driver is using. When not bound
  374. // to any device, this must be NULL. Drivers may set this to
  375. // any non-NULL value if they are in a state where they do not
  376. // wish to claim any device or interface (eg, if getting data
  377. // from the HID parser).
  378. Device_t *device;
  379. friend class USBHost;
  380. };
  381. // Device drivers may create these timer objects to schedule a timer call
  382. class USBDriverTimer {
  383. public:
  384. USBDriverTimer() { }
  385. USBDriverTimer(USBDriver *d) : driver(d) { }
  386. void init(USBDriver *d) { driver = d; };
  387. void start(uint32_t microseconds);
  388. void *pointer;
  389. uint32_t integer;
  390. uint32_t started_micros; // testing only
  391. private:
  392. USBDriver *driver;
  393. uint32_t usec;
  394. USBDriverTimer *next;
  395. USBDriverTimer *prev;
  396. friend class USBHost;
  397. };
  398. // Device drivers may inherit from this base class, if they wish to receive
  399. // HID input data fully decoded by the USBHIDParser driver
  400. class USBHIDInput {
  401. public:
  402. operator bool() { return (mydevice != nullptr); }
  403. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  404. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  405. private:
  406. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  407. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  408. virtual void hid_input_data(uint32_t usage, int32_t value);
  409. virtual void hid_input_end();
  410. virtual void disconnect_collection(Device_t *dev);
  411. void add_to_list();
  412. USBHIDInput *next;
  413. friend class USBHIDParser;
  414. protected:
  415. Device_t *mydevice = NULL;
  416. };
  417. /************************************************/
  418. /* USB Device Drivers */
  419. /************************************************/
  420. class USBHub : public USBDriver {
  421. public:
  422. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  423. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  424. // Hubs with more more than 7 ports are built from two tiers of hubs
  425. // using 4 or 7 port hub chips. While the USB spec seems to allow
  426. // hubs to have up to 255 ports, in practice all hub chips on the
  427. // market are only 2, 3, 4 or 7 ports.
  428. enum { MAXPORTS = 7 };
  429. typedef uint8_t portbitmask_t;
  430. enum {
  431. PORT_OFF = 0,
  432. PORT_DISCONNECT = 1,
  433. PORT_DEBOUNCE1 = 2,
  434. PORT_DEBOUNCE2 = 3,
  435. PORT_DEBOUNCE3 = 4,
  436. PORT_DEBOUNCE4 = 5,
  437. PORT_DEBOUNCE5 = 6,
  438. PORT_RESET = 7,
  439. PORT_RECOVERY = 8,
  440. PORT_ACTIVE = 9
  441. };
  442. protected:
  443. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  444. virtual void control(const Transfer_t *transfer);
  445. virtual void timer_event(USBDriverTimer *whichTimer);
  446. virtual void disconnect();
  447. void init();
  448. bool can_send_control_now();
  449. void send_poweron(uint32_t port);
  450. void send_getstatus(uint32_t port);
  451. void send_clearstatus_connect(uint32_t port);
  452. void send_clearstatus_enable(uint32_t port);
  453. void send_clearstatus_suspend(uint32_t port);
  454. void send_clearstatus_overcurrent(uint32_t port);
  455. void send_clearstatus_reset(uint32_t port);
  456. void send_setreset(uint32_t port);
  457. static void callback(const Transfer_t *transfer);
  458. void status_change(const Transfer_t *transfer);
  459. void new_port_status(uint32_t port, uint32_t status);
  460. void start_debounce_timer(uint32_t port);
  461. void stop_debounce_timer(uint32_t port);
  462. private:
  463. Device_t mydevices[MAXPORTS];
  464. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  465. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  466. USBDriverTimer debouncetimer;
  467. USBDriverTimer resettimer;
  468. setup_t setup;
  469. Pipe_t *changepipe;
  470. Device_t *devicelist[MAXPORTS];
  471. uint32_t changebits;
  472. uint32_t statusbits;
  473. uint8_t hub_desc[16];
  474. uint8_t endpoint;
  475. uint8_t interval;
  476. uint8_t numports;
  477. uint8_t characteristics;
  478. uint8_t powertime;
  479. uint8_t sending_control_transfer;
  480. uint8_t port_doing_reset;
  481. uint8_t port_doing_reset_speed;
  482. uint8_t portstate[MAXPORTS];
  483. portbitmask_t send_pending_poweron;
  484. portbitmask_t send_pending_getstatus;
  485. portbitmask_t send_pending_clearstatus_connect;
  486. portbitmask_t send_pending_clearstatus_enable;
  487. portbitmask_t send_pending_clearstatus_suspend;
  488. portbitmask_t send_pending_clearstatus_overcurrent;
  489. portbitmask_t send_pending_clearstatus_reset;
  490. portbitmask_t send_pending_setreset;
  491. portbitmask_t debounce_in_use;
  492. static volatile bool reset_busy;
  493. };
  494. class USBHIDParser : public USBDriver {
  495. public:
  496. USBHIDParser(USBHost &host) { init(); }
  497. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  498. protected:
  499. enum { TOPUSAGE_LIST_LEN = 4 };
  500. enum { USAGE_LIST_LEN = 24 };
  501. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  502. virtual void control(const Transfer_t *transfer);
  503. virtual void disconnect();
  504. static void in_callback(const Transfer_t *transfer);
  505. static void out_callback(const Transfer_t *transfer);
  506. void in_data(const Transfer_t *transfer);
  507. void out_data(const Transfer_t *transfer);
  508. bool check_if_using_report_id();
  509. void parse();
  510. USBHIDInput * find_driver(uint32_t topusage);
  511. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  512. void init();
  513. private:
  514. Pipe_t *in_pipe;
  515. Pipe_t *out_pipe;
  516. static USBHIDInput *available_hid_drivers_list;
  517. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  518. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  519. uint16_t in_size;
  520. uint16_t out_size;
  521. setup_t setup;
  522. uint8_t descriptor[512];
  523. uint8_t report[64];
  524. uint16_t descsize;
  525. bool use_report_id;
  526. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  527. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  528. };
  529. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  530. public:
  531. typedef union {
  532. struct {
  533. uint8_t numLock : 1;
  534. uint8_t capsLock : 1;
  535. uint8_t scrollLock : 1;
  536. uint8_t compose : 1;
  537. uint8_t kana : 1;
  538. uint8_t reserved : 3;
  539. };
  540. uint8_t byte;
  541. } KBDLeds_t;
  542. public:
  543. KeyboardController(USBHost &host) { init(); }
  544. KeyboardController(USBHost *host) { init(); }
  545. int available();
  546. int read();
  547. uint16_t getKey() { return keyCode; }
  548. uint8_t getModifiers() { return modifiers; }
  549. uint8_t getOemKey() { return keyOEM; }
  550. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  551. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  552. void LEDS(uint8_t leds);
  553. uint8_t LEDS() {return leds_.byte;}
  554. void updateLEDS(void);
  555. bool numLock() {return leds_.numLock;}
  556. bool capsLock() {return leds_.capsLock;}
  557. bool scrollLock() {return leds_.scrollLock;}
  558. void numLock(bool f);
  559. void capsLock(bool f);
  560. void scrollLock(bool f);
  561. protected:
  562. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  563. virtual void control(const Transfer_t *transfer);
  564. virtual void disconnect();
  565. static void callback(const Transfer_t *transfer);
  566. void new_data(const Transfer_t *transfer);
  567. void init();
  568. private:
  569. void update();
  570. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  571. void key_press(uint32_t mod, uint32_t key);
  572. void key_release(uint32_t mod, uint32_t key);
  573. void (*keyPressedFunction)(int unicode);
  574. void (*keyReleasedFunction)(int unicode);
  575. Pipe_t *datapipe;
  576. setup_t setup;
  577. uint8_t report[8];
  578. uint16_t keyCode;
  579. uint8_t modifiers;
  580. uint8_t keyOEM;
  581. uint8_t prev_report[8];
  582. KBDLeds_t leds_ = {0};
  583. bool update_leds_ = false;
  584. bool processing_new_data_ = false;
  585. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  586. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  587. };
  588. class MIDIDevice : public USBDriver {
  589. public:
  590. enum { SYSEX_MAX_LEN = 60 };
  591. MIDIDevice(USBHost &host) { init(); }
  592. MIDIDevice(USBHost *host) { init(); }
  593. bool read(uint8_t channel=0, uint8_t cable=0);
  594. uint8_t getType(void) {
  595. return msg_type;
  596. };
  597. uint8_t getChannel(void) {
  598. return msg_channel;
  599. };
  600. uint8_t getData1(void) {
  601. return msg_data1;
  602. };
  603. uint8_t getData2(void) {
  604. return msg_data2;
  605. };
  606. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  607. handleNoteOff = f;
  608. };
  609. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  610. handleNoteOn = f;
  611. };
  612. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  613. handleVelocityChange = f;
  614. };
  615. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  616. handleControlChange = f;
  617. };
  618. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  619. handleProgramChange = f;
  620. };
  621. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  622. handleAfterTouch = f;
  623. };
  624. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  625. handlePitchChange = f;
  626. };
  627. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  628. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  629. }
  630. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  631. handleRealTimeSystem = f;
  632. };
  633. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  634. handleTimeCodeQuarterFrame = f;
  635. };
  636. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  637. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  638. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  639. }
  640. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  641. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  642. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  643. }
  644. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  645. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  646. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  647. }
  648. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  649. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  650. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  651. }
  652. void sendProgramChange(uint32_t program, uint32_t channel) {
  653. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  654. | ((program & 0x7F) << 16));
  655. }
  656. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  657. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  658. | ((pressure & 0x7F) << 16));
  659. }
  660. void sendPitchBend(uint32_t value, uint32_t channel) {
  661. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  662. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  663. }
  664. void sendSysEx(uint32_t length, const void *data);
  665. void sendRealTime(uint32_t type) {
  666. switch (type) {
  667. case 0xF8: // Clock
  668. case 0xFA: // Start
  669. case 0xFC: // Stop
  670. case 0xFB: // Continue
  671. case 0xFE: // ActiveSensing
  672. case 0xFF: // SystemReset
  673. write_packed((type << 8) | 0x0F);
  674. break;
  675. default: // Invalid Real Time marker
  676. break;
  677. }
  678. }
  679. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  680. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  681. sendTimeCodeQuarterFrame(data);
  682. }
  683. void sendTimeCodeQuarterFrame(uint32_t data) {
  684. write_packed(0xF108 | ((data & 0x7F) << 16));
  685. }
  686. protected:
  687. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  688. virtual void disconnect();
  689. static void rx_callback(const Transfer_t *transfer);
  690. static void tx_callback(const Transfer_t *transfer);
  691. void rx_data(const Transfer_t *transfer);
  692. void tx_data(const Transfer_t *transfer);
  693. void init();
  694. void write_packed(uint32_t data);
  695. void sysex_byte(uint8_t b);
  696. private:
  697. Pipe_t *rxpipe;
  698. Pipe_t *txpipe;
  699. enum { MAX_PACKET_SIZE = 64 };
  700. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  701. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  702. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  703. uint16_t rx_size;
  704. uint16_t tx_size;
  705. uint32_t rx_queue[RX_QUEUE_SIZE];
  706. bool rx_packet_queued;
  707. uint16_t rx_head;
  708. uint16_t rx_tail;
  709. uint8_t rx_ep;
  710. uint8_t tx_ep;
  711. uint8_t msg_channel;
  712. uint8_t msg_type;
  713. uint8_t msg_data1;
  714. uint8_t msg_data2;
  715. uint8_t msg_sysex[SYSEX_MAX_LEN];
  716. uint8_t msg_sysex_len;
  717. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  718. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  719. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  720. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  721. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  722. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  723. void (*handlePitchChange)(uint8_t ch, int pitch);
  724. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  725. void (*handleRealTimeSystem)(uint8_t rtb);
  726. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  727. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  728. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  729. };
  730. class MouseController : public USBHIDInput {
  731. public:
  732. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  733. bool available() { return mouseEvent; }
  734. void mouseDataClear();
  735. uint8_t getButtons() { return buttons; }
  736. int getMouseX() { return mouseX; }
  737. int getMouseY() { return mouseY; }
  738. int getWheel() { return wheel; }
  739. int getWheelH() { return wheelH; }
  740. protected:
  741. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  742. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  743. virtual void hid_input_data(uint32_t usage, int32_t value);
  744. virtual void hid_input_end();
  745. virtual void disconnect_collection(Device_t *dev);
  746. private:
  747. uint8_t collections_claimed = 0;
  748. volatile bool mouseEvent = false;
  749. volatile bool hid_input_begin_ = false;
  750. uint8_t buttons = 0;
  751. int mouseX = 0;
  752. int mouseY = 0;
  753. int wheel = 0;
  754. int wheelH = 0;
  755. };
  756. class JoystickController : public USBHIDInput {
  757. public:
  758. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  759. bool available() { return joystickEvent; }
  760. void joystickDataClear();
  761. uint32_t getButtons() { return buttons; }
  762. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  763. protected:
  764. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  765. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  766. virtual void hid_input_data(uint32_t usage, int32_t value);
  767. virtual void hid_input_end();
  768. virtual void disconnect_collection(Device_t *dev);
  769. private:
  770. uint8_t collections_claimed = 0;
  771. bool anychange = false;
  772. volatile bool joystickEvent = false;
  773. uint32_t buttons = 0;
  774. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  775. };
  776. class KeyboardHIDExtrasController : public USBHIDInput {
  777. public:
  778. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  779. void clear() { event_ = false;}
  780. bool available() { return event_; }
  781. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  782. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  783. enum {MAX_KEYS_DOWN=4};
  784. // uint32_t buttons() { return buttons_; }
  785. protected:
  786. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  787. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  788. virtual void hid_input_data(uint32_t usage, int32_t value);
  789. virtual void hid_input_end();
  790. virtual void disconnect_collection(Device_t *dev);
  791. private:
  792. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  793. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  794. uint32_t topusage_ = 0; // What top report am I processing?
  795. uint8_t collections_claimed_ = 0;
  796. volatile bool event_ = false;
  797. volatile bool hid_input_begin_ = false;
  798. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  799. uint8_t count_keys_down_ = 0;
  800. uint16_t keys_down[MAX_KEYS_DOWN];
  801. };
  802. #endif