Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

USBHost_t36.h 77KB

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