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.

2118 rindas
77KB

  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__) && !defined(__IMXRT1052__) && !defined(__IMXRT1062__)
  27. #error "USBHost_t36 only works with Teensy 3.6 or Teensy 4.x. Please select it in Tools > Boards"
  28. #endif
  29. #include "utility/imxrt_usbhs.h"
  30. #include "utility/msc.h"
  31. // Dear inquisitive reader, USB is a complex protocol defined with
  32. // very specific terminology. To have any chance of understand this
  33. // source code, you absolutely must have solid knowledge of specific
  34. // USB terms such as host, device, endpoint, pipe, enumeration....
  35. // You really must also have at least a basic knowledge of the
  36. // different USB transfers: control, bulk, interrupt, isochronous.
  37. //
  38. // The USB 2.0 specification explains these in chapter 4 (pages 15
  39. // to 24), and provides more detail in the first part of chapter 5
  40. // (pages 25 to 55). The USB spec is published for free at
  41. // www.usb.org. Here is a convenient link to just the main PDF:
  42. //
  43. // https://www.pjrc.com/teensy/beta/usb20.pdf
  44. //
  45. // This is a huge file, but chapter 4 is short and easy to read.
  46. // If you're not familiar with the USB lingo, please do yourself
  47. // a favor by reading at least chapter 4 to get up to speed on the
  48. // meaning of these important USB concepts and terminology.
  49. //
  50. // If you wish to ask questions (which belong on the forum, not
  51. // github issues) or discuss development of this library, you
  52. // ABSOLUTELY MUST know the basic USB terminology from chapter 4.
  53. // Please repect other people's valuable time & effort by making
  54. // your best effort to read chapter 4 before asking USB questions!
  55. // Uncomment this line to see lots of debugging info!
  56. //#define USBHOST_PRINT_DEBUG
  57. // This can let you control where to send the debugging messages
  58. //#define USBHDBGSerial Serial1
  59. #ifndef USBHDBGSerial
  60. #define USBHDBGSerial Serial
  61. #endif
  62. /************************************************/
  63. /* Data Types */
  64. /************************************************/
  65. // These 6 types are the key to understanding how this USB Host
  66. // library really works.
  67. // USBHost is a static class controlling the hardware.
  68. // All common USB functionality is implemented here.
  69. class USBHost;
  70. // These 3 structures represent the actual USB entities
  71. // USBHost manipulates. One Device_t is created for
  72. // each active USB device. One Pipe_t is create for
  73. // each endpoint. Transfer_t structures are created
  74. // when any data transfer is added to the EHCI work
  75. // queues, and then returned to the free pool after the
  76. // data transfer completes and the driver has processed
  77. // the results.
  78. typedef struct Device_struct Device_t;
  79. typedef struct Pipe_struct Pipe_t;
  80. typedef struct Transfer_struct Transfer_t;
  81. typedef enum { CLAIM_NO=0, CLAIM_REPORT, CLAIM_INTERFACE} hidclaim_t;
  82. // All USB device drivers inherit use these classes.
  83. // Drivers build user-visible functionality on top
  84. // of these classes, which receive USB events from
  85. // USBHost.
  86. class USBDriver;
  87. class USBDriverTimer;
  88. class USBHIDInput;
  89. /************************************************/
  90. /* Added Defines */
  91. /************************************************/
  92. // Keyboard special Keys
  93. #define KEYD_UP 0xDA
  94. #define KEYD_DOWN 0xD9
  95. #define KEYD_LEFT 0xD8
  96. #define KEYD_RIGHT 0xD7
  97. #define KEYD_INSERT 0xD1
  98. #define KEYD_DELETE 0xD4
  99. #define KEYD_PAGE_UP 0xD3
  100. #define KEYD_PAGE_DOWN 0xD6
  101. #define KEYD_HOME 0xD2
  102. #define KEYD_END 0xD5
  103. #define KEYD_F1 0xC2
  104. #define KEYD_F2 0xC3
  105. #define KEYD_F3 0xC4
  106. #define KEYD_F4 0xC5
  107. #define KEYD_F5 0xC6
  108. #define KEYD_F6 0xC7
  109. #define KEYD_F7 0xC8
  110. #define KEYD_F8 0xC9
  111. #define KEYD_F9 0xCA
  112. #define KEYD_F10 0xCB
  113. #define KEYD_F11 0xCC
  114. #define KEYD_F12 0xCD
  115. // USBSerial formats - Lets encode format into bits
  116. // Bits: 0-4 - Number of data bits
  117. // Bits: 5-7 - Parity (0=none, 1=odd, 2 = even)
  118. // bits: 8-9 - Stop bits. 0=1, 1=2
  119. #define USBHOST_SERIAL_7E1 0x047
  120. #define USBHOST_SERIAL_7O1 0x027
  121. #define USBHOST_SERIAL_8N1 0x08
  122. #define USBHOST_SERIAL_8N2 0x108
  123. #define USBHOST_SERIAL_8E1 0x048
  124. #define USBHOST_SERIAL_8O1 0x028
  125. /************************************************/
  126. /* Data Structure Definitions */
  127. /************************************************/
  128. // setup_t holds the 8 byte USB SETUP packet data.
  129. // These unions & structs allow convenient access to
  130. // the setup fields.
  131. typedef union {
  132. struct {
  133. union {
  134. struct {
  135. uint8_t bmRequestType;
  136. uint8_t bRequest;
  137. };
  138. uint16_t wRequestAndType;
  139. };
  140. uint16_t wValue;
  141. uint16_t wIndex;
  142. uint16_t wLength;
  143. };
  144. struct {
  145. uint32_t word1;
  146. uint32_t word2;
  147. };
  148. } setup_t;
  149. typedef struct {
  150. enum {STRING_BUF_SIZE=50};
  151. enum {STR_ID_MAN=0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
  152. uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
  153. uint8_t buffer[STRING_BUF_SIZE];
  154. } strbuf_t;
  155. #define DEVICE_STRUCT_STRING_BUF_SIZE 50
  156. // Device_t holds all the information about a USB device
  157. struct Device_struct {
  158. Pipe_t *control_pipe;
  159. Pipe_t *data_pipes;
  160. Device_t *next;
  161. USBDriver *drivers;
  162. strbuf_t *strbuf;
  163. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  164. uint8_t address;
  165. uint8_t hub_address;
  166. uint8_t hub_port;
  167. uint8_t enum_state;
  168. uint8_t bDeviceClass;
  169. uint8_t bDeviceSubClass;
  170. uint8_t bDeviceProtocol;
  171. uint8_t bmAttributes;
  172. uint8_t bMaxPower;
  173. uint16_t idVendor;
  174. uint16_t idProduct;
  175. uint16_t LanguageID;
  176. };
  177. // Pipe_t holes all information about each USB endpoint/pipe
  178. // The first half is an EHCI QH structure for the pipe.
  179. struct Pipe_struct {
  180. // Queue Head (QH), EHCI page 46-50
  181. struct { // must be aligned to 32 byte boundary
  182. volatile uint32_t horizontal_link;
  183. volatile uint32_t capabilities[2];
  184. volatile uint32_t current;
  185. volatile uint32_t next;
  186. volatile uint32_t alt_next;
  187. volatile uint32_t token;
  188. volatile uint32_t buffer[5];
  189. } qh;
  190. Device_t *device;
  191. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  192. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  193. uint8_t start_mask;
  194. uint8_t complete_mask;
  195. Pipe_t *next;
  196. void (*callback_function)(const Transfer_t *);
  197. uint16_t periodic_interval;
  198. uint16_t periodic_offset;
  199. uint16_t bandwidth_interval;
  200. uint16_t bandwidth_offset;
  201. uint16_t bandwidth_shift;
  202. uint8_t bandwidth_stime;
  203. uint8_t bandwidth_ctime;
  204. uint32_t unused1;
  205. uint32_t unused2;
  206. uint32_t unused3;
  207. uint32_t unused4;
  208. uint32_t unused5;
  209. };
  210. // Transfer_t represents a single transaction on the USB bus.
  211. // The first portion is an EHCI qTD structure. Transfer_t are
  212. // allocated as-needed from a memory pool, loaded with pointers
  213. // to the actual data buffers, linked into a followup list,
  214. // and placed on ECHI Queue Heads. When the ECHI interrupt
  215. // occurs, the followup lists are used to find the Transfer_t
  216. // in memory. Callbacks are made, and then the Transfer_t are
  217. // returned to the memory pool.
  218. struct Transfer_struct {
  219. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  220. struct { // must be aligned to 32 byte boundary
  221. volatile uint32_t next;
  222. volatile uint32_t alt_next;
  223. volatile uint32_t token;
  224. volatile uint32_t buffer[5];
  225. } qtd;
  226. // Linked list of queued, not-yet-completed transfers
  227. Transfer_t *next_followup;
  228. Transfer_t *prev_followup;
  229. Pipe_t *pipe;
  230. // Data to be used by callback function. When a group
  231. // of Transfer_t are created, these fields and the
  232. // interrupt-on-complete bit in the qTD token are only
  233. // set in the last Transfer_t of the list.
  234. void *buffer;
  235. uint32_t length;
  236. setup_t setup;
  237. USBDriver *driver;
  238. };
  239. /************************************************/
  240. /* Main USB EHCI Controller */
  241. /************************************************/
  242. class USBHost {
  243. public:
  244. static void begin();
  245. static void Task();
  246. static void countFree(uint32_t &devices, uint32_t &pipes, uint32_t &trans, uint32_t &strs);
  247. protected:
  248. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  249. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  250. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  251. void *buf, USBDriver *driver);
  252. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  253. uint32_t len, USBDriver *driver);
  254. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  255. static void disconnect_Device(Device_t *dev);
  256. static void enumeration(const Transfer_t *transfer);
  257. static void driver_ready_for_device(USBDriver *driver);
  258. static volatile bool enumeration_busy;
  259. public: // Maybe others may want/need to contribute memory example HID devices may want to add transfers.
  260. static void contribute_Devices(Device_t *devices, uint32_t num);
  261. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  262. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  263. static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
  264. private:
  265. static void isr();
  266. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  267. static void claim_drivers(Device_t *dev);
  268. static uint32_t assign_address(void);
  269. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  270. static void init_Device_Pipe_Transfer_memory(void);
  271. static Device_t * allocate_Device(void);
  272. static void delete_Pipe(Pipe_t *pipe);
  273. static void free_Device(Device_t *q);
  274. static Pipe_t * allocate_Pipe(void);
  275. static void free_Pipe(Pipe_t *q);
  276. static Transfer_t * allocate_Transfer(void);
  277. static void free_Transfer(Transfer_t *q);
  278. static strbuf_t * allocate_string_buffer(void);
  279. static void free_string_buffer(strbuf_t *strbuf);
  280. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  281. uint32_t maxlen, uint32_t interval);
  282. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  283. static bool followup_Transfer(Transfer_t *transfer);
  284. static void followup_Error(void);
  285. protected:
  286. #ifdef USBHOST_PRINT_DEBUG
  287. static void print_(const Transfer_t *transfer);
  288. static void print_(const Transfer_t *first, const Transfer_t *last);
  289. static void print_token(uint32_t token);
  290. static void print_(const Pipe_t *pipe);
  291. static void print_driverlist(const char *name, const USBDriver *driver);
  292. static void print_qh_list(const Pipe_t *list);
  293. static void print_device_descriptor(const uint8_t *p);
  294. static void print_config_descriptor(const uint8_t *p, uint32_t maxlen);
  295. static void print_string_descriptor(const char *name, const uint8_t *p);
  296. static void print_hexbytes(const void *ptr, uint32_t len);
  297. static void print_(const char *s) { USBHDBGSerial.print(s); }
  298. static void print_(int n) { USBHDBGSerial.print(n); }
  299. static void print_(unsigned int n) { USBHDBGSerial.print(n); }
  300. static void print_(long n) { USBHDBGSerial.print(n); }
  301. static void print_(unsigned long n) { USBHDBGSerial.print(n); }
  302. static void println_(const char *s) { USBHDBGSerial.println(s); }
  303. static void println_(int n) { USBHDBGSerial.println(n); }
  304. static void println_(unsigned int n) { USBHDBGSerial.println(n); }
  305. static void println_(long n) { USBHDBGSerial.println(n); }
  306. static void println_(unsigned long n) { USBHDBGSerial.println(n); }
  307. static void println_() { USBHDBGSerial.println(); }
  308. static void print_(uint32_t n, uint8_t b) { USBHDBGSerial.print(n, b); }
  309. static void println_(uint32_t n, uint8_t b) { USBHDBGSerial.println(n, b); }
  310. static void print_(const char *s, int n, uint8_t b = DEC) {
  311. USBHDBGSerial.print(s); USBHDBGSerial.print(n, b); }
  312. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  313. USBHDBGSerial.print(s); USBHDBGSerial.print(n, b); }
  314. static void print_(const char *s, long n, uint8_t b = DEC) {
  315. USBHDBGSerial.print(s); USBHDBGSerial.print(n, b); }
  316. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  317. USBHDBGSerial.print(s); USBHDBGSerial.print(n, b); }
  318. static void println_(const char *s, int n, uint8_t b = DEC) {
  319. USBHDBGSerial.print(s); USBHDBGSerial.println(n, b); }
  320. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  321. USBHDBGSerial.print(s); USBHDBGSerial.println(n, b); }
  322. static void println_(const char *s, long n, uint8_t b = DEC) {
  323. USBHDBGSerial.print(s); USBHDBGSerial.println(n, b); }
  324. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  325. USBHDBGSerial.print(s); USBHDBGSerial.println(n, b); }
  326. friend class USBDriverTimer; // for access to print & println
  327. #else
  328. static void print_(const Transfer_t *transfer) {}
  329. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  330. static void print_token(uint32_t token) {}
  331. static void print_(const Pipe_t *pipe) {}
  332. static void print_driverlist(const char *name, const USBDriver *driver) {}
  333. static void print_qh_list(const Pipe_t *list) {}
  334. static void print_device_descriptor(const uint8_t *p) {}
  335. static void print_config_descriptor(const uint8_t *p, uint32_t maxlen) {}
  336. static void print_string_descriptor(const char *name, const uint8_t *p) {}
  337. static void print_hexbytes(const void *ptr, uint32_t len) {}
  338. static void print_(const char *s) {}
  339. static void print_(int n) {}
  340. static void print_(unsigned int n) {}
  341. static void print_(long n) {}
  342. static void print_(unsigned long n) {}
  343. static void println_(const char *s) {}
  344. static void println_(int n) {}
  345. static void println_(unsigned int n) {}
  346. static void println_(long n) {}
  347. static void println_(unsigned long n) {}
  348. static void println_() {}
  349. static void print_(uint32_t n, uint8_t b) {}
  350. static void println_(uint32_t n, uint8_t b) {}
  351. static void print_(const char *s, int n, uint8_t b = DEC) {}
  352. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  353. static void print_(const char *s, long n, uint8_t b = DEC) {}
  354. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  355. static void println_(const char *s, int n, uint8_t b = DEC) {}
  356. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  357. static void println_(const char *s, long n, uint8_t b = DEC) {}
  358. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  359. #endif
  360. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  361. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  362. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  363. s.word2 = wIndex | (wLength << 16);
  364. }
  365. };
  366. /************************************************/
  367. /* USB Device Driver Common Base Class */
  368. /************************************************/
  369. // All USB device drivers inherit from this base class.
  370. class USBDriver : public USBHost {
  371. public:
  372. operator bool() {
  373. Device_t *dev = *(Device_t * volatile *)&device;
  374. return dev != nullptr;
  375. }
  376. uint16_t idVendor() {
  377. Device_t *dev = *(Device_t * volatile *)&device;
  378. return (dev != nullptr) ? dev->idVendor : 0;
  379. }
  380. uint16_t idProduct() {
  381. Device_t *dev = *(Device_t * volatile *)&device;
  382. return (dev != nullptr) ? dev->idProduct : 0;
  383. }
  384. const uint8_t *manufacturer() {
  385. Device_t *dev = *(Device_t * volatile *)&device;
  386. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  387. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_MAN]];
  388. }
  389. const uint8_t *product() {
  390. Device_t *dev = *(Device_t * volatile *)&device;
  391. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  392. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_PROD]];
  393. }
  394. const uint8_t *serialNumber() {
  395. Device_t *dev = *(Device_t * volatile *)&device;
  396. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  397. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]];
  398. }
  399. protected:
  400. USBDriver() : next(NULL), device(NULL) {}
  401. // Check if a driver wishes to claim a device or interface or group
  402. // of interfaces within a device. When this function returns true,
  403. // the driver is considered bound or loaded for that device. When
  404. // new devices are detected, enumeration.cpp calls this function on
  405. // all unbound driver objects, to give them an opportunity to bind
  406. // to the new device.
  407. // device has its vid&pid, class/subclass fields initialized
  408. // type is 0 for device level, 1 for interface level, 2 for IAD
  409. // descriptors points to the specific descriptor data
  410. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  411. // When an unknown (not chapter 9) control transfer completes, this
  412. // function is called for all drivers bound to the device. Return
  413. // true means this driver originated this control transfer, so no
  414. // more drivers need to be offered an opportunity to process it.
  415. // This function is optional, only needed if the driver uses control
  416. // transfers and wishes to be notified when they complete.
  417. virtual void control(const Transfer_t *transfer) { }
  418. // When any of the USBDriverTimer objects a driver creates generates
  419. // a timer event, this function is called.
  420. virtual void timer_event(USBDriverTimer *whichTimer) { }
  421. // When the user calls USBHost::Task, this Task function for all
  422. // active drivers is called, so they may update state and/or call
  423. // any attached user callback functions.
  424. virtual void Task() { }
  425. // When a device disconnects from the USB, this function is called.
  426. // The driver must free all resources it allocated and update any
  427. // internal state necessary to deal with the possibility of user
  428. // code continuing to call its API. However, pipes and transfers
  429. // are the handled by lower layers, so device drivers do not free
  430. // pipes they created or cancel transfers they had in progress.
  431. virtual void disconnect();
  432. // Drivers are managed by this single-linked list. All inactive
  433. // (not bound to any device) drivers are linked from
  434. // available_drivers in enumeration.cpp. When bound to a device,
  435. // drivers are linked from that Device_t drivers list.
  436. USBDriver *next;
  437. // The device this object instance is bound to. In words, this
  438. // is the specific device this driver is using. When not bound
  439. // to any device, this must be NULL. Drivers may set this to
  440. // any non-NULL value if they are in a state where they do not
  441. // wish to claim any device or interface (eg, if getting data
  442. // from the HID parser).
  443. Device_t *device;
  444. friend class USBHost;
  445. };
  446. // Device drivers may create these timer objects to schedule a timer call
  447. class USBDriverTimer {
  448. public:
  449. USBDriverTimer() { }
  450. USBDriverTimer(USBDriver *d) : driver(d) { }
  451. USBDriverTimer(USBHIDInput *hd) : driver(nullptr), hidinput(hd) { }
  452. void init(USBDriver *d) { driver = d; };
  453. void start(uint32_t microseconds);
  454. void stop();
  455. void *pointer;
  456. uint32_t integer;
  457. uint32_t started_micros; // testing only
  458. private:
  459. USBDriver *driver;
  460. USBHIDInput *hidinput;
  461. uint32_t usec;
  462. USBDriverTimer *next;
  463. USBDriverTimer *prev;
  464. friend class USBHost;
  465. };
  466. // Device drivers may inherit from this base class, if they wish to receive
  467. // HID input data fully decoded by the USBHIDParser driver
  468. class USBHIDParser;
  469. class USBHIDInput {
  470. public:
  471. operator bool() { return (mydevice != nullptr); }
  472. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  473. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  474. const uint8_t *manufacturer()
  475. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  476. const uint8_t *product()
  477. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  478. const uint8_t *serialNumber()
  479. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  480. private:
  481. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  482. virtual bool hid_process_in_data(const Transfer_t *transfer) {return false;}
  483. virtual bool hid_process_out_data(const Transfer_t *transfer) {return false;}
  484. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  485. virtual void hid_input_data(uint32_t usage, int32_t value);
  486. virtual void hid_input_end();
  487. virtual void disconnect_collection(Device_t *dev);
  488. virtual void hid_timer_event(USBDriverTimer *whichTimer) { }
  489. void add_to_list();
  490. USBHIDInput *next = NULL;
  491. friend class USBHIDParser;
  492. protected:
  493. Device_t *mydevice = NULL;
  494. };
  495. // Device drivers may inherit from this base class, if they wish to receive
  496. // HID input like data from Bluetooth HID device.
  497. class BluetoothController;
  498. class BTHIDInput {
  499. public:
  500. operator bool() { return (btdevice != nullptr); }
  501. uint16_t idVendor() { return (btdevice != nullptr) ? btdevice->idVendor : 0; }
  502. uint16_t idProduct() { return (btdevice != nullptr) ? btdevice->idProduct : 0; }
  503. const uint8_t *manufacturer()
  504. { return ((btdevice == nullptr) || (btdevice->strbuf == nullptr)) ? nullptr : &btdevice->strbuf->buffer[btdevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  505. const uint8_t *product()
  506. { return remote_name_; }
  507. const uint8_t *serialNumber()
  508. { return ((btdevice == nullptr) || (btdevice->strbuf == nullptr)) ? nullptr : &btdevice->strbuf->buffer[btdevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  509. private:
  510. virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class, uint8_t *remoteName) {return false;}
  511. virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length) {return false;}
  512. virtual void release_bluetooth() {};
  513. virtual bool remoteNameComplete(const uint8_t *remoteName) {return true;}
  514. virtual void connectionComplete(void) {};
  515. void add_to_list();
  516. BTHIDInput *next = NULL;
  517. friend class BluetoothController;
  518. protected:
  519. enum {SP_NEED_CONNECT=0x1, SP_DONT_NEED_CONNECT=0x02, SP_PS3_IDS=0x4};
  520. enum {REMOTE_NAME_SIZE=32};
  521. uint8_t special_process_required = 0;
  522. Device_t *btdevice = NULL;
  523. uint8_t remote_name_[REMOTE_NAME_SIZE] = {0};
  524. };
  525. /************************************************/
  526. /* USB Device Drivers */
  527. /************************************************/
  528. class USBHub : public USBDriver {
  529. public:
  530. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  531. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  532. // Hubs with more more than 7 ports are built from two tiers of hubs
  533. // using 4 or 7 port hub chips. While the USB spec seems to allow
  534. // hubs to have up to 255 ports, in practice all hub chips on the
  535. // market are only 2, 3, 4 or 7 ports.
  536. enum { MAXPORTS = 7 };
  537. typedef uint8_t portbitmask_t;
  538. enum {
  539. PORT_OFF = 0,
  540. PORT_DISCONNECT = 1,
  541. PORT_DEBOUNCE1 = 2,
  542. PORT_DEBOUNCE2 = 3,
  543. PORT_DEBOUNCE3 = 4,
  544. PORT_DEBOUNCE4 = 5,
  545. PORT_DEBOUNCE5 = 6,
  546. PORT_RESET = 7,
  547. PORT_RECOVERY = 8,
  548. PORT_ACTIVE = 9
  549. };
  550. protected:
  551. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  552. virtual void control(const Transfer_t *transfer);
  553. virtual void timer_event(USBDriverTimer *whichTimer);
  554. virtual void disconnect();
  555. void init();
  556. bool can_send_control_now();
  557. void send_poweron(uint32_t port);
  558. void send_getstatus(uint32_t port);
  559. void send_clearstatus_connect(uint32_t port);
  560. void send_clearstatus_enable(uint32_t port);
  561. void send_clearstatus_suspend(uint32_t port);
  562. void send_clearstatus_overcurrent(uint32_t port);
  563. void send_clearstatus_reset(uint32_t port);
  564. void send_setreset(uint32_t port);
  565. void send_setinterface();
  566. static void callback(const Transfer_t *transfer);
  567. void status_change(const Transfer_t *transfer);
  568. void new_port_status(uint32_t port, uint32_t status);
  569. void start_debounce_timer(uint32_t port);
  570. void stop_debounce_timer(uint32_t port);
  571. private:
  572. Device_t mydevices[MAXPORTS];
  573. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  574. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  575. strbuf_t mystring_bufs[1];
  576. USBDriverTimer debouncetimer;
  577. USBDriverTimer resettimer;
  578. setup_t setup;
  579. Pipe_t *changepipe;
  580. Device_t *devicelist[MAXPORTS];
  581. uint32_t changebits;
  582. uint32_t statusbits;
  583. uint8_t hub_desc[16];
  584. uint8_t interface_count;
  585. uint8_t interface_number;
  586. uint8_t altsetting;
  587. uint8_t protocol;
  588. uint8_t endpoint;
  589. uint8_t interval;
  590. uint8_t numports;
  591. uint8_t characteristics;
  592. uint8_t powertime;
  593. uint8_t sending_control_transfer;
  594. uint8_t port_doing_reset;
  595. uint8_t port_doing_reset_speed;
  596. uint8_t portstate[MAXPORTS];
  597. portbitmask_t send_pending_poweron;
  598. portbitmask_t send_pending_getstatus;
  599. portbitmask_t send_pending_clearstatus_connect;
  600. portbitmask_t send_pending_clearstatus_enable;
  601. portbitmask_t send_pending_clearstatus_suspend;
  602. portbitmask_t send_pending_clearstatus_overcurrent;
  603. portbitmask_t send_pending_clearstatus_reset;
  604. portbitmask_t send_pending_setreset;
  605. portbitmask_t debounce_in_use;
  606. static volatile bool reset_busy;
  607. };
  608. //--------------------------------------------------------------------------
  609. class USBHIDParser : public USBDriver {
  610. public:
  611. USBHIDParser(USBHost &host) : hidTimer(this) { init(); }
  612. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  613. bool sendPacket(const uint8_t *buffer, int cb=-1);
  614. void setTXBuffers(uint8_t *buffer1, uint8_t *buffer2, uint8_t cb);
  615. bool sendControlPacket(uint32_t bmRequestType, uint32_t bRequest,
  616. uint32_t wValue, uint32_t wIndex, uint32_t wLength, void *buf);
  617. // Atempt for RAWhid and SEREMU to take over processing of data
  618. //
  619. uint16_t inSize(void) {return in_size;}
  620. uint16_t outSize(void) {return out_size;}
  621. void startTimer(uint32_t microseconds) {hidTimer.start(microseconds);}
  622. void stopTimer() {hidTimer.stop();}
  623. uint8_t interfaceNumber() { return bInterfaceNumber;}
  624. protected:
  625. enum { TOPUSAGE_LIST_LEN = 4 };
  626. enum { USAGE_LIST_LEN = 24 };
  627. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  628. virtual void control(const Transfer_t *transfer);
  629. virtual void disconnect();
  630. static void in_callback(const Transfer_t *transfer);
  631. static void out_callback(const Transfer_t *transfer);
  632. virtual void timer_event(USBDriverTimer *whichTimer);
  633. void in_data(const Transfer_t *transfer);
  634. void out_data(const Transfer_t *transfer);
  635. bool check_if_using_report_id();
  636. void parse();
  637. USBHIDInput * find_driver(uint32_t topusage);
  638. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  639. void init();
  640. uint8_t activeSendMask(void) {return txstate;}
  641. private:
  642. Pipe_t *in_pipe;
  643. Pipe_t *out_pipe;
  644. static USBHIDInput *available_hid_drivers_list;
  645. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  646. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  647. uint16_t in_size;
  648. uint16_t out_size;
  649. setup_t setup;
  650. uint8_t descriptor[800];
  651. uint8_t report[64];
  652. uint16_t descsize;
  653. bool use_report_id;
  654. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  655. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  656. strbuf_t mystring_bufs[1];
  657. uint8_t txstate = 0;
  658. uint8_t *tx1 = nullptr;
  659. uint8_t *tx2 = nullptr;
  660. bool hid_driver_claimed_control_ = false;
  661. USBDriverTimer hidTimer;
  662. uint8_t bInterfaceNumber = 0;
  663. };
  664. //--------------------------------------------------------------------------
  665. class KeyboardController : public USBDriver , public USBHIDInput, public BTHIDInput {
  666. public:
  667. typedef union {
  668. struct {
  669. uint8_t numLock : 1;
  670. uint8_t capsLock : 1;
  671. uint8_t scrollLock : 1;
  672. uint8_t compose : 1;
  673. uint8_t kana : 1;
  674. uint8_t reserved : 3;
  675. };
  676. uint8_t byte;
  677. } KBDLeds_t;
  678. public:
  679. KeyboardController(USBHost &host) { init(); }
  680. KeyboardController(USBHost *host) { init(); }
  681. // need their own versions as both USBDriver and USBHIDInput provide
  682. uint16_t idVendor();
  683. uint16_t idProduct();
  684. const uint8_t *manufacturer();
  685. const uint8_t *product();
  686. const uint8_t *serialNumber();
  687. operator bool() { return ((device != nullptr) || (btdevice != nullptr)); }
  688. // Main boot keyboard functions.
  689. uint16_t getKey() { return keyCode; }
  690. uint8_t getModifiers() { return modifiers; }
  691. uint8_t getOemKey() { return keyOEM; }
  692. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  693. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  694. void attachRawPress(void (*f)(uint8_t keycode)) { rawKeyPressedFunction = f; }
  695. void attachRawRelease(void (*f)(uint8_t keycode)) { rawKeyReleasedFunction = f; }
  696. void LEDS(uint8_t leds);
  697. uint8_t LEDS() {return leds_.byte;}
  698. void updateLEDS(void);
  699. bool numLock() {return leds_.numLock;}
  700. bool capsLock() {return leds_.capsLock;}
  701. bool scrollLock() {return leds_.scrollLock;}
  702. void numLock(bool f);
  703. void capsLock(bool f);
  704. void scrollLock(bool f);
  705. // Added for extras information.
  706. void attachExtrasPress(void (*f)(uint32_t top, uint16_t code)) { extrasKeyPressedFunction = f; }
  707. void attachExtrasRelease(void (*f)(uint32_t top, uint16_t code)) { extrasKeyReleasedFunction = f; }
  708. void forceBootProtocol();
  709. enum {MAX_KEYS_DOWN=4};
  710. protected:
  711. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  712. virtual void control(const Transfer_t *transfer);
  713. virtual void disconnect();
  714. static void callback(const Transfer_t *transfer);
  715. void new_data(const Transfer_t *transfer);
  716. void init();
  717. // Bluetooth data
  718. virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class, uint8_t *remoteName);
  719. virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length);
  720. virtual bool remoteNameComplete(const uint8_t *remoteName);
  721. virtual void release_bluetooth();
  722. protected: // HID functions for extra keyboard data.
  723. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  724. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  725. virtual void hid_input_data(uint32_t usage, int32_t value);
  726. virtual void hid_input_end();
  727. virtual void disconnect_collection(Device_t *dev);
  728. private:
  729. void update();
  730. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  731. void key_press(uint32_t mod, uint32_t key);
  732. void key_release(uint32_t mod, uint32_t key);
  733. void (*keyPressedFunction)(int unicode);
  734. void (*keyReleasedFunction)(int unicode);
  735. void (*rawKeyPressedFunction)(uint8_t keycode) = nullptr;
  736. void (*rawKeyReleasedFunction)(uint8_t keycode) = nullptr;
  737. Pipe_t *datapipe;
  738. setup_t setup;
  739. uint8_t report[8];
  740. uint16_t keyCode;
  741. uint8_t modifiers;
  742. uint8_t keyOEM;
  743. uint8_t prev_report[8];
  744. KBDLeds_t leds_ = {0};
  745. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  746. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  747. strbuf_t mystring_bufs[1];
  748. // Added to process secondary HID data.
  749. void (*extrasKeyPressedFunction)(uint32_t top, uint16_t code);
  750. void (*extrasKeyReleasedFunction)(uint32_t top, uint16_t code);
  751. uint32_t topusage_ = 0; // What top report am I processing?
  752. uint8_t collections_claimed_ = 0;
  753. volatile bool hid_input_begin_ = false;
  754. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  755. uint8_t count_keys_down_ = 0;
  756. uint16_t keys_down[MAX_KEYS_DOWN];
  757. bool force_boot_protocol; // User or VID/PID said force boot protocol?
  758. bool control_queued;
  759. };
  760. class MouseController : public USBHIDInput, public BTHIDInput {
  761. public:
  762. MouseController(USBHost &host) { init(); }
  763. bool available() { return mouseEvent; }
  764. void mouseDataClear();
  765. uint8_t getButtons() { return buttons; }
  766. int getMouseX() { return mouseX; }
  767. int getMouseY() { return mouseY; }
  768. int getWheel() { return wheel; }
  769. int getWheelH() { return wheelH; }
  770. protected:
  771. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  772. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  773. virtual void hid_input_data(uint32_t usage, int32_t value);
  774. virtual void hid_input_end();
  775. virtual void disconnect_collection(Device_t *dev);
  776. // Bluetooth data
  777. virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class, uint8_t *remoteName);
  778. virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length);
  779. virtual void release_bluetooth();
  780. private:
  781. void init();
  782. BluetoothController *btdriver_ = nullptr;
  783. uint8_t collections_claimed = 0;
  784. volatile bool mouseEvent = false;
  785. volatile bool hid_input_begin_ = false;
  786. uint8_t buttons = 0;
  787. int mouseX = 0;
  788. int mouseY = 0;
  789. int wheel = 0;
  790. int wheelH = 0;
  791. };
  792. //--------------------------------------------------------------------------
  793. class DigitizerController : public USBHIDInput, public BTHIDInput {
  794. public:
  795. DigitizerController(USBHost &host) { init(); }
  796. bool available() { return digitizerEvent; }
  797. void digitizerDataClear();
  798. uint8_t getButtons() { return buttons; }
  799. int getMouseX() { return mouseX; }
  800. int getMouseY() { return mouseY; }
  801. int getWheel() { return wheel; }
  802. int getWheelH() { return wheelH; }
  803. int getAxis(uint32_t index) { return (index < (sizeof(digiAxes)/sizeof(digiAxes[0]))) ? digiAxes[index] : 0; }
  804. protected:
  805. virtual hidclaim_t claim_collection(USBHIDParser *driver, 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. void init();
  812. uint8_t collections_claimed = 0;
  813. volatile bool digitizerEvent = false;
  814. volatile bool hid_input_begin_ = false;
  815. uint8_t buttons = 0;
  816. int mouseX = 0;
  817. int mouseY = 0;
  818. int wheel = 0;
  819. int wheelH = 0;
  820. int digiAxes[16];
  821. };
  822. //--------------------------------------------------------------------------
  823. class JoystickController : public USBDriver, public USBHIDInput, public BTHIDInput {
  824. public:
  825. JoystickController(USBHost &host) { init(); }
  826. uint16_t idVendor();
  827. uint16_t idProduct();
  828. const uint8_t *manufacturer();
  829. const uint8_t *product();
  830. const uint8_t *serialNumber();
  831. operator bool() { return (((device != nullptr) || (mydevice != nullptr || (btdevice != nullptr))) && connected_); } // override as in both USBDriver and in USBHIDInput
  832. bool available() { return joystickEvent; }
  833. void joystickDataClear();
  834. uint32_t getButtons() { return buttons; }
  835. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  836. uint64_t axisMask() {return axis_mask_;}
  837. uint64_t axisChangedMask() { return axis_changed_mask_;}
  838. uint64_t axisChangeNotifyMask() {return axis_change_notify_mask_;}
  839. void axisChangeNotifyMask(uint64_t notify_mask) {axis_change_notify_mask_ = notify_mask;}
  840. // set functions functionality depends on underlying joystick.
  841. bool setRumble(uint8_t lValue, uint8_t rValue, uint8_t timeout=0xff);
  842. // setLEDs on PS4(RGB), PS3 simple LED setting (only uses lb)
  843. bool setLEDs(uint8_t lr, uint8_t lg, uint8_t lb); // sets Leds,
  844. bool inline setLEDs(uint32_t leds) {return setLEDs((leds >> 16) & 0xff, (leds >> 8) & 0xff, leds & 0xff);} // sets Leds - passing one arg for all leds
  845. enum { STANDARD_AXIS_COUNT = 10, ADDITIONAL_AXIS_COUNT = 54, TOTAL_AXIS_COUNT = (STANDARD_AXIS_COUNT+ADDITIONAL_AXIS_COUNT) };
  846. typedef enum { UNKNOWN=0, PS3, PS4, XBOXONE, XBOX360, PS3_MOTION, SpaceNav, SWITCH} joytype_t;
  847. joytype_t joystickType() {return joystickType_;}
  848. // PS3 pair function. hack, requires that it be connect4ed by USB and we have the address of the Bluetooth dongle...
  849. bool PS3Pair(uint8_t* bdaddr);
  850. protected:
  851. // From USBDriver
  852. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  853. virtual void control(const Transfer_t *transfer);
  854. virtual void disconnect();
  855. // From USBHIDInput
  856. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  857. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  858. virtual void hid_input_data(uint32_t usage, int32_t value);
  859. virtual void hid_input_end();
  860. virtual void disconnect_collection(Device_t *dev);
  861. virtual bool hid_process_out_data(const Transfer_t *transfer);
  862. // Bluetooth data
  863. virtual bool claim_bluetooth(BluetoothController *driver, uint32_t bluetooth_class, uint8_t *remoteName);
  864. virtual bool process_bluetooth_HID_data(const uint8_t *data, uint16_t length);
  865. virtual void release_bluetooth();
  866. virtual bool remoteNameComplete(const uint8_t *remoteName);
  867. virtual void connectionComplete(void);
  868. joytype_t joystickType_ = UNKNOWN;
  869. private:
  870. // Class specific
  871. void init();
  872. USBHIDParser *driver_ = nullptr;
  873. BluetoothController *btdriver_ = nullptr;
  874. joytype_t mapVIDPIDtoJoystickType(uint16_t idVendor, uint16_t idProduct, bool exclude_hid_devices);
  875. bool transmitPS4UserFeedbackMsg();
  876. bool transmitPS3UserFeedbackMsg();
  877. bool transmitPS3MotionUserFeedbackMsg();
  878. bool mapNameToJoystickType(const uint8_t *remoteName);
  879. bool anychange = false;
  880. volatile bool joystickEvent = false;
  881. uint32_t buttons = 0;
  882. int axis[TOTAL_AXIS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  883. uint64_t axis_mask_ = 0; // which axis have valid data
  884. uint64_t axis_changed_mask_ = 0;
  885. uint64_t axis_change_notify_mask_ = 0x3ff; // assume the low 10 values only.
  886. uint16_t additional_axis_usage_page_ = 0;
  887. uint16_t additional_axis_usage_start_ = 0;
  888. uint16_t additional_axis_usage_count_ = 0;
  889. // State values to output to Joystick.
  890. uint8_t rumble_lValue_ = 0;
  891. uint8_t rumble_rValue_ = 0;
  892. uint8_t rumble_timeout_ = 0;
  893. uint8_t leds_[3] = {0,0,0};
  894. uint8_t connected_ = 0; // what type of device if any is connected xbox 360...
  895. // Used by HID code
  896. uint8_t collections_claimed = 0;
  897. // Used by USBDriver code
  898. static void rx_callback(const Transfer_t *transfer);
  899. static void tx_callback(const Transfer_t *transfer);
  900. void rx_data(const Transfer_t *transfer);
  901. void tx_data(const Transfer_t *transfer);
  902. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  903. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  904. strbuf_t mystring_bufs[1];
  905. uint8_t rx_ep_ = 0; // remember which end point this object is...
  906. uint16_t rx_size_ = 0;
  907. uint16_t tx_size_ = 0;
  908. Pipe_t *rxpipe_;
  909. Pipe_t *txpipe_;
  910. uint8_t rxbuf_[64]; // receive circular buffer
  911. uint8_t txbuf_[64]; // buffer to use to send commands to joystick
  912. // Mapping table to say which devices we handle
  913. typedef struct {
  914. uint16_t idVendor;
  915. uint16_t idProduct;
  916. joytype_t joyType;
  917. bool hidDevice;
  918. } product_vendor_mapping_t;
  919. static product_vendor_mapping_t pid_vid_mapping[];
  920. };
  921. //--------------------------------------------------------------------------
  922. class MIDIDeviceBase : public USBDriver {
  923. public:
  924. enum { SYSEX_MAX_LEN = 290 };
  925. // Message type names for compatibility with Arduino MIDI library 4.3.1
  926. enum MidiType {
  927. InvalidType = 0x00, // For notifying errors
  928. NoteOff = 0x80, // Note Off
  929. NoteOn = 0x90, // Note On
  930. AfterTouchPoly = 0xA0, // Polyphonic AfterTouch
  931. ControlChange = 0xB0, // Control Change / Channel Mode
  932. ProgramChange = 0xC0, // Program Change
  933. AfterTouchChannel = 0xD0, // Channel (monophonic) AfterTouch
  934. PitchBend = 0xE0, // Pitch Bend
  935. SystemExclusive = 0xF0, // System Exclusive
  936. TimeCodeQuarterFrame = 0xF1, // System Common - MIDI Time Code Quarter Frame
  937. SongPosition = 0xF2, // System Common - Song Position Pointer
  938. SongSelect = 0xF3, // System Common - Song Select
  939. TuneRequest = 0xF6, // System Common - Tune Request
  940. Clock = 0xF8, // System Real Time - Timing Clock
  941. Start = 0xFA, // System Real Time - Start
  942. Continue = 0xFB, // System Real Time - Continue
  943. Stop = 0xFC, // System Real Time - Stop
  944. ActiveSensing = 0xFE, // System Real Time - Active Sensing
  945. SystemReset = 0xFF, // System Real Time - System Reset
  946. };
  947. MIDIDeviceBase(USBHost &host, uint32_t *rx, uint32_t *tx1, uint32_t *tx2,
  948. uint16_t bufsize, uint32_t *rqueue, uint16_t qsize) :
  949. txtimer(this), rx_buffer(rx), tx_buffer1(tx1), tx_buffer2(tx2),
  950. rx_queue(rqueue), max_packet_size(bufsize), rx_queue_size(qsize) {
  951. init();
  952. }
  953. void sendNoteOff(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  954. send(0x80, note, velocity, channel, cable);
  955. }
  956. void sendNoteOn(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  957. send(0x90, note, velocity, channel, cable);
  958. }
  959. void sendPolyPressure(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  960. send(0xA0, note, pressure, channel, cable);
  961. }
  962. void sendAfterTouchPoly(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  963. send(0xA0, note, pressure, channel, cable);
  964. }
  965. void sendControlChange(uint8_t control, uint8_t value, uint8_t channel, uint8_t cable=0) {
  966. send(0xB0, control, value, channel, cable);
  967. }
  968. void sendProgramChange(uint8_t program, uint8_t channel, uint8_t cable=0) {
  969. send(0xC0, program, 0, channel, cable);
  970. }
  971. void sendAfterTouch(uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  972. send(0xD0, pressure, 0, channel, cable);
  973. }
  974. void sendPitchBend(int value, uint8_t channel, uint8_t cable=0) {
  975. if (value < -8192) {
  976. value = -8192;
  977. } else if (value > 8191) {
  978. value = 8191;
  979. }
  980. value += 8192;
  981. send(0xE0, value, value >> 7, channel, cable);
  982. }
  983. void sendSysEx(uint32_t length, const uint8_t *data, bool hasTerm=false, uint8_t cable=0) {
  984. //if (cable >= MIDI_NUM_CABLES) return;
  985. if (hasTerm) {
  986. send_sysex_buffer_has_term(data, length, cable);
  987. } else {
  988. send_sysex_add_term_bytes(data, length, cable);
  989. }
  990. }
  991. void sendRealTime(uint8_t type, uint8_t cable=0) {
  992. switch (type) {
  993. case 0xF8: // Clock
  994. case 0xFA: // Start
  995. case 0xFB: // Continue
  996. case 0xFC: // Stop
  997. case 0xFE: // ActiveSensing
  998. case 0xFF: // SystemReset
  999. send(type, 0, 0, 0, cable);
  1000. break;
  1001. default: // Invalid Real Time marker
  1002. break;
  1003. }
  1004. }
  1005. void sendTimeCodeQuarterFrame(uint8_t type, uint8_t value, uint8_t cable=0) {
  1006. send(0xF1, ((type & 0x07) << 4) | (value & 0x0F), 0, 0, cable);
  1007. }
  1008. void sendSongPosition(uint16_t beats, uint8_t cable=0) {
  1009. send(0xF2, beats, beats >> 7, 0, cable);
  1010. }
  1011. void sendSongSelect(uint8_t song, uint8_t cable=0) {
  1012. send(0xF3, song, 0, 0, cable);
  1013. }
  1014. void sendTuneRequest(uint8_t cable=0) {
  1015. send(0xF6, 0, 0, 0, cable);
  1016. }
  1017. void beginRpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  1018. sendControlChange(101, number >> 7, channel, cable);
  1019. sendControlChange(100, number, channel, cable);
  1020. }
  1021. void sendRpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  1022. sendControlChange(6, value >> 7, channel, cable);
  1023. sendControlChange(38, value, channel, cable);
  1024. }
  1025. void sendRpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  1026. sendControlChange(96, amount, channel, cable);
  1027. }
  1028. void sendRpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  1029. sendControlChange(97, amount, channel, cable);
  1030. }
  1031. void endRpn(uint8_t channel, uint8_t cable=0) {
  1032. sendControlChange(101, 0x7F, channel, cable);
  1033. sendControlChange(100, 0x7F, channel, cable);
  1034. }
  1035. void beginNrpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  1036. sendControlChange(99, number >> 7, channel, cable);
  1037. sendControlChange(98, number, channel, cable);
  1038. }
  1039. void sendNrpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  1040. sendControlChange(6, value >> 7, channel, cable);
  1041. sendControlChange(38, value, channel, cable);
  1042. }
  1043. void sendNrpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  1044. sendControlChange(96, amount, channel, cable);
  1045. }
  1046. void sendNrpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  1047. sendControlChange(97, amount, channel, cable);
  1048. }
  1049. void endNrpn(uint8_t channel, uint8_t cable=0) {
  1050. sendControlChange(99, 0x7F, channel, cable);
  1051. sendControlChange(98, 0x7F, channel, cable);
  1052. }
  1053. void send(uint8_t type, uint8_t data1, uint8_t data2, uint8_t channel, uint8_t cable=0) {
  1054. //if (cable >= MIDI_NUM_CABLES) return;
  1055. if (type < 0xF0) {
  1056. if (type < 0x80) return;
  1057. type &= 0xF0;
  1058. write_packed((type << 8) | (type >> 4) | ((cable & 0x0F) << 4)
  1059. | (((channel - 1) & 0x0F) << 8) | ((data1 & 0x7F) << 16)
  1060. | ((data2 & 0x7F) << 24));
  1061. } else if (type >= 0xF8 || type == 0xF6) {
  1062. write_packed((type << 8) | 0x0F | ((cable & 0x0F) << 4));
  1063. } else if (type == 0xF1 || type == 0xF3) {
  1064. write_packed((type << 8) | 0x02 | ((cable & 0x0F) << 4)
  1065. | ((data1 & 0x7F) << 16));
  1066. } else if (type == 0xF2) {
  1067. write_packed((type << 8) | 0x03 | ((cable & 0x0F) << 4)
  1068. | ((data1 & 0x7F) << 16) | ((data2 & 0x7F) << 24));
  1069. }
  1070. }
  1071. void send_now(void) __attribute__((always_inline)) {
  1072. }
  1073. bool read(uint8_t channel=0);
  1074. uint8_t getType(void) {
  1075. return msg_type;
  1076. };
  1077. uint8_t getCable(void) {
  1078. return msg_cable;
  1079. }
  1080. uint8_t getChannel(void) {
  1081. return msg_channel;
  1082. };
  1083. uint8_t getData1(void) {
  1084. return msg_data1;
  1085. };
  1086. uint8_t getData2(void) {
  1087. return msg_data2;
  1088. };
  1089. uint8_t * getSysExArray(void) {
  1090. return msg_sysex;
  1091. }
  1092. uint16_t getSysExArrayLength(void) {
  1093. return msg_data2 << 8 | msg_data1;
  1094. }
  1095. void setHandleNoteOff(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1096. // type: 0x80 NoteOff
  1097. handleNoteOff = fptr;
  1098. }
  1099. void setHandleNoteOn(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1100. // type: 0x90 NoteOn
  1101. handleNoteOn = fptr;
  1102. }
  1103. void setHandleVelocityChange(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  1104. // type: 0xA0 AfterTouchPoly
  1105. handleVelocityChange = fptr;
  1106. }
  1107. void setHandleAfterTouchPoly(void (*fptr)(uint8_t channel, uint8_t note, uint8_t pressure)) {
  1108. // type: 0xA0 AfterTouchPoly
  1109. handleVelocityChange = fptr;
  1110. }
  1111. void setHandleControlChange(void (*fptr)(uint8_t channel, uint8_t control, uint8_t value)) {
  1112. // type: 0xB0 ControlChange
  1113. handleControlChange = fptr;
  1114. }
  1115. void setHandleProgramChange(void (*fptr)(uint8_t channel, uint8_t program)) {
  1116. // type: 0xC0 ProgramChange
  1117. handleProgramChange = fptr;
  1118. }
  1119. void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1120. // type: 0xD0 AfterTouchChannel
  1121. handleAfterTouch = fptr;
  1122. }
  1123. void setHandleAfterTouchChannel(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  1124. // type: 0xD0 AfterTouchChannel
  1125. handleAfterTouch = fptr;
  1126. }
  1127. void setHandlePitchChange(void (*fptr)(uint8_t channel, int pitch)) {
  1128. // type: 0xE0 PitchBend
  1129. handlePitchChange = fptr;
  1130. }
  1131. void setHandleSysEx(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1132. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1133. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1134. }
  1135. void setHandleSystemExclusive(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1136. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1137. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1138. }
  1139. void setHandleSystemExclusive(void (*fptr)(uint8_t *data, unsigned int size)) {
  1140. // type: 0xF0 SystemExclusive - single call, message larger than buffer is truncated
  1141. handleSysExComplete = fptr;
  1142. }
  1143. void setHandleTimeCodeQuarterFrame(void (*fptr)(uint8_t data)) {
  1144. // type: 0xF1 TimeCodeQuarterFrame
  1145. handleTimeCodeQuarterFrame = fptr;
  1146. }
  1147. void setHandleSongPosition(void (*fptr)(uint16_t beats)) {
  1148. // type: 0xF2 SongPosition
  1149. handleSongPosition = fptr;
  1150. }
  1151. void setHandleSongSelect(void (*fptr)(uint8_t songnumber)) {
  1152. // type: 0xF3 SongSelect
  1153. handleSongSelect = fptr;
  1154. }
  1155. void setHandleTuneRequest(void (*fptr)(void)) {
  1156. // type: 0xF6 TuneRequest
  1157. handleTuneRequest = fptr;
  1158. }
  1159. void setHandleClock(void (*fptr)(void)) {
  1160. // type: 0xF8 Clock
  1161. handleClock = fptr;
  1162. }
  1163. void setHandleStart(void (*fptr)(void)) {
  1164. // type: 0xFA Start
  1165. handleStart = fptr;
  1166. }
  1167. void setHandleContinue(void (*fptr)(void)) {
  1168. // type: 0xFB Continue
  1169. handleContinue = fptr;
  1170. }
  1171. void setHandleStop(void (*fptr)(void)) {
  1172. // type: 0xFC Stop
  1173. handleStop = fptr;
  1174. }
  1175. void setHandleActiveSensing(void (*fptr)(void)) {
  1176. // type: 0xFE ActiveSensing
  1177. handleActiveSensing = fptr;
  1178. }
  1179. void setHandleSystemReset(void (*fptr)(void)) {
  1180. // type: 0xFF SystemReset
  1181. handleSystemReset = fptr;
  1182. }
  1183. void setHandleRealTimeSystem(void (*fptr)(uint8_t realtimebyte)) {
  1184. // type: 0xF8-0xFF - if more specific handler not configured
  1185. handleRealTimeSystem = fptr;
  1186. }
  1187. protected:
  1188. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1189. virtual void disconnect();
  1190. virtual void timer_event(USBDriverTimer *timer);
  1191. static void rx_callback(const Transfer_t *transfer);
  1192. static void tx_callback(const Transfer_t *transfer);
  1193. void rx_data(const Transfer_t *transfer);
  1194. void tx_data(const Transfer_t *transfer);
  1195. void init();
  1196. void write_packed(uint32_t data);
  1197. void send_sysex_buffer_has_term(const uint8_t *data, uint32_t length, uint8_t cable);
  1198. void send_sysex_add_term_bytes(const uint8_t *data, uint32_t length, uint8_t cable);
  1199. void sysex_byte(uint8_t b);
  1200. private:
  1201. Pipe_t *rxpipe;
  1202. Pipe_t *txpipe;
  1203. USBDriverTimer txtimer;
  1204. //enum { MAX_PACKET_SIZE = 64 };
  1205. //enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1206. //uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  1207. //uint32_t tx_buffer1[MAX_PACKET_SIZE/4];
  1208. //uint32_t tx_buffer2[MAX_PACKET_SIZE/4];
  1209. uint32_t * const rx_buffer;
  1210. uint32_t * const tx_buffer1;
  1211. uint32_t * const tx_buffer2;
  1212. uint16_t rx_size;
  1213. uint16_t tx_size;
  1214. //uint32_t rx_queue[RX_QUEUE_SIZE];
  1215. uint32_t * const rx_queue;
  1216. bool rx_packet_queued;
  1217. const uint16_t max_packet_size;
  1218. const uint16_t rx_queue_size;
  1219. uint16_t rx_head;
  1220. uint16_t rx_tail;
  1221. volatile uint8_t tx1_count;
  1222. volatile uint8_t tx2_count;
  1223. uint8_t rx_ep;
  1224. uint8_t tx_ep;
  1225. uint8_t rx_ep_type;
  1226. uint8_t tx_ep_type;
  1227. uint8_t msg_cable;
  1228. uint8_t msg_channel;
  1229. uint8_t msg_type;
  1230. uint8_t msg_data1;
  1231. uint8_t msg_data2;
  1232. uint8_t msg_sysex[SYSEX_MAX_LEN];
  1233. uint16_t msg_sysex_len;
  1234. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  1235. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  1236. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  1237. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  1238. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  1239. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  1240. void (*handlePitchChange)(uint8_t ch, int pitch);
  1241. void (*handleSysExPartial)(const uint8_t *data, uint16_t length, uint8_t complete);
  1242. void (*handleSysExComplete)(uint8_t *data, unsigned int size);
  1243. void (*handleTimeCodeQuarterFrame)(uint8_t data);
  1244. void (*handleSongPosition)(uint16_t beats);
  1245. void (*handleSongSelect)(uint8_t songnumber);
  1246. void (*handleTuneRequest)(void);
  1247. void (*handleClock)(void);
  1248. void (*handleStart)(void);
  1249. void (*handleContinue)(void);
  1250. void (*handleStop)(void);
  1251. void (*handleActiveSensing)(void);
  1252. void (*handleSystemReset)(void);
  1253. void (*handleRealTimeSystem)(uint8_t rtb);
  1254. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1255. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1256. strbuf_t mystring_bufs[1];
  1257. };
  1258. class MIDIDevice : public MIDIDeviceBase {
  1259. public:
  1260. MIDIDevice(USBHost &host) :
  1261. MIDIDeviceBase(host, rx, tx1, tx2, MAX_PACKET_SIZE, queue, RX_QUEUE_SIZE) {};
  1262. // MIDIDevice(USBHost *host) : ....
  1263. private:
  1264. enum { MAX_PACKET_SIZE = 64 };
  1265. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1266. uint32_t rx[MAX_PACKET_SIZE/4];
  1267. uint32_t tx1[MAX_PACKET_SIZE/4];
  1268. uint32_t tx2[MAX_PACKET_SIZE/4];
  1269. uint32_t queue[RX_QUEUE_SIZE];
  1270. };
  1271. class MIDIDevice_BigBuffer : public MIDIDeviceBase {
  1272. public:
  1273. MIDIDevice_BigBuffer(USBHost &host) :
  1274. MIDIDeviceBase(host, rx, tx1, tx2, MAX_PACKET_SIZE, queue, RX_QUEUE_SIZE) {};
  1275. // MIDIDevice(USBHost *host) : ....
  1276. private:
  1277. enum { MAX_PACKET_SIZE = 512 };
  1278. enum { RX_QUEUE_SIZE = 400 }; // must be more than MAX_PACKET_SIZE/4
  1279. uint32_t rx[MAX_PACKET_SIZE/4];
  1280. uint32_t tx1[MAX_PACKET_SIZE/4];
  1281. uint32_t tx2[MAX_PACKET_SIZE/4];
  1282. uint32_t queue[RX_QUEUE_SIZE];
  1283. };
  1284. //--------------------------------------------------------------------------
  1285. class USBSerialBase: public USBDriver, public Stream {
  1286. public:
  1287. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  1288. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1289. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  1290. USBSerialBase(USBHost &host, uint32_t *big_buffer, uint16_t buffer_size,
  1291. uint16_t min_pipe_rxtx, uint16_t max_pipe_rxtx) :
  1292. txtimer(this),
  1293. _bigBuffer(big_buffer),
  1294. _big_buffer_size(buffer_size),
  1295. _min_rxtx(min_pipe_rxtx),
  1296. _max_rxtx(max_pipe_rxtx)
  1297. {
  1298. init();
  1299. }
  1300. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  1301. void end(void);
  1302. uint32_t writeTimeout() {return write_timeout_;}
  1303. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  1304. virtual int available(void);
  1305. virtual int peek(void);
  1306. virtual int read(void);
  1307. virtual int availableForWrite();
  1308. virtual size_t write(uint8_t c);
  1309. virtual void flush(void);
  1310. using Print::write;
  1311. protected:
  1312. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1313. virtual void control(const Transfer_t *transfer);
  1314. virtual void disconnect();
  1315. virtual void timer_event(USBDriverTimer *whichTimer);
  1316. private:
  1317. static void rx_callback(const Transfer_t *transfer);
  1318. static void tx_callback(const Transfer_t *transfer);
  1319. void rx_data(const Transfer_t *transfer);
  1320. void tx_data(const Transfer_t *transfer);
  1321. void rx_queue_packets(uint32_t head, uint32_t tail);
  1322. void init();
  1323. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  1324. bool init_buffers(uint32_t rsize, uint32_t tsize);
  1325. void ch341_setBaud(uint8_t byte_index);
  1326. private:
  1327. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1328. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1329. strbuf_t mystring_bufs[1];
  1330. USBDriverTimer txtimer;
  1331. uint32_t *_bigBuffer;
  1332. uint16_t _big_buffer_size;
  1333. uint16_t _min_rxtx;
  1334. uint16_t _max_rxtx;
  1335. setup_t setup;
  1336. uint8_t setupdata[16]; //
  1337. uint32_t baudrate;
  1338. uint32_t format_;
  1339. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  1340. Pipe_t *rxpipe;
  1341. Pipe_t *txpipe;
  1342. uint8_t *rx1; // location for first incoming packet
  1343. uint8_t *rx2; // location for second incoming packet
  1344. uint8_t *rxbuf; // receive circular buffer
  1345. uint8_t *tx1; // location for first outgoing packet
  1346. uint8_t *tx2; // location for second outgoing packet
  1347. uint8_t *txbuf;
  1348. volatile uint16_t rxhead;// receive head
  1349. volatile uint16_t rxtail;// receive tail
  1350. volatile uint16_t txhead;
  1351. volatile uint16_t txtail;
  1352. uint16_t rxsize;// size of receive circular buffer
  1353. uint16_t txsize;// size of transmit circular buffer
  1354. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  1355. volatile uint8_t txstate;
  1356. uint8_t pending_control;
  1357. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  1358. uint8_t pl2303_v1; // Which version do we have
  1359. uint8_t pl2303_v2;
  1360. uint8_t interface;
  1361. bool control_queued; // Is there already a queued control messaged
  1362. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  1363. sertype_t sertype;
  1364. typedef struct {
  1365. uint16_t idVendor;
  1366. uint16_t idProduct;
  1367. sertype_t sertype;
  1368. int claim_at_type;
  1369. } product_vendor_mapping_t;
  1370. static product_vendor_mapping_t pid_vid_mapping[];
  1371. };
  1372. class USBSerial : public USBSerialBase {
  1373. public:
  1374. USBSerial(USBHost &host) :
  1375. // hard code the normal one to 1 and 64 bytes for most likely most are 64
  1376. USBSerialBase(host, bigbuffer, sizeof(bigbuffer), 1, 64) {};
  1377. private:
  1378. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1379. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  1380. };
  1381. class USBSerial_BigBuffer: public USBSerialBase {
  1382. public:
  1383. // Default to larger than can be handled by other serial, but can overide
  1384. USBSerial_BigBuffer(USBHost &host, uint16_t min_rxtx=65) :
  1385. // hard code the normal one to 1 and 64 bytes for most likely most are 64
  1386. USBSerialBase(host, bigbuffer, sizeof(bigbuffer), min_rxtx, 512) {};
  1387. private:
  1388. enum { BUFFER_SIZE = 4096 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1389. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  1390. };
  1391. //--------------------------------------------------------------------------
  1392. class AntPlus: public USBDriver {
  1393. // Please post any AntPlus feedback or contributions on this forum thread:
  1394. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  1395. public:
  1396. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  1397. void begin(const uint8_t key=0);
  1398. void onStatusChange(void (*function)(int channel, int status)) {
  1399. user_onStatusChange = function;
  1400. }
  1401. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  1402. user_onDeviceID = function;
  1403. }
  1404. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  1405. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  1406. memset(&hrm, 0, sizeof(hrm));
  1407. user_onHeartRateMonitor = f;
  1408. }
  1409. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  1410. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  1411. memset(&spdcad, 0, sizeof(spdcad));
  1412. user_onSpeedCadence = f;
  1413. }
  1414. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  1415. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  1416. memset(&spd, 0, sizeof(spd));
  1417. user_onSpeed = f;
  1418. }
  1419. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  1420. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  1421. memset(&cad, 0, sizeof(cad));
  1422. user_onCadence = f;
  1423. }
  1424. void setWheelCircumference(float meters) {
  1425. wheelCircumference = meters * 1000.0f;
  1426. }
  1427. protected:
  1428. virtual void Task();
  1429. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1430. virtual void disconnect();
  1431. virtual void timer_event(USBDriverTimer *whichTimer);
  1432. private:
  1433. static void rx_callback(const Transfer_t *transfer);
  1434. static void tx_callback(const Transfer_t *transfer);
  1435. void rx_data(const Transfer_t *transfer);
  1436. void tx_data(const Transfer_t *transfer);
  1437. void init();
  1438. size_t write(const void *data, const size_t size);
  1439. int read(void *data, const size_t size);
  1440. void transmit();
  1441. private:
  1442. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1443. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1444. strbuf_t mystring_bufs[1];
  1445. //USBDriverTimer txtimer;
  1446. USBDriverTimer updatetimer;
  1447. Pipe_t *rxpipe;
  1448. Pipe_t *txpipe;
  1449. bool first_update;
  1450. uint8_t txbuffer[240];
  1451. uint8_t rxpacket[64];
  1452. volatile uint16_t txhead;
  1453. volatile uint16_t txtail;
  1454. volatile bool txready;
  1455. volatile uint8_t rxlen;
  1456. volatile bool do_polling;
  1457. private:
  1458. enum _eventi {
  1459. EVENTI_MESSAGE = 0,
  1460. EVENTI_CHANNEL,
  1461. EVENTI_TOTAL
  1462. };
  1463. enum _profiles {
  1464. PROFILE_HRM = 0,
  1465. PROFILE_SPDCAD,
  1466. PROFILE_POWER,
  1467. PROFILE_STRIDE,
  1468. PROFILE_SPEED,
  1469. PROFILE_CADENCE,
  1470. PROFILE_TOTAL
  1471. };
  1472. typedef struct {
  1473. uint8_t channel;
  1474. uint8_t RFFreq;
  1475. uint8_t networkNumber;
  1476. uint8_t stub;
  1477. uint8_t searchTimeout;
  1478. uint8_t channelType;
  1479. uint8_t deviceType;
  1480. uint8_t transType;
  1481. uint16_t channelPeriod;
  1482. uint16_t searchWaveform;
  1483. uint32_t deviceNumber; // deviceId
  1484. struct {
  1485. uint8_t chanIdOnce;
  1486. uint8_t keyAccepted;
  1487. uint8_t profileValid;
  1488. uint8_t channelStatus;
  1489. uint8_t channelStatusOld;
  1490. } flags;
  1491. } TDCONFIG;
  1492. struct {
  1493. uint8_t initOnce;
  1494. uint8_t key; // key index
  1495. int iDevice; // index to the antplus we're interested in, if > one found
  1496. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1497. } ant;
  1498. void (*user_onStatusChange)(int channel, int status);
  1499. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1500. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1501. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1502. void (*user_onSpeed)(float speed, float distance);
  1503. void (*user_onCadence)(float cadence);
  1504. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1505. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1506. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1507. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1508. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1509. static int msgGetLength(uint8_t *stream);
  1510. int handleMessages(uint8_t *buffer, int tBytes);
  1511. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1512. void message_channel(const int chan, const int eventId,
  1513. const uint8_t *payload, const size_t dataLength);
  1514. void message_response(const int chan, const int msgId,
  1515. const uint8_t *payload, const size_t dataLength);
  1516. void message_event(const int channel, const int msgId,
  1517. const uint8_t *payload, const size_t dataLength);
  1518. int ResetSystem();
  1519. int RequestMessage(const int channel, const int message);
  1520. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1521. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1522. int SetChannelPeriod(const int channel, const int period);
  1523. int SetChannelRFFreq(const int channel, const int freq);
  1524. int SetSearchWaveform(const int channel, const int wave);
  1525. int OpenChannel(const int channel);
  1526. int CloseChannel(const int channel);
  1527. int AssignChannel(const int channel, const int channelType, const int network);
  1528. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1529. const int transmissionType);
  1530. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1531. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1532. int SendBroadcastData(const int channel, const uint8_t *data);
  1533. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1534. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1535. const int TranType, const uint8_t *data);
  1536. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1537. const int TranType, const uint8_t *data);
  1538. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1539. const int devType, const int TranType, const uint8_t *data);
  1540. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1541. const int tranType, const uint8_t *data, const int nunPackets);
  1542. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1543. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1544. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1545. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1546. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1547. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1548. struct {
  1549. struct {
  1550. uint8_t bpm;
  1551. uint8_t sequence;
  1552. uint16_t time;
  1553. } previous;
  1554. } hrm;
  1555. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1556. struct {
  1557. struct {
  1558. uint16_t cadenceTime;
  1559. uint16_t cadenceCt;
  1560. uint16_t speedTime;
  1561. uint16_t speedCt;
  1562. } previous;
  1563. float distance;
  1564. } spdcad;
  1565. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1566. /* struct {
  1567. struct {
  1568. uint8_t sequence;
  1569. uint16_t pedalPowerContribution;
  1570. uint8_t pedalPower;
  1571. uint8_t instantCadence;
  1572. uint16_t sumPower;
  1573. uint16_t instantPower;
  1574. } current;
  1575. struct {
  1576. uint16_t stub;
  1577. } previous;
  1578. } pwr; */
  1579. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1580. /* struct {
  1581. struct {
  1582. uint16_t speed;
  1583. uint16_t cadence;
  1584. uint8_t strides;
  1585. } current;
  1586. struct {
  1587. uint8_t strides;
  1588. uint16_t speed;
  1589. uint16_t cadence;
  1590. } previous;
  1591. } stride; */
  1592. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1593. struct {
  1594. struct {
  1595. uint16_t speedTime;
  1596. uint16_t speedCt;
  1597. } previous;
  1598. float distance;
  1599. } spd;
  1600. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1601. struct {
  1602. struct {
  1603. uint16_t cadenceTime;
  1604. uint16_t cadenceCt;
  1605. } previous;
  1606. } cad;
  1607. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1608. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1609. };
  1610. //--------------------------------------------------------------------------
  1611. class RawHIDController : public USBHIDInput {
  1612. public:
  1613. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1614. uint32_t usage(void) {return usage_;}
  1615. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1616. bool sendPacket(const uint8_t *buffer);
  1617. protected:
  1618. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1619. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1620. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1621. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1622. virtual void hid_input_data(uint32_t usage, int32_t value);
  1623. virtual void hid_input_end();
  1624. virtual void disconnect_collection(Device_t *dev);
  1625. private:
  1626. void init();
  1627. USBHIDParser *driver_;
  1628. enum { MAX_PACKET_SIZE = 64 };
  1629. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1630. uint8_t collections_claimed = 0;
  1631. //volatile bool hid_input_begin_ = false;
  1632. uint32_t fixed_usage_;
  1633. uint32_t usage_ = 0;
  1634. // See if we can contribute transfers
  1635. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1636. };
  1637. //--------------------------------------------------------------------------
  1638. class USBSerialEmu : public USBHIDInput, public Stream {
  1639. public:
  1640. USBSerialEmu(USBHost &host) { init(); }
  1641. uint32_t usage(void) {return usage_;}
  1642. // Stream stuff.
  1643. uint32_t writeTimeout() {return write_timeout_;}
  1644. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  1645. virtual int available(void);
  1646. virtual int peek(void);
  1647. virtual int read(void);
  1648. virtual int availableForWrite();
  1649. virtual size_t write(uint8_t c);
  1650. virtual void flush(void);
  1651. using Print::write;
  1652. protected:
  1653. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1654. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1655. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1656. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1657. virtual void hid_input_data(uint32_t usage, int32_t value);
  1658. virtual void hid_input_end();
  1659. virtual void disconnect_collection(Device_t *dev);
  1660. virtual void hid_timer_event(USBDriverTimer *whichTimer);
  1661. bool sendPacket();
  1662. private:
  1663. void init();
  1664. USBHIDParser *driver_;
  1665. enum { MAX_PACKET_SIZE = 64 };
  1666. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1667. uint8_t collections_claimed = 0;
  1668. uint32_t usage_ = 0;
  1669. // We have max of 512 byte packets coming in. How about enough room for 3+3
  1670. enum { RX_BUFFER_SIZE=1024, TX_BUFFER_SIZE = 512 };
  1671. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  1672. uint8_t rx_buffer_[RX_BUFFER_SIZE];
  1673. uint8_t tx_buffer_[TX_BUFFER_SIZE];
  1674. volatile uint8_t tx_out_data_pending_ = 0;
  1675. volatile uint16_t rx_head_;// receive head
  1676. volatile uint16_t rx_tail_;// receive tail
  1677. volatile uint16_t tx_head_;
  1678. uint16_t rx_pipe_size_;// size of receive circular buffer
  1679. uint16_t tx_pipe_size_;// size of transmit circular buffer
  1680. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  1681. // See if we can contribute transfers
  1682. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1683. };
  1684. //--------------------------------------------------------------------------
  1685. class BluetoothController: public USBDriver {
  1686. public:
  1687. static const uint8_t MAX_CONNECTIONS = 4;
  1688. typedef struct {
  1689. BTHIDInput * device_driver_ = nullptr;;
  1690. uint16_t connection_rxid_ = 0;
  1691. uint16_t control_dcid_ = 0x70;
  1692. uint16_t interrupt_dcid_ = 0x71;
  1693. uint16_t interrupt_scid_;
  1694. uint16_t control_scid_;
  1695. uint8_t device_bdaddr_[6];// remember devices address
  1696. uint8_t device_ps_repetion_mode_ ; // mode
  1697. uint8_t device_clock_offset_[2];
  1698. uint32_t device_class_; // class of device.
  1699. uint16_t device_connection_handle_; // handle to connection
  1700. uint8_t remote_ver_;
  1701. uint16_t remote_man_;
  1702. uint8_t remote_subv_;
  1703. uint8_t connection_complete_ = false; //
  1704. } connection_info_t;
  1705. BluetoothController(USBHost &host, bool pair = false, const char *pin = "0000") : do_pair_device_(pair), pair_pincode_(pin), delayTimer_(this)
  1706. { init(); }
  1707. enum {MAX_ENDPOINTS=4, NUM_SERVICES=4, }; // Max number of Bluetooth services - if you need more than 4 simply increase this number
  1708. enum {BT_CLASS_DEVICE= 0x0804}; // Toy - Robot
  1709. static void driver_ready_for_bluetooth(BTHIDInput *driver);
  1710. const uint8_t* myBDAddr(void) {return my_bdaddr_;}
  1711. // BUGBUG version to allow some of the controlled objects to call?
  1712. enum {CONTROL_SCID=-1, INTERRUPT_SCID=-2};
  1713. void sendL2CapCommand(uint8_t* data, uint8_t nbytes, int channel = (int)0x0001);
  1714. protected:
  1715. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1716. virtual void control(const Transfer_t *transfer);
  1717. virtual void disconnect();
  1718. virtual void timer_event(USBDriverTimer *whichTimer);
  1719. BTHIDInput * find_driver(uint32_t device_type, uint8_t *remoteName=nullptr);
  1720. // Hack to allow PS3 to maybe change values
  1721. uint16_t next_dcid_ = 0x70; // Lets try not hard coding control and interrupt dcid
  1722. #if 0
  1723. uint16_t connection_rxid_ = 0;
  1724. uint16_t control_dcid_ = 0x70;
  1725. uint16_t interrupt_dcid_ = 0x71;
  1726. uint16_t interrupt_scid_;
  1727. uint16_t control_scid_;
  1728. #else
  1729. connection_info_t connections_[MAX_CONNECTIONS];
  1730. uint8_t count_connections_ = 0;
  1731. uint8_t current_connection_ = 0; // need to figure out when this changes and/or...
  1732. #endif
  1733. private:
  1734. friend class BTHIDInput;
  1735. static void rx_callback(const Transfer_t *transfer);
  1736. static void rx2_callback(const Transfer_t *transfer);
  1737. static void tx_callback(const Transfer_t *transfer);
  1738. void rx_data(const Transfer_t *transfer);
  1739. void rx2_data(const Transfer_t *transfer);
  1740. void tx_data(const Transfer_t *transfer);
  1741. void init();
  1742. // HCI support functions...
  1743. void sendHCICommand(uint16_t hciCommand, uint16_t cParams, const uint8_t* data);
  1744. //void sendHCIReadLocalSupportedFeatures();
  1745. void inline sendHCI_INQUIRY();
  1746. void inline sendHCIInquiryCancel();
  1747. void inline sendHCICreateConnection();
  1748. void inline sendHCIAuthenticationRequested();
  1749. void inline sendHCIAcceptConnectionRequest();
  1750. void inline sendHCILinkKeyNegativeReply();
  1751. void inline sendHCIPinCodeReply();
  1752. void inline sendResetHCI();
  1753. void inline sendHDCWriteClassOfDev();
  1754. void inline sendHCIReadBDAddr();
  1755. void inline sendHCIReadLocalVersionInfo();
  1756. void inline sendHCIWriteScanEnable(uint8_t scan_op);
  1757. void inline sendHCIHCIWriteInquiryMode(uint8_t inquiry_mode);
  1758. void inline sendHCISetEventMask();
  1759. void inline sendHCIRemoteNameRequest();
  1760. void inline sendHCIRemoteVersionInfoRequest();
  1761. void handle_hci_command_complete();
  1762. void handle_hci_command_status();
  1763. void handle_hci_inquiry_result(bool fRSSI=false);
  1764. void handle_hci_extended_inquiry_result();
  1765. void handle_hci_inquiry_complete();
  1766. void handle_hci_incoming_connect();
  1767. void handle_hci_connection_complete();
  1768. void handle_hci_disconnect_complete();
  1769. void handle_hci_authentication_complete();
  1770. void handle_hci_remote_name_complete();
  1771. void handle_hci_remote_version_information_complete();
  1772. void handle_hci_pin_code_request();
  1773. void handle_hci_link_key_notification();
  1774. void handle_hci_link_key_request();
  1775. void queue_next_hci_command();
  1776. void sendl2cap_ConnectionResponse(uint16_t handle, uint8_t rxid, uint16_t dcid, uint16_t scid, uint8_t result);
  1777. void sendl2cap_ConnectionRequest(uint16_t handle, uint8_t rxid, uint16_t scid, uint16_t psm);
  1778. void sendl2cap_ConfigRequest(uint16_t handle, uint8_t rxid, uint16_t dcid);
  1779. void sendl2cap_ConfigResponse(uint16_t handle, uint8_t rxid, uint16_t scid);
  1780. void sendL2CapCommand(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00);
  1781. void process_l2cap_connection_request(uint8_t *data);
  1782. void process_l2cap_connection_response(uint8_t *data);
  1783. void process_l2cap_config_request(uint8_t *data);
  1784. void process_l2cap_config_response(uint8_t *data);
  1785. void process_l2cap_command_reject(uint8_t *data);
  1786. void process_l2cap_disconnect_request(uint8_t *data);
  1787. void setHIDProtocol(uint8_t protocol);
  1788. void handleHIDTHDRData(uint8_t *buffer); // Pass the whole buffer...
  1789. static BTHIDInput *available_bthid_drivers_list;
  1790. setup_t setup;
  1791. Pipe_t mypipes[4] __attribute__ ((aligned(32)));
  1792. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1793. strbuf_t mystring_bufs[2]; // 2 string buffers - one for our device - one for remote device...
  1794. uint16_t pending_control_ = 0;
  1795. uint16_t pending_control_tx_ = 0;
  1796. uint16_t rx_size_ = 0;
  1797. uint16_t rx2_size_ = 0;
  1798. uint16_t tx_size_ = 0;
  1799. Pipe_t *rxpipe_;
  1800. Pipe_t *rx2pipe_;
  1801. Pipe_t *txpipe_;
  1802. uint8_t rxbuf_[256]; // used to receive data from RX, which may come with several packets...
  1803. uint8_t rx_packet_data_remaining=0; // how much data remaining
  1804. uint8_t rx2buf_[64]; // receive buffer from Bulk end point
  1805. uint8_t txbuf_[256]; // buffer to use to send commands to bluetooth
  1806. uint8_t hciVersion; // what version of HCI do we have?
  1807. bool do_pair_device_; // Should we do a pair for a new device?
  1808. const char *pair_pincode_; // What pin code to use for the pairing
  1809. USBDriverTimer delayTimer_;
  1810. uint8_t my_bdaddr_[6]; // The bluetooth dongles Bluetooth address.
  1811. uint8_t features[8]; // remember our local features.
  1812. typedef struct {
  1813. uint16_t idVendor;
  1814. uint16_t idProduct;
  1815. } product_vendor_mapping_t;
  1816. static product_vendor_mapping_t pid_vid_mapping[];
  1817. };
  1818. class ADK: public USBDriver {
  1819. public:
  1820. ADK(USBHost &host) { init(); }
  1821. bool ready();
  1822. void begin(char *adk_manufacturer, char *adk_model, char *adk_desc, char *adk_version, char *adk_uri, char *adk_serial);
  1823. void end();
  1824. int available(void);
  1825. int peek(void);
  1826. int read(void);
  1827. size_t write(size_t len, uint8_t *buf);
  1828. protected:
  1829. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1830. virtual void disconnect();
  1831. virtual void control(const Transfer_t *transfer);
  1832. static void rx_callback(const Transfer_t *transfer);
  1833. static void tx_callback(const Transfer_t *transfer);
  1834. void rx_data(const Transfer_t *transfer);
  1835. void tx_data(const Transfer_t *transfer);
  1836. void init();
  1837. void rx_queue_packets(uint32_t head, uint32_t tail);
  1838. void sendStr(Device_t *dev, uint8_t index, char *str);
  1839. private:
  1840. int state = 0;
  1841. Pipe_t *rxpipe;
  1842. Pipe_t *txpipe;
  1843. enum { MAX_PACKET_SIZE = 512 };
  1844. enum { RX_QUEUE_SIZE = 1024 }; // must be more than MAX_PACKET_SIZE
  1845. uint8_t rx_buffer[MAX_PACKET_SIZE];
  1846. uint8_t tx_buffer[MAX_PACKET_SIZE];
  1847. uint16_t rx_size;
  1848. uint16_t tx_size;
  1849. uint8_t rx_queue[RX_QUEUE_SIZE];
  1850. bool rx_packet_queued;
  1851. uint16_t rx_head;
  1852. uint16_t rx_tail;
  1853. uint8_t rx_ep;
  1854. uint8_t tx_ep;
  1855. char *manufacturer;
  1856. char *model;
  1857. char *desc;
  1858. char *version;
  1859. char *uri;
  1860. char *serial;
  1861. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1862. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1863. };
  1864. //--------------------------------------------------------------------------
  1865. class msController : public USBDriver {
  1866. public:
  1867. msController(USBHost &host) { init(); }
  1868. msController(USBHost *host) { init(); }
  1869. msSCSICapacity_t msCapacity;
  1870. msInquiryResponse_t msInquiry;
  1871. msRequestSenseResponse_t msSense;
  1872. msDriveInfo_t msDriveInfo;
  1873. bool mscTransferComplete = false;
  1874. uint8_t mscInit(void);
  1875. void msReset(uint32_t interfaceNumber);
  1876. uint8_t msGetMaxLun(uint32_t interfaceNumber);
  1877. void msCurrentLun(uint8_t lun) {currentLUN = lun;}
  1878. uint8_t msCurrentLun() {return currentLUN;}
  1879. bool available() { delay(0); return deviceAvailable; }
  1880. uint8_t checkConnectedInitialized(void);
  1881. uint16_t getIDVendor() {return idVendor; }
  1882. uint16_t getIDProduct() {return idProduct; }
  1883. uint8_t getHubNumber() { return hubNumber; }
  1884. uint8_t getHubPort() { return hubPort; }
  1885. uint8_t getDeviceAddress() { return deviceAddress; }
  1886. uint8_t WaitMediaReady();
  1887. uint8_t msTestReady();
  1888. uint8_t msReportLUNs(uint8_t *Buffer);
  1889. uint8_t msStartStopUnit(uint8_t mode);
  1890. uint8_t msReadDeviceCapacity(msSCSICapacity_t * const Capacity);
  1891. uint8_t msDeviceInquiry(msInquiryResponse_t * const Inquiry);
  1892. uint8_t msProcessError(uint8_t msStatus);
  1893. uint8_t msRequestSense(msRequestSenseResponse_t * const Sense);
  1894. uint8_t msRequestSense(void *Sense);
  1895. uint8_t msReadBlocks(const uint32_t BlockAddress, const uint16_t Blocks,
  1896. const uint16_t BlockSize, void * sectorBuffer);
  1897. uint8_t msWriteBlocks(const uint32_t BlockAddress, const uint16_t Blocks,
  1898. const uint16_t BlockSize, const void * sectorBuffer);
  1899. protected:
  1900. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1901. virtual void control(const Transfer_t *transfer);
  1902. virtual void disconnect();
  1903. static void callbackIn(const Transfer_t *transfer);
  1904. static void callbackOut(const Transfer_t *transfer);
  1905. void new_dataIn(const Transfer_t *transfer);
  1906. void new_dataOut(const Transfer_t *transfer);
  1907. void init();
  1908. uint8_t msDoCommand(msCommandBlockWrapper_t *CBW, void *buffer);
  1909. uint8_t msGetCSW(void);
  1910. private:
  1911. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1912. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1913. strbuf_t mystring_bufs[1];
  1914. uint32_t packetSizeIn;
  1915. uint32_t packetSizeOut;
  1916. Pipe_t *datapipeIn;
  1917. Pipe_t *datapipeOut;
  1918. uint32_t endpointIn = 0;
  1919. uint32_t endpointOut = 0;
  1920. setup_t setup;
  1921. uint8_t report[8];
  1922. uint8_t maxLUN = 0;
  1923. uint8_t currentLUN = 0;
  1924. // msSCSICapacity_t msCapacity;
  1925. // msInquiryResponse_t msInquiry;
  1926. // msRequestSenseResponse_t msSense;
  1927. uint16_t idVendor = 0;
  1928. uint16_t idProduct = 0;
  1929. uint8_t hubNumber = 0;
  1930. uint8_t hubPort = 0;
  1931. uint8_t deviceAddress = 0;
  1932. volatile bool msOutCompleted = false;
  1933. volatile bool msInCompleted = false;
  1934. volatile bool msControlCompleted = false;
  1935. uint32_t CBWTag = 0;
  1936. bool deviceAvailable = false;
  1937. };
  1938. #endif