You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

USBHost_t36.h 42KB

7 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. /* USB EHCI Host for Teensy 3.6
  2. * Copyright 2017 Paul Stoffregen (paul@pjrc.com)
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included
  13. * in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #ifndef USB_HOST_TEENSY36_
  24. #define USB_HOST_TEENSY36_
  25. #include <stdint.h>
  26. #if !defined(__MK66FX1M0__)
  27. #error "USBHost_t36 only works with Teensy 3.6. Please select it in Tools > Boards"
  28. #endif
  29. // Dear inquisitive reader, USB is a complex protocol defined with
  30. // very specific terminology. To have any chance of understand this
  31. // source code, you absolutely must have solid knowledge of specific
  32. // USB terms such as host, device, endpoint, pipe, enumeration....
  33. // You really must also have at least a basic knowledge of the
  34. // different USB transfers: control, bulk, interrupt, isochronous.
  35. //
  36. // The USB 2.0 specification explains these in chapter 4 (pages 15
  37. // to 24), and provides more detail in the first part of chapter 5
  38. // (pages 25 to 55). The USB spec is published for free at
  39. // www.usb.org. Here is a convenient link to just the main PDF:
  40. //
  41. // https://www.pjrc.com/teensy/beta/usb20.pdf
  42. //
  43. // This is a huge file, but chapter 4 is short and easy to read.
  44. // If you're not familiar with the USB lingo, please do yourself
  45. // a favor by reading at least chapter 4 to get up to speed on the
  46. // meaning of these important USB concepts and terminology.
  47. //
  48. // If you wish to ask questions (which belong on the forum, not
  49. // github issues) or discuss development of this library, you
  50. // ABSOLUTELY MUST know the basic USB terminology from chapter 4.
  51. // Please repect other people's valuable time & effort by making
  52. // your best effort to read chapter 4 before asking USB questions!
  53. //#define USBHOST_PRINT_DEBUG
  54. /************************************************/
  55. /* Data Types */
  56. /************************************************/
  57. // These 6 types are the key to understanding how this USB Host
  58. // library really works.
  59. // USBHost is a static class controlling the hardware.
  60. // All common USB functionality is implemented here.
  61. class USBHost;
  62. // These 3 structures represent the actual USB entities
  63. // USBHost manipulates. One Device_t is created for
  64. // each active USB device. One Pipe_t is create for
  65. // each endpoint. Transfer_t structures are created
  66. // when any data transfer is added to the EHCI work
  67. // queues, and then returned to the free pool after the
  68. // data transfer completes and the driver has processed
  69. // the results.
  70. typedef struct Device_struct Device_t;
  71. typedef struct Pipe_struct Pipe_t;
  72. typedef struct Transfer_struct Transfer_t;
  73. // All USB device drivers inherit use these classes.
  74. // Drivers build user-visible functionality on top
  75. // of these classes, which receive USB events from
  76. // USBHost.
  77. class USBDriver;
  78. class USBDriverTimer;
  79. /************************************************/
  80. /* Added Defines */
  81. /************************************************/
  82. #define KEYD_UP 0xDA
  83. #define KEYD_DOWN 0xD9
  84. #define KEYD_LEFT 0xD8
  85. #define KEYD_RIGHT 0xD7
  86. #define KEYD_INSERT 0xD1
  87. #define KEYD_DELETE 0xD4
  88. #define KEYD_PAGE_UP 0xD3
  89. #define KEYD_PAGE_DOWN 0xD6
  90. #define KEYD_HOME 0xD2
  91. #define KEYD_END 0xD5
  92. #define KEYD_F1 0xC2
  93. #define KEYD_F2 0xC3
  94. #define KEYD_F3 0xC4
  95. #define KEYD_F4 0xC5
  96. #define KEYD_F5 0xC6
  97. #define KEYD_F6 0xC7
  98. #define KEYD_F7 0xC8
  99. #define KEYD_F8 0xC9
  100. #define KEYD_F9 0xCA
  101. #define KEYD_F10 0xCB
  102. #define KEYD_F11 0xCC
  103. #define KEYD_F12 0xCD
  104. /************************************************/
  105. /* Data Structure Definitions */
  106. /************************************************/
  107. // setup_t holds the 8 byte USB SETUP packet data.
  108. // These unions & structs allow convenient access to
  109. // the setup fields.
  110. typedef union {
  111. struct {
  112. union {
  113. struct {
  114. uint8_t bmRequestType;
  115. uint8_t bRequest;
  116. };
  117. uint16_t wRequestAndType;
  118. };
  119. uint16_t wValue;
  120. uint16_t wIndex;
  121. uint16_t wLength;
  122. };
  123. struct {
  124. uint32_t word1;
  125. uint32_t word2;
  126. };
  127. } setup_t;
  128. typedef struct {
  129. enum {STRING_BUF_SIZE=50};
  130. enum {STR_ID_MAN=0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
  131. uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
  132. uint8_t buffer[STRING_BUF_SIZE];
  133. } strbuf_t;
  134. #define DEVICE_STRUCT_STRING_BUF_SIZE 50
  135. // Device_t holds all the information about a USB device
  136. struct Device_struct {
  137. Pipe_t *control_pipe;
  138. Pipe_t *data_pipes;
  139. Device_t *next;
  140. USBDriver *drivers;
  141. strbuf_t *strbuf;
  142. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  143. uint8_t address;
  144. uint8_t hub_address;
  145. uint8_t hub_port;
  146. uint8_t enum_state;
  147. uint8_t bDeviceClass;
  148. uint8_t bDeviceSubClass;
  149. uint8_t bDeviceProtocol;
  150. uint8_t bmAttributes;
  151. uint8_t bMaxPower;
  152. uint16_t idVendor;
  153. uint16_t idProduct;
  154. uint16_t LanguageID;
  155. };
  156. // Pipe_t holes all information about each USB endpoint/pipe
  157. // The first half is an EHCI QH structure for the pipe.
  158. struct Pipe_struct {
  159. // Queue Head (QH), EHCI page 46-50
  160. struct { // must be aligned to 32 byte boundary
  161. volatile uint32_t horizontal_link;
  162. volatile uint32_t capabilities[2];
  163. volatile uint32_t current;
  164. volatile uint32_t next;
  165. volatile uint32_t alt_next;
  166. volatile uint32_t token;
  167. volatile uint32_t buffer[5];
  168. } qh;
  169. Device_t *device;
  170. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  171. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  172. uint8_t start_mask;
  173. uint8_t complete_mask;
  174. Pipe_t *next;
  175. void (*callback_function)(const Transfer_t *);
  176. uint16_t periodic_interval;
  177. uint16_t periodic_offset;
  178. uint32_t unused1;
  179. uint32_t unused2;
  180. uint32_t unused3;
  181. uint32_t unused4;
  182. uint32_t unused5;
  183. uint32_t unused6;
  184. uint32_t unused7;
  185. };
  186. // Transfer_t represents a single transaction on the USB bus.
  187. // The first portion is an EHCI qTD structure. Transfer_t are
  188. // allocated as-needed from a memory pool, loaded with pointers
  189. // to the actual data buffers, linked into a followup list,
  190. // and placed on ECHI Queue Heads. When the ECHI interrupt
  191. // occurs, the followup lists are used to find the Transfer_t
  192. // in memory. Callbacks are made, and then the Transfer_t are
  193. // returned to the memory pool.
  194. struct Transfer_struct {
  195. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  196. struct { // must be aligned to 32 byte boundary
  197. volatile uint32_t next;
  198. volatile uint32_t alt_next;
  199. volatile uint32_t token;
  200. volatile uint32_t buffer[5];
  201. } qtd;
  202. // Linked list of queued, not-yet-completed transfers
  203. Transfer_t *next_followup;
  204. Transfer_t *prev_followup;
  205. Pipe_t *pipe;
  206. // Data to be used by callback function. When a group
  207. // of Transfer_t are created, these fields and the
  208. // interrupt-on-complete bit in the qTD token are only
  209. // set in the last Transfer_t of the list.
  210. void *buffer;
  211. uint32_t length;
  212. setup_t setup;
  213. USBDriver *driver;
  214. };
  215. /************************************************/
  216. /* Main USB EHCI Controller */
  217. /************************************************/
  218. class USBHost {
  219. public:
  220. static void begin();
  221. static void Task();
  222. protected:
  223. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  224. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  225. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  226. void *buf, USBDriver *driver);
  227. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  228. uint32_t len, USBDriver *driver);
  229. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  230. static void disconnect_Device(Device_t *dev);
  231. static void enumeration(const Transfer_t *transfer);
  232. static void driver_ready_for_device(USBDriver *driver);
  233. static void contribute_Devices(Device_t *devices, uint32_t num);
  234. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  235. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  236. static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
  237. static volatile bool enumeration_busy;
  238. private:
  239. static void isr();
  240. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  241. static void claim_drivers(Device_t *dev);
  242. static uint32_t assign_address(void);
  243. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  244. static void init_Device_Pipe_Transfer_memory(void);
  245. static Device_t * allocate_Device(void);
  246. static void delete_Pipe(Pipe_t *pipe);
  247. static void free_Device(Device_t *q);
  248. static Pipe_t * allocate_Pipe(void);
  249. static void free_Pipe(Pipe_t *q);
  250. static Transfer_t * allocate_Transfer(void);
  251. static void free_Transfer(Transfer_t *q);
  252. static strbuf_t * allocate_string_buffer(void);
  253. static void free_string_buffer(strbuf_t *strbuf);
  254. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  255. uint32_t maxlen, uint32_t interval);
  256. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  257. static bool followup_Transfer(Transfer_t *transfer);
  258. static void followup_Error(void);
  259. protected:
  260. #ifdef USBHOST_PRINT_DEBUG
  261. static void print_(const Transfer_t *transfer);
  262. static void print_(const Transfer_t *first, const Transfer_t *last);
  263. static void print_token(uint32_t token);
  264. static void print_(const Pipe_t *pipe);
  265. static void print_driverlist(const char *name, const USBDriver *driver);
  266. static void print_qh_list(const Pipe_t *list);
  267. static void print_hexbytes(const void *ptr, uint32_t len);
  268. static void print_(const char *s) { Serial.print(s); }
  269. static void print_(int n) { Serial.print(n); }
  270. static void print_(unsigned int n) { Serial.print(n); }
  271. static void print_(long n) { Serial.print(n); }
  272. static void print_(unsigned long n) { Serial.print(n); }
  273. static void println_(const char *s) { Serial.println(s); }
  274. static void println_(int n) { Serial.println(n); }
  275. static void println_(unsigned int n) { Serial.println(n); }
  276. static void println_(long n) { Serial.println(n); }
  277. static void println_(unsigned long n) { Serial.println(n); }
  278. static void println_() { Serial.println(); }
  279. static void print_(uint32_t n, uint8_t b) { Serial.print(n, b); }
  280. static void println_(uint32_t n, uint8_t b) { Serial.println(n, b); }
  281. static void print_(const char *s, int n, uint8_t b = DEC) {
  282. Serial.print(s); Serial.print(n, b); }
  283. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  284. Serial.print(s); Serial.print(n, b); }
  285. static void print_(const char *s, long n, uint8_t b = DEC) {
  286. Serial.print(s); Serial.print(n, b); }
  287. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  288. Serial.print(s); Serial.print(n, b); }
  289. static void println_(const char *s, int n, uint8_t b = DEC) {
  290. Serial.print(s); Serial.println(n, b); }
  291. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  292. Serial.print(s); Serial.println(n, b); }
  293. static void println_(const char *s, long n, uint8_t b = DEC) {
  294. Serial.print(s); Serial.println(n, b); }
  295. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  296. Serial.print(s); Serial.println(n, b); }
  297. friend class USBDriverTimer; // for access to print & println
  298. #else
  299. static void print_(const Transfer_t *transfer) {}
  300. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  301. static void print_token(uint32_t token) {}
  302. static void print_(const Pipe_t *pipe) {}
  303. static void print_driverlist(const char *name, const USBDriver *driver) {}
  304. static void print_qh_list(const Pipe_t *list) {}
  305. static void print_hexbytes(const void *ptr, uint32_t len) {}
  306. static void print_(const char *s) {}
  307. static void print_(int n) {}
  308. static void print_(unsigned int n) {}
  309. static void print_(long n) {}
  310. static void print_(unsigned long n) {}
  311. static void println_(const char *s) {}
  312. static void println_(int n) {}
  313. static void println_(unsigned int n) {}
  314. static void println_(long n) {}
  315. static void println_(unsigned long n) {}
  316. static void println_() {}
  317. static void print_(uint32_t n, uint8_t b) {}
  318. static void println_(uint32_t n, uint8_t b) {}
  319. static void print_(const char *s, int n, uint8_t b = DEC) {}
  320. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  321. static void print_(const char *s, long n, uint8_t b = DEC) {}
  322. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  323. static void println_(const char *s, int n, uint8_t b = DEC) {}
  324. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  325. static void println_(const char *s, long n, uint8_t b = DEC) {}
  326. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  327. #endif
  328. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  329. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  330. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  331. s.word2 = wIndex | (wLength << 16);
  332. }
  333. };
  334. /************************************************/
  335. /* USB Device Driver Common Base Class */
  336. /************************************************/
  337. // All USB device drivers inherit from this base class.
  338. class USBDriver : public USBHost {
  339. public:
  340. operator bool() { return (device != nullptr); }
  341. uint16_t idVendor() { return (device != nullptr) ? device->idVendor : 0; }
  342. uint16_t idProduct() { return (device != nullptr) ? device->idProduct : 0; }
  343. const uint8_t *manufacturer()
  344. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  345. const uint8_t *product()
  346. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  347. const uint8_t *serialNumber()
  348. { return ((device == nullptr) || (device->strbuf == nullptr)) ? nullptr : &device->strbuf->buffer[device->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  349. // TODO: user-level functions
  350. // check if device is bound/active/online
  351. // query vid, pid
  352. // query string: manufacturer, product, serial number
  353. protected:
  354. USBDriver() : next(NULL), device(NULL) {}
  355. // Check if a driver wishes to claim a device or interface or group
  356. // of interfaces within a device. When this function returns true,
  357. // the driver is considered bound or loaded for that device. When
  358. // new devices are detected, enumeration.cpp calls this function on
  359. // all unbound driver objects, to give them an opportunity to bind
  360. // to the new device.
  361. // device has its vid&pid, class/subclass fields initialized
  362. // type is 0 for device level, 1 for interface level, 2 for IAD
  363. // descriptors points to the specific descriptor data
  364. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  365. // When an unknown (not chapter 9) control transfer completes, this
  366. // function is called for all drivers bound to the device. Return
  367. // true means this driver originated this control transfer, so no
  368. // more drivers need to be offered an opportunity to process it.
  369. // This function is optional, only needed if the driver uses control
  370. // transfers and wishes to be notified when they complete.
  371. virtual void control(const Transfer_t *transfer) { }
  372. // When any of the USBDriverTimer objects a driver creates generates
  373. // a timer event, this function is called.
  374. virtual void timer_event(USBDriverTimer *whichTimer) { }
  375. // When the user calls USBHost::Task, this Task function for all
  376. // active drivers is called, so they may update state and/or call
  377. // any attached user callback functions.
  378. virtual void Task() { }
  379. // When a device disconnects from the USB, this function is called.
  380. // The driver must free all resources it allocated and update any
  381. // internal state necessary to deal with the possibility of user
  382. // code continuing to call its API. However, pipes and transfers
  383. // are the handled by lower layers, so device drivers do not free
  384. // pipes they created or cancel transfers they had in progress.
  385. virtual void disconnect();
  386. // Drivers are managed by this single-linked list. All inactive
  387. // (not bound to any device) drivers are linked from
  388. // available_drivers in enumeration.cpp. When bound to a device,
  389. // drivers are linked from that Device_t drivers list.
  390. USBDriver *next;
  391. // The device this object instance is bound to. In words, this
  392. // is the specific device this driver is using. When not bound
  393. // to any device, this must be NULL. Drivers may set this to
  394. // any non-NULL value if they are in a state where they do not
  395. // wish to claim any device or interface (eg, if getting data
  396. // from the HID parser).
  397. Device_t *device;
  398. friend class USBHost;
  399. };
  400. // Device drivers may create these timer objects to schedule a timer call
  401. class USBDriverTimer {
  402. public:
  403. USBDriverTimer() { }
  404. USBDriverTimer(USBDriver *d) : driver(d) { }
  405. void init(USBDriver *d) { driver = d; };
  406. void start(uint32_t microseconds);
  407. void stop();
  408. void *pointer;
  409. uint32_t integer;
  410. uint32_t started_micros; // testing only
  411. private:
  412. USBDriver *driver;
  413. uint32_t usec;
  414. USBDriverTimer *next;
  415. USBDriverTimer *prev;
  416. friend class USBHost;
  417. };
  418. // Device drivers may inherit from this base class, if they wish to receive
  419. // HID input data fully decoded by the USBHIDParser driver
  420. class USBHIDInput {
  421. public:
  422. operator bool() { return (mydevice != nullptr); }
  423. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  424. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  425. const uint8_t *manufacturer()
  426. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  427. const uint8_t *product()
  428. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  429. const uint8_t *serialNumber()
  430. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  431. private:
  432. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  433. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  434. virtual void hid_input_data(uint32_t usage, int32_t value);
  435. virtual void hid_input_end();
  436. virtual void disconnect_collection(Device_t *dev);
  437. void add_to_list();
  438. USBHIDInput *next;
  439. friend class USBHIDParser;
  440. protected:
  441. Device_t *mydevice = NULL;
  442. };
  443. /************************************************/
  444. /* USB Device Drivers */
  445. /************************************************/
  446. class USBHub : public USBDriver {
  447. public:
  448. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  449. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  450. // Hubs with more more than 7 ports are built from two tiers of hubs
  451. // using 4 or 7 port hub chips. While the USB spec seems to allow
  452. // hubs to have up to 255 ports, in practice all hub chips on the
  453. // market are only 2, 3, 4 or 7 ports.
  454. enum { MAXPORTS = 7 };
  455. typedef uint8_t portbitmask_t;
  456. enum {
  457. PORT_OFF = 0,
  458. PORT_DISCONNECT = 1,
  459. PORT_DEBOUNCE1 = 2,
  460. PORT_DEBOUNCE2 = 3,
  461. PORT_DEBOUNCE3 = 4,
  462. PORT_DEBOUNCE4 = 5,
  463. PORT_DEBOUNCE5 = 6,
  464. PORT_RESET = 7,
  465. PORT_RECOVERY = 8,
  466. PORT_ACTIVE = 9
  467. };
  468. protected:
  469. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  470. virtual void control(const Transfer_t *transfer);
  471. virtual void timer_event(USBDriverTimer *whichTimer);
  472. virtual void disconnect();
  473. void init();
  474. bool can_send_control_now();
  475. void send_poweron(uint32_t port);
  476. void send_getstatus(uint32_t port);
  477. void send_clearstatus_connect(uint32_t port);
  478. void send_clearstatus_enable(uint32_t port);
  479. void send_clearstatus_suspend(uint32_t port);
  480. void send_clearstatus_overcurrent(uint32_t port);
  481. void send_clearstatus_reset(uint32_t port);
  482. void send_setreset(uint32_t port);
  483. static void callback(const Transfer_t *transfer);
  484. void status_change(const Transfer_t *transfer);
  485. void new_port_status(uint32_t port, uint32_t status);
  486. void start_debounce_timer(uint32_t port);
  487. void stop_debounce_timer(uint32_t port);
  488. private:
  489. Device_t mydevices[MAXPORTS];
  490. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  491. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  492. strbuf_t mystring_bufs[1];
  493. USBDriverTimer debouncetimer;
  494. USBDriverTimer resettimer;
  495. setup_t setup;
  496. Pipe_t *changepipe;
  497. Device_t *devicelist[MAXPORTS];
  498. uint32_t changebits;
  499. uint32_t statusbits;
  500. uint8_t hub_desc[16];
  501. uint8_t endpoint;
  502. uint8_t interval;
  503. uint8_t numports;
  504. uint8_t characteristics;
  505. uint8_t powertime;
  506. uint8_t sending_control_transfer;
  507. uint8_t port_doing_reset;
  508. uint8_t port_doing_reset_speed;
  509. uint8_t portstate[MAXPORTS];
  510. portbitmask_t send_pending_poweron;
  511. portbitmask_t send_pending_getstatus;
  512. portbitmask_t send_pending_clearstatus_connect;
  513. portbitmask_t send_pending_clearstatus_enable;
  514. portbitmask_t send_pending_clearstatus_suspend;
  515. portbitmask_t send_pending_clearstatus_overcurrent;
  516. portbitmask_t send_pending_clearstatus_reset;
  517. portbitmask_t send_pending_setreset;
  518. portbitmask_t debounce_in_use;
  519. static volatile bool reset_busy;
  520. };
  521. class USBHIDParser : public USBDriver {
  522. public:
  523. USBHIDParser(USBHost &host) { init(); }
  524. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  525. protected:
  526. enum { TOPUSAGE_LIST_LEN = 4 };
  527. enum { USAGE_LIST_LEN = 24 };
  528. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  529. virtual void control(const Transfer_t *transfer);
  530. virtual void disconnect();
  531. static void in_callback(const Transfer_t *transfer);
  532. static void out_callback(const Transfer_t *transfer);
  533. void in_data(const Transfer_t *transfer);
  534. void out_data(const Transfer_t *transfer);
  535. bool check_if_using_report_id();
  536. void parse();
  537. USBHIDInput * find_driver(uint32_t topusage);
  538. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  539. void init();
  540. private:
  541. Pipe_t *in_pipe;
  542. Pipe_t *out_pipe;
  543. static USBHIDInput *available_hid_drivers_list;
  544. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  545. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  546. uint16_t in_size;
  547. uint16_t out_size;
  548. setup_t setup;
  549. uint8_t descriptor[512];
  550. uint8_t report[64];
  551. uint16_t descsize;
  552. bool use_report_id;
  553. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  554. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  555. strbuf_t mystring_bufs[1];
  556. };
  557. class KeyboardController : public USBDriver /* , public USBHIDInput */ {
  558. public:
  559. typedef union {
  560. struct {
  561. uint8_t numLock : 1;
  562. uint8_t capsLock : 1;
  563. uint8_t scrollLock : 1;
  564. uint8_t compose : 1;
  565. uint8_t kana : 1;
  566. uint8_t reserved : 3;
  567. };
  568. uint8_t byte;
  569. } KBDLeds_t;
  570. public:
  571. KeyboardController(USBHost &host) { init(); }
  572. KeyboardController(USBHost *host) { init(); }
  573. int available();
  574. int read();
  575. uint16_t getKey() { return keyCode; }
  576. uint8_t getModifiers() { return modifiers; }
  577. uint8_t getOemKey() { return keyOEM; }
  578. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  579. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  580. void LEDS(uint8_t leds);
  581. uint8_t LEDS() {return leds_.byte;}
  582. void updateLEDS(void);
  583. bool numLock() {return leds_.numLock;}
  584. bool capsLock() {return leds_.capsLock;}
  585. bool scrollLock() {return leds_.scrollLock;}
  586. void numLock(bool f);
  587. void capsLock(bool f);
  588. void scrollLock(bool f);
  589. protected:
  590. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  591. virtual void control(const Transfer_t *transfer);
  592. virtual void disconnect();
  593. static void callback(const Transfer_t *transfer);
  594. void new_data(const Transfer_t *transfer);
  595. void init();
  596. private:
  597. void update();
  598. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  599. void key_press(uint32_t mod, uint32_t key);
  600. void key_release(uint32_t mod, uint32_t key);
  601. void (*keyPressedFunction)(int unicode);
  602. void (*keyReleasedFunction)(int unicode);
  603. Pipe_t *datapipe;
  604. setup_t setup;
  605. uint8_t report[8];
  606. uint16_t keyCode;
  607. uint8_t modifiers;
  608. uint8_t keyOEM;
  609. uint8_t prev_report[8];
  610. KBDLeds_t leds_ = {0};
  611. bool update_leds_ = false;
  612. bool processing_new_data_ = false;
  613. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  614. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  615. strbuf_t mystring_bufs[1];
  616. };
  617. class MIDIDevice : public USBDriver {
  618. public:
  619. enum { SYSEX_MAX_LEN = 60 };
  620. MIDIDevice(USBHost &host) { init(); }
  621. MIDIDevice(USBHost *host) { init(); }
  622. bool read(uint8_t channel=0, uint8_t cable=0);
  623. uint8_t getType(void) {
  624. return msg_type;
  625. };
  626. uint8_t getChannel(void) {
  627. return msg_channel;
  628. };
  629. uint8_t getData1(void) {
  630. return msg_data1;
  631. };
  632. uint8_t getData2(void) {
  633. return msg_data2;
  634. };
  635. void setHandleNoteOff(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  636. handleNoteOff = f;
  637. };
  638. void setHandleNoteOn(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  639. handleNoteOn = f;
  640. };
  641. void setHandleVelocityChange(void (*f)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  642. handleVelocityChange = f;
  643. };
  644. void setHandleControlChange(void (*f)(uint8_t channel, uint8_t control, uint8_t value)) {
  645. handleControlChange = f;
  646. };
  647. void setHandleProgramChange(void (*f)(uint8_t channel, uint8_t program)) {
  648. handleProgramChange = f;
  649. };
  650. void setHandleAfterTouch(void (*f)(uint8_t channel, uint8_t pressure)) {
  651. handleAfterTouch = f;
  652. };
  653. void setHandlePitchChange(void (*f)(uint8_t channel, int pitch)) {
  654. handlePitchChange = f;
  655. };
  656. void setHandleSysEx(void (*f)(const uint8_t *data, uint16_t length, bool complete)) {
  657. handleSysEx = (void (*)(const uint8_t *, uint16_t, uint8_t))f;
  658. }
  659. void setHandleRealTimeSystem(void (*f)(uint8_t realtimebyte)) {
  660. handleRealTimeSystem = f;
  661. };
  662. void setHandleTimeCodeQuarterFrame(void (*f)(uint16_t data)) {
  663. handleTimeCodeQuarterFrame = f;
  664. };
  665. void sendNoteOff(uint32_t note, uint32_t velocity, uint32_t channel) {
  666. write_packed(0x8008 | (((channel - 1) & 0x0F) << 8)
  667. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  668. }
  669. void sendNoteOn(uint32_t note, uint32_t velocity, uint32_t channel) {
  670. write_packed(0x9009 | (((channel - 1) & 0x0F) << 8)
  671. | ((note & 0x7F) << 16) | ((velocity & 0x7F) << 24));
  672. }
  673. void sendPolyPressure(uint32_t note, uint32_t pressure, uint32_t channel) {
  674. write_packed(0xA00A | (((channel - 1) & 0x0F) << 8)
  675. | ((note & 0x7F) << 16) | ((pressure & 0x7F) << 24));
  676. }
  677. void sendControlChange(uint32_t control, uint32_t value, uint32_t channel) {
  678. write_packed(0xB00B | (((channel - 1) & 0x0F) << 8)
  679. | ((control & 0x7F) << 16) | ((value & 0x7F) << 24));
  680. }
  681. void sendProgramChange(uint32_t program, uint32_t channel) {
  682. write_packed(0xC00C | (((channel - 1) & 0x0F) << 8)
  683. | ((program & 0x7F) << 16));
  684. }
  685. void sendAfterTouch(uint32_t pressure, uint32_t channel) {
  686. write_packed(0xD00D | (((channel - 1) & 0x0F) << 8)
  687. | ((pressure & 0x7F) << 16));
  688. }
  689. void sendPitchBend(uint32_t value, uint32_t channel) {
  690. write_packed(0xE00E | (((channel - 1) & 0x0F) << 8)
  691. | ((value & 0x7F) << 16) | ((value & 0x3F80) << 17));
  692. }
  693. void sendSysEx(uint32_t length, const void *data);
  694. void sendRealTime(uint32_t type) {
  695. switch (type) {
  696. case 0xF8: // Clock
  697. case 0xFA: // Start
  698. case 0xFC: // Stop
  699. case 0xFB: // Continue
  700. case 0xFE: // ActiveSensing
  701. case 0xFF: // SystemReset
  702. write_packed((type << 8) | 0x0F);
  703. break;
  704. default: // Invalid Real Time marker
  705. break;
  706. }
  707. }
  708. void sendTimeCodeQuarterFrame(uint32_t type, uint32_t value) {
  709. uint32_t data = ( ((type & 0x07) << 4) | (value & 0x0F) );
  710. sendTimeCodeQuarterFrame(data);
  711. }
  712. void sendTimeCodeQuarterFrame(uint32_t data) {
  713. write_packed(0xF108 | ((data & 0x7F) << 16));
  714. }
  715. protected:
  716. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  717. virtual void disconnect();
  718. static void rx_callback(const Transfer_t *transfer);
  719. static void tx_callback(const Transfer_t *transfer);
  720. void rx_data(const Transfer_t *transfer);
  721. void tx_data(const Transfer_t *transfer);
  722. void init();
  723. void write_packed(uint32_t data);
  724. void sysex_byte(uint8_t b);
  725. private:
  726. Pipe_t *rxpipe;
  727. Pipe_t *txpipe;
  728. enum { MAX_PACKET_SIZE = 64 };
  729. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  730. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  731. uint32_t tx_buffer[MAX_PACKET_SIZE/4];
  732. uint16_t rx_size;
  733. uint16_t tx_size;
  734. uint32_t rx_queue[RX_QUEUE_SIZE];
  735. bool rx_packet_queued;
  736. uint16_t rx_head;
  737. uint16_t rx_tail;
  738. uint8_t rx_ep;
  739. uint8_t tx_ep;
  740. uint8_t msg_channel;
  741. uint8_t msg_type;
  742. uint8_t msg_data1;
  743. uint8_t msg_data2;
  744. uint8_t msg_sysex[SYSEX_MAX_LEN];
  745. uint8_t msg_sysex_len;
  746. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  747. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  748. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  749. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  750. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  751. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  752. void (*handlePitchChange)(uint8_t ch, int pitch);
  753. void (*handleSysEx)(const uint8_t *data, uint16_t length, uint8_t complete);
  754. void (*handleRealTimeSystem)(uint8_t rtb);
  755. void (*handleTimeCodeQuarterFrame)(uint16_t data);
  756. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  757. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  758. strbuf_t mystring_bufs[1];
  759. };
  760. class USBSerial: public USBDriver, public Stream {
  761. public:
  762. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  763. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  764. USBSerial(USBHost &host) : txtimer(this) { init(); }
  765. void begin(uint32_t baud, uint32_t format=0);
  766. void end(void);
  767. virtual int available(void);
  768. virtual int peek(void);
  769. virtual int read(void);
  770. virtual int availableForWrite();
  771. virtual size_t write(uint8_t c);
  772. using Print::write;
  773. protected:
  774. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  775. virtual void control(const Transfer_t *transfer);
  776. virtual void disconnect();
  777. virtual void timer_event(USBDriverTimer *whichTimer);
  778. private:
  779. static void rx_callback(const Transfer_t *transfer);
  780. static void tx_callback(const Transfer_t *transfer);
  781. void rx_data(const Transfer_t *transfer);
  782. void tx_data(const Transfer_t *transfer);
  783. void rx_queue_packets(uint32_t head, uint32_t tail);
  784. void init();
  785. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  786. bool init_buffers(uint32_t rsize, uint32_t tsize);
  787. private:
  788. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  789. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  790. strbuf_t mystring_bufs[1];
  791. USBDriverTimer txtimer;
  792. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  793. setup_t setup;
  794. uint8_t setupdata[8];
  795. uint32_t baudrate;
  796. Pipe_t *rxpipe;
  797. Pipe_t *txpipe;
  798. uint8_t *rx1; // location for first incoming packet
  799. uint8_t *rx2; // location for second incoming packet
  800. uint8_t *rxbuf; // receive circular buffer
  801. uint8_t *tx1; // location for first outgoing packet
  802. uint8_t *tx2; // location for second outgoing packet
  803. uint8_t *txbuf;
  804. volatile uint16_t rxhead;// receive head
  805. volatile uint16_t rxtail;// receive tail
  806. volatile uint16_t txhead;
  807. volatile uint16_t txtail;
  808. uint16_t rxsize;// size of receive circular buffer
  809. uint16_t txsize;// size of transmit circular buffer
  810. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  811. volatile uint8_t txstate;
  812. uint8_t pending_control;
  813. bool control_queued;
  814. enum { CDCACM, FTDI, PL2303, CH341 } sertype;
  815. };
  816. class AntPlus: public USBDriver {
  817. public:
  818. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  819. void begin(const uint8_t key=0);
  820. void onStatusChange(void (*function)(int channel, int status)) {
  821. user_onStatusChange = function;
  822. }
  823. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  824. user_onDeviceID = function;
  825. }
  826. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  827. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  828. memset(&hrm, 0, sizeof(hrm));
  829. user_onHeartRateMonitor = f;
  830. }
  831. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  832. user_onSpeedCadence = f;
  833. }
  834. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  835. user_onSpeed = f;
  836. }
  837. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  838. user_onCadence = f;
  839. }
  840. void setWheelCircumference(float meters) {
  841. wheelCircumference = meters * 1000.0f;
  842. }
  843. protected:
  844. virtual void Task();
  845. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  846. virtual void disconnect();
  847. virtual void timer_event(USBDriverTimer *whichTimer);
  848. private:
  849. static void rx_callback(const Transfer_t *transfer);
  850. static void tx_callback(const Transfer_t *transfer);
  851. void rx_data(const Transfer_t *transfer);
  852. void tx_data(const Transfer_t *transfer);
  853. void init();
  854. size_t write(const void *data, const size_t size);
  855. int read(void *data, const size_t size);
  856. void transmit();
  857. private:
  858. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  859. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  860. strbuf_t mystring_bufs[1];
  861. //USBDriverTimer txtimer;
  862. USBDriverTimer updatetimer;
  863. Pipe_t *rxpipe;
  864. Pipe_t *txpipe;
  865. bool first_update;
  866. uint8_t txbuffer[240];
  867. uint8_t rxpacket[64];
  868. volatile uint16_t txhead;
  869. volatile uint16_t txtail;
  870. volatile bool txready;
  871. volatile uint8_t rxlen;
  872. volatile bool do_polling;
  873. private:
  874. enum _eventi {
  875. EVENTI_MESSAGE = 0,
  876. EVENTI_CHANNEL,
  877. EVENTI_TOTAL
  878. };
  879. enum _profiles {
  880. PROFILE_HRM = 0,
  881. PROFILE_SPDCAD,
  882. PROFILE_POWER,
  883. PROFILE_STRIDE,
  884. PROFILE_SPEED,
  885. PROFILE_CADENCE,
  886. PROFILE_TOTAL
  887. };
  888. typedef struct {
  889. uint8_t channel;
  890. uint8_t RFFreq;
  891. uint8_t networkNumber;
  892. uint8_t stub;
  893. uint8_t searchTimeout;
  894. uint8_t channelType;
  895. uint8_t deviceType;
  896. uint8_t transType;
  897. uint16_t channelPeriod;
  898. uint16_t searchWaveform;
  899. uint32_t deviceNumber; // deviceId
  900. struct {
  901. uint8_t chanIdOnce;
  902. uint8_t keyAccepted;
  903. uint8_t profileValid;
  904. uint8_t channelStatus;
  905. uint8_t channelStatusOld;
  906. } flags;
  907. } TDCONFIG;
  908. struct {
  909. uint8_t initOnce;
  910. uint8_t key; // key index
  911. int iDevice; // index to the antplus we're interested in, if > one found
  912. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  913. } ant;
  914. void (*user_onStatusChange)(int channel, int status);
  915. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  916. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  917. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  918. void (*user_onSpeed)(float speed, float distance);
  919. void (*user_onCadence)(float cadence);
  920. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  921. static const uint8_t *getAntKey(const uint8_t keyIdx);
  922. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  923. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  924. static int msgCheckIntegrity(uint8_t *stream, const int len);
  925. static int msgGetLength(uint8_t *stream);
  926. int handleMessages(uint8_t *buffer, int tBytes);
  927. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  928. void message_channel(const int chan, const int eventId,
  929. const uint8_t *payload, const size_t dataLength);
  930. void message_response(const int chan, const int msgId,
  931. const uint8_t *payload, const size_t dataLength);
  932. void message_event(const int channel, const int msgId,
  933. const uint8_t *payload, const size_t dataLength);
  934. int ResetSystem();
  935. int RequestMessage(const int channel, const int message);
  936. int SetNetworkKey(const int netNumber, const uint8_t *key);
  937. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  938. int SetChannelPeriod(const int channel, const int period);
  939. int SetChannelRFFreq(const int channel, const int freq);
  940. int SetSearchWaveform(const int channel, const int wave);
  941. int OpenChannel(const int channel);
  942. int CloseChannel(const int channel);
  943. int AssignChannel(const int channel, const int channelType, const int network);
  944. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  945. const int transmissionType);
  946. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  947. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  948. int SendBroadcastData(const int channel, const uint8_t *data);
  949. int SendAcknowledgedData(const int channel, const uint8_t *data);
  950. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  951. const int TranType, const uint8_t *data);
  952. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  953. const int TranType, const uint8_t *data);
  954. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  955. const int devType, const int TranType, const uint8_t *data);
  956. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  957. const int tranType, const uint8_t *data, const int nunPackets);
  958. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  959. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  960. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  961. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  962. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  963. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  964. struct {
  965. struct {
  966. uint8_t bpm;
  967. uint8_t sequence;
  968. uint16_t time;
  969. } previous;
  970. } hrm;
  971. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  972. struct {
  973. struct {
  974. uint16_t cadenceTime;
  975. uint16_t cadenceCt;
  976. uint16_t speedTime;
  977. uint16_t speedCt;
  978. } previous;
  979. float distance;
  980. } spdcad;
  981. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  982. /* struct {
  983. struct {
  984. uint8_t sequence;
  985. uint16_t pedalPowerContribution;
  986. uint8_t pedalPower;
  987. uint8_t instantCadence;
  988. uint16_t sumPower;
  989. uint16_t instantPower;
  990. } current;
  991. struct {
  992. uint16_t stub;
  993. } previous;
  994. } pwr; */
  995. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  996. /* struct {
  997. struct {
  998. uint16_t speed;
  999. uint16_t cadence;
  1000. uint8_t strides;
  1001. } current;
  1002. struct {
  1003. uint8_t strides;
  1004. uint16_t speed;
  1005. uint16_t cadence;
  1006. } previous;
  1007. } stride; */
  1008. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1009. struct {
  1010. struct {
  1011. uint16_t speedTime;
  1012. uint16_t speedCt;
  1013. } previous;
  1014. float distance;
  1015. } spd;
  1016. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1017. struct {
  1018. struct {
  1019. uint16_t cadenceTime;
  1020. uint16_t cadenceCt;
  1021. } previous;
  1022. } cad;
  1023. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1024. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1025. };
  1026. class MouseController : public USBHIDInput {
  1027. public:
  1028. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  1029. bool available() { return mouseEvent; }
  1030. void mouseDataClear();
  1031. uint8_t getButtons() { return buttons; }
  1032. int getMouseX() { return mouseX; }
  1033. int getMouseY() { return mouseY; }
  1034. int getWheel() { return wheel; }
  1035. int getWheelH() { return wheelH; }
  1036. protected:
  1037. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  1038. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1039. virtual void hid_input_data(uint32_t usage, int32_t value);
  1040. virtual void hid_input_end();
  1041. virtual void disconnect_collection(Device_t *dev);
  1042. private:
  1043. uint8_t collections_claimed = 0;
  1044. volatile bool mouseEvent = false;
  1045. volatile bool hid_input_begin_ = false;
  1046. uint8_t buttons = 0;
  1047. int mouseX = 0;
  1048. int mouseY = 0;
  1049. int wheel = 0;
  1050. int wheelH = 0;
  1051. };
  1052. class JoystickController : public USBHIDInput {
  1053. public:
  1054. JoystickController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  1055. bool available() { return joystickEvent; }
  1056. void joystickDataClear();
  1057. uint32_t getButtons() { return buttons; }
  1058. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  1059. protected:
  1060. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  1061. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1062. virtual void hid_input_data(uint32_t usage, int32_t value);
  1063. virtual void hid_input_end();
  1064. virtual void disconnect_collection(Device_t *dev);
  1065. private:
  1066. uint8_t collections_claimed = 0;
  1067. bool anychange = false;
  1068. volatile bool joystickEvent = false;
  1069. uint32_t buttons = 0;
  1070. int16_t axis[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  1071. };
  1072. class KeyboardHIDExtrasController : public USBHIDInput {
  1073. public:
  1074. KeyboardHIDExtrasController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  1075. void clear() { event_ = false;}
  1076. bool available() { return event_; }
  1077. void attachPress(void (*f)(uint32_t top, uint16_t code)) { keyPressedFunction = f; }
  1078. void attachRelease(void (*f)(uint32_t top, uint16_t code)) { keyReleasedFunction = f; }
  1079. enum {MAX_KEYS_DOWN=4};
  1080. // uint32_t buttons() { return buttons_; }
  1081. protected:
  1082. virtual bool claim_collection(Device_t *dev, uint32_t topusage);
  1083. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1084. virtual void hid_input_data(uint32_t usage, int32_t value);
  1085. virtual void hid_input_end();
  1086. virtual void disconnect_collection(Device_t *dev);
  1087. private:
  1088. void (*keyPressedFunction)(uint32_t top, uint16_t code);
  1089. void (*keyReleasedFunction)(uint32_t top, uint16_t code);
  1090. uint32_t topusage_ = 0; // What top report am I processing?
  1091. uint8_t collections_claimed_ = 0;
  1092. volatile bool event_ = false;
  1093. volatile bool hid_input_begin_ = false;
  1094. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  1095. uint8_t count_keys_down_ = 0;
  1096. uint16_t keys_down[MAX_KEYS_DOWN];
  1097. };
  1098. #endif