Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

pirms 7 gadiem
pirms 7 gadiem
pirms 7 gadiem
pirms 7 gadiem
pirms 7 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. protected:
  221. #ifdef USBHOST_PRINT_DEBUG
  222. static void print(const Transfer_t *transfer);
  223. static void print(const Transfer_t *first, const Transfer_t *last);
  224. static void print_token(uint32_t token);
  225. static void print(const Pipe_t *pipe);
  226. static void print_driverlist(const char *name, const USBDriver *driver);
  227. static void print_qh_list(const Pipe_t *list);
  228. static void print_hexbytes(const void *ptr, uint32_t len);
  229. static void print(const char *s) { Serial.print(s); }
  230. static void print(int n) { Serial.print(n); }
  231. static void print(unsigned int n) { Serial.print(n); }
  232. static void print(long n) { Serial.print(n); }
  233. static void print(unsigned long n) { Serial.print(n); }
  234. static void println(const char *s) { Serial.println(s); }
  235. static void println(int n) { Serial.println(n); }
  236. static void println(unsigned int n) { Serial.println(n); }
  237. static void println(long n) { Serial.println(n); }
  238. static void println(unsigned long n) { Serial.println(n); }
  239. static void println() { Serial.println(); }
  240. static void print(uint32_t n, uint8_t b) { Serial.print(n, b); }
  241. static void println(uint32_t n, uint8_t b) { Serial.println(n, b); }
  242. static void println(const char *s, int n) {
  243. Serial.print(s); Serial.println(n); }
  244. static void println(const char *s, unsigned int n) {
  245. Serial.print(s); Serial.println(n); }
  246. static void println(const char *s, long n) {
  247. Serial.print(s); Serial.println(n); }
  248. static void println(const char *s, unsigned long n) {
  249. Serial.print(s); Serial.println(n); }
  250. static void println(const char *s, int n, uint8_t b) {
  251. Serial.print(s); Serial.println(n, b); }
  252. static void println(const char *s, unsigned int n, uint8_t b) {
  253. Serial.print(s); Serial.println(n, b); }
  254. static void println(const char *s, long n, uint8_t b) {
  255. Serial.print(s); Serial.println(n, b); }
  256. static void println(const char *s, unsigned long n, uint8_t b) {
  257. Serial.print(s); Serial.println(n, b); }
  258. #else
  259. static void print(const Transfer_t *transfer) {}
  260. static void print(const Transfer_t *first, const Transfer_t *last) {}
  261. static void print_token(uint32_t token) {}
  262. static void print(const Pipe_t *pipe) {}
  263. static void print_driverlist(const char *name, const USBDriver *driver) {}
  264. static void print_qh_list(const Pipe_t *list) {}
  265. static void print_hexbytes(const void *ptr, uint32_t len) {}
  266. static void print(const char *s) {}
  267. static void print(int n) {}
  268. static void print(unsigned int n) {}
  269. static void print(long n) {}
  270. static void print(unsigned long n) {}
  271. static void println(const char *s) {}
  272. static void println(int n) {}
  273. static void println(unsigned int n) {}
  274. static void println(long n) {}
  275. static void println(unsigned long n) {}
  276. static void println() {}
  277. static void print(uint32_t n, uint8_t b) {}
  278. static void println(uint32_t n, uint8_t b) {}
  279. static void println(const char *s, int n) {}
  280. static void println(const char *s, unsigned int n) {}
  281. static void println(const char *s, long n) {}
  282. static void println(const char *s, unsigned long n) {}
  283. static void println(const char *s, int n, uint8_t b) {}
  284. static void println(const char *s, unsigned int n, uint8_t b) {}
  285. static void println(const char *s, long n, uint8_t b) {}
  286. static void println(const char *s, unsigned long n, uint8_t b) {}
  287. #endif
  288. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  289. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  290. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  291. s.word2 = wIndex | (wLength << 16);
  292. }
  293. };
  294. /************************************************/
  295. /* USB Device Driver Common Base Class */
  296. /************************************************/
  297. // All USB device drivers inherit from this base class.
  298. class USBDriver : public USBHost {
  299. public:
  300. // TODO: user-level functions
  301. // check if device is bound/active/online
  302. // query vid, pid
  303. // query string: manufacturer, product, serial number
  304. protected:
  305. USBDriver() : next(NULL), device(NULL) {}
  306. // Check if a driver wishes to claim a device or interface or group
  307. // of interfaces within a device. When this function returns true,
  308. // the driver is considered bound or loaded for that device. When
  309. // new devices are detected, enumeration.cpp calls this function on
  310. // all unbound driver objects, to give them an opportunity to bind
  311. // to the new device.
  312. // device has its vid&pid, class/subclass fields initialized
  313. // type is 0 for device level, 1 for interface level, 2 for IAD
  314. // descriptors points to the specific descriptor data
  315. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  316. // When an unknown (not chapter 9) control transfer completes, this
  317. // function is called for all drivers bound to the device. Return
  318. // true means this driver originated this control transfer, so no
  319. // more drivers need to be offered an opportunity to process it.
  320. // This function is optional, only needed if the driver uses control
  321. // transfers and wishes to be notified when they complete.
  322. virtual void control(const Transfer_t *transfer) { }
  323. // When any of the USBDriverTimer objects a driver creates generates
  324. // a timer event, this function is called.
  325. virtual void timer_event(USBDriverTimer *whichTimer) { }
  326. // When the user calls USBHost::Task, this Task function for all
  327. // active drivers is called, so they may update state and/or call
  328. // any attached user callback functions.
  329. virtual void Task() { }
  330. // When a device disconnects from the USB, this function is called.
  331. // The driver must free all resources it allocated and update any
  332. // internal state necessary to deal with the possibility of user
  333. // code continuing to call its API. However, pipes and transfers
  334. // are the handled by lower layers, so device drivers do not free
  335. // pipes they created or cancel transfers they had in progress.
  336. virtual void disconnect();
  337. // Drivers are managed by this single-linked list. All inactive
  338. // (not bound to any device) drivers are linked from
  339. // available_drivers in enumeration.cpp. When bound to a device,
  340. // drivers are linked from that Device_t drivers list.
  341. USBDriver *next;
  342. // The device this object instance is bound to. In words, this
  343. // is the specific device this driver is using. When not bound
  344. // to any device, this must be NULL.
  345. Device_t *device;
  346. friend class USBHost;
  347. };
  348. // Device drivers may create these timer objects to schedule a timer call
  349. class USBDriverTimer {
  350. public:
  351. USBDriverTimer() { }
  352. USBDriverTimer(USBDriver *d) : driver(d) { }
  353. void init(USBDriver *d) { driver = d; };
  354. void start(uint32_t microseconds);
  355. void *pointer;
  356. uint32_t integer;
  357. uint32_t started_micros; // testing only
  358. private:
  359. USBDriver *driver;
  360. uint32_t usec;
  361. USBDriverTimer *next;
  362. USBDriverTimer *prev;
  363. friend class USBHost;
  364. };
  365. /************************************************/
  366. /* USB Device Drivers */
  367. /************************************************/
  368. class USBHub : public USBDriver {
  369. public:
  370. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  371. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  372. // Hubs with more more than 7 ports are built from two tiers of hubs
  373. // using 4 or 7 port hub chips. While the USB spec seems to allow
  374. // hubs to have up to 255 ports, in practice all hub chips on the
  375. // market are only 2, 3, 4 or 7 ports.
  376. enum { MAXPORTS = 7 };
  377. typedef uint8_t portbitmask_t;
  378. enum {
  379. PORT_OFF = 0,
  380. PORT_DISCONNECT = 1,
  381. PORT_DEBOUNCE1 = 2,
  382. PORT_DEBOUNCE2 = 3,
  383. PORT_DEBOUNCE3 = 4,
  384. PORT_DEBOUNCE4 = 5,
  385. PORT_DEBOUNCE5 = 6,
  386. PORT_RESET = 7,
  387. PORT_RECOVERY = 8,
  388. PORT_ACTIVE = 9
  389. };
  390. protected:
  391. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  392. virtual void control(const Transfer_t *transfer);
  393. virtual void timer_event(USBDriverTimer *whichTimer);
  394. virtual void disconnect();
  395. void init();
  396. bool can_send_control_now();
  397. void send_poweron(uint32_t port);
  398. void send_getstatus(uint32_t port);
  399. void send_clearstatus_connect(uint32_t port);
  400. void send_clearstatus_enable(uint32_t port);
  401. void send_clearstatus_suspend(uint32_t port);
  402. void send_clearstatus_overcurrent(uint32_t port);
  403. void send_clearstatus_reset(uint32_t port);
  404. void send_setreset(uint32_t port);
  405. static void callback(const Transfer_t *transfer);
  406. void status_change(const Transfer_t *transfer);
  407. void new_port_status(uint32_t port, uint32_t status);
  408. void start_debounce_timer(uint32_t port);
  409. void stop_debounce_timer(uint32_t port);
  410. private:
  411. Device_t mydevices[MAXPORTS];
  412. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  413. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  414. USBDriverTimer debouncetimer;
  415. USBDriverTimer resettimer;
  416. setup_t setup;
  417. Pipe_t *changepipe;
  418. Device_t *devicelist[MAXPORTS];
  419. uint32_t changebits;
  420. uint32_t statusbits;
  421. uint8_t hub_desc[16];
  422. uint8_t endpoint;
  423. uint8_t interval;
  424. uint8_t numports;
  425. uint8_t characteristics;
  426. uint8_t powertime;
  427. uint8_t sending_control_transfer;
  428. uint8_t port_doing_reset;
  429. uint8_t port_doing_reset_speed;
  430. uint8_t portstate[MAXPORTS];
  431. portbitmask_t send_pending_poweron;
  432. portbitmask_t send_pending_getstatus;
  433. portbitmask_t send_pending_clearstatus_connect;
  434. portbitmask_t send_pending_clearstatus_enable;
  435. portbitmask_t send_pending_clearstatus_suspend;
  436. portbitmask_t send_pending_clearstatus_overcurrent;
  437. portbitmask_t send_pending_clearstatus_reset;
  438. portbitmask_t send_pending_setreset;
  439. portbitmask_t debounce_in_use;
  440. static volatile bool reset_busy;
  441. };
  442. class KeyboardController : public USBDriver {
  443. public:
  444. KeyboardController(USBHost &host) { init(); }
  445. KeyboardController(USBHost *host) { init(); }
  446. int available();
  447. int read();
  448. uint16_t getKey() { return keyCode; }
  449. uint8_t getModifiers() { return modifiers; }
  450. uint8_t getOemKey() { return keyOEM; }
  451. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  452. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  453. protected:
  454. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  455. virtual void control(const Transfer_t *transfer);
  456. virtual void disconnect();
  457. static void callback(const Transfer_t *transfer);
  458. void new_data(const Transfer_t *transfer);
  459. void init();
  460. private:
  461. void update();
  462. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  463. void key_press(uint32_t mod, uint32_t key);
  464. void key_release(uint32_t mod, uint32_t key);
  465. void (*keyPressedFunction)(int unicode);
  466. void (*keyReleasedFunction)(int unicode);
  467. Pipe_t *datapipe;
  468. setup_t setup;
  469. uint8_t report[8];
  470. uint16_t keyCode;
  471. uint8_t modifiers;
  472. uint8_t keyOEM;
  473. uint8_t prev_report[8];
  474. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  475. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  476. };
  477. class MIDIDevice : public USBDriver {
  478. public:
  479. enum { SYSEX_MAX_LEN = 60 };
  480. MIDIDevice(USBHost &host) { init(); }
  481. MIDIDevice(USBHost *host) { init(); }
  482. bool read(uint8_t channel=0, uint8_t cable=0);
  483. uint8_t getType(void) {
  484. return msg_type;
  485. };
  486. uint8_t getChannel(void) {
  487. return msg_channel;
  488. };
  489. uint8_t getData1(void) {
  490. return msg_data1;
  491. };
  492. uint8_t getData2(void) {
  493. return msg_data2;
  494. };
  495. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  496. handleNoteOff = f;
  497. };
  498. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  499. handleNoteOn = f;
  500. };
  501. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  502. handleVelocityChange = f;
  503. };
  504. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  505. handleControlChange = f;
  506. };
  507. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  508. handleProgramChange = f;
  509. };
  510. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  511. handleAfterTouch = f;
  512. };
  513. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  514. handlePitchChange = f;
  515. };
  516. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  517. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  518. }
  519. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  520. handleRealTimeSystem = f;
  521. };
  522. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  523. handleTimeCodeQuarterFrame = f;
  524. };
  525. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  526. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  527. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  528. }
  529. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  530. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  531. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  532. }
  533. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  534. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  535. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  536. }
  537. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  538. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  539. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  540. }
  541. void sendProgramChange(uint32_t program, uint32_t channel) {
  542. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  543. | ((program & 0x7F) << 16));
  544. }
  545. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  546. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  547. | ((pressure & 0x7F) << 16));
  548. }
  549. void sendPitchBend(uint32_t value, uint32_t channel) {
  550. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  551. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  552. }
  553. void sendSysEx(uint32_t length, const void *data);
  554. void sendRealTime(uint32_t type) {
  555. switch (type) {
  556. case 0xF8: // Clock
  557. case 0xFA: // Start
  558. case 0xFC: // Stop
  559. case 0xFB: // Continue
  560. case 0xFE: // ActiveSensing
  561. case 0xFF: // SystemReset
  562. write_packed((type << 8) | 0x0F);
  563. break;
  564. default: // Invalid Real Time marker
  565. break;
  566. }
  567. }
  568. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  569. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  570. sendTimeCodeQuarterFrame(data);
  571. }
  572. void sendTimeCodeQuarterFrame(uint32_t data) {
  573. write_packed(0xF108 | ((data & 0x7F) << 16));
  574. }
  575. protected:
  576. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  577. virtual void disconnect();
  578. static void rx_callback(const Transfer_t *transfer);
  579. static void tx_callback(const Transfer_t *transfer);
  580. void rx_data(const Transfer_t *transfer);
  581. void tx_data(const Transfer_t *transfer);
  582. void init();
  583. void write_packed(uint32_t data);
  584. void sysex_byte(uint8_t b);
  585. private:
  586. Pipe_t *rxpipe;
  587. Pipe_t *txpipe;
  588. enum { MAX_PACKET_SIZE = 64 };
  589. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  590. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  591. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  592. uint16_t rx_size;
  593. uint16_t tx_size;
  594. uint32_t rx_queue[RX_QUEUE_SIZE];
  595. bool rx_packet_queued;
  596. uint16_t rx_head;
  597. uint16_t rx_tail;
  598. uint8_t rx_ep;
  599. uint8_t tx_ep;
  600. uint8_t msg_channel;
  601. uint8_t msg_type;
  602. uint8_t msg_data1;
  603. uint8_t msg_data2;
  604. uint8_t msg_sysex[SYSEX_MAX_LEN];
  605. uint8_t msg_sysex_len;
  606. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  607. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  608. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  609. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  610. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  611. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  612. void (*handlePitchChange)(uint8_t ch, int pitch);
  613. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  614. void (*handleRealTimeSystem)(uint8_t rtb);
  615. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  616. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  617. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  618. };
  619. #endif