No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

USBHost_t36.h 34KB

hace 7 años
hace 7 años
hace 7 años
hace 7 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #ifndef USB_HOST_TEENSY36_
  24. #define USB_HOST_TEENSY36_
  25. #include <stdint.h>
  26. #if !defined(__MK66FX1M0__)
  27. #error "USBHost_t36 only works with Teensy 3.6. Please select it in Tools > Boards"
  28. #endif
  29. // Dear inquisitive reader, USB is a complex protocol defined with
  30. // very specific terminology. To have any chance of understand this
  31. // source code, you absolutely must have solid knowledge of specific
  32. // USB terms such as host, device, endpoint, pipe, enumeration....
  33. // You really must also have at least a basic knowledge of the
  34. // different USB transfers: control, bulk, interrupt, isochronous.
  35. //
  36. // The USB 2.0 specification explains these in chapter 4 (pages 15
  37. // to 24), and provides more detail in the first part of chapter 5
  38. // (pages 25 to 55). The USB spec is published for free at
  39. // www.usb.org. Here is a convenient link to just the main PDF:
  40. //
  41. // https://www.pjrc.com/teensy/beta/usb20.pdf
  42. //
  43. // This is a huge file, but chapter 4 is short and easy to read.
  44. // If you're not familiar with the USB lingo, please do yourself
  45. // a favor by reading at least chapter 4 to get up to speed on the
  46. // meaning of these important USB concepts and terminology.
  47. //
  48. // If you wish to ask questions (which belong on the forum, not
  49. // github issues) or discuss development of this library, you
  50. // ABSOLUTELY MUST know the basic USB terminology from chapter 4.
  51. // Please repect other people's valuable time & effort by making
  52. // your best effort to read chapter 4 before asking USB questions!
  53. //#define USBHOST_PRINT_DEBUG
  54. /************************************************/
  55. /* Data Types */
  56. /************************************************/
  57. // These 6 types are the key to understanding how this USB Host
  58. // library really works.
  59. // USBHost is a static class controlling the hardware.
  60. // All common USB functionality is implemented here.
  61. class USBHost;
  62. // These 3 structures represent the actual USB entities
  63. // USBHost manipulates. One Device_t is created for
  64. // each active USB device. One Pipe_t is create for
  65. // each endpoint. Transfer_t structures are created
  66. // when any data transfer is added to the EHCI work
  67. // queues, and then returned to the free pool after the
  68. // data transfer completes and the driver has processed
  69. // the results.
  70. typedef struct Device_struct Device_t;
  71. typedef struct Pipe_struct Pipe_t;
  72. typedef struct Transfer_struct Transfer_t;
  73. // All USB device drivers inherit use these classes.
  74. // Drivers build user-visible functionality on top
  75. // of these classes, which receive USB events from
  76. // USBHost.
  77. class USBDriver;
  78. class USBDriverTimer;
  79. /************************************************/
  80. /* Added Defines */
  81. /************************************************/
  82. #define KEYD_UP 0xDA
  83. #define KEYD_DOWN 0xD9
  84. #define KEYD_LEFT 0xD8
  85. #define KEYD_RIGHT 0xD7
  86. #define KEYD_INSERT 0xD1
  87. #define KEYD_DELETE 0xD4
  88. #define KEYD_PAGE_UP 0xD3
  89. #define KEYD_PAGE_DOWN 0xD6
  90. #define KEYD_HOME 0xD2
  91. #define KEYD_END 0xD5
  92. #define KEYD_F1 0xC2
  93. #define KEYD_F2 0xC3
  94. #define KEYD_F3 0xC4
  95. #define KEYD_F4 0xC5
  96. #define KEYD_F5 0xC6
  97. #define KEYD_F6 0xC7
  98. #define KEYD_F7 0xC8
  99. #define KEYD_F8 0xC9
  100. #define KEYD_F9 0xCA
  101. #define KEYD_F10 0xCB
  102. #define KEYD_F11 0xCC
  103. #define KEYD_F12 0xCD
  104. /************************************************/
  105. /* Data Structure Definitions */
  106. /************************************************/
  107. // setup_t holds the 8 byte USB SETUP packet data.
  108. // These unions & structs allow convenient access to
  109. // the setup fields.
  110. typedef union {
  111. struct {
  112. union {
  113. struct {
  114. uint8_t bmRequestType;
  115. uint8_t bRequest;
  116. };
  117. uint16_t wRequestAndType;
  118. };
  119. uint16_t wValue;
  120. uint16_t wIndex;
  121. uint16_t wLength;
  122. };
  123. struct {
  124. uint32_t word1;
  125. uint32_t word2;
  126. };
  127. } setup_t;
  128. // Device_t holds all the information about a USB device
  129. #define DEVICE_STRUCT_STRING_BUF_SIZE 48
  130. struct Device_struct {
  131. Pipe_t *control_pipe;
  132. Pipe_t *data_pipes;
  133. Device_t *next;
  134. USBDriver *drivers;
  135. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  136. uint8_t address;
  137. uint8_t hub_address;
  138. uint8_t hub_port;
  139. uint8_t enum_state;
  140. uint8_t bDeviceClass;
  141. uint8_t bDeviceSubClass;
  142. uint8_t bDeviceProtocol;
  143. uint8_t bmAttributes;
  144. uint8_t bMaxPower;
  145. uint16_t idVendor;
  146. uint16_t idProduct;
  147. uint16_t LanguageID;
  148. uint8_t string_buf[DEVICE_STRUCT_STRING_BUF_SIZE]; // Probably want a place to allocate fewer of these...
  149. uint8_t iStrings[3]; // 3 indexes - vendor string, product string, serial number.
  150. };
  151. // Pipe_t holes all information about each USB endpoint/pipe
  152. // The first half is an EHCI QH structure for the pipe.
  153. struct Pipe_struct {
  154. // Queue Head (QH), EHCI page 46-50
  155. struct { // must be aligned to 32 byte boundary
  156. volatile uint32_t horizontal_link;
  157. volatile uint32_t capabilities[2];
  158. volatile uint32_t current;
  159. volatile uint32_t next;
  160. volatile uint32_t alt_next;
  161. volatile uint32_t token;
  162. volatile uint32_t buffer[5];
  163. } qh;
  164. Device_t *device;
  165. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  166. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  167. uint8_t start_mask;
  168. uint8_t complete_mask;
  169. Pipe_t *next;
  170. void (*callback_function)(const Transfer_t *);
  171. uint16_t periodic_interval;
  172. uint16_t periodic_offset;
  173. uint32_t unused1;
  174. uint32_t unused2;
  175. uint32_t unused3;
  176. uint32_t unused4;
  177. uint32_t unused5;
  178. uint32_t unused6;
  179. uint32_t unused7;
  180. };
  181. // Transfer_t represents a single transaction on the USB bus.
  182. // The first portion is an EHCI qTD structure. Transfer_t are
  183. // allocated as-needed from a memory pool, loaded with pointers
  184. // to the actual data buffers, linked into a followup list,
  185. // and placed on ECHI Queue Heads. When the ECHI interrupt
  186. // occurs, the followup lists are used to find the Transfer_t
  187. // in memory. Callbacks are made, and then the Transfer_t are
  188. // returned to the memory pool.
  189. struct Transfer_struct {
  190. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  191. struct { // must be aligned to 32 byte boundary
  192. volatile uint32_t next;
  193. volatile uint32_t alt_next;
  194. volatile uint32_t token;
  195. volatile uint32_t buffer[5];
  196. } qtd;
  197. // Linked list of queued, not-yet-completed transfers
  198. Transfer_t *next_followup;
  199. Transfer_t *prev_followup;
  200. Pipe_t *pipe;
  201. // Data to be used by callback function. When a group
  202. // of Transfer_t are created, these fields and the
  203. // interrupt-on-complete bit in the qTD token are only
  204. // set in the last Transfer_t of the list.
  205. void *buffer;
  206. uint32_t length;
  207. setup_t setup;
  208. USBDriver *driver;
  209. };
  210. /************************************************/
  211. /* Main USB EHCI Controller */
  212. /************************************************/
  213. class USBHost {
  214. public:
  215. static void begin();
  216. static void Task();
  217. protected:
  218. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  219. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  220. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  221. void *buf, USBDriver *driver);
  222. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  223. uint32_t len, USBDriver *driver);
  224. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  225. static void disconnect_Device(Device_t *dev);
  226. static void enumeration(const Transfer_t *transfer);
  227. static void driver_ready_for_device(USBDriver *driver);
  228. static void contribute_Devices(Device_t *devices, uint32_t num);
  229. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  230. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  231. static volatile bool enumeration_busy;
  232. private:
  233. static void isr();
  234. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  235. static void claim_drivers(Device_t *dev);
  236. static uint32_t assign_address(void);
  237. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  238. static void init_Device_Pipe_Transfer_memory(void);
  239. static Device_t * allocate_Device(void);
  240. static void delete_Pipe(Pipe_t *pipe);
  241. static void free_Device(Device_t *q);
  242. static Pipe_t * allocate_Pipe(void);
  243. static void free_Pipe(Pipe_t *q);
  244. static Transfer_t * allocate_Transfer(void);
  245. static void free_Transfer(Transfer_t *q);
  246. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  247. uint32_t maxlen, uint32_t interval);
  248. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  249. static bool followup_Transfer(Transfer_t *transfer);
  250. static void followup_Error(void);
  251. protected:
  252. #ifdef USBHOST_PRINT_DEBUG
  253. static void print_(const Transfer_t *transfer);
  254. static void print_(const Transfer_t *first, const Transfer_t *last);
  255. static void print_token(uint32_t token);
  256. static void print_(const Pipe_t *pipe);
  257. static void print_driverlist(const char *name, const USBDriver *driver);
  258. static void print_qh_list(const Pipe_t *list);
  259. static void print_hexbytes(const void *ptr, uint32_t len);
  260. static void print_(const char *s) { Serial.print(s); }
  261. static void print_(int n) { Serial.print(n); }
  262. static void print_(unsigned int n) { Serial.print(n); }
  263. static void print_(long n) { Serial.print(n); }
  264. static void print_(unsigned long n) { Serial.print(n); }
  265. static void println_(const char *s) { Serial.println(s); }
  266. static void println_(int n) { Serial.println(n); }
  267. static void println_(unsigned int n) { Serial.println(n); }
  268. static void println_(long n) { Serial.println(n); }
  269. static void println_(unsigned long n) { Serial.println(n); }
  270. static void println_() { Serial.println(); }
  271. static void print_(uint32_t n, uint8_t b) { Serial.print(n, b); }
  272. static void println_(uint32_t n, uint8_t b) { Serial.println(n, b); }
  273. static void print_(const char *s, int n, uint8_t b = DEC) {
  274. Serial.print(s); Serial.print(n, b); }
  275. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  276. Serial.print(s); Serial.print(n, b); }
  277. static void print_(const char *s, long n, uint8_t b = DEC) {
  278. Serial.print(s); Serial.print(n, b); }
  279. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  280. Serial.print(s); Serial.print(n, b); }
  281. static void println_(const char *s, int n, uint8_t b = DEC) {
  282. Serial.print(s); Serial.println(n, b); }
  283. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  284. Serial.print(s); Serial.println(n, b); }
  285. static void println_(const char *s, long n, uint8_t b = DEC) {
  286. Serial.print(s); Serial.println(n, b); }
  287. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  288. Serial.print(s); Serial.println(n, b); }
  289. friend class USBDriverTimer; // for access to print & println
  290. #else
  291. static void print_(const Transfer_t *transfer) {}
  292. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  293. static void print_token(uint32_t token) {}
  294. static void print_(const Pipe_t *pipe) {}
  295. static void print_driverlist(const char *name, const USBDriver *driver) {}
  296. static void print_qh_list(const Pipe_t *list) {}
  297. static void print_hexbytes(const void *ptr, uint32_t len) {}
  298. static void print_(const char *s) {}
  299. static void print_(int n) {}
  300. static void print_(unsigned int n) {}
  301. static void print_(long n) {}
  302. static void print_(unsigned long n) {}
  303. static void println_(const char *s) {}
  304. static void println_(int n) {}
  305. static void println_(unsigned int n) {}
  306. static void println_(long n) {}
  307. static void println_(unsigned long n) {}
  308. static void println_() {}
  309. static void print_(uint32_t n, uint8_t b) {}
  310. static void println_(uint32_t n, uint8_t b) {}
  311. static void print_(const char *s, int n, uint8_t b = DEC) {}
  312. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  313. static void print_(const char *s, long n, uint8_t b = DEC) {}
  314. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  315. static void println_(const char *s, int n, uint8_t b = DEC) {}
  316. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  317. static void println_(const char *s, long n, uint8_t b = DEC) {}
  318. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  319. #endif
  320. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  321. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  322. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  323. s.word2 = wIndex | (wLength << 16);
  324. }
  325. };
  326. /************************************************/
  327. /* USB Device Driver Common Base Class */
  328. /************************************************/
  329. // All USB device drivers inherit from this base class.
  330. class USBDriver : public USBHost {
  331. public:
  332. operator bool() { return (device != nullptr); }
  333. uint16_t idVendor() { return (device != nullptr) ? device->idVendor : 0; }
  334. uint16_t idProduct() { return (device != nullptr) ? device->idProduct : 0; }
  335. const uint8_t *manufacturer() { return (device != nullptr) ? &(device->string_buf[device->iStrings[0]]) : nullptr; }
  336. const uint8_t *product() { return (device != nullptr) ? &(device->string_buf[device->iStrings[1]]) : nullptr; }
  337. const uint8_t *serialNumber() { return (device != nullptr) ? &(device->string_buf[device->iStrings[2]]) : nullptr; }
  338. // TODO: user-level functions
  339. // check if device is bound/active/online
  340. // query vid, pid
  341. // query string: manufacturer, product, serial number
  342. protected:
  343. USBDriver() : next(NULL), device(NULL) {}
  344. // Check if a driver wishes to claim a device or interface or group
  345. // of interfaces within a device. When this function returns true,
  346. // the driver is considered bound or loaded for that device. When
  347. // new devices are detected, enumeration.cpp calls this function on
  348. // all unbound driver objects, to give them an opportunity to bind
  349. // to the new device.
  350. // device has its vid&pid, class/subclass fields initialized
  351. // type is 0 for device level, 1 for interface level, 2 for IAD
  352. // descriptors points to the specific descriptor data
  353. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  354. // When an unknown (not chapter 9) control transfer completes, this
  355. // function is called for all drivers bound to the device. Return
  356. // true means this driver originated this control transfer, so no
  357. // more drivers need to be offered an opportunity to process it.
  358. // This function is optional, only needed if the driver uses control
  359. // transfers and wishes to be notified when they complete.
  360. virtual void control(const Transfer_t *transfer) { }
  361. // When any of the USBDriverTimer objects a driver creates generates
  362. // a timer event, this function is called.
  363. virtual void timer_event(USBDriverTimer *whichTimer) { }
  364. // When the user calls USBHost::Task, this Task function for all
  365. // active drivers is called, so they may update state and/or call
  366. // any attached user callback functions.
  367. virtual void Task() { }
  368. // When a device disconnects from the USB, this function is called.
  369. // The driver must free all resources it allocated and update any
  370. // internal state necessary to deal with the possibility of user
  371. // code continuing to call its API. However, pipes and transfers
  372. // are the handled by lower layers, so device drivers do not free
  373. // pipes they created or cancel transfers they had in progress.
  374. virtual void disconnect();
  375. // Drivers are managed by this single-linked list. All inactive
  376. // (not bound to any device) drivers are linked from
  377. // available_drivers in enumeration.cpp. When bound to a device,
  378. // drivers are linked from that Device_t drivers list.
  379. USBDriver *next;
  380. // The device this object instance is bound to. In words, this
  381. // is the specific device this driver is using. When not bound
  382. // to any device, this must be NULL. Drivers may set this to
  383. // any non-NULL value if they are in a state where they do not
  384. // wish to claim any device or interface (eg, if getting data
  385. // from the HID parser).
  386. Device_t *device;
  387. friend class USBHost;
  388. };
  389. // Device drivers may create these timer objects to schedule a timer call
  390. class USBDriverTimer {
  391. public:
  392. USBDriverTimer() { }
  393. USBDriverTimer(USBDriver *d) : driver(d) { }
  394. void init(USBDriver *d) { driver = d; };
  395. void start(uint32_t microseconds);
  396. void stop();
  397. void *pointer;
  398. uint32_t integer;
  399. uint32_t started_micros; // testing only
  400. private:
  401. USBDriver *driver;
  402. uint32_t usec;
  403. USBDriverTimer *next;
  404. USBDriverTimer *prev;
  405. friend class USBHost;
  406. };
  407. // Device drivers may inherit from this base class, if they wish to receive
  408. // HID input data fully decoded by the USBHIDParser driver
  409. class USBHIDInput {
  410. public:
  411. operator bool() { return (mydevice != nullptr); }
  412. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  413. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  414. private:
  415. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  416. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  417. virtual void hid_input_data(uint32_t usage, int32_t value);
  418. virtual void hid_input_end();
  419. virtual void disconnect_collection(Device_t *dev);
  420. void add_to_list();
  421. USBHIDInput *next;
  422. friend class USBHIDParser;
  423. protected:
  424. Device_t *mydevice = NULL;
  425. };
  426. /************************************************/
  427. /* USB Device Drivers */
  428. /************************************************/
  429. class USBHub : public USBDriver {
  430. public:
  431. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  432. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  433. // Hubs with more more than 7 ports are built from two tiers of hubs
  434. // using 4 or 7 port hub chips. While the USB spec seems to allow
  435. // hubs to have up to 255 ports, in practice all hub chips on the
  436. // market are only 2, 3, 4 or 7 ports.
  437. enum { MAXPORTS = 7 };
  438. typedef uint8_t portbitmask_t;
  439. enum {
  440. PORT_OFF = 0,
  441. PORT_DISCONNECT = 1,
  442. PORT_DEBOUNCE1 = 2,
  443. PORT_DEBOUNCE2 = 3,
  444. PORT_DEBOUNCE3 = 4,
  445. PORT_DEBOUNCE4 = 5,
  446. PORT_DEBOUNCE5 = 6,
  447. PORT_RESET = 7,
  448. PORT_RECOVERY = 8,
  449. PORT_ACTIVE = 9
  450. };
  451. protected:
  452. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  453. virtual void control(const Transfer_t *transfer);
  454. virtual void timer_event(USBDriverTimer *whichTimer);
  455. virtual void disconnect();
  456. void init();
  457. bool can_send_control_now();
  458. void send_poweron(uint32_t port);
  459. void send_getstatus(uint32_t port);
  460. void send_clearstatus_connect(uint32_t port);
  461. void send_clearstatus_enable(uint32_t port);
  462. void send_clearstatus_suspend(uint32_t port);
  463. void send_clearstatus_overcurrent(uint32_t port);
  464. void send_clearstatus_reset(uint32_t port);
  465. void send_setreset(uint32_t port);
  466. static void callback(const Transfer_t *transfer);
  467. void status_change(const Transfer_t *transfer);
  468. void new_port_status(uint32_t port, uint32_t status);
  469. void start_debounce_timer(uint32_t port);
  470. void stop_debounce_timer(uint32_t port);
  471. private:
  472. Device_t mydevices[MAXPORTS];
  473. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  474. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  475. USBDriverTimer debouncetimer;
  476. USBDriverTimer resettimer;
  477. setup_t setup;
  478. Pipe_t *changepipe;
  479. Device_t *devicelist[MAXPORTS];
  480. uint32_t changebits;
  481. uint32_t statusbits;
  482. uint8_t hub_desc[16];
  483. uint8_t endpoint;
  484. uint8_t interval;
  485. uint8_t numports;
  486. uint8_t characteristics;
  487. uint8_t powertime;
  488. uint8_t sending_control_transfer;
  489. uint8_t port_doing_reset;
  490. uint8_t port_doing_reset_speed;
  491. uint8_t portstate[MAXPORTS];
  492. portbitmask_t send_pending_poweron;
  493. portbitmask_t send_pending_getstatus;
  494. portbitmask_t send_pending_clearstatus_connect;
  495. portbitmask_t send_pending_clearstatus_enable;
  496. portbitmask_t send_pending_clearstatus_suspend;
  497. portbitmask_t send_pending_clearstatus_overcurrent;
  498. portbitmask_t send_pending_clearstatus_reset;
  499. portbitmask_t send_pending_setreset;
  500. portbitmask_t debounce_in_use;
  501. static volatile bool reset_busy;
  502. };
  503. class USBHIDParser : public USBDriver {
  504. public:
  505. USBHIDParser(USBHost &host) { init(); }
  506. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  507. protected:
  508. enum { TOPUSAGE_LIST_LEN = 4 };
  509. enum { USAGE_LIST_LEN = 24 };
  510. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  511. virtual void control(const Transfer_t *transfer);
  512. virtual void disconnect();
  513. static void in_callback(const Transfer_t *transfer);
  514. static void out_callback(const Transfer_t *transfer);
  515. void in_data(const Transfer_t *transfer);
  516. void out_data(const Transfer_t *transfer);
  517. bool check_if_using_report_id();
  518. void parse();
  519. USBHIDInput * find_driver(uint32_t topusage);
  520. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  521. void init();
  522. private:
  523. Pipe_t *in_pipe;
  524. Pipe_t *out_pipe;
  525. static USBHIDInput *available_hid_drivers_list;
  526. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  527. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  528. uint16_t in_size;
  529. uint16_t out_size;
  530. setup_t setup;
  531. uint8_t descriptor[512];
  532. uint8_t report[64];
  533. uint16_t descsize;
  534. bool use_report_id;
  535. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  536. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  537. };
  538. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  539. public:
  540. typedef union {
  541. struct {
  542. uint8_t numLock : 1;
  543. uint8_t capsLock : 1;
  544. uint8_t scrollLock : 1;
  545. uint8_t compose : 1;
  546. uint8_t kana : 1;
  547. uint8_t reserved : 3;
  548. };
  549. uint8_t byte;
  550. } KBDLeds_t;
  551. public:
  552. KeyboardController(USBHost &host) { init(); }
  553. KeyboardController(USBHost *host) { init(); }
  554. int available();
  555. int read();
  556. uint16_t getKey() { return keyCode; }
  557. uint8_t getModifiers() { return modifiers; }
  558. uint8_t getOemKey() { return keyOEM; }
  559. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  560. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  561. void LEDS(uint8_t leds);
  562. uint8_t LEDS() {return leds_.byte;}
  563. void updateLEDS(void);
  564. bool numLock() {return leds_.numLock;}
  565. bool capsLock() {return leds_.capsLock;}
  566. bool scrollLock() {return leds_.scrollLock;}
  567. void numLock(bool f);
  568. void capsLock(bool f);
  569. void scrollLock(bool f);
  570. protected:
  571. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  572. virtual void control(const Transfer_t *transfer);
  573. virtual void disconnect();
  574. static void callback(const Transfer_t *transfer);
  575. void new_data(const Transfer_t *transfer);
  576. void init();
  577. private:
  578. void update();
  579. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  580. void key_press(uint32_t mod, uint32_t key);
  581. void key_release(uint32_t mod, uint32_t key);
  582. void (*keyPressedFunction)(int unicode);
  583. void (*keyReleasedFunction)(int unicode);
  584. Pipe_t *datapipe;
  585. setup_t setup;
  586. uint8_t report[8];
  587. uint16_t keyCode;
  588. uint8_t modifiers;
  589. uint8_t keyOEM;
  590. uint8_t prev_report[8];
  591. KBDLeds_t leds_ = {0};
  592. bool update_leds_ = false;
  593. bool processing_new_data_ = false;
  594. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  595. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  596. };
  597. class MIDIDevice : public USBDriver {
  598. public:
  599. enum { SYSEX_MAX_LEN = 60 };
  600. MIDIDevice(USBHost &host) { init(); }
  601. MIDIDevice(USBHost *host) { init(); }
  602. bool read(uint8_t channel=0, uint8_t cable=0);
  603. uint8_t getType(void) {
  604. return msg_type;
  605. };
  606. uint8_t getChannel(void) {
  607. return msg_channel;
  608. };
  609. uint8_t getData1(void) {
  610. return msg_data1;
  611. };
  612. uint8_t getData2(void) {
  613. return msg_data2;
  614. };
  615. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  616. handleNoteOff = f;
  617. };
  618. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  619. handleNoteOn = f;
  620. };
  621. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  622. handleVelocityChange = f;
  623. };
  624. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  625. handleControlChange = f;
  626. };
  627. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  628. handleProgramChange = f;
  629. };
  630. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  631. handleAfterTouch = f;
  632. };
  633. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  634. handlePitchChange = f;
  635. };
  636. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  637. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  638. }
  639. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  640. handleRealTimeSystem = f;
  641. };
  642. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  643. handleTimeCodeQuarterFrame = f;
  644. };
  645. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  646. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  647. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  648. }
  649. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  650. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  651. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  652. }
  653. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  654. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  655. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  656. }
  657. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  658. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  659. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  660. }
  661. void sendProgramChange(uint32_t program, uint32_t channel) {
  662. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  663. | ((program & 0x7F) << 16));
  664. }
  665. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  666. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  667. | ((pressure & 0x7F) << 16));
  668. }
  669. void sendPitchBend(uint32_t value, uint32_t channel) {
  670. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  671. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  672. }
  673. void sendSysEx(uint32_t length, const void *data);
  674. void sendRealTime(uint32_t type) {
  675. switch (type) {
  676. case 0xF8: // Clock
  677. case 0xFA: // Start
  678. case 0xFC: // Stop
  679. case 0xFB: // Continue
  680. case 0xFE: // ActiveSensing
  681. case 0xFF: // SystemReset
  682. write_packed((type << 8) | 0x0F);
  683. break;
  684. default: // Invalid Real Time marker
  685. break;
  686. }
  687. }
  688. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  689. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  690. sendTimeCodeQuarterFrame(data);
  691. }
  692. void sendTimeCodeQuarterFrame(uint32_t data) {
  693. write_packed(0xF108 | ((data & 0x7F) << 16));
  694. }
  695. protected:
  696. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  697. virtual void disconnect();
  698. static void rx_callback(const Transfer_t *transfer);
  699. static void tx_callback(const Transfer_t *transfer);
  700. void rx_data(const Transfer_t *transfer);
  701. void tx_data(const Transfer_t *transfer);
  702. void init();
  703. void write_packed(uint32_t data);
  704. void sysex_byte(uint8_t b);
  705. private:
  706. Pipe_t *rxpipe;
  707. Pipe_t *txpipe;
  708. enum { MAX_PACKET_SIZE = 64 };
  709. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  710. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  711. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  712. uint16_t rx_size;
  713. uint16_t tx_size;
  714. uint32_t rx_queue[RX_QUEUE_SIZE];
  715. bool rx_packet_queued;
  716. uint16_t rx_head;
  717. uint16_t rx_tail;
  718. uint8_t rx_ep;
  719. uint8_t tx_ep;
  720. uint8_t msg_channel;
  721. uint8_t msg_type;
  722. uint8_t msg_data1;
  723. uint8_t msg_data2;
  724. uint8_t msg_sysex[SYSEX_MAX_LEN];
  725. uint8_t msg_sysex_len;
  726. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  727. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  728. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  729. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  730. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  731. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  732. void (*handlePitchChange)(uint8_t ch, int pitch);
  733. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  734. void (*handleRealTimeSystem)(uint8_t rtb);
  735. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  736. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  737. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  738. };
  739. class USBSerial: public USBDriver, public Stream {
  740. public:
  741. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  742. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  743. USBSerial(USBHost &host) : txtimer(this) { init(); }
  744. void begin(uint32_t baud, uint32_t format=0);
  745. void end(void);
  746. virtual int available(void);
  747. virtual int peek(void);
  748. virtual int read(void);
  749. virtual int availableForWrite();
  750. virtual size_t write(uint8_t c);
  751. using Print::write;
  752. protected:
  753. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  754. virtual void control(const Transfer_t *transfer);
  755. virtual void disconnect();
  756. virtual void timer_event(USBDriverTimer *whichTimer);
  757. private:
  758. static void rx_callback(const Transfer_t *transfer);
  759. static void tx_callback(const Transfer_t *transfer);
  760. void rx_data(const Transfer_t *transfer);
  761. void tx_data(const Transfer_t *transfer);
  762. void rx_queue_packets(uint32_t head, uint32_t tail);
  763. void init();
  764. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  765. bool init_buffers(uint32_t rsize, uint32_t tsize);
  766. private:
  767. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  768. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  769. USBDriverTimer txtimer;
  770. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  771. setup_t setup;
  772. uint8_t setupdata[8];
  773. uint32_t baudrate;
  774. Pipe_t *rxpipe;
  775. Pipe_t *txpipe;
  776. uint8_t *rx1; // location for first incoming packet
  777. uint8_t *rx2; // location for second incoming packet
  778. uint8_t *rxbuf; // receive circular buffer
  779. uint8_t *tx1; // location for first outgoing packet
  780. uint8_t *tx2; // location for second outgoing packet
  781. uint8_t *txbuf;
  782. volatile uint16_t rxhead;// receive head
  783. volatile uint16_t rxtail;// receive tail
  784. volatile uint16_t txhead;
  785. volatile uint16_t txtail;
  786. uint16_t rxsize;// size of receive circular buffer
  787. uint16_t txsize;// size of transmit circular buffer
  788. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  789. volatile uint8_t txstate;
  790. uint8_t pending_control;
  791. bool control_queued;
  792. enum { CDCACM, FTDI, PL2303, CH341 } sertype;
  793. };
  794. class MouseController : public USBHIDInput {
  795. public:
  796. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  797. bool available() { return mouseEvent; }
  798. void mouseDataClear();
  799. uint8_t getButtons() { return buttons; }
  800. int getMouseX() { return mouseX; }
  801. int getMouseY() { return mouseY; }
  802. int getWheel() { return wheel; }
  803. int getWheelH() { return wheelH; }
  804. protected:
  805. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  806. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  807. virtual void hid_input_data(uint32_t usage, int32_t value);
  808. virtual void hid_input_end();
  809. virtual void disconnect_collection(Device_t *dev);
  810. private:
  811. uint8_t collections_claimed = 0;
  812. volatile bool mouseEvent = false;
  813. volatile bool hid_input_begin_ = false;
  814. uint8_t buttons = 0;
  815. int mouseX = 0;
  816. int mouseY = 0;
  817. int wheel = 0;
  818. int wheelH = 0;
  819. };
  820. class JoystickController : public USBHIDInput {
  821. public:
  822. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  823. bool available() { return joystickEvent; }
  824. void joystickDataClear();
  825. uint32_t getButtons() { return buttons; }
  826. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  827. protected:
  828. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  829. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  830. virtual void hid_input_data(uint32_t usage, int32_t value);
  831. virtual void hid_input_end();
  832. virtual void disconnect_collection(Device_t *dev);
  833. private:
  834. uint8_t collections_claimed = 0;
  835. bool anychange = false;
  836. volatile bool joystickEvent = false;
  837. uint32_t buttons = 0;
  838. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  839. };
  840. class KeyboardHIDExtrasController : public USBHIDInput {
  841. public:
  842. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  843. void clear() { event_ = false;}
  844. bool available() { return event_; }
  845. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  846. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  847. enum {MAX_KEYS_DOWN=4};
  848. // uint32_t buttons() { return buttons_; }
  849. protected:
  850. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  851. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  852. virtual void hid_input_data(uint32_t usage, int32_t value);
  853. virtual void hid_input_end();
  854. virtual void disconnect_collection(Device_t *dev);
  855. private:
  856. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  857. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  858. uint32_t topusage_ = 0; // What top report am I processing?
  859. uint8_t collections_claimed_ = 0;
  860. volatile bool event_ = false;
  861. volatile bool hid_input_begin_ = false;
  862. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  863. uint8_t count_keys_down_ = 0;
  864. uint16_t keys_down[MAX_KEYS_DOWN];
  865. };
  866. #endif