選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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