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

745 行
27KB

  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. // TODO: user-level functions
  303. // check if device is bound/active/online
  304. // query vid, pid
  305. // query string: manufacturer, product, serial number
  306. protected:
  307. USBDriver() : next(NULL), device(NULL) {}
  308. // Check if a driver wishes to claim a device or interface or group
  309. // of interfaces within a device. When this function returns true,
  310. // the driver is considered bound or loaded for that device. When
  311. // new devices are detected, enumeration.cpp calls this function on
  312. // all unbound driver objects, to give them an opportunity to bind
  313. // to the new device.
  314. // device has its vid&pid, class/subclass fields initialized
  315. // type is 0 for device level, 1 for interface level, 2 for IAD
  316. // descriptors points to the specific descriptor data
  317. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  318. // When an unknown (not chapter 9) control transfer completes, this
  319. // function is called for all drivers bound to the device. Return
  320. // true means this driver originated this control transfer, so no
  321. // more drivers need to be offered an opportunity to process it.
  322. // This function is optional, only needed if the driver uses control
  323. // transfers and wishes to be notified when they complete.
  324. virtual void control(const Transfer_t *transfer) { }
  325. // When any of the USBDriverTimer objects a driver creates generates
  326. // a timer event, this function is called.
  327. virtual void timer_event(USBDriverTimer *whichTimer) { }
  328. // When the user calls USBHost::Task, this Task function for all
  329. // active drivers is called, so they may update state and/or call
  330. // any attached user callback functions.
  331. virtual void Task() { }
  332. // When a device disconnects from the USB, this function is called.
  333. // The driver must free all resources it allocated and update any
  334. // internal state necessary to deal with the possibility of user
  335. // code continuing to call its API. However, pipes and transfers
  336. // are the handled by lower layers, so device drivers do not free
  337. // pipes they created or cancel transfers they had in progress.
  338. virtual void disconnect();
  339. // Drivers are managed by this single-linked list. All inactive
  340. // (not bound to any device) drivers are linked from
  341. // available_drivers in enumeration.cpp. When bound to a device,
  342. // drivers are linked from that Device_t drivers list.
  343. USBDriver *next;
  344. // The device this object instance is bound to. In words, this
  345. // is the specific device this driver is using. When not bound
  346. // to any device, this must be NULL.
  347. Device_t *device;
  348. friend class USBHost;
  349. };
  350. // Device drivers may create these timer objects to schedule a timer call
  351. class USBDriverTimer {
  352. public:
  353. USBDriverTimer() { }
  354. USBDriverTimer(USBDriver *d) : driver(d) { }
  355. void init(USBDriver *d) { driver = d; };
  356. void start(uint32_t microseconds);
  357. void *pointer;
  358. uint32_t integer;
  359. uint32_t started_micros; // testing only
  360. private:
  361. USBDriver *driver;
  362. uint32_t usec;
  363. USBDriverTimer *next;
  364. USBDriverTimer *prev;
  365. friend class USBHost;
  366. };
  367. // Device drivers may inherit from this base class, if they wish to receive
  368. // HID input data fully decoded by the USBHIDParser driver
  369. class USBHIDInput {
  370. public:
  371. USBHIDInput();
  372. private:
  373. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  374. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int min, int max);
  375. virtual void hid_input_data(uint32_t usage, int32_t value);
  376. virtual void hid_input_end();
  377. virtual void disconnect_collection(Device_t *dev);
  378. USBHIDInput *next;
  379. static USBHIDInput *list;
  380. friend class USBHIDParser;
  381. };
  382. /************************************************/
  383. /* USB Device Drivers */
  384. /************************************************/
  385. class USBHub : public USBDriver {
  386. public:
  387. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  388. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  389. // Hubs with more more than 7 ports are built from two tiers of hubs
  390. // using 4 or 7 port hub chips. While the USB spec seems to allow
  391. // hubs to have up to 255 ports, in practice all hub chips on the
  392. // market are only 2, 3, 4 or 7 ports.
  393. enum { MAXPORTS = 7 };
  394. typedef uint8_t portbitmask_t;
  395. enum {
  396. PORT_OFF = 0,
  397. PORT_DISCONNECT = 1,
  398. PORT_DEBOUNCE1 = 2,
  399. PORT_DEBOUNCE2 = 3,
  400. PORT_DEBOUNCE3 = 4,
  401. PORT_DEBOUNCE4 = 5,
  402. PORT_DEBOUNCE5 = 6,
  403. PORT_RESET = 7,
  404. PORT_RECOVERY = 8,
  405. PORT_ACTIVE = 9
  406. };
  407. protected:
  408. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  409. virtual void control(const Transfer_t *transfer);
  410. virtual void timer_event(USBDriverTimer *whichTimer);
  411. virtual void disconnect();
  412. void init();
  413. bool can_send_control_now();
  414. void send_poweron(uint32_t port);
  415. void send_getstatus(uint32_t port);
  416. void send_clearstatus_connect(uint32_t port);
  417. void send_clearstatus_enable(uint32_t port);
  418. void send_clearstatus_suspend(uint32_t port);
  419. void send_clearstatus_overcurrent(uint32_t port);
  420. void send_clearstatus_reset(uint32_t port);
  421. void send_setreset(uint32_t port);
  422. static void callback(const Transfer_t *transfer);
  423. void status_change(const Transfer_t *transfer);
  424. void new_port_status(uint32_t port, uint32_t status);
  425. void start_debounce_timer(uint32_t port);
  426. void stop_debounce_timer(uint32_t port);
  427. private:
  428. Device_t mydevices[MAXPORTS];
  429. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  430. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  431. USBDriverTimer debouncetimer;
  432. USBDriverTimer resettimer;
  433. setup_t setup;
  434. Pipe_t *changepipe;
  435. Device_t *devicelist[MAXPORTS];
  436. uint32_t changebits;
  437. uint32_t statusbits;
  438. uint8_t hub_desc[16];
  439. uint8_t endpoint;
  440. uint8_t interval;
  441. uint8_t numports;
  442. uint8_t characteristics;
  443. uint8_t powertime;
  444. uint8_t sending_control_transfer;
  445. uint8_t port_doing_reset;
  446. uint8_t port_doing_reset_speed;
  447. uint8_t portstate[MAXPORTS];
  448. portbitmask_t send_pending_poweron;
  449. portbitmask_t send_pending_getstatus;
  450. portbitmask_t send_pending_clearstatus_connect;
  451. portbitmask_t send_pending_clearstatus_enable;
  452. portbitmask_t send_pending_clearstatus_suspend;
  453. portbitmask_t send_pending_clearstatus_overcurrent;
  454. portbitmask_t send_pending_clearstatus_reset;
  455. portbitmask_t send_pending_setreset;
  456. portbitmask_t debounce_in_use;
  457. static volatile bool reset_busy;
  458. };
  459. class USBHIDParser : public USBDriver {
  460. public:
  461. USBHIDParser(USBHost &host) { init(); }
  462. void driver_ready_for_hid_collection(USBHIDInput *driver);
  463. protected:
  464. enum { TOPUSAGE_LIST_LEN = 4 };
  465. enum { USAGE_LIST_LEN = 12 };
  466. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  467. virtual void control(const Transfer_t *transfer);
  468. virtual void disconnect();
  469. static void in_callback(const Transfer_t *transfer);
  470. static void out_callback(const Transfer_t *transfer);
  471. void in_data(const Transfer_t *transfer);
  472. void out_data(const Transfer_t *transfer);
  473. bool check_if_using_report_id();
  474. void parse();
  475. USBHIDInput * find_driver(uint32_t topusage);
  476. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  477. void init();
  478. private:
  479. Pipe_t *in_pipe;
  480. Pipe_t *out_pipe;
  481. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  482. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  483. uint16_t in_size;
  484. uint16_t out_size;
  485. setup_t setup;
  486. uint8_t descriptor[256];
  487. uint8_t report[64];
  488. uint16_t descsize;
  489. bool use_report_id;
  490. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  491. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  492. };
  493. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  494. public:
  495. KeyboardController(USBHost &host) { init(); }
  496. KeyboardController(USBHost *host) { init(); }
  497. int available();
  498. int read();
  499. uint16_t getKey() { return keyCode; }
  500. uint8_t getModifiers() { return modifiers; }
  501. uint8_t getOemKey() { return keyOEM; }
  502. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  503. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  504. protected:
  505. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  506. virtual void control(const Transfer_t *transfer);
  507. virtual void disconnect();
  508. static void callback(const Transfer_t *transfer);
  509. void new_data(const Transfer_t *transfer);
  510. void init();
  511. private:
  512. void update();
  513. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  514. void key_press(uint32_t mod, uint32_t key);
  515. void key_release(uint32_t mod, uint32_t key);
  516. void (*keyPressedFunction)(int unicode);
  517. void (*keyReleasedFunction)(int unicode);
  518. Pipe_t *datapipe;
  519. setup_t setup;
  520. uint8_t report[8];
  521. uint16_t keyCode;
  522. uint8_t modifiers;
  523. uint8_t keyOEM;
  524. uint8_t prev_report[8];
  525. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  526. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  527. };
  528. class MIDIDevice : public USBDriver {
  529. public:
  530. enum { SYSEX_MAX_LEN = 60 };
  531. MIDIDevice(USBHost &host) { init(); }
  532. MIDIDevice(USBHost *host) { init(); }
  533. bool read(uint8_t channel=0, uint8_t cable=0);
  534. uint8_t getType(void) {
  535. return msg_type;
  536. };
  537. uint8_t getChannel(void) {
  538. return msg_channel;
  539. };
  540. uint8_t getData1(void) {
  541. return msg_data1;
  542. };
  543. uint8_t getData2(void) {
  544. return msg_data2;
  545. };
  546. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  547. handleNoteOff = f;
  548. };
  549. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  550. handleNoteOn = f;
  551. };
  552. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  553. handleVelocityChange = f;
  554. };
  555. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  556. handleControlChange = f;
  557. };
  558. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  559. handleProgramChange = f;
  560. };
  561. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  562. handleAfterTouch = f;
  563. };
  564. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  565. handlePitchChange = f;
  566. };
  567. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  568. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  569. }
  570. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  571. handleRealTimeSystem = f;
  572. };
  573. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  574. handleTimeCodeQuarterFrame = f;
  575. };
  576. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  577. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  578. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  579. }
  580. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  581. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  582. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  583. }
  584. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  585. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  586. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  587. }
  588. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  589. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  590. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  591. }
  592. void sendProgramChange(uint32_t program, uint32_t channel) {
  593. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  594. | ((program & 0x7F) << 16));
  595. }
  596. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  597. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  598. | ((pressure & 0x7F) << 16));
  599. }
  600. void sendPitchBend(uint32_t value, uint32_t channel) {
  601. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  602. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  603. }
  604. void sendSysEx(uint32_t length, const void *data);
  605. void sendRealTime(uint32_t type) {
  606. switch (type) {
  607. case 0xF8: // Clock
  608. case 0xFA: // Start
  609. case 0xFC: // Stop
  610. case 0xFB: // Continue
  611. case 0xFE: // ActiveSensing
  612. case 0xFF: // SystemReset
  613. write_packed((type << 8) | 0x0F);
  614. break;
  615. default: // Invalid Real Time marker
  616. break;
  617. }
  618. }
  619. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  620. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  621. sendTimeCodeQuarterFrame(data);
  622. }
  623. void sendTimeCodeQuarterFrame(uint32_t data) {
  624. write_packed(0xF108 | ((data & 0x7F) << 16));
  625. }
  626. protected:
  627. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  628. virtual void disconnect();
  629. static void rx_callback(const Transfer_t *transfer);
  630. static void tx_callback(const Transfer_t *transfer);
  631. void rx_data(const Transfer_t *transfer);
  632. void tx_data(const Transfer_t *transfer);
  633. void init();
  634. void write_packed(uint32_t data);
  635. void sysex_byte(uint8_t b);
  636. private:
  637. Pipe_t *rxpipe;
  638. Pipe_t *txpipe;
  639. enum { MAX_PACKET_SIZE = 64 };
  640. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  641. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  642. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  643. uint16_t rx_size;
  644. uint16_t tx_size;
  645. uint32_t rx_queue[RX_QUEUE_SIZE];
  646. bool rx_packet_queued;
  647. uint16_t rx_head;
  648. uint16_t rx_tail;
  649. uint8_t rx_ep;
  650. uint8_t tx_ep;
  651. uint8_t msg_channel;
  652. uint8_t msg_type;
  653. uint8_t msg_data1;
  654. uint8_t msg_data2;
  655. uint8_t msg_sysex[SYSEX_MAX_LEN];
  656. uint8_t msg_sysex_len;
  657. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  658. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  659. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  660. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  661. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  662. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  663. void (*handlePitchChange)(uint8_t ch, int pitch);
  664. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  665. void (*handleRealTimeSystem)(uint8_t rtb);
  666. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  667. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  668. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  669. };
  670. class MouseController : public USBDriver {
  671. public:
  672. MouseController(USBHost &host) { init(); }
  673. MouseController(USBHost *host) { init(); }
  674. bool available() { return mouseEvent; }
  675. void mouseDataClear();
  676. uint8_t getButtons() { return buttons; }
  677. int8_t getMouseX() { return mouseX; }
  678. int8_t getMouseY() { return mouseY; }
  679. int8_t getWheel() { return wheel; }
  680. protected:
  681. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  682. virtual void control(const Transfer_t *transfer);
  683. virtual void disconnect();
  684. static void callback(const Transfer_t *transfer);
  685. void new_data(const Transfer_t *transfer);
  686. void init();
  687. private:
  688. void update();
  689. Pipe_t *datapipe;
  690. setup_t setup;
  691. uint32_t packetSize;
  692. uint8_t buttons;
  693. int8_t mouseX;
  694. int8_t mouseY;
  695. int8_t wheel;
  696. bool mouseEvent = false;
  697. uint8_t report[20]; // Set to largest packet size 20 bytes
  698. uint8_t prev_report[20]; // Same as above
  699. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  700. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  701. };
  702. #endif