Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

765 Zeilen
28KB

  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. Drivers may set this to
  347. // any non-NULL value if they are in a state where they do not
  348. // wish to claim any device or interface (eg, if getting data
  349. // from the HID parser).
  350. Device_t *device;
  351. friend class USBHost;
  352. };
  353. // Device drivers may create these timer objects to schedule a timer call
  354. class USBDriverTimer {
  355. public:
  356. USBDriverTimer() { }
  357. USBDriverTimer(USBDriver *d) : driver(d) { }
  358. void init(USBDriver *d) { driver = d; };
  359. void start(uint32_t microseconds);
  360. void *pointer;
  361. uint32_t integer;
  362. uint32_t started_micros; // testing only
  363. private:
  364. USBDriver *driver;
  365. uint32_t usec;
  366. USBDriverTimer *next;
  367. USBDriverTimer *prev;
  368. friend class USBHost;
  369. };
  370. // Device drivers may inherit from this base class, if they wish to receive
  371. // HID input data fully decoded by the USBHIDParser driver
  372. class USBHIDInput {
  373. private:
  374. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  375. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  376. virtual void hid_input_data(uint32_t usage, int32_t value);
  377. virtual void hid_input_end();
  378. virtual void disconnect_collection(Device_t *dev);
  379. void add_to_list();
  380. USBHIDInput *next;
  381. friend class USBHIDParser;
  382. };
  383. /************************************************/
  384. /* USB Device Drivers */
  385. /************************************************/
  386. class USBHub : public USBDriver {
  387. public:
  388. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  389. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  390. // Hubs with more more than 7 ports are built from two tiers of hubs
  391. // using 4 or 7 port hub chips. While the USB spec seems to allow
  392. // hubs to have up to 255 ports, in practice all hub chips on the
  393. // market are only 2, 3, 4 or 7 ports.
  394. enum { MAXPORTS = 7 };
  395. typedef uint8_t portbitmask_t;
  396. enum {
  397. PORT_OFF = 0,
  398. PORT_DISCONNECT = 1,
  399. PORT_DEBOUNCE1 = 2,
  400. PORT_DEBOUNCE2 = 3,
  401. PORT_DEBOUNCE3 = 4,
  402. PORT_DEBOUNCE4 = 5,
  403. PORT_DEBOUNCE5 = 6,
  404. PORT_RESET = 7,
  405. PORT_RECOVERY = 8,
  406. PORT_ACTIVE = 9
  407. };
  408. protected:
  409. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  410. virtual void control(const Transfer_t *transfer);
  411. virtual void timer_event(USBDriverTimer *whichTimer);
  412. virtual void disconnect();
  413. void init();
  414. bool can_send_control_now();
  415. void send_poweron(uint32_t port);
  416. void send_getstatus(uint32_t port);
  417. void send_clearstatus_connect(uint32_t port);
  418. void send_clearstatus_enable(uint32_t port);
  419. void send_clearstatus_suspend(uint32_t port);
  420. void send_clearstatus_overcurrent(uint32_t port);
  421. void send_clearstatus_reset(uint32_t port);
  422. void send_setreset(uint32_t port);
  423. static void callback(const Transfer_t *transfer);
  424. void status_change(const Transfer_t *transfer);
  425. void new_port_status(uint32_t port, uint32_t status);
  426. void start_debounce_timer(uint32_t port);
  427. void stop_debounce_timer(uint32_t port);
  428. private:
  429. Device_t mydevices[MAXPORTS];
  430. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  431. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  432. USBDriverTimer debouncetimer;
  433. USBDriverTimer resettimer;
  434. setup_t setup;
  435. Pipe_t *changepipe;
  436. Device_t *devicelist[MAXPORTS];
  437. uint32_t changebits;
  438. uint32_t statusbits;
  439. uint8_t hub_desc[16];
  440. uint8_t endpoint;
  441. uint8_t interval;
  442. uint8_t numports;
  443. uint8_t characteristics;
  444. uint8_t powertime;
  445. uint8_t sending_control_transfer;
  446. uint8_t port_doing_reset;
  447. uint8_t port_doing_reset_speed;
  448. uint8_t portstate[MAXPORTS];
  449. portbitmask_t send_pending_poweron;
  450. portbitmask_t send_pending_getstatus;
  451. portbitmask_t send_pending_clearstatus_connect;
  452. portbitmask_t send_pending_clearstatus_enable;
  453. portbitmask_t send_pending_clearstatus_suspend;
  454. portbitmask_t send_pending_clearstatus_overcurrent;
  455. portbitmask_t send_pending_clearstatus_reset;
  456. portbitmask_t send_pending_setreset;
  457. portbitmask_t debounce_in_use;
  458. static volatile bool reset_busy;
  459. };
  460. class USBHIDParser : public USBDriver {
  461. public:
  462. USBHIDParser(USBHost &host) { init(); }
  463. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  464. protected:
  465. enum { TOPUSAGE_LIST_LEN = 4 };
  466. enum { USAGE_LIST_LEN = 12 };
  467. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  468. virtual void control(const Transfer_t *transfer);
  469. virtual void disconnect();
  470. static void in_callback(const Transfer_t *transfer);
  471. static void out_callback(const Transfer_t *transfer);
  472. void in_data(const Transfer_t *transfer);
  473. void out_data(const Transfer_t *transfer);
  474. bool check_if_using_report_id();
  475. void parse();
  476. USBHIDInput * find_driver(uint32_t topusage);
  477. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  478. void init();
  479. private:
  480. Pipe_t *in_pipe;
  481. Pipe_t *out_pipe;
  482. static USBHIDInput *available_hid_drivers_list;
  483. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  484. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  485. uint16_t in_size;
  486. uint16_t out_size;
  487. setup_t setup;
  488. uint8_t descriptor[512];
  489. uint8_t report[64];
  490. uint16_t descsize;
  491. bool use_report_id;
  492. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  493. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  494. };
  495. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  496. public:
  497. KeyboardController(USBHost &host) { init(); }
  498. KeyboardController(USBHost *host) { init(); }
  499. int available();
  500. int read();
  501. uint16_t getKey() { return keyCode; }
  502. uint8_t getModifiers() { return modifiers; }
  503. uint8_t getOemKey() { return keyOEM; }
  504. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  505. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  506. protected:
  507. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  508. virtual void control(const Transfer_t *transfer);
  509. virtual void disconnect();
  510. static void callback(const Transfer_t *transfer);
  511. void new_data(const Transfer_t *transfer);
  512. void init();
  513. private:
  514. void update();
  515. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  516. void key_press(uint32_t mod, uint32_t key);
  517. void key_release(uint32_t mod, uint32_t key);
  518. void (*keyPressedFunction)(int unicode);
  519. void (*keyReleasedFunction)(int unicode);
  520. Pipe_t *datapipe;
  521. setup_t setup;
  522. uint8_t report[8];
  523. uint16_t keyCode;
  524. uint8_t modifiers;
  525. uint8_t keyOEM;
  526. uint8_t prev_report[8];
  527. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  528. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  529. };
  530. class MIDIDevice : public USBDriver {
  531. public:
  532. enum { SYSEX_MAX_LEN = 60 };
  533. MIDIDevice(USBHost &host) { init(); }
  534. MIDIDevice(USBHost *host) { init(); }
  535. bool read(uint8_t channel=0, uint8_t cable=0);
  536. uint8_t getType(void) {
  537. return msg_type;
  538. };
  539. uint8_t getChannel(void) {
  540. return msg_channel;
  541. };
  542. uint8_t getData1(void) {
  543. return msg_data1;
  544. };
  545. uint8_t getData2(void) {
  546. return msg_data2;
  547. };
  548. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  549. handleNoteOff = f;
  550. };
  551. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  552. handleNoteOn = f;
  553. };
  554. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  555. handleVelocityChange = f;
  556. };
  557. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  558. handleControlChange = f;
  559. };
  560. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  561. handleProgramChange = f;
  562. };
  563. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  564. handleAfterTouch = f;
  565. };
  566. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  567. handlePitchChange = f;
  568. };
  569. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  570. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  571. }
  572. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  573. handleRealTimeSystem = f;
  574. };
  575. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  576. handleTimeCodeQuarterFrame = f;
  577. };
  578. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  579. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  580. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  581. }
  582. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  583. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  584. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  585. }
  586. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  587. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  588. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  589. }
  590. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  591. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  592. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  593. }
  594. void sendProgramChange(uint32_t program, uint32_t channel) {
  595. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  596. | ((program & 0x7F) << 16));
  597. }
  598. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  599. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  600. | ((pressure & 0x7F) << 16));
  601. }
  602. void sendPitchBend(uint32_t value, uint32_t channel) {
  603. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  604. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  605. }
  606. void sendSysEx(uint32_t length, const void *data);
  607. void sendRealTime(uint32_t type) {
  608. switch (type) {
  609. case 0xF8: // Clock
  610. case 0xFA: // Start
  611. case 0xFC: // Stop
  612. case 0xFB: // Continue
  613. case 0xFE: // ActiveSensing
  614. case 0xFF: // SystemReset
  615. write_packed((type << 8) | 0x0F);
  616. break;
  617. default: // Invalid Real Time marker
  618. break;
  619. }
  620. }
  621. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  622. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  623. sendTimeCodeQuarterFrame(data);
  624. }
  625. void sendTimeCodeQuarterFrame(uint32_t data) {
  626. write_packed(0xF108 | ((data & 0x7F) << 16));
  627. }
  628. protected:
  629. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  630. virtual void disconnect();
  631. static void rx_callback(const Transfer_t *transfer);
  632. static void tx_callback(const Transfer_t *transfer);
  633. void rx_data(const Transfer_t *transfer);
  634. void tx_data(const Transfer_t *transfer);
  635. void init();
  636. void write_packed(uint32_t data);
  637. void sysex_byte(uint8_t b);
  638. private:
  639. Pipe_t *rxpipe;
  640. Pipe_t *txpipe;
  641. enum { MAX_PACKET_SIZE = 64 };
  642. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  643. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  644. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  645. uint16_t rx_size;
  646. uint16_t tx_size;
  647. uint32_t rx_queue[RX_QUEUE_SIZE];
  648. bool rx_packet_queued;
  649. uint16_t rx_head;
  650. uint16_t rx_tail;
  651. uint8_t rx_ep;
  652. uint8_t tx_ep;
  653. uint8_t msg_channel;
  654. uint8_t msg_type;
  655. uint8_t msg_data1;
  656. uint8_t msg_data2;
  657. uint8_t msg_sysex[SYSEX_MAX_LEN];
  658. uint8_t msg_sysex_len;
  659. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  660. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  661. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  662. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  663. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  664. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  665. void (*handlePitchChange)(uint8_t ch, int pitch);
  666. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  667. void (*handleRealTimeSystem)(uint8_t rtb);
  668. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  669. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  670. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  671. };
  672. class MouseController : public USBHIDInput {
  673. public:
  674. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  675. bool available() { return mouseEvent; }
  676. void mouseDataClear();
  677. uint8_t getButtons() { return buttons; }
  678. int getMouseX() { return mouseX; }
  679. int getMouseY() { return mouseY; }
  680. int getWheel() { return wheel; }
  681. int getWheelH() { return wheelH; }
  682. protected:
  683. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  684. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  685. virtual void hid_input_data(uint32_t usage, int32_t value);
  686. virtual void hid_input_end();
  687. virtual void disconnect_collection(Device_t *dev);
  688. private:
  689. Device_t *mydevice = NULL;
  690. uint8_t collections_claimed = 0;
  691. volatile bool mouseEvent = false;
  692. uint8_t buttons = 0;
  693. int mouseX = 0;
  694. int mouseY = 0;
  695. int wheel = 0;
  696. int wheelH = 0;
  697. };
  698. class JoystickController : public USBHIDInput {
  699. public:
  700. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  701. bool available() { return joystickEvent; }
  702. void joystickDataClear();
  703. uint32_t getButtons() { return buttons; }
  704. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  705. protected:
  706. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  707. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  708. virtual void hid_input_data(uint32_t usage, int32_t value);
  709. virtual void hid_input_end();
  710. virtual void disconnect_collection(Device_t *dev);
  711. private:
  712. Device_t *mydevice = NULL;
  713. uint8_t collections_claimed = 0;
  714. bool anychange = false;
  715. volatile bool joystickEvent = false;
  716. uint32_t buttons = 0;
  717. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  718. };
  719. #endif