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.

2127 líneas
78KB

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