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

2042 líneas
75KB

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