diff --git a/_b_t_d_8cpp_source.html b/_b_t_d_8cpp_source.html index 63fd5ff5..48b714dd 100644 --- a/_b_t_d_8cpp_source.html +++ b/_b_t_d_8cpp_source.html @@ -63,7 +63,7 @@ $(function() {
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 useSimplePairing(false),
33 pUsb(p), // Pointer to USB class instance - mandatory
34 bAddress(0), // Device address - mandatory
35 bNumEP(1), // If config descriptor needs to be parsed
36 qNextPollTime(0), // Reset NextPollTime
37 pollInterval(0),
38 simple_pairing_supported(false),
39 bPollEnable(false) // Don't start polling before dongle is connected
40 {
41  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
42  btService[i] = NULL;
43 
44  Initialize(); // Set all variables, endpoint structs etc. to default values
45 
46  if(pUsb) // Register in USB subsystem
47  pUsb->RegisterDeviceClass(this); // Set devConfig[] entry
48 }
49 
50 uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
51  const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
52  uint8_t buf[constBufSize];
53  USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
54  uint8_t rcode;
55  UsbDevice *p = NULL;
56  EpInfo *oldep_ptr = NULL;
57 
58  Initialize(); // Set all variables, endpoint structs etc. to default values
59 
60  AddressPool &addrPool = pUsb->GetAddressPool(); // Get memory address of USB device address pool
61 #ifdef EXTRADEBUG
62  Notify(PSTR("\r\nBTD ConfigureDevice"), 0x80);
63 #endif
64 
65  if(bAddress) { // Check if address has already been assigned to an instance
66 #ifdef DEBUG_USB_HOST
67  Notify(PSTR("\r\nAddress in use"), 0x80);
68 #endif
70  }
71 
72  p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned
73  if(!p) {
74 #ifdef DEBUG_USB_HOST
75  Notify(PSTR("\r\nAddress not found"), 0x80);
76 #endif
78  }
79 
80  if(!p->epinfo) {
81 #ifdef DEBUG_USB_HOST
82  Notify(PSTR("\r\nepinfo is null"), 0x80);
83 #endif
85  }
86 
87  oldep_ptr = p->epinfo; // Save old pointer to EP_RECORD of address 0
88  p->epinfo = epInfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
89  p->lowspeed = lowspeed;
90  rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
91 
92  p->epinfo = oldep_ptr; // Restore p->epinfo
93 
94  if(rcode)
95  goto FailGetDevDescr;
96 
97  bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class
98 
99  if(!bAddress) {
100 #ifdef DEBUG_USB_HOST
101  Notify(PSTR("\r\nOut of address space"), 0x80);
102 #endif
104  }
105 
106  if (udd->bDeviceClass == 0x09) // Some dongles have an USB hub inside
107  goto FailHub;
108 
109  epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor
110  epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory
111 
112  VID = udd->idVendor;
113  PID = udd->idProduct;
114 
116 
117 FailHub:
118 #ifdef DEBUG_USB_HOST
119  Notify(PSTR("\r\nPlease create a hub instance in your code: \"USBHub Hub1(&Usb);\""), 0x80);
120 #endif
121  pUsb->setAddr(bAddress, 0, 0); // Reset address
123  Release();
124  return rcode;
125 
126 FailGetDevDescr:
127 #ifdef DEBUG_USB_HOST
128  NotifyFailGetDevDescr(rcode);
129 #endif
130  if(rcode != hrJERR)
132  Release();
133  return rcode;
134 };
135 
136 uint8_t BTD::Init(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed) {
137  uint8_t rcode;
138  uint8_t num_of_conf = epInfo[1].epAddr; // Number of configurations
139  epInfo[1].epAddr = 0;
140 
141  AddressPool &addrPool = pUsb->GetAddressPool();
142 #ifdef EXTRADEBUG
143  Notify(PSTR("\r\nBTD Init"), 0x80);
144 #endif
145  UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
146 
147  if(!p) {
148 #ifdef DEBUG_USB_HOST
149  Notify(PSTR("\r\nAddress not found"), 0x80);
150 #endif
152  }
153 
154  delay(300); // Assign new address to the device
155 
156  rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device
157  if(rcode) {
158 #ifdef DEBUG_USB_HOST
159  Notify(PSTR("\r\nsetAddr: "), 0x80);
160  D_PrintHex<uint8_t > (rcode, 0x80);
161 #endif
162  p->lowspeed = false;
163  goto Fail;
164  }
165 #ifdef EXTRADEBUG
166  Notify(PSTR("\r\nAddr: "), 0x80);
167  D_PrintHex<uint8_t > (bAddress, 0x80);
168 #endif
169 
170  p->lowspeed = false;
171 
172  p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
173  if(!p) {
174 #ifdef DEBUG_USB_HOST
175  Notify(PSTR("\r\nAddress not found"), 0x80);
176 #endif
178  }
179 
180  p->lowspeed = lowspeed;
181 
182  rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known
183  if(rcode)
184  goto FailSetDevTblEntry;
185 
186  if(VID == PS3_VID && (PID == PS3_PID || PID == PS3NAVIGATION_PID || PID == PS3MOVE_PID)) {
187  delay(100);
188  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
189  if(rcode)
190  goto FailSetConfDescr;
191 
192 #ifdef DEBUG_USB_HOST
193  if(PID == PS3_PID || PID == PS3NAVIGATION_PID) {
194  if(PID == PS3_PID)
195  Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80);
196  else // It must be a navigation controller
197  Notify(PSTR("\r\nNavigation Controller Connected"), 0x80);
198  } else // It must be a Motion controller
199  Notify(PSTR("\r\nMotion Controller Connected"), 0x80);
200 #endif
201 
202  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) {
203 #ifdef DEBUG_USB_HOST
204  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);
205 #endif
206  } else {
207  if(PID == PS3_PID || PID == PS3NAVIGATION_PID)
208  setBdaddr(my_bdaddr); // Set internal Bluetooth address
209  else
210  setMoveBdaddr(my_bdaddr); // Set internal Bluetooth address
211 #ifdef DEBUG_USB_HOST
212  Notify(PSTR("\r\nBluetooth Address was set to: "), 0x80);
213  for(int8_t i = 5; i > 0; i--) {
214  D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
215  Notify(PSTR(":"), 0x80);
216  }
217  D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
218 #endif
219  }
220 
221  pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, 0); // Reset configuration value
222  pUsb->setAddr(bAddress, 0, 0); // Reset address
223  Release(); // Release device
225  } else {
226  // Check if attached device is a Bluetooth dongle and fill endpoint data structure
227  // First interface in the configuration must have Bluetooth assigned Class/Subclass/Protocol
228  // And 3 endpoints - interrupt-IN, bulk-IN, bulk-OUT, not necessarily in this order
229  for(uint8_t i = 0; i < num_of_conf; i++) {
230  if((VID == IOGEAR_GBU521_VID && PID == IOGEAR_GBU521_PID) || (VID == BELKIN_F8T065BF_VID && PID == BELKIN_F8T065BF_PID)) {
231  ConfigDescParser<USB_CLASS_VENDOR_SPECIFIC, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this); // Workaround issue with some dongles
232  rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
233  } else {
234  ConfigDescParser<USB_CLASS_WIRELESS_CTRL, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this); // Set class id according to the specification
235  rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
236  }
237  if(rcode) // Check error code
238  goto FailGetConfDescr;
239  if(bNumEP >= BTD_MAX_ENDPOINTS) // All endpoints extracted
240  break;
241  }
242 
244  goto FailUnknownDevice;
245 
246  // Assign epInfo to epinfo pointer - this time all 3 endpoins
247  rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
248  if(rcode)
249  goto FailSetDevTblEntry;
250 
251  // Set Configuration Value
252  rcode = pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bConfNum);
253  if(rcode)
254  goto FailSetConfDescr;
255 
256  hci_num_reset_loops = 100; // only loop 100 times before trying to send the hci reset command
257  hci_counter = 0;
258  hci_state = HCI_INIT_STATE;
259  waitingForConnection = false;
260  bPollEnable = true;
261 
262 #ifdef DEBUG_USB_HOST
263  Notify(PSTR("\r\nBluetooth Dongle Initialized"), 0x80);
264 #endif
265  }
266  return 0; // Successful configuration
267 
268  /* Diagnostic messages */
269 FailSetDevTblEntry:
270 #ifdef DEBUG_USB_HOST
272  goto Fail;
273 #endif
274 
275 FailGetConfDescr:
276 #ifdef DEBUG_USB_HOST
278  goto Fail;
279 #endif
280 
281 FailSetConfDescr:
282 #ifdef DEBUG_USB_HOST
284 #endif
285  goto Fail;
286 
287 FailUnknownDevice:
288 #ifdef DEBUG_USB_HOST
289  NotifyFailUnknownDevice(VID, PID);
290 #endif
291  pUsb->setAddr(bAddress, 0, 0); // Reset address
293 Fail:
294 #ifdef DEBUG_USB_HOST
295  Notify(PSTR("\r\nBTD Init Failed, error code: "), 0x80);
296  NotifyFail(rcode);
297 #endif
298  Release();
299  return rcode;
300 }
301 
302 void BTD::Initialize() {
303  uint8_t i;
304  for(i = 0; i < BTD_MAX_ENDPOINTS; i++) {
305  epInfo[i].epAddr = 0;
306  epInfo[i].maxPktSize = (i) ? 0 : 8;
307  epInfo[i].bmSndToggle = 0;
308  epInfo[i].bmRcvToggle = 0;
310  }
311  for(i = 0; i < BTD_NUM_SERVICES; i++) {
312  if(btService[i])
313  btService[i]->Reset(); // Reset all Bluetooth services
314  }
315 
316  connectToWii = false;
317  incomingWii = false;
318  connectToHIDDevice = false;
319  incomingHIDDevice = false;
320  incomingPS4 = false;
321  bAddress = 0; // Clear device address
322  bNumEP = 1; // Must have to be reset to 1
323  qNextPollTime = 0; // Reset next poll time
324  pollInterval = 0;
325  bPollEnable = false; // Don't start polling before dongle is connected
326  simple_pairing_supported = false;
327 }
328 
329 /* Extracts interrupt-IN, bulk-IN, bulk-OUT endpoint information from config descriptor */
330 void BTD::EndpointXtract(uint8_t conf, uint8_t iface __attribute__((unused)), uint8_t alt, uint8_t proto __attribute__((unused)), const USB_ENDPOINT_DESCRIPTOR *pep) {
331  //ErrorMessage<uint8_t>(PSTR("Conf.Val"),conf);
332  //ErrorMessage<uint8_t>(PSTR("Iface Num"),iface);
333  //ErrorMessage<uint8_t>(PSTR("Alt.Set"),alt);
334 
335  if(alt) // Wrong interface - by BT spec, no alt setting
336  return;
337 
338  bConfNum = conf;
339  uint8_t index;
340 
341  if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_INTERRUPT && (pep->bEndpointAddress & 0x80) == 0x80) { // Interrupt In endpoint found
342  index = BTD_EVENT_PIPE;
344  } else if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_BULK) // Bulk endpoint found
345  index = ((pep->bEndpointAddress & 0x80) == 0x80) ? BTD_DATAIN_PIPE : BTD_DATAOUT_PIPE;
346  else
347  return;
348 
349  // Fill the rest of endpoint data structure
350  epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
351  epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
352 #ifdef EXTRADEBUG
354 #endif
355  if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints
356  pollInterval = pep->bInterval;
357  bNumEP++;
358 }
359 
360 void BTD::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr __attribute__((unused))) {
361 #ifdef EXTRADEBUG
362  Notify(PSTR("\r\nEndpoint descriptor:"), 0x80);
363  Notify(PSTR("\r\nLength:\t\t"), 0x80);
364  D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
365  Notify(PSTR("\r\nType:\t\t"), 0x80);
366  D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
367  Notify(PSTR("\r\nAddress:\t"), 0x80);
368  D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
369  Notify(PSTR("\r\nAttributes:\t"), 0x80);
370  D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
371  Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
372  D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
373  Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
374  D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
375 #endif
376 }
377 
378 /* Performs a cleanup after failed Init() attempt */
379 uint8_t BTD::Release() {
380  Initialize(); // Set all variables, endpoint structs etc. to default values
382  return 0;
383 }
384 
385 uint8_t BTD::Poll() {
386  if(!bPollEnable)
387  return 0;
388  if((int32_t)((uint32_t)millis() - qNextPollTime) >= 0L) { // Don't poll if shorter than polling interval
389  qNextPollTime = (uint32_t)millis() + pollInterval; // Set new poll time
390  HCI_event_task(); // Poll the HCI event pipe
391  HCI_task(); // HCI state machine
392  ACL_event_task(); // Poll the ACL input pipe too
393  }
394  return 0;
395 }
396 
398  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
399  if(btService[i])
400  btService[i]->disconnect();
401 };
402 
403 void BTD::HCI_event_task() {
404  uint16_t length = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this
405  uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &length, hcibuf, pollInterval); // Input on endpoint 1
406 
407  if(!rcode || rcode == hrNAK) { // Check for errors
408  switch(hcibuf[0]) { // Switch on event type
409  case EV_COMMAND_COMPLETE:
410  if(!hcibuf[5]) { // Check if command succeeded
411  hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag
412  if((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information
413  hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm
414 #ifdef EXTRADEBUG
416  Notify(PSTR("\r\nHCI version: "), 0x80);
417  D_PrintHex<uint8_t > (hci_version, 0x80);
418  }
419 #endif
421  } else if((hcibuf[3] == 0x04) && (hcibuf[4] == 0x10)) { // Parameters from read local extended features
423 #ifdef EXTRADEBUG
424  Notify(PSTR("\r\nPage number: "), 0x80);
425  D_PrintHex<uint8_t > (hcibuf[6], 0x80);
426  Notify(PSTR("\r\nMaximum page number: "), 0x80);
427  D_PrintHex<uint8_t > (hcibuf[7], 0x80);
428  Notify(PSTR("\r\nExtended LMP features:"), 0x80);
429  for(uint8_t i = 0; i < 8; i++) {
430  Notify(PSTR(" "), 0x80);
431  D_PrintHex<uint8_t > (hcibuf[8 + i], 0x80);
432  }
433 #endif
434  if(hcibuf[6] == 0) { // Page 0
435 #ifdef DEBUG_USB_HOST
436  Notify(PSTR("\r\nDongle "), 0x80);
437 #endif
438  if(hcibuf[8 + 6] & (1U << 3)) {
439  simple_pairing_supported = true;
440 #ifdef DEBUG_USB_HOST
441  Notify(PSTR("supports"), 0x80);
442 #endif
443  } else {
444  simple_pairing_supported = false;
445 #ifdef DEBUG_USB_HOST
446  Notify(PSTR("does NOT support"), 0x80);
447 #endif
448  }
449 #ifdef DEBUG_USB_HOST
450  Notify(PSTR(" secure simple pairing (controller support)"), 0x80);
451 #endif
452  } else if(hcibuf[6] == 1) { // Page 1
453 #ifdef DEBUG_USB_HOST
454  Notify(PSTR("\r\nDongle "), 0x80);
455  if(hcibuf[8 + 0] & (1U << 0))
456  Notify(PSTR("supports"), 0x80);
457  else
458  Notify(PSTR("does NOT support"), 0x80);
459  Notify(PSTR(" secure simple pairing (host support)"), 0x80);
460 #endif
461  }
462  }
463 
465  } else if((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address
466  for(uint8_t i = 0; i < 6; i++)
467  my_bdaddr[i] = hcibuf[6 + i];
469  }
470  }
471  break;
472 
473  case EV_COMMAND_STATUS:
474  if(hcibuf[2]) { // Show status on serial if not OK
475 #ifdef DEBUG_USB_HOST
476  Notify(PSTR("\r\nHCI Command Failed: "), 0x80);
477  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
478  Notify(PSTR("\r\nNum HCI Command Packets: "), 0x80);
479  D_PrintHex<uint8_t > (hcibuf[3], 0x80);
480  Notify(PSTR("\r\nCommand Opcode: "), 0x80);
481  D_PrintHex<uint8_t > (hcibuf[4], 0x80);
482  Notify(PSTR(" "), 0x80);
483  D_PrintHex<uint8_t > (hcibuf[5], 0x80);
484 #endif
485  }
486  break;
487 
488  case EV_INQUIRY_COMPLETE:
489  if(inquiry_counter >= 5 && (pairWithWii || pairWithHIDDevice)) {
490  inquiry_counter = 0;
491 #ifdef DEBUG_USB_HOST
492  if(pairWithWii)
493  Notify(PSTR("\r\nCouldn't find Wiimote"), 0x80);
494  else
495  Notify(PSTR("\r\nCouldn't find HID device"), 0x80);
496 #endif
497  connectToWii = false;
498  pairWithWii = false;
499  connectToHIDDevice = false;
500  pairWithHIDDevice = false;
501  hci_state = HCI_SCANNING_STATE;
502  }
503  inquiry_counter++;
504  break;
505 
506  case EV_INQUIRY_RESULT:
507  if(hcibuf[2]) { // Check that there is more than zero responses
508 #ifdef EXTRADEBUG
509  Notify(PSTR("\r\nNumber of responses: "), 0x80);
510  Notify(hcibuf[2], 0x80);
511 #endif
512  for(uint8_t i = 0; i < hcibuf[2]; i++) {
513  uint8_t offset = 8 * hcibuf[2] + 3 * i;
514 
515  for(uint8_t j = 0; j < 3; j++)
516  classOfDevice[j] = hcibuf[j + 4 + offset];
517 
518 #ifdef EXTRADEBUG
519  Notify(PSTR("\r\nClass of device: "), 0x80);
520  D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
521  Notify(PSTR(" "), 0x80);
522  D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
523  Notify(PSTR(" "), 0x80);
524  D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
525 #endif
526 
527  if(pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] == 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information
528  checkRemoteName = true; // Check remote name to distinguish between the different controllers
529 
530  for(uint8_t j = 0; j < 6; j++)
531  disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
532 
534  break;
535  } else if(pairWithHIDDevice && (classOfDevice[1] & 0x0F) == 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
536 #ifdef DEBUG_USB_HOST
537  checkRemoteName = true; // Used to print name in the serial monitor if serial debugging is enabled
538 
539  if(classOfDevice[0] & 0x80)
540  Notify(PSTR("\r\nMouse found"), 0x80);
541  if(classOfDevice[0] & 0x40)
542  Notify(PSTR("\r\nKeyboard found"), 0x80);
543  if(classOfDevice[0] & 0x08)
544  Notify(PSTR("\r\nGamepad found"), 0x80);
545 #endif
546  for(uint8_t j = 0; j < 6; j++)
547  disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
548 
550  break;
551  }
552  }
553  }
554  break;
555 
556  case EV_CONNECT_COMPLETE:
558  if(!hcibuf[2]) { // Check if connected OK
559 #ifdef EXTRADEBUG
560  Notify(PSTR("\r\nConnection established"), 0x80);
561 #endif
562  hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // Store the handle for the ACL connection
563  hci_set_flag(HCI_FLAG_CONNECT_COMPLETE); // Set connection complete flag
564  } else {
565  hci_state = HCI_CHECK_DEVICE_SERVICE;
566 #ifdef DEBUG_USB_HOST
567  Notify(PSTR("\r\nConnection Failed: "), 0x80);
568  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
569 #endif
570  }
571  break;
572 
574  if(!hcibuf[2]) { // Check if disconnected OK
575  hci_set_flag(HCI_FLAG_DISCONNECT_COMPLETE); // Set disconnect command complete flag
576  hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); // Clear connection complete flag
577  }
578  break;
579 
581  if(!hcibuf[2]) { // Check if reading is OK
582  for(uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) {
583  remote_name[i] = hcibuf[9 + i];
584  if(remote_name[i] == '\0') // End of string
585  break;
586  }
587  // TODO: Always set '\0' in remote name!
589  }
590  break;
591 
592  case EV_INCOMING_CONNECT:
593  for(uint8_t i = 0; i < 6; i++)
594  disc_bdaddr[i] = hcibuf[i + 2];
595 
596  for(uint8_t i = 0; i < 3; i++)
597  classOfDevice[i] = hcibuf[i + 8];
598 
599  if((classOfDevice[1] & 0x0F) == 0x05 && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad
600 #ifdef DEBUG_USB_HOST
601  if(classOfDevice[0] & 0x80)
602  Notify(PSTR("\r\nMouse is connecting"), 0x80);
603  if(classOfDevice[0] & 0x40)
604  Notify(PSTR("\r\nKeyboard is connecting"), 0x80);
605  if(classOfDevice[0] & 0x08)
606  Notify(PSTR("\r\nGamepad is connecting"), 0x80);
607 #endif
608  incomingHIDDevice = true;
609  }
610 
611 #ifdef EXTRADEBUG
612  Notify(PSTR("\r\nClass of device: "), 0x80);
613  D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
614  Notify(PSTR(" "), 0x80);
615  D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
616  Notify(PSTR(" "), 0x80);
617  D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
618 #endif
620  break;
621 
622  case EV_PIN_CODE_REQUEST:
623  if(pairWithWii) {
624 #ifdef DEBUG_USB_HOST
625  Notify(PSTR("\r\nPairing with Wiimote"), 0x80);
626 #endif
628  } else if(btdPin != NULL) {
629 #ifdef DEBUG_USB_HOST
630  Notify(PSTR("\r\nBluetooth pin is set too: "), 0x80);
631  NotifyStr(btdPin, 0x80);
632 #endif
634  } else {
635 #ifdef DEBUG_USB_HOST
636  Notify(PSTR("\r\nNo pin was set"), 0x80);
637 #endif
639  }
640  break;
641 
642  case EV_LINK_KEY_REQUEST:
643 #ifdef DEBUG_USB_HOST
644  Notify(PSTR("\r\nReceived Key Request"), 0x80);
645 #endif
647  break;
648 
650  if(!hcibuf[2]) { // Check if pairing was successful
651  if(pairWithWii && !connectToWii) {
652 #ifdef DEBUG_USB_HOST
653  Notify(PSTR("\r\nPairing successful with Wiimote"), 0x80);
654 #endif
655  connectToWii = true; // Used to indicate to the Wii service, that it should connect to this device
656  } else if(pairWithHIDDevice && !connectToHIDDevice) {
657 #ifdef DEBUG_USB_HOST
658  Notify(PSTR("\r\nPairing successful with HID device"), 0x80);
659 #endif
660  connectToHIDDevice = true; // Used to indicate to the BTHID service, that it should connect to this device
661  } else {
662 #ifdef EXTRADEBUG
663  Notify(PSTR("\r\nPairing was successful"), 0x80);
664 #endif
665  }
666  } else {
667 #ifdef DEBUG_USB_HOST
668  Notify(PSTR("\r\nPairing Failed: "), 0x80);
669  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
670 #endif
672  hci_state = HCI_DISCONNECT_STATE;
673  }
674  break;
675 
677 #ifdef DEBUG_USB_HOST
678  Notify(PSTR("\r\nReceived IO Capability Request"), 0x80);
679 #endif
681  break;
682 
684 #ifdef EXTRADEBUG
685  Notify(PSTR("\r\nReceived IO Capability Response: "), 0x80);
686  Notify(PSTR("\r\nIO capability: "), 0x80);
687  D_PrintHex<uint8_t > (hcibuf[8], 0x80);
688  Notify(PSTR("\r\nOOB data present: "), 0x80);
689  D_PrintHex<uint8_t > (hcibuf[9], 0x80);
690  Notify(PSTR("\r\nAuthentication request: "), 0x80);
691  D_PrintHex<uint8_t > (hcibuf[10], 0x80);
692 #endif
693  break;
694 
696 #ifdef DEBUG_USB_HOST
697  Notify(PSTR("\r\nUser confirmation Request"), 0x80);
698 #ifdef EXTRADEBUG
699  Notify(PSTR(": \r\nNumeric value: "), 0x80);
700  for(uint8_t i = 0; i < 4; i++) {
701  Notify(PSTR(" "), 0x80);
702  D_PrintHex<uint8_t > (hcibuf[8 + i], 0x80);
703  }
704 #endif
705 #endif
706  // Simply confirm the connection, as the host has no "NoInputNoOutput" capabilities
708  break;
709 
711 #ifdef EXTRADEBUG
712  if(!hcibuf[2]) { // Check if connected OK
713  Notify(PSTR("\r\nSimple Pairing succeeded"), 0x80);
714  } else {
715  Notify(PSTR("\r\nSimple Pairing failed: "), 0x80);
716  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
717  }
718 #endif
719  break;
720 
721  /* We will just ignore the following events */
722  case EV_MAX_SLOTS_CHANGE:
723  case EV_NUM_COMPLETE_PKT:
724  break;
725  case EV_ROLE_CHANGED:
727  case EV_LOOPBACK_COMMAND:
734 #ifdef EXTRADEBUG
735  if(hcibuf[0] != 0x00) {
736  Notify(PSTR("\r\nIgnore HCI Event: "), 0x80);
737  D_PrintHex<uint8_t > (hcibuf[0], 0x80);
738  }
739 #endif
740  break;
741 #ifdef EXTRADEBUG
742  default:
743  if(hcibuf[0] != 0x00) {
744  Notify(PSTR("\r\nUnmanaged HCI Event: "), 0x80);
745  D_PrintHex<uint8_t > (hcibuf[0], 0x80);
746  Notify(PSTR(", data: "), 0x80);
747  for(uint16_t i = 0; i < hcibuf[1]; i++) {
748  D_PrintHex<uint8_t > (hcibuf[2 + i], 0x80);
749  Notify(PSTR(" "), 0x80);
750  }
751  }
752  break;
753 #endif
754  } // Switch
755  }
756 #ifdef EXTRADEBUG
757  else {
758  Notify(PSTR("\r\nHCI event error: "), 0x80);
759  D_PrintHex<uint8_t > (rcode, 0x80);
760  }
761 #endif
762 }
763 
764 /* Poll Bluetooth and print result */
765 void BTD::HCI_task() {
766  switch(hci_state) {
767  case HCI_INIT_STATE:
768  hci_counter++;
769  if(hci_counter > hci_num_reset_loops) { // wait until we have looped x times to clear any old events
770  hci_reset();
771  hci_state = HCI_RESET_STATE;
772  hci_counter = 0;
773  }
774  break;
775 
776  case HCI_RESET_STATE:
777  hci_counter++;
779  hci_counter = 0;
780 #ifdef DEBUG_USB_HOST
781  Notify(PSTR("\r\nHCI Reset complete"), 0x80);
782 #endif
783  hci_state = HCI_CLASS_STATE;
785  } else if(hci_counter > hci_num_reset_loops) {
786  hci_num_reset_loops *= 10;
787  if(hci_num_reset_loops > 2000)
788  hci_num_reset_loops = 2000;
789 #ifdef DEBUG_USB_HOST
790  Notify(PSTR("\r\nNo response to HCI Reset"), 0x80);
791 #endif
792  hci_state = HCI_INIT_STATE;
793  hci_counter = 0;
794  }
795  break;
796 
797  case HCI_CLASS_STATE:
799 #ifdef DEBUG_USB_HOST
800  Notify(PSTR("\r\nWrite class of device"), 0x80);
801 #endif
802  hci_state = HCI_BDADDR_STATE;
803  hci_read_bdaddr();
804  }
805  break;
806 
807  case HCI_BDADDR_STATE:
809 #ifdef DEBUG_USB_HOST
810  Notify(PSTR("\r\nLocal Bluetooth Address: "), 0x80);
811  for(int8_t i = 5; i > 0; i--) {
812  D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
813  Notify(PSTR(":"), 0x80);
814  }
815  D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
816 #endif
818  hci_state = HCI_LOCAL_VERSION_STATE;
819  }
820  break;
821 
822  case HCI_LOCAL_VERSION_STATE: // The local version is used by the PS3BT class
824  if(btdName != NULL) {
826  hci_state = HCI_WRITE_NAME_STATE;
827  } else if(useSimplePairing) {
828  hci_read_local_extended_features(0); // "Requests the normal LMP features as returned by Read_Local_Supported_Features"
829  //hci_read_local_extended_features(1); // Read page 1
831  } else
832  hci_state = HCI_CHECK_DEVICE_SERVICE;
833  }
834  break;
835 
838 #ifdef DEBUG_USB_HOST
839  Notify(PSTR("\r\nThe name was set to: "), 0x80);
840  NotifyStr(btdName, 0x80);
841 #endif
842  if(useSimplePairing) {
843  hci_read_local_extended_features(0); // "Requests the normal LMP features as returned by Read_Local_Supported_Features"
844  //hci_read_local_extended_features(1); // Read page 1
846  } else
847  hci_state = HCI_CHECK_DEVICE_SERVICE;
848  }
849  break;
850 
853  if(simple_pairing_supported) {
855  hci_state = HCI_WRITE_SIMPLE_PAIRING_STATE;
856  } else
857  hci_state = HCI_CHECK_DEVICE_SERVICE;
858  }
859  break;
860 
863 #ifdef DEBUG_USB_HOST
864  Notify(PSTR("\r\nSimple pairing was enabled"), 0x80);
865 #endif
867  hci_state = HCI_SET_EVENT_MASK_STATE;
868  }
869  break;
870 
873 #ifdef DEBUG_USB_HOST
874  Notify(PSTR("\r\nSet event mask completed"), 0x80);
875 #endif
876  hci_state = HCI_CHECK_DEVICE_SERVICE;
877  }
878  break;
879 
881  if(pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote
882 #ifdef DEBUG_USB_HOST
883  if(pairWithWii)
884  Notify(PSTR("\r\nStarting inquiry\r\nPress 1 & 2 on the Wiimote\r\nOr press the SYNC button if you are using a Wii U Pro Controller or a Wii Balance Board"), 0x80);
885  else
886  Notify(PSTR("\r\nPlease enable discovery of your device"), 0x80);
887 #endif
888  hci_inquiry();
889  hci_state = HCI_INQUIRY_STATE;
890  } else
891  hci_state = HCI_SCANNING_STATE; // Don't try to connect to a Wiimote
892  break;
893 
894  case HCI_INQUIRY_STATE:
896  hci_inquiry_cancel(); // Stop inquiry
897 #ifdef DEBUG_USB_HOST
898  if(pairWithWii)
899  Notify(PSTR("\r\nWiimote found"), 0x80);
900  else
901  Notify(PSTR("\r\nHID device found"), 0x80);
902 
903  Notify(PSTR("\r\nNow just create the instance like so:"), 0x80);
904  if(pairWithWii)
905  Notify(PSTR("\r\nWII Wii(&Btd);"), 0x80);
906  else
907  Notify(PSTR("\r\nBTHID bthid(&Btd);"), 0x80);
908 
909  Notify(PSTR("\r\nAnd then press any button on the "), 0x80);
910  if(pairWithWii)
911  Notify(PSTR("Wiimote"), 0x80);
912  else
913  Notify(PSTR("device"), 0x80);
914 #endif
915  if(checkRemoteName) {
916  hci_remote_name(); // We need to know the name to distinguish between the Wiimote, the new Wiimote with Motion Plus inside, a Wii U Pro Controller and a Wii Balance Board
917  hci_state = HCI_REMOTE_NAME_STATE;
918  } else
919  hci_state = HCI_CONNECT_DEVICE_STATE;
920  }
921  break;
922 
925 #ifdef DEBUG_USB_HOST
926  if(pairWithWii)
927  Notify(PSTR("\r\nConnecting to Wiimote"), 0x80);
928  else
929  Notify(PSTR("\r\nConnecting to HID device"), 0x80);
930 #endif
931  checkRemoteName = false;
932  hci_connect();
933  hci_state = HCI_CONNECTED_DEVICE_STATE;
934  }
935  break;
936 
940 #ifdef DEBUG_USB_HOST
941  if(pairWithWii)
942  Notify(PSTR("\r\nConnected to Wiimote"), 0x80);
943  else
944  Notify(PSTR("\r\nConnected to HID device"), 0x80);
945 #endif
946  hci_authentication_request(); // This will start the pairing with the device
947  hci_state = HCI_SCANNING_STATE;
948  } else {
949 #ifdef DEBUG_USB_HOST
950  Notify(PSTR("\r\nTrying to connect one more time..."), 0x80);
951 #endif
952  hci_connect(); // Try to connect one more time
953  }
954  }
955  break;
956 
957  case HCI_SCANNING_STATE:
959 #ifdef DEBUG_USB_HOST
960  Notify(PSTR("\r\nWait For Incoming Connection Request"), 0x80);
961 #endif
963  waitingForConnection = true;
964  hci_state = HCI_CONNECT_IN_STATE;
965  }
966  break;
967 
970  waitingForConnection = false;
971 #ifdef DEBUG_USB_HOST
972  Notify(PSTR("\r\nIncoming Connection Request"), 0x80);
973 #endif
974  hci_remote_name();
975  hci_state = HCI_REMOTE_NAME_STATE;
977  hci_state = HCI_DISCONNECT_STATE;
978  break;
979 
982 #ifdef DEBUG_USB_HOST
983  Notify(PSTR("\r\nRemote Name: "), 0x80);
984  for(uint8_t i = 0; i < strlen(remote_name); i++)
985  Notifyc(remote_name[i], 0x80);
986 #endif
987  if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) {
988  incomingWii = true;
989  motionPlusInside = false;
990  wiiUProController = false;
991  pairWiiUsingSync = false;
992 #ifdef DEBUG_USB_HOST
993  Notify(PSTR("\r\nWiimote is connecting"), 0x80);
994 #endif
995  if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) {
996 #ifdef DEBUG_USB_HOST
997  Notify(PSTR(" with Motion Plus Inside"), 0x80);
998 #endif
999  motionPlusInside = true;
1000  } else if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) {
1001 #ifdef DEBUG_USB_HOST
1002  Notify(PSTR(" - Wii U Pro Controller"), 0x80);
1003 #endif
1004  wiiUProController = motionPlusInside = pairWiiUsingSync = true;
1005  } else if(strncmp((const char*)remote_name, "Nintendo RVL-WBC-01", 19) == 0) {
1006 #ifdef DEBUG_USB_HOST
1007  Notify(PSTR(" - Wii Balance Board"), 0x80);
1008 #endif
1009  pairWiiUsingSync = true;
1010  }
1011  }
1012  if(classOfDevice[2] == 0 && classOfDevice[1] == 0x25 && classOfDevice[0] == 0x08 && strncmp((const char*)remote_name, "Wireless Controller", 19) == 0) {
1013 #ifdef DEBUG_USB_HOST
1014  Notify(PSTR("\r\nPS4 controller is connecting"), 0x80);
1015 #endif
1016  incomingPS4 = true;
1017  }
1018  if((pairWithWii || pairWithHIDDevice) && checkRemoteName)
1019  hci_state = HCI_CONNECT_DEVICE_STATE;
1020  else {
1022  hci_state = HCI_CONNECTED_STATE;
1023  }
1024  }
1025  break;
1026 
1027  case HCI_CONNECTED_STATE:
1029 #ifdef DEBUG_USB_HOST
1030  Notify(PSTR("\r\nConnected to Device: "), 0x80);
1031  for(int8_t i = 5; i > 0; i--) {
1032  D_PrintHex<uint8_t > (disc_bdaddr[i], 0x80);
1033  Notify(PSTR(":"), 0x80);
1034  }
1035  D_PrintHex<uint8_t > (disc_bdaddr[0], 0x80);
1036 #endif
1037  if(incomingPS4)
1038  connectToHIDDevice = true; // We should always connect to the PS4 controller
1039 
1040  // Clear these flags for a new connection
1041  l2capConnectionClaimed = false;
1042  sdpConnectionClaimed = false;
1043  rfcommConnectionClaimed = false;
1044 
1045  hci_event_flag = 0;
1046  hci_state = HCI_DONE_STATE;
1047  }
1048  break;
1049 
1050  case HCI_DONE_STATE:
1051  hci_counter++;
1052  if(hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started
1053  hci_counter = 0;
1054  hci_state = HCI_SCANNING_STATE;
1055  }
1056  break;
1057 
1058  case HCI_DISCONNECT_STATE:
1060 #ifdef DEBUG_USB_HOST
1061  Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80);
1062 #endif
1063  hci_event_flag = 0; // Clear all flags
1064 
1065  // Reset all buffers
1066  memset(hcibuf, 0, BULK_MAXPKTSIZE);
1067  memset(l2capinbuf, 0, BULK_MAXPKTSIZE);
1068 
1069  connectToWii = incomingWii = pairWithWii = false;
1070  connectToHIDDevice = incomingHIDDevice = pairWithHIDDevice = checkRemoteName = false;
1071  incomingPS4 = false;
1072 
1073  hci_state = HCI_SCANNING_STATE;
1074  }
1075  break;
1076  default:
1077  break;
1078  }
1079 }
1080 
1081 void BTD::ACL_event_task() {
1082  uint16_t length = BULK_MAXPKTSIZE;
1083  uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf, pollInterval); // Input on endpoint 2
1084 
1085  if(!rcode) { // Check for errors
1086  if(length > 0) { // Check if any data was read
1087  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
1088  if(btService[i])
1089  btService[i]->ACLData(l2capinbuf);
1090  }
1091  }
1092  }
1093 #ifdef EXTRADEBUG
1094  else if(rcode != hrNAK) {
1095  Notify(PSTR("\r\nACL data in error: "), 0x80);
1096  D_PrintHex<uint8_t > (rcode, 0x80);
1097  }
1098 #endif
1099  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
1100  if(btService[i])
1101  btService[i]->Run();
1102 }
1103 
1104 /************************************************************/
1105 /* HCI Commands */
1106 
1107 /************************************************************/
1108 void BTD::HCI_Command(uint8_t* data, uint16_t nbytes) {
1110  pUsb->ctrlReq(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, 0x00, 0x00, 0x00, 0x00, nbytes, nbytes, data, NULL);
1111 }
1112 
1114  hci_event_flag = 0; // Clear all the flags
1115  hcibuf[0] = 0x03; // HCI OCF = 3
1116  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1117  hcibuf[2] = 0x00;
1118 
1119  HCI_Command(hcibuf, 3);
1120 }
1121 
1124  hcibuf[0] = 0x1A; // HCI OCF = 1A
1125  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1126  hcibuf[2] = 0x01; // parameter length = 1
1127  if(btdName != NULL)
1128  hcibuf[3] = 0x03; // Inquiry Scan enabled. Page Scan enabled.
1129  else
1130  hcibuf[3] = 0x02; // Inquiry Scan disabled. Page Scan enabled.
1131 
1132  HCI_Command(hcibuf, 4);
1133 }
1134 
1136  hcibuf[0] = 0x1A; // HCI OCF = 1A
1137  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1138  hcibuf[2] = 0x01; // parameter length = 1
1139  hcibuf[3] = 0x00; // Inquiry Scan disabled. Page Scan disabled.
1140 
1141  HCI_Command(hcibuf, 4);
1142 }
1143 
1146  hcibuf[0] = 0x09; // HCI OCF = 9
1147  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
1148  hcibuf[2] = 0x00;
1149 
1150  HCI_Command(hcibuf, 3);
1151 }
1152 
1155  hcibuf[0] = 0x01; // HCI OCF = 1
1156  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
1157  hcibuf[2] = 0x00;
1158 
1159  HCI_Command(hcibuf, 3);
1160 }
1161 
1162 void BTD::hci_read_local_extended_features(uint8_t page_number) {
1164  hcibuf[0] = 0x04; // HCI OCF = 4
1165  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
1166  hcibuf[2] = 0x01; // parameter length = 1
1167  hcibuf[3] = page_number;
1168 
1169  HCI_Command(hcibuf, 4);
1170 }
1171 
1174  hcibuf[0] = 0x09; // HCI OCF = 9
1175  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1176  hcibuf[2] = 0x07; // parameter length 7
1177  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1178  hcibuf[4] = disc_bdaddr[1];
1179  hcibuf[5] = disc_bdaddr[2];
1180  hcibuf[6] = disc_bdaddr[3];
1181  hcibuf[7] = disc_bdaddr[4];
1182  hcibuf[8] = disc_bdaddr[5];
1183  hcibuf[9] = 0x00; // Switch role to master
1184 
1185  HCI_Command(hcibuf, 10);
1186 }
1187 
1190  hcibuf[0] = 0x19; // HCI OCF = 19
1191  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1192  hcibuf[2] = 0x0A; // parameter length = 10
1193  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1194  hcibuf[4] = disc_bdaddr[1];
1195  hcibuf[5] = disc_bdaddr[2];
1196  hcibuf[6] = disc_bdaddr[3];
1197  hcibuf[7] = disc_bdaddr[4];
1198  hcibuf[8] = disc_bdaddr[5];
1199  hcibuf[9] = 0x01; // Page Scan Repetition Mode
1200  hcibuf[10] = 0x00; // Reserved
1201  hcibuf[11] = 0x00; // Clock offset - low byte
1202  hcibuf[12] = 0x00; // Clock offset - high byte
1203 
1204  HCI_Command(hcibuf, 13);
1205 }
1206 
1207 void BTD::hci_write_local_name(const char* name) {
1208  hcibuf[0] = 0x13; // HCI OCF = 13
1209  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1210  hcibuf[2] = strlen(name) + 1; // parameter length = the length of the string + end byte
1211  uint8_t i;
1212  for(i = 0; i < strlen(name); i++)
1213  hcibuf[i + 3] = name[i];
1214  hcibuf[i + 3] = 0x00; // End of string
1215 
1216  HCI_Command(hcibuf, 4 + strlen(name));
1217 }
1218 
1220  hcibuf[0] = 0x01; // HCI OCF = 01
1221  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1222  hcibuf[2] = 0x08;
1223  // The first 6 bytes are the default of 1FFF FFFF FFFF
1224  // However we need to set bits 48-55 for simple pairing to work
1225  hcibuf[3] = 0xFF;
1226  hcibuf[4] = 0xFF;
1227  hcibuf[5] = 0xFF;
1228  hcibuf[6] = 0xFF;
1229  hcibuf[7] = 0xFF;
1230  hcibuf[8] = 0x1F;
1231  hcibuf[9] = 0xFF; // Enable bits 48-55 used for simple pairing
1232  hcibuf[10] = 0x00;
1233 
1234  HCI_Command(hcibuf, 11);
1235 }
1236 
1238  hcibuf[0] = 0x56; // HCI OCF = 56
1239  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1240  hcibuf[2] = 1; // parameter length = 1
1241  hcibuf[3] = enable ? 1 : 0;
1242 
1243  HCI_Command(hcibuf, 4);
1244 }
1245 
1248  hcibuf[0] = 0x01;
1249  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1250  hcibuf[2] = 0x05; // Parameter Total Length = 5
1251  hcibuf[3] = 0x33; // LAP: Genera/Unlimited Inquiry Access Code (GIAC = 0x9E8B33) - see https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
1252  hcibuf[4] = 0x8B;
1253  hcibuf[5] = 0x9E;
1254  hcibuf[6] = 0x30; // Inquiry time = 61.44 sec (maximum)
1255  hcibuf[7] = 0x0A; // 10 number of responses
1256 
1257  HCI_Command(hcibuf, 8);
1258 }
1259 
1261  hcibuf[0] = 0x02;
1262  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1263  hcibuf[2] = 0x00; // Parameter Total Length = 0
1264 
1265  HCI_Command(hcibuf, 3);
1266 }
1267 
1269  hci_connect(disc_bdaddr); // Use last discovered device
1270 }
1271 
1272 void BTD::hci_connect(uint8_t *bdaddr) {
1274  hcibuf[0] = 0x05; // HCI OCF = 5
1275  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1276  hcibuf[2] = 0x0D; // parameter Total Length = 13
1277  hcibuf[3] = bdaddr[0]; // 6 octet bdaddr (LSB)
1278  hcibuf[4] = bdaddr[1];
1279  hcibuf[5] = bdaddr[2];
1280  hcibuf[6] = bdaddr[3];
1281  hcibuf[7] = bdaddr[4];
1282  hcibuf[8] = bdaddr[5];
1283  hcibuf[9] = 0x18; // DM1 or DH1 may be used
1284  hcibuf[10] = 0xCC; // DM3, DH3, DM5, DH5 may be used
1285  hcibuf[11] = 0x01; // Page repetition mode R1
1286  hcibuf[12] = 0x00; // Reserved
1287  hcibuf[13] = 0x00; // Clock offset
1288  hcibuf[14] = 0x00; // Invalid clock offset
1289  hcibuf[15] = 0x00; // Do not allow role switch
1290 
1291  HCI_Command(hcibuf, 16);
1292 }
1293 
1295  hcibuf[0] = 0x0D; // HCI OCF = 0D
1296  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1297  hcibuf[2] = 0x17; // parameter length 23
1298  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1299  hcibuf[4] = disc_bdaddr[1];
1300  hcibuf[5] = disc_bdaddr[2];
1301  hcibuf[6] = disc_bdaddr[3];
1302  hcibuf[7] = disc_bdaddr[4];
1303  hcibuf[8] = disc_bdaddr[5];
1304  if(pairWithWii) {
1305  hcibuf[9] = 6; // Pin length is the length of the Bluetooth address
1306  if(pairWiiUsingSync) {
1307 #ifdef DEBUG_USB_HOST
1308  Notify(PSTR("\r\nPairing with Wii controller via SYNC"), 0x80);
1309 #endif
1310  for(uint8_t i = 0; i < 6; i++)
1311  hcibuf[10 + i] = my_bdaddr[i]; // The pin is the Bluetooth dongles Bluetooth address backwards
1312  } else {
1313  for(uint8_t i = 0; i < 6; i++)
1314  hcibuf[10 + i] = disc_bdaddr[i]; // The pin is the Wiimote's Bluetooth address backwards
1315  }
1316  for(uint8_t i = 16; i < 26; i++)
1317  hcibuf[i] = 0x00; // The rest should be 0
1318  } else {
1319  hcibuf[9] = strlen(btdPin); // Length of pin
1320  uint8_t i;
1321  for(i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16
1322  hcibuf[i + 10] = btdPin[i];
1323  for(; i < 16; i++)
1324  hcibuf[i + 10] = 0x00; // The rest should be 0
1325  }
1326 
1327  HCI_Command(hcibuf, 26);
1328 }
1329 
1331  hcibuf[0] = 0x0E; // HCI OCF = 0E
1332  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1333  hcibuf[2] = 0x06; // parameter length 6
1334  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1335  hcibuf[4] = disc_bdaddr[1];
1336  hcibuf[5] = disc_bdaddr[2];
1337  hcibuf[6] = disc_bdaddr[3];
1338  hcibuf[7] = disc_bdaddr[4];
1339  hcibuf[8] = disc_bdaddr[5];
1340 
1341  HCI_Command(hcibuf, 9);
1342 }
1343 
1345  hcibuf[0] = 0x0C; // HCI OCF = 0C
1346  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1347  hcibuf[2] = 0x06; // parameter length 6
1348  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1349  hcibuf[4] = disc_bdaddr[1];
1350  hcibuf[5] = disc_bdaddr[2];
1351  hcibuf[6] = disc_bdaddr[3];
1352  hcibuf[7] = disc_bdaddr[4];
1353  hcibuf[8] = disc_bdaddr[5];
1354 
1355  HCI_Command(hcibuf, 9);
1356 }
1357 
1359  hcibuf[0] = 0x2B; // HCI OCF = 2B
1360  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1361  hcibuf[2] = 0x09;
1362  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1363  hcibuf[4] = disc_bdaddr[1];
1364  hcibuf[5] = disc_bdaddr[2];
1365  hcibuf[6] = disc_bdaddr[3];
1366  hcibuf[7] = disc_bdaddr[4];
1367  hcibuf[8] = disc_bdaddr[5];
1368  hcibuf[9] = 0x03; // NoInputNoOutput
1369  hcibuf[10] = 0x00; // OOB authentication data not present
1370  hcibuf[11] = 0x00; // MITM Protection Not Required – No Bonding. Numeric comparison with automatic accept allowed
1371 
1372  HCI_Command(hcibuf, 12);
1373 }
1374 
1376  hcibuf[0] = 0x2C; // HCI OCF = 2C
1377  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1378  hcibuf[2] = 0x06; // parameter length 6
1379  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1380  hcibuf[4] = disc_bdaddr[1];
1381  hcibuf[5] = disc_bdaddr[2];
1382  hcibuf[6] = disc_bdaddr[3];
1383  hcibuf[7] = disc_bdaddr[4];
1384  hcibuf[8] = disc_bdaddr[5];
1385 
1386  HCI_Command(hcibuf, 9);
1387 }
1388 
1390  hcibuf[0] = 0x11; // HCI OCF = 11
1391  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1392  hcibuf[2] = 0x02; // parameter length = 2
1393  hcibuf[3] = (uint8_t)(hci_handle & 0xFF); //connection handle - low byte
1394  hcibuf[4] = (uint8_t)((hci_handle >> 8) & 0x0F); //connection handle - high byte
1395 
1396  HCI_Command(hcibuf, 5);
1397 }
1398 
1399 void BTD::hci_disconnect(uint16_t handle) { // This is called by the different services
1401  hcibuf[0] = 0x06; // HCI OCF = 6
1402  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1403  hcibuf[2] = 0x03; // parameter length = 3
1404  hcibuf[3] = (uint8_t)(handle & 0xFF); //connection handle - low byte
1405  hcibuf[4] = (uint8_t)((handle >> 8) & 0x0F); //connection handle - high byte
1406  hcibuf[5] = 0x13; // reason
1407 
1408  HCI_Command(hcibuf, 6);
1409 }
1410 
1411 void BTD::hci_write_class_of_device() { // See http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
1412  hcibuf[0] = 0x24; // HCI OCF = 24
1413  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1414  hcibuf[2] = 0x03; // parameter length = 3
1415  hcibuf[3] = 0x04; // Robot
1416  hcibuf[4] = 0x08; // Toy
1417  hcibuf[5] = 0x00;
1418 
1419  HCI_Command(hcibuf, 6);
1420 }
1421 /*******************************************************************
1422  * *
1423  * HCI ACL Data Packet *
1424  * *
1425  * buf[0] buf[1] buf[2] buf[3]
1426  * 0 4 8 11 12 16 24 31 MSB
1427  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1428  * | HCI Handle |PB |BC | Data Total Length | HCI ACL Data Packet
1429  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1430  *
1431  * buf[4] buf[5] buf[6] buf[7]
1432  * 0 8 16 31 MSB
1433  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1434  * | Length | Channel ID | Basic L2CAP header
1435  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1436  *
1437  * buf[8] buf[9] buf[10] buf[11]
1438  * 0 8 16 31 MSB
1439  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1440  * | Code | Identifier | Length | Control frame (C-frame)
1441  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-. (signaling packet format)
1442  */
1443 /************************************************************/
1444 /* L2CAP Commands */
1445 
1446 /************************************************************/
1447 void BTD::L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh) {
1448  uint8_t buf[8 + nbytes];
1449  buf[0] = (uint8_t)(handle & 0xff); // HCI handle with PB,BC flag
1450  buf[1] = (uint8_t)(((handle >> 8) & 0x0f) | 0x20);
1451  buf[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
1452  buf[3] = (uint8_t)((4 + nbytes) >> 8);
1453  buf[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
1454  buf[5] = (uint8_t)(nbytes >> 8);
1455  buf[6] = channelLow;
1456  buf[7] = channelHigh;
1457 
1458  for(uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame
1459  buf[8 + i] = data[i];
1460 
1461  uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ BTD_DATAOUT_PIPE ].epAddr, (8 + nbytes), buf);
1462  if(rcode) {
1463  delay(100); // This small delay prevents it from overflowing if it fails
1464 #ifdef DEBUG_USB_HOST
1465  Notify(PSTR("\r\nError sending L2CAP message: 0x"), 0x80);
1466  D_PrintHex<uint8_t > (rcode, 0x80);
1467  Notify(PSTR(" - Channel ID: "), 0x80);
1468  D_PrintHex<uint8_t > (channelHigh, 0x80);
1469  Notify(PSTR(" "), 0x80);
1470  D_PrintHex<uint8_t > (channelLow, 0x80);
1471 #endif
1472  }
1473 }
1474 
1475 void BTD::l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm) {
1476  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
1477  l2capoutbuf[1] = rxid; // Identifier
1478  l2capoutbuf[2] = 0x04; // Length
1479  l2capoutbuf[3] = 0x00;
1480  l2capoutbuf[4] = (uint8_t)(psm & 0xff); // PSM
1481  l2capoutbuf[5] = (uint8_t)(psm >> 8);
1482  l2capoutbuf[6] = scid[0]; // Source CID
1483  l2capoutbuf[7] = scid[1];
1484 
1485  L2CAP_Command(handle, l2capoutbuf, 8);
1486 }
1487 
1488 void BTD::l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result) {
1489  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
1490  l2capoutbuf[1] = rxid; // Identifier
1491  l2capoutbuf[2] = 0x08; // Length
1492  l2capoutbuf[3] = 0x00;
1493  l2capoutbuf[4] = dcid[0]; // Destination CID
1494  l2capoutbuf[5] = dcid[1];
1495  l2capoutbuf[6] = scid[0]; // Source CID
1496  l2capoutbuf[7] = scid[1];
1497  l2capoutbuf[8] = result; // Result: Pending or Success
1498  l2capoutbuf[9] = 0x00;
1499  l2capoutbuf[10] = 0x00; // No further information
1500  l2capoutbuf[11] = 0x00;
1501 
1502  L2CAP_Command(handle, l2capoutbuf, 12);
1503 }
1504 
1505 void BTD::l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid) {
1506  l2capoutbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
1507  l2capoutbuf[1] = rxid; // Identifier
1508  l2capoutbuf[2] = 0x08; // Length
1509  l2capoutbuf[3] = 0x00;
1510  l2capoutbuf[4] = dcid[0]; // Destination CID
1511  l2capoutbuf[5] = dcid[1];
1512  l2capoutbuf[6] = 0x00; // Flags
1513  l2capoutbuf[7] = 0x00;
1514  l2capoutbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
1515  l2capoutbuf[9] = 0x02; // Config Opt: length
1516  l2capoutbuf[10] = 0xFF; // MTU
1517  l2capoutbuf[11] = 0xFF;
1518 
1519  L2CAP_Command(handle, l2capoutbuf, 12);
1520 }
1521 
1522 void BTD::l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid) {
1523  l2capoutbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
1524  l2capoutbuf[1] = rxid; // Identifier
1525  l2capoutbuf[2] = 0x0A; // Length
1526  l2capoutbuf[3] = 0x00;
1527  l2capoutbuf[4] = scid[0]; // Source CID
1528  l2capoutbuf[5] = scid[1];
1529  l2capoutbuf[6] = 0x00; // Flag
1530  l2capoutbuf[7] = 0x00;
1531  l2capoutbuf[8] = 0x00; // Result
1532  l2capoutbuf[9] = 0x00;
1533  l2capoutbuf[10] = 0x01; // Config
1534  l2capoutbuf[11] = 0x02;
1535  l2capoutbuf[12] = 0xA0;
1536  l2capoutbuf[13] = 0x02;
1537 
1538  L2CAP_Command(handle, l2capoutbuf, 14);
1539 }
1540 
1541 void BTD::l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1542  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_REQUEST; // Code
1543  l2capoutbuf[1] = rxid; // Identifier
1544  l2capoutbuf[2] = 0x04; // Length
1545  l2capoutbuf[3] = 0x00;
1546  l2capoutbuf[4] = dcid[0];
1547  l2capoutbuf[5] = dcid[1];
1548  l2capoutbuf[6] = scid[0];
1549  l2capoutbuf[7] = scid[1];
1550 
1551  L2CAP_Command(handle, l2capoutbuf, 8);
1552 }
1553 
1554 void BTD::l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1555  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_RESPONSE; // Code
1556  l2capoutbuf[1] = rxid; // Identifier
1557  l2capoutbuf[2] = 0x04; // Length
1558  l2capoutbuf[3] = 0x00;
1559  l2capoutbuf[4] = dcid[0];
1560  l2capoutbuf[5] = dcid[1];
1561  l2capoutbuf[6] = scid[0];
1562  l2capoutbuf[7] = scid[1];
1563 
1564  L2CAP_Command(handle, l2capoutbuf, 8);
1565 }
1566 
1567 void BTD::l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh) {
1568  l2capoutbuf[0] = L2CAP_CMD_INFORMATION_RESPONSE; // Code
1569  l2capoutbuf[1] = rxid; // Identifier
1570  l2capoutbuf[2] = 0x08; // Length
1571  l2capoutbuf[3] = 0x00;
1572  l2capoutbuf[4] = infoTypeLow;
1573  l2capoutbuf[5] = infoTypeHigh;
1574  l2capoutbuf[6] = 0x00; // Result = success
1575  l2capoutbuf[7] = 0x00; // Result = success
1576  l2capoutbuf[8] = 0x00;
1577  l2capoutbuf[9] = 0x00;
1578  l2capoutbuf[10] = 0x00;
1579  l2capoutbuf[11] = 0x00;
1580 
1581  L2CAP_Command(handle, l2capoutbuf, 12);
1582 }
1583 
1584 /* PS3 Commands - only set Bluetooth address is implemented in this library */
1585 void BTD::setBdaddr(uint8_t* bdaddr) {
1586  /* Set the internal Bluetooth address */
1587  uint8_t buf[8];
1588  buf[0] = 0x01;
1589  buf[1] = 0x00;
1590 
1591  for(uint8_t i = 0; i < 6; i++)
1592  buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first
1593 
1594  // 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
1595  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
1596 }
1597 
1598 void BTD::setMoveBdaddr(uint8_t* bdaddr) {
1599  /* Set the internal Bluetooth address */
1600  uint8_t buf[11];
1601  buf[0] = 0x05;
1602  buf[7] = 0x10;
1603  buf[8] = 0x01;
1604  buf[9] = 0x02;
1605  buf[10] = 0x12;
1606 
1607  for(uint8_t i = 0; i < 6; i++)
1608  buf[i + 1] = bdaddr[i];
1609 
1610  // 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
1611  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
1612 }
static const uint8_t BTD_DATAOUT_PIPE
Definition: BTD.h:558
+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 useSimplePairing(false),
33 pUsb(p), // Pointer to USB class instance - mandatory
34 bAddress(0), // Device address - mandatory
35 bNumEP(1), // If config descriptor needs to be parsed
36 qNextPollTime(0), // Reset NextPollTime
37 pollInterval(0),
38 simple_pairing_supported(false),
39 bPollEnable(false) // Don't start polling before dongle is connected
40 {
41  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
42  btService[i] = NULL;
43 
44  Initialize(); // Set all variables, endpoint structs etc. to default values
45 
46  if(pUsb) // Register in USB subsystem
47  pUsb->RegisterDeviceClass(this); // Set devConfig[] entry
48 }
49 
50 uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
51  const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
52  uint8_t buf[constBufSize];
53  USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
54  uint8_t rcode;
55  UsbDevice *p = NULL;
56  EpInfo *oldep_ptr = NULL;
57 
58  Initialize(); // Set all variables, endpoint structs etc. to default values
59 
60  AddressPool &addrPool = pUsb->GetAddressPool(); // Get memory address of USB device address pool
61 #ifdef EXTRADEBUG
62  Notify(PSTR("\r\nBTD ConfigureDevice"), 0x80);
63 #endif
64 
65  if(bAddress) { // Check if address has already been assigned to an instance
66 #ifdef DEBUG_USB_HOST
67  Notify(PSTR("\r\nAddress in use"), 0x80);
68 #endif
70  }
71 
72  p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned
73  if(!p) {
74 #ifdef DEBUG_USB_HOST
75  Notify(PSTR("\r\nAddress not found"), 0x80);
76 #endif
78  }
79 
80  if(!p->epinfo) {
81 #ifdef DEBUG_USB_HOST
82  Notify(PSTR("\r\nepinfo is null"), 0x80);
83 #endif
85  }
86 
87  oldep_ptr = p->epinfo; // Save old pointer to EP_RECORD of address 0
88  p->epinfo = epInfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
89  p->lowspeed = lowspeed;
90  rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
91 
92  p->epinfo = oldep_ptr; // Restore p->epinfo
93 
94  if(rcode)
95  goto FailGetDevDescr;
96 
97  bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class
98 
99  if(!bAddress) {
100 #ifdef DEBUG_USB_HOST
101  Notify(PSTR("\r\nOut of address space"), 0x80);
102 #endif
104  }
105 
106  if (udd->bDeviceClass == 0x09) // Some dongles have an USB hub inside
107  goto FailHub;
108 
109  epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor
110  epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory
111 
112  VID = udd->idVendor;
113  PID = udd->idProduct;
114 
116 
117 FailHub:
118 #ifdef DEBUG_USB_HOST
119  Notify(PSTR("\r\nPlease create a hub instance in your code: \"USBHub Hub1(&Usb);\""), 0x80);
120 #endif
121  pUsb->setAddr(bAddress, 0, 0); // Reset address
123  Release();
124  return rcode;
125 
126 FailGetDevDescr:
127 #ifdef DEBUG_USB_HOST
128  NotifyFailGetDevDescr(rcode);
129 #endif
130  if(rcode != hrJERR)
132  Release();
133  return rcode;
134 };
135 
136 uint8_t BTD::Init(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed) {
137  uint8_t rcode;
138  uint8_t num_of_conf = epInfo[1].epAddr; // Number of configurations
139  epInfo[1].epAddr = 0;
140 
141  AddressPool &addrPool = pUsb->GetAddressPool();
142 #ifdef EXTRADEBUG
143  Notify(PSTR("\r\nBTD Init"), 0x80);
144 #endif
145  UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
146 
147  if(!p) {
148 #ifdef DEBUG_USB_HOST
149  Notify(PSTR("\r\nAddress not found"), 0x80);
150 #endif
152  }
153 
154  delay(300); // Assign new address to the device
155 
156  rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device
157  if(rcode) {
158 #ifdef DEBUG_USB_HOST
159  Notify(PSTR("\r\nsetAddr: "), 0x80);
160  D_PrintHex<uint8_t > (rcode, 0x80);
161 #endif
162  p->lowspeed = false;
163  goto Fail;
164  }
165 #ifdef EXTRADEBUG
166  Notify(PSTR("\r\nAddr: "), 0x80);
167  D_PrintHex<uint8_t > (bAddress, 0x80);
168 #endif
169 
170  p->lowspeed = false;
171 
172  p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
173  if(!p) {
174 #ifdef DEBUG_USB_HOST
175  Notify(PSTR("\r\nAddress not found"), 0x80);
176 #endif
178  }
179 
180  p->lowspeed = lowspeed;
181 
182  rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known
183  if(rcode)
184  goto FailSetDevTblEntry;
185 
186  if(VID == PS3_VID && (PID == PS3_PID || PID == PS3NAVIGATION_PID || PID == PS3MOVE_PID)) {
187  delay(100);
188  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
189  if(rcode)
190  goto FailSetConfDescr;
191 
192 #ifdef DEBUG_USB_HOST
193  if(PID == PS3_PID || PID == PS3NAVIGATION_PID) {
194  if(PID == PS3_PID)
195  Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80);
196  else // It must be a navigation controller
197  Notify(PSTR("\r\nNavigation Controller Connected"), 0x80);
198  } else // It must be a Motion controller
199  Notify(PSTR("\r\nMotion Controller Connected"), 0x80);
200 #endif
201 
202  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) {
203 #ifdef DEBUG_USB_HOST
204  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);
205 #endif
206  } else {
207  if(PID == PS3_PID || PID == PS3NAVIGATION_PID)
208  setBdaddr(my_bdaddr); // Set internal Bluetooth address
209  else
210  setMoveBdaddr(my_bdaddr); // Set internal Bluetooth address
211 #ifdef DEBUG_USB_HOST
212  Notify(PSTR("\r\nBluetooth Address was set to: "), 0x80);
213  for(int8_t i = 5; i > 0; i--) {
214  D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
215  Notify(PSTR(":"), 0x80);
216  }
217  D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
218 #endif
219  }
220 
221  pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, 0); // Reset configuration value
222  pUsb->setAddr(bAddress, 0, 0); // Reset address
223  Release(); // Release device
225  } else {
226  // Check if attached device is a Bluetooth dongle and fill endpoint data structure
227  // First interface in the configuration must have Bluetooth assigned Class/Subclass/Protocol
228  // And 3 endpoints - interrupt-IN, bulk-IN, bulk-OUT, not necessarily in this order
229  for(uint8_t i = 0; i < num_of_conf; i++) {
230  if((VID == IOGEAR_GBU521_VID && PID == IOGEAR_GBU521_PID) || (VID == BELKIN_F8T065BF_VID && PID == BELKIN_F8T065BF_PID)) {
231  ConfigDescParser<USB_CLASS_VENDOR_SPECIFIC, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this); // Workaround issue with some dongles
232  rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
233  } else {
234  ConfigDescParser<USB_CLASS_WIRELESS_CTRL, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this); // Set class id according to the specification
235  rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
236  }
237  if(rcode) // Check error code
238  goto FailGetConfDescr;
239  if(bNumEP >= BTD_MAX_ENDPOINTS) // All endpoints extracted
240  break;
241  }
242 
244  goto FailUnknownDevice;
245 
246  // Assign epInfo to epinfo pointer - this time all 3 endpoins
247  rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
248  if(rcode)
249  goto FailSetDevTblEntry;
250 
251  // Set Configuration Value
252  rcode = pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bConfNum);
253  if(rcode)
254  goto FailSetConfDescr;
255 
256  hci_num_reset_loops = 100; // only loop 100 times before trying to send the hci reset command
257  hci_counter = 0;
258  hci_state = HCI_INIT_STATE;
259  waitingForConnection = false;
260  bPollEnable = true;
261 
262 #ifdef DEBUG_USB_HOST
263  Notify(PSTR("\r\nBluetooth Dongle Initialized"), 0x80);
264 #endif
265  }
266  return 0; // Successful configuration
267 
268  /* Diagnostic messages */
269 FailSetDevTblEntry:
270 #ifdef DEBUG_USB_HOST
272  goto Fail;
273 #endif
274 
275 FailGetConfDescr:
276 #ifdef DEBUG_USB_HOST
278  goto Fail;
279 #endif
280 
281 FailSetConfDescr:
282 #ifdef DEBUG_USB_HOST
284 #endif
285  goto Fail;
286 
287 FailUnknownDevice:
288 #ifdef DEBUG_USB_HOST
289  NotifyFailUnknownDevice(VID, PID);
290 #endif
291  pUsb->setAddr(bAddress, 0, 0); // Reset address
293 Fail:
294 #ifdef DEBUG_USB_HOST
295  Notify(PSTR("\r\nBTD Init Failed, error code: "), 0x80);
296  NotifyFail(rcode);
297 #endif
298  Release();
299  return rcode;
300 }
301 
302 void BTD::Initialize() {
303  uint8_t i;
304  for(i = 0; i < BTD_MAX_ENDPOINTS; i++) {
305  epInfo[i].epAddr = 0;
306  epInfo[i].maxPktSize = (i) ? 0 : 8;
307  epInfo[i].bmSndToggle = 0;
308  epInfo[i].bmRcvToggle = 0;
310  }
311  for(i = 0; i < BTD_NUM_SERVICES; i++) {
312  if(btService[i])
313  btService[i]->Reset(); // Reset all Bluetooth services
314  }
315 
316  connectToWii = false;
317  incomingWii = false;
318  connectToHIDDevice = false;
319  incomingHIDDevice = false;
320  incomingPSController = false;
321  bAddress = 0; // Clear device address
322  bNumEP = 1; // Must have to be reset to 1
323  qNextPollTime = 0; // Reset next poll time
324  pollInterval = 0;
325  bPollEnable = false; // Don't start polling before dongle is connected
326  simple_pairing_supported = false;
327 }
328 
329 /* Extracts interrupt-IN, bulk-IN, bulk-OUT endpoint information from config descriptor */
330 void BTD::EndpointXtract(uint8_t conf, uint8_t iface __attribute__((unused)), uint8_t alt, uint8_t proto __attribute__((unused)), const USB_ENDPOINT_DESCRIPTOR *pep) {
331  //ErrorMessage<uint8_t>(PSTR("Conf.Val"),conf);
332  //ErrorMessage<uint8_t>(PSTR("Iface Num"),iface);
333  //ErrorMessage<uint8_t>(PSTR("Alt.Set"),alt);
334 
335  if(alt) // Wrong interface - by BT spec, no alt setting
336  return;
337 
338  bConfNum = conf;
339  uint8_t index;
340 
341  if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_INTERRUPT && (pep->bEndpointAddress & 0x80) == 0x80) { // Interrupt In endpoint found
342  index = BTD_EVENT_PIPE;
344  } else if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_BULK) // Bulk endpoint found
345  index = ((pep->bEndpointAddress & 0x80) == 0x80) ? BTD_DATAIN_PIPE : BTD_DATAOUT_PIPE;
346  else
347  return;
348 
349  // Fill the rest of endpoint data structure
350  epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
351  epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
352 #ifdef EXTRADEBUG
354 #endif
355  if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints
356  pollInterval = pep->bInterval;
357  bNumEP++;
358 }
359 
360 void BTD::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr __attribute__((unused))) {
361 #ifdef EXTRADEBUG
362  Notify(PSTR("\r\nEndpoint descriptor:"), 0x80);
363  Notify(PSTR("\r\nLength:\t\t"), 0x80);
364  D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
365  Notify(PSTR("\r\nType:\t\t"), 0x80);
366  D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
367  Notify(PSTR("\r\nAddress:\t"), 0x80);
368  D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
369  Notify(PSTR("\r\nAttributes:\t"), 0x80);
370  D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
371  Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
372  D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
373  Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
374  D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
375 #endif
376 }
377 
378 /* Performs a cleanup after failed Init() attempt */
379 uint8_t BTD::Release() {
380  Initialize(); // Set all variables, endpoint structs etc. to default values
382  return 0;
383 }
384 
385 uint8_t BTD::Poll() {
386  if(!bPollEnable)
387  return 0;
388  if((int32_t)((uint32_t)millis() - qNextPollTime) >= 0L) { // Don't poll if shorter than polling interval
389  qNextPollTime = (uint32_t)millis() + pollInterval; // Set new poll time
390  HCI_event_task(); // Poll the HCI event pipe
391  HCI_task(); // HCI state machine
392  ACL_event_task(); // Poll the ACL input pipe too
393  }
394  return 0;
395 }
396 
398  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
399  if(btService[i])
400  btService[i]->disconnect();
401 };
402 
403 void BTD::HCI_event_task() {
404  uint16_t length = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this
405  uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &length, hcibuf, pollInterval); // Input on endpoint 1
406 
407  if(!rcode || rcode == hrNAK) { // Check for errors
408  switch(hcibuf[0]) { // Switch on event type
409  case EV_COMMAND_COMPLETE:
410  if(!hcibuf[5]) { // Check if command succeeded
411  hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag
412  if((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information
413  hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm
414 #ifdef EXTRADEBUG
416  Notify(PSTR("\r\nHCI version: "), 0x80);
417  D_PrintHex<uint8_t > (hci_version, 0x80);
418  }
419 #endif
421  } else if((hcibuf[3] == 0x04) && (hcibuf[4] == 0x10)) { // Parameters from read local extended features
423 #ifdef EXTRADEBUG
424  Notify(PSTR("\r\nPage number: "), 0x80);
425  D_PrintHex<uint8_t > (hcibuf[6], 0x80);
426  Notify(PSTR("\r\nMaximum page number: "), 0x80);
427  D_PrintHex<uint8_t > (hcibuf[7], 0x80);
428  Notify(PSTR("\r\nExtended LMP features:"), 0x80);
429  for(uint8_t i = 0; i < 8; i++) {
430  Notify(PSTR(" "), 0x80);
431  D_PrintHex<uint8_t > (hcibuf[8 + i], 0x80);
432  }
433 #endif
434  if(hcibuf[6] == 0) { // Page 0
435 #ifdef DEBUG_USB_HOST
436  Notify(PSTR("\r\nDongle "), 0x80);
437 #endif
438  if(hcibuf[8 + 6] & (1U << 3)) {
439  simple_pairing_supported = true;
440 #ifdef DEBUG_USB_HOST
441  Notify(PSTR("supports"), 0x80);
442 #endif
443  } else {
444  simple_pairing_supported = false;
445 #ifdef DEBUG_USB_HOST
446  Notify(PSTR("does NOT support"), 0x80);
447 #endif
448  }
449 #ifdef DEBUG_USB_HOST
450  Notify(PSTR(" secure simple pairing (controller support)"), 0x80);
451 #endif
452  } else if(hcibuf[6] == 1) { // Page 1
453 #ifdef DEBUG_USB_HOST
454  Notify(PSTR("\r\nDongle "), 0x80);
455  if(hcibuf[8 + 0] & (1U << 0))
456  Notify(PSTR("supports"), 0x80);
457  else
458  Notify(PSTR("does NOT support"), 0x80);
459  Notify(PSTR(" secure simple pairing (host support)"), 0x80);
460 #endif
461  }
462  }
463 
465  } else if((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address
466  for(uint8_t i = 0; i < 6; i++)
467  my_bdaddr[i] = hcibuf[6 + i];
469  }
470  }
471  break;
472 
473  case EV_COMMAND_STATUS:
474  if(hcibuf[2]) { // Show status on serial if not OK
475 #ifdef DEBUG_USB_HOST
476  Notify(PSTR("\r\nHCI Command Failed: "), 0x80);
477  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
478  Notify(PSTR("\r\nNum HCI Command Packets: "), 0x80);
479  D_PrintHex<uint8_t > (hcibuf[3], 0x80);
480  Notify(PSTR("\r\nCommand Opcode: "), 0x80);
481  D_PrintHex<uint8_t > (hcibuf[4], 0x80);
482  Notify(PSTR(" "), 0x80);
483  D_PrintHex<uint8_t > (hcibuf[5], 0x80);
484 #endif
485  }
486  break;
487 
488  case EV_INQUIRY_COMPLETE:
489  if(inquiry_counter >= 5 && (pairWithWii || pairWithHIDDevice)) {
490  inquiry_counter = 0;
491 #ifdef DEBUG_USB_HOST
492  if(pairWithWii)
493  Notify(PSTR("\r\nCouldn't find Wiimote"), 0x80);
494  else
495  Notify(PSTR("\r\nCouldn't find HID device"), 0x80);
496 #endif
497  connectToWii = false;
498  pairWithWii = false;
499  connectToHIDDevice = false;
500  pairWithHIDDevice = false;
501  hci_state = HCI_SCANNING_STATE;
502  }
503  inquiry_counter++;
504  break;
505 
506  case EV_INQUIRY_RESULT:
507  if(hcibuf[2]) { // Check that there is more than zero responses
508 #ifdef EXTRADEBUG
509  Notify(PSTR("\r\nNumber of responses: "), 0x80);
510  Notify(hcibuf[2], 0x80);
511 #endif
512  for(uint8_t i = 0; i < hcibuf[2]; i++) {
513  uint8_t offset = 8 * hcibuf[2] + 3 * i;
514 
515  for(uint8_t j = 0; j < 3; j++)
516  classOfDevice[j] = hcibuf[j + 4 + offset];
517 
518 #ifdef EXTRADEBUG
519  Notify(PSTR("\r\nClass of device: "), 0x80);
520  D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
521  Notify(PSTR(" "), 0x80);
522  D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
523  Notify(PSTR(" "), 0x80);
524  D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
525 #endif
526 
527  if(pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] == 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information
528  checkRemoteName = true; // Check remote name to distinguish between the different controllers
529 
530  for(uint8_t j = 0; j < 6; j++)
531  disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
532 
534  break;
535  } else if(pairWithHIDDevice && (classOfDevice[1] & 0x0F) == 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
536 #ifdef DEBUG_USB_HOST
537  checkRemoteName = true; // Used to print name in the serial monitor if serial debugging is enabled
538 
539  if(classOfDevice[0] & 0x80)
540  Notify(PSTR("\r\nMouse found"), 0x80);
541  if(classOfDevice[0] & 0x40)
542  Notify(PSTR("\r\nKeyboard found"), 0x80);
543  if(classOfDevice[0] & 0x08)
544  Notify(PSTR("\r\nGamepad found"), 0x80);
545 #endif
546  for(uint8_t j = 0; j < 6; j++)
547  disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
548 
550  break;
551  }
552  }
553  }
554  break;
555 
556  case EV_CONNECT_COMPLETE:
558  if(!hcibuf[2]) { // Check if connected OK
559 #ifdef EXTRADEBUG
560  Notify(PSTR("\r\nConnection established"), 0x80);
561 #endif
562  hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // Store the handle for the ACL connection
563  hci_set_flag(HCI_FLAG_CONNECT_COMPLETE); // Set connection complete flag
564  } else {
565  hci_state = HCI_CHECK_DEVICE_SERVICE;
566 #ifdef DEBUG_USB_HOST
567  Notify(PSTR("\r\nConnection Failed: "), 0x80);
568  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
569 #endif
570  }
571  break;
572 
574  if(!hcibuf[2]) { // Check if disconnected OK
575  hci_set_flag(HCI_FLAG_DISCONNECT_COMPLETE); // Set disconnect command complete flag
576  hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); // Clear connection complete flag
577  }
578  break;
579 
581  if(!hcibuf[2]) { // Check if reading is OK
582  for(uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) {
583  remote_name[i] = hcibuf[9 + i];
584  if(remote_name[i] == '\0') // End of string
585  break;
586  }
587  // TODO: Always set '\0' in remote name!
589  }
590  break;
591 
592  case EV_INCOMING_CONNECT:
593  for(uint8_t i = 0; i < 6; i++)
594  disc_bdaddr[i] = hcibuf[i + 2];
595 
596  for(uint8_t i = 0; i < 3; i++)
597  classOfDevice[i] = hcibuf[i + 8];
598 
599  if((classOfDevice[1] & 0x0F) == 0x05 && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad
600 #ifdef DEBUG_USB_HOST
601  if(classOfDevice[0] & 0x80)
602  Notify(PSTR("\r\nMouse is connecting"), 0x80);
603  if(classOfDevice[0] & 0x40)
604  Notify(PSTR("\r\nKeyboard is connecting"), 0x80);
605  if(classOfDevice[0] & 0x08)
606  Notify(PSTR("\r\nGamepad is connecting"), 0x80);
607 #endif
608  incomingHIDDevice = true;
609  }
610 
611 #ifdef EXTRADEBUG
612  Notify(PSTR("\r\nClass of device: "), 0x80);
613  D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
614  Notify(PSTR(" "), 0x80);
615  D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
616  Notify(PSTR(" "), 0x80);
617  D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
618 #endif
620  break;
621 
622  case EV_PIN_CODE_REQUEST:
623  if(pairWithWii) {
624 #ifdef DEBUG_USB_HOST
625  Notify(PSTR("\r\nPairing with Wiimote"), 0x80);
626 #endif
628  } else if(btdPin != NULL) {
629 #ifdef DEBUG_USB_HOST
630  Notify(PSTR("\r\nBluetooth pin is set too: "), 0x80);
631  NotifyStr(btdPin, 0x80);
632 #endif
634  } else {
635 #ifdef DEBUG_USB_HOST
636  Notify(PSTR("\r\nNo pin was set"), 0x80);
637 #endif
639  }
640  break;
641 
642  case EV_LINK_KEY_REQUEST:
643 #ifdef DEBUG_USB_HOST
644  Notify(PSTR("\r\nReceived Key Request"), 0x80);
645 #endif
647  break;
648 
650  if(!hcibuf[2]) { // Check if pairing was successful
651  if(pairWithWii && !connectToWii) {
652 #ifdef DEBUG_USB_HOST
653  Notify(PSTR("\r\nPairing successful with Wiimote"), 0x80);
654 #endif
655  connectToWii = true; // Used to indicate to the Wii service, that it should connect to this device
656  } else if(pairWithHIDDevice && !connectToHIDDevice) {
657 #ifdef DEBUG_USB_HOST
658  Notify(PSTR("\r\nPairing successful with HID device"), 0x80);
659 #endif
660  connectToHIDDevice = true; // Used to indicate to the BTHID service, that it should connect to this device
661  } else {
662 #ifdef EXTRADEBUG
663  Notify(PSTR("\r\nPairing was successful"), 0x80);
664 #endif
665  }
666  } else {
667 #ifdef DEBUG_USB_HOST
668  Notify(PSTR("\r\nPairing Failed: "), 0x80);
669  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
670 #endif
672  hci_state = HCI_DISCONNECT_STATE;
673  }
674  break;
675 
677 #ifdef DEBUG_USB_HOST
678  Notify(PSTR("\r\nReceived IO Capability Request"), 0x80);
679 #endif
681  break;
682 
684 #ifdef EXTRADEBUG
685  Notify(PSTR("\r\nReceived IO Capability Response: "), 0x80);
686  Notify(PSTR("\r\nIO capability: "), 0x80);
687  D_PrintHex<uint8_t > (hcibuf[8], 0x80);
688  Notify(PSTR("\r\nOOB data present: "), 0x80);
689  D_PrintHex<uint8_t > (hcibuf[9], 0x80);
690  Notify(PSTR("\r\nAuthentication request: "), 0x80);
691  D_PrintHex<uint8_t > (hcibuf[10], 0x80);
692 #endif
693  break;
694 
696 #ifdef DEBUG_USB_HOST
697  Notify(PSTR("\r\nUser confirmation Request"), 0x80);
698 #ifdef EXTRADEBUG
699  Notify(PSTR(": \r\nNumeric value: "), 0x80);
700  for(uint8_t i = 0; i < 4; i++) {
701  Notify(PSTR(" "), 0x80);
702  D_PrintHex<uint8_t > (hcibuf[8 + i], 0x80);
703  }
704 #endif
705 #endif
706  // Simply confirm the connection, as the host has no "NoInputNoOutput" capabilities
708  break;
709 
711 #ifdef EXTRADEBUG
712  if(!hcibuf[2]) { // Check if connected OK
713  Notify(PSTR("\r\nSimple Pairing succeeded"), 0x80);
714  } else {
715  Notify(PSTR("\r\nSimple Pairing failed: "), 0x80);
716  D_PrintHex<uint8_t > (hcibuf[2], 0x80);
717  }
718 #endif
719  break;
720 
721  /* We will just ignore the following events */
722  case EV_MAX_SLOTS_CHANGE:
723  case EV_NUM_COMPLETE_PKT:
724  break;
725  case EV_ROLE_CHANGED:
727  case EV_LOOPBACK_COMMAND:
734 #ifdef EXTRADEBUG
735  if(hcibuf[0] != 0x00) {
736  Notify(PSTR("\r\nIgnore HCI Event: "), 0x80);
737  D_PrintHex<uint8_t > (hcibuf[0], 0x80);
738  }
739 #endif
740  break;
741 #ifdef EXTRADEBUG
742  default:
743  if(hcibuf[0] != 0x00) {
744  Notify(PSTR("\r\nUnmanaged HCI Event: "), 0x80);
745  D_PrintHex<uint8_t > (hcibuf[0], 0x80);
746  Notify(PSTR(", data: "), 0x80);
747  for(uint16_t i = 0; i < hcibuf[1]; i++) {
748  D_PrintHex<uint8_t > (hcibuf[2 + i], 0x80);
749  Notify(PSTR(" "), 0x80);
750  }
751  }
752  break;
753 #endif
754  } // Switch
755  }
756 #ifdef EXTRADEBUG
757  else {
758  Notify(PSTR("\r\nHCI event error: "), 0x80);
759  D_PrintHex<uint8_t > (rcode, 0x80);
760  }
761 #endif
762 }
763 
764 /* Poll Bluetooth and print result */
765 void BTD::HCI_task() {
766  switch(hci_state) {
767  case HCI_INIT_STATE:
768  hci_counter++;
769  if(hci_counter > hci_num_reset_loops) { // wait until we have looped x times to clear any old events
770  hci_reset();
771  hci_state = HCI_RESET_STATE;
772  hci_counter = 0;
773  }
774  break;
775 
776  case HCI_RESET_STATE:
777  hci_counter++;
779  hci_counter = 0;
780 #ifdef DEBUG_USB_HOST
781  Notify(PSTR("\r\nHCI Reset complete"), 0x80);
782 #endif
783  hci_state = HCI_CLASS_STATE;
785  } else if(hci_counter > hci_num_reset_loops) {
786  hci_num_reset_loops *= 10;
787  if(hci_num_reset_loops > 2000)
788  hci_num_reset_loops = 2000;
789 #ifdef DEBUG_USB_HOST
790  Notify(PSTR("\r\nNo response to HCI Reset"), 0x80);
791 #endif
792  hci_state = HCI_INIT_STATE;
793  hci_counter = 0;
794  }
795  break;
796 
797  case HCI_CLASS_STATE:
799 #ifdef DEBUG_USB_HOST
800  Notify(PSTR("\r\nWrite class of device"), 0x80);
801 #endif
802  hci_state = HCI_BDADDR_STATE;
803  hci_read_bdaddr();
804  }
805  break;
806 
807  case HCI_BDADDR_STATE:
809 #ifdef DEBUG_USB_HOST
810  Notify(PSTR("\r\nLocal Bluetooth Address: "), 0x80);
811  for(int8_t i = 5; i > 0; i--) {
812  D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
813  Notify(PSTR(":"), 0x80);
814  }
815  D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
816 #endif
818  hci_state = HCI_LOCAL_VERSION_STATE;
819  }
820  break;
821 
822  case HCI_LOCAL_VERSION_STATE: // The local version is used by the PS3BT class
824  if(btdName != NULL) {
826  hci_state = HCI_WRITE_NAME_STATE;
827  } else if(useSimplePairing) {
828  hci_read_local_extended_features(0); // "Requests the normal LMP features as returned by Read_Local_Supported_Features"
829  //hci_read_local_extended_features(1); // Read page 1
831  } else
832  hci_state = HCI_CHECK_DEVICE_SERVICE;
833  }
834  break;
835 
838 #ifdef DEBUG_USB_HOST
839  Notify(PSTR("\r\nThe name was set to: "), 0x80);
840  NotifyStr(btdName, 0x80);
841 #endif
842  if(useSimplePairing) {
843  hci_read_local_extended_features(0); // "Requests the normal LMP features as returned by Read_Local_Supported_Features"
844  //hci_read_local_extended_features(1); // Read page 1
846  } else
847  hci_state = HCI_CHECK_DEVICE_SERVICE;
848  }
849  break;
850 
853  if(simple_pairing_supported) {
855  hci_state = HCI_WRITE_SIMPLE_PAIRING_STATE;
856  } else
857  hci_state = HCI_CHECK_DEVICE_SERVICE;
858  }
859  break;
860 
863 #ifdef DEBUG_USB_HOST
864  Notify(PSTR("\r\nSimple pairing was enabled"), 0x80);
865 #endif
867  hci_state = HCI_SET_EVENT_MASK_STATE;
868  }
869  break;
870 
873 #ifdef DEBUG_USB_HOST
874  Notify(PSTR("\r\nSet event mask completed"), 0x80);
875 #endif
876  hci_state = HCI_CHECK_DEVICE_SERVICE;
877  }
878  break;
879 
881  if(pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote
882 #ifdef DEBUG_USB_HOST
883  if(pairWithWii)
884  Notify(PSTR("\r\nStarting inquiry\r\nPress 1 & 2 on the Wiimote\r\nOr press the SYNC button if you are using a Wii U Pro Controller or a Wii Balance Board"), 0x80);
885  else
886  Notify(PSTR("\r\nPlease enable discovery of your device"), 0x80);
887 #endif
888  hci_inquiry();
889  hci_state = HCI_INQUIRY_STATE;
890  } else
891  hci_state = HCI_SCANNING_STATE; // Don't try to connect to a Wiimote
892  break;
893 
894  case HCI_INQUIRY_STATE:
896  hci_inquiry_cancel(); // Stop inquiry
897 #ifdef DEBUG_USB_HOST
898  if(pairWithWii)
899  Notify(PSTR("\r\nWiimote found"), 0x80);
900  else
901  Notify(PSTR("\r\nHID device found"), 0x80);
902 
903  Notify(PSTR("\r\nNow just create the instance like so:"), 0x80);
904  if(pairWithWii)
905  Notify(PSTR("\r\nWII Wii(&Btd);"), 0x80);
906  else
907  Notify(PSTR("\r\nBTHID bthid(&Btd);"), 0x80);
908 
909  Notify(PSTR("\r\nAnd then press any button on the "), 0x80);
910  if(pairWithWii)
911  Notify(PSTR("Wiimote"), 0x80);
912  else
913  Notify(PSTR("device"), 0x80);
914 #endif
915  if(checkRemoteName) {
916  hci_remote_name(); // We need to know the name to distinguish between the Wiimote, the new Wiimote with Motion Plus inside, a Wii U Pro Controller and a Wii Balance Board
917  hci_state = HCI_REMOTE_NAME_STATE;
918  } else
919  hci_state = HCI_CONNECT_DEVICE_STATE;
920  }
921  break;
922 
925 #ifdef DEBUG_USB_HOST
926  if(pairWithWii)
927  Notify(PSTR("\r\nConnecting to Wiimote"), 0x80);
928  else
929  Notify(PSTR("\r\nConnecting to HID device"), 0x80);
930 #endif
931  checkRemoteName = false;
932  hci_connect();
933  hci_state = HCI_CONNECTED_DEVICE_STATE;
934  }
935  break;
936 
940 #ifdef DEBUG_USB_HOST
941  if(pairWithWii)
942  Notify(PSTR("\r\nConnected to Wiimote"), 0x80);
943  else
944  Notify(PSTR("\r\nConnected to HID device"), 0x80);
945 #endif
946  hci_authentication_request(); // This will start the pairing with the device
947  hci_state = HCI_SCANNING_STATE;
948  } else {
949 #ifdef DEBUG_USB_HOST
950  Notify(PSTR("\r\nTrying to connect one more time..."), 0x80);
951 #endif
952  hci_connect(); // Try to connect one more time
953  }
954  }
955  break;
956 
957  case HCI_SCANNING_STATE:
959 #ifdef DEBUG_USB_HOST
960  Notify(PSTR("\r\nWait For Incoming Connection Request"), 0x80);
961 #endif
963  waitingForConnection = true;
964  hci_state = HCI_CONNECT_IN_STATE;
965  }
966  break;
967 
970  waitingForConnection = false;
971 #ifdef DEBUG_USB_HOST
972  Notify(PSTR("\r\nIncoming Connection Request"), 0x80);
973 #endif
974  hci_remote_name();
975  hci_state = HCI_REMOTE_NAME_STATE;
977  hci_state = HCI_DISCONNECT_STATE;
978  break;
979 
982 #ifdef DEBUG_USB_HOST
983  Notify(PSTR("\r\nRemote Name: "), 0x80);
984  for(uint8_t i = 0; i < strlen(remote_name); i++)
985  Notifyc(remote_name[i], 0x80);
986 #endif
987  if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) {
988  incomingWii = true;
989  motionPlusInside = false;
990  wiiUProController = false;
991  pairWiiUsingSync = false;
992 #ifdef DEBUG_USB_HOST
993  Notify(PSTR("\r\nWiimote is connecting"), 0x80);
994 #endif
995  if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) {
996 #ifdef DEBUG_USB_HOST
997  Notify(PSTR(" with Motion Plus Inside"), 0x80);
998 #endif
999  motionPlusInside = true;
1000  } else if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) {
1001 #ifdef DEBUG_USB_HOST
1002  Notify(PSTR(" - Wii U Pro Controller"), 0x80);
1003 #endif
1004  wiiUProController = motionPlusInside = pairWiiUsingSync = true;
1005  } else if(strncmp((const char*)remote_name, "Nintendo RVL-WBC-01", 19) == 0) {
1006 #ifdef DEBUG_USB_HOST
1007  Notify(PSTR(" - Wii Balance Board"), 0x80);
1008 #endif
1009  pairWiiUsingSync = true;
1010  }
1011  }
1012  if(classOfDevice[2] == 0 && classOfDevice[1] == 0x25 && classOfDevice[0] == 0x08 && strncmp((const char*)remote_name, "Wireless Controller", 19) == 0) {
1013 #ifdef DEBUG_USB_HOST
1014  Notify(PSTR("\r\nPS4/PS5 controller is connecting"), 0x80);
1015 #endif
1016  incomingPSController = true;
1017  }
1018  if((pairWithWii || pairWithHIDDevice) && checkRemoteName)
1019  hci_state = HCI_CONNECT_DEVICE_STATE;
1020  else {
1022  hci_state = HCI_CONNECTED_STATE;
1023  }
1024  }
1025  break;
1026 
1027  case HCI_CONNECTED_STATE:
1029 #ifdef DEBUG_USB_HOST
1030  Notify(PSTR("\r\nConnected to Device: "), 0x80);
1031  for(int8_t i = 5; i > 0; i--) {
1032  D_PrintHex<uint8_t > (disc_bdaddr[i], 0x80);
1033  Notify(PSTR(":"), 0x80);
1034  }
1035  D_PrintHex<uint8_t > (disc_bdaddr[0], 0x80);
1036 #endif
1037  if(incomingPSController)
1038  connectToHIDDevice = true; // We should always connect to the PS4/PS5 controller
1039 
1040  // Clear these flags for a new connection
1041  l2capConnectionClaimed = false;
1042  sdpConnectionClaimed = false;
1043  rfcommConnectionClaimed = false;
1044 
1045  hci_event_flag = 0;
1046  hci_state = HCI_DONE_STATE;
1047  }
1048  break;
1049 
1050  case HCI_DONE_STATE:
1051  hci_counter++;
1052  if(hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started
1053  hci_counter = 0;
1054  hci_state = HCI_SCANNING_STATE;
1055  }
1056  break;
1057 
1058  case HCI_DISCONNECT_STATE:
1060 #ifdef DEBUG_USB_HOST
1061  Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80);
1062 #endif
1063  hci_event_flag = 0; // Clear all flags
1064 
1065  // Reset all buffers
1066  memset(hcibuf, 0, BULK_MAXPKTSIZE);
1067  memset(l2capinbuf, 0, BULK_MAXPKTSIZE);
1068 
1069  connectToWii = incomingWii = pairWithWii = false;
1070  connectToHIDDevice = incomingHIDDevice = pairWithHIDDevice = checkRemoteName = false;
1071  incomingPSController = false;
1072 
1073  hci_state = HCI_SCANNING_STATE;
1074  }
1075  break;
1076  default:
1077  break;
1078  }
1079 }
1080 
1081 void BTD::ACL_event_task() {
1082  uint16_t length = BULK_MAXPKTSIZE;
1083  uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf, pollInterval); // Input on endpoint 2
1084 
1085  if(!rcode) { // Check for errors
1086  if(length > 0) { // Check if any data was read
1087  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
1088  if(btService[i])
1089  btService[i]->ACLData(l2capinbuf);
1090  }
1091  }
1092  }
1093 #ifdef EXTRADEBUG
1094  else if(rcode != hrNAK) {
1095  Notify(PSTR("\r\nACL data in error: "), 0x80);
1096  D_PrintHex<uint8_t > (rcode, 0x80);
1097  }
1098 #endif
1099  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
1100  if(btService[i])
1101  btService[i]->Run();
1102 }
1103 
1104 /************************************************************/
1105 /* HCI Commands */
1106 
1107 /************************************************************/
1108 void BTD::HCI_Command(uint8_t* data, uint16_t nbytes) {
1110  pUsb->ctrlReq(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, 0x00, 0x00, 0x00, 0x00, nbytes, nbytes, data, NULL);
1111 }
1112 
1114  hci_event_flag = 0; // Clear all the flags
1115  hcibuf[0] = 0x03; // HCI OCF = 3
1116  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1117  hcibuf[2] = 0x00;
1118 
1119  HCI_Command(hcibuf, 3);
1120 }
1121 
1124  hcibuf[0] = 0x1A; // HCI OCF = 1A
1125  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1126  hcibuf[2] = 0x01; // parameter length = 1
1127  if(btdName != NULL)
1128  hcibuf[3] = 0x03; // Inquiry Scan enabled. Page Scan enabled.
1129  else
1130  hcibuf[3] = 0x02; // Inquiry Scan disabled. Page Scan enabled.
1131 
1132  HCI_Command(hcibuf, 4);
1133 }
1134 
1136  hcibuf[0] = 0x1A; // HCI OCF = 1A
1137  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1138  hcibuf[2] = 0x01; // parameter length = 1
1139  hcibuf[3] = 0x00; // Inquiry Scan disabled. Page Scan disabled.
1140 
1141  HCI_Command(hcibuf, 4);
1142 }
1143 
1146  hcibuf[0] = 0x09; // HCI OCF = 9
1147  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
1148  hcibuf[2] = 0x00;
1149 
1150  HCI_Command(hcibuf, 3);
1151 }
1152 
1155  hcibuf[0] = 0x01; // HCI OCF = 1
1156  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
1157  hcibuf[2] = 0x00;
1158 
1159  HCI_Command(hcibuf, 3);
1160 }
1161 
1162 void BTD::hci_read_local_extended_features(uint8_t page_number) {
1164  hcibuf[0] = 0x04; // HCI OCF = 4
1165  hcibuf[1] = 0x04 << 2; // HCI OGF = 4
1166  hcibuf[2] = 0x01; // parameter length = 1
1167  hcibuf[3] = page_number;
1168 
1169  HCI_Command(hcibuf, 4);
1170 }
1171 
1174  hcibuf[0] = 0x09; // HCI OCF = 9
1175  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1176  hcibuf[2] = 0x07; // parameter length 7
1177  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1178  hcibuf[4] = disc_bdaddr[1];
1179  hcibuf[5] = disc_bdaddr[2];
1180  hcibuf[6] = disc_bdaddr[3];
1181  hcibuf[7] = disc_bdaddr[4];
1182  hcibuf[8] = disc_bdaddr[5];
1183  hcibuf[9] = 0x00; // Switch role to master
1184 
1185  HCI_Command(hcibuf, 10);
1186 }
1187 
1190  hcibuf[0] = 0x19; // HCI OCF = 19
1191  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1192  hcibuf[2] = 0x0A; // parameter length = 10
1193  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1194  hcibuf[4] = disc_bdaddr[1];
1195  hcibuf[5] = disc_bdaddr[2];
1196  hcibuf[6] = disc_bdaddr[3];
1197  hcibuf[7] = disc_bdaddr[4];
1198  hcibuf[8] = disc_bdaddr[5];
1199  hcibuf[9] = 0x01; // Page Scan Repetition Mode
1200  hcibuf[10] = 0x00; // Reserved
1201  hcibuf[11] = 0x00; // Clock offset - low byte
1202  hcibuf[12] = 0x00; // Clock offset - high byte
1203 
1204  HCI_Command(hcibuf, 13);
1205 }
1206 
1207 void BTD::hci_write_local_name(const char* name) {
1208  hcibuf[0] = 0x13; // HCI OCF = 13
1209  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1210  hcibuf[2] = strlen(name) + 1; // parameter length = the length of the string + end byte
1211  uint8_t i;
1212  for(i = 0; i < strlen(name); i++)
1213  hcibuf[i + 3] = name[i];
1214  hcibuf[i + 3] = 0x00; // End of string
1215 
1216  HCI_Command(hcibuf, 4 + strlen(name));
1217 }
1218 
1220  hcibuf[0] = 0x01; // HCI OCF = 01
1221  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1222  hcibuf[2] = 0x08;
1223  // The first 6 bytes are the default of 1FFF FFFF FFFF
1224  // However we need to set bits 48-55 for simple pairing to work
1225  hcibuf[3] = 0xFF;
1226  hcibuf[4] = 0xFF;
1227  hcibuf[5] = 0xFF;
1228  hcibuf[6] = 0xFF;
1229  hcibuf[7] = 0xFF;
1230  hcibuf[8] = 0x1F;
1231  hcibuf[9] = 0xFF; // Enable bits 48-55 used for simple pairing
1232  hcibuf[10] = 0x00;
1233 
1234  HCI_Command(hcibuf, 11);
1235 }
1236 
1238  hcibuf[0] = 0x56; // HCI OCF = 56
1239  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1240  hcibuf[2] = 1; // parameter length = 1
1241  hcibuf[3] = enable ? 1 : 0;
1242 
1243  HCI_Command(hcibuf, 4);
1244 }
1245 
1248  hcibuf[0] = 0x01;
1249  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1250  hcibuf[2] = 0x05; // Parameter Total Length = 5
1251  hcibuf[3] = 0x33; // LAP: Genera/Unlimited Inquiry Access Code (GIAC = 0x9E8B33) - see https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
1252  hcibuf[4] = 0x8B;
1253  hcibuf[5] = 0x9E;
1254  hcibuf[6] = 0x30; // Inquiry time = 61.44 sec (maximum)
1255  hcibuf[7] = 0x0A; // 10 number of responses
1256 
1257  HCI_Command(hcibuf, 8);
1258 }
1259 
1261  hcibuf[0] = 0x02;
1262  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1263  hcibuf[2] = 0x00; // Parameter Total Length = 0
1264 
1265  HCI_Command(hcibuf, 3);
1266 }
1267 
1269  hci_connect(disc_bdaddr); // Use last discovered device
1270 }
1271 
1272 void BTD::hci_connect(uint8_t *bdaddr) {
1274  hcibuf[0] = 0x05; // HCI OCF = 5
1275  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1276  hcibuf[2] = 0x0D; // parameter Total Length = 13
1277  hcibuf[3] = bdaddr[0]; // 6 octet bdaddr (LSB)
1278  hcibuf[4] = bdaddr[1];
1279  hcibuf[5] = bdaddr[2];
1280  hcibuf[6] = bdaddr[3];
1281  hcibuf[7] = bdaddr[4];
1282  hcibuf[8] = bdaddr[5];
1283  hcibuf[9] = 0x18; // DM1 or DH1 may be used
1284  hcibuf[10] = 0xCC; // DM3, DH3, DM5, DH5 may be used
1285  hcibuf[11] = 0x01; // Page repetition mode R1
1286  hcibuf[12] = 0x00; // Reserved
1287  hcibuf[13] = 0x00; // Clock offset
1288  hcibuf[14] = 0x00; // Invalid clock offset
1289  hcibuf[15] = 0x00; // Do not allow role switch
1290 
1291  HCI_Command(hcibuf, 16);
1292 }
1293 
1295  hcibuf[0] = 0x0D; // HCI OCF = 0D
1296  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1297  hcibuf[2] = 0x17; // parameter length 23
1298  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1299  hcibuf[4] = disc_bdaddr[1];
1300  hcibuf[5] = disc_bdaddr[2];
1301  hcibuf[6] = disc_bdaddr[3];
1302  hcibuf[7] = disc_bdaddr[4];
1303  hcibuf[8] = disc_bdaddr[5];
1304  if(pairWithWii) {
1305  hcibuf[9] = 6; // Pin length is the length of the Bluetooth address
1306  if(pairWiiUsingSync) {
1307 #ifdef DEBUG_USB_HOST
1308  Notify(PSTR("\r\nPairing with Wii controller via SYNC"), 0x80);
1309 #endif
1310  for(uint8_t i = 0; i < 6; i++)
1311  hcibuf[10 + i] = my_bdaddr[i]; // The pin is the Bluetooth dongles Bluetooth address backwards
1312  } else {
1313  for(uint8_t i = 0; i < 6; i++)
1314  hcibuf[10 + i] = disc_bdaddr[i]; // The pin is the Wiimote's Bluetooth address backwards
1315  }
1316  for(uint8_t i = 16; i < 26; i++)
1317  hcibuf[i] = 0x00; // The rest should be 0
1318  } else {
1319  hcibuf[9] = strlen(btdPin); // Length of pin
1320  uint8_t i;
1321  for(i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16
1322  hcibuf[i + 10] = btdPin[i];
1323  for(; i < 16; i++)
1324  hcibuf[i + 10] = 0x00; // The rest should be 0
1325  }
1326 
1327  HCI_Command(hcibuf, 26);
1328 }
1329 
1331  hcibuf[0] = 0x0E; // HCI OCF = 0E
1332  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1333  hcibuf[2] = 0x06; // parameter length 6
1334  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1335  hcibuf[4] = disc_bdaddr[1];
1336  hcibuf[5] = disc_bdaddr[2];
1337  hcibuf[6] = disc_bdaddr[3];
1338  hcibuf[7] = disc_bdaddr[4];
1339  hcibuf[8] = disc_bdaddr[5];
1340 
1341  HCI_Command(hcibuf, 9);
1342 }
1343 
1345  hcibuf[0] = 0x0C; // HCI OCF = 0C
1346  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1347  hcibuf[2] = 0x06; // parameter length 6
1348  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1349  hcibuf[4] = disc_bdaddr[1];
1350  hcibuf[5] = disc_bdaddr[2];
1351  hcibuf[6] = disc_bdaddr[3];
1352  hcibuf[7] = disc_bdaddr[4];
1353  hcibuf[8] = disc_bdaddr[5];
1354 
1355  HCI_Command(hcibuf, 9);
1356 }
1357 
1359  hcibuf[0] = 0x2B; // HCI OCF = 2B
1360  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1361  hcibuf[2] = 0x09;
1362  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1363  hcibuf[4] = disc_bdaddr[1];
1364  hcibuf[5] = disc_bdaddr[2];
1365  hcibuf[6] = disc_bdaddr[3];
1366  hcibuf[7] = disc_bdaddr[4];
1367  hcibuf[8] = disc_bdaddr[5];
1368  hcibuf[9] = 0x03; // NoInputNoOutput
1369  hcibuf[10] = 0x00; // OOB authentication data not present
1370  hcibuf[11] = 0x00; // MITM Protection Not Required – No Bonding. Numeric comparison with automatic accept allowed
1371 
1372  HCI_Command(hcibuf, 12);
1373 }
1374 
1376  hcibuf[0] = 0x2C; // HCI OCF = 2C
1377  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1378  hcibuf[2] = 0x06; // parameter length 6
1379  hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
1380  hcibuf[4] = disc_bdaddr[1];
1381  hcibuf[5] = disc_bdaddr[2];
1382  hcibuf[6] = disc_bdaddr[3];
1383  hcibuf[7] = disc_bdaddr[4];
1384  hcibuf[8] = disc_bdaddr[5];
1385 
1386  HCI_Command(hcibuf, 9);
1387 }
1388 
1390  hcibuf[0] = 0x11; // HCI OCF = 11
1391  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1392  hcibuf[2] = 0x02; // parameter length = 2
1393  hcibuf[3] = (uint8_t)(hci_handle & 0xFF); //connection handle - low byte
1394  hcibuf[4] = (uint8_t)((hci_handle >> 8) & 0x0F); //connection handle - high byte
1395 
1396  HCI_Command(hcibuf, 5);
1397 }
1398 
1399 void BTD::hci_disconnect(uint16_t handle) { // This is called by the different services
1401  hcibuf[0] = 0x06; // HCI OCF = 6
1402  hcibuf[1] = 0x01 << 2; // HCI OGF = 1
1403  hcibuf[2] = 0x03; // parameter length = 3
1404  hcibuf[3] = (uint8_t)(handle & 0xFF); //connection handle - low byte
1405  hcibuf[4] = (uint8_t)((handle >> 8) & 0x0F); //connection handle - high byte
1406  hcibuf[5] = 0x13; // reason
1407 
1408  HCI_Command(hcibuf, 6);
1409 }
1410 
1411 void BTD::hci_write_class_of_device() { // See http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
1412  hcibuf[0] = 0x24; // HCI OCF = 24
1413  hcibuf[1] = 0x03 << 2; // HCI OGF = 3
1414  hcibuf[2] = 0x03; // parameter length = 3
1415  hcibuf[3] = 0x04; // Robot
1416  hcibuf[4] = 0x08; // Toy
1417  hcibuf[5] = 0x00;
1418 
1419  HCI_Command(hcibuf, 6);
1420 }
1421 /*******************************************************************
1422  * *
1423  * HCI ACL Data Packet *
1424  * *
1425  * buf[0] buf[1] buf[2] buf[3]
1426  * 0 4 8 11 12 16 24 31 MSB
1427  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1428  * | HCI Handle |PB |BC | Data Total Length | HCI ACL Data Packet
1429  * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1430  *
1431  * buf[4] buf[5] buf[6] buf[7]
1432  * 0 8 16 31 MSB
1433  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1434  * | Length | Channel ID | Basic L2CAP header
1435  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1436  *
1437  * buf[8] buf[9] buf[10] buf[11]
1438  * 0 8 16 31 MSB
1439  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
1440  * | Code | Identifier | Length | Control frame (C-frame)
1441  * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-. (signaling packet format)
1442  */
1443 /************************************************************/
1444 /* L2CAP Commands */
1445 
1446 /************************************************************/
1447 void BTD::L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh) {
1448  uint8_t buf[8 + nbytes];
1449  buf[0] = (uint8_t)(handle & 0xff); // HCI handle with PB,BC flag
1450  buf[1] = (uint8_t)(((handle >> 8) & 0x0f) | 0x20);
1451  buf[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
1452  buf[3] = (uint8_t)((4 + nbytes) >> 8);
1453  buf[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
1454  buf[5] = (uint8_t)(nbytes >> 8);
1455  buf[6] = channelLow;
1456  buf[7] = channelHigh;
1457 
1458  for(uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame
1459  buf[8 + i] = data[i];
1460 
1461  uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ BTD_DATAOUT_PIPE ].epAddr, (8 + nbytes), buf);
1462  if(rcode) {
1463  delay(100); // This small delay prevents it from overflowing if it fails
1464 #ifdef DEBUG_USB_HOST
1465  Notify(PSTR("\r\nError sending L2CAP message: 0x"), 0x80);
1466  D_PrintHex<uint8_t > (rcode, 0x80);
1467  Notify(PSTR(" - Channel ID: "), 0x80);
1468  D_PrintHex<uint8_t > (channelHigh, 0x80);
1469  Notify(PSTR(" "), 0x80);
1470  D_PrintHex<uint8_t > (channelLow, 0x80);
1471 #endif
1472  }
1473 }
1474 
1475 void BTD::l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm) {
1476  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
1477  l2capoutbuf[1] = rxid; // Identifier
1478  l2capoutbuf[2] = 0x04; // Length
1479  l2capoutbuf[3] = 0x00;
1480  l2capoutbuf[4] = (uint8_t)(psm & 0xff); // PSM
1481  l2capoutbuf[5] = (uint8_t)(psm >> 8);
1482  l2capoutbuf[6] = scid[0]; // Source CID
1483  l2capoutbuf[7] = scid[1];
1484 
1485  L2CAP_Command(handle, l2capoutbuf, 8);
1486 }
1487 
1488 void BTD::l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result) {
1489  l2capoutbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
1490  l2capoutbuf[1] = rxid; // Identifier
1491  l2capoutbuf[2] = 0x08; // Length
1492  l2capoutbuf[3] = 0x00;
1493  l2capoutbuf[4] = dcid[0]; // Destination CID
1494  l2capoutbuf[5] = dcid[1];
1495  l2capoutbuf[6] = scid[0]; // Source CID
1496  l2capoutbuf[7] = scid[1];
1497  l2capoutbuf[8] = result; // Result: Pending or Success
1498  l2capoutbuf[9] = 0x00;
1499  l2capoutbuf[10] = 0x00; // No further information
1500  l2capoutbuf[11] = 0x00;
1501 
1502  L2CAP_Command(handle, l2capoutbuf, 12);
1503 }
1504 
1505 void BTD::l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid) {
1506  l2capoutbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
1507  l2capoutbuf[1] = rxid; // Identifier
1508  l2capoutbuf[2] = 0x08; // Length
1509  l2capoutbuf[3] = 0x00;
1510  l2capoutbuf[4] = dcid[0]; // Destination CID
1511  l2capoutbuf[5] = dcid[1];
1512  l2capoutbuf[6] = 0x00; // Flags
1513  l2capoutbuf[7] = 0x00;
1514  l2capoutbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
1515  l2capoutbuf[9] = 0x02; // Config Opt: length
1516  l2capoutbuf[10] = 0xFF; // MTU
1517  l2capoutbuf[11] = 0xFF;
1518 
1519  L2CAP_Command(handle, l2capoutbuf, 12);
1520 }
1521 
1522 void BTD::l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid) {
1523  l2capoutbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
1524  l2capoutbuf[1] = rxid; // Identifier
1525  l2capoutbuf[2] = 0x0A; // Length
1526  l2capoutbuf[3] = 0x00;
1527  l2capoutbuf[4] = scid[0]; // Source CID
1528  l2capoutbuf[5] = scid[1];
1529  l2capoutbuf[6] = 0x00; // Flag
1530  l2capoutbuf[7] = 0x00;
1531  l2capoutbuf[8] = 0x00; // Result
1532  l2capoutbuf[9] = 0x00;
1533  l2capoutbuf[10] = 0x01; // Config
1534  l2capoutbuf[11] = 0x02;
1535  l2capoutbuf[12] = 0xA0;
1536  l2capoutbuf[13] = 0x02;
1537 
1538  L2CAP_Command(handle, l2capoutbuf, 14);
1539 }
1540 
1541 void BTD::l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1542  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_REQUEST; // Code
1543  l2capoutbuf[1] = rxid; // Identifier
1544  l2capoutbuf[2] = 0x04; // Length
1545  l2capoutbuf[3] = 0x00;
1546  l2capoutbuf[4] = dcid[0];
1547  l2capoutbuf[5] = dcid[1];
1548  l2capoutbuf[6] = scid[0];
1549  l2capoutbuf[7] = scid[1];
1550 
1551  L2CAP_Command(handle, l2capoutbuf, 8);
1552 }
1553 
1554 void BTD::l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
1555  l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_RESPONSE; // Code
1556  l2capoutbuf[1] = rxid; // Identifier
1557  l2capoutbuf[2] = 0x04; // Length
1558  l2capoutbuf[3] = 0x00;
1559  l2capoutbuf[4] = dcid[0];
1560  l2capoutbuf[5] = dcid[1];
1561  l2capoutbuf[6] = scid[0];
1562  l2capoutbuf[7] = scid[1];
1563 
1564  L2CAP_Command(handle, l2capoutbuf, 8);
1565 }
1566 
1567 void BTD::l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh) {
1568  l2capoutbuf[0] = L2CAP_CMD_INFORMATION_RESPONSE; // Code
1569  l2capoutbuf[1] = rxid; // Identifier
1570  l2capoutbuf[2] = 0x08; // Length
1571  l2capoutbuf[3] = 0x00;
1572  l2capoutbuf[4] = infoTypeLow;
1573  l2capoutbuf[5] = infoTypeHigh;
1574  l2capoutbuf[6] = 0x00; // Result = success
1575  l2capoutbuf[7] = 0x00; // Result = success
1576  l2capoutbuf[8] = 0x00;
1577  l2capoutbuf[9] = 0x00;
1578  l2capoutbuf[10] = 0x00;
1579  l2capoutbuf[11] = 0x00;
1580 
1581  L2CAP_Command(handle, l2capoutbuf, 12);
1582 }
1583 
1584 /* PS3 Commands - only set Bluetooth address is implemented in this library */
1585 void BTD::setBdaddr(uint8_t* bdaddr) {
1586  /* Set the internal Bluetooth address */
1587  uint8_t buf[8];
1588  buf[0] = 0x01;
1589  buf[1] = 0x00;
1590 
1591  for(uint8_t i = 0; i < 6; i++)
1592  buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first
1593 
1594  // 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
1595  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
1596 }
1597 
1598 void BTD::setMoveBdaddr(uint8_t* bdaddr) {
1599  /* Set the internal Bluetooth address */
1600  uint8_t buf[11];
1601  buf[0] = 0x05;
1602  buf[7] = 0x10;
1603  buf[8] = 0x01;
1604  buf[9] = 0x02;
1605  buf[10] = 0x12;
1606 
1607  for(uint8_t i = 0; i < 6; i++)
1608  buf[i + 1] = bdaddr[i];
1609 
1610  // 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
1611  pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
1612 }
static const uint8_t BTD_DATAOUT_PIPE
Definition: BTD.h:558
uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t *dataptr)
Definition: Usb.cpp:801
uint8_t bmRcvToggle
Definition: address.h:48
bool incomingWii
Definition: BTD.h:504
diff --git a/_b_t_d_8h.html b/_b_t_d_8h.html index f2fd6182..5cc205f5 100644 --- a/_b_t_d_8h.html +++ b/_b_t_d_8h.html @@ -83,17 +83,18 @@ This graph shows which files directly or indirectly include this file:
- - - - - + + + + + - - - - + + + + +
diff --git a/_b_t_d_8h__dep__incl.map b/_b_t_d_8h__dep__incl.map index d124b572..f7b0e8bb 100644 --- a/_b_t_d_8h__dep__incl.map +++ b/_b_t_d_8h__dep__incl.map @@ -1,13 +1,14 @@ - - - - - + + + + + - - - - + + + + + diff --git a/_b_t_d_8h__dep__incl.md5 b/_b_t_d_8h__dep__incl.md5 index c59fa974..e025c0af 100644 --- a/_b_t_d_8h__dep__incl.md5 +++ b/_b_t_d_8h__dep__incl.md5 @@ -1 +1 @@ -f319401190d1085c45724d4fdcb1e6d0 \ No newline at end of file +cf0549b2c2a90bf20d4d75b13087ec87 \ No newline at end of file diff --git a/_b_t_d_8h__dep__incl.png b/_b_t_d_8h__dep__incl.png index 008b22f1..4712263c 100644 Binary files a/_b_t_d_8h__dep__incl.png and b/_b_t_d_8h__dep__incl.png differ diff --git a/_b_t_d_8h_source.html b/_b_t_d_8h_source.html index d4605bdf..290b5a5e 100644 --- a/_b_t_d_8h_source.html +++ b/_b_t_d_8h_source.html @@ -63,7 +63,7 @@ $(function() {
BTD.h
-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 #ifndef _btd_h_
19 #define _btd_h_
20 
21 #include "Usb.h"
22 #include "usbhid.h"
23 
24 //PID and VID of the Sony PS3 devices
25 #define PS3_VID 0x054C // Sony Corporation
26 #define PS3_PID 0x0268 // PS3 Controller DualShock 3
27 #define PS3NAVIGATION_PID 0x042F // Navigation controller
28 #define PS3MOVE_PID 0x03D5 // Motion controller
29 
30 // These dongles do not present themselves correctly, so we have to check for them manually
31 #define IOGEAR_GBU521_VID 0x0A5C
32 #define IOGEAR_GBU521_PID 0x21E8
33 #define BELKIN_F8T065BF_VID 0x050D
34 #define BELKIN_F8T065BF_PID 0x065A
35 
36 /* Bluetooth dongle data taken from descriptors */
37 #define BULK_MAXPKTSIZE 64 // Max size for ACL data
38 
39 // Used in control endpoint header for HCI Commands
40 #define bmREQ_HCI_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
41 
42 /* Bluetooth HCI states for hci_task() */
43 #define HCI_INIT_STATE 0
44 #define HCI_RESET_STATE 1
45 #define HCI_CLASS_STATE 2
46 #define HCI_BDADDR_STATE 3
47 #define HCI_LOCAL_VERSION_STATE 4
48 #define HCI_WRITE_NAME_STATE 5
49 #define HCI_CHECK_DEVICE_SERVICE 6
50 
51 #define HCI_INQUIRY_STATE 7 // These three states are only used if it should pair and connect to a device
52 #define HCI_CONNECT_DEVICE_STATE 8
53 #define HCI_CONNECTED_DEVICE_STATE 9
54 
55 #define HCI_SCANNING_STATE 10
56 #define HCI_CONNECT_IN_STATE 11
57 #define HCI_REMOTE_NAME_STATE 12
58 #define HCI_CONNECTED_STATE 13
59 #define HCI_DISABLE_SCAN_STATE 14
60 #define HCI_DONE_STATE 15
61 #define HCI_DISCONNECT_STATE 16
62 #define HCI_LOCAL_EXTENDED_FEATURES_STATE 17
63 #define HCI_WRITE_SIMPLE_PAIRING_STATE 18
64 #define HCI_SET_EVENT_MASK_STATE 19
65 
66 /* HCI event flags*/
67 #define HCI_FLAG_CMD_COMPLETE (1UL << 0)
68 #define HCI_FLAG_CONNECT_COMPLETE (1UL << 1)
69 #define HCI_FLAG_DISCONNECT_COMPLETE (1UL << 2)
70 #define HCI_FLAG_REMOTE_NAME_COMPLETE (1UL << 3)
71 #define HCI_FLAG_INCOMING_REQUEST (1UL << 4)
72 #define HCI_FLAG_READ_BDADDR (1UL << 5)
73 #define HCI_FLAG_READ_VERSION (1UL << 6)
74 #define HCI_FLAG_DEVICE_FOUND (1UL << 7)
75 #define HCI_FLAG_CONNECT_EVENT (1UL << 8)
76 #define HCI_FLAG_LOCAL_EXTENDED_FEATURES (1UL << 9)
77 
78 /* Macros for HCI event flag tests */
79 #define hci_check_flag(flag) (hci_event_flag & (flag))
80 #define hci_set_flag(flag) (hci_event_flag |= (flag))
81 #define hci_clear_flag(flag) (hci_event_flag &= ~(flag))
82 
83 /* HCI Events managed */
84 #define EV_INQUIRY_COMPLETE 0x01
85 #define EV_INQUIRY_RESULT 0x02
86 #define EV_CONNECT_COMPLETE 0x03
87 #define EV_INCOMING_CONNECT 0x04
88 #define EV_DISCONNECT_COMPLETE 0x05
89 #define EV_AUTHENTICATION_COMPLETE 0x06
90 #define EV_REMOTE_NAME_COMPLETE 0x07
91 #define EV_ENCRYPTION_CHANGE 0x08
92 #define EV_CHANGE_CONNECTION_LINK 0x09
93 #define EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE 0x0C
94 #define EV_QOS_SETUP_COMPLETE 0x0D
95 #define EV_COMMAND_COMPLETE 0x0E
96 #define EV_COMMAND_STATUS 0x0F
97 #define EV_ROLE_CHANGED 0x12
98 #define EV_NUM_COMPLETE_PKT 0x13
99 #define EV_PIN_CODE_REQUEST 0x16
100 #define EV_LINK_KEY_REQUEST 0x17
101 #define EV_LINK_KEY_NOTIFICATION 0x18
102 #define EV_DATA_BUFFER_OVERFLOW 0x1A
103 #define EV_MAX_SLOTS_CHANGE 0x1B
104 #define EV_LOOPBACK_COMMAND 0x19
105 #define EV_PAGE_SCAN_REP_MODE 0x20
106 #define EV_READ_REMOTE_EXTENDED_FEATURES_COMPLETE 0x23
107 #define EV_IO_CAPABILITY_REQUEST 0x31
108 #define EV_IO_CAPABILITY_RESPONSE 0x32
109 #define EV_USER_CONFIRMATION_REQUEST 0x33
110 #define EV_SIMPLE_PAIRING_COMPLETE 0x36
111 
112 /* Bluetooth states for the different Bluetooth drivers */
113 #define L2CAP_WAIT 0
114 #define L2CAP_DONE 1
115 
116 /* Used for HID Control channel */
117 #define L2CAP_CONTROL_CONNECT_REQUEST 2
118 #define L2CAP_CONTROL_CONFIG_REQUEST 3
119 #define L2CAP_CONTROL_SUCCESS 4
120 #define L2CAP_CONTROL_DISCONNECT 5
121 
122 /* Used for HID Interrupt channel */
123 #define L2CAP_INTERRUPT_SETUP 6
124 #define L2CAP_INTERRUPT_CONNECT_REQUEST 7
125 #define L2CAP_INTERRUPT_CONFIG_REQUEST 8
126 #define L2CAP_INTERRUPT_DISCONNECT 9
127 
128 /* Used for SDP channel */
129 #define L2CAP_SDP_WAIT 10
130 #define L2CAP_SDP_SUCCESS 11
131 
132 /* Used for RFCOMM channel */
133 #define L2CAP_RFCOMM_WAIT 12
134 #define L2CAP_RFCOMM_SUCCESS 13
135 
136 #define L2CAP_DISCONNECT_RESPONSE 14 // Used for both SDP and RFCOMM channel
137 
138 /* Bluetooth states used by some drivers */
139 #define TURN_ON_LED 17
140 #define PS3_ENABLE_SIXAXIS 18
141 #define WII_CHECK_MOTION_PLUS_STATE 19
142 #define WII_CHECK_EXTENSION_STATE 20
143 #define WII_INIT_MOTION_PLUS_STATE 21
144 
145 /* L2CAP event flags for HID Control channel */
146 #define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST (1UL << 0)
147 #define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS (1UL << 1)
148 #define L2CAP_FLAG_CONTROL_CONNECTED (1UL << 2)
149 #define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE (1UL << 3)
150 
151 /* L2CAP event flags for HID Interrupt channel */
152 #define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST (1UL << 4)
153 #define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS (1UL << 5)
154 #define L2CAP_FLAG_INTERRUPT_CONNECTED (1UL << 6)
155 #define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE (1UL << 7)
156 
157 /* L2CAP event flags for SDP channel */
158 #define L2CAP_FLAG_CONNECTION_SDP_REQUEST (1UL << 8)
159 #define L2CAP_FLAG_CONFIG_SDP_SUCCESS (1UL << 9)
160 #define L2CAP_FLAG_DISCONNECT_SDP_REQUEST (1UL << 10)
161 
162 /* L2CAP event flags for RFCOMM channel */
163 #define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST (1UL << 11)
164 #define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS (1UL << 12)
165 #define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST (1UL << 13)
166 
167 #define L2CAP_FLAG_DISCONNECT_RESPONSE (1UL << 14)
168 
169 /* Macros for L2CAP event flag tests */
170 #define l2cap_check_flag(flag) (l2cap_event_flag & (flag))
171 #define l2cap_set_flag(flag) (l2cap_event_flag |= (flag))
172 #define l2cap_clear_flag(flag) (l2cap_event_flag &= ~(flag))
173 
174 /* L2CAP signaling commands */
175 #define L2CAP_CMD_COMMAND_REJECT 0x01
176 #define L2CAP_CMD_CONNECTION_REQUEST 0x02
177 #define L2CAP_CMD_CONNECTION_RESPONSE 0x03
178 #define L2CAP_CMD_CONFIG_REQUEST 0x04
179 #define L2CAP_CMD_CONFIG_RESPONSE 0x05
180 #define L2CAP_CMD_DISCONNECT_REQUEST 0x06
181 #define L2CAP_CMD_DISCONNECT_RESPONSE 0x07
182 #define L2CAP_CMD_INFORMATION_REQUEST 0x0A
183 #define L2CAP_CMD_INFORMATION_RESPONSE 0x0B
184 
185 // Used For Connection Response - Remember to Include High Byte
186 #define PENDING 0x01
187 #define SUCCESSFUL 0x00
188 
189 /* Bluetooth L2CAP PSM - see http://www.bluetooth.org/Technical/AssignedNumbers/logical_link.htm */
190 #define SDP_PSM 0x01 // Service Discovery Protocol PSM Value
191 #define RFCOMM_PSM 0x03 // RFCOMM PSM Value
192 #define HID_CTRL_PSM 0x11 // HID_Control PSM Value
193 #define HID_INTR_PSM 0x13 // HID_Interrupt PSM Value
194 
195 /* Used for SDP */
196 #define SDP_SERVICE_SEARCH_REQUEST 0x02
197 #define SDP_SERVICE_SEARCH_RESPONSE 0x03
198 #define SDP_SERVICE_ATTRIBUTE_REQUEST 0x04
199 #define SDP_SERVICE_ATTRIBUTE_RESPONSE 0x05
200 #define SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST 0x06 // See the RFCOMM specs
201 #define SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE 0x07 // See the RFCOMM specs
202 #define PNP_INFORMATION_UUID 0x1200
203 #define SERIALPORT_UUID 0x1101 // See http://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
204 #define L2CAP_UUID 0x0100
205 
206 // Used to determine if it is a Bluetooth dongle
207 #define WI_SUBCLASS_RF 0x01 // RF Controller
208 #define WI_PROTOCOL_BT 0x01 // Bluetooth Programming Interface
209 
210 #define BTD_MAX_ENDPOINTS 4
211 #define BTD_NUM_SERVICES 4 // Max number of Bluetooth services - if you need more than 4 simply increase this number
212 
213 #define PAIR 1
214 
215 class BluetoothService;
216 
221 class BTD : public USBDeviceConfig, public UsbConfigXtracter {
222 public:
227  BTD(USB *p);
228 
237  uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
245  uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
250  uint8_t Release();
255  uint8_t Poll();
256 
261  virtual uint8_t GetAddress() {
262  return bAddress;
263  };
264 
269  virtual bool isReady() {
270  return bPollEnable;
271  };
272 
278  virtual bool DEVCLASSOK(uint8_t klass) {
279  return (klass == USB_CLASS_WIRELESS_CTRL);
280  };
281 
289  virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
290  if((vid == IOGEAR_GBU521_VID && pid == IOGEAR_GBU521_PID) || (vid == BELKIN_F8T065BF_VID && pid == BELKIN_F8T065BF_PID))
291  return true;
292  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) { // Check if Bluetooth address is set
293  if(vid == PS3_VID && (pid == PS3_PID || pid == PS3NAVIGATION_PID || pid == PS3MOVE_PID))
294  return true;
295  }
296  return false;
297  };
309  void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
313  void disconnect();
314 
321  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
322  if(!btService[i]) {
323  btService[i] = pService;
324  return i; // Return ID
325  }
326  }
327  return -1; // Error registering BluetoothService
328  };
329 
336  void HCI_Command(uint8_t* data, uint16_t nbytes);
338  void hci_reset();
340  void hci_read_bdaddr();
344  void hci_read_local_extended_features(uint8_t page_number);
349  void hci_write_local_name(const char* name);
351  void hci_write_simple_pairing_mode(bool enable);
353  void hci_set_event_mask();
355  void hci_write_scan_enable();
357  void hci_write_scan_disable();
359  void hci_remote_name();
361  void hci_accept_connection();
366  void hci_disconnect(uint16_t handle);
385  void hci_inquiry();
387  void hci_inquiry_cancel();
389  void hci_connect();
396  void hci_connect(uint8_t *bdaddr);
410  void L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00);
418  void l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm);
427  void l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result);
434  void l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid);
441  void l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid);
449  void l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
457  void l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
464  void l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh);
475 
477  const char* btdName;
479  const char* btdPin;
480 
482  uint8_t my_bdaddr[6];
484  uint16_t hci_handle;
486  uint8_t disc_bdaddr[6];
488  char remote_name[30];
494  uint8_t hci_version;
495 
498  pairWithWii = true;
499  hci_state = HCI_CHECK_DEVICE_SERVICE;
500  };
502  bool connectToWii;
511 
513  void pairWithHID() {
514  waitingForConnection = false;
515  pairWithHIDDevice = true;
516  hci_state = HCI_CHECK_DEVICE_SERVICE;
517  };
519  bool connectToHIDDevice;
524 
529  uint8_t readPollInterval() {
530  return pollInterval;
531  };
532 
534  bool useSimplePairing;
535 
536 protected:
540  uint8_t bAddress;
543 
545  uint8_t bConfNum;
547  uint8_t bNumEP;
549  uint32_t qNextPollTime;
550 
552  static const uint8_t BTD_CONTROL_PIPE;
554  static const uint8_t BTD_EVENT_PIPE;
556  static const uint8_t BTD_DATAIN_PIPE;
558  static const uint8_t BTD_DATAOUT_PIPE;
559 
565 
566 private:
567  void Initialize(); // Set all variables, endpoint structs etc. to default values
569 
570  uint16_t PID, VID; // PID and VID of device connected
571 
572  uint8_t pollInterval;
573  bool simple_pairing_supported;
574  bool bPollEnable;
575 
576  bool pairWiiUsingSync; // True if pairing was done using the Wii SYNC button.
577  bool checkRemoteName; // Used to check remote device's name before connecting.
578  bool incomingPS4; // True if a PS4 controller is connecting
579  uint8_t classOfDevice[3]; // Class of device of last device
580 
581  /* Variables used by high level HCI task */
582  uint8_t hci_state; // Current state of Bluetooth HCI connection
583  uint16_t hci_counter; // Counter used for Bluetooth HCI reset loops
584  uint16_t hci_num_reset_loops; // This value indicate how many times it should read before trying to reset
585  uint16_t hci_event_flag; // HCI flags of received Bluetooth events
586  uint8_t inquiry_counter;
587 
588  uint8_t hcibuf[BULK_MAXPKTSIZE]; // General purpose buffer for HCI data
589  uint8_t l2capinbuf[BULK_MAXPKTSIZE]; // General purpose buffer for L2CAP in data
590  uint8_t l2capoutbuf[14]; // General purpose buffer for L2CAP out data
591 
592  /* State machines */
593  void HCI_event_task(); // Poll the HCI event pipe
594  void HCI_task(); // HCI state machine
595  void ACL_event_task(); // ACL input pipe
596 
597  /* Used to set the Bluetooth Address internally to the PS3 Controllers */
598  void setBdaddr(uint8_t* BDADDR);
599  void setMoveBdaddr(uint8_t* BDADDR);
600 };
601 
604 public:
605  BluetoothService(BTD *p) : pBtd(p) {
606  if(pBtd)
607  pBtd->registerBluetoothService(this); // Register it as a Bluetooth service
608  };
613  virtual void ACLData(uint8_t* ACLData) = 0;
615  virtual void Run() = 0;
617  virtual void Reset() = 0;
619  virtual void disconnect() = 0;
620 
625  void attachOnInit(void (*funcOnInit)(void)) {
626  pFuncOnInit = funcOnInit; // TODO: This really belong in a class of it's own as it is repeated several times
627  };
628 
629 protected:
635  virtual void onInit() = 0;
636 
638  bool checkHciHandle(uint8_t *buf, uint16_t handle) {
639  return (buf[0] == (handle & 0xFF)) && (buf[1] == ((handle >> 8) | 0x20));
640  }
641 
643  void (*pFuncOnInit)(void);
644 
647 
649  uint16_t hci_handle;
650 
653 
655  uint8_t identifier;
656 };
657 
658 #endif
static const uint8_t BTD_DATAOUT_PIPE
Definition: BTD.h:558
+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 #ifndef _btd_h_
19 #define _btd_h_
20 
21 #include "Usb.h"
22 #include "usbhid.h"
23 
24 //PID and VID of the Sony PS3 devices
25 #define PS3_VID 0x054C // Sony Corporation
26 #define PS3_PID 0x0268 // PS3 Controller DualShock 3
27 #define PS3NAVIGATION_PID 0x042F // Navigation controller
28 #define PS3MOVE_PID 0x03D5 // Motion controller
29 
30 // These dongles do not present themselves correctly, so we have to check for them manually
31 #define IOGEAR_GBU521_VID 0x0A5C
32 #define IOGEAR_GBU521_PID 0x21E8
33 #define BELKIN_F8T065BF_VID 0x050D
34 #define BELKIN_F8T065BF_PID 0x065A
35 
36 /* Bluetooth dongle data taken from descriptors */
37 #define BULK_MAXPKTSIZE 64 // Max size for ACL data
38 
39 // Used in control endpoint header for HCI Commands
40 #define bmREQ_HCI_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
41 
42 /* Bluetooth HCI states for hci_task() */
43 #define HCI_INIT_STATE 0
44 #define HCI_RESET_STATE 1
45 #define HCI_CLASS_STATE 2
46 #define HCI_BDADDR_STATE 3
47 #define HCI_LOCAL_VERSION_STATE 4
48 #define HCI_WRITE_NAME_STATE 5
49 #define HCI_CHECK_DEVICE_SERVICE 6
50 
51 #define HCI_INQUIRY_STATE 7 // These three states are only used if it should pair and connect to a device
52 #define HCI_CONNECT_DEVICE_STATE 8
53 #define HCI_CONNECTED_DEVICE_STATE 9
54 
55 #define HCI_SCANNING_STATE 10
56 #define HCI_CONNECT_IN_STATE 11
57 #define HCI_REMOTE_NAME_STATE 12
58 #define HCI_CONNECTED_STATE 13
59 #define HCI_DISABLE_SCAN_STATE 14
60 #define HCI_DONE_STATE 15
61 #define HCI_DISCONNECT_STATE 16
62 #define HCI_LOCAL_EXTENDED_FEATURES_STATE 17
63 #define HCI_WRITE_SIMPLE_PAIRING_STATE 18
64 #define HCI_SET_EVENT_MASK_STATE 19
65 
66 /* HCI event flags*/
67 #define HCI_FLAG_CMD_COMPLETE (1UL << 0)
68 #define HCI_FLAG_CONNECT_COMPLETE (1UL << 1)
69 #define HCI_FLAG_DISCONNECT_COMPLETE (1UL << 2)
70 #define HCI_FLAG_REMOTE_NAME_COMPLETE (1UL << 3)
71 #define HCI_FLAG_INCOMING_REQUEST (1UL << 4)
72 #define HCI_FLAG_READ_BDADDR (1UL << 5)
73 #define HCI_FLAG_READ_VERSION (1UL << 6)
74 #define HCI_FLAG_DEVICE_FOUND (1UL << 7)
75 #define HCI_FLAG_CONNECT_EVENT (1UL << 8)
76 #define HCI_FLAG_LOCAL_EXTENDED_FEATURES (1UL << 9)
77 
78 /* Macros for HCI event flag tests */
79 #define hci_check_flag(flag) (hci_event_flag & (flag))
80 #define hci_set_flag(flag) (hci_event_flag |= (flag))
81 #define hci_clear_flag(flag) (hci_event_flag &= ~(flag))
82 
83 /* HCI Events managed */
84 #define EV_INQUIRY_COMPLETE 0x01
85 #define EV_INQUIRY_RESULT 0x02
86 #define EV_CONNECT_COMPLETE 0x03
87 #define EV_INCOMING_CONNECT 0x04
88 #define EV_DISCONNECT_COMPLETE 0x05
89 #define EV_AUTHENTICATION_COMPLETE 0x06
90 #define EV_REMOTE_NAME_COMPLETE 0x07
91 #define EV_ENCRYPTION_CHANGE 0x08
92 #define EV_CHANGE_CONNECTION_LINK 0x09
93 #define EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE 0x0C
94 #define EV_QOS_SETUP_COMPLETE 0x0D
95 #define EV_COMMAND_COMPLETE 0x0E
96 #define EV_COMMAND_STATUS 0x0F
97 #define EV_ROLE_CHANGED 0x12
98 #define EV_NUM_COMPLETE_PKT 0x13
99 #define EV_PIN_CODE_REQUEST 0x16
100 #define EV_LINK_KEY_REQUEST 0x17
101 #define EV_LINK_KEY_NOTIFICATION 0x18
102 #define EV_DATA_BUFFER_OVERFLOW 0x1A
103 #define EV_MAX_SLOTS_CHANGE 0x1B
104 #define EV_LOOPBACK_COMMAND 0x19
105 #define EV_PAGE_SCAN_REP_MODE 0x20
106 #define EV_READ_REMOTE_EXTENDED_FEATURES_COMPLETE 0x23
107 #define EV_IO_CAPABILITY_REQUEST 0x31
108 #define EV_IO_CAPABILITY_RESPONSE 0x32
109 #define EV_USER_CONFIRMATION_REQUEST 0x33
110 #define EV_SIMPLE_PAIRING_COMPLETE 0x36
111 
112 /* Bluetooth states for the different Bluetooth drivers */
113 #define L2CAP_WAIT 0
114 #define L2CAP_DONE 1
115 
116 /* Used for HID Control channel */
117 #define L2CAP_CONTROL_CONNECT_REQUEST 2
118 #define L2CAP_CONTROL_CONFIG_REQUEST 3
119 #define L2CAP_CONTROL_SUCCESS 4
120 #define L2CAP_CONTROL_DISCONNECT 5
121 
122 /* Used for HID Interrupt channel */
123 #define L2CAP_INTERRUPT_SETUP 6
124 #define L2CAP_INTERRUPT_CONNECT_REQUEST 7
125 #define L2CAP_INTERRUPT_CONFIG_REQUEST 8
126 #define L2CAP_INTERRUPT_DISCONNECT 9
127 
128 /* Used for SDP channel */
129 #define L2CAP_SDP_WAIT 10
130 #define L2CAP_SDP_SUCCESS 11
131 
132 /* Used for RFCOMM channel */
133 #define L2CAP_RFCOMM_WAIT 12
134 #define L2CAP_RFCOMM_SUCCESS 13
135 
136 #define L2CAP_DISCONNECT_RESPONSE 14 // Used for both SDP and RFCOMM channel
137 
138 /* Bluetooth states used by some drivers */
139 #define TURN_ON_LED 17
140 #define PS3_ENABLE_SIXAXIS 18
141 #define WII_CHECK_MOTION_PLUS_STATE 19
142 #define WII_CHECK_EXTENSION_STATE 20
143 #define WII_INIT_MOTION_PLUS_STATE 21
144 
145 /* L2CAP event flags for HID Control channel */
146 #define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST (1UL << 0)
147 #define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS (1UL << 1)
148 #define L2CAP_FLAG_CONTROL_CONNECTED (1UL << 2)
149 #define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE (1UL << 3)
150 
151 /* L2CAP event flags for HID Interrupt channel */
152 #define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST (1UL << 4)
153 #define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS (1UL << 5)
154 #define L2CAP_FLAG_INTERRUPT_CONNECTED (1UL << 6)
155 #define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE (1UL << 7)
156 
157 /* L2CAP event flags for SDP channel */
158 #define L2CAP_FLAG_CONNECTION_SDP_REQUEST (1UL << 8)
159 #define L2CAP_FLAG_CONFIG_SDP_SUCCESS (1UL << 9)
160 #define L2CAP_FLAG_DISCONNECT_SDP_REQUEST (1UL << 10)
161 
162 /* L2CAP event flags for RFCOMM channel */
163 #define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST (1UL << 11)
164 #define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS (1UL << 12)
165 #define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST (1UL << 13)
166 
167 #define L2CAP_FLAG_DISCONNECT_RESPONSE (1UL << 14)
168 
169 /* Macros for L2CAP event flag tests */
170 #define l2cap_check_flag(flag) (l2cap_event_flag & (flag))
171 #define l2cap_set_flag(flag) (l2cap_event_flag |= (flag))
172 #define l2cap_clear_flag(flag) (l2cap_event_flag &= ~(flag))
173 
174 /* L2CAP signaling commands */
175 #define L2CAP_CMD_COMMAND_REJECT 0x01
176 #define L2CAP_CMD_CONNECTION_REQUEST 0x02
177 #define L2CAP_CMD_CONNECTION_RESPONSE 0x03
178 #define L2CAP_CMD_CONFIG_REQUEST 0x04
179 #define L2CAP_CMD_CONFIG_RESPONSE 0x05
180 #define L2CAP_CMD_DISCONNECT_REQUEST 0x06
181 #define L2CAP_CMD_DISCONNECT_RESPONSE 0x07
182 #define L2CAP_CMD_INFORMATION_REQUEST 0x0A
183 #define L2CAP_CMD_INFORMATION_RESPONSE 0x0B
184 
185 // Used For Connection Response - Remember to Include High Byte
186 #define PENDING 0x01
187 #define SUCCESSFUL 0x00
188 
189 /* Bluetooth L2CAP PSM - see http://www.bluetooth.org/Technical/AssignedNumbers/logical_link.htm */
190 #define SDP_PSM 0x01 // Service Discovery Protocol PSM Value
191 #define RFCOMM_PSM 0x03 // RFCOMM PSM Value
192 #define HID_CTRL_PSM 0x11 // HID_Control PSM Value
193 #define HID_INTR_PSM 0x13 // HID_Interrupt PSM Value
194 
195 /* Used for SDP */
196 #define SDP_SERVICE_SEARCH_REQUEST 0x02
197 #define SDP_SERVICE_SEARCH_RESPONSE 0x03
198 #define SDP_SERVICE_ATTRIBUTE_REQUEST 0x04
199 #define SDP_SERVICE_ATTRIBUTE_RESPONSE 0x05
200 #define SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST 0x06 // See the RFCOMM specs
201 #define SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE 0x07 // See the RFCOMM specs
202 #define PNP_INFORMATION_UUID 0x1200
203 #define SERIALPORT_UUID 0x1101 // See http://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
204 #define L2CAP_UUID 0x0100
205 
206 // Used to determine if it is a Bluetooth dongle
207 #define WI_SUBCLASS_RF 0x01 // RF Controller
208 #define WI_PROTOCOL_BT 0x01 // Bluetooth Programming Interface
209 
210 #define BTD_MAX_ENDPOINTS 4
211 #define BTD_NUM_SERVICES 4 // Max number of Bluetooth services - if you need more than 4 simply increase this number
212 
213 #define PAIR 1
214 
215 class BluetoothService;
216 
221 class BTD : public USBDeviceConfig, public UsbConfigXtracter {
222 public:
227  BTD(USB *p);
228 
237  uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
245  uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
250  uint8_t Release();
255  uint8_t Poll();
256 
261  virtual uint8_t GetAddress() {
262  return bAddress;
263  };
264 
269  virtual bool isReady() {
270  return bPollEnable;
271  };
272 
278  virtual bool DEVCLASSOK(uint8_t klass) {
279  return (klass == USB_CLASS_WIRELESS_CTRL);
280  };
281 
289  virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
290  if((vid == IOGEAR_GBU521_VID && pid == IOGEAR_GBU521_PID) || (vid == BELKIN_F8T065BF_VID && pid == BELKIN_F8T065BF_PID))
291  return true;
292  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) { // Check if Bluetooth address is set
293  if(vid == PS3_VID && (pid == PS3_PID || pid == PS3NAVIGATION_PID || pid == PS3MOVE_PID))
294  return true;
295  }
296  return false;
297  };
309  void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
313  void disconnect();
314 
321  for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
322  if(!btService[i]) {
323  btService[i] = pService;
324  return i; // Return ID
325  }
326  }
327  return -1; // Error registering BluetoothService
328  };
329 
336  void HCI_Command(uint8_t* data, uint16_t nbytes);
338  void hci_reset();
340  void hci_read_bdaddr();
344  void hci_read_local_extended_features(uint8_t page_number);
349  void hci_write_local_name(const char* name);
351  void hci_write_simple_pairing_mode(bool enable);
353  void hci_set_event_mask();
355  void hci_write_scan_enable();
357  void hci_write_scan_disable();
359  void hci_remote_name();
361  void hci_accept_connection();
366  void hci_disconnect(uint16_t handle);
385  void hci_inquiry();
387  void hci_inquiry_cancel();
389  void hci_connect();
396  void hci_connect(uint8_t *bdaddr);
410  void L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00);
418  void l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm);
427  void l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result);
434  void l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid);
441  void l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid);
449  void l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
457  void l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
464  void l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh);
475 
477  const char* btdName;
479  const char* btdPin;
480 
482  uint8_t my_bdaddr[6];
484  uint16_t hci_handle;
486  uint8_t disc_bdaddr[6];
488  char remote_name[30];
494  uint8_t hci_version;
495 
498  pairWithWii = true;
499  hci_state = HCI_CHECK_DEVICE_SERVICE;
500  };
502  bool connectToWii;
511 
513  void pairWithHID() {
514  waitingForConnection = false;
515  pairWithHIDDevice = true;
516  hci_state = HCI_CHECK_DEVICE_SERVICE;
517  };
519  bool connectToHIDDevice;
524 
529  uint8_t readPollInterval() {
530  return pollInterval;
531  };
532 
534  bool useSimplePairing;
535 
536 protected:
540  uint8_t bAddress;
543 
545  uint8_t bConfNum;
547  uint8_t bNumEP;
549  uint32_t qNextPollTime;
550 
552  static const uint8_t BTD_CONTROL_PIPE;
554  static const uint8_t BTD_EVENT_PIPE;
556  static const uint8_t BTD_DATAIN_PIPE;
558  static const uint8_t BTD_DATAOUT_PIPE;
559 
565 
566 private:
567  void Initialize(); // Set all variables, endpoint structs etc. to default values
569 
570  uint16_t PID, VID; // PID and VID of device connected
571 
572  uint8_t pollInterval;
573  bool simple_pairing_supported;
574  bool bPollEnable;
575 
576  bool pairWiiUsingSync; // True if pairing was done using the Wii SYNC button.
577  bool checkRemoteName; // Used to check remote device's name before connecting.
578  bool incomingPSController; // True if a PS4/PS5 controller is connecting
579  uint8_t classOfDevice[3]; // Class of device of last device
580 
581  /* Variables used by high level HCI task */
582  uint8_t hci_state; // Current state of Bluetooth HCI connection
583  uint16_t hci_counter; // Counter used for Bluetooth HCI reset loops
584  uint16_t hci_num_reset_loops; // This value indicate how many times it should read before trying to reset
585  uint16_t hci_event_flag; // HCI flags of received Bluetooth events
586  uint8_t inquiry_counter;
587 
588  uint8_t hcibuf[BULK_MAXPKTSIZE]; // General purpose buffer for HCI data
589  uint8_t l2capinbuf[BULK_MAXPKTSIZE]; // General purpose buffer for L2CAP in data
590  uint8_t l2capoutbuf[14]; // General purpose buffer for L2CAP out data
591 
592  /* State machines */
593  void HCI_event_task(); // Poll the HCI event pipe
594  void HCI_task(); // HCI state machine
595  void ACL_event_task(); // ACL input pipe
596 
597  /* Used to set the Bluetooth Address internally to the PS3 Controllers */
598  void setBdaddr(uint8_t* BDADDR);
599  void setMoveBdaddr(uint8_t* BDADDR);
600 };
601 
604 public:
605  BluetoothService(BTD *p) : pBtd(p) {
606  if(pBtd)
607  pBtd->registerBluetoothService(this); // Register it as a Bluetooth service
608  };
613  virtual void ACLData(uint8_t* ACLData) = 0;
615  virtual void Run() = 0;
617  virtual void Reset() = 0;
619  virtual void disconnect() = 0;
620 
625  void attachOnInit(void (*funcOnInit)(void)) {
626  pFuncOnInit = funcOnInit; // TODO: This really belong in a class of it's own as it is repeated several times
627  };
628 
629 protected:
635  virtual void onInit() = 0;
636 
638  bool checkHciHandle(uint8_t *buf, uint16_t handle) {
639  return (buf[0] == (handle & 0xFF)) && (buf[1] == ((handle >> 8) | 0x20));
640  }
641 
643  void (*pFuncOnInit)(void);
644 
647 
649  uint16_t hci_handle;
650 
653 
655  uint8_t identifier;
656 };
657 
658 #endif
static const uint8_t BTD_DATAOUT_PIPE
Definition: BTD.h:558
bool incomingWii
Definition: BTD.h:504
bool useSimplePairing
Definition: BTD.h:531
void hci_connect()
Definition: BTD.cpp:1268
diff --git a/_b_t_h_i_d_8cpp_source.html b/_b_t_h_i_d_8cpp_source.html index f3ffeace..08e7cbc7 100644 --- a/_b_t_h_i_d_8cpp_source.html +++ b/_b_t_h_i_d_8cpp_source.html @@ -63,7 +63,7 @@ $(function() {
BTHID.cpp
-Go to the documentation of this file.
1 /* Copyright (C) 2013 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 "BTHID.h"
19 // To enable serial debugging see "settings.h"
20 //#define EXTRADEBUG // Uncomment to get even more debugging data
21 //#define PRINTREPORT // Uncomment to print the report send by the HID device
22 
23 BTHID::BTHID(BTD *p, bool pair, const char *pin) :
24 BluetoothService(p), // Pointer to USB class instance - mandatory
25 protocolMode(USB_HID_BOOT_PROTOCOL) {
26  for(uint8_t i = 0; i < NUM_PARSERS; i++)
27  pRptParser[i] = NULL;
28 
30  pBtd->btdPin = pin;
31 
32  /* Set device cid for the control and intterrupt channelse - LSB */
33  sdp_dcid[0] = 0x50; // 0x0050
34  sdp_dcid[1] = 0x00;
35  control_dcid[0] = 0x70; // 0x0070
36  control_dcid[1] = 0x00;
37  interrupt_dcid[0] = 0x71; // 0x0071
38  interrupt_dcid[1] = 0x00;
39 
40  Reset();
41 }
42 
43 void BTHID::Reset() {
44  connected = false;
45  activeConnection = false;
46  SDPConnected = false;
47  l2cap_event_flag = 0; // Reset flags
49  l2cap_state = L2CAP_WAIT;
50  ResetBTHID();
51 }
52 
53 void BTHID::disconnect() { // Use this void to disconnect the device
54  if(SDPConnected)
56  // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection
58  Reset();
60  l2cap_state = L2CAP_INTERRUPT_DISCONNECT;
61 }
62 
63 void BTHID::ACLData(uint8_t* l2capinbuf) {
64  if(!connected) {
65  if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
66  if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM && !pBtd->sdpConnectionClaimed) {
67  pBtd->sdpConnectionClaimed = true;
68  hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
69  l2cap_sdp_state = L2CAP_SDP_WAIT; // Reset state
70  }
71  }
72  }
73 
74  if(!pBtd->l2capConnectionClaimed && pBtd->incomingHIDDevice && !connected && !activeConnection) {
75  if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
76  if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
77  pBtd->incomingHIDDevice = false;
78  pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service
79  activeConnection = true;
80  hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
81  l2cap_state = L2CAP_WAIT;
82  }
83  }
84  }
85 
86  if(checkHciHandle(l2capinbuf, hci_handle)) { // acl_handle_ok
87  if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U
88  if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) {
89 #ifdef DEBUG_USB_HOST
90  Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
91  D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
92  Notify(PSTR(" "), 0x80);
93  D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
94  Notify(PSTR(" "), 0x80);
95  D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
96  Notify(PSTR(" "), 0x80);
97  D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
98  Notify(PSTR(" "), 0x80);
99  D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
100  Notify(PSTR(" "), 0x80);
101  D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
102 #endif
103  } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) {
104  if(((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success
105  if(l2capinbuf[14] == sdp_dcid[0] && l2capinbuf[15] == sdp_dcid[1]) {
106 #ifdef EXTRADEBUG
107  Notify(PSTR("\r\nSDP Connection Complete"), 0x80);
108 #endif
109  identifier = l2capinbuf[9];
110  sdp_scid[0] = l2capinbuf[12];
111  sdp_scid[1] = l2capinbuf[13];
112 #ifdef DEBUG_USB_HOST
113  Notify(PSTR("\r\nSend SDP Config Request"), 0x80);
114 #endif
115  identifier++;
117  } else if(l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) {
118 #ifdef EXTRADEBUG
119  Notify(PSTR("\r\nHID Control Connection Complete"), 0x80);
120 #endif
121  identifier = l2capinbuf[9];
122  control_scid[0] = l2capinbuf[12];
123  control_scid[1] = l2capinbuf[13];
125  } else if(l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) {
126 #ifdef EXTRADEBUG
127  Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80);
128 #endif
129  identifier = l2capinbuf[9];
130  interrupt_scid[0] = l2capinbuf[12];
131  interrupt_scid[1] = l2capinbuf[13];
133  }
134  }
135  } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
136 #ifdef EXTRADEBUG
137  Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
138  D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
139  Notify(PSTR(" "), 0x80);
140  D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
141  Notify(PSTR(" SCID: "), 0x80);
142  D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
143  Notify(PSTR(" "), 0x80);
144  D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
145  Notify(PSTR(" Identifier: "), 0x80);
146  D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
147 #endif
148  if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM) {
149  identifier = l2capinbuf[9];
150  sdp_scid[0] = l2capinbuf[14];
151  sdp_scid[1] = l2capinbuf[15];
153  } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
154  identifier = l2capinbuf[9];
155  control_scid[0] = l2capinbuf[14];
156  control_scid[1] = l2capinbuf[15];
158  } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) {
159  identifier = l2capinbuf[9];
160  interrupt_scid[0] = l2capinbuf[14];
161  interrupt_scid[1] = l2capinbuf[15];
163  }
164  } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) {
165  if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success
166  if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
167 #ifdef EXTRADEBUG
168  Notify(PSTR("\r\nSDP Configuration Complete"), 0x80);
169 #endif
170  identifier = l2capinbuf[9];
172  } else if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
173 #ifdef EXTRADEBUG
174  Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80);
175 #endif
176  identifier = l2capinbuf[9];
178  } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
179 #ifdef EXTRADEBUG
180  Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80);
181 #endif
182  identifier = l2capinbuf[9];
184  }
185  }
186  } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) {
187  if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
188 #ifdef EXTRADEBUG
189  Notify(PSTR("\r\nSDP Configuration Request"), 0x80);
190 #endif
191  pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], sdp_scid);
192  } else if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
193 #ifdef EXTRADEBUG
194  Notify(PSTR("\r\nHID Control Configuration Request"), 0x80);
195 #endif
197  } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
198 #ifdef EXTRADEBUG
199  Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80);
200 #endif
202  }
203  } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) {
204  if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
205 #ifdef DEBUG_USB_HOST
206  Notify(PSTR("\r\nDisconnect Request: SDP Channel"), 0x80);
207 #endif
208  identifier = l2capinbuf[9];
210  } else if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
211 #ifdef DEBUG_USB_HOST
212  Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80);
213 #endif
214  identifier = l2capinbuf[9];
216  Reset();
217  } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
218 #ifdef DEBUG_USB_HOST
219  Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80);
220 #endif
221  identifier = l2capinbuf[9];
223  Reset();
224  }
225  } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) {
226  if(l2capinbuf[12] == sdp_scid[0] && l2capinbuf[13] == sdp_scid[1]) {
227 #ifdef EXTRADEBUG
228  Notify(PSTR("\r\nDisconnect Response: SDP Channel"), 0x80);
229 #endif
230  identifier = l2capinbuf[9];
232  } else if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) {
233 #ifdef EXTRADEBUG
234  Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80);
235 #endif
236  identifier = l2capinbuf[9];
238  } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) {
239 #ifdef EXTRADEBUG
240  Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80);
241 #endif
242  identifier = l2capinbuf[9];
244  }
245  } else if(l2capinbuf[8] == L2CAP_CMD_INFORMATION_REQUEST) {
246 #ifdef DEBUG_USB_HOST
247  Notify(PSTR("\r\nInformation request"), 0x80);
248 #endif
249  identifier = l2capinbuf[9];
250  pBtd->l2cap_information_response(hci_handle, identifier, l2capinbuf[12], l2capinbuf[13]);
251  }
252 #ifdef EXTRADEBUG
253  else {
254  identifier = l2capinbuf[9];
255  Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
256  D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
257  }
258 #endif
259  } else if(l2capinbuf[6] == sdp_dcid[0] && l2capinbuf[7] == sdp_dcid[1]) { // SDP
260  if(l2capinbuf[8] == SDP_SERVICE_SEARCH_REQUEST) {
261 #ifdef EXTRADEBUG
262  Notify(PSTR("\r\nSDP_SERVICE_SEARCH_REQUEST"), 0x80);
263 #endif
264  // Send response
265  l2capoutbuf[0] = SDP_SERVICE_SEARCH_RESPONSE;
266  l2capoutbuf[1] = l2capinbuf[9];//transactionIDHigh;
267  l2capoutbuf[2] = l2capinbuf[10];//transactionIDLow;
268 
269  l2capoutbuf[3] = 0x00; // MSB Parameter Length
270  l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5
271 
272  l2capoutbuf[5] = 0x00; // MSB TotalServiceRecordCount
273  l2capoutbuf[6] = 0x00; // LSB TotalServiceRecordCount = 0
274 
275  l2capoutbuf[7] = 0x00; // MSB CurrentServiceRecordCount
276  l2capoutbuf[8] = 0x00; // LSB CurrentServiceRecordCount = 0
277 
278  l2capoutbuf[9] = 0x00; // No continuation state
279 
280  SDP_Command(l2capoutbuf, 10);
281  } else if(l2capinbuf[8] == SDP_SERVICE_ATTRIBUTE_REQUEST) {
282 #ifdef EXTRADEBUG
283  Notify(PSTR("\r\nSDP_SERVICE_ATTRIBUTE_REQUEST"), 0x80);
284 #endif
285  // Send response
286  l2capoutbuf[0] = SDP_SERVICE_ATTRIBUTE_RESPONSE;
287  l2capoutbuf[1] = l2capinbuf[9];//transactionIDHigh;
288  l2capoutbuf[2] = l2capinbuf[10];//transactionIDLow;
289 
290  l2capoutbuf[3] = 0x00; // MSB Parameter Length
291  l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5
292 
293  l2capoutbuf[5] = 0x00; // MSB AttributeListByteCount
294  l2capoutbuf[6] = 0x02; // LSB AttributeListByteCount = 2
295 
296  // TODO: What to send?
297  l2capoutbuf[7] = 0x35; // Data element sequence - length in next byte
298  l2capoutbuf[8] = 0x00; // Length = 0
299 
300  l2capoutbuf[9] = 0x00; // No continuation state
301 
302  SDP_Command(l2capoutbuf, 10);
303  } else if(l2capinbuf[8] == SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST) {
304 #ifdef EXTRADEBUG
305  Notify(PSTR("\r\nSDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST"), 0x80);
306  Notify(PSTR("\r\nUUID: "), 0x80);
307  uint16_t uuid;
308  if((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000) // Check if it's sending the UUID as a 128-bit UUID
309  uuid = (l2capinbuf[18] << 8 | l2capinbuf[19]);
310  else // Short UUID
311  uuid = (l2capinbuf[16] << 8 | l2capinbuf[17]);
312  D_PrintHex<uint16_t > (uuid, 0x80);
313 
314  Notify(PSTR("\r\nLength: "), 0x80);
315  uint16_t length = l2capinbuf[11] << 8 | l2capinbuf[12];
316  D_PrintHex<uint16_t > (length, 0x80);
317  Notify(PSTR("\r\nData: "), 0x80);
318  for(uint8_t i = 0; i < length; i++) {
319  D_PrintHex<uint8_t > (l2capinbuf[13 + i], 0x80);
320  Notify(PSTR(" "), 0x80);
321  }
322 #endif
323  serviceNotSupported(l2capinbuf[9], l2capinbuf[10]); // The service is not supported
324  }
325 #ifdef EXTRADEBUG
326  else {
327  Notify(PSTR("\r\nUnknown PDU: "), 0x80);
328  D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
329  }
330 #endif
331  } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt
332 #ifdef PRINTREPORT
333  Notify(PSTR("\r\nL2CAP Interrupt: "), 0x80);
334  for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
335  D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
336  Notify(PSTR(" "), 0x80);
337  }
338 #endif
339  if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT
340  uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]);
341  ParseBTHIDData((uint8_t)(length - 1), &l2capinbuf[9]);
342 
343  switch(l2capinbuf[9]) {
344  case 0x01: // Keyboard or Joystick events
345  if(pRptParser[KEYBOARD_PARSER_ID])
346  pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast<USBHID *>(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance
347  break;
348 
349  case 0x02: // Mouse events
350  if(pRptParser[MOUSE_PARSER_ID])
351  pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast<USBHID *>(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance
352  break;
353 #ifdef EXTRADEBUG
354  default:
355  Notify(PSTR("\r\nUnknown Report type: "), 0x80);
356  D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
357  break;
358 #endif
359  }
360  }
361  } else if(l2capinbuf[6] == control_dcid[0] && l2capinbuf[7] == control_dcid[1]) { // l2cap_control
362 #ifdef PRINTREPORT
363  Notify(PSTR("\r\nL2CAP Control: "), 0x80);
364  for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
365  D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
366  Notify(PSTR(" "), 0x80);
367  }
368 #endif
369  if(l2capinbuf[8] == 0xA3) {
370  uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]);
371  ParseBTHIDControlData((uint8_t)(length - 1), &l2capinbuf[9]);
372  }
373  }
374 #ifdef EXTRADEBUG
375  else {
376  Notify(PSTR("\r\nUnsupported L2CAP Data - Channel ID: "), 0x80);
377  D_PrintHex<uint8_t > (l2capinbuf[7], 0x80);
378  Notify(PSTR(" "), 0x80);
379  D_PrintHex<uint8_t > (l2capinbuf[6], 0x80);
380 
381  Notify(PSTR("\r\nData: "), 0x80);
382  Notify(PSTR("\r\n"), 0x80);
383  for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
384  D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
385  Notify(PSTR(" "), 0x80);
386  }
387  }
388 #endif
389  SDP_task();
390  L2CAP_task();
391  }
392 }
393 
394 void BTHID::SDP_task() {
395  switch(l2cap_sdp_state) {
396  case L2CAP_SDP_WAIT:
399 #ifdef DEBUG_USB_HOST
400  Notify(PSTR("\r\nSDP Incoming Connection Request"), 0x80);
401 #endif
403  delay(1);
405  identifier++;
406  delay(1);
411  SDPConnected = false;
412 #ifdef DEBUG_USB_HOST
413  Notify(PSTR("\r\nDisconnected SDP Channel"), 0x80);
414 #endif
416  }
417  break;
418  case L2CAP_SDP_SUCCESS:
421 #ifdef DEBUG_USB_HOST
422  Notify(PSTR("\r\nSDP Successfully Configured"), 0x80);
423 #endif
424  SDPConnected = true;
426  }
427  break;
428 
429  case L2CAP_DISCONNECT_RESPONSE: // This is for both disconnection response from the RFCOMM and SDP channel if they were connected
431 #ifdef DEBUG_USB_HOST
432  Notify(PSTR("\r\nDisconnected L2CAP Connection"), 0x80);
433 #endif
435  hci_handle = -1; // Reset handle
436  Reset();
437  }
438  break;
439  }
440 }
441 
442 void BTHID::L2CAP_task() {
443  switch(l2cap_state) {
444  /* These states are used if the HID device is the host */
447 #ifdef DEBUG_USB_HOST
448  Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80);
449 #endif
450  setProtocol(); // Set protocol before establishing HID interrupt channel
451  l2cap_state = L2CAP_INTERRUPT_SETUP;
452  }
453  break;
454 
457 #ifdef DEBUG_USB_HOST
458  Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80);
459 #endif
461  delay(1);
463  identifier++;
464  delay(1);
466 
467  l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
468  }
469  break;
470 
471  /* These states are used if the Arduino is the host */
474 #ifdef DEBUG_USB_HOST
475  Notify(PSTR("\r\nSend HID Control Config Request"), 0x80);
476 #endif
477  identifier++;
479  l2cap_state = L2CAP_CONTROL_CONFIG_REQUEST;
480  }
481  break;
482 
485  setProtocol(); // Set protocol before establishing HID interrupt channel
486  delay(1); // Short delay between commands - just to be sure
487 #ifdef DEBUG_USB_HOST
488  Notify(PSTR("\r\nSend HID Interrupt Connection Request"), 0x80);
489 #endif
490  identifier++;
492  l2cap_state = L2CAP_INTERRUPT_CONNECT_REQUEST;
493  }
494  break;
495 
498 #ifdef DEBUG_USB_HOST
499  Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80);
500 #endif
501  identifier++;
503  l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
504  }
505  break;
506 
508  if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established
509 #ifdef DEBUG_USB_HOST
510  Notify(PSTR("\r\nHID Channels Established"), 0x80);
511 #endif
512  pBtd->connectToHIDDevice = false;
513  pBtd->pairWithHIDDevice = false;
514  connected = true;
515  onInit();
516  l2cap_state = L2CAP_DONE;
517  }
518  break;
519 
520  case L2CAP_DONE:
521  break;
522 
525 #ifdef DEBUG_USB_HOST
526  Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80);
527 #endif
528  identifier++;
530  l2cap_state = L2CAP_CONTROL_DISCONNECT;
531  }
532  break;
533 
536 #ifdef DEBUG_USB_HOST
537  Notify(PSTR("\r\nDisconnected Control Channel"), 0x80);
538 #endif
540  hci_handle = -1; // Reset handle
541  l2cap_event_flag = 0; // Reset flags
542  l2cap_state = L2CAP_WAIT;
543  }
544  break;
545  }
546 }
547 
548 void BTHID::Run() {
549  switch(l2cap_state) {
550  case L2CAP_WAIT:
551  if(pBtd->connectToHIDDevice && !pBtd->l2capConnectionClaimed && !connected && !activeConnection) {
553  activeConnection = true;
554 #ifdef DEBUG_USB_HOST
555  Notify(PSTR("\r\nSend HID Control Connection Request"), 0x80);
556 #endif
557  hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
558  l2cap_event_flag = 0; // Reset flags
559  identifier = 0;
561  l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST;
563 #ifdef DEBUG_USB_HOST
564  Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80);
565 #endif
567  delay(1);
569  identifier++;
570  delay(1);
572  l2cap_state = L2CAP_CONTROL_SUCCESS;
573  }
574  break;
575  }
576 }
577 
578 void BTHID::SDP_Command(uint8_t* data, uint8_t nbytes) { // See page 223 in the Bluetooth specs
579  pBtd->L2CAP_Command(hci_handle, data, nbytes, sdp_scid[0], sdp_scid[1]);
580 }
581 
582 void BTHID::serviceNotSupported(uint8_t transactionIDHigh, uint8_t transactionIDLow) { // See page 235 in the Bluetooth specs
583  l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE;
584  l2capoutbuf[1] = transactionIDHigh;
585  l2capoutbuf[2] = transactionIDLow;
586  l2capoutbuf[3] = 0x00; // MSB Parameter Length
587  l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5
588  l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount
589  l2capoutbuf[6] = 0x02; // LSB AttributeListsByteCount = 2
590 
591  /* Attribute ID/Value Sequence: */
592  l2capoutbuf[7] = 0x35; // Data element sequence - length in next byte
593  l2capoutbuf[8] = 0x00; // Length = 0
594  l2capoutbuf[9] = 0x00; // No continuation state
595 
596  SDP_Command(l2capoutbuf, 10);
597 }
598 
599 /************************************************************/
600 /* HID Commands */
601 
602 /************************************************************/
603 void BTHID::setProtocol() {
604 #ifdef DEBUG_USB_HOST
605  Notify(PSTR("\r\nSet protocol mode: "), 0x80);
606  D_PrintHex<uint8_t > (protocolMode, 0x80);
607 #endif
608  if (protocolMode != USB_HID_BOOT_PROTOCOL && protocolMode != HID_RPT_PROTOCOL) {
609 #ifdef DEBUG_USB_HOST
610  Notify(PSTR("\r\nNot a valid protocol mode. Using Boot protocol instead."), 0x80);
611 #endif
612  protocolMode = USB_HID_BOOT_PROTOCOL; // Use Boot Protocol by default
613  }
614  uint8_t command = 0x70 | protocolMode; // Set Protocol, see Bluetooth HID specs page 33
615  pBtd->L2CAP_Command(hci_handle, &command, 1, control_scid[0], control_scid[1]);
616 }
617 
618 void BTHID::setLeds(uint8_t data) {
619  uint8_t buf[3];
620  buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
621  buf[1] = 0x01; // Report ID
622  buf[2] = data;
624 }
#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE
Definition: BTD.h:149
+Go to the documentation of this file.
1 /* Copyright (C) 2013 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 "BTHID.h"
19 // To enable serial debugging see "settings.h"
20 //#define EXTRADEBUG // Uncomment to get even more debugging data
21 //#define PRINTREPORT // Uncomment to print the report send by the HID device
22 
23 BTHID::BTHID(BTD *p, bool pair, const char *pin) :
24 BluetoothService(p), // Pointer to USB class instance - mandatory
25 protocolMode(USB_HID_BOOT_PROTOCOL) {
26  for(uint8_t i = 0; i < NUM_PARSERS; i++)
27  pRptParser[i] = NULL;
28 
30  pBtd->btdPin = pin;
31 
32  /* Set device cid for the control and intterrupt channelse - LSB */
33  sdp_dcid[0] = 0x50; // 0x0050
34  sdp_dcid[1] = 0x00;
35  control_dcid[0] = 0x70; // 0x0070
36  control_dcid[1] = 0x00;
37  interrupt_dcid[0] = 0x71; // 0x0071
38  interrupt_dcid[1] = 0x00;
39 
40  Reset();
41 }
42 
43 void BTHID::Reset() {
44  connected = false;
45  activeConnection = false;
46  SDPConnected = false;
47  l2cap_event_flag = 0; // Reset flags
49  l2cap_state = L2CAP_WAIT;
50  ResetBTHID();
51 }
52 
53 void BTHID::disconnect() { // Use this void to disconnect the device
54  if(SDPConnected)
56  // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection
58  Reset();
60  l2cap_state = L2CAP_INTERRUPT_DISCONNECT;
61 }
62 
63 void BTHID::ACLData(uint8_t* l2capinbuf) {
64  if(!connected) {
65  if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
66  if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM && !pBtd->sdpConnectionClaimed) {
67  pBtd->sdpConnectionClaimed = true;
68  hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
69  l2cap_sdp_state = L2CAP_SDP_WAIT; // Reset state
70  }
71  }
72  }
73 
74  if(!pBtd->l2capConnectionClaimed && pBtd->incomingHIDDevice && !connected && !activeConnection) {
75  if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
76  if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
77  pBtd->incomingHIDDevice = false;
78  pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service
79  activeConnection = true;
80  hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
81  l2cap_state = L2CAP_WAIT;
82  }
83  }
84  }
85 
86  if(checkHciHandle(l2capinbuf, hci_handle)) { // acl_handle_ok
87  if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U
88  if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) {
89 #ifdef DEBUG_USB_HOST
90  Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
91  D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
92  Notify(PSTR(" "), 0x80);
93  D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
94  Notify(PSTR(" "), 0x80);
95  D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
96  Notify(PSTR(" "), 0x80);
97  D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
98  Notify(PSTR(" "), 0x80);
99  D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
100  Notify(PSTR(" "), 0x80);
101  D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
102 #endif
103  } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) {
104  if(((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success
105  if(l2capinbuf[14] == sdp_dcid[0] && l2capinbuf[15] == sdp_dcid[1]) {
106 #ifdef EXTRADEBUG
107  Notify(PSTR("\r\nSDP Connection Complete"), 0x80);
108 #endif
109  identifier = l2capinbuf[9];
110  sdp_scid[0] = l2capinbuf[12];
111  sdp_scid[1] = l2capinbuf[13];
112 #ifdef DEBUG_USB_HOST
113  Notify(PSTR("\r\nSend SDP Config Request"), 0x80);
114 #endif
115  identifier++;
117  } else if(l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) {
118 #ifdef EXTRADEBUG
119  Notify(PSTR("\r\nHID Control Connection Complete"), 0x80);
120 #endif
121  identifier = l2capinbuf[9];
122  control_scid[0] = l2capinbuf[12];
123  control_scid[1] = l2capinbuf[13];
125  } else if(l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) {
126 #ifdef EXTRADEBUG
127  Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80);
128 #endif
129  identifier = l2capinbuf[9];
130  interrupt_scid[0] = l2capinbuf[12];
131  interrupt_scid[1] = l2capinbuf[13];
133  }
134  }
135  } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
136 #ifdef EXTRADEBUG
137  Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
138  D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
139  Notify(PSTR(" "), 0x80);
140  D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
141  Notify(PSTR(" SCID: "), 0x80);
142  D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
143  Notify(PSTR(" "), 0x80);
144  D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
145  Notify(PSTR(" Identifier: "), 0x80);
146  D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
147 #endif
148  if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM) {
149  identifier = l2capinbuf[9];
150  sdp_scid[0] = l2capinbuf[14];
151  sdp_scid[1] = l2capinbuf[15];
153  } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
154  identifier = l2capinbuf[9];
155  control_scid[0] = l2capinbuf[14];
156  control_scid[1] = l2capinbuf[15];
158  } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) {
159  identifier = l2capinbuf[9];
160  interrupt_scid[0] = l2capinbuf[14];
161  interrupt_scid[1] = l2capinbuf[15];
163  }
164  } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) {
165  if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success
166  if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
167 #ifdef EXTRADEBUG
168  Notify(PSTR("\r\nSDP Configuration Complete"), 0x80);
169 #endif
170  identifier = l2capinbuf[9];
172  } else if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
173 #ifdef EXTRADEBUG
174  Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80);
175 #endif
176  identifier = l2capinbuf[9];
178  } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
179 #ifdef EXTRADEBUG
180  Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80);
181 #endif
182  identifier = l2capinbuf[9];
184  }
185  }
186  } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) {
187  if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
188 #ifdef EXTRADEBUG
189  Notify(PSTR("\r\nSDP Configuration Request"), 0x80);
190 #endif
191  pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], sdp_scid);
192  } else if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
193 #ifdef EXTRADEBUG
194  Notify(PSTR("\r\nHID Control Configuration Request"), 0x80);
195 #endif
197  } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
198 #ifdef EXTRADEBUG
199  Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80);
200 #endif
202  }
203  } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) {
204  if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
205 #ifdef DEBUG_USB_HOST
206  Notify(PSTR("\r\nDisconnect Request: SDP Channel"), 0x80);
207 #endif
208  identifier = l2capinbuf[9];
210  } else if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
211 #ifdef DEBUG_USB_HOST
212  Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80);
213 #endif
214  identifier = l2capinbuf[9];
216  Reset();
217  } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
218 #ifdef DEBUG_USB_HOST
219  Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80);
220 #endif
221  identifier = l2capinbuf[9];
223  Reset();
224  }
225  } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) {
226  if(l2capinbuf[12] == sdp_scid[0] && l2capinbuf[13] == sdp_scid[1]) {
227 #ifdef EXTRADEBUG
228  Notify(PSTR("\r\nDisconnect Response: SDP Channel"), 0x80);
229 #endif
230  identifier = l2capinbuf[9];
232  } else if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) {
233 #ifdef EXTRADEBUG
234  Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80);
235 #endif
236  identifier = l2capinbuf[9];
238  } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) {
239 #ifdef EXTRADEBUG
240  Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80);
241 #endif
242  identifier = l2capinbuf[9];
244  }
245  } else if(l2capinbuf[8] == L2CAP_CMD_INFORMATION_REQUEST) {
246 #ifdef DEBUG_USB_HOST
247  Notify(PSTR("\r\nInformation request"), 0x80);
248 #endif
249  identifier = l2capinbuf[9];
250  pBtd->l2cap_information_response(hci_handle, identifier, l2capinbuf[12], l2capinbuf[13]);
251  }
252 #ifdef EXTRADEBUG
253  else {
254  identifier = l2capinbuf[9];
255  Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
256  D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
257  }
258 #endif
259  } else if(l2capinbuf[6] == sdp_dcid[0] && l2capinbuf[7] == sdp_dcid[1]) { // SDP
260  if(l2capinbuf[8] == SDP_SERVICE_SEARCH_REQUEST) {
261 #ifdef EXTRADEBUG
262  Notify(PSTR("\r\nSDP_SERVICE_SEARCH_REQUEST"), 0x80);
263 #endif
264  // Send response
265  l2capoutbuf[0] = SDP_SERVICE_SEARCH_RESPONSE;
266  l2capoutbuf[1] = l2capinbuf[9];//transactionIDHigh;
267  l2capoutbuf[2] = l2capinbuf[10];//transactionIDLow;
268 
269  l2capoutbuf[3] = 0x00; // MSB Parameter Length
270  l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5
271 
272  l2capoutbuf[5] = 0x00; // MSB TotalServiceRecordCount
273  l2capoutbuf[6] = 0x00; // LSB TotalServiceRecordCount = 0
274 
275  l2capoutbuf[7] = 0x00; // MSB CurrentServiceRecordCount
276  l2capoutbuf[8] = 0x00; // LSB CurrentServiceRecordCount = 0
277 
278  l2capoutbuf[9] = 0x00; // No continuation state
279 
280  SDP_Command(l2capoutbuf, 10);
281  } else if(l2capinbuf[8] == SDP_SERVICE_ATTRIBUTE_REQUEST) {
282 #ifdef EXTRADEBUG
283  Notify(PSTR("\r\nSDP_SERVICE_ATTRIBUTE_REQUEST"), 0x80);
284 #endif
285  // Send response
286  l2capoutbuf[0] = SDP_SERVICE_ATTRIBUTE_RESPONSE;
287  l2capoutbuf[1] = l2capinbuf[9];//transactionIDHigh;
288  l2capoutbuf[2] = l2capinbuf[10];//transactionIDLow;
289 
290  l2capoutbuf[3] = 0x00; // MSB Parameter Length
291  l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5
292 
293  l2capoutbuf[5] = 0x00; // MSB AttributeListByteCount
294  l2capoutbuf[6] = 0x02; // LSB AttributeListByteCount = 2
295 
296  // TODO: What to send?
297  l2capoutbuf[7] = 0x35; // Data element sequence - length in next byte
298  l2capoutbuf[8] = 0x00; // Length = 0
299 
300  l2capoutbuf[9] = 0x00; // No continuation state
301 
302  SDP_Command(l2capoutbuf, 10);
303  } else if(l2capinbuf[8] == SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST) {
304 #ifdef EXTRADEBUG
305  Notify(PSTR("\r\nSDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST"), 0x80);
306  Notify(PSTR("\r\nUUID: "), 0x80);
307  uint16_t uuid;
308  if((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000) // Check if it's sending the UUID as a 128-bit UUID
309  uuid = (l2capinbuf[18] << 8 | l2capinbuf[19]);
310  else // Short UUID
311  uuid = (l2capinbuf[16] << 8 | l2capinbuf[17]);
312  D_PrintHex<uint16_t > (uuid, 0x80);
313 
314  Notify(PSTR("\r\nLength: "), 0x80);
315  uint16_t length = l2capinbuf[11] << 8 | l2capinbuf[12];
316  D_PrintHex<uint16_t > (length, 0x80);
317  Notify(PSTR("\r\nData: "), 0x80);
318  for(uint8_t i = 0; i < length; i++) {
319  D_PrintHex<uint8_t > (l2capinbuf[13 + i], 0x80);
320  Notify(PSTR(" "), 0x80);
321  }
322 #endif
323  serviceNotSupported(l2capinbuf[9], l2capinbuf[10]); // The service is not supported
324  }
325 #ifdef EXTRADEBUG
326  else {
327  Notify(PSTR("\r\nUnknown PDU: "), 0x80);
328  D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
329  }
330 #endif
331  } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt
332 #ifdef PRINTREPORT
333  Notify(PSTR("\r\nL2CAP Interrupt: "), 0x80);
334  for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
335  D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
336  Notify(PSTR(" "), 0x80);
337  }
338 #endif
339  if(l2capinbuf[8] == 0xA1) { // HID BT DATA (0xA0) | Report Type (Input 0x01)
340  uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]);
341  ParseBTHIDData((uint8_t)(length - 1), &l2capinbuf[9]); // First byte will be the report ID
342 
343  switch(l2capinbuf[9]) { // Report ID
344  case 0x01: // Keyboard or Joystick events
345  if(pRptParser[KEYBOARD_PARSER_ID])
346  pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast<USBHID *>(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance
347  break;
348 
349  case 0x02: // Mouse events
350  if(pRptParser[MOUSE_PARSER_ID])
351  pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast<USBHID *>(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance
352  break;
353 #ifdef EXTRADEBUG
354  default:
355  Notify(PSTR("\r\nUnknown Report type: "), 0x80);
356  D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
357  break;
358 #endif
359  }
360  } else {
361 #ifdef EXTRADEBUG
362  Notify(PSTR("\r\nUnhandled L2CAP interrupt report: "), 0x80);
363  D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
364 #endif
365  }
366  } else if(l2capinbuf[6] == control_dcid[0] && l2capinbuf[7] == control_dcid[1]) { // l2cap_control
367 #ifdef PRINTREPORT
368  Notify(PSTR("\r\nL2CAP Control: "), 0x80);
369  for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
370  D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
371  Notify(PSTR(" "), 0x80);
372  }
373 #endif
374  if(l2capinbuf[8] == 0xA3) { // HID BT DATA (0xA0) | Report Type (Feature 0x03)
375  uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]);
376  ParseBTHIDControlData((uint8_t)(length - 1), &l2capinbuf[9]); // First byte will be the report ID
377  } else {
378 #ifdef EXTRADEBUG
379  Notify(PSTR("\r\nUnhandled L2CAP control report: "), 0x80);
380  D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
381 #endif
382  }
383  }
384 #ifdef EXTRADEBUG
385  else {
386  Notify(PSTR("\r\nUnsupported L2CAP Data - Channel ID: "), 0x80);
387  D_PrintHex<uint8_t > (l2capinbuf[7], 0x80);
388  Notify(PSTR(" "), 0x80);
389  D_PrintHex<uint8_t > (l2capinbuf[6], 0x80);
390 
391  Notify(PSTR("\r\nData: "), 0x80);
392  Notify(PSTR("\r\n"), 0x80);
393  for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
394  D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
395  Notify(PSTR(" "), 0x80);
396  }
397  }
398 #endif
399  SDP_task();
400  L2CAP_task();
401  }
402 }
403 
404 void BTHID::SDP_task() {
405  switch(l2cap_sdp_state) {
406  case L2CAP_SDP_WAIT:
409 #ifdef DEBUG_USB_HOST
410  Notify(PSTR("\r\nSDP Incoming Connection Request"), 0x80);
411 #endif
413  delay(1);
415  identifier++;
416  delay(1);
421  SDPConnected = false;
422 #ifdef DEBUG_USB_HOST
423  Notify(PSTR("\r\nDisconnected SDP Channel"), 0x80);
424 #endif
426  }
427  break;
428  case L2CAP_SDP_SUCCESS:
431 #ifdef DEBUG_USB_HOST
432  Notify(PSTR("\r\nSDP Successfully Configured"), 0x80);
433 #endif
434  SDPConnected = true;
436  }
437  break;
438 
439  case L2CAP_DISCONNECT_RESPONSE: // This is for both disconnection response from the RFCOMM and SDP channel if they were connected
441 #ifdef DEBUG_USB_HOST
442  Notify(PSTR("\r\nDisconnected L2CAP Connection"), 0x80);
443 #endif
445  hci_handle = -1; // Reset handle
446  Reset();
447  }
448  break;
449  }
450 }
451 
452 void BTHID::L2CAP_task() {
453  switch(l2cap_state) {
454  /* These states are used if the HID device is the host */
457 #ifdef DEBUG_USB_HOST
458  Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80);
459 #endif
460  setProtocol(); // Set protocol before establishing HID interrupt channel
461  l2cap_state = L2CAP_INTERRUPT_SETUP;
462  }
463  break;
464 
467 #ifdef DEBUG_USB_HOST
468  Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80);
469 #endif
471  delay(1);
473  identifier++;
474  delay(1);
476 
477  l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
478  }
479  break;
480 
481  /* These states are used if the Arduino is the host */
484 #ifdef DEBUG_USB_HOST
485  Notify(PSTR("\r\nSend HID Control Config Request"), 0x80);
486 #endif
487  identifier++;
489  l2cap_state = L2CAP_CONTROL_CONFIG_REQUEST;
490  }
491  break;
492 
495  setProtocol(); // Set protocol before establishing HID interrupt channel
496  delay(1); // Short delay between commands - just to be sure
497 #ifdef DEBUG_USB_HOST
498  Notify(PSTR("\r\nSend HID Interrupt Connection Request"), 0x80);
499 #endif
500  identifier++;
502  l2cap_state = L2CAP_INTERRUPT_CONNECT_REQUEST;
503  }
504  break;
505 
508 #ifdef DEBUG_USB_HOST
509  Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80);
510 #endif
511  identifier++;
513  l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
514  }
515  break;
516 
518  if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established
519 #ifdef DEBUG_USB_HOST
520  Notify(PSTR("\r\nHID Channels Established"), 0x80);
521 #endif
522  pBtd->connectToHIDDevice = false;
523  pBtd->pairWithHIDDevice = false;
524  connected = true;
525  onInit();
526  l2cap_state = L2CAP_DONE;
527  }
528  break;
529 
530  case L2CAP_DONE:
531  break;
532 
535 #ifdef DEBUG_USB_HOST
536  Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80);
537 #endif
538  identifier++;
540  l2cap_state = L2CAP_CONTROL_DISCONNECT;
541  }
542  break;
543 
546 #ifdef DEBUG_USB_HOST
547  Notify(PSTR("\r\nDisconnected Control Channel"), 0x80);
548 #endif
550  hci_handle = -1; // Reset handle
551  l2cap_event_flag = 0; // Reset flags
552  l2cap_state = L2CAP_WAIT;
553  }
554  break;
555  }
556 }
557 
558 void BTHID::Run() {
559  switch(l2cap_state) {
560  case L2CAP_WAIT:
561  if(pBtd->connectToHIDDevice && !pBtd->l2capConnectionClaimed && !connected && !activeConnection) {
563  activeConnection = true;
564 #ifdef DEBUG_USB_HOST
565  Notify(PSTR("\r\nSend HID Control Connection Request"), 0x80);
566 #endif
567  hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
568  l2cap_event_flag = 0; // Reset flags
569  identifier = 0;
571  l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST;
573 #ifdef DEBUG_USB_HOST
574  Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80);
575 #endif
577  delay(1);
579  identifier++;
580  delay(1);
582  l2cap_state = L2CAP_CONTROL_SUCCESS;
583  }
584  break;
585  }
586 }
587 
588 void BTHID::SDP_Command(uint8_t* data, uint8_t nbytes) { // See page 223 in the Bluetooth specs
589  pBtd->L2CAP_Command(hci_handle, data, nbytes, sdp_scid[0], sdp_scid[1]);
590 }
591 
592 void BTHID::serviceNotSupported(uint8_t transactionIDHigh, uint8_t transactionIDLow) { // See page 235 in the Bluetooth specs
593  l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE;
594  l2capoutbuf[1] = transactionIDHigh;
595  l2capoutbuf[2] = transactionIDLow;
596  l2capoutbuf[3] = 0x00; // MSB Parameter Length
597  l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5
598  l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount
599  l2capoutbuf[6] = 0x02; // LSB AttributeListsByteCount = 2
600 
601  /* Attribute ID/Value Sequence: */
602  l2capoutbuf[7] = 0x35; // Data element sequence - length in next byte
603  l2capoutbuf[8] = 0x00; // Length = 0
604  l2capoutbuf[9] = 0x00; // No continuation state
605 
606  SDP_Command(l2capoutbuf, 10);
607 }
608 
609 /************************************************************/
610 /* HID Commands */
611 
612 /************************************************************/
613 void BTHID::setProtocol() {
614 #ifdef DEBUG_USB_HOST
615  Notify(PSTR("\r\nSet protocol mode: "), 0x80);
616  D_PrintHex<uint8_t > (protocolMode, 0x80);
617 #endif
618  if (protocolMode != USB_HID_BOOT_PROTOCOL && protocolMode != HID_RPT_PROTOCOL) {
619 #ifdef DEBUG_USB_HOST
620  Notify(PSTR("\r\nNot a valid protocol mode. Using Boot protocol instead."), 0x80);
621 #endif
622  protocolMode = USB_HID_BOOT_PROTOCOL; // Use Boot Protocol by default
623  }
624  uint8_t command = 0x70 | protocolMode; // Set Protocol, see Bluetooth HID specs page 33
625  pBtd->L2CAP_Command(hci_handle, &command, 1, control_scid[0], control_scid[1]);
626 }
627 
628 void BTHID::setLeds(uint8_t data) {
629  uint8_t buf[3];
630  buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
631  buf[1] = 0x01; // Report ID
632  buf[2] = data;
634 }
#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE
Definition: BTD.h:149
#define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS
Definition: BTD.h:153
#define L2CAP_INTERRUPT_CONFIG_REQUEST
Definition: BTD.h:125
#define L2CAP_INTERRUPT_SETUP
Definition: BTD.h:123
@@ -81,7 +81,7 @@ $(function() {
#define SDP_SERVICE_ATTRIBUTE_REQUEST
Definition: BTD.h:198
bool connected
Definition: BTHID.h:88
#define L2CAP_SDP_SUCCESS
Definition: BTD.h:130
-
void Run()
Definition: BTHID.cpp:548
+
void Run()
Definition: BTHID.cpp:558
const char * btdPin
Definition: BTD.h:479
#define L2CAP_DONE
Definition: BTD.h:114
#define L2CAP_CONTROL_SUCCESS
Definition: BTD.h:119
diff --git a/_b_t_h_i_d_8h.html b/_b_t_h_i_d_8h.html index 7fe9dd9e..883475aa 100644 --- a/_b_t_h_i_d_8h.html +++ b/_b_t_h_i_d_8h.html @@ -87,7 +87,8 @@ This graph shows which files directly or indirectly include this file:
- + +
diff --git a/_b_t_h_i_d_8h__dep__incl.map b/_b_t_h_i_d_8h__dep__incl.map index a8f40d95..9357d95b 100644 --- a/_b_t_h_i_d_8h__dep__incl.map +++ b/_b_t_h_i_d_8h__dep__incl.map @@ -1,5 +1,6 @@ - + + diff --git a/_b_t_h_i_d_8h__dep__incl.md5 b/_b_t_h_i_d_8h__dep__incl.md5 index 6a659db3..fd41a5a7 100644 --- a/_b_t_h_i_d_8h__dep__incl.md5 +++ b/_b_t_h_i_d_8h__dep__incl.md5 @@ -1 +1 @@ -f5ffabeee933ef99da0ca226df2def53 \ No newline at end of file +23a000c41dd5dd0fa67a484993db484a \ No newline at end of file diff --git a/_b_t_h_i_d_8h__dep__incl.png b/_b_t_h_i_d_8h__dep__incl.png index 2b3e98b5..f68eb584 100644 Binary files a/_b_t_h_i_d_8h__dep__incl.png and b/_b_t_h_i_d_8h__dep__incl.png differ diff --git a/_b_t_h_i_d_8h_source.html b/_b_t_h_i_d_8h_source.html index cc0f4445..7bbc038c 100644 --- a/_b_t_h_i_d_8h_source.html +++ b/_b_t_h_i_d_8h_source.html @@ -70,7 +70,7 @@ $(function() {
Definition: BTD.h:221
uint8_t interrupt_scid[2]
Definition: BTHID.h:149
bool connected
Definition: BTHID.h:88
-
void Run()
Definition: BTHID.cpp:548
+
void Run()
Definition: BTHID.cpp:558
virtual void ResetBTHID()
Definition: BTHID.h:140
void Reset()
Definition: BTHID.cpp:43
uint8_t control_scid[2]
Definition: BTHID.h:146
diff --git a/_p_s3_b_t_8cpp_source.html b/_p_s3_b_t_8cpp_source.html index 960ac8ec..8dfcf971 100644 --- a/_p_s3_b_t_8cpp_source.html +++ b/_p_s3_b_t_8cpp_source.html @@ -86,20 +86,20 @@ $(function() {
Definition: PS3Enums.h:127
Definition: PS3Enums.h:135
uint8_t hci_version
Definition: BTD.h:494
-
-
+
+
bool pairWithWii
Definition: BTD.h:506
uint8_t identifier
Definition: BTD.h:655
Definition: PS3Enums.h:138
String getTemperature()
Definition: PS3BT.cpp:141
-
AnalogHatEnum
+
AnalogHatEnum
void moveSetRumble(uint8_t rumble)
Definition: PS3BT.cpp:617
#define TURN_ON_LED
Definition: BTD.h:139
-
-
+
+
void printStatusString()
Definition: PS3BT.cpp:160
void setAllOff()
Definition: PS3BT.cpp:519
-
+
#define L2CAP_DONE
Definition: BTD.h:114
Definition: PS3Enums.h:121
Definition: PS3Enums.h:119
@@ -109,9 +109,9 @@ $(function() {
#define HID_BUFFERSIZE
Definition: PS3BT.h:24
void Reset()
Definition: PS3BT.cpp:204
#define pgm_read_byte(addr)
-
+
char remote_name[30]
Definition: BTD.h:488
-
+
const uint32_t PS3_BUTTONS[]
Definition: PS3Enums.h:62
bool getButtonPress(ButtonEnum b)
Definition: PS3BT.cpp:49
LEDEnum
@@ -121,10 +121,10 @@ $(function() {
RumbleEnum
#define USB_HOST_SERIAL
Definition: settings.h:49
#define HID_CTRL_PSM
Definition: BTD.h:192
-
+
Definition: PS3Enums.h:122
Definition: PS3Enums.h:123
-
+
bool connectToWii
Definition: BTD.h:500
uint8_t getAnalogHat(AnalogHatEnum a)
Definition: PS3BT.cpp:64
@@ -133,12 +133,12 @@ $(function() {
void hci_disconnect(uint16_t handle)
Definition: BTD.cpp:1399
Definition: BTD.h:603
#define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE
Definition: BTD.h:155
-
+
ButtonEnum
void moveSetBulb(uint8_t r, uint8_t g, uint8_t b)
Definition: PS3BT.cpp:604
bool PS3MoveConnected
Definition: PS3BT.h:182
uint8_t my_bdaddr[6]
Definition: BTD.h:482
-
+
void setRumbleOn(RumbleEnum mode)
Definition: PS3BT.cpp:540
void(* pFuncOnInit)(void)
Definition: BTD.h:643
float get9DOFValues(SensorEnum a)
Definition: PS3BT.cpp:112
@@ -154,13 +154,13 @@ $(function() {
ColorsEnum
BTD * pBtd
Definition: BTD.h:646
#define BULK_MAXPKTSIZE
Definition: BTD.h:37
-
+
#define HID_INTR_PSM
Definition: BTD.h:193
const uint8_t PS3_ANALOG_BUTTONS[]
Definition: PS3Enums.h:92
-
+
bool l2capConnectionClaimed
Definition: BTD.h:470
-
AngleEnum
+
AngleEnum
#define PS3_ENABLE_SIXAXIS
Definition: BTD.h:140
Definition: PS3Enums.h:129
#define L2CAP_CMD_DISCONNECT_RESPONSE
Definition: BTD.h:181
@@ -186,15 +186,15 @@ $(function() {
#define l2cap_set_flag(flag)
Definition: BTD.h:171
void l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t *dcid)
Definition: BTD.cpp:1505
#define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS
Definition: BTD.h:147
-
SensorEnum
+
SensorEnum
Definition: PS3Enums.h:128
#define L2CAP_CMD_CONNECTION_REQUEST
Definition: BTD.h:176
uint8_t getAnalogButton(ButtonEnum a)
Definition: PS3BT.cpp:60
-
+
float getAngle(AngleEnum a)
Definition: PS3BT.cpp:85
void setLedRaw(uint8_t value)
Definition: PS3BT.cpp:559
PS3BT(BTD *pBtd, uint8_t btadr5=0, uint8_t btadr4=0, uint8_t btadr3=0, uint8_t btadr2=0, uint8_t btadr1=0, uint8_t btadr0=0)
Definition: PS3BT.cpp:23
-
+
bool checkHciHandle(uint8_t *buf, uint16_t handle)
Definition: BTD.h:638
void onInit()
Definition: PS3BT.cpp:628
Definition: PS3Enums.h:125
diff --git a/_p_s3_b_t_8h_source.html b/_p_s3_b_t_8h_source.html index 7cea80c8..b9159374 100644 --- a/_p_s3_b_t_8h_source.html +++ b/_p_s3_b_t_8h_source.html @@ -69,7 +69,7 @@ $(function() {
Definition: BTD.h:221
void setLedOn(LEDEnum a)
Definition: PS3BT.cpp:569
String getTemperature()
Definition: PS3BT.cpp:141
-
AnalogHatEnum
+
AnalogHatEnum
void moveSetRumble(uint8_t rumble)
Definition: PS3BT.cpp:617
void printStatusString()
Definition: PS3BT.cpp:160
void setAllOff()
Definition: PS3BT.cpp:519
@@ -93,12 +93,12 @@ $(function() {
ColorsEnum
BTD * pBtd
Definition: BTD.h:646
#define BULK_MAXPKTSIZE
Definition: BTD.h:37
-
AngleEnum
+
AngleEnum
void ACLData(uint8_t *ACLData)
Definition: PS3BT.cpp:224
void setLedOff()
Definition: PS3BT.h:138
void setLedToggle(LEDEnum a)
Definition: PS3BT.cpp:578
void disconnect()
Definition: PS3BT.cpp:217
-
SensorEnum
+
SensorEnum
uint8_t getAnalogButton(ButtonEnum a)
Definition: PS3BT.cpp:60
float getAngle(AngleEnum a)
Definition: PS3BT.cpp:85
diff --git a/_p_s3_u_s_b_8cpp_source.html b/_p_s3_u_s_b_8cpp_source.html index 35e51af7..4d8ed597 100644 --- a/_p_s3_u_s_b_8cpp_source.html +++ b/_p_s3_u_s_b_8cpp_source.html @@ -90,8 +90,8 @@ $(function() {
#define PS3_OUTPUT_PIPE
Definition: PS3USB.h:30
#define NotifyFail(...)
Definition: message.h:62
bool PS3MoveConnected
Definition: PS3USB.h:262
-
AnalogHatEnum
-
+
AnalogHatEnum
+
uint8_t setConf(uint8_t addr, uint8_t ep, uint8_t conf_value)
Definition: Usb.cpp:840
Definition: PS3Enums.h:121
Definition: PS3Enums.h:119
@@ -103,7 +103,7 @@ $(function() {
#define pgm_read_byte(addr)
#define NotifyFailGetDevDescr(...)
Definition: message.h:57
uint8_t getAnalogButton(ButtonEnum a)
Definition: PS3USB.cpp:327
-
+
uint16_t getSensor(SensorEnum a)
Definition: PS3USB.cpp:335
uint8_t setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo *eprecord_ptr)
Definition: Usb.cpp:64
void setRumbleOff()
Definition: PS3USB.cpp:410
@@ -133,7 +133,7 @@ $(function() {
void printStatusString()
Definition: PS3USB.cpp:364
void setAllOff()
Definition: PS3USB.cpp:403
uint8_t outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *data)
Definition: Usb.cpp:303
-
+
ButtonEnum
const uint8_t PS3_LEDS[]
Definition: PS3Enums.h:43
virtual uint8_t AllocAddress(uint8_t parent, bool is_hub=false, uint8_t port=0)=0
@@ -147,7 +147,7 @@ $(function() {
const uint8_t PS3_ANALOG_BUTTONS[]
Definition: PS3Enums.h:92
#define USB_NAK_NOWAIT
Definition: address.h:36
-
AngleEnum
+
AngleEnum
#define USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL
Definition: UsbCore.h:95
#define PS3_PID
Definition: BTD.h:26
#define PS3NAVIGATION_PID
Definition: BTD.h:27
@@ -174,12 +174,12 @@ $(function() {
#define bmREQ_HID_IN
Definition: usbhid.h:64
float getAngle(AngleEnum a)
Definition: PS3USB.cpp:339
-
SensorEnum
+
SensorEnum
#define HID_REQUEST_SET_REPORT
Definition: usbhid.h:72
uint8_t RegisterDeviceClass(USBDeviceConfig *pdev)
Definition: UsbCore.h:230
#define NotifyFailSetConfDescr(...)
Definition: message.h:60
#define HID_REQUEST_GET_REPORT
Definition: usbhid.h:69
-
+
PS3USB(USB *pUsb, uint8_t btadr5=0, uint8_t btadr4=0, uint8_t btadr3=0, uint8_t btadr2=0, uint8_t btadr1=0, uint8_t btadr0=0)
Definition: PS3USB.cpp:23
void getMoveCalibration(uint8_t *data)
Definition: PS3USB.cpp:553
Definition: PS3Enums.h:125
diff --git a/_p_s3_u_s_b_8h_source.html b/_p_s3_u_s_b_8h_source.html index 3899d50d..cc03bb87 100644 --- a/_p_s3_u_s_b_8h_source.html +++ b/_p_s3_u_s_b_8h_source.html @@ -72,7 +72,7 @@ $(function() {
uint8_t Release()
Definition: PS3USB.cpp:262
bool getButtonPress(ButtonEnum b)
Definition: PS3USB.cpp:316
bool PS3MoveConnected
Definition: PS3USB.h:262
-
AnalogHatEnum
+
AnalogHatEnum
StatusEnum
Definition: PS3Enums.h:113
Definition: UsbCore.h:134
void getMoveBdaddr(uint8_t *bdaddr)
Definition: PS3USB.cpp:543
@@ -99,7 +99,7 @@ $(function() {
uint8_t getAnalogHat(AnalogHatEnum a)
Definition: PS3USB.cpp:331
USB * pUsb
Definition: PS3USB.h:268
ColorsEnum
-
AngleEnum
+
AngleEnum
void moveSetRumble(uint8_t rumble)
Definition: PS3USB.cpp:517
uint8_t Poll()
Definition: PS3USB.cpp:272
#define PS3MOVE_PID
Definition: PS3USB.h:37
@@ -114,7 +114,7 @@ $(function() {
void setMoveBdaddr(uint8_t *bdaddr)
Definition: PS3USB.cpp:527
Definition: UsbCore.h:210
float getAngle(AngleEnum a)
Definition: PS3USB.cpp:339
-
SensorEnum
+
SensorEnum
PS3USB(USB *pUsb, uint8_t btadr5=0, uint8_t btadr4=0, uint8_t btadr3=0, uint8_t btadr2=0, uint8_t btadr1=0, uint8_t btadr0=0)
Definition: PS3USB.cpp:23
void getMoveCalibration(uint8_t *data)
Definition: PS3USB.cpp:553
bool getStatus(StatusEnum c)
Definition: PS3USB.cpp:360
diff --git a/_p_s4_parser_8cpp.html b/_p_s4_parser_8cpp.html index 9a1f433f..2cd7cd32 100644 --- a/_p_s4_parser_8cpp.html +++ b/_p_s4_parser_8cpp.html @@ -93,16 +93,27 @@ Enumerations DPAD_LEFT_UP = 0x7,
  DPAD_OFF = 0x8, +DPAD_UP = 0x0, +DPAD_UP_RIGHT = 0x1, +DPAD_RIGHT = 0x2, +
+  DPAD_RIGHT_DOWN = 0x3, +DPAD_DOWN = 0x4, +DPAD_DOWN_LEFT = 0x5, +DPAD_LEFT = 0x6, +
+  DPAD_LEFT_UP = 0x7, +DPAD_OFF = 0x8, DPAD_OFF = 0x0, DPAD_UP = 0x1, -DPAD_UP_RIGHT = 0x2,
-  DPAD_RIGHT = 0x3, +  DPAD_UP_RIGHT = 0x2, +DPAD_RIGHT = 0x3, DPAD_RIGHT_DOWN = 0x4, DPAD_DOWN = 0x5, -DPAD_DOWN_LEFT = 0x6,
-  DPAD_LEFT = 0x7, +  DPAD_DOWN_LEFT = 0x6, +DPAD_LEFT = 0x7, DPAD_LEFT_UP = 0x8
} @@ -130,6 +141,15 @@ Enumerations DPAD_LEFT  DPAD_LEFT_UP  DPAD_OFF  +DPAD_UP  +DPAD_UP_RIGHT  +DPAD_RIGHT  +DPAD_RIGHT_DOWN  +DPAD_DOWN  +DPAD_DOWN_LEFT  +DPAD_LEFT  +DPAD_LEFT_UP  +DPAD_OFF  DPAD_OFF  DPAD_UP  DPAD_UP_RIGHT  diff --git a/_p_s4_parser_8cpp_source.html b/_p_s4_parser_8cpp_source.html index d4b23eea..c9d3f210 100644 --- a/_p_s4_parser_8cpp_source.html +++ b/_p_s4_parser_8cpp_source.html @@ -70,7 +70,7 @@ $(function() {
uint8_t hatValue[4]
Definition: PS4Parser.h:94
uint8_t b
Definition: PS4Parser.h:118
bool getButtonPress(ButtonEnum b)
Definition: PS4Parser.cpp:50
-
AnalogHatEnum
+
AnalogHatEnum
DPADEnum
Definition: PS4Parser.cpp:20
Definition: PS4Parser.cpp:24
uint8_t touching
Definition: PS4Parser.h:78
diff --git a/_p_s4_parser_8h_source.html b/_p_s4_parser_8h_source.html index df4083a6..a226603b 100644 --- a/_p_s4_parser_8h_source.html +++ b/_p_s4_parser_8h_source.html @@ -67,16 +67,16 @@ $(function() {
uint32_t val
Definition: PS4Parser.h:71
uint16_t getY(uint8_t finger=0, uint8_t xyId=0)
Definition: PS4Parser.h:182
uint8_t usb
Definition: PS4Parser.h:86
-
+
Definition: PS4Parser.h:84
Definition: PS4Parser.h:92
uint8_t r1
Definition: PS4Parser.h:59
PS4Status status
Definition: PS4Parser.h:104
void setLed(uint8_t r, uint8_t g, uint8_t b)
Definition: PS4Parser.h:320
uint8_t mic
Definition: PS4Parser.h:88
-
AnalogHatEnum
+
AnalogHatEnum
uint8_t reportCounter
Definition: PS4Parser.h:69
-
+
void setLed(ColorsEnum color)
Definition: PS4Parser.h:331
uint8_t audio
Definition: PS4Parser.h:87
void setRumbleOn(uint8_t bigRumble, uint8_t smallRumble)
Definition: PS4Parser.h:305
@@ -85,7 +85,7 @@ $(function() {
int16_t getSensor(SensorEnum s)
Definition: PS4Parser.h:227
uint8_t flashOn
Definition: PS4Parser.h:119
Definition: PS4Parser.h:116
-
+
uint8_t share
Definition: PS4Parser.h:62
uint8_t unknown
Definition: PS4Parser.h:89
@@ -105,7 +105,7 @@ $(function() {
uint16_t y
Definition: PS4Parser.h:80
const uint8_t PS4_BUTTONS[]
Definition: PS4Parser.h:25
-
+
ButtonEnum
uint8_t r
Definition: PS4Parser.h:118
void setRumbleOff()
Definition: PS4Parser.h:285
@@ -118,8 +118,8 @@ $(function() {
uint8_t dpad
Definition: PS4Parser.h:52
ColorsEnum
int16_t gyroZ
Definition: PS4Parser.h:100
-
-
AngleEnum
+
+
AngleEnum
Definition: PS4Parser.h:74
uint16_t getX(uint8_t finger=0, uint8_t xyId=0)
Definition: PS4Parser.h:170
PS4Parser()
Definition: PS4Parser.h:127
@@ -133,13 +133,13 @@ $(function() {
uint8_t battery
Definition: PS4Parser.h:85
uint8_t l3
Definition: PS4Parser.h:64
PS4Buttons btn
Definition: PS4Parser.h:95
-
SensorEnum
+
SensorEnum
uint8_t circle
Definition: PS4Parser.h:55
uint16_t x
Definition: PS4Parser.h:79
int16_t accZ
Definition: PS4Parser.h:101
-
+
void setLedFlash(uint8_t flashOn, uint8_t flashOff)
Definition: PS4Parser.h:340
-
+
bool getUsbStatus()
Definition: PS4Parser.h:258
bool getAudioStatus()
Definition: PS4Parser.h:266
diff --git a/_p_s5_b_t_8h.html b/_p_s5_b_t_8h.html new file mode 100644 index 00000000..36d586e0 --- /dev/null +++ b/_p_s5_b_t_8h.html @@ -0,0 +1,149 @@ + + + + + + + +USB Host Shield 2.0: PS5BT.h File Reference + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + + +
+
+ + +
+ +
+ +
+
+ +
+
PS5BT.h File Reference
+
+
+
#include "BTHID.h"
+#include "PS5Parser.h"
+
+Include dependency graph for PS5BT.h:
+
+
+ + + + + + + + + + + +
+
+

Go to the source code of this file.

+ + + + +

+Classes

class  PS5BT
 
+ + + +

+Macros

#define CRC32_POLY_LE   0xedb88320
 
+ + + +

+Variables

const uint32_t crc32_table []
 
+

Macro Definition Documentation

+ +

◆ CRC32_POLY_LE

+ +
+
+ + + + +
#define CRC32_POLY_LE   0xedb88320
+
+ +

Definition at line 80 of file PS5BT.h.

+ +
+
+

Variable Documentation

+ +

◆ crc32_table

+ +
+
+ + + + +
const uint32_t crc32_table[]
+
+

Generated from the standard Ethernet CRC-32 polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x^1+x^0 Source: http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/libkern/crc32.c

+ +

Definition at line 29 of file PS5BT.h.

+ +
+
+
+ + + + diff --git a/_p_s5_b_t_8h__incl.map b/_p_s5_b_t_8h__incl.map new file mode 100644 index 00000000..2f631df2 --- /dev/null +++ b/_p_s5_b_t_8h__incl.map @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/_p_s5_b_t_8h__incl.md5 b/_p_s5_b_t_8h__incl.md5 new file mode 100644 index 00000000..96eb877c --- /dev/null +++ b/_p_s5_b_t_8h__incl.md5 @@ -0,0 +1 @@ +1e5d5d372677845ed1b1074bd58a0189 \ No newline at end of file diff --git a/_p_s5_b_t_8h__incl.png b/_p_s5_b_t_8h__incl.png new file mode 100644 index 00000000..ba671d7d Binary files /dev/null and b/_p_s5_b_t_8h__incl.png differ diff --git a/_p_s5_b_t_8h_source.html b/_p_s5_b_t_8h_source.html new file mode 100644 index 00000000..c17e9016 --- /dev/null +++ b/_p_s5_b_t_8h_source.html @@ -0,0 +1,114 @@ + + + + + + + +USB Host Shield 2.0: PS5BT.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+
PS5BT.h
+
+
+Go to the documentation of this file.
1 /* Copyright (C) 2021 Kristian Sloth Lauszus. 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 Sloth Lauszus
14  Web : https://lauszus.com
15  e-mail : lauszus@gmail.com
16  */
17 
18 #ifndef _ps5bt_h_
19 #define _ps5bt_h_
20 
21 #include "BTHID.h"
22 #include "PS5Parser.h"
23 
29 const uint32_t crc32_table[] PROGMEM = {
30  0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
31  0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
32  0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
33  0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
34  0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
35  0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
36  0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
37  0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
38  0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
39  0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
40  0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
41  0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
42  0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
43  0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
44  0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
45  0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
46  0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
47  0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
48  0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
49  0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
50  0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
51  0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
52  0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
53  0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
54  0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
55  0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
56  0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
57  0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
58  0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
59  0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
60  0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
61  0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
62  0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
63  0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
64  0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
65  0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
66  0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
67  0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
68  0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
69  0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
70  0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
71  0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
72  0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
73 };
74 
75 /*
76  * There are multiple 16-bit CRC polynomials in common use, but this is
77  * *the* standard CRC-32 polynomial, first popularized by Ethernet.
78  * x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x^1+x^0
79  */
80 #define CRC32_POLY_LE 0xedb88320
81 
82 static inline uint32_t crc32_le_generic(uint32_t crc, uint8_t const *p, size_t len, uint32_t polynomial) {
83  // Source: https://github.com/torvalds/linux/blob/c4cf498dc0241fa2d758dba177634268446afb06/lib/crc32.c
84  int i;
85  while (len--) {
86  crc ^= *p++;
87  for (i = 0; i < 8; i++)
88  crc = (crc >> 1) ^ ((crc & 1) ? polynomial : 0);
89  }
90  return crc;
91 }
92 
93 static inline uint32_t crc32(uint32_t crc, const void *buf, size_t size) {
94 #if 1 // Use a table, as it's faster, but takes up more space
95  // Inspired by: http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/libkern/crc32.c
96  const uint8_t *p = (const uint8_t*)buf;
97  while (size--)
98  crc = pgm_read_dword(&crc32_table[*p++ ^ (crc & 0xFF)]) ^ (crc >> 8);
99  return crc;
100 #else // Can be used to save flash, but is slower
101  return crc32_le_generic(crc, (uint8_t const*)buf, size, CRC32_POLY_LE);
102 #endif
103 };
104 
109 class PS5BT : public BTHID, public PS5Parser {
110 public:
117  PS5BT(BTD *p, bool pair = false, const char *pin = "0000") :
118  BTHID(p, pair, pin), output_sequence_counter(0) {
120  };
121 
126  bool connected() {
127  return BTHID::connected;
128  };
129 
130 protected:
137  virtual void ParseBTHIDData(uint8_t len, uint8_t *buf) {
138  PS5Parser::Parse(len, buf);
139  };
140 
146  virtual void OnInitBTHID() {
148  enable_sixaxis(); // Make the controller send out the entire output report
149 
150  // Only call this is a user function has not been set
151  if (!pFuncOnInit)
152  setLed(Red); // Set the LED to red, as the PS5 controller turns Bluetooth when searching for a device
153  };
154 
156  virtual void ResetBTHID() {
158  };
162  virtual void sendOutputReport(PS5Output *output) {
163  // See the series of patches here: https://patchwork.kernel.org/project/linux-input/cover/20201219062336.72568-1-roderick@gaikai.com/
164  uint8_t buf[1 /* BT DATA Output Report */ + 1 /* report id */ + 1 /* seq_tag */ + 1 /* tag */ + 47 /* common */ + 24 /* reserved */ + 4 /* crc32 */];
165  memset(buf, 0, sizeof(buf));
166 
167  // Send as a Bluetooth HID DATA output report on the interrupt channel
168  buf[0] = 0xA2; // HID BT DATA (0xA0) | Report Type (Output 0x02)
169 
170  buf[0x01] = 0x31; // Report ID
171  buf[0x02] = (output_sequence_counter << 4) | 0x0; // Highest 4-bit is a sequence number, which needs to be increased every report. Lowest 4-bit is tag and can be zero for now.
172  if(++output_sequence_counter == 15)
173  output_sequence_counter = 0;
174  buf[0x03] = 0x10; // Magic number must be set to 0x10
175 
176  buf[0x01 + 3] = 0xFF; // feature flags 1
177  buf[0x02 + 3]= 0xF7; // feature flags 2
178 
179  buf[0x03 + 3] = output->smallRumble; // Small Rumble
180  buf[0x04 + 3] = output->bigRumble; // Big rumble
181 
182  // 5-7 headphone, speaker, mic volume, audio flags
183 
184  buf[0x09 + 3] = (uint8_t)output->microphoneLed;
185 
186  // 0x0A mute flags
187 
188  // Adaptive Triggers: 0x0B-0x14 right, 0x15 unknown, 0x16-0x1F left
189  rightTrigger.processTrigger(&buf[0x0B + 3]); // right
190  leftTrigger.processTrigger(&buf[0x16 + 3]); // left
191 
192  // 0x20-0x24 unknown
193  // 0x25 trigger motor effect strengths
194  // 0x26 speaker volume
195 
196  // player LEDs
197  buf[0x27 + 3] = 0x03; // led brightness, pulse
198  buf[0x2A + 3] = output->disableLeds ? 0x01 : 0x2; // led pulse option
199  // buf[0x2B] LED brightness, 0 = full, 1= medium, 2 = low
200  buf[0x2C + 3] = output->playerLeds; // 5 white player LEDs
201 
202  // lightbar
203  buf[0x2D + 3] = output->r; // Red
204  buf[0x2E + 3] = output->g; // Green
205  buf[0x2F + 3] = output->b; // Blue
206 
207  uint32_t crc = ~crc32(0xFFFFFFFF, buf, sizeof(buf) - 4 /* Do not include the crc32 */); // Note how the report type is also included in the output report
208  buf[75] = crc & 0xFF;
209  buf[76] = (crc >> 8) & 0xFF;
210  buf[77] = (crc >> 16);
211  buf[78] = (crc >> 24);
212 
213  output->reportChanged = false;
214 
215  // Send the Bluetooth DATA output report on the interrupt channel
216  pBtd->L2CAP_Command(hci_handle, buf, sizeof(buf), interrupt_scid[0], interrupt_scid[1]);
217  };
220 private:
221  void enable_sixaxis() { // Command used to make the PS5 controller send out the entire output report
222  // Request the paring info. This makes the controller send out the full report - see: https://patchwork.kernel.org/project/linux-input/cover/20201219062336.72568-1-roderick@gaikai.com/
223  uint8_t buf[2];
224  buf[0] = 0x43; // HID BT Get_report (0x40) | Report Type (Feature 0x03)
225  buf[1] = 0x09; // Report ID for paring info
226 
227  // Send the Bluetooth Get_report Feature report on the control channel
229  };
230 
231  uint8_t output_sequence_counter;
232 };
233 #endif
+
#define pgm_read_dword(addr)
+
bool reportChanged
Definition: PS5Parser.h:145
+
Definition: BTD.h:221
+
uint8_t disableLeds
Definition: PS5Parser.h:142
+
uint8_t playerLeds
Definition: PS5Parser.h:143
+
uint8_t interrupt_scid[2]
Definition: BTHID.h:149
+
bool connected()
Definition: PS5BT.h:126
+ +
bool connected
Definition: BTHID.h:88
+
Definition: PS5BT.h:109
+
PS5BT(BTD *p, bool pair=false, const char *pin="0000")
Definition: PS5BT.h:117
+
#define CRC32_POLY_LE
Definition: PS5BT.h:80
+
uint8_t r
Definition: PS5Parser.h:144
+ +
uint8_t control_scid[2]
Definition: BTHID.h:146
+
virtual void OnInitBTHID()
Definition: PS5BT.h:146
+
void Parse(uint8_t len, uint8_t *buf)
Definition: PS5Parser.cpp:80
+
PS5Trigger leftTrigger
Definition: PS5Parser.h:154
+ +
PS5Trigger rightTrigger
Definition: PS5Parser.h:154
+
virtual void ParseBTHIDData(uint8_t len, uint8_t *buf)
Definition: PS5BT.h:137
+
void(* pFuncOnInit)(void)
Definition: BTD.h:643
+
BTD * pBtd
Definition: BTD.h:646
+
uint8_t microphoneLed
Definition: PS5Parser.h:141
+
uint8_t bigRumble
Definition: PS5Parser.h:140
+
const uint32_t crc32_table[]
Definition: PS5BT.h:29
+
void setLed(uint8_t r, uint8_t g, uint8_t b)
Definition: PS5Parser.h:339
+
uint8_t b
Definition: PS5Parser.h:144
+
uint16_t hci_handle
Definition: BTD.h:649
+
virtual void sendOutputReport(PS5Output *output)
Definition: PS5BT.h:162
+
void processTrigger(uint8_t *buffer)
Apply the trigger data to a PS5 update buffer.
Definition: PS5Trigger.cpp:34
+
uint8_t smallRumble
Definition: PS5Parser.h:140
+ +
void L2CAP_Command(uint16_t handle, uint8_t *data, uint8_t nbytes, uint8_t channelLow=0x01, uint8_t channelHigh=0x00)
Definition: BTD.cpp:1447
+
Definition: BTHID.h:29
+
uint8_t g
Definition: PS5Parser.h:144
+
virtual void ResetBTHID()
Definition: PS5BT.h:156
+
void Reset()
Definition: PS5Parser.cpp:140
+
void pair(void)
Definition: BTHID.h:91
+
+ + + + diff --git a/_p_s5_parser_8cpp.html b/_p_s5_parser_8cpp.html new file mode 100644 index 00000000..9412a727 --- /dev/null +++ b/_p_s5_parser_8cpp.html @@ -0,0 +1,177 @@ + + + + + + + +USB Host Shield 2.0: PS5Parser.cpp File Reference + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + + +
+
+ + +
+ +
+ +
+
+ +
+
PS5Parser.cpp File Reference
+
+
+
#include "PS5Parser.h"
+
+Include dependency graph for PS5Parser.cpp:
+
+
+ + + + + + +
+
+

Go to the source code of this file.

+ + + + +

+Enumerations

enum  DPADEnum {
+  DPAD_UP = 0x0, +DPAD_UP_RIGHT = 0x1, +DPAD_RIGHT = 0x2, +DPAD_RIGHT_DOWN = 0x3, +
+  DPAD_DOWN = 0x4, +DPAD_DOWN_LEFT = 0x5, +DPAD_LEFT = 0x6, +DPAD_LEFT_UP = 0x7, +
+  DPAD_OFF = 0x8, +DPAD_UP = 0x0, +DPAD_UP_RIGHT = 0x1, +DPAD_RIGHT = 0x2, +
+  DPAD_RIGHT_DOWN = 0x3, +DPAD_DOWN = 0x4, +DPAD_DOWN_LEFT = 0x5, +DPAD_LEFT = 0x6, +
+  DPAD_LEFT_UP = 0x7, +DPAD_OFF = 0x8, +DPAD_OFF = 0x0, +DPAD_UP = 0x1, +
+  DPAD_UP_RIGHT = 0x2, +DPAD_RIGHT = 0x3, +DPAD_RIGHT_DOWN = 0x4, +DPAD_DOWN = 0x5, +
+  DPAD_DOWN_LEFT = 0x6, +DPAD_LEFT = 0x7, +DPAD_LEFT_UP = 0x8 +
+ }
 
+

Enumeration Type Documentation

+ +

◆ DPADEnum

+ +
+
+ + + + +
enum DPADEnum
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Enumerator
DPAD_UP 
DPAD_UP_RIGHT 
DPAD_RIGHT 
DPAD_RIGHT_DOWN 
DPAD_DOWN 
DPAD_DOWN_LEFT 
DPAD_LEFT 
DPAD_LEFT_UP 
DPAD_OFF 
DPAD_UP 
DPAD_UP_RIGHT 
DPAD_RIGHT 
DPAD_RIGHT_DOWN 
DPAD_DOWN 
DPAD_DOWN_LEFT 
DPAD_LEFT 
DPAD_LEFT_UP 
DPAD_OFF 
DPAD_OFF 
DPAD_UP 
DPAD_UP_RIGHT 
DPAD_RIGHT 
DPAD_RIGHT_DOWN 
DPAD_DOWN 
DPAD_DOWN_LEFT 
DPAD_LEFT 
DPAD_LEFT_UP 
+ +

Definition at line 24 of file PS5Parser.cpp.

+ +
+
+
+ + + + diff --git a/_p_s5_parser_8cpp__incl.map b/_p_s5_parser_8cpp__incl.map new file mode 100644 index 00000000..d5974310 --- /dev/null +++ b/_p_s5_parser_8cpp__incl.map @@ -0,0 +1,6 @@ + + + + + + diff --git a/_p_s5_parser_8cpp__incl.md5 b/_p_s5_parser_8cpp__incl.md5 new file mode 100644 index 00000000..f83a78ca --- /dev/null +++ b/_p_s5_parser_8cpp__incl.md5 @@ -0,0 +1 @@ +97c8c343dcbc6359725e2020c4a1f735 \ No newline at end of file diff --git a/_p_s5_parser_8cpp__incl.png b/_p_s5_parser_8cpp__incl.png new file mode 100644 index 00000000..546ee2a8 Binary files /dev/null and b/_p_s5_parser_8cpp__incl.png differ diff --git a/_p_s5_parser_8cpp_source.html b/_p_s5_parser_8cpp_source.html new file mode 100644 index 00000000..30061fdb --- /dev/null +++ b/_p_s5_parser_8cpp_source.html @@ -0,0 +1,126 @@ + + + + + + + +USB Host Shield 2.0: PS5Parser.cpp Source File + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+
PS5Parser.cpp
+
+
+Go to the documentation of this file.
1 /* Copyright (C) 2021 Kristian Sloth Lauszus. 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 Sloth Lauszus
14  Web : https://lauszus.com
15  e-mail : lauszus@gmail.com
16 
17  Thanks to Joseph Duchesne for the initial code.
18  Based on Ludwig Füchsl's https://github.com/Ohjurot/DualSense-Windows PS5 port
19  and the series of patches found here: https://patchwork.kernel.org/project/linux-input/cover/20201219062336.72568-1-roderick@gaikai.com/
20  */
21 
22 #include "PS5Parser.h"
23 
24 enum DPADEnum {
25  DPAD_UP = 0x0,
27  DPAD_RIGHT = 0x2,
29  DPAD_DOWN = 0x4,
31  DPAD_LEFT = 0x6,
32  DPAD_LEFT_UP = 0x7,
33  DPAD_OFF = 0x8,
34 };
35 
36 // To enable serial debugging see "settings.h"
37 //#define PRINTREPORT // Uncomment to print the report send by the PS5 Controller
38 
39 bool PS5Parser::checkDpad(ButtonEnum b) {
40  switch (b) {
41  case UP:
42  return ps5Data.btn.dpad == DPAD_LEFT_UP || ps5Data.btn.dpad == DPAD_UP || ps5Data.btn.dpad == DPAD_UP_RIGHT;
43  case RIGHT:
44  return ps5Data.btn.dpad == DPAD_UP_RIGHT || ps5Data.btn.dpad == DPAD_RIGHT || ps5Data.btn.dpad == DPAD_RIGHT_DOWN;
45  case DOWN:
46  return ps5Data.btn.dpad == DPAD_RIGHT_DOWN || ps5Data.btn.dpad == DPAD_DOWN || ps5Data.btn.dpad == DPAD_DOWN_LEFT;
47  case LEFT:
48  return ps5Data.btn.dpad == DPAD_DOWN_LEFT || ps5Data.btn.dpad == DPAD_LEFT || ps5Data.btn.dpad == DPAD_LEFT_UP;
49  default:
50  return false;
51  }
52 }
53 
55  if (b <= LEFT) // Dpad
56  return checkDpad(b);
57  else
58  return ps5Data.btn.val & (1UL << pgm_read_byte(&PS5_BUTTONS[(uint8_t)b]));
59 }
60 
62  uint32_t mask = 1UL << pgm_read_byte(&PS5_BUTTONS[(uint8_t)b]);
63  bool click = buttonClickState.val & mask;
64  buttonClickState.val &= ~mask; // Clear "click" event
65  return click;
66 }
67 
69  if (b == L2) // These are the only analog buttons on the controller
70  return ps5Data.trigger[0];
71  else if (b == R2)
72  return ps5Data.trigger[1];
73  return 0;
74 }
75 
77  return ps5Data.hatValue[(uint8_t)a];
78 }
79 
80 void PS5Parser::Parse(uint8_t len, uint8_t *buf) {
81  if (len > 1 && buf) {
82 #ifdef PRINTREPORT
83  Notify(PSTR("\r\nLen: "), 0x80); Notify(len, 0x80);
84  Notify(PSTR(", data: "), 0x80);
85  for (uint8_t i = 0; i < len; i++) {
86  D_PrintHex<uint8_t > (buf[i], 0x80);
87  Notify(PSTR(" "), 0x80);
88  }
89 #endif
90 
91  if (buf[0] == 0x01) // Check report ID
92  memcpy(&ps5Data, buf + 1, min((uint8_t)(len - 1), MFK_CASTUINT8T sizeof(ps5Data)));
93  else if (buf[0] == 0x31) { // This report is send via Bluetooth, it has an offset of 1 compared to the USB data
94  if (len < 3) {
95 #ifdef DEBUG_USB_HOST
96  Notify(PSTR("\r\nReport is too short: "), 0x80);
97  D_PrintHex<uint8_t > (len, 0x80);
98 #endif
99  return;
100  }
101  memcpy(&ps5Data, buf + 2, min((uint8_t)(len - 2), MFK_CASTUINT8T sizeof(ps5Data)));
102  } else {
103 #ifdef DEBUG_USB_HOST
104  Notify(PSTR("\r\nUnknown report id: "), 0x80);
105  D_PrintHex<uint8_t > (buf[0], 0x80);
106  Notify(PSTR(", len: "), 0x80);
107  D_PrintHex<uint8_t > (len, 0x80);
108 #endif
109  return;
110  }
111 
112  if (ps5Data.btn.val != oldButtonState.val) { // Check if anything has changed
113  buttonClickState.val = ps5Data.btn.val & ~oldButtonState.val; // Update click state variable
114  oldButtonState.val = ps5Data.btn.val;
115 
116  // The DPAD buttons does not set the different bits, but set a value corresponding to the buttons pressed, we will simply set the bits ourself
117  uint8_t newDpad = 0;
118  if (checkDpad(UP))
119  newDpad |= 1 << UP;
120  if (checkDpad(RIGHT))
121  newDpad |= 1 << RIGHT;
122  if (checkDpad(DOWN))
123  newDpad |= 1 << DOWN;
124  if (checkDpad(LEFT))
125  newDpad |= 1 << LEFT;
126  if (newDpad != oldDpad) {
127  buttonClickState.dpad = newDpad & ~oldDpad; // Override values
128  oldDpad = newDpad;
129  }
130  }
131 
132  message_counter++;
133  }
134 
136  sendOutputReport(&ps5Output); // Send output report
137 }
138 
139 
141  uint8_t i;
142  for (i = 0; i < sizeof(ps5Data.hatValue); i++)
143  ps5Data.hatValue[i] = 127; // Center value
144  ps5Data.btn.val = 0;
145  oldButtonState.val = 0;
146  for (i = 0; i < sizeof(ps5Data.trigger); i++)
147  ps5Data.trigger[i] = 0;
148  for (i = 0; i < sizeof(ps5Data.xy.finger)/sizeof(ps5Data.xy.finger[0]); i++)
149  ps5Data.xy.finger[i].touching = 1; // The bit is cleared if the finger is touching the touchpad
150 
151  ps5Data.btn.dpad = DPAD_OFF;
152  oldButtonState.dpad = DPAD_OFF;
153  buttonClickState.dpad = 0;
154  oldDpad = 0;
155 
156  leftTrigger.Reset();
158 
159  ps5Output.bigRumble = ps5Output.smallRumble = 0;
160  ps5Output.microphoneLed = 0;
161  ps5Output.disableLeds = 0;
162  ps5Output.playerLeds = 0;
163  ps5Output.r = ps5Output.g = ps5Output.b = 0;
164  ps5Output.reportChanged = false;
165 };
bool reportChanged
Definition: PS5Parser.h:145
+
uint8_t disableLeds
Definition: PS5Parser.h:142
+
uint8_t playerLeds
Definition: PS5Parser.h:143
+ + + +
AnalogHatEnum
+
uint8_t hatValue[4]
Definition: PS5Parser.h:107
+
DPADEnum
Definition: PS4Parser.cpp:20
+
#define pgm_read_byte(addr)
+
uint32_t val
Definition: PS5Parser.h:78
+ + +
uint8_t r
Definition: PS5Parser.h:144
+
uint8_t touching
Definition: PS5Parser.h:84
+ +
uint8_t trigger[2]
Definition: PS5Parser.h:108
+ +
struct ps5TouchpadXY::@31 finger[2]
+
#define Notify(...)
Definition: message.h:51
+
virtual void sendOutputReport(PS5Output *output)=0
+
void Parse(uint8_t len, uint8_t *buf)
Definition: PS5Parser.cpp:80
+ +
PS5Buttons btn
Definition: PS5Parser.h:112
+
const uint8_t PS5_BUTTONS[]
Definition: PS5Parser.h:30
+
bool getButtonPress(ButtonEnum b)
Definition: PS5Parser.cpp:54
+
PS5Trigger leftTrigger
Definition: PS5Parser.h:154
+
uint8_t getAnalogButton(ButtonEnum b)
Definition: PS5Parser.cpp:68
+ +
ButtonEnum
+
PS5Trigger rightTrigger
Definition: PS5Parser.h:154
+
uint8_t dpad
Definition: PS5Parser.h:58
+
bool reportChanged
Definition: PS5Trigger.h:88
+ + +
uint8_t getAnalogHat(AnalogHatEnum a)
Definition: PS5Parser.cpp:76
+
#define PSTR(str)
+
#define MFK_CASTUINT8T
Definition: settings.h:194
+ +
uint8_t microphoneLed
Definition: PS5Parser.h:141
+
uint8_t bigRumble
Definition: PS5Parser.h:140
+
ps5TouchpadXY xy
Definition: PS5Parser.h:125
+
uint8_t b
Definition: PS5Parser.h:144
+ +
bool getButtonClick(ButtonEnum b)
Definition: PS5Parser.cpp:61
+ +
uint8_t smallRumble
Definition: PS5Parser.h:140
+
uint8_t g
Definition: PS5Parser.h:144
+ +
void Reset()
Definition: PS5Trigger.h:100
+
void Reset()
Definition: PS5Parser.cpp:140
+ +
+ + + + diff --git a/_p_s5_parser_8h.html b/_p_s5_parser_8h.html new file mode 100644 index 00000000..92fe0740 --- /dev/null +++ b/_p_s5_parser_8h.html @@ -0,0 +1,145 @@ + + + + + + + +USB Host Shield 2.0: PS5Parser.h File Reference + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + + +
+
+ + +
+ +
+ +
+
+ +
+
PS5Parser.h File Reference
+
+
+
#include "Usb.h"
+#include "controllerEnums.h"
+#include "PS5Trigger.h"
+
+Include dependency graph for PS5Parser.h:
+
+
+ + + + + +
+
+This graph shows which files directly or indirectly include this file:
+
+
+ + + + + +
+
+

Go to the source code of this file.

+ + + + + + + + + + + + + + +

+Classes

union  PS5Buttons
 
struct  ps5TouchpadXY
 
union  PS5Status
 
struct  PS5Data
 
struct  PS5Output
 
class  PS5Parser
 
+ + + +

+Variables

const uint8_t PS5_BUTTONS []
 
+

Variable Documentation

+ +

◆ PS5_BUTTONS

+ +
+
+ + + + +
const uint8_t PS5_BUTTONS[]
+
+Initial value:
= {
UP,
DOWN,
LEFT,
0x0C,
0x0D,
0x0E,
0x0F,
0x0A,
0x0B,
0x08,
0x09,
0x07,
0x06,
0x05,
0x04,
0x10,
0x11,
0x12,
}
+ + + +

Buttons on the controller

+ +

Definition at line 30 of file PS5Parser.h.

+ +
+
+
+ + + + diff --git a/_p_s5_parser_8h__dep__incl.map b/_p_s5_parser_8h__dep__incl.map new file mode 100644 index 00000000..deb25120 --- /dev/null +++ b/_p_s5_parser_8h__dep__incl.map @@ -0,0 +1,5 @@ + + + + + diff --git a/_p_s5_parser_8h__dep__incl.md5 b/_p_s5_parser_8h__dep__incl.md5 new file mode 100644 index 00000000..9d4bf899 --- /dev/null +++ b/_p_s5_parser_8h__dep__incl.md5 @@ -0,0 +1 @@ +fcee511d6736a910b5372bdfcac4f8bc \ No newline at end of file diff --git a/_p_s5_parser_8h__dep__incl.png b/_p_s5_parser_8h__dep__incl.png new file mode 100644 index 00000000..3cbc7ff0 Binary files /dev/null and b/_p_s5_parser_8h__dep__incl.png differ diff --git a/_p_s5_parser_8h__incl.map b/_p_s5_parser_8h__incl.map new file mode 100644 index 00000000..713c9b1f --- /dev/null +++ b/_p_s5_parser_8h__incl.map @@ -0,0 +1,5 @@ + + + + + diff --git a/_p_s5_parser_8h__incl.md5 b/_p_s5_parser_8h__incl.md5 new file mode 100644 index 00000000..6c2415a3 --- /dev/null +++ b/_p_s5_parser_8h__incl.md5 @@ -0,0 +1 @@ +cde57ab91e7f48eccb70d2bfffb8cf36 \ No newline at end of file diff --git a/_p_s5_parser_8h__incl.png b/_p_s5_parser_8h__incl.png new file mode 100644 index 00000000..9eac8286 Binary files /dev/null and b/_p_s5_parser_8h__incl.png differ diff --git a/_p_s5_parser_8h_source.html b/_p_s5_parser_8h_source.html new file mode 100644 index 00000000..0b92f0e4 --- /dev/null +++ b/_p_s5_parser_8h_source.html @@ -0,0 +1,165 @@ + + + + + + + +USB Host Shield 2.0: PS5Parser.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+
PS5Parser.h
+
+
+Go to the documentation of this file.
1 /* Copyright (C) 2021 Kristian Sloth Lauszus. 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 Sloth Lauszus
14  Web : https://lauszus.com
15  e-mail : lauszus@gmail.com
16 
17  Thanks to Joseph Duchesne for the initial code.
18  Based on Ludwig Füchsl's https://github.com/Ohjurot/DualSense-Windows PS5 port
19  and the series of patches found here: https://patchwork.kernel.org/project/linux-input/cover/20201219062336.72568-1-roderick@gaikai.com/
20  */
21 
22 #ifndef _ps5parser_h_
23 #define _ps5parser_h_
24 
25 #include "Usb.h"
26 #include "controllerEnums.h"
27 #include "PS5Trigger.h"
28 
30 const uint8_t PS5_BUTTONS[] PROGMEM = {
31  UP, // UP
32  RIGHT, // RIGHT
33  DOWN, // DOWN
34  LEFT, // LEFT
35 
36  0x0C, // CREATE
37  0x0D, // OPTIONS
38  0x0E, // L3
39  0x0F, // R3
40 
41  0x0A, // L2
42  0x0B, // R2
43  0x08, // L1
44  0x09, // R1
45 
46  0x07, // TRIANGLE
47  0x06, // CIRCLE
48  0x05, // CROSS
49  0x04, // SQUARE
50 
51  0x10, // PS
52  0x11, // TOUCHPAD
53  0x12, // MICROPHONE
54 };
55 
56 union PS5Buttons {
57  struct {
58  uint8_t dpad : 4;
59  uint8_t square : 1;
60  uint8_t cross : 1;
61  uint8_t circle : 1;
62  uint8_t triangle : 1;
63 
64  uint8_t l1 : 1;
65  uint8_t r1 : 1;
66  uint8_t l2 : 1;
67  uint8_t r2 : 1;
68  uint8_t create : 1;
69  uint8_t menu : 1;
70  uint8_t l3 : 1;
71  uint8_t r3 : 1;
72 
73  uint8_t ps : 1;
74  uint8_t touchpad : 1;
75  uint8_t mic : 1;
76  uint8_t dummy : 5;
77  } __attribute__((packed));
78  uint32_t val : 24;
79 } __attribute__((packed));
80 
81 struct ps5TouchpadXY {
82  struct {
83  uint8_t counter : 7; // Increments every time a finger is touching the touchpad
84  uint8_t touching : 1; // The top bit is cleared if the finger is touching the touchpad
85  uint16_t x : 12;
86  uint16_t y : 12;
87  } __attribute__((packed)) finger[2]; // 0 = first finger, 1 = second finger
88 } __attribute__((packed));
89 
90 union PS5Status {
91  struct {
92  // first byte
93  uint8_t headphone : 1;
94  uint8_t dummy : 2; // Seems to change when a jack is plugged in. First bit stays on when a mic is plugged in.
95  uint8_t usb : 1; // charging
96  uint8_t dummy2: 4;
97 
98  // second byte
99  uint8_t mic : 1;
100  uint8_t dummy3 : 3;
101  } __attribute__((packed));
102  uint16_t val;
103 } __attribute__((packed));
104 
105 struct PS5Data {
106  /* Button and joystick values */
107  uint8_t hatValue[4]; // 0-3 bytes
108  uint8_t trigger[2]; // 4-5
109 
110  uint8_t sequence_number; // 6
111 
112  PS5Buttons btn; // 7-9
113 
114  uint8_t reserved[5]; // 0xA-0xD
115 
116  /* Gyro and accelerometer values */
117  int16_t gyroX, gyroZ, gyroY; // 0x0F - 0x14
118  int16_t accX, accZ, accY; // 0x15-0x1A
120 
121  uint8_t reserved2;
122 
123  // 0x20 - 0x23 touchpad point 1
124  // 0x24 - 0x27 touchpad point 2
126 
127 #if 0 // The status byte depends on if it's sent via USB or Bluetooth, so is not parsed for now
128  uint8_t reserved3; // 0x28
129 
130  uint8_t rightTriggerFeedback; // 0x29
131  uint8_t leftTriggerFeedback; // 0x2A
132  uint8_t reserved4[10]; // 0x2B - 0x34
133 
134  // status bytes 0x35-0x36
135  PS5Status status;
136 #endif
137 } __attribute__((packed));
138 
139 struct PS5Output {
140  uint8_t bigRumble, smallRumble; // Rumble
141  uint8_t microphoneLed;
142  uint8_t disableLeds;
143  uint8_t playerLeds;
144  uint8_t r, g, b; // RGB for lightbar
145  bool reportChanged; // The data is send when data is received from the controller
146 } __attribute__((packed));
147 
149 class PS5Parser {
150 public:
152  PS5Parser() : leftTrigger(), rightTrigger() {
153  Reset();
154  };
155 
157  PS5Trigger leftTrigger, rightTrigger;
158 
170  bool getButtonPress(ButtonEnum b);
171  bool getButtonClick(ButtonEnum b);
181  uint8_t getAnalogButton(ButtonEnum b);
182 
188  uint8_t getAnalogHat(AnalogHatEnum a);
189 
194  uint16_t getX(uint8_t finger = 0) {
195  return ps5Data.xy.finger[finger].x;
196  };
197 
203  uint16_t getY(uint8_t finger = 0) {
204  return ps5Data.xy.finger[finger].y;
205  };
206 
212  bool isTouching(uint8_t finger = 0) {
213  return !(ps5Data.xy.finger[finger].touching); // The bit is cleared when a finger is touching the touchpad
214  };
215 
221  uint8_t getTouchCounter(uint8_t finger = 00) {
222  return ps5Data.xy.finger[finger].counter;
223  };
224 
230  float getAngle(AngleEnum a) {
231  if (a == Pitch)
232  return (atan2f(-ps5Data.accY, -ps5Data.accZ) + PI) * RAD_TO_DEG;
233  else
234  return (atan2f(ps5Data.accX, -ps5Data.accZ) + PI) * RAD_TO_DEG;
235  };
236 
242  int16_t getSensor(SensorEnum s) {
243  switch(s) {
244  case gX:
245  return ps5Data.gyroX;
246  case gY:
247  return ps5Data.gyroY;
248  case gZ:
249  return ps5Data.gyroZ;
250  case aX:
251  return ps5Data.accX;
252  case aY:
253  return ps5Data.accY;
254  case aZ:
255  return ps5Data.accZ;
256  default:
257  return 0;
258  }
259  };
260 
261 #if 0 // Seems to only be available via Bluetooth, so have been disabled for now
262 
266  uint8_t getBatteryLevel() {
267  return ps5Data.status.battery;
268  };
269 #endif
270 
271 #if 0 // These are only valid via USB, so have been commented out for now
272 
276  bool getUsbStatus() {
277  return ps5Data.status.usb;
278  };
279 
284  bool getAudioStatus() {
285  return ps5Data.status.headphone;
286  };
287 
292  bool getMicStatus() {
293  return ps5Data.status.mic;
294  };
295 #endif
296 
298  void setAllOff() {
299  setRumbleOff();
300  setLedOff();
301  };
302 
304  void setRumbleOff() {
305  setRumbleOn(0, 0);
306  };
307 
312  void setRumbleOn(RumbleEnum mode) {
313  if (mode == RumbleLow)
314  setRumbleOn(0x00, 0xFF);
315  else
316  setRumbleOn(0xFF, 0x00);
317  };
318 
324  void setRumbleOn(uint8_t bigRumble, uint8_t smallRumble) {
325  ps5Output.bigRumble = bigRumble;
326  ps5Output.smallRumble = smallRumble;
327  ps5Output.reportChanged = true;
328  };
329 
331  void setLedOff() {
332  setLed(0, 0, 0);
333  };
334 
339  void setLed(uint8_t r, uint8_t g, uint8_t b) {
340  ps5Output.r = r;
341  ps5Output.g = g;
342  ps5Output.b = b;
343  ps5Output.reportChanged = true;
344  };
345 
350  void setLed(ColorsEnum color) {
351  setLed((uint8_t)(color >> 16), (uint8_t)(color >> 8), (uint8_t)(color));
352  };
353 
356  setPlayerLed(0);
357  }
358 
363  void setPlayerLed(uint8_t mask) {
364  ps5Output.playerLeds = mask;
365  ps5Output.reportChanged = true;
366  }
367 
369  void setMicLedOff() {
370  setMicLed(0);
371  }
372 
377  void setMicLed(bool on) {
378  ps5Output.microphoneLed = on ? 1 : 0;
379  ps5Output.reportChanged = true;
380  }
381 
383  uint16_t getMessageCounter(){
384  return message_counter;
385  }
386 
387 protected:
393  void Parse(uint8_t len, uint8_t *buf);
394 
396  void Reset();
397 
402  virtual void sendOutputReport(PS5Output *output) = 0;
403 
404 
405 private:
406  bool checkDpad(ButtonEnum b); // Used to check PS5 DPAD buttons
407 
408  PS5Data ps5Data;
409  PS5Buttons oldButtonState, buttonClickState;
410  PS5Output ps5Output;
411  uint8_t oldDpad;
412  uint16_t message_counter = 0;
413 };
414 #endif
uint8_t getTouchCounter(uint8_t finger=00)
Definition: PS5Parser.h:221
+ +
uint8_t cross
Definition: PS5Parser.h:60
+
uint16_t getX(uint8_t finger=0)
Definition: PS5Parser.h:194
+ +
bool reportChanged
Definition: PS5Parser.h:145
+
uint8_t dummy
Definition: PS5Parser.h:76
+
uint8_t reserved2
Definition: PS5Parser.h:121
+ +
uint8_t circle
Definition: PS5Parser.h:61
+
void setLed(ColorsEnum color)
Definition: PS5Parser.h:350
+
uint8_t disableLeds
Definition: PS5Parser.h:142
+
uint8_t playerLeds
Definition: PS5Parser.h:143
+
uint8_t l2
Definition: PS5Parser.h:66
+
AnalogHatEnum
+
uint16_t getY(uint8_t finger=0)
Definition: PS5Parser.h:203
+
void setMicLed(bool on)
Definition: PS5Parser.h:377
+ + + +
Based on Ludwig Füchsl&#39;s DualSense Windows driver https://github.com/Ohjurot/DualSense-Windows.
+
void setLedOff()
Definition: PS5Parser.h:331
+ +
uint16_t x
Definition: PS5Parser.h:85
+
uint32_t val
Definition: PS5Parser.h:78
+ +
uint16_t val
Definition: PS5Parser.h:102
+
uint8_t r2
Definition: PS5Parser.h:67
+
uint8_t mic
Definition: PS5Parser.h:75
+
void setRumbleOn(uint8_t bigRumble, uint8_t smallRumble)
Definition: PS5Parser.h:324
+
uint8_t r
Definition: PS5Parser.h:144
+
uint8_t touching
Definition: PS5Parser.h:84
+ + +
void setMicLedOff()
Definition: PS5Parser.h:369
+ +
RumbleEnum
+
uint8_t dummy3
Definition: PS5Parser.h:100
+
uint8_t headphone
Definition: PS5Parser.h:93
+
uint8_t touchpad
Definition: PS5Parser.h:74
+
PS5Buttons btn
Definition: PS5Parser.h:112
+
uint8_t l1
Definition: PS5Parser.h:64
+
const uint8_t PS5_BUTTONS[]
Definition: PS5Parser.h:30
+
uint8_t square
Definition: PS5Parser.h:59
+ +
void setRumbleOn(RumbleEnum mode)
Definition: PS5Parser.h:312
+ +
ButtonEnum
+
int16_t getSensor(SensorEnum s)
Definition: PS5Parser.h:242
+
PS5Trigger rightTrigger
Definition: PS5Parser.h:154
+
uint8_t dpad
Definition: PS5Parser.h:58
+
void setRumbleOff()
Definition: PS5Parser.h:304
+
uint8_t r1
Definition: PS5Parser.h:65
+
uint8_t usb
Definition: PS5Parser.h:95
+
void setPlayerLed(uint8_t mask)
Definition: PS5Parser.h:363
+
float getAngle(AngleEnum a)
Definition: PS5Parser.h:230
+
int16_t gyroZ
Definition: PS5Parser.h:117
+
ColorsEnum
+
uint8_t microphoneLed
Definition: PS5Parser.h:141
+ + +
uint8_t mic
Definition: PS5Parser.h:99
+
int16_t accZ
Definition: PS5Parser.h:118
+
AngleEnum
+
ps5TouchpadXY xy
Definition: PS5Parser.h:125
+
uint8_t r3
Definition: PS5Parser.h:71
+ +
uint8_t create
Definition: PS5Parser.h:68
+
void setLed(uint8_t r, uint8_t g, uint8_t b)
Definition: PS5Parser.h:339
+ +
uint16_t y
Definition: PS5Parser.h:86
+
uint8_t menu
Definition: PS5Parser.h:69
+
uint8_t counter
Definition: PS5Parser.h:83
+
uint8_t sequence_number
Definition: PS5Parser.h:110
+
uint8_t triangle
Definition: PS5Parser.h:62
+
uint16_t getMessageCounter()
Definition: PS5Parser.h:383
+
uint8_t dummy2
Definition: PS5Parser.h:96
+
uint8_t smallRumble
Definition: PS5Parser.h:140
+
bool isTouching(uint8_t finger=0)
Definition: PS5Parser.h:212
+
void setAllOff()
Definition: PS5Parser.h:298
+
int32_t sensor_timestamp
Definition: PS5Parser.h:119
+
SensorEnum
+
uint8_t dummy
Definition: PS5Parser.h:94
+ + +
void setPlayerLedOff()
Definition: PS5Parser.h:355
+ +
uint8_t l3
Definition: PS5Parser.h:70
+ +
uint8_t ps
Definition: PS5Parser.h:73
+ +
+ + + + diff --git a/_p_s5_trigger_8cpp.html b/_p_s5_trigger_8cpp.html new file mode 100644 index 00000000..09814a14 --- /dev/null +++ b/_p_s5_trigger_8cpp.html @@ -0,0 +1,100 @@ + + + + + + + +USB Host Shield 2.0: PS5Trigger.cpp File Reference + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + + +
+
+ + +
+ +
+ +
+
+
+
PS5Trigger.cpp File Reference
+
+
+ +

Based on Ludwig Füchsl's DualSense Windows driver https://github.com/Ohjurot/DualSense-Windows. +More...

+
#include "PS5Trigger.h"
+
+Include dependency graph for PS5Trigger.cpp:
+
+
+ + + +
+
+

Go to the source code of this file.

+

Detailed Description

+

Based on Ludwig Füchsl's DualSense Windows driver https://github.com/Ohjurot/DualSense-Windows.

+
Author
Ludwig Füchsl, adapted for USB_Host_Library SAMD by Joseph Duchesne
+
Date
2020-11-25
+ +

MIT License

+

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

+

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

+

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+

Minor updates by Kristian Sloth Lauszus.

+ +

Definition in file PS5Trigger.cpp.

+
+ + + + diff --git a/_p_s5_trigger_8cpp__incl.map b/_p_s5_trigger_8cpp__incl.map new file mode 100644 index 00000000..42d95d5f --- /dev/null +++ b/_p_s5_trigger_8cpp__incl.map @@ -0,0 +1,3 @@ + + + diff --git a/_p_s5_trigger_8cpp__incl.md5 b/_p_s5_trigger_8cpp__incl.md5 new file mode 100644 index 00000000..5dd45910 --- /dev/null +++ b/_p_s5_trigger_8cpp__incl.md5 @@ -0,0 +1 @@ +4d8a1847a0c39433a111a80b8167f291 \ No newline at end of file diff --git a/_p_s5_trigger_8cpp__incl.png b/_p_s5_trigger_8cpp__incl.png new file mode 100644 index 00000000..880838ba Binary files /dev/null and b/_p_s5_trigger_8cpp__incl.png differ diff --git a/_p_s5_trigger_8cpp_source.html b/_p_s5_trigger_8cpp_source.html new file mode 100644 index 00000000..58487b47 --- /dev/null +++ b/_p_s5_trigger_8cpp_source.html @@ -0,0 +1,77 @@ + + + + + + + +USB Host Shield 2.0: PS5Trigger.cpp Source File + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+
PS5Trigger.cpp
+
+
+Go to the documentation of this file.
1 
32 #include "PS5Trigger.h"
33 
34 void PS5Trigger::processTrigger(uint8_t* buffer) {
35  // Switch on effect
36  switch (data.effectType) {
37  // Continious
38  case EffectType::ContinuousResitance:
39  // Mode
40  buffer[0x00] = 0x01;
41  // Parameters
42  buffer[0x01] = data.Continuous.startPosition;
43  buffer[0x02] = data.Continuous.force;
44 
45  break;
46 
47  // Section
48  case EffectType::SectionResitance:
49  // Mode
50  buffer[0x00] = 0x02;
51  // Parameters
52  buffer[0x01] = data.Section.startPosition;
53  buffer[0x02] = data.Section.endPosition;
54 
55  break;
56 
57  // EffectEx
58  case EffectType::EffectEx:
59  // Mode
60  buffer[0x00] = 0x02 | 0x20 | 0x04;
61  // Parameters
62  buffer[0x01] = 0xFF - data.EffectEx.startPosition;
63  // Keep flag
64  if (data.EffectEx.keepEffect)
65  buffer[0x02] = 0x02;
66  // Forces
67  buffer[0x04] = data.EffectEx.beginForce;
68  buffer[0x05] = data.EffectEx.middleForce;
69  buffer[0x06] = data.EffectEx.endForce;
70  // Frequency
71  buffer[0x09] = data.EffectEx.frequency / 2;
72  if(buffer[0x09] < 1) buffer[0x09] = 1; // minimum frequency
73 
74  break;
75 
76  // Calibrate
77  case EffectType::Calibrate:
78  // Mode
79  buffer[0x00] = 0xFC;
80 
81  break;
82 
83  // No resistance / default
84  case EffectType::NoResitance:
85  default:
86  // All zero
87  buffer[0x00] = 0x00;
88  buffer[0x01] = 0x00;
89  buffer[0x02] = 0x00;
90 
91  break;
92  }
93  reportChanged = false;
94 }
Based on Ludwig Füchsl&#39;s DualSense Windows driver https://github.com/Ohjurot/DualSense-Windows.
+
bool reportChanged
Definition: PS5Trigger.h:88
+
void processTrigger(uint8_t *buffer)
Apply the trigger data to a PS5 update buffer.
Definition: PS5Trigger.cpp:34
+
+ + + + diff --git a/_p_s5_trigger_8h.html b/_p_s5_trigger_8h.html new file mode 100644 index 00000000..9d315360 --- /dev/null +++ b/_p_s5_trigger_8h.html @@ -0,0 +1,120 @@ + + + + + + + +USB Host Shield 2.0: PS5Trigger.h File Reference + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + + +
+
+ + +
+ +
+ +
+
+ +
+
PS5Trigger.h File Reference
+
+
+ +

Based on Ludwig Füchsl's DualSense Windows driver https://github.com/Ohjurot/DualSense-Windows. +More...

+
#include <inttypes.h>
+
+Include dependency graph for PS5Trigger.h:
+
+
+ + +
+
+This graph shows which files directly or indirectly include this file:
+
+
+ + + + + + + +
+
+

Go to the source code of this file.

+ + + + +

+Classes

class  PS5Trigger
 
+

Detailed Description

+

Based on Ludwig Füchsl's DualSense Windows driver https://github.com/Ohjurot/DualSense-Windows.

+
Author
Ludwig Füchsl, adapted for USB_Host_Library SAMD by Joseph Duchesne
+
Version
0.1
+
Date
2020-11-25
+ +

MIT License

+

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

+

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

+

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+

Minor updates by Kristian Sloth Lauszus.

+ +

Definition in file PS5Trigger.h.

+
+ + + + diff --git a/_p_s5_trigger_8h__dep__incl.map b/_p_s5_trigger_8h__dep__incl.map new file mode 100644 index 00000000..4f43eed1 --- /dev/null +++ b/_p_s5_trigger_8h__dep__incl.map @@ -0,0 +1,7 @@ + + + + + + + diff --git a/_p_s5_trigger_8h__dep__incl.md5 b/_p_s5_trigger_8h__dep__incl.md5 new file mode 100644 index 00000000..302208f1 --- /dev/null +++ b/_p_s5_trigger_8h__dep__incl.md5 @@ -0,0 +1 @@ +819587c266e34a5fdeb368f8f4a05d54 \ No newline at end of file diff --git a/_p_s5_trigger_8h__dep__incl.png b/_p_s5_trigger_8h__dep__incl.png new file mode 100644 index 00000000..b3f38ec4 Binary files /dev/null and b/_p_s5_trigger_8h__dep__incl.png differ diff --git a/_p_s5_trigger_8h__incl.map b/_p_s5_trigger_8h__incl.map new file mode 100644 index 00000000..c7e6e901 --- /dev/null +++ b/_p_s5_trigger_8h__incl.map @@ -0,0 +1,2 @@ + + diff --git a/_p_s5_trigger_8h__incl.md5 b/_p_s5_trigger_8h__incl.md5 new file mode 100644 index 00000000..a3c38e2e --- /dev/null +++ b/_p_s5_trigger_8h__incl.md5 @@ -0,0 +1 @@ +933b51d2a99b1ab644e570075ab908af \ No newline at end of file diff --git a/_p_s5_trigger_8h__incl.png b/_p_s5_trigger_8h__incl.png new file mode 100644 index 00000000..ef677ba9 Binary files /dev/null and b/_p_s5_trigger_8h__incl.png differ diff --git a/_p_s5_trigger_8h_source.html b/_p_s5_trigger_8h_source.html new file mode 100644 index 00000000..54c60998 --- /dev/null +++ b/_p_s5_trigger_8h_source.html @@ -0,0 +1,82 @@ + + + + + + + +USB Host Shield 2.0: PS5Trigger.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+
PS5Trigger.h
+
+
+Go to the documentation of this file.
1 
33 #ifndef _ps5trigger_h_
34 #define _ps5trigger_h_
35 
36 #include <inttypes.h>
37 
38 class PS5Trigger {
39 private:
40  // Type of trigger effect
41  typedef enum _EffectType : uint8_t {
42  NoResitance = 0x00, // No resistance is applied
43  ContinuousResitance = 0x01, // Continuous Resitance is applied
44  SectionResitance = 0x02, // Seciton resistance is appleyed
45  EffectEx = 0x26, // Extended trigger effect
46  Calibrate = 0xFC, // Calibrate triggers
47  } EffectType;
48 
49  // Trigger effect
50  typedef struct _EffectData {
51  // Trigger effect type
52  EffectType effectType;
53 
54  // Union for effect parameters
55  union {
56  // Union one raw data
57  uint8_t _u1_raw[6];
58 
59  // For type == ContinuousResitance
60  struct {
61  uint8_t startPosition; // Start position of resistance
62  uint8_t force; // Force of resistance
63  uint8_t _pad[4]; // PAD / UNUSED
64  } __attribute__((packed)) Continuous;
65 
66  // For type == SectionResitance
67  struct {
68  uint8_t startPosition; // Start position of resistance
69  uint8_t endPosition; // End position of resistance (>= start)
70  uint8_t _pad[4]; // PAD / UNUSED
71  } __attribute__((packed)) Section;
72 
73  // For type == EffectEx
74  struct {
75  uint8_t startPosition; // Position at witch the effect starts
76  bool keepEffect; // Wher the effect should keep playing when trigger goes beyond 255
77  uint8_t beginForce; // Force applied when trigger >= (255 / 2)
78  uint8_t middleForce; // Force applied when trigger <= (255 / 2)
79  uint8_t endForce; // Force applied when trigger is beyond 255
80  uint8_t frequency; // Vibration frequency of the trigger
81  } __attribute__((packed)) EffectEx;
82  } __attribute__((packed));
83  } __attribute__((packed)) EffectData;
84 
85  EffectData data;
86 
87 public:
88  bool reportChanged = false;
89 
95  void processTrigger(uint8_t* buffer);
96 
100  void Reset() {
101  data.effectType = EffectType::NoResitance;
102 
103  reportChanged = false;
104  };
105 
110  data.effectType = EffectType::NoResitance;
111 
112  reportChanged = true;
113  };
114 
120  void setTriggerForce(uint8_t start, uint8_t force) {
121  if (force == 0)
122  data.effectType = EffectType::NoResitance;
123  else {
124  data.effectType = EffectType::ContinuousResitance;
125  data.Continuous.startPosition = start;
126  data.Continuous.force = force;
127  }
128 
129  reportChanged = true;
130  };
131 
137  void setTriggerForceSection(uint8_t start, uint8_t end) {
138  data.effectType = EffectType::SectionResitance;
139  data.Section.startPosition = start;
140  data.Section.endPosition = end;
141 
142  reportChanged = true;
143  };
144 
154  void setTriggerForceEffect(uint8_t start, bool keep, uint8_t begin_force, uint8_t mid_force, uint8_t end_force, uint8_t frequency) {
155  data.effectType = EffectType::SectionResitance;
156  data.EffectEx.startPosition = start;
157  data.EffectEx.keepEffect = keep;
158  data.EffectEx.beginForce = begin_force;
159  data.EffectEx.middleForce = mid_force;
160  data.EffectEx.endForce = end_force;
161  data.EffectEx.frequency = frequency;
162 
163  reportChanged = true;
164  };
165 
166 };
167 
168 #endif
void clearTriggerForce()
Definition: PS5Trigger.h:109
+
void setTriggerForceEffect(uint8_t start, bool keep, uint8_t begin_force, uint8_t mid_force, uint8_t end_force, uint8_t frequency)
Definition: PS5Trigger.h:154
+
bool reportChanged
Definition: PS5Trigger.h:88
+ +
void processTrigger(uint8_t *buffer)
Apply the trigger data to a PS5 update buffer.
Definition: PS5Trigger.cpp:34
+
void Reset()
Definition: PS5Trigger.h:100
+
void setTriggerForceSection(uint8_t start, uint8_t end)
Definition: PS5Trigger.h:137
+
void setTriggerForce(uint8_t start, uint8_t force)
Definition: PS5Trigger.h:120
+
+ + + + diff --git a/_p_s5_u_s_b_8h.html b/_p_s5_u_s_b_8h.html new file mode 100644 index 00000000..7fee2703 --- /dev/null +++ b/_p_s5_u_s_b_8h.html @@ -0,0 +1,142 @@ + + + + + + + +USB Host Shield 2.0: PS5USB.h File Reference + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + + +
+
+ + +
+ +
+ +
+
+ +
+
PS5USB.h File Reference
+
+
+
#include "hiduniversal.h"
+#include "PS5Parser.h"
+
+Include dependency graph for PS5USB.h:
+
+
+ + + + + + + + + + +
+
+

Go to the source code of this file.

+ + + + +

+Classes

class  PS5USB
 
+ + + + + +

+Macros

#define PS5_VID   0x054C
 
#define PS5_PID   0x0CE6
 
+

Macro Definition Documentation

+ +

◆ PS5_VID

+ +
+
+ + + + +
#define PS5_VID   0x054C
+
+ +

Definition at line 27 of file PS5USB.h.

+ +
+
+ +

◆ PS5_PID

+ +
+
+ + + + +
#define PS5_PID   0x0CE6
+
+ +

Definition at line 28 of file PS5USB.h.

+ +
+
+
+ + + + diff --git a/_p_s5_u_s_b_8h__incl.map b/_p_s5_u_s_b_8h__incl.map new file mode 100644 index 00000000..bf9d475f --- /dev/null +++ b/_p_s5_u_s_b_8h__incl.map @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/_p_s5_u_s_b_8h__incl.md5 b/_p_s5_u_s_b_8h__incl.md5 new file mode 100644 index 00000000..fe18e879 --- /dev/null +++ b/_p_s5_u_s_b_8h__incl.md5 @@ -0,0 +1 @@ +3be065c8ceb7b72bb0cc17dc2e48f08f \ No newline at end of file diff --git a/_p_s5_u_s_b_8h__incl.png b/_p_s5_u_s_b_8h__incl.png new file mode 100644 index 00000000..11e3ef3f Binary files /dev/null and b/_p_s5_u_s_b_8h__incl.png differ diff --git a/_p_s5_u_s_b_8h_source.html b/_p_s5_u_s_b_8h_source.html new file mode 100644 index 00000000..804a3faf --- /dev/null +++ b/_p_s5_u_s_b_8h_source.html @@ -0,0 +1,116 @@ + + + + + + + +USB Host Shield 2.0: PS5USB.h Source File + + + + + + + + + + +
+
+ + + + + + +
+
USB Host Shield 2.0 +
+
+
+ + + + + + + +
+ +
+
+ + +
+ +
+ +
+
+
PS5USB.h
+
+
+Go to the documentation of this file.
1 /* Copyright (C) 2021 Kristian Sloth Lauszus. 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 Sloth Lauszus
14  Web : https://lauszus.com
15  e-mail : lauszus@gmail.com
16 
17  Thanks to Joseph Duchesne for the initial port. Data structure mapping partially based
18  on values from Ludwig Füchsl's https://github.com/Ohjurot/DualSense-Windows
19  */
20 
21 #ifndef _ps5usb_h_
22 #define _ps5usb_h_
23 
24 #include "hiduniversal.h"
25 #include "PS5Parser.h"
26 
27 #define PS5_VID 0x054C // Sony Corporation
28 #define PS5_PID 0x0CE6 // PS5 Controller
29 
34 class PS5USB : public HIDUniversal, public PS5Parser {
35 public:
40  PS5USB(USB *p) :
41  HIDUniversal(p) {
43  };
44 
49  bool connected() {
51  };
52 
57  void attachOnInit(void (*funcOnInit)(void)) {
58  pFuncOnInit = funcOnInit;
59  };
60 
61 protected:
70  virtual void ParseHIDData(USBHID *hid __attribute__((unused)), bool is_rpt_id __attribute__((unused)), uint8_t len, uint8_t *buf) {
72  PS5Parser::Parse(len, buf);
73  };
74 
80  virtual uint8_t OnInitSuccessful() {
83  if (pFuncOnInit)
84  pFuncOnInit(); // Call the user function
85  else
86  setLed(Red); // Set the LED to red, so it is consistent with the PS5BT driver
87  };
88  return 0;
89  };
93  virtual void sendOutputReport(PS5Output *output) { // Source: https://github.com/chrippa/ds4drv
94  // PS4 Source: https://github.com/chrippa/ds4drv
95  // PS5 values from https://www.reddit.com/r/gamedev/comments/jumvi5/dualsense_haptics_leds_and_more_hid_output_report/,
96  // Ludwig Füchsl's https://github.com/Ohjurot/DualSense-Windows and
97  // the series of patches found here: https://patchwork.kernel.org/project/linux-input/cover/20201219062336.72568-1-roderick@gaikai.com/
98  uint8_t buf[1 /* report id */ + 47 /* common */];
99  memset(buf, 0, sizeof(buf));
100 
101  buf[0x00] = 0x02; // Report ID
102 
103  buf[0x01] = 0xFF; // feature flags 1
104  buf[0x02]= 0xF7; // feature flags 2
105 
106  buf[0x03] = output->smallRumble; // Small Rumble
107  buf[0x04] = output->bigRumble; // Big rumble
108 
109  // 5-7 headphone, speaker, mic volume, audio flags
110 
111  buf[0x09] = (uint8_t)output->microphoneLed;
112 
113  // 0x0A mute flags
114 
115  // Adaptive Triggers: 0x0B-0x14 right, 0x15 unknown, 0x16-0x1F left
116  rightTrigger.processTrigger(&buf[0x0B]); // right
117  leftTrigger.processTrigger(&buf[0x16]); // left
118 
119  // 0x20-0x24 unknown
120  // 0x25 trigger motor effect strengths
121  // 0x26 speaker volume
122 
123  // player LEDs
124  buf[0x27] = 0x03; // led brightness, pulse
125  buf[0x2A] = output->disableLeds ? 0x01 : 0x2; // led pulse option
126  // buf[0x2B] LED brightness, 0 = full, 1= medium, 2 = low
127  buf[0x2C] = output->playerLeds; // 5 white player LEDs
128 
129  // lightbar
130  buf[0x2D] = output->r; // Red
131  buf[0x2E] = output->g; // Green
132  buf[0x2F] = output->b; // Blue
133 
134  output->reportChanged = false;
135 
136  // There is no need to calculate a crc32 when the controller is connected via USB
137 
138  pUsb->outTransfer(bAddress, epInfo[ hidInterfaces[0].epIndex[epInterruptOutIndex] ].epAddr, sizeof(buf), buf);
139  };
149  virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
150  return (vid == PS5_VID && pid == PS5_PID);
151  };
154 private:
155  void (*pFuncOnInit)(void); // Pointer to function called in onInit()
156 };
157 #endif
+
Definition: usbhid.h:143
+
virtual void ParseHIDData(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
Definition: PS5USB.h:70
+
USB * pUsb
Definition: usbhid.h:145
+
bool reportChanged
Definition: PS5Parser.h:145
+
uint8_t disableLeds
Definition: PS5Parser.h:142
+
uint8_t playerLeds
Definition: PS5Parser.h:143
+ +
virtual bool isReady()
Definition: hidcomposite.h:99
+
HIDInterface hidInterfaces[maxHidInterfaces]
Definition: hidcomposite.h:64
+
EpInfo epInfo[totalEndpoints]
Definition: hidcomposite.h:63
+
virtual uint8_t OnInitSuccessful()
Definition: PS5USB.h:80
+
uint8_t r
Definition: PS5Parser.h:144
+ +
virtual bool VIDPIDOK(uint16_t vid, uint16_t pid)
Definition: PS5USB.h:149
+
PS5USB(USB *p)
Definition: PS5USB.h:40
+
void Parse(uint8_t len, uint8_t *buf)
Definition: PS5Parser.cpp:80
+
void attachOnInit(void(*funcOnInit)(void))
Definition: PS5USB.h:57
+
PS5Trigger leftTrigger
Definition: PS5Parser.h:154
+
uint8_t outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t *data)
Definition: Usb.cpp:303
+
static const uint8_t epInterruptOutIndex
Definition: usbhid.h:150
+
uint8_t bAddress
Definition: usbhid.h:146
+
PS5Trigger rightTrigger
Definition: PS5Parser.h:154
+
uint16_t PID
Definition: hidcomposite.h:71
+
Definition: PS5USB.h:34
+ +
uint8_t microphoneLed
Definition: PS5Parser.h:141
+
uint16_t VID
Definition: hidcomposite.h:71
+
#define PS5_PID
Definition: PS5USB.h:28
+
uint8_t bigRumble
Definition: PS5Parser.h:140
+
void setLed(uint8_t r, uint8_t g, uint8_t b)
Definition: PS5Parser.h:339
+
uint8_t b
Definition: PS5Parser.h:144
+
bool connected()
Definition: PS5USB.h:49
+
void processTrigger(uint8_t *buffer)
Apply the trigger data to a PS5 update buffer.
Definition: PS5Trigger.cpp:34
+
Definition: UsbCore.h:210
+
uint8_t smallRumble
Definition: PS5Parser.h:140
+ +
uint8_t g
Definition: PS5Parser.h:144
+
void Reset()
Definition: PS5Parser.cpp:140
+
#define PS5_VID
Definition: PS5USB.h:27
+
virtual void sendOutputReport(PS5Output *output)
Definition: PS5USB.h:93
+ +
+ + + + diff --git a/_p_s_buzz_8h_source.html b/_p_s_buzz_8h_source.html index 4761be98..7bbcda36 100644 --- a/_p_s_buzz_8h_source.html +++ b/_p_s_buzz_8h_source.html @@ -63,9 +63,8 @@ $(function() {
PSBuzz.h
-Go to the documentation of this file.
1 /* Copyright (C) 2014 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 #ifndef _psbuzz_h_
19 #define _psbuzz_h_
20 
21 #include "hiduniversal.h"
22 #include "controllerEnums.h"
23 
24 #define PSBUZZ_VID 0x054C // Sony Corporation
25 #define PSBUZZ_PID 0x1000 // PS Buzz Controller
26 
29  struct {
30  uint8_t red : 1;
31  uint8_t yellow : 1;
32  uint8_t green : 1;
33  uint8_t orange : 1;
34  uint8_t blue : 1;
35  } __attribute__((packed)) btn[4];
36  uint32_t val : 20;
37 } __attribute__((packed));
38 
43 class PSBuzz : public HIDUniversal {
44 public:
49  PSBuzz(USB *p) :
50  HIDUniversal(p) {
51  Reset();
52  };
53 
58  bool connected() {
60  };
61 
66  void attachOnInit(void (*funcOnInit)(void)) {
67  pFuncOnInit = funcOnInit;
68  };
69 
82  bool getButtonPress(ButtonEnum b, uint8_t controller = 0);
83  bool getButtonClick(ButtonEnum b, uint8_t controller = 0);
95  void setLedRaw(bool value, uint8_t controller = 0);
96 
98  void setLedOffAll() {
99  for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw
100  ledState[i] = false; // Just an easy way to set all four off at the same time
101  setLedRaw(false); // Turn the LED off, on all four controllers
102  };
103 
108  void setLedOff(uint8_t controller = 0) {
109  setLedRaw(false, controller);
110  };
111 
112 
114  void setLedOnAll() {
115  for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw
116  ledState[i] = true; // Just an easy way to set all four off at the same time
117  setLedRaw(true); // Turn the LED on, on all four controllers
118  };
119 
124  void setLedOn(uint8_t controller = 0) {
125  setLedRaw(true, controller);
126  };
127 
132  void setLedToggle(uint8_t controller = 0) {
133  setLedRaw(!ledState[controller], controller);
134  };
137 protected:
146  void ParseHIDData(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
147 
153  uint8_t OnInitSuccessful();
157  void Reset() {
158  psbuzzButtons.val = 0;
159  oldButtonState.val = 0;
160  buttonClickState.val = 0;
161  for (uint8_t i = 0; i < sizeof(ledState); i++)
162  ledState[i] = 0;
163  };
164 
172  virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
173  return (vid == PSBUZZ_VID && pid == PSBUZZ_PID);
174  };
177 private:
178  void (*pFuncOnInit)(void); // Pointer to function called in onInit()
179 
180  void PSBuzz_Command(uint8_t *data, uint16_t nbytes);
181 
182  PSBUZZButtons psbuzzButtons, oldButtonState, buttonClickState;
183  bool ledState[4];
184 };
185 #endif
Definition: usbhid.h:143
+Go to the documentation of this file.
1 /* Copyright (C) 2014 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 #ifndef _psbuzz_h_
19 #define _psbuzz_h_
20 
21 #include "hiduniversal.h"
22 #include "controllerEnums.h"
23 
24 #define PSBUZZ_VID 0x054C // Sony Corporation
25 #define PSBUZZ_PID 0x1000 // PS Buzz Controller
26 
29  struct {
30  uint8_t red : 1;
31  uint8_t yellow : 1;
32  uint8_t green : 1;
33  uint8_t orange : 1;
34  uint8_t blue : 1;
35  } __attribute__((packed)) btn[4];
36  uint32_t val : 20;
37 } __attribute__((packed));
38 
43 class PSBuzz : public HIDUniversal {
44 public:
49  PSBuzz(USB *p) :
50  HIDUniversal(p) {
51  Reset();
52  };
53 
58  bool connected() {
60  };
61 
66  void attachOnInit(void (*funcOnInit)(void)) {
67  pFuncOnInit = funcOnInit;
68  };
69 
82  bool getButtonPress(ButtonEnum b, uint8_t controller = 0);
83  bool getButtonClick(ButtonEnum b, uint8_t controller = 0);
95  void setLedRaw(bool value, uint8_t controller = 0);
96 
98  void setLedOffAll() {
99  for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw
100  ledState[i] = false; // Just an easy way to set all four off at the same time
101  setLedRaw(false); // Turn the LED off, on all four controllers
102  };
103 
108  void setLedOff(uint8_t controller = 0) {
109  setLedRaw(false, controller);
110  };
111 
112 
114  void setLedOnAll() {
115  for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw
116  ledState[i] = true; // Just an easy way to set all four off at the same time
117  setLedRaw(true); // Turn the LED on, on all four controllers
118  };
119 
124  void setLedOn(uint8_t controller = 0) {
125  setLedRaw(true, controller);
126  };
127 
132  void setLedToggle(uint8_t controller = 0) {
133  setLedRaw(!ledState[controller], controller);
134  };
137 protected:
146  void ParseHIDData(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
147 
153  uint8_t OnInitSuccessful();
157  void Reset() {
158  psbuzzButtons.val = 0;
159  oldButtonState.val = 0;
160  buttonClickState.val = 0;
161  for (uint8_t i = 0; i < sizeof(ledState); i++)
162  ledState[i] = 0;
163  };
164 
172  virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
173  return (vid == PSBUZZ_VID && pid == PSBUZZ_PID);
174  };
177 private:
178  void (*pFuncOnInit)(void); // Pointer to function called in onInit()
179 
180  void PSBuzz_Command(uint8_t *data, uint16_t nbytes);
181 
182  PSBUZZButtons psbuzzButtons, oldButtonState, buttonClickState;
183  bool ledState[4];
184 };
185 #endif
Definition: usbhid.h:143
uint8_t red
Definition: PSBuzz.h:30
-
struct PSBUZZButtons::@29 btn[4]
void setLedToggle(uint8_t controller=0)
Definition: PSBuzz.h:132
void attachOnInit(void(*funcOnInit)(void))
Definition: PSBuzz.h:66
void Reset()
Definition: PSBuzz.h:157
@@ -86,6 +85,7 @@ $(function() {
uint16_t VID
Definition: hidcomposite.h:71
PSBuzz(USB *p)
Definition: PSBuzz.h:49
+
struct PSBUZZButtons::@39 btn[4]
void setLedOnAll()
Definition: PSBuzz.h:114
Definition: UsbCore.h:210
void setLedOn(uint8_t controller=0)
Definition: PSBuzz.h:124
diff --git a/_r_e_a_d_m_e_8md_source.html b/_r_e_a_d_m_e_8md_source.html index 8518808d..bf006baf 100644 --- a/_r_e_a_d_m_e_8md_source.html +++ b/_r_e_a_d_m_e_8md_source.html @@ -63,7 +63,7 @@ $(function() {
README.md
-Go to the documentation of this file.
1 # USB Host Library Rev. 2.0
2 
3 The code is released under the GNU General Public License.
4 __________
5 [![](https://github.com/felis/USB_Host_Shield_2.0/workflows/CI/badge.svg)](https://github.com/felis/USB_Host_Shield_2.0/actions?query=branch%3Amaster)
6 
7 # Summary
8 This is Revision 2.0 of MAX3421E-based USB Host Shield Library for AVR's.
9 
10 Project main web site is: <https://chome.nerpa.tech/arduino_usb_host_shield_projects/>.
11 
12 Some information can also be found at: <http://blog.tkjelectronics.dk/>.
13 
14 The shield can be purchased from [TKJ Electronics](http://tkjelectronics.com/): <http://shop.tkjelectronics.dk/product_info.php?products_id=43>.
15 
16 ![USB Host Shield](http://shop.tkjelectronics.dk/images/USB_Host_Shield1.jpg)
17 
18 For more information about the hardware see the [Hardware Manual](https://chome.nerpa.tech/usb-host-shield-hardware-manual/).
19 
20 # Developed By
21 
22 * __Oleg Mazurov__ - <mazurov@gmail.com>
23 * __Alexei Glushchenko__ - <alex-gl@mail.ru>
24  * Developers of the USB Core, HID, FTDI, ADK, ACM, and PL2303 libraries
25 * __Kristian Sloth Lauszus__ - <lauszus@gmail.com>
26  * Developer of the [BTD](#bluetooth-libraries), [BTHID](#bthid-library), [SPP](#spp-library), [PS4](#ps4-library), [PS3](#ps3-library), [Wii](#wii-library), [Xbox](#xbox-library), and [PSBuzz](#ps-buzz-library) libraries
27 * __Andrew Kroll__ - <xxxajk@gmail.com>
28  * Major contributor to mass storage code
29 * __guruthree__
30  * [Xbox ONE](#xbox-one-library) controller support
31 * __Yuuichi Akagawa__ - [\@YuuichiAkagawa](https://twitter.com/yuuichiakagawa)
32  * Developer of the [MIDI](#midi-library) library
33 
34 
35 # Table of Contents
36 
37 * [How to include the library](#how-to-include-the-library)
38  * [Arduino Library Manager](#arduino-library-manager)
39  * [Manual installation](#manual-installation)
40 * [How to use the library](#how-to-use-the-library)
41  * [Documentation](#documentation)
42  * [Enable debugging](#enable-debugging)
43  * [Boards](#boards)
44  * [Bluetooth libraries](#bluetooth-libraries)
45  * [BTHID library](#bthid-library)
46  * [SPP library](#spp-library)
47  * [PS4 Library](#ps4-library)
48  * [PS3 Library](#ps3-library)
49  * [Xbox Libraries](#xbox-libraries)
50  * [Xbox library](#xbox-library)
51  * [Xbox 360 Library](#xbox-360-library)
52  * [Xbox ONE Library](#xbox-one-library)
53  * [Xbox ONE S Library](#xbox-one-s-library)
54  * [Wii library](#wii-library)
55  * [PS Buzz Library](#ps-buzz-library)
56  * [HID Libraries](#hid-libraries)
57  * [MIDI Library](#midi-library)
58 * [Interface modifications](#interface-modifications)
59 * [FAQ](#faq)
60 
61 # How to include the library
62 
63 ### Arduino Library Manager
64 
65 First install Arduino IDE version 1.6.2 or newer, then simply use the Arduino Library Manager to install the library.
66 
67 Please see the following page for instructions: <http://www.arduino.cc/en/Guide/Libraries#toc3>.
68 
69 ### Manual installation
70 
71 First download the library by clicking on the following link: <https://github.com/felis/USB_Host_Shield_2.0/archive/master.zip>.
72 
73 Then uncompress the zip folder and rename the directory to "USB\_Host\_Shield\_20", as any special characters are not supported by the Arduino IDE.
74 
75 Now open up the Arduino IDE and open "File>Preferences". There you will see the location of your sketchbook. Open that directory and create a directory called "libraries" inside that directory.
76 Now move the "USB\_Host\_Shield\_20" directory to the "libraries" directory.
77 
78 The final structure should look like this:
79 
80 * Arduino/
81  * libraries/
82  * USB\_Host\_Shield\_20/
83 
84 Now quit the Arduino IDE and reopen it.
85 
86 Now you should be able to go open all the examples codes by navigating to "File>Examples>USB\_Host\_Shield\_20" and then select the example you will like to open.
87 
88 For more information visit the following sites: <http://arduino.cc/en/Guide/Libraries> and <https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use>.
89 
90 # How to use the library
91 
92 ### Documentation
93 
94 Documentation for the library can be found at the following link: <https://felis.github.io/USB_Host_Shield_2.0/>.
95 
96 ### Enable debugging
97 
98 By default serial debugging is disabled. To turn it on simply change ```ENABLE_UHS_DEBUGGING``` to 1 in [settings.h](settings.h) like so:
99 
100 ```C++
101 #define ENABLE_UHS_DEBUGGING 1
102 ```
103 
104 ### Boards
105 
106 Currently the following boards are supported by the library:
107 
108 * All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.)
109 * Arduino Due, Intel Galileo, Intel Galileo 2, and Intel Edison
110  * Note that the Intel Galileo uses pin 2 and 3 as INT and SS pin respectively by default, so some modifications to the shield are needed. See the "Interface modifications" section in the [hardware manual](https://chome.nerpa.tech/usb-host-shield-hardware-manual) for more information.
111  * Note native USB host is not supported on any of these platforms. You will have to use the shield for now.
112 * Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, Teensy 3.x, Teensy LC and Teensy 4.x)
113  * Note if you are using the Teensy 3.x you should download this SPI library as well: <https://github.com/xxxajk/spi4teensy3>. You should then add ```#include <spi4teensy3.h>``` to your .ino file.
114 * Balanduino
115 * Sanguino
116 * Black Widdow
117 * RedBearLab nRF51822
118 * Digilent chipKIT
119  * Please see: <https://chome.nerpa.tech/mcu/usb/running-usb-host-code-on-digilent-chipkit-board>.
120 * STM32F4
121  * Currently the [NUCLEO-F446RE](http://www.st.com/web/catalog/tools/FM116/SC959/SS1532/LN1847/PF262063) is supported featuring the STM32F446. Take a look at the following example code: <https://github.com/Lauszus/Nucleo_F446RE_USBHost>.
122 * ESP8266 is supported using the [ESP8266 Arduino core](https://github.com/esp8266/Arduino)
123  * Note it uses pin 15 and 5 for SS and INT respectively
124  * Also please be aware that:
125  * GPIO16 is **NOT** usable, as it will be used for some other purposes. For example, reset the SoC itself from sleep mode.
126  * GPIO6 to 11 is also **NOT** usable, as they are used to connect SPI flash chip and it is used for storing the executable binary content.
127 * ESP32 is supported using the [arduino-esp32](https://github.com/espressif/arduino-esp32/)
128  * GPIO5 : SS, GPIO17 : INT, GPIO18 : SCK, GPIO19 : MISO, GPIO23 : MOSI
129 
130 The following boards need to be activated manually in [settings.h](settings.h):
131 
132 * Arduino Mega ADK
133  * If you are using Arduino 1.5.5 or newer there is no need to activate the Arduino Mega ADK manually
134 * Black Widdow
135 
136 Simply set the corresponding value to 1 instead of 0.
137 
138 ### [Bluetooth libraries](BTD.cpp)
139 
140 The [BTD library](BTD.cpp) is a general purpose library for an ordinary Bluetooth dongle.
141 This library make it easy to add support for different Bluetooth services like a PS3 or a Wii controller or SPP which is a virtual serial port via Bluetooth.
142 Some different examples can be found in the [example directory](examples/Bluetooth).
143 
144 The BTD library also makes it possible to use multiple services at once, the following example sketch is an example of this:
145 [PS3SPP.ino](examples/Bluetooth/PS3SPP/PS3SPP.ino).
146 
147 ### [BTHID library](BTHID.cpp)
148 
149 The [Bluetooth HID library](BTHID.cpp) allows you to connect HID devices via Bluetooth to the USB Host Shield.
150 
151 Currently HID mice and keyboards are supported.
152 
153 It uses the standard Boot protocol by default, but it is also able to use the Report protocol as well. You would simply have to call ```setProtocolMode()``` and then parse ```HID_RPT_PROTOCOL``` as an argument. You will then have to modify the parser for your device. See the example: [BTHID.ino](examples/Bluetooth/BTHID/BTHID.ino) for more information.
154 
155 The [PS4 library](#ps4-library) also uses this class to handle all Bluetooth communication.
156 
157 For information see the following blog post: <http://blog.tkjelectronics.dk/2013/12/bluetooth-hid-devices-now-supported-by-the-usb-host-library/>.
158 
159 ### [SPP library](SPP.cpp)
160 
161 SPP stands for "Serial Port Profile" and is a Bluetooth protocol that implements a virtual comport which allows you to send data back and forth from your computer/phone to your Arduino via Bluetooth.
162 It has been tested successfully on Windows, Mac OS X, Linux, and Android.
163 
164 Take a look at the [SPP.ino](examples/Bluetooth/SPP/SPP.ino) example for more information.
165 
166 More information can be found at these blog posts:
167 
168 * <http://chome.nerpa.tech/mcu/bluetooth-rfcommspp-service-support-for-usb-host-2-0-library-released>
169 * <http://blog.tkjelectronics.dk/2012/07/rfcommspp-library-for-arduino/>
170 
171 To implement the SPP protocol I used a Bluetooth sniffing tool called [PacketLogger](http://www.tkjelectronics.com/uploads/PacketLogger.zip) developed by Apple.
172 It enables me to see the Bluetooth communication between my Mac and any device.
173 
174 ### PS4 Library
175 
176 The PS4BT library is split up into the [PS4BT](PS4BT.h) and the [PS4USB](PS4USB.h) library. These allow you to use the Sony PS4 controller via Bluetooth and USB.
177 
178 The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) and [PS4USB.ino](examples/PS4USB/PS4USB.ino) examples shows how to easily read the buttons, joysticks, touchpad and IMU on the controller via Bluetooth and USB respectively. It is also possible to control the rumble and light on the controller and get the battery level.
179 
180 Before you can use the PS4 controller via Bluetooth you will need to pair with it.
181 
182 Simply create the PS4BT instance like so: ```PS4BT PS4(&Btd, PAIR);``` and then hold down the Share button and then hold down the PS without releasing the Share button. The PS4 controller will then start to blink rapidly indicating that it is in pairing mode.
183 
184 It should then automatically pair the dongle with your controller. This only have to be done once.
185 
186 For information see the following blog post: <http://blog.tkjelectronics.dk/2014/01/ps4-controller-now-supported-by-the-usb-host-library/>.
187 
188 Also check out this excellent Wiki by Frank Zhao about the PS4 controller: <http://eleccelerator.com/wiki/index.php?title=DualShock_4> and this Linux driver: <https://github.com/chrippa/ds4drv>.
189 
190 Several guides on how to use the PS4 library has been written by Dr. James E. Barger and are available at the following link: <https://sites.google.com/view/crosswaystation/ps4-tutorials>.
191 
192 ### PS3 Library
193 
194 These libraries consist of the [PS3BT](PS3BT.cpp) and [PS3USB](PS3USB.cpp). These libraries allows you to use a Dualshock 3, Navigation or a Motion controller with the USB Host Shield both via Bluetooth and USB.
195 
196 In order to use your Playstation controller via Bluetooth you have to set the Bluetooth address of the dongle internally to your PS3 Controller. This can be achieved by first plugging in the Bluetooth dongle and wait a few seconds. Now plug in the controller via USB and wait until the LEDs start to flash. The library has now written the Bluetooth address of the dongle to the PS3 controller.
197 
198 Finally simply plug in the Bluetooth dongle again and press PS on the PS3 controller. After a few seconds it should be connected to the dongle and ready to use.
199 
200 __Note:__ You will have to plug in the Bluetooth dongle before connecting the controller, as the library needs to read the address of the dongle. Alternatively you could set it in code like so: [PS3BT.ino#L20](examples/Bluetooth/PS3BT/PS3BT.ino#L20).
201 
202 For more information about the PS3 protocol see the official wiki: <https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information>.
203 
204 Also take a look at the blog posts:
205 
206 * <http://blog.tkjelectronics.dk/2012/01/ps3-controller-bt-library-for-arduino/>
207 * <http://chome.nerpa.tech/mcu/sony-ps3-controller-support-added-to-usb-host-library>
208 * <http://chome.nerpa.tech/mcu/arduino/interfacing-ps3-controllers-via-usb>
209 
210 A special thanks go to the following people:
211 
212 1. _Richard Ibbotson_ who made this excellent guide: <http://chome.nerpa.tech/mcu/ps3-and-wiimote-game-controllers-on-the-arduino-host-shield-part>
213 2. _Tomoyuki Tanaka_ for releasing his code for the Arduino USB Host shield connected to the wiimote: <http://chome.nerpa.tech/mcu/rc-car-controlled-by-wii-remote-on-arduino>
214 
215 Also a big thanks all the people behind these sites about the Motion controller:
216 
217 * <http://thp.io/2010/psmove/>
218 * <http://www.copenhagengamecollective.org/unimove/>
219 * <https://github.com/thp/psmoveapi>
220 * <http://code.google.com/p/moveonpc/>
221 
222 ### Xbox Libraries
223 
224 The library supports both the original Xbox controller via USB and the Xbox 360 controller both via USB and wirelessly.
225 
226 #### Xbox library
227 
228 The [XBOXOLD](XBOXOLD.cpp) class implements support for the original Xbox controller via USB.
229 
230 All the information are from the following sites:
231 
232 * <https://github.com/torvalds/linux/blob/master/Documentation/input/xpad.txt>
233 * <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
234 * <http://euc.jp/periphs/xbox-controller.ja.html>
235 * <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL#L15>
236 
237 #### Xbox 360 Library
238 
239 The library support one Xbox 360 via USB or up to four Xbox 360 controllers wirelessly by using a [Xbox 360 wireless receiver](http://blog.tkjelectronics.dk/wp-content/uploads/xbox360-wireless-receiver.jpg).
240 
241 To use it via USB use the [XBOXUSB](XBOXUSB.cpp) library or to use it wirelessly use the [XBOXRECV](XBOXRECV.cpp) library.
242 
243 __Note that a Wireless controller can NOT be used via USB!__
244 
245 Examples code can be found in the [examples directory](examples/Xbox).
246 
247 Also see the following blog posts:
248 
249 * <http://chome.nerpa.tech/mcu/xbox360-controller-support-added-to-usb-host-shield-2-0-library>
250 * <http://blog.tkjelectronics.dk/2012/07/xbox-360-controller-support-added-to-the-usb-host-library/>
251 * <http://blog.tkjelectronics.dk/2012/12/xbox-360-receiver-added-to-the-usb-host-library/>
252 
253 All the information regarding the Xbox 360 controller protocol are form these sites:
254 
255 * <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/UsbInfo>
256 * <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/WirelessUsbInfo>
257 * <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL>
258 
259 #### Xbox ONE Library
260 
261 A Xbox ONE controller is supported via USB in the [XBOXONE](XBOXONE.cpp) class. It is heavily based on the 360 library above. In addition to cross referencing the above, information on the protocol was found at:
262 
263 * <https://github.com/quantus/xbox-one-controller-protocol>
264 * <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
265 * <https://github.com/kylelemons/xbox/blob/master/xbox.go>
266 
267 #### Xbox ONE S Library
268 
269 A Xbox ONE controller is supported via Bluetooth in the [XBOXONESBT](XBOXONESBT.cpp) class.
270 
271 Special thanks to [HisashiKato](https://github.com/HisashiKato) for his help: <https://github.com/felis/USB_Host_Shield_2.0/issues/252#issuecomment-716912362>.
272 
273 ### [Wii library](Wii.cpp)
274 
275 The [Wii](Wii.cpp) library support the Wiimote, but also the Nunchuch and Motion Plus extensions via Bluetooth. The Wii U Pro Controller and Wii Balance Board are also supported via Bluetooth.
276 
277 First you have to pair with the controller, this is done automatically by the library if you create the instance like so:
278 
279 ```C++
280 WII Wii(&Btd, PAIR);
281 ```
282 
283 And then press 1 & 2 at once on the Wiimote or the SYNC buttons if you are using a Wii U Pro Controller or a Wii Balance Board.
284 
285 After that you can simply create the instance like so:
286 
287 ```C++
288 WII Wii(&Btd);
289 ```
290 
291 Then just press any button on the Wiimote and it will then connect to the dongle.
292 
293 Take a look at the example for more information: [Wii.ino](examples/Bluetooth/Wii/Wii.ino).
294 
295 Also take a look at the blog post:
296 
297 * <http://blog.tkjelectronics.dk/2012/08/wiimote-added-to-usb-host-library/>
298 
299 The Wii IR camera can also be used, but you will have to activate the code for it manually as it is quite large. Simply set ```ENABLE_WII_IR_CAMERA``` to 1 in [settings.h](settings.h).
300 
301 The [WiiIRCamera.ino](examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino) example shows how it can be used.
302 
303 All the information about the Wii controllers are from these sites:
304 
305 * <http://wiibrew.org/wiki/Wiimote>
306 * <http://wiibrew.org/wiki/Wiimote/Extension_Controllers>
307 * <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Nunchuck>
308 * <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Wii_Motion_Plus>
309 * <http://wiibrew.org/wiki/Wii_Balance_Board>
310 * The old library created by _Tomoyuki Tanaka_: <https://github.com/moyuchin/WiiRemote_on_Arduino> also helped a lot.
311 
312 ### [PS Buzz Library](PSBuzz.cpp)
313 
314 This library implements support for the Playstation Buzz controllers via USB.
315 
316 It is essentially just a wrapper around the [HIDUniversal](hiduniversal.cpp) which takes care of the initializing and reading of the controllers. The [PSBuzz](PSBuzz.cpp) class simply inherits this and parses the data, so it is easy for users to read the buttons and turn the big red button on the controllers on and off.
317 
318 The example [PSBuzz.ino](examples/PSBuzz/PSBuzz.ino) shows how one can do this with just a few lines of code.
319 
320 More information about the controller can be found at the following sites:
321 
322 * http://www.developerfusion.com/article/84338/making-usb-c-friendly/
323 * https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c
324 
325 ### HID Libraries
326 
327 HID devices are also supported by the library. However these require you to write your own driver. A few example are provided in the [examples/HID](examples/HID) directory. Including an example for the [SteelSeries SRW-S1 Steering Wheel](examples/HID/SRWS1/SRWS1.ino).
328 
329 ### [MIDI Library](usbh_midi.cpp)
330 
331 The library support MIDI devices.
332 You can convert USB MIDI keyboard to legacy serial MIDI.
333 
334 * [USB_MIDI_converter.ino](examples/USBH_MIDI/USB_MIDI_converter/USB_MIDI_converter.ino)
335 * [USB_MIDI_converter_multi.ino](examples/USBH_MIDI/USB_MIDI_converter_multi/USB_MIDI_converter_multi.ino)
336 
337 For information see the following page: <http://yuuichiakagawa.github.io/USBH_MIDI/>.
338 
339 # Interface modifications
340 
341 The shield is using SPI for communicating with the MAX3421E USB host controller. It uses the SCK, MISO and MOSI pins via the ICSP on your board.
342 
343 Note this means that it uses pin 13, 12, 11 on an Arduino Uno, so these pins can not be used for anything else than SPI communication!
344 
345 Furthermore it uses one pin as SS and one INT pin. These are by default located on pin 10 and 9 respectively. They can easily be reconfigured in case you need to use them for something else by cutting the jumper on the shield and then solder a wire from the pad to the new pin.
346 
347 After that you need modify the following entry in [UsbCore.h](UsbCore.h):
348 
349 ```C++
350 typedef MAX3421e<P10, P9> MAX3421E;
351 ```
352 
353 For instance if you have rerouted SS to pin 7 it should read:
354 
355 ```C++
356 typedef MAX3421e<P7, P9> MAX3421E;
357 ```
358 
359 See the "Interface modifications" section in the [hardware manual](https://chome.nerpa.tech/usb-host-shield-hardware-manual) for more information.
360 
361 # FAQ
362 
363 > When I plug my device into the USB connector nothing happens?
364 
365 * Try to connect a external power supply to the Arduino - this solves the problem in most cases.
366 * You can also use a powered hub between the device and the USB Host Shield. You should then include the USB hub library: ```#include <usbhub.h>``` and create the instance like so: ```USBHub Hub1(&Usb);```.
367 
368 > When I connecting my PS3 controller I get a output like this:
369 
370 ```
371 Dualshock 3 Controller Enabled
372 
373 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
374 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
375 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
376 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
377 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
378 ```
379 
380 * This means that your dongle does not support 2.0+EDR, so you will need another dongle. Please see the following [list](https://github.com/felis/USB_Host_Shield_2.0/wiki/Bluetooth-dongles) for tested working dongles.
381 
382 > When compiling I am getting the following error: "fatal error: SPI.h: No such file or directory".
383 
384 * Please make sure to include the SPI library like so: ```#include <SPI.h>``` in your .ino file.
+Go to the documentation of this file.
1 # USB Host Library Rev. 2.0
2 
3 The code is released under the GNU General Public License.
4 __________
5 [![](https://github.com/felis/USB_Host_Shield_2.0/workflows/CI/badge.svg)](https://github.com/felis/USB_Host_Shield_2.0/actions?query=branch%3Amaster)
6 
7 # Summary
8 This is Revision 2.0 of MAX3421E-based USB Host Shield Library for AVR's.
9 
10 Project main web site is: <https://chome.nerpa.tech/arduino_usb_host_shield_projects/>.
11 
12 Some information can also be found at: <http://blog.tkjelectronics.dk/>.
13 
14 The shield can be purchased from [TKJ Electronics](http://tkjelectronics.com/): <http://shop.tkjelectronics.dk/product_info.php?products_id=43>.
15 
16 ![USB Host Shield](http://shop.tkjelectronics.dk/images/USB_Host_Shield1.jpg)
17 
18 For more information about the hardware see the [Hardware Manual](https://chome.nerpa.tech/usb-host-shield-hardware-manual/).
19 
20 # Developed By
21 
22 * __Oleg Mazurov__ - <mazurov@gmail.com>
23 * __Alexei Glushchenko__ - <alex-gl@mail.ru>
24  * Developers of the USB Core, HID, FTDI, ADK, ACM, and PL2303 libraries
25 * __Kristian Sloth Lauszus__ - <lauszus@gmail.com>
26  * Developer of the [BTD](#bluetooth-libraries), [BTHID](#bthid-library), [SPP](#spp-library), [PS5](#ps5-library), [PS4](#ps4-library), [PS3](#ps3-library), [Wii](#wii-library), [Xbox](#xbox-library), and [PSBuzz](#ps-buzz-library) libraries
27 * __Andrew Kroll__ - <xxxajk@gmail.com>
28  * Major contributor to mass storage code
29 * __guruthree__
30  * [Xbox ONE](#xbox-one-library) controller support
31 * __Yuuichi Akagawa__ - [\@YuuichiAkagawa](https://twitter.com/yuuichiakagawa)
32  * Developer of the [MIDI](#midi-library) library
33 
34 
35 # Table of Contents
36 
37 * [How to include the library](#how-to-include-the-library)
38  * [Arduino Library Manager](#arduino-library-manager)
39  * [Manual installation](#manual-installation)
40 * [How to use the library](#how-to-use-the-library)
41  * [Documentation](#documentation)
42  * [Enable debugging](#enable-debugging)
43  * [Boards](#boards)
44  * [Bluetooth libraries](#bluetooth-libraries)
45  * [BTHID library](#bthid-library)
46  * [SPP library](#spp-library)
47  * [PS5 Library](#ps5-library)
48  * [PS4 Library](#ps4-library)
49  * [PS3 Library](#ps3-library)
50  * [Xbox Libraries](#xbox-libraries)
51  * [Xbox library](#xbox-library)
52  * [Xbox 360 Library](#xbox-360-library)
53  * [Xbox ONE Library](#xbox-one-library)
54  * [Xbox ONE S Library](#xbox-one-s-library)
55  * [Wii library](#wii-library)
56  * [PS Buzz Library](#ps-buzz-library)
57  * [HID Libraries](#hid-libraries)
58  * [MIDI Library](#midi-library)
59 * [Interface modifications](#interface-modifications)
60 * [FAQ](#faq)
61 
62 # How to include the library
63 
64 ### Arduino Library Manager
65 
66 First install Arduino IDE version 1.6.2 or newer, then simply use the Arduino Library Manager to install the library.
67 
68 Please see the following page for instructions: <http://www.arduino.cc/en/Guide/Libraries#toc3>.
69 
70 ### Manual installation
71 
72 First download the library by clicking on the following link: <https://github.com/felis/USB_Host_Shield_2.0/archive/master.zip>.
73 
74 Then uncompress the zip folder and rename the directory to "USB\_Host\_Shield\_20", as any special characters are not supported by the Arduino IDE.
75 
76 Now open up the Arduino IDE and open "File>Preferences". There you will see the location of your sketchbook. Open that directory and create a directory called "libraries" inside that directory.
77 Now move the "USB\_Host\_Shield\_20" directory to the "libraries" directory.
78 
79 The final structure should look like this:
80 
81 * Arduino/
82  * libraries/
83  * USB\_Host\_Shield\_20/
84 
85 Now quit the Arduino IDE and reopen it.
86 
87 Now you should be able to go open all the examples codes by navigating to "File>Examples>USB\_Host\_Shield\_20" and then select the example you will like to open.
88 
89 For more information visit the following sites: <http://arduino.cc/en/Guide/Libraries> and <https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use>.
90 
91 # How to use the library
92 
93 ### Documentation
94 
95 Documentation for the library can be found at the following link: <https://felis.github.io/USB_Host_Shield_2.0/>.
96 
97 ### Enable debugging
98 
99 By default serial debugging is disabled. To turn it on simply change ```ENABLE_UHS_DEBUGGING``` to 1 in [settings.h](settings.h) like so:
100 
101 ```C++
102 #define ENABLE_UHS_DEBUGGING 1
103 ```
104 
105 ### Boards
106 
107 Currently the following boards are supported by the library:
108 
109 * All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.)
110 * Arduino Due, Intel Galileo, Intel Galileo 2, and Intel Edison
111  * Note that the Intel Galileo uses pin 2 and 3 as INT and SS pin respectively by default, so some modifications to the shield are needed. See the "Interface modifications" section in the [hardware manual](https://chome.nerpa.tech/usb-host-shield-hardware-manual) for more information.
112  * Note native USB host is not supported on any of these platforms. You will have to use the shield for now.
113 * Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, Teensy 3.x, Teensy LC and Teensy 4.x)
114  * Note if you are using the Teensy 3.x you should download this SPI library as well: <https://github.com/xxxajk/spi4teensy3>. You should then add ```#include <spi4teensy3.h>``` to your .ino file.
115 * Balanduino
116 * Sanguino
117 * Black Widdow
118 * RedBearLab nRF51822
119 * Digilent chipKIT
120  * Please see: <https://chome.nerpa.tech/mcu/usb/running-usb-host-code-on-digilent-chipkit-board>.
121 * STM32F4
122  * Currently the [NUCLEO-F446RE](http://www.st.com/web/catalog/tools/FM116/SC959/SS1532/LN1847/PF262063) is supported featuring the STM32F446. Take a look at the following example code: <https://github.com/Lauszus/Nucleo_F446RE_USBHost>.
123 * ESP8266 is supported using the [ESP8266 Arduino core](https://github.com/esp8266/Arduino)
124  * Note it uses pin 15 and 5 for SS and INT respectively
125  * Also please be aware that:
126  * GPIO16 is **NOT** usable, as it will be used for some other purposes. For example, reset the SoC itself from sleep mode.
127  * GPIO6 to 11 is also **NOT** usable, as they are used to connect SPI flash chip and it is used for storing the executable binary content.
128 * ESP32 is supported using the [arduino-esp32](https://github.com/espressif/arduino-esp32/)
129  * GPIO5 : SS, GPIO17 : INT, GPIO18 : SCK, GPIO19 : MISO, GPIO23 : MOSI
130 
131 The following boards need to be activated manually in [settings.h](settings.h):
132 
133 * Arduino Mega ADK
134  * If you are using Arduino 1.5.5 or newer there is no need to activate the Arduino Mega ADK manually
135 * Black Widdow
136 
137 Simply set the corresponding value to 1 instead of 0.
138 
139 ### [Bluetooth libraries](BTD.cpp)
140 
141 The [BTD library](BTD.cpp) is a general purpose library for an ordinary Bluetooth dongle.
142 This library make it easy to add support for different Bluetooth services like a PS3 or a Wii controller or SPP which is a virtual serial port via Bluetooth.
143 Some different examples can be found in the [example directory](examples/Bluetooth).
144 
145 The BTD library also makes it possible to use multiple services at once, the following example sketch is an example of this:
146 [PS3SPP.ino](examples/Bluetooth/PS3SPP/PS3SPP.ino).
147 
148 ### [BTHID library](BTHID.cpp)
149 
150 The [Bluetooth HID library](BTHID.cpp) allows you to connect HID devices via Bluetooth to the USB Host Shield.
151 
152 Currently HID mice and keyboards are supported.
153 
154 It uses the standard Boot protocol by default, but it is also able to use the Report protocol as well. You would simply have to call ```setProtocolMode()``` and then parse ```HID_RPT_PROTOCOL``` as an argument. You will then have to modify the parser for your device. See the example: [BTHID.ino](examples/Bluetooth/BTHID/BTHID.ino) for more information.
155 
156 The [PS4 library](#ps4-library) also uses this class to handle all Bluetooth communication.
157 
158 For information see the following blog post: <http://blog.tkjelectronics.dk/2013/12/bluetooth-hid-devices-now-supported-by-the-usb-host-library/>.
159 
160 ### [SPP library](SPP.cpp)
161 
162 SPP stands for "Serial Port Profile" and is a Bluetooth protocol that implements a virtual comport which allows you to send data back and forth from your computer/phone to your Arduino via Bluetooth.
163 It has been tested successfully on Windows, Mac OS X, Linux, and Android.
164 
165 Take a look at the [SPP.ino](examples/Bluetooth/SPP/SPP.ino) example for more information.
166 
167 More information can be found at these blog posts:
168 
169 * <http://chome.nerpa.tech/mcu/bluetooth-rfcommspp-service-support-for-usb-host-2-0-library-released>
170 * <http://blog.tkjelectronics.dk/2012/07/rfcommspp-library-for-arduino/>
171 
172 To implement the SPP protocol I used a Bluetooth sniffing tool called [PacketLogger](http://www.tkjelectronics.com/uploads/PacketLogger.zip) developed by Apple.
173 It enables me to see the Bluetooth communication between my Mac and any device.
174 
175 ### PS5 Library
176 
177 The PS5 library is split up into the [PS5BT](PS5BT.h) and the [PS5USB](PS5USB.h) library. These allow you to use the Sony PS5 controller via Bluetooth and USB.
178 
179 The [PS5BT.ino](examples/Bluetooth/PS5BT/PS5BT.ino) and [PS5USB.ino](examples/PS5USB/PS5USB.ino) examples shows how to easily read the buttons, joysticks, touchpad and IMU on the controller via Bluetooth and USB respectively. It is also possible to control the rumble, lightbar, microphone LED and player LEDs on the controller. Furthermore the new haptic trigger effects are also supported.
180 
181 To pair with the PS5 controller via Bluetooth you need create the PS5BT instance like so: ```PS5BT PS5(&Btd, PAIR);``` and then hold down the Create button and then hold down the PS without releasing the Create button. The PS5 controller will then start to blink blue indicating that it is in pairing mode.
182 
183 It should then automatically pair the dongle with your controller. This only have to be done once.
184 
185 Thanks to Joseph Duchesne for the initial USB code.
186 
187 The driver is based on the official Sony driver for Linux: <https://patchwork.kernel.org/project/linux-input/cover/20201219062336.72568-1-roderick@gaikai.com/>.
188 
189 Also thanks to Ludwig Füchsl's <https://github.com/Ohjurot/DualSense-Windows> for his work on the haptic triggers.
190 
191 ### PS4 Library
192 
193 The PS4 library is split up into the [PS4BT](PS4BT.h) and the [PS4USB](PS4USB.h) library. These allow you to use the Sony PS4 controller via Bluetooth and USB.
194 
195 The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) and [PS4USB.ino](examples/PS4USB/PS4USB.ino) examples shows how to easily read the buttons, joysticks, touchpad and IMU on the controller via Bluetooth and USB respectively. It is also possible to control the rumble and light on the controller and get the battery level.
196 
197 Before you can use the PS4 controller via Bluetooth you will need to pair with it.
198 
199 Simply create the PS4BT instance like so: ```PS4BT PS4(&Btd, PAIR);``` and then hold down the Share button and then hold down the PS without releasing the Share button. The PS4 controller will then start to blink rapidly indicating that it is in pairing mode.
200 
201 It should then automatically pair the dongle with your controller. This only have to be done once.
202 
203 For information see the following blog post: <http://blog.tkjelectronics.dk/2014/01/ps4-controller-now-supported-by-the-usb-host-library/>.
204 
205 Also check out this excellent Wiki by Frank Zhao about the PS4 controller: <http://eleccelerator.com/wiki/index.php?title=DualShock_4> and this Linux driver: <https://github.com/chrippa/ds4drv>.
206 
207 Several guides on how to use the PS4 library has been written by Dr. James E. Barger and are available at the following link: <https://sites.google.com/view/crosswaystation/ps4-tutorials>.
208 
209 ### PS3 Library
210 
211 These libraries consist of the [PS3BT](PS3BT.cpp) and [PS3USB](PS3USB.cpp). These libraries allows you to use a Dualshock 3, Navigation or a Motion controller with the USB Host Shield both via Bluetooth and USB.
212 
213 In order to use your Playstation controller via Bluetooth you have to set the Bluetooth address of the dongle internally to your PS3 Controller. This can be achieved by first plugging in the Bluetooth dongle and wait a few seconds. Now plug in the controller via USB and wait until the LEDs start to flash. The library has now written the Bluetooth address of the dongle to the PS3 controller.
214 
215 Finally simply plug in the Bluetooth dongle again and press PS on the PS3 controller. After a few seconds it should be connected to the dongle and ready to use.
216 
217 __Note:__ You will have to plug in the Bluetooth dongle before connecting the controller, as the library needs to read the address of the dongle. Alternatively you could set it in code like so: [PS3BT.ino#L20](examples/Bluetooth/PS3BT/PS3BT.ino#L20).
218 
219 For more information about the PS3 protocol see the official wiki: <https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information>.
220 
221 Also take a look at the blog posts:
222 
223 * <http://blog.tkjelectronics.dk/2012/01/ps3-controller-bt-library-for-arduino/>
224 * <http://chome.nerpa.tech/mcu/sony-ps3-controller-support-added-to-usb-host-library>
225 * <http://chome.nerpa.tech/mcu/arduino/interfacing-ps3-controllers-via-usb>
226 
227 A special thanks go to the following people:
228 
229 1. _Richard Ibbotson_ who made this excellent guide: <http://chome.nerpa.tech/mcu/ps3-and-wiimote-game-controllers-on-the-arduino-host-shield-part>
230 2. _Tomoyuki Tanaka_ for releasing his code for the Arduino USB Host shield connected to the wiimote: <http://chome.nerpa.tech/mcu/rc-car-controlled-by-wii-remote-on-arduino>
231 
232 Also a big thanks all the people behind these sites about the Motion controller:
233 
234 * <http://thp.io/2010/psmove/>
235 * <http://www.copenhagengamecollective.org/unimove/>
236 * <https://github.com/thp/psmoveapi>
237 * <http://code.google.com/p/moveonpc/>
238 
239 ### Xbox Libraries
240 
241 The library supports both the original Xbox controller via USB and the Xbox 360 controller both via USB and wirelessly.
242 
243 #### Xbox library
244 
245 The [XBOXOLD](XBOXOLD.cpp) class implements support for the original Xbox controller via USB.
246 
247 All the information are from the following sites:
248 
249 * <https://github.com/torvalds/linux/blob/master/Documentation/input/xpad.txt>
250 * <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
251 * <http://euc.jp/periphs/xbox-controller.ja.html>
252 * <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL#L15>
253 
254 #### Xbox 360 Library
255 
256 The library support one Xbox 360 via USB or up to four Xbox 360 controllers wirelessly by using a [Xbox 360 wireless receiver](http://blog.tkjelectronics.dk/wp-content/uploads/xbox360-wireless-receiver.jpg).
257 
258 To use it via USB use the [XBOXUSB](XBOXUSB.cpp) library or to use it wirelessly use the [XBOXRECV](XBOXRECV.cpp) library.
259 
260 __Note that a Wireless controller can NOT be used via USB!__
261 
262 Examples code can be found in the [examples directory](examples/Xbox).
263 
264 Also see the following blog posts:
265 
266 * <http://chome.nerpa.tech/mcu/xbox360-controller-support-added-to-usb-host-shield-2-0-library>
267 * <http://blog.tkjelectronics.dk/2012/07/xbox-360-controller-support-added-to-the-usb-host-library/>
268 * <http://blog.tkjelectronics.dk/2012/12/xbox-360-receiver-added-to-the-usb-host-library/>
269 
270 All the information regarding the Xbox 360 controller protocol are form these sites:
271 
272 * <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/UsbInfo>
273 * <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/WirelessUsbInfo>
274 * <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL>
275 
276 #### Xbox ONE Library
277 
278 A Xbox ONE controller is supported via USB in the [XBOXONE](XBOXONE.cpp) class. It is heavily based on the 360 library above. In addition to cross referencing the above, information on the protocol was found at:
279 
280 * <https://github.com/quantus/xbox-one-controller-protocol>
281 * <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
282 * <https://github.com/kylelemons/xbox/blob/master/xbox.go>
283 
284 #### Xbox ONE S Library
285 
286 A Xbox ONE controller is supported via Bluetooth in the [XBOXONESBT](XBOXONESBT.cpp) class.
287 
288 Special thanks to [HisashiKato](https://github.com/HisashiKato) for his help: <https://github.com/felis/USB_Host_Shield_2.0/issues/252#issuecomment-716912362>.
289 
290 ### [Wii library](Wii.cpp)
291 
292 The [Wii](Wii.cpp) library support the Wiimote, but also the Nunchuch and Motion Plus extensions via Bluetooth. The Wii U Pro Controller and Wii Balance Board are also supported via Bluetooth.
293 
294 First you have to pair with the controller, this is done automatically by the library if you create the instance like so:
295 
296 ```C++
297 WII Wii(&Btd, PAIR);
298 ```
299 
300 And then press 1 & 2 at once on the Wiimote or the SYNC buttons if you are using a Wii U Pro Controller or a Wii Balance Board.
301 
302 After that you can simply create the instance like so:
303 
304 ```C++
305 WII Wii(&Btd);
306 ```
307 
308 Then just press any button on the Wiimote and it will then connect to the dongle.
309 
310 Take a look at the example for more information: [Wii.ino](examples/Bluetooth/Wii/Wii.ino).
311 
312 Also take a look at the blog post:
313 
314 * <http://blog.tkjelectronics.dk/2012/08/wiimote-added-to-usb-host-library/>
315 
316 The Wii IR camera can also be used, but you will have to activate the code for it manually as it is quite large. Simply set ```ENABLE_WII_IR_CAMERA``` to 1 in [settings.h](settings.h).
317 
318 The [WiiIRCamera.ino](examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino) example shows how it can be used.
319 
320 All the information about the Wii controllers are from these sites:
321 
322 * <http://wiibrew.org/wiki/Wiimote>
323 * <http://wiibrew.org/wiki/Wiimote/Extension_Controllers>
324 * <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Nunchuck>
325 * <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Wii_Motion_Plus>
326 * <http://wiibrew.org/wiki/Wii_Balance_Board>
327 * The old library created by _Tomoyuki Tanaka_: <https://github.com/moyuchin/WiiRemote_on_Arduino> also helped a lot.
328 
329 ### [PS Buzz Library](PSBuzz.cpp)
330 
331 This library implements support for the Playstation Buzz controllers via USB.
332 
333 It is essentially just a wrapper around the [HIDUniversal](hiduniversal.cpp) which takes care of the initializing and reading of the controllers. The [PSBuzz](PSBuzz.cpp) class simply inherits this and parses the data, so it is easy for users to read the buttons and turn the big red button on the controllers on and off.
334 
335 The example [PSBuzz.ino](examples/PSBuzz/PSBuzz.ino) shows how one can do this with just a few lines of code.
336 
337 More information about the controller can be found at the following sites:
338 
339 * http://www.developerfusion.com/article/84338/making-usb-c-friendly/
340 * https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c
341 
342 ### HID Libraries
343 
344 HID devices are also supported by the library. However these require you to write your own driver. A few example are provided in the [examples/HID](examples/HID) directory. Including an example for the [SteelSeries SRW-S1 Steering Wheel](examples/HID/SRWS1/SRWS1.ino).
345 
346 ### [MIDI Library](usbh_midi.cpp)
347 
348 The library support MIDI devices.
349 You can convert USB MIDI keyboard to legacy serial MIDI.
350 
351 * [USB_MIDI_converter.ino](examples/USBH_MIDI/USB_MIDI_converter/USB_MIDI_converter.ino)
352 * [USB_MIDI_converter_multi.ino](examples/USBH_MIDI/USB_MIDI_converter_multi/USB_MIDI_converter_multi.ino)
353 
354 For information see the following page: <http://yuuichiakagawa.github.io/USBH_MIDI/>.
355 
356 # Interface modifications
357 
358 The shield is using SPI for communicating with the MAX3421E USB host controller. It uses the SCK, MISO and MOSI pins via the ICSP on your board.
359 
360 Note this means that it uses pin 13, 12, 11 on an Arduino Uno, so these pins can not be used for anything else than SPI communication!
361 
362 Furthermore it uses one pin as SS and one INT pin. These are by default located on pin 10 and 9 respectively. They can easily be reconfigured in case you need to use them for something else by cutting the jumper on the shield and then solder a wire from the pad to the new pin.
363 
364 After that you need modify the following entry in [UsbCore.h](UsbCore.h):
365 
366 ```C++
367 typedef MAX3421e<P10, P9> MAX3421E;
368 ```
369 
370 For instance if you have rerouted SS to pin 7 it should read:
371 
372 ```C++
373 typedef MAX3421e<P7, P9> MAX3421E;
374 ```
375 
376 See the "Interface modifications" section in the [hardware manual](https://chome.nerpa.tech/usb-host-shield-hardware-manual) for more information.
377 
378 # FAQ
379 
380 > When I plug my device into the USB connector nothing happens?
381 
382 * Try to connect a external power supply to the Arduino - this solves the problem in most cases.
383 * You can also use a powered hub between the device and the USB Host Shield. You should then include the USB hub library: ```#include <usbhub.h>``` and create the instance like so: ```USBHub Hub1(&Usb);```.
384 
385 > When I connecting my PS3 controller I get a output like this:
386 
387 ```
388 Dualshock 3 Controller Enabled
389 
390 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
391 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
392 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
393 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
394 LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
395 ```
396 
397 * This means that your dongle does not support 2.0+EDR, so you will need another dongle. Please see the following [list](https://github.com/felis/USB_Host_Shield_2.0/wiki/Bluetooth-dongles) for tested working dongles.
398 
399 > When compiling I am getting the following error: "fatal error: SPI.h: No such file or directory".
400 
401 * Please make sure to include the SPI library like so: ```#include <SPI.h>``` in your .ino file.