Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

USBHost_t36.h 57KB

il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  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. typedef enum { CLAIM_NO=0, CLAIM_REPORT, CLAIM_INTERFACE} hidclaim_t;
  74. // All USB device drivers inherit use these classes.
  75. // Drivers build user-visible functionality on top
  76. // of these classes, which receive USB events from
  77. // USBHost.
  78. class USBDriver;
  79. class USBDriverTimer;
  80. /************************************************/
  81. /* Added Defines */
  82. /************************************************/
  83. // Keyboard special Keys
  84. #define KEYD_UP 0xDA
  85. #define KEYD_DOWN 0xD9
  86. #define KEYD_LEFT 0xD8
  87. #define KEYD_RIGHT 0xD7
  88. #define KEYD_INSERT 0xD1
  89. #define KEYD_DELETE 0xD4
  90. #define KEYD_PAGE_UP 0xD3
  91. #define KEYD_PAGE_DOWN 0xD6
  92. #define KEYD_HOME 0xD2
  93. #define KEYD_END 0xD5
  94. #define KEYD_F1 0xC2
  95. #define KEYD_F2 0xC3
  96. #define KEYD_F3 0xC4
  97. #define KEYD_F4 0xC5
  98. #define KEYD_F5 0xC6
  99. #define KEYD_F6 0xC7
  100. #define KEYD_F7 0xC8
  101. #define KEYD_F8 0xC9
  102. #define KEYD_F9 0xCA
  103. #define KEYD_F10 0xCB
  104. #define KEYD_F11 0xCC
  105. #define KEYD_F12 0xCD
  106. // USBSerial formats - Lets encode format into bits
  107. // Bits: 0-4 - Number of data bits
  108. // Bits: 5-7 - Parity (0=none, 1=odd, 2 = even)
  109. // bits: 8-9 - Stop bits. 0=1, 1=2
  110. #define USBHOST_SERIAL_7E1 0x047
  111. #define USBHOST_SERIAL_7O1 0x027
  112. #define USBHOST_SERIAL_8N1 0x08
  113. #define USBHOST_SERIAL_8N2 0x108
  114. #define USBHOST_SERIAL_8E1 0x048
  115. #define USBHOST_SERIAL_8O1 0x028
  116. /************************************************/
  117. /* Data Structure Definitions */
  118. /************************************************/
  119. // setup_t holds the 8 byte USB SETUP packet data.
  120. // These unions & structs allow convenient access to
  121. // the setup fields.
  122. typedef union {
  123. struct {
  124. union {
  125. struct {
  126. uint8_t bmRequestType;
  127. uint8_t bRequest;
  128. };
  129. uint16_t wRequestAndType;
  130. };
  131. uint16_t wValue;
  132. uint16_t wIndex;
  133. uint16_t wLength;
  134. };
  135. struct {
  136. uint32_t word1;
  137. uint32_t word2;
  138. };
  139. } setup_t;
  140. typedef struct {
  141. enum {STRING_BUF_SIZE=50};
  142. enum {STR_ID_MAN=0, STR_ID_PROD, STR_ID_SERIAL, STR_ID_CNT};
  143. uint8_t iStrings[STR_ID_CNT]; // Index into array for the three indexes
  144. uint8_t buffer[STRING_BUF_SIZE];
  145. } strbuf_t;
  146. #define DEVICE_STRUCT_STRING_BUF_SIZE 50
  147. // Device_t holds all the information about a USB device
  148. struct Device_struct {
  149. Pipe_t *control_pipe;
  150. Pipe_t *data_pipes;
  151. Device_t *next;
  152. USBDriver *drivers;
  153. strbuf_t *strbuf;
  154. uint8_t speed; // 0=12, 1=1.5, 2=480 Mbit/sec
  155. uint8_t address;
  156. uint8_t hub_address;
  157. uint8_t hub_port;
  158. uint8_t enum_state;
  159. uint8_t bDeviceClass;
  160. uint8_t bDeviceSubClass;
  161. uint8_t bDeviceProtocol;
  162. uint8_t bmAttributes;
  163. uint8_t bMaxPower;
  164. uint16_t idVendor;
  165. uint16_t idProduct;
  166. uint16_t LanguageID;
  167. };
  168. // Pipe_t holes all information about each USB endpoint/pipe
  169. // The first half is an EHCI QH structure for the pipe.
  170. struct Pipe_struct {
  171. // Queue Head (QH), EHCI page 46-50
  172. struct { // must be aligned to 32 byte boundary
  173. volatile uint32_t horizontal_link;
  174. volatile uint32_t capabilities[2];
  175. volatile uint32_t current;
  176. volatile uint32_t next;
  177. volatile uint32_t alt_next;
  178. volatile uint32_t token;
  179. volatile uint32_t buffer[5];
  180. } qh;
  181. Device_t *device;
  182. uint8_t type; // 0=control, 1=isochronous, 2=bulk, 3=interrupt
  183. uint8_t direction; // 0=out, 1=in (changes for control, others fixed)
  184. uint8_t start_mask;
  185. uint8_t complete_mask;
  186. Pipe_t *next;
  187. void (*callback_function)(const Transfer_t *);
  188. uint16_t periodic_interval;
  189. uint16_t periodic_offset;
  190. uint16_t bandwidth_interval;
  191. uint16_t bandwidth_offset;
  192. uint16_t bandwidth_shift;
  193. uint8_t bandwidth_stime;
  194. uint8_t bandwidth_ctime;
  195. uint32_t unused1;
  196. uint32_t unused2;
  197. uint32_t unused3;
  198. uint32_t unused4;
  199. uint32_t unused5;
  200. };
  201. // Transfer_t represents a single transaction on the USB bus.
  202. // The first portion is an EHCI qTD structure. Transfer_t are
  203. // allocated as-needed from a memory pool, loaded with pointers
  204. // to the actual data buffers, linked into a followup list,
  205. // and placed on ECHI Queue Heads. When the ECHI interrupt
  206. // occurs, the followup lists are used to find the Transfer_t
  207. // in memory. Callbacks are made, and then the Transfer_t are
  208. // returned to the memory pool.
  209. struct Transfer_struct {
  210. // Queue Element Transfer Descriptor (qTD), EHCI pg 40-45
  211. struct { // must be aligned to 32 byte boundary
  212. volatile uint32_t next;
  213. volatile uint32_t alt_next;
  214. volatile uint32_t token;
  215. volatile uint32_t buffer[5];
  216. } qtd;
  217. // Linked list of queued, not-yet-completed transfers
  218. Transfer_t *next_followup;
  219. Transfer_t *prev_followup;
  220. Pipe_t *pipe;
  221. // Data to be used by callback function. When a group
  222. // of Transfer_t are created, these fields and the
  223. // interrupt-on-complete bit in the qTD token are only
  224. // set in the last Transfer_t of the list.
  225. void *buffer;
  226. uint32_t length;
  227. setup_t setup;
  228. USBDriver *driver;
  229. };
  230. /************************************************/
  231. /* Main USB EHCI Controller */
  232. /************************************************/
  233. class USBHost {
  234. public:
  235. static void begin();
  236. static void Task();
  237. static void countFree(uint32_t &devices, uint32_t &pipes, uint32_t &trans, uint32_t &strs);
  238. protected:
  239. static Pipe_t * new_Pipe(Device_t *dev, uint32_t type, uint32_t endpoint,
  240. uint32_t direction, uint32_t maxlen, uint32_t interval=0);
  241. static bool queue_Control_Transfer(Device_t *dev, setup_t *setup,
  242. void *buf, USBDriver *driver);
  243. static bool queue_Data_Transfer(Pipe_t *pipe, void *buffer,
  244. uint32_t len, USBDriver *driver);
  245. static Device_t * new_Device(uint32_t speed, uint32_t hub_addr, uint32_t hub_port);
  246. static void disconnect_Device(Device_t *dev);
  247. static void enumeration(const Transfer_t *transfer);
  248. static void driver_ready_for_device(USBDriver *driver);
  249. static volatile bool enumeration_busy;
  250. public: // Maybe others may want/need to contribute memory example HID devices may want to add transfers.
  251. static void contribute_Devices(Device_t *devices, uint32_t num);
  252. static void contribute_Pipes(Pipe_t *pipes, uint32_t num);
  253. static void contribute_Transfers(Transfer_t *transfers, uint32_t num);
  254. static void contribute_String_Buffers(strbuf_t *strbuf, uint32_t num);
  255. private:
  256. static void isr();
  257. static void convertStringDescriptorToASCIIString(uint8_t string_index, Device_t *dev, const Transfer_t *transfer);
  258. static void claim_drivers(Device_t *dev);
  259. static uint32_t assign_address(void);
  260. static bool queue_Transfer(Pipe_t *pipe, Transfer_t *transfer);
  261. static void init_Device_Pipe_Transfer_memory(void);
  262. static Device_t * allocate_Device(void);
  263. static void delete_Pipe(Pipe_t *pipe);
  264. static void free_Device(Device_t *q);
  265. static Pipe_t * allocate_Pipe(void);
  266. static void free_Pipe(Pipe_t *q);
  267. static Transfer_t * allocate_Transfer(void);
  268. static void free_Transfer(Transfer_t *q);
  269. static strbuf_t * allocate_string_buffer(void);
  270. static void free_string_buffer(strbuf_t *strbuf);
  271. static bool allocate_interrupt_pipe_bandwidth(Pipe_t *pipe,
  272. uint32_t maxlen, uint32_t interval);
  273. static void add_qh_to_periodic_schedule(Pipe_t *pipe);
  274. static bool followup_Transfer(Transfer_t *transfer);
  275. static void followup_Error(void);
  276. protected:
  277. #ifdef USBHOST_PRINT_DEBUG
  278. static void print_(const Transfer_t *transfer);
  279. static void print_(const Transfer_t *first, const Transfer_t *last);
  280. static void print_token(uint32_t token);
  281. static void print_(const Pipe_t *pipe);
  282. static void print_driverlist(const char *name, const USBDriver *driver);
  283. static void print_qh_list(const Pipe_t *list);
  284. static void print_hexbytes(const void *ptr, uint32_t len);
  285. static void print_(const char *s) { Serial.print(s); }
  286. static void print_(int n) { Serial.print(n); }
  287. static void print_(unsigned int n) { Serial.print(n); }
  288. static void print_(long n) { Serial.print(n); }
  289. static void print_(unsigned long n) { Serial.print(n); }
  290. static void println_(const char *s) { Serial.println(s); }
  291. static void println_(int n) { Serial.println(n); }
  292. static void println_(unsigned int n) { Serial.println(n); }
  293. static void println_(long n) { Serial.println(n); }
  294. static void println_(unsigned long n) { Serial.println(n); }
  295. static void println_() { Serial.println(); }
  296. static void print_(uint32_t n, uint8_t b) { Serial.print(n, b); }
  297. static void println_(uint32_t n, uint8_t b) { Serial.println(n, b); }
  298. static void print_(const char *s, int n, uint8_t b = DEC) {
  299. Serial.print(s); Serial.print(n, b); }
  300. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {
  301. Serial.print(s); Serial.print(n, b); }
  302. static void print_(const char *s, long n, uint8_t b = DEC) {
  303. Serial.print(s); Serial.print(n, b); }
  304. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {
  305. Serial.print(s); Serial.print(n, b); }
  306. static void println_(const char *s, int n, uint8_t b = DEC) {
  307. Serial.print(s); Serial.println(n, b); }
  308. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {
  309. Serial.print(s); Serial.println(n, b); }
  310. static void println_(const char *s, long n, uint8_t b = DEC) {
  311. Serial.print(s); Serial.println(n, b); }
  312. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {
  313. Serial.print(s); Serial.println(n, b); }
  314. friend class USBDriverTimer; // for access to print & println
  315. #else
  316. static void print_(const Transfer_t *transfer) {}
  317. static void print_(const Transfer_t *first, const Transfer_t *last) {}
  318. static void print_token(uint32_t token) {}
  319. static void print_(const Pipe_t *pipe) {}
  320. static void print_driverlist(const char *name, const USBDriver *driver) {}
  321. static void print_qh_list(const Pipe_t *list) {}
  322. static void print_hexbytes(const void *ptr, uint32_t len) {}
  323. static void print_(const char *s) {}
  324. static void print_(int n) {}
  325. static void print_(unsigned int n) {}
  326. static void print_(long n) {}
  327. static void print_(unsigned long n) {}
  328. static void println_(const char *s) {}
  329. static void println_(int n) {}
  330. static void println_(unsigned int n) {}
  331. static void println_(long n) {}
  332. static void println_(unsigned long n) {}
  333. static void println_() {}
  334. static void print_(uint32_t n, uint8_t b) {}
  335. static void println_(uint32_t n, uint8_t b) {}
  336. static void print_(const char *s, int n, uint8_t b = DEC) {}
  337. static void print_(const char *s, unsigned int n, uint8_t b = DEC) {}
  338. static void print_(const char *s, long n, uint8_t b = DEC) {}
  339. static void print_(const char *s, unsigned long n, uint8_t b = DEC) {}
  340. static void println_(const char *s, int n, uint8_t b = DEC) {}
  341. static void println_(const char *s, unsigned int n, uint8_t b = DEC) {}
  342. static void println_(const char *s, long n, uint8_t b = DEC) {}
  343. static void println_(const char *s, unsigned long n, uint8_t b = DEC) {}
  344. #endif
  345. static void mk_setup(setup_t &s, uint32_t bmRequestType, uint32_t bRequest,
  346. uint32_t wValue, uint32_t wIndex, uint32_t wLength) {
  347. s.word1 = bmRequestType | (bRequest << 8) | (wValue << 16);
  348. s.word2 = wIndex | (wLength << 16);
  349. }
  350. };
  351. /************************************************/
  352. /* USB Device Driver Common Base Class */
  353. /************************************************/
  354. // All USB device drivers inherit from this base class.
  355. class USBDriver : public USBHost {
  356. public:
  357. operator bool() {
  358. Device_t *dev = *(Device_t * volatile *)&device;
  359. return dev != nullptr;
  360. }
  361. uint16_t idVendor() {
  362. Device_t *dev = *(Device_t * volatile *)&device;
  363. return (dev != nullptr) ? dev->idVendor : 0;
  364. }
  365. uint16_t idProduct() {
  366. Device_t *dev = *(Device_t * volatile *)&device;
  367. return (dev != nullptr) ? dev->idProduct : 0;
  368. }
  369. const uint8_t *manufacturer() {
  370. Device_t *dev = *(Device_t * volatile *)&device;
  371. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  372. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_MAN]];
  373. }
  374. const uint8_t *product() {
  375. Device_t *dev = *(Device_t * volatile *)&device;
  376. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  377. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_PROD]];
  378. }
  379. const uint8_t *serialNumber() {
  380. Device_t *dev = *(Device_t * volatile *)&device;
  381. if (dev == nullptr || dev->strbuf == nullptr) return nullptr;
  382. return &dev->strbuf->buffer[dev->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]];
  383. }
  384. protected:
  385. USBDriver() : next(NULL), device(NULL) {}
  386. // Check if a driver wishes to claim a device or interface or group
  387. // of interfaces within a device. When this function returns true,
  388. // the driver is considered bound or loaded for that device. When
  389. // new devices are detected, enumeration.cpp calls this function on
  390. // all unbound driver objects, to give them an opportunity to bind
  391. // to the new device.
  392. // device has its vid&pid, class/subclass fields initialized
  393. // type is 0 for device level, 1 for interface level, 2 for IAD
  394. // descriptors points to the specific descriptor data
  395. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  396. // When an unknown (not chapter 9) control transfer completes, this
  397. // function is called for all drivers bound to the device. Return
  398. // true means this driver originated this control transfer, so no
  399. // more drivers need to be offered an opportunity to process it.
  400. // This function is optional, only needed if the driver uses control
  401. // transfers and wishes to be notified when they complete.
  402. virtual void control(const Transfer_t *transfer) { }
  403. // When any of the USBDriverTimer objects a driver creates generates
  404. // a timer event, this function is called.
  405. virtual void timer_event(USBDriverTimer *whichTimer) { }
  406. // When the user calls USBHost::Task, this Task function for all
  407. // active drivers is called, so they may update state and/or call
  408. // any attached user callback functions.
  409. virtual void Task() { }
  410. // When a device disconnects from the USB, this function is called.
  411. // The driver must free all resources it allocated and update any
  412. // internal state necessary to deal with the possibility of user
  413. // code continuing to call its API. However, pipes and transfers
  414. // are the handled by lower layers, so device drivers do not free
  415. // pipes they created or cancel transfers they had in progress.
  416. virtual void disconnect();
  417. // Drivers are managed by this single-linked list. All inactive
  418. // (not bound to any device) drivers are linked from
  419. // available_drivers in enumeration.cpp. When bound to a device,
  420. // drivers are linked from that Device_t drivers list.
  421. USBDriver *next;
  422. // The device this object instance is bound to. In words, this
  423. // is the specific device this driver is using. When not bound
  424. // to any device, this must be NULL. Drivers may set this to
  425. // any non-NULL value if they are in a state where they do not
  426. // wish to claim any device or interface (eg, if getting data
  427. // from the HID parser).
  428. Device_t *device;
  429. friend class USBHost;
  430. };
  431. // Device drivers may create these timer objects to schedule a timer call
  432. class USBDriverTimer {
  433. public:
  434. USBDriverTimer() { }
  435. USBDriverTimer(USBDriver *d) : driver(d) { }
  436. void init(USBDriver *d) { driver = d; };
  437. void start(uint32_t microseconds);
  438. void stop();
  439. void *pointer;
  440. uint32_t integer;
  441. uint32_t started_micros; // testing only
  442. private:
  443. USBDriver *driver;
  444. uint32_t usec;
  445. USBDriverTimer *next;
  446. USBDriverTimer *prev;
  447. friend class USBHost;
  448. };
  449. // Device drivers may inherit from this base class, if they wish to receive
  450. // HID input data fully decoded by the USBHIDParser driver
  451. class USBHIDParser;
  452. class USBHIDInput {
  453. public:
  454. operator bool() { return (mydevice != nullptr); }
  455. uint16_t idVendor() { return (mydevice != nullptr) ? mydevice->idVendor : 0; }
  456. uint16_t idProduct() { return (mydevice != nullptr) ? mydevice->idProduct : 0; }
  457. const uint8_t *manufacturer()
  458. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_MAN]]; }
  459. const uint8_t *product()
  460. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_PROD]]; }
  461. const uint8_t *serialNumber()
  462. { return ((mydevice == nullptr) || (mydevice->strbuf == nullptr)) ? nullptr : &mydevice->strbuf->buffer[mydevice->strbuf->iStrings[strbuf_t::STR_ID_SERIAL]]; }
  463. private:
  464. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  465. virtual bool hid_process_in_data(const Transfer_t *transfer) {return false;}
  466. virtual bool hid_process_out_data(const Transfer_t *transfer) {return false;}
  467. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  468. virtual void hid_input_data(uint32_t usage, int32_t value);
  469. virtual void hid_input_end();
  470. virtual void disconnect_collection(Device_t *dev);
  471. void add_to_list();
  472. USBHIDInput *next;
  473. friend class USBHIDParser;
  474. protected:
  475. Device_t *mydevice = NULL;
  476. };
  477. /************************************************/
  478. /* USB Device Drivers */
  479. /************************************************/
  480. class USBHub : public USBDriver {
  481. public:
  482. USBHub(USBHost &host) : debouncetimer(this), resettimer(this) { init(); }
  483. USBHub(USBHost *host) : debouncetimer(this), resettimer(this) { init(); }
  484. // Hubs with more more than 7 ports are built from two tiers of hubs
  485. // using 4 or 7 port hub chips. While the USB spec seems to allow
  486. // hubs to have up to 255 ports, in practice all hub chips on the
  487. // market are only 2, 3, 4 or 7 ports.
  488. enum { MAXPORTS = 7 };
  489. typedef uint8_t portbitmask_t;
  490. enum {
  491. PORT_OFF = 0,
  492. PORT_DISCONNECT = 1,
  493. PORT_DEBOUNCE1 = 2,
  494. PORT_DEBOUNCE2 = 3,
  495. PORT_DEBOUNCE3 = 4,
  496. PORT_DEBOUNCE4 = 5,
  497. PORT_DEBOUNCE5 = 6,
  498. PORT_RESET = 7,
  499. PORT_RECOVERY = 8,
  500. PORT_ACTIVE = 9
  501. };
  502. protected:
  503. virtual bool claim(Device_t *dev, int type, const uint8_t *descriptors, uint32_t len);
  504. virtual void control(const Transfer_t *transfer);
  505. virtual void timer_event(USBDriverTimer *whichTimer);
  506. virtual void disconnect();
  507. void init();
  508. bool can_send_control_now();
  509. void send_poweron(uint32_t port);
  510. void send_getstatus(uint32_t port);
  511. void send_clearstatus_connect(uint32_t port);
  512. void send_clearstatus_enable(uint32_t port);
  513. void send_clearstatus_suspend(uint32_t port);
  514. void send_clearstatus_overcurrent(uint32_t port);
  515. void send_clearstatus_reset(uint32_t port);
  516. void send_setreset(uint32_t port);
  517. static void callback(const Transfer_t *transfer);
  518. void status_change(const Transfer_t *transfer);
  519. void new_port_status(uint32_t port, uint32_t status);
  520. void start_debounce_timer(uint32_t port);
  521. void stop_debounce_timer(uint32_t port);
  522. private:
  523. Device_t mydevices[MAXPORTS];
  524. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  525. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  526. strbuf_t mystring_bufs[1];
  527. USBDriverTimer debouncetimer;
  528. USBDriverTimer resettimer;
  529. setup_t setup;
  530. Pipe_t *changepipe;
  531. Device_t *devicelist[MAXPORTS];
  532. uint32_t changebits;
  533. uint32_t statusbits;
  534. uint8_t hub_desc[16];
  535. uint8_t endpoint;
  536. uint8_t interval;
  537. uint8_t numports;
  538. uint8_t characteristics;
  539. uint8_t powertime;
  540. uint8_t sending_control_transfer;
  541. uint8_t port_doing_reset;
  542. uint8_t port_doing_reset_speed;
  543. uint8_t portstate[MAXPORTS];
  544. portbitmask_t send_pending_poweron;
  545. portbitmask_t send_pending_getstatus;
  546. portbitmask_t send_pending_clearstatus_connect;
  547. portbitmask_t send_pending_clearstatus_enable;
  548. portbitmask_t send_pending_clearstatus_suspend;
  549. portbitmask_t send_pending_clearstatus_overcurrent;
  550. portbitmask_t send_pending_clearstatus_reset;
  551. portbitmask_t send_pending_setreset;
  552. portbitmask_t debounce_in_use;
  553. static volatile bool reset_busy;
  554. };
  555. //--------------------------------------------------------------------------
  556. class USBHIDParser : public USBDriver {
  557. public:
  558. USBHIDParser(USBHost &host) { init(); }
  559. static void driver_ready_for_hid_collection(USBHIDInput *driver);
  560. bool sendPacket(const uint8_t *buffer, int cb=-1);
  561. void setTXBuffers(uint8_t *buffer1, uint8_t *buffer2, uint8_t cb);
  562. bool sendControlPacket(uint32_t bmRequestType, uint32_t bRequest,
  563. uint32_t wValue, uint32_t wIndex, uint32_t wLength, void *buf);
  564. protected:
  565. enum { TOPUSAGE_LIST_LEN = 4 };
  566. enum { USAGE_LIST_LEN = 24 };
  567. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  568. virtual void control(const Transfer_t *transfer);
  569. virtual void disconnect();
  570. static void in_callback(const Transfer_t *transfer);
  571. static void out_callback(const Transfer_t *transfer);
  572. void in_data(const Transfer_t *transfer);
  573. void out_data(const Transfer_t *transfer);
  574. bool check_if_using_report_id();
  575. void parse();
  576. USBHIDInput * find_driver(uint32_t topusage);
  577. void parse(uint16_t type_and_report_id, const uint8_t *data, uint32_t len);
  578. void init();
  579. // Atempt for RAWhid to take over processing of data
  580. //
  581. uint16_t inSize(void) {return in_size;}
  582. uint16_t outSize(void) {return out_size;}
  583. uint8_t activeSendMask(void) {return txstate;}
  584. private:
  585. Pipe_t *in_pipe;
  586. Pipe_t *out_pipe;
  587. static USBHIDInput *available_hid_drivers_list;
  588. //uint32_t topusage_list[TOPUSAGE_LIST_LEN];
  589. USBHIDInput *topusage_drivers[TOPUSAGE_LIST_LEN];
  590. uint16_t in_size;
  591. uint16_t out_size;
  592. setup_t setup;
  593. uint8_t descriptor[512];
  594. uint8_t report[64];
  595. uint16_t descsize;
  596. bool use_report_id;
  597. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  598. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  599. strbuf_t mystring_bufs[1];
  600. uint8_t txstate = 0;
  601. uint8_t *tx1 = nullptr;
  602. uint8_t *tx2 = nullptr;
  603. bool hid_driver_claimed_control_ = false;
  604. };
  605. //--------------------------------------------------------------------------
  606. class KeyboardController : public USBDriver , public USBHIDInput {
  607. public:
  608. typedef union {
  609. struct {
  610. uint8_t numLock : 1;
  611. uint8_t capsLock : 1;
  612. uint8_t scrollLock : 1;
  613. uint8_t compose : 1;
  614. uint8_t kana : 1;
  615. uint8_t reserved : 3;
  616. };
  617. uint8_t byte;
  618. } KBDLeds_t;
  619. public:
  620. KeyboardController(USBHost &host) { init(); }
  621. KeyboardController(USBHost *host) { init(); }
  622. // Some methods are in both public classes so we need to figure out which one to use
  623. operator bool() { return (device != nullptr); }
  624. // Main boot keyboard functions.
  625. uint16_t getKey() { return keyCode; }
  626. uint8_t getModifiers() { return modifiers; }
  627. uint8_t getOemKey() { return keyOEM; }
  628. void attachPress(void (*f)(int unicode)) { keyPressedFunction = f; }
  629. void attachRelease(void (*f)(int unicode)) { keyReleasedFunction = f; }
  630. void LEDS(uint8_t leds);
  631. uint8_t LEDS() {return leds_.byte;}
  632. void updateLEDS(void);
  633. bool numLock() {return leds_.numLock;}
  634. bool capsLock() {return leds_.capsLock;}
  635. bool scrollLock() {return leds_.scrollLock;}
  636. void numLock(bool f);
  637. void capsLock(bool f);
  638. void scrollLock(bool f);
  639. // Added for extras information.
  640. void attachExtrasPress(void (*f)(uint32_t top, uint16_t code)) { extrasKeyPressedFunction = f; }
  641. void attachExtrasRelease(void (*f)(uint32_t top, uint16_t code)) { extrasKeyReleasedFunction = f; }
  642. enum {MAX_KEYS_DOWN=4};
  643. protected:
  644. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  645. virtual void control(const Transfer_t *transfer);
  646. virtual void disconnect();
  647. static void callback(const Transfer_t *transfer);
  648. void new_data(const Transfer_t *transfer);
  649. void init();
  650. protected: // HID functions for extra keyboard data.
  651. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  652. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  653. virtual void hid_input_data(uint32_t usage, int32_t value);
  654. virtual void hid_input_end();
  655. virtual void disconnect_collection(Device_t *dev);
  656. private:
  657. void update();
  658. uint16_t convert_to_unicode(uint32_t mod, uint32_t key);
  659. void key_press(uint32_t mod, uint32_t key);
  660. void key_release(uint32_t mod, uint32_t key);
  661. void (*keyPressedFunction)(int unicode);
  662. void (*keyReleasedFunction)(int unicode);
  663. Pipe_t *datapipe;
  664. setup_t setup;
  665. uint8_t report[8];
  666. uint16_t keyCode;
  667. uint8_t modifiers;
  668. uint8_t keyOEM;
  669. uint8_t prev_report[8];
  670. KBDLeds_t leds_ = {0};
  671. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  672. Transfer_t mytransfers[4] __attribute__ ((aligned(32)));
  673. strbuf_t mystring_bufs[1];
  674. // Added to process secondary HID data.
  675. void (*extrasKeyPressedFunction)(uint32_t top, uint16_t code);
  676. void (*extrasKeyReleasedFunction)(uint32_t top, uint16_t code);
  677. uint32_t topusage_ = 0; // What top report am I processing?
  678. uint8_t collections_claimed_ = 0;
  679. volatile bool hid_input_begin_ = false;
  680. volatile bool hid_input_data_ = false; // did we receive any valid data with report?
  681. uint8_t count_keys_down_ = 0;
  682. uint16_t keys_down[MAX_KEYS_DOWN];
  683. };
  684. class MouseController : public USBHIDInput {
  685. public:
  686. MouseController(USBHost &host) { USBHIDParser::driver_ready_for_hid_collection(this); }
  687. bool available() { return mouseEvent; }
  688. void mouseDataClear();
  689. uint8_t getButtons() { return buttons; }
  690. int getMouseX() { return mouseX; }
  691. int getMouseY() { return mouseY; }
  692. int getWheel() { return wheel; }
  693. int getWheelH() { return wheelH; }
  694. protected:
  695. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  696. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  697. virtual void hid_input_data(uint32_t usage, int32_t value);
  698. virtual void hid_input_end();
  699. virtual void disconnect_collection(Device_t *dev);
  700. private:
  701. uint8_t collections_claimed = 0;
  702. volatile bool mouseEvent = false;
  703. volatile bool hid_input_begin_ = false;
  704. uint8_t buttons = 0;
  705. int mouseX = 0;
  706. int mouseY = 0;
  707. int wheel = 0;
  708. int wheelH = 0;
  709. };
  710. //--------------------------------------------------------------------------
  711. class JoystickController : public USBDriver, public USBHIDInput {
  712. public:
  713. JoystickController(USBHost &host) { init(); }
  714. uint16_t idVendor();
  715. uint16_t idProduct();
  716. const uint8_t *manufacturer();
  717. const uint8_t *product();
  718. const uint8_t *serialNumber();
  719. operator bool() { return (((device != nullptr) || (mydevice != nullptr)) && connected_); } // override as in both USBDriver and in USBHIDInput
  720. bool available() { return joystickEvent; }
  721. void joystickDataClear();
  722. uint32_t getButtons() { return buttons; }
  723. int getAxis(uint32_t index) { return (index < (sizeof(axis)/sizeof(axis[0]))) ? axis[index] : 0; }
  724. uint64_t axisMask() {return axis_mask_;}
  725. uint64_t axisChangedMask() { return axis_changed_mask_;}
  726. uint64_t axisChangeNotifyMask() {return axis_change_notify_mask_;}
  727. void axisChangeNotifyMask(uint64_t notify_mask) {axis_change_notify_mask_ = notify_mask;}
  728. // set functions functionality depends on underlying joystick.
  729. bool setRumble(uint8_t lValue, uint8_t rValue, uint8_t timeout=0xff);
  730. // setLEDs on PS4(RGB), PS3 simple LED setting (only uses lr)
  731. bool setLEDs(uint8_t lr, uint8_t lg=0, uint8_t lb=0); // sets Leds,
  732. enum { STANDARD_AXIS_COUNT = 10, ADDITIONAL_AXIS_COUNT = 54, TOTAL_AXIS_COUNT = (STANDARD_AXIS_COUNT+ADDITIONAL_AXIS_COUNT) };
  733. typedef enum { UNKNOWN=0, PS3, PS4, XBOXONE, XBOX360} joytype_t;
  734. joytype_t joystickType = UNKNOWN;
  735. protected:
  736. // From USBDriver
  737. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  738. virtual void control(const Transfer_t *transfer);
  739. virtual void disconnect();
  740. // From USBHIDInput
  741. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  742. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  743. virtual void hid_input_data(uint32_t usage, int32_t value);
  744. virtual void hid_input_end();
  745. virtual void disconnect_collection(Device_t *dev);
  746. virtual bool hid_process_out_data(const Transfer_t *transfer);
  747. private:
  748. // Class specific
  749. void init();
  750. USBHIDParser *driver_ = nullptr;
  751. joytype_t mapVIDPIDtoJoystickType(uint16_t idVendor, uint16_t idProduct, bool exclude_hid_devices);
  752. bool transmitPS4UserFeedbackMsg();
  753. bool transmitPS3UserFeedbackMsg();
  754. bool anychange = false;
  755. volatile bool joystickEvent = false;
  756. uint32_t buttons = 0;
  757. int axis[TOTAL_AXIS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  758. uint64_t axis_mask_ = 0; // which axis have valid data
  759. uint64_t axis_changed_mask_ = 0;
  760. uint64_t axis_change_notify_mask_ = 0x3ff; // assume the low 10 values only.
  761. uint16_t additional_axis_usage_page_ = 0;
  762. uint16_t additional_axis_usage_start_ = 0;
  763. uint16_t additional_axis_usage_count_ = 0;
  764. // State values to output to Joystick.
  765. uint8_t rumble_lValue_ = 0;
  766. uint8_t rumble_rValue_ = 0;
  767. uint8_t rumble_timeout_ = 0;
  768. uint8_t leds_[3] = {0,0,0};
  769. uint8_t connected_ = 0; // what type of device if any is connected xbox 360...
  770. // Used by HID code
  771. uint8_t collections_claimed = 0;
  772. // Used by USBDriver code
  773. static void rx_callback(const Transfer_t *transfer);
  774. static void tx_callback(const Transfer_t *transfer);
  775. void rx_data(const Transfer_t *transfer);
  776. void tx_data(const Transfer_t *transfer);
  777. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  778. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  779. strbuf_t mystring_bufs[1];
  780. uint16_t rx_size_ = 0;
  781. uint16_t tx_size_ = 0;
  782. Pipe_t *rxpipe_;
  783. Pipe_t *txpipe_;
  784. uint8_t rxbuf_[64]; // receive circular buffer
  785. uint8_t txbuf_[64]; // buffer to use to send commands to joystick
  786. // Mapping table to say which devices we handle
  787. typedef struct {
  788. uint16_t idVendor;
  789. uint16_t idProduct;
  790. joytype_t joyType;
  791. bool hidDevice;
  792. } product_vendor_mapping_t;
  793. static product_vendor_mapping_t pid_vid_mapping[];
  794. };
  795. //--------------------------------------------------------------------------
  796. class MIDIDevice : public USBDriver {
  797. public:
  798. enum { SYSEX_MAX_LEN = 290 };
  799. // Message type names for compatibility with Arduino MIDI library 4.3.1
  800. enum MidiType {
  801. InvalidType = 0x00, // For notifying errors
  802. NoteOff = 0x80, // Note Off
  803. NoteOn = 0x90, // Note On
  804. AfterTouchPoly = 0xA0, // Polyphonic AfterTouch
  805. ControlChange = 0xB0, // Control Change / Channel Mode
  806. ProgramChange = 0xC0, // Program Change
  807. AfterTouchChannel = 0xD0, // Channel (monophonic) AfterTouch
  808. PitchBend = 0xE0, // Pitch Bend
  809. SystemExclusive = 0xF0, // System Exclusive
  810. TimeCodeQuarterFrame = 0xF1, // System Common - MIDI Time Code Quarter Frame
  811. SongPosition = 0xF2, // System Common - Song Position Pointer
  812. SongSelect = 0xF3, // System Common - Song Select
  813. TuneRequest = 0xF6, // System Common - Tune Request
  814. Clock = 0xF8, // System Real Time - Timing Clock
  815. Start = 0xFA, // System Real Time - Start
  816. Continue = 0xFB, // System Real Time - Continue
  817. Stop = 0xFC, // System Real Time - Stop
  818. ActiveSensing = 0xFE, // System Real Time - Active Sensing
  819. SystemReset = 0xFF, // System Real Time - System Reset
  820. };
  821. MIDIDevice(USBHost &host) { init(); }
  822. MIDIDevice(USBHost *host) { init(); }
  823. void sendNoteOff(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  824. send(0x80, note, velocity, channel, cable);
  825. }
  826. void sendNoteOn(uint8_t note, uint8_t velocity, uint8_t channel, uint8_t cable=0) {
  827. send(0x90, note, velocity, channel, cable);
  828. }
  829. void sendPolyPressure(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  830. send(0xA0, note, pressure, channel, cable);
  831. }
  832. void sendAfterTouchPoly(uint8_t note, uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  833. send(0xA0, note, pressure, channel, cable);
  834. }
  835. void sendControlChange(uint8_t control, uint8_t value, uint8_t channel, uint8_t cable=0) {
  836. send(0xB0, control, value, channel, cable);
  837. }
  838. void sendProgramChange(uint8_t program, uint8_t channel, uint8_t cable=0) {
  839. send(0xC0, program, 0, channel, cable);
  840. }
  841. void sendAfterTouch(uint8_t pressure, uint8_t channel, uint8_t cable=0) {
  842. send(0xD0, pressure, 0, channel, cable);
  843. }
  844. void sendPitchBend(int value, uint8_t channel, uint8_t cable=0) {
  845. if (value < -8192) {
  846. value = -8192;
  847. } else if (value > 8191) {
  848. value = 8191;
  849. }
  850. value += 8192;
  851. send(0xE0, value, value >> 7, channel, cable);
  852. }
  853. void sendSysEx(uint32_t length, const uint8_t *data, bool hasTerm=false, uint8_t cable=0) {
  854. //if (cable >= MIDI_NUM_CABLES) return;
  855. if (hasTerm) {
  856. send_sysex_buffer_has_term(data, length, cable);
  857. } else {
  858. send_sysex_add_term_bytes(data, length, cable);
  859. }
  860. }
  861. void sendRealTime(uint8_t type, uint8_t cable=0) {
  862. switch (type) {
  863. case 0xF8: // Clock
  864. case 0xFA: // Start
  865. case 0xFB: // Continue
  866. case 0xFC: // Stop
  867. case 0xFE: // ActiveSensing
  868. case 0xFF: // SystemReset
  869. send(type, 0, 0, 0, cable);
  870. break;
  871. default: // Invalid Real Time marker
  872. break;
  873. }
  874. }
  875. void sendTimeCodeQuarterFrame(uint8_t type, uint8_t value, uint8_t cable=0) {
  876. send(0xF1, ((type & 0x07) << 4) | (value & 0x0F), 0, 0, cable);
  877. }
  878. void sendSongPosition(uint16_t beats, uint8_t cable=0) {
  879. send(0xF2, beats, beats >> 7, 0, cable);
  880. }
  881. void sendSongSelect(uint8_t song, uint8_t cable=0) {
  882. send(0xF3, song, 0, 0, cable);
  883. }
  884. void sendTuneRequest(uint8_t cable=0) {
  885. send(0xF6, 0, 0, 0, cable);
  886. }
  887. void beginRpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  888. sendControlChange(101, number >> 7, channel, cable);
  889. sendControlChange(100, number, channel, cable);
  890. }
  891. void sendRpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  892. sendControlChange(6, value >> 7, channel, cable);
  893. sendControlChange(38, value, channel, cable);
  894. }
  895. void sendRpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  896. sendControlChange(96, amount, channel, cable);
  897. }
  898. void sendRpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  899. sendControlChange(97, amount, channel, cable);
  900. }
  901. void endRpn(uint8_t channel, uint8_t cable=0) {
  902. sendControlChange(101, 0x7F, channel, cable);
  903. sendControlChange(100, 0x7F, channel, cable);
  904. }
  905. void beginNrpn(uint16_t number, uint8_t channel, uint8_t cable=0) {
  906. sendControlChange(99, number >> 7, channel, cable);
  907. sendControlChange(98, number, channel, cable);
  908. }
  909. void sendNrpnValue(uint16_t value, uint8_t channel, uint8_t cable=0) {
  910. sendControlChange(6, value >> 7, channel, cable);
  911. sendControlChange(38, value, channel, cable);
  912. }
  913. void sendNrpnIncrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  914. sendControlChange(96, amount, channel, cable);
  915. }
  916. void sendNrpnDecrement(uint8_t amount, uint8_t channel, uint8_t cable=0) {
  917. sendControlChange(97, amount, channel, cable);
  918. }
  919. void endNrpn(uint8_t channel, uint8_t cable=0) {
  920. sendControlChange(99, 0x7F, channel, cable);
  921. sendControlChange(98, 0x7F, channel, cable);
  922. }
  923. void send(uint8_t type, uint8_t data1, uint8_t data2, uint8_t channel, uint8_t cable=0) {
  924. //if (cable >= MIDI_NUM_CABLES) return;
  925. if (type < 0xF0) {
  926. if (type < 0x80) return;
  927. type &= 0xF0;
  928. write_packed((type << 8) | (type >> 4) | ((cable & 0x0F) << 4)
  929. | (((channel - 1) & 0x0F) << 8) | ((data1 & 0x7F) << 16)
  930. | ((data2 & 0x7F) << 24));
  931. } else if (type >= 0xF8 || type == 0xF6) {
  932. write_packed((type << 8) | 0x0F | ((cable & 0x0F) << 4));
  933. } else if (type == 0xF1 || type == 0xF3) {
  934. write_packed((type << 8) | 0x02 | ((cable & 0x0F) << 4)
  935. | ((data1 & 0x7F) << 16));
  936. } else if (type == 0xF2) {
  937. write_packed((type << 8) | 0x03 | ((cable & 0x0F) << 4)
  938. | ((data1 & 0x7F) << 16) | ((data2 & 0x7F) << 24));
  939. }
  940. }
  941. void send_now(void) __attribute__((always_inline)) {
  942. }
  943. bool read(uint8_t channel=0);
  944. uint8_t getType(void) {
  945. return msg_type;
  946. };
  947. uint8_t getCable(void) {
  948. return msg_cable;
  949. }
  950. uint8_t getChannel(void) {
  951. return msg_channel;
  952. };
  953. uint8_t getData1(void) {
  954. return msg_data1;
  955. };
  956. uint8_t getData2(void) {
  957. return msg_data2;
  958. };
  959. uint8_t * getSysExArray(void) {
  960. return msg_sysex;
  961. }
  962. uint16_t getSysExArrayLength(void) {
  963. return msg_data2 << 8 | msg_data1;
  964. }
  965. void setHandleNoteOff(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  966. // type: 0x80 NoteOff
  967. handleNoteOff = fptr;
  968. }
  969. void setHandleNoteOn(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  970. // type: 0x90 NoteOn
  971. handleNoteOn = fptr;
  972. }
  973. void setHandleVelocityChange(void (*fptr)(uint8_t channel, uint8_t note, uint8_t velocity)) {
  974. // type: 0xA0 AfterTouchPoly
  975. handleVelocityChange = fptr;
  976. }
  977. void setHandleAfterTouchPoly(void (*fptr)(uint8_t channel, uint8_t note, uint8_t pressure)) {
  978. // type: 0xA0 AfterTouchPoly
  979. handleVelocityChange = fptr;
  980. }
  981. void setHandleControlChange(void (*fptr)(uint8_t channel, uint8_t control, uint8_t value)) {
  982. // type: 0xB0 ControlChange
  983. handleControlChange = fptr;
  984. }
  985. void setHandleProgramChange(void (*fptr)(uint8_t channel, uint8_t program)) {
  986. // type: 0xC0 ProgramChange
  987. handleProgramChange = fptr;
  988. }
  989. void setHandleAfterTouch(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  990. // type: 0xD0 AfterTouchChannel
  991. handleAfterTouch = fptr;
  992. }
  993. void setHandleAfterTouchChannel(void (*fptr)(uint8_t channel, uint8_t pressure)) {
  994. // type: 0xD0 AfterTouchChannel
  995. handleAfterTouch = fptr;
  996. }
  997. void setHandlePitchChange(void (*fptr)(uint8_t channel, int pitch)) {
  998. // type: 0xE0 PitchBend
  999. handlePitchChange = fptr;
  1000. }
  1001. void setHandleSysEx(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1002. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1003. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1004. }
  1005. void setHandleSystemExclusive(void (*fptr)(const uint8_t *data, uint16_t length, bool complete)) {
  1006. // type: 0xF0 SystemExclusive - multiple calls for message bigger than buffer
  1007. handleSysExPartial = (void (*)(const uint8_t *, uint16_t, uint8_t))fptr;
  1008. }
  1009. void setHandleSystemExclusive(void (*fptr)(uint8_t *data, unsigned int size)) {
  1010. // type: 0xF0 SystemExclusive - single call, message larger than buffer is truncated
  1011. handleSysExComplete = fptr;
  1012. }
  1013. void setHandleTimeCodeQuarterFrame(void (*fptr)(uint8_t data)) {
  1014. // type: 0xF1 TimeCodeQuarterFrame
  1015. handleTimeCodeQuarterFrame = fptr;
  1016. }
  1017. void setHandleSongPosition(void (*fptr)(uint16_t beats)) {
  1018. // type: 0xF2 SongPosition
  1019. handleSongPosition = fptr;
  1020. }
  1021. void setHandleSongSelect(void (*fptr)(uint8_t songnumber)) {
  1022. // type: 0xF3 SongSelect
  1023. handleSongSelect = fptr;
  1024. }
  1025. void setHandleTuneRequest(void (*fptr)(void)) {
  1026. // type: 0xF6 TuneRequest
  1027. handleTuneRequest = fptr;
  1028. }
  1029. void setHandleClock(void (*fptr)(void)) {
  1030. // type: 0xF8 Clock
  1031. handleClock = fptr;
  1032. }
  1033. void setHandleStart(void (*fptr)(void)) {
  1034. // type: 0xFA Start
  1035. handleStart = fptr;
  1036. }
  1037. void setHandleContinue(void (*fptr)(void)) {
  1038. // type: 0xFB Continue
  1039. handleContinue = fptr;
  1040. }
  1041. void setHandleStop(void (*fptr)(void)) {
  1042. // type: 0xFC Stop
  1043. handleStop = fptr;
  1044. }
  1045. void setHandleActiveSensing(void (*fptr)(void)) {
  1046. // type: 0xFE ActiveSensing
  1047. handleActiveSensing = fptr;
  1048. }
  1049. void setHandleSystemReset(void (*fptr)(void)) {
  1050. // type: 0xFF SystemReset
  1051. handleSystemReset = fptr;
  1052. }
  1053. void setHandleRealTimeSystem(void (*fptr)(uint8_t realtimebyte)) {
  1054. // type: 0xF8-0xFF - if more specific handler not configured
  1055. handleRealTimeSystem = fptr;
  1056. }
  1057. protected:
  1058. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1059. virtual void disconnect();
  1060. static void rx_callback(const Transfer_t *transfer);
  1061. static void tx_callback(const Transfer_t *transfer);
  1062. void rx_data(const Transfer_t *transfer);
  1063. void tx_data(const Transfer_t *transfer);
  1064. void init();
  1065. void write_packed(uint32_t data);
  1066. void send_sysex_buffer_has_term(const uint8_t *data, uint32_t length, uint8_t cable);
  1067. void send_sysex_add_term_bytes(const uint8_t *data, uint32_t length, uint8_t cable);
  1068. void sysex_byte(uint8_t b);
  1069. private:
  1070. Pipe_t *rxpipe;
  1071. Pipe_t *txpipe;
  1072. enum { MAX_PACKET_SIZE = 64 };
  1073. enum { RX_QUEUE_SIZE = 80 }; // must be more than MAX_PACKET_SIZE/4
  1074. uint32_t rx_buffer[MAX_PACKET_SIZE/4];
  1075. uint32_t tx_buffer1[MAX_PACKET_SIZE/4];
  1076. uint32_t tx_buffer2[MAX_PACKET_SIZE/4];
  1077. uint16_t rx_size;
  1078. uint16_t tx_size;
  1079. uint32_t rx_queue[RX_QUEUE_SIZE];
  1080. bool rx_packet_queued;
  1081. uint16_t rx_head;
  1082. uint16_t rx_tail;
  1083. volatile uint8_t tx1_count;
  1084. volatile uint8_t tx2_count;
  1085. uint8_t rx_ep;
  1086. uint8_t tx_ep;
  1087. uint8_t rx_ep_type;
  1088. uint8_t tx_ep_type;
  1089. uint8_t msg_cable;
  1090. uint8_t msg_channel;
  1091. uint8_t msg_type;
  1092. uint8_t msg_data1;
  1093. uint8_t msg_data2;
  1094. uint8_t msg_sysex[SYSEX_MAX_LEN];
  1095. uint16_t msg_sysex_len;
  1096. void (*handleNoteOff)(uint8_t ch, uint8_t note, uint8_t vel);
  1097. void (*handleNoteOn)(uint8_t ch, uint8_t note, uint8_t vel);
  1098. void (*handleVelocityChange)(uint8_t ch, uint8_t note, uint8_t vel);
  1099. void (*handleControlChange)(uint8_t ch, uint8_t control, uint8_t value);
  1100. void (*handleProgramChange)(uint8_t ch, uint8_t program);
  1101. void (*handleAfterTouch)(uint8_t ch, uint8_t pressure);
  1102. void (*handlePitchChange)(uint8_t ch, int pitch);
  1103. void (*handleSysExPartial)(const uint8_t *data, uint16_t length, uint8_t complete);
  1104. void (*handleSysExComplete)(uint8_t *data, unsigned int size);
  1105. void (*handleTimeCodeQuarterFrame)(uint8_t data);
  1106. void (*handleSongPosition)(uint16_t beats);
  1107. void (*handleSongSelect)(uint8_t songnumber);
  1108. void (*handleTuneRequest)(void);
  1109. void (*handleClock)(void);
  1110. void (*handleStart)(void);
  1111. void (*handleContinue)(void);
  1112. void (*handleStop)(void);
  1113. void (*handleActiveSensing)(void);
  1114. void (*handleSystemReset)(void);
  1115. void (*handleRealTimeSystem)(uint8_t rtb);
  1116. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1117. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1118. strbuf_t mystring_bufs[1];
  1119. };
  1120. //--------------------------------------------------------------------------
  1121. class USBSerial: public USBDriver, public Stream {
  1122. public:
  1123. // FIXME: need different USBSerial, with bigger buffers for 480 Mbit & faster speed
  1124. enum { BUFFER_SIZE = 648 }; // must hold at least 6 max size packets, plus 2 extra bytes
  1125. enum { DEFAULT_WRITE_TIMEOUT = 3500};
  1126. USBSerial(USBHost &host) : txtimer(this) { init(); }
  1127. void begin(uint32_t baud, uint32_t format=USBHOST_SERIAL_8N1);
  1128. void end(void);
  1129. uint32_t writeTimeout() {return write_timeout_;}
  1130. void writeTimeOut(uint32_t write_timeout) {write_timeout_ = write_timeout;} // Will not impact current ones.
  1131. virtual int available(void);
  1132. virtual int peek(void);
  1133. virtual int read(void);
  1134. virtual int availableForWrite();
  1135. virtual size_t write(uint8_t c);
  1136. virtual void flush(void);
  1137. using Print::write;
  1138. protected:
  1139. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1140. virtual void control(const Transfer_t *transfer);
  1141. virtual void disconnect();
  1142. virtual void timer_event(USBDriverTimer *whichTimer);
  1143. private:
  1144. static void rx_callback(const Transfer_t *transfer);
  1145. static void tx_callback(const Transfer_t *transfer);
  1146. void rx_data(const Transfer_t *transfer);
  1147. void tx_data(const Transfer_t *transfer);
  1148. void rx_queue_packets(uint32_t head, uint32_t tail);
  1149. void init();
  1150. static bool check_rxtx_ep(uint32_t &rxep, uint32_t &txep);
  1151. bool init_buffers(uint32_t rsize, uint32_t tsize);
  1152. void ch341_setBaud(uint8_t byte_index);
  1153. private:
  1154. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1155. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1156. strbuf_t mystring_bufs[1];
  1157. USBDriverTimer txtimer;
  1158. uint32_t bigbuffer[(BUFFER_SIZE+3)/4];
  1159. setup_t setup;
  1160. uint8_t setupdata[16]; //
  1161. uint32_t baudrate;
  1162. uint32_t format_;
  1163. uint32_t write_timeout_ = DEFAULT_WRITE_TIMEOUT;
  1164. Pipe_t *rxpipe;
  1165. Pipe_t *txpipe;
  1166. uint8_t *rx1; // location for first incoming packet
  1167. uint8_t *rx2; // location for second incoming packet
  1168. uint8_t *rxbuf; // receive circular buffer
  1169. uint8_t *tx1; // location for first outgoing packet
  1170. uint8_t *tx2; // location for second outgoing packet
  1171. uint8_t *txbuf;
  1172. volatile uint16_t rxhead;// receive head
  1173. volatile uint16_t rxtail;// receive tail
  1174. volatile uint16_t txhead;
  1175. volatile uint16_t txtail;
  1176. uint16_t rxsize;// size of receive circular buffer
  1177. uint16_t txsize;// size of transmit circular buffer
  1178. volatile uint8_t rxstate;// bitmask: which receive packets are queued
  1179. volatile uint8_t txstate;
  1180. uint8_t pending_control;
  1181. uint8_t setup_state; // PL2303 - has several steps... Could use pending control?
  1182. uint8_t pl2303_v1; // Which version do we have
  1183. uint8_t pl2303_v2;
  1184. uint8_t interface;
  1185. bool control_queued;
  1186. typedef enum { UNKNOWN=0, CDCACM, FTDI, PL2303, CH341, CP210X } sertype_t;
  1187. sertype_t sertype;
  1188. typedef struct {
  1189. uint16_t idVendor;
  1190. uint16_t idProduct;
  1191. sertype_t sertype;
  1192. } product_vendor_mapping_t;
  1193. static product_vendor_mapping_t pid_vid_mapping[];
  1194. };
  1195. //--------------------------------------------------------------------------
  1196. class AntPlus: public USBDriver {
  1197. // Please post any AntPlus feedback or contributions on this forum thread:
  1198. // https://forum.pjrc.com/threads/43110-Ant-libarary-and-USB-driver-for-Teensy-3-5-6
  1199. public:
  1200. AntPlus(USBHost &host) : /* txtimer(this),*/ updatetimer(this) { init(); }
  1201. void begin(const uint8_t key=0);
  1202. void onStatusChange(void (*function)(int channel, int status)) {
  1203. user_onStatusChange = function;
  1204. }
  1205. void onDeviceID(void (*function)(int channel, int devId, int devType, int transType)) {
  1206. user_onDeviceID = function;
  1207. }
  1208. void onHeartRateMonitor(void (*f)(int bpm, int msec, int seqNum), uint32_t devid=0) {
  1209. profileSetup_HRM(&ant.dcfg[PROFILE_HRM], devid);
  1210. memset(&hrm, 0, sizeof(hrm));
  1211. user_onHeartRateMonitor = f;
  1212. }
  1213. void onSpeedCadence(void (*f)(float speed, float distance, float rpm), uint32_t devid=0) {
  1214. profileSetup_SPDCAD(&ant.dcfg[PROFILE_SPDCAD], devid);
  1215. memset(&spdcad, 0, sizeof(spdcad));
  1216. user_onSpeedCadence = f;
  1217. }
  1218. void onSpeed(void (*f)(float speed, float distance), uint32_t devid=0) {
  1219. profileSetup_SPEED(&ant.dcfg[PROFILE_SPEED], devid);
  1220. memset(&spd, 0, sizeof(spd));
  1221. user_onSpeed = f;
  1222. }
  1223. void onCadence(void (*f)(float rpm), uint32_t devid=0) {
  1224. profileSetup_CADENCE(&ant.dcfg[PROFILE_CADENCE], devid);
  1225. memset(&cad, 0, sizeof(cad));
  1226. user_onCadence = f;
  1227. }
  1228. void setWheelCircumference(float meters) {
  1229. wheelCircumference = meters * 1000.0f;
  1230. }
  1231. protected:
  1232. virtual void Task();
  1233. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1234. virtual void disconnect();
  1235. virtual void timer_event(USBDriverTimer *whichTimer);
  1236. private:
  1237. static void rx_callback(const Transfer_t *transfer);
  1238. static void tx_callback(const Transfer_t *transfer);
  1239. void rx_data(const Transfer_t *transfer);
  1240. void tx_data(const Transfer_t *transfer);
  1241. void init();
  1242. size_t write(const void *data, const size_t size);
  1243. int read(void *data, const size_t size);
  1244. void transmit();
  1245. private:
  1246. Pipe_t mypipes[2] __attribute__ ((aligned(32)));
  1247. Transfer_t mytransfers[3] __attribute__ ((aligned(32)));
  1248. strbuf_t mystring_bufs[1];
  1249. //USBDriverTimer txtimer;
  1250. USBDriverTimer updatetimer;
  1251. Pipe_t *rxpipe;
  1252. Pipe_t *txpipe;
  1253. bool first_update;
  1254. uint8_t txbuffer[240];
  1255. uint8_t rxpacket[64];
  1256. volatile uint16_t txhead;
  1257. volatile uint16_t txtail;
  1258. volatile bool txready;
  1259. volatile uint8_t rxlen;
  1260. volatile bool do_polling;
  1261. private:
  1262. enum _eventi {
  1263. EVENTI_MESSAGE = 0,
  1264. EVENTI_CHANNEL,
  1265. EVENTI_TOTAL
  1266. };
  1267. enum _profiles {
  1268. PROFILE_HRM = 0,
  1269. PROFILE_SPDCAD,
  1270. PROFILE_POWER,
  1271. PROFILE_STRIDE,
  1272. PROFILE_SPEED,
  1273. PROFILE_CADENCE,
  1274. PROFILE_TOTAL
  1275. };
  1276. typedef struct {
  1277. uint8_t channel;
  1278. uint8_t RFFreq;
  1279. uint8_t networkNumber;
  1280. uint8_t stub;
  1281. uint8_t searchTimeout;
  1282. uint8_t channelType;
  1283. uint8_t deviceType;
  1284. uint8_t transType;
  1285. uint16_t channelPeriod;
  1286. uint16_t searchWaveform;
  1287. uint32_t deviceNumber; // deviceId
  1288. struct {
  1289. uint8_t chanIdOnce;
  1290. uint8_t keyAccepted;
  1291. uint8_t profileValid;
  1292. uint8_t channelStatus;
  1293. uint8_t channelStatusOld;
  1294. } flags;
  1295. } TDCONFIG;
  1296. struct {
  1297. uint8_t initOnce;
  1298. uint8_t key; // key index
  1299. int iDevice; // index to the antplus we're interested in, if > one found
  1300. TDCONFIG dcfg[PROFILE_TOTAL]; // channel config, we're using one channel per device
  1301. } ant;
  1302. void (*user_onStatusChange)(int channel, int status);
  1303. void (*user_onDeviceID)(int channel, int devId, int devType, int transType);
  1304. void (*user_onHeartRateMonitor)(int beatsPerMinute, int milliseconds, int sequenceNumber);
  1305. void (*user_onSpeedCadence)(float speed, float distance, float cadence);
  1306. void (*user_onSpeed)(float speed, float distance);
  1307. void (*user_onCadence)(float cadence);
  1308. void dispatchPayload(TDCONFIG *cfg, const uint8_t *payload, const int len);
  1309. static const uint8_t *getAntKey(const uint8_t keyIdx);
  1310. static uint8_t calcMsgChecksum (const uint8_t *buffer, const uint8_t len);
  1311. static uint8_t * findStreamSync(uint8_t *stream, const size_t rlen, int *pos);
  1312. static int msgCheckIntegrity(uint8_t *stream, const int len);
  1313. static int msgGetLength(uint8_t *stream);
  1314. int handleMessages(uint8_t *buffer, int tBytes);
  1315. void sendMessageChannelStatus(TDCONFIG *cfg, const uint32_t channelStatus);
  1316. void message_channel(const int chan, const int eventId,
  1317. const uint8_t *payload, const size_t dataLength);
  1318. void message_response(const int chan, const int msgId,
  1319. const uint8_t *payload, const size_t dataLength);
  1320. void message_event(const int channel, const int msgId,
  1321. const uint8_t *payload, const size_t dataLength);
  1322. int ResetSystem();
  1323. int RequestMessage(const int channel, const int message);
  1324. int SetNetworkKey(const int netNumber, const uint8_t *key);
  1325. int SetChannelSearchTimeout(const int channel, const int searchTimeout);
  1326. int SetChannelPeriod(const int channel, const int period);
  1327. int SetChannelRFFreq(const int channel, const int freq);
  1328. int SetSearchWaveform(const int channel, const int wave);
  1329. int OpenChannel(const int channel);
  1330. int CloseChannel(const int channel);
  1331. int AssignChannel(const int channel, const int channelType, const int network);
  1332. int SetChannelId(const int channel, const int deviceNum, const int deviceType,
  1333. const int transmissionType);
  1334. int SendBurstTransferPacket(const int channelSeq, const uint8_t *data);
  1335. int SendBurstTransfer(const int channel, const uint8_t *data, const int nunPackets);
  1336. int SendBroadcastData(const int channel, const uint8_t *data);
  1337. int SendAcknowledgedData(const int channel, const uint8_t *data);
  1338. int SendExtAcknowledgedData(const int channel, const int devNum, const int devType,
  1339. const int TranType, const uint8_t *data);
  1340. int SendExtBroadcastData(const int channel, const int devNum, const int devType,
  1341. const int TranType, const uint8_t *data);
  1342. int SendExtBurstTransferPacket(const int chanSeq, const int devNum,
  1343. const int devType, const int TranType, const uint8_t *data);
  1344. int SendExtBurstTransfer(const int channel, const int devNum, const int devType,
  1345. const int tranType, const uint8_t *data, const int nunPackets);
  1346. static void profileSetup_HRM(TDCONFIG *cfg, const uint32_t deviceId);
  1347. static void profileSetup_SPDCAD(TDCONFIG *cfg, const uint32_t deviceId);
  1348. static void profileSetup_POWER(TDCONFIG *cfg, const uint32_t deviceId);
  1349. static void profileSetup_STRIDE(TDCONFIG *cfg, const uint32_t deviceId);
  1350. static void profileSetup_SPEED(TDCONFIG *cfg, const uint32_t deviceId);
  1351. static void profileSetup_CADENCE(TDCONFIG *cfg, const uint32_t deviceId);
  1352. struct {
  1353. struct {
  1354. uint8_t bpm;
  1355. uint8_t sequence;
  1356. uint16_t time;
  1357. } previous;
  1358. } hrm;
  1359. void payload_HRM(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1360. struct {
  1361. struct {
  1362. uint16_t cadenceTime;
  1363. uint16_t cadenceCt;
  1364. uint16_t speedTime;
  1365. uint16_t speedCt;
  1366. } previous;
  1367. float distance;
  1368. } spdcad;
  1369. void payload_SPDCAD(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1370. /* struct {
  1371. struct {
  1372. uint8_t sequence;
  1373. uint16_t pedalPowerContribution;
  1374. uint8_t pedalPower;
  1375. uint8_t instantCadence;
  1376. uint16_t sumPower;
  1377. uint16_t instantPower;
  1378. } current;
  1379. struct {
  1380. uint16_t stub;
  1381. } previous;
  1382. } pwr; */
  1383. void payload_POWER(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1384. /* struct {
  1385. struct {
  1386. uint16_t speed;
  1387. uint16_t cadence;
  1388. uint8_t strides;
  1389. } current;
  1390. struct {
  1391. uint8_t strides;
  1392. uint16_t speed;
  1393. uint16_t cadence;
  1394. } previous;
  1395. } stride; */
  1396. void payload_STRIDE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1397. struct {
  1398. struct {
  1399. uint16_t speedTime;
  1400. uint16_t speedCt;
  1401. } previous;
  1402. float distance;
  1403. } spd;
  1404. void payload_SPEED(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1405. struct {
  1406. struct {
  1407. uint16_t cadenceTime;
  1408. uint16_t cadenceCt;
  1409. } previous;
  1410. } cad;
  1411. void payload_CADENCE(TDCONFIG *cfg, const uint8_t *data, const size_t dataLength);
  1412. uint16_t wheelCircumference; // default is WHEEL_CIRCUMFERENCE (2122cm)
  1413. };
  1414. //--------------------------------------------------------------------------
  1415. class RawHIDController : public USBHIDInput {
  1416. public:
  1417. RawHIDController(USBHost &host, uint32_t usage = 0) : fixed_usage_(usage) { init(); }
  1418. uint32_t usage(void) {return usage_;}
  1419. void attachReceive(bool (*f)(uint32_t usage, const uint8_t *data, uint32_t len)) {receiveCB = f;}
  1420. bool sendPacket(const uint8_t *buffer);
  1421. protected:
  1422. virtual hidclaim_t claim_collection(USBHIDParser *driver, Device_t *dev, uint32_t topusage);
  1423. virtual bool hid_process_in_data(const Transfer_t *transfer);
  1424. virtual bool hid_process_out_data(const Transfer_t *transfer);
  1425. virtual void hid_input_begin(uint32_t topusage, uint32_t type, int lgmin, int lgmax);
  1426. virtual void hid_input_data(uint32_t usage, int32_t value);
  1427. virtual void hid_input_end();
  1428. virtual void disconnect_collection(Device_t *dev);
  1429. private:
  1430. void init();
  1431. USBHIDParser *driver_;
  1432. enum { MAX_PACKET_SIZE = 64 };
  1433. bool (*receiveCB)(uint32_t usage, const uint8_t *data, uint32_t len) = nullptr;
  1434. uint8_t collections_claimed = 0;
  1435. //volatile bool hid_input_begin_ = false;
  1436. uint32_t fixed_usage_;
  1437. uint32_t usage_ = 0;
  1438. // See if we can contribute transfers
  1439. Transfer_t mytransfers[2] __attribute__ ((aligned(32)));
  1440. };
  1441. //--------------------------------------------------------------------------
  1442. class BluetoothController: public USBDriver {
  1443. public:
  1444. BluetoothController(USBHost &host) { init(); }
  1445. enum {MAX_ENDPOINTS=4, NUM_SERVICES=4}; // Max number of Bluetooth services - if you need more than 4 simply increase this number
  1446. protected:
  1447. virtual bool claim(Device_t *device, int type, const uint8_t *descriptors, uint32_t len);
  1448. virtual void control(const Transfer_t *transfer);
  1449. virtual void disconnect();
  1450. //virtual void timer_event(USBDriverTimer *whichTimer);
  1451. private:
  1452. static void rx_callback(const Transfer_t *transfer);
  1453. static void tx_callback(const Transfer_t *transfer);
  1454. void rx_data(const Transfer_t *transfer);
  1455. void tx_data(const Transfer_t *transfer);
  1456. void init();
  1457. Pipe_t mypipes[3] __attribute__ ((aligned(32)));
  1458. Transfer_t mytransfers[7] __attribute__ ((aligned(32)));
  1459. strbuf_t mystring_bufs[1];
  1460. };
  1461. #endif