You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

BTD.cpp 59KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. /* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
  2. This software may be distributed and modified under the terms of the GNU
  3. General Public License version 2 (GPL2) as published by the Free Software
  4. Foundation and appearing in the file GPL2.TXT included in the packaging of
  5. this file. Please note that GPL2 Section 2[b] requires that all works based
  6. on this software must also be made publicly available under the terms of
  7. the GPL2 ("Copyleft").
  8. Contact information
  9. -------------------
  10. Kristian Lauszus, TKJ Electronics
  11. Web : http://www.tkjelectronics.com
  12. e-mail : [email protected]
  13. */
  14. #include "BTD.h"
  15. // To enable serial debugging see "settings.h"
  16. //#define EXTRADEBUG // Uncomment to get even more debugging data
  17. const uint8_t BTD::BTD_CONTROL_PIPE = 0;
  18. const uint8_t BTD::BTD_EVENT_PIPE = 1;
  19. const uint8_t BTD::BTD_DATAIN_PIPE = 2;
  20. const uint8_t BTD::BTD_DATAOUT_PIPE = 3;
  21. BTD::BTD(USB *p) :
  22. connectToWii(false),
  23. pairWithWii(false),
  24. connectToHIDDevice(false),
  25. pairWithHIDDevice(false),
  26. pUsb(p), // Pointer to USB class instance - mandatory
  27. bAddress(0), // Device address - mandatory
  28. bNumEP(1), // If config descriptor needs to be parsed
  29. qNextPollTime(0), // Reset NextPollTime
  30. pollInterval(0),
  31. bPollEnable(false) // Don't start polling before dongle is connected
  32. {
  33. for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
  34. btService[i] = NULL;
  35. Initialize(); // Set all variables, endpoint structs etc. to default values
  36. if(pUsb) // Register in USB subsystem
  37. pUsb->RegisterDeviceClass(this); // Set devConfig[] entry
  38. }
  39. uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
  40. const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
  41. uint8_t buf[constBufSize];
  42. USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
  43. uint8_t rcode;
  44. UsbDevice *p = NULL;
  45. EpInfo *oldep_ptr = NULL;
  46. Initialize(); // Set all variables, endpoint structs etc. to default values
  47. AddressPool &addrPool = pUsb->GetAddressPool(); // Get memory address of USB device address pool
  48. #ifdef EXTRADEBUG
  49. Notify(PSTR("\r\nBTD ConfigureDevice"), 0x80);
  50. #endif
  51. if(bAddress) { // Check if address has already been assigned to an instance
  52. #ifdef DEBUG_USB_HOST
  53. Notify(PSTR("\r\nAddress in use"), 0x80);
  54. #endif
  55. return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
  56. }
  57. p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned
  58. if(!p) {
  59. #ifdef DEBUG_USB_HOST
  60. Notify(PSTR("\r\nAddress not found"), 0x80);
  61. #endif
  62. return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  63. }
  64. if(!p->epinfo) {
  65. #ifdef DEBUG_USB_HOST
  66. Notify(PSTR("\r\nepinfo is null"), 0x80);
  67. #endif
  68. return USB_ERROR_EPINFO_IS_NULL;
  69. }
  70. oldep_ptr = p->epinfo; // Save old pointer to EP_RECORD of address 0
  71. p->epinfo = epInfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
  72. p->lowspeed = lowspeed;
  73. rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
  74. p->epinfo = oldep_ptr; // Restore p->epinfo
  75. if(rcode)
  76. goto FailGetDevDescr;
  77. bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class
  78. if(!bAddress) {
  79. #ifdef DEBUG_USB_HOST
  80. Notify(PSTR("\r\nOut of address space"), 0x80);
  81. #endif
  82. return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
  83. }
  84. epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor
  85. epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory
  86. VID = udd->idVendor;
  87. PID = udd->idProduct;
  88. return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET;
  89. FailGetDevDescr:
  90. #ifdef DEBUG_USB_HOST
  91. NotifyFailGetDevDescr(rcode);
  92. #endif
  93. if(rcode != hrJERR)
  94. rcode = USB_ERROR_FailGetDevDescr;
  95. Release();
  96. return rcode;
  97. };
  98. uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) {
  99. uint8_t rcode;
  100. uint8_t num_of_conf = epInfo[1].epAddr; // Number of configurations
  101. epInfo[1].epAddr = 0;
  102. AddressPool &addrPool = pUsb->GetAddressPool();
  103. #ifdef EXTRADEBUG
  104. Notify(PSTR("\r\nBTD Init"), 0x80);
  105. #endif
  106. UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
  107. if(!p) {
  108. #ifdef DEBUG_USB_HOST
  109. Notify(PSTR("\r\nAddress not found"), 0x80);
  110. #endif
  111. return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  112. }
  113. delay(300); // Assign new address to the device
  114. rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device
  115. if(rcode) {
  116. #ifdef DEBUG_USB_HOST
  117. Notify(PSTR("\r\nsetAddr: "), 0x80);
  118. D_PrintHex<uint8_t > (rcode, 0x80);
  119. #endif
  120. p->lowspeed = false;
  121. goto Fail;
  122. }
  123. #ifdef EXTRADEBUG
  124. Notify(PSTR("\r\nAddr: "), 0x80);
  125. D_PrintHex<uint8_t > (bAddress, 0x80);
  126. #endif
  127. p->lowspeed = false;
  128. p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
  129. if(!p) {
  130. #ifdef DEBUG_USB_HOST
  131. Notify(PSTR("\r\nAddress not found"), 0x80);
  132. #endif
  133. return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
  134. }
  135. p->lowspeed = lowspeed;
  136. rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known
  137. if(rcode)
  138. goto FailSetDevTblEntry;
  139. if(VID == PS3_VID && (PID == PS3_PID || PID == PS3NAVIGATION_PID || PID == PS3MOVE_PID)) {
  140. delay(100);
  141. rcode = pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, 1); // We only need the Control endpoint, so we don't have to initialize the other endpoints of device
  142. if(rcode)
  143. goto FailSetConfDescr;
  144. #ifdef DEBUG_USB_HOST
  145. if(PID == PS3_PID || PID == PS3NAVIGATION_PID) {
  146. if(PID == PS3_PID)
  147. Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80);
  148. else // It must be a navigation controller
  149. Notify(PSTR("\r\nNavigation Controller Connected"), 0x80);
  150. } else // It must be a Motion controller
  151. Notify(PSTR("\r\nMotion Controller Connected"), 0x80);
  152. #endif
  153. if(my_bdaddr[0] == 0x00 && my_bdaddr[1] == 0x00 && my_bdaddr[2] == 0x00 && my_bdaddr[3] == 0x00 && my_bdaddr[4] == 0x00 && my_bdaddr[5] == 0x00) {
  154. #ifdef DEBUG_USB_HOST
  155. Notify(PSTR("\r\nPlease plug in the dongle before trying to pair with the PS3 Controller\r\nor set the Bluetooth address in the constructor of the PS3BT class"), 0x80);
  156. #endif
  157. } else {
  158. if(PID == PS3_PID || PID == PS3NAVIGATION_PID)
  159. setBdaddr(my_bdaddr); // Set internal Bluetooth address
  160. else
  161. setMoveBdaddr(my_bdaddr); // Set internal Bluetooth address
  162. #ifdef DEBUG_USB_HOST
  163. Notify(PSTR("\r\nBluetooth Address was set to: "), 0x80);
  164. for(int8_t i = 5; i > 0; i--) {
  165. D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
  166. Notify(PSTR(":"), 0x80);
  167. }
  168. D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
  169. #endif
  170. }
  171. pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, 0); // Reset configuration value
  172. pUsb->setAddr(bAddress, 0, 0); // Reset address
  173. Release(); // Release device
  174. return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Return
  175. } else {
  176. // Check if attached device is a Bluetooth dongle and fill endpoint data structure
  177. // First interface in the configuration must have Bluetooth assigned Class/Subclass/Protocol
  178. // And 3 endpoints - interrupt-IN, bulk-IN, bulk-OUT, not necessarily in this order
  179. for(uint8_t i = 0; i < num_of_conf; i++) {
  180. if(VID == IOGEAR_GBU521_VID && PID == IOGEAR_GBU521_PID) {
  181. ConfigDescParser<USB_CLASS_VENDOR_SPECIFIC, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this); // Needed for the IOGEAR GBU521
  182. rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
  183. } else {
  184. ConfigDescParser<USB_CLASS_WIRELESS_CTRL, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this);
  185. rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
  186. }
  187. if(rcode) // Check error code
  188. goto FailGetConfDescr;
  189. if(bNumEP >= BTD_MAX_ENDPOINTS) // All endpoints extracted
  190. break;
  191. }
  192. if(bNumEP < BTD_MAX_ENDPOINTS)
  193. goto FailUnknownDevice;
  194. // Assign epInfo to epinfo pointer - this time all 3 endpoins
  195. rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
  196. if(rcode)
  197. goto FailSetDevTblEntry;
  198. // Set Configuration Value
  199. rcode = pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bConfNum);
  200. if(rcode)
  201. goto FailSetConfDescr;
  202. hci_num_reset_loops = 100; // only loop 100 times before trying to send the hci reset command
  203. hci_counter = 0;
  204. hci_state = HCI_INIT_STATE;
  205. watingForConnection = false;
  206. bPollEnable = true;
  207. #ifdef DEBUG_USB_HOST
  208. Notify(PSTR("\r\nBluetooth Dongle Initialized"), 0x80);
  209. #endif
  210. }
  211. return 0; // Successful configuration
  212. /* Diagnostic messages */
  213. FailSetDevTblEntry:
  214. #ifdef DEBUG_USB_HOST
  215. NotifyFailSetDevTblEntry();
  216. goto Fail;
  217. #endif
  218. FailGetConfDescr:
  219. #ifdef DEBUG_USB_HOST
  220. NotifyFailGetConfDescr();
  221. goto Fail;
  222. #endif
  223. FailSetConfDescr:
  224. #ifdef DEBUG_USB_HOST
  225. NotifyFailSetConfDescr();
  226. #endif
  227. goto Fail;
  228. FailUnknownDevice:
  229. #ifdef DEBUG_USB_HOST
  230. NotifyFailUnknownDevice(VID, PID);
  231. #endif
  232. pUsb->setAddr(bAddress, 0, 0); // Reset address
  233. rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
  234. Fail:
  235. #ifdef DEBUG_USB_HOST
  236. Notify(PSTR("\r\nBTD Init Failed, error code: "), 0x80);
  237. NotifyFail(rcode);
  238. #endif
  239. Release();
  240. return rcode;
  241. }
  242. void BTD::Initialize() {
  243. uint8_t i;
  244. for(i = 0; i < BTD_MAX_ENDPOINTS; i++) {
  245. epInfo[i].epAddr = 0;
  246. epInfo[i].maxPktSize = (i) ? 0 : 8;
  247. epInfo[i].epAttribs = 0;
  248. epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
  249. }
  250. for(i = 0; i < BTD_NUM_SERVICES; i++) {
  251. if(btService[i])
  252. btService[i]->Reset(); // Reset all Bluetooth services
  253. }
  254. connectToWii = false;
  255. incomingWii = false;
  256. connectToHIDDevice = false;
  257. incomingHIDDevice = false;
  258. incomingPS4 = false;
  259. bAddress = 0; // Clear device address
  260. bNumEP = 1; // Must have to be reset to 1
  261. qNextPollTime = 0; // Reset next poll time
  262. pollInterval = 0;
  263. bPollEnable = false; // Don't start polling before dongle is connected
  264. }
  265. /* Extracts interrupt-IN, bulk-IN, bulk-OUT endpoint information from config descriptor */
  266. void BTD::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
  267. //ErrorMessage<uint8_t>(PSTR("Conf.Val"),conf);
  268. //ErrorMessage<uint8_t>(PSTR("Iface Num"),iface);
  269. //ErrorMessage<uint8_t>(PSTR("Alt.Set"),alt);
  270. if(alt) // Wrong interface - by BT spec, no alt setting
  271. return;
  272. bConfNum = conf;
  273. uint8_t index;
  274. if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { // Interrupt In endpoint found
  275. index = BTD_EVENT_PIPE;
  276. epInfo[index].bmNakPower = USB_NAK_NOWAIT;
  277. } else {
  278. if((pep->bmAttributes & 0x02) == 2) // Bulk endpoint found
  279. index = ((pep->bEndpointAddress & 0x80) == 0x80) ? BTD_DATAIN_PIPE : BTD_DATAOUT_PIPE;
  280. else
  281. return;
  282. }
  283. // Fill the rest of endpoint data structure
  284. epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
  285. epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
  286. #ifdef EXTRADEBUG
  287. PrintEndpointDescriptor(pep);
  288. #endif
  289. if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints
  290. pollInterval = pep->bInterval;
  291. bNumEP++;
  292. }
  293. void BTD::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
  294. #ifdef EXTRADEBUG
  295. Notify(PSTR("\r\nEndpoint descriptor:"), 0x80);
  296. Notify(PSTR("\r\nLength:\t\t"), 0x80);
  297. D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
  298. Notify(PSTR("\r\nType:\t\t"), 0x80);
  299. D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
  300. Notify(PSTR("\r\nAddress:\t"), 0x80);
  301. D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
  302. Notify(PSTR("\r\nAttributes:\t"), 0x80);
  303. D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
  304. Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
  305. D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
  306. Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
  307. D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
  308. #endif
  309. }
  310. /* Performs a cleanup after failed Init() attempt */
  311. uint8_t BTD::Release() {
  312. Initialize(); // Set all variables, endpoint structs etc. to default values
  313. pUsb->GetAddressPool().FreeAddress(bAddress);
  314. return 0;
  315. }
  316. uint8_t BTD::Poll() {
  317. if(!bPollEnable)
  318. return 0;
  319. if((long)(millis() - qNextPollTime) >= 0L) { // Don't poll if shorter than polling interval
  320. qNextPollTime = millis() + pollInterval; // Set new poll time
  321. HCI_event_task(); // Poll the HCI event pipe
  322. HCI_task(); // HCI state machine
  323. ACL_event_task(); // Poll the ACL input pipe too
  324. }
  325. return 0;
  326. }
  327. void BTD::disconnect() {
  328. for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
  329. if(btService[i])
  330. btService[i]->disconnect();
  331. };
  332. void BTD::HCI_event_task() {
  333. uint16_t length = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this
  334. uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &length, hcibuf); // Input on endpoint 1
  335. if(!rcode || rcode == hrNAK) { // Check for errors
  336. switch(hcibuf[0]) { // Switch on event type
  337. case EV_COMMAND_COMPLETE:
  338. if(!hcibuf[5]) { // Check if command succeeded
  339. hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag
  340. if((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information
  341. hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm
  342. hci_set_flag(HCI_FLAG_READ_VERSION);
  343. } else if((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address
  344. for(uint8_t i = 0; i < 6; i++)
  345. my_bdaddr[i] = hcibuf[6 + i];
  346. hci_set_flag(HCI_FLAG_READ_BDADDR);
  347. }
  348. }
  349. break;
  350. case EV_COMMAND_STATUS:
  351. if(hcibuf[2]) { // Show status on serial if not OK
  352. #ifdef DEBUG_USB_HOST
  353. Notify(PSTR("\r\nHCI Command Failed: "), 0x80);
  354. D_PrintHex<uint8_t > (hcibuf[2], 0x80);
  355. #endif
  356. }
  357. break;
  358. case EV_INQUIRY_COMPLETE:
  359. if(inquiry_counter >= 5 && (pairWithWii || pairWithHIDDevice)) {
  360. inquiry_counter = 0;
  361. #ifdef DEBUG_USB_HOST
  362. if(pairWithWii)
  363. Notify(PSTR("\r\nCouldn't find Wiimote"), 0x80);
  364. else
  365. Notify(PSTR("\r\nCouldn't find HID device"), 0x80);
  366. #endif
  367. connectToWii = false;
  368. pairWithWii = false;
  369. connectToHIDDevice = false;
  370. pairWithHIDDevice = false;
  371. hci_state = HCI_SCANNING_STATE;
  372. }
  373. inquiry_counter++;
  374. break;
  375. case EV_INQUIRY_RESULT:
  376. if(hcibuf[2]) { // Check that there is more than zero responses
  377. #ifdef EXTRADEBUG
  378. Notify(PSTR("\r\nNumber of responses: "), 0x80);
  379. Notify(hcibuf[2], 0x80);
  380. #endif
  381. for(uint8_t i = 0; i < hcibuf[2]; i++) {
  382. uint8_t offset = 8 * hcibuf[2] + 3 * i;
  383. for(uint8_t j = 0; j < 3; j++)
  384. classOfDevice[j] = hcibuf[j + 4 + offset];
  385. #ifdef EXTRADEBUG
  386. Notify(PSTR("\r\nClass of device: "), 0x80);
  387. D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
  388. Notify(PSTR(" "), 0x80);
  389. D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
  390. Notify(PSTR(" "), 0x80);
  391. D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
  392. #endif
  393. if(pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information
  394. checkRemoteName = true; // Check remote name to distinguish between the different controllers
  395. for(uint8_t j = 0; j < 6; j++)
  396. disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
  397. hci_set_flag(HCI_FLAG_DEVICE_FOUND);
  398. break;
  399. } else if(pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
  400. #ifdef DEBUG_USB_HOST
  401. if(classOfDevice[0] & 0x80)
  402. Notify(PSTR("\r\nMouse found"), 0x80);
  403. if(classOfDevice[0] & 0x40)
  404. Notify(PSTR("\r\nKeyboard found"), 0x80);
  405. if(classOfDevice[0] & 0x08)
  406. Notify(PSTR("\r\nGamepad found"), 0x80);
  407. #endif
  408. for(uint8_t j = 0; j < 6; j++)
  409. disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
  410. hci_set_flag(HCI_FLAG_DEVICE_FOUND);
  411. break;
  412. }
  413. }
  414. }
  415. break;
  416. case EV_CONNECT_COMPLETE:
  417. hci_set_flag(HCI_FLAG_CONNECT_EVENT);
  418. if(!hcibuf[2]) { // Check if connected OK
  419. #ifdef EXTRADEBUG
  420. Notify(PSTR("\r\nConnection established"), 0x80);
  421. #endif
  422. hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // Store the handle for the ACL connection
  423. hci_set_flag(HCI_FLAG_CONNECT_COMPLETE); // Set connection complete flag
  424. } else {
  425. hci_state = HCI_CHECK_DEVICE_SERVICE;
  426. #ifdef DEBUG_USB_HOST
  427. Notify(PSTR("\r\nConnection Failed: "), 0x80);
  428. D_PrintHex<uint8_t > (hcibuf[2], 0x80);
  429. #endif
  430. }
  431. break;
  432. case EV_DISCONNECT_COMPLETE:
  433. if(!hcibuf[2]) { // Check if disconnected OK
  434. hci_set_flag(HCI_FLAG_DISCONNECT_COMPLETE); // Set disconnect command complete flag
  435. hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); // Clear connection complete flag
  436. }
  437. break;
  438. case EV_REMOTE_NAME_COMPLETE:
  439. if(!hcibuf[2]) { // Check if reading is OK
  440. for(uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) {
  441. remote_name[i] = hcibuf[9 + i];
  442. if(remote_name[i] == '\0') // End of string
  443. break;
  444. }
  445. // TODO: Altid sæt '\0' i remote name!
  446. hci_set_flag(HCI_FLAG_REMOTE_NAME_COMPLETE);
  447. }
  448. break;
  449. case EV_INCOMING_CONNECT:
  450. for(uint8_t i = 0; i < 6; i++)
  451. disc_bdaddr[i] = hcibuf[i + 2];
  452. for(uint8_t i = 0; i < 3; i++)
  453. classOfDevice[i] = hcibuf[i + 8];
  454. if((classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad
  455. #ifdef DEBUG_USB_HOST
  456. if(classOfDevice[0] & 0x80)
  457. Notify(PSTR("\r\nMouse is connecting"), 0x80);
  458. if(classOfDevice[0] & 0x40)
  459. Notify(PSTR("\r\nKeyboard is connecting"), 0x80);
  460. if(classOfDevice[0] & 0x08)
  461. Notify(PSTR("\r\nGamepad is connecting"), 0x80);
  462. #endif
  463. incomingHIDDevice = true;
  464. }
  465. #ifdef EXTRADEBUG
  466. Notify(PSTR("\r\nClass of device: "), 0x80);
  467. D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
  468. Notify(PSTR(" "), 0x80);
  469. D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
  470. Notify(PSTR(" "), 0x80);
  471. D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
  472. #endif
  473. hci_set_flag(HCI_FLAG_INCOMING_REQUEST);
  474. break;
  475. case EV_PIN_CODE_REQUEST:
  476. if(pairWithWii) {
  477. #ifdef DEBUG_USB_HOST
  478. Notify(PSTR("\r\nPairing with Wiimote"), 0x80);
  479. #endif
  480. hci_pin_code_request_reply();
  481. } else if(btdPin != NULL) {
  482. #ifdef DEBUG_USB_HOST
  483. Notify(PSTR("\r\nBluetooth pin is set too: "), 0x80);
  484. NotifyStr(btdPin, 0x80);
  485. #endif
  486. hci_pin_code_request_reply();
  487. } else {
  488. #ifdef DEBUG_USB_HOST
  489. Notify(PSTR("\r\nNo pin was set"), 0x80);
  490. #endif
  491. hci_pin_code_negative_request_reply();
  492. }
  493. break;
  494. case EV_LINK_KEY_REQUEST:
  495. #ifdef DEBUG_USB_HOST
  496. Notify(PSTR("\r\nReceived Key Request"), 0x80);
  497. #endif
  498. hci_link_key_request_negative_reply();
  499. break;
  500. case EV_AUTHENTICATION_COMPLETE:
  501. if(pairWithWii && !connectToWii) {
  502. #ifdef DEBUG_USB_HOST
  503. Notify(PSTR("\r\nPairing successful with Wiimote"), 0x80);
  504. #endif
  505. connectToWii = true; // Used to indicate to the Wii service, that it should connect to this device
  506. } else if(pairWithHIDDevice && !connectToHIDDevice) {
  507. #ifdef DEBUG_USB_HOST
  508. Notify(PSTR("\r\nPairing successful with HID device"), 0x80);
  509. #endif
  510. connectToHIDDevice = true; // Used to indicate to the BTHID service, that it should connect to this device
  511. }
  512. break;
  513. /* We will just ignore the following events */
  514. case EV_NUM_COMPLETE_PKT:
  515. case EV_ROLE_CHANGED:
  516. case EV_PAGE_SCAN_REP_MODE:
  517. case EV_LOOPBACK_COMMAND:
  518. case EV_DATA_BUFFER_OVERFLOW:
  519. case EV_CHANGE_CONNECTION_LINK:
  520. case EV_MAX_SLOTS_CHANGE:
  521. case EV_QOS_SETUP_COMPLETE:
  522. case EV_LINK_KEY_NOTIFICATION:
  523. case EV_ENCRYPTION_CHANGE:
  524. case EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE:
  525. break;
  526. #ifdef EXTRADEBUG
  527. default:
  528. if(hcibuf[0] != 0x00) {
  529. Notify(PSTR("\r\nUnmanaged HCI Event: "), 0x80);
  530. D_PrintHex<uint8_t > (hcibuf[0], 0x80);
  531. }
  532. break;
  533. #endif
  534. } // Switch
  535. }
  536. #ifdef EXTRADEBUG
  537. else {
  538. Notify(PSTR("\r\nHCI event error: "), 0x80);
  539. D_PrintHex<uint8_t > (rcode, 0x80);
  540. }
  541. #endif
  542. }
  543. /* Poll Bluetooth and print result */
  544. void BTD::HCI_task() {
  545. switch(hci_state) {
  546. case HCI_INIT_STATE:
  547. hci_counter++;
  548. if(hci_counter > hci_num_reset_loops) { // wait until we have looped x times to clear any old events
  549. hci_reset();
  550. hci_state = HCI_RESET_STATE;
  551. hci_counter = 0;
  552. }
  553. break;
  554. case HCI_RESET_STATE:
  555. hci_counter++;
  556. if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
  557. hci_counter = 0;
  558. #ifdef DEBUG_USB_HOST
  559. Notify(PSTR("\r\nHCI Reset complete"), 0x80);
  560. #endif
  561. hci_state = HCI_CLASS_STATE;
  562. hci_write_class_of_device();
  563. } else if(hci_counter > hci_num_reset_loops) {
  564. hci_num_reset_loops *= 10;
  565. if(hci_num_reset_loops > 2000)
  566. hci_num_reset_loops = 2000;
  567. #ifdef DEBUG_USB_HOST
  568. Notify(PSTR("\r\nNo response to HCI Reset"), 0x80);
  569. #endif
  570. hci_state = HCI_INIT_STATE;
  571. hci_counter = 0;
  572. }
  573. break;
  574. case HCI_CLASS_STATE:
  575. if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
  576. #ifdef DEBUG_USB_HOST
  577. Notify(PSTR("\r\nWrite class of device"), 0x80);
  578. #endif
  579. hci_state = HCI_BDADDR_STATE;
  580. hci_read_bdaddr();
  581. }
  582. break;
  583. case HCI_BDADDR_STATE:
  584. if(hci_check_flag(HCI_FLAG_READ_BDADDR)) {
  585. #ifdef DEBUG_USB_HOST
  586. Notify(PSTR("\r\nLocal Bluetooth Address: "), 0x80);
  587. for(int8_t i = 5; i > 0; i--) {
  588. D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
  589. Notify(PSTR(":"), 0x80);
  590. }
  591. D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
  592. #endif
  593. hci_read_local_version_information();
  594. hci_state = HCI_LOCAL_VERSION_STATE;
  595. }
  596. break;
  597. case HCI_LOCAL_VERSION_STATE: // The local version is used by the PS3BT class
  598. if(hci_check_flag(HCI_FLAG_READ_VERSION)) {
  599. if(btdName != NULL) {
  600. hci_set_local_name(btdName);
  601. hci_state = HCI_SET_NAME_STATE;
  602. } else
  603. hci_state = HCI_CHECK_DEVICE_SERVICE;
  604. }
  605. break;
  606. case HCI_SET_NAME_STATE:
  607. if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
  608. #ifdef DEBUG_USB_HOST
  609. Notify(PSTR("\r\nThe name is set to: "), 0x80);
  610. NotifyStr(btdName, 0x80);
  611. #endif
  612. hci_state = HCI_CHECK_DEVICE_SERVICE;
  613. }
  614. break;
  615. case HCI_CHECK_DEVICE_SERVICE:
  616. if(pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote
  617. #ifdef DEBUG_USB_HOST
  618. if(pairWithWii)
  619. Notify(PSTR("\r\nStarting inquiry\r\nPress 1 & 2 on the Wiimote\r\nOr press the SYNC button if you are using a Wii U Pro Controller or a Wii Balance Board"), 0x80);
  620. else
  621. Notify(PSTR("\r\nPlease enable discovery of your device"), 0x80);
  622. #endif
  623. hci_inquiry();
  624. hci_state = HCI_INQUIRY_STATE;
  625. } else
  626. hci_state = HCI_SCANNING_STATE; // Don't try to connect to a Wiimote
  627. break;
  628. case HCI_INQUIRY_STATE:
  629. if(hci_check_flag(HCI_FLAG_DEVICE_FOUND)) {
  630. hci_inquiry_cancel(); // Stop inquiry
  631. #ifdef DEBUG_USB_HOST
  632. if(pairWithWii)
  633. Notify(PSTR("\r\nWiimote found"), 0x80);
  634. else
  635. Notify(PSTR("\r\nHID device found"), 0x80);
  636. Notify(PSTR("\r\nNow just create the instance like so:"), 0x80);
  637. if(pairWithWii)
  638. Notify(PSTR("\r\nWII Wii(&Btd);"), 0x80);
  639. else
  640. Notify(PSTR("\r\nBTHID bthid(&Btd);"), 0x80);
  641. Notify(PSTR("\r\nAnd then press any button on the "), 0x80);
  642. if(pairWithWii)
  643. Notify(PSTR("Wiimote"), 0x80);
  644. else
  645. Notify(PSTR("device"), 0x80);
  646. #endif
  647. if(checkRemoteName) {
  648. hci_remote_name(); // We need to know the name to distinguish between the Wiimote, the new Wiimote with Motion Plus inside, a Wii U Pro Controller and a Wii Balance Board
  649. hci_state = HCI_REMOTE_NAME_STATE;
  650. } else
  651. hci_state = HCI_CONNECT_DEVICE_STATE;
  652. }
  653. break;
  654. case HCI_CONNECT_DEVICE_STATE:
  655. if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
  656. #ifdef DEBUG_USB_HOST
  657. if(pairWithWii)
  658. Notify(PSTR("\r\nConnecting to Wiimote"), 0x80);
  659. else
  660. Notify(PSTR("\r\nConnecting to HID device"), 0x80);
  661. #endif
  662. checkRemoteName = false;
  663. hci_connect();
  664. hci_state = HCI_CONNECTED_DEVICE_STATE;
  665. }
  666. break;
  667. case HCI_CONNECTED_DEVICE_STATE:
  668. if(hci_check_flag(HCI_FLAG_CONNECT_EVENT)) {
  669. if(hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) {
  670. #ifdef DEBUG_USB_HOST
  671. if(pairWithWii)
  672. Notify(PSTR("\r\nConnected to Wiimote"), 0x80);
  673. else
  674. Notify(PSTR("\r\nConnected to HID device"), 0x80);
  675. #endif
  676. hci_authentication_request(); // This will start the pairing with the Wiimote
  677. hci_state = HCI_SCANNING_STATE;
  678. } else {
  679. #ifdef DEBUG_USB_HOST
  680. Notify(PSTR("\r\nTrying to connect one more time..."), 0x80);
  681. #endif
  682. hci_connect(); // Try to connect one more time
  683. }
  684. }
  685. break;
  686. case HCI_SCANNING_STATE:
  687. if(!connectToWii && !pairWithWii && !connectToHIDDevice && !pairWithHIDDevice) {
  688. #ifdef DEBUG_USB_HOST
  689. Notify(PSTR("\r\nWait For Incoming Connection Request"), 0x80);
  690. #endif
  691. hci_write_scan_enable();
  692. watingForConnection = true;
  693. hci_state = HCI_CONNECT_IN_STATE;
  694. }
  695. break;
  696. case HCI_CONNECT_IN_STATE:
  697. if(hci_check_flag(HCI_FLAG_INCOMING_REQUEST)) {
  698. watingForConnection = false;
  699. #ifdef DEBUG_USB_HOST
  700. Notify(PSTR("\r\nIncoming Connection Request"), 0x80);
  701. #endif
  702. hci_remote_name();
  703. hci_state = HCI_REMOTE_NAME_STATE;
  704. } else if(hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE))
  705. hci_state = HCI_DISCONNECT_STATE;
  706. break;
  707. case HCI_REMOTE_NAME_STATE:
  708. if(hci_check_flag(HCI_FLAG_REMOTE_NAME_COMPLETE)) {
  709. #ifdef DEBUG_USB_HOST
  710. Notify(PSTR("\r\nRemote Name: "), 0x80);
  711. for(uint8_t i = 0; i < strlen(remote_name); i++)
  712. Notifyc(remote_name[i], 0x80);
  713. #endif
  714. if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) {
  715. incomingWii = true;
  716. motionPlusInside = false;
  717. wiiUProController = false;
  718. pairWiiUsingSync = false;
  719. #ifdef DEBUG_USB_HOST
  720. Notify(PSTR("\r\nWiimote is connecting"), 0x80);
  721. #endif
  722. if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) {
  723. #ifdef DEBUG_USB_HOST
  724. Notify(PSTR(" with Motion Plus Inside"), 0x80);
  725. #endif
  726. motionPlusInside = true;
  727. } else if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) {
  728. #ifdef DEBUG_USB_HOST
  729. Notify(PSTR(" - Wii U Pro Controller"), 0x80);
  730. #endif
  731. wiiUProController = motionPlusInside = pairWiiUsingSync = true;
  732. } else if(strncmp((const char*)remote_name, "Nintendo RVL-WBC-01", 19) == 0) {
  733. #ifdef DEBUG_USB_HOST
  734. Notify(PSTR(" - Wii Balance Board"), 0x80);
  735. #endif
  736. pairWiiUsingSync = true;
  737. }
  738. }
  739. if(classOfDevice[2] == 0 && classOfDevice[1] == 0x25 && classOfDevice[0] == 0x08 && strncmp((const char*)remote_name, "Wireless Controller", 19) == 0) {
  740. #ifdef DEBUG_USB_HOST
  741. Notify(PSTR("\r\nPS4 controller is connecting"), 0x80);
  742. #endif
  743. incomingPS4 = true;
  744. }
  745. if(pairWithWii && checkRemoteName)
  746. hci_state = HCI_CONNECT_DEVICE_STATE;
  747. else {
  748. hci_accept_connection();
  749. hci_state = HCI_CONNECTED_STATE;
  750. }
  751. }
  752. break;
  753. case HCI_CONNECTED_STATE:
  754. if(hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) {
  755. #ifdef DEBUG_USB_HOST
  756. Notify(PSTR("\r\nConnected to Device: "), 0x80);
  757. for(int8_t i = 5; i > 0; i--) {
  758. D_PrintHex<uint8_t > (disc_bdaddr[i], 0x80);
  759. Notify(PSTR(":"), 0x80);
  760. }
  761. D_PrintHex<uint8_t > (disc_bdaddr[0], 0x80);
  762. #endif
  763. if(incomingPS4)
  764. connectToHIDDevice = true; // We should always connect to the PS4 controller
  765. // Clear these flags for a new connection
  766. l2capConnectionClaimed = false;
  767. sdpConnectionClaimed = false;
  768. rfcommConnectionClaimed = false;
  769. hci_event_flag = 0;
  770. hci_state = HCI_DONE_STATE;
  771. }
  772. break;
  773. case HCI_DONE_STATE:
  774. hci_counter++;
  775. if(hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started
  776. hci_counter = 0;
  777. hci_state = HCI_SCANNING_STATE;
  778. }
  779. break;
  780. case HCI_DISCONNECT_STATE:
  781. if(hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) {
  782. #ifdef DEBUG_USB_HOST
  783. Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80);
  784. #endif
  785. hci_event_flag = 0; // Clear all flags
  786. // Reset all buffers
  787. memset(hcibuf, 0, BULK_MAXPKTSIZE);
  788. memset(l2capinbuf, 0, BULK_MAXPKTSIZE);
  789. connectToWii = incomingWii = pairWithWii = false;
  790. connectToHIDDevice = incomingHIDDevice = pairWithHIDDevice = checkRemoteName = false;
  791. incomingPS4 = false;
  792. hci_state = HCI_SCANNING_STATE;
  793. }
  794. break;
  795. default:
  796. break;
  797. }
  798. }
  799. void BTD::ACL_event_task() {
  800. uint16_t length = BULK_MAXPKTSIZE;
  801. uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf); // Input on endpoint 2
  802. if(!rcode) { // Check for errors
  803. if(length > 0) { // Check if any data was read
  804. for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
  805. if(btService[i])
  806. btService[i]->ACLData(l2capinbuf);
  807. }
  808. }
  809. }
  810. #ifdef EXTRADEBUG
  811. else if(rcode != hrNAK) {
  812. Notify(PSTR("\r\nACL data in error: "), 0x80);
  813. D_PrintHex<uint8_t > (rcode, 0x80);
  814. }
  815. #endif
  816. for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
  817. if(btService[i])
  818. btService[i]->Run();
  819. }
  820. /************************************************************/
  821. /* HCI Commands */
  822. /************************************************************/
  823. void BTD::HCI_Command(uint8_t* data, uint16_t nbytes) {
  824. hci_clear_flag(HCI_FLAG_CMD_COMPLETE);
  825. pUsb->ctrlReq(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, 0x00, 0x00, 0x00, 0x00, nbytes, nbytes, data, NULL);
  826. }
  827. void BTD::hci_reset() {
  828. hci_event_flag = 0; // Clear all the flags
  829. hcibuf[0] = 0x03; // HCI OCF = 3
  830. hcibuf[1] = 0x03 << 2; // HCI OGF = 3
  831. hcibuf[2] = 0x00;
  832. HCI_Command(hcibuf, 3);
  833. }
  834. void BTD::hci_write_scan_enable() {
  835. hci_clear_flag(HCI_FLAG_INCOMING_REQUEST);
  836. hcibuf[0] = 0x1A; // HCI OCF = 1A
  837. hcibuf[1] = 0x03 << 2; // HCI OGF = 3
  838. hcibuf[2] = 0x01; // parameter length = 1
  839. if(btdName != NULL)
  840. hcibuf[3] = 0x03; // Inquiry Scan enabled. Page Scan enabled.
  841. else
  842. hcibuf[3] = 0x02; // Inquiry Scan disabled. Page Scan enabled.
  843. HCI_Command(hcibuf, 4);
  844. }
  845. void BTD::hci_write_scan_disable() {
  846. hcibuf[0] = 0x1A; // HCI OCF = 1A
  847. hcibuf[1] = 0x03 << 2; // HCI OGF = 3
  848. hcibuf[2] = 0x01; // parameter length = 1
  849. hcibuf[3] = 0x00; // Inquiry Scan disabled. Page Scan disabled.
  850. HCI_Command(hcibuf, 4);
  851. }
  852. void BTD::hci_read_bdaddr() {
  853. hci_clear_flag(HCI_FLAG_READ_BDADDR);
  854. hcibuf[0] = 0x09; // HCI OCF = 9
  855. hcibuf[1] = 0x04 << 2; // HCI OGF = 4
  856. hcibuf[2] = 0x00;
  857. HCI_Command(hcibuf, 3);
  858. }
  859. void BTD::hci_read_local_version_information() {
  860. hci_clear_flag(HCI_FLAG_READ_VERSION);
  861. hcibuf[0] = 0x01; // HCI OCF = 1
  862. hcibuf[1] = 0x04 << 2; // HCI OGF = 4
  863. hcibuf[2] = 0x00;
  864. HCI_Command(hcibuf, 3);
  865. }
  866. void BTD::hci_accept_connection() {
  867. hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE);
  868. hcibuf[0] = 0x09; // HCI OCF = 9
  869. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  870. hcibuf[2] = 0x07; // parameter length 7
  871. hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
  872. hcibuf[4] = disc_bdaddr[1];
  873. hcibuf[5] = disc_bdaddr[2];
  874. hcibuf[6] = disc_bdaddr[3];
  875. hcibuf[7] = disc_bdaddr[4];
  876. hcibuf[8] = disc_bdaddr[5];
  877. hcibuf[9] = 0x00; // Switch role to master
  878. HCI_Command(hcibuf, 10);
  879. }
  880. void BTD::hci_remote_name() {
  881. hci_clear_flag(HCI_FLAG_REMOTE_NAME_COMPLETE);
  882. hcibuf[0] = 0x19; // HCI OCF = 19
  883. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  884. hcibuf[2] = 0x0A; // parameter length = 10
  885. hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
  886. hcibuf[4] = disc_bdaddr[1];
  887. hcibuf[5] = disc_bdaddr[2];
  888. hcibuf[6] = disc_bdaddr[3];
  889. hcibuf[7] = disc_bdaddr[4];
  890. hcibuf[8] = disc_bdaddr[5];
  891. hcibuf[9] = 0x01; // Page Scan Repetition Mode
  892. hcibuf[10] = 0x00; // Reserved
  893. hcibuf[11] = 0x00; // Clock offset - low byte
  894. hcibuf[12] = 0x00; // Clock offset - high byte
  895. HCI_Command(hcibuf, 13);
  896. }
  897. void BTD::hci_set_local_name(const char* name) {
  898. hcibuf[0] = 0x13; // HCI OCF = 13
  899. hcibuf[1] = 0x03 << 2; // HCI OGF = 3
  900. hcibuf[2] = strlen(name) + 1; // parameter length = the length of the string + end byte
  901. uint8_t i;
  902. for(i = 0; i < strlen(name); i++)
  903. hcibuf[i + 3] = name[i];
  904. hcibuf[i + 3] = 0x00; // End of string
  905. HCI_Command(hcibuf, 4 + strlen(name));
  906. }
  907. void BTD::hci_inquiry() {
  908. hci_clear_flag(HCI_FLAG_DEVICE_FOUND);
  909. hcibuf[0] = 0x01;
  910. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  911. hcibuf[2] = 0x05; // Parameter Total Length = 5
  912. hcibuf[3] = 0x33; // LAP: Genera/Unlimited Inquiry Access Code (GIAC = 0x9E8B33) - see https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
  913. hcibuf[4] = 0x8B;
  914. hcibuf[5] = 0x9E;
  915. hcibuf[6] = 0x30; // Inquiry time = 61.44 sec (maximum)
  916. hcibuf[7] = 0x0A; // 10 number of responses
  917. HCI_Command(hcibuf, 8);
  918. }
  919. void BTD::hci_inquiry_cancel() {
  920. hcibuf[0] = 0x02;
  921. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  922. hcibuf[2] = 0x00; // Parameter Total Length = 0
  923. HCI_Command(hcibuf, 3);
  924. }
  925. void BTD::hci_connect() {
  926. hci_connect(disc_bdaddr); // Use last discovered device
  927. }
  928. void BTD::hci_connect(uint8_t *bdaddr) {
  929. hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE | HCI_FLAG_CONNECT_EVENT);
  930. hcibuf[0] = 0x05;
  931. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  932. hcibuf[2] = 0x0D; // parameter Total Length = 13
  933. hcibuf[3] = bdaddr[0]; // 6 octet bdaddr (LSB)
  934. hcibuf[4] = bdaddr[1];
  935. hcibuf[5] = bdaddr[2];
  936. hcibuf[6] = bdaddr[3];
  937. hcibuf[7] = bdaddr[4];
  938. hcibuf[8] = bdaddr[5];
  939. hcibuf[9] = 0x18; // DM1 or DH1 may be used
  940. hcibuf[10] = 0xCC; // DM3, DH3, DM5, DH5 may be used
  941. hcibuf[11] = 0x01; // Page repetition mode R1
  942. hcibuf[12] = 0x00; // Reserved
  943. hcibuf[13] = 0x00; // Clock offset
  944. hcibuf[14] = 0x00; // Invalid clock offset
  945. hcibuf[15] = 0x00; // Do not allow role switch
  946. HCI_Command(hcibuf, 16);
  947. }
  948. void BTD::hci_pin_code_request_reply() {
  949. hcibuf[0] = 0x0D; // HCI OCF = 0D
  950. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  951. hcibuf[2] = 0x17; // parameter length 23
  952. hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
  953. hcibuf[4] = disc_bdaddr[1];
  954. hcibuf[5] = disc_bdaddr[2];
  955. hcibuf[6] = disc_bdaddr[3];
  956. hcibuf[7] = disc_bdaddr[4];
  957. hcibuf[8] = disc_bdaddr[5];
  958. if(pairWithWii) {
  959. hcibuf[9] = 6; // Pin length is the length of the Bluetooth address
  960. if(pairWiiUsingSync) {
  961. #ifdef DEBUG_USB_HOST
  962. Notify(PSTR("\r\nParing with Wii controller via SYNC"), 0x80);
  963. #endif
  964. for(uint8_t i = 0; i < 6; i++)
  965. hcibuf[10 + i] = my_bdaddr[i]; // The pin is the Bluetooth dongles Bluetooth address backwards
  966. } else {
  967. for(uint8_t i = 0; i < 6; i++)
  968. hcibuf[10 + i] = disc_bdaddr[i]; // The pin is the Wiimote's Bluetooth address backwards
  969. }
  970. for(uint8_t i = 16; i < 26; i++)
  971. hcibuf[i] = 0x00; // The rest should be 0
  972. } else {
  973. hcibuf[9] = strlen(btdPin); // Length of pin
  974. uint8_t i;
  975. for(i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16
  976. hcibuf[i + 10] = btdPin[i];
  977. for(; i < 16; i++)
  978. hcibuf[i + 10] = 0x00; // The rest should be 0
  979. }
  980. HCI_Command(hcibuf, 26);
  981. }
  982. void BTD::hci_pin_code_negative_request_reply() {
  983. hcibuf[0] = 0x0E; // HCI OCF = 0E
  984. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  985. hcibuf[2] = 0x06; // parameter length 6
  986. hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
  987. hcibuf[4] = disc_bdaddr[1];
  988. hcibuf[5] = disc_bdaddr[2];
  989. hcibuf[6] = disc_bdaddr[3];
  990. hcibuf[7] = disc_bdaddr[4];
  991. hcibuf[8] = disc_bdaddr[5];
  992. HCI_Command(hcibuf, 9);
  993. }
  994. void BTD::hci_link_key_request_negative_reply() {
  995. hcibuf[0] = 0x0C; // HCI OCF = 0C
  996. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  997. hcibuf[2] = 0x06; // parameter length 6
  998. hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
  999. hcibuf[4] = disc_bdaddr[1];
  1000. hcibuf[5] = disc_bdaddr[2];
  1001. hcibuf[6] = disc_bdaddr[3];
  1002. hcibuf[7] = disc_bdaddr[4];
  1003. hcibuf[8] = disc_bdaddr[5];
  1004. HCI_Command(hcibuf, 9);
  1005. }
  1006. void BTD::hci_authentication_request() {
  1007. hcibuf[0] = 0x11; // HCI OCF = 11
  1008. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  1009. hcibuf[2] = 0x02; // parameter length = 2
  1010. hcibuf[3] = (uint8_t)(hci_handle & 0xFF); //connection handle - low byte
  1011. hcibuf[4] = (uint8_t)((hci_handle >> 8) & 0x0F); //connection handle - high byte
  1012. HCI_Command(hcibuf, 5);
  1013. }
  1014. void BTD::hci_disconnect(uint16_t handle) { // This is called by the different services
  1015. hci_clear_flag(HCI_FLAG_DISCONNECT_COMPLETE);
  1016. hcibuf[0] = 0x06; // HCI OCF = 6
  1017. hcibuf[1] = 0x01 << 2; // HCI OGF = 1
  1018. hcibuf[2] = 0x03; // parameter length = 3
  1019. hcibuf[3] = (uint8_t)(handle & 0xFF); //connection handle - low byte
  1020. hcibuf[4] = (uint8_t)((handle >> 8) & 0x0F); //connection handle - high byte
  1021. hcibuf[5] = 0x13; // reason
  1022. HCI_Command(hcibuf, 6);
  1023. }
  1024. void BTD::hci_write_class_of_device() { // See http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
  1025. hcibuf[0] = 0x24; // HCI OCF = 24
  1026. hcibuf[1] = 0x03 << 2; // HCI OGF = 3
  1027. hcibuf[2] = 0x03; // parameter length = 3
  1028. hcibuf[3] = 0x04; // Robot
  1029. hcibuf[4] = 0x08; // Toy
  1030. hcibuf[5] = 0x00;
  1031. HCI_Command(hcibuf, 6);
  1032. }
  1033. /*******************************************************************
  1034. * *
  1035. * HCI ACL Data Packet *
  1036. * *
  1037. * buf[0] buf[1] buf[2] buf[3]
  1038. * 0 4 8 11 12 16 24 31 MSB
  1039. * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
  1040. * | HCI Handle |PB |BC | Data Total Length | HCI ACL Data Packet
  1041. * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
  1042. *
  1043. * buf[4] buf[5] buf[6] buf[7]
  1044. * 0 8 16 31 MSB
  1045. * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
  1046. * | Length | Channel ID | Basic L2CAP header
  1047. * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
  1048. *
  1049. * buf[8] buf[9] buf[10] buf[11]
  1050. * 0 8 16 31 MSB
  1051. * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
  1052. * | Code | Identifier | Length | Control frame (C-frame)
  1053. * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-. (signaling packet format)
  1054. */
  1055. /************************************************************/
  1056. /* L2CAP Commands */
  1057. /************************************************************/
  1058. void BTD::L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh) {
  1059. uint8_t buf[8 + nbytes];
  1060. buf[0] = (uint8_t)(handle & 0xff); // HCI handle with PB,BC flag
  1061. buf[1] = (uint8_t)(((handle >> 8) & 0x0f) | 0x20);
  1062. buf[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
  1063. buf[3] = (uint8_t)((4 + nbytes) >> 8);
  1064. buf[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
  1065. buf[5] = (uint8_t)(nbytes >> 8);
  1066. buf[6] = channelLow;
  1067. buf[7] = channelHigh;
  1068. for(uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame
  1069. buf[8 + i] = data[i];
  1070. uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ BTD_DATAOUT_PIPE ].epAddr, (8 + nbytes), buf);
  1071. if(rcode) {
  1072. delay(100); // This small delay prevents it from overflowing if it fails
  1073. #ifdef DEBUG_USB_HOST
  1074. Notify(PSTR("\r\nError sending L2CAP message: 0x"), 0x80);
  1075. D_PrintHex<uint8_t > (rcode, 0x80);
  1076. Notify(PSTR(" - Channel ID: "), 0x80);
  1077. D_PrintHex<uint8_t > (channelHigh, 0x80);
  1078. Notify(PSTR(" "), 0x80);
  1079. D_PrintHex<uint8_t > (channelLow, 0x80);
  1080. #endif
  1081. }
  1082. }
  1083. void BTD::l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm) {
  1084. l2capoutbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
  1085. l2capoutbuf[1] = rxid; // Identifier
  1086. l2capoutbuf[2] = 0x04; // Length
  1087. l2capoutbuf[3] = 0x00;
  1088. l2capoutbuf[4] = (uint8_t)(psm & 0xff); // PSM
  1089. l2capoutbuf[5] = (uint8_t)(psm >> 8);
  1090. l2capoutbuf[6] = scid[0]; // Source CID
  1091. l2capoutbuf[7] = scid[1];
  1092. L2CAP_Command(handle, l2capoutbuf, 8);
  1093. }
  1094. void BTD::l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result) {
  1095. l2capoutbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
  1096. l2capoutbuf[1] = rxid; // Identifier
  1097. l2capoutbuf[2] = 0x08; // Length
  1098. l2capoutbuf[3] = 0x00;
  1099. l2capoutbuf[4] = dcid[0]; // Destination CID
  1100. l2capoutbuf[5] = dcid[1];
  1101. l2capoutbuf[6] = scid[0]; // Source CID
  1102. l2capoutbuf[7] = scid[1];
  1103. l2capoutbuf[8] = result; // Result: Pending or Success
  1104. l2capoutbuf[9] = 0x00;
  1105. l2capoutbuf[10] = 0x00; // No further information
  1106. l2capoutbuf[11] = 0x00;
  1107. L2CAP_Command(handle, l2capoutbuf, 12);
  1108. }
  1109. void BTD::l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid) {
  1110. l2capoutbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
  1111. l2capoutbuf[1] = rxid; // Identifier
  1112. l2capoutbuf[2] = 0x08; // Length
  1113. l2capoutbuf[3] = 0x00;
  1114. l2capoutbuf[4] = dcid[0]; // Destination CID
  1115. l2capoutbuf[5] = dcid[1];
  1116. l2capoutbuf[6] = 0x00; // Flags
  1117. l2capoutbuf[7] = 0x00;
  1118. l2capoutbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
  1119. l2capoutbuf[9] = 0x02; // Config Opt: length
  1120. l2capoutbuf[10] = 0xFF; // MTU
  1121. l2capoutbuf[11] = 0xFF;
  1122. L2CAP_Command(handle, l2capoutbuf, 12);
  1123. }
  1124. void BTD::l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid) {
  1125. l2capoutbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
  1126. l2capoutbuf[1] = rxid; // Identifier
  1127. l2capoutbuf[2] = 0x0A; // Length
  1128. l2capoutbuf[3] = 0x00;
  1129. l2capoutbuf[4] = scid[0]; // Source CID
  1130. l2capoutbuf[5] = scid[1];
  1131. l2capoutbuf[6] = 0x00; // Flag
  1132. l2capoutbuf[7] = 0x00;
  1133. l2capoutbuf[8] = 0x00; // Result
  1134. l2capoutbuf[9] = 0x00;
  1135. l2capoutbuf[10] = 0x01; // Config
  1136. l2capoutbuf[11] = 0x02;
  1137. l2capoutbuf[12] = 0xA0;
  1138. l2capoutbuf[13] = 0x02;
  1139. L2CAP_Command(handle, l2capoutbuf, 14);
  1140. }
  1141. void BTD::l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
  1142. l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_REQUEST; // Code
  1143. l2capoutbuf[1] = rxid; // Identifier
  1144. l2capoutbuf[2] = 0x04; // Length
  1145. l2capoutbuf[3] = 0x00;
  1146. l2capoutbuf[4] = dcid[0];
  1147. l2capoutbuf[5] = dcid[1];
  1148. l2capoutbuf[6] = scid[0];
  1149. l2capoutbuf[7] = scid[1];
  1150. L2CAP_Command(handle, l2capoutbuf, 8);
  1151. }
  1152. void BTD::l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
  1153. l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_RESPONSE; // Code
  1154. l2capoutbuf[1] = rxid; // Identifier
  1155. l2capoutbuf[2] = 0x04; // Length
  1156. l2capoutbuf[3] = 0x00;
  1157. l2capoutbuf[4] = dcid[0];
  1158. l2capoutbuf[5] = dcid[1];
  1159. l2capoutbuf[6] = scid[0];
  1160. l2capoutbuf[7] = scid[1];
  1161. L2CAP_Command(handle, l2capoutbuf, 8);
  1162. }
  1163. void BTD::l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh) {
  1164. l2capoutbuf[0] = L2CAP_CMD_INFORMATION_RESPONSE; // Code
  1165. l2capoutbuf[1] = rxid; // Identifier
  1166. l2capoutbuf[2] = 0x08; // Length
  1167. l2capoutbuf[3] = 0x00;
  1168. l2capoutbuf[4] = infoTypeLow;
  1169. l2capoutbuf[5] = infoTypeHigh;
  1170. l2capoutbuf[6] = 0x00; // Result = success
  1171. l2capoutbuf[7] = 0x00; // Result = success
  1172. l2capoutbuf[8] = 0x00;
  1173. l2capoutbuf[9] = 0x00;
  1174. l2capoutbuf[10] = 0x00;
  1175. l2capoutbuf[11] = 0x00;
  1176. L2CAP_Command(handle, l2capoutbuf, 12);
  1177. }
  1178. /* PS3 Commands - only set Bluetooth address is implemented in this library */
  1179. void BTD::setBdaddr(uint8_t* bdaddr) {
  1180. /* Set the internal Bluetooth address */
  1181. uint8_t buf[8];
  1182. buf[0] = 0x01;
  1183. buf[1] = 0x00;
  1184. for(uint8_t i = 0; i < 6; i++)
  1185. buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first
  1186. // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0xF5), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
  1187. pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
  1188. }
  1189. void BTD::setMoveBdaddr(uint8_t* bdaddr) {
  1190. /* Set the internal Bluetooth address */
  1191. uint8_t buf[11];
  1192. buf[0] = 0x05;
  1193. buf[7] = 0x10;
  1194. buf[8] = 0x01;
  1195. buf[9] = 0x02;
  1196. buf[10] = 0x12;
  1197. for(uint8_t i = 0; i < 6; i++)
  1198. buf[i + 1] = bdaddr[i];
  1199. // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x05), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
  1200. pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
  1201. }