USB Host Shield 2.0
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 
384  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
385  if(btService[i])
386  btService[i]->disconnect();
387 };
388 
389 void BTD::HCI_event_task() {
390  uint16_t length = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this
391  uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &length, hcibuf); // Input on endpoint 1
392 
393  if(!rcode || rcode == hrNAK) { // Check for errors
394  switch(hcibuf[0]) { // Switch on event type
395  case EV_COMMAND_COMPLETE:
396  if(!hcibuf[5]) { // Check if command succeeded
397  hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag
398  if((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information
399  hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm
401  } else if((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address
402  for(uint8_t i = 0; i < 6; i++)
403  my_bdaddr[i] = hcibuf[6 + i];
405  }
406  }
407  break;
408 
409  case EV_COMMAND_STATUS:
410  if(hcibuf[2]) { // Show status on serial if not OK
411 #ifdef DEBUG_USB_HOST
412  Notify(PSTR("\r\nHCI Command Failed: "), 0x80);
413  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
414 #endif
415  }
416  break;
417 
418  case EV_INQUIRY_COMPLETE:
419  if(inquiry_counter >= 5 && (pairWithWii || pairWithHIDDevice)) {
420  inquiry_counter = 0;
421 #ifdef DEBUG_USB_HOST
422  if(pairWithWii)
423  Notify(PSTR("\r\nCouldn't find Wiimote"), 0x80);
424  else
425  Notify(PSTR("\r\nCouldn't find HID device"), 0x80);
426 #endif
427  connectToWii = false;
428  pairWithWii = false;
429  connectToHIDDevice = false;
430  pairWithHIDDevice = false;
431  hci_state = HCI_SCANNING_STATE;
432  }
433  inquiry_counter++;
434  break;
435 
436  case EV_INQUIRY_RESULT:
437  if(hcibuf[2]) { // Check that there is more than zero responses
438 #ifdef EXTRADEBUG
439  Notify(PSTR("\r\nNumber of responses: "), 0x80);
440  Notify(hcibuf[2], 0x80);
441 #endif
442  for(uint8_t i = 0; i < hcibuf[2]; i++) {
443  uint8_t offset = 8 * hcibuf[2] + 3 * i;
444 
445  for(uint8_t j = 0; j < 3; j++)
446  classOfDevice[j] = hcibuf[j + 4 + offset];
447 
448  if(pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information
449  if(classOfDevice[0] & 0x08) // Check if it's the new Wiimote with motion plus inside that was detected
450  motionPlusInside = true;
451  else
452  motionPlusInside = false;
453 
454  for(uint8_t j = 0; j < 6; j++)
455  disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
456 
458  break;
459  } 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
460 #ifdef DEBUG_USB_HOST
461  if(classOfDevice[0] & 0x80)
462  Notify(PSTR("\r\nMouse found"), 0x80);
463  if(classOfDevice[0] & 0x40)
464  Notify(PSTR("\r\nKeyboard found"), 0x80);
465  if(classOfDevice[0] & 0x08)
466  Notify(PSTR("\r\nGamepad found"), 0x80);
467 #endif
468 
469  for(uint8_t j = 0; j < 6; j++)
470  disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
471 
473  break;
474  }
475 #ifdef EXTRADEBUG
476  else {
477  Notify(PSTR("\r\nClass of device: "), 0x80);
478  D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
479  Notify(PSTR(" "), 0x80);
480  D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
481  Notify(PSTR(" "), 0x80);
482  D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
483  }
484 #endif
485  }
486  }
487  break;
488 
489  case EV_CONNECT_COMPLETE:
491  if(!hcibuf[2]) { // Check if connected OK
492 #ifdef EXTRADEBUG
493  Notify(PSTR("\r\nConnection established"), 0x80);
494 #endif
495  hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // Store the handle for the ACL connection
496  hci_set_flag(HCI_FLAG_CONNECT_COMPLETE); // Set connection complete flag
497  } else {
498  hci_state = HCI_CHECK_DEVICE_SERVICE;
499 #ifdef DEBUG_USB_HOST
500  Notify(PSTR("\r\nConnection Failed: "), 0x80);
501  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
502 #endif
503  }
504  break;
505 
507  if(!hcibuf[2]) { // Check if disconnected OK
508  hci_set_flag(HCI_FLAG_DISCONNECT_COMPLETE); // Set disconnect command complete flag
509  hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); // Clear connection complete flag
510  }
511  break;
512 
514  if(!hcibuf[2]) { // Check if reading is OK
515  for(uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) {
516  remote_name[i] = hcibuf[9 + i];
517  if(remote_name[i] == '\0') // End of string
518  break;
519  }
520  // TODO: Altid sæt '\0' i remote name!
522  }
523  break;
524 
525  case EV_INCOMING_CONNECT:
526  for(uint8_t i = 0; i < 6; i++)
527  disc_bdaddr[i] = hcibuf[i + 2];
528 
529  for(uint8_t i = 0; i < 3; i++)
530  classOfDevice[i] = hcibuf[i + 8];
531 
532  if((classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad
533 #ifdef DEBUG_USB_HOST
534  if(classOfDevice[0] & 0x80)
535  Notify(PSTR("\r\nMouse is connecting"), 0x80);
536  if(classOfDevice[0] & 0x40)
537  Notify(PSTR("\r\nKeyboard is connecting"), 0x80);
538  if(classOfDevice[0] & 0x08)
539  Notify(PSTR("\r\nGamepad is connecting"), 0x80);
540 #endif
541  incomingHIDDevice = true;
542  }
543 
544 #ifdef EXTRADEBUG
545  Notify(PSTR("\r\nClass of device: "), 0x80);
546  D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
547  Notify(PSTR(" "), 0x80);
548  D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
549  Notify(PSTR(" "), 0x80);
550  D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
551 #endif
553  break;
554 
555  case EV_PIN_CODE_REQUEST:
556  if(pairWithWii) {
557 #ifdef DEBUG_USB_HOST
558  Notify(PSTR("\r\nPairing with wiimote"), 0x80);
559 #endif
561  } else if(btdPin != NULL) {
562 #ifdef DEBUG_USB_HOST
563  Notify(PSTR("\r\nBluetooth pin is set too: "), 0x80);
564  NotifyStr(btdPin, 0x80);
565 #endif
567  } else {
568 #ifdef DEBUG_USB_HOST
569  Notify(PSTR("\r\nNo pin was set"), 0x80);
570 #endif
572  }
573  break;
574 
575  case EV_LINK_KEY_REQUEST:
576 #ifdef DEBUG_USB_HOST
577  Notify(PSTR("\r\nReceived Key Request"), 0x80);
578 #endif
580  break;
581 
583  if(pairWithWii && !connectToWii) {
584 #ifdef DEBUG_USB_HOST
585  Notify(PSTR("\r\nPairing successful with Wiimote"), 0x80);
586 #endif
587  connectToWii = true; // Used to indicate to the Wii service, that it should connect to this device
588  } else if(pairWithHIDDevice && !connectToHIDDevice) {
589 #ifdef DEBUG_USB_HOST
590  Notify(PSTR("\r\nPairing successful with HID device"), 0x80);
591 #endif
592  connectToHIDDevice = true; // Used to indicate to the BTHID service, that it should connect to this device
593  }
594  break;
595  /* We will just ignore the following events */
596  case EV_NUM_COMPLETE_PKT:
597  case EV_ROLE_CHANGED:
599  case EV_LOOPBACK_COMMAND:
602  case EV_MAX_SLOTS_CHANGE:
607  break;
608 #ifdef EXTRADEBUG
609  default:
610  if(hcibuf[0] != 0x00) {
611  Notify(PSTR("\r\nUnmanaged HCI Event: "), 0x80);
612  D_PrintHex<uint8_t > (hcibuf[0], 0x80);
613  }
614  break;
615 #endif
616  } // Switch
617  }
618 #ifdef EXTRADEBUG
619  else {
620  Notify(PSTR("\r\nHCI event error: "), 0x80);
621  D_PrintHex<uint8_t > (rcode, 0x80);
622  }
623 #endif
624 }
625 
626 /* Poll Bluetooth and print result */
627 void BTD::HCI_task() {
628  switch(hci_state) {
629  case HCI_INIT_STATE:
630  hci_counter++;
631  if(hci_counter > hci_num_reset_loops) { // wait until we have looped x times to clear any old events
632  hci_reset();
633  hci_state = HCI_RESET_STATE;
634  hci_counter = 0;
635  }
636  break;
637 
638  case HCI_RESET_STATE:
639  hci_counter++;
641  hci_counter = 0;
642 #ifdef DEBUG_USB_HOST
643  Notify(PSTR("\r\nHCI Reset complete"), 0x80);
644 #endif
645  hci_state = HCI_CLASS_STATE;
647  } else if(hci_counter > hci_num_reset_loops) {
648  hci_num_reset_loops *= 10;
649  if(hci_num_reset_loops > 2000)
650  hci_num_reset_loops = 2000;
651 #ifdef DEBUG_USB_HOST
652  Notify(PSTR("\r\nNo response to HCI Reset"), 0x80);
653 #endif
654  hci_state = HCI_INIT_STATE;
655  hci_counter = 0;
656  }
657  break;
658 
659  case HCI_CLASS_STATE:
661 #ifdef DEBUG_USB_HOST
662  Notify(PSTR("\r\nWrite class of device"), 0x80);
663 #endif
664  hci_state = HCI_BDADDR_STATE;
665  hci_read_bdaddr();
666  }
667  break;
668 
669  case HCI_BDADDR_STATE:
671 #ifdef DEBUG_USB_HOST
672  Notify(PSTR("\r\nLocal Bluetooth Address: "), 0x80);
673  for(int8_t i = 5; i > 0; i--) {
674  D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
675  Notify(PSTR(":"), 0x80);
676  }
677  D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
678 #endif
680  hci_state = HCI_LOCAL_VERSION_STATE;
681  }
682  break;
683 
684  case HCI_LOCAL_VERSION_STATE: // The local version is used by the PS3BT class
686  if(btdName != NULL) {
688  hci_state = HCI_SET_NAME_STATE;
689  } else
690  hci_state = HCI_CHECK_DEVICE_SERVICE;
691  }
692  break;
693 
694  case HCI_SET_NAME_STATE:
696 #ifdef DEBUG_USB_HOST
697  Notify(PSTR("\r\nThe name is set to: "), 0x80);
698  NotifyStr(btdName, 0x80);
699 #endif
700  hci_state = HCI_CHECK_DEVICE_SERVICE;
701  }
702  break;
703 
705  if(pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote
706 #ifdef DEBUG_USB_HOST
707  if(pairWithWii)
708  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);
709  else
710  Notify(PSTR("\r\nPlease enable discovery of your device"), 0x80);
711 #endif
712  hci_inquiry();
713  hci_state = HCI_INQUIRY_STATE;
714  } else
715  hci_state = HCI_SCANNING_STATE; // Don't try to connect to a Wiimote
716  break;
717 
718  case HCI_INQUIRY_STATE:
720  hci_inquiry_cancel(); // Stop inquiry
721 #ifdef DEBUG_USB_HOST
722  if(pairWithWii)
723  Notify(PSTR("\r\nWiimote found"), 0x80);
724  else
725  Notify(PSTR("\r\nHID device found"), 0x80);
726 
727  Notify(PSTR("\r\nNow just create the instance like so:"), 0x80);
728  if(pairWithWii)
729  Notify(PSTR("\r\nWII Wii(&Btd);"), 0x80);
730  else
731  Notify(PSTR("\r\nBTHID bthid(&Btd);"), 0x80);
732 
733  Notify(PSTR("\r\nAnd then press any button on the "), 0x80);
734  if(pairWithWii)
735  Notify(PSTR("Wiimote"), 0x80);
736  else
737  Notify(PSTR("device"), 0x80);
738 #endif
739  if(motionPlusInside) {
740  hci_remote_name(); // We need to know the name to distinguish between a Wiimote and a Wii U Pro Controller
741  hci_state = HCI_REMOTE_NAME_STATE;
742  } else
743  hci_state = HCI_CONNECT_DEVICE_STATE;
744  }
745  break;
746 
749 #ifdef DEBUG_USB_HOST
750  if(pairWithWii)
751  Notify(PSTR("\r\nConnecting to Wiimote"), 0x80);
752  else
753  Notify(PSTR("\r\nConnecting to HID device"), 0x80);
754 #endif
755  hci_connect();
756  hci_state = HCI_CONNECTED_DEVICE_STATE;
757  }
758  break;
759 
763 #ifdef DEBUG_USB_HOST
764  if(pairWithWii)
765  Notify(PSTR("\r\nConnected to Wiimote"), 0x80);
766  else
767  Notify(PSTR("\r\nConnected to HID device"), 0x80);
768 #endif
769  hci_authentication_request(); // This will start the pairing with the Wiimote
770  hci_state = HCI_SCANNING_STATE;
771  } else {
772 #ifdef DEBUG_USB_HOST
773  Notify(PSTR("\r\nTrying to connect one more time..."), 0x80);
774 #endif
775  hci_connect(); // Try to connect one more time
776  }
777  }
778  break;
779 
780  case HCI_SCANNING_STATE:
782 #ifdef DEBUG_USB_HOST
783  Notify(PSTR("\r\nWait For Incoming Connection Request"), 0x80);
784 #endif
786  watingForConnection = true;
787  hci_state = HCI_CONNECT_IN_STATE;
788  }
789  break;
790 
793  watingForConnection = false;
794 #ifdef DEBUG_USB_HOST
795  Notify(PSTR("\r\nIncoming Connection Request"), 0x80);
796 #endif
797  hci_remote_name();
798  hci_state = HCI_REMOTE_NAME_STATE;
800  hci_state = HCI_DISCONNECT_STATE;
801  break;
802 
805 #ifdef DEBUG_USB_HOST
806  Notify(PSTR("\r\nRemote Name: "), 0x80);
807  for(uint8_t i = 0; i < strlen(remote_name); i++)
808  Notifyc(remote_name[i], 0x80);
809 #endif
810  if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) {
811  incomingWii = true;
812 #ifdef DEBUG_USB_HOST
813  Notify(PSTR("\r\nWiimote is connecting"), 0x80);
814 #endif
815  if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) {
816 #ifdef DEBUG_USB_HOST
817  Notify(PSTR(" with Motion Plus Inside"), 0x80);
818 #endif
819  motionPlusInside = true;
820  } else if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) {
821 #ifdef DEBUG_USB_HOST
822  Notify(PSTR(" - Wii U Pro Controller"), 0x80);
823 #endif
824  motionPlusInside = true;
825  wiiUProController = true;
826  } else {
827  motionPlusInside = false;
828  wiiUProController = false;
829  }
830  }
831  if(classOfDevice[2] == 0 && classOfDevice[1] == 0x25 && classOfDevice[0] == 0x08 && strncmp((const char*)remote_name, "Wireless Controller", 19) == 0) {
832 #ifdef DEBUG_USB_HOST
833  Notify(PSTR("\r\nPS4 controller is connecting"), 0x80);
834 #endif
835  incomingPS4 = true;
836  }
838  hci_state = HCI_CONNECT_DEVICE_STATE;
839  else {
841  hci_state = HCI_CONNECTED_STATE;
842  }
843  }
844  break;
845 
846  case HCI_CONNECTED_STATE:
848 #ifdef DEBUG_USB_HOST
849  Notify(PSTR("\r\nConnected to Device: "), 0x80);
850  for(int8_t i = 5; i > 0; i--) {
851  D_PrintHex<uint8_t > (disc_bdaddr[i], 0x80);
852  Notify(PSTR(":"), 0x80);
853  }
854  D_PrintHex<uint8_t > (disc_bdaddr[0], 0x80);
855 #endif
856  if(incomingPS4)
857  connectToHIDDevice = true; // We should always connect to the PS4 controller
858 
859  // Clear these flags for a new connection
860  l2capConnectionClaimed = false;
861  sdpConnectionClaimed = false;
862  rfcommConnectionClaimed = false;
863 
864  hci_event_flag = 0;
865  hci_state = HCI_DONE_STATE;
866  }
867  break;
868 
869  case HCI_DONE_STATE:
870  hci_counter++;
871  if(hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started
872  hci_counter = 0;
873  hci_state = HCI_SCANNING_STATE;
874  }
875  break;
876 
879 #ifdef DEBUG_USB_HOST
880  Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80);
881 #endif
882  hci_event_flag = 0; // Clear all flags
883 
884  // Reset all buffers
885  memset(hcibuf, 0, BULK_MAXPKTSIZE);
886  memset(l2capinbuf, 0, BULK_MAXPKTSIZE);
887 
890  incomingPS4 = false;
891 
892  hci_state = HCI_SCANNING_STATE;
893  }
894  break;
895  default:
896  break;
897  }
898 }
899 
900 void BTD::ACL_event_task() {
901  uint16_t length = BULK_MAXPKTSIZE;
902  uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf); // Input on endpoint 2
903 
904  if(!rcode) { // Check for errors
905  if(length > 0) { // Check if any data was read
906  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
907  if(btService[i])
908  btService[i]->ACLData(l2capinbuf);
909  }
910  }
911  }
912 #ifdef EXTRADEBUG
913  else if(rcode != hrNAK) {
914  Notify(PSTR("\r\nACL data in error: "), 0x80);
915  D_PrintHex<uint8_t > (rcode, 0x80);
916  }
917 #endif
918  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
919  if(btService[i])
920  btService[i]->Run();
921 }
922 
923 /************************************************************/
924 /* HCI Commands */
925 
926 /************************************************************/
927 void BTD::HCI_Command(uint8_t* data, uint16_t nbytes) {
929  pUsb->ctrlReq(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, 0x00, 0x00, 0x00, 0x00, nbytes, nbytes, data, NULL);
930 }
931 
933  hci_event_flag = 0; // Clear all the flags
934  hcibuf[0] = 0x03; // HCI OCF = 3
935  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
936  hcibuf[2] = 0x00;
937 
938  HCI_Command(hcibuf, 3);
939 }
940 
943  hcibuf[0] = 0x1A; // HCI OCF = 1A
944  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
945  hcibuf[2] = 0x01; // parameter length = 1
946  if(btdName != NULL)
947  hcibuf[3] = 0x03; // Inquiry Scan enabled. Page Scan enabled.
948  else
949  hcibuf[3] = 0x02; // Inquiry Scan disabled. Page Scan enabled.
950 
951  HCI_Command(hcibuf, 4);
952 }
953 
955  hcibuf[0] = 0x1A; // HCI OCF = 1A
956  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
957  hcibuf[2] = 0x01; // parameter length = 1
958  hcibuf[3] = 0x00; // Inquiry Scan disabled. Page Scan disabled.
959 
960  HCI_Command(hcibuf, 4);
961 }
962 
965  hcibuf[0] = 0x09; // HCI OCF = 9
966  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
967  hcibuf[2] = 0x00;
968 
969  HCI_Command(hcibuf, 3);
970 }
971 
974  hcibuf[0] = 0x01; // HCI OCF = 1
975  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
976  hcibuf[2] = 0x00;
977 
978  HCI_Command(hcibuf, 3);
979 }
980 
983  hcibuf[0] = 0x09; // HCI OCF = 9
984  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
985  hcibuf[2] = 0x07; // parameter length 7
986  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
987  hcibuf[4] = disc_bdaddr[1];
988  hcibuf[5] = disc_bdaddr[2];
989  hcibuf[6] = disc_bdaddr[3];
990  hcibuf[7] = disc_bdaddr[4];
991  hcibuf[8] = disc_bdaddr[5];
992  hcibuf[9] = 0x00; // Switch role to master
993 
994  HCI_Command(hcibuf, 10);
995 }
996 
999  hcibuf[0] = 0x19; // HCI OCF = 19
1000  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1001  hcibuf[2] = 0x0A; // parameter length = 10
1002  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1003  hcibuf[4] = disc_bdaddr[1];
1004  hcibuf[5] = disc_bdaddr[2];
1005  hcibuf[6] = disc_bdaddr[3];
1006  hcibuf[7] = disc_bdaddr[4];
1007  hcibuf[8] = disc_bdaddr[5];
1008  hcibuf[9] = 0x01; // Page Scan Repetition Mode
1009  hcibuf[10] = 0x00; // Reserved
1010  hcibuf[11] = 0x00; // Clock offset - low byte
1011  hcibuf[12] = 0x00; // Clock offset - high byte
1012 
1013  HCI_Command(hcibuf, 13);
1014 }
1015 
1016 void BTD::hci_set_local_name(const char* name) {
1017  hcibuf[0] = 0x13; // HCI OCF = 13
1018  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1019  hcibuf[2] = strlen(name) + 1; // parameter length = the length of the string + end byte
1020  uint8_t i;
1021  for(i = 0; i < strlen(name); i++)
1022  hcibuf[i + 3] = name[i];
1023  hcibuf[i + 3] = 0x00; // End of string
1024 
1025  HCI_Command(hcibuf, 4 + strlen(name));
1026 }
1027 
1030  hcibuf[0] = 0x01;
1031  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1032  hcibuf[2] = 0x05; // Parameter Total Length = 5
1033  hcibuf[3] = 0x33; // LAP: Genera/Unlimited Inquiry Access Code (GIAC = 0x9E8B33) - see https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
1034  hcibuf[4] = 0x8B;
1035  hcibuf[5] = 0x9E;
1036  hcibuf[6] = 0x30; // Inquiry time = 61.44 sec (maximum)
1037  hcibuf[7] = 0x0A; // 10 number of responses
1038 
1039  HCI_Command(hcibuf, 8);
1040 }
1041 
1043  hcibuf[0] = 0x02;
1044  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1045  hcibuf[2] = 0x00; // Parameter Total Length = 0
1046 
1047  HCI_Command(hcibuf, 3);
1048 }
1049 
1051  hci_connect(disc_bdaddr); // Use last discovered device
1052 }
1053 
1054 void BTD::hci_connect(uint8_t *bdaddr) {
1056  hcibuf[0] = 0x05;
1057  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1058  hcibuf[2] = 0x0D; // parameter Total Length = 13
1059  hcibuf[3] = bdaddr[0]; // 6 octet bdaddr (LSB)
1060  hcibuf[4] = bdaddr[1];
1061  hcibuf[5] = bdaddr[2];
1062  hcibuf[6] = bdaddr[3];
1063  hcibuf[7] = bdaddr[4];
1064  hcibuf[8] = bdaddr[5];
1065  hcibuf[9] = 0x18; // DM1 or DH1 may be used
1066  hcibuf[10] = 0xCC; // DM3, DH3, DM5, DH5 may be used
1067  hcibuf[11] = 0x01; // Page repetition mode R1
1068  hcibuf[12] = 0x00; // Reserved
1069  hcibuf[13] = 0x00; // Clock offset
1070  hcibuf[14] = 0x00; // Invalid clock offset
1071  hcibuf[15] = 0x00; // Do not allow role switch
1072 
1073  HCI_Command(hcibuf, 16);
1074 }
1075 
1077  hcibuf[0] = 0x0D; // HCI OCF = 0D
1078  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1079  hcibuf[2] = 0x17; // parameter length 23
1080  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1081  hcibuf[4] = disc_bdaddr[1];
1082  hcibuf[5] = disc_bdaddr[2];
1083  hcibuf[6] = disc_bdaddr[3];
1084  hcibuf[7] = disc_bdaddr[4];
1085  hcibuf[8] = disc_bdaddr[5];
1086  if(pairWithWii) {
1087  hcibuf[9] = 6; // Pin length is the length of the Bluetooth address
1088  if(wiiUProController) {
1089 #ifdef DEBUG_USB_HOST
1090  Notify(PSTR("\r\nParing with Wii U Pro Controller"), 0x80);
1091 #endif
1092  for(uint8_t i = 0; i < 6; i++)
1093  hcibuf[10 + i] = my_bdaddr[i]; // The pin is the Bluetooth dongles Bluetooth address backwards
1094  } else {
1095  for(uint8_t i = 0; i < 6; i++)
1096  hcibuf[10 + i] = disc_bdaddr[i]; // The pin is the Wiimote's Bluetooth address backwards
1097  }
1098  for(uint8_t i = 16; i < 26; i++)
1099  hcibuf[i] = 0x00; // The rest should be 0
1100  } else {
1101  hcibuf[9] = strlen(btdPin); // Length of pin
1102  uint8_t i;
1103  for(i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16
1104  hcibuf[i + 10] = btdPin[i];
1105  for(; i < 16; i++)
1106  hcibuf[i + 10] = 0x00; // The rest should be 0
1107  }
1108 
1109  HCI_Command(hcibuf, 26);
1110 }
1111 
1113  hcibuf[0] = 0x0E; // HCI OCF = 0E
1114  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1115  hcibuf[2] = 0x06; // parameter length 6
1116  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1117  hcibuf[4] = disc_bdaddr[1];
1118  hcibuf[5] = disc_bdaddr[2];
1119  hcibuf[6] = disc_bdaddr[3];
1120  hcibuf[7] = disc_bdaddr[4];
1121  hcibuf[8] = disc_bdaddr[5];
1122 
1123  HCI_Command(hcibuf, 9);
1124 }
1125 
1127  hcibuf[0] = 0x0C; // HCI OCF = 0C
1128  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1129  hcibuf[2] = 0x06; // parameter length 6
1130  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1131  hcibuf[4] = disc_bdaddr[1];
1132  hcibuf[5] = disc_bdaddr[2];
1133  hcibuf[6] = disc_bdaddr[3];
1134  hcibuf[7] = disc_bdaddr[4];
1135  hcibuf[8] = disc_bdaddr[5];
1136 
1137  HCI_Command(hcibuf, 9);
1138 }
1139 
1141  hcibuf[0] = 0x11; // HCI OCF = 11
1142  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1143  hcibuf[2] = 0x02; // parameter length = 2
1144  hcibuf[3] = (uint8_t)(hci_handle & 0xFF); //connection handle - low byte
1145  hcibuf[4] = (uint8_t)((hci_handle >> 8) & 0x0F); //connection handle - high byte
1146 
1147  HCI_Command(hcibuf, 5);
1148 }
1149 
1150 void BTD::hci_disconnect(uint16_t handle) { // This is called by the different services
1152  hcibuf[0] = 0x06; // HCI OCF = 6
1153  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1154  hcibuf[2] = 0x03; // parameter length = 3
1155  hcibuf[3] = (uint8_t)(handle & 0xFF); //connection handle - low byte
1156  hcibuf[4] = (uint8_t)((handle >> 8) & 0x0F); //connection handle - high byte
1157  hcibuf[5] = 0x13; // reason
1158 
1159  HCI_Command(hcibuf, 6);
1160 }
1161 
1162 void BTD::hci_write_class_of_device() { // See http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
1163  hcibuf[0] = 0x24; // HCI OCF = 24
1164  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1165  hcibuf[2] = 0x03; // parameter length = 3
1166  hcibuf[3] = 0x04; // Robot
1167  hcibuf[4] = 0x08; // Toy
1168  hcibuf[5] = 0x00;
1169 
1170  HCI_Command(hcibuf, 6);
1171 }
1172 /*******************************************************************
1173  * *
1174  * HCI ACL Data Packet *
1175  * *
1176  * buf[0] buf[1] buf[2] buf[3]
1177  * 0 4 8 11 12 16 24 31 MSB
1178  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1179  * | HCI Handle |PB |BC | Data Total Length | HCI ACL Data Packet
1180  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1181  *
1182  * buf[4] buf[5] buf[6] buf[7]
1183  * 0 8 16 31 MSB
1184  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1185  * | Length | Channel ID | Basic L2CAP header
1186  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1187  *
1188  * buf[8] buf[9] buf[10] buf[11]
1189  * 0 8 16 31 MSB
1190  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1191  * | Code | Identifier | Length | Control frame (C-frame)
1192  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-. (signaling packet format)
1193  */
1194 /************************************************************/
1195 /* L2CAP Commands */
1196 
1197 /************************************************************/
1198 void BTD::L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh) {
1199  uint8_t buf[8 + nbytes];
1200  buf[0] = (uint8_t)(handle & 0xff); // HCI handle with PB,BC flag
1201  buf[1] = (uint8_t)(((handle >> 8) & 0x0f) | 0x20);
1202  buf[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
1203  buf[3] = (uint8_t)((4 + nbytes) >> 8);
1204  buf[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
1205  buf[5] = (uint8_t)(nbytes >> 8);
1206  buf[6] = channelLow;
1207  buf[7] = channelHigh;
1208 
1209  for(uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame
1210  buf[8 + i] = data[i];
1211 
1212  uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ BTD_DATAOUT_PIPE ].epAddr, (8 + nbytes), buf);
1213  if(rcode) {
1214  delay(100); // This small delay prevents it from overflowing if it fails
1215 #ifdef DEBUG_USB_HOST
1216  Notify(PSTR("\r\nError sending L2CAP message: 0x"), 0x80);
1217  D_PrintHex<uint8_t > (rcode, 0x80);
1218  Notify(PSTR(" - Channel ID: "), 0x80);
1219  D_PrintHex<uint8_t > (channelHigh, 0x80);
1220  Notify(PSTR(" "), 0x80);
1221  D_PrintHex<uint8_t > (channelLow, 0x80);
1222 #endif
1223  }
1224 }
1225 
1226 void BTD::l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm) {
1227  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
1228  l2capoutbuf[1] = rxid; // Identifier
1229  l2capoutbuf[2] = 0x04; // Length
1230  l2capoutbuf[3] = 0x00;
1231  l2capoutbuf[4] = (uint8_t)(psm & 0xff); // PSM
1232  l2capoutbuf[5] = (uint8_t)(psm >> 8);
1233  l2capoutbuf[6] = scid[0]; // Source CID
1234  l2capoutbuf[7] = scid[1];
1235 
1236  L2CAP_Command(handle, l2capoutbuf, 8);
1237 }
1238 
1239 void BTD::l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result) {
1240  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
1241  l2capoutbuf[1] = rxid; // Identifier
1242  l2capoutbuf[2] = 0x08; // Length
1243  l2capoutbuf[3] = 0x00;
1244  l2capoutbuf[4] = dcid[0]; // Destination CID
1245  l2capoutbuf[5] = dcid[1];
1246  l2capoutbuf[6] = scid[0]; // Source CID
1247  l2capoutbuf[7] = scid[1];
1248  l2capoutbuf[8] = result; // Result: Pending or Success
1249  l2capoutbuf[9] = 0x00;
1250  l2capoutbuf[10] = 0x00; // No further information
1251  l2capoutbuf[11] = 0x00;
1252 
1253  L2CAP_Command(handle, l2capoutbuf, 12);
1254 }
1255 
1256 void BTD::l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid) {
1257  l2capoutbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
1258  l2capoutbuf[1] = rxid; // Identifier
1259  l2capoutbuf[2] = 0x08; // Length
1260  l2capoutbuf[3] = 0x00;
1261  l2capoutbuf[4] = dcid[0]; // Destination CID
1262  l2capoutbuf[5] = dcid[1];
1263  l2capoutbuf[6] = 0x00; // Flags
1264  l2capoutbuf[7] = 0x00;
1265  l2capoutbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
1266  l2capoutbuf[9] = 0x02; // Config Opt: length
1267  l2capoutbuf[10] = 0xFF; // MTU
1268  l2capoutbuf[11] = 0xFF;
1269 
1270  L2CAP_Command(handle, l2capoutbuf, 12);
1271 }
1272 
1273 void BTD::l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid) {
1274  l2capoutbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
1275  l2capoutbuf[1] = rxid; // Identifier
1276  l2capoutbuf[2] = 0x0A; // Length
1277  l2capoutbuf[3] = 0x00;
1278  l2capoutbuf[4] = scid[0]; // Source CID
1279  l2capoutbuf[5] = scid[1];
1280  l2capoutbuf[6] = 0x00; // Flag
1281  l2capoutbuf[7] = 0x00;
1282  l2capoutbuf[8] = 0x00; // Result
1283  l2capoutbuf[9] = 0x00;
1284  l2capoutbuf[10] = 0x01; // Config
1285  l2capoutbuf[11] = 0x02;
1286  l2capoutbuf[12] = 0xA0;
1287  l2capoutbuf[13] = 0x02;
1288 
1289  L2CAP_Command(handle, l2capoutbuf, 14);
1290 }
1291 
1292 void BTD::l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1293  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_REQUEST; // Code
1294  l2capoutbuf[1] = rxid; // Identifier
1295  l2capoutbuf[2] = 0x04; // Length
1296  l2capoutbuf[3] = 0x00;
1297  l2capoutbuf[4] = dcid[0];
1298  l2capoutbuf[5] = dcid[1];
1299  l2capoutbuf[6] = scid[0];
1300  l2capoutbuf[7] = scid[1];
1301 
1302  L2CAP_Command(handle, l2capoutbuf, 8);
1303 }
1304 
1305 void BTD::l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1306  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_RESPONSE; // Code
1307  l2capoutbuf[1] = rxid; // Identifier
1308  l2capoutbuf[2] = 0x04; // Length
1309  l2capoutbuf[3] = 0x00;
1310  l2capoutbuf[4] = dcid[0];
1311  l2capoutbuf[5] = dcid[1];
1312  l2capoutbuf[6] = scid[0];
1313  l2capoutbuf[7] = scid[1];
1314 
1315  L2CAP_Command(handle, l2capoutbuf, 8);
1316 }
1317 
1318 void BTD::l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh) {
1319  l2capoutbuf[0] = L2CAP_CMD_INFORMATION_RESPONSE; // Code
1320  l2capoutbuf[1] = rxid; // Identifier
1321  l2capoutbuf[2] = 0x08; // Length
1322  l2capoutbuf[3] = 0x00;
1323  l2capoutbuf[4] = infoTypeLow;
1324  l2capoutbuf[5] = infoTypeHigh;
1325  l2capoutbuf[6] = 0x00; // Result = success
1326  l2capoutbuf[7] = 0x00; // Result = success
1327  l2capoutbuf[8] = 0x00;
1328  l2capoutbuf[9] = 0x00;
1329  l2capoutbuf[10] = 0x00;
1330  l2capoutbuf[11] = 0x00;
1331 
1332  L2CAP_Command(handle, l2capoutbuf, 12);
1333 }
1334 
1335 /* PS3 Commands - only set Bluetooth address is implemented in this library */
1336 void BTD::setBdaddr(uint8_t* bdaddr) {
1337  /* Set the internal Bluetooth address */
1338  uint8_t buf[8];
1339  buf[0] = 0x01;
1340  buf[1] = 0x00;
1341 
1342  for(uint8_t i = 0; i < 6; i++)
1343  buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first
1344 
1345  // 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
1346  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
1347 }
1348 
1349 void BTD::setMoveBdaddr(uint8_t* bdaddr) {
1350  /* Set the internal Bluetooth address */
1351  uint8_t buf[11];
1352  buf[0] = 0x05;
1353  buf[7] = 0x10;
1354  buf[8] = 0x01;
1355  buf[9] = 0x02;
1356  buf[10] = 0x12;
1357 
1358  for(uint8_t i = 0; i < 6; i++)
1359  buf[i + 1] = bdaddr[i];
1360 
1361  // 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
1362  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
1363 }
static const uint8_t BTD_DATAOUT_PIPE
Definition: BTD.h:521
uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t *dataptr)
Definition: Usb.cpp:769
bool incomingWii
Definition: BTD.h:471
void hci_connect()
Definition: BTD.cpp:1050
uint8_t bNumEP
Definition: BTD.h:510
EpInfo * epinfo
Definition: address.h:76
const char * btdName
Definition: BTD.h:444
void hci_reset()
Definition: BTD.cpp:932
void l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t *dcid, uint8_t *scid, uint8_t result)
Definition: BTD.cpp:1239
#define HCI_SCANNING_STATE
Definition: BTD.h:52
bool lowspeed
Definition: address.h:79
#define USB_ERROR_EPINFO_IS_NULL
Definition: UsbCore.h:83
void l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t *scid, uint16_t psm)
Definition: BTD.cpp:1226
#define EV_COMMAND_STATUS
Definition: BTD.h:96
#define EV_REMOTE_NAME_COMPLETE
Definition: BTD.h:83
uint8_t bmNakPower
Definition: address.h:42
bool sdpConnectionClaimed
Definition: BTD.h:439
#define bmREQ_HCI_OUT
Definition: BTD.h:37
void l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t *dcid, uint8_t *scid)
Definition: BTD.cpp:1292
bool rfcommConnectionClaimed
Definition: BTD.h:441
uint8_t hci_version
Definition: BTD.h:461
#define EV_INQUIRY_COMPLETE
Definition: BTD.h:77
void hci_inquiry()
Definition: BTD.cpp:1028
static const uint8_t BTD_EVENT_PIPE
Definition: BTD.h:517
#define PS3MOVE_PID
Definition: BTD.h:28
bool pairWithWii
Definition: BTD.h:473
uint8_t bMaxPacketSize0
Definition: usb_ch9.h:105
#define HID_REQUEST_SET_REPORT
Definition: hid.h:72
void hci_write_scan_disable()
Definition: BTD.cpp:954
#define NotifyFail(...)
Definition: message.h:55
#define HCI_SET_NAME_STATE
Definition: BTD.h:45
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:89
#define HCI_DONE_STATE
Definition: BTD.h:57
#define BTD_NUM_SERVICES
Definition: BTD.h:188
#define EV_DATA_BUFFER_OVERFLOW
Definition: BTD.h:91
#define HCI_DISCONNECT_STATE
Definition: BTD.h:58
#define HCI_FLAG_CONNECT_COMPLETE
Definition: BTD.h:62
#define EV_PIN_CODE_REQUEST
Definition: BTD.h:88
uint8_t setConf(uint8_t addr, uint8_t ep, uint8_t conf_value)
Definition: Usb.cpp:808
const char * btdPin
Definition: BTD.h:446
bool motionPlusInside
Definition: BTD.h:475
#define EV_AUTHENTICATION_COMPLETE
Definition: BTD.h:82
void hci_remote_name()
Definition: BTD.cpp:997
#define bmREQ_HID_OUT
Definition: hid.h:63
#define HCI_FLAG_CONNECT_EVENT
Definition: BTD.h:69
#define HCI_FLAG_DISCONNECT_COMPLETE
Definition: BTD.h:63
#define HCI_REMOTE_NAME_STATE
Definition: BTD.h:54
#define USB_ERROR_FailGetDevDescr
Definition: UsbCore.h:89
#define HCI_FLAG_CMD_COMPLETE
Definition: BTD.h:61
#define PS3_VID
Definition: BTD.h:25
#define NotifyFailGetDevDescr(...)
Definition: message.h:50
BTD(USB *p)
Definition: BTD.cpp:27
char remote_name[30]
Definition: BTD.h:455
#define hrJERR
Definition: max3421e.h:220
uint8_t setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo *eprecord_ptr)
Definition: Usb.cpp:64
virtual void Reset()=0
#define EV_MAX_SLOTS_CHANGE
Definition: BTD.h:92
static const uint8_t BTD_DATAIN_PIPE
Definition: BTD.h:519
void hci_set_local_name(const char *name)
Definition: BTD.cpp:1016
#define EV_QOS_SETUP_COMPLETE
Definition: BTD.h:94
void hci_write_scan_enable()
Definition: BTD.cpp:941
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:1305
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:435
#define HCI_BDADDR_STATE
Definition: BTD.h:43
#define HCI_CONNECT_DEVICE_STATE
Definition: BTD.h:49
#define Notify(...)
Definition: message.h:44
bool connectToHIDDevice
Definition: BTD.h:483
uint8_t setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr)
Definition: Usb.cpp:799
uint8_t bAddress
Definition: BTD.h:503
#define NotifyFailGetConfDescr(...)
Definition: message.h:52
uint8_t epAddr
Definition: address.h:33
bool incomingHIDDevice
Definition: BTD.h:487
#define NotifyFailUnknownDevice(...)
Definition: message.h:54
bool pairWithHIDDevice
Definition: BTD.h:489
uint32_t qNextPollTime
Definition: BTD.h:512
#define USB_NAK_MAX_POWER
Definition: address.h:27
#define EV_CONNECT_COMPLETE
Definition: BTD.h:79
void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR *ep_ptr)
Definition: BTD.cpp:346
#define EV_DISCONNECT_COMPLETE
Definition: BTD.h:81
#define HCI_FLAG_READ_BDADDR
Definition: BTD.h:66
#define IOGEAR_GBU521_PID
Definition: BTD.h:31
bool connectToWii
Definition: BTD.h:467
uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed)
Definition: BTD.cpp:48
#define HCI_LOCAL_VERSION_STATE
Definition: BTD.h:44
virtual void disconnect()=0
bool wiiUProController
Definition: BTD.h:477
uint16_t hci_handle
Definition: BTD.h:451
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:1150
#define HCI_RESET_STATE
Definition: BTD.h:41
uint8_t outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *data)
Definition: Usb.cpp:292
#define hrNAK
Definition: max3421e.h:211
void hci_read_bdaddr()
Definition: BTD.cpp:963
void hci_inquiry_cancel()
Definition: BTD.cpp:1042
#define L2CAP_CMD_INFORMATION_RESPONSE
Definition: BTD.h:171
uint16_t wMaxPacketSize
Definition: usb_ch9.h:146
virtual void Run()=0
uint8_t my_bdaddr[6]
Definition: BTD.h:449
#define EV_INCOMING_CONNECT
Definition: BTD.h:80
#define HCI_CONNECT_IN_STATE
Definition: BTD.h:53
#define HCI_INQUIRY_STATE
Definition: BTD.h:48
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:55
#define EV_INQUIRY_RESULT
Definition: BTD.h:78
#define USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE
Definition: UsbCore.h:85
#define L2CAP_CMD_CONFIG_REQUEST
Definition: BTD.h:166
#define PSTR(str)
uint8_t Poll()
Definition: BTD.cpp:371
#define L2CAP_CMD_DISCONNECT_REQUEST
Definition: BTD.h:168
static const uint8_t BTD_CONTROL_PIPE
Definition: BTD.h:515
#define BULK_MAXPKTSIZE
Definition: BTD.h:34
void disconnect()
Definition: BTD.cpp:383
#define HCI_FLAG_READ_VERSION
Definition: BTD.h:67
uint8_t disc_bdaddr[6]
Definition: BTD.h:453
bool l2capConnectionClaimed
Definition: BTD.h:437
#define USB_NAK_NOWAIT
Definition: address.h:29
#define HCI_FLAG_INCOMING_REQUEST
Definition: BTD.h:65
#define EV_NUM_COMPLETE_PKT
Definition: BTD.h:87
#define USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL
Definition: UsbCore.h:82
EpInfo epInfo[BTD_MAX_ENDPOINTS]
Definition: BTD.h:505
#define IOGEAR_GBU521_VID
Definition: BTD.h:30
#define PS3_PID
Definition: BTD.h:26
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:187
#define PS3NAVIGATION_PID
Definition: BTD.h:27
#define USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED
Definition: UsbCore.h:77
#define L2CAP_CMD_DISCONNECT_RESPONSE
Definition: BTD.h:169
#define EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE
Definition: BTD.h:93
#define EV_COMMAND_COMPLETE
Definition: BTD.h:95
void l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh)
Definition: BTD.cpp:1318
uint16_t idProduct
Definition: usb_ch9.h:107
#define L2CAP_CMD_CONNECTION_RESPONSE
Definition: BTD.h:165
#define L2CAP_CMD_CONFIG_RESPONSE
Definition: BTD.h:167
#define hci_set_flag(flag)
Definition: BTD.h:73
void hci_write_class_of_device()
Definition: BTD.cpp:1162
#define HCI_CONNECTED_DEVICE_STATE
Definition: BTD.h:50
#define HCI_INIT_STATE
Definition: BTD.h:40
void hci_pin_code_negative_request_reply()
Definition: BTD.cpp:1112
#define EV_CHANGE_CONNECTION_LINK
Definition: BTD.h:85
virtual void ACLData(uint8_t *ACLData)=0
uint8_t bNumConfigurations
Definition: usb_ch9.h:112
#define USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL
Definition: UsbCore.h:80
#define hci_check_flag(flag)
Definition: BTD.h:72
#define EV_ROLE_CHANGED
Definition: BTD.h:86
uint8_t maxPktSize
Definition: address.h:34
AddressPool & GetAddressPool()
Definition: UsbCore.h:213
#define HCI_CHECK_DEVICE_SERVICE
Definition: BTD.h:46
Definition: UsbCore.h:197
uint8_t bConfNum
Definition: BTD.h:508
void hci_link_key_request_negative_reply()
Definition: BTD.cpp:1126
#define EV_LOOPBACK_COMMAND
Definition: BTD.h:97
void L2CAP_Command(uint16_t handle, uint8_t *data, uint8_t nbytes, uint8_t channelLow=0x01, uint8_t channelHigh=0x00)
Definition: BTD.cpp:1198
#define EV_LINK_KEY_NOTIFICATION
Definition: BTD.h:90
void l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t *scid)
Definition: BTD.cpp:1273
void l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t *dcid)
Definition: BTD.cpp:1256
void hci_pin_code_request_reply()
Definition: BTD.cpp:1076
#define L2CAP_CMD_CONNECTION_REQUEST
Definition: BTD.h:164
uint8_t RegisterDeviceClass(USBDeviceConfig *pdev)
Definition: UsbCore.h:217
#define EV_ENCRYPTION_CHANGE
Definition: BTD.h:84
#define NotifyFailSetConfDescr(...)
Definition: message.h:53
#define hci_clear_flag(flag)
Definition: BTD.h:74
USB * pUsb
Definition: BTD.h:497
#define NotifyStr(...)
Definition: message.h:45
void hci_authentication_request()
Definition: BTD.cpp:1140
void hci_read_local_version_information()
Definition: BTD.cpp:972
#define HCI_FLAG_REMOTE_NAME_COMPLETE
Definition: BTD.h:64
void hci_accept_connection()
Definition: BTD.cpp:981
#define EV_PAGE_SCAN_REP_MODE
Definition: BTD.h:98
#define HCI_FLAG_DEVICE_FOUND
Definition: BTD.h:68
#define HCI_CLASS_STATE
Definition: BTD.h:42
uint8_t getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *dataptr)
defined(USB_METHODS_INLINE)
Definition: Usb.cpp:764
#define NotifyFailSetDevTblEntry(...)
Definition: message.h:51
#define USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET
Definition: UsbCore.h:88
void HCI_Command(uint8_t *data, uint16_t nbytes)
Definition: BTD.cpp:927