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

796 行
29KB

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