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_NUM_SERVICES; 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_NUM_SERVICES; 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((long)(millis() - qNextPollTime) >= 0L) { // 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 bthid(&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 < strlen(remote_name); i++)
800  Notifyc(remote_name[i], 0x80);
801 #endif
802  if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) {
803  incomingWii = true;
804 #ifdef DEBUG_USB_HOST
805  Notify(PSTR("\r\nWiimote is connecting"), 0x80);
806 #endif
807  if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) {
808 #ifdef DEBUG_USB_HOST
809  Notify(PSTR(" with Motion Plus Inside"), 0x80);
810 #endif
811  motionPlusInside = true;
812  } else if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) {
813 #ifdef DEBUG_USB_HOST
814  Notify(PSTR(" - Wii U Pro Controller"), 0x80);
815 #endif
816  motionPlusInside = true;
817  wiiUProController = true;
818  } else {
819  motionPlusInside = false;
820  wiiUProController = false;
821  }
822  }
823  if(classOfDevice[2] == 0 && classOfDevice[1] == 0x25 && classOfDevice[0] == 0x08 && strncmp((const char*)remote_name, "Wireless Controller", 19) == 0) {
824 #ifdef DEBUG_USB_HOST
825  Notify(PSTR("\r\nPS4 controller is connecting"), 0x80);
826 #endif
827  incomingPS4 = true;
828  }
830  hci_state = HCI_CONNECT_DEVICE_STATE;
831  else {
833  hci_state = HCI_CONNECTED_STATE;
834  }
835  }
836  break;
837 
838  case HCI_CONNECTED_STATE:
840 #ifdef DEBUG_USB_HOST
841  Notify(PSTR("\r\nConnected to Device: "), 0x80);
842  for(int8_t i = 5; i > 0; i--) {
843  D_PrintHex<uint8_t > (disc_bdaddr[i], 0x80);
844  Notify(PSTR(":"), 0x80);
845  }
846  D_PrintHex<uint8_t > (disc_bdaddr[0], 0x80);
847 #endif
848  if(incomingPS4)
849  connectToHIDDevice = true; // We should always connect to the PS4 controller
850 
851  // Clear these flags for a new connection
852  l2capConnectionClaimed = false;
853  sdpConnectionClaimed = false;
854  rfcommConnectionClaimed = false;
855 
856  hci_event_flag = 0;
857  hci_state = HCI_DONE_STATE;
858  }
859  break;
860 
861  case HCI_DONE_STATE:
862  hci_counter++;
863  if(hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started
864  hci_counter = 0;
865  hci_state = HCI_SCANNING_STATE;
866  }
867  break;
868 
871 #ifdef DEBUG_USB_HOST
872  Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80);
873 #endif
874  hci_event_flag = 0; // Clear all flags
875 
876  // Reset all buffers
877  memset(hcibuf, 0, BULK_MAXPKTSIZE);
878  memset(l2capinbuf, 0, BULK_MAXPKTSIZE);
879 
882  incomingPS4 = false;
883 
884  hci_state = HCI_SCANNING_STATE;
885  }
886  break;
887  default:
888  break;
889  }
890 }
891 
892 void BTD::ACL_event_task() {
893  uint16_t length = BULK_MAXPKTSIZE;
894  uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf); // Input on endpoint 2
895 
896  if(!rcode) { // Check for errors
897  if(length > 0) { // Check if any data was read
898  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
899  if(btService[i])
900  btService[i]->ACLData(l2capinbuf);
901  }
902  }
903  }
904 #ifdef EXTRADEBUG
905  else if(rcode != hrNAK) {
906  Notify(PSTR("\r\nACL data in error: "), 0x80);
907  D_PrintHex<uint8_t > (rcode, 0x80);
908  }
909 #endif
910  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
911  if(btService[i])
912  btService[i]->Run();
913 }
914 
915 /************************************************************/
916 /* HCI Commands */
917 
918 /************************************************************/
919 void BTD::HCI_Command(uint8_t* data, uint16_t nbytes) {
921  pUsb->ctrlReq(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, 0x00, 0x00, 0x00, 0x00, nbytes, nbytes, data, NULL);
922 }
923 
925  hci_event_flag = 0; // Clear all the flags
926  hcibuf[0] = 0x03; // HCI OCF = 3
927  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
928  hcibuf[2] = 0x00;
929 
930  HCI_Command(hcibuf, 3);
931 }
932 
935  hcibuf[0] = 0x1A; // HCI OCF = 1A
936  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
937  hcibuf[2] = 0x01; // parameter length = 1
938  if(btdName != NULL)
939  hcibuf[3] = 0x03; // Inquiry Scan enabled. Page Scan enabled.
940  else
941  hcibuf[3] = 0x02; // Inquiry Scan disabled. Page Scan enabled.
942 
943  HCI_Command(hcibuf, 4);
944 }
945 
947  hcibuf[0] = 0x1A; // HCI OCF = 1A
948  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
949  hcibuf[2] = 0x01; // parameter length = 1
950  hcibuf[3] = 0x00; // Inquiry Scan disabled. Page Scan disabled.
951 
952  HCI_Command(hcibuf, 4);
953 }
954 
957  hcibuf[0] = 0x09; // HCI OCF = 9
958  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
959  hcibuf[2] = 0x00;
960 
961  HCI_Command(hcibuf, 3);
962 }
963 
966  hcibuf[0] = 0x01; // HCI OCF = 1
967  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
968  hcibuf[2] = 0x00;
969 
970  HCI_Command(hcibuf, 3);
971 }
972 
975  hcibuf[0] = 0x09; // HCI OCF = 9
976  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
977  hcibuf[2] = 0x07; // parameter length 7
978  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
979  hcibuf[4] = disc_bdaddr[1];
980  hcibuf[5] = disc_bdaddr[2];
981  hcibuf[6] = disc_bdaddr[3];
982  hcibuf[7] = disc_bdaddr[4];
983  hcibuf[8] = disc_bdaddr[5];
984  hcibuf[9] = 0x00; // Switch role to master
985 
986  HCI_Command(hcibuf, 10);
987 }
988 
991  hcibuf[0] = 0x19; // HCI OCF = 19
992  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
993  hcibuf[2] = 0x0A; // parameter length = 10
994  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
995  hcibuf[4] = disc_bdaddr[1];
996  hcibuf[5] = disc_bdaddr[2];
997  hcibuf[6] = disc_bdaddr[3];
998  hcibuf[7] = disc_bdaddr[4];
999  hcibuf[8] = disc_bdaddr[5];
1000  hcibuf[9] = 0x01; // Page Scan Repetition Mode
1001  hcibuf[10] = 0x00; // Reserved
1002  hcibuf[11] = 0x00; // Clock offset - low byte
1003  hcibuf[12] = 0x00; // Clock offset - high byte
1004 
1005  HCI_Command(hcibuf, 13);
1006 }
1007 
1008 void BTD::hci_set_local_name(const char* name) {
1009  hcibuf[0] = 0x13; // HCI OCF = 13
1010  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1011  hcibuf[2] = strlen(name) + 1; // parameter length = the length of the string + end byte
1012  uint8_t i;
1013  for(i = 0; i < strlen(name); i++)
1014  hcibuf[i + 3] = name[i];
1015  hcibuf[i + 3] = 0x00; // End of string
1016 
1017  HCI_Command(hcibuf, 4 + strlen(name));
1018 }
1019 
1022  hcibuf[0] = 0x01;
1023  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1024  hcibuf[2] = 0x05; // Parameter Total Length = 5
1025  hcibuf[3] = 0x33; // LAP: Genera/Unlimited Inquiry Access Code (GIAC = 0x9E8B33) - see https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
1026  hcibuf[4] = 0x8B;
1027  hcibuf[5] = 0x9E;
1028  hcibuf[6] = 0x30; // Inquiry time = 61.44 sec (maximum)
1029  hcibuf[7] = 0x0A; // 10 number of responses
1030 
1031  HCI_Command(hcibuf, 8);
1032 }
1033 
1035  hcibuf[0] = 0x02;
1036  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1037  hcibuf[2] = 0x00; // Parameter Total Length = 0
1038 
1039  HCI_Command(hcibuf, 3);
1040 }
1041 
1043  hci_connect(disc_bdaddr); // Use last discovered device
1044 }
1045 
1046 void BTD::hci_connect(uint8_t *bdaddr) {
1048  hcibuf[0] = 0x05;
1049  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1050  hcibuf[2] = 0x0D; // parameter Total Length = 13
1051  hcibuf[3] = bdaddr[0]; // 6 octet bdaddr (LSB)
1052  hcibuf[4] = bdaddr[1];
1053  hcibuf[5] = bdaddr[2];
1054  hcibuf[6] = bdaddr[3];
1055  hcibuf[7] = bdaddr[4];
1056  hcibuf[8] = bdaddr[5];
1057  hcibuf[9] = 0x18; // DM1 or DH1 may be used
1058  hcibuf[10] = 0xCC; // DM3, DH3, DM5, DH5 may be used
1059  hcibuf[11] = 0x01; // Page repetition mode R1
1060  hcibuf[12] = 0x00; // Reserved
1061  hcibuf[13] = 0x00; // Clock offset
1062  hcibuf[14] = 0x00; // Invalid clock offset
1063  hcibuf[15] = 0x00; // Do not allow role switch
1064 
1065  HCI_Command(hcibuf, 16);
1066 }
1067 
1069  hcibuf[0] = 0x0D; // HCI OCF = 0D
1070  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1071  hcibuf[2] = 0x17; // parameter length 23
1072  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1073  hcibuf[4] = disc_bdaddr[1];
1074  hcibuf[5] = disc_bdaddr[2];
1075  hcibuf[6] = disc_bdaddr[3];
1076  hcibuf[7] = disc_bdaddr[4];
1077  hcibuf[8] = disc_bdaddr[5];
1078  if(pairWithWii) {
1079  hcibuf[9] = 6; // Pin length is the length of the Bluetooth address
1080  if(wiiUProController) {
1081 #ifdef DEBUG_USB_HOST
1082  Notify(PSTR("\r\nParing with Wii U Pro Controller"), 0x80);
1083 #endif
1084  for(uint8_t i = 0; i < 6; i++)
1085  hcibuf[10 + i] = my_bdaddr[i]; // The pin is the Bluetooth dongles Bluetooth address backwards
1086  } else {
1087  for(uint8_t i = 0; i < 6; i++)
1088  hcibuf[10 + i] = disc_bdaddr[i]; // The pin is the Wiimote's Bluetooth address backwards
1089  }
1090  for(uint8_t i = 16; i < 26; i++)
1091  hcibuf[i] = 0x00; // The rest should be 0
1092  } else {
1093  hcibuf[9] = strlen(btdPin); // Length of pin
1094  uint8_t i;
1095  for(i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16
1096  hcibuf[i + 10] = btdPin[i];
1097  for(; i < 16; i++)
1098  hcibuf[i + 10] = 0x00; // The rest should be 0
1099  }
1100 
1101  HCI_Command(hcibuf, 26);
1102 }
1103 
1105  hcibuf[0] = 0x0E; // HCI OCF = 0E
1106  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1107  hcibuf[2] = 0x06; // parameter length 6
1108  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1109  hcibuf[4] = disc_bdaddr[1];
1110  hcibuf[5] = disc_bdaddr[2];
1111  hcibuf[6] = disc_bdaddr[3];
1112  hcibuf[7] = disc_bdaddr[4];
1113  hcibuf[8] = disc_bdaddr[5];
1114 
1115  HCI_Command(hcibuf, 9);
1116 }
1117 
1119  hcibuf[0] = 0x0C; // HCI OCF = 0C
1120  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1121  hcibuf[2] = 0x06; // parameter length 6
1122  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1123  hcibuf[4] = disc_bdaddr[1];
1124  hcibuf[5] = disc_bdaddr[2];
1125  hcibuf[6] = disc_bdaddr[3];
1126  hcibuf[7] = disc_bdaddr[4];
1127  hcibuf[8] = disc_bdaddr[5];
1128 
1129  HCI_Command(hcibuf, 9);
1130 }
1131 
1133  hcibuf[0] = 0x11; // HCI OCF = 11
1134  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1135  hcibuf[2] = 0x02; // parameter length = 2
1136  hcibuf[3] = (uint8_t)(hci_handle & 0xFF); //connection handle - low byte
1137  hcibuf[4] = (uint8_t)((hci_handle >> 8) & 0x0F); //connection handle - high byte
1138 
1139  HCI_Command(hcibuf, 5);
1140 }
1141 
1142 void BTD::hci_disconnect(uint16_t handle) { // This is called by the different services
1144  hcibuf[0] = 0x06; // HCI OCF = 6
1145  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1146  hcibuf[2] = 0x03; // parameter length = 3
1147  hcibuf[3] = (uint8_t)(handle & 0xFF); //connection handle - low byte
1148  hcibuf[4] = (uint8_t)((handle >> 8) & 0x0F); //connection handle - high byte
1149  hcibuf[5] = 0x13; // reason
1150 
1151  HCI_Command(hcibuf, 6);
1152 }
1153 
1154 void BTD::hci_write_class_of_device() { // See http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
1155  hcibuf[0] = 0x24; // HCI OCF = 24
1156  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1157  hcibuf[2] = 0x03; // parameter length = 3
1158  hcibuf[3] = 0x04; // Robot
1159  hcibuf[4] = 0x08; // Toy
1160  hcibuf[5] = 0x00;
1161 
1162  HCI_Command(hcibuf, 6);
1163 }
1164 /*******************************************************************
1165  * *
1166  * HCI ACL Data Packet *
1167  * *
1168  * buf[0] buf[1] buf[2] buf[3]
1169  * 0 4 8 11 12 16 24 31 MSB
1170  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1171  * | HCI Handle |PB |BC | Data Total Length | HCI ACL Data Packet
1172  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1173  *
1174  * buf[4] buf[5] buf[6] buf[7]
1175  * 0 8 16 31 MSB
1176  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1177  * | Length | Channel ID | Basic L2CAP header
1178  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1179  *
1180  * buf[8] buf[9] buf[10] buf[11]
1181  * 0 8 16 31 MSB
1182  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1183  * | Code | Identifier | Length | Control frame (C-frame)
1184  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-. (signaling packet format)
1185  */
1186 /************************************************************/
1187 /* L2CAP Commands */
1188 
1189 /************************************************************/
1190 void BTD::L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh) {
1191  uint8_t buf[8 + nbytes];
1192  buf[0] = (uint8_t)(handle & 0xff); // HCI handle with PB,BC flag
1193  buf[1] = (uint8_t)(((handle >> 8) & 0x0f) | 0x20);
1194  buf[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
1195  buf[3] = (uint8_t)((4 + nbytes) >> 8);
1196  buf[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
1197  buf[5] = (uint8_t)(nbytes >> 8);
1198  buf[6] = channelLow;
1199  buf[7] = channelHigh;
1200 
1201  for(uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame
1202  buf[8 + i] = data[i];
1203 
1204  uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ BTD_DATAOUT_PIPE ].epAddr, (8 + nbytes), buf);
1205  if(rcode) {
1206  delay(100); // This small delay prevents it from overflowing if it fails
1207 #ifdef DEBUG_USB_HOST
1208  Notify(PSTR("\r\nError sending L2CAP message: 0x"), 0x80);
1209  D_PrintHex<uint8_t > (rcode, 0x80);
1210  Notify(PSTR(" - Channel ID: "), 0x80);
1211  D_PrintHex<uint8_t > (channelHigh, 0x80);
1212  Notify(PSTR(" "), 0x80);
1213  D_PrintHex<uint8_t > (channelLow, 0x80);
1214 #endif
1215  }
1216 }
1217 
1218 void BTD::l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm) {
1219  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
1220  l2capoutbuf[1] = rxid; // Identifier
1221  l2capoutbuf[2] = 0x04; // Length
1222  l2capoutbuf[3] = 0x00;
1223  l2capoutbuf[4] = (uint8_t)(psm & 0xff); // PSM
1224  l2capoutbuf[5] = (uint8_t)(psm >> 8);
1225  l2capoutbuf[6] = scid[0]; // Source CID
1226  l2capoutbuf[7] = scid[1];
1227 
1228  L2CAP_Command(handle, l2capoutbuf, 8);
1229 }
1230 
1231 void BTD::l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result) {
1232  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
1233  l2capoutbuf[1] = rxid; // Identifier
1234  l2capoutbuf[2] = 0x08; // Length
1235  l2capoutbuf[3] = 0x00;
1236  l2capoutbuf[4] = dcid[0]; // Destination CID
1237  l2capoutbuf[5] = dcid[1];
1238  l2capoutbuf[6] = scid[0]; // Source CID
1239  l2capoutbuf[7] = scid[1];
1240  l2capoutbuf[8] = result; // Result: Pending or Success
1241  l2capoutbuf[9] = 0x00;
1242  l2capoutbuf[10] = 0x00; // No further information
1243  l2capoutbuf[11] = 0x00;
1244 
1245  L2CAP_Command(handle, l2capoutbuf, 12);
1246 }
1247 
1248 void BTD::l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid) {
1249  l2capoutbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
1250  l2capoutbuf[1] = rxid; // Identifier
1251  l2capoutbuf[2] = 0x08; // Length
1252  l2capoutbuf[3] = 0x00;
1253  l2capoutbuf[4] = dcid[0]; // Destination CID
1254  l2capoutbuf[5] = dcid[1];
1255  l2capoutbuf[6] = 0x00; // Flags
1256  l2capoutbuf[7] = 0x00;
1257  l2capoutbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
1258  l2capoutbuf[9] = 0x02; // Config Opt: length
1259  l2capoutbuf[10] = 0xFF; // MTU
1260  l2capoutbuf[11] = 0xFF;
1261 
1262  L2CAP_Command(handle, l2capoutbuf, 12);
1263 }
1264 
1265 void BTD::l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid) {
1266  l2capoutbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
1267  l2capoutbuf[1] = rxid; // Identifier
1268  l2capoutbuf[2] = 0x0A; // Length
1269  l2capoutbuf[3] = 0x00;
1270  l2capoutbuf[4] = scid[0]; // Source CID
1271  l2capoutbuf[5] = scid[1];
1272  l2capoutbuf[6] = 0x00; // Flag
1273  l2capoutbuf[7] = 0x00;
1274  l2capoutbuf[8] = 0x00; // Result
1275  l2capoutbuf[9] = 0x00;
1276  l2capoutbuf[10] = 0x01; // Config
1277  l2capoutbuf[11] = 0x02;
1278  l2capoutbuf[12] = 0xA0;
1279  l2capoutbuf[13] = 0x02;
1280 
1281  L2CAP_Command(handle, l2capoutbuf, 14);
1282 }
1283 
1284 void BTD::l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1285  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_REQUEST; // Code
1286  l2capoutbuf[1] = rxid; // Identifier
1287  l2capoutbuf[2] = 0x04; // Length
1288  l2capoutbuf[3] = 0x00;
1289  l2capoutbuf[4] = dcid[0];
1290  l2capoutbuf[5] = dcid[1];
1291  l2capoutbuf[6] = scid[0];
1292  l2capoutbuf[7] = scid[1];
1293 
1294  L2CAP_Command(handle, l2capoutbuf, 8);
1295 }
1296 
1297 void BTD::l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1298  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_RESPONSE; // Code
1299  l2capoutbuf[1] = rxid; // Identifier
1300  l2capoutbuf[2] = 0x04; // Length
1301  l2capoutbuf[3] = 0x00;
1302  l2capoutbuf[4] = dcid[0];
1303  l2capoutbuf[5] = dcid[1];
1304  l2capoutbuf[6] = scid[0];
1305  l2capoutbuf[7] = scid[1];
1306 
1307  L2CAP_Command(handle, l2capoutbuf, 8);
1308 }
1309 
1310 void BTD::l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh) {
1311  l2capoutbuf[0] = L2CAP_CMD_INFORMATION_RESPONSE; // Code
1312  l2capoutbuf[1] = rxid; // Identifier
1313  l2capoutbuf[2] = 0x08; // Length
1314  l2capoutbuf[3] = 0x00;
1315  l2capoutbuf[4] = infoTypeLow;
1316  l2capoutbuf[5] = infoTypeHigh;
1317  l2capoutbuf[6] = 0x00; // Result = success
1318  l2capoutbuf[7] = 0x00; // Result = success
1319  l2capoutbuf[8] = 0x00;
1320  l2capoutbuf[9] = 0x00;
1321  l2capoutbuf[10] = 0x00;
1322  l2capoutbuf[11] = 0x00;
1323 
1324  L2CAP_Command(handle, l2capoutbuf, 12);
1325 }
1326 
1327 /* PS3 Commands - only set Bluetooth address is implemented in this library */
1328 void BTD::setBdaddr(uint8_t* bdaddr) {
1329  /* Set the internal Bluetooth address */
1330  uint8_t buf[8];
1331  buf[0] = 0x01;
1332  buf[1] = 0x00;
1333 
1334  for(uint8_t i = 0; i < 6; i++)
1335  buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first
1336 
1337  // 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
1338  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
1339 }
1340 
1341 void BTD::setMoveBdaddr(uint8_t* bdaddr) {
1342  /* Set the internal Bluetooth address */
1343  uint8_t buf[11];
1344  buf[0] = 0x05;
1345  buf[7] = 0x10;
1346  buf[8] = 0x01;
1347  buf[9] = 0x02;
1348  buf[10] = 0x12;
1349 
1350  for(uint8_t i = 0; i < 6; i++)
1351  buf[i + 1] = bdaddr[i];
1352 
1353  // 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
1354  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
1355 }
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:1042
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:924
void l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t *dcid, uint8_t *scid, uint8_t result)
Definition: BTD.cpp:1231
#define HCI_SCANNING_STATE
Definition: BTD.h:54
bool lowspeed
Definition: address.h:79
#define USB_ERROR_EPINFO_IS_NULL
Definition: UsbCore.h:81
void l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t *scid, uint16_t psm)
Definition: BTD.cpp:1218
#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:1284
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:1020
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:946
#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 BTD_NUM_SERVICES
Definition: BTD.h:190
#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:989
#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:87
#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
char remote_name[30]
Definition: BTD.h:491
#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:1008
#define EV_QOS_SETUP_COMPLETE
Definition: BTD.h:96
void hci_write_scan_enable()
Definition: BTD.cpp:933
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:1297
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:1142
#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:955
void hci_inquiry_cancel()
Definition: BTD.cpp:1034
#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:83
#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:80
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:75
#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:1310
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:1154
#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:1104
#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:78
#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:206
#define HCI_CHECK_DEVICE_SERVICE
Definition: BTD.h:48
Definition: UsbCore.h:190
virtual void Run()
uint8_t bConfNum
Definition: BTD.h:544
void hci_link_key_request_negative_reply()
Definition: BTD.cpp:1118
#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:1190
#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:1265
void l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t *dcid)
Definition: BTD.cpp:1248
void hci_pin_code_request_reply()
Definition: BTD.cpp:1068
#define L2CAP_CMD_CONNECTION_REQUEST
Definition: BTD.h:166
uint8_t RegisterDeviceClass(USBDeviceConfig *pdev)
Definition: UsbCore.h:210
#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:1132
void hci_read_local_version_information()
Definition: BTD.cpp:964
#define HCI_FLAG_REMOTE_NAME_COMPLETE
Definition: BTD.h:66
void hci_accept_connection()
Definition: BTD.cpp:973
#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:86
void HCI_Command(uint8_t *data, uint16_t nbytes)
Definition: BTD.cpp:919