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 72KB

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