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