From e18eb57752095fc59725090e640073b45458b638 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 4 Dec 2013 18:40:23 -0500 Subject: [PATCH 001/145] fix all warnings for ARM, fix a few small bugs --- BTD.cpp | 11 +- BTD.h | 4 +- PS3USB.cpp | 22 +-- Usb.cpp | 11 +- XBOXOLD.cpp | 23 +-- XBOXRECV.cpp | 53 ++++--- XBOXUSB.cpp | 19 +-- address.h | 20 ++- adk.cpp | 17 +- avrpins.h | 1 + cdcacm.cpp | 12 +- cdcacm.h | 102 ++++++------ cdcftdi.cpp | 14 +- cdcprolific.cpp | 11 +- confdescparser.h | 16 +- examples/HID/USBHID_desc/USBHID_desc.ino | 24 +-- hid.h | 149 +++++++++--------- hidboot.h | 46 ++++-- hidescriptorparser.cpp | 188 +++++++++++++++-------- hidescriptorparser.h | 3 +- hiduniversal.cpp | 9 +- masstorage.cpp | 17 +- masstorage.h | 2 +- message.cpp | 2 +- usbhub.cpp | 13 +- 25 files changed, 456 insertions(+), 333 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 9cf2436b..a1561e7c 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -46,6 +46,7 @@ bPollEnable(false) // Don't start polling before dongle is connected uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -98,11 +99,11 @@ uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; } - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; // Extract Max Packet Size from device descriptor - epInfo[1].epAddr = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; // Steal and abuse from epInfo structure to save memory + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor + epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory - VID = ((USB_DEVICE_DESCRIPTOR*)buf)->idVendor; - PID = ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct; + VID = udd->idVendor; + PID = udd->idProduct; return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET; @@ -249,8 +250,8 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { return 0; // Successful configuration /* diagnostic messages */ -FailGetDevDescr: #ifdef DEBUG_USB_HOST +FailGetDevDescr: NotifyFailGetDevDescr(); goto Fail; #endif diff --git a/BTD.h b/BTD.h index a2e3d62d..c6a705a9 100755 --- a/BTD.h +++ b/BTD.h @@ -468,13 +468,13 @@ private: uint16_t PID, VID; // PID and VID of device connected - bool bPollEnable; uint8_t pollInterval; + bool bPollEnable; /* Variables used by high level HCI task */ uint8_t hci_state; //current state of bluetooth hci connection uint16_t hci_counter; // counter used for bluetooth hci reset loops - uint8_t hci_num_reset_loops; // this value indicate how many times it should read before trying to reset + uint16_t hci_num_reset_loops; // this value indicate how many times it should read before trying to reset uint16_t hci_event_flag; // hci flags of received bluetooth events uint8_t inquiry_counter; diff --git a/PS3USB.cpp b/PS3USB.cpp index 0d02a9e1..868d7aba 100644 --- a/PS3USB.cpp +++ b/PS3USB.cpp @@ -45,6 +45,7 @@ bPollEnable(false) // don't start polling before dongle is connected uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -97,8 +98,8 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { if (rcode) goto FailGetDevDescr; - VID = ((USB_DEVICE_DESCRIPTOR*)buf)->idVendor; - PID = ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct; + VID = udd->idVendor; + PID = udd->idProduct; if (VID != PS3_VID || (PID != PS3_PID && PID != PS3NAVIGATION_PID && PID != PS3MOVE_PID)) goto FailUnknownDevice; @@ -110,7 +111,7 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -129,7 +130,7 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { D_PrintHex (bAddress, 0x80); #endif delay(300); // Spec says you should wait at least 200ms - + p->lowspeed = false; //get pointer to assigned address record @@ -154,14 +155,14 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ PS3_OUTPUT_PIPE ].epAttribs = EP_INTERRUPT; epInfo[ PS3_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ PS3_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ PS3_OUTPUT_PIPE ].bmSndToggle = bmSNDTOG0; - epInfo[ PS3_OUTPUT_PIPE ].bmRcvToggle = bmRCVTOG0; + epInfo[ PS3_OUTPUT_PIPE ].bmSndToggle = 0; + epInfo[ PS3_OUTPUT_PIPE ].bmRcvToggle = 0; epInfo[ PS3_INPUT_PIPE ].epAddr = 0x01; // PS3 report endpoint epInfo[ PS3_INPUT_PIPE ].epAttribs = EP_INTERRUPT; epInfo[ PS3_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ PS3_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ PS3_INPUT_PIPE ].bmSndToggle = bmSNDTOG0; - epInfo[ PS3_INPUT_PIPE ].bmRcvToggle = bmRCVTOG0; + epInfo[ PS3_INPUT_PIPE ].bmSndToggle = 0; + epInfo[ PS3_INPUT_PIPE ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); if (rcode) @@ -237,16 +238,17 @@ FailSetDevTblEntry: FailSetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailSetConfDescr(); -#endif goto Fail; +#endif + FailUnknownDevice: #ifdef DEBUG_USB_HOST NotifyFailUnknownDevice(VID, PID); #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; -Fail: #ifdef DEBUG_USB_HOST +Fail: Notify(PSTR("\r\nPS3 Init Failed, error code: "), 0x80); NotifyFail(rcode); #endif diff --git a/Usb.cpp b/Usb.cpp index 6bcf092e..4e4fde61 100644 --- a/Usb.cpp +++ b/Usb.cpp @@ -650,6 +650,7 @@ uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t devConfigIndex; uint8_t rcode = 0; uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; + USB_DEVICE_DESCRIPTOR *udd = reinterpret_cast(buf); UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; EpInfo epInfo; @@ -694,10 +695,9 @@ uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) { //if (!bAddress) // return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - uint16_t vid = (uint16_t)((USB_DEVICE_DESCRIPTOR*)buf)->idVendor; - uint16_t pid = (uint16_t)((USB_DEVICE_DESCRIPTOR*)buf)->idProduct; - uint8_t klass = ((USB_DEVICE_DESCRIPTOR*)buf)->bDeviceClass; + uint16_t vid = udd->idVendor; + uint16_t pid = udd->idProduct; + uint8_t klass = udd->bDeviceClass; // Attempt to configure if VID/PID or device class matches with a driver for (devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { @@ -767,13 +767,14 @@ uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t con uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p) { const uint8_t bufSize = 64; uint8_t buf[bufSize]; + USB_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast(buf); uint8_t ret = getConfDescr(addr, ep, 9, conf, buf); if (ret) return ret; - uint16_t total = ((USB_CONFIGURATION_DESCRIPTOR*)buf)->wTotalLength; + uint16_t total = ucd->wTotalLength; //USBTRACE2("\r\ntotal conf.size:", total); diff --git a/XBOXOLD.cpp b/XBOXOLD.cpp index 4c9bcb20..34c80b67 100644 --- a/XBOXOLD.cpp +++ b/XBOXOLD.cpp @@ -42,7 +42,7 @@ const uint8_t XBOXOLDBUTTONS[] PROGMEM = { 0, // A 2, // X 3, // Y -}; +}; XBOXOLD::XBOXOLD(USB *p) : pUsb(p), // pointer to USB class instance - mandatory @@ -61,6 +61,7 @@ bPollEnable(false) { // don't start polling before dongle is connected uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -113,12 +114,12 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { if (rcode) goto FailGetDevDescr; - VID = ((USB_DEVICE_DESCRIPTOR*)buf)->idVendor; - PID = ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct; + VID = udd->idVendor; + PID = udd->idProduct; if ((VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_OLD_PID1 && PID != XBOX_OLD_PID2 && PID != XBOX_OLD_PID3 && PID != XBOX_OLD_PID4)) // Check if VID and PID match goto FailUnknownDevice; - + // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); @@ -126,7 +127,7 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -145,7 +146,7 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { D_PrintHex (bAddress, 0x80); #endif delay(300); // Spec says you should wait at least 200ms - + p->lowspeed = false; //get pointer to assigned address record @@ -169,14 +170,14 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ XBOX_INPUT_PIPE ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = 0; + epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = 0; epInfo[ XBOX_OUTPUT_PIPE ].epAddr = 0x02; // XBOX output endpoint epInfo[ XBOX_OUTPUT_PIPE ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = 0; + epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); if (rcode) @@ -221,8 +222,8 @@ FailUnknownDevice: #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; -Fail: #ifdef DEBUG_USB_HOST +Fail: Notify(PSTR("\r\nXbox Init Failed, error code: "), 0x80); NotifyFail(rcode); #endif diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index 3784f25a..c011dc34 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -39,6 +39,7 @@ bPollEnable(false) { // don't start polling before dongle is connected uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -91,8 +92,8 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { if (rcode) goto FailGetDevDescr; - VID = ((USB_DEVICE_DESCRIPTOR*)buf)->idVendor; - PID = ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct; + VID = udd->idVendor; + PID = udd->idProduct; if (VID != XBOX_VID && VID != MADCATZ_VID) // We just check if it's a Xbox receiver using the Vendor ID goto FailUnknownDevice; @@ -110,7 +111,7 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -129,7 +130,7 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { D_PrintHex (bAddress, 0x80); #endif delay(300); // Spec says you should wait at least 200ms - + p->lowspeed = false; //get pointer to assigned address record @@ -153,53 +154,53 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ XBOX_INPUT_PIPE_1 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_INPUT_PIPE_1 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_INPUT_PIPE_1 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_INPUT_PIPE_1 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_INPUT_PIPE_1 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_INPUT_PIPE_1 ].bmSndToggle = 0; + epInfo[ XBOX_INPUT_PIPE_1 ].bmRcvToggle = 0; epInfo[ XBOX_OUTPUT_PIPE_1 ].epAddr = 0x01; // XBOX 360 output endpoint - poll interval 8ms epInfo[ XBOX_OUTPUT_PIPE_1 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_OUTPUT_PIPE_1 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_OUTPUT_PIPE_1 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_OUTPUT_PIPE_1 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_OUTPUT_PIPE_1 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_OUTPUT_PIPE_1 ].bmSndToggle = 0; + epInfo[ XBOX_OUTPUT_PIPE_1 ].bmRcvToggle = 0; epInfo[ XBOX_INPUT_PIPE_2 ].epAddr = 0x03; // XBOX 360 report endpoint - poll interval 1ms epInfo[ XBOX_INPUT_PIPE_2 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_INPUT_PIPE_2 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_INPUT_PIPE_2 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_INPUT_PIPE_2 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_INPUT_PIPE_2 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_INPUT_PIPE_2 ].bmSndToggle = 0; + epInfo[ XBOX_INPUT_PIPE_2 ].bmRcvToggle = 0; epInfo[ XBOX_OUTPUT_PIPE_2 ].epAddr = 0x03; // XBOX 360 output endpoint - poll interval 8ms epInfo[ XBOX_OUTPUT_PIPE_2 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_OUTPUT_PIPE_2 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_OUTPUT_PIPE_2 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_OUTPUT_PIPE_2 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_OUTPUT_PIPE_2 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_OUTPUT_PIPE_2 ].bmSndToggle = 0; + epInfo[ XBOX_OUTPUT_PIPE_2 ].bmRcvToggle = 0; epInfo[ XBOX_INPUT_PIPE_3 ].epAddr = 0x05; // XBOX 360 report endpoint - poll interval 1ms epInfo[ XBOX_INPUT_PIPE_3 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_INPUT_PIPE_3 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_INPUT_PIPE_3 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_INPUT_PIPE_3 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_INPUT_PIPE_3 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_INPUT_PIPE_3 ].bmSndToggle = 0; + epInfo[ XBOX_INPUT_PIPE_3 ].bmRcvToggle = 0; epInfo[ XBOX_OUTPUT_PIPE_3 ].epAddr = 0x05; // XBOX 360 output endpoint - poll interval 8ms epInfo[ XBOX_OUTPUT_PIPE_3 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_OUTPUT_PIPE_3 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_OUTPUT_PIPE_3 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_OUTPUT_PIPE_3 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_OUTPUT_PIPE_3 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_OUTPUT_PIPE_3 ].bmSndToggle = 0; + epInfo[ XBOX_OUTPUT_PIPE_3 ].bmRcvToggle = 0; epInfo[ XBOX_INPUT_PIPE_4 ].epAddr = 0x07; // XBOX 360 report endpoint - poll interval 1ms epInfo[ XBOX_INPUT_PIPE_4 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_INPUT_PIPE_4 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_INPUT_PIPE_4 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_INPUT_PIPE_4 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_INPUT_PIPE_4 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_INPUT_PIPE_4 ].bmSndToggle = 0; + epInfo[ XBOX_INPUT_PIPE_4 ].bmRcvToggle = 0; epInfo[ XBOX_OUTPUT_PIPE_4 ].epAddr = 0x07; // XBOX 360 output endpoint - poll interval 8ms epInfo[ XBOX_OUTPUT_PIPE_4 ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_OUTPUT_PIPE_4 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_OUTPUT_PIPE_4 ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_OUTPUT_PIPE_4 ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_OUTPUT_PIPE_4 ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_OUTPUT_PIPE_4 ].bmSndToggle = 0; + epInfo[ XBOX_OUTPUT_PIPE_4 ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 9, epInfo); if (rcode) @@ -235,7 +236,6 @@ FailSetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailSetConfDescr(); #endif - goto Fail; FailUnknownDevice: #ifdef DEBUG_USB_HOST @@ -243,8 +243,8 @@ FailUnknownDevice: #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; -Fail: #ifdef DEBUG_USB_HOST +Fail: Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80); NotifyFail(rcode); #endif @@ -442,7 +442,9 @@ uint8_t XBOXRECV::getBatteryLevel(uint8_t controller) { } void XBOXRECV::XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes) { +#ifdef EXTRADEBUG uint8_t rcode; +#endif uint8_t outputPipe; switch (controller) { case 0: outputPipe = XBOX_OUTPUT_PIPE_1; @@ -453,8 +455,13 @@ void XBOXRECV::XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes) { break; case 3: outputPipe = XBOX_OUTPUT_PIPE_4; break; + default: + return; } - rcode = pUsb->outTransfer(bAddress, epInfo[ outputPipe ].epAddr, nbytes, data); +#ifdef EXTRADEBUG + rcode = +#endif + pUsb->outTransfer(bAddress, epInfo[ outputPipe ].epAddr, nbytes, data); #ifdef EXTRADEBUG if (rcode) Notify(PSTR("Error sending Xbox message\r\n"), 0x80); diff --git a/XBOXUSB.cpp b/XBOXUSB.cpp index 1b195f70..2bac3152 100644 --- a/XBOXUSB.cpp +++ b/XBOXUSB.cpp @@ -37,6 +37,7 @@ bPollEnable(false) { // don't start polling before dongle is connected uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -89,8 +90,8 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { if (rcode) goto FailGetDevDescr; - VID = ((USB_DEVICE_DESCRIPTOR*)buf)->idVendor; - PID = ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct; + VID = udd->idVendor; + PID = udd->idProduct; if (VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID && VID != GAMESTOP_VID) // Check VID goto FailUnknownDevice; @@ -114,7 +115,7 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -133,7 +134,7 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { D_PrintHex (bAddress, 0x80); #endif delay(300); // Spec says you should wait at least 200ms - + p->lowspeed = false; //get pointer to assigned address record @@ -157,14 +158,14 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ XBOX_INPUT_PIPE ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = 0; + epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = 0; epInfo[ XBOX_OUTPUT_PIPE ].epAddr = 0x02; // XBOX 360 output endpoint epInfo[ XBOX_OUTPUT_PIPE ].epAttribs = EP_INTERRUPT; epInfo[ XBOX_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints epInfo[ XBOX_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE; - epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = bmSNDTOG0; - epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = bmRCVTOG0; + epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = 0; + epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); if (rcode) @@ -208,8 +209,8 @@ FailUnknownDevice: #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; -Fail: #ifdef DEBUG_USB_HOST +Fail: Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80); NotifyFail(rcode); #endif diff --git a/address.h b/address.h index d52fda73..dd281b12 100644 --- a/address.h +++ b/address.h @@ -122,7 +122,8 @@ class AddressPoolImpl : public AddressPool { uint8_t FindChildIndex(UsbDeviceAddress addr, uint8_t start = 1) { for(uint8_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) { - if(((UsbDeviceAddress*) & thePool[i].address)->bmParent == addr.bmAddress) + UsbDeviceAddress* uda = reinterpret_cast(&thePool[i].address); + if(uda->bmParent == addr.bmAddress) return i; } return 0; @@ -133,14 +134,14 @@ class AddressPoolImpl : public AddressPool { // Zerro field is reserved and should not be affected if(index == 0) return; - + UsbDeviceAddress* uda = reinterpret_cast(& thePool[index].address); // If a hub was switched off all port addresses should be freed - if(((UsbDeviceAddress*) & thePool[index].address)->bmHub == 1) { - for(uint8_t i = 1; (i = FindChildIndex(*((UsbDeviceAddress*) & thePool[index].address), i));) + if(uda->bmHub == 1) { + for(uint8_t i = 1; (i = FindChildIndex(*uda, i));) FreeAddressByIndex(i); // If the hub had the last allocated address, hubCounter should be decremented - if(hubCounter == ((UsbDeviceAddress*) & thePool[index].address)->bmAddress) + if(hubCounter == uda->bmAddress) hubCounter--; } InitEntry(index); @@ -220,8 +221,9 @@ public: UsbDeviceAddress addr; addr.devAddress = 0; // Ensure all bits are zero - - addr.bmParent = ((UsbDeviceAddress*) & parent)->bmAddress; + UsbDeviceAddress* uda = reinterpret_cast(&parent); + //addr.bmParent = ((UsbDeviceAddress*) & parent)->bmAddress; + addr.bmParent = uda->bmAddress; if(is_hub) { addr.bmHub = 1; @@ -230,7 +232,9 @@ public: addr.bmHub = 0; addr.bmAddress = port; } - thePool[index].address = *((uint8_t*) & addr); + uint8_t* uaddr = reinterpret_cast(&addr); + //thePool[index].address = *((uint8_t*) & addr); + thePool[index].address = *uaddr; /* USB_HOST_SERIAL.print("Addr:"); USB_HOST_SERIAL.print(addr.bmHub, HEX); diff --git a/adk.cpp b/adk.cpp index 453833dc..ef59c052 100644 --- a/adk.cpp +++ b/adk.cpp @@ -66,6 +66,7 @@ uint8_t ADK::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; uint8_t num_of_conf; // number of configurations UsbDevice *p = NULL; @@ -117,7 +118,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { bAddress = addrPool.AllocAddress(parent, false, port); // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); if (rcode) { @@ -149,11 +150,11 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { } //check if ADK device is already in accessory mode; if yes, configure and exit - if (((USB_DEVICE_DESCRIPTOR*)buf)->idVendor == ADK_VID && - (((USB_DEVICE_DESCRIPTOR*)buf)->idProduct == ADK_PID || ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct == ADB_PID)) { + if (udd->idVendor == ADK_VID && + (udd->idProduct == ADK_PID || udd->idProduct == ADB_PID)) { USBTRACE("\r\nAcc.mode device detected"); /* go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */ - num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; + num_of_conf = udd->bNumConfigurations; //USBTRACE2("\r\nNC:",num_of_conf); @@ -268,15 +269,15 @@ FailSwAcc: goto Fail; #endif -SwAttempt: -#ifdef DEBUG_USB_HOST - USBTRACE("\r\nAccessory mode switch attempt"); -#endif //FailOnInit: // USBTRACE("OnInit:"); // goto Fail; // +SwAttempt: +#ifdef DEBUG_USB_HOST + USBTRACE("\r\nAccessory mode switch attempt"); Fail: +#endif //USBTRACE2("\r\nADK Init Failed, error code: ", rcode); //NotifyFail(rcode); Release(); diff --git a/avrpins.h b/avrpins.h index 5a7e1756..16b0c0fb 100644 --- a/avrpins.h +++ b/avrpins.h @@ -821,4 +821,5 @@ MAKE_PIN(P33, CORE_PIN33_PORTREG, CORE_PIN33_BIT, CORE_PIN33_CONFIG); #endif // __arm__ +#define output_pgm_message(wa, fp, mp , el) wa = &mp, fp((char *)pgm_read_pointer(wa), el) #endif //_avrpins_h_ diff --git a/cdcacm.cpp b/cdcacm.cpp index 0f9fffde..948b58c8 100644 --- a/cdcacm.cpp +++ b/cdcacm.cpp @@ -28,8 +28,8 @@ bControlIface(0), bDataIface(0), bNumEP(1), qNextPollTime(0), -ready(false), -bPollEnable(false) { +bPollEnable(false), +ready(false) { for (uint8_t i = 0; i < ACM_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; @@ -48,6 +48,8 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); + uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -95,7 +97,7 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -119,7 +121,7 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = lowspeed; - num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; + num_of_conf = udd->bNumConfigurations; // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); @@ -211,8 +213,8 @@ FailOnInit: USBTRACE("OnInit:"); #endif -Fail: #ifdef DEBUG_USB_HOST +Fail: NotifyFail(rcode); #endif Release(); diff --git a/cdcacm.h b/cdcacm.h index e8c4e57d..b94c2360 100644 --- a/cdcacm.h +++ b/cdcacm.h @@ -19,67 +19,67 @@ e-mail : support@circuitsathome.com #include "Usb.h" -#define bmREQ_CDCOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE -#define bmREQ_CDCIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE +#define bmREQ_CDCOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE +#define bmREQ_CDCIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE // CDC Subclass Constants -#define CDC_SUBCLASS_DLCM 0x01 // Direct Line Control Model -#define CDC_SUBCLASS_ACM 0x02 // Abstract Control Model -#define CDC_SUBCLASS_TCM 0x03 // Telephone Control Model -#define CDC_SUBCLASS_MCCM 0x04 // Multi Channel Control Model -#define CDC_SUBCLASS_CAPI 0x05 // CAPI Control Model -#define CDC_SUBCLASS_ETHERNET 0x06 // Ethernet Network Control Model -#define CDC_SUBCLASS_ATM 0x07 // ATM Network Control Model -#define CDC_SUBCLASS_WIRELESS_HANDSET 0x08 // Wireless Handset Control Model -#define CDC_SUBCLASS_DEVICE_MANAGEMENT 0x09 // Device Management -#define CDC_SUBCLASS_MOBILE_DIRECT_LINE 0x0A // Mobile Direct Line Model -#define CDC_SUBCLASS_OBEX 0x0B // OBEX -#define CDC_SUBCLASS_ETHERNET_EMU 0x0C // Ethernet Emulation Model +#define CDC_SUBCLASS_DLCM 0x01 // Direct Line Control Model +#define CDC_SUBCLASS_ACM 0x02 // Abstract Control Model +#define CDC_SUBCLASS_TCM 0x03 // Telephone Control Model +#define CDC_SUBCLASS_MCCM 0x04 // Multi Channel Control Model +#define CDC_SUBCLASS_CAPI 0x05 // CAPI Control Model +#define CDC_SUBCLASS_ETHERNET 0x06 // Ethernet Network Control Model +#define CDC_SUBCLASS_ATM 0x07 // ATM Network Control Model +#define CDC_SUBCLASS_WIRELESS_HANDSET 0x08 // Wireless Handset Control Model +#define CDC_SUBCLASS_DEVICE_MANAGEMENT 0x09 // Device Management +#define CDC_SUBCLASS_MOBILE_DIRECT_LINE 0x0A // Mobile Direct Line Model +#define CDC_SUBCLASS_OBEX 0x0B // OBEX +#define CDC_SUBCLASS_ETHERNET_EMU 0x0C // Ethernet Emulation Model // Communication Interface Class Control Protocol Codes -#define CDC_PROTOCOL_ITU_T_V_250 0x01 // AT Commands defined by ITU-T V.250 -#define CDC_PROTOCOL_PCCA_101 0x02 // AT Commands defined by PCCA-101 -#define CDC_PROTOCOL_PCCA_101_O 0x03 // AT Commands defined by PCCA-101 & Annex O -#define CDC_PROTOCOL_GSM_7_07 0x04 // AT Commands defined by GSM 7.07 -#define CDC_PROTOCOL_3GPP_27_07 0x05 // AT Commands defined by 3GPP 27.007 -#define CDC_PROTOCOL_C_S0017_0 0x06 // AT Commands defined by TIA for CDMA -#define CDC_PROTOCOL_USB_EEM 0x07 // Ethernet Emulation Model +#define CDC_PROTOCOL_ITU_T_V_250 0x01 // AT Commands defined by ITU-T V.250 +#define CDC_PROTOCOL_PCCA_101 0x02 // AT Commands defined by PCCA-101 +#define CDC_PROTOCOL_PCCA_101_O 0x03 // AT Commands defined by PCCA-101 & Annex O +#define CDC_PROTOCOL_GSM_7_07 0x04 // AT Commands defined by GSM 7.07 +#define CDC_PROTOCOL_3GPP_27_07 0x05 // AT Commands defined by 3GPP 27.007 +#define CDC_PROTOCOL_C_S0017_0 0x06 // AT Commands defined by TIA for CDMA +#define CDC_PROTOCOL_USB_EEM 0x07 // Ethernet Emulation Model // CDC Commands defined by CDC 1.2 -#define CDC_SEND_ENCAPSULATED_COMMAND 0x00 -#define CDC_GET_ENCAPSULATED_RESPONSE 0x01 +#define CDC_SEND_ENCAPSULATED_COMMAND 0x00 +#define CDC_GET_ENCAPSULATED_RESPONSE 0x01 // CDC Commands defined by PSTN 1.2 -#define CDC_SET_COMM_FEATURE 0x02 -#define CDC_GET_COMM_FEATURE 0x03 -#define CDC_CLEAR_COMM_FEATURE 0x04 -#define CDC_SET_AUX_LINE_STATE 0x10 -#define CDC_SET_HOOK_STATE 0x11 -#define CDC_PULSE_SETUP 0x12 -#define CDC_SEND_PULSE 0x13 -#define CDC_SET_PULSE_TIME 0x14 -#define CDC_RING_AUX_JACK 0x15 -#define CDC_SET_LINE_CODING 0x20 -#define CDC_GET_LINE_CODING 0x21 -#define CDC_SET_CONTROL_LINE_STATE 0x22 -#define CDC_SEND_BREAK 0x23 -#define CDC_SET_RINGER_PARMS 0x30 -#define CDC_GET_RINGER_PARMS 0x31 -#define CDC_SET_OPERATION_PARMS 0x32 -#define CDC_GET_OPERATION_PARMS 0x33 -#define CDC_SET_LINE_PARMS 0x34 -#define CDC_GET_LINE_PARMS 0x35 -#define CDC_DIAL_DIGITS 0x36 +#define CDC_SET_COMM_FEATURE 0x02 +#define CDC_GET_COMM_FEATURE 0x03 +#define CDC_CLEAR_COMM_FEATURE 0x04 +#define CDC_SET_AUX_LINE_STATE 0x10 +#define CDC_SET_HOOK_STATE 0x11 +#define CDC_PULSE_SETUP 0x12 +#define CDC_SEND_PULSE 0x13 +#define CDC_SET_PULSE_TIME 0x14 +#define CDC_RING_AUX_JACK 0x15 +#define CDC_SET_LINE_CODING 0x20 +#define CDC_GET_LINE_CODING 0x21 +#define CDC_SET_CONTROL_LINE_STATE 0x22 +#define CDC_SEND_BREAK 0x23 +#define CDC_SET_RINGER_PARMS 0x30 +#define CDC_GET_RINGER_PARMS 0x31 +#define CDC_SET_OPERATION_PARMS 0x32 +#define CDC_GET_OPERATION_PARMS 0x33 +#define CDC_SET_LINE_PARMS 0x34 +#define CDC_GET_LINE_PARMS 0x35 +#define CDC_DIAL_DIGITS 0x36 //Class-Specific Notification Codes -#define NETWORK_CONNECTION 0x00 -#define RESPONSE_AVAILABLE 0x01 -#define AUX_JACK_HOOK_STATE 0x08 -#define RING_DETECT 0x09 -#define SERIAL_STATE 0x20 -#define CALL_STATE_CHANGE 0x28 -#define LINE_STATE_CHANGE 0x29 -#define CONNECTION_SPEED_CHANGE 0x2a +#define NETWORK_CONNECTION 0x00 +#define RESPONSE_AVAILABLE 0x01 +#define AUX_JACK_HOOK_STATE 0x08 +#define RING_DETECT 0x09 +#define SERIAL_STATE 0x20 +#define CALL_STATE_CHANGE 0x28 +#define LINE_STATE_CHANGE 0x29 +#define CONNECTION_SPEED_CHANGE 0x2a // CDC Functional Descriptor Structures diff --git a/cdcftdi.cpp b/cdcftdi.cpp index 20d1dd66..40c5776f 100644 --- a/cdcftdi.cpp +++ b/cdcftdi.cpp @@ -42,6 +42,7 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -78,19 +79,18 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = lowspeed; // Get device descriptor - rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); + rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), buf); // Restore p->epinfo p->epinfo = oldep_ptr; if (rcode) goto FailGetDevDescr; - - if (((USB_DEVICE_DESCRIPTOR*)buf)->idVendor != FTDI_VID || ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct != FTDI_PID) + if (udd->idVendor != FTDI_VID || udd->idProduct != FTDI_PID) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Save type of FTDI chip - wFTDIType = ((USB_DEVICE_DESCRIPTOR*)buf)->bcdDevice; + wFTDIType = udd->bcdDevice; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); @@ -99,7 +99,7 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -123,7 +123,7 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = lowspeed; - num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; + num_of_conf = udd->bNumConfigurations; // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); @@ -204,10 +204,8 @@ FailSetConfDescr: FailOnInit: #ifdef DEBUG_USB_HOST USBTRACE("OnInit:"); -#endif Fail: -#ifdef DEBUG_USB_HOST NotifyFail(rcode); #endif Release(); diff --git a/cdcprolific.cpp b/cdcprolific.cpp index 649cab95..9992e4fe 100644 --- a/cdcprolific.cpp +++ b/cdcprolific.cpp @@ -25,6 +25,7 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -65,11 +66,11 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { if (rcode) goto FailGetDevDescr; - if (((USB_DEVICE_DESCRIPTOR*)buf)->idVendor != PL_VID && ((USB_DEVICE_DESCRIPTOR*)buf)->idProduct != PL_PID) + if (udd->idVendor != PL_VID && udd->idProduct != PL_PID) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Save type of PL chip - wPLType = ((USB_DEVICE_DESCRIPTOR*)buf)->bcdDevice; + wPLType = udd->bcdDevice; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); @@ -78,7 +79,7 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -102,7 +103,7 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = lowspeed; - num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; + num_of_conf = udd->bNumConfigurations; // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); @@ -184,8 +185,8 @@ FailOnInit: USBTRACE("OnInit:"); #endif -Fail: #ifdef DEBUG_USB_HOST +Fail: NotifyFail(rcode); #endif Release(); diff --git a/confdescparser.h b/confdescparser.h index b0c87d31..d7646a98 100644 --- a/confdescparser.h +++ b/confdescparser.h @@ -88,6 +88,8 @@ void ConfigDescParser::Parse(const uin compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */ template bool ConfigDescParser::ParseDescriptor(uint8_t **pp, uint16_t *pcntdn) { + USB_CONFIGURATION_DESCRIPTOR* ucd= reinterpret_cast(varBuffer); + USB_INTERFACE_DESCRIPTOR* uid= reinterpret_cast(varBuffer); switch(stateParseDescr) { case 0: theBuffer.valueSize = 2; @@ -128,22 +130,22 @@ bool ConfigDescParser::ParseDescriptor case USB_DESCRIPTOR_CONFIGURATION: if(!valParser.Parse(pp, pcntdn)) return false; - confValue = ((USB_CONFIGURATION_DESCRIPTOR*) varBuffer)->bConfigurationValue; + confValue = ucd->bConfigurationValue; break; case USB_DESCRIPTOR_INTERFACE: if(!valParser.Parse(pp, pcntdn)) return false; - if((MASK & CP_MASK_COMPARE_CLASS) && ((USB_INTERFACE_DESCRIPTOR*) varBuffer)->bInterfaceClass != CLASS_ID) + if((MASK & CP_MASK_COMPARE_CLASS) && uid->bInterfaceClass != CLASS_ID) break; - if((MASK & CP_MASK_COMPARE_SUBCLASS) && ((USB_INTERFACE_DESCRIPTOR*) varBuffer)->bInterfaceSubClass != SUBCLASS_ID) + if((MASK & CP_MASK_COMPARE_SUBCLASS) && uid->bInterfaceSubClass != SUBCLASS_ID) break; - if((MASK & CP_MASK_COMPARE_PROTOCOL) && ((USB_INTERFACE_DESCRIPTOR*) varBuffer)->bInterfaceProtocol != PROTOCOL_ID) + if((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID) break; isGoodInterface = true; - ifaceNumber = ((USB_INTERFACE_DESCRIPTOR*) varBuffer)->bInterfaceNumber; - ifaceAltSet = ((USB_INTERFACE_DESCRIPTOR*) varBuffer)->bAlternateSetting; - protoValue = ((USB_INTERFACE_DESCRIPTOR*) varBuffer)->bInterfaceProtocol; + ifaceNumber = uid->bInterfaceNumber; + ifaceAltSet = uid->bAlternateSetting; + protoValue = uid->bInterfaceProtocol; break; case USB_DESCRIPTOR_ENDPOINT: if(!valParser.Parse(pp, pcntdn)) diff --git a/examples/HID/USBHID_desc/USBHID_desc.ino b/examples/HID/USBHID_desc/USBHID_desc.ino index b156cafe..63ae76c7 100644 --- a/examples/HID/USBHID_desc/USBHID_desc.ino +++ b/examples/HID/USBHID_desc/USBHID_desc.ino @@ -2,14 +2,16 @@ #include #include #include - -#include "pgmstrings.h" +#ifdef arm +#include +#endif +#include "pgmstrings.h" class HIDUniversal2 : public HIDUniversal { public: HIDUniversal2(USB *usb) : HIDUniversal(usb) {}; - + protected: virtual uint8_t OnInitSuccessful(); }; @@ -17,13 +19,13 @@ protected: uint8_t HIDUniversal2::OnInitSuccessful() { uint8_t rcode; - + HexDumper Hex; ReportDescParser Rpt; if (rcode = GetReportDescr(0, &Hex)) goto FailGetReportDescr1; - + if (rcode = GetReportDescr(0, &Rpt)) goto FailGetReportDescr2; @@ -43,10 +45,10 @@ Fail: return rcode; } -USB Usb; -//USBHub Hub(&Usb); -HIDUniversal2 Hid(&Usb); -UniversalReportParser Uni; +USB Usb; +//USBHub Hub(&Usb); +HIDUniversal2 Hid(&Usb); +UniversalReportParser Uni; void setup() { @@ -56,11 +58,11 @@ void setup() if (Usb.Init() == -1) Serial.println("OSC did not start."); - + delay( 200 ); if (!Hid.SetReportParser(0, &Uni)) - ErrorMessage(PSTR("SetReportParser"), 1 ); + ErrorMessage(PSTR("SetReportParser"), 1 ); } void loop() diff --git a/hid.h b/hid.h index 8afd9936..53ef325c 100644 --- a/hid.h +++ b/hid.h @@ -20,75 +20,101 @@ e-mail : support@circuitsathome.com #include "Usb.h" #include "hidusagestr.h" -#define DATA_SIZE_MASK 0x03 -#define TYPE_MASK 0x0C -#define TAG_MASK 0xF0 +#define MAX_REPORT_PARSERS 2 +#define HID_MAX_HID_CLASS_DESCRIPTORS 5 -#define DATA_SIZE_0 0x00 -#define DATA_SIZE_1 0x01 -#define DATA_SIZE_2 0x02 -#define DATA_SIZE_4 0x03 +#define DATA_SIZE_MASK 0x03 +#define TYPE_MASK 0x0C +#define TAG_MASK 0xF0 -#define TYPE_MAIN 0x00 -#define TYPE_GLOBAL 0x04 -#define TYPE_LOCAL 0x08 +#define DATA_SIZE_0 0x00 +#define DATA_SIZE_1 0x01 +#define DATA_SIZE_2 0x02 +#define DATA_SIZE_4 0x03 -#define TAG_MAIN_INPUT 0x80 -#define TAG_MAIN_OUTPUT 0x90 -#define TAG_MAIN_COLLECTION 0xA0 -#define TAG_MAIN_FEATURE 0xB0 -#define TAG_MAIN_ENDCOLLECTION 0xC0 +#define TYPE_MAIN 0x00 +#define TYPE_GLOBAL 0x04 +#define TYPE_LOCAL 0x08 -#define TAG_GLOBAL_USAGEPAGE 0x00 -#define TAG_GLOBAL_LOGICALMIN 0x10 -#define TAG_GLOBAL_LOGICALMAX 0x20 -#define TAG_GLOBAL_PHYSMIN 0x30 -#define TAG_GLOBAL_PHYSMAX 0x40 -#define TAG_GLOBAL_UNITEXP 0x50 -#define TAG_GLOBAL_UNIT 0x60 -#define TAG_GLOBAL_REPORTSIZE 0x70 -#define TAG_GLOBAL_REPORTID 0x80 -#define TAG_GLOBAL_REPORTCOUNT 0x90 -#define TAG_GLOBAL_PUSH 0xA0 -#define TAG_GLOBAL_POP 0xB0 +#define TAG_MAIN_INPUT 0x80 +#define TAG_MAIN_OUTPUT 0x90 +#define TAG_MAIN_COLLECTION 0xA0 +#define TAG_MAIN_FEATURE 0xB0 +#define TAG_MAIN_ENDCOLLECTION 0xC0 -#define TAG_LOCAL_USAGE 0x00 -#define TAG_LOCAL_USAGEMIN 0x10 -#define TAG_LOCAL_USAGEMAX 0x20 +#define TAG_GLOBAL_USAGEPAGE 0x00 +#define TAG_GLOBAL_LOGICALMIN 0x10 +#define TAG_GLOBAL_LOGICALMAX 0x20 +#define TAG_GLOBAL_PHYSMIN 0x30 +#define TAG_GLOBAL_PHYSMAX 0x40 +#define TAG_GLOBAL_UNITEXP 0x50 +#define TAG_GLOBAL_UNIT 0x60 +#define TAG_GLOBAL_REPORTSIZE 0x70 +#define TAG_GLOBAL_REPORTID 0x80 +#define TAG_GLOBAL_REPORTCOUNT 0x90 +#define TAG_GLOBAL_PUSH 0xA0 +#define TAG_GLOBAL_POP 0xB0 + +#define TAG_LOCAL_USAGE 0x00 +#define TAG_LOCAL_USAGEMIN 0x10 +#define TAG_LOCAL_USAGEMAX 0x20 /* HID requests */ -#define bmREQ_HIDOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE -#define bmREQ_HIDIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE -#define bmREQ_HIDREPORT USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_INTERFACE +#define bmREQ_HIDOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE +#define bmREQ_HIDIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE +#define bmREQ_HIDREPORT USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_INTERFACE /* HID constants. Not part of chapter 9 */ /* Class-Specific Requests */ -#define HID_REQUEST_GET_REPORT 0x01 -#define HID_REQUEST_GET_IDLE 0x02 -#define HID_REQUEST_GET_PROTOCOL 0x03 -#define HID_REQUEST_SET_REPORT 0x09 -#define HID_REQUEST_SET_IDLE 0x0A -#define HID_REQUEST_SET_PROTOCOL 0x0B +#define HID_REQUEST_GET_REPORT 0x01 +#define HID_REQUEST_GET_IDLE 0x02 +#define HID_REQUEST_GET_PROTOCOL 0x03 +#define HID_REQUEST_SET_REPORT 0x09 +#define HID_REQUEST_SET_IDLE 0x0A +#define HID_REQUEST_SET_PROTOCOL 0x0B /* Class Descriptor Types */ -#define HID_DESCRIPTOR_HID 0x21 -#define HID_DESCRIPTOR_REPORT 0x22 -#define HID_DESRIPTOR_PHY 0x23 +#define HID_DESCRIPTOR_HID 0x21 +#define HID_DESCRIPTOR_REPORT 0x22 +#define HID_DESRIPTOR_PHY 0x23 /* Protocol Selection */ -#define HID_BOOT_PROTOCOL 0x00 -#define HID_RPT_PROTOCOL 0x01 +#define HID_BOOT_PROTOCOL 0x00 +#define HID_RPT_PROTOCOL 0x01 /* HID Interface Class Code */ -#define HID_INTF 0x03 +#define HID_INTF 0x03 /* HID Interface Class SubClass Codes */ -#define HID_BOOT_INTF_SUBCLASS 0x01 +#define HID_BOOT_INTF_SUBCLASS 0x01 /* HID Interface Class Protocol Codes */ -#define HID_PROTOCOL_NONE 0x00 -#define HID_PROTOCOL_KEYBOARD 0x01 -#define HID_PROTOCOL_MOUSE 0x02 +#define HID_PROTOCOL_NONE 0x00 +#define HID_PROTOCOL_KEYBOARD 0x01 +#define HID_PROTOCOL_MOUSE 0x02 + +#define HID_ITEM_TYPE_MAIN 0 +#define HID_ITEM_TYPE_GLOBAL 1 +#define HID_ITEM_TYPE_LOCAL 2 +#define HID_ITEM_TYPE_RESERVED 3 + +#define HID_LONG_ITEM_PREFIX 0xfe // Long item prefix value + +#define bmHID_MAIN_ITEM_TAG 0xfc // Main item tag mask + +#define bmHID_MAIN_ITEM_INPUT 0x80 // Main item Input tag value +#define bmHID_MAIN_ITEM_OUTPUT 0x90 // Main item Output tag value +#define bmHID_MAIN_ITEM_FEATURE 0xb0 // Main item Feature tag value +#define bmHID_MAIN_ITEM_COLLECTION 0xa0 // Main item Collection tag value +#define bmHID_MAIN_ITEM_END_COLLECTION 0xce // Main item End Collection tag value + +#define HID_MAIN_ITEM_COLLECTION_PHYSICAL 0 +#define HID_MAIN_ITEM_COLLECTION_APPLICATION 1 +#define HID_MAIN_ITEM_COLLECTION_LOGICAL 2 +#define HID_MAIN_ITEM_COLLECTION_REPORT 3 +#define HID_MAIN_ITEM_COLLECTION_NAMED_ARRAY 4 +#define HID_MAIN_ITEM_COLLECTION_USAGE_SWITCH 5 +#define HID_MAIN_ITEM_COLLECTION_USAGE_MODIFIER 6 struct HidItemPrefix { uint8_t bSize : 2; @@ -96,29 +122,6 @@ struct HidItemPrefix { uint8_t bTag : 4; }; -#define HID_ITEM_TYPE_MAIN 0 -#define HID_ITEM_TYPE_GLOBAL 1 -#define HID_ITEM_TYPE_LOCAL 2 -#define HID_ITEM_TYPE_RESERVED 3 - -#define HID_LONG_ITEM_PREFIX 0xfe // Long item prefix value - -#define bmHID_MAIN_ITEM_TAG 0xfc // Main item tag mask - -#define bmHID_MAIN_ITEM_INPUT 0x80 // Main item Input tag value -#define bmHID_MAIN_ITEM_OUTPUT 0x90 // Main item Output tag value -#define bmHID_MAIN_ITEM_FEATURE 0xb0 // Main item Feature tag value -#define bmHID_MAIN_ITEM_COLLECTION 0xa0 // Main item Collection tag value -#define bmHID_MAIN_ITEM_END_COLLECTION 0xce // Main item End Collection tag value - -#define HID_MAIN_ITEM_COLLECTION_PHYSICAL 0 -#define HID_MAIN_ITEM_COLLECTION_APPLICATION 1 -#define HID_MAIN_ITEM_COLLECTION_LOGICAL 2 -#define HID_MAIN_ITEM_COLLECTION_REPORT 3 -#define HID_MAIN_ITEM_COLLECTION_NAMED_ARRAY 4 -#define HID_MAIN_ITEM_COLLECTION_USAGE_SWITCH 5 -#define HID_MAIN_ITEM_COLLECTION_USAGE_MODIFIER 6 - struct MainItemIOFeature { uint8_t bmIsConstantOrData : 1; uint8_t bmIsArrayOrVariable : 1; @@ -137,8 +140,6 @@ public: virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) = 0; }; -#define MAX_REPORT_PARSERS 2 -#define HID_MAX_HID_CLASS_DESCRIPTORS 5 class HID : public USBDeviceConfig, public UsbConfigXtracter { protected: diff --git a/hidboot.h b/hidboot.h index 826e8e72..1faec28a 100644 --- a/hidboot.h +++ b/hidboot.h @@ -19,11 +19,43 @@ e-mail : support@circuitsathome.com #include "hid.h" -#define KEY_SPACE 0x2c -#define KEY_ZERO 0x27 -#define KEY_ZERO2 0x62 -#define KEY_ENTER 0x28 -#define KEY_PERIOD 0x63 +// +// FIX-ME: +// Prevent teensy HID collisions. +// These are problematic. Who changes? +// The best policy for now is to take over these definitions. +// This is a classic reason why a library should prefix defines with something unique. +// I suggest prefixing with 'UHS_' for every define in the entire library. +// Yes, this could break things, but what is one to do? +// +#ifdef KEY_SPACE +#undef KEY_SPACE +#endif +#ifdef KEY_ENTER +#undef KEY_ENTER +#endif +#ifdef KEY_PERIOD +#undef KEY_PERIOD +#endif +#ifdef KEY_NUM_LOCK +#undef KEY_NUM_LOCK +#endif +#ifdef KEY_CAPS_LOCK +#undef KEY_CAPS_LOCK +#endif +#ifdef KEY_SCROLL_LOCK +#undef KEY_SCROLL_LOCK +#endif + +#define KEY_ZERO 0x27 +#define KEY_ENTER 0x28 +#define KEY_SPACE 0x2c +#define KEY_CAPS_LOCK 0x39 +#define KEY_SCROLL_LOCK 0x47 +#define KEY_NUM_LOCK 0x53 +#define KEY_ZERO2 0x62 +#define KEY_PERIOD 0x63 + struct MOUSEINFO { @@ -107,10 +139,6 @@ struct KBDLEDS { uint8_t bmReserved : 3; }; -#define KEY_NUM_LOCK 0x53 -#define KEY_CAPS_LOCK 0x39 -#define KEY_SCROLL_LOCK 0x47 - class KeyboardReportParser : public HIDReportParser { static const uint8_t numKeys[]; static const uint8_t symKeysUp[]; diff --git a/hidescriptorparser.cpp b/hidescriptorparser.cpp index d4c96f20..c4c7338d 100644 --- a/hidescriptorparser.cpp +++ b/hidescriptorparser.cpp @@ -1073,8 +1073,8 @@ void ReportDescParserBase::PrintItemTitle(uint8_t prefix) { uint8_t ReportDescParserBase::ParseItem(uint8_t **pp, uint16_t *pcntdn) { //uint8_t ret = enErrorSuccess; - - switch (itemParseState) { + //reinterpret_cast<>(varBuffer); +switch (itemParseState) { case 0: if (**pp == HID_LONG_ITEM_PREFIX) USBTRACE("\r\nLONG\r\n"); @@ -1113,9 +1113,10 @@ uint8_t ReportDescParserBase::ParseItem(uint8_t **pp, uint16_t *pcntdn) { switch (itemPrefix & (TYPE_MASK | TAG_MASK)) { case (TYPE_LOCAL | TAG_LOCAL_USAGE): if (pfUsage) { - if (theBuffer.valueSize > 1) - pfUsage(*((uint16_t*)varBuffer)); - else + if (theBuffer.valueSize > 1) { + uint16_t* ui16 = reinterpret_cast(varBuffer); + pfUsage(*ui16); + } else pfUsage(data); } break; @@ -1237,16 +1238,19 @@ void ReportDescParserBase::SetUsagePage(uint16_t page) { } void ReportDescParserBase::PrintUsagePage(uint16_t page) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (page > 0x00 && page < 0x11) - E_Notify((char*)pgm_read_pointer(&usagePageTitles0[page - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&usagePageTitles0[page - 1]), 0x80); + output_pgm_message(w, E_Notify, usagePageTitles0[page - 1], 0x80); else if (page > 0x7f && page < 0x84) E_Notify(pstrUsagePageMonitor, 0x80); else if (page > 0x83 && page < 0x8c) E_Notify(pstrUsagePagePower, 0x80); else if (page > 0x8b && page < 0x92) - E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c]), 0x80); + //E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c]), 0x80); + output_pgm_message(w, E_Notify, usagePageTitles1[page - 0x8c], 0x80); else if (page > 0xfeff && page <= 0xffff) E_Notify(pstrUsagePageVendorDefined, 0x80); else @@ -1280,188 +1284,249 @@ void ReportDescParserBase::PrintOrdinalPageUsage(uint16_t usage) { } void ReportDescParserBase::PrintGenericDesktopPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x0a) - E_Notify((char*)pgm_read_pointer(&genDesktopTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&genDesktopTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, genDesktopTitles0[usage - 1], 0x80); else if (usage > 0x2f && usage < 0x49) - E_Notify((char*)pgm_read_pointer(&genDesktopTitles1[usage - 0x30]), 0x80); + //E_Notify((char*)pgm_read_pointer(&genDesktopTitles1[usage - 0x30]), 0x80); + output_pgm_message(w, E_Notify, genDesktopTitles1[usage - 0x30], 0x80); else if (usage > 0x7f && usage < 0x94) - E_Notify((char*)pgm_read_pointer(&genDesktopTitles2[usage - 0x80]), 0x80); + //E_Notify((char*)pgm_read_pointer(&genDesktopTitles2[usage - 0x80]), 0x80); + output_pgm_message(w, E_Notify, genDesktopTitles2[usage - 0x80], 0x80); else if (usage > 0x9f && usage < 0xa9) - E_Notify((char*)pgm_read_pointer(&genDesktopTitles3[usage - 0xa0]), 0x80); + //E_Notify((char*)pgm_read_pointer(&genDesktopTitles3[usage - 0xa0]), 0x80); + output_pgm_message(w, E_Notify, genDesktopTitles3[usage - 0xa0], 0x80); else if (usage > 0xaf && usage < 0xb8) - E_Notify((char*)pgm_read_pointer(&genDesktopTitles4[usage - 0xb0]), 0x80); + //E_Notify((char*)pgm_read_pointer(&genDesktopTitles4[usage - 0xb0]), 0x80); + output_pgm_message(w, E_Notify, genDesktopTitles4[usage - 0xb0], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintSimulationControlsPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x0d) - E_Notify((char*)pgm_read_pointer(&simuTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&simuTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, simuTitles0[usage - 1], 0x80); else if (usage > 0x1f && usage < 0x26) - E_Notify((char*)pgm_read_pointer(&simuTitles1[usage - 0x20]), 0x80); + //E_Notify((char*)pgm_read_pointer(&simuTitles1[usage - 0x20]), 0x80); + output_pgm_message(w, E_Notify, simuTitles1[usage - 0x20], 0x80); else if (usage > 0xaf && usage < 0xd1) - E_Notify((char*)pgm_read_pointer(&simuTitles2[usage - 0xb0]), 0x80); + //E_Notify((char*)pgm_read_pointer(&simuTitles2[usage - 0xb0]), 0x80); + output_pgm_message(w, E_Notify, simuTitles2[usage - 0xb0], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintVRControlsPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x0b) - E_Notify((char*)pgm_read_pointer(&vrTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&vrTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, vrTitles0[usage - 1], 0x80); else if (usage > 0x1f && usage < 0x22) - E_Notify((char*)pgm_read_pointer(&vrTitles1[usage - 0x20]), 0x80); + //E_Notify((char*)pgm_read_pointer(&vrTitles1[usage - 0x20]), 0x80); + output_pgm_message(w, E_Notify, vrTitles1[usage - 0x20], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintSportsControlsPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x05) - E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, sportsCtrlTitles0[usage - 1], 0x80); else if (usage > 0x2f && usage < 0x3a) - E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles1[usage - 0x30]), 0x80); + //E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles1[usage - 0x30]), 0x80); + output_pgm_message(w, E_Notify, sportsCtrlTitles1[usage - 0x30], 0x80); else if (usage > 0x4f && usage < 0x64) - E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles2[usage - 0x50]), 0x80); + //E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles2[usage - 0x50]), 0x80); + output_pgm_message(w, E_Notify, sportsCtrlTitles2[usage - 0x50], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintGameControlsPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x04) - E_Notify((char*)pgm_read_pointer(&gameTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&gameTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, gameTitles0[usage - 1], 0x80); else if (usage > 0x1f && usage < 0x3a) - E_Notify((char*)pgm_read_pointer(&gameTitles1[usage - 0x20]), 0x80); + //E_Notify((char*)pgm_read_pointer(&gameTitles1[usage - 0x20]), 0x80); + output_pgm_message(w, E_Notify, gameTitles1[usage - 0x20], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintGenericDeviceControlsPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x1f && usage < 0x27) - E_Notify((char*)pgm_read_pointer(&genDevCtrlTitles[usage - 0x20]), 0x80); + //E_Notify((char*)pgm_read_pointer(&genDevCtrlTitles[usage - 0x20]), 0x80); + output_pgm_message(w, E_Notify, genDevCtrlTitles[usage - 0x20], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintLEDPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x4e) - E_Notify((char*)pgm_read_pointer(&ledTitles[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&ledTitles[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, ledTitles[usage - 1], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintTelephonyPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x08) - E_Notify((char*)pgm_read_pointer(&telTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&telTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, telTitles0[usage - 1], 0x80); else if (usage > 0x1f && usage < 0x32) - E_Notify((char*)pgm_read_pointer(&telTitles1[usage - 0x1f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&telTitles1[usage - 0x1f]), 0x80); + output_pgm_message(w, E_Notify, telTitles1[usage - 0x1f], 0x80); else if (usage > 0x4f && usage < 0x54) - E_Notify((char*)pgm_read_pointer(&telTitles2[usage - 0x4f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&telTitles2[usage - 0x4f]), 0x80); + output_pgm_message(w, E_Notify, telTitles2[usage - 0x4f], 0x80); else if (usage > 0x6f && usage < 0x75) - E_Notify((char*)pgm_read_pointer(&telTitles3[usage - 0x6f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&telTitles3[usage - 0x6f]), 0x80); + output_pgm_message(w, E_Notify, telTitles3[usage - 0x6f], 0x80); else if (usage > 0x8f && usage < 0x9f) - E_Notify((char*)pgm_read_pointer(&telTitles4[usage - 0x8f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&telTitles4[usage - 0x8f]), 0x80); + output_pgm_message(w, E_Notify, telTitles4[usage - 0x8f], 0x80); else if (usage > 0xaf && usage < 0xc0) - E_Notify((char*)pgm_read_pointer(&telTitles5[usage - 0xaf]), 0x80); + //E_Notify((char*)pgm_read_pointer(&telTitles5[usage - 0xaf]), 0x80); + output_pgm_message(w, E_Notify, telTitles5[usage - 0xaf], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintConsumerPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x07) - E_Notify((char*)pgm_read_pointer(&consTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, consTitles0[usage - 1], 0x80); else if (usage > 0x1f && usage < 0x23) - E_Notify((char*)pgm_read_pointer(&consTitles1[usage - 0x1f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles1[usage - 0x1f]), 0x80); + output_pgm_message(w, E_Notify, consTitles1[usage - 0x1f], 0x80); else if (usage > 0x2f && usage < 0x37) - E_Notify((char*)pgm_read_pointer(&consTitles2[usage - 0x2f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles2[usage - 0x2f]), 0x80); + output_pgm_message(w, E_Notify, consTitles2[usage - 0x2f], 0x80); else if (usage > 0x3f && usage < 0x49) - E_Notify((char*)pgm_read_pointer(&consTitles3[usage - 0x3f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles3[usage - 0x3f]), 0x80); + output_pgm_message(w, E_Notify, consTitles3[usage - 0x3f], 0x80); else if (usage > 0x5f && usage < 0x67) - E_Notify((char*)pgm_read_pointer(&consTitles4[usage - 0x5f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles4[usage - 0x5f]), 0x80); + output_pgm_message(w, E_Notify, consTitles4[usage - 0x5f], 0x80); else if (usage > 0x7f && usage < 0xa5) - E_Notify((char*)pgm_read_pointer(&consTitles5[usage - 0x7f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles5[usage - 0x7f]), 0x80); + output_pgm_message(w, E_Notify, consTitles5[usage - 0x7f], 0x80); else if (usage > 0xaf && usage < 0xcf) - E_Notify((char*)pgm_read_pointer(&consTitles6[usage - 0xaf]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles6[usage - 0xaf]), 0x80); + output_pgm_message(w, E_Notify, consTitles6[usage - 0xaf], 0x80); else if (usage > 0xdf && usage < 0xeb) - E_Notify((char*)pgm_read_pointer(&consTitles7[usage - 0xdf]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles7[usage - 0xdf]), 0x80); + output_pgm_message(w, E_Notify, consTitles7[usage - 0xdf], 0x80); else if (usage > 0xef && usage < 0xf6) - E_Notify((char*)pgm_read_pointer(&consTitles8[usage - 0xef]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles8[usage - 0xef]), 0x80); + output_pgm_message(w, E_Notify, consTitles8[usage - 0xef], 0x80); else if (usage > 0xff && usage < 0x10e) - E_Notify((char*)pgm_read_pointer(&consTitles9[usage - 0xff]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitles9[usage - 0xff]), 0x80); + output_pgm_message(w, E_Notify, consTitles9[usage - 0xff], 0x80); else if (usage > 0x14f && usage < 0x156) - E_Notify((char*)pgm_read_pointer(&consTitlesA[usage - 0x14f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitlesA[usage - 0x14f]), 0x80); + output_pgm_message(w, E_Notify, consTitlesA[usage - 0x14f], 0x80); else if (usage > 0x15f && usage < 0x16b) - E_Notify((char*)pgm_read_pointer(&consTitlesB[usage - 0x15f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitlesB[usage - 0x15f]), 0x80); + output_pgm_message(w, E_Notify, consTitlesB[usage - 0x15f], 0x80); else if (usage > 0x16f && usage < 0x175) - E_Notify((char*)pgm_read_pointer(&consTitlesC[usage - 0x16f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitlesC[usage - 0x16f]), 0x80); + output_pgm_message(w, E_Notify, consTitlesC[usage - 0x16f], 0x80); else if (usage > 0x17f && usage < 0x1c8) - E_Notify((char*)pgm_read_pointer(&consTitlesD[usage - 0x17f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitlesD[usage - 0x17f]), 0x80); + output_pgm_message(w, E_Notify, consTitlesD[usage - 0x17f], 0x80); else if (usage > 0x1ff && usage < 0x29d) - E_Notify((char*)pgm_read_pointer(&consTitlesE[usage - 0x1ff]), 0x80); + //E_Notify((char*)pgm_read_pointer(&consTitlesE[usage - 0x1ff]), 0x80); + output_pgm_message(w, E_Notify, consTitlesE[usage - 0x1ff], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintDigitizerPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x0e) - E_Notify((char*)pgm_read_pointer(&digitTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&digitTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, digitTitles0[usage - 1], 0x80); else if (usage > 0x1f && usage < 0x23) - E_Notify((char*)pgm_read_pointer(&digitTitles1[usage - 0x1f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&digitTitles1[usage - 0x1f]), 0x80); + output_pgm_message(w, E_Notify, digitTitles1[usage - 0x1f], 0x80); else if (usage > 0x2f && usage < 0x47) - E_Notify((char*)pgm_read_pointer(&digitTitles2[usage - 0x2f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&digitTitles2[usage - 0x2f]), 0x80); + output_pgm_message(w, E_Notify, digitTitles2[usage - 0x2f], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintAlphanumDisplayPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); if (usage > 0x00 && usage < 0x03) - E_Notify((char*)pgm_read_pointer(&aplphanumTitles0[usage - 1]), 0x80); + //E_Notify((char*)pgm_read_pointer(&aplphanumTitles0[usage - 1]), 0x80); + output_pgm_message(w, E_Notify, aplphanumTitles0[usage - 1], 0x80); else if (usage > 0x1f && usage < 0x4e) - E_Notify((char*)pgm_read_pointer(&aplphanumTitles1[usage - 0x1f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&aplphanumTitles1[usage - 0x1f]), 0x80); + output_pgm_message(w, E_Notify, aplphanumTitles1[usage - 0x1f], 0x80); else if (usage > 0x7f && usage < 0x96) - E_Notify((char*)pgm_read_pointer(&digitTitles2[usage - 0x80]), 0x80); + //E_Notify((char*)pgm_read_pointer(&digitTitles2[usage - 0x80]), 0x80); + output_pgm_message(w, E_Notify, digitTitles2[usage - 0x80], 0x80); else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) { + const char * const * w; E_Notify(pstrSpace, 0x80); - + //output_pgm_message(w, E_Notify, , 0x80); if (usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80); else if (usage > 0x1f && usage < 0x28) - E_Notify((char*)pgm_read_pointer(&medInstrTitles0[usage - 0x1f]), 0x80); + //E_Notify((char*)pgm_read_pointer(&medInstrTitles0[usage - 0x1f]), 0x80); + output_pgm_message(w, E_Notify, medInstrTitles0[usage - 0x1f], 0x80); else if (usage > 0x3f && usage < 0x45) - E_Notify((char*)pgm_read_pointer(&medInstrTitles1[usage - 0x40]), 0x80); + //E_Notify((char*)pgm_read_pointer(&medInstrTitles1[usage - 0x40]), 0x80); + output_pgm_message(w, E_Notify, medInstrTitles1[usage - 0x40], 0x80); else if (usage > 0x5f && usage < 0x62) - E_Notify((char*)pgm_read_pointer(&medInstrTitles2[usage - 0x60]), 0x80); + //E_Notify((char*)pgm_read_pointer(&medInstrTitles2[usage - 0x60]), 0x80); + output_pgm_message(w, E_Notify, medInstrTitles2[usage - 0x60], 0x80); else if (usage == 0x70) E_Notify(pstrUsageDepthGainCompensation, 0x80); else if (usage > 0x7f && usage < 0x8a) - E_Notify((char*)pgm_read_pointer(&medInstrTitles3[usage - 0x80]), 0x80); + //E_Notify((char*)pgm_read_pointer(&medInstrTitles3[usage - 0x80]), 0x80); + output_pgm_message(w, E_Notify, medInstrTitles3[usage - 0x80], 0x80); else if (usage > 0x9f && usage < 0xa2) - E_Notify((char*)pgm_read_pointer(&medInstrTitles4[usage - 0xa0]), 0x80); - else + // E_Notify((char*)pgm_read_pointer(&medInstrTitles4[usage - 0xa0]), 0x80); + output_pgm_message(w, E_Notify, medInstrTitles4[usage - 0xa0], 0x80); + else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1502,9 +1567,10 @@ uint8_t ReportDescParser2::ParseItem(uint8_t **pp, uint16_t *pcntdn) { switch (itemPrefix & (TYPE_MASK | TAG_MASK)) { case (TYPE_LOCAL | TAG_LOCAL_USAGE): if (pfUsage) { - if (theBuffer.valueSize > 1) - pfUsage(*((uint16_t*)varBuffer)); - else + if (theBuffer.valueSize > 1) { + uint16_t* ui16 = reinterpret_cast(varBuffer); + pfUsage(*ui16); + } else pfUsage(data); } break; diff --git a/hidescriptorparser.h b/hidescriptorparser.h index a28ff212..ac030e8e 100644 --- a/hidescriptorparser.h +++ b/hidescriptorparser.h @@ -126,7 +126,8 @@ public: itemPrefix(0), rptSize(0), rptCount(0), - pfUsage(NULL) { + pfUsage(NULL) + { theBuffer.pValue = varBuffer; valParser.Initialize(&theBuffer); theSkipper.Initialize(&theBuffer); diff --git a/hiduniversal.cpp b/hiduniversal.cpp index 536b0193..e55e80ff 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -77,6 +77,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -134,7 +135,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -147,7 +148,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { return rcode; } - delay( 2 ); //per USB 2.0 sect.9.2.6.3 + delay( 2 ); //per USB 2.0 sect.9.2.6.3 USBTRACE2("Addr:", bAddress); @@ -166,7 +167,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { if (rcode) goto FailGetDevDescr; - num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; + num_of_conf = udd->bNumConfigurations; // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); @@ -252,8 +253,8 @@ FailSetIdle: USBTRACE("SetIdle:"); #endif -Fail: #ifdef DEBUG_USB_HOST +Fail: NotifyFail(rcode); #endif Release(); diff --git a/masstorage.cpp b/masstorage.cpp index c593ae22..be35d9b0 100644 --- a/masstorage.cpp +++ b/masstorage.cpp @@ -236,6 +236,7 @@ uint8_t BulkOnly::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -282,9 +283,9 @@ uint8_t BulkOnly::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Steal and abuse from epInfo structure to save on memory. - epInfo[1].epAddr = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; + epInfo[1].epAddr = udd->bNumConfigurations; // return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET; @@ -294,7 +295,6 @@ FailGetDevDescr: #endif rcode = USB_ERROR_FailGetDevDescr; -Fail: Release(); return rcode; }; @@ -436,7 +436,7 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { printf(" standards.\r\n"); #endif uint8_t tries = 0xf0; - while (rcode = TestUnitReady(lun)) { + while ((rcode = TestUnitReady(lun))) { if (rcode == 0x08) break; // break on no media, this is OK to do. // try to lock media and spin up if (tries < 14) { @@ -489,8 +489,8 @@ FailGetMaxLUN: goto Fail; #endif -FailInvalidSectorSize: #ifdef DEBUG_USB_HOST +FailInvalidSectorSize: USBTRACE("Sector Size is NOT VALID: "); goto Fail; #endif @@ -506,8 +506,8 @@ FailGetConfDescr: NotifyFailGetConfDescr(); #endif -Fail: #ifdef DEBUG_USB_HOST +Fail: NotifyFail(rcode); #endif Release(); @@ -808,9 +808,8 @@ uint8_t BulkOnly::ClearEpHalt(uint8_t index) { uint8_t ret = 0; - while (ret = (pUsb->ctrlReq(bAddress, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_STANDARD | USB_SETUP_RECIPIENT_ENDPOINT, - USB_REQUEST_CLEAR_FEATURE, USB_FEATURE_ENDPOINT_HALT, 0, ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr), 0, 0, NULL, NULL)) - == 0x01) delay(6); + while ((ret = (pUsb->ctrlReq(bAddress, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_STANDARD | USB_SETUP_RECIPIENT_ENDPOINT, USB_REQUEST_CLEAR_FEATURE, USB_FEATURE_ENDPOINT_HALT, 0, ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr), 0, 0, NULL, NULL)) == 0x01)) + delay(6); if (ret) { ErrorMessage (PSTR("ClearEpHalt"), ret); diff --git a/masstorage.h b/masstorage.h index 12a61ec9..6a1391a0 100644 --- a/masstorage.h +++ b/masstorage.h @@ -394,7 +394,7 @@ public: bmCBWLUN(lu), bmReserved1(0), bmCBWCBLength(cmdlen), bmReserved2(0) { for(int i = 0; i < 16; i++) CBWCB[i] = 0; // Type punning can cause optimization problems and bugs. - // Using reinterpret_cast to a different object is the proper way to do this. + // Using reinterpret_cast to a dreinterpretifferent object is the proper way to do this. //(((BASICCDB_t *) CBWCB)->LUN) = cmd; BASICCDB_t *x = reinterpret_cast (CBWCB); x->LUN = cmd; diff --git a/message.cpp b/message.cpp index 1ac73f48..4ec9d5c8 100644 --- a/message.cpp +++ b/message.cpp @@ -44,7 +44,7 @@ void E_NotifyStr(char const * msg, int lvl) { if (!msg) return; char c; - while (c = *msg++) E_Notifyc(c, lvl); + while ((c = *msg++)) E_Notifyc(c, lvl); } void E_Notify(uint8_t b, int lvl) { diff --git a/usbhub.cpp b/usbhub.cpp index e117a069..0e49c401 100644 --- a/usbhub.cpp +++ b/usbhub.cpp @@ -41,6 +41,9 @@ bPollEnable(false) { uint8_t USBHub::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t buf[32]; + USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); + HubDescriptor* hd = reinterpret_cast(buf); + USB_CONFIGURATION_DESCRIPTOR * ucd = reinterpret_cast(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; @@ -90,17 +93,17 @@ uint8_t USBHub::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Extract device class from device descriptor // If device class is not a hub return - if (((USB_DEVICE_DESCRIPTOR*)buf)->bDeviceClass != 0x09) + if (udd->bDeviceClass != 0x09) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, (((USB_DEVICE_DESCRIPTOR*)buf)->bDeviceClass == 0x09) ? true : false, port); + bAddress = addrPool.AllocAddress(parent, (udd->bDeviceClass == 0x09) ? true : false, port); if (!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = ((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -140,7 +143,7 @@ uint8_t USBHub::Init(uint8_t parent, uint8_t port, bool lowspeed) { goto FailGetHubDescr; // Save number of ports for future use - bNbrPorts = ((HubDescriptor*)buf)->bNbrPorts; + bNbrPorts = hd->bNbrPorts; // bInitState = 2; @@ -149,7 +152,7 @@ uint8_t USBHub::Init(uint8_t parent, uint8_t port, bool lowspeed) { rcode = pUsb->getConfDescr(bAddress, 0, 8, 0, buf); if (!rcode) { - cd_len = ((USB_CONFIGURATION_DESCRIPTOR*)buf)->wTotalLength; + cd_len = ucd->wTotalLength; rcode = pUsb->getConfDescr(bAddress, 0, cd_len, 0, buf); } if (rcode) From f38a0f65157af628ca5f7706499748c199f0611b Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 4 Dec 2013 21:11:25 -0500 Subject: [PATCH 002/145] Refactor conflicting defines --- hidboot.cpp | 18 +++++++++--------- hidboot.h | 44 ++++++++------------------------------------ 2 files changed, 17 insertions(+), 45 deletions(-) diff --git a/hidboot.cpp b/hidboot.cpp index c7f33789..2737b7b9 100644 --- a/hidboot.cpp +++ b/hidboot.cpp @@ -56,7 +56,7 @@ void KeyboardReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t if (prevState.bInfo[0x00] != buf[0x00]) { OnControlKeysChanged(prevState.bInfo[0x00], buf[0x00]); } - + for (uint8_t i = 2; i < 8; i++) { bool down = false; bool up = false; @@ -82,13 +82,13 @@ uint8_t KeyboardReportParser::HandleLockingKeys(HID *hid, uint8_t key) { uint8_t old_keys = kbdLockingKeys.bLeds; switch (key) { - case KEY_NUM_LOCK: + case UHS_HID_BOOT_KEY_NUM_LOCK: kbdLockingKeys.kbdLeds.bmNumLock = ~kbdLockingKeys.kbdLeds.bmNumLock; break; - case KEY_CAPS_LOCK: + case UHS_HID_BOOT_KEY_CAPS_LOCK: kbdLockingKeys.kbdLeds.bmCapsLock = ~kbdLockingKeys.kbdLeds.bmCapsLock; break; - case KEY_SCROLL_LOCK: + case UHS_HID_BOOT_KEY_SCROLL_LOCK: kbdLockingKeys.kbdLeds.bmScrollLock = ~kbdLockingKeys.kbdLeds.bmScrollLock; break; } @@ -133,11 +133,11 @@ uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { return (uint8_t)pgm_read_byte(&padKeys[key - 0x54]); else { switch (key) { - case KEY_SPACE: return (0x20); - case KEY_ENTER: return (0x13); - case KEY_ZERO: return ((shift) ? ')': '0'); - case KEY_ZERO2: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '0': 0); - case KEY_PERIOD: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '.': 0); + case UHS_HID_BOOT_KEY_SPACE: return (0x20); + case UHS_HID_BOOT_KEY_ENTER: return (0x13); + case UHS_HID_BOOT_KEY_ZERO: return ((shift) ? ')': '0'); + case UHS_HID_BOOT_KEY_ZERO2: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '0': 0); + case UHS_HID_BOOT_KEY_PERIOD: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '.': 0); } } return ( 0); diff --git a/hidboot.h b/hidboot.h index 1faec28a..30d00ae8 100644 --- a/hidboot.h +++ b/hidboot.h @@ -19,42 +19,14 @@ e-mail : support@circuitsathome.com #include "hid.h" -// -// FIX-ME: -// Prevent teensy HID collisions. -// These are problematic. Who changes? -// The best policy for now is to take over these definitions. -// This is a classic reason why a library should prefix defines with something unique. -// I suggest prefixing with 'UHS_' for every define in the entire library. -// Yes, this could break things, but what is one to do? -// -#ifdef KEY_SPACE -#undef KEY_SPACE -#endif -#ifdef KEY_ENTER -#undef KEY_ENTER -#endif -#ifdef KEY_PERIOD -#undef KEY_PERIOD -#endif -#ifdef KEY_NUM_LOCK -#undef KEY_NUM_LOCK -#endif -#ifdef KEY_CAPS_LOCK -#undef KEY_CAPS_LOCK -#endif -#ifdef KEY_SCROLL_LOCK -#undef KEY_SCROLL_LOCK -#endif - -#define KEY_ZERO 0x27 -#define KEY_ENTER 0x28 -#define KEY_SPACE 0x2c -#define KEY_CAPS_LOCK 0x39 -#define KEY_SCROLL_LOCK 0x47 -#define KEY_NUM_LOCK 0x53 -#define KEY_ZERO2 0x62 -#define KEY_PERIOD 0x63 +#define UHS_HID_BOOT_KEY_ZERO 0x27 +#define UHS_HID_BOOT_KEY_ENTER 0x28 +#define UHS_HID_BOOT_KEY_SPACE 0x2c +#define UHS_HID_BOOT_KEY_CAPS_LOCK 0x39 +#define UHS_HID_BOOT_KEY_SCROLL_LOCK 0x47 +#define UHS_HID_BOOT_KEY_NUM_LOCK 0x53 +#define UHS_HID_BOOT_KEY_ZERO2 0x62 +#define UHS_HID_BOOT_KEY_PERIOD 0x63 struct MOUSEINFO { From ac1212647785f8f4d7e94ae0237777aa7072fe0f Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 4 Dec 2013 21:55:24 -0500 Subject: [PATCH 003/145] Macroize desc parser --- avrpins.h | 1 - hidescriptorparser.cpp | 276 +++++++++++++---------------------------- macros.h | 5 + 3 files changed, 88 insertions(+), 194 deletions(-) diff --git a/avrpins.h b/avrpins.h index 16b0c0fb..5a7e1756 100644 --- a/avrpins.h +++ b/avrpins.h @@ -821,5 +821,4 @@ MAKE_PIN(P33, CORE_PIN33_PORTREG, CORE_PIN33_BIT, CORE_PIN33_CONFIG); #endif // __arm__ -#define output_pgm_message(wa, fp, mp , el) wa = &mp, fp((char *)pgm_read_pointer(wa), el) #endif //_avrpins_h_ diff --git a/hidescriptorparser.cpp b/hidescriptorparser.cpp index c4c7338d..c25ded35 100644 --- a/hidescriptorparser.cpp +++ b/hidescriptorparser.cpp @@ -1216,16 +1216,21 @@ ReportDescParserBase::UsagePageFunc ReportDescParserBase::usagePageFunctions[] / void ReportDescParserBase::SetUsagePage(uint16_t page) { pfUsage = NULL; - if (page > 0x00 && page < 0x11) - pfUsage = /*(UsagePageFunc)pgm_read_pointer*/(usagePageFunctions[page - 1]); - //else if (page > 0x7f && page < 0x84) - // E_Notify(pstrUsagePageMonitor); - //else if (page > 0x83 && page < 0x8c) - // E_Notify(pstrUsagePagePower); - //else if (page > 0x8b && page < 0x92) - // E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c])); - //else if (page > 0xfeff && page <= 0xffff) - // E_Notify(pstrUsagePageVendorDefined); + if (VALUE_BETWEEN(page, 0x00, 0x11)) + pfUsage = (usagePageFunctions[page - 1]); + + // Dead code... + // + // pfUsage = (UsagePageFunc)pgm_read_pointer(usagePageFunctions[page - 1]); + //else if (page > 0x7f && page < 0x84) + // E_Notify(pstrUsagePageMonitor); + //else if (page > 0x83 && page < 0x8c) + // E_Notify(pstrUsagePagePower); + //else if (page > 0x8b && page < 0x92) + // E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c])); + //else if (page > 0xfeff && page <= 0xffff) + // E_Notify(pstrUsagePageVendorDefined); + // else switch (page) { case 0x14: @@ -1241,17 +1246,13 @@ void ReportDescParserBase::PrintUsagePage(uint16_t page) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (page > 0x00 && page < 0x11) - //E_Notify((char*)pgm_read_pointer(&usagePageTitles0[page - 1]), 0x80); - output_pgm_message(w, E_Notify, usagePageTitles0[page - 1], 0x80); - else if (page > 0x7f && page < 0x84) + output_if_between(page, 0x00, 0x11, w, E_Notify, usagePageTitles0[page - 1], 0x80) + else output_if_between(page, 0x8b, 0x92, w, E_Notify, usagePageTitles1[page - 0x8c], 0x80) + else if (VALUE_BETWEEN(page, 0x7f, 0x84)) E_Notify(pstrUsagePageMonitor, 0x80); - else if (page > 0x83 && page < 0x8c) + else if (VALUE_BETWEEN(page, 0x83, 0x8c)) E_Notify(pstrUsagePagePower, 0x80); - else if (page > 0x8b && page < 0x92) - //E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c]), 0x80); - output_pgm_message(w, E_Notify, usagePageTitles1[page - 0x8c], 0x80); - else if (page > 0xfeff && page <= 0xffff) + else if (page > 0xfeff /* && page <= 0xffff */) E_Notify(pstrUsagePageVendorDefined, 0x80); else switch (page) { @@ -1287,247 +1288,136 @@ void ReportDescParserBase::PrintGenericDesktopPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x0a) - //E_Notify((char*)pgm_read_pointer(&genDesktopTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, genDesktopTitles0[usage - 1], 0x80); - else if (usage > 0x2f && usage < 0x49) - //E_Notify((char*)pgm_read_pointer(&genDesktopTitles1[usage - 0x30]), 0x80); - output_pgm_message(w, E_Notify, genDesktopTitles1[usage - 0x30], 0x80); - else if (usage > 0x7f && usage < 0x94) - //E_Notify((char*)pgm_read_pointer(&genDesktopTitles2[usage - 0x80]), 0x80); - output_pgm_message(w, E_Notify, genDesktopTitles2[usage - 0x80], 0x80); - else if (usage > 0x9f && usage < 0xa9) - //E_Notify((char*)pgm_read_pointer(&genDesktopTitles3[usage - 0xa0]), 0x80); - output_pgm_message(w, E_Notify, genDesktopTitles3[usage - 0xa0], 0x80); - else if (usage > 0xaf && usage < 0xb8) - //E_Notify((char*)pgm_read_pointer(&genDesktopTitles4[usage - 0xb0]), 0x80); - output_pgm_message(w, E_Notify, genDesktopTitles4[usage - 0xb0], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x0a, w, E_Notify, genDesktopTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x2f, 0x49, w, E_Notify, genDesktopTitles1[usage - 0x30], 0x80) + else output_if_between(usage, 0x7f, 0x94, w, E_Notify, genDesktopTitles2[usage - 0x80], 0x80) + else output_if_between(usage, 0x9f, 0xa9, w, E_Notify, genDesktopTitles3[usage - 0xa0], 0x80) + else output_if_between(usage, 0xaf, 0xb8, w, E_Notify, genDesktopTitles4[usage - 0xb0], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintSimulationControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x0d) - //E_Notify((char*)pgm_read_pointer(&simuTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, simuTitles0[usage - 1], 0x80); - else if (usage > 0x1f && usage < 0x26) - //E_Notify((char*)pgm_read_pointer(&simuTitles1[usage - 0x20]), 0x80); - output_pgm_message(w, E_Notify, simuTitles1[usage - 0x20], 0x80); - else if (usage > 0xaf && usage < 0xd1) - //E_Notify((char*)pgm_read_pointer(&simuTitles2[usage - 0xb0]), 0x80); - output_pgm_message(w, E_Notify, simuTitles2[usage - 0xb0], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x0d, w, E_Notify, simuTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x1f, 0x26, w, E_Notify, simuTitles1[usage - 0x20], 0x80) + else output_if_between(usage, 0xaf, 0xd1, w, E_Notify, simuTitles2[usage - 0xb0], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintVRControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x0b) - //E_Notify((char*)pgm_read_pointer(&vrTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, vrTitles0[usage - 1], 0x80); - else if (usage > 0x1f && usage < 0x22) - //E_Notify((char*)pgm_read_pointer(&vrTitles1[usage - 0x20]), 0x80); - output_pgm_message(w, E_Notify, vrTitles1[usage - 0x20], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x0b, w, E_Notify, vrTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x1f, 0x22, w, E_Notify, vrTitles1[usage - 0x20], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintSportsControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x05) - //E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, sportsCtrlTitles0[usage - 1], 0x80); - else if (usage > 0x2f && usage < 0x3a) - //E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles1[usage - 0x30]), 0x80); - output_pgm_message(w, E_Notify, sportsCtrlTitles1[usage - 0x30], 0x80); - else if (usage > 0x4f && usage < 0x64) - //E_Notify((char*)pgm_read_pointer(&sportsCtrlTitles2[usage - 0x50]), 0x80); - output_pgm_message(w, E_Notify, sportsCtrlTitles2[usage - 0x50], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x05, w, E_Notify, sportsCtrlTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x2f, 0x3a, w, E_Notify, sportsCtrlTitles1[usage - 0x30], 0x80) + else output_if_between(usage, 0x4f, 0x64, w, E_Notify, sportsCtrlTitles2[usage - 0x50], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintGameControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x04) - //E_Notify((char*)pgm_read_pointer(&gameTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, gameTitles0[usage - 1], 0x80); - else if (usage > 0x1f && usage < 0x3a) - //E_Notify((char*)pgm_read_pointer(&gameTitles1[usage - 0x20]), 0x80); - output_pgm_message(w, E_Notify, gameTitles1[usage - 0x20], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x04, w, E_Notify, gameTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x1f, 0x3a, w, E_Notify, gameTitles1[usage - 0x20], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintGenericDeviceControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x1f && usage < 0x27) - //E_Notify((char*)pgm_read_pointer(&genDevCtrlTitles[usage - 0x20]), 0x80); - output_pgm_message(w, E_Notify, genDevCtrlTitles[usage - 0x20], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x1f, 0x27, w, E_Notify, genDevCtrlTitles[usage - 0x20], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintLEDPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x4e) - //E_Notify((char*)pgm_read_pointer(&ledTitles[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, ledTitles[usage - 1], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x4e, w, E_Notify, ledTitles[usage - 1], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintTelephonyPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x08) - //E_Notify((char*)pgm_read_pointer(&telTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, telTitles0[usage - 1], 0x80); - else if (usage > 0x1f && usage < 0x32) - //E_Notify((char*)pgm_read_pointer(&telTitles1[usage - 0x1f]), 0x80); - output_pgm_message(w, E_Notify, telTitles1[usage - 0x1f], 0x80); - else if (usage > 0x4f && usage < 0x54) - //E_Notify((char*)pgm_read_pointer(&telTitles2[usage - 0x4f]), 0x80); - output_pgm_message(w, E_Notify, telTitles2[usage - 0x4f], 0x80); - else if (usage > 0x6f && usage < 0x75) - //E_Notify((char*)pgm_read_pointer(&telTitles3[usage - 0x6f]), 0x80); - output_pgm_message(w, E_Notify, telTitles3[usage - 0x6f], 0x80); - else if (usage > 0x8f && usage < 0x9f) - //E_Notify((char*)pgm_read_pointer(&telTitles4[usage - 0x8f]), 0x80); - output_pgm_message(w, E_Notify, telTitles4[usage - 0x8f], 0x80); - else if (usage > 0xaf && usage < 0xc0) - //E_Notify((char*)pgm_read_pointer(&telTitles5[usage - 0xaf]), 0x80); - output_pgm_message(w, E_Notify, telTitles5[usage - 0xaf], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x08, w, E_Notify, telTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x1f, 0x32, w, E_Notify, telTitles1[usage - 0x1f], 0x80) + else output_if_between(usage, 0x4f, 0x54, w, E_Notify, telTitles2[usage - 0x4f], 0x80) + else output_if_between(usage, 0x6f, 0x75, w, E_Notify, telTitles3[usage - 0x6f], 0x80) + else output_if_between(usage, 0x8f, 0x9f, w, E_Notify, telTitles4[usage - 0x8f], 0x80) + else output_if_between(usage, 0xaf, 0xc0, w, E_Notify, telTitles5[usage - 0xaf], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintConsumerPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x07) - //E_Notify((char*)pgm_read_pointer(&consTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, consTitles0[usage - 1], 0x80); - else if (usage > 0x1f && usage < 0x23) - //E_Notify((char*)pgm_read_pointer(&consTitles1[usage - 0x1f]), 0x80); - output_pgm_message(w, E_Notify, consTitles1[usage - 0x1f], 0x80); - else if (usage > 0x2f && usage < 0x37) - //E_Notify((char*)pgm_read_pointer(&consTitles2[usage - 0x2f]), 0x80); - output_pgm_message(w, E_Notify, consTitles2[usage - 0x2f], 0x80); - else if (usage > 0x3f && usage < 0x49) - //E_Notify((char*)pgm_read_pointer(&consTitles3[usage - 0x3f]), 0x80); - output_pgm_message(w, E_Notify, consTitles3[usage - 0x3f], 0x80); - else if (usage > 0x5f && usage < 0x67) - //E_Notify((char*)pgm_read_pointer(&consTitles4[usage - 0x5f]), 0x80); - output_pgm_message(w, E_Notify, consTitles4[usage - 0x5f], 0x80); - else if (usage > 0x7f && usage < 0xa5) - //E_Notify((char*)pgm_read_pointer(&consTitles5[usage - 0x7f]), 0x80); - output_pgm_message(w, E_Notify, consTitles5[usage - 0x7f], 0x80); - else if (usage > 0xaf && usage < 0xcf) - //E_Notify((char*)pgm_read_pointer(&consTitles6[usage - 0xaf]), 0x80); - output_pgm_message(w, E_Notify, consTitles6[usage - 0xaf], 0x80); - else if (usage > 0xdf && usage < 0xeb) - //E_Notify((char*)pgm_read_pointer(&consTitles7[usage - 0xdf]), 0x80); - output_pgm_message(w, E_Notify, consTitles7[usage - 0xdf], 0x80); - else if (usage > 0xef && usage < 0xf6) - //E_Notify((char*)pgm_read_pointer(&consTitles8[usage - 0xef]), 0x80); - output_pgm_message(w, E_Notify, consTitles8[usage - 0xef], 0x80); - else if (usage > 0xff && usage < 0x10e) - //E_Notify((char*)pgm_read_pointer(&consTitles9[usage - 0xff]), 0x80); - output_pgm_message(w, E_Notify, consTitles9[usage - 0xff], 0x80); - else if (usage > 0x14f && usage < 0x156) - //E_Notify((char*)pgm_read_pointer(&consTitlesA[usage - 0x14f]), 0x80); - output_pgm_message(w, E_Notify, consTitlesA[usage - 0x14f], 0x80); - else if (usage > 0x15f && usage < 0x16b) - //E_Notify((char*)pgm_read_pointer(&consTitlesB[usage - 0x15f]), 0x80); - output_pgm_message(w, E_Notify, consTitlesB[usage - 0x15f], 0x80); - else if (usage > 0x16f && usage < 0x175) - //E_Notify((char*)pgm_read_pointer(&consTitlesC[usage - 0x16f]), 0x80); - output_pgm_message(w, E_Notify, consTitlesC[usage - 0x16f], 0x80); - else if (usage > 0x17f && usage < 0x1c8) - //E_Notify((char*)pgm_read_pointer(&consTitlesD[usage - 0x17f]), 0x80); - output_pgm_message(w, E_Notify, consTitlesD[usage - 0x17f], 0x80); - else if (usage > 0x1ff && usage < 0x29d) - //E_Notify((char*)pgm_read_pointer(&consTitlesE[usage - 0x1ff]), 0x80); - output_pgm_message(w, E_Notify, consTitlesE[usage - 0x1ff], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x07, w, E_Notify, consTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x1f, 0x23, w, E_Notify, consTitles1[usage - 0x1f], 0x80) + else output_if_between(usage, 0x2f, 0x37, w, E_Notify, consTitles2[usage - 0x2f], 0x80) + else output_if_between(usage, 0x3f, 0x49, w, E_Notify, consTitles3[usage - 0x3f], 0x80) + else output_if_between(usage, 0x5f, 0x67, w, E_Notify, consTitles4[usage - 0x5f], 0x80) + else output_if_between(usage, 0x7f, 0xa5, w, E_Notify, consTitles5[usage - 0x7f], 0x80) + else output_if_between(usage, 0xaf, 0xcf, w, E_Notify, consTitles6[usage - 0xaf], 0x80) + else output_if_between(usage, 0xdf, 0xeb, w, E_Notify, consTitles7[usage - 0xdf], 0x80) + else output_if_between(usage, 0xef, 0xf6, w, E_Notify, consTitles8[usage - 0xef], 0x80) + else output_if_between(usage, 0xff, 0x10e, w, E_Notify, consTitles9[usage - 0xff], 0x80) + else output_if_between(usage, 0x14f, 0x156, w, E_Notify, consTitlesA[usage - 0x14f], 0x80) + else output_if_between(usage, 0x15f, 0x16b, w, E_Notify, consTitlesB[usage - 0x15f], 0x80) + else output_if_between(usage, 0x16f, 0x175, w, E_Notify, consTitlesC[usage - 0x16f], 0x80) + else output_if_between(usage, 0x17f, 0x1c8, w, E_Notify, consTitlesD[usage - 0x17f], 0x80) + else output_if_between(usage, 0x1ff, 0x29d, w, E_Notify, consTitlesE[usage - 0x1ff], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintDigitizerPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x0e) - //E_Notify((char*)pgm_read_pointer(&digitTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, digitTitles0[usage - 1], 0x80); - else if (usage > 0x1f && usage < 0x23) - //E_Notify((char*)pgm_read_pointer(&digitTitles1[usage - 0x1f]), 0x80); - output_pgm_message(w, E_Notify, digitTitles1[usage - 0x1f], 0x80); - else if (usage > 0x2f && usage < 0x47) - //E_Notify((char*)pgm_read_pointer(&digitTitles2[usage - 0x2f]), 0x80); - output_pgm_message(w, E_Notify, digitTitles2[usage - 0x2f], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x0e, w, E_Notify, digitTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x1f, 0x23, w, E_Notify, digitTitles1[usage - 0x1f], 0x80) + else output_if_between(usage, 0x2f, 0x47, w, E_Notify, digitTitles2[usage - 0x2f], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintAlphanumDisplayPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage > 0x00 && usage < 0x03) - //E_Notify((char*)pgm_read_pointer(&aplphanumTitles0[usage - 1]), 0x80); - output_pgm_message(w, E_Notify, aplphanumTitles0[usage - 1], 0x80); - else if (usage > 0x1f && usage < 0x4e) - //E_Notify((char*)pgm_read_pointer(&aplphanumTitles1[usage - 0x1f]), 0x80); - output_pgm_message(w, E_Notify, aplphanumTitles1[usage - 0x1f], 0x80); - else if (usage > 0x7f && usage < 0x96) - //E_Notify((char*)pgm_read_pointer(&digitTitles2[usage - 0x80]), 0x80); - output_pgm_message(w, E_Notify, digitTitles2[usage - 0x80], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + output_if_between(usage, 0x00, 0x03, w, E_Notify, aplphanumTitles0[usage - 1], 0x80) + else output_if_between(usage, 0x1f, 0x4e, w, E_Notify, aplphanumTitles1[usage - 0x1f], 0x80) + else output_if_between(usage, 0x7f, 0x96, w, E_Notify, digitTitles2[usage - 0x80], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - //output_pgm_message(w, E_Notify, , 0x80); - if (usage == 1) - E_Notify(pstrUsageMedicalUltrasound, 0x80); - else if (usage > 0x1f && usage < 0x28) - //E_Notify((char*)pgm_read_pointer(&medInstrTitles0[usage - 0x1f]), 0x80); - output_pgm_message(w, E_Notify, medInstrTitles0[usage - 0x1f], 0x80); - else if (usage > 0x3f && usage < 0x45) - //E_Notify((char*)pgm_read_pointer(&medInstrTitles1[usage - 0x40]), 0x80); - output_pgm_message(w, E_Notify, medInstrTitles1[usage - 0x40], 0x80); - else if (usage > 0x5f && usage < 0x62) - //E_Notify((char*)pgm_read_pointer(&medInstrTitles2[usage - 0x60]), 0x80); - output_pgm_message(w, E_Notify, medInstrTitles2[usage - 0x60], 0x80); + + if (usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80); else if (usage == 0x70) E_Notify(pstrUsageDepthGainCompensation, 0x80); - else if (usage > 0x7f && usage < 0x8a) - //E_Notify((char*)pgm_read_pointer(&medInstrTitles3[usage - 0x80]), 0x80); - output_pgm_message(w, E_Notify, medInstrTitles3[usage - 0x80], 0x80); - else if (usage > 0x9f && usage < 0xa2) - // E_Notify((char*)pgm_read_pointer(&medInstrTitles4[usage - 0xa0]), 0x80); - output_pgm_message(w, E_Notify, medInstrTitles4[usage - 0xa0], 0x80); - else - E_Notify(pstrUsagePageUndefined, 0x80); + else output_if_between(usage, 0x1f, 0x28, w, E_Notify, medInstrTitles0[usage - 0x1f], 0x80) + else output_if_between(usage, 0x3f, 0x45, w, E_Notify, medInstrTitles1[usage - 0x40], 0x80) + else output_if_between(usage, 0x5f, 0x62, w, E_Notify, medInstrTitles2[usage - 0x60], 0x80) + else output_if_between(usage, 0x7f, 0x8a, w, E_Notify, medInstrTitles3[usage - 0x80], 0x80) + else output_if_between(usage, 0x9f, 0xa2, w, E_Notify, medInstrTitles4[usage - 0xa0], 0x80) + else E_Notify(pstrUsagePageUndefined, 0x80); } uint8_t ReportDescParser2::ParseItem(uint8_t **pp, uint16_t *pcntdn) { diff --git a/macros.h b/macros.h index 8877f48e..45a6ea86 100644 --- a/macros.h +++ b/macros.h @@ -14,6 +14,11 @@ // HANDY MACROS //////////////////////////////////////////////////////////////////////////////// +#define VALUE_BETWEEN(v,l,h) (((v)>(l)) && ((v)<(h))) +#define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) +#define output_pgm_message(wa,fp,mp,el) wa = &mp, fp((char *)pgm_read_pointer(wa), el) +#define output_if_between(v,l,h,wa,fp,mp,el) if(VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp,el); + #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) #ifndef __BYTE_GRABBING_DEFINED__ #define __BYTE_GRABBING_DEFINED__ 1 From edf9682923685da489fcc3af10579de2c0d6f59c Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 4 Dec 2013 21:56:06 -0500 Subject: [PATCH 004/145] Support spi4teensy3 in all examples automatically --- examples/Bluetooth/PS3BT/PS3BT.ino | 4 ++ examples/Bluetooth/PS3Multi/PS3Multi.ino | 4 ++ examples/Bluetooth/PS3SPP/PS3SPP.ino | 4 ++ examples/Bluetooth/SPP/SPP.ino | 4 ++ examples/Bluetooth/SPPMulti/SPPMulti.ino | 4 ++ examples/Bluetooth/Wii/Wii.ino | 4 ++ .../Bluetooth/WiiIRCamera/WiiIRCamera.ino | 4 ++ examples/Bluetooth/WiiMulti/WiiMulti.ino | 4 ++ .../WiiUProController/WiiUProController.ino | 4 ++ examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino | 4 ++ .../HID/USBHIDBootMouse/USBHIDBootMouse.ino | 14 ++-- examples/HID/USBHID_desc/USBHID_desc.ino | 5 +- examples/HID/le3dp/le3dp.ino | 8 ++- examples/HID/scale/scale.ino | 14 ++-- examples/PS3USB/PS3USB.ino | 4 ++ examples/USB_desc/USB_desc.ino | 68 ++++++++++--------- examples/Xbox/XBOXOLD/XBOXOLD.ino | 4 ++ examples/Xbox/XBOXRECV/XBOXRECV.ino | 4 ++ examples/Xbox/XBOXUSB/XBOXUSB.ino | 4 ++ examples/acm/acm_terminal/acm_terminal.ino | 37 +++++----- examples/board_qc/board_qc.ino | 4 ++ .../ftdi/USBFTDILoopback/USBFTDILoopback.ino | 42 ++++++------ examples/hub_demo/hub_demo.ino | 68 ++++++++++--------- .../pl2303_gprs_terminal.ino | 36 +++++----- examples/pl2303/pl2303_gps/pl2303_gps.ino | 36 +++++----- .../pl2303/pl2303_tinygps/pl2303_tinygps.ino | 50 +++++++------- .../pl2303_xbee_terminal.ino | 40 ++++++----- 27 files changed, 292 insertions(+), 186 deletions(-) diff --git a/examples/Bluetooth/PS3BT/PS3BT.ino b/examples/Bluetooth/PS3BT/PS3BT.ino index f8b13ad7..87cc9939 100644 --- a/examples/Bluetooth/PS3BT/PS3BT.ino +++ b/examples/Bluetooth/PS3BT/PS3BT.ino @@ -6,6 +6,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/Bluetooth/PS3Multi/PS3Multi.ino b/examples/Bluetooth/PS3Multi/PS3Multi.ino index d7ec631c..dece1c98 100644 --- a/examples/Bluetooth/PS3Multi/PS3Multi.ino +++ b/examples/Bluetooth/PS3Multi/PS3Multi.ino @@ -7,6 +7,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/Bluetooth/PS3SPP/PS3SPP.ino b/examples/Bluetooth/PS3SPP/PS3SPP.ino index 214ce26a..5c0a0d5a 100644 --- a/examples/Bluetooth/PS3SPP/PS3SPP.ino +++ b/examples/Bluetooth/PS3SPP/PS3SPP.ino @@ -12,6 +12,10 @@ #include #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/Bluetooth/SPP/SPP.ino b/examples/Bluetooth/SPP/SPP.ino index e5b92089..6a326a3d 100644 --- a/examples/Bluetooth/SPP/SPP.ino +++ b/examples/Bluetooth/SPP/SPP.ino @@ -6,6 +6,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/Bluetooth/SPPMulti/SPPMulti.ino b/examples/Bluetooth/SPPMulti/SPPMulti.ino index af32fd85..23bb6ed6 100644 --- a/examples/Bluetooth/SPPMulti/SPPMulti.ino +++ b/examples/Bluetooth/SPPMulti/SPPMulti.ino @@ -6,6 +6,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/Bluetooth/Wii/Wii.ino b/examples/Bluetooth/Wii/Wii.ino index 214625c5..f4d68a62 100644 --- a/examples/Bluetooth/Wii/Wii.ino +++ b/examples/Bluetooth/Wii/Wii.ino @@ -6,6 +6,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino b/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino index 5d0fa91b..5e49fad1 100644 --- a/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino +++ b/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino @@ -13,6 +13,10 @@ Otherwise, wire up a IR LED yourself. #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif #ifndef WIICAMERA // Used to check if WIICAMERA is defined #error "Uncomment WIICAMERA in Wii.h to use this example" diff --git a/examples/Bluetooth/WiiMulti/WiiMulti.ino b/examples/Bluetooth/WiiMulti/WiiMulti.ino index 51c9160b..d99da9a4 100644 --- a/examples/Bluetooth/WiiMulti/WiiMulti.ino +++ b/examples/Bluetooth/WiiMulti/WiiMulti.ino @@ -7,6 +7,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/Bluetooth/WiiUProController/WiiUProController.ino b/examples/Bluetooth/WiiUProController/WiiUProController.ino index eb686879..59c4f1dc 100644 --- a/examples/Bluetooth/WiiUProController/WiiUProController.ino +++ b/examples/Bluetooth/WiiUProController/WiiUProController.ino @@ -6,6 +6,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside diff --git a/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino b/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino index b3adb558..b5944f0a 100644 --- a/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino +++ b/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino @@ -1,5 +1,9 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif class KbdRptParser : public KeyboardReportParser { diff --git a/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino b/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino index 80dbcd4d..aa2e3b34 100644 --- a/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino +++ b/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino @@ -1,5 +1,9 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif class MouseRptParser : public MouseReportParser { @@ -12,14 +16,14 @@ protected: virtual void OnMiddleButtonUp (MOUSEINFO *mi); virtual void OnMiddleButtonDown (MOUSEINFO *mi); }; -void MouseRptParser::OnMouseMove(MOUSEINFO *mi) +void MouseRptParser::OnMouseMove(MOUSEINFO *mi) { Serial.print("dx="); Serial.print(mi->dX, DEC); Serial.print(" dy="); Serial.println(mi->dY, DEC); }; -void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi) +void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi) { Serial.println("L Butt Up"); }; @@ -60,11 +64,11 @@ void setup() if (Usb.Init() == -1) Serial.println("OSC did not start."); - + delay( 200 ); - + next_time = millis() + 5000; - + HidMouse.SetReportParser(0,(HIDReportParser*)&Prs); } diff --git a/examples/HID/USBHID_desc/USBHID_desc.ino b/examples/HID/USBHID_desc/USBHID_desc.ino index 63ae76c7..d3558a8e 100644 --- a/examples/HID/USBHID_desc/USBHID_desc.ino +++ b/examples/HID/USBHID_desc/USBHID_desc.ino @@ -2,10 +2,11 @@ #include #include #include -#ifdef arm +#include "pgmstrings.h" +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude #include #endif -#include "pgmstrings.h" class HIDUniversal2 : public HIDUniversal { diff --git a/examples/HID/le3dp/le3dp.ino b/examples/HID/le3dp/le3dp.ino index 3728b307..fbf07b2f 100644 --- a/examples/HID/le3dp/le3dp.ino +++ b/examples/HID/le3dp/le3dp.ino @@ -5,6 +5,10 @@ #include #include "le3dp_rptparser.h" +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; USBHub Hub(&Usb); @@ -20,11 +24,11 @@ void setup() if (Usb.Init() == -1) Serial.println("OSC did not start."); - + delay( 200 ); if (!Hid.SetReportParser(0, &Joy)) - ErrorMessage(PSTR("SetReportParser"), 1 ); + ErrorMessage(PSTR("SetReportParser"), 1 ); } void loop() diff --git a/examples/HID/scale/scale.ino b/examples/HID/scale/scale.ino index 2f48c4c0..c790cb1c 100644 --- a/examples/HID/scale/scale.ino +++ b/examples/HID/scale/scale.ino @@ -6,6 +6,10 @@ #include #include "scale_rptparser.h" +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; USBHub Hub(&Usb); @@ -22,18 +26,18 @@ void setup() if (Usb.Init() == -1) Serial.println("OSC did not start."); - - // set up the LCD's number of rows and columns: + + // set up the LCD's number of rows and columns: LCD.begin(16, 2); LCD.clear(); LCD.home(); LCD.setCursor(0,0); - LCD.write('R'); - + LCD.write('R'); + delay( 200 ); if (!Hid.SetReportParser(0, &Scale)) - ErrorMessage(PSTR("SetReportParser"), 1 ); + ErrorMessage(PSTR("SetReportParser"), 1 ); } void loop() diff --git a/examples/PS3USB/PS3USB.ino b/examples/PS3USB/PS3USB.ino index b3e6e2c4..e05f55b5 100644 --- a/examples/PS3USB/PS3USB.ino +++ b/examples/PS3USB/PS3USB.ino @@ -5,6 +5,10 @@ */ #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; /* You can create the instance of the class in two ways */ diff --git a/examples/USB_desc/USB_desc.ino b/examples/USB_desc/USB_desc.ino index 7f4a363a..71e2fdc3 100644 --- a/examples/USB_desc/USB_desc.ino +++ b/examples/USB_desc/USB_desc.ino @@ -1,6 +1,10 @@ #include #include "pgmstrings.h" +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); @@ -50,9 +54,9 @@ void setup() if (Usb.Init() == -1) Serial.println("OSC did not start."); - + delay( 200 ); - + next_time = millis() + 10000; } @@ -62,19 +66,19 @@ void PrintDescriptors(uint8_t addr) { uint8_t rcode = 0; byte num_conf = 0; - + rcode = getdevdescr( (byte)addr, num_conf ); - if( rcode ) + if( rcode ) { printProgStr(Gen_Error_str); print_hex( rcode, 8 ); } Serial.print("\r\n"); - + for (int i=0; i= next_time) { - Usb.ForEachUsbDevice(&PrintAllDescriptors); + Usb.ForEachUsbDevice(&PrintAllDescriptors); Usb.ForEachUsbDevice(&PrintAllAddresses); - + while( 1 ); //stop } - } + } } - + byte getdevdescr( byte addr, byte &num_conf ) { USB_DEVICE_DESCRIPTOR buf; @@ -122,7 +126,7 @@ byte getdevdescr( byte addr, byte &num_conf ) print_hex( buf.bDescriptorType, 8 ); printProgStr(Dev_Version_str); print_hex( buf.bcdUSB, 16 ); - printProgStr(Dev_Class_str); + printProgStr(Dev_Class_str); print_hex( buf.bDeviceClass, 8 ); printProgStr(Dev_Subclass_str); print_hex( buf.bDeviceSubClass, 8 ); @@ -147,46 +151,46 @@ byte getdevdescr( byte addr, byte &num_conf ) num_conf = buf.bNumConfigurations; return( 0 ); } - + void printhubdescr(uint8_t *descrptr, uint8_t addr) { HubDescriptor *pHub = (HubDescriptor*) descrptr; uint8_t len = *((uint8_t*)descrptr); - + printProgStr(PSTR("\r\n\r\nHub Descriptor:\r\n")); printProgStr(PSTR("bDescLength:\t\t")); Serial.println(pHub->bDescLength, HEX); - + printProgStr(PSTR("bDescriptorType:\t")); Serial.println(pHub->bDescriptorType, HEX); - + printProgStr(PSTR("bNbrPorts:\t\t")); Serial.println(pHub->bNbrPorts, HEX); - + printProgStr(PSTR("LogPwrSwitchMode:\t")); Serial.println(pHub->LogPwrSwitchMode, BIN); - + printProgStr(PSTR("CompoundDevice:\t\t")); Serial.println(pHub->CompoundDevice, BIN); - + printProgStr(PSTR("OverCurrentProtectMode:\t")); Serial.println(pHub->OverCurrentProtectMode, BIN); - + printProgStr(PSTR("TTThinkTime:\t\t")); Serial.println(pHub->TTThinkTime, BIN); - + printProgStr(PSTR("PortIndicatorsSupported:")); Serial.println(pHub->PortIndicatorsSupported, BIN); - + printProgStr(PSTR("Reserved:\t\t")); Serial.println(pHub->Reserved, HEX); printProgStr(PSTR("bPwrOn2PwrGood:\t\t")); Serial.println(pHub->bPwrOn2PwrGood, HEX); - + printProgStr(PSTR("bHubContrCurrent:\t")); Serial.println(pHub->bHubContrCurrent, HEX); - + for (uint8_t i=7; i> (num_nibbles-1) * 4)) & 0x0f; Serial.print(digit, HEX); - } + } while(--num_nibbles); } /* function to print configuration descriptor */ @@ -309,7 +313,7 @@ void printepdescr( uint8_t* descr_ptr ) print_hex( ep_ptr->wMaxPacketSize, 16 ); printProgStr(End_Interval_str); print_hex( ep_ptr->bInterval, 8 ); - + return; } /*function to print unknown descriptor */ @@ -329,8 +333,8 @@ void printunkdescr( uint8_t* descr_ptr ) descr_ptr++; } } - - + + /* Print a string from Program Memory directly to save RAM */ void printProgStr(const prog_char str[]) { diff --git a/examples/Xbox/XBOXOLD/XBOXOLD.ino b/examples/Xbox/XBOXOLD/XBOXOLD.ino index 1bdfc9f9..968c8df7 100644 --- a/examples/Xbox/XBOXOLD/XBOXOLD.ino +++ b/examples/Xbox/XBOXOLD/XBOXOLD.ino @@ -6,6 +6,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; USBHub Hub1(&Usb); // The controller has a built in hub, so this instance is needed diff --git a/examples/Xbox/XBOXRECV/XBOXRECV.ino b/examples/Xbox/XBOXRECV/XBOXRECV.ino index 5896b9dc..1f43b912 100644 --- a/examples/Xbox/XBOXRECV/XBOXRECV.ino +++ b/examples/Xbox/XBOXRECV/XBOXRECV.ino @@ -6,6 +6,10 @@ */ #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; XBOXRECV Xbox(&Usb); diff --git a/examples/Xbox/XBOXUSB/XBOXUSB.ino b/examples/Xbox/XBOXUSB/XBOXUSB.ino index b7d5a625..89161d24 100644 --- a/examples/Xbox/XBOXUSB/XBOXUSB.ino +++ b/examples/Xbox/XBOXUSB/XBOXUSB.ino @@ -5,6 +5,10 @@ */ #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; XBOXUSB Xbox(&Usb); diff --git a/examples/acm/acm_terminal/acm_terminal.ino b/examples/acm/acm_terminal/acm_terminal.ino index 8fc8edea..5e4d152c 100644 --- a/examples/acm/acm_terminal/acm_terminal.ino +++ b/examples/acm/acm_terminal/acm_terminal.ino @@ -1,7 +1,12 @@ #include #include -#include "pgmstrings.h" +#include "pgmstrings.h" + +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif class ACMAsyncOper : public CDCAsyncOper { @@ -22,16 +27,16 @@ uint8_t ACMAsyncOper::OnInit(ACM *pacm) } LINE_CODING lc; - lc.dwDTERate = 115200; + lc.dwDTERate = 115200; lc.bCharFormat = 0; lc.bParityType = 0; - lc.bDataBits = 8; - + lc.bDataBits = 8; + rcode = pacm->SetLineCoding(&lc); if (rcode) ErrorMessage(PSTR("SetLineCoding"), rcode); - + return rcode; } @@ -48,17 +53,17 @@ void setup() if (Usb.Init() == -1) Serial.println("OSCOKIRQ failed to assert"); - - delay( 200 ); + + delay( 200 ); } void loop() { Usb.Task(); - - if( Acm.isReady()) { + + if( Acm.isReady()) { uint8_t rcode; - + /* reading the keyboard */ if(Serial.available()) { uint8_t data= Serial.read(); @@ -69,24 +74,24 @@ void loop() }//if(Serial.available()... delay(50); - + /* reading the phone */ /* buffer size must be greater or equal to max.packet size */ /* it it set to 64 (largest possible max.packet size) here, can be tuned down for particular endpoint */ - uint8_t buf[64]; + uint8_t buf[64]; uint16_t rcvd = 64; rcode = Acm.RcvData(&rcvd, buf); if (rcode && rcode != hrNAK) ErrorMessage(PSTR("Ret"), rcode); - + if( rcvd ) { //more than zero bytes received for(uint16_t i=0; i < rcvd; i++ ) { Serial.print((char)buf[i]); //printing on the screen - } + } } - delay(10); - }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. + delay(10); + }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. } diff --git a/examples/board_qc/board_qc.ino b/examples/board_qc/board_qc.ino index a2ca05c6..94df16cf 100644 --- a/examples/board_qc/board_qc.ino +++ b/examples/board_qc/board_qc.ino @@ -4,6 +4,10 @@ /* otherwise press any key after getting GPIO error to complete the test */ /**/ #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif /* variables */ uint8_t rcode; diff --git a/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino b/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino index ad3d319e..26b5624d 100644 --- a/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino +++ b/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino @@ -1,7 +1,11 @@ #include #include -#include "pgmstrings.h" +#include "pgmstrings.h" +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif class FTDIAsync : public FTDIAsyncOper { @@ -12,7 +16,7 @@ public: uint8_t FTDIAsync::OnInit(FTDI *pftdi) { uint8_t rcode = 0; - + rcode = pftdi->SetBaudRate(115200); if (rcode) @@ -21,10 +25,10 @@ uint8_t FTDIAsync::OnInit(FTDI *pftdi) return rcode; } rcode = pftdi->SetFlowControl(FTDI_SIO_DISABLE_FLOW_CTRL); - + if (rcode) ErrorMessage(PSTR("SetFlowControl"), rcode); - + return rcode; } @@ -43,48 +47,48 @@ void setup() if (Usb.Init() == -1) Serial.println("OSC did not start."); - + delay( 200 ); - + next_time = millis() + 5000; } void loop() { Usb.Task(); - + if( Usb.getUsbTaskState() == USB_STATE_RUNNING ) - { + { uint8_t rcode; char strbuf[] = "DEADBEEF"; //char strbuf[] = "The quick brown fox jumps over the lazy dog"; //char strbuf[] = "This string contains 61 character to demonstrate FTDI buffers"; //add one symbol to it to see some garbage Serial.print("."); - + rcode = Ftdi.SndData(strlen(strbuf), (uint8_t*)strbuf); if (rcode) ErrorMessage(PSTR("SndData"), rcode); delay(50); - + uint8_t buf[64]; - + for (uint8_t i=0; i<64; i++) buf[i] = 0; - + uint16_t rcvd = 64; rcode = Ftdi.RcvData(&rcvd, buf); - + if (rcode && rcode != hrNAK) ErrorMessage(PSTR("Ret"), rcode); - + // The device reserves the first two bytes of data // to contain the current values of the modem and line status registers. - if (rcvd > 2) - Serial.print((char*)(buf+2)); - - delay(10); - } + if (rcvd > 2) + Serial.print((char*)(buf+2)); + + delay(10); + } } diff --git a/examples/hub_demo/hub_demo.ino b/examples/hub_demo/hub_demo.ino index 77c502fe..d80d9ea2 100644 --- a/examples/hub_demo/hub_demo.ino +++ b/examples/hub_demo/hub_demo.ino @@ -1,5 +1,9 @@ #include #include "pgmstrings.h" +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; USBHub Hub1(&Usb); @@ -46,9 +50,9 @@ void setup() if (Usb.Init() == -1) Serial.println("OSC did not start."); - + delay( 200 ); - + next_time = millis() + 10000; } @@ -58,19 +62,19 @@ void PrintDescriptors(uint8_t addr) { uint8_t rcode = 0; byte num_conf = 0; - + rcode = getdevdescr( (byte)addr, num_conf ); - if( rcode ) + if( rcode ) { printProgStr(Gen_Error_str); print_hex( rcode, 8 ); } Serial.print("\r\n"); - + for (int i=0; i= next_time) { - Usb.ForEachUsbDevice(&PrintAllDescriptors); + Usb.ForEachUsbDevice(&PrintAllDescriptors); Usb.ForEachUsbDevice(&PrintAllAddresses); - + while( 1 ); //stop } - } + } } - + byte getdevdescr( byte addr, byte &num_conf ) { USB_DEVICE_DESCRIPTOR buf; @@ -118,7 +122,7 @@ byte getdevdescr( byte addr, byte &num_conf ) print_hex( buf.bDescriptorType, 8 ); printProgStr(Dev_Version_str); print_hex( buf.bcdUSB, 16 ); - printProgStr(Dev_Class_str); + printProgStr(Dev_Class_str); print_hex( buf.bDeviceClass, 8 ); printProgStr(Dev_Subclass_str); print_hex( buf.bDeviceSubClass, 8 ); @@ -143,46 +147,46 @@ byte getdevdescr( byte addr, byte &num_conf ) num_conf = buf.bNumConfigurations; return( 0 ); } - + void printhubdescr(uint8_t *descrptr, uint8_t addr) { HubDescriptor *pHub = (HubDescriptor*) descrptr; uint8_t len = *((uint8_t*)descrptr); - + printProgStr(PSTR("\r\n\r\nHub Descriptor:\r\n")); printProgStr(PSTR("bDescLength:\t\t")); Serial.println(pHub->bDescLength, HEX); - + printProgStr(PSTR("bDescriptorType:\t")); Serial.println(pHub->bDescriptorType, HEX); - + printProgStr(PSTR("bNbrPorts:\t\t")); Serial.println(pHub->bNbrPorts, HEX); - + printProgStr(PSTR("LogPwrSwitchMode:\t")); Serial.println(pHub->LogPwrSwitchMode, BIN); - + printProgStr(PSTR("CompoundDevice:\t\t")); Serial.println(pHub->CompoundDevice, BIN); - + printProgStr(PSTR("OverCurrentProtectMode:\t")); Serial.println(pHub->OverCurrentProtectMode, BIN); - + printProgStr(PSTR("TTThinkTime:\t\t")); Serial.println(pHub->TTThinkTime, BIN); - + printProgStr(PSTR("PortIndicatorsSupported:")); Serial.println(pHub->PortIndicatorsSupported, BIN); - + printProgStr(PSTR("Reserved:\t\t")); Serial.println(pHub->Reserved, HEX); printProgStr(PSTR("bPwrOn2PwrGood:\t\t")); Serial.println(pHub->bPwrOn2PwrGood, HEX); - + printProgStr(PSTR("bHubContrCurrent:\t")); Serial.println(pHub->bHubContrCurrent, HEX); - + for (uint8_t i=7; i> (num_nibbles-1) * 4)) & 0x0f; Serial.print(digit, HEX); - } + } while(--num_nibbles); } /* function to print configuration descriptor */ @@ -305,7 +309,7 @@ void printepdescr( uint8_t* descr_ptr ) print_hex( ep_ptr->wMaxPacketSize, 16 ); printProgStr(End_Interval_str); print_hex( ep_ptr->bInterval, 8 ); - + return; } /*function to print unknown descriptor */ @@ -325,8 +329,8 @@ void printunkdescr( uint8_t* descr_ptr ) descr_ptr++; } } - - + + /* Print a string from Program Memory directly to save RAM */ void printProgStr(const prog_char str[]) { diff --git a/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino b/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino index fea00e52..4770809d 100644 --- a/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino +++ b/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino @@ -4,6 +4,10 @@ /* CDC support */ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif class PLAsyncOper : public CDCAsyncOper { @@ -14,7 +18,7 @@ public: uint8_t PLAsyncOper::OnInit(ACM *pacm) { uint8_t rcode; - + // Set DTR = 1 rcode = pacm->SetControlLineState(1); @@ -29,13 +33,13 @@ uint8_t PLAsyncOper::OnInit(ACM *pacm) lc.dwDTERate = 115200; lc.bCharFormat = 0; lc.bParityType = 0; - lc.bDataBits = 8; - + lc.bDataBits = 8; + rcode = pacm->SetLineCoding(&lc); if (rcode) ErrorMessage(PSTR("SetLineCoding"), rcode); - + return rcode; } USB Usb; @@ -51,43 +55,43 @@ void setup() if (Usb.Init() == -1) Serial.println("OSCOKIRQ failed to assert"); - - delay( 200 ); + + delay( 200 ); } void loop() { Usb.Task(); - + if( Usb.getUsbTaskState() == USB_STATE_RUNNING ) - { + { uint8_t rcode; - + /* reading the keyboard */ if(Serial.available()) { uint8_t data= Serial.read(); - + /* sending to the phone */ rcode = Pl.SndData(1, &data); if (rcode) ErrorMessage(PSTR("SndData"), rcode); }//if(Serial.available()... - + /* reading the converter */ /* buffer size must be greater or equal to max.packet size */ /* it it set to 64 (largest possible max.packet size) here, can be tuned down for particular endpoint */ - uint8_t buf[64]; + uint8_t buf[64]; uint16_t rcvd = 64; rcode = Pl.RcvData(&rcvd, buf); if (rcode && rcode != hrNAK) ErrorMessage(PSTR("Ret"), rcode); - + if( rcvd ) { //more than zero bytes received for(uint16_t i=0; i < rcvd; i++ ) { - Serial.print((char)buf[i]); //printing on the screen - } + Serial.print((char)buf[i]); //printing on the screen + } }//if( rcvd ... - }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. + }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. } diff --git a/examples/pl2303/pl2303_gps/pl2303_gps.ino b/examples/pl2303/pl2303_gps/pl2303_gps.ino index f756f408..9f33766a 100644 --- a/examples/pl2303/pl2303_gps/pl2303_gps.ino +++ b/examples/pl2303/pl2303_gps/pl2303_gps.ino @@ -5,6 +5,10 @@ /* CDC support */ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif class PLAsyncOper : public CDCAsyncOper { @@ -15,7 +19,7 @@ public: uint8_t PLAsyncOper::OnInit(ACM *pacm) { uint8_t rcode; - + // Set DTR = 1 rcode = pacm->SetControlLineState(1); @@ -26,16 +30,16 @@ uint8_t PLAsyncOper::OnInit(ACM *pacm) } LINE_CODING lc; - lc.dwDTERate = 4800; //default serial speed of GPS unit + lc.dwDTERate = 4800; //default serial speed of GPS unit lc.bCharFormat = 0; lc.bParityType = 0; - lc.bDataBits = 8; - + lc.bDataBits = 8; + rcode = pacm->SetLineCoding(&lc); if (rcode) ErrorMessage(PSTR("SetLineCoding"), rcode); - + return rcode; } @@ -54,32 +58,32 @@ void setup() if (Usb.Init() == -1) Serial.println("OSCOKIRQ failed to assert"); - - delay( 200 ); + + delay( 200 ); } void loop() { uint8_t rcode; -uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint -uint16_t rcvd = 64; +uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint +uint16_t rcvd = 64; Usb.Task(); - - if( Pl.isReady()) { + + if( Pl.isReady()) { /* reading the GPS */ if( read_delay < millis() ){ - read_delay += READ_DELAY; + read_delay += READ_DELAY; rcode = Pl.RcvData(&rcvd, buf); if ( rcode && rcode != hrNAK ) - ErrorMessage(PSTR("Ret"), rcode); + ErrorMessage(PSTR("Ret"), rcode); if( rcvd ) { //more than zero bytes received for( uint16_t i=0; i < rcvd; i++ ) { Serial.print((char)buf[i]); //printing on the screen - }//for( uint16_t i=0; i < rcvd; i++... + }//for( uint16_t i=0; i < rcvd; i++... }//if( rcvd - }//if( read_delay > millis()... - }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. + }//if( read_delay > millis()... + }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. } diff --git a/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino b/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino index 818df512..db25e42a 100644 --- a/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino +++ b/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino @@ -11,6 +11,10 @@ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif /* This sample code demonstrates the normal use of a TinyGPS object. Modified to be used with USB Host Shield Library r2.0 @@ -26,7 +30,7 @@ public: uint8_t PLAsyncOper::OnInit(ACM *pacm) { uint8_t rcode; - + // Set DTR = 1 rcode = pacm->SetControlLineState(1); @@ -36,17 +40,17 @@ uint8_t PLAsyncOper::OnInit(ACM *pacm) } LINE_CODING lc; - lc.dwDTERate = 4800; //default serial speed of GPS unit + lc.dwDTERate = 4800; //default serial speed of GPS unit lc.bCharFormat = 0; lc.bParityType = 0; - lc.bDataBits = 8; - + lc.bDataBits = 8; + rcode = pacm->SetLineCoding(&lc); if (rcode) { ErrorMessage(PSTR("SetLineCoding"), rcode); } - + return rcode; } @@ -65,7 +69,7 @@ void setup() Serial.begin(115200); while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection - + Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version()); Serial.println("by Mikal Hart"); Serial.println(); @@ -75,16 +79,16 @@ void setup() if (Usb.Init() == -1) { Serial.println("OSCOKIRQ failed to assert"); } - - delay( 200 ); + + delay( 200 ); } void loop() { Usb.Task(); - + if( Pl.isReady()) { - + bool newdata = false; unsigned long start = millis(); @@ -94,7 +98,7 @@ void loop() newdata = true; } }//while (millis()... - + if (newdata) { Serial.println("Acquired Data"); Serial.println("-------------"); @@ -118,7 +122,7 @@ void printFloat(double number, int digits) double rounding = 0.5; for (uint8_t i=0; i 0) - Serial.print("."); + Serial.print("."); // Extract digits from the remainder one at a time while (digits-- > 0) @@ -136,8 +140,8 @@ void printFloat(double number, int digits) remainder *= 10.0; int toPrint = int(remainder); Serial.print(toPrint); - remainder -= toPrint; - } + remainder -= toPrint; + } } void gpsdump(TinyGPS &gps) @@ -150,9 +154,9 @@ void gpsdump(TinyGPS &gps) unsigned short sentences, failed; gps.get_position(&lat, &lon, &age); - Serial.print("Lat/Long(10^-5 deg): "); Serial.print(lat); Serial.print(", "); Serial.print(lon); + Serial.print("Lat/Long(10^-5 deg): "); Serial.print(lat); Serial.print(", "); Serial.print(lon); Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms."); - + feedgps(); // If we don't feed the gps during this long routine, we may drop characters and get checksum errors gps.f_get_position(&flat, &flon, &age); @@ -171,7 +175,7 @@ void gpsdump(TinyGPS &gps) Serial.print("Date: "); Serial.print(static_cast(month)); Serial.print("/"); Serial.print(static_cast(day)); Serial.print("/"); Serial.print(year); Serial.print(" Time: "); Serial.print(static_cast(hour)); Serial.print(":"); Serial.print(static_cast(minute)); Serial.print(":"); Serial.print(static_cast(second)); Serial.print("."); Serial.print(static_cast(hundredths)); Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms."); - + feedgps(); Serial.print("Alt(cm): "); Serial.print(gps.altitude()); Serial.print(" Course(10^-2 deg): "); Serial.print(gps.course()); Serial.print(" Speed(10^-2 knots): "); Serial.println(gps.speed()); @@ -184,13 +188,13 @@ void gpsdump(TinyGPS &gps) gps.stats(&chars, &sentences, &failed); Serial.print("Stats: characters: "); Serial.print(chars); Serial.print(" sentences: "); Serial.print(sentences); Serial.print(" failed checksum: "); Serial.println(failed); } - + bool feedgps() { uint8_t rcode; - uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint - uint16_t rcvd = 64; - { + uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint + uint16_t rcvd = 64; + { /* reading the GPS */ rcode = Pl.RcvData(&rcvd, buf); if (rcode && rcode != hrNAK) @@ -201,7 +205,7 @@ bool feedgps() if( gps.encode((char)buf[i])) { //feed a character to gps object rcode = true; }//if( gps.encode(buf[i]... - }//for( uint16_t i=0; i < rcvd; i++... + }//for( uint16_t i=0; i < rcvd; i++... }//if( rcvd... } return( rcode ); diff --git a/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino b/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino index 60a3e15d..9e17d3cf 100644 --- a/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino +++ b/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino @@ -5,6 +5,10 @@ /* CDC support */ #include #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif class PLAsyncOper : public CDCAsyncOper { @@ -15,7 +19,7 @@ public: uint8_t PLAsyncOper::OnInit(ACM *pacm) { uint8_t rcode; - + // Set DTR = 1 rcode = pacm->SetControlLineState(1); @@ -26,16 +30,16 @@ uint8_t PLAsyncOper::OnInit(ACM *pacm) } LINE_CODING lc; - lc.dwDTERate = 115200; + lc.dwDTERate = 115200; lc.bCharFormat = 0; lc.bParityType = 0; - lc.bDataBits = 8; - + lc.bDataBits = 8; + rcode = pacm->SetLineCoding(&lc); if (rcode) ErrorMessage(PSTR("SetLineCoding"), rcode); - + return rcode; } USB Usb; @@ -51,29 +55,29 @@ void setup() if (Usb.Init() == -1) Serial.println("OSCOKIRQ failed to assert"); - - delay( 200 ); + + delay( 200 ); } void loop() { Usb.Task(); - + if( Usb.getUsbTaskState() == USB_STATE_RUNNING ) - { + { uint8_t rcode; - + /* reading the keyboard */ if(Serial.available()) { uint8_t data= Serial.read(); - + if ( data == '\r' ) { Serial.print("\r\n"); //insert linefeed } else { Serial.print( data ); //echo back to the screen } - + /* sending to the phone */ rcode = Pl.SndData(1, &data); if (rcode) @@ -81,17 +85,17 @@ void loop() }//if(Serial.available()... delay(50); - + /* reading the converter */ /* buffer size must be greater or equal to max.packet size */ /* it it set to 64 (largest possible max.packet size) here, can be tuned down for particular endpoint */ - uint8_t buf[64]; + uint8_t buf[64]; uint16_t rcvd = 64; rcode = Pl.RcvData(&rcvd, buf); if (rcode && rcode != hrNAK) ErrorMessage(PSTR("Ret"), rcode); - + if( rcvd ) { //more than zero bytes received for(uint16_t i=0; i < rcvd; i++ ) { if( buf[i] =='\r' ) { @@ -100,10 +104,10 @@ void loop() else { Serial.print((char)buf[i]); //printing on the screen } - } + } } - delay(10); - }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. + delay(10); + }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. } From 6d927d8cd3a8a7f6bd6ad199fd88e34e052b8c53 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 4 Dec 2013 22:41:13 -0500 Subject: [PATCH 005/145] Remove unused vasriable and setting --- XBOXRECV.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index 07963c52..662be5fb 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -106,7 +106,7 @@ uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { // Extract Max Packet Size from device descriptor epInfo[0].maxPktSize = udd->bMaxPacketSize0; - epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory + //epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory delay(20); // Wait a little before resetting device @@ -138,8 +138,8 @@ Fail: uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t rcode; - uint8_t num_of_conf = epInfo[1].epAddr; // Number of configurations - epInfo[1].epAddr = 0; + //uint8_t num_of_conf = epInfo[1].epAddr; // Number of configurations + //epInfo[1].epAddr = 0; AddressPool &addrPool = pUsb->GetAddressPool(); #ifdef EXTRADEBUG @@ -262,8 +262,8 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { return 0; // Successful configuration /* Diagnostic messages */ -FailGetDevDescr: #ifdef DEBUG_USB_HOST +FailGetDevDescr: NotifyFailGetDevDescr(); goto Fail; #endif @@ -279,8 +279,8 @@ FailSetConfDescr: NotifyFailSetConfDescr(); #endif -FailUnknownDevice: #ifdef DEBUG_USB_HOST +FailUnknownDevice: NotifyFailUnknownDevice(VID,PID); #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; From d168409b04f606e317588856e6acbd0b5476c4f4 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 5 Dec 2013 07:32:32 +0100 Subject: [PATCH 006/145] Included spi4teensy3.h in BTHID example This should really be fixed in the Arduino IDE --- examples/Bluetooth/BTHID/BTHID.ino | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/Bluetooth/BTHID/BTHID.ino b/examples/Bluetooth/BTHID/BTHID.ino index fecc4b50..a38411b5 100644 --- a/examples/Bluetooth/BTHID/BTHID.ino +++ b/examples/Bluetooth/BTHID/BTHID.ino @@ -8,6 +8,10 @@ #include #include "KeyboardParser.h" #include "MouseParser.h" +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside From b1006773547d0a87e7abbb54be3369a6f763d709 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 5 Dec 2013 07:39:28 +0100 Subject: [PATCH 007/145] Fixed bug - epMUL was already defined --- BTHID.cpp | 2 +- BTHID.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index 3e626b18..ab1617dc 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -24,7 +24,7 @@ BTHID::BTHID(BTD *p, bool pair, const char *pin) : pBtd(p), // pointer to USB class instance - mandatory protocolMode(HID_BOOT_PROTOCOL) { - for (uint8_t i = 0; i < epMUL; i++) + for (uint8_t i = 0; i < NUM_PARSERS; i++) pRptParser[i] = NULL; if (pBtd) diff --git a/BTHID.h b/BTHID.h index 7eae9494..f7d18b10 100644 --- a/BTHID.h +++ b/BTHID.h @@ -61,7 +61,7 @@ #define KEYBOARD_PARSER_ID 0 #define MOUSE_PARSER_ID 1 -#define epMUL 2 +#define NUM_PARSERS 2 /** This BluetoothService class implements support for the HID keyboard and mice. */ class BTHID : public BluetoothService { @@ -124,7 +124,7 @@ public: private: BTD *pBtd; // Pointer to BTD instance - HIDReportParser *pRptParser[epMUL]; + HIDReportParser *pRptParser[NUM_PARSERS]; /** Set report protocol. */ void setProtocol(); From 16f124d59691e198c14ca521599768eda064de93 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 5 Dec 2013 07:40:07 +0100 Subject: [PATCH 008/145] Removed unused code --- XBOXRECV.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index 662be5fb..a6d79091 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -104,9 +104,7 @@ uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; } - // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; - //epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory + epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor delay(20); // Wait a little before resetting device @@ -138,8 +136,6 @@ Fail: uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t rcode; - //uint8_t num_of_conf = epInfo[1].epAddr; // Number of configurations - //epInfo[1].epAddr = 0; AddressPool &addrPool = pUsb->GetAddressPool(); #ifdef EXTRADEBUG From aa235ac3ed03b51b2841139e2f08797e0dccc019 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 5 Dec 2013 07:41:57 +0100 Subject: [PATCH 009/145] Macros were renamed in f38a0f65157af628ca5f7706499748c199f0611b --- examples/Bluetooth/BTHID/KeyboardParser.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/Bluetooth/BTHID/KeyboardParser.h b/examples/Bluetooth/BTHID/KeyboardParser.h index b7ab08e9..c5394331 100644 --- a/examples/Bluetooth/BTHID/KeyboardParser.h +++ b/examples/Bluetooth/BTHID/KeyboardParser.h @@ -17,15 +17,15 @@ uint8_t KbdRptParser::HandleLockingKeys(HID *hid, uint8_t key) { uint8_t old_keys = kbdLockingKeys.bLeds; switch (key) { - case KEY_NUM_LOCK: + case UHS_HID_BOOT_KEY_NUM_LOCK: Serial.println(F("Num lock")); kbdLockingKeys.kbdLeds.bmNumLock = ~kbdLockingKeys.kbdLeds.bmNumLock; break; - case KEY_CAPS_LOCK: + case UHS_HID_BOOT_KEY_CAPS_LOCK: Serial.println(F("Caps lock")); kbdLockingKeys.kbdLeds.bmCapsLock = ~kbdLockingKeys.kbdLeds.bmCapsLock; break; - case KEY_SCROLL_LOCK: + case UHS_HID_BOOT_KEY_SCROLL_LOCK: Serial.println(F("Scroll lock")); kbdLockingKeys.kbdLeds.bmScrollLock = ~kbdLockingKeys.kbdLeds.bmScrollLock; break; From fd13b87c18d59ceda932ccd34f0111f19a4ece78 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 5 Dec 2013 02:06:07 -0500 Subject: [PATCH 010/145] Improve macro farther --- hidescriptorparser.cpp | 102 ++++++++++++++++++++--------------------- macros.h | 2 +- message.cpp | 2 +- 3 files changed, 53 insertions(+), 53 deletions(-) diff --git a/hidescriptorparser.cpp b/hidescriptorparser.cpp index c25ded35..f83c3af6 100644 --- a/hidescriptorparser.cpp +++ b/hidescriptorparser.cpp @@ -1246,8 +1246,8 @@ void ReportDescParserBase::PrintUsagePage(uint16_t page) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(page, 0x00, 0x11, w, E_Notify, usagePageTitles0[page - 1], 0x80) - else output_if_between(page, 0x8b, 0x92, w, E_Notify, usagePageTitles1[page - 0x8c], 0x80) + output_if_between(page, 0x00, 0x11, w, E_Notify, usagePageTitles0, 0x80) + else output_if_between(page, 0x8b, 0x92, w, E_Notify, usagePageTitles1, 0x80) else if (VALUE_BETWEEN(page, 0x7f, 0x84)) E_Notify(pstrUsagePageMonitor, 0x80); else if (VALUE_BETWEEN(page, 0x83, 0x8c)) @@ -1288,11 +1288,11 @@ void ReportDescParserBase::PrintGenericDesktopPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x0a, w, E_Notify, genDesktopTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x2f, 0x49, w, E_Notify, genDesktopTitles1[usage - 0x30], 0x80) - else output_if_between(usage, 0x7f, 0x94, w, E_Notify, genDesktopTitles2[usage - 0x80], 0x80) - else output_if_between(usage, 0x9f, 0xa9, w, E_Notify, genDesktopTitles3[usage - 0xa0], 0x80) - else output_if_between(usage, 0xaf, 0xb8, w, E_Notify, genDesktopTitles4[usage - 0xb0], 0x80) + output_if_between(usage, 0x00, 0x0a, w, E_Notify, genDesktopTitles0, 0x80) + else output_if_between(usage, 0x2f, 0x49, w, E_Notify, genDesktopTitles1, 0x80) + else output_if_between(usage, 0x7f, 0x94, w, E_Notify, genDesktopTitles2, 0x80) + else output_if_between(usage, 0x9f, 0xa9, w, E_Notify, genDesktopTitles3, 0x80) + else output_if_between(usage, 0xaf, 0xb8, w, E_Notify, genDesktopTitles4, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1300,9 +1300,9 @@ void ReportDescParserBase::PrintSimulationControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x0d, w, E_Notify, simuTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x1f, 0x26, w, E_Notify, simuTitles1[usage - 0x20], 0x80) - else output_if_between(usage, 0xaf, 0xd1, w, E_Notify, simuTitles2[usage - 0xb0], 0x80) + output_if_between(usage, 0x00, 0x0d, w, E_Notify, simuTitles0, 0x80) + else output_if_between(usage, 0x1f, 0x26, w, E_Notify, simuTitles1, 0x80) + else output_if_between(usage, 0xaf, 0xd1, w, E_Notify, simuTitles2, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1310,8 +1310,8 @@ void ReportDescParserBase::PrintVRControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x0b, w, E_Notify, vrTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x1f, 0x22, w, E_Notify, vrTitles1[usage - 0x20], 0x80) + output_if_between(usage, 0x00, 0x0b, w, E_Notify, vrTitles0, 0x80) + else output_if_between(usage, 0x1f, 0x22, w, E_Notify, vrTitles1, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1319,9 +1319,9 @@ void ReportDescParserBase::PrintSportsControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x05, w, E_Notify, sportsCtrlTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x2f, 0x3a, w, E_Notify, sportsCtrlTitles1[usage - 0x30], 0x80) - else output_if_between(usage, 0x4f, 0x64, w, E_Notify, sportsCtrlTitles2[usage - 0x50], 0x80) + output_if_between(usage, 0x00, 0x05, w, E_Notify, sportsCtrlTitles0, 0x80) + else output_if_between(usage, 0x2f, 0x3a, w, E_Notify, sportsCtrlTitles1, 0x80) + else output_if_between(usage, 0x4f, 0x64, w, E_Notify, sportsCtrlTitles2, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1329,8 +1329,8 @@ void ReportDescParserBase::PrintGameControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x04, w, E_Notify, gameTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x1f, 0x3a, w, E_Notify, gameTitles1[usage - 0x20], 0x80) + output_if_between(usage, 0x00, 0x04, w, E_Notify, gameTitles0, 0x80) + else output_if_between(usage, 0x1f, 0x3a, w, E_Notify, gameTitles1, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1338,7 +1338,7 @@ void ReportDescParserBase::PrintGenericDeviceControlsPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x1f, 0x27, w, E_Notify, genDevCtrlTitles[usage - 0x20], 0x80) + output_if_between(usage, 0x1f, 0x27, w, E_Notify, genDevCtrlTitles, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1346,7 +1346,7 @@ void ReportDescParserBase::PrintLEDPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x4e, w, E_Notify, ledTitles[usage - 1], 0x80) + output_if_between(usage, 0x00, 0x4e, w, E_Notify, ledTitles, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1354,12 +1354,12 @@ void ReportDescParserBase::PrintTelephonyPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x08, w, E_Notify, telTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x1f, 0x32, w, E_Notify, telTitles1[usage - 0x1f], 0x80) - else output_if_between(usage, 0x4f, 0x54, w, E_Notify, telTitles2[usage - 0x4f], 0x80) - else output_if_between(usage, 0x6f, 0x75, w, E_Notify, telTitles3[usage - 0x6f], 0x80) - else output_if_between(usage, 0x8f, 0x9f, w, E_Notify, telTitles4[usage - 0x8f], 0x80) - else output_if_between(usage, 0xaf, 0xc0, w, E_Notify, telTitles5[usage - 0xaf], 0x80) + output_if_between(usage, 0x00, 0x08, w, E_Notify, telTitles0, 0x80) + else output_if_between(usage, 0x1f, 0x32, w, E_Notify, telTitles1, 0x80) + else output_if_between(usage, 0x4f, 0x54, w, E_Notify, telTitles2, 0x80) + else output_if_between(usage, 0x6f, 0x75, w, E_Notify, telTitles3, 0x80) + else output_if_between(usage, 0x8f, 0x9f, w, E_Notify, telTitles4, 0x80) + else output_if_between(usage, 0xaf, 0xc0, w, E_Notify, telTitles5, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1367,21 +1367,21 @@ void ReportDescParserBase::PrintConsumerPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x07, w, E_Notify, consTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x1f, 0x23, w, E_Notify, consTitles1[usage - 0x1f], 0x80) - else output_if_between(usage, 0x2f, 0x37, w, E_Notify, consTitles2[usage - 0x2f], 0x80) - else output_if_between(usage, 0x3f, 0x49, w, E_Notify, consTitles3[usage - 0x3f], 0x80) - else output_if_between(usage, 0x5f, 0x67, w, E_Notify, consTitles4[usage - 0x5f], 0x80) - else output_if_between(usage, 0x7f, 0xa5, w, E_Notify, consTitles5[usage - 0x7f], 0x80) - else output_if_between(usage, 0xaf, 0xcf, w, E_Notify, consTitles6[usage - 0xaf], 0x80) - else output_if_between(usage, 0xdf, 0xeb, w, E_Notify, consTitles7[usage - 0xdf], 0x80) - else output_if_between(usage, 0xef, 0xf6, w, E_Notify, consTitles8[usage - 0xef], 0x80) - else output_if_between(usage, 0xff, 0x10e, w, E_Notify, consTitles9[usage - 0xff], 0x80) - else output_if_between(usage, 0x14f, 0x156, w, E_Notify, consTitlesA[usage - 0x14f], 0x80) - else output_if_between(usage, 0x15f, 0x16b, w, E_Notify, consTitlesB[usage - 0x15f], 0x80) - else output_if_between(usage, 0x16f, 0x175, w, E_Notify, consTitlesC[usage - 0x16f], 0x80) - else output_if_between(usage, 0x17f, 0x1c8, w, E_Notify, consTitlesD[usage - 0x17f], 0x80) - else output_if_between(usage, 0x1ff, 0x29d, w, E_Notify, consTitlesE[usage - 0x1ff], 0x80) + output_if_between(usage, 0x00, 0x07, w, E_Notify, consTitles0, 0x80) + else output_if_between(usage, 0x1f, 0x23, w, E_Notify, consTitles1, 0x80) + else output_if_between(usage, 0x2f, 0x37, w, E_Notify, consTitles2, 0x80) + else output_if_between(usage, 0x3f, 0x49, w, E_Notify, consTitles3, 0x80) + else output_if_between(usage, 0x5f, 0x67, w, E_Notify, consTitles4, 0x80) + else output_if_between(usage, 0x7f, 0xa5, w, E_Notify, consTitles5, 0x80) + else output_if_between(usage, 0xaf, 0xcf, w, E_Notify, consTitles6, 0x80) + else output_if_between(usage, 0xdf, 0xeb, w, E_Notify, consTitles7, 0x80) + else output_if_between(usage, 0xef, 0xf6, w, E_Notify, consTitles8, 0x80) + else output_if_between(usage, 0xff, 0x10e, w, E_Notify, consTitles9, 0x80) + else output_if_between(usage, 0x14f, 0x156, w, E_Notify, consTitlesA, 0x80) + else output_if_between(usage, 0x15f, 0x16b, w, E_Notify, consTitlesB, 0x80) + else output_if_between(usage, 0x16f, 0x175, w, E_Notify, consTitlesC, 0x80) + else output_if_between(usage, 0x17f, 0x1c8, w, E_Notify, consTitlesD, 0x80) + else output_if_between(usage, 0x1ff, 0x29d, w, E_Notify, consTitlesE, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1389,9 +1389,9 @@ void ReportDescParserBase::PrintDigitizerPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x0e, w, E_Notify, digitTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x1f, 0x23, w, E_Notify, digitTitles1[usage - 0x1f], 0x80) - else output_if_between(usage, 0x2f, 0x47, w, E_Notify, digitTitles2[usage - 0x2f], 0x80) + output_if_between(usage, 0x00, 0x0e, w, E_Notify, digitTitles0, 0x80) + else output_if_between(usage, 0x1f, 0x23, w, E_Notify, digitTitles1, 0x80) + else output_if_between(usage, 0x2f, 0x47, w, E_Notify, digitTitles2, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1399,9 +1399,9 @@ void ReportDescParserBase::PrintAlphanumDisplayPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - output_if_between(usage, 0x00, 0x03, w, E_Notify, aplphanumTitles0[usage - 1], 0x80) - else output_if_between(usage, 0x1f, 0x4e, w, E_Notify, aplphanumTitles1[usage - 0x1f], 0x80) - else output_if_between(usage, 0x7f, 0x96, w, E_Notify, digitTitles2[usage - 0x80], 0x80) + output_if_between(usage, 0x00, 0x03, w, E_Notify, aplphanumTitles0, 0x80) + else output_if_between(usage, 0x1f, 0x4e, w, E_Notify, aplphanumTitles1, 0x80) + else output_if_between(usage, 0x7f, 0x96, w, E_Notify, digitTitles2, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } @@ -1412,11 +1412,11 @@ void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) { if (usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80); else if (usage == 0x70) E_Notify(pstrUsageDepthGainCompensation, 0x80); - else output_if_between(usage, 0x1f, 0x28, w, E_Notify, medInstrTitles0[usage - 0x1f], 0x80) - else output_if_between(usage, 0x3f, 0x45, w, E_Notify, medInstrTitles1[usage - 0x40], 0x80) - else output_if_between(usage, 0x5f, 0x62, w, E_Notify, medInstrTitles2[usage - 0x60], 0x80) - else output_if_between(usage, 0x7f, 0x8a, w, E_Notify, medInstrTitles3[usage - 0x80], 0x80) - else output_if_between(usage, 0x9f, 0xa2, w, E_Notify, medInstrTitles4[usage - 0xa0], 0x80) + else output_if_between(usage, 0x1f, 0x28, w, E_Notify, medInstrTitles0, 0x80) + else output_if_between(usage, 0x3f, 0x45, w, E_Notify, medInstrTitles1, 0x80) + else output_if_between(usage, 0x5f, 0x62, w, E_Notify, medInstrTitles2, 0x80) + else output_if_between(usage, 0x7f, 0x8a, w, E_Notify, medInstrTitles3, 0x80) + else output_if_between(usage, 0x9f, 0xa2, w, E_Notify, medInstrTitles4, 0x80) else E_Notify(pstrUsagePageUndefined, 0x80); } diff --git a/macros.h b/macros.h index 45a6ea86..70f04262 100644 --- a/macros.h +++ b/macros.h @@ -17,7 +17,7 @@ #define VALUE_BETWEEN(v,l,h) (((v)>(l)) && ((v)<(h))) #define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) #define output_pgm_message(wa,fp,mp,el) wa = &mp, fp((char *)pgm_read_pointer(wa), el) -#define output_if_between(v,l,h,wa,fp,mp,el) if(VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp,el); +#define output_if_between(v,l,h,wa,fp,mp,el) if(VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp[v-(l+1)],el); #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) #ifndef __BYTE_GRABBING_DEFINED__ diff --git a/message.cpp b/message.cpp index 4ec9d5c8..5965e51b 100644 --- a/message.cpp +++ b/message.cpp @@ -18,7 +18,7 @@ e-mail : support@circuitsathome.com #include "Usb.h" // 0x80 is the default (i.e. trace) to turn off set this global to something lower. // this allows for 126 other debugging levels. -// TO-DO: Allow assignment to a different serial port +// TO-DO: Allow assignment to a different serial port by software int UsbDEBUGlvl = 0x80; void E_Notifyc(char c, int lvl) { From 0a7ffe57766e400db0c21c63ae17a411a178f646 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 5 Dec 2013 19:57:50 +0100 Subject: [PATCH 011/145] Allow to override default arrays in hidboot, so it can easily be used with other keyboard layouts --- hidboot.cpp | 19 +++++++++---------- hidboot.h | 24 ++++++++++++++++++++---- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/hidboot.cpp b/hidboot.cpp index 2737b7b9..b94bbd56 100644 --- a/hidboot.cpp +++ b/hidboot.cpp @@ -99,10 +99,10 @@ uint8_t KeyboardReportParser::HandleLockingKeys(HID *hid, uint8_t key) { return 0; } -const uint8_t KeyboardReportParser::numKeys[] PROGMEM = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')'}; -const uint8_t KeyboardReportParser::symKeysUp[] PROGMEM = {'_', '+', '{', '}', '|', '~', ':', '"', '~', '<', '>', '?'}; -const uint8_t KeyboardReportParser::symKeysLo[] PROGMEM = {'-', '=', '[', ']', '\\', ' ', ';', '\'', '`', ',', '.', '/'}; -const uint8_t KeyboardReportParser::padKeys[] PROGMEM = {'/', '*', '-', '+', 0x13}; +const uint8_t KeyboardReportParser::numKeys[10] PROGMEM = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')'}; +const uint8_t KeyboardReportParser::symKeysUp[12] PROGMEM = {'_', '+', '{', '}', '|', '~', ':', '"', '~', '<', '>', '?'}; +const uint8_t KeyboardReportParser::symKeysLo[12] PROGMEM = {'-', '=', '[', ']', '\\', ' ', ';', '\'', '`', ',', '.', '/'}; +const uint8_t KeyboardReportParser::padKeys[5] PROGMEM = {'/', '*', '-', '+', 0x13}; uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { uint8_t shift = (mod & 0x22); @@ -118,24 +118,23 @@ uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { else return (key - 4 + 'a'); }// Numbers - else if (key > 0x1d && key < 0x27) { + else if (key > 0x1d && key < 0x28) { if (shift) - return ((uint8_t)pgm_read_byte(&numKeys[key - 0x1e])); + return ((uint8_t)pgm_read_byte(&getNumKeys()[key - 0x1e])); else - return (key - 0x1e + '1'); + return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1'); }// Keypad Numbers else if (key > 0x58 && key < 0x62) { if (kbdLockingKeys.kbdLeds.bmNumLock == 1) return (key - 0x59 + '1'); } else if (key > 0x2c && key < 0x39) - return ((shift) ? (uint8_t)pgm_read_byte(&symKeysUp[key - 0x2d]) : (uint8_t)pgm_read_byte(&symKeysLo[key - 0x2d])); + return ((shift) ? (uint8_t)pgm_read_byte(&getSymKeysUp()[key - 0x2d]) : (uint8_t)pgm_read_byte(&getSymKeysLo()[key - 0x2d])); else if (key > 0x53 && key < 0x59) - return (uint8_t)pgm_read_byte(&padKeys[key - 0x54]); + return (uint8_t)pgm_read_byte(&getPadKeys()[key - 0x54]); else { switch (key) { case UHS_HID_BOOT_KEY_SPACE: return (0x20); case UHS_HID_BOOT_KEY_ENTER: return (0x13); - case UHS_HID_BOOT_KEY_ZERO: return ((shift) ? ')': '0'); case UHS_HID_BOOT_KEY_ZERO2: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '0': 0); case UHS_HID_BOOT_KEY_PERIOD: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '.': 0); } diff --git a/hidboot.h b/hidboot.h index 57f6862e..b418dc4c 100644 --- a/hidboot.h +++ b/hidboot.h @@ -112,10 +112,10 @@ struct KBDLEDS { }; class KeyboardReportParser : public HIDReportParser { - static const uint8_t numKeys[]; - static const uint8_t symKeysUp[]; - static const uint8_t symKeysLo[]; - static const uint8_t padKeys[]; + static const uint8_t numKeys[10]; + static const uint8_t symKeysUp[12]; + static const uint8_t symKeysLo[12]; + static const uint8_t padKeys[5]; protected: @@ -150,6 +150,22 @@ protected: virtual void OnKeyUp(uint8_t mod, uint8_t key) { }; + + virtual const uint8_t *getNumKeys() { + return numKeys; + }; + + virtual const uint8_t *getSymKeysUp() { + return symKeysUp; + }; + + virtual const uint8_t *getSymKeysLo() { + return symKeysLo; + }; + + virtual const uint8_t *getPadKeys() { + return padKeys; + }; }; #define totalEndpoints (((BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD)? 2 : 0)+((BOOT_PROTOCOL & HID_PROTOCOL_MOUSE)? 1 : 0)) From 34ea983e88892f0ca3e7bc20a4242e190ee54232 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 5 Dec 2013 20:07:31 +0100 Subject: [PATCH 012/145] Use VALUE_WITHIN macro --- hidboot.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/hidboot.cpp b/hidboot.cpp index b94bbd56..b323bd15 100644 --- a/hidboot.cpp +++ b/hidboot.cpp @@ -108,7 +108,7 @@ uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { uint8_t shift = (mod & 0x22); // [a-z] - if (key > 0x03 && key < 0x1e) { + if (VALUE_WITHIN(key, 0x04, 0x1d)) { // Upper case letters if ((kbdLockingKeys.kbdLeds.bmCapsLock == 0 && (mod & 2)) || (kbdLockingKeys.kbdLeds.bmCapsLock == 1 && (mod & 2) == 0)) @@ -118,18 +118,18 @@ uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { else return (key - 4 + 'a'); }// Numbers - else if (key > 0x1d && key < 0x28) { + else if (VALUE_WITHIN(key, 0x1e, 0x27)) { if (shift) return ((uint8_t)pgm_read_byte(&getNumKeys()[key - 0x1e])); else return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1'); }// Keypad Numbers - else if (key > 0x58 && key < 0x62) { + else if (VALUE_WITHIN(key, 0x59, 0x61)) { if (kbdLockingKeys.kbdLeds.bmNumLock == 1) return (key - 0x59 + '1'); - } else if (key > 0x2c && key < 0x39) + } else if (VALUE_WITHIN(key, 0x2d, 0x38)) return ((shift) ? (uint8_t)pgm_read_byte(&getSymKeysUp()[key - 0x2d]) : (uint8_t)pgm_read_byte(&getSymKeysLo()[key - 0x2d])); - else if (key > 0x53 && key < 0x59) + else if (VALUE_WITHIN(key, 0x54, 0x58)) return (uint8_t)pgm_read_byte(&getPadKeys()[key - 0x54]); else { switch (key) { From b4bb7c92448f95e7b4eda227714c821955856d0d Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 6 Dec 2013 22:58:16 +0100 Subject: [PATCH 013/145] Fixed some bugs introduced in e18eb57752095fc59725090e640073b45458b638 --- PS3USB.cpp | 9 +++++---- XBOXOLD.cpp | 5 +++-- XBOXUSB.cpp | 5 +++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/PS3USB.cpp b/PS3USB.cpp index c91e8074..1f6226eb 100644 --- a/PS3USB.cpp +++ b/PS3USB.cpp @@ -221,14 +221,15 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { bPollEnable = true; Notify(PSTR("\r\n"), 0x80); timer = millis(); - return 0; // successful configuration + return 0; // Successful configuration - /* diagnostic messages */ + /* Diagnostic messages */ FailGetDevDescr: #ifdef DEBUG_USB_HOST NotifyFailGetDevDescr(); goto Fail; #endif + FailSetDevTblEntry: #ifdef DEBUG_USB_HOST NotifyFailSetDevTblEntry(); @@ -238,8 +239,8 @@ FailSetDevTblEntry: FailSetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailSetConfDescr(); - goto Fail; #endif + goto Fail; FailUnknownDevice: #ifdef DEBUG_USB_HOST @@ -247,8 +248,8 @@ FailUnknownDevice: #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; -#ifdef DEBUG_USB_HOST Fail: +#ifdef DEBUG_USB_HOST Notify(PSTR("\r\nPS3 Init Failed, error code: "), 0x80); NotifyFail(rcode); #endif diff --git a/XBOXOLD.cpp b/XBOXOLD.cpp index f82efc0c..e60330c8 100644 --- a/XBOXOLD.cpp +++ b/XBOXOLD.cpp @@ -214,16 +214,17 @@ FailSetDevTblEntry: FailSetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailSetConfDescr(); - goto Fail; #endif + goto Fail; + FailUnknownDevice: #ifdef DEBUG_USB_HOST NotifyFailUnknownDevice(VID, PID); #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; -#ifdef DEBUG_USB_HOST Fail: +#ifdef DEBUG_USB_HOST Notify(PSTR("\r\nXbox Init Failed, error code: "), 0x80); NotifyFail(rcode); #endif diff --git a/XBOXUSB.cpp b/XBOXUSB.cpp index 2228af7e..a7900811 100644 --- a/XBOXUSB.cpp +++ b/XBOXUSB.cpp @@ -201,16 +201,17 @@ FailSetDevTblEntry: FailSetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailSetConfDescr(); - goto Fail; #endif + goto Fail; + FailUnknownDevice: #ifdef DEBUG_USB_HOST NotifyFailUnknownDevice(VID, PID); #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; -#ifdef DEBUG_USB_HOST Fail: +#ifdef DEBUG_USB_HOST Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80); NotifyFail(rcode); #endif From 4f738d3ef9939d6b5d0a82af184f1633f588d5e5 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 6 Dec 2013 22:59:12 +0100 Subject: [PATCH 014/145] Removed some unused code --- BTD.cpp | 8 +------- XBOXRECV.cpp | 6 ------ 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 0495689c..62a96b70 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -251,13 +251,7 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { } return 0; // Successful configuration - /* diagnostic messages */ -#ifdef DEBUG_USB_HOST -FailGetDevDescr: - NotifyFailGetDevDescr(); - goto Fail; -#endif - + /* Diagnostic messages */ FailSetDevTblEntry: #ifdef DEBUG_USB_HOST NotifyFailSetDevTblEntry(); diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index a6d79091..8e4008a3 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -275,12 +275,6 @@ FailSetConfDescr: NotifyFailSetConfDescr(); #endif -#ifdef DEBUG_USB_HOST -FailUnknownDevice: - NotifyFailUnknownDevice(VID,PID); -#endif - rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - Fail: #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80); From 655b60ea90010a3f041e9363262cded755774026 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 6 Dec 2013 23:24:25 +0100 Subject: [PATCH 015/145] Added some delays between USB commands --- adk.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/adk.cpp b/adk.cpp index 63427b26..a3530d00 100644 --- a/adk.cpp +++ b/adk.cpp @@ -228,14 +228,23 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { USBTRACE2("\r\nADK protocol rev. ", adkproto); } + delay(100); + //sending ID strings sendStr(ACCESSORY_STRING_MANUFACTURER, manufacturer); + delay(10); sendStr(ACCESSORY_STRING_MODEL, model); + delay(10); sendStr(ACCESSORY_STRING_DESCRIPTION, description); + delay(10); sendStr(ACCESSORY_STRING_VERSION, version); + delay(10); sendStr(ACCESSORY_STRING_URI, uri); + delay(10); sendStr(ACCESSORY_STRING_SERIAL, serial); + delay(100); + //switch to accessory mode //the Android phone will reset rcode = switchAcc(); @@ -243,7 +252,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { goto FailSwAcc; //init fails } rcode = USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET; - delay(1000); // Give Android a chance to do its reset. This is a guess, and possibly could be lower. + delay(100); // Give Android a chance to do its reset. This is a guess, and possibly could be lower. goto SwAttempt; //switch to accessory mode attempted /* diagnostic messages */ From 843eec8ba6c4c3ed9590dc65d08331f3c1292ae6 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 6 Dec 2013 23:27:26 +0100 Subject: [PATCH 016/145] Print when connected and disconnected from accessory --- examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino b/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino index bc0cb95a..dc6ab92c 100644 --- a/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino +++ b/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino @@ -13,6 +13,7 @@ ADK adk(&Usb, "TKJElectronics", // Manufacturer Name #define LED LED_BUILTIN // Use built in LED - note that pin 13 is occupied by the SCK pin on a normal Arduino (Uno, Duemilanove etc.), so use a different pin uint32_t timer; +boolean connected; void setup() { Serial.begin(115200); @@ -27,7 +28,13 @@ void setup() { void loop() { Usb.Task(); + if (adk.isReady()) { + if (!connected) { + connected = true; + Serial.print(F("\r\nConnected to accessory")); + } + uint8_t msg[1]; uint16_t len = sizeof(msg); uint8_t rcode = adk.RcvData(&len, msg); @@ -51,7 +58,11 @@ void loop() { Serial.print(timer); } } + } else { + if (connected) { + connected = false; + Serial.print(F("\r\nDisconnected from accessory")); + digitalWrite(LED, LOW); + } } - else - digitalWrite(LED, LOW); } From 4533e3cd4451d9d6c4f476ef1d9b7809b82af8da Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 7 Dec 2013 00:26:49 +0100 Subject: [PATCH 017/145] Allow SPP to work in Arduino 0.2.3 and below --- SPP.cpp | 14 +++++++++++++- SPP.h | 16 ++++++++++++++++ settings.h | 1 + 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/SPP.cpp b/SPP.cpp index 0c133830..f0a83927 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -756,17 +756,29 @@ bool SPP::checkFcs(uint8_t *data, uint8_t fcs) { } /* Serial commands */ +#if defined(ARDUINO) && ARDUINO >=100 size_t SPP::write(uint8_t data) { - return write(&data,1); + return write(&data, 1); } +#else +void SPP::write(uint8_t data) { + write(&data, 1); +} +#endif +#if defined(ARDUINO) && ARDUINO >=100 size_t SPP::write(const uint8_t *data, size_t size) { +#else +void SPP::write(const uint8_t *data, size_t size) { +#endif for(uint8_t i = 0; i < size; i++) { if(sppIndex >= sizeof(sppOutputBuffer)/sizeof(sppOutputBuffer[0])) send(); // Send the current data in the buffer sppOutputBuffer[sppIndex++] = data[i]; // All the bytes are put into a buffer and then send using the send() function } +#if defined(ARDUINO) && ARDUINO >=100 return size; +#endif } void SPP::send() { diff --git a/SPP.h b/SPP.h index 81b83829..201fb77b 100644 --- a/SPP.h +++ b/SPP.h @@ -147,6 +147,8 @@ public: * @return Return the byte. Will return -1 if no bytes are available. */ virtual int read(void); + +#if defined(ARDUINO) && ARDUINO >=100 /** * Writes the byte to send to a buffer. The message is send when either send() or after Usb.Task() is called. * @param data The byte to write. @@ -162,6 +164,20 @@ public: virtual size_t write(const uint8_t* data, size_t size); /** Pull in write(const char *str) from Print */ using Print::write; +#else + /** + * Writes the byte to send to a buffer. The message is send when either send() or after Usb.Task() is called. + * @param data The byte to write. + */ + virtual void write(uint8_t data); + /** + * Writes the bytes to send to a buffer. The message is send when either send() or after Usb.Task() is called. + * @param data The data array to send. + * @param size Size of the data. + */ + virtual void write(const uint8_t* data, size_t size); +#endif + /** Discard all the bytes in the buffer. */ void discard(void); /** diff --git a/settings.h b/settings.h index bd64ff3f..bc8878ee 100644 --- a/settings.h +++ b/settings.h @@ -75,6 +75,7 @@ #include #include #include +#define F(str) (str) #endif #if USE_XMEM_SPI_LOCK | defined(USE_MULTIPLE_APP_API) From 00442ce2e5f3999c19dd9b40cf1ed0dae1c13949 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 7 Dec 2013 00:32:21 +0100 Subject: [PATCH 018/145] Updated max_LCD to inherit the standard Print class Works both in Arduino < 1.0.0 and newer versions of Arduino --- max_LCD.cpp | 7 +++++++ max_LCD.h | 10 ++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/max_LCD.cpp b/max_LCD.cpp index 71c2247a..ce7ad683 100644 --- a/max_LCD.cpp +++ b/max_LCD.cpp @@ -223,9 +223,16 @@ inline void Max_LCD::command(uint8_t value) { delayMicroseconds(100); } +#if defined(ARDUINO) && ARDUINO >=100 +inline size_t Max_LCD::write(uint8_t value) { + LCD_sendchar(value); + return 1; // Assume success +} +#else inline void Max_LCD::write(uint8_t value) { LCD_sendchar(value); } +#endif void Max_LCD::sendbyte(uint8_t val) { lcdPins &= 0x0f; //prepare place for the upper nibble diff --git a/max_LCD.h b/max_LCD.h index be9f2615..668ebb2d 100644 --- a/max_LCD.h +++ b/max_LCD.h @@ -62,7 +62,7 @@ e-mail : support@circuitsathome.com #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 -class Max_LCD //: public Print +class Max_LCD : public Print { USB *pUsb; @@ -86,9 +86,15 @@ public: void noAutoscroll(); void createChar(uint8_t, uint8_t[]); void setCursor(uint8_t, uint8_t); - virtual void write(uint8_t); void command(uint8_t); +#if defined(ARDUINO) && ARDUINO >=100 + virtual size_t write(uint8_t); + using Print::write; +#else + virtual void write(uint8_t); +#endif + private: void sendbyte(uint8_t val); uint8_t _displayfunction; //tokill From 8072e6f1bbcd2f2065905b4f3c30ff9f36059307 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 7 Dec 2013 00:34:33 +0100 Subject: [PATCH 019/145] Added max_LCD example Copy of: https://github.com/arduino/Arduino/blob/ide-1.5.x/libraries/LiquidCrystal/examples/HelloWorld/HelloWorld.ino --- examples/max_LCD/max_LCD.ino | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 examples/max_LCD/max_LCD.ino diff --git a/examples/max_LCD/max_LCD.ino b/examples/max_LCD/max_LCD.ino new file mode 100644 index 00000000..baadf2d0 --- /dev/null +++ b/examples/max_LCD/max_LCD.ino @@ -0,0 +1,23 @@ +// Just a copy of the HelloWorld example bundled with the LiquidCrystal in the Arduino IDE + +// HD44780 compatible LCD display via MAX3421E GPOUT support header +// pinout: D[4-7] -> GPOUT[4-7], RS-> GPOUT[2], E ->GPOUT[3] + +#include + +USB Usb; +Max_LCD lcd(&Usb); + +void setup() { + // Set up the LCD's number of columns and rows: + lcd.begin(16, 2); + // Print a message to the LCD. + lcd.print("Hello, World!"); +} + +void loop() { + // Set the cursor to column 0, line 1 (note: line 1 is the second row, since counting begins with 0): + lcd.setCursor(0, 1); + // Print the number of seconds since reset: + lcd.print(millis() / 1000); +} From e92dd0d03d5a0c08e920336c8fee7e1f472f2947 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 8 Dec 2013 17:42:14 +0100 Subject: [PATCH 020/145] Typo --- examples/max_LCD/max_LCD.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/max_LCD/max_LCD.ino b/examples/max_LCD/max_LCD.ino index baadf2d0..f60ed4d5 100644 --- a/examples/max_LCD/max_LCD.ino +++ b/examples/max_LCD/max_LCD.ino @@ -1,4 +1,4 @@ -// Just a copy of the HelloWorld example bundled with the LiquidCrystal in the Arduino IDE +// Just a copy of the HelloWorld example bundled with the LiquidCrystal library in the Arduino IDE // HD44780 compatible LCD display via MAX3421E GPOUT support header // pinout: D[4-7] -> GPOUT[4-7], RS-> GPOUT[2], E ->GPOUT[3] From 9b3bae9dbeb2df2068b9bce8cb1b763b035f5002 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 10 Dec 2013 00:39:12 +0100 Subject: [PATCH 021/145] Workaround for bug in GCC < 4.6.2 --- settings.h | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/settings.h b/settings.h index bc8878ee..ea114ed3 100644 --- a/settings.h +++ b/settings.h @@ -71,13 +71,26 @@ #include #else #include -// I am not sure what WProgram.h does not include, so these are here. --xxxajk #include #include #include #define F(str) (str) #endif +#ifdef __GNUC__ +#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#if GCC_VERSION < 40602 // Test for GCC < 4.6.2 +#ifdef PROGMEM +#undef PROGMEM +#define PROGMEM __attribute__((section(".progmem.data"))) // Workaround for http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734#c4 +#ifdef PSTR +#undef PSTR +#define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) // Copied from pgmspace.h in avr-libc source +#endif +#endif +#endif +#endif + #if USE_XMEM_SPI_LOCK | defined(USE_MULTIPLE_APP_API) #include #else From 73bffffddc8bd941074fb316e3452e0e65d62938 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 10 Dec 2013 00:50:03 +0100 Subject: [PATCH 022/145] =?UTF-8?q?Don=E2=80=99t=20inlcude=20avr/pgmspace.?= =?UTF-8?q?h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is needed, as we work around bug in GCC - see: 9b3bae9dbeb2df2068b9bce8cb1b763b035f5002 --- hidusagestr.h | 2 +- hidusagetitlearrays.cpp | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/hidusagestr.h b/hidusagestr.h index 6c137e02..32ab0771 100644 --- a/hidusagestr.h +++ b/hidusagestr.h @@ -17,7 +17,7 @@ e-mail : support@circuitsathome.com #if !defined( __HIDUSAGESTR_H__) #define __HIDUSAGESTR_H__ -#include +#include "Usb.h" const char pstrSpace [] PROGMEM = " "; const char pstrCRLF [] PROGMEM = "\r\n"; diff --git a/hidusagetitlearrays.cpp b/hidusagetitlearrays.cpp index 09d59302..0aa1b9c7 100644 --- a/hidusagetitlearrays.cpp +++ b/hidusagetitlearrays.cpp @@ -17,7 +17,6 @@ e-mail : support@circuitsathome.com #if !defined(__HIDUSAGETITLEARRAYS_H__) #define __HIDUSAGETITLEARRAYS_H__ -#include #include "hidusagestr.h" //const char *usagePageTitles0[] PROGMEM = From ed36d04e7ccd399799474866b979b70b561fcc47 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 11 Dec 2013 09:29:38 +0100 Subject: [PATCH 023/145] Move all L2CAP states etc. into BTD.h, so the different drivers does not conflict when used together --- BTD.h | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- BTHID.h | 40 +------------------------ PS3BT.cpp | 40 +++++++------------------ PS3BT.h | 37 ++--------------------- SPP.h | 39 ++---------------------- Wii.cpp | 20 ++++++------- Wii.h | 54 ++++----------------------------- 7 files changed, 118 insertions(+), 201 deletions(-) diff --git a/BTD.h b/BTD.h index 2bf5e7ba..c4293327 100755 --- a/BTD.h +++ b/BTD.h @@ -47,7 +47,7 @@ #define HCI_SET_NAME_STATE 5 #define HCI_CHECK_DEVICE_SERVICE 6 -#define HCI_INQUIRY_STATE 7 // These three states are only used if it should pair and connect to a Wii controller +#define HCI_INQUIRY_STATE 7 // These three states are only used if it should pair and connect to a device #define HCI_CONNECT_DEVICE_STATE 8 #define HCI_CONNECTED_DEVICE_STATE 9 @@ -105,6 +105,89 @@ #define EV_LOOPBACK_COMMAND 0x19 #define EV_PAGE_SCAN_REP_MODE 0x20 +/* Bluetooth states for the different Bluetooth drivers */ +#define L2CAP_WAIT 0 +#define L2CAP_DONE 1 + +/* Used for HID Control channel */ +#define L2CAP_CONTROL_CONNECT_REQUEST 2 +#define L2CAP_CONTROL_CONFIG_REQUEST 3 +#define L2CAP_CONTROL_SUCCESS 4 +#define L2CAP_CONTROL_DISCONNECT 5 + +/* Used for HID Interrupt channel */ +#define L2CAP_INTERRUPT_SETUP 6 +#define L2CAP_INTERRUPT_CONNECT_REQUEST 7 +#define L2CAP_INTERRUPT_CONFIG_REQUEST 8 +#define L2CAP_INTERRUPT_DISCONNECT 9 + +/* Used for SDP channel */ +#define L2CAP_SDP_WAIT 10 +#define L2CAP_SDP_REQUEST 11 +#define L2CAP_SDP_SUCCESS 12 +#define L2CAP_SDP_DONE 13 +#define L2CAP_DISCONNECT_RESPONSE 14 + +/* Used for RFCOMM channel */ +#define L2CAP_RFCOMM_WAIT 15 +#define L2CAP_RFCOMM_REQUEST 16 +#define L2CAP_RFCOMM_SUCCESS 17 +#define L2CAP_RFCOMM_DONE 18 + +/* Bluetooth states used by some drivers */ +#define TURN_ON_LED 19 +#define PS3_ENABLE_SIXAXIS 20 +#define WII_CHECK_MOTION_PLUS_STATE 21 +#define WII_CHECK_EXTENSION_STATE 22 +#define WII_INIT_MOTION_PLUS_STATE 23 + +/* L2CAP event flags */ +#define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST 0x00000001 +#define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS 0x00000002 +#define L2CAP_FLAG_CONTROL_CONNECTED 0x00000004 +#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE 0x00000008 + +#define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST 0x00000010 +#define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS 0x00000020 +#define L2CAP_FLAG_INTERRUPT_CONNECTED 0x00000040 +#define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE 0x00000080 + +#define L2CAP_FLAG_CONNECTION_SDP_REQUEST 0x00000100 +#define L2CAP_FLAG_CONFIG_SDP_REQUEST 0x00000200 +#define L2CAP_FLAG_CONFIG_SDP_SUCCESS 0x00000400 +#define L2CAP_FLAG_DISCONNECT_SDP_REQUEST 0x00000800 + +#define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST 0x00001000 +#define L2CAP_FLAG_CONFIG_RFCOMM_REQUEST 0x00002000 +#define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS 0x00004000 +#define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST 0x00008000 + +#define L2CAP_FLAG_DISCONNECT_RESPONSE 0x00010000 + +/* Macros for L2CAP event flag tests */ + +#define l2cap_connection_request_control_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_CONTROL_REQUEST) +#define l2cap_config_success_control_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_CONTROL_SUCCESS) +#define l2cap_connected_control_flag (l2cap_event_flag & L2CAP_FLAG_CONTROL_CONNECTED) +#define l2cap_disconnect_response_control_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE) + +#define l2cap_connection_request_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST) +#define l2cap_config_success_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS) +#define l2cap_connected_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_INTERRUPT_CONNECTED) +#define l2cap_disconnect_response_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) + +#define l2cap_connection_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_SDP_REQUEST) +#define l2cap_config_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_SDP_REQUEST) +#define l2cap_config_success_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_SDP_SUCCESS) +#define l2cap_disconnect_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_SDP_REQUEST) + +#define l2cap_connection_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST) +#define l2cap_config_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_RFCOMM_REQUEST) +#define l2cap_config_success_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS) +#define l2cap_disconnect_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST) + +#define l2cap_disconnect_response_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_RESPONSE) + /* L2CAP signaling commands */ #define L2CAP_CMD_COMMAND_REJECT 0x01 #define L2CAP_CMD_CONNECTION_REQUEST 0x02 @@ -131,11 +214,11 @@ #define WI_PROTOCOL_BT 0x01 // Bluetooth Programming Interface #define BTD_MAX_ENDPOINTS 4 -#define BTD_NUMSERVICES 4 // Max number of Bluetooth services - if you need more than four simply increase this number +#define BTD_NUMSERVICES 4 // Max number of Bluetooth services - if you need more than 4 simply increase this number #define PAIR 1 -/** All Bluetooth services should include this class. */ +/** All Bluetooth services should inherit this class. */ class BluetoothService { public: /** diff --git a/BTHID.h b/BTHID.h index f7d18b10..b4cb21f2 100644 --- a/BTHID.h +++ b/BTHID.h @@ -21,44 +21,6 @@ #include "BTD.h" #include "hidboot.h" -/* Bluetooth L2CAP states for L2CAP_task() */ -#define L2CAP_WAIT 0 - -// These states are used if the device is the host -#define L2CAP_CONTROL_SUCCESS 1 -#define L2CAP_INTERRUPT_SETUP 2 - -// These states are used if the Arduino is the host -#define L2CAP_CONTROL_CONNECT_REQUEST 3 -#define L2CAP_CONTROL_CONFIG_REQUEST 4 -#define L2CAP_INTERRUPT_CONNECT_REQUEST 5 - -#define L2CAP_INTERRUPT_CONFIG_REQUEST 6 -#define L2CAP_DONE 7 - -#define L2CAP_INTERRUPT_DISCONNECT 8 -#define L2CAP_CONTROL_DISCONNECT 9 - -/* L2CAP event flags */ -#define L2CAP_FLAG_CONTROL_CONNECTED 0x01 -#define L2CAP_FLAG_INTERRUPT_CONNECTED 0x02 -#define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS 0x04 -#define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS 0x08 -#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE 0x10 -#define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE 0x20 -#define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST 0x40 -#define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST 0x80 - -/* Macros for L2CAP event flag tests */ -#define l2cap_connected_control_flag (l2cap_event_flag & L2CAP_FLAG_CONTROL_CONNECTED) -#define l2cap_connected_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_INTERRUPT_CONNECTED) -#define l2cap_config_success_control_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_CONTROL_SUCCESS) -#define l2cap_config_success_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS) -#define l2cap_disconnect_response_control_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE) -#define l2cap_disconnect_response_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) -#define l2cap_connection_request_control_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_CONTROL_REQUEST) -#define l2cap_connection_request_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST) - #define KEYBOARD_PARSER_ID 0 #define MOUSE_PARSER_ID 1 #define NUM_PARSERS 2 @@ -149,7 +111,7 @@ private: /* Variables used by high level L2CAP task */ uint8_t l2cap_state; - uint8_t l2cap_event_flag; // l2cap flags of received Bluetooth events + uint32_t l2cap_event_flag; // l2cap flags of received Bluetooth events /* L2CAP Channels */ uint8_t control_scid[2]; // L2CAP source CID for HID_Control diff --git a/PS3BT.cpp b/PS3BT.cpp index 9ed5da75..a56efa73 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -305,12 +305,10 @@ void PS3BT::ACLData(uint8_t* ACLData) { } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Request"), 0x80); - identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_CONTROL_REQUEST; + pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], control_scid); } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80); - identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_INTERRUPT_REQUEST; + pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], interrupt_scid); } } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { @@ -390,15 +388,6 @@ void PS3BT::L2CAP_task() { identifier++; delay(1); pBtd->l2cap_config_request(hci_handle, identifier, control_scid); - l2cap_state = L2CAP_CONTROL_REQUEST; - } - break; - case L2CAP_CONTROL_REQUEST: - if (l2cap_config_request_control_flag) { -#ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nHID Control Configuration Request"), 0x80); -#endif - pBtd->l2cap_config_response(hci_handle, identifier, control_scid); l2cap_state = L2CAP_CONTROL_SUCCESS; } break; @@ -411,6 +400,7 @@ void PS3BT::L2CAP_task() { l2cap_state = L2CAP_INTERRUPT_SETUP; } break; + case L2CAP_INTERRUPT_SETUP: if (l2cap_connection_request_interrupt_flag) { #ifdef DEBUG_USB_HOST @@ -423,28 +413,20 @@ void PS3BT::L2CAP_task() { delay(1); pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid); - l2cap_state = L2CAP_INTERRUPT_REQUEST; + l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST; } break; - case L2CAP_INTERRUPT_REQUEST: - if (l2cap_config_request_interrupt_flag) { -#ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80); -#endif - pBtd->l2cap_config_response(hci_handle, identifier, interrupt_scid); - l2cap_state = L2CAP_INTERRUPT_SUCCESS; - } - break; - case L2CAP_INTERRUPT_SUCCESS: + + case L2CAP_INTERRUPT_CONFIG_REQUEST: if (l2cap_config_success_interrupt_flag) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Successfully Configured"), 0x80); #endif if (remote_name[0] == 'M') { // First letter in Motion Controller ('M') memset(l2capinbuf, 0, BULK_MAXPKTSIZE); // Reset l2cap in buffer as it sometimes read it as a button has been pressed - l2cap_state = L2CAP_HID_PS3_LED; + l2cap_state = TURN_ON_LED; } else - l2cap_state = L2CAP_HID_ENABLE_SIXAXIS; + l2cap_state = PS3_ENABLE_SIXAXIS; timer = millis(); } break; @@ -478,18 +460,18 @@ void PS3BT::L2CAP_task() { void PS3BT::Run() { switch (l2cap_state) { - case L2CAP_HID_ENABLE_SIXAXIS: + case PS3_ENABLE_SIXAXIS: if (millis() - timer > 1000) { // loop 1 second before sending the command memset(l2capinbuf, 0, BULK_MAXPKTSIZE); // Reset l2cap in buffer as it sometimes read it as a button has been pressed for (uint8_t i = 15; i < 19; i++) l2capinbuf[i] = 0x7F; // Set the analog joystick values to center position enable_sixaxis(); - l2cap_state = L2CAP_HID_PS3_LED; + l2cap_state = TURN_ON_LED; timer = millis(); } break; - case L2CAP_HID_PS3_LED: + case TURN_ON_LED: if (millis() - timer > 1000) { // loop 1 second before sending the command if (remote_name[0] == 'P') { // First letter in PLAYSTATION(R)3 Controller ('P') #ifdef DEBUG_USB_HOST diff --git a/PS3BT.h b/PS3BT.h index 6b901402..8d796649 100644 --- a/PS3BT.h +++ b/PS3BT.h @@ -21,40 +21,7 @@ #include "BTD.h" #include "PS3Enums.h" -#define HID_BUFFERSIZE 50 // Size of the buffer for the Playstation Motion Controller - -/* Bluetooth L2CAP states for L2CAP_task() */ -#define L2CAP_WAIT 0 -#define L2CAP_CONTROL_REQUEST 1 -#define L2CAP_CONTROL_SUCCESS 2 -#define L2CAP_INTERRUPT_SETUP 3 -#define L2CAP_INTERRUPT_REQUEST 4 -#define L2CAP_INTERRUPT_SUCCESS 5 -#define L2CAP_HID_ENABLE_SIXAXIS 6 -#define L2CAP_HID_PS3_LED 7 -#define L2CAP_DONE 8 -#define L2CAP_INTERRUPT_DISCONNECT 9 -#define L2CAP_CONTROL_DISCONNECT 10 - -/* L2CAP event flags */ -#define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST 0x01 -#define L2CAP_FLAG_CONFIG_CONTROL_REQUEST 0x02 -#define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS 0x04 -#define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST 0x08 -#define L2CAP_FLAG_CONFIG_INTERRUPT_REQUEST 0x10 -#define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS 0x20 -#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE 0x40 -#define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE 0x80 - -/*Macros for L2CAP event flag tests */ -#define l2cap_connection_request_control_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_CONTROL_REQUEST) -#define l2cap_config_request_control_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_CONTROL_REQUEST) -#define l2cap_config_success_control_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_CONTROL_SUCCESS) -#define l2cap_connection_request_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST) -#define l2cap_config_request_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_INTERRUPT_REQUEST) -#define l2cap_config_success_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS) -#define l2cap_disconnect_response_control_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE) -#define l2cap_disconnect_response_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) +#define HID_BUFFERSIZE 50 // Size of the buffer for the Playstation Motion Controller /** * This BluetoothService class implements support for all the official PS3 Controllers: @@ -249,7 +216,7 @@ private: /* variables used by high level L2CAP task */ uint8_t l2cap_state; - uint16_t l2cap_event_flag; // L2CAP flags of received Bluetooth events + uint32_t l2cap_event_flag; // L2CAP flags of received Bluetooth events unsigned long timer; diff --git a/SPP.h b/SPP.h index 201fb77b..47493fd5 100644 --- a/SPP.h +++ b/SPP.h @@ -20,41 +20,6 @@ #include "BTD.h" -/* Bluetooth L2CAP states for SDP_task() */ -#define L2CAP_SDP_WAIT 0 -#define L2CAP_SDP_REQUEST 1 -#define L2CAP_SDP_SUCCESS 2 -#define L2CAP_SDP_DONE 3 -#define L2CAP_DISCONNECT_RESPONSE 4 - -/* Bluetooth L2CAP states for RFCOMM_task() */ -#define L2CAP_RFCOMM_WAIT 0 -#define L2CAP_RFCOMM_REQUEST 1 -#define L2CAP_RFCOMM_SUCCESS 2 -#define L2CAP_RFCOMM_DONE 3 - -/* L2CAP event flags */ -#define L2CAP_FLAG_CONNECTION_SDP_REQUEST 0x001 -#define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST 0x002 -#define L2CAP_FLAG_CONFIG_SDP_REQUEST 0x004 -#define L2CAP_FLAG_CONFIG_RFCOMM_REQUEST 0x008 -#define L2CAP_FLAG_CONFIG_SDP_SUCCESS 0x010 -#define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS 0x020 -#define L2CAP_FLAG_DISCONNECT_SDP_REQUEST 0x040 -#define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST 0x080 -#define L2CAP_FLAG_DISCONNECT_RESPONSE 0x100 - -/* Macros for L2CAP event flag tests */ -#define l2cap_connection_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_SDP_REQUEST) -#define l2cap_connection_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST) -#define l2cap_config_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_SDP_REQUEST) -#define l2cap_config_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_RFCOMM_REQUEST) -#define l2cap_config_success_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_SDP_SUCCESS) -#define l2cap_config_success_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS) -#define l2cap_disconnect_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_SDP_REQUEST) -#define l2cap_disconnect_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST) -#define l2cap_disconnect_response_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_RESPONSE) - /* Used for SDP */ #define SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST_PDU 0x06 // See the RFCOMM specs #define SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU 0x07 // See the RFCOMM specs @@ -91,7 +56,7 @@ /** * This BluetoothService class implements the Serial Port Protocol (SPP). - * It inherits the Arduino Stream class. This allows it to use all the standard Arduino print functions. + * It inherits the Arduino Stream class. This allows it to use all the standard Arduino print and stream functions. */ class SPP : public BluetoothService, public Stream { public: @@ -201,7 +166,7 @@ private: /* Variables used by L2CAP state machines */ uint8_t l2cap_sdp_state; uint8_t l2cap_rfcomm_state; - uint16_t l2cap_event_flag; // l2cap flags of received Bluetooth events + uint32_t l2cap_event_flag; // l2cap flags of received Bluetooth events uint8_t l2capoutbuf[BULK_MAXPKTSIZE]; // General purpose buffer for l2cap out data uint8_t rfcommbuf[10]; // Buffer for RFCOMM Commands diff --git a/Wii.cpp b/Wii.cpp index d55d4e79..73e638d1 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -375,7 +375,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { Notify(PSTR("\r\nInactive Wii Motion Plus"), 0x80); Notify(PSTR("\r\nPlease unplug the Motion Plus, disconnect the Wiimote and then replug the Motion Plus Extension"), 0x80); #endif - stateCounter = 300; // Skip the rest in "L2CAP_CHECK_MOTION_PLUS_STATE" + stateCounter = 300; // Skip the rest in "WII_CHECK_MOTION_PLUS_STATE" } else if (l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x01 && l2capinbuf[20] == 0x20) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nWii U Pro Controller connected"), 0x80); @@ -648,7 +648,7 @@ void WII::L2CAP_task() { pBtd->connectToWii = false; pBtd->pairWithWii = false; stateCounter = 0; - l2cap_state = L2CAP_CHECK_MOTION_PLUS_STATE; + l2cap_state = WII_CHECK_MOTION_PLUS_STATE; } break; @@ -711,7 +711,7 @@ void WII::Run() { } break; - case L2CAP_CHECK_MOTION_PLUS_STATE: + case WII_CHECK_MOTION_PLUS_STATE: #ifdef DEBUG_USB_HOST if (stateCounter == 0) // Only print onnce Notify(PSTR("\r\nChecking if a Motion Plus is connected"), 0x80); @@ -721,7 +721,7 @@ void WII::Run() { checkMotionPresent(); // Check if there is a motion plus connected if (motion_plus_connected_flag) { stateCounter = 0; - l2cap_state = L2CAP_INIT_MOTION_PLUS_STATE; + l2cap_state = WII_INIT_MOTION_PLUS_STATE; timer = micros(); if (unknownExtensionConnected) { @@ -736,11 +736,11 @@ void WII::Run() { Notify(PSTR("\r\nNo Motion Plus was detected"), 0x80); #endif stateCounter = 0; - l2cap_state = L2CAP_CHECK_EXTENSION_STATE; + l2cap_state = WII_CHECK_EXTENSION_STATE; } break; - case L2CAP_CHECK_EXTENSION_STATE: // This is used to check if there is anything plugged in to the extension port + case WII_CHECK_EXTENSION_STATE: // This is used to check if there is anything plugged in to the extension port #ifdef DEBUG_USB_HOST if (stateCounter == 0) // Only print onnce Notify(PSTR("\r\nChecking if there is any extension connected"), 0x80); @@ -760,11 +760,11 @@ void WII::Run() { unknownExtensionConnected = false; } else if (stateCounter == 400) { stateCounter = 0; - l2cap_state = L2CAP_LED_STATE; + l2cap_state = TURN_ON_LED; } break; - case L2CAP_INIT_MOTION_PLUS_STATE: + case WII_INIT_MOTION_PLUS_STATE: stateCounter++; if (stateCounter == 1) initMotionPlus(); @@ -775,11 +775,11 @@ void WII::Run() { else if (stateCounter == 300) { stateCounter = 0; unknownExtensionConnected = false; // The motion plus will send a status report when it's activated, we will set this to false so it doesn't reinitialize the Motion Plus - l2cap_state = L2CAP_LED_STATE; + l2cap_state = TURN_ON_LED; } break; - case L2CAP_LED_STATE: + case TURN_ON_LED: if (nunchuck_connected_flag) nunchuckConnected = true; wiimoteConnected = true; diff --git a/Wii.h b/Wii.h index 397b837f..0d8f7c96 100755 --- a/Wii.h +++ b/Wii.h @@ -26,55 +26,12 @@ /** You will have to uncomment this to use the IR camera */ //#define WIICAMERA -/* Bluetooth L2CAP states for L2CAP_task() */ -#define L2CAP_WAIT 0 - -// These states are used if the Wiimote is the host -#define L2CAP_CONTROL_SUCCESS 1 -#define L2CAP_INTERRUPT_SETUP 2 - -// These states are used if the Arduino is the host -#define L2CAP_CONTROL_CONNECT_REQUEST 3 -#define L2CAP_CONTROL_CONFIG_REQUEST 4 -#define L2CAP_INTERRUPT_CONNECT_REQUEST 5 - -#define L2CAP_INTERRUPT_CONFIG_REQUEST 6 - -#define L2CAP_CHECK_MOTION_PLUS_STATE 7 -#define L2CAP_CHECK_EXTENSION_STATE 8 -#define L2CAP_INIT_MOTION_PLUS_STATE 9 -#define L2CAP_LED_STATE 10 -#define L2CAP_DONE 11 - -#define L2CAP_INTERRUPT_DISCONNECT 12 -#define L2CAP_CONTROL_DISCONNECT 13 - -/* L2CAP event flags */ -#define L2CAP_FLAG_CONTROL_CONNECTED 0x001 -#define L2CAP_FLAG_INTERRUPT_CONNECTED 0x002 -#define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS 0x004 -#define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS 0x008 -#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE 0x040 -#define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE 0x080 -#define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST 0x100 -#define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST 0x200 - -/* Macros for L2CAP event flag tests */ -#define l2cap_connected_control_flag (l2cap_event_flag & L2CAP_FLAG_CONTROL_CONNECTED) -#define l2cap_connected_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_INTERRUPT_CONNECTED) -#define l2cap_config_success_control_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_CONTROL_SUCCESS) -#define l2cap_config_success_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS) -#define l2cap_disconnect_response_control_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE) -#define l2cap_disconnect_response_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) -#define l2cap_connection_request_control_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_CONTROL_REQUEST) -#define l2cap_connection_request_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST) - /* Wii event flags */ -#define WII_FLAG_MOTION_PLUS_CONNECTED 0x400 -#define WII_FLAG_NUNCHUCK_CONNECTED 0x800 +#define WII_FLAG_MOTION_PLUS_CONNECTED 0x01 +#define WII_FLAG_NUNCHUCK_CONNECTED 0x02 -#define motion_plus_connected_flag (l2cap_event_flag & WII_FLAG_MOTION_PLUS_CONNECTED) -#define nunchuck_connected_flag (l2cap_event_flag & WII_FLAG_NUNCHUCK_CONNECTED) +#define motion_plus_connected_flag (wii_event_flag & WII_FLAG_MOTION_PLUS_CONNECTED) +#define nunchuck_connected_flag (wii_event_flag & WII_FLAG_NUNCHUCK_CONNECTED) /** Enum used to read the joystick on the Nunchuck. */ enum Hat { @@ -447,7 +404,8 @@ private: /* Variables used by high level L2CAP task */ uint8_t l2cap_state; - uint16_t l2cap_event_flag; // l2cap flags of received Bluetooth events + uint32_t l2cap_event_flag; // L2CAP flags of received Bluetooth events + uint8_t wii_event_flag; // Used for Wii flags uint32_t ButtonState; uint32_t OldButtonState; From 809e80a1b092d56745b7ac502d772cf9781a9ae0 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 11 Dec 2013 09:59:58 +0100 Subject: [PATCH 024/145] Clear and set flags in a more readable way --- BTD.h | 25 +++--------------------- BTHID.cpp | 34 ++++++++++++++++---------------- PS3BT.cpp | 24 +++++++++++------------ SPP.cpp | 58 +++++++++++++++++++++++++++---------------------------- Wii.cpp | 48 ++++++++++++++++++++++----------------------- Wii.h | 5 +++-- 6 files changed, 88 insertions(+), 106 deletions(-) diff --git a/BTD.h b/BTD.h index c4293327..b18ed8c3 100755 --- a/BTD.h +++ b/BTD.h @@ -165,28 +165,9 @@ #define L2CAP_FLAG_DISCONNECT_RESPONSE 0x00010000 /* Macros for L2CAP event flag tests */ - -#define l2cap_connection_request_control_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_CONTROL_REQUEST) -#define l2cap_config_success_control_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_CONTROL_SUCCESS) -#define l2cap_connected_control_flag (l2cap_event_flag & L2CAP_FLAG_CONTROL_CONNECTED) -#define l2cap_disconnect_response_control_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE) - -#define l2cap_connection_request_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST) -#define l2cap_config_success_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS) -#define l2cap_connected_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_INTERRUPT_CONNECTED) -#define l2cap_disconnect_response_interrupt_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) - -#define l2cap_connection_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_SDP_REQUEST) -#define l2cap_config_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_SDP_REQUEST) -#define l2cap_config_success_sdp_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_SDP_SUCCESS) -#define l2cap_disconnect_request_sdp_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_SDP_REQUEST) - -#define l2cap_connection_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST) -#define l2cap_config_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_RFCOMM_REQUEST) -#define l2cap_config_success_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS) -#define l2cap_disconnect_request_rfcomm_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST) - -#define l2cap_disconnect_response_flag (l2cap_event_flag & L2CAP_FLAG_DISCONNECT_RESPONSE) +#define l2cap_check_flag(flag) (l2cap_event_flag & flag) +#define l2cap_set_flag(flag) (l2cap_event_flag |= flag) +#define l2cap_clear_flag(flag) (l2cap_event_flag &= ~flag) /* L2CAP signaling commands */ #define L2CAP_CMD_COMMAND_REJECT 0x01 diff --git a/BTHID.cpp b/BTHID.cpp index ab1617dc..f410bcc2 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -94,13 +94,13 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[12]; control_scid[1] = l2capinbuf[13]; - l2cap_event_flag |= L2CAP_FLAG_CONTROL_CONNECTED; + l2cap_set_flag(L2CAP_FLAG_CONTROL_CONNECTED); } else if (l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80); identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[12]; interrupt_scid[1] = l2capinbuf[13]; - l2cap_event_flag |= L2CAP_FLAG_INTERRUPT_CONNECTED; + l2cap_set_flag(L2CAP_FLAG_INTERRUPT_CONNECTED); } } } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { @@ -120,23 +120,23 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[14]; control_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_CONTROL_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST); } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[14]; interrupt_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST); } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_CONTROL_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS); } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS); } } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { @@ -167,11 +167,11 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { if (l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE); } else if (l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE); } } #ifdef EXTRADEBUG @@ -251,7 +251,7 @@ void BTHID::L2CAP_task() { switch (l2cap_state) { /* These states are used if the HID device is the host */ case L2CAP_CONTROL_SUCCESS: - if (l2cap_config_success_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80); #endif @@ -261,7 +261,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_SETUP: - if (l2cap_connection_request_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80); #endif @@ -278,7 +278,7 @@ void BTHID::L2CAP_task() { /* These states are used if the Arduino is the host */ case L2CAP_CONTROL_CONNECT_REQUEST: - if (l2cap_connected_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Control Config Request"), 0x80); #endif @@ -289,7 +289,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_CONTROL_CONFIG_REQUEST: - if (l2cap_config_success_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { setProtocol(); // Set protocol before establishing HID interrupt channel delay(1); // Short delay between commands - just to be sure #ifdef DEBUG_USB_HOST @@ -302,7 +302,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_CONNECT_REQUEST: - if (l2cap_connected_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80); #endif @@ -313,7 +313,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_CONFIG_REQUEST: - if (l2cap_config_success_interrupt_flag) { // Now the HID channels is established + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Channels Established"), 0x80); #endif @@ -329,7 +329,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_DISCONNECT: - if (l2cap_disconnect_response_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80); #endif @@ -340,7 +340,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_CONTROL_DISCONNECT: - if (l2cap_disconnect_response_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Control Channel"), 0x80); #endif @@ -367,7 +367,7 @@ void BTHID::Run() { identifier = 0; pBtd->l2cap_connection_request(hci_handle, identifier, control_dcid, HID_CTRL_PSM); l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST; - } else if (l2cap_connection_request_control_flag) { + } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80); #endif diff --git a/PS3BT.cpp b/PS3BT.cpp index a56efa73..6edd4ca7 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -285,21 +285,21 @@ void PS3BT::ACLData(uint8_t* ACLData) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[14]; control_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_CONTROL_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST); } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[14]; interrupt_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST); } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80); - l2cap_event_flag |= L2CAP_FLAG_CONFIG_CONTROL_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS); } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80); - l2cap_event_flag |= L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS); } } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { @@ -330,11 +330,11 @@ void PS3BT::ACLData(uint8_t* ACLData) { if (l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE); } else if (l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE); } } #ifdef EXTRADEBUG @@ -378,7 +378,7 @@ void PS3BT::ACLData(uint8_t* ACLData) { void PS3BT::L2CAP_task() { switch (l2cap_state) { case L2CAP_WAIT: - if (l2cap_connection_request_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80); #endif @@ -393,7 +393,7 @@ void PS3BT::L2CAP_task() { break; case L2CAP_CONTROL_SUCCESS: - if (l2cap_config_success_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80); #endif @@ -402,7 +402,7 @@ void PS3BT::L2CAP_task() { break; case L2CAP_INTERRUPT_SETUP: - if (l2cap_connection_request_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80); #endif @@ -418,7 +418,7 @@ void PS3BT::L2CAP_task() { break; case L2CAP_INTERRUPT_CONFIG_REQUEST: - if (l2cap_config_success_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Successfully Configured"), 0x80); #endif @@ -434,7 +434,7 @@ void PS3BT::L2CAP_task() { /* These states are handled in Run() */ case L2CAP_INTERRUPT_DISCONNECT: - if (l2cap_disconnect_response_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80); #endif @@ -445,7 +445,7 @@ void PS3BT::L2CAP_task() { break; case L2CAP_CONTROL_DISCONNECT: - if (l2cap_disconnect_response_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Control Channel"), 0x80); #endif diff --git a/SPP.cpp b/SPP.cpp index f0a83927..7a13ca1d 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -131,52 +131,52 @@ void SPP::ACLData(uint8_t* l2capinbuf) { identifier = l2capinbuf[9]; sdp_scid[0] = l2capinbuf[14]; sdp_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_SDP_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST); } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == RFCOMM_PSM) { // ----- || ----- identifier = l2capinbuf[9]; rfcomm_scid[0] = l2capinbuf[14]; rfcomm_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST); } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { //Notify(PSTR("\r\nSDP Configuration Complete"), 0x80); - l2cap_event_flag |= L2CAP_FLAG_CONFIG_SDP_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS); } else if (l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { //Notify(PSTR("\r\nRFCOMM Configuration Complete"), 0x80); - l2cap_event_flag |= L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS); } } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { //Notify(PSTR("\r\nSDP Configuration Request"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_SDP_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONFIG_SDP_REQUEST); } else if (l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { //Notify(PSTR("\r\nRFCOMM Configuration Request"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_RFCOMM_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONFIG_RFCOMM_REQUEST); } } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { //Notify(PSTR("\r\nDisconnect Request: SDP Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_SDP_REQUEST; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST); } else if (l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { //Notify(PSTR("\r\nDisconnect Request: RFCOMM Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST); } } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { if (l2capinbuf[12] == sdp_scid[0] && l2capinbuf[13] == sdp_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: SDP Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RESPONSE); } else if (l2capinbuf[12] == rfcomm_scid[0] && l2capinbuf[13] == rfcomm_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: RFCOMM Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RESPONSE); } } else if (l2capinbuf[8] == L2CAP_CMD_INFORMATION_REQUEST) { #ifdef DEBUG_USB_HOST @@ -442,8 +442,8 @@ void SPP::Run() { void SPP::SDP_task() { switch (l2cap_sdp_state) { case L2CAP_SDP_WAIT: - if (l2cap_connection_request_sdp_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_CONNECTION_SDP_REQUEST; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSDP Incoming Connection Request"), 0x80); #endif @@ -457,8 +457,8 @@ void SPP::SDP_task() { } break; case L2CAP_SDP_REQUEST: - if (l2cap_config_request_sdp_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_CONFIG_SDP_REQUEST; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_SDP_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_CONFIG_SDP_REQUEST); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSDP Configuration Request"), 0x80); #endif @@ -467,8 +467,8 @@ void SPP::SDP_task() { } break; case L2CAP_SDP_SUCCESS: - if (l2cap_config_success_sdp_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_CONFIG_SDP_SUCCESS; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS)) { + l2cap_clear_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSDP Successfully Configured"), 0x80); #endif @@ -478,19 +478,19 @@ void SPP::SDP_task() { } break; case L2CAP_SDP_DONE: - if (l2cap_disconnect_request_sdp_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_DISCONNECT_SDP_REQUEST; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST); // Clear flag SDPConnected = false; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected SDP Channel"), 0x80); #endif pBtd->l2cap_disconnection_response(hci_handle, identifier, sdp_dcid, sdp_scid); l2cap_sdp_state = L2CAP_SDP_WAIT; - } else if (l2cap_connection_request_sdp_flag) + } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST)) l2cap_rfcomm_state = L2CAP_SDP_WAIT; break; case L2CAP_DISCONNECT_RESPONSE: // This is for both disconnection response from the RFCOMM and SDP channel if they were connected - if (l2cap_disconnect_response_flag) { + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected L2CAP Connection"), 0x80); #endif @@ -509,8 +509,8 @@ void SPP::SDP_task() { void SPP::RFCOMM_task() { switch (l2cap_rfcomm_state) { case L2CAP_RFCOMM_WAIT: - if (l2cap_connection_request_rfcomm_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRFCOMM Incoming Connection Request"), 0x80); #endif @@ -524,8 +524,8 @@ void SPP::RFCOMM_task() { } break; case L2CAP_RFCOMM_REQUEST: - if (l2cap_config_request_rfcomm_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_CONFIG_RFCOMM_REQUEST; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_RFCOMM_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_CONFIG_RFCOMM_REQUEST); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRFCOMM Configuration Request"), 0x80); #endif @@ -534,8 +534,8 @@ void SPP::RFCOMM_task() { } break; case L2CAP_RFCOMM_SUCCESS: - if (l2cap_config_success_rfcomm_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS)) { + l2cap_clear_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRFCOMM Successfully Configured"), 0x80); #endif @@ -546,8 +546,8 @@ void SPP::RFCOMM_task() { } break; case L2CAP_RFCOMM_DONE: - if (l2cap_disconnect_request_rfcomm_flag) { - l2cap_event_flag &= ~L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST; // Clear flag + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST); // Clear flag RFCOMMConnected = false; connected = false; #ifdef DEBUG_USB_HOST @@ -555,7 +555,7 @@ void SPP::RFCOMM_task() { #endif pBtd->l2cap_disconnection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid); l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; - } else if (l2cap_connection_request_rfcomm_flag) + } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST)) l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; break; } diff --git a/Wii.cpp b/Wii.cpp index 73e638d1..02cddecf 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -168,13 +168,13 @@ void WII::ACLData(uint8_t* l2capinbuf) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[12]; control_scid[1] = l2capinbuf[13]; - l2cap_event_flag |= L2CAP_FLAG_CONTROL_CONNECTED; + l2cap_set_flag(L2CAP_FLAG_CONTROL_CONNECTED); } else if (l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80); identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[12]; interrupt_scid[1] = l2capinbuf[13]; - l2cap_event_flag |= L2CAP_FLAG_INTERRUPT_CONNECTED; + l2cap_set_flag(L2CAP_FLAG_INTERRUPT_CONNECTED); } } } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { @@ -194,23 +194,23 @@ void WII::ACLData(uint8_t* l2capinbuf) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[14]; control_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_CONTROL_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST); } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[14]; interrupt_scid[1] = l2capinbuf[15]; - l2cap_event_flag |= L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST; + l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST); } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_CONTROL_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS); } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS; + l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS); } } } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { @@ -241,11 +241,11 @@ void WII::ACLData(uint8_t* l2capinbuf) { if (l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE); } else if (l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80); identifier = l2capinbuf[9]; - l2cap_event_flag |= L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE; + l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE); } } #ifdef EXTRADEBUG @@ -319,7 +319,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { #ifdef DEBUG_USB_HOST Notify(PSTR(" - from Motion Plus"), 0x80); #endif - l2cap_event_flag &= ~WII_FLAG_NUNCHUCK_CONNECTED; + wii_clear_flag(WII_FLAG_NUNCHUCK_CONNECTED); if (!activateNunchuck) // If it's already trying to initialize the Nunchuck don't set it to false nunchuckConnected = false; //else if(classicControllerConnected) @@ -328,7 +328,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" - Nunchuck"), 0x80); #endif nunchuckConnected = false; // It must be the Nunchuck controller then - l2cap_event_flag &= ~WII_FLAG_NUNCHUCK_CONNECTED; + wii_clear_flag(WII_FLAG_NUNCHUCK_CONNECTED); onInit(); setReportMode(false, 0x31); // If there is no extension connected we will read the buttons and accelerometer } else @@ -344,12 +344,12 @@ void WII::ACLData(uint8_t* l2capinbuf) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nNunchuck connected"), 0x80); #endif - l2cap_event_flag |= WII_FLAG_NUNCHUCK_CONNECTED; + wii_set_flag(WII_FLAG_NUNCHUCK_CONNECTED); } else if (l2capinbuf[16] == 0x00 && (l2capinbuf[17] == 0xA6 || l2capinbuf[17] == 0xA4) && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x00 && l2capinbuf[20] == 0x05) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nMotion Plus connected"), 0x80); #endif - l2cap_event_flag |= WII_FLAG_MOTION_PLUS_CONNECTED; + wii_set_flag(WII_FLAG_MOTION_PLUS_CONNECTED); } else if (l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x04 && l2capinbuf[20] == 0x05) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nMotion Plus activated in normal mode"), 0x80); @@ -582,7 +582,7 @@ void WII::L2CAP_task() { switch (l2cap_state) { /* These states are used if the Wiimote is the host */ case L2CAP_CONTROL_SUCCESS: - if (l2cap_config_success_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80); #endif @@ -591,7 +591,7 @@ void WII::L2CAP_task() { break; case L2CAP_INTERRUPT_SETUP: - if (l2cap_connection_request_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80); #endif @@ -608,7 +608,7 @@ void WII::L2CAP_task() { /* These states are used if the Arduino is the host */ case L2CAP_CONTROL_CONNECT_REQUEST: - if (l2cap_connected_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Control Config Request"), 0x80); #endif @@ -619,7 +619,7 @@ void WII::L2CAP_task() { break; case L2CAP_CONTROL_CONFIG_REQUEST: - if (l2cap_config_success_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Interrupt Connection Request"), 0x80); #endif @@ -630,7 +630,7 @@ void WII::L2CAP_task() { break; case L2CAP_INTERRUPT_CONNECT_REQUEST: - if (l2cap_connected_interrupt_flag) { + if (l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80); #endif @@ -641,7 +641,7 @@ void WII::L2CAP_task() { break; case L2CAP_INTERRUPT_CONFIG_REQUEST: - if (l2cap_config_success_interrupt_flag) { // Now the HID channels is established + if (l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Channels Established"), 0x80); #endif @@ -655,7 +655,7 @@ void WII::L2CAP_task() { /* The next states are in run() */ case L2CAP_INTERRUPT_DISCONNECT: - if (l2cap_disconnect_response_interrupt_flag && millis() > timer) { + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) && millis() > timer) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80); #endif @@ -666,7 +666,7 @@ void WII::L2CAP_task() { break; case L2CAP_CONTROL_DISCONNECT: - if (l2cap_disconnect_response_control_flag) { + if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Control Channel"), 0x80); #endif @@ -697,7 +697,7 @@ void WII::Run() { identifier = 0; pBtd->l2cap_connection_request(hci_handle, identifier, control_dcid, HID_CTRL_PSM); l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST; - } else if (l2cap_connection_request_control_flag) { + } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80); #endif @@ -719,7 +719,7 @@ void WII::Run() { stateCounter++; if (stateCounter % 200 == 0) checkMotionPresent(); // Check if there is a motion plus connected - if (motion_plus_connected_flag) { + if (wii_check_flag(WII_FLAG_MOTION_PLUS_CONNECTED)) { stateCounter = 0; l2cap_state = WII_INIT_MOTION_PLUS_STATE; timer = micros(); @@ -780,7 +780,7 @@ void WII::Run() { break; case TURN_ON_LED: - if (nunchuck_connected_flag) + if (wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED)) nunchuckConnected = true; wiimoteConnected = true; onInit(); @@ -806,7 +806,7 @@ void WII::Run() { else if (stateCounter == 200) readExtensionType(); else if (stateCounter == 250) { - if (nunchuck_connected_flag) { + if (wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nNunchuck was reconnected"), 0x80); #endif diff --git a/Wii.h b/Wii.h index 0d8f7c96..06a74ee5 100755 --- a/Wii.h +++ b/Wii.h @@ -30,8 +30,9 @@ #define WII_FLAG_MOTION_PLUS_CONNECTED 0x01 #define WII_FLAG_NUNCHUCK_CONNECTED 0x02 -#define motion_plus_connected_flag (wii_event_flag & WII_FLAG_MOTION_PLUS_CONNECTED) -#define nunchuck_connected_flag (wii_event_flag & WII_FLAG_NUNCHUCK_CONNECTED) +#define wii_check_flag(flag) (wii_event_flag & flag) +#define wii_set_flag(flag) (wii_event_flag |= flag) +#define wii_clear_flag(flag) (wii_event_flag &= ~flag) /** Enum used to read the joystick on the Nunchuck. */ enum Hat { From dec1a31bc7fddc48bf43d4ef3bae74fd4dcd845e Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 11 Dec 2013 10:06:40 +0100 Subject: [PATCH 025/145] Updated some comments --- BTD.cpp | 47 ++++++++++++++++++++--------------------------- 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 62a96b70..83edb198 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -388,11 +388,11 @@ void BTD::HCI_event_task() { { case EV_COMMAND_COMPLETE: if (!hcibuf[5]) { // Check if command succeeded - hci_event_flag |= HCI_FLAG_CMD_COMPLETE; // set command complete flag - if ((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // parameters from read local version information + hci_event_flag |= HCI_FLAG_CMD_COMPLETE; // Set command complete flag + if ((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm hci_event_flag |= HCI_FLAG_READ_VERSION; - } else if ((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // parameters from read local bluetooth address + } else if ((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address for (uint8_t i = 0; i < 6; i++) my_bdaddr[i] = hcibuf[6 + i]; hci_event_flag |= HCI_FLAG_READ_BDADDR; @@ -440,7 +440,7 @@ void BTD::HCI_event_task() { for (uint8_t j = 0; j < 3; j++) classOfDevice[j] = hcibuf[j + 4 + offset]; - if (pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0x0C)) { // See http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html and http://wiibrew.org/wiki/Wiimote#SDP_information + if (pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information if (classOfDevice[0] & 0x08) // Check if it's the new Wiimote with motion plus inside that was detected motionPlusInside = true; else @@ -451,7 +451,7 @@ void BTD::HCI_event_task() { hci_event_flag |= HCI_FLAG_DEVICE_FOUND; break; - } else if (pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC0)) { // Check if it is a mouse or keyboard + } else if (pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC0)) { // Check if it is a mouse or keyboard - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html #ifdef DEBUG_USB_HOST if (classOfDevice[0] & 0x80) Notify(PSTR("\r\nMouse found"), 0x80); @@ -480,12 +480,12 @@ void BTD::HCI_event_task() { case EV_CONNECT_COMPLETE: hci_event_flag |= HCI_FLAG_CONNECT_EVENT; - if (!hcibuf[2]) { // check if connected OK + if (!hcibuf[2]) { // Check if connected OK #ifdef EXTRADEBUG Notify(PSTR("\r\nConnection established"), 0x80); #endif - hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // store the handle for the ACL connection - hci_event_flag |= HCI_FLAG_CONN_COMPLETE; // set connection complete flag + hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // Store the handle for the ACL connection + hci_event_flag |= HCI_FLAG_CONN_COMPLETE; // Set connection complete flag } else { hci_state = HCI_CHECK_DEVICE_SERVICE; #ifdef DEBUG_USB_HOST @@ -496,9 +496,9 @@ void BTD::HCI_event_task() { break; case EV_DISCONNECT_COMPLETE: - if (!hcibuf[2]) { // check if disconnected OK - hci_event_flag |= HCI_FLAG_DISCONN_COMPLETE; // set disconnect command complete flag - hci_event_flag &= ~HCI_FLAG_CONN_COMPLETE; // clear connection complete flag + if (!hcibuf[2]) { // Check if disconnected OK + hci_event_flag |= HCI_FLAG_DISCONN_COMPLETE; // Set disconnect command complete flag + hci_event_flag &= ~HCI_FLAG_CONN_COMPLETE; // Clear connection complete flag } break; @@ -567,12 +567,12 @@ void BTD::HCI_event_task() { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nPairing successful with Wiimote"), 0x80); #endif - connectToWii = true; // Only send the ACL data to the Wii service + connectToWii = true; // Used to indicate to the Wii service, that it should connect to this device } else if (pairWithHIDDevice && !connectToHIDDevice) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nPairing successful with HID device"), 0x80); #endif - connectToHIDDevice = true; // Only send the ACL data to the Wii service + connectToHIDDevice = true; // Used to indicate to the BTHID service, that it should connect to this device } break; /* We will just ignore the following events */ @@ -596,7 +596,7 @@ void BTD::HCI_event_task() { } break; #endif - } // switch + } // Switch } #ifdef EXTRADEBUG else { @@ -686,7 +686,7 @@ void BTD::HCI_task() { break; case HCI_CHECK_DEVICE_SERVICE: - if (pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a wiimote + if (pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote #ifdef DEBUG_USB_HOST if (pairWithWii) Notify(PSTR("\r\nStarting inquiry\r\nPress 1 & 2 on the Wiimote\r\nOr press sync if you are using a Wii U Pro Controller"), 0x80); @@ -750,7 +750,7 @@ void BTD::HCI_task() { else Notify(PSTR("\r\nConnected to HID device"), 0x80); #endif - hci_authentication_request(); // This will start the pairing with the wiimote + hci_authentication_request(); // This will start the pairing with the Wiimote hci_state = HCI_SCANNING_STATE; } else { #ifdef DEBUG_USB_HOST @@ -860,18 +860,11 @@ void BTD::HCI_task() { hci_event_flag = 0; // Clear all flags // Reset all buffers - for (uint8_t i = 0; i < BULK_MAXPKTSIZE; i++) - hcibuf[i] = 0; - for (uint8_t i = 0; i < BULK_MAXPKTSIZE; i++) - l2capinbuf[i] = 0; + memset(hcibuf, 0, BULK_MAXPKTSIZE); + memset(l2capinbuf, 0, BULK_MAXPKTSIZE); - connectToWii = false; - incomingWii = false; - pairWithWii = false; - - connectToHIDDevice = false; - incomingHIDDevice = false; - pairWithHIDDevice = false; + connectToWii = incomingWii = pairWithWii = false; + connectToHIDDevice = incomingHIDDevice = pairWithHIDDevice = false; hci_state = HCI_SCANNING_STATE; } From 712bc3818d0a49b80e8cc77fedd28b204ea40440 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 11 Dec 2013 10:10:12 +0100 Subject: [PATCH 026/145] Fixed warning Check if we are at the end of the string properly --- BTD.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 83edb198..776774fe 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -503,9 +503,12 @@ void BTD::HCI_event_task() { break; case EV_REMOTE_NAME_COMPLETE: - if (!hcibuf[2]) { // check if reading is OK - for (uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) + if (!hcibuf[2]) { // Check if reading is OK + for (uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) { remote_name[i] = hcibuf[9 + i]; + if (remote_name[i] == '\0') // End of string + break; + } hci_event_flag |= HCI_FLAG_REMOTE_NAME_COMPLETE; } break; @@ -789,7 +792,7 @@ void BTD::HCI_task() { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRemote Name: "), 0x80); for (uint8_t i = 0; i < 30; i++) { - if (remote_name[i] == NULL) + if (remote_name[i] == '\0') // End of string break; Notifyc(remote_name[i], 0x80); } From 6909ecd6b8e27d73f9524cabfee0149475e88510 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 11 Dec 2013 10:37:18 +0100 Subject: [PATCH 027/145] Use more readable macros in the BTD class as well --- BTD.cpp | 66 +++++++++++++++++++++++++++++---------------------------- BTD.h | 25 ++++++++++------------ 2 files changed, 45 insertions(+), 46 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 776774fe..286c2c78 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -388,14 +388,14 @@ void BTD::HCI_event_task() { { case EV_COMMAND_COMPLETE: if (!hcibuf[5]) { // Check if command succeeded - hci_event_flag |= HCI_FLAG_CMD_COMPLETE; // Set command complete flag + hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag if ((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm - hci_event_flag |= HCI_FLAG_READ_VERSION; + hci_set_flag(HCI_FLAG_READ_VERSION); } else if ((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address for (uint8_t i = 0; i < 6; i++) my_bdaddr[i] = hcibuf[6 + i]; - hci_event_flag |= HCI_FLAG_READ_BDADDR; + hci_set_flag(HCI_FLAG_READ_BDADDR); } } break; @@ -449,7 +449,7 @@ void BTD::HCI_event_task() { for (uint8_t j = 0; j < 6; j++) disc_bdaddr[j] = hcibuf[j + 3 + 6 * i]; - hci_event_flag |= HCI_FLAG_DEVICE_FOUND; + hci_set_flag(HCI_FLAG_DEVICE_FOUND); break; } else if (pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC0)) { // Check if it is a mouse or keyboard - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html #ifdef DEBUG_USB_HOST @@ -462,7 +462,7 @@ void BTD::HCI_event_task() { for (uint8_t j = 0; j < 6; j++) disc_bdaddr[j] = hcibuf[j + 3 + 6 * i]; - hci_event_flag |= HCI_FLAG_DEVICE_FOUND; + hci_set_flag(HCI_FLAG_DEVICE_FOUND); } #ifdef EXTRADEBUG else { @@ -479,13 +479,13 @@ void BTD::HCI_event_task() { break; case EV_CONNECT_COMPLETE: - hci_event_flag |= HCI_FLAG_CONNECT_EVENT; + hci_set_flag(HCI_FLAG_CONNECT_EVENT); if (!hcibuf[2]) { // Check if connected OK #ifdef EXTRADEBUG Notify(PSTR("\r\nConnection established"), 0x80); #endif hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // Store the handle for the ACL connection - hci_event_flag |= HCI_FLAG_CONN_COMPLETE; // Set connection complete flag + hci_set_flag(HCI_FLAG_CONNECT_COMPLETE); // Set connection complete flag } else { hci_state = HCI_CHECK_DEVICE_SERVICE; #ifdef DEBUG_USB_HOST @@ -497,8 +497,8 @@ void BTD::HCI_event_task() { case EV_DISCONNECT_COMPLETE: if (!hcibuf[2]) { // Check if disconnected OK - hci_event_flag |= HCI_FLAG_DISCONN_COMPLETE; // Set disconnect command complete flag - hci_event_flag &= ~HCI_FLAG_CONN_COMPLETE; // Clear connection complete flag + hci_set_flag(HCI_FLAG_DISCONNECT_COMPLETE); // Set disconnect command complete flag + hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); // Clear connection complete flag } break; @@ -509,7 +509,7 @@ void BTD::HCI_event_task() { if (remote_name[i] == '\0') // End of string break; } - hci_event_flag |= HCI_FLAG_REMOTE_NAME_COMPLETE; + hci_set_flag(HCI_FLAG_REMOTE_NAME_COMPLETE); } break; @@ -535,7 +535,7 @@ void BTD::HCI_event_task() { Notify(PSTR(" "), 0x80); D_PrintHex (hcibuf[8], 0x80); #endif - hci_event_flag |= HCI_FLAG_INCOMING_REQUEST; + hci_set_flag(HCI_FLAG_INCOMING_REQUEST); break; case EV_PIN_CODE_REQUEST: @@ -624,7 +624,7 @@ void BTD::HCI_task() { case HCI_RESET_STATE: hci_counter++; - if (hci_cmd_complete) { + if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { hci_counter = 0; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHCI Reset complete"), 0x80); @@ -644,7 +644,7 @@ void BTD::HCI_task() { break; case HCI_CLASS_STATE: - if (hci_cmd_complete) { + if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nWrite class of device"), 0x80); #endif @@ -654,7 +654,7 @@ void BTD::HCI_task() { break; case HCI_BDADDR_STATE: - if (hci_read_bdaddr_complete) { + if (hci_check_flag(HCI_FLAG_READ_BDADDR)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nLocal Bluetooth Address: "), 0x80); for (int8_t i = 5; i > 0; i--) { @@ -669,7 +669,7 @@ void BTD::HCI_task() { break; case HCI_LOCAL_VERSION_STATE: // The local version is used by the PS3BT class - if (hci_read_version_complete) { + if (hci_check_flag(HCI_FLAG_READ_VERSION)) { if (btdName != NULL) { hci_set_local_name(btdName); hci_state = HCI_SET_NAME_STATE; @@ -679,7 +679,7 @@ void BTD::HCI_task() { break; case HCI_SET_NAME_STATE: - if (hci_cmd_complete) { + if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nThe name is set to: "), 0x80); NotifyStr(btdName, 0x80); @@ -703,7 +703,7 @@ void BTD::HCI_task() { break; case HCI_INQUIRY_STATE: - if (hci_device_found) { + if (hci_check_flag(HCI_FLAG_DEVICE_FOUND)) { hci_inquiry_cancel(); // Stop inquiry #ifdef DEBUG_USB_HOST if (pairWithWii) @@ -732,7 +732,7 @@ void BTD::HCI_task() { break; case HCI_CONNECT_DEVICE_STATE: - if (hci_cmd_complete) { + if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { #ifdef DEBUG_USB_HOST if (pairWithWii) Notify(PSTR("\r\nConnecting to Wiimote"), 0x80); @@ -745,8 +745,8 @@ void BTD::HCI_task() { break; case HCI_CONNECTED_DEVICE_STATE: - if (hci_connect_event) { - if (hci_connect_complete) { + if (hci_check_flag(HCI_FLAG_CONNECT_EVENT)) { + if (hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) { #ifdef DEBUG_USB_HOST if (pairWithWii) Notify(PSTR("\r\nConnected to Wiimote"), 0x80); @@ -776,19 +776,19 @@ void BTD::HCI_task() { break; case HCI_CONNECT_IN_STATE: - if (hci_incoming_connect_request) { + if (hci_check_flag(HCI_FLAG_INCOMING_REQUEST)) { watingForConnection = false; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nIncoming Connection Request"), 0x80); #endif hci_remote_name(); hci_state = HCI_REMOTE_NAME_STATE; - } else if (hci_disconnect_complete) + } else if (hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) hci_state = HCI_DISCONNECT_STATE; break; case HCI_REMOTE_NAME_STATE: - if (hci_remote_name_complete) { + if (hci_check_flag(HCI_FLAG_REMOTE_NAME_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRemote Name: "), 0x80); for (uint8_t i = 0; i < 30; i++) { @@ -828,7 +828,7 @@ void BTD::HCI_task() { break; case HCI_CONNECTED_STATE: - if (hci_connect_complete) { + if (hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nConnected to Device: "), 0x80); for (int8_t i = 5; i > 0; i--) { @@ -856,7 +856,7 @@ void BTD::HCI_task() { break; case HCI_DISCONNECT_STATE: - if (hci_disconnect_complete) { + if (hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80); #endif @@ -901,7 +901,7 @@ void BTD::ACL_event_task() { /************************************************************/ void BTD::HCI_Command(uint8_t* data, uint16_t nbytes) { - hci_event_flag &= ~HCI_FLAG_CMD_COMPLETE; + hci_clear_flag(HCI_FLAG_CMD_COMPLETE); pUsb->ctrlReq(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, 0x00, 0x00, 0x00, 0x00, nbytes, nbytes, data, NULL); } @@ -915,7 +915,7 @@ void BTD::hci_reset() { } void BTD::hci_write_scan_enable() { - hci_event_flag &= ~HCI_FLAG_INCOMING_REQUEST; + hci_clear_flag(HCI_FLAG_INCOMING_REQUEST); hcibuf[0] = 0x1A; // HCI OCF = 1A hcibuf[1] = 0x03 << 2; // HCI OGF = 3 hcibuf[2] = 0x01; // parameter length = 1 @@ -937,6 +937,7 @@ void BTD::hci_write_scan_disable() { } void BTD::hci_read_bdaddr() { + hci_clear_flag(HCI_FLAG_READ_BDADDR); hcibuf[0] = 0x09; // HCI OCF = 9 hcibuf[1] = 0x04 << 2; // HCI OGF = 4 hcibuf[2] = 0x00; @@ -945,6 +946,7 @@ void BTD::hci_read_bdaddr() { } void BTD::hci_read_local_version_information() { + hci_clear_flag(HCI_FLAG_READ_VERSION); hcibuf[0] = 0x01; // HCI OCF = 1 hcibuf[1] = 0x04 << 2; // HCI OGF = 4 hcibuf[2] = 0x00; @@ -953,7 +955,7 @@ void BTD::hci_read_local_version_information() { } void BTD::hci_accept_connection() { - hci_event_flag &= ~HCI_FLAG_CONN_COMPLETE; + hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); hcibuf[0] = 0x09; // HCI OCF = 9 hcibuf[1] = 0x01 << 2; // HCI OGF = 1 hcibuf[2] = 0x07; // parameter length 7 @@ -969,7 +971,7 @@ void BTD::hci_accept_connection() { } void BTD::hci_remote_name() { - hci_event_flag &= ~HCI_FLAG_REMOTE_NAME_COMPLETE; + hci_clear_flag(HCI_FLAG_REMOTE_NAME_COMPLETE); hcibuf[0] = 0x19; // HCI OCF = 19 hcibuf[1] = 0x01 << 2; // HCI OGF = 1 hcibuf[2] = 0x0A; // parameter length = 10 @@ -1000,7 +1002,7 @@ void BTD::hci_set_local_name(const char* name) { } void BTD::hci_inquiry() { - hci_event_flag &= ~HCI_FLAG_DEVICE_FOUND; + hci_clear_flag(HCI_FLAG_DEVICE_FOUND); hcibuf[0] = 0x01; hcibuf[1] = 0x01 << 2; // HCI OGF = 1 hcibuf[2] = 0x05; // Parameter Total Length = 5 @@ -1026,7 +1028,7 @@ void BTD::hci_connect() { } void BTD::hci_connect(uint8_t *bdaddr) { - hci_event_flag &= ~(HCI_FLAG_CONN_COMPLETE | HCI_FLAG_CONNECT_EVENT); + hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE | HCI_FLAG_CONNECT_EVENT); hcibuf[0] = 0x05; hcibuf[1] = 0x01 << 2; // HCI OGF = 1 hcibuf[2] = 0x0D; // parameter Total Length = 13 @@ -1122,7 +1124,7 @@ void BTD::hci_authentication_request() { } void BTD::hci_disconnect(uint16_t handle) { // This is called by the different services - hci_event_flag &= ~HCI_FLAG_DISCONN_COMPLETE; + hci_clear_flag(HCI_FLAG_DISCONNECT_COMPLETE); hcibuf[0] = 0x06; // HCI OCF = 6 hcibuf[1] = 0x01 << 2; // HCI OGF = 1 hcibuf[2] = 0x03; // parameter length = 3 diff --git a/BTD.h b/BTD.h index b18ed8c3..becc3da3 100755 --- a/BTD.h +++ b/BTD.h @@ -61,8 +61,8 @@ /* HCI event flags*/ #define HCI_FLAG_CMD_COMPLETE 0x01 -#define HCI_FLAG_CONN_COMPLETE 0x02 -#define HCI_FLAG_DISCONN_COMPLETE 0x04 +#define HCI_FLAG_CONNECT_COMPLETE 0x02 +#define HCI_FLAG_DISCONNECT_COMPLETE 0x04 #define HCI_FLAG_REMOTE_NAME_COMPLETE 0x08 #define HCI_FLAG_INCOMING_REQUEST 0x10 #define HCI_FLAG_READ_BDADDR 0x20 @@ -70,16 +70,10 @@ #define HCI_FLAG_DEVICE_FOUND 0x80 #define HCI_FLAG_CONNECT_EVENT 0x100 -/*Macros for HCI event flag tests */ -#define hci_cmd_complete (hci_event_flag & HCI_FLAG_CMD_COMPLETE) -#define hci_connect_complete (hci_event_flag & HCI_FLAG_CONN_COMPLETE) -#define hci_disconnect_complete (hci_event_flag & HCI_FLAG_DISCONN_COMPLETE) -#define hci_remote_name_complete (hci_event_flag & HCI_FLAG_REMOTE_NAME_COMPLETE) -#define hci_incoming_connect_request (hci_event_flag & HCI_FLAG_INCOMING_REQUEST) -#define hci_read_bdaddr_complete (hci_event_flag & HCI_FLAG_READ_BDADDR) -#define hci_read_version_complete (hci_event_flag & HCI_FLAG_READ_VERSION) -#define hci_device_found (hci_event_flag & HCI_FLAG_DEVICE_FOUND) -#define hci_connect_event (hci_event_flag & HCI_FLAG_CONNECT_EVENT) +/* Macros for HCI event flag tests */ +#define hci_check_flag(flag) (hci_event_flag & flag) +#define hci_set_flag(flag) (hci_event_flag |= flag) +#define hci_clear_flag(flag) (hci_event_flag &= ~flag) /* HCI Events managed */ #define EV_INQUIRY_COMPLETE 0x01 @@ -141,22 +135,25 @@ #define WII_CHECK_EXTENSION_STATE 22 #define WII_INIT_MOTION_PLUS_STATE 23 -/* L2CAP event flags */ +/* L2CAP event flags for HID Control channel */ #define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST 0x00000001 #define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS 0x00000002 #define L2CAP_FLAG_CONTROL_CONNECTED 0x00000004 #define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE 0x00000008 +/* L2CAP event flags for HID Interrupt channel */ #define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST 0x00000010 #define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS 0x00000020 #define L2CAP_FLAG_INTERRUPT_CONNECTED 0x00000040 #define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE 0x00000080 +/* L2CAP event flags for SDP channel */ #define L2CAP_FLAG_CONNECTION_SDP_REQUEST 0x00000100 #define L2CAP_FLAG_CONFIG_SDP_REQUEST 0x00000200 #define L2CAP_FLAG_CONFIG_SDP_SUCCESS 0x00000400 #define L2CAP_FLAG_DISCONNECT_SDP_REQUEST 0x00000800 +/* L2CAP event flags for RFCOMM channel */ #define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST 0x00001000 #define L2CAP_FLAG_CONFIG_RFCOMM_REQUEST 0x00002000 #define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS 0x00004000 @@ -467,7 +464,7 @@ public: /** The name you wish to make the dongle show up as. It is set automatically by the SPP library. */ const char* btdName; - /** The pin you wish to make the dongle use for authentication. It is set automatically by the SPP library. */ + /** The pin you wish to make the dongle use for authentication. It is set automatically by the SPP and BTHID library. */ const char* btdPin; /** The bluetooth dongles Bluetooth address. */ From c1f82e9e47d31e55213aa89c1d37477b4be30a44 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 11 Dec 2013 11:56:05 +0100 Subject: [PATCH 028/145] Check length is larger than 0 before sending data to Bluetooth services --- BTD.cpp | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 286c2c78..8c8093b9 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -372,20 +372,19 @@ uint8_t BTD::Poll() { return 0; if (qNextPollTime <= millis()) { // Don't poll if shorter than polling interval qNextPollTime = millis() + pollInterval; // Set new poll time - HCI_event_task(); // poll the HCI event pipe - ACL_event_task(); // start polling the ACL input pipe too, though discard data until connected + HCI_event_task(); // Poll the HCI event pipe + HCI_task(); // HCI state machine + ACL_event_task(); // Poll the ACL input pipe too } return 0; } void BTD::HCI_event_task() { - /* check the event pipe*/ - uint16_t MAX_BUFFER_SIZE = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this - uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &MAX_BUFFER_SIZE, hcibuf); // input on endpoint 1 - if (!rcode || rcode == hrNAK) // Check for errors - { - switch (hcibuf[0]) //switch on event type - { + uint16_t length = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this + uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &length, hcibuf); // Input on endpoint 1 + + if (!rcode || rcode == hrNAK) { // Check for errors + switch (hcibuf[0]) { // Switch on event type case EV_COMMAND_COMPLETE: if (!hcibuf[5]) { // Check if command succeeded hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag @@ -607,7 +606,6 @@ void BTD::HCI_event_task() { D_PrintHex (rcode, 0x80); } #endif - HCI_task(); } /* Poll Bluetooth and print result */ @@ -878,12 +876,16 @@ void BTD::HCI_task() { } void BTD::ACL_event_task() { - uint16_t MAX_BUFFER_SIZE = BULK_MAXPKTSIZE; - uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &MAX_BUFFER_SIZE, l2capinbuf); // input on endpoint 2 + uint16_t length = BULK_MAXPKTSIZE; + uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf); // Input on endpoint 2 + if (!rcode) { // Check for errors - for (uint8_t i = 0; i < BTD_NUMSERVICES; i++) - if (btService[i]) - btService[i]->ACLData(l2capinbuf); + if (length > 0) { // Check if any data was read + for (uint8_t i = 0; i < BTD_NUMSERVICES; i++) { + if (btService[i]) + btService[i]->ACLData(l2capinbuf); + } + } } #ifdef EXTRADEBUG else if (rcode != hrNAK) { From 6e70087f0bf6f2407a7990208bfb4c4194d38d4a Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 11 Dec 2013 14:15:51 -0500 Subject: [PATCH 029/145] teensy 3.1 support --- settings.h | 2 +- usbhost.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/settings.h b/settings.h index ea114ed3..d49b7aa5 100644 --- a/settings.h +++ b/settings.h @@ -98,7 +98,7 @@ #define XMEM_RELEASE_SPI() (void(0)) #endif -#ifdef __MK20DX128__ +#if defined(__MK20DX128__) || defined(__MK20DX256__) #define USING_SPI4TEENSY3 USE_SPI4TEENSY3 #else #define USING_SPI4TEENSY3 0 diff --git a/usbhost.h b/usbhost.h index bc65e106..81949431 100644 --- a/usbhost.h +++ b/usbhost.h @@ -67,7 +67,7 @@ typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi; typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi; #elif defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) typedef SPi< Pb7, Pb5, Pb6, Pb4 > spi; -#elif defined(__MK20DX128__) +#elif defined(__MK20DX128__) || defined(__MK20DX256__) typedef SPi< P13, P11, P12, P10 > spi; #else #error "No SPI entry in usbhost.h" From 084c3f54788309ff1650157406c795bf88349bc2 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 12 Dec 2013 01:01:50 +0100 Subject: [PATCH 030/145] Removed non-generic case --- BTHID.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index f410bcc2..71e35743 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -204,13 +204,6 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast (this), 0, (uint8_t) length, &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance } break; - - case 0x03: -#ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nChange mode event: "), 0x80); - D_PrintHex (l2capinbuf[11], 0x80); -#endif - break; #ifdef DEBUG_USB_HOST default: Notify(PSTR("\r\nUnknown Report type: "), 0x80); From a7f6b2e4dc9626ee45ea9555cbeb47a5e3d1783f Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 13 Dec 2013 10:35:27 +0100 Subject: [PATCH 031/145] Removed unneeded case --- BTD.h | 9 +++------ SPP.cpp | 28 +++------------------------- 2 files changed, 6 insertions(+), 31 deletions(-) diff --git a/BTD.h b/BTD.h index becc3da3..cfbc2023 100755 --- a/BTD.h +++ b/BTD.h @@ -30,7 +30,7 @@ #define IOGEAR_GBU521_PID 0x21E8 /* Bluetooth dongle data taken from descriptors */ -#define BULK_MAXPKTSIZE 64 // max size for ACL data +#define BULK_MAXPKTSIZE 64 // Max size for ACL data // Used in control endpoint header for HCI Commands #define bmREQ_HCI_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE @@ -117,17 +117,16 @@ /* Used for SDP channel */ #define L2CAP_SDP_WAIT 10 -#define L2CAP_SDP_REQUEST 11 #define L2CAP_SDP_SUCCESS 12 #define L2CAP_SDP_DONE 13 -#define L2CAP_DISCONNECT_RESPONSE 14 /* Used for RFCOMM channel */ #define L2CAP_RFCOMM_WAIT 15 -#define L2CAP_RFCOMM_REQUEST 16 #define L2CAP_RFCOMM_SUCCESS 17 #define L2CAP_RFCOMM_DONE 18 +#define L2CAP_DISCONNECT_RESPONSE 14 // Used for both SDP and RFCOMM channel + /* Bluetooth states used by some drivers */ #define TURN_ON_LED 19 #define PS3_ENABLE_SIXAXIS 20 @@ -149,13 +148,11 @@ /* L2CAP event flags for SDP channel */ #define L2CAP_FLAG_CONNECTION_SDP_REQUEST 0x00000100 -#define L2CAP_FLAG_CONFIG_SDP_REQUEST 0x00000200 #define L2CAP_FLAG_CONFIG_SDP_SUCCESS 0x00000400 #define L2CAP_FLAG_DISCONNECT_SDP_REQUEST 0x00000800 /* L2CAP event flags for RFCOMM channel */ #define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST 0x00001000 -#define L2CAP_FLAG_CONFIG_RFCOMM_REQUEST 0x00002000 #define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS 0x00004000 #define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST 0x00008000 diff --git a/SPP.cpp b/SPP.cpp index 7a13ca1d..f21b6770 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -151,12 +151,10 @@ void SPP::ACLData(uint8_t* l2capinbuf) { } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { //Notify(PSTR("\r\nSDP Configuration Request"), 0x80); - identifier = l2capinbuf[9]; - l2cap_set_flag(L2CAP_FLAG_CONFIG_SDP_REQUEST); + pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], sdp_scid); } else if (l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { //Notify(PSTR("\r\nRFCOMM Configuration Request"), 0x80); - identifier = l2capinbuf[9]; - l2cap_set_flag(L2CAP_FLAG_CONFIG_RFCOMM_REQUEST); + pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], rfcomm_scid); } } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { @@ -403,7 +401,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { connected = true; // The RFCOMM channel is now established sppIndex = 0; } -#ifdef DEBUG_USB_HOST +#ifdef EXTRADEBUG else if (rfcommChannelType != RFCOMM_DISC) { Notify(PSTR("\r\nUnsupported RFCOMM Data - ChannelType: "), 0x80); D_PrintHex (rfcommChannelType, 0x80); @@ -453,16 +451,6 @@ void SPP::SDP_task() { identifier++; delay(1); pBtd->l2cap_config_request(hci_handle, identifier, sdp_scid); - l2cap_sdp_state = L2CAP_SDP_REQUEST; - } - break; - case L2CAP_SDP_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_SDP_REQUEST)) { - l2cap_clear_flag(L2CAP_FLAG_CONFIG_SDP_REQUEST); // Clear flag -#ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nSDP Configuration Request"), 0x80); -#endif - pBtd->l2cap_config_response(hci_handle, identifier, sdp_scid); l2cap_sdp_state = L2CAP_SDP_SUCCESS; } break; @@ -520,16 +508,6 @@ void SPP::RFCOMM_task() { identifier++; delay(1); pBtd->l2cap_config_request(hci_handle, identifier, rfcomm_scid); - l2cap_rfcomm_state = L2CAP_RFCOMM_REQUEST; - } - break; - case L2CAP_RFCOMM_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_RFCOMM_REQUEST)) { - l2cap_clear_flag(L2CAP_FLAG_CONFIG_RFCOMM_REQUEST); // Clear flag -#ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nRFCOMM Configuration Request"), 0x80); -#endif - pBtd->l2cap_config_response(hci_handle, identifier, rfcomm_scid); l2cap_rfcomm_state = L2CAP_RFCOMM_SUCCESS; } break; From 413e65a44fb4e742c82665fa74d6838084c273c3 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 13 Dec 2013 10:36:15 +0100 Subject: [PATCH 032/145] Reorder values --- BTD.h | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/BTD.h b/BTD.h index cfbc2023..a6b7b479 100755 --- a/BTD.h +++ b/BTD.h @@ -117,22 +117,22 @@ /* Used for SDP channel */ #define L2CAP_SDP_WAIT 10 -#define L2CAP_SDP_SUCCESS 12 -#define L2CAP_SDP_DONE 13 +#define L2CAP_SDP_SUCCESS 11 +#define L2CAP_SDP_DONE 12 /* Used for RFCOMM channel */ -#define L2CAP_RFCOMM_WAIT 15 -#define L2CAP_RFCOMM_SUCCESS 17 -#define L2CAP_RFCOMM_DONE 18 +#define L2CAP_RFCOMM_WAIT 13 +#define L2CAP_RFCOMM_SUCCESS 14 +#define L2CAP_RFCOMM_DONE 15 -#define L2CAP_DISCONNECT_RESPONSE 14 // Used for both SDP and RFCOMM channel +#define L2CAP_DISCONNECT_RESPONSE 16 // Used for both SDP and RFCOMM channel /* Bluetooth states used by some drivers */ -#define TURN_ON_LED 19 -#define PS3_ENABLE_SIXAXIS 20 -#define WII_CHECK_MOTION_PLUS_STATE 21 -#define WII_CHECK_EXTENSION_STATE 22 -#define WII_INIT_MOTION_PLUS_STATE 23 +#define TURN_ON_LED 17 +#define PS3_ENABLE_SIXAXIS 18 +#define WII_CHECK_MOTION_PLUS_STATE 19 +#define WII_CHECK_EXTENSION_STATE 20 +#define WII_INIT_MOTION_PLUS_STATE 21 /* L2CAP event flags for HID Control channel */ #define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST 0x00000001 @@ -148,15 +148,15 @@ /* L2CAP event flags for SDP channel */ #define L2CAP_FLAG_CONNECTION_SDP_REQUEST 0x00000100 -#define L2CAP_FLAG_CONFIG_SDP_SUCCESS 0x00000400 -#define L2CAP_FLAG_DISCONNECT_SDP_REQUEST 0x00000800 +#define L2CAP_FLAG_CONFIG_SDP_SUCCESS 0x00000200 +#define L2CAP_FLAG_DISCONNECT_SDP_REQUEST 0x00000400 /* L2CAP event flags for RFCOMM channel */ -#define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST 0x00001000 -#define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS 0x00004000 -#define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST 0x00008000 +#define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST 0x00000800 +#define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS 0x00001000 +#define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST 0x00002000 -#define L2CAP_FLAG_DISCONNECT_RESPONSE 0x00010000 +#define L2CAP_FLAG_DISCONNECT_RESPONSE 0x00004000 /* Macros for L2CAP event flag tests */ #define l2cap_check_flag(flag) (l2cap_event_flag & flag) From 1ef78c3674f5ad6e4626502d3402b4c8eebaa6bd Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 13 Dec 2013 10:38:41 +0100 Subject: [PATCH 033/145] Do not hardcode identifier when disconnecting --- BTHID.cpp | 2 +- PS3BT.cpp | 6 +++--- SPP.cpp | 6 +++--- Wii.cpp | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index 71e35743..5f4c2e57 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -53,7 +53,7 @@ void BTHID::Reset() { void BTHID::disconnect() { // Use this void to disconnect any of the controllers // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection - pBtd->l2cap_disconnection_request(hci_handle, 0x0A, interrupt_scid, interrupt_dcid); + pBtd->l2cap_disconnection_request(hci_handle, ++identifier, interrupt_scid, interrupt_dcid); Reset(); l2cap_state = L2CAP_INTERRUPT_DISCONNECT; } diff --git a/PS3BT.cpp b/PS3BT.cpp index 6edd4ca7..16beea60 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -218,14 +218,14 @@ void PS3BT::Reset() { l2cap_event_flag = 0; // Reset flags l2cap_state = L2CAP_WAIT; - // Needed for PS3 Dualshock Controller commands to work via bluetooth + // Needed for PS3 Dualshock Controller commands to work via Bluetooth for (uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) HIDBuffer[i + 2] = pgm_read_byte(&PS3_REPORT_BUFFER[i]); // First two bytes reserved for report type and ID } void PS3BT::disconnect() { // Use this void to disconnect any of the controllers - //First the HID interrupt channel has to be disconencted, then the HID control channel and finally the HCI connection - pBtd->l2cap_disconnection_request(hci_handle, 0x0A, interrupt_scid, interrupt_dcid); + // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection + pBtd->l2cap_disconnection_request(hci_handle, ++identifier, interrupt_scid, interrupt_dcid); Reset(); l2cap_state = L2CAP_INTERRUPT_DISCONNECT; } diff --git a/SPP.cpp b/SPP.cpp index f21b6770..b36b2e4f 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -73,13 +73,13 @@ void SPP::Reset() { void SPP::disconnect() { connected = false; - // First the two L2CAP channels has to be disconencted and then the HCI connection + // First the two L2CAP channels has to be disconnected and then the HCI connection if (RFCOMMConnected) - pBtd->l2cap_disconnection_request(hci_handle, 0x0A, rfcomm_scid, rfcomm_dcid); + pBtd->l2cap_disconnection_request(hci_handle, ++identifier, rfcomm_scid, rfcomm_dcid); if (RFCOMMConnected && SDPConnected) delay(1); // Add delay between commands if (SDPConnected) - pBtd->l2cap_disconnection_request(hci_handle, 0x0B, sdp_scid, sdp_dcid); + pBtd->l2cap_disconnection_request(hci_handle, ++identifier, sdp_scid, sdp_dcid); l2cap_sdp_state = L2CAP_DISCONNECT_RESPONSE; } diff --git a/Wii.cpp b/Wii.cpp index 02cddecf..56cd70e5 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -126,7 +126,7 @@ void WII::disconnect() { // Use this void to disconnect any of the controllers } else timer = millis(); // Don't wait // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection - pBtd->l2cap_disconnection_request(hci_handle, 0x0A, interrupt_scid, interrupt_dcid); + pBtd->l2cap_disconnection_request(hci_handle, ++identifier, interrupt_scid, interrupt_dcid); Reset(); l2cap_state = L2CAP_INTERRUPT_DISCONNECT; } From 184770489f19b9874b1bcd75b2d249bd4d96846a Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 13 Dec 2013 10:41:12 +0100 Subject: [PATCH 034/145] Removed another unneeded case in the state machine --- BTD.h | 8 +++----- SPP.cpp | 56 ++++++++++++++++++++++---------------------------------- 2 files changed, 25 insertions(+), 39 deletions(-) diff --git a/BTD.h b/BTD.h index a6b7b479..ca1e903e 100755 --- a/BTD.h +++ b/BTD.h @@ -118,14 +118,12 @@ /* Used for SDP channel */ #define L2CAP_SDP_WAIT 10 #define L2CAP_SDP_SUCCESS 11 -#define L2CAP_SDP_DONE 12 /* Used for RFCOMM channel */ -#define L2CAP_RFCOMM_WAIT 13 -#define L2CAP_RFCOMM_SUCCESS 14 -#define L2CAP_RFCOMM_DONE 15 +#define L2CAP_RFCOMM_WAIT 12 +#define L2CAP_RFCOMM_SUCCESS 13 -#define L2CAP_DISCONNECT_RESPONSE 16 // Used for both SDP and RFCOMM channel +#define L2CAP_DISCONNECT_RESPONSE 14 // Used for both SDP and RFCOMM channel /* Bluetooth states used by some drivers */ #define TURN_ON_LED 17 diff --git a/SPP.cpp b/SPP.cpp index b36b2e4f..db79f2cb 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -452,6 +452,13 @@ void SPP::SDP_task() { delay(1); pBtd->l2cap_config_request(hci_handle, identifier, sdp_scid); l2cap_sdp_state = L2CAP_SDP_SUCCESS; + } else if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST); // Clear flag + SDPConnected = false; +#ifdef DEBUG_USB_HOST + Notify(PSTR("\r\nDisconnected SDP Channel"), 0x80); +#endif + pBtd->l2cap_disconnection_response(hci_handle, identifier, sdp_dcid, sdp_scid); } break; case L2CAP_SDP_SUCCESS: @@ -462,33 +469,18 @@ void SPP::SDP_task() { #endif firstMessage = true; // Reset bool SDPConnected = true; - l2cap_sdp_state = L2CAP_SDP_DONE; + l2cap_sdp_state = L2CAP_SDP_WAIT; } break; - case L2CAP_SDP_DONE: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST)) { - l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST); // Clear flag - SDPConnected = false; -#ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nDisconnected SDP Channel"), 0x80); -#endif - pBtd->l2cap_disconnection_response(hci_handle, identifier, sdp_dcid, sdp_scid); - l2cap_sdp_state = L2CAP_SDP_WAIT; - } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST)) - l2cap_rfcomm_state = L2CAP_SDP_WAIT; - break; + case L2CAP_DISCONNECT_RESPONSE: // This is for both disconnection response from the RFCOMM and SDP channel if they were connected if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected L2CAP Connection"), 0x80); #endif - RFCOMMConnected = false; - SDPConnected = false; pBtd->hci_disconnect(hci_handle); hci_handle = -1; // Reset handle - l2cap_event_flag = 0; // Reset flags - l2cap_sdp_state = L2CAP_SDP_WAIT; - l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; + Reset(); } break; } @@ -509,6 +501,14 @@ void SPP::RFCOMM_task() { delay(1); pBtd->l2cap_config_request(hci_handle, identifier, rfcomm_scid); l2cap_rfcomm_state = L2CAP_RFCOMM_SUCCESS; + } else if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST)) { + l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST); // Clear flag + RFCOMMConnected = false; + connected = false; +#ifdef DEBUG_USB_HOST + Notify(PSTR("\r\nDisconnected RFCOMM Channel"), 0x80); +#endif + pBtd->l2cap_disconnection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid); } break; case L2CAP_RFCOMM_SUCCESS: @@ -520,22 +520,9 @@ void SPP::RFCOMM_task() { rfcommAvailable = 0; // Reset number of bytes available bytesRead = 0; // Reset number of bytes received RFCOMMConnected = true; - l2cap_rfcomm_state = L2CAP_RFCOMM_DONE; + l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; } break; - case L2CAP_RFCOMM_DONE: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST)) { - l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST); // Clear flag - RFCOMMConnected = false; - connected = false; -#ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nDisconnected RFCOMM Channel"), 0x80); -#endif - pBtd->l2cap_disconnection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid); - l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; - } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST)) - l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; - break; } } /************************************************************/ @@ -719,10 +706,11 @@ uint8_t SPP::crc(uint8_t *data) { /* Calculate FCS */ uint8_t SPP::calcFcs(uint8_t *data) { + uint8_t temp = crc(data); if ((data[1] & 0xEF) == RFCOMM_UIH) - return (0xFF - crc(data)); // FCS on 2 bytes + return (0xFF - temp); // FCS on 2 bytes else - return (0xFF - pgm_read_byte(&rfcomm_crc_table[crc(data) ^ data[2]])); // FCS on 3 bytes + return (0xFF - pgm_read_byte(&rfcomm_crc_table[temp ^ data[2]])); // FCS on 3 bytes } /* Check FCS */ From 471a8d9163590a7fdb1e6106b49b909e6c6d9223 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 13 Dec 2013 10:41:59 +0100 Subject: [PATCH 035/145] Set pin even if it should not pair to a device Needed by some Bluetooth mice that always want authentication --- BTHID.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index 5f4c2e57..17b5ea63 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -31,9 +31,7 @@ protocolMode(HID_BOOT_PROTOCOL) pBtd->registerServiceClass(this); // Register it as a Bluetooth service pBtd->pairWithHIDDevice = pair; - - if (pair) - pBtd->btdPin= pin; + pBtd->btdPin= pin; /* Set device cid for the control and intterrupt channelse - LSB */ control_dcid[0] = 0x70; // 0x0070 From 6ea34f955e8704696072e4ce9eaaa7d357330d7e Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 13 Dec 2013 11:18:30 +0100 Subject: [PATCH 036/145] Fixed flag macros Needed if you want to clear multiple flags at once --- BTD.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/BTD.h b/BTD.h index ca1e903e..cc328deb 100755 --- a/BTD.h +++ b/BTD.h @@ -71,9 +71,9 @@ #define HCI_FLAG_CONNECT_EVENT 0x100 /* Macros for HCI event flag tests */ -#define hci_check_flag(flag) (hci_event_flag & flag) -#define hci_set_flag(flag) (hci_event_flag |= flag) -#define hci_clear_flag(flag) (hci_event_flag &= ~flag) +#define hci_check_flag(flag) (hci_event_flag & (flag)) +#define hci_set_flag(flag) (hci_event_flag |= (flag)) +#define hci_clear_flag(flag) (hci_event_flag &= ~(flag)) /* HCI Events managed */ #define EV_INQUIRY_COMPLETE 0x01 @@ -157,9 +157,9 @@ #define L2CAP_FLAG_DISCONNECT_RESPONSE 0x00004000 /* Macros for L2CAP event flag tests */ -#define l2cap_check_flag(flag) (l2cap_event_flag & flag) -#define l2cap_set_flag(flag) (l2cap_event_flag |= flag) -#define l2cap_clear_flag(flag) (l2cap_event_flag &= ~flag) +#define l2cap_check_flag(flag) (l2cap_event_flag & (flag)) +#define l2cap_set_flag(flag) (l2cap_event_flag |= (flag)) +#define l2cap_clear_flag(flag) (l2cap_event_flag &= ~(flag)) /* L2CAP signaling commands */ #define L2CAP_CMD_COMMAND_REJECT 0x01 From 0b2e444e7b9db182d18b3c7ea7100c59f088b31d Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 13 Dec 2013 11:27:05 +0100 Subject: [PATCH 037/145] Fixed macros in Wii.h as well --- Wii.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Wii.h b/Wii.h index 06a74ee5..8b46c2b2 100755 --- a/Wii.h +++ b/Wii.h @@ -30,9 +30,9 @@ #define WII_FLAG_MOTION_PLUS_CONNECTED 0x01 #define WII_FLAG_NUNCHUCK_CONNECTED 0x02 -#define wii_check_flag(flag) (wii_event_flag & flag) -#define wii_set_flag(flag) (wii_event_flag |= flag) -#define wii_clear_flag(flag) (wii_event_flag &= ~flag) +#define wii_check_flag(flag) (wii_event_flag & (flag)) +#define wii_set_flag(flag) (wii_event_flag |= (flag)) +#define wii_clear_flag(flag) (wii_event_flag &= ~(flag)) /** Enum used to read the joystick on the Nunchuck. */ enum Hat { From f283e90402a9abab6776aa2697c35320ae8037fc Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 15 Dec 2013 22:19:50 +0100 Subject: [PATCH 038/145] Renamed CLK, MOSI, MISO and SS variables, as they conflicted with defines in pins_arduino.h See: https://github.com/arduino/Arduino/commit/7fcba37acfd11313640b3f5d5c813d63d2f59999 --- usbhost.h | 96 +++++++++++++++++++++++++++---------------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/usbhost.h b/usbhost.h index 81949431..90b4da5a 100644 --- a/usbhost.h +++ b/usbhost.h @@ -28,7 +28,7 @@ e-mail : support@circuitsathome.com #endif /* SPI initialization */ -template< typename CLK, typename MOSI, typename MISO, typename SPI_SS > class SPi { +template< typename SPI_CLK, typename SPI_MOSI, typename SPI_MISO, typename SPI_SS > class SPi { #if USING_SPI4TEENSY3 public: @@ -46,9 +46,9 @@ public: static void init() { //uint8_t tmp; - CLK::SetDirWrite(); - MOSI::SetDirWrite(); - MISO::SetDirRead(); + SPI_CLK::SetDirWrite(); + SPI_MOSI::SetDirWrite(); + SPI_MISO::SetDirRead(); SPI_SS::SetDirWrite(); /* mode 00 (CPOL=0, CPHA=0) master, fclk/2. Mode 11 (CPOL=11, CPHA=11) is also supported by MAX3421E */ SPCR = 0x50; @@ -78,7 +78,7 @@ typedef enum { vbus_off = GPX_VBDET } VBUS_t; -template< typename SS, typename INTR > class MAX3421e /* : public spi */ { +template< typename SPI_SS, typename INTR > class MAX3421e /* : public spi */ { static uint8_t vbusState; public: @@ -106,12 +106,12 @@ public: uint8_t Task(); }; -template< typename SS, typename INTR > - uint8_t MAX3421e< SS, INTR >::vbusState = 0; +template< typename SPI_SS, typename INTR > + uint8_t MAX3421e< SPI_SS, INTR >::vbusState = 0; /* constructor */ -template< typename SS, typename INTR > -MAX3421e< SS, INTR >::MAX3421e() { +template< typename SPI_SS, typename INTR > +MAX3421e< SPI_SS, INTR >::MAX3421e() { // Leaving ADK hardware setup in here, for now. This really belongs with the other parts. #ifdef BOARD_MEGA_ADK // For Mega ADK, which has a Max3421e on-board, set MAX_RESET to output mode, and then set it to HIGH @@ -121,10 +121,10 @@ MAX3421e< SS, INTR >::MAX3421e() { }; /* write single byte into MAX3421 register */ -template< typename SS, typename INTR > -void MAX3421e< SS, INTR >::regWr(uint8_t reg, uint8_t data) { +template< typename SPI_SS, typename INTR > +void MAX3421e< SPI_SS, INTR >::regWr(uint8_t reg, uint8_t data) { XMEM_ACQUIRE_SPI(); - SS::Clear(); + SPI_SS::Clear(); #if USING_SPI4TEENSY3 uint8_t c[2]; c[0] = reg | 0x02; @@ -136,17 +136,17 @@ void MAX3421e< SS, INTR >::regWr(uint8_t reg, uint8_t data) { SPDR = data; while(!(SPSR & (1 << SPIF))); #endif - SS::Set(); + SPI_SS::Set(); XMEM_RELEASE_SPI(); return; }; /* multiple-byte write */ /* returns a pointer to memory position after last written */ -template< typename SS, typename INTR > -uint8_t* MAX3421e< SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* data_p) { +template< typename SPI_SS, typename INTR > +uint8_t* MAX3421e< SPI_SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* data_p) { XMEM_ACQUIRE_SPI(); - SS::Clear(); + SPI_SS::Clear(); #if USING_SPI4TEENSY3 spi4teensy3::send(reg | 0x02); spi4teensy3::send(data_p, nbytes); @@ -160,7 +160,7 @@ uint8_t* MAX3421e< SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* dat } while(!(SPSR & (1 << SPIF))); #endif - SS::Set(); + SPI_SS::Set(); XMEM_RELEASE_SPI(); return( data_p); } @@ -168,8 +168,8 @@ uint8_t* MAX3421e< SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* dat /*GPIO byte is split between 2 registers, so two writes are needed to write one byte */ /* GPOUT bits are in the low nibble. 0-3 in IOPINS1, 4-7 in IOPINS2 */ -template< typename SS, typename INTR > -void MAX3421e< SS, INTR >::gpioWr(uint8_t data) { +template< typename SPI_SS, typename INTR > +void MAX3421e< SPI_SS, INTR >::gpioWr(uint8_t data) { regWr(rIOPINS1, data); data >>= 4; regWr(rIOPINS2, data); @@ -177,20 +177,20 @@ void MAX3421e< SS, INTR >::gpioWr(uint8_t data) { } /* single host register read */ -template< typename SS, typename INTR > -uint8_t MAX3421e< SS, INTR >::regRd(uint8_t reg) { +template< typename SPI_SS, typename INTR > +uint8_t MAX3421e< SPI_SS, INTR >::regRd(uint8_t reg) { XMEM_ACQUIRE_SPI(); - SS::Clear(); + SPI_SS::Clear(); #if USING_SPI4TEENSY3 spi4teensy3::send(reg); uint8_t rv = spi4teensy3::receive(); - SS::Set(); + SPI_SS::Set(); #else SPDR = reg; while(!(SPSR & (1 << SPIF))); SPDR = 0; //send empty byte while(!(SPSR & (1 << SPIF))); - SS::Set(); + SPI_SS::Set(); uint8_t rv = SPDR; #endif XMEM_RELEASE_SPI(); @@ -199,10 +199,10 @@ uint8_t MAX3421e< SS, INTR >::regRd(uint8_t reg) { /* multiple-byte register read */ /* returns a pointer to a memory position after last read */ -template< typename SS, typename INTR > -uint8_t* MAX3421e< SS, INTR >::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t* data_p) { +template< typename SPI_SS, typename INTR > +uint8_t* MAX3421e< SPI_SS, INTR >::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t* data_p) { XMEM_ACQUIRE_SPI(); - SS::Clear(); + SPI_SS::Clear(); #if USING_SPI4TEENSY3 spi4teensy3::send(reg); spi4teensy3::receive(data_p, nbytes); @@ -227,15 +227,15 @@ uint8_t* MAX3421e< SS, INTR >::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t* dat } #endif #endif - SS::Set(); + SPI_SS::Set(); XMEM_RELEASE_SPI(); return( data_p); } /* GPIO read. See gpioWr for explanation */ /* GPIN pins are in high nibbles of IOPINS1, IOPINS2 */ -template< typename SS, typename INTR > -uint8_t MAX3421e< SS, INTR >::gpioRd() { +template< typename SPI_SS, typename INTR > +uint8_t MAX3421e< SPI_SS, INTR >::gpioRd() { uint8_t gpin = 0; gpin = regRd(rIOPINS2); //pins 4-7 gpin &= 0xf0; //clean lower nibble @@ -245,8 +245,8 @@ uint8_t MAX3421e< SS, INTR >::gpioRd() { /* reset MAX3421E. Returns number of cycles it took for PLL to stabilize after reset or zero if PLL haven't stabilized in 65535 cycles */ -template< typename SS, typename INTR > -uint16_t MAX3421e< SS, INTR >::reset() { +template< typename SPI_SS, typename INTR > +uint16_t MAX3421e< SPI_SS, INTR >::reset() { uint16_t i = 0; regWr(rUSBCTL, bmCHIPRES); regWr(rUSBCTL, 0x00); @@ -259,15 +259,15 @@ uint16_t MAX3421e< SS, INTR >::reset() { } /* initialize MAX3421E. Set Host mode, pullups, and stuff. Returns 0 if success, -1 if not */ -template< typename SS, typename INTR > -int8_t MAX3421e< SS, INTR >::Init() { +template< typename SPI_SS, typename INTR > +int8_t MAX3421e< SPI_SS, INTR >::Init() { XMEM_ACQUIRE_SPI(); // Moved here. // you really should not init hardware in the constructor when it involves locks. // Also avoids the vbus flicker issue confusing some devices. /* pin and peripheral setup */ - SS::SetDirWrite(); - SS::Set(); + SPI_SS::SetDirWrite(); + SPI_SS::Set(); spi::init(); INTR::SetDirRead(); XMEM_RELEASE_SPI(); @@ -296,15 +296,15 @@ int8_t MAX3421e< SS, INTR >::Init() { } /* initialize MAX3421E. Set Host mode, pullups, and stuff. Returns 0 if success, -1 if not */ -template< typename SS, typename INTR > -int8_t MAX3421e< SS, INTR >::Init(int mseconds) { +template< typename SPI_SS, typename INTR > +int8_t MAX3421e< SPI_SS, INTR >::Init(int mseconds) { XMEM_ACQUIRE_SPI(); // Moved here. // you really should not init hardware in the constructor when it involves locks. // Also avoids the vbus flicker issue confusing some devices. /* pin and peripheral setup */ - SS::SetDirWrite(); - SS::Set(); + SPI_SS::SetDirWrite(); + SPI_SS::Set(); spi::init(); INTR::SetDirRead(); XMEM_RELEASE_SPI(); @@ -340,8 +340,8 @@ int8_t MAX3421e< SS, INTR >::Init(int mseconds) { } /* probe bus to determine device presence and speed and switch host to this speed */ -template< typename SS, typename INTR > -void MAX3421e< SS, INTR >::busprobe() { +template< typename SPI_SS, typename INTR > +void MAX3421e< SPI_SS, INTR >::busprobe() { uint8_t bus_sample; bus_sample = regRd(rHRSL); //Get J,K status bus_sample &= (bmJSTATUS | bmKSTATUS); //zero the rest of the byte @@ -375,8 +375,8 @@ void MAX3421e< SS, INTR >::busprobe() { } /* MAX3421 state change task and interrupt handler */ -template< typename SS, typename INTR > -uint8_t MAX3421e< SS, INTR >::Task(void) { +template< typename SPI_SS, typename INTR > +uint8_t MAX3421e< SPI_SS, INTR >::Task(void) { uint8_t rcode = 0; uint8_t pinvalue; //USB_HOST_SERIAL.print("Vbus state: "); @@ -394,8 +394,8 @@ uint8_t MAX3421e< SS, INTR >::Task(void) { return( rcode); } -template< typename SS, typename INTR > -uint8_t MAX3421e< SS, INTR >::IntHandler() { +template< typename SPI_SS, typename INTR > +uint8_t MAX3421e< SPI_SS, INTR >::IntHandler() { uint8_t HIRQ; uint8_t HIRQ_sendback = 0x00; HIRQ = regRd(rHIRQ); //determine interrupt source @@ -410,8 +410,8 @@ uint8_t MAX3421e< SS, INTR >::IntHandler() { regWr(rHIRQ, HIRQ_sendback); return( HIRQ_sendback); } -//template< typename SS, typename INTR > -//uint8_t MAX3421e< SS, INTR >::GpxHandler() +//template< typename SPI_SS, typename INTR > +//uint8_t MAX3421e< SPI_SS, INTR >::GpxHandler() //{ // uint8_t GPINIRQ = regRd( rGPINIRQ ); //read GPIN IRQ register //// if( GPINIRQ & bmGPINIRQ7 ) { //vbus overload From 92c7a6430917b22222fecc0f0c934e080527d6c4 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 16 Dec 2013 09:16:12 +0100 Subject: [PATCH 039/145] Store all strings in getStatusString() in flash --- PS3BT.cpp | 60 +++++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/PS3BT.cpp b/PS3BT.cpp index 16beea60..7745e38e 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -162,48 +162,48 @@ bool PS3BT::getStatus(Status c) { String PS3BT::getStatusString() { if (PS3Connected || PS3NavigationConnected) { - char statusOutput[100]; + char statusOutput[100]; // Max string length plus null character - strcpy(statusOutput, "ConnectionStatus: "); + strcpy_P(statusOutput, PSTR("ConnectionStatus: ")); - if (getStatus(Plugged)) strcat(statusOutput, "Plugged"); - else if (getStatus(Unplugged)) strcat(statusOutput, "Unplugged"); - else strcat(statusOutput, "Error"); + if (getStatus(Plugged)) strcat_P(statusOutput, PSTR("Plugged")); + else if (getStatus(Unplugged)) strcat_P(statusOutput, PSTR("Unplugged")); + else strcat_P(statusOutput, PSTR("Error")); - strcat(statusOutput, " - PowerRating: "); - if (getStatus(Charging)) strcat(statusOutput, "Charging"); - else if (getStatus(NotCharging)) strcat(statusOutput, "Not Charging"); - else if (getStatus(Shutdown)) strcat(statusOutput, "Shutdown"); - else if (getStatus(Dying)) strcat(statusOutput, "Dying"); - else if (getStatus(Low)) strcat(statusOutput, "Low"); - else if (getStatus(High)) strcat(statusOutput, "High"); - else if (getStatus(Full)) strcat(statusOutput, "Full"); - else strcat(statusOutput, "Error"); + strcat_P(statusOutput, PSTR(" - PowerRating: ")); + if (getStatus(Charging)) strcat_P(statusOutput, PSTR("Charging")); + else if (getStatus(NotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); + else if (getStatus(Shutdown)) strcat_P(statusOutput, PSTR("Shutdown")); + else if (getStatus(Dying)) strcat_P(statusOutput, PSTR("Dying")); + else if (getStatus(Low)) strcat_P(statusOutput, PSTR("Low")); + else if (getStatus(High)) strcat_P(statusOutput, PSTR("High")); + else if (getStatus(Full)) strcat_P(statusOutput, PSTR("Full")); + else strcat_P(statusOutput, PSTR("Error")); - strcat(statusOutput, " - WirelessStatus: "); + strcat_P(statusOutput, PSTR(" - WirelessStatus: ")); - if (getStatus(CableRumble)) strcat(statusOutput, "Cable - Rumble is on"); - else if (getStatus(Cable)) strcat(statusOutput, "Cable - Rumble is off"); - else if (getStatus(BluetoothRumble)) strcat(statusOutput, "Bluetooth - Rumble is on"); - else if (getStatus(Bluetooth)) strcat(statusOutput, "Bluetooth - Rumble is off"); - else strcat(statusOutput, "Error"); + if (getStatus(CableRumble)) strcat_P(statusOutput, PSTR("Cable - Rumble is on")); + else if (getStatus(Cable)) strcat_P(statusOutput, PSTR("Cable - Rumble is off")); + else if (getStatus(BluetoothRumble)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is on")); + else if (getStatus(Bluetooth)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is off")); + else strcat_P(statusOutput, PSTR("Error")); return statusOutput; } else if (PS3MoveConnected) { - char statusOutput[50]; + char statusOutput[26]; // Max string length plus null character - strcpy(statusOutput, "PowerRating: "); + strcpy_P(statusOutput, PSTR("PowerRating: ")); - if (getStatus(MoveCharging)) strcat(statusOutput, "Charging"); - else if (getStatus(MoveNotCharging)) strcat(statusOutput, "Not Charging"); - else if (getStatus(MoveShutdown)) strcat(statusOutput, "Shutdown"); - else if (getStatus(MoveDying)) strcat(statusOutput, "Dying"); - else if (getStatus(MoveLow)) strcat(statusOutput, "Low"); - else if (getStatus(MoveHigh)) strcat(statusOutput, "High"); - else if (getStatus(MoveFull)) strcat(statusOutput, "Full"); - else strcat(statusOutput, "Error"); + if (getStatus(MoveCharging)) strcat_P(statusOutput, PSTR("Charging")); + else if (getStatus(MoveNotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); + else if (getStatus(MoveShutdown)) strcat_P(statusOutput, PSTR("Shutdown")); + else if (getStatus(MoveDying)) strcat_P(statusOutput, PSTR("Dying")); + else if (getStatus(MoveLow)) strcat_P(statusOutput, PSTR("Low")); + else if (getStatus(MoveHigh)) strcat_P(statusOutput, PSTR("High")); + else if (getStatus(MoveFull)) strcat_P(statusOutput, PSTR("Full")); + else strcat_P(statusOutput, PSTR("Error")); return statusOutput; } else From fdd65eab68eaf509d2f768aa20540fec3eec7b95 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 16 Dec 2013 09:18:01 +0100 Subject: [PATCH 040/145] Whitespace --- SPP.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SPP.cpp b/SPP.cpp index db79f2cb..60973547 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -706,7 +706,7 @@ uint8_t SPP::crc(uint8_t *data) { /* Calculate FCS */ uint8_t SPP::calcFcs(uint8_t *data) { - uint8_t temp = crc(data); + uint8_t temp = crc(data); if ((data[1] & 0xEF) == RFCOMM_UIH) return (0xFF - temp); // FCS on 2 bytes else From 5785115cdb150e74944c107ce2e6e1a6a2e7a0b1 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 18 Dec 2013 15:18:28 -0500 Subject: [PATCH 041/145] Type fixes, new debug macro, debug bug fixes. --- BTHID.cpp | 4 +-- SPP.cpp | 4 +-- Usb.cpp | 6 +++-- Wii.cpp | 4 +-- XBOXRECV.cpp | 10 ++++---- address.h | 67 +++++++++++++++++++++++------------------------- hidboot.h | 28 ++++++++++---------- hiduniversal.cpp | 2 +- macros.h | 1 + masstorage.cpp | 10 ++++---- 10 files changed, 69 insertions(+), 67 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index f410bcc2..4d491ba7 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -70,8 +70,8 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { } } } - if ((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000)) { // acl_handle_ok or it's a new connection - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001) { // l2cap_control - Channel ID for ACL-U + if ((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); diff --git a/SPP.cpp b/SPP.cpp index 7a13ca1d..8d6be648 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -97,8 +97,8 @@ void SPP::ACLData(uint8_t* l2capinbuf) { } } } - if (((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000))) { // acl_handle_ok - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001) { //l2cap_control - Channel ID for ACL-U + if (((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000U))) { // acl_handle_ok + if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); diff --git a/Usb.cpp b/Usb.cpp index f8c8edae..8f498dba 100644 --- a/Usb.cpp +++ b/Usb.cpp @@ -70,7 +70,7 @@ uint8_t USB::setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr) if (!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - p->address = addr; + p->address.devAddress = addr; p->epinfo = eprecord_ptr; p->epcount = epcount; @@ -210,7 +210,9 @@ uint8_t USB::inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t* uint8_t rcode = SetAddress(addr, ep, &pep, nak_limit); if (rcode) { - //printf("SetAddress Failed"); + USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81); + USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81); + USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81); return rcode; } return InTransfer(pep, nak_limit, nbytesptr, data); diff --git a/Wii.cpp b/Wii.cpp index 02cddecf..202b3c2f 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -144,8 +144,8 @@ void WII::ACLData(uint8_t* l2capinbuf) { } } } - if ((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000)) { // acl_handle_ok or it's a new connection - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001) { //l2cap_control - Channel ID for ACL-U + if ((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index 8e4008a3..7317b14b 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -258,11 +258,11 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { return 0; // Successful configuration /* Diagnostic messages */ -#ifdef DEBUG_USB_HOST -FailGetDevDescr: - NotifyFailGetDevDescr(); - goto Fail; -#endif +//#ifdef DEBUG_USB_HOST +//FailGetDevDescr: +// NotifyFailGetDevDescr(); +// goto Fail; +//#endif FailSetDevTblEntry: #ifdef DEBUG_USB_HOST diff --git a/address.h b/address.h index dd281b12..d933f2e6 100644 --- a/address.h +++ b/address.h @@ -62,7 +62,7 @@ struct UsbDeviceAddress { uint8_t bmAddress : 3; // device address/port number uint8_t bmParent : 3; // parent hub address uint8_t bmHub : 1; // hub flag - uint8_t bmReserved : 1; // reserved, must be zerro + uint8_t bmReserved : 1; // reserved, must be zero } __attribute__((packed)); uint8_t devAddress; }; @@ -74,7 +74,7 @@ struct UsbDeviceAddress { struct UsbDevice { EpInfo *epinfo; // endpoint info pointer - uint8_t address; // address + UsbDeviceAddress address; uint8_t epcount; // number of endpoints bool lowspeed; // indicates if a device is the low speed one // uint8_t devclass; // device class @@ -104,50 +104,50 @@ class AddressPoolImpl : public AddressPool { // Initializes address pool entry void InitEntry(uint8_t index) { - thePool[index].address = 0; + thePool[index].address.devAddress = 0; thePool[index].epcount = 1; thePool[index].lowspeed = 0; thePool[index].epinfo = &dev0ep; }; - // Returns thePool index for a given address + // Returns thePool index for a given address uint8_t FindAddressIndex(uint8_t address = 0) { for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) { - if(thePool[i].address == address) + if(thePool[i].address.devAddress == address) return i; } return 0; }; - // Returns thePool child index for a given parent + // Returns thePool child index for a given parent uint8_t FindChildIndex(UsbDeviceAddress addr, uint8_t start = 1) { for(uint8_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) { - UsbDeviceAddress* uda = reinterpret_cast(&thePool[i].address); - if(uda->bmParent == addr.bmAddress) + if(thePool[i].address.bmParent == addr.bmAddress) return i; } return 0; }; - // Frees address entry specified by index parameter + // Frees address entry specified by index parameter void FreeAddressByIndex(uint8_t index) { - // Zerro field is reserved and should not be affected + // Zero field is reserved and should not be affected if(index == 0) return; - UsbDeviceAddress* uda = reinterpret_cast(& thePool[index].address); + + UsbDeviceAddress uda = thePool[index].address; // If a hub was switched off all port addresses should be freed - if(uda->bmHub == 1) { - for(uint8_t i = 1; (i = FindChildIndex(*uda, i));) + if(uda.bmHub == 1) { + for(uint8_t i = 1; (i = FindChildIndex(uda, i));) FreeAddressByIndex(i); // If the hub had the last allocated address, hubCounter should be decremented - if(hubCounter == uda->bmAddress) + if(hubCounter == uda.bmAddress) hubCounter--; } InitEntry(index); } - // Initializes the whole address pool at once + // Initializes the whole address pool at once void InitAllAddresses() { for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) InitEntry(i); @@ -161,7 +161,7 @@ public: // Zero address is reserved InitEntry(0); - thePool[0].address = 0; + thePool[0].address.devAddress = 0; thePool[0].epinfo = &dev0ep; dev0ep.epAddr = 0; dev0ep.maxPktSize = 8; @@ -170,8 +170,8 @@ public: InitAllAddresses(); }; - // Returns a pointer to a specified address entry + // Returns a pointer to a specified address entry virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) { if(!addr) return thePool; @@ -182,22 +182,23 @@ public: }; // Performs an operation specified by pfunc for each addressed device - void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { if(!pfunc) return; for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) - if(thePool[i].address) + if(thePool[i].address.devAddress) pfunc(thePool + i); }; - // Allocates new address + // Allocates new address virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) { /* if (parent != 0 && port == 0) USB_HOST_SERIAL.println("PRT:0"); */ - - if(parent > 127 || port > 7) + UsbDeviceAddress _parent; + _parent.devAddress = parent; + if(_parent.bmReserved || port > 7) + //if(parent > 127 || port > 7) return 0; if(is_hub && hubCounter == 7) @@ -209,22 +210,19 @@ public: if(!index) // if empty entry is not found return 0; - if(parent == 0) { + if(_parent.devAddress == 0) { if(is_hub) { - thePool[index].address = 0x41; + thePool[index].address.devAddress = 0x41; hubCounter++; } else - thePool[index].address = 1; + thePool[index].address.devAddress = 1; - return thePool[index].address; + return thePool[index].address.devAddress; } UsbDeviceAddress addr; addr.devAddress = 0; // Ensure all bits are zero - UsbDeviceAddress* uda = reinterpret_cast(&parent); - //addr.bmParent = ((UsbDeviceAddress*) & parent)->bmAddress; - addr.bmParent = uda->bmAddress; - + addr.bmParent = _parent.bmAddress; if(is_hub) { addr.bmHub = 1; addr.bmAddress = ++hubCounter; @@ -232,9 +230,7 @@ public: addr.bmHub = 0; addr.bmAddress = port; } - uint8_t* uaddr = reinterpret_cast(&addr); - //thePool[index].address = *((uint8_t*) & addr); - thePool[index].address = *uaddr; + thePool[index].address = addr; /* USB_HOST_SERIAL.print("Addr:"); USB_HOST_SERIAL.print(addr.bmHub, HEX); @@ -243,10 +239,10 @@ public: USB_HOST_SERIAL.print("."); USB_HOST_SERIAL.println(addr.bmAddress, HEX); */ - return thePool[index].address; + return thePool[index].address.devAddress; }; - // Empties pool entry + // Empties pool entry virtual void FreeAddress(uint8_t addr) { // if the root hub is disconnected all the addresses should be initialized if(addr == 0x41) { @@ -256,6 +252,7 @@ public: uint8_t index = FindAddressIndex(addr); FreeAddressByIndex(index); }; + // Returns number of hubs attached // It can be rather helpfull to find out if there are hubs attached than getting the exact number of hubs. //uint8_t GetNumHubs() diff --git a/hidboot.h b/hidboot.h index b418dc4c..8f228a92 100644 --- a/hidboot.h +++ b/hidboot.h @@ -372,9 +372,9 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed } } - USBTRACE2("\r\nbAddr:", bAddress); - USBTRACE2("\r\nbNumEP:", bNumEP); - USBTRACE2("\r\ntotalEndpoints:", totalEndpoints); + USBTRACE2("bAddr:", bAddress); + USBTRACE2("bNumEP:", bNumEP); + USBTRACE2("totalEndpoints:", totalEndpoints); if(bNumEP != totalEndpoints) { rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; goto Fail; @@ -382,8 +382,8 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - - USBTRACE2("\r\nCnf:", bConfNum); + USBTRACE2("setEpInfoEntry returned ", rcode); + USBTRACE2("Cnf:", bConfNum); // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); @@ -391,7 +391,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed if(rcode) goto FailSetConfDescr; - USBTRACE2("\r\nIf:", bIfaceNum); + USBTRACE2("If:", bIfaceNum); rcode = SetProtocol(bIfaceNum, HID_BOOT_PROTOCOL); @@ -422,11 +422,11 @@ FailSetDevTblEntry: goto Fail; #endif -FailGetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetConfDescr(); - goto Fail; -#endif +//FailGetConfDescr: +//#ifdef DEBUG_USB_HOST +// NotifyFailGetConfDescr(); +// goto Fail; +//#endif FailSetConfDescr: #ifdef DEBUG_USB_HOST @@ -503,7 +503,9 @@ uint8_t HIDBoot::Poll() { const uint8_t const_buff_len = 16; uint8_t buf[const_buff_len]; - + USBTRACE3("(hidboot.h) i=", i, 0x81); + USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].epAddr=", epInfo[epInterruptInIndex + i].epAddr, 0x81); + USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].maxPktSize=", epInfo[epInterruptInIndex + i].maxPktSize, 0x81); uint16_t read = (uint16_t) epInfo[epInterruptInIndex + i].maxPktSize; uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[epInterruptInIndex + i].epAddr, &read, buf); @@ -521,7 +523,7 @@ uint8_t HIDBoot::Poll() { #endif } else { if(rcode != hrNAK) { - USBTRACE2("Poll:", rcode); + USBTRACE3("(hidboot.h) Poll:", rcode, 0x81); break; } } diff --git a/hiduniversal.cpp b/hiduniversal.cpp index e55e80ff..b669e6bf 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -360,7 +360,7 @@ uint8_t HIDUniversal::Poll() { if (rcode) { if (rcode != hrNAK) - USBTRACE2("Poll:", rcode); + USBTRACE3("(hiduniversal.h) Poll:", rcode, 0x81); return rcode; } diff --git a/macros.h b/macros.h index 70f04262..c5ec6b8a 100644 --- a/macros.h +++ b/macros.h @@ -64,6 +64,7 @@ */ #define USBTRACE(s) (Notify(PSTR(s), 0x80)) #define USBTRACE2(s,r) (Notify(PSTR(s), 0x80), D_PrintHex((r), 0x80), Notify(PSTR("\r\n"), 0x80)) +#define USBTRACE3(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l), Notify(PSTR("\r\n"), l)) #endif /* MACROS_H */ diff --git a/masstorage.cpp b/masstorage.cpp index be35d9b0..c4967880 100644 --- a/masstorage.cpp +++ b/masstorage.cpp @@ -489,11 +489,11 @@ FailGetMaxLUN: goto Fail; #endif -#ifdef DEBUG_USB_HOST -FailInvalidSectorSize: - USBTRACE("Sector Size is NOT VALID: "); - goto Fail; -#endif +//#ifdef DEBUG_USB_HOST +//FailInvalidSectorSize: +// USBTRACE("Sector Size is NOT VALID: "); +// goto Fail; +//#endif FailSetDevTblEntry: #ifdef DEBUG_USB_HOST From ddaa6f0220639a38d797ad0061c98eb3d74662a7 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 18 Dec 2013 23:01:01 +0100 Subject: [PATCH 042/145] =?UTF-8?q?Fixed=20=E2=80=9Ccomparison=20between?= =?UTF-8?q?=20signed=20and=20unsigned=20integer=20expressions=E2=80=9D=20w?= =?UTF-8?q?arning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BTHID.cpp | 2 +- PS3BT.cpp | 4 ++-- SPP.cpp | 2 +- Wii.cpp | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index a5353f65..5d1451a9 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -68,7 +68,7 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { } } } - if ((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if ((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST diff --git a/PS3BT.cpp b/PS3BT.cpp index 7745e38e..ac185576 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -250,9 +250,9 @@ void PS3BT::ACLData(uint8_t* ACLData) { } } } - if (((ACLData[0] | (ACLData[1] << 8)) == (hci_handle | 0x2000))) { //acl_handle_ok + if ((ACLData[0] | (uint16_t)ACLData[1] << 8) == (hci_handle | 0x2000U)) { //acl_handle_ok memcpy(l2capinbuf, ACLData, BULK_MAXPKTSIZE); - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001) { //l2cap_control - Channel ID for ACL-U + if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); diff --git a/SPP.cpp b/SPP.cpp index 9f9dd46f..670b91dc 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -97,7 +97,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { } } } - if (((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000U))) { // acl_handle_ok + if ((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST diff --git a/Wii.cpp b/Wii.cpp index 91e6ff49..e0d79707 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -144,7 +144,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { } } } - if ((l2capinbuf[0] | (l2capinbuf[1] << 8)) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if ((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST From 77efe42a718472d1d649465b4d6a8bfeee145e30 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 18 Dec 2013 21:58:24 -0500 Subject: [PATCH 043/145] Fix hidboot not allocating or checking properly on mouse. Removal of duplicate code: Force all drivers to delay after setting address. --- PS3USB.cpp | 2 +- Usb.cpp | 16 +++++---- XBOXOLD.cpp | 2 +- XBOXUSB.cpp | 2 +- adk.cpp | 2 +- hidboot.h | 86 +++++++++++++++++++++++++++++------------------- hiduniversal.cpp | 2 +- 7 files changed, 68 insertions(+), 44 deletions(-) diff --git a/PS3USB.cpp b/PS3USB.cpp index 1f6226eb..8cc4a40f 100644 --- a/PS3USB.cpp +++ b/PS3USB.cpp @@ -129,7 +129,7 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nAddr: "), 0x80); D_PrintHex (bAddress, 0x80); #endif - delay(300); // Spec says you should wait at least 200ms + //delay(300); // Spec says you should wait at least 200ms p->lowspeed = false; diff --git a/Usb.cpp b/Usb.cpp index 8f498dba..3bcea447 100644 --- a/Usb.cpp +++ b/Usb.cpp @@ -447,7 +447,7 @@ void USB::Task(void) //USB state machine case LSHOST: lowspeed = true; - //intentional fallthrough + //intentional fallthrough case FSHOST: //attached if ((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) { delay = millis() + USB_SETTLE_DELAY; @@ -503,11 +503,11 @@ void USB::Task(void) //USB state machine break; case USB_ATTACHED_SUBSTATE_WAIT_RESET: if (delay < millis()) usb_task_state = USB_STATE_CONFIGURING; - else break; // don't fall through + else break; // don't fall through case USB_STATE_CONFIGURING: - //Serial.print("\r\nConf.LS: "); - //Serial.println(lowspeed, HEX); + //Serial.print("\r\nConf.LS: "); + //Serial.println(lowspeed, HEX); rcode = Configuring(0, 0, lowspeed); @@ -748,7 +748,7 @@ uint8_t USB::ReleaseDevice(uint8_t addr) { return 0; for (uint8_t i = 0; i < USB_NUMDEVICES; i++) { - if(!devConfig[i]) continue; + if (!devConfig[i]) continue; if (devConfig[i]->GetAddress() == addr) return devConfig[i]->Release(); } @@ -794,7 +794,11 @@ uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t ns, uint8_t index, u //set address uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) { - return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL)); + uint8_t rcode = ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL); + //delay(2); //per USB 2.0 sect.9.2.6.3 + delay(300); // Older spec says you should wait at least 200ms + return rcode; + //return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL)); } //set configuration diff --git a/XBOXOLD.cpp b/XBOXOLD.cpp index e60330c8..d615f83f 100644 --- a/XBOXOLD.cpp +++ b/XBOXOLD.cpp @@ -145,7 +145,7 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nAddr: "), 0x80); D_PrintHex (bAddress, 0x80); #endif - delay(300); // Spec says you should wait at least 200ms + //delay(300); // Spec says you should wait at least 200ms p->lowspeed = false; diff --git a/XBOXUSB.cpp b/XBOXUSB.cpp index a7900811..111c5c3e 100644 --- a/XBOXUSB.cpp +++ b/XBOXUSB.cpp @@ -133,7 +133,7 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nAddr: "), 0x80); D_PrintHex (bAddress, 0x80); #endif - delay(300); // Spec says you should wait at least 200ms + //delay(300); // Spec says you should wait at least 200ms p->lowspeed = false; diff --git a/adk.cpp b/adk.cpp index a3530d00..2d655b74 100644 --- a/adk.cpp +++ b/adk.cpp @@ -128,7 +128,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { //USBTRACE2("\r\nAddr:", bAddress); // Spec says you should wait at least 200ms. - delay(300); + //delay(300); p->lowspeed = false; diff --git a/hidboot.h b/hidboot.h index 8f228a92..32430caa 100644 --- a/hidboot.h +++ b/hidboot.h @@ -28,7 +28,6 @@ e-mail : support@circuitsathome.com #define UHS_HID_BOOT_KEY_ZERO2 0x62 #define UHS_HID_BOOT_KEY_PERIOD 0x63 - struct MOUSEINFO { struct { @@ -168,15 +167,16 @@ protected: }; }; -#define totalEndpoints (((BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD)? 2 : 0)+((BOOT_PROTOCOL & HID_PROTOCOL_MOUSE)? 1 : 0)) -#define epMUL (((BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD)? 1 : 0)+((BOOT_PROTOCOL & HID_PROTOCOL_MOUSE)? 1 : 0)) +#define bitsEndpoints(p) (((p & HID_PROTOCOL_KEYBOARD)? 2 : 0)+((p & HID_PROTOCOL_MOUSE)? 1 : 0)) +#define totalEndpoints(p) ((bitsEndpoints(p) == 3) ? 3 : 2) +#define epMUL(p) (((p & HID_PROTOCOL_KEYBOARD)? 1 : 0)+((p & HID_PROTOCOL_MOUSE)? 1 : 0)) #define HID_MAX_HID_CLASS_DESCRIPTORS 5 template class HIDBoot : public HID //public USBDeviceConfig, public UsbConfigXtracter { - EpInfo epInfo[totalEndpoints]; - HIDReportParser *pRptParser[epMUL]; + EpInfo epInfo[totalEndpoints(BOOT_PROTOCOL)]; + HIDReportParser *pRptParser[epMUL(BOOT_PROTOCOL)]; uint8_t bConfNum; // configuration number uint8_t bIfaceNum; // Interface Number @@ -219,7 +219,7 @@ qNextPollTime(0), bPollEnable(false) { Initialize(); - for(uint8_t i = 0; i < epMUL; i++) { + for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { pRptParser[i] = NULL; } if(pUsb) @@ -228,7 +228,7 @@ bPollEnable(false) { template void HIDBoot::Initialize() { - for(uint8_t i = 0; i < totalEndpoints; i++) { + for(int i = 0; i < totalEndpoints(BOOT_PROTOCOL); i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; @@ -314,6 +314,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed USBTRACE2("setAddr:", rcode); return rcode; } + delay(2); //per USB 2.0 sect.9.2.6.3 USBTRACE2("Addr:", bAddress); @@ -335,15 +336,22 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed num_of_conf = ((USB_DEVICE_DESCRIPTOR*) buf)->bNumConfigurations; // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); + //rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if(rcode) - goto FailSetDevTblEntry; + //if(rcode) + // goto FailSetDevTblEntry; //USBTRACE2("NC:", num_of_conf); + // GCC will optimize unused stuff away. + //if((totalEndpoints(BOOT_PROTOCOL)) != 3) { + // bNumEP = 0; + //} + USBTRACE2("bNumEP:", bNumEP); + USBTRACE2("totalEndpoints:", (uint8_t) (bitsEndpoints(BOOT_PROTOCOL))); // GCC will optimize unused stuff away. if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { + USBTRACE("HID_PROTOCOL_KEYBOARD\r\n"); for(uint8_t i = 0; i < num_of_conf; i++) { ConfigDescParser< USB_CLASS_HID, @@ -351,46 +359,55 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed HID_PROTOCOL_KEYBOARD, CP_MASK_COMPARE_ALL> confDescrParserA(this); - if(bNumEP == totalEndpoints) - break; pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); + if(bNumEP == (uint8_t) (bitsEndpoints(BOOT_PROTOCOL))) + break; } } // GCC will optimize unused stuff away. if(BOOT_PROTOCOL & HID_PROTOCOL_MOUSE) { + USBTRACE("HID_PROTOCOL_MOUSE\r\n"); for(uint8_t i = 0; i < num_of_conf; i++) { ConfigDescParser< USB_CLASS_HID, HID_BOOT_INTF_SUBCLASS, HID_PROTOCOL_MOUSE, CP_MASK_COMPARE_ALL> confDescrParserB(this); - if(bNumEP == totalEndpoints) - break; pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); + if(bNumEP > 1 /* (uint8_t) (totalEndpoints(BOOT_PROTOCOL))*/) + break; + } } + USBTRACE2("bAddr:", bAddress); USBTRACE2("bNumEP:", bNumEP); - USBTRACE2("totalEndpoints:", totalEndpoints); - if(bNumEP != totalEndpoints) { - rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - goto Fail; - } + USBTRACE2("totalEndpoints:", (uint8_t) (bitsEndpoints(BOOT_PROTOCOL))); + USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL)); + + if(bNumEP != (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) { + rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; + goto Fail; + } // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); USBTRACE2("setEpInfoEntry returned ", rcode); USBTRACE2("Cnf:", bConfNum); + delay(1000); + // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); if(rcode) goto FailSetConfDescr; + delay(1000); + USBTRACE2("If:", bIfaceNum); rcode = SetProtocol(bIfaceNum, HID_BOOT_PROTOCOL); @@ -416,17 +433,17 @@ FailGetDevDescr: goto Fail; #endif -FailSetDevTblEntry: -#ifdef DEBUG_USB_HOST - NotifyFailSetDevTblEntry(); - goto Fail; -#endif + //FailSetDevTblEntry: + //#ifdef DEBUG_USB_HOST + // NotifyFailSetDevTblEntry(); + // goto Fail; + //#endif -//FailGetConfDescr: -//#ifdef DEBUG_USB_HOST -// NotifyFailGetConfDescr(); -// goto Fail; -//#endif + //FailGetConfDescr: + //#ifdef DEBUG_USB_HOST + // NotifyFailGetConfDescr(); + // goto Fail; + //#endif FailSetConfDescr: #ifdef DEBUG_USB_HOST @@ -450,6 +467,7 @@ Fail: NotifyFail(rcode); #endif Release(); + return rcode; } @@ -463,7 +481,8 @@ void HIDBoot::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t bIfaceNum = iface; if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { - uint8_t index = bNumEP;//epInterruptInIndex; //+ bNumEP; + + uint8_t index = bNumEP; //epInterruptInIndex; //+ bNumEP; // Fill in the endpoint info structure epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); @@ -485,6 +504,7 @@ uint8_t HIDBoot::Release() { bAddress = 0; qNextPollTime = 0; bPollEnable = false; + return 0; } @@ -499,7 +519,7 @@ uint8_t HIDBoot::Poll() { qNextPollTime = millis() + 10; // To-do: optimize manually, getting rid of the loop - for(uint8_t i = 0; i < epMUL; i++) { + for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { const uint8_t const_buff_len = 16; uint8_t buf[const_buff_len]; @@ -514,11 +534,11 @@ uint8_t HIDBoot::Poll() { pRptParser[i]->Parse((HID*)this, 0, (uint8_t) read, buf); #if 0 // Set this to 1 to print the incoming data - for (uint8_t i=0; i < read; i++) { + for(uint8_t i = 0; i < read; i++) { PrintHex (buf[i], 0x80); USB_HOST_SERIAL.write(' '); } - if (read) + if(read) USB_HOST_SERIAL.println(); #endif } else { diff --git a/hiduniversal.cpp b/hiduniversal.cpp index b669e6bf..9cbd09c4 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -148,7 +148,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { return rcode; } - delay( 2 ); //per USB 2.0 sect.9.2.6.3 + //delay(2); //per USB 2.0 sect.9.2.6.3 USBTRACE2("Addr:", bAddress); From 6638f6135260dfc2810c186d26800e14d46261c4 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 18 Dec 2013 22:20:50 -0500 Subject: [PATCH 044/145] Finalize fix --- hidboot.h | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/hidboot.h b/hidboot.h index 32430caa..0d9a338d 100644 --- a/hidboot.h +++ b/hidboot.h @@ -256,6 +256,8 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed AddressPool &addrPool = pUsb->GetAddressPool(); USBTRACE("BM Init\r\n"); + USBTRACE2("totalEndpoints:", (uint8_t)(totalEndpoints(BOOT_PROTOCOL))); + USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL)); if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; @@ -314,7 +316,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed USBTRACE2("setAddr:", rcode); return rcode; } - delay(2); //per USB 2.0 sect.9.2.6.3 + //delay(2); //per USB 2.0 sect.9.2.6.3 USBTRACE2("Addr:", bAddress); @@ -348,7 +350,6 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed //} USBTRACE2("bNumEP:", bNumEP); - USBTRACE2("totalEndpoints:", (uint8_t) (bitsEndpoints(BOOT_PROTOCOL))); // GCC will optimize unused stuff away. if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { USBTRACE("HID_PROTOCOL_KEYBOARD\r\n"); @@ -360,7 +361,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed CP_MASK_COMPARE_ALL> confDescrParserA(this); pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); - if(bNumEP == (uint8_t) (bitsEndpoints(BOOT_PROTOCOL))) + if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) break; } } @@ -376,7 +377,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed CP_MASK_COMPARE_ALL> confDescrParserB(this); pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); - if(bNumEP > 1 /* (uint8_t) (totalEndpoints(BOOT_PROTOCOL))*/) + if(bNumEP == ((uint8_t)(totalEndpoints(BOOT_PROTOCOL)))) break; } @@ -385,8 +386,6 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed USBTRACE2("bAddr:", bAddress); USBTRACE2("bNumEP:", bNumEP); - USBTRACE2("totalEndpoints:", (uint8_t) (bitsEndpoints(BOOT_PROTOCOL))); - USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL)); if(bNumEP != (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) { rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; From f789c65c02ba437a18d9e6930c8e7c771573cead Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 19 Dec 2013 13:01:48 -0500 Subject: [PATCH 045/145] fix demos --- examples/USB_desc/USB_desc.ino | 6 +++--- examples/hub_demo/hub_demo.ino | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/USB_desc/USB_desc.ino b/examples/USB_desc/USB_desc.ino index 71e2fdc3..b0013914 100644 --- a/examples/USB_desc/USB_desc.ino +++ b/examples/USB_desc/USB_desc.ino @@ -20,7 +20,7 @@ uint32_t next_time; void PrintAllAddresses(UsbDevice *pdev) { UsbDeviceAddress adr; - adr.devAddress = pdev->address; + adr.devAddress = pdev->address.devAddress; Serial.print("\r\nAddr:"); Serial.print(adr.devAddress, HEX); Serial.print("("); @@ -90,9 +90,9 @@ void PrintDescriptors(uint8_t addr) void PrintAllDescriptors(UsbDevice *pdev) { Serial.println("\r\n"); - print_hex(pdev->address, 8); + print_hex(pdev->address.devAddress, 8); Serial.println("\r\n--"); - PrintDescriptors( pdev->address ); + PrintDescriptors( pdev->address.devAddress ); } void loop() diff --git a/examples/hub_demo/hub_demo.ino b/examples/hub_demo/hub_demo.ino index d80d9ea2..466ae4d7 100644 --- a/examples/hub_demo/hub_demo.ino +++ b/examples/hub_demo/hub_demo.ino @@ -16,7 +16,7 @@ uint32_t next_time; void PrintAllAddresses(UsbDevice *pdev) { UsbDeviceAddress adr; - adr.devAddress = pdev->address; + adr.devAddress = pdev->address.devAddress; Serial.print("\r\nAddr:"); Serial.print(adr.devAddress, HEX); Serial.print("("); @@ -86,9 +86,9 @@ void PrintDescriptors(uint8_t addr) void PrintAllDescriptors(UsbDevice *pdev) { Serial.println("\r\n"); - print_hex(pdev->address, 8); + print_hex(pdev->address.devAddress, 8); Serial.println("\r\n--"); - PrintDescriptors( pdev->address ); + PrintDescriptors( pdev->address.devAddress ); } void loop() From 35e8bb2dbf17d7bd8922f359a52644fb77f9c09f Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 21 Dec 2013 13:39:47 +0100 Subject: [PATCH 046/145] Removed unused code --- XBOXRECV.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index 7317b14b..ec6c4546 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -258,12 +258,6 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { return 0; // Successful configuration /* Diagnostic messages */ -//#ifdef DEBUG_USB_HOST -//FailGetDevDescr: -// NotifyFailGetDevDescr(); -// goto Fail; -//#endif - FailSetDevTblEntry: #ifdef DEBUG_USB_HOST NotifyFailSetDevTblEntry(); From ef4757f88fe0a38bab3d7beb37aaca4a3ddf67b2 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 21 Dec 2013 13:40:28 +0100 Subject: [PATCH 047/145] Check if GCC_VERSION is defined before defining it --- settings.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/settings.h b/settings.h index d49b7aa5..f7914b2a 100644 --- a/settings.h +++ b/settings.h @@ -78,7 +78,9 @@ #endif #ifdef __GNUC__ +#ifndef GCC_VERSION #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif #if GCC_VERSION < 40602 // Test for GCC < 4.6.2 #ifdef PROGMEM #undef PROGMEM From c298e349ae01717b798b382b81e344c2d2007f75 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Mon, 23 Dec 2013 14:12:29 -0500 Subject: [PATCH 048/145] HID_BOOT fixes. Fix Keyboard init issue. Set boot protocol and idle on all interfaces. TO-DO: Investagate mouse init issue. There are many devices with quirks that can not be worked around easily on such a small platform. These need to be addressed. Note! This commit does not fully fix mouse problems on all mouse adaptors, but more of them should start working. --- hidboot.h | 85 ++++++++++++++++++++++++++----------------------------- 1 file changed, 40 insertions(+), 45 deletions(-) diff --git a/hidboot.h b/hidboot.h index 0d9a338d..700c2e4b 100644 --- a/hidboot.h +++ b/hidboot.h @@ -184,6 +184,7 @@ class HIDBoot : public HID //public USBDeviceConfig, public UsbConfigXtracter uint8_t bNumEP; // total number of EP in the configuration uint32_t qNextPollTime; // next poll time bool bPollEnable; // poll enable flag + uint8_t bInterval; // largest interval void Initialize(); @@ -256,12 +257,13 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed AddressPool &addrPool = pUsb->GetAddressPool(); USBTRACE("BM Init\r\n"); - USBTRACE2("totalEndpoints:", (uint8_t)(totalEndpoints(BOOT_PROTOCOL))); - USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL)); + //USBTRACE2("totalEndpoints:", (uint8_t) (totalEndpoints(BOOT_PROTOCOL))); + //USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL)); if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; + bInterval = 0; // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); @@ -337,19 +339,8 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed num_of_conf = ((USB_DEVICE_DESCRIPTOR*) buf)->bNumConfigurations; - // Assign epInfo to epinfo pointer - //rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); + USBTRACE2("NC:", num_of_conf); - //if(rcode) - // goto FailSetDevTblEntry; - - //USBTRACE2("NC:", num_of_conf); - // GCC will optimize unused stuff away. - //if((totalEndpoints(BOOT_PROTOCOL)) != 3) { - // bNumEP = 0; - //} - - USBTRACE2("bNumEP:", bNumEP); // GCC will optimize unused stuff away. if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { USBTRACE("HID_PROTOCOL_KEYBOARD\r\n"); @@ -361,7 +352,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed CP_MASK_COMPARE_ALL> confDescrParserA(this); pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); - if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) + if(bNumEP == (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) break; } } @@ -377,24 +368,22 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed CP_MASK_COMPARE_ALL> confDescrParserB(this); pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); - if(bNumEP == ((uint8_t)(totalEndpoints(BOOT_PROTOCOL)))) + if(bNumEP == ((uint8_t) (totalEndpoints(BOOT_PROTOCOL)))) break; } } - - USBTRACE2("bAddr:", bAddress); USBTRACE2("bNumEP:", bNumEP); - if(bNumEP != (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) { - rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - goto Fail; - } + if(bNumEP != (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) { + rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; + goto Fail; + } // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - USBTRACE2("setEpInfoEntry returned ", rcode); + //USBTRACE2("setEpInfoEntry returned ", rcode); USBTRACE2("Cnf:", bConfNum); delay(1000); @@ -407,19 +396,28 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed delay(1000); - USBTRACE2("If:", bIfaceNum); + USBTRACE2("bIfaceNum:", bIfaceNum); + USBTRACE2("bNumIface:", bNumIface); - rcode = SetProtocol(bIfaceNum, HID_BOOT_PROTOCOL); + // Yes, mouse wants SetProtocol and SetIdle too! + for(uint8_t i = 0; i < epMUL(BOOT_PROTOCOL); i++) { + USBTRACE2("\r\nInterface:", i); + rcode = SetProtocol(i, HID_BOOT_PROTOCOL); + if(rcode) goto FailSetProtocol; + USBTRACE2("PROTOCOL SET HID_BOOT rcode:", rcode); + rcode = SetIdle(i, 0, 0); + USBTRACE2("SET_IDLE rcode:", rcode); + if(rcode) goto FailSetIdle; + } - if(rcode) - goto FailSetProtocol; - - // GCC will optimize unused stuff away. if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { - rcode = SetIdle(0/* bIfaceNum*/, 0, 0); - - if(rcode) - goto FailSetIdle; + // Wake keyboard interface by twinkling up to 7 LEDs + rcode = 0x80; // Reuse rcode. + while(rcode) { + rcode >>= 1; + SetReport(0, 0, 2, 0, 1, &rcode); // Eventually becomes zero (All off) + delay(25); + } } USBTRACE("BM configured\r\n"); @@ -472,6 +470,7 @@ Fail: template void HIDBoot::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { + // If the first configuration satisfies, the others are not considered. if(bNumEP > 1 && conf != bConfNum) return; @@ -480,14 +479,13 @@ void HIDBoot::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t bIfaceNum = iface; if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { - - uint8_t index = bNumEP; //epInterruptInIndex; //+ bNumEP; + if(pep->bInterval > bInterval) bInterval = pep->bInterval; // Fill in the endpoint info structure - epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[index].maxPktSize = (uint8_t) pep->wMaxPacketSize; - epInfo[index].epAttribs = 0; - epInfo[index].bmNakPower = USB_NAK_NOWAIT; + epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F); + epInfo[bNumEP].maxPktSize = (uint8_t) pep->wMaxPacketSize; + epInfo[bNumEP].epAttribs = 0; + epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT; bNumEP++; } @@ -511,11 +509,7 @@ template uint8_t HIDBoot::Poll() { uint8_t rcode = 0; - if(!bPollEnable) - return 0; - - if(qNextPollTime <= millis()) { - qNextPollTime = millis() + 10; + if(bPollEnable && qNextPollTime <= millis()) { // To-do: optimize manually, getting rid of the loop for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { @@ -543,10 +537,11 @@ uint8_t HIDBoot::Poll() { } else { if(rcode != hrNAK) { USBTRACE3("(hidboot.h) Poll:", rcode, 0x81); - break; + //break; } } } + qNextPollTime = millis() + bInterval; } return rcode; } From 81d30180224fee8446ec517a9a6f7e546ecb55f1 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 25 Dec 2013 01:07:17 -0500 Subject: [PATCH 049/145] a sink parser that throws away data. --- sink_parser.h | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 sink_parser.h diff --git a/sink_parser.h b/sink_parser.h new file mode 100644 index 00000000..033d024e --- /dev/null +++ b/sink_parser.h @@ -0,0 +1,36 @@ +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com + */ +#if !defined(_usb_h_) || defined(__SINK_PARSER_H__) +#error "Never include hexdump.h directly; include Usb.h instead" +#else +#define __SINK_PARSER_H__ + +extern int UsbDEBUGlvl; + +// This parser does absolutely nothing with the data, just swallows it. +template +class SinkParser : public BASE_CLASS { + +public: + + SinkParser() {}; + void Initialize() {}; + void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) {}; +}; + + +#endif // __HEXDUMP_H__ From d17e1f94cb1fad4608e10c36c2870655f9882bef Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 25 Dec 2013 01:08:02 -0500 Subject: [PATCH 050/145] HID fixes Fix incorrect GetReportDescr args. We want the interface index. HID BOOT mouse will now always work HID BOOT keyboard will now always work --- Usb.h | 1 + confdescparser.h | 22 +++++++----- hexdump.h | 2 +- hid.cpp | 14 +++++++- hid.h | 2 +- hidboot.h | 89 +++++++++++++++++++++++++++++++----------------- 6 files changed, 88 insertions(+), 42 deletions(-) diff --git a/Usb.h b/Usb.h index c9dccb53..d903ff51 100644 --- a/Usb.h +++ b/Usb.h @@ -28,6 +28,7 @@ e-mail : support@circuitsathome.com #include "printhex.h" #include "message.h" #include "hexdump.h" +#include "sink_parser.h" #include "max3421e.h" #include "address.h" #include "avrpins.h" diff --git a/confdescparser.h b/confdescparser.h index d7646a98..186de7be 100644 --- a/confdescparser.h +++ b/confdescparser.h @@ -20,7 +20,6 @@ e-mail : support@circuitsathome.com #define __CONFDESCPARSER_H__ - class UsbConfigXtracter { public: //virtual void ConfigXtract(const USB_CONFIGURATION_DESCRIPTOR *conf) = 0; @@ -54,11 +53,12 @@ class ConfigDescParser : public USBReadParser { uint8_t ifaceNumber; // Interface number uint8_t ifaceAltSet; // Interface alternate settings + bool UseOr; bool ParseDescriptor(uint8_t **pp, uint16_t *pcntdn); - void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc); public: + void SetOR(void) { UseOr = true; } ConfigDescParser(UsbConfigXtracter *xtractor); virtual void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset); }; @@ -68,12 +68,14 @@ ConfigDescParser::ConfigDescParser(Usb theXtractor(xtractor), stateParseDescr(0), dscrLen(0), -dscrType(0) { +dscrType(0), +UseOr(false) { theBuffer.pValue = varBuffer; valParser.Initialize(&theBuffer); theSkipper.Initialize(&theBuffer); }; + template void ConfigDescParser::Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset) { uint16_t cntdn = (uint16_t) len; @@ -88,8 +90,8 @@ void ConfigDescParser::Parse(const uin compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */ template bool ConfigDescParser::ParseDescriptor(uint8_t **pp, uint16_t *pcntdn) { - USB_CONFIGURATION_DESCRIPTOR* ucd= reinterpret_cast(varBuffer); - USB_INTERFACE_DESCRIPTOR* uid= reinterpret_cast(varBuffer); + USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast (varBuffer); + USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast (varBuffer); switch(stateParseDescr) { case 0: theBuffer.valueSize = 2; @@ -139,9 +141,13 @@ bool ConfigDescParser::ParseDescriptor break; if((MASK & CP_MASK_COMPARE_SUBCLASS) && uid->bInterfaceSubClass != SUBCLASS_ID) break; - if((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID) - break; - + if(UseOr) { + if((!((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol))) + break; + } else { + if((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID) + break; + } isGoodInterface = true; ifaceNumber = uid->bInterfaceNumber; ifaceAltSet = uid->bAlternateSetting; diff --git a/hexdump.h b/hexdump.h index cf491d94..5d6f8e11 100644 --- a/hexdump.h +++ b/hexdump.h @@ -58,4 +58,4 @@ void HexDumper::Parse(const LEN_TYPE len, con } } -#endif // __HEXDUMP_H__ \ No newline at end of file +#endif // __HEXDUMP_H__ diff --git a/hid.cpp b/hid.cpp index 0405b04b..02c89720 100644 --- a/hid.cpp +++ b/hid.cpp @@ -1,7 +1,7 @@ #include "hid.h" //get HID report descriptor - +/* WRONG! Endpoint is _ALWAYS_ ZERO for HID! We want the _INTERFACE_ value here! uint8_t HID::GetReportDescr(uint8_t ep, USBReadParser *parser) { const uint8_t constBufLen = 64; uint8_t buf[constBufLen]; @@ -12,6 +12,18 @@ uint8_t HID::GetReportDescr(uint8_t ep, USBReadParser *parser) { //return ((rcode != hrSTALL) ? rcode : 0); return rcode; } +*/ +uint8_t HID::GetReportDescr(uint16_t wIndex, USBReadParser *parser) { + const uint8_t constBufLen = 64; + uint8_t buf[constBufLen]; + + uint8_t rcode = pUsb->ctrlReq(bAddress, 0x00, bmREQ_HIDREPORT, USB_REQUEST_GET_DESCRIPTOR, 0x00, + HID_DESCRIPTOR_REPORT, wIndex, 128, constBufLen, buf, (USBReadParser*)parser); + + //return ((rcode != hrSTALL) ? rcode : 0); + return rcode; +} + //uint8_t HID::getHidDescr( uint8_t ep, uint16_t nbytes, uint8_t* dataptr ) //{ // return( pUsb->ctrlReq( bAddress, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, HID_DESCRIPTOR_HID, 0x0000, nbytes, dataptr )); diff --git a/hid.h b/hid.h index 53ef325c..2037cc15 100644 --- a/hid.h +++ b/hid.h @@ -174,7 +174,7 @@ public: uint8_t GetIdle(uint8_t iface, uint8_t reportID, uint8_t* dataptr); uint8_t SetIdle(uint8_t iface, uint8_t reportID, uint8_t duration); - uint8_t GetReportDescr(uint8_t ep, USBReadParser *parser = NULL); + uint8_t GetReportDescr(uint16_t wIndex, USBReadParser *parser = NULL); uint8_t GetHidDescr(uint8_t ep, uint16_t nbytes, uint8_t* dataptr); uint8_t GetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr); diff --git a/hidboot.h b/hidboot.h index 700c2e4b..91f9819d 100644 --- a/hidboot.h +++ b/hidboot.h @@ -28,6 +28,14 @@ e-mail : support@circuitsathome.com #define UHS_HID_BOOT_KEY_ZERO2 0x62 #define UHS_HID_BOOT_KEY_PERIOD 0x63 +// Don't worry, GCC will optimize the result to a final value. +#define bitsEndpoints(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 2 : 0) | (((p) & HID_PROTOCOL_MOUSE)? 1 : 0)) +#define totalEndpoints(p) ((bitsEndpoints(p) == 3) ? 3 : 2) +#define epMUL(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 1 : 0) + (((p) & HID_PROTOCOL_MOUSE)? 1 : 0)) + +// Already defined in hid.h +// #define HID_MAX_HID_CLASS_DESCRIPTORS 5 + struct MOUSEINFO { struct { @@ -167,11 +175,6 @@ protected: }; }; -#define bitsEndpoints(p) (((p & HID_PROTOCOL_KEYBOARD)? 2 : 0)+((p & HID_PROTOCOL_MOUSE)? 1 : 0)) -#define totalEndpoints(p) ((bitsEndpoints(p) == 3) ? 3 : 2) -#define epMUL(p) (((p & HID_PROTOCOL_KEYBOARD)? 1 : 0)+((p & HID_PROTOCOL_MOUSE)? 1 : 0)) -#define HID_MAX_HID_CLASS_DESCRIPTORS 5 - template class HIDBoot : public HID //public USBDeviceConfig, public UsbConfigXtracter { @@ -342,38 +345,53 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed USBTRACE2("NC:", num_of_conf); // GCC will optimize unused stuff away. - if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { - USBTRACE("HID_PROTOCOL_KEYBOARD\r\n"); + if((BOOT_PROTOCOL & (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) == (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) { + USBTRACE("HID_PROTOCOL_KEYBOARD AND MOUSE\r\n"); + ConfigDescParser< + USB_CLASS_HID, + HID_BOOT_INTF_SUBCLASS, + HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE, + CP_MASK_COMPARE_ALL > confDescrParser(this); + confDescrParser.SetOR(); // Use the OR variant. for(uint8_t i = 0; i < num_of_conf; i++) { - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_KEYBOARD, - CP_MASK_COMPARE_ALL> confDescrParserA(this); - - pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); + pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); if(bNumEP == (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) break; } - } + } else { + // GCC will optimize unused stuff away. + if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { + USBTRACE("HID_PROTOCOL_KEYBOARD\r\n"); + for(uint8_t i = 0; i < num_of_conf; i++) { + ConfigDescParser< + USB_CLASS_HID, + HID_BOOT_INTF_SUBCLASS, + HID_PROTOCOL_KEYBOARD, + CP_MASK_COMPARE_ALL> confDescrParserA(this); - // GCC will optimize unused stuff away. - if(BOOT_PROTOCOL & HID_PROTOCOL_MOUSE) { - USBTRACE("HID_PROTOCOL_MOUSE\r\n"); - for(uint8_t i = 0; i < num_of_conf; i++) { - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_MOUSE, - CP_MASK_COMPARE_ALL> confDescrParserB(this); + pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); + if(bNumEP == (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) + break; + } + } - pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); - if(bNumEP == ((uint8_t) (totalEndpoints(BOOT_PROTOCOL)))) - break; + // GCC will optimize unused stuff away. + if(BOOT_PROTOCOL & HID_PROTOCOL_MOUSE) { + USBTRACE("HID_PROTOCOL_MOUSE\r\n"); + for(uint8_t i = 0; i < num_of_conf; i++) { + ConfigDescParser< + USB_CLASS_HID, + HID_BOOT_INTF_SUBCLASS, + HID_PROTOCOL_MOUSE, + CP_MASK_COMPARE_ALL> confDescrParserB(this); + pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); + if(bNumEP == ((uint8_t) (totalEndpoints(BOOT_PROTOCOL)))) + break; + + } } } - USBTRACE2("bNumEP:", bNumEP); if(bNumEP != (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) { @@ -408,13 +426,21 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed rcode = SetIdle(i, 0, 0); USBTRACE2("SET_IDLE rcode:", rcode); if(rcode) goto FailSetIdle; + // Get the RPIPE and just throw it away. + SinkParser sink; + rcode = GetReportDescr(i, &sink); + USBTRACE2("RPIPE rcode:", rcode); } + // Get RPIPE and throw it away. + if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { - // Wake keyboard interface by twinkling up to 7 LEDs - rcode = 0x80; // Reuse rcode. + // Wake keyboard interface by twinkling up to 5 LEDs that are in the spec. + // kana, compose, scroll, caps, num + rcode = 0x20; // Reuse rcode. while(rcode) { rcode >>= 1; + // Ignore any error returned, we don't care if LED is not supported SetReport(0, 0, 2, 0, 1, &rcode); // Eventually becomes zero (All off) delay(25); } @@ -472,7 +498,8 @@ template void HIDBoot::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { // If the first configuration satisfies, the others are not considered. - if(bNumEP > 1 && conf != bConfNum) + //if(bNumEP > 1 && conf != bConfNum) + if(bNumEP == totalEndpoints(BOOT_PROTOCOL)) return; bConfNum = conf; From b8fb19fb90a4860cbe4b27c848528a676f5c5b4c Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 25 Dec 2013 04:49:01 -0500 Subject: [PATCH 051/145] Optimize mouse code, add notes. --- hidboot.cpp | 97 ++++++++++++++++++++++++++++++++++++++++++++++++----- hidboot.h | 75 +++++++++++++++++++++++------------------ 2 files changed, 130 insertions(+), 42 deletions(-) diff --git a/hidboot.cpp b/hidboot.cpp index b323bd15..4b62d423 100644 --- a/hidboot.cpp +++ b/hidboot.cpp @@ -18,7 +18,10 @@ e-mail : support@circuitsathome.com void MouseReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { MOUSEINFO *pmi = (MOUSEINFO*)buf; + // Future: + // bool event; +#if 0 if (prevState.mouseInfo.bmLeftButton == 0 && pmi->bmLeftButton == 1) OnLeftButtonDown(pmi); @@ -43,6 +46,82 @@ void MouseReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *bu if (len > sizeof (MOUSEINFO)) for (uint8_t i = 0; ibmLeftButton ) { + if(pmi->bmLeftButton) { + OnLeftButtonDown(pmi); + } else { + OnLeftButtonUp(pmi); + } + // Future: + // event = true; + } + + if(prevState.mouseInfo.bmRightButton != pmi->bmRightButton) { + if(pmi->bmRightButton) { + OnRightButtonDown(pmi); + } else { + OnRightButtonUp(pmi); + } + // Future: + // event = true; + } + + if(prevState.mouseInfo.bmMiddleButton != prevState.mouseInfo.bmMiddleButton) { + if(pmi->bmMiddleButton) { + OnMiddleButtonDown(pmi); + } else { + OnMiddleButtonUp(pmi); + } + // Future: + // event = true; + } + + // + // Scroll wheel(s), are not part of the spec, but we could support it. + // Logitech wireless keyboard and mouse combo reports scroll wheel in byte 4 + // We wouldn't even need to save this information. + //if(len > 3) { + //} + // + + // Mice only report motion when they actually move! + // Why not just pass the x/y values to simplify things?? + if(pmi->dX || pmi->dY) { + OnMouseMove(pmi); + // Future: + // event = true; + } + + // + // Future: + // Provide a callback that operates on the gathered events from above. + // + // if(event) OnMouse(); + // + + // Only the first byte matters (buttons). We do NOT need to save position info. + prevState.bInfo[0] = buf[0]; +#endif + }; void KeyboardReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { @@ -52,10 +131,10 @@ void KeyboardReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t //KBDINFO *pki = (KBDINFO*)buf; - // provide event for changed control key state - if (prevState.bInfo[0x00] != buf[0x00]) { - OnControlKeysChanged(prevState.bInfo[0x00], buf[0x00]); - } + // provide event for changed control key state + if (prevState.bInfo[0x00] != buf[0x00]) { + OnControlKeysChanged(prevState.bInfo[0x00], buf[0x00]); + } for (uint8_t i = 2; i < 8; i++) { bool down = false; @@ -124,15 +203,15 @@ uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { else return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1'); }// Keypad Numbers - else if (VALUE_WITHIN(key, 0x59, 0x61)) { - if (kbdLockingKeys.kbdLeds.bmNumLock == 1) + else if(VALUE_WITHIN(key, 0x59, 0x61)) { + if(kbdLockingKeys.kbdLeds.bmNumLock == 1) return (key - 0x59 + '1'); - } else if (VALUE_WITHIN(key, 0x2d, 0x38)) + } else if(VALUE_WITHIN(key, 0x2d, 0x38)) return ((shift) ? (uint8_t)pgm_read_byte(&getSymKeysUp()[key - 0x2d]) : (uint8_t)pgm_read_byte(&getSymKeysLo()[key - 0x2d])); - else if (VALUE_WITHIN(key, 0x54, 0x58)) + else if(VALUE_WITHIN(key, 0x54, 0x58)) return (uint8_t)pgm_read_byte(&getPadKeys()[key - 0x54]); else { - switch (key) { + switch(key) { case UHS_HID_BOOT_KEY_SPACE: return (0x20); case UHS_HID_BOOT_KEY_ENTER: return (0x13); case UHS_HID_BOOT_KEY_ZERO2: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '0': 0); diff --git a/hidboot.h b/hidboot.h index 91f9819d..00c4d9db 100644 --- a/hidboot.h +++ b/hidboot.h @@ -52,7 +52,7 @@ class MouseReportParser : public HIDReportParser { union { MOUSEINFO mouseInfo; - uint8_t bInfo[sizeof(MOUSEINFO)]; + uint8_t bInfo[sizeof (MOUSEINFO)]; } prevState; public: @@ -128,7 +128,7 @@ protected: union { KBDINFO kbdInfo; - uint8_t bInfo[sizeof(KBDINFO)]; + uint8_t bInfo[sizeof (KBDINFO)]; } prevState; union { @@ -245,7 +245,7 @@ void HIDBoot::Initialize() { template uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed) { - const uint8_t constBufSize = sizeof(USB_DEVICE_DESCRIPTOR); + const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; uint8_t rcode; @@ -287,7 +287,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed p->lowspeed = lowspeed; // Get device descriptor - rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*) buf); + rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); if(!rcode) len = (buf[0] > constBufSize) ? constBufSize : buf[0]; @@ -309,7 +309,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t) ((USB_DEVICE_DESCRIPTOR*) buf)->bMaxPacketSize0; + epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); @@ -335,12 +335,12 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed p->lowspeed = lowspeed; if(len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*) buf); + rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); if(rcode) goto FailGetDevDescr; - num_of_conf = ((USB_DEVICE_DESCRIPTOR*) buf)->bNumConfigurations; + num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; USBTRACE2("NC:", num_of_conf); @@ -355,7 +355,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed confDescrParser.SetOR(); // Use the OR variant. for(uint8_t i = 0; i < num_of_conf; i++) { pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - if(bNumEP == (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) + if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) break; } } else { @@ -370,7 +370,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed CP_MASK_COMPARE_ALL> confDescrParserA(this); pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); - if(bNumEP == (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) + if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) break; } } @@ -386,7 +386,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed CP_MASK_COMPARE_ALL> confDescrParserB(this); pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); - if(bNumEP == ((uint8_t) (totalEndpoints(BOOT_PROTOCOL)))) + if(bNumEP == ((uint8_t)(totalEndpoints(BOOT_PROTOCOL)))) break; } @@ -394,7 +394,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed } USBTRACE2("bNumEP:", bNumEP); - if(bNumEP != (uint8_t) (totalEndpoints(BOOT_PROTOCOL))) { + if(bNumEP != (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) { rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; goto Fail; } @@ -425,7 +425,7 @@ uint8_t HIDBoot::Init(uint8_t parent, uint8_t port, bool lowspeed USBTRACE2("PROTOCOL SET HID_BOOT rcode:", rcode); rcode = SetIdle(i, 0, 0); USBTRACE2("SET_IDLE rcode:", rcode); - if(rcode) goto FailSetIdle; + // if(rcode) goto FailSetIdle; This can fail. // Get the RPIPE and just throw it away. SinkParser sink; rcode = GetReportDescr(i, &sink); @@ -480,10 +480,10 @@ FailSetProtocol: goto Fail; #endif -FailSetIdle: -#ifdef DEBUG_USB_HOST - USBTRACE("SetIdle:"); -#endif + //FailSetIdle: + //#ifdef DEBUG_USB_HOST + // USBTRACE("SetIdle:"); + //#endif Fail: #ifdef DEBUG_USB_HOST @@ -510,7 +510,7 @@ void HIDBoot::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t // Fill in the endpoint info structure epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[bNumEP].maxPktSize = (uint8_t) pep->wMaxPacketSize; + epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize; epInfo[bNumEP].epAttribs = 0; epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT; bNumEP++; @@ -538,35 +538,44 @@ uint8_t HIDBoot::Poll() { if(bPollEnable && qNextPollTime <= millis()) { - // To-do: optimize manually, getting rid of the loop + // To-do: optimize manually, using the for loop only if needed. for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { - const uint8_t const_buff_len = 16; + const uint16_t const_buff_len = 16; uint8_t buf[const_buff_len]; USBTRACE3("(hidboot.h) i=", i, 0x81); USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].epAddr=", epInfo[epInterruptInIndex + i].epAddr, 0x81); USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].maxPktSize=", epInfo[epInterruptInIndex + i].maxPktSize, 0x81); - uint16_t read = (uint16_t) epInfo[epInterruptInIndex + i].maxPktSize; + uint16_t read = (uint16_t)epInfo[epInterruptInIndex + i].maxPktSize; - uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[epInterruptInIndex + i].epAddr, &read, buf); - if(!rcode) { + rcode = pUsb->inTransfer(bAddress, epInfo[epInterruptInIndex + i].epAddr, &read, buf); + // SOME buggy dongles report extra keys (like sleep) using a 2 byte packet on the wrong endpoint. + // Since keyboard and mice must report at least 3 bytes, we ignore the extra data. + if(!rcode && read > 2) { if(pRptParser[i]) - pRptParser[i]->Parse((HID*)this, 0, (uint8_t) read, buf); - -#if 0 // Set this to 1 to print the incoming data - for(uint8_t i = 0; i < read; i++) { - PrintHex (buf[i], 0x80); - USB_HOST_SERIAL.write(' '); - } - if(read) - USB_HOST_SERIAL.println(); -#endif + pRptParser[i]->Parse((HID*)this, 0, (uint8_t)read, buf); +#ifdef DEBUG_USB_HOST + // We really don't care about errors and anomalies unless we are debugging. } else { if(rcode != hrNAK) { USBTRACE3("(hidboot.h) Poll:", rcode, 0x81); - //break; + } + if(!rcode && read) { + USBTRACE3("(hidboot.h) Strange read count: ", read, 0x80); + USBTRACE3("(hidboot.h) Interface:", i, 0x80); } } + + if(!rcode && read && (UsbDEBUGlvl > 0x7f)) { + for(uint8_t i = 0; i < read; i++) { + PrintHex (buf[i], 0x80); + USBTRACE1(" ", 0x80); + } + if(read) + USBTRACE1("\r\n", 0x80); +#endif + } + } qNextPollTime = millis() + bInterval; } From f1af9b08ecdd1e10e73c533743771b71bcb1a488 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 25 Dec 2013 05:09:57 -0500 Subject: [PATCH 052/145] Janitorial, whitespace fixes. No new code. --- BTD.cpp | 250 +++++++++++++++++------------------ BTD.h | 11 +- BTHID.cpp | 114 ++++++++-------- BTHID.h | 7 +- PS3BT.cpp | 198 ++++++++++++++-------------- PS3BT.h | 1 + PS3Enums.h | 2 +- PS3USB.cpp | 110 ++++++++-------- PS3USB.h | 1 + SPP.cpp | 168 ++++++++++++------------ SPP.h | 3 +- Usb.cpp | 173 ++++++++++++------------- UsbCore.h | 55 +++++--- Wii.cpp | 281 ++++++++++++++++++++-------------------- Wii.h | 15 ++- XBOXOLD.cpp | 66 +++++----- XBOXOLD.h | 2 +- XBOXRECV.cpp | 114 ++++++++-------- XBOXRECV.h | 2 +- XBOXUSB.cpp | 64 ++++----- address.h | 12 +- adk.cpp | 50 +++---- adk.h | 12 +- avrpins.h | 2 +- cdcacm.cpp | 40 +++--- cdcacm.h | 25 ++-- cdcftdi.cpp | 56 ++++---- cdcftdi.h | 2 +- cdcprolific.cpp | 34 +++-- confdescparser.h | 24 ++-- controllerEnums.h | 2 +- hexdump.h | 2 +- hid.cpp | 3 +- hid.h | 1 - hidescriptorparser.cpp | 98 +++++++------- hidescriptorparser.h | 5 +- hiduniversal.cpp | 104 +++++++-------- hiduniversal.h | 2 +- hidusagestr.h | 2 +- hidusagetitlearrays.cpp | 2 +- macros.h | 1 + masstorage.cpp | 216 +++++++++++++++--------------- masstorage.h | 4 +- max_LCD.cpp | 10 +- max_LCD.h | 5 +- message.cpp | 20 +-- parsetools.cpp | 16 +-- parsetools.h | 6 +- printhex.h | 14 +- sink_parser.h | 13 +- usbhost.h | 22 ++-- usbhub.cpp | 212 +++++++++++++++--------------- usbhub.h | 24 ++-- xboxEnums.h | 2 +- 54 files changed, 1370 insertions(+), 1310 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 8c8093b9..7fc278da 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -36,12 +36,12 @@ qNextPollTime(0), // Reset NextPollTime pollInterval(0), bPollEnable(false) // Don't start polling before dongle is connected { - for (uint8_t i = 0; i < BTD_NUMSERVICES; i++) + for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) btService[i] = NULL; Initialize(); // Set all variables, endpoint structs etc. to default values - if (pUsb) // Register in USB subsystem + if(pUsb) // Register in USB subsystem pUsb->RegisterDeviceClass(this); // Set devConfig[] entry } @@ -60,7 +60,7 @@ uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nBTD ConfigureDevice"), 0x80); #endif - if (bAddress) { // Check if address has already been assigned to an instance + if(bAddress) { // Check if address has already been assigned to an instance #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress in use"), 0x80); #endif @@ -68,14 +68,14 @@ uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { } p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } - if (!p->epinfo) { + if(!p->epinfo) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nepinfo is null"), 0x80); #endif @@ -89,12 +89,12 @@ uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { p->epinfo = oldep_ptr; // Restore p->epinfo - if (rcode) + if(rcode) goto FailGetDevDescr; bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class - if (!bAddress) { + if(!bAddress) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nOut of address space"), 0x80); #endif @@ -113,7 +113,7 @@ FailGetDevDescr: #ifdef DEBUG_USB_HOST NotifyFailGetDevDescr(rcode); #endif - if (rcode != hrJERR) + if(rcode != hrJERR) rcode = USB_ERROR_FailGetDevDescr; Release(); return rcode; @@ -130,7 +130,7 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { #endif UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif @@ -140,7 +140,7 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { delay(300); // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device - if (rcode) { + if(rcode) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nsetAddr: "), 0x80); D_PrintHex (rcode, 0x80); @@ -156,7 +156,7 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = false; p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif @@ -166,18 +166,18 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = lowspeed; rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known - if (rcode) + if(rcode) goto FailSetDevTblEntry; - if (VID == PS3_VID && (PID == PS3_PID || PID == PS3NAVIGATION_PID || PID == PS3MOVE_PID)) { + if(VID == PS3_VID && (PID == PS3_PID || PID == PS3NAVIGATION_PID || PID == PS3MOVE_PID)) { delay(100); 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 - if (rcode) + if(rcode) goto FailSetConfDescr; #ifdef DEBUG_USB_HOST - if (PID == PS3_PID || PID == PS3NAVIGATION_PID) { - if (PID == PS3_PID) + if(PID == PS3_PID || PID == PS3NAVIGATION_PID) { + if(PID == PS3_PID) Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80); else // It must be a navigation controller Notify(PSTR("\r\nNavigation Controller Connected"), 0x80); @@ -185,18 +185,18 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nMotion Controller Connected"), 0x80); #endif - 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) { + 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) { #ifdef DEBUG_USB_HOST 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); #endif } else { - if (PID == PS3_PID || PID == PS3NAVIGATION_PID) + if(PID == PS3_PID || PID == PS3NAVIGATION_PID) setBdaddr(my_bdaddr); // Set internal Bluetooth address else setMoveBdaddr(my_bdaddr); // Set internal Bluetooth address #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nBluetooth Address was set to: "), 0x80); - for (int8_t i = 5; i > 0; i--) { + for(int8_t i = 5; i > 0; i--) { D_PrintHex (my_bdaddr[i], 0x80); Notify(PSTR(":"), 0x80); } @@ -212,31 +212,31 @@ uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Check if attached device is a Bluetooth dongle and fill endpoint data structure // First interface in the configuration must have Bluetooth assigned Class/Subclass/Protocol // And 3 endpoints - interrupt-IN, bulk-IN, bulk-OUT, not necessarily in this order - for (uint8_t i = 0; i < num_of_conf; i++) { - if (VID == IOGEAR_GBU521_VID && PID == IOGEAR_GBU521_PID) { + for(uint8_t i = 0; i < num_of_conf; i++) { + if(VID == IOGEAR_GBU521_VID && PID == IOGEAR_GBU521_PID) { ConfigDescParser confDescrParser(this); // Needed for the IOGEAR GBU521 rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); } else { ConfigDescParser confDescrParser(this); rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); } - if (rcode) // Check error code + if(rcode) // Check error code goto FailGetConfDescr; - if (bNumEP >= BTD_MAX_ENDPOINTS) // All endpoints extracted + if(bNumEP >= BTD_MAX_ENDPOINTS) // All endpoints extracted break; } - if (bNumEP < BTD_MAX_ENDPOINTS) + if(bNumEP < BTD_MAX_ENDPOINTS) goto FailUnknownDevice; // Assign epInfo to epinfo pointer - this time all 3 endpoins rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; // Set Configuration Value rcode = pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bConfNum); - if (rcode) + if(rcode) goto FailSetConfDescr; hci_num_reset_loops = 100; // only loop 100 times before trying to send the hci reset command @@ -287,14 +287,14 @@ Fail: void BTD::Initialize() { uint8_t i; - for (i = 0; i < BTD_MAX_ENDPOINTS; i++) { + for(i = 0; i < BTD_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; } - for (i = 0; i < BTD_NUMSERVICES; i++) { - if (btService[i]) + for(i = 0; i < BTD_NUMSERVICES; i++) { + if(btService[i]) btService[i]->Reset(); // Reset all Bluetooth services } @@ -315,17 +315,17 @@ void BTD::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto //ErrorMessage(PSTR("Iface Num"),iface); //ErrorMessage(PSTR("Alt.Set"),alt); - if (alt) // Wrong interface - by BT spec, no alt setting + if(alt) // Wrong interface - by BT spec, no alt setting return; bConfNum = conf; uint8_t index; - if ((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { // Interrupt In endpoint found + if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { // Interrupt In endpoint found index = BTD_EVENT_PIPE; epInfo[index].bmNakPower = USB_NAK_NOWAIT; } else { - if ((pep->bmAttributes & 0x02) == 2) // Bulk endpoint found + if((pep->bmAttributes & 0x02) == 2) // Bulk endpoint found index = ((pep->bEndpointAddress & 0x80) == 0x80) ? BTD_DATAIN_PIPE : BTD_DATAOUT_PIPE; else return; @@ -337,7 +337,7 @@ void BTD::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto #ifdef EXTRADEBUG PrintEndpointDescriptor(pep); #endif - if (pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints + if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints pollInterval = pep->bInterval; bNumEP++; } @@ -368,9 +368,9 @@ uint8_t BTD::Release() { } uint8_t BTD::Poll() { - if (!bPollEnable) + if(!bPollEnable) return 0; - if (qNextPollTime <= millis()) { // Don't poll if shorter than polling interval + if(qNextPollTime <= millis()) { // Don't poll if shorter than polling interval qNextPollTime = millis() + pollInterval; // Set new poll time HCI_event_task(); // Poll the HCI event pipe HCI_task(); // HCI state machine @@ -383,16 +383,16 @@ void BTD::HCI_event_task() { uint16_t length = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &length, hcibuf); // Input on endpoint 1 - if (!rcode || rcode == hrNAK) { // Check for errors - switch (hcibuf[0]) { // Switch on event type + if(!rcode || rcode == hrNAK) { // Check for errors + switch(hcibuf[0]) { // Switch on event type case EV_COMMAND_COMPLETE: - if (!hcibuf[5]) { // Check if command succeeded + if(!hcibuf[5]) { // Check if command succeeded hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag - if ((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information + if((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm hci_set_flag(HCI_FLAG_READ_VERSION); - } else if ((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address - for (uint8_t i = 0; i < 6; i++) + } else if((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address + for(uint8_t i = 0; i < 6; i++) my_bdaddr[i] = hcibuf[6 + i]; hci_set_flag(HCI_FLAG_READ_BDADDR); } @@ -400,7 +400,7 @@ void BTD::HCI_event_task() { break; case EV_COMMAND_STATUS: - if (hcibuf[2]) { // Show status on serial if not OK + if(hcibuf[2]) { // Show status on serial if not OK #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHCI Command Failed: "), 0x80); D_PrintHex (hcibuf[2], 0x80); @@ -409,10 +409,10 @@ void BTD::HCI_event_task() { break; case EV_INQUIRY_COMPLETE: - if (inquiry_counter >= 5 && (pairWithWii || pairWithHIDDevice)) { + if(inquiry_counter >= 5 && (pairWithWii || pairWithHIDDevice)) { inquiry_counter = 0; #ifdef DEBUG_USB_HOST - if (pairWithWii) + if(pairWithWii) Notify(PSTR("\r\nCouldn't find Wiimote"), 0x80); else Notify(PSTR("\r\nCouldn't find HID device"), 0x80); @@ -427,38 +427,38 @@ void BTD::HCI_event_task() { break; case EV_INQUIRY_RESULT: - if (hcibuf[2]) { // Check that there is more than zero responses + if(hcibuf[2]) { // Check that there is more than zero responses #ifdef EXTRADEBUG Notify(PSTR("\r\nNumber of responses: "), 0x80); Notify(hcibuf[2], 0x80); #endif - for (uint8_t i = 0; i < hcibuf[2]; i++) { + for(uint8_t i = 0; i < hcibuf[2]; i++) { uint8_t offset = 8 * hcibuf[2] + 3 * i; uint8_t classOfDevice[3]; - for (uint8_t j = 0; j < 3; j++) + for(uint8_t j = 0; j < 3; j++) classOfDevice[j] = hcibuf[j + 4 + offset]; - if (pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information - if (classOfDevice[0] & 0x08) // Check if it's the new Wiimote with motion plus inside that was detected + if(pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information + if(classOfDevice[0] & 0x08) // Check if it's the new Wiimote with motion plus inside that was detected motionPlusInside = true; else motionPlusInside = false; - for (uint8_t j = 0; j < 6; j++) + for(uint8_t j = 0; j < 6; j++) disc_bdaddr[j] = hcibuf[j + 3 + 6 * i]; hci_set_flag(HCI_FLAG_DEVICE_FOUND); break; - } else if (pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC0)) { // Check if it is a mouse or keyboard - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html + } else if(pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC0)) { // Check if it is a mouse or keyboard - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html #ifdef DEBUG_USB_HOST - if (classOfDevice[0] & 0x80) + if(classOfDevice[0] & 0x80) Notify(PSTR("\r\nMouse found"), 0x80); - if (classOfDevice[0] & 0x40) + if(classOfDevice[0] & 0x40) Notify(PSTR("\r\nKeyboard found"), 0x80); #endif - for (uint8_t j = 0; j < 6; j++) + for(uint8_t j = 0; j < 6; j++) disc_bdaddr[j] = hcibuf[j + 3 + 6 * i]; hci_set_flag(HCI_FLAG_DEVICE_FOUND); @@ -479,7 +479,7 @@ void BTD::HCI_event_task() { case EV_CONNECT_COMPLETE: hci_set_flag(HCI_FLAG_CONNECT_EVENT); - if (!hcibuf[2]) { // Check if connected OK + if(!hcibuf[2]) { // Check if connected OK #ifdef EXTRADEBUG Notify(PSTR("\r\nConnection established"), 0x80); #endif @@ -495,17 +495,17 @@ void BTD::HCI_event_task() { break; case EV_DISCONNECT_COMPLETE: - if (!hcibuf[2]) { // Check if disconnected OK + if(!hcibuf[2]) { // Check if disconnected OK hci_set_flag(HCI_FLAG_DISCONNECT_COMPLETE); // Set disconnect command complete flag hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); // Clear connection complete flag } break; case EV_REMOTE_NAME_COMPLETE: - if (!hcibuf[2]) { // Check if reading is OK - for (uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) { + if(!hcibuf[2]) { // Check if reading is OK + for(uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) { remote_name[i] = hcibuf[9 + i]; - if (remote_name[i] == '\0') // End of string + if(remote_name[i] == '\0') // End of string break; } hci_set_flag(HCI_FLAG_REMOTE_NAME_COMPLETE); @@ -513,14 +513,14 @@ void BTD::HCI_event_task() { break; case EV_INCOMING_CONNECT: - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) disc_bdaddr[i] = hcibuf[i + 2]; - if ((hcibuf[9] & 0x05) && (hcibuf[8] & 0xC0)) { // Check if it is a mouse or keyboard + if((hcibuf[9] & 0x05) && (hcibuf[8] & 0xC0)) { // Check if it is a mouse or keyboard #ifdef DEBUG_USB_HOST - if (hcibuf[8] & 0x80) + if(hcibuf[8] & 0x80) Notify(PSTR("\r\nMouse is connecting"), 0x80); - if (hcibuf[8] & 0x40) + if(hcibuf[8] & 0x40) Notify(PSTR("\r\nKeyboard is connecting"), 0x80); #endif incomingHIDDevice = true; @@ -538,12 +538,12 @@ void BTD::HCI_event_task() { break; case EV_PIN_CODE_REQUEST: - if (pairWithWii) { + if(pairWithWii) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nPairing with wiimote"), 0x80); #endif hci_pin_code_request_reply(); - } else if (btdPin != NULL) { + } else if(btdPin != NULL) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nBluetooth pin is set too: "), 0x80); NotifyStr(btdPin, 0x80); @@ -565,12 +565,12 @@ void BTD::HCI_event_task() { break; case EV_AUTHENTICATION_COMPLETE: - if (pairWithWii && !connectToWii) { + if(pairWithWii && !connectToWii) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nPairing successful with Wiimote"), 0x80); #endif connectToWii = true; // Used to indicate to the Wii service, that it should connect to this device - } else if (pairWithHIDDevice && !connectToHIDDevice) { + } else if(pairWithHIDDevice && !connectToHIDDevice) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nPairing successful with HID device"), 0x80); #endif @@ -592,7 +592,7 @@ void BTD::HCI_event_task() { break; #ifdef EXTRADEBUG default: - if (hcibuf[0] != 0x00) { + if(hcibuf[0] != 0x00) { Notify(PSTR("\r\nUnmanaged HCI Event: "), 0x80); D_PrintHex (hcibuf[0], 0x80); } @@ -610,10 +610,10 @@ void BTD::HCI_event_task() { /* Poll Bluetooth and print result */ void BTD::HCI_task() { - switch (hci_state) { + switch(hci_state) { case HCI_INIT_STATE: hci_counter++; - if (hci_counter > hci_num_reset_loops) { // wait until we have looped x times to clear any old events + if(hci_counter > hci_num_reset_loops) { // wait until we have looped x times to clear any old events hci_reset(); hci_state = HCI_RESET_STATE; hci_counter = 0; @@ -622,16 +622,16 @@ void BTD::HCI_task() { case HCI_RESET_STATE: hci_counter++; - if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { hci_counter = 0; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHCI Reset complete"), 0x80); #endif hci_state = HCI_CLASS_STATE; hci_write_class_of_device(); - } else if (hci_counter > hci_num_reset_loops) { + } else if(hci_counter > hci_num_reset_loops) { hci_num_reset_loops *= 10; - if (hci_num_reset_loops > 2000) + if(hci_num_reset_loops > 2000) hci_num_reset_loops = 2000; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nNo response to HCI Reset"), 0x80); @@ -642,7 +642,7 @@ void BTD::HCI_task() { break; case HCI_CLASS_STATE: - if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nWrite class of device"), 0x80); #endif @@ -652,10 +652,10 @@ void BTD::HCI_task() { break; case HCI_BDADDR_STATE: - if (hci_check_flag(HCI_FLAG_READ_BDADDR)) { + if(hci_check_flag(HCI_FLAG_READ_BDADDR)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nLocal Bluetooth Address: "), 0x80); - for (int8_t i = 5; i > 0; i--) { + for(int8_t i = 5; i > 0; i--) { D_PrintHex (my_bdaddr[i], 0x80); Notify(PSTR(":"), 0x80); } @@ -667,8 +667,8 @@ void BTD::HCI_task() { break; case HCI_LOCAL_VERSION_STATE: // The local version is used by the PS3BT class - if (hci_check_flag(HCI_FLAG_READ_VERSION)) { - if (btdName != NULL) { + if(hci_check_flag(HCI_FLAG_READ_VERSION)) { + if(btdName != NULL) { hci_set_local_name(btdName); hci_state = HCI_SET_NAME_STATE; } else @@ -677,7 +677,7 @@ void BTD::HCI_task() { break; case HCI_SET_NAME_STATE: - if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nThe name is set to: "), 0x80); NotifyStr(btdName, 0x80); @@ -687,9 +687,9 @@ void BTD::HCI_task() { break; case HCI_CHECK_DEVICE_SERVICE: - if (pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote + if(pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote #ifdef DEBUG_USB_HOST - if (pairWithWii) + if(pairWithWii) Notify(PSTR("\r\nStarting inquiry\r\nPress 1 & 2 on the Wiimote\r\nOr press sync if you are using a Wii U Pro Controller"), 0x80); else Notify(PSTR("\r\nPlease enable discovery of your device"), 0x80); @@ -701,27 +701,27 @@ void BTD::HCI_task() { break; case HCI_INQUIRY_STATE: - if (hci_check_flag(HCI_FLAG_DEVICE_FOUND)) { + if(hci_check_flag(HCI_FLAG_DEVICE_FOUND)) { hci_inquiry_cancel(); // Stop inquiry #ifdef DEBUG_USB_HOST - if (pairWithWii) + if(pairWithWii) Notify(PSTR("\r\nWiimote found"), 0x80); else Notify(PSTR("\r\nHID device found"), 0x80); Notify(PSTR("\r\nNow just create the instance like so:"), 0x80); - if (pairWithWii) + if(pairWithWii) Notify(PSTR("\r\nWII Wii(&Btd);"), 0x80); else Notify(PSTR("\r\nBTHID hid(&Btd);"), 0x80); Notify(PSTR("\r\nAnd then press any button on the "), 0x80); - if (pairWithWii) + if(pairWithWii) Notify(PSTR("Wiimote"), 0x80); else Notify(PSTR("device"), 0x80); #endif - if (motionPlusInside) { + if(motionPlusInside) { hci_remote_name(); // We need to know the name to distinguish between a Wiimote and a Wii U Pro Controller hci_state = HCI_REMOTE_NAME_STATE; } else @@ -730,9 +730,9 @@ void BTD::HCI_task() { break; case HCI_CONNECT_DEVICE_STATE: - if (hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) { #ifdef DEBUG_USB_HOST - if (pairWithWii) + if(pairWithWii) Notify(PSTR("\r\nConnecting to Wiimote"), 0x80); else Notify(PSTR("\r\nConnecting to HID device"), 0x80); @@ -743,10 +743,10 @@ void BTD::HCI_task() { break; case HCI_CONNECTED_DEVICE_STATE: - if (hci_check_flag(HCI_FLAG_CONNECT_EVENT)) { - if (hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_CONNECT_EVENT)) { + if(hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) { #ifdef DEBUG_USB_HOST - if (pairWithWii) + if(pairWithWii) Notify(PSTR("\r\nConnected to Wiimote"), 0x80); else Notify(PSTR("\r\nConnected to HID device"), 0x80); @@ -763,7 +763,7 @@ void BTD::HCI_task() { break; case HCI_SCANNING_STATE: - if (!connectToWii && !pairWithWii && !connectToHIDDevice && !pairWithHIDDevice) { + if(!connectToWii && !pairWithWii && !connectToHIDDevice && !pairWithHIDDevice) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nWait For Incoming Connection Request"), 0x80); #endif @@ -774,38 +774,38 @@ void BTD::HCI_task() { break; case HCI_CONNECT_IN_STATE: - if (hci_check_flag(HCI_FLAG_INCOMING_REQUEST)) { + if(hci_check_flag(HCI_FLAG_INCOMING_REQUEST)) { watingForConnection = false; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nIncoming Connection Request"), 0x80); #endif hci_remote_name(); hci_state = HCI_REMOTE_NAME_STATE; - } else if (hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) + } else if(hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) hci_state = HCI_DISCONNECT_STATE; break; case HCI_REMOTE_NAME_STATE: - if (hci_check_flag(HCI_FLAG_REMOTE_NAME_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_REMOTE_NAME_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRemote Name: "), 0x80); - for (uint8_t i = 0; i < 30; i++) { - if (remote_name[i] == '\0') // End of string + for(uint8_t i = 0; i < 30; i++) { + if(remote_name[i] == '\0') // End of string break; Notifyc(remote_name[i], 0x80); } #endif - if (strncmp((const char*)remote_name, "Nintendo", 8) == 0) { + if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) { incomingWii = true; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nWiimote is connecting"), 0x80); #endif - if (strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) { + if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) { #ifdef DEBUG_USB_HOST Notify(PSTR(" with Motion Plus Inside"), 0x80); #endif motionPlusInside = true; - } else if (strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) { + } else if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) { #ifdef DEBUG_USB_HOST Notify(PSTR(" - Wii U Pro Controller"), 0x80); #endif @@ -816,7 +816,7 @@ void BTD::HCI_task() { wiiUProController = false; } } - if (pairWithWii && motionPlusInside) + if(pairWithWii && motionPlusInside) hci_state = HCI_CONNECT_DEVICE_STATE; else { hci_accept_connection(); @@ -826,10 +826,10 @@ void BTD::HCI_task() { break; case HCI_CONNECTED_STATE: - if (hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nConnected to Device: "), 0x80); - for (int8_t i = 5; i > 0; i--) { + for(int8_t i = 5; i > 0; i--) { D_PrintHex (disc_bdaddr[i], 0x80); Notify(PSTR(":"), 0x80); } @@ -847,14 +847,14 @@ void BTD::HCI_task() { case HCI_DONE_STATE: hci_counter++; - if (hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started + if(hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started hci_counter = 0; hci_state = HCI_SCANNING_STATE; } break; case HCI_DISCONNECT_STATE: - if (hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) { + if(hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80); #endif @@ -879,22 +879,22 @@ void BTD::ACL_event_task() { uint16_t length = BULK_MAXPKTSIZE; uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf); // Input on endpoint 2 - if (!rcode) { // Check for errors - if (length > 0) { // Check if any data was read - for (uint8_t i = 0; i < BTD_NUMSERVICES; i++) { - if (btService[i]) + if(!rcode) { // Check for errors + if(length > 0) { // Check if any data was read + for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) { + if(btService[i]) btService[i]->ACLData(l2capinbuf); } } } #ifdef EXTRADEBUG - else if (rcode != hrNAK) { + else if(rcode != hrNAK) { Notify(PSTR("\r\nACL data in error: "), 0x80); D_PrintHex (rcode, 0x80); } #endif - for (uint8_t i = 0; i < BTD_NUMSERVICES; i++) - if (btService[i]) + for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) + if(btService[i]) btService[i]->Run(); } @@ -921,7 +921,7 @@ void BTD::hci_write_scan_enable() { hcibuf[0] = 0x1A; // HCI OCF = 1A hcibuf[1] = 0x03 << 2; // HCI OGF = 3 hcibuf[2] = 0x01; // parameter length = 1 - if (btdName != NULL) + if(btdName != NULL) hcibuf[3] = 0x03; // Inquiry Scan enabled. Page Scan enabled. else hcibuf[3] = 0x02; // Inquiry Scan disabled. Page Scan enabled. @@ -996,7 +996,7 @@ void BTD::hci_set_local_name(const char* name) { hcibuf[1] = 0x03 << 2; // HCI OGF = 3 hcibuf[2] = strlen(name) + 1; // parameter length = the length of the string + end byte uint8_t i; - for (i = 0; i < strlen(name); i++) + for(i = 0; i < strlen(name); i++) hcibuf[i + 3] = name[i]; hcibuf[i + 3] = 0x00; // End of string @@ -1061,26 +1061,26 @@ void BTD::hci_pin_code_request_reply() { hcibuf[6] = disc_bdaddr[3]; hcibuf[7] = disc_bdaddr[4]; hcibuf[8] = disc_bdaddr[5]; - if (pairWithWii) { + if(pairWithWii) { hcibuf[9] = 6; // Pin length is the length of the Bluetooth address - if (wiiUProController) { + if(wiiUProController) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nParing with Wii U Pro Controller"), 0x80); #endif - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) hcibuf[10 + i] = my_bdaddr[i]; // The pin is the Bluetooth dongles Bluetooth address backwards } else { - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) hcibuf[10 + i] = disc_bdaddr[i]; // The pin is the Wiimote's Bluetooth address backwards } - for (uint8_t i = 16; i < 26; i++) + for(uint8_t i = 16; i < 26; i++) hcibuf[i] = 0x00; // The rest should be 0 } else { hcibuf[9] = strlen(btdPin); // Length of pin uint8_t i; - for (i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16 + for(i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16 hcibuf[i + 10] = btdPin[i]; - for (; i < 16; i++) + for(; i < 16; i++) hcibuf[i + 10] = 0x00; // The rest should be 0 } @@ -1184,11 +1184,11 @@ void BTD::L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t buf[6] = channelLow; buf[7] = channelHigh; - for (uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame + for(uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame buf[8 + i] = data[i]; uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ BTD_DATAOUT_PIPE ].epAddr, (8 + nbytes), buf); - if (rcode) { + if(rcode) { delay(100); // This small delay prevents it from overflowing if it fails #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nError sending L2CAP message: 0x"), 0x80); @@ -1317,7 +1317,7 @@ void BTD::setBdaddr(uint8_t* bdaddr) { buf[0] = 0x01; buf[1] = 0x00; - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first // 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 @@ -1333,7 +1333,7 @@ void BTD::setMoveBdaddr(uint8_t* bdaddr) { buf[9] = 0x02; buf[10] = 0x12; - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) buf[i + 1] = bdaddr[i]; // 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 diff --git a/BTD.h b/BTD.h index cc328deb..e870427d 100755 --- a/BTD.h +++ b/BTD.h @@ -262,12 +262,15 @@ public: virtual bool isReady() { return bPollEnable; }; + /** * Used by the USB core to check what this driver support. * @param klass The device's USB class. * @return Returns true if the device's USB class matches this driver. */ - virtual boolean DEVCLASSOK(uint8_t klass) { return (klass == USB_CLASS_WIRELESS_CTRL); } + virtual boolean DEVCLASSOK(uint8_t klass) { + return (klass == USB_CLASS_WIRELESS_CTRL); + } /** * Used by the USB core to check what this driver support. @@ -277,10 +280,10 @@ public: * @return Returns true if the device's VID and PID matches this driver. */ virtual boolean VIDPIDOK(uint16_t vid, uint16_t pid) { - if (vid == IOGEAR_GBU521_VID && pid == IOGEAR_GBU521_PID) + if(vid == IOGEAR_GBU521_VID && pid == IOGEAR_GBU521_PID) return true; - 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 - if (vid == PS3_VID && (pid == PS3_PID || pid == PS3NAVIGATION_PID || pid == PS3MOVE_PID)) + 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 + if(vid == PS3_VID && (pid == PS3_PID || pid == PS3NAVIGATION_PID || pid == PS3MOVE_PID)) return true; } return false; diff --git a/BTHID.cpp b/BTHID.cpp index 5d1451a9..39575aea 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -22,16 +22,15 @@ BTHID::BTHID(BTD *p, bool pair, const char *pin) : pBtd(p), // pointer to USB class instance - mandatory -protocolMode(HID_BOOT_PROTOCOL) -{ - for (uint8_t i = 0; i < NUM_PARSERS; i++) +protocolMode(HID_BOOT_PROTOCOL) { + for(uint8_t i = 0; i < NUM_PARSERS; i++) pRptParser[i] = NULL; - if (pBtd) + if(pBtd) pBtd->registerServiceClass(this); // Register it as a Bluetooth service pBtd->pairWithHIDDevice = pair; - pBtd->btdPin= pin; + pBtd->btdPin = pin; /* Set device cid for the control and intterrupt channelse - LSB */ control_dcid[0] = 0x70; // 0x0070 @@ -57,9 +56,9 @@ void BTHID::disconnect() { // Use this void to disconnect any of the controllers } void BTHID::ACLData(uint8_t* l2capinbuf) { - if (!pBtd->l2capConnectionClaimed && pBtd->incomingHIDDevice && !connected && !activeConnection) { - if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { - if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { + if(!pBtd->l2capConnectionClaimed && pBtd->incomingHIDDevice && !connected && !activeConnection) { + if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { + if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { pBtd->incomingHIDDevice = false; pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service activeConnection = true; @@ -68,9 +67,9 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { } } } - if ((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U - if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { + if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U + if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -85,15 +84,15 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" "), 0x80); D_PrintHex (l2capinbuf[14], 0x80); #endif - } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) { - if (((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success - if (l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) { + if(((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success + if(l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Connection Complete"), 0x80); identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[12]; control_scid[1] = l2capinbuf[13]; l2cap_set_flag(L2CAP_FLAG_CONTROL_CONNECTED); - } else if (l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) { + } else if(l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80); identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[12]; @@ -101,7 +100,7 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { l2cap_set_flag(L2CAP_FLAG_INTERRUPT_CONNECTED); } } - } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { #ifdef EXTRADEBUG Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -114,46 +113,46 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" Identifier: "), 0x80); D_PrintHex (l2capinbuf[9], 0x80); #endif - if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { + if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[14]; control_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST); - } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { + } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[14]; interrupt_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST); } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { - if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { + if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS); } } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], control_scid); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], interrupt_scid); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80); #endif identifier = l2capinbuf[9]; pBtd->l2cap_disconnection_response(hci_handle, identifier, control_dcid, control_scid); Reset(); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80); #endif @@ -161,12 +160,12 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { pBtd->l2cap_disconnection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid); Reset(); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { - if (l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { + if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE); - } else if (l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { + } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE); @@ -179,27 +178,27 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { D_PrintHex (l2capinbuf[8], 0x80); } #endif - } else if (l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt + } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt #ifdef PRINTREPORT Notify(PSTR("\r\nL2CAP Interrupt: "), 0x80); - for (uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) { + for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) { D_PrintHex (l2capinbuf[i + 8], 0x80); Notify(PSTR(" "), 0x80); } #endif - if (l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT - switch (l2capinbuf[9]) { + if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT + switch(l2capinbuf[9]) { case 0x01: // Keyboard events - if (pRptParser[KEYBOARD_PARSER_ID]) { - uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); - pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast (this), 0, (uint8_t) length, &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance + if(pRptParser[KEYBOARD_PARSER_ID]) { + uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); + pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)length, &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance } break; case 0x02: // Mouse events - if (pRptParser[MOUSE_PARSER_ID]) { - uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); - pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast (this), 0, (uint8_t) length, &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance + if(pRptParser[MOUSE_PARSER_ID]) { + uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); + pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)length, &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance } break; #ifdef DEBUG_USB_HOST @@ -210,10 +209,10 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { #endif } } - } else if (l2capinbuf[6] == control_dcid[0] && l2capinbuf[7] == control_dcid[1]) { // l2cap_control + } else if(l2capinbuf[6] == control_dcid[0] && l2capinbuf[7] == control_dcid[1]) { // l2cap_control #ifdef PRINTREPORT Notify(PSTR("\r\nL2CAP Control: "), 0x80); - for (uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) { + for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) { D_PrintHex (l2capinbuf[i + 8], 0x80); Notify(PSTR(" "), 0x80); } @@ -228,7 +227,7 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { Notify(PSTR("\r\nData: "), 0x80); Notify(PSTR("\r\n"), 0x80); - for (uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) { + for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) { D_PrintHex (l2capinbuf[i + 8], 0x80); Notify(PSTR(" "), 0x80); } @@ -239,10 +238,10 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { } void BTHID::L2CAP_task() { - switch (l2cap_state) { + switch(l2cap_state) { /* These states are used if the HID device is the host */ case L2CAP_CONTROL_SUCCESS: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80); #endif @@ -252,7 +251,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_SETUP: - if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { + if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80); #endif @@ -269,7 +268,7 @@ void BTHID::L2CAP_task() { /* These states are used if the Arduino is the host */ case L2CAP_CONTROL_CONNECT_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) { + if(l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Control Config Request"), 0x80); #endif @@ -280,7 +279,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_CONTROL_CONFIG_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { setProtocol(); // Set protocol before establishing HID interrupt channel delay(1); // Short delay between commands - just to be sure #ifdef DEBUG_USB_HOST @@ -293,7 +292,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_CONNECT_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) { + if(l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80); #endif @@ -304,7 +303,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_CONFIG_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Channels Established"), 0x80); #endif @@ -320,7 +319,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_INTERRUPT_DISCONNECT: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80); #endif @@ -331,7 +330,7 @@ void BTHID::L2CAP_task() { break; case L2CAP_CONTROL_DISCONNECT: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Control Channel"), 0x80); #endif @@ -345,9 +344,9 @@ void BTHID::L2CAP_task() { } void BTHID::Run() { - switch (l2cap_state) { + switch(l2cap_state) { case L2CAP_WAIT: - if (pBtd->connectToHIDDevice && !pBtd->l2capConnectionClaimed && !connected && !activeConnection) { + if(pBtd->connectToHIDDevice && !pBtd->l2capConnectionClaimed && !connected && !activeConnection) { pBtd->l2capConnectionClaimed = true; activeConnection = true; #ifdef DEBUG_USB_HOST @@ -358,7 +357,7 @@ void BTHID::Run() { identifier = 0; pBtd->l2cap_connection_request(hci_handle, identifier, control_dcid, HID_CTRL_PSM); l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST; - } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { + } else if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80); #endif @@ -376,6 +375,7 @@ void BTHID::Run() { /************************************************************/ /* HID Commands */ + /************************************************************/ void BTHID::setProtocol() { #ifdef DEBUG_USB_HOST @@ -392,4 +392,4 @@ void BTHID::setLeds(uint8_t data) { buf[1] = 0x01; // Report ID buf[2] = data; pBtd->L2CAP_Command(hci_handle, buf, 3, interrupt_scid[0], interrupt_scid[1]); -} \ No newline at end of file +} diff --git a/BTHID.h b/BTHID.h index b4cb21f2..e8842e6b 100644 --- a/BTHID.h +++ b/BTHID.h @@ -48,6 +48,7 @@ public: virtual void Reset(); /** Used this to disconnect any of the controllers. */ virtual void disconnect(); + /**@}*/ HIDReportParser *GetReportParser(uint8_t id) { @@ -71,7 +72,7 @@ public: /** Call this to start the paring sequence with a controller */ void pair(void) { - if (pBtd) + if(pBtd) pBtd->pairWithHID(); }; @@ -98,7 +99,7 @@ private: * This is useful for instance if you want to set the LEDs in a specific way. */ void onInit() { - if (pFuncOnInit) + if(pFuncOnInit) pFuncOnInit(); // Call the user function } void (*pFuncOnInit)(void); // Pointer to function called in onInit() @@ -120,4 +121,4 @@ private: uint8_t interrupt_dcid[2]; // 0x0071 uint8_t identifier; // Identifier for connection }; -#endif \ No newline at end of file +#endif diff --git a/PS3BT.cpp b/PS3BT.cpp index ac185576..fbcb5dfc 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -23,7 +23,7 @@ PS3BT::PS3BT(BTD *p, uint8_t btadr5, uint8_t btadr4, uint8_t btadr3, uint8_t btadr2, uint8_t btadr1, uint8_t btadr0) : pBtd(p) // pointer to USB class instance - mandatory { - if (pBtd) + if(pBtd) pBtd->registerServiceClass(this); // Register it as a Bluetooth service pBtd->my_bdaddr[5] = btadr5; // Change to your dongle's Bluetooth address instead @@ -69,15 +69,15 @@ uint8_t PS3BT::getAnalogHat(AnalogHat a) { } int16_t PS3BT::getSensor(Sensor a) { - if (PS3Connected) { - if (a == aX || a == aY || a == aZ || a == gZ) + if(PS3Connected) { + if(a == aX || a == aY || a == aZ || a == gZ) return ((l2capinbuf[(uint16_t)a] << 8) | l2capinbuf[(uint16_t)a + 1]); else return 0; - } else if (PS3MoveConnected) { - if (a == mXmove || a == mYmove) // These are all 12-bits long + } else if(PS3MoveConnected) { + if(a == mXmove || a == mYmove) // These are all 12-bits long return (((l2capinbuf[(uint16_t)a] & 0x0F) << 8) | (l2capinbuf[(uint16_t)a + 1])); - else if (a == mZmove || a == tempMove) // The tempearature is also 12 bits long + else if(a == mZmove || a == tempMove) // The tempearature is also 12 bits long return ((l2capinbuf[(uint16_t)a] << 4) | ((l2capinbuf[(uint16_t)a + 1] & 0xF0) >> 4)); else // aXmove, aYmove, aZmove, gXmove, gYmove and gZmove return (l2capinbuf[(uint16_t)a] | (l2capinbuf[(uint16_t)a + 1] << 8)); @@ -88,13 +88,13 @@ int16_t PS3BT::getSensor(Sensor a) { double PS3BT::getAngle(Angle a) { double accXval, accYval, accZval; - if (PS3Connected) { + if(PS3Connected) { // Data for the Kionix KXPC4 used in the DualShock 3 const double zeroG = 511.5; // 1.65/3.3*1023 (1.65V) accXval = -((double)getSensor(aX) - zeroG); accYval = -((double)getSensor(aY) - zeroG); accZval = -((double)getSensor(aZ) - zeroG); - } else if (PS3MoveConnected) { + } else if(PS3MoveConnected) { // It's a Kionix KXSC4 inside the Motion controller const uint16_t zeroG = 0x8000; accXval = -(int16_t)(getSensor(aXmove) - zeroG); @@ -106,34 +106,34 @@ double PS3BT::getAngle(Angle a) { // Convert to 360 degrees resolution // atan2 outputs the value of -π to π (radians) // We are then converting it to 0 to 2π and then to degrees - if (a == Pitch) + if(a == Pitch) return (atan2(accYval, accZval) + PI) * RAD_TO_DEG; else return (atan2(accXval, accZval) + PI) * RAD_TO_DEG; } double PS3BT::get9DOFValues(Sensor a) { // Thanks to Manfred Piendl - if (!PS3MoveConnected) + if(!PS3MoveConnected) return 0; int16_t value = getSensor(a); - if (a == mXmove || a == mYmove || a == mZmove) { - if (value > 2047) + if(a == mXmove || a == mYmove || a == mZmove) { + if(value > 2047) value -= 0x1000; return (double)value / 3.2; // unit: muT = 10^(-6) Tesla - } else if (a == aXmove || a == aYmove || a == aZmove) { - if (value < 0) + } else if(a == aXmove || a == aYmove || a == aZmove) { + if(value < 0) value += 0x8000; else value -= 0x8000; return (double)value / 442.0; // unit: m/(s^2) - } else if (a == gXmove || a == gYmove || a == gZmove) { - if (value < 0) + } else if(a == gXmove || a == gYmove || a == gZmove) { + if(value < 0) value += 0x8000; else value -= 0x8000; - if (a == gXmove) + if(a == gXmove) return (double)value / 11.6; // unit: deg/s - else if (a == gYmove) + else if(a == gYmove) return (double)value / 11.2; // unit: deg/s else // gZmove return (double)value / 9.6; // unit: deg/s @@ -142,12 +142,12 @@ double PS3BT::get9DOFValues(Sensor a) { // Thanks to Manfred Piendl } String PS3BT::getTemperature() { - if (PS3MoveConnected) { + if(PS3MoveConnected) { int16_t input = getSensor(tempMove); String output = String(input / 100); output += "."; - if (input % 100 < 10) + if(input % 100 < 10) output += "0"; output += String(input % 100); @@ -161,48 +161,48 @@ bool PS3BT::getStatus(Status c) { } String PS3BT::getStatusString() { - if (PS3Connected || PS3NavigationConnected) { + if(PS3Connected || PS3NavigationConnected) { char statusOutput[100]; // Max string length plus null character strcpy_P(statusOutput, PSTR("ConnectionStatus: ")); - if (getStatus(Plugged)) strcat_P(statusOutput, PSTR("Plugged")); - else if (getStatus(Unplugged)) strcat_P(statusOutput, PSTR("Unplugged")); + if(getStatus(Plugged)) strcat_P(statusOutput, PSTR("Plugged")); + else if(getStatus(Unplugged)) strcat_P(statusOutput, PSTR("Unplugged")); else strcat_P(statusOutput, PSTR("Error")); strcat_P(statusOutput, PSTR(" - PowerRating: ")); - if (getStatus(Charging)) strcat_P(statusOutput, PSTR("Charging")); - else if (getStatus(NotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); - else if (getStatus(Shutdown)) strcat_P(statusOutput, PSTR("Shutdown")); - else if (getStatus(Dying)) strcat_P(statusOutput, PSTR("Dying")); - else if (getStatus(Low)) strcat_P(statusOutput, PSTR("Low")); - else if (getStatus(High)) strcat_P(statusOutput, PSTR("High")); - else if (getStatus(Full)) strcat_P(statusOutput, PSTR("Full")); + if(getStatus(Charging)) strcat_P(statusOutput, PSTR("Charging")); + else if(getStatus(NotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); + else if(getStatus(Shutdown)) strcat_P(statusOutput, PSTR("Shutdown")); + else if(getStatus(Dying)) strcat_P(statusOutput, PSTR("Dying")); + else if(getStatus(Low)) strcat_P(statusOutput, PSTR("Low")); + else if(getStatus(High)) strcat_P(statusOutput, PSTR("High")); + else if(getStatus(Full)) strcat_P(statusOutput, PSTR("Full")); else strcat_P(statusOutput, PSTR("Error")); strcat_P(statusOutput, PSTR(" - WirelessStatus: ")); - if (getStatus(CableRumble)) strcat_P(statusOutput, PSTR("Cable - Rumble is on")); - else if (getStatus(Cable)) strcat_P(statusOutput, PSTR("Cable - Rumble is off")); - else if (getStatus(BluetoothRumble)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is on")); - else if (getStatus(Bluetooth)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is off")); + if(getStatus(CableRumble)) strcat_P(statusOutput, PSTR("Cable - Rumble is on")); + else if(getStatus(Cable)) strcat_P(statusOutput, PSTR("Cable - Rumble is off")); + else if(getStatus(BluetoothRumble)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is on")); + else if(getStatus(Bluetooth)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is off")); else strcat_P(statusOutput, PSTR("Error")); return statusOutput; - } else if (PS3MoveConnected) { + } else if(PS3MoveConnected) { char statusOutput[26]; // Max string length plus null character strcpy_P(statusOutput, PSTR("PowerRating: ")); - if (getStatus(MoveCharging)) strcat_P(statusOutput, PSTR("Charging")); - else if (getStatus(MoveNotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); - else if (getStatus(MoveShutdown)) strcat_P(statusOutput, PSTR("Shutdown")); - else if (getStatus(MoveDying)) strcat_P(statusOutput, PSTR("Dying")); - else if (getStatus(MoveLow)) strcat_P(statusOutput, PSTR("Low")); - else if (getStatus(MoveHigh)) strcat_P(statusOutput, PSTR("High")); - else if (getStatus(MoveFull)) strcat_P(statusOutput, PSTR("Full")); + if(getStatus(MoveCharging)) strcat_P(statusOutput, PSTR("Charging")); + else if(getStatus(MoveNotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); + else if(getStatus(MoveShutdown)) strcat_P(statusOutput, PSTR("Shutdown")); + else if(getStatus(MoveDying)) strcat_P(statusOutput, PSTR("Dying")); + else if(getStatus(MoveLow)) strcat_P(statusOutput, PSTR("Low")); + else if(getStatus(MoveHigh)) strcat_P(statusOutput, PSTR("High")); + else if(getStatus(MoveFull)) strcat_P(statusOutput, PSTR("Full")); else strcat_P(statusOutput, PSTR("Error")); return statusOutput; @@ -219,7 +219,7 @@ void PS3BT::Reset() { l2cap_state = L2CAP_WAIT; // Needed for PS3 Dualshock Controller commands to work via Bluetooth - for (uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) + for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) HIDBuffer[i + 2] = pgm_read_byte(&PS3_REPORT_BUFFER[i]); // First two bytes reserved for report type and ID } @@ -231,17 +231,17 @@ void PS3BT::disconnect() { // Use this void to disconnect any of the controllers } void PS3BT::ACLData(uint8_t* ACLData) { - if (!pBtd->l2capConnectionClaimed && !PS3Connected && !PS3MoveConnected && !PS3NavigationConnected && !activeConnection && !pBtd->connectToWii && !pBtd->incomingWii && !pBtd->pairWithWii) { - if (ACLData[8] == L2CAP_CMD_CONNECTION_REQUEST) { - if ((ACLData[12] | (ACLData[13] << 8)) == HID_CTRL_PSM) { + if(!pBtd->l2capConnectionClaimed && !PS3Connected && !PS3MoveConnected && !PS3NavigationConnected && !activeConnection && !pBtd->connectToWii && !pBtd->incomingWii && !pBtd->pairWithWii) { + if(ACLData[8] == L2CAP_CMD_CONNECTION_REQUEST) { + if((ACLData[12] | (ACLData[13] << 8)) == HID_CTRL_PSM) { pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service activeConnection = true; hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection l2cap_state = L2CAP_WAIT; - for (uint8_t i = 0; i < 30; i++) + for(uint8_t i = 0; i < 30; i++) remote_name[i] = pBtd->remote_name[i]; // Store the remote name for the connection #ifdef DEBUG_USB_HOST - if (pBtd->hci_version < 3) { // Check the HCI Version of the Bluetooth dongle + if(pBtd->hci_version < 3) { // Check the HCI Version of the Bluetooth dongle Notify(PSTR("\r\nYour dongle may not support reading the analog buttons, sensors and status\r\nYour HCI Version is: "), 0x80); Notify(pBtd->hci_version, 0x80); Notify(PSTR("\r\nBut should be at least 3\r\nThis means that it doesn't support Bluetooth Version 2.0+EDR"), 0x80); @@ -250,10 +250,10 @@ void PS3BT::ACLData(uint8_t* ACLData) { } } } - if ((ACLData[0] | (uint16_t)ACLData[1] << 8) == (hci_handle | 0x2000U)) { //acl_handle_ok + if((ACLData[0] | (uint16_t)ACLData[1] << 8) == (hci_handle | 0x2000U)) { //acl_handle_ok memcpy(l2capinbuf, ACLData, BULK_MAXPKTSIZE); - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U - if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { + if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U + if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -268,7 +268,7 @@ void PS3BT::ACLData(uint8_t* ACLData) { Notify(PSTR(" "), 0x80); D_PrintHex (l2capinbuf[14], 0x80); #endif - } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { #ifdef EXTRADEBUG Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -281,44 +281,44 @@ void PS3BT::ACLData(uint8_t* ACLData) { Notify(PSTR(" Identifier: "), 0x80); D_PrintHex (l2capinbuf[9], 0x80); #endif - if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { + if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[14]; control_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST); - } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { + } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[14]; interrupt_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST); } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { - if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { + if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80); l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80); l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS); } } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], control_scid); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], interrupt_scid); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80); #endif identifier = l2capinbuf[9]; pBtd->l2cap_disconnection_response(hci_handle, identifier, control_dcid, control_scid); Reset(); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80); #endif @@ -326,12 +326,12 @@ void PS3BT::ACLData(uint8_t* ACLData) { pBtd->l2cap_disconnection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid); Reset(); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { - if (l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { + if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE); - } else if (l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { + } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE); @@ -343,26 +343,26 @@ void PS3BT::ACLData(uint8_t* ACLData) { D_PrintHex (l2capinbuf[8], 0x80); } #endif - } else if (l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt + } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt //Notify(PSTR("\r\nL2CAP Interrupt"), 0x80); - if (PS3Connected || PS3MoveConnected || PS3NavigationConnected) { + if(PS3Connected || PS3MoveConnected || PS3NavigationConnected) { /* Read Report */ - if (l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT - if (PS3Connected || PS3NavigationConnected) + if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT + if(PS3Connected || PS3NavigationConnected) ButtonState = (uint32_t)(l2capinbuf[11] | ((uint16_t)l2capinbuf[12] << 8) | ((uint32_t)l2capinbuf[13] << 16)); - else if (PS3MoveConnected) + else if(PS3MoveConnected) ButtonState = (uint32_t)(l2capinbuf[10] | ((uint16_t)l2capinbuf[11] << 8) | ((uint32_t)l2capinbuf[12] << 16)); //Notify(PSTR("\r\nButtonState", 0x80); //PrintHex(ButtonState, 0x80); - if (ButtonState != OldButtonState) { + if(ButtonState != OldButtonState) { ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable OldButtonState = ButtonState; } #ifdef PRINTREPORT // Uncomment "#define PRINTREPORT" to print the report send by the PS3 Controllers - for (uint8_t i = 10; i < 58; i++) { + for(uint8_t i = 10; i < 58; i++) { D_PrintHex (l2capinbuf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -376,9 +376,9 @@ void PS3BT::ACLData(uint8_t* ACLData) { } void PS3BT::L2CAP_task() { - switch (l2cap_state) { + switch(l2cap_state) { case L2CAP_WAIT: - if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { + if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80); #endif @@ -393,7 +393,7 @@ void PS3BT::L2CAP_task() { break; case L2CAP_CONTROL_SUCCESS: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80); #endif @@ -402,7 +402,7 @@ void PS3BT::L2CAP_task() { break; case L2CAP_INTERRUPT_SETUP: - if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { + if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80); #endif @@ -418,11 +418,11 @@ void PS3BT::L2CAP_task() { break; case L2CAP_INTERRUPT_CONFIG_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Successfully Configured"), 0x80); #endif - if (remote_name[0] == 'M') { // First letter in Motion Controller ('M') + if(remote_name[0] == 'M') { // First letter in Motion Controller ('M') memset(l2capinbuf, 0, BULK_MAXPKTSIZE); // Reset l2cap in buffer as it sometimes read it as a button has been pressed l2cap_state = TURN_ON_LED; } else @@ -434,7 +434,7 @@ void PS3BT::L2CAP_task() { /* These states are handled in Run() */ case L2CAP_INTERRUPT_DISCONNECT: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80); #endif @@ -445,7 +445,7 @@ void PS3BT::L2CAP_task() { break; case L2CAP_CONTROL_DISCONNECT: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Control Channel"), 0x80); #endif @@ -459,11 +459,11 @@ void PS3BT::L2CAP_task() { } void PS3BT::Run() { - switch (l2cap_state) { + switch(l2cap_state) { case PS3_ENABLE_SIXAXIS: - if (millis() - timer > 1000) { // loop 1 second before sending the command + if(millis() - timer > 1000) { // loop 1 second before sending the command memset(l2capinbuf, 0, BULK_MAXPKTSIZE); // Reset l2cap in buffer as it sometimes read it as a button has been pressed - for (uint8_t i = 15; i < 19; i++) + for(uint8_t i = 15; i < 19; i++) l2capinbuf[i] = 0x7F; // Set the analog joystick values to center position enable_sixaxis(); l2cap_state = TURN_ON_LED; @@ -472,18 +472,18 @@ void PS3BT::Run() { break; case TURN_ON_LED: - if (millis() - timer > 1000) { // loop 1 second before sending the command - if (remote_name[0] == 'P') { // First letter in PLAYSTATION(R)3 Controller ('P') + if(millis() - timer > 1000) { // loop 1 second before sending the command + if(remote_name[0] == 'P') { // First letter in PLAYSTATION(R)3 Controller ('P') #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDualshock 3 Controller Enabled\r\n"), 0x80); #endif PS3Connected = true; - } else if (remote_name[0] == 'N') { // First letter in Navigation Controller ('N') + } else if(remote_name[0] == 'N') { // First letter in Navigation Controller ('N') #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nNavigation Controller Enabled\r\n"), 0x80); #endif PS3NavigationConnected = true; - } else if (remote_name[0] == 'M') { // First letter in Motion Controller ('M') + } else if(remote_name[0] == 'M') { // First letter in Motion Controller ('M') timerBulbRumble = millis(); #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nMotion Controller Enabled\r\n"), 0x80); @@ -500,8 +500,8 @@ void PS3BT::Run() { break; case L2CAP_DONE: - if (PS3MoveConnected) { // The Bulb and rumble values, has to be send at aproximatly every 5th second for it to stay on - if (millis() - timerBulbRumble > 4000) { // Send at least every 4th second + if(PS3MoveConnected) { // The Bulb and rumble values, has to be send at aproximatly every 5th second for it to stay on + if(millis() - timerBulbRumble > 4000) { // Send at least every 4th second HIDMove_Command(HIDMoveBuffer, HID_BUFFERSIZE); // The Bulb and rumble values, has to be written again and again, for it to stay turned on timerBulbRumble = millis(); } @@ -517,7 +517,7 @@ void PS3BT::Run() { // Playstation Sixaxis Dualshock and Navigation Controller commands void PS3BT::HID_Command(uint8_t* data, uint8_t nbytes) { - if (millis() - timerHID <= 150) // Check if is has been more than 150ms since last command + if(millis() - timerHID <= 150) // Check if is has been more than 150ms since last command delay((uint32_t)(150 - (millis() - timerHID))); // There have to be a delay between commands pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); // Both the Navigation and Dualshock controller sends data via the control channel timerHID = millis(); @@ -544,8 +544,8 @@ void PS3BT::setRumbleOff() { } void PS3BT::setRumbleOn(Rumble mode) { - uint8_t power[2] = { 0xff, 0x00 }; // Defaults to RumbleLow - if (mode == RumbleHigh) { + uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow + if(mode == RumbleHigh) { power[0] = 0x00; power[1] = 0xff; } @@ -595,7 +595,7 @@ void PS3BT::enable_sixaxis() { // Command used to enable the Dualshock 3 and Nav // Playstation Move Controller commands void PS3BT::HIDMove_Command(uint8_t* data, uint8_t nbytes) { - if (millis() - timerHID <= 150)// Check if is has been less than 150ms since last command + if(millis() - timerHID <= 150)// Check if is has been less than 150ms since last command delay((uint32_t)(150 - (millis() - timerHID))); // There have to be a delay between commands pBtd->L2CAP_Command(hci_handle, data, nbytes, interrupt_scid[0], interrupt_scid[1]); // The Move controller sends it's data via the intterrupt channel timerHID = millis(); @@ -616,7 +616,7 @@ void PS3BT::moveSetBulb(Colors color) { //Use this to set the Color using the pr void PS3BT::moveSetRumble(uint8_t rumble) { #ifdef DEBUG_USB_HOST - if (rumble < 64 && rumble != 0) // The rumble value has to at least 64, or approximately 25% (64/255*100) + if(rumble < 64 && rumble != 0) // The rumble value has to at least 64, or approximately 25% (64/255*100) Notify(PSTR("\r\nThe rumble value has to at least 64, or approximately 25%"), 0x80); #endif // Set the rumble value into the write buffer @@ -626,12 +626,12 @@ void PS3BT::moveSetRumble(uint8_t rumble) { } void PS3BT::onInit() { - if (pFuncOnInit) + if(pFuncOnInit) pFuncOnInit(); // Call the user function else { - if (PS3MoveConnected) + if(PS3MoveConnected) moveSetBulb(Red); else // Dualshock 3 or Navigation controller setLedOn(LED1); } -} \ No newline at end of file +} diff --git a/PS3BT.h b/PS3BT.h index 8d796649..ff441a2c 100644 --- a/PS3BT.h +++ b/PS3BT.h @@ -143,6 +143,7 @@ public: * @param value See: ::LED enum. */ void setLedRaw(uint8_t value); + /** Turn all LEDs off. */ void setLedOff() { setLedRaw(0); diff --git a/PS3Enums.h b/PS3Enums.h index b6a7b22d..8565e572 100644 --- a/PS3Enums.h +++ b/PS3Enums.h @@ -212,4 +212,4 @@ enum Rumble { RumbleLow = 0x20, }; -#endif \ No newline at end of file +#endif diff --git a/PS3USB.cpp b/PS3USB.cpp index 8cc4a40f..25bfba4b 100644 --- a/PS3USB.cpp +++ b/PS3USB.cpp @@ -25,14 +25,14 @@ pUsb(p), // pointer to USB class instance - mandatory bAddress(0), // device address - mandatory bPollEnable(false) // don't start polling before dongle is connected { - for (uint8_t i = 0; i < PS3_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < PS3_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; } - if (pUsb) // register in USB subsystem + if(pUsb) // register in USB subsystem pUsb->RegisterDeviceClass(this); //set devConfig[] entry my_bdaddr[5] = btadr5; // Change to your dongle's Bluetooth address instead @@ -58,7 +58,7 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nPS3USB Init"), 0x80); #endif // check if address has already been assigned to an instance - if (bAddress) { + if(bAddress) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress in use"), 0x80); #endif @@ -68,14 +68,14 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } - if (!p->epinfo) { + if(!p->epinfo) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nepinfo is null"), 0x80); #endif @@ -95,19 +95,19 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) + if(rcode) goto FailGetDevDescr; VID = udd->idVendor; PID = udd->idProduct; - if (VID != PS3_VID || (PID != PS3_PID && PID != PS3NAVIGATION_PID && PID != PS3MOVE_PID)) + if(VID != PS3_VID || (PID != PS3_PID && PID != PS3NAVIGATION_PID && PID != PS3MOVE_PID)) goto FailUnknownDevice; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from device descriptor @@ -115,7 +115,7 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -135,14 +135,14 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { //get pointer to assigned address record p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; // Assign epInfo to epinfo pointer - only EP0 is known rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; @@ -165,17 +165,17 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ PS3_INPUT_PIPE ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; delay(200); //Give time for address change rcode = pUsb->setConf(bAddress, epInfo[ PS3_CONTROL_PIPE ].epAddr, 1); - if (rcode) + if(rcode) goto FailSetConfDescr; - if (PID == PS3_PID || PID == PS3NAVIGATION_PID) { - if (PID == PS3_PID) { + if(PID == PS3_PID || PID == PS3NAVIGATION_PID) { + if(PID == PS3_PID) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80); #endif @@ -189,10 +189,10 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { enable_sixaxis(); // The PS3 controller needs a special command before it starts sending data // Needed for PS3 Dualshock and Navigation commands to work - for (uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) + for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) writeBuf[i] = pgm_read_byte(&PS3_REPORT_BUFFER[i]); - for (uint8_t i = 6; i < 10; i++) + for(uint8_t i = 6; i < 10; i++) readBuf[i] = 0x7F; // Set the analog joystick values to center position } else { // must be a Motion controller #ifdef DEBUG_USB_HOST @@ -201,15 +201,15 @@ uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) { PS3MoveConnected = true; writeBuf[0] = 0x02; // Set report ID, this is needed for Move commands to work } - 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) { - if (PS3MoveConnected) + 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) { + if(PS3MoveConnected) setMoveBdaddr(my_bdaddr); // Set internal Bluetooth address else setBdaddr(my_bdaddr); // Set internal Bluetooth address #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nBluetooth Address was set to: "), 0x80); - for (int8_t i = 5; i > 0; i--) { + for(int8_t i = 5; i > 0; i--) { D_PrintHex (my_bdaddr[i], 0x80); Notify(PSTR(":"), 0x80); } @@ -269,20 +269,20 @@ uint8_t PS3USB::Release() { } uint8_t PS3USB::Poll() { - if (!bPollEnable) + if(!bPollEnable) return 0; - if (PS3Connected || PS3NavigationConnected) { + if(PS3Connected || PS3NavigationConnected) { uint16_t BUFFER_SIZE = EP_MAXPKTSIZE; pUsb->inTransfer(bAddress, epInfo[ PS3_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1 - if (millis() - timer > 100) { // Loop 100ms before processing data + if(millis() - timer > 100) { // Loop 100ms before processing data readReport(); #ifdef PRINTREPORT printReport(); // Uncomment "#define PRINTREPORT" to print the report send by the PS3 Controllers #endif } - } else if (PS3MoveConnected) { // One can only set the color of the bulb, set the rumble, set and get the bluetooth address and calibrate the magnetometer via USB - if (millis() - timer > 4000) { // Send at least every 4th second + } else if(PS3MoveConnected) { // One can only set the color of the bulb, set the rumble, set and get the bluetooth address and calibrate the magnetometer via USB + if(millis() - timer > 4000) { // Send at least every 4th second Move_Command(writeBuf, MOVE_REPORT_BUFFER_SIZE); // The Bulb and rumble values, has to be written again and again, for it to stay turned on timer = millis(); } @@ -296,7 +296,7 @@ void PS3USB::readReport() { //Notify(PSTR("\r\nButtonState", 0x80); //PrintHex(ButtonState, 0x80); - if (ButtonState != OldButtonState) { + if(ButtonState != OldButtonState) { ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable OldButtonState = ButtonState; } @@ -304,7 +304,7 @@ void PS3USB::readReport() { void PS3USB::printReport() { // Uncomment "#define PRINTREPORT" to print the report send by the PS3 Controllers #ifdef PRINTREPORT - for (uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) { + for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) { D_PrintHex (readBuf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -336,7 +336,7 @@ uint16_t PS3USB::getSensor(Sensor a) { } double PS3USB::getAngle(Angle a) { - if (PS3Connected) { + if(PS3Connected) { double accXval; double accYval; double accZval; @@ -350,7 +350,7 @@ double PS3USB::getAngle(Angle a) { // Convert to 360 degrees resolution // atan2 outputs the value of -π to π (radians) // We are then converting it to 0 to 2π and then to degrees - if (a == Pitch) + if(a == Pitch) return (atan2(accYval, accZval) + PI) * RAD_TO_DEG; else return (atan2(accXval, accZval) + PI) * RAD_TO_DEG; @@ -363,33 +363,33 @@ bool PS3USB::getStatus(Status c) { } String PS3USB::getStatusString() { - if (PS3Connected || PS3NavigationConnected) { + if(PS3Connected || PS3NavigationConnected) { char statusOutput[100]; strcpy(statusOutput, "ConnectionStatus: "); - if (getStatus(Plugged)) strcat(statusOutput, "Plugged"); - else if (getStatus(Unplugged)) strcat(statusOutput, "Unplugged"); + if(getStatus(Plugged)) strcat(statusOutput, "Plugged"); + else if(getStatus(Unplugged)) strcat(statusOutput, "Unplugged"); else strcat(statusOutput, "Error"); strcat(statusOutput, " - PowerRating: "); - if (getStatus(Charging)) strcat(statusOutput, "Charging"); - else if (getStatus(NotCharging)) strcat(statusOutput, "Not Charging"); - else if (getStatus(Shutdown)) strcat(statusOutput, "Shutdown"); - else if (getStatus(Dying)) strcat(statusOutput, "Dying"); - else if (getStatus(Low)) strcat(statusOutput, "Low"); - else if (getStatus(High)) strcat(statusOutput, "High"); - else if (getStatus(Full)) strcat(statusOutput, "Full"); + if(getStatus(Charging)) strcat(statusOutput, "Charging"); + else if(getStatus(NotCharging)) strcat(statusOutput, "Not Charging"); + else if(getStatus(Shutdown)) strcat(statusOutput, "Shutdown"); + else if(getStatus(Dying)) strcat(statusOutput, "Dying"); + else if(getStatus(Low)) strcat(statusOutput, "Low"); + else if(getStatus(High)) strcat(statusOutput, "High"); + else if(getStatus(Full)) strcat(statusOutput, "Full"); else strcat(statusOutput, "Error"); strcat(statusOutput, " - WirelessStatus: "); - if (getStatus(CableRumble)) strcat(statusOutput, "Cable - Rumble is on"); - else if (getStatus(Cable)) strcat(statusOutput, "Cable - Rumble is off"); - else if (getStatus(BluetoothRumble)) strcat(statusOutput, "Bluetooth - Rumble is on"); - else if (getStatus(Bluetooth)) strcat(statusOutput, "Bluetooth - Rumble is off"); + if(getStatus(CableRumble)) strcat(statusOutput, "Cable - Rumble is on"); + else if(getStatus(Cable)) strcat(statusOutput, "Cable - Rumble is off"); + else if(getStatus(BluetoothRumble)) strcat(statusOutput, "Bluetooth - Rumble is on"); + else if(getStatus(Bluetooth)) strcat(statusOutput, "Bluetooth - Rumble is off"); else strcat(statusOutput, "Error"); return statusOutput; @@ -404,7 +404,7 @@ void PS3USB::PS3_Command(uint8_t *data, uint16_t nbytes) { } void PS3USB::setAllOff() { - for (uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) + for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) writeBuf[i] = pgm_read_byte(&PS3_REPORT_BUFFER[i]); // Reset buffer PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE); @@ -420,9 +420,9 @@ void PS3USB::setRumbleOff() { } void PS3USB::setRumbleOn(Rumble mode) { - if ((mode & 0x30) > 0x00) { + if((mode & 0x30) > 0x00) { uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow - if (mode == RumbleHigh) { + if(mode == RumbleHigh) { power[0] = 0x00; power[1] = 0xff; } @@ -464,7 +464,7 @@ void PS3USB::setBdaddr(uint8_t *bdaddr) { buf[0] = 0x01; buf[1] = 0x00; - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first // 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 @@ -477,7 +477,7 @@ void PS3USB::getBdaddr(uint8_t *bdaddr) { // bmRequest = Device to host (0x80) | Class (0x20) | Interface (0x01) = 0xA1, bRequest = Get Report (0x01), Report ID (0xF5), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_IN, HID_REQUEST_GET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL); - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) bdaddr[5 - i] = buf[i + 2]; // Copy into buffer reversed, so it is LSB first } @@ -512,7 +512,7 @@ void PS3USB::moveSetBulb(Colors color) { // Use this to set the Color using the void PS3USB::moveSetRumble(uint8_t rumble) { #ifdef DEBUG_USB_HOST - if (rumble < 64 && rumble != 0) // The rumble value has to at least 64, or approximately 25% (64/255*100) + if(rumble < 64 && rumble != 0) // The rumble value has to at least 64, or approximately 25% (64/255*100) Notify(PSTR("\r\nThe rumble value has to at least 64, or approximately 25%"), 0x80); #endif writeBuf[6] = rumble; // Set the rumble value into the write buffer @@ -529,7 +529,7 @@ void PS3USB::setMoveBdaddr(uint8_t *bdaddr) { buf[9] = 0x02; buf[10] = 0x12; - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) buf[i + 1] = bdaddr[i]; // 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 @@ -542,27 +542,27 @@ void PS3USB::getMoveBdaddr(uint8_t *bdaddr) { // bmRequest = Device to host (0x80) | Class (0x20) | Interface (0x01) = 0xA1, bRequest = Get Report (0x01), Report ID (0x04), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_IN, HID_REQUEST_GET_REPORT, 0x04, 0x03, 0x00, 16, 16, buf, NULL); - for (uint8_t i = 0; i < 6; i++) + for(uint8_t i = 0; i < 6; i++) bdaddr[i] = buf[10 + i]; } void PS3USB::getMoveCalibration(uint8_t *data) { uint8_t buf[49]; - for (uint8_t i = 0; i < 3; i++) { + for(uint8_t i = 0; i < 3; i++) { // bmRequest = Device to host (0x80) | Class (0x20) | Interface (0x01) = 0xA1, bRequest = Get Report (0x01), Report ID (0x10), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_IN, HID_REQUEST_GET_REPORT, 0x10, 0x03, 0x00, 49, 49, buf, NULL); - for (byte j = 0; j < 49; j++) + for(byte j = 0; j < 49; j++) data[49 * i + j] = buf[j]; } } void PS3USB::onInit() { - if (pFuncOnInit) + if(pFuncOnInit) pFuncOnInit(); // Call the user function else { - if (PS3MoveConnected) + if(PS3MoveConnected) moveSetBulb(Red); else // Dualshock 3 or Navigation controller setLedOn(LED1); diff --git a/PS3USB.h b/PS3USB.h index 82559acd..9e40a2ea 100644 --- a/PS3USB.h +++ b/PS3USB.h @@ -220,6 +220,7 @@ public: * @param value See: ::LED enum. */ void setLedRaw(uint8_t value); + /** Turn all LEDs off. */ void setLedOff() { setLedRaw(0); diff --git a/SPP.cpp b/SPP.cpp index 670b91dc..ff75c9cb 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -45,7 +45,7 @@ const uint8_t rfcomm_crc_table[256] PROGMEM = {/* reversed, 8-bit, poly=0x07 */ SPP::SPP(BTD *p, const char* name, const char* pin) : pBtd(p) // Pointer to BTD class instance - mandatory { - if (pBtd) + if(pBtd) pBtd->registerServiceClass(this); // Register it as a Bluetooth service pBtd->btdName = name; @@ -74,32 +74,32 @@ void SPP::Reset() { void SPP::disconnect() { connected = false; // First the two L2CAP channels has to be disconnected and then the HCI connection - if (RFCOMMConnected) + if(RFCOMMConnected) pBtd->l2cap_disconnection_request(hci_handle, ++identifier, rfcomm_scid, rfcomm_dcid); - if (RFCOMMConnected && SDPConnected) + if(RFCOMMConnected && SDPConnected) delay(1); // Add delay between commands - if (SDPConnected) + if(SDPConnected) pBtd->l2cap_disconnection_request(hci_handle, ++identifier, sdp_scid, sdp_dcid); l2cap_sdp_state = L2CAP_DISCONNECT_RESPONSE; } void SPP::ACLData(uint8_t* l2capinbuf) { - if (!connected) { - if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { - if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM && !pBtd->sdpConnectionClaimed) { + if(!connected) { + if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { + if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM && !pBtd->sdpConnectionClaimed) { pBtd->sdpConnectionClaimed = true; hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection l2cap_sdp_state = L2CAP_SDP_WAIT; // Reset state - } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == RFCOMM_PSM && !pBtd->rfcommConnectionClaimed) { + } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == RFCOMM_PSM && !pBtd->rfcommConnectionClaimed) { pBtd->rfcommConnectionClaimed = true; hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; // Reset state } } } - if ((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U - if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { + if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok + if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U + if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -114,7 +114,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" "), 0x80); D_PrintHex (l2capinbuf[14], 0x80); #endif - } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { #ifdef EXTRADEBUG Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -127,56 +127,56 @@ void SPP::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" Identifier: "), 0x80); D_PrintHex (l2capinbuf[9], 0x80); #endif - if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM) { // It doesn't matter if it receives another reqeust, since it waits for the channel to disconnect in the L2CAP_SDP_DONE state, and the l2cap_event_flag will be cleared if so + if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM) { // It doesn't matter if it receives another reqeust, since it waits for the channel to disconnect in the L2CAP_SDP_DONE state, and the l2cap_event_flag will be cleared if so identifier = l2capinbuf[9]; sdp_scid[0] = l2capinbuf[14]; sdp_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST); - } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == RFCOMM_PSM) { // ----- || ----- + } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == RFCOMM_PSM) { // ----- || ----- identifier = l2capinbuf[9]; rfcomm_scid[0] = l2capinbuf[14]; rfcomm_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST); } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { - if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success - if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { + if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success + if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { //Notify(PSTR("\r\nSDP Configuration Complete"), 0x80); l2cap_set_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS); - } else if (l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { + } else if(l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { //Notify(PSTR("\r\nRFCOMM Configuration Complete"), 0x80); l2cap_set_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS); } } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { - if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { + if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { //Notify(PSTR("\r\nSDP Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], sdp_scid); - } else if (l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { + } else if(l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { //Notify(PSTR("\r\nRFCOMM Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], rfcomm_scid); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { - if (l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { + if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) { //Notify(PSTR("\r\nDisconnect Request: SDP Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST); - } else if (l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { + } else if(l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) { //Notify(PSTR("\r\nDisconnect Request: RFCOMM Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { - if (l2capinbuf[12] == sdp_scid[0] && l2capinbuf[13] == sdp_scid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { + if(l2capinbuf[12] == sdp_scid[0] && l2capinbuf[13] == sdp_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: SDP Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RESPONSE); - } else if (l2capinbuf[12] == rfcomm_scid[0] && l2capinbuf[13] == rfcomm_scid[1]) { + } else if(l2capinbuf[12] == rfcomm_scid[0] && l2capinbuf[13] == rfcomm_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: RFCOMM Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RESPONSE); } - } else if (l2capinbuf[8] == L2CAP_CMD_INFORMATION_REQUEST) { + } else if(l2capinbuf[8] == L2CAP_CMD_INFORMATION_REQUEST) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nInformation request"), 0x80); #endif @@ -189,18 +189,18 @@ void SPP::ACLData(uint8_t* l2capinbuf) { D_PrintHex (l2capinbuf[8], 0x80); } #endif - } else if (l2capinbuf[6] == sdp_dcid[0] && l2capinbuf[7] == sdp_dcid[1]) { // SDP - if (l2capinbuf[8] == SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST_PDU) { - if (((l2capinbuf[16] << 8 | l2capinbuf[17]) == SERIALPORT_UUID) || ((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000 && (l2capinbuf[18] << 8 | l2capinbuf[19]) == SERIALPORT_UUID)) { // Check if it's sending the full UUID, see: https://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm, we will just check the first four bytes - if (firstMessage) { + } else if(l2capinbuf[6] == sdp_dcid[0] && l2capinbuf[7] == sdp_dcid[1]) { // SDP + if(l2capinbuf[8] == SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST_PDU) { + if(((l2capinbuf[16] << 8 | l2capinbuf[17]) == SERIALPORT_UUID) || ((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000 && (l2capinbuf[18] << 8 | l2capinbuf[19]) == SERIALPORT_UUID)) { // Check if it's sending the full UUID, see: https://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm, we will just check the first four bytes + if(firstMessage) { serialPortResponse1(l2capinbuf[9], l2capinbuf[10]); firstMessage = false; } else { serialPortResponse2(l2capinbuf[9], l2capinbuf[10]); // Serialport continuation state firstMessage = true; } - } else if (((l2capinbuf[16] << 8 | l2capinbuf[17]) == L2CAP_UUID) || ((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000 && (l2capinbuf[18] << 8 | l2capinbuf[19]) == L2CAP_UUID)) { - if (firstMessage) { + } else if(((l2capinbuf[16] << 8 | l2capinbuf[17]) == L2CAP_UUID) || ((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000 && (l2capinbuf[18] << 8 | l2capinbuf[19]) == L2CAP_UUID)) { + if(firstMessage) { l2capResponse1(l2capinbuf[9], l2capinbuf[10]); firstMessage = false; } else { @@ -216,14 +216,14 @@ void SPP::ACLData(uint8_t* l2capinbuf) { uuid = (l2capinbuf[18] << 8 | l2capinbuf[19]); else // Short UUID uuid = (l2capinbuf[16] << 8 | l2capinbuf[17]); - D_PrintHex (uuid, 0x80); + D_PrintHex (uuid, 0x80); Notify(PSTR("\r\nLength: "), 0x80); uint16_t length = l2capinbuf[11] << 8 | l2capinbuf[12]; - D_PrintHex (length, 0x80); + D_PrintHex (length, 0x80); Notify(PSTR("\r\nData: "), 0x80); - for (uint8_t i = 0; i < length; i++) { - D_PrintHex (l2capinbuf[13+i], 0x80); + for(uint8_t i = 0; i < length; i++) { + D_PrintHex (l2capinbuf[13 + i], 0x80); Notify(PSTR(" "), 0x80); } #endif @@ -234,14 +234,14 @@ void SPP::ACLData(uint8_t* l2capinbuf) { D_PrintHex (l2capinbuf[8], 0x80); } #endif - } else if (l2capinbuf[6] == rfcomm_dcid[0] && l2capinbuf[7] == rfcomm_dcid[1]) { // RFCOMM + } else if(l2capinbuf[6] == rfcomm_dcid[0] && l2capinbuf[7] == rfcomm_dcid[1]) { // RFCOMM rfcommChannel = l2capinbuf[8] & 0xF8; rfcommDirection = l2capinbuf[8] & 0x04; rfcommCommandResponse = l2capinbuf[8] & 0x02; rfcommChannelType = l2capinbuf[9] & 0xEF; rfcommPfBit = l2capinbuf[9] & 0x10; - if (rfcommChannel >> 3 != 0x00) + if(rfcommChannel >> 3 != 0x00) rfcommChannelConnection = rfcommChannel; #ifdef EXTRADEBUG @@ -256,7 +256,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" PF_BIT: "), 0x80); D_PrintHex (rfcommPfBit, 0x80); #endif - if (rfcommChannelType == RFCOMM_DISC) { + if(rfcommChannelType == RFCOMM_DISC) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nReceived Disconnect RFCOMM Command on channel: "), 0x80); D_PrintHex (rfcommChannel >> 3, 0x80); @@ -264,15 +264,15 @@ void SPP::ACLData(uint8_t* l2capinbuf) { connected = false; sendRfcomm(rfcommChannel, rfcommDirection, rfcommCommandResponse, RFCOMM_UA, rfcommPfBit, rfcommbuf, 0x00); // UA Command } - if (connected) { + if(connected) { /* Read the incoming message */ - if (rfcommChannelType == RFCOMM_UIH && rfcommChannel == rfcommChannelConnection) { + if(rfcommChannelType == RFCOMM_UIH && rfcommChannel == rfcommChannelConnection) { uint8_t length = l2capinbuf[10] >> 1; // Get length uint8_t offset = l2capinbuf[4] - length - 4; // Check if there is credit - if (checkFcs(&l2capinbuf[8], l2capinbuf[11 + length + offset])) { + if(checkFcs(&l2capinbuf[8], l2capinbuf[11 + length + offset])) { uint8_t i = 0; - for (; i < length; i++) { - if (rfcommAvailable + i >= sizeof (rfcommDataBuffer)) { + for(; i < length; i++) { + if(rfcommAvailable + i >= sizeof (rfcommDataBuffer)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nWarning: Buffer is full!"), 0x80); #endif @@ -284,7 +284,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { #ifdef EXTRADEBUG Notify(PSTR("\r\nRFCOMM Data Available: "), 0x80); Notify(rfcommAvailable, 0x80); - if (offset) { + if(offset) { Notify(PSTR(" - Credit: 0x"), 0x80); D_PrintHex (l2capinbuf[11], 0x80); } @@ -295,10 +295,10 @@ void SPP::ACLData(uint8_t* l2capinbuf) { Notify(PSTR("\r\nError in FCS checksum!"), 0x80); #endif #ifdef PRINTREPORT // Uncomment "#define PRINTREPORT" to print the report send to the Arduino via Bluetooth - for (uint8_t i = 0; i < length; i++) + for(uint8_t i = 0; i < length; i++) Notifyc(l2capinbuf[i + 11 + offset], 0x80); #endif - } else if (rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_RPN_CMD) { // UIH Remote Port Negotiation Command + } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_RPN_CMD) { // UIH Remote Port Negotiation Command #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nReceived UIH Remote Port Negotiation Command"), 0x80); #endif @@ -313,7 +313,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { rfcommbuf[8] = l2capinbuf[19]; // MaxRatransm. rfcommbuf[9] = l2capinbuf[20]; // Number of Frames sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x0A); // UIH Remote Port Negotiation Response - } else if (rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_CMD) { // UIH Modem Status Command + } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_CMD) { // UIH Modem Status Command #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend UIH Modem Status Response"), 0x80); #endif @@ -324,12 +324,12 @@ void SPP::ACLData(uint8_t* l2capinbuf) { sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x04); } } else { - if (rfcommChannelType == RFCOMM_SABM) { // SABM Command - this is sent twice: once for channel 0 and then for the channel to establish + if(rfcommChannelType == RFCOMM_SABM) { // SABM Command - this is sent twice: once for channel 0 and then for the channel to establish #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nReceived SABM Command"), 0x80); #endif sendRfcomm(rfcommChannel, rfcommDirection, rfcommCommandResponse, RFCOMM_UA, rfcommPfBit, rfcommbuf, 0x00); // UA Command - } else if (rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_PN_CMD) { // UIH Parameter Negotiation Command + } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_PN_CMD) { // UIH Parameter Negotiation Command #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nReceived UIH Parameter Negotiation Command"), 0x80); #endif @@ -344,7 +344,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { rfcommbuf[8] = 0x00; // MaxRatransm. rfcommbuf[9] = 0x00; // Number of Frames sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x0A); - } else if (rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_CMD) { // UIH Modem Status Command + } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_CMD) { // UIH Modem Status Command #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend UIH Modem Status Response"), 0x80); #endif @@ -364,8 +364,8 @@ void SPP::ACLData(uint8_t* l2capinbuf) { rfcommbuf[3] = 0x8D; // Can receive frames (YES), Ready to Communicate (YES), Ready to Receive (YES), Incomig Call (NO), Data is Value (YES) sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x04); - } else if (rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_RSP) { // UIH Modem Status Response - if (!creditSent) { + } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_RSP) { // UIH Modem Status Response + if(!creditSent) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend UIH Command with credit"), 0x80); #endif @@ -374,11 +374,11 @@ void SPP::ACLData(uint8_t* l2capinbuf) { timer = millis(); waitForLastCommand = true; } - } else if (rfcommChannelType == RFCOMM_UIH && l2capinbuf[10] == 0x01) { // UIH Command with credit + } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[10] == 0x01) { // UIH Command with credit #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nReceived UIH Command with credit"), 0x80); #endif - } else if (rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_RPN_CMD) { // UIH Remote Port Negotiation Command + } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_RPN_CMD) { // UIH Remote Port Negotiation Command #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nReceived UIH Remote Port Negotiation Command"), 0x80); #endif @@ -402,7 +402,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { sppIndex = 0; } #ifdef EXTRADEBUG - else if (rfcommChannelType != RFCOMM_DISC) { + else if(rfcommChannelType != RFCOMM_DISC) { Notify(PSTR("\r\nUnsupported RFCOMM Data - ChannelType: "), 0x80); D_PrintHex (rfcommChannelType, 0x80); Notify(PSTR(" Command: "), 0x80); @@ -425,7 +425,7 @@ void SPP::ACLData(uint8_t* l2capinbuf) { } void SPP::Run() { - if (waitForLastCommand && (millis() - timer) > 100) { // We will only wait 100ms and see if the UIH Remote Port Negotiation Command is send, as some deviced don't send it + if(waitForLastCommand && (millis() - timer) > 100) { // We will only wait 100ms and see if the UIH Remote Port Negotiation Command is send, as some deviced don't send it #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRFCOMM Connection is now established - Automatic\r\n"), 0x80); #endif @@ -438,9 +438,9 @@ void SPP::Run() { } void SPP::SDP_task() { - switch (l2cap_sdp_state) { + switch(l2cap_sdp_state) { case L2CAP_SDP_WAIT: - if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST)) { + if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST)) { l2cap_clear_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSDP Incoming Connection Request"), 0x80); @@ -452,7 +452,7 @@ void SPP::SDP_task() { delay(1); pBtd->l2cap_config_request(hci_handle, identifier, sdp_scid); l2cap_sdp_state = L2CAP_SDP_SUCCESS; - } else if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST)) { + } else if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST)) { l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST); // Clear flag SDPConnected = false; #ifdef DEBUG_USB_HOST @@ -462,7 +462,7 @@ void SPP::SDP_task() { } break; case L2CAP_SDP_SUCCESS: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS)) { + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS)) { l2cap_clear_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSDP Successfully Configured"), 0x80); @@ -474,7 +474,7 @@ void SPP::SDP_task() { break; case L2CAP_DISCONNECT_RESPONSE: // This is for both disconnection response from the RFCOMM and SDP channel if they were connected - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RESPONSE)) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected L2CAP Connection"), 0x80); #endif @@ -487,9 +487,9 @@ void SPP::SDP_task() { } void SPP::RFCOMM_task() { - switch (l2cap_rfcomm_state) { + switch(l2cap_rfcomm_state) { case L2CAP_RFCOMM_WAIT: - if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST)) { + if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST)) { l2cap_clear_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRFCOMM Incoming Connection Request"), 0x80); @@ -501,7 +501,7 @@ void SPP::RFCOMM_task() { delay(1); pBtd->l2cap_config_request(hci_handle, identifier, rfcomm_scid); l2cap_rfcomm_state = L2CAP_RFCOMM_SUCCESS; - } else if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST)) { + } else if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST)) { l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST); // Clear flag RFCOMMConnected = false; connected = false; @@ -512,7 +512,7 @@ void SPP::RFCOMM_task() { } break; case L2CAP_RFCOMM_SUCCESS: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS)) { + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS)) { l2cap_clear_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS); // Clear flag #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRFCOMM Successfully Configured"), 0x80); @@ -670,12 +670,12 @@ void SPP::sendRfcomm(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t cha l2capoutbuf[1] = channelType | pfBit; // RFCOMM Control l2capoutbuf[2] = length << 1 | 0x01; // Length and format (always 0x01 bytes format) uint8_t i = 0; - for (; i < length; i++) + for(; i < length; i++) l2capoutbuf[i + 3] = data[i]; l2capoutbuf[i + 3] = calcFcs(l2capoutbuf); #ifdef EXTRADEBUG Notify(PSTR(" - RFCOMM Data: "), 0x80); - for (i = 0; i < length + 4; i++) { + for(i = 0; i < length + 4; i++) { D_PrintHex (l2capoutbuf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -691,7 +691,7 @@ void SPP::sendRfcommCredit(uint8_t channel, uint8_t direction, uint8_t CR, uint8 l2capoutbuf[4] = calcFcs(l2capoutbuf); #ifdef EXTRADEBUG Notify(PSTR(" - RFCOMM Credit Data: "), 0x80); - for (uint8_t i = 0; i < 5; i++) { + for(uint8_t i = 0; i < 5; i++) { D_PrintHex (l2capoutbuf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -707,7 +707,7 @@ uint8_t SPP::crc(uint8_t *data) { /* Calculate FCS */ uint8_t SPP::calcFcs(uint8_t *data) { uint8_t temp = crc(data); - if ((data[1] & 0xEF) == RFCOMM_UIH) + if((data[1] & 0xEF) == RFCOMM_UIH) return (0xFF - temp); // FCS on 2 bytes else return (0xFF - pgm_read_byte(&rfcomm_crc_table[temp ^ data[2]])); // FCS on 3 bytes @@ -716,29 +716,33 @@ uint8_t SPP::calcFcs(uint8_t *data) { /* Check FCS */ bool SPP::checkFcs(uint8_t *data, uint8_t fcs) { uint8_t temp = crc(data); - if ((data[1] & 0xEF) != RFCOMM_UIH) + if((data[1] & 0xEF) != RFCOMM_UIH) temp = pgm_read_byte(&rfcomm_crc_table[temp ^ data[2]]); // FCS on 3 bytes return (pgm_read_byte(&rfcomm_crc_table[temp ^ fcs]) == 0xCF); } /* Serial commands */ #if defined(ARDUINO) && ARDUINO >=100 + size_t SPP::write(uint8_t data) { return write(&data, 1); } #else + void SPP::write(uint8_t data) { write(&data, 1); } #endif #if defined(ARDUINO) && ARDUINO >=100 + size_t SPP::write(const uint8_t *data, size_t size) { #else + void SPP::write(const uint8_t *data, size_t size) { #endif for(uint8_t i = 0; i < size; i++) { - if(sppIndex >= sizeof(sppOutputBuffer)/sizeof(sppOutputBuffer[0])) + if(sppIndex >= sizeof (sppOutputBuffer) / sizeof (sppOutputBuffer[0])) send(); // Send the current data in the buffer sppOutputBuffer[sppIndex++] = data[i]; // All the bytes are put into a buffer and then send using the send() function } @@ -748,7 +752,7 @@ void SPP::write(const uint8_t *data, size_t size) { } void SPP::send() { - if (!connected || !sppIndex) + if(!connected || !sppIndex) return; uint8_t length; // This is the length of the string we are sending uint8_t offset = 0; // This is used to keep track of where we are in the string @@ -756,15 +760,15 @@ void SPP::send() { l2capoutbuf[0] = rfcommChannelConnection | 0 | 0 | extendAddress; // RFCOMM Address l2capoutbuf[1] = RFCOMM_UIH; // RFCOMM Control - while (sppIndex) { // We will run this while loop until this variable is 0 - if (sppIndex > (sizeof (l2capoutbuf) - 4)) // Check if the string is larger than the outgoing buffer + while(sppIndex) { // We will run this while loop until this variable is 0 + if(sppIndex > (sizeof (l2capoutbuf) - 4)) // Check if the string is larger than the outgoing buffer length = sizeof (l2capoutbuf) - 4; else length = sppIndex; l2capoutbuf[2] = length << 1 | 1; // Length uint8_t i = 0; - for (; i < length; i++) + for(; i < length; i++) l2capoutbuf[i + 3] = sppOutputBuffer[i + offset]; l2capoutbuf[i + 3] = calcFcs(l2capoutbuf); // Calculate checksum @@ -784,20 +788,20 @@ void SPP::discard(void) { } int SPP::peek(void) { - if (rfcommAvailable == 0) // Don't read if there is nothing in the buffer + if(rfcommAvailable == 0) // Don't read if there is nothing in the buffer return -1; return rfcommDataBuffer[0]; } int SPP::read(void) { - if (rfcommAvailable == 0) // Don't read if there is nothing in the buffer + if(rfcommAvailable == 0) // Don't read if there is nothing in the buffer return -1; uint8_t output = rfcommDataBuffer[0]; - for (uint8_t i = 1; i < rfcommAvailable; i++) + for(uint8_t i = 1; i < rfcommAvailable; i++) rfcommDataBuffer[i - 1] = rfcommDataBuffer[i]; // Shift the buffer one left rfcommAvailable--; bytesRead++; - if (bytesRead > (sizeof (rfcommDataBuffer) - 5)) { // We will send the command just before it runs out of credit + if(bytesRead > (sizeof (rfcommDataBuffer) - 5)) { // We will send the command just before it runs out of credit bytesRead = 0; sendRfcommCredit(rfcommChannelConnection, rfcommDirection, 0, RFCOMM_UIH, 0x10, sizeof (rfcommDataBuffer)); // Send more credit #ifdef EXTRADEBUG diff --git a/SPP.h b/SPP.h index 47493fd5..d9f6761c 100644 --- a/SPP.h +++ b/SPP.h @@ -98,6 +98,7 @@ public: * @return Return the number of bytes ready to be read. */ virtual int available(void); + /** Send out all bytes in the buffer. */ virtual void flush(void) { send(); @@ -218,4 +219,4 @@ private: bool checkFcs(uint8_t *data, uint8_t fcs); uint8_t crc(uint8_t *data); }; -#endif \ No newline at end of file +#endif diff --git a/Usb.cpp b/Usb.cpp index 3bcea447..e21ca1fe 100644 --- a/Usb.cpp +++ b/Usb.cpp @@ -44,13 +44,13 @@ void USB::setUsbTaskState(uint8_t state) { EpInfo* USB::getEpInfoEntry(uint8_t addr, uint8_t ep) { UsbDevice *p = addrPool.GetUsbDevicePtr(addr); - if (!p || !p->epinfo) + if(!p || !p->epinfo) return NULL; EpInfo *pep = p->epinfo; - for (uint8_t i = 0; i < p->epcount; i++) { - if ((pep)->epAddr == ep) + for(uint8_t i = 0; i < p->epcount; i++) { + if((pep)->epAddr == ep) return pep; pep++; @@ -62,12 +62,12 @@ EpInfo* USB::getEpInfoEntry(uint8_t addr, uint8_t ep) { /* each device is different and has different number of endpoints. This function plugs endpoint record structure, defined in application, to devtable */ uint8_t USB::setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr) { - if (!eprecord_ptr) + if(!eprecord_ptr) return USB_ERROR_INVALID_ARGUMENT; UsbDevice *p = addrPool.GetUsbDevicePtr(addr); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->address.devAddress = addr; @@ -80,15 +80,15 @@ uint8_t USB::setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr) uint8_t USB::SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t &nak_limit) { UsbDevice *p = addrPool.GetUsbDevicePtr(addr); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - if (!p->epinfo) + if(!p->epinfo) return USB_ERROR_EPINFO_IS_NULL; *ppep = getEpInfoEntry(addr, ep); - if (!*ppep) + if(!*ppep) return USB_ERROR_EP_NOT_FOUND_IN_TBL; nak_limit = (0x0001UL << (((*ppep)->bmNakPower > USB_NAK_MAX_POWER) ? USB_NAK_MAX_POWER : (*ppep)->bmNakPower)); @@ -134,7 +134,7 @@ uint8_t USB::ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bReque rcode = SetAddress(addr, ep, &pep, nak_limit); - if (rcode) + if(rcode) return rcode; direction = ((bmReqType & 0x80) > 0); @@ -151,39 +151,39 @@ uint8_t USB::ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bReque rcode = dispatchPkt(tokSETUP, ep, nak_limit); //dispatch packet - if (rcode) //return HRSLT if not zero + if(rcode) //return HRSLT if not zero return ( rcode); - if (dataptr != NULL) //data stage, if present + if(dataptr != NULL) //data stage, if present { - if (direction) //IN transfer + if(direction) //IN transfer { uint16_t left = total; pep->bmRcvToggle = 1; //bmRCVTOG1; - while (left) { + while(left) { // Bytes read into buffer uint16_t read = nbytes; //uint16_t read = (leftbmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; continue; } - if (rcode) + if(rcode) return rcode; // Invoke callback function if inTransfer completed successfully and callback function pointer is specified - if (!rcode && p) + if(!rcode && p) ((USBReadParser*)p)->Parse(read, dataptr, total - left); left -= read; - if (read < nbytes) + if(read < nbytes) break; } } else //OUT transfer @@ -191,7 +191,7 @@ uint8_t USB::ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bReque pep->bmSndToggle = 1; //bmSNDTOG1; rcode = OutTransfer(pep, nak_limit, nbytes, dataptr); } - if (rcode) //return error + if(rcode) //return error return ( rcode); } // Status stage @@ -209,7 +209,7 @@ uint8_t USB::inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t* uint8_t rcode = SetAddress(addr, ep, &pep, nak_limit); - if (rcode) { + if(rcode) { USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81); USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81); USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81); @@ -229,22 +229,22 @@ uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, ui *nbytesptr = 0; regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value - while (1) // use a 'return' to exit this loop - { + // use a 'break' to exit this loop + while(1) { rcode = dispatchPkt(tokIN, pep->epAddr, nak_limit); //IN packet to EP-'endpoint'. Function takes care of NAKS. - if (rcode == hrTOGERR) { + if(rcode == hrTOGERR) { // yes, we flip it wrong here so that next time it is actually correct! pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value continue; } - if (rcode) { + if(rcode) { //printf(">>>>>>>> Problem! dispatchPkt %2.2x\r\n", rcode); break; //should be 0, indicating ACK. Else return error code. } /* check for RCVDAVIRQ and generate error if not present */ /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */ - if ((regRd(rHIRQ) & bmRCVDAVIRQ) == 0) { + if((regRd(rHIRQ) & bmRCVDAVIRQ) == 0) { //printf(">>>>>>>> Problem! NO RCVDAVIRQ!\r\n"); rcode = 0xf0; //receive error break; @@ -253,7 +253,7 @@ uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, ui //printf("Got %i bytes \r\n", pktsize); // This would be OK, but... //assert(pktsize <= nbytes); - if (pktsize > nbytes) { + if(pktsize > nbytes) { // This can happen. Use of assert on Arduino locks up the Arduino. // So I will trim the value, and hope for the best. //printf(">>>>>>>> Problem! Wanted %i bytes but got %i.\r\n", nbytes, pktsize); @@ -262,7 +262,7 @@ uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, ui int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr); - if (mem_left < 0) + if(mem_left < 0) mem_left = 0; data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data); @@ -273,7 +273,7 @@ uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, ui /* The transfer is complete under two conditions: */ /* 1. The device sent a short packet (L.T. maxPacketSize) */ /* 2. 'nbytes' have been transferred. */ - if ((pktsize < maxpktsize) || (*nbytesptr >= nbytes)) // have we transferred 'nbytes' bytes? + if((pktsize < maxpktsize) || (*nbytesptr >= nbytes)) // have we transferred 'nbytes' bytes? { // Save toggle value pep->bmRcvToggle = ((regRd(rHRSL) & bmRCVTOGRD)) ? 1 : 0; @@ -295,7 +295,7 @@ uint8_t USB::outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dat uint8_t rcode = SetAddress(addr, ep, &pep, nak_limit); - if (rcode) + if(rcode) return rcode; return OutTransfer(pep, nak_limit, nbytes, data); @@ -309,35 +309,35 @@ uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8 uint8_t maxpktsize = pep->maxPktSize; - if (maxpktsize < 1 || maxpktsize > 64) + if(maxpktsize < 1 || maxpktsize > 64) return USB_ERROR_INVALID_MAX_PKT_SIZE; unsigned long timeout = millis() + USB_XFER_TIMEOUT; regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); //set toggle value - while (bytes_left) { + while(bytes_left) { retry_count = 0; nak_count = 0; bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left; bytesWr(rSNDFIFO, bytes_tosend, data_p); //filling output FIFO regWr(rSNDBC, bytes_tosend); //set number of bytes regWr(rHXFR, (tokOUT | pep->epAddr)); //dispatch packet - while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ + while(!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ rcode = (regRd(rHRSL) & 0x0f); - while (rcode && (timeout > millis())) { - switch (rcode) { + while(rcode && (timeout > millis())) { + switch(rcode) { case hrNAK: nak_count++; - if (nak_limit && (nak_count == nak_limit)) + if(nak_limit && (nak_count == nak_limit)) goto breakout; //return ( rcode); break; case hrTIMEOUT: retry_count++; - if (retry_count == USB_RETRY_LIMIT) + if(retry_count == USB_RETRY_LIMIT) goto breakout; //return ( rcode); break; @@ -355,7 +355,7 @@ uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8 regWr(rSNDFIFO, *data_p); regWr(rSNDBC, bytes_tosend); regWr(rHXFR, (tokOUT | pep->epAddr)); //dispatch packet - while (!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ + while(!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ rcode = (regRd(rHRSL) & 0x0f); }//while( rcode && .... @@ -380,15 +380,15 @@ uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) { uint8_t retry_count = 0; uint16_t nak_count = 0; - while (timeout > millis()) { + while(timeout > millis()) { regWr(rHXFR, (token | ep)); //launch the transfer rcode = USB_ERROR_TRANSFER_TIMEOUT; - while (timeout > millis()) //wait for transfer completion + while(timeout > millis()) //wait for transfer completion { tmpdata = regRd(rHIRQ); - if (tmpdata & bmHXFRDNIRQ) { + if(tmpdata & bmHXFRDNIRQ) { regWr(rHIRQ, bmHXFRDNIRQ); //clear the interrupt rcode = 0x00; break; @@ -401,15 +401,15 @@ uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) { rcode = (regRd(rHRSL) & 0x0f); //analyze transfer result - switch (rcode) { + switch(rcode) { case hrNAK: nak_count++; - if (nak_limit && (nak_count == nak_limit)) + if(nak_limit && (nak_count == nak_limit)) return (rcode); break; case hrTIMEOUT: retry_count++; - if (retry_count == USB_RETRY_LIMIT) + if(retry_count == USB_RETRY_LIMIT) return (rcode); break; default: @@ -434,13 +434,13 @@ void USB::Task(void) //USB state machine tmpdata = getVbusState(); /* modify USB task state if Vbus changed */ - switch (tmpdata) { + switch(tmpdata) { case SE1: //illegal state usb_task_state = USB_DETACHED_SUBSTATE_ILLEGAL; lowspeed = false; break; case SE0: //disconnected - if ((usb_task_state & USB_STATE_MASK) != USB_STATE_DETACHED) + if((usb_task_state & USB_STATE_MASK) != USB_STATE_DETACHED) usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; lowspeed = false; break; @@ -449,23 +449,23 @@ void USB::Task(void) //USB state machine lowspeed = true; //intentional fallthrough case FSHOST: //attached - if ((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) { + if((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) { delay = millis() + USB_SETTLE_DELAY; usb_task_state = USB_ATTACHED_SUBSTATE_SETTLE; } break; }// switch( tmpdata - for (uint8_t i = 0; i < USB_NUMDEVICES; i++) - if (devConfig[i]) + for(uint8_t i = 0; i < USB_NUMDEVICES; i++) + if(devConfig[i]) rcode = devConfig[i]->Poll(); - switch (usb_task_state) { + switch(usb_task_state) { case USB_DETACHED_SUBSTATE_INITIALIZE: init(); - for (uint8_t i = 0; i < USB_NUMDEVICES; i++) - if (devConfig[i]) + for(uint8_t i = 0; i < USB_NUMDEVICES; i++) + if(devConfig[i]) rcode = devConfig[i]->Release(); usb_task_state = USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE; @@ -475,7 +475,7 @@ void USB::Task(void) //USB state machine case USB_DETACHED_SUBSTATE_ILLEGAL: //just sit here break; case USB_ATTACHED_SUBSTATE_SETTLE: //settle time for just attached device - if (delay < millis()) + if(delay < millis()) usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE; else break; // don't fall through case USB_ATTACHED_SUBSTATE_RESET_DEVICE: @@ -483,7 +483,7 @@ void USB::Task(void) //USB state machine usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE; break; case USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE: - if ((regRd(rHCTL) & bmBUSRST) == 0) { + if((regRd(rHCTL) & bmBUSRST) == 0) { tmpdata = regRd(rMODE) | bmSOFKAENAB; //start SOF generation regWr(rMODE, tmpdata); usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_SOF; @@ -491,7 +491,7 @@ void USB::Task(void) //USB state machine } break; case USB_ATTACHED_SUBSTATE_WAIT_SOF: //todo: change check order - if (regRd(rHIRQ) & bmFRAMEIRQ) { + if(regRd(rHIRQ) & bmFRAMEIRQ) { //when first SOF received _and_ 20ms has passed we can continue /* if (delay < millis()) //20ms passed @@ -502,7 +502,7 @@ void USB::Task(void) //USB state machine } break; case USB_ATTACHED_SUBSTATE_WAIT_RESET: - if (delay < millis()) usb_task_state = USB_STATE_CONFIGURING; + if(delay < millis()) usb_task_state = USB_STATE_CONFIGURING; else break; // don't fall through case USB_STATE_CONFIGURING: @@ -511,8 +511,8 @@ void USB::Task(void) //USB state machine rcode = Configuring(0, 0, lowspeed); - if (rcode) { - if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) { + if(rcode) { + if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) { usb_error = rcode; usb_task_state = USB_STATE_ERROR; } @@ -535,10 +535,10 @@ uint8_t USB::DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed) { // Get pointer to pseudo device with address 0 assigned p0 = addrPool.GetUsbDevicePtr(0); - if (!p0) + if(!p0) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - if (!p0->epinfo) + if(!p0->epinfo) return USB_ERROR_EPINFO_IS_NULL; p0->lowspeed = (lowspeed) ? true : false; @@ -546,12 +546,12 @@ uint8_t USB::DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed) { // Allocate new address according to device class uint8_t bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; @@ -559,7 +559,7 @@ uint8_t USB::DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { addrPool.FreeAddress(bAddress); bAddress = 0; return rcode; @@ -573,8 +573,8 @@ uint8_t USB::AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lo again: uint8_t rcode = devConfig[driver]->ConfigureDevice(parent, port, lowspeed); - if (rcode == USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET) { - if (parent == 0) { + if(rcode == USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET) { + if(parent == 0) { // Send a bus reset on the root interface. regWr(rHCTL, bmBUSRST); //issue bus reset delay(102); // delay 102ms, compensate for clock inaccuracy. @@ -582,22 +582,22 @@ again: // reset parent port devConfig[parent]->ResetHubPort(port); } - } else if (rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works + } else if(rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works delay(100); retries++; goto again; - } else if (rcode) + } else if(rcode) return rcode; rcode = devConfig[driver]->Init(parent, port, lowspeed); - if (rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works + if(rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works delay(100); retries++; goto again; } - if (rcode) { + if(rcode) { // Issue a bus reset, because the device may be in a limbo state - if (parent == 0) { + if(parent == 0) { // Send a bus reset on the root interface. regWr(rHCTL, bmBUSRST); //issue bus reset delay(102); // delay 102ms, compensate for clock inaccuracy. @@ -669,7 +669,7 @@ uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) { AddressPool &addrPool = GetAddressPool(); // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) { + if(!p) { //printf("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n"); return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } @@ -689,7 +689,7 @@ uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) { + if(rcode) { //printf("Configuring error: Can't get USB_DEVICE_DESCRIPTOR\r\n"); return rcode; } @@ -705,30 +705,30 @@ uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) { uint8_t klass = udd->bDeviceClass; // Attempt to configure if VID/PID or device class matches with a driver - for (devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { - if (!devConfig[devConfigIndex]) continue; // no driver - if (devConfig[devConfigIndex]->GetAddress()) continue; // consumed - if (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) { + for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { + if(!devConfig[devConfigIndex]) continue; // no driver + if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed + if(devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) { rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); - if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED) + if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED) break; } } - if (devConfigIndex < USB_NUMDEVICES) { + if(devConfigIndex < USB_NUMDEVICES) { return rcode; } // blindly attempt to configure - for (devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { - if (!devConfig[devConfigIndex]) continue; - if (devConfig[devConfigIndex]->GetAddress()) continue; // consumed - if (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) continue; // If this is true it means it must have returned USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED above + for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { + if(!devConfig[devConfigIndex]) continue; + if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed + if(devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) continue; // If this is true it means it must have returned USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED above rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); //printf("ERROR ENUMERATING %2.2x\r\n", rcode); - if (!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) { + if(!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) { // in case of an error dev_index should be reset to 0 // in order to start from the very beginning the // next time the program gets here @@ -744,12 +744,12 @@ uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) { } uint8_t USB::ReleaseDevice(uint8_t addr) { - if (!addr) + if(!addr) return 0; - for (uint8_t i = 0; i < USB_NUMDEVICES; i++) { - if (!devConfig[i]) continue; - if (devConfig[i]->GetAddress() == addr) + for(uint8_t i = 0; i < USB_NUMDEVICES; i++) { + if(!devConfig[i]) continue; + if(devConfig[i]->GetAddress() == addr) return devConfig[i]->Release(); } return 0; @@ -776,7 +776,7 @@ uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser uint8_t ret = getConfDescr(addr, ep, 9, conf, buf); - if (ret) + if(ret) return ret; uint16_t total = ucd->wTotalLength; @@ -807,4 +807,3 @@ uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) { } #endif // defined(USB_METHODS_INLINE) - diff --git a/UsbCore.h b/UsbCore.h index bbcbfa0e..9a09d804 100644 --- a/UsbCore.h +++ b/UsbCore.h @@ -104,14 +104,38 @@ typedef MAX3421e MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega class USBDeviceConfig { public: - virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed) { return 0; } - virtual uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {return 0; } - virtual uint8_t Release() { return 0; } - virtual uint8_t Poll() { return 0; } - virtual uint8_t GetAddress() { return 0; } - virtual void ResetHubPort(uint8_t port) { return; } // Note used for hubs only! - virtual boolean VIDPIDOK(uint16_t vid, uint16_t pid) { return false; } - virtual boolean DEVCLASSOK(uint8_t klass) { return false; } + + virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed) { + return 0; + } + + virtual uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { + return 0; + } + + virtual uint8_t Release() { + return 0; + } + + virtual uint8_t Poll() { + return 0; + } + + virtual uint8_t GetAddress() { + return 0; + } + + virtual void ResetHubPort(uint8_t port) { + return; + } // Note used for hubs only! + + virtual boolean VIDPIDOK(uint16_t vid, uint16_t pid) { + return false; + } + + virtual boolean DEVCLASSOK(uint8_t klass) { + return false; + } }; /* USB Setup Packet Structure */ @@ -138,7 +162,7 @@ typedef struct { } wVal_u; uint16_t wIndex; // 4 Depends on bRequest uint16_t wLength; // 6 Depends on bRequest -}__attribute__((packed)) SETUP_PKT, *PSETUP_PKT; +} __attribute__((packed)) SETUP_PKT, *PSETUP_PKT; @@ -166,7 +190,7 @@ public: }; AddressPool& GetAddressPool() { - return(AddressPool&) addrPool; + return (AddressPool&)addrPool; }; uint8_t RegisterDeviceClass(USBDeviceConfig *pdev) { @@ -225,30 +249,29 @@ private: //get device descriptor inline uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) { - return( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, dataptr)); + return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, dataptr)); } //get configuration descriptor inline uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) { - return( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, dataptr)); + return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, dataptr)); } //get string descriptor inline uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t nuint8_ts, uint8_t index, uint16_t langid, uint8_t* dataptr) { - return( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nuint8_ts, dataptr)); + return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nuint8_ts, dataptr)); } //set address inline uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) { - return( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, NULL)); + return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, NULL)); } //set configuration inline uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) { - return( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, NULL)); + return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, NULL)); } #endif // defined(USB_METHODS_INLINE) #endif /* USBCORE_H */ - diff --git a/Wii.cpp b/Wii.cpp index e0d79707..1fbd95f4 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -84,7 +84,7 @@ const uint32_t PROCONTROLLERBUTTONS[] PROGMEM = { WII::WII(BTD *p, bool pair) : pBtd(p) // pointer to USB class instance - mandatory { - if (pBtd) + if(pBtd) pBtd->registerServiceClass(this); // Register it as a Bluetooth service pBtd->pairWithWii = pair; @@ -115,8 +115,8 @@ void WII::Reset() { } void WII::disconnect() { // Use this void to disconnect any of the controllers - if (!motionPlusInside) { // The old Wiimote needs a delay after the first command or it will automatically reconnect - if (motionPlusConnected) { + if(!motionPlusInside) { // The old Wiimote needs a delay after the first command or it will automatically reconnect + if(motionPlusConnected) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDeactivating Motion Plus"), 0x80); #endif @@ -132,9 +132,9 @@ void WII::disconnect() { // Use this void to disconnect any of the controllers } void WII::ACLData(uint8_t* l2capinbuf) { - if (!pBtd->l2capConnectionClaimed && pBtd->incomingWii && !wiimoteConnected && !activeConnection) { - if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { - if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { + if(!pBtd->l2capConnectionClaimed && pBtd->incomingWii && !wiimoteConnected && !activeConnection) { + if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { + if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { motionPlusInside = pBtd->motionPlusInside; pBtd->incomingWii = false; pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service @@ -144,9 +144,9 @@ void WII::ACLData(uint8_t* l2capinbuf) { } } } - if ((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection - if ((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U - if (l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { + if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U + if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -161,15 +161,15 @@ void WII::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" "), 0x80); D_PrintHex (l2capinbuf[14], 0x80); #endif - } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) { - if (((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success - if (l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) { + if(((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success + if(l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Connection Complete"), 0x80); identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[12]; control_scid[1] = l2capinbuf[13]; l2cap_set_flag(L2CAP_FLAG_CONTROL_CONNECTED); - } else if (l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) { + } else if(l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80); identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[12]; @@ -177,7 +177,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { l2cap_set_flag(L2CAP_FLAG_INTERRUPT_CONNECTED); } } - } else if (l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) { #ifdef EXTRADEBUG Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80); D_PrintHex (l2capinbuf[13], 0x80); @@ -190,46 +190,46 @@ void WII::ACLData(uint8_t* l2capinbuf) { Notify(PSTR(" Identifier: "), 0x80); D_PrintHex (l2capinbuf[9], 0x80); #endif - if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { + if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) { identifier = l2capinbuf[9]; control_scid[0] = l2capinbuf[14]; control_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST); - } else if ((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { + } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) { identifier = l2capinbuf[9]; interrupt_scid[0] = l2capinbuf[14]; interrupt_scid[1] = l2capinbuf[15]; l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST); } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { - if ((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) { + if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS); } } - } else if (l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) { + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { //Notify(PSTR("\r\nHID Control Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], control_scid); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { //Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80); pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], interrupt_scid); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { - if (l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) { + if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80); #endif identifier = l2capinbuf[9]; pBtd->l2cap_disconnection_response(hci_handle, identifier, control_dcid, control_scid); Reset(); - } else if (l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { + } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80); #endif @@ -237,12 +237,12 @@ void WII::ACLData(uint8_t* l2capinbuf) { pBtd->l2cap_disconnection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid); Reset(); } - } else if (l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { - if (l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { + } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) { + if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE); - } else if (l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { + } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) { //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80); identifier = l2capinbuf[9]; l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE); @@ -255,41 +255,41 @@ void WII::ACLData(uint8_t* l2capinbuf) { D_PrintHex (l2capinbuf[8], 0x80); } #endif - } else if (l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt + } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt //Notify(PSTR("\r\nL2CAP Interrupt"), 0x80); - if (l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT - if ((l2capinbuf[9] >= 0x20 && l2capinbuf[9] <= 0x22) || (l2capinbuf[9] >= 0x30 && l2capinbuf[9] <= 0x37) || l2capinbuf[9] == 0x3e || l2capinbuf[9] == 0x3f) { // These reports include the buttons - if ((l2capinbuf[9] >= 0x20 && l2capinbuf[9] <= 0x22) || l2capinbuf[9] == 0x31 || l2capinbuf[9] == 0x33) // These reports have no extensions bytes + if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT + if((l2capinbuf[9] >= 0x20 && l2capinbuf[9] <= 0x22) || (l2capinbuf[9] >= 0x30 && l2capinbuf[9] <= 0x37) || l2capinbuf[9] == 0x3e || l2capinbuf[9] == 0x3f) { // These reports include the buttons + if((l2capinbuf[9] >= 0x20 && l2capinbuf[9] <= 0x22) || l2capinbuf[9] == 0x31 || l2capinbuf[9] == 0x33) // These reports have no extensions bytes ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8)); - else if (wiiUProControllerConnected) + else if(wiiUProControllerConnected) ButtonState = (uint32_t)(((~l2capinbuf[23]) & 0xFE) | ((uint16_t)(~l2capinbuf[24]) << 8) | ((uint32_t)((~l2capinbuf[25]) & 0x03) << 16)); - else if (motionPlusConnected) { - if (l2capinbuf[20] & 0x02) // Only update the wiimote buttons, since the extension bytes are from the Motion Plus + else if(motionPlusConnected) { + if(l2capinbuf[20] & 0x02) // Only update the wiimote buttons, since the extension bytes are from the Motion Plus ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8) | ((uint32_t)(ButtonState & 0xFFFF0000))); - else if (nunchuckConnected) // Update if it's a report from the Nunchuck + else if(nunchuckConnected) // Update if it's a report from the Nunchuck ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8) | ((uint32_t)((~l2capinbuf[20]) & 0x0C) << 14)); //else if(classicControllerConnected) // Update if it's a report from the Classic Controller - } else if (nunchuckConnected) // The Nunchuck is directly connected + } else if(nunchuckConnected) // The Nunchuck is directly connected ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8) | ((uint32_t)((~l2capinbuf[20]) & 0x03) << 16)); //else if(classicControllerConnected) // The Classic Controller is directly connected - else if (!unknownExtensionConnected) + else if(!unknownExtensionConnected) ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8)); #ifdef PRINTREPORT Notify(PSTR("ButtonState: "), 0x80); D_PrintHex (ButtonState, 0x80); Notify(PSTR("\r\n"), 0x80); #endif - if (ButtonState != OldButtonState) { + if(ButtonState != OldButtonState) { ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable OldButtonState = ButtonState; } } - if (l2capinbuf[9] == 0x31 || l2capinbuf[9] == 0x33 || l2capinbuf[9] == 0x35 || l2capinbuf[9] == 0x37) { // Read the accelerometer + if(l2capinbuf[9] == 0x31 || l2capinbuf[9] == 0x33 || l2capinbuf[9] == 0x35 || l2capinbuf[9] == 0x37) { // Read the accelerometer accXwiimote = ((l2capinbuf[12] << 2) | (l2capinbuf[10] & 0x60 >> 5)) - 500; accYwiimote = ((l2capinbuf[13] << 2) | (l2capinbuf[11] & 0x20 >> 4)) - 500; accZwiimote = ((l2capinbuf[14] << 2) | (l2capinbuf[11] & 0x40 >> 5)) - 500; } - switch (l2capinbuf[9]) { + switch(l2capinbuf[9]) { case 0x20: // Status Information - (a1) 20 BB BB LF 00 00 VV #ifdef EXTRADEBUG Notify(PSTR("\r\nStatus report was received"), 0x80); @@ -297,33 +297,33 @@ void WII::ACLData(uint8_t* l2capinbuf) { wiiState = l2capinbuf[12]; // (0x01: Battery is nearly empty), (0x02: An Extension Controller is connected), (0x04: Speaker enabled), (0x08: IR enabled), (0x10: LED1, 0x20: LED2, 0x40: LED3, 0x80: LED4) batteryLevel = l2capinbuf[15]; // Update battery level #ifdef DEBUG_USB_HOST - if (l2capinbuf[12] & 0x01) + if(l2capinbuf[12] & 0x01) Notify(PSTR("\r\nWARNING: Battery is nearly empty"), 0x80); #endif - if (checkExtension) { // If this is false it means that the user must have called getBatteryLevel() - if (l2capinbuf[12] & 0x02) { // Check if a extension is connected + if(checkExtension) { // If this is false it means that the user must have called getBatteryLevel() + if(l2capinbuf[12] & 0x02) { // Check if a extension is connected #ifdef DEBUG_USB_HOST - if (!unknownExtensionConnected) + if(!unknownExtensionConnected) Notify(PSTR("\r\nExtension connected"), 0x80); #endif unknownExtensionConnected = true; #ifdef WIICAMERA - if (!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera + if(!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera #endif - setReportMode(false, 0x35); // Also read the extension + setReportMode(false, 0x35); // Also read the extension } else { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nExtension disconnected"), 0x80); #endif - if (motionPlusConnected) { + if(motionPlusConnected) { #ifdef DEBUG_USB_HOST Notify(PSTR(" - from Motion Plus"), 0x80); #endif wii_clear_flag(WII_FLAG_NUNCHUCK_CONNECTED); - if (!activateNunchuck) // If it's already trying to initialize the Nunchuck don't set it to false + if(!activateNunchuck) // If it's already trying to initialize the Nunchuck don't set it to false nunchuckConnected = false; //else if(classicControllerConnected) - } else if (nunchuckConnected) { + } else if(nunchuckConnected) { #ifdef DEBUG_USB_HOST Notify(PSTR(" - Nunchuck"), 0x80); #endif @@ -338,28 +338,28 @@ void WII::ACLData(uint8_t* l2capinbuf) { checkExtension = true; // Check for extensions by default break; case 0x21: // Read Memory Data - if ((l2capinbuf[12] & 0x0F) == 0) { // No error + if((l2capinbuf[12] & 0x0F) == 0) { // No error // See: http://wiibrew.org/wiki/Wiimote/Extension_Controllers - if (l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x00 && l2capinbuf[20] == 0x00) { + if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x00 && l2capinbuf[20] == 0x00) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nNunchuck connected"), 0x80); #endif wii_set_flag(WII_FLAG_NUNCHUCK_CONNECTED); - } else if (l2capinbuf[16] == 0x00 && (l2capinbuf[17] == 0xA6 || l2capinbuf[17] == 0xA4) && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x00 && l2capinbuf[20] == 0x05) { + } else if(l2capinbuf[16] == 0x00 && (l2capinbuf[17] == 0xA6 || l2capinbuf[17] == 0xA4) && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x00 && l2capinbuf[20] == 0x05) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nMotion Plus connected"), 0x80); #endif wii_set_flag(WII_FLAG_MOTION_PLUS_CONNECTED); - } else if (l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x04 && l2capinbuf[20] == 0x05) { + } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x04 && l2capinbuf[20] == 0x05) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nMotion Plus activated in normal mode"), 0x80); #endif motionPlusConnected = true; #ifdef WIICAMERA - if (!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera + if(!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera #endif setReportMode(false, 0x35); // Also read the extension - } else if (l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x05 && l2capinbuf[20] == 0x05) { + } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x05 && l2capinbuf[20] == 0x05) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nMotion Plus activated in Nunchuck pass-through mode"), 0x80); #endif @@ -367,16 +367,16 @@ void WII::ACLData(uint8_t* l2capinbuf) { motionPlusConnected = true; nunchuckConnected = true; #ifdef WIICAMERA - if (!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera + if(!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera #endif setReportMode(false, 0x35); // Also read the extension - } else if (l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA6 && l2capinbuf[18] == 0x20 && (l2capinbuf[19] == 0x00 || l2capinbuf[19] == 0x04 || l2capinbuf[19] == 0x05 || l2capinbuf[19] == 0x07) && l2capinbuf[20] == 0x05) { + } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA6 && l2capinbuf[18] == 0x20 && (l2capinbuf[19] == 0x00 || l2capinbuf[19] == 0x04 || l2capinbuf[19] == 0x05 || l2capinbuf[19] == 0x07) && l2capinbuf[20] == 0x05) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nInactive Wii Motion Plus"), 0x80); Notify(PSTR("\r\nPlease unplug the Motion Plus, disconnect the Wiimote and then replug the Motion Plus Extension"), 0x80); #endif stateCounter = 300; // Skip the rest in "WII_CHECK_MOTION_PLUS_STATE" - } else if (l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x01 && l2capinbuf[20] == 0x20) { + } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x01 && l2capinbuf[20] == 0x20) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nWii U Pro Controller connected"), 0x80); #endif @@ -388,7 +388,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { D_PrintHex (l2capinbuf[13], 0x80); D_PrintHex (l2capinbuf[14], 0x80); Notify(PSTR("\r\nData: "), 0x80); - for (uint8_t i = 0; i < ((l2capinbuf[12] >> 4) + 1); i++) { // bit 4-7 is the length-1 + for(uint8_t i = 0; i < ((l2capinbuf[12] >> 4) + 1); i++) { // bit 4-7 is the length-1 D_PrintHex (l2capinbuf[15 + i], 0x80); Notify(PSTR(" "), 0x80); } @@ -405,7 +405,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { break; case 0x22: // Acknowledge output report, return function result #ifdef DEBUG_USB_HOST - if (l2capinbuf[13] != 0x00) { // Check if there is an error + if(l2capinbuf[13] != 0x00) { // Check if there is an error Notify(PSTR("\r\nCommand failed: "), 0x80); D_PrintHex (l2capinbuf[12], 0x80); } @@ -461,9 +461,9 @@ void WII::ACLData(uint8_t* l2capinbuf) { break; case 0x35: // Core Buttons and Accelerometer with 16 Extension Bytes // (a1) 35 BB BB AA AA AA EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE - if (motionPlusConnected) { - if (l2capinbuf[20] & 0x02) { // Check if it's a report from the Motion controller or the extension - if (motionValuesReset) { // We will only use the values when the gyro value has been set + if(motionPlusConnected) { + if(l2capinbuf[20] & 0x02) { // Check if it's a report from the Motion controller or the extension + if(motionValuesReset) { // We will only use the values when the gyro value has been set gyroYawRaw = ((l2capinbuf[15] | ((l2capinbuf[18] & 0xFC) << 6)) - gyroYawZero); gyroRollRaw = ((l2capinbuf[16] | ((l2capinbuf[19] & 0xFC) << 6)) - gyroRollZero); gyroPitchRaw = ((l2capinbuf[17] | ((l2capinbuf[20] & 0xFC) << 6)) - gyroPitchZero); @@ -473,11 +473,11 @@ void WII::ACLData(uint8_t* l2capinbuf) { pitchGyroSpeed = (double)gyroPitchRaw / ((double)gyroPitchZero / pitchGyroScale); /* The onboard gyro has two ranges for slow and fast mode */ - if (!(l2capinbuf[18] & 0x02)) // Check if fast mode is used + if(!(l2capinbuf[18] & 0x02)) // Check if fast mode is used yawGyroSpeed *= 4.545; - if (!(l2capinbuf[18] & 0x01)) // Check if fast mode is used + if(!(l2capinbuf[18] & 0x01)) // Check if fast mode is used pitchGyroSpeed *= 4.545; - if (!(l2capinbuf[19] & 0x02)) // Check if fast mode is used + if(!(l2capinbuf[19] & 0x02)) // Check if fast mode is used rollGyroSpeed *= 4.545; compPitch = (0.93 * (compPitch + (pitchGyroSpeed * (double)(micros() - timer) / 1000000)))+(0.07 * getWiimotePitch()); // Use a complimentary filter to calculate the angle @@ -495,15 +495,15 @@ void WII::ACLData(uint8_t* l2capinbuf) { Notify(gyroRoll, 0x80); Notify(PSTR("\tgyroPitch: "), 0x80); Notify(gyroPitch, 0x80); - */ + */ /* Notify(PSTR("\twiimoteRoll: "), 0x80); Notify(wiimoteRoll, 0x80); Notify(PSTR("\twiimotePitch: "), 0x80); Notify(wiimotePitch, 0x80); - */ + */ } else { - if ((micros() - timer) > 1000000) { // Loop for 1 sec before resetting the values + if((micros() - timer) > 1000000) { // Loop for 1 sec before resetting the values #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nThe gyro values has been reset"), 0x80); #endif @@ -524,7 +524,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { } } } else { - if (nunchuckConnected) { + if(nunchuckConnected) { hatValues[HatX] = l2capinbuf[15]; hatValues[HatY] = l2capinbuf[16]; accXnunchuck = ((l2capinbuf[17] << 2) | (l2capinbuf[20] & 0x10 >> 3)) - 416; @@ -533,8 +533,8 @@ void WII::ACLData(uint8_t* l2capinbuf) { } //else if(classicControllerConnected) { } } - if (l2capinbuf[19] & 0x01) { - if (!extensionConnected) { + if(l2capinbuf[19] & 0x01) { + if(!extensionConnected) { extensionConnected = true; unknownExtensionConnected = true; #ifdef DEBUG_USB_HOST @@ -542,7 +542,7 @@ void WII::ACLData(uint8_t* l2capinbuf) { #endif } } else { - if (extensionConnected && !unknownExtensionConnected) { + if(extensionConnected && !unknownExtensionConnected) { extensionConnected = false; unknownExtensionConnected = true; #ifdef DEBUG_USB_HOST @@ -552,13 +552,13 @@ void WII::ACLData(uint8_t* l2capinbuf) { } } - } else if (nunchuckConnected) { + } else if(nunchuckConnected) { hatValues[HatX] = l2capinbuf[15]; hatValues[HatY] = l2capinbuf[16]; accXnunchuck = ((l2capinbuf[17] << 2) | (l2capinbuf[20] & 0x0C >> 2)) - 416; accYnunchuck = ((l2capinbuf[18] << 2) | (l2capinbuf[20] & 0x30 >> 4)) - 416; accZnunchuck = ((l2capinbuf[19] << 2) | (l2capinbuf[20] & 0xC0 >> 6)) - 416; - } else if (wiiUProControllerConnected) { + } else if(wiiUProControllerConnected) { hatValues[LeftHatX] = (l2capinbuf[15] | l2capinbuf[16] << 8); hatValues[RightHatX] = (l2capinbuf[17] | l2capinbuf[18] << 8); hatValues[LeftHatY] = (l2capinbuf[19] | l2capinbuf[20] << 8); @@ -579,10 +579,10 @@ void WII::ACLData(uint8_t* l2capinbuf) { } void WII::L2CAP_task() { - switch (l2cap_state) { + switch(l2cap_state) { /* These states are used if the Wiimote is the host */ case L2CAP_CONTROL_SUCCESS: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80); #endif @@ -591,7 +591,7 @@ void WII::L2CAP_task() { break; case L2CAP_INTERRUPT_SETUP: - if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { + if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80); #endif @@ -608,7 +608,7 @@ void WII::L2CAP_task() { /* These states are used if the Arduino is the host */ case L2CAP_CONTROL_CONNECT_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) { + if(l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Control Config Request"), 0x80); #endif @@ -619,7 +619,7 @@ void WII::L2CAP_task() { break; case L2CAP_CONTROL_CONFIG_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Interrupt Connection Request"), 0x80); #endif @@ -630,7 +630,7 @@ void WII::L2CAP_task() { break; case L2CAP_INTERRUPT_CONNECT_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) { + if(l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80); #endif @@ -641,7 +641,7 @@ void WII::L2CAP_task() { break; case L2CAP_INTERRUPT_CONFIG_REQUEST: - if (l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established + if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Channels Established"), 0x80); #endif @@ -655,7 +655,7 @@ void WII::L2CAP_task() { /* The next states are in run() */ case L2CAP_INTERRUPT_DISCONNECT: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) && millis() > timer) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) && millis() > timer) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80); #endif @@ -666,7 +666,7 @@ void WII::L2CAP_task() { break; case L2CAP_CONTROL_DISCONNECT: - if (l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Control Channel"), 0x80); #endif @@ -680,12 +680,12 @@ void WII::L2CAP_task() { } void WII::Run() { - if (l2cap_state == L2CAP_INTERRUPT_DISCONNECT && millis() > timer) + if(l2cap_state == L2CAP_INTERRUPT_DISCONNECT && millis() > timer) L2CAP_task(); // Call the rest of the disconnection routine after we have waited long enough - switch (l2cap_state) { + switch(l2cap_state) { case L2CAP_WAIT: - if (pBtd->connectToWii && !pBtd->l2capConnectionClaimed && !wiimoteConnected && !activeConnection) { + if(pBtd->connectToWii && !pBtd->l2capConnectionClaimed && !wiimoteConnected && !activeConnection) { pBtd->l2capConnectionClaimed = true; activeConnection = true; motionPlusInside = pBtd->motionPlusInside; @@ -697,7 +697,7 @@ void WII::Run() { identifier = 0; pBtd->l2cap_connection_request(hci_handle, identifier, control_dcid, HID_CTRL_PSM); l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST; - } else if (l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { + } else if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80); #endif @@ -713,25 +713,25 @@ void WII::Run() { case WII_CHECK_MOTION_PLUS_STATE: #ifdef DEBUG_USB_HOST - if (stateCounter == 0) // Only print onnce + if(stateCounter == 0) // Only print onnce Notify(PSTR("\r\nChecking if a Motion Plus is connected"), 0x80); #endif stateCounter++; - if (stateCounter % 200 == 0) + if(stateCounter % 200 == 0) checkMotionPresent(); // Check if there is a motion plus connected - if (wii_check_flag(WII_FLAG_MOTION_PLUS_CONNECTED)) { + if(wii_check_flag(WII_FLAG_MOTION_PLUS_CONNECTED)) { stateCounter = 0; l2cap_state = WII_INIT_MOTION_PLUS_STATE; timer = micros(); - if (unknownExtensionConnected) { + if(unknownExtensionConnected) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nA extension is also connected"), 0x80); #endif activateNunchuck = true; // For we will just set this to true as this the only extension supported so far } - } else if (stateCounter == 601) { // We will try three times to check for the motion plus + } else if(stateCounter == 601) { // We will try three times to check for the motion plus #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nNo Motion Plus was detected"), 0x80); #endif @@ -742,23 +742,23 @@ void WII::Run() { case WII_CHECK_EXTENSION_STATE: // This is used to check if there is anything plugged in to the extension port #ifdef DEBUG_USB_HOST - if (stateCounter == 0) // Only print onnce + if(stateCounter == 0) // Only print onnce Notify(PSTR("\r\nChecking if there is any extension connected"), 0x80); #endif stateCounter++; // We use this counter as there has to be a short delay between the commands - if (stateCounter == 1) + if(stateCounter == 1) statusRequest(); // See if a new device has connected - if (stateCounter == 100) { - if (unknownExtensionConnected) // Check if there is a extension is connected to the port + if(stateCounter == 100) { + if(unknownExtensionConnected) // Check if there is a extension is connected to the port initExtension1(); else stateCounter = 399; - } else if (stateCounter == 200) + } else if(stateCounter == 200) initExtension2(); - else if (stateCounter == 300) { + else if(stateCounter == 300) { readExtensionType(); unknownExtensionConnected = false; - } else if (stateCounter == 400) { + } else if(stateCounter == 400) { stateCounter = 0; l2cap_state = TURN_ON_LED; } @@ -766,13 +766,13 @@ void WII::Run() { case WII_INIT_MOTION_PLUS_STATE: stateCounter++; - if (stateCounter == 1) + if(stateCounter == 1) initMotionPlus(); - else if (stateCounter == 100) + else if(stateCounter == 100) activateMotionPlus(); - else if (stateCounter == 200) + else if(stateCounter == 200) readExtensionType(); // Check if it has been activated - else if (stateCounter == 300) { + else if(stateCounter == 300) { stateCounter = 0; unknownExtensionConnected = false; // The motion plus will send a status report when it's activated, we will set this to false so it doesn't reinitialize the Motion Plus l2cap_state = TURN_ON_LED; @@ -780,7 +780,7 @@ void WII::Run() { break; case TURN_ON_LED: - if (wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED)) + if(wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED)) nunchuckConnected = true; wiimoteConnected = true; onInit(); @@ -788,46 +788,46 @@ void WII::Run() { break; case L2CAP_DONE: - if (unknownExtensionConnected) { + if(unknownExtensionConnected) { #ifdef DEBUG_USB_HOST - if (stateCounter == 0) // Only print once + if(stateCounter == 0) // Only print once Notify(PSTR("\r\nChecking extension port"), 0x80); #endif stateCounter++; // We will use this counter as there has to be a short delay between the commands - if (stateCounter == 50) + if(stateCounter == 50) statusRequest(); - else if (stateCounter == 100) + else if(stateCounter == 100) initExtension1(); - else if (stateCounter == 150) - if ((extensionConnected && motionPlusConnected) || (unknownExtensionConnected && !motionPlusConnected)) + else if(stateCounter == 150) + if((extensionConnected && motionPlusConnected) || (unknownExtensionConnected && !motionPlusConnected)) initExtension2(); else stateCounter = 299; // There is no extension connected - else if (stateCounter == 200) + else if(stateCounter == 200) readExtensionType(); - else if (stateCounter == 250) { - if (wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED)) { + else if(stateCounter == 250) { + if(wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nNunchuck was reconnected"), 0x80); #endif activateNunchuck = true; nunchuckConnected = true; } - if (!motionPlusConnected) + if(!motionPlusConnected) stateCounter = 449; - } else if (stateCounter == 300) { - if (motionPlusConnected) { + } else if(stateCounter == 300) { + if(motionPlusConnected) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nReactivating the Motion Plus"), 0x80); #endif initMotionPlus(); } else stateCounter = 449; - } else if (stateCounter == 350) + } else if(stateCounter == 350) activateMotionPlus(); - else if (stateCounter == 400) + else if(stateCounter == 400) readExtensionType(); // Check if it has been activated - else if (stateCounter == 450) { + else if(stateCounter == 450) { onInit(); stateCounter = 0; unknownExtensionConnected = false; @@ -843,7 +843,7 @@ void WII::Run() { /************************************************************/ void WII::HID_Command(uint8_t* data, uint8_t nbytes) { - if (motionPlusInside) + if(motionPlusInside) pBtd->L2CAP_Command(hci_handle, data, nbytes, interrupt_scid[0], interrupt_scid[1]); // It's the new wiimote with the Motion Plus Inside else pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); @@ -878,6 +878,7 @@ void WII::setLedRaw(uint8_t value) { HIDBuffer[2] = value | (HIDBuffer[2] & 0x01); // Keep the rumble bit HID_Command(HIDBuffer, 3); } + void WII::setLedOff(LED a) { HIDBuffer[1] = 0x11; HIDBuffer[2] &= ~(pgm_read_byte(&LEDS[(uint8_t)a])); @@ -899,11 +900,11 @@ void WII::setLedToggle(LED a) { void WII::setLedStatus() { HIDBuffer[1] = 0x11; HIDBuffer[2] = (HIDBuffer[2] & 0x01); // Keep the rumble bit - if (wiimoteConnected) + if(wiimoteConnected) HIDBuffer[2] |= 0x10; // If it's connected LED1 will light up - if (motionPlusConnected) + if(motionPlusConnected) HIDBuffer[2] |= 0x20; // If it's connected LED2 will light up - if (nunchuckConnected) + if(nunchuckConnected) HIDBuffer[2] |= 0x40; // If it's connected LED3 will light up HID_Command(HIDBuffer, 3); @@ -919,7 +920,7 @@ void WII::setReportMode(bool continuous, uint8_t mode) { uint8_t cmd_buf[4]; cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02) cmd_buf[1] = 0x12; - if (continuous) + if(continuous) cmd_buf[2] = 0x04 | (HIDBuffer[2] & 0x01); // Keep the rumble bit else cmd_buf[2] = 0x00 | (HIDBuffer[2] & 0x01); // Keep the rumble bit @@ -949,9 +950,9 @@ void WII::writeData(uint32_t offset, uint8_t size, uint8_t* data) { cmd_buf[5] = (uint8_t)(offset & 0xFF); cmd_buf[6] = size; uint8_t i = 0; - for (; i < size; i++) + for(; i < size; i++) cmd_buf[7 + i] = data[i]; - for (; i < 16; i++) // Set the rest to zero + for(; i < 16; i++) // Set the rest to zero cmd_buf[7 + i] = 0x00; HID_Command(cmd_buf, 23); } @@ -976,17 +977,17 @@ void WII::initMotionPlus() { void WII::activateMotionPlus() { uint8_t buf[1]; - if (pBtd->wiiUProController) { + if(pBtd->wiiUProController) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nActivating Wii U Pro Controller"), 0x80); #endif buf[0] = 0x00; // It seems like you can send anything but 0x04, 0x05, and 0x07 - } else if (activateNunchuck) { + } else if(activateNunchuck) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nActivating Motion Plus in pass-through mode"), 0x80); #endif buf[0] = 0x05; // Activate nunchuck pass-through mode - } //else if(classicControllerConnected && extensionConnected) + }//else if(classicControllerConnected && extensionConnected) //buf[0] = 0x07; else { #ifdef DEBUG_USB_HOST @@ -1001,7 +1002,7 @@ void WII::readData(uint32_t offset, uint16_t size, bool EEPROM) { uint8_t cmd_buf[8]; cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02) cmd_buf[1] = 0x17; // Read data - if (EEPROM) + if(EEPROM) cmd_buf[2] = 0x00 | (HIDBuffer[2] & 0x01); // Read from EEPROM else cmd_buf[2] = 0x04 | (HIDBuffer[2] & 0x01); // Read from memory @@ -1032,7 +1033,7 @@ void WII::checkMotionPresent() { /************************************************************/ bool WII::getButtonPress(Button b) { // Return true when a button is pressed - if (wiiUProControllerConnected) + if(wiiUProControllerConnected) return (ButtonState & pgm_read_dword(&PROCONTROLLERBUTTONS[(uint8_t)b])); else return (ButtonState & pgm_read_dword(&BUTTONS[(uint8_t)b])); @@ -1040,7 +1041,7 @@ bool WII::getButtonPress(Button b) { // Return true when a button is pressed bool WII::getButtonClick(Button b) { // Only return true when a button is clicked uint32_t button; - if (wiiUProControllerConnected) + if(wiiUProControllerConnected) button = pgm_read_dword(&PROCONTROLLERBUTTONS[(uint8_t)b]); else button = pgm_read_dword(&BUTTONS[(uint8_t)b]); @@ -1050,11 +1051,11 @@ bool WII::getButtonClick(Button b) { // Only return true when a button is clicke } uint8_t WII::getAnalogHat(Hat a) { - if (!nunchuckConnected) + if(!nunchuckConnected) return 127; // Return center position else { uint8_t output = hatValues[(uint8_t)a]; - if (output == 0xFF || output == 0x00) // The joystick will only read 255 or 0 when the cable is unplugged or initializing, so we will just return the center position + if(output == 0xFF || output == 0x00) // The joystick will only read 255 or 0 when the cable is unplugged or initializing, so we will just return the center position return 127; else return output; @@ -1062,11 +1063,11 @@ uint8_t WII::getAnalogHat(Hat a) { } uint16_t WII::getAnalogHat(AnalogHat a) { - if (!wiiUProControllerConnected) + if(!wiiUProControllerConnected) return 2000; else { uint16_t output = hatValues[(uint8_t)a]; - if (output == 0x00) // The joystick will only read 0 when it is first initializing, so we will just return the center position + if(output == 0x00) // The joystick will only read 0 when it is first initializing, so we will just return the center position return 2000; else return output; @@ -1074,7 +1075,7 @@ uint16_t WII::getAnalogHat(AnalogHat a) { } void WII::onInit() { - if (pFuncOnInit) + if(pFuncOnInit) pFuncOnInit(); // Call the user function else setLedStatus(); diff --git a/Wii.h b/Wii.h index 8b46c2b2..ead789c9 100755 --- a/Wii.h +++ b/Wii.h @@ -85,6 +85,7 @@ public: /**@}*/ /** @name Wii Controller functions */ + /** Call this to start the paring sequence with a controller */ void pair(void) { if(pBtd) @@ -108,7 +109,7 @@ public: * @return Pitch in the range from 0-360. */ double getPitch() { - if (motionPlusConnected) + if(motionPlusConnected) return compPitch; return getWiimotePitch(); }; @@ -118,7 +119,7 @@ public: * @return Roll in the range from 0-360. */ double getRoll() { - if (motionPlusConnected) + if(motionPlusConnected) return compRoll; return getWiimoteRoll(); }; @@ -147,6 +148,7 @@ public: * @param value See: ::LED enum. */ void setLedRaw(uint8_t value); + /** Turn all LEDs off. */ void setLedOff() { setLedRaw(0); @@ -180,6 +182,7 @@ public: * @return The battery level in the range 0-255. */ uint8_t getBatteryLevel(); + /** * Return the Wiimote state. * @return See: http://wiibrew.org/wiki/Wiimote#0x20:_Status. @@ -211,20 +214,24 @@ public: /* IMU Data, might be usefull if you need to do something more advanced than just calculating the angle */ /**@{*/ + /** Pitch and roll calculated from the accelerometer inside the Wiimote. */ double getWiimotePitch() { return (atan2(accYwiimote, accZwiimote) + PI) * RAD_TO_DEG; }; + double getWiimoteRoll() { return (atan2(accXwiimote, accZwiimote) + PI) * RAD_TO_DEG; }; /**@}*/ /**@{*/ + /** Pitch and roll calculated from the accelerometer inside the Nunchuck. */ double getNunchuckPitch() { return (atan2(accYnunchuck, accZnunchuck) + PI) * RAD_TO_DEG; }; + double getNunchuckRoll() { return (atan2(accXnunchuck, accZnunchuck) + PI) * RAD_TO_DEG; }; @@ -381,7 +388,7 @@ public: * @return True if it's enabled, false if not. */ bool isIRCameraEnabled() { - return(wiiState & 0x08); + return (wiiState & 0x08); }; /**@}*/ #endif @@ -479,4 +486,4 @@ private: uint8_t IR_object_s4; #endif }; -#endif \ No newline at end of file +#endif diff --git a/XBOXOLD.cpp b/XBOXOLD.cpp index d615f83f..7bde6133 100644 --- a/XBOXOLD.cpp +++ b/XBOXOLD.cpp @@ -48,14 +48,14 @@ XBOXOLD::XBOXOLD(USB *p) : pUsb(p), // pointer to USB class instance - mandatory bAddress(0), // device address - mandatory bPollEnable(false) { // don't start polling before dongle is connected - for (uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; } - if (pUsb) // register in USB subsystem + if(pUsb) // register in USB subsystem pUsb->RegisterDeviceClass(this); //set devConfig[] entry } @@ -74,7 +74,7 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nXBOXUSB Init"), 0x80); #endif // check if address has already been assigned to an instance - if (bAddress) { + if(bAddress) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress in use"), 0x80); #endif @@ -84,14 +84,14 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } - if (!p->epinfo) { + if(!p->epinfo) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nepinfo is null"), 0x80); #endif @@ -111,19 +111,19 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) + if(rcode) goto FailGetDevDescr; VID = udd->idVendor; PID = udd->idProduct; - if ((VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_OLD_PID1 && PID != XBOX_OLD_PID2 && PID != XBOX_OLD_PID3 && PID != XBOX_OLD_PID4)) // Check if VID and PID match + if((VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_OLD_PID1 && PID != XBOX_OLD_PID2 && PID != XBOX_OLD_PID3 && PID != XBOX_OLD_PID4)) // Check if VID and PID match goto FailUnknownDevice; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from device descriptor @@ -131,7 +131,7 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -151,14 +151,14 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { //get pointer to assigned address record p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; // Assign epInfo to epinfo pointer - only EP0 is known rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; /* The application will work in reduced host mode, so we can save program and data @@ -180,19 +180,19 @@ uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; delay(200); // Give time for address change rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1); - if (rcode) + if(rcode) goto FailSetConfDescr; #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nXbox Controller Connected\r\n"), 0x80); #endif - if (pFuncOnInit) + if(pFuncOnInit) pFuncOnInit(); // Call the user function XboxConnected = true; bPollEnable = true; @@ -242,7 +242,7 @@ uint8_t XBOXOLD::Release() { } uint8_t XBOXOLD::Poll() { - if (!bPollEnable) + if(!bPollEnable) return 0; uint16_t BUFFER_SIZE = EP_MAXPKTSIZE; pUsb->inTransfer(bAddress, epInfo[ XBOX_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1 @@ -256,8 +256,8 @@ uint8_t XBOXOLD::Poll() { void XBOXOLD::readReport() { ButtonState = readBuf[2]; - for (uint8_t i = 0; i < sizeof(buttonValues); i++) - buttonValues[i] = readBuf[i + 4]; // A, B, X, Y, BLACK, WHITE, L1, and R1 + for(uint8_t i = 0; i < sizeof (buttonValues); i++) + buttonValues[i] = readBuf[i + 4]; // A, B, X, Y, BLACK, WHITE, L1, and R1 hatValue[LeftHatX] = (int16_t)(((uint16_t)readBuf[12] << 8) | readBuf[13]); hatValue[LeftHatY] = (int16_t)(((uint16_t)readBuf[14] << 8) | readBuf[15]); @@ -267,23 +267,23 @@ void XBOXOLD::readReport() { //Notify(PSTR("\r\nButtonState"), 0x80); //PrintHex(ButtonState, 0x80); - if (ButtonState != OldButtonState || memcmp(buttonValues, oldButtonValues, sizeof(buttonValues)) != 0) { + if(ButtonState != OldButtonState || memcmp(buttonValues, oldButtonValues, sizeof (buttonValues)) != 0) { ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable OldButtonState = ButtonState; - for (uint8_t i = 0; i < sizeof(buttonValues); i++) { - if (oldButtonValues[i] == 0 && buttonValues[i] != 0) - buttonClicked[i] = true; // Update A, B, X, Y, BLACK, WHITE, L1, and R1 click state - oldButtonValues[i] = buttonValues[i]; + for(uint8_t i = 0; i < sizeof (buttonValues); i++) { + if(oldButtonValues[i] == 0 && buttonValues[i] != 0) + buttonClicked[i] = true; // Update A, B, X, Y, BLACK, WHITE, L1, and R1 click state + oldButtonValues[i] = buttonValues[i]; } } } void XBOXOLD::printReport(uint16_t length) { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox controller #ifdef PRINTREPORT - if (readBuf == NULL) + if(readBuf == NULL) return; - for (uint8_t i = 0; i < length; i++) { + for(uint8_t i = 0; i < length; i++) { D_PrintHex (readBuf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -293,19 +293,19 @@ void XBOXOLD::printReport(uint16_t length) { //Uncomment "#define PRINTREPORT" t uint8_t XBOXOLD::getButtonPress(Button b) { uint8_t button = pgm_read_byte(&XBOXOLDBUTTONS[(uint8_t)b]); - if (b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons - return buttonValues[button]; // Analog buttons + if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons + return buttonValues[button]; // Analog buttons return (ButtonState & button); // Digital buttons } bool XBOXOLD::getButtonClick(Button b) { uint8_t button = pgm_read_byte(&XBOXOLDBUTTONS[(uint8_t)b]); - if (b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) { // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons - if (buttonClicked[button]) { - buttonClicked[button] = false; - return true; - } - return false; + if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) { // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons + if(buttonClicked[button]) { + buttonClicked[button] = false; + return true; + } + return false; } bool click = (ButtonClickState & button); @@ -334,4 +334,4 @@ void XBOXOLD::setRumbleOn(uint8_t lValue, uint8_t rValue) { writeBuf[5] = lValue; // big weight XboxCommand(writeBuf, 6); -} \ No newline at end of file +} diff --git a/XBOXOLD.h b/XBOXOLD.h index 02eadbbc..8b3fcce0 100644 --- a/XBOXOLD.h +++ b/XBOXOLD.h @@ -189,4 +189,4 @@ private: /* Private commands */ void XboxCommand(uint8_t* data, uint16_t nbytes); }; -#endif \ No newline at end of file +#endif diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index ec6c4546..2db24c72 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -26,14 +26,14 @@ XBOXRECV::XBOXRECV(USB *p) : pUsb(p), // pointer to USB class instance - mandatory bAddress(0), // device address - mandatory bPollEnable(false) { // don't start polling before dongle is connected - for (uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; } - if (pUsb) // register in USB subsystem + if(pUsb) // register in USB subsystem pUsb->RegisterDeviceClass(this); //set devConfig[] entry } @@ -51,7 +51,7 @@ uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nXBOXRECV Init"), 0x80); #endif - if (bAddress) { // Check if address has already been assigned to an instance + if(bAddress) { // Check if address has already been assigned to an instance #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress in use"), 0x80); #endif @@ -60,14 +60,14 @@ uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } - if (!p->epinfo) { + if(!p->epinfo) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nepinfo is null"), 0x80); #endif @@ -82,13 +82,13 @@ uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { p->epinfo = oldep_ptr; // Restore p->epinfo - if (rcode) + if(rcode) goto FailGetDevDescr; VID = udd->idVendor; PID = udd->idProduct; - if ((VID != XBOX_VID && VID != MADCATZ_VID) || (PID != XBOX_WIRELESS_RECEIVER_PID && PID != XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID)) { // Check if it's a Xbox receiver using the Vendor ID and Product ID + if((VID != XBOX_VID && VID != MADCATZ_VID) || (PID != XBOX_WIRELESS_RECEIVER_PID && PID != XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID)) { // Check if it's a Xbox receiver using the Vendor ID and Product ID #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nYou'll need a wireless receiver for this libary to work"), 0x80); #endif @@ -97,7 +97,7 @@ uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class - if (!bAddress) { + if(!bAddress) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nOut of address space"), 0x80); #endif @@ -115,13 +115,13 @@ FailGetDevDescr: #ifdef DEBUG_USB_HOST NotifyFailGetDevDescr(rcode); #endif - if (rcode != hrJERR) + if(rcode != hrJERR) rcode = USB_ERROR_FailGetDevDescr; goto Fail; FailUnknownDevice: #ifdef DEBUG_USB_HOST - NotifyFailUnknownDevice(VID,PID); + NotifyFailUnknownDevice(VID, PID); #endif rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; @@ -143,7 +143,7 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { #endif UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif @@ -153,7 +153,7 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { delay(300); // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device - if (rcode) { + if(rcode) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nsetAddr: "), 0x80); D_PrintHex (rcode, 0x80); @@ -169,7 +169,7 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = false; p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif @@ -179,7 +179,7 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { p->lowspeed = lowspeed; rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known - if (rcode) + if(rcode) goto FailSetDevTblEntry; /* The application will work in reduced host mode, so we can save program and data @@ -240,13 +240,13 @@ uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ XBOX_OUTPUT_PIPE_4 ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 9, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; delay(200); //Give time for address change rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1); - if (rcode) + if(rcode) goto FailSetConfDescr; #ifdef DEBUG_USB_HOST @@ -281,7 +281,7 @@ Fail: /* Performs a cleanup after failed Init() attempt */ uint8_t XBOXRECV::Release() { XboxReceiverConnected = false; - for (uint8_t i = 0; i < 4; i++) + for(uint8_t i = 0; i < 4; i++) Xbox360Connected[i] = 0x00; pUsb->GetAddressPool().FreeAddress(bAddress); bAddress = 0; @@ -290,28 +290,28 @@ uint8_t XBOXRECV::Release() { } uint8_t XBOXRECV::Poll() { - if (!bPollEnable) + if(!bPollEnable) return 0; - if (!checkStatusTimer || ((millis() - checkStatusTimer) > 3000)) { // Run checkStatus every 3 seconds + if(!checkStatusTimer || ((millis() - checkStatusTimer) > 3000)) { // Run checkStatus every 3 seconds checkStatusTimer = millis(); checkStatus(); } uint8_t inputPipe; uint16_t bufferSize; - for (uint8_t i = 0; i < 4; i++) { - if (i == 0) + for(uint8_t i = 0; i < 4; i++) { + if(i == 0) inputPipe = XBOX_INPUT_PIPE_1; - else if (i == 1) + else if(i == 1) inputPipe = XBOX_INPUT_PIPE_2; - else if (i == 2) + else if(i == 2) inputPipe = XBOX_INPUT_PIPE_3; else inputPipe = XBOX_INPUT_PIPE_4; bufferSize = EP_MAXPKTSIZE; // This is the maximum number of bytes we want to receive pUsb->inTransfer(bAddress, epInfo[ inputPipe ].epAddr, &bufferSize, readBuf); - if (bufferSize > 0) { // The number of received bytes + if(bufferSize > 0) { // The number of received bytes #ifdef EXTRADEBUG Notify(PSTR("Bytes Received: "), 0x80); D_PrintHex (bufferSize, 0x80); @@ -327,19 +327,19 @@ uint8_t XBOXRECV::Poll() { } void XBOXRECV::readReport(uint8_t controller) { - if (readBuf == NULL) + if(readBuf == NULL) return; // This report is send when a controller is connected and disconnected - if (readBuf[0] == 0x08 && readBuf[1] != Xbox360Connected[controller]) { + if(readBuf[0] == 0x08 && readBuf[1] != Xbox360Connected[controller]) { Xbox360Connected[controller] = readBuf[1]; #ifdef DEBUG_USB_HOST Notify(PSTR("Controller "), 0x80); Notify(controller, 0x80); #endif - if (Xbox360Connected[controller]) { + if(Xbox360Connected[controller]) { #ifdef DEBUG_USB_HOST const char* str = 0; - switch (readBuf[1]) { + switch(readBuf[1]) { case 0x80: str = PSTR(" as controller\r\n"); break; case 0x40: str = PSTR(" as headset\r\n"); @@ -359,15 +359,15 @@ void XBOXRECV::readReport(uint8_t controller) { return; } // Controller status report - if (readBuf[1] == 0x00 && readBuf[3] & 0x13 && readBuf[4] >= 0x22) { + if(readBuf[1] == 0x00 && readBuf[3] & 0x13 && readBuf[4] >= 0x22) { controllerStatus[controller] = ((uint16_t)readBuf[3] << 8) | readBuf[4]; return; } - if (readBuf[1] != 0x01) // Check if it's the correct report - the receiver also sends different status reports + if(readBuf[1] != 0x01) // Check if it's the correct report - the receiver also sends different status reports return; // A controller must be connected if it's sending data - if (!Xbox360Connected[controller]) + if(!Xbox360Connected[controller]) Xbox360Connected[controller] |= 0x80; ButtonState[controller] = (uint32_t)(readBuf[9] | ((uint16_t)readBuf[8] << 8) | ((uint32_t)readBuf[7] << 16) | ((uint32_t)readBuf[6] << 24)); @@ -380,12 +380,12 @@ void XBOXRECV::readReport(uint8_t controller) { //Notify(PSTR("\r\nButtonState: "), 0x80); //PrintHex(ButtonState[controller], 0x80); - if (ButtonState[controller] != OldButtonState[controller]) { + if(ButtonState[controller] != OldButtonState[controller]) { buttonStateChanged[controller] = true; ButtonClickState[controller] = (ButtonState[controller] >> 16) & ((~OldButtonState[controller]) >> 16); // Update click state variable, but don't include the two trigger buttons L2 and R2 - if (((uint8_t)OldButtonState[controller]) == 0 && ((uint8_t)ButtonState[controller]) != 0) // The L2 and R2 buttons are special as they are analog buttons + if(((uint8_t)OldButtonState[controller]) == 0 && ((uint8_t)ButtonState[controller]) != 0) // The L2 and R2 buttons are special as they are analog buttons R2Clicked[controller] = true; - if ((uint8_t)(OldButtonState[controller] >> 8) == 0 && (uint8_t)(ButtonState[controller] >> 8) != 0) + if((uint8_t)(OldButtonState[controller] >> 8) == 0 && (uint8_t)(ButtonState[controller] >> 8) != 0) L2Clicked[controller] = true; OldButtonState[controller] = ButtonState[controller]; } @@ -393,12 +393,12 @@ void XBOXRECV::readReport(uint8_t controller) { void XBOXRECV::printReport(uint8_t controller, uint8_t nBytes) { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller #ifdef PRINTREPORT - if (readBuf == NULL) + if(readBuf == NULL) return; Notify(PSTR("Controller "), 0x80); Notify(controller, 0x80); Notify(PSTR(": "), 0x80); - for (uint8_t i = 0; i < nBytes; i++) { + for(uint8_t i = 0; i < nBytes; i++) { D_PrintHex (readBuf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -407,22 +407,22 @@ void XBOXRECV::printReport(uint8_t controller, uint8_t nBytes) { //Uncomment "#d } uint8_t XBOXRECV::getButtonPress(Button b, uint8_t controller) { - if (b == L2) // These are analog buttons + if(b == L2) // These are analog buttons return (uint8_t)(ButtonState[controller] >> 8); - else if (b == R2) + else if(b == R2) return (uint8_t)ButtonState[controller]; return (bool)(ButtonState[controller] & ((uint32_t)pgm_read_word(&XBOXBUTTONS[(uint8_t)b]) << 16)); } bool XBOXRECV::getButtonClick(Button b, uint8_t controller) { - if (b == L2) { - if (L2Clicked[controller]) { + if(b == L2) { + if(L2Clicked[controller]) { L2Clicked[controller] = false; return true; } return false; - } else if (b == R2) { - if (R2Clicked[controller]) { + } else if(b == R2) { + if(R2Clicked[controller]) { R2Clicked[controller] = false; return true; } @@ -472,7 +472,7 @@ void XBOXRECV::XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes) { uint8_t rcode; #endif uint8_t outputPipe; - switch (controller) { + switch(controller) { case 0: outputPipe = XBOX_OUTPUT_PIPE_1; break; case 1: outputPipe = XBOX_OUTPUT_PIPE_2; @@ -489,7 +489,7 @@ void XBOXRECV::XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes) { #endif pUsb->outTransfer(bAddress, epInfo[ outputPipe ].epAddr, nbytes, data); #ifdef EXTRADEBUG - if (rcode) + if(rcode) Notify(PSTR("Error sending Xbox message\r\n"), 0x80); #endif } @@ -513,7 +513,7 @@ void XBOXRECV::setLedRaw(uint8_t value, uint8_t controller) { } void XBOXRECV::setLedOn(LED led, uint8_t controller) { - if (led != ALL) // All LEDs can't be on a the same time + if(led != ALL) // All LEDs can't be on a the same time setLedRaw(pgm_read_byte(&XBOXLEDS[(uint8_t)led]) + 4, controller); } @@ -530,14 +530,14 @@ Thanks to BusHound from Perisoft.net for the Windows USB Analysis output Found by timstamp.co.uk */ void XBOXRECV::checkStatus() { - if (!bPollEnable) + if(!bPollEnable) return; // Get controller info writeBuf[0] = 0x08; writeBuf[1] = 0x00; writeBuf[2] = 0x0f; writeBuf[3] = 0xc0; - for (uint8_t i = 0; i < 4; i++) { + for(uint8_t i = 0; i < 4; i++) { XboxCommand(i, writeBuf, 4); } // Get battery status @@ -545,8 +545,8 @@ void XBOXRECV::checkStatus() { writeBuf[1] = 0x00; writeBuf[2] = 0x00; writeBuf[3] = 0x40; - for (uint8_t i = 0; i < 4; i++) { - if (Xbox360Connected[i]) + for(uint8_t i = 0; i < 4; i++) { + if(Xbox360Connected[i]) XboxCommand(i, writeBuf, 4); } } @@ -564,18 +564,18 @@ void XBOXRECV::setRumbleOn(uint8_t lValue, uint8_t rValue, uint8_t controller) { } void XBOXRECV::onInit(uint8_t controller) { - if (pFuncOnInit) + if(pFuncOnInit) pFuncOnInit(); // Call the user function else { LED led; - if (controller == 0) - led = LED1; - else if (controller == 1) - led = LED2; - else if (controller == 2) - led = LED3; + if(controller == 0) + led = LED1; + else if(controller == 1) + led = LED2; + else if(controller == 2) + led = LED3; else - led = LED4; + led = LED4; setLedOn(led, controller); } } diff --git a/XBOXRECV.h b/XBOXRECV.h index eee75cda..25d7fe7f 100644 --- a/XBOXRECV.h +++ b/XBOXRECV.h @@ -277,4 +277,4 @@ private: void XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes); void checkStatus(); }; -#endif \ No newline at end of file +#endif diff --git a/XBOXUSB.cpp b/XBOXUSB.cpp index 111c5c3e..cfbb2b34 100644 --- a/XBOXUSB.cpp +++ b/XBOXUSB.cpp @@ -24,14 +24,14 @@ XBOXUSB::XBOXUSB(USB *p) : pUsb(p), // pointer to USB class instance - mandatory bAddress(0), // device address - mandatory bPollEnable(false) { // don't start polling before dongle is connected - for (uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; } - if (pUsb) // register in USB subsystem + if(pUsb) // register in USB subsystem pUsb->RegisterDeviceClass(this); //set devConfig[] entry } @@ -50,7 +50,7 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nXBOXUSB Init"), 0x80); #endif // check if address has already been assigned to an instance - if (bAddress) { + if(bAddress) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress in use"), 0x80); #endif @@ -60,14 +60,14 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) { + if(!p) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nAddress not found"), 0x80); #endif return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } - if (!p->epinfo) { + if(!p->epinfo) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nepinfo is null"), 0x80); #endif @@ -87,31 +87,31 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) + if(rcode) goto FailGetDevDescr; VID = udd->idVendor; PID = udd->idProduct; - if (VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID && VID != GAMESTOP_VID) // Check VID + if(VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID && VID != GAMESTOP_VID) // Check VID goto FailUnknownDevice; - if (PID == XBOX_WIRELESS_PID) { + if(PID == XBOX_WIRELESS_PID) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nYou have plugged in a wireless Xbox 360 controller - it doesn't support USB communication"), 0x80); #endif goto FailUnknownDevice; - } else if (PID == XBOX_WIRELESS_RECEIVER_PID || PID == XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID) { + } else if(PID == XBOX_WIRELESS_RECEIVER_PID || PID == XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nThis library only supports Xbox 360 controllers via USB"), 0x80); #endif goto FailUnknownDevice; - } else if (PID != XBOX_WIRED_PID && PID != GAMESTOP_WIRED_PID) // Check PID + } else if(PID != XBOX_WIRED_PID && PID != GAMESTOP_WIRED_PID) // Check PID goto FailUnknownDevice; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from device descriptor @@ -119,7 +119,7 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -139,14 +139,14 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { //get pointer to assigned address record p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; // Assign epInfo to epinfo pointer - only EP0 is known rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; /* The application will work in reduced host mode, so we can save program and data @@ -168,13 +168,13 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = 0; rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; delay(200); // Give time for address change rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1); - if (rcode) + if(rcode) goto FailSetConfDescr; #ifdef DEBUG_USB_HOST @@ -229,7 +229,7 @@ uint8_t XBOXUSB::Release() { } uint8_t XBOXUSB::Poll() { - if (!bPollEnable) + if(!bPollEnable) return 0; uint16_t BUFFER_SIZE = EP_MAXPKTSIZE; pUsb->inTransfer(bAddress, epInfo[ XBOX_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1 @@ -241,9 +241,9 @@ uint8_t XBOXUSB::Poll() { } void XBOXUSB::readReport() { - if (readBuf == NULL) + if(readBuf == NULL) return; - if (readBuf[0] != 0x00 || readBuf[1] != 0x14) { // Check if it's the correct report - the controller also sends different status reports + if(readBuf[0] != 0x00 || readBuf[1] != 0x14) { // Check if it's the correct report - the controller also sends different status reports return; } @@ -257,11 +257,11 @@ void XBOXUSB::readReport() { //Notify(PSTR("\r\nButtonState"), 0x80); //PrintHex(ButtonState, 0x80); - if (ButtonState != OldButtonState) { + if(ButtonState != OldButtonState) { ButtonClickState = (ButtonState >> 16) & ((~OldButtonState) >> 16); // Update click state variable, but don't include the two trigger buttons L2 and R2 - if (((uint8_t)OldButtonState) == 0 && ((uint8_t)ButtonState) != 0) // The L2 and R2 buttons are special as they are analog buttons + if(((uint8_t)OldButtonState) == 0 && ((uint8_t)ButtonState) != 0) // The L2 and R2 buttons are special as they are analog buttons R2Clicked = true; - if ((uint8_t)(OldButtonState >> 8) == 0 && (uint8_t)(ButtonState >> 8) != 0) + if((uint8_t)(OldButtonState >> 8) == 0 && (uint8_t)(ButtonState >> 8) != 0) L2Clicked = true; OldButtonState = ButtonState; } @@ -269,9 +269,9 @@ void XBOXUSB::readReport() { void XBOXUSB::printReport() { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller #ifdef PRINTREPORT - if (readBuf == NULL) + if(readBuf == NULL) return; - for (uint8_t i = 0; i < XBOX_REPORT_BUFFER_SIZE; i++) { + for(uint8_t i = 0; i < XBOX_REPORT_BUFFER_SIZE; i++) { D_PrintHex (readBuf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -280,22 +280,22 @@ void XBOXUSB::printReport() { //Uncomment "#define PRINTREPORT" to print the rep } uint8_t XBOXUSB::getButtonPress(Button b) { - if (b == L2) // These are analog buttons + if(b == L2) // These are analog buttons return (uint8_t)(ButtonState >> 8); - else if (b == R2) + else if(b == R2) return (uint8_t)ButtonState; return (bool)(ButtonState & ((uint32_t)pgm_read_word(&XBOXBUTTONS[(uint8_t)b]) << 16)); } bool XBOXUSB::getButtonClick(Button b) { - if (b == L2) { - if (L2Clicked) { + if(b == L2) { + if(L2Clicked) { L2Clicked = false; return true; } return false; - } else if (b == R2) { - if (R2Clicked) { + } else if(b == R2) { + if(R2Clicked) { R2Clicked = false; return true; } @@ -326,7 +326,7 @@ void XBOXUSB::setLedRaw(uint8_t value) { } void XBOXUSB::setLedOn(LED led) { - if (led != ALL) // All LEDs can't be on a the same time + if(led != ALL) // All LEDs can't be on a the same time setLedRaw((pgm_read_byte(&XBOXLEDS[(uint8_t)led])) + 4); } @@ -352,7 +352,7 @@ void XBOXUSB::setRumbleOn(uint8_t lValue, uint8_t rValue) { } void XBOXUSB::onInit() { - if (pFuncOnInit) + if(pFuncOnInit) pFuncOnInit(); // Call the user function else setLedOn(LED1); diff --git a/address.h b/address.h index d933f2e6..158e287d 100644 --- a/address.h +++ b/address.h @@ -111,6 +111,7 @@ class AddressPoolImpl : public AddressPool { }; // Returns thePool index for a given address + uint8_t FindAddressIndex(uint8_t address = 0) { for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) { if(thePool[i].address.devAddress == address) @@ -120,6 +121,7 @@ class AddressPoolImpl : public AddressPool { }; // Returns thePool child index for a given parent + uint8_t FindChildIndex(UsbDeviceAddress addr, uint8_t start = 1) { for(uint8_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) { if(thePool[i].address.bmParent == addr.bmAddress) @@ -129,6 +131,7 @@ class AddressPoolImpl : public AddressPool { }; // Frees address entry specified by index parameter + void FreeAddressByIndex(uint8_t index) { // Zero field is reserved and should not be affected if(index == 0) @@ -148,6 +151,7 @@ class AddressPoolImpl : public AddressPool { } // Initializes the whole address pool at once + void InitAllAddresses() { for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) InitEntry(i); @@ -172,16 +176,18 @@ public: }; // Returns a pointer to a specified address entry + virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) { if(!addr) return thePool; uint8_t index = FindAddressIndex(addr); - return(!index) ? NULL : thePool + index; + return (!index) ? NULL : thePool + index; }; // Performs an operation specified by pfunc for each addressed device + void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { if(!pfunc) return; @@ -192,13 +198,14 @@ public: }; // Allocates new address + virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) { /* if (parent != 0 && port == 0) USB_HOST_SERIAL.println("PRT:0"); */ UsbDeviceAddress _parent; _parent.devAddress = parent; if(_parent.bmReserved || port > 7) - //if(parent > 127 || port > 7) + //if(parent > 127 || port > 7) return 0; if(is_hub && hubCounter == 7) @@ -243,6 +250,7 @@ public: }; // Empties pool entry + virtual void FreeAddress(uint8_t addr) { // if the root hub is disconnected all the addresses should be initialized if(addr == 0x41) { diff --git a/adk.cpp b/adk.cpp index 2d655b74..1171da1c 100644 --- a/adk.cpp +++ b/adk.cpp @@ -13,7 +13,7 @@ Contact information Circuits At Home, LTD Web : http://www.circuitsathome.com e-mail : support@circuitsathome.com -*/ + */ /* Google ADK interface */ @@ -42,7 +42,7 @@ bConfNum(0), //configuration number bNumEP(1), //if config descriptor needs to be parsed ready(false) { // initialize endpoint data structures - for (uint8_t i = 0; i < ADK_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < ADK_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; @@ -50,7 +50,7 @@ ready(false) { }//for(uint8_t i=0; iRegisterDeviceClass(this); //set devConfig[] entry } } @@ -74,7 +74,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { USBTRACE("\r\nADK Init"); // check if address has already been assigned to an instance - if (bAddress) { + if(bAddress) { USBTRACE("\r\nAddress in use"); return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; } @@ -82,12 +82,12 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) { + if(!p) { USBTRACE("\r\nAddress not found"); return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } - if (!p->epinfo) { + if(!p->epinfo) { USBTRACE("epinfo is null\r\n"); return USB_ERROR_EPINFO_IS_NULL; } @@ -106,7 +106,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) { + if(rcode) { goto FailGetDevDescr; } @@ -118,7 +118,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -134,7 +134,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { //get pointer to assigned address record p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) { + if(!p) { return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } @@ -142,49 +142,49 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign epInfo to epinfo pointer - only EP0 is known rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) { + if(rcode) { goto FailSetDevTblEntry; } //check if ADK device is already in accessory mode; if yes, configure and exit - if (udd->idVendor == ADK_VID && + if(udd->idVendor == ADK_VID && (udd->idProduct == ADK_PID || udd->idProduct == ADB_PID)) { USBTRACE("\r\nAcc.mode device detected"); /* go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */ num_of_conf = udd->bNumConfigurations; //USBTRACE2("\r\nNC:",num_of_conf); - for (uint8_t i = 0; i < num_of_conf; i++) { + for(uint8_t i = 0; i < num_of_conf; i++) { ConfigDescParser < 0, 0, 0, 0 > confDescrParser(this); delay(1); rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); #if defined(XOOM) //added by Jaylen Scott Vanorden - if (rcode) { + if(rcode) { USBTRACE2("\r\nGot 1st bad code for config: ", rcode); // Try once more rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); } #endif - if (rcode) { + if(rcode) { goto FailGetConfDescr; } - if (bNumEP > 2) { + if(bNumEP > 2) { break; } } // for (uint8_t i=0; isetEpInfoEntry(bAddress, 3, epInfo); - if (rcode) { + if(rcode) { goto FailSetDevTblEntry; } } // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); - if (rcode) { + if(rcode) { goto FailSetConfDescr; } /* print endpoint structure */ @@ -202,7 +202,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { USBTRACE2("\r\nAddr: ", epInfo[epDataInIndex].epAddr); USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataInIndex].maxPktSize); USBTRACE2("\r\nAttr: ", epInfo[epDataInIndex].epAttribs); - */ + */ USBTRACE("\r\nConfiguration successful"); ready = true; @@ -216,13 +216,13 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { rcode = getProto((uint8_t*) & adkproto); #if defined(XOOM) //added by Jaylen Scott Vanorden - if (rcode) { + if(rcode) { USBTRACE2("\r\nGot 1st bad code for proto: ", rcode); // Try once more rcode = getProto((uint8_t*) & adkproto); } #endif - if (rcode) { + if(rcode) { goto FailGetProto; //init fails } USBTRACE2("\r\nADK protocol rev. ", adkproto); @@ -248,7 +248,7 @@ uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) { //switch to accessory mode //the Android phone will reset rcode = switchAcc(); - if (rcode) { + if(rcode) { goto FailSwAcc; //init fails } rcode = USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET; @@ -292,7 +292,7 @@ FailSwAcc: goto Fail; #endif -//FailOnInit: + //FailOnInit: // USBTRACE("OnInit:"); // goto Fail; // @@ -314,13 +314,13 @@ void ADK::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto //ErrorMessage(PSTR("Alt.Set"), alt); //added by Yuuichi Akagawa - if (bNumEP == 3) { + if(bNumEP == 3) { return; } bConfNum = conf; - if ((pep->bmAttributes & 0x02) == 2) { + if((pep->bmAttributes & 0x02) == 2) { uint8_t index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; // Fill in the endpoint info structure epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); diff --git a/adk.h b/adk.h index ab5ed38f..542078bb 100644 --- a/adk.h +++ b/adk.h @@ -13,7 +13,7 @@ Contact information Circuits At Home, LTD Web : http://www.circuitsathome.com e-mail : support@circuitsathome.com -*/ + */ /* Google ADK interface support header */ @@ -27,8 +27,8 @@ e-mail : support@circuitsathome.com #define ADB_PID 0x2D01 #define XOOM //enables repeating getProto() and getConf() attempts - //necessary for slow devices such as Motorola XOOM - //defined by default, can be commented out to save memory +//necessary for slow devices such as Motorola XOOM +//defined by default, can be commented out to save memory /* requests */ @@ -124,17 +124,17 @@ public: /* returns 2 bytes in *adkproto */ inline uint8_t ADK::getProto(uint8_t* adkproto) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_GET, ADK_GETPROTO, 0, 0, 0, 2, 2, adkproto, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_GET, ADK_GETPROTO, 0, 0, 0, 2, 2, adkproto, NULL)); } /* send ADK string */ inline uint8_t ADK::sendStr(uint8_t index, const char* str) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_SENDSTR, 0, 0, index, strlen(str) + 1, strlen(str) + 1, (uint8_t*) str, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_SENDSTR, 0, 0, index, strlen(str) + 1, strlen(str) + 1, (uint8_t*)str, NULL)); } /* switch to accessory mode */ inline uint8_t ADK::switchAcc(void) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_ACCSTART, 0, 0, 0, 0, 0, NULL, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_ACCSTART, 0, 0, 0, 0, 0, NULL, NULL)); } #endif // _ADK_H_ diff --git a/avrpins.h b/avrpins.h index 5a7e1756..ca83a8a9 100644 --- a/avrpins.h +++ b/avrpins.h @@ -218,7 +218,7 @@ public: } static uint8_t IsSet() { - return PORT::PinRead() & (uint8_t) (1 << PIN); + return PORT::PinRead() & (uint8_t)(1 << PIN); } static void WaiteForSet() { diff --git a/cdcacm.cpp b/cdcacm.cpp index 948b58c8..3d50f600 100644 --- a/cdcacm.cpp +++ b/cdcacm.cpp @@ -30,7 +30,7 @@ bNumEP(1), qNextPollTime(0), bPollEnable(false), ready(false) { - for (uint8_t i = 0; i < ACM_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < ACM_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; @@ -40,7 +40,7 @@ ready(false) { //if (!i) epInfo[i].bmNakPower = USB_NAK_MAX_POWER; } - if (pUsb) + if(pUsb) pUsb->RegisterDeviceClass(this); } @@ -59,16 +59,16 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { USBTRACE("ACM Init\r\n"); - if (bAddress) + if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - if (!p->epinfo) { + if(!p->epinfo) { USBTRACE("epinfo\r\n"); return USB_ERROR_EPINFO_IS_NULL; } @@ -87,13 +87,13 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) + if(rcode) goto FailGetDevDescr; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor @@ -102,7 +102,7 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -116,7 +116,7 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; @@ -126,12 +126,12 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; USBTRACE2("NC:", num_of_conf); - for (uint8_t i = 0; i < num_of_conf; i++) { + for(uint8_t i = 0; i < num_of_conf; i++) { ConfigDescParser< USB_CLASS_COM_AND_CDC_CTRL, CDC_SUBCLASS_ACM, CDC_PROTOCOL_ITU_T_V_250, @@ -144,19 +144,19 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcControlParser); - if (rcode) + if(rcode) goto FailGetConfDescr; rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcDataParser); - if (rcode) + if(rcode) goto FailGetConfDescr; - if (bNumEP > 1) + if(bNumEP > 1) break; } // for - if (bNumEP < 4) + if(bNumEP < 4) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Assign epInfo to epinfo pointer @@ -167,12 +167,12 @@ uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); - if (rcode) + if(rcode) goto FailSetConfDescr; rcode = pAsync->OnInit(this); - if (rcode) + if(rcode) goto FailOnInit; USBTRACE("ACM configured\r\n"); @@ -230,10 +230,10 @@ void ACM::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto uint8_t index; - if ((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) + if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) index = epInterruptInIndex; else - if ((pep->bmAttributes & 0x02) == 2) + if((pep->bmAttributes & 0x02) == 2) index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; else return; @@ -264,7 +264,7 @@ uint8_t ACM::Release() { uint8_t ACM::Poll() { uint8_t rcode = 0; - if (!bPollEnable) + if(!bPollEnable) return 0; //uint32_t time_now = millis(); diff --git a/cdcacm.h b/cdcacm.h index b94c2360..4a2a1362 100644 --- a/cdcacm.h +++ b/cdcacm.h @@ -114,14 +114,13 @@ typedef struct { uint8_t bDataBits; // Data bits (5, 6, 7, 8 or 16) } LINE_CODING; -typedef struct -{ - uint8_t bmRequestType; // 0xa1 for class-specific notifications - uint8_t bNotification; - uint16_t wValue; - uint16_t wIndex; - uint16_t wLength; - uint16_t bmState; //UART state bitmap for SERIAL_STATE, other notifications variable length +typedef struct { + uint8_t bmRequestType; // 0xa1 for class-specific notifications + uint8_t bNotification; + uint16_t wValue; + uint16_t wIndex; + uint16_t wLength; + uint16_t bmState; //UART state bitmap for SERIAL_STATE, other notifications variable length } CLASS_NOTIFICATION; class ACM; @@ -151,7 +150,7 @@ protected: uint8_t bNumEP; // total number of EP in the configuration uint32_t qNextPollTime; // next poll time bool bPollEnable; // poll enable flag - bool ready; //device ready indicator + bool ready; //device ready indicator EpInfo epInfo[ACM_MAX_ENDPOINTS]; @@ -167,7 +166,7 @@ public: uint8_t GetLineCoding(LINE_CODING *dataptr); uint8_t SetControlLineState(uint8_t state); uint8_t SendBreak(uint16_t duration); - uint8_t GetNotif( uint16_t *bytes_rcvd, uint8_t *dataptr ); + uint8_t GetNotif(uint16_t *bytes_rcvd, uint8_t *dataptr); // Methods for recieving and sending data uint8_t RcvData(uint16_t *nbytesptr, uint8_t *dataptr); @@ -182,9 +181,9 @@ public: return bAddress; }; - virtual bool isReady() { - return ready; - }; + virtual bool isReady() { + return ready; + }; // UsbConfigXtracter implementation virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); diff --git a/cdcftdi.cpp b/cdcftdi.cpp index 40c5776f..13ca683f 100644 --- a/cdcftdi.cpp +++ b/cdcftdi.cpp @@ -26,7 +26,7 @@ pUsb(p), bAddress(0), bNumEP(1), wFTDIType(0) { - for (uint8_t i = 0; i < FTDI_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < FTDI_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; @@ -34,7 +34,7 @@ wFTDIType(0) { //if (!i) epInfo[i].bmNakPower = USB_NAK_MAX_POWER; } - if (pUsb) + if(pUsb) pUsb->RegisterDeviceClass(this); } @@ -56,16 +56,16 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { USBTRACE("FTDI Init\r\n"); - if (bAddress) + if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - if (!p->epinfo) { + if(!p->epinfo) { USBTRACE("epinfo\r\n"); return USB_ERROR_EPINFO_IS_NULL; } @@ -84,9 +84,9 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) + if(rcode) goto FailGetDevDescr; - if (udd->idVendor != FTDI_VID || udd->idProduct != FTDI_PID) + if(udd->idVendor != FTDI_VID || udd->idProduct != FTDI_PID) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Save type of FTDI chip @@ -95,7 +95,7 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor @@ -104,7 +104,7 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -118,7 +118,7 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; @@ -128,30 +128,30 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; USBTRACE2("NC:", num_of_conf); - for (uint8_t i = 0; i < num_of_conf; i++) { + for(uint8_t i = 0; i < num_of_conf; i++) { HexDumper HexDump; ConfigDescParser < 0xFF, 0xFF, 0xFF, CP_MASK_COMPARE_ALL> confDescrParser(this); rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump); - if (rcode) + if(rcode) goto FailGetConfDescr; rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - if (rcode) + if(rcode) goto FailGetConfDescr; - if (bNumEP > 1) + if(bNumEP > 1) break; } // for - if (bNumEP < 2) + if(bNumEP < 2) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; USBTRACE2("NumEP:", bNumEP); @@ -164,12 +164,12 @@ uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); - if (rcode) + if(rcode) goto FailSetConfDescr; rcode = pAsync->OnInit(this); - if (rcode) + if(rcode) goto FailOnInit; USBTRACE("FTDI configured\r\n"); @@ -221,10 +221,10 @@ void FTDI::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t prot uint8_t index; - if ((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) + if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) index = epInterruptInIndex; else - if ((pep->bmAttributes & 0x02) == 2) + if((pep->bmAttributes & 0x02) == 2) index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; else return; @@ -270,19 +270,19 @@ uint8_t FTDI::SetBaudRate(uint32_t baud) { divisor3 = 48000000 / 2 / baud; // divisor shifted 3 bits to the left - if (wFTDIType == FT232AM) { - if ((divisor3 & 0x7) == 7) + if(wFTDIType == FT232AM) { + if((divisor3 & 0x7) == 7) divisor3++; // round x.7/8 up to x+1 baud_value = divisor3 >> 3; divisor3 &= 0x7; - if (divisor3 == 1) baud_value |= 0xc000; + if(divisor3 == 1) baud_value |= 0xc000; else // 0.125 - if (divisor3 >= 4) baud_value |= 0x4000; + if(divisor3 >= 4) baud_value |= 0x4000; else // 0.5 - if (divisor3 != 0) baud_value |= 0x8000; // 0.25 - if (baud_value == 1) baud_value = 0; /* special case for maximum baud rate */ + if(divisor3 != 0) baud_value |= 0x8000; // 0.25 + if(baud_value == 1) baud_value = 0; /* special case for maximum baud rate */ } else { static const unsigned char divfrac [8] = {0, 3, 2, 0, 1, 1, 2, 3}; static const unsigned char divindex[8] = {0, 0, 0, 1, 0, 1, 1, 1}; @@ -292,9 +292,9 @@ uint8_t FTDI::SetBaudRate(uint32_t baud) { baud_index = divindex[divisor3 & 0x7]; /* Deal with special cases for highest baud rates. */ - if (baud_value == 1) baud_value = 0; + if(baud_value == 1) baud_value = 0; else // 1.0 - if (baud_value == 0x4001) baud_value = 1; // 1.5 + if(baud_value == 0x4001) baud_value = 1; // 1.5 } USBTRACE2("baud_value:", baud_value); USBTRACE2("baud_index:", baud_index); diff --git a/cdcftdi.h b/cdcftdi.h index e576e246..866e2d7d 100644 --- a/cdcftdi.h +++ b/cdcftdi.h @@ -130,4 +130,4 @@ public: virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); }; -#endif // __CDCFTDI_H__ \ No newline at end of file +#endif // __CDCFTDI_H__ diff --git a/cdcprolific.cpp b/cdcprolific.cpp index 9992e4fe..d629ad55 100644 --- a/cdcprolific.cpp +++ b/cdcprolific.cpp @@ -35,16 +35,16 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { USBTRACE("PL Init\r\n"); - if (bAddress) + if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - if (!p->epinfo) { + if(!p->epinfo) { USBTRACE("epinfo\r\n"); return USB_ERROR_EPINFO_IS_NULL; } @@ -63,10 +63,10 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) + if(rcode) goto FailGetDevDescr; - if (udd->idVendor != PL_VID && udd->idProduct != PL_PID) + if(udd->idVendor != PL_VID && udd->idProduct != PL_PID) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Save type of PL chip @@ -75,7 +75,7 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor @@ -84,7 +84,7 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -98,7 +98,7 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; @@ -108,30 +108,30 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; USBTRACE2("NC:", num_of_conf); - for (uint8_t i = 0; i < num_of_conf; i++) { + for(uint8_t i = 0; i < num_of_conf; i++) { HexDumper HexDump; ConfigDescParser < 0xFF, 0, 0, CP_MASK_COMPARE_CLASS> confDescrParser(this); rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump); - if (rcode) + if(rcode) goto FailGetConfDescr; rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - if (rcode) + if(rcode) goto FailGetConfDescr; - if (bNumEP > 1) + if(bNumEP > 1) break; } // for - if (bNumEP < 2) + if(bNumEP < 2) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Assign epInfo to epinfo pointer @@ -142,12 +142,12 @@ uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); - if (rcode) + if(rcode) goto FailSetConfDescr; rcode = pAsync->OnInit(this); - if (rcode) + if(rcode) goto FailOnInit; USBTRACE("PL configured\r\n"); @@ -208,5 +208,3 @@ Fail: // //} // return rcode; //} - - diff --git a/confdescparser.h b/confdescparser.h index 186de7be..f16d6fce 100644 --- a/confdescparser.h +++ b/confdescparser.h @@ -58,7 +58,10 @@ class ConfigDescParser : public USBReadParser { void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc); public: - void SetOR(void) { UseOr = true; } + + void SetOR(void) { + UseOr = true; + } ConfigDescParser(UsbConfigXtracter *xtractor); virtual void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset); }; @@ -75,11 +78,10 @@ UseOr(false) { theSkipper.Initialize(&theBuffer); }; - template void ConfigDescParser::Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset) { - uint16_t cntdn = (uint16_t) len; - uint8_t *p = (uint8_t*) pbuf; + uint16_t cntdn = (uint16_t)len; + uint8_t *p = (uint8_t*)pbuf; while(cntdn) if(!ParseDescriptor(&p, &cntdn)) @@ -90,8 +92,8 @@ void ConfigDescParser::Parse(const uin compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */ template bool ConfigDescParser::ParseDescriptor(uint8_t **pp, uint16_t *pcntdn) { - USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast (varBuffer); - USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast (varBuffer); + USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast(varBuffer); + USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast(varBuffer); switch(stateParseDescr) { case 0: theBuffer.valueSize = 2; @@ -100,8 +102,8 @@ bool ConfigDescParser::ParseDescriptor case 1: if(!valParser.Parse(pp, pcntdn)) return false; - dscrLen = *((uint8_t*) theBuffer.pValue); - dscrType = *((uint8_t*) theBuffer.pValue + 1); + dscrLen = *((uint8_t*)theBuffer.pValue); + dscrType = *((uint8_t*)theBuffer.pValue + 1); stateParseDescr = 2; case 2: // This is a sort of hack. Assuming that two bytes are all ready in the buffer @@ -116,10 +118,10 @@ bool ConfigDescParser::ParseDescriptor case USB_DESCRIPTOR_INTERFACE: isGoodInterface = false; case USB_DESCRIPTOR_CONFIGURATION: - theBuffer.valueSize = sizeof(USB_CONFIGURATION_DESCRIPTOR) - 2; + theBuffer.valueSize = sizeof (USB_CONFIGURATION_DESCRIPTOR) - 2; break; case USB_DESCRIPTOR_ENDPOINT: - theBuffer.valueSize = sizeof(USB_ENDPOINT_DESCRIPTOR) - 2; + theBuffer.valueSize = sizeof (USB_ENDPOINT_DESCRIPTOR) - 2; break; case HID_DESCRIPTOR_HID: theBuffer.valueSize = dscrLen - 2; @@ -158,7 +160,7 @@ bool ConfigDescParser::ParseDescriptor return false; if(isGoodInterface) if(theXtractor) - theXtractor->EndpointXtract(confValue, ifaceNumber, ifaceAltSet, protoValue, (USB_ENDPOINT_DESCRIPTOR*) varBuffer); + theXtractor->EndpointXtract(confValue, ifaceNumber, ifaceAltSet, protoValue, (USB_ENDPOINT_DESCRIPTOR*)varBuffer); break; //case HID_DESCRIPTOR_HID: // if (!valParser.Parse(pp, pcntdn)) diff --git a/controllerEnums.h b/controllerEnums.h index 5e0d6dc8..edb42987 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -117,4 +117,4 @@ enum AnalogHat { RightHatY = 3, }; -#endif \ No newline at end of file +#endif diff --git a/hexdump.h b/hexdump.h index 5d6f8e11..3818d850 100644 --- a/hexdump.h +++ b/hexdump.h @@ -41,7 +41,7 @@ public: template void HexDumper::Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) { - if(UsbDEBUGlvl >= 0x80) { // Fully bypass this block of code if we do not debug. + if(UsbDEBUGlvl >= 0x80) { // Fully bypass this block of code if we do not debug. for(LEN_TYPE j = 0; j < len; j++, byteCount++, byteTotal++) { if(!byteCount) { PrintHex (byteTotal, 0x80); diff --git a/hid.cpp b/hid.cpp index 02c89720..c86f6b91 100644 --- a/hid.cpp +++ b/hid.cpp @@ -1,6 +1,7 @@ #include "hid.h" //get HID report descriptor + /* WRONG! Endpoint is _ALWAYS_ ZERO for HID! We want the _INTERFACE_ value here! uint8_t HID::GetReportDescr(uint8_t ep, USBReadParser *parser) { const uint8_t constBufLen = 64; @@ -12,7 +13,7 @@ uint8_t HID::GetReportDescr(uint8_t ep, USBReadParser *parser) { //return ((rcode != hrSTALL) ? rcode : 0); return rcode; } -*/ + */ uint8_t HID::GetReportDescr(uint16_t wIndex, USBReadParser *parser) { const uint8_t constBufLen = 64; uint8_t buf[constBufLen]; diff --git a/hid.h b/hid.h index 2037cc15..a61cfb90 100644 --- a/hid.h +++ b/hid.h @@ -140,7 +140,6 @@ public: virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) = 0; }; - class HID : public USBDeviceConfig, public UsbConfigXtracter { protected: USB *pUsb; // USB class instance pointer diff --git a/hidescriptorparser.cpp b/hidescriptorparser.cpp index f83c3af6..fd9d2d2d 100644 --- a/hidescriptorparser.cpp +++ b/hidescriptorparser.cpp @@ -980,7 +980,7 @@ void ReportDescParserBase::Parse(const uint16_t len, const uint8_t *pbuf, const totalSize = 0; - while (cntdn) { + while(cntdn) { //USB_HOST_SERIAL.println(""); //PrintHex(offset + len - cntdn); //USB_HOST_SERIAL.print(":"); @@ -995,7 +995,7 @@ void ReportDescParserBase::Parse(const uint16_t len, const uint8_t *pbuf, const void ReportDescParserBase::PrintValue(uint8_t *p, uint8_t len) { E_Notify(PSTR("("), 0x80); - for (; len; p++, len--) + for(; len; p++, len--) PrintHex (*p, 0x80); E_Notify(PSTR(")"), 0x80); } @@ -1007,7 +1007,7 @@ void ReportDescParserBase::PrintByteValue(uint8_t data) { } void ReportDescParserBase::PrintItemTitle(uint8_t prefix) { - switch (prefix & (TYPE_MASK | TAG_MASK)) { + switch(prefix & (TYPE_MASK | TAG_MASK)) { case (TYPE_GLOBAL | TAG_GLOBAL_PUSH): E_Notify(PSTR("\r\nPush"), 0x80); break; @@ -1074,9 +1074,9 @@ void ReportDescParserBase::PrintItemTitle(uint8_t prefix) { uint8_t ReportDescParserBase::ParseItem(uint8_t **pp, uint16_t *pcntdn) { //uint8_t ret = enErrorSuccess; //reinterpret_cast<>(varBuffer); -switch (itemParseState) { + switch(itemParseState) { case 0: - if (**pp == HID_LONG_ITEM_PREFIX) + if(**pp == HID_LONG_ITEM_PREFIX) USBTRACE("\r\nLONG\r\n"); else { uint8_t size = ((**pp) & DATA_SIZE_MASK); @@ -1091,10 +1091,10 @@ switch (itemParseState) { itemSize--; itemParseState = 1; - if (!itemSize) + if(!itemSize) break; - if (!pcntdn) + if(!pcntdn) return enErrorIncomplete; case 1: //USBTRACE2("\r\niSz:",itemSize); @@ -1103,18 +1103,18 @@ switch (itemParseState) { valParser.Initialize(&theBuffer); itemParseState = 2; case 2: - if (!valParser.Parse(pp, pcntdn)) + if(!valParser.Parse(pp, pcntdn)) return enErrorIncomplete; itemParseState = 3; case 3: { uint8_t data = *((uint8_t*)varBuffer); - switch (itemPrefix & (TYPE_MASK | TAG_MASK)) { + switch(itemPrefix & (TYPE_MASK | TAG_MASK)) { case (TYPE_LOCAL | TAG_LOCAL_USAGE): - if (pfUsage) { - if (theBuffer.valueSize > 1) { - uint16_t* ui16 = reinterpret_cast(varBuffer); + if(pfUsage) { + if(theBuffer.valueSize > 1) { + uint16_t* ui16 = reinterpret_cast(varBuffer); pfUsage(*ui16); } else pfUsage(data); @@ -1149,7 +1149,7 @@ switch (itemParseState) { break; case (TYPE_MAIN | TAG_MAIN_COLLECTION): case (TYPE_MAIN | TAG_MAIN_ENDCOLLECTION): - switch (data) { + switch(data) { case 0x00: E_Notify(PSTR(" Physical"), 0x80); break; @@ -1216,23 +1216,23 @@ ReportDescParserBase::UsagePageFunc ReportDescParserBase::usagePageFunctions[] / void ReportDescParserBase::SetUsagePage(uint16_t page) { pfUsage = NULL; - if (VALUE_BETWEEN(page, 0x00, 0x11)) + if(VALUE_BETWEEN(page, 0x00, 0x11)) pfUsage = (usagePageFunctions[page - 1]); - // Dead code... - // - // pfUsage = (UsagePageFunc)pgm_read_pointer(usagePageFunctions[page - 1]); - //else if (page > 0x7f && page < 0x84) - // E_Notify(pstrUsagePageMonitor); - //else if (page > 0x83 && page < 0x8c) - // E_Notify(pstrUsagePagePower); - //else if (page > 0x8b && page < 0x92) - // E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c])); - //else if (page > 0xfeff && page <= 0xffff) - // E_Notify(pstrUsagePageVendorDefined); - // + // Dead code... + // + // pfUsage = (UsagePageFunc)pgm_read_pointer(usagePageFunctions[page - 1]); + //else if (page > 0x7f && page < 0x84) + // E_Notify(pstrUsagePageMonitor); + //else if (page > 0x83 && page < 0x8c) + // E_Notify(pstrUsagePagePower); + //else if (page > 0x8b && page < 0x92) + // E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c])); + //else if (page > 0xfeff && page <= 0xffff) + // E_Notify(pstrUsagePageVendorDefined); + // else - switch (page) { + switch(page) { case 0x14: pfUsage = &ReportDescParserBase::PrintAlphanumDisplayPageUsage; break; @@ -1248,14 +1248,14 @@ void ReportDescParserBase::PrintUsagePage(uint16_t page) { output_if_between(page, 0x00, 0x11, w, E_Notify, usagePageTitles0, 0x80) else output_if_between(page, 0x8b, 0x92, w, E_Notify, usagePageTitles1, 0x80) - else if (VALUE_BETWEEN(page, 0x7f, 0x84)) + else if(VALUE_BETWEEN(page, 0x7f, 0x84)) E_Notify(pstrUsagePageMonitor, 0x80); - else if (VALUE_BETWEEN(page, 0x83, 0x8c)) + else if(VALUE_BETWEEN(page, 0x83, 0x8c)) E_Notify(pstrUsagePagePower, 0x80); - else if (page > 0xfeff /* && page <= 0xffff */) + else if(page > 0xfeff /* && page <= 0xffff */) E_Notify(pstrUsagePageVendorDefined, 0x80); else - switch (page) { + switch(page) { case 0x14: E_Notify(pstrUsagePageAlphaNumericDisplay, 0x80); break; @@ -1409,8 +1409,8 @@ void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) { const char * const * w; E_Notify(pstrSpace, 0x80); - if (usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80); - else if (usage == 0x70) + if(usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80); + else if(usage == 0x70) E_Notify(pstrUsageDepthGainCompensation, 0x80); else output_if_between(usage, 0x1f, 0x28, w, E_Notify, medInstrTitles0, 0x80) else output_if_between(usage, 0x3f, 0x45, w, E_Notify, medInstrTitles1, 0x80) @@ -1423,9 +1423,9 @@ void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) { uint8_t ReportDescParser2::ParseItem(uint8_t **pp, uint16_t *pcntdn) { //uint8_t ret = enErrorSuccess; - switch (itemParseState) { + switch(itemParseState) { case 0: - if (**pp == HID_LONG_ITEM_PREFIX) + if(**pp == HID_LONG_ITEM_PREFIX) USBTRACE("\r\nLONG\r\n"); else { uint8_t size = ((**pp) & DATA_SIZE_MASK); @@ -1437,28 +1437,28 @@ uint8_t ReportDescParser2::ParseItem(uint8_t **pp, uint16_t *pcntdn) { itemSize--; itemParseState = 1; - if (!itemSize) + if(!itemSize) break; - if (!pcntdn) + if(!pcntdn) return enErrorIncomplete; case 1: theBuffer.valueSize = itemSize; valParser.Initialize(&theBuffer); itemParseState = 2; case 2: - if (!valParser.Parse(pp, pcntdn)) + if(!valParser.Parse(pp, pcntdn)) return enErrorIncomplete; itemParseState = 3; case 3: { uint8_t data = *((uint8_t*)varBuffer); - switch (itemPrefix & (TYPE_MASK | TAG_MASK)) { + switch(itemPrefix & (TYPE_MASK | TAG_MASK)) { case (TYPE_LOCAL | TAG_LOCAL_USAGE): - if (pfUsage) { - if (theBuffer.valueSize > 1) { - uint16_t* ui16 = reinterpret_cast(varBuffer); + if(pfUsage) { + if(theBuffer.valueSize > 1) { + uint16_t* ui16 = reinterpret_cast(varBuffer); pfUsage(*ui16); } else pfUsage(data); @@ -1512,7 +1512,7 @@ void ReportDescParser2::OnInputItem(uint8_t itm) { uint8_t bit_offset = totalSize - tmp; // number of bits in the current byte already handled uint8_t *p = pBuf + byte_offset; // current byte pointer - if (bit_offset) + if(bit_offset) *p >>= bit_offset; uint8_t usage = useMin; @@ -1522,7 +1522,7 @@ void ReportDescParser2::OnInputItem(uint8_t itm) { uint8_t bits_of_byte = 8; // for each field in field array defined by rptCount - for (uint8_t field = 0; field < rptCount; field++, usage++) { + for(uint8_t field = 0; field < rptCount; field++, usage++) { union { uint8_t bResult[4]; @@ -1533,7 +1533,7 @@ void ReportDescParser2::OnInputItem(uint8_t itm) { result.dwResult = 0; uint8_t mask = 0; - if (print_usemin_usemax) + if(print_usemin_usemax) pfUsage(usage); // bits_left - number of bits in the field(array of fields, depending on Report Count) left to process @@ -1541,7 +1541,7 @@ void ReportDescParser2::OnInputItem(uint8_t itm) { // bits_to_copy - number of bits to copy to result buffer // for each bit in a field - for (uint8_t bits_left = rptSize, bits_to_copy = 0; bits_left; + for(uint8_t bits_left = rptSize, bits_to_copy = 0; bits_left; bits_left -= bits_to_copy) { bits_to_copy = (bits_left > bits_of_byte) ? bits_of_byte : bits_left; @@ -1553,7 +1553,7 @@ void ReportDescParser2::OnInputItem(uint8_t itm) { mask = 0; - for (uint8_t j = bits_to_copy; j; j--) { + for(uint8_t j = bits_to_copy; j; j--) { mask <<= 1; mask |= 1; } @@ -1562,7 +1562,7 @@ void ReportDescParser2::OnInputItem(uint8_t itm) { bits_of_byte -= bits_to_copy; - if (bits_of_byte < 1) { + if(bits_of_byte < 1) { bits_of_byte = 8; p++; } @@ -1577,6 +1577,6 @@ void UniversalReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t uint8_t ret = hid->GetReportDescr(0, &prs); - if (ret) + if(ret) ErrorMessage (PSTR("GetReportDescr-2"), ret); } diff --git a/hidescriptorparser.h b/hidescriptorparser.h index ac030e8e..c43aaaea 100644 --- a/hidescriptorparser.h +++ b/hidescriptorparser.h @@ -101,7 +101,7 @@ protected: MultiValueBuffer theBuffer; MultiByteValueParser valParser; ByteSkipper theSkipper; - uint8_t varBuffer[sizeof(USB_CONFIGURATION_DESCRIPTOR)]; + uint8_t varBuffer[sizeof (USB_CONFIGURATION_DESCRIPTOR)]; uint8_t itemParseState; // Item parser state variable uint8_t itemSize; // Item size @@ -126,8 +126,7 @@ public: itemPrefix(0), rptSize(0), rptCount(0), - pfUsage(NULL) - { + pfUsage(NULL) { theBuffer.pValue = varBuffer; valParser.Initialize(&theBuffer); theSkipper.Initialize(&theBuffer); diff --git a/hiduniversal.cpp b/hiduniversal.cpp index 9cbd09c4..fb19683f 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -7,14 +7,14 @@ bPollEnable(false), bHasReportId(false) { Initialize(); - if (pUsb) + if(pUsb) pUsb->RegisterDeviceClass(this); } uint16_t HIDUniversal::GetHidClassDescrLen(uint8_t type, uint8_t num) { - for (uint8_t i = 0, n = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { - if (descrInfo[i].bDescrType == type) { - if (n == num) + for(uint8_t i = 0, n = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { + if(descrInfo[i].bDescrType == type) { + if(n == num) return descrInfo[i].wDescriptorLength; n++; } @@ -23,22 +23,22 @@ uint16_t HIDUniversal::GetHidClassDescrLen(uint8_t type, uint8_t num) { } void HIDUniversal::Initialize() { - for (uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { + for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { rptParsers[i].rptId = 0; rptParsers[i].rptParser = NULL; } - for (uint8_t i = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { + for(uint8_t i = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { descrInfo[i].bDescrType = 0; descrInfo[i].wDescriptorLength = 0; } - for (uint8_t i = 0; i < maxHidInterfaces; i++) { + for(uint8_t i = 0; i < maxHidInterfaces; i++) { hidInterfaces[i].bmInterface = 0; hidInterfaces[i].bmProtocol = 0; - for (uint8_t j = 0; j < maxEpPerInterface; j++) + for(uint8_t j = 0; j < maxEpPerInterface; j++) hidInterfaces[i].epIndex[j] = 0; } - for (uint8_t i = 0; i < totalEndpoints; i++) { + for(uint8_t i = 0; i < totalEndpoints; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; @@ -52,8 +52,8 @@ void HIDUniversal::Initialize() { } bool HIDUniversal::SetReportParser(uint8_t id, HIDReportParser *prs) { - for (uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - if (rptParsers[i].rptId == 0 && rptParsers[i].rptParser == NULL) { + for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { + if(rptParsers[i].rptId == 0 && rptParsers[i].rptParser == NULL) { rptParsers[i].rptId = id; rptParsers[i].rptParser = prs; return true; @@ -63,11 +63,11 @@ bool HIDUniversal::SetReportParser(uint8_t id, HIDReportParser *prs) { } HIDReportParser* HIDUniversal::GetReportParser(uint8_t id) { - if (!bHasReportId) + if(!bHasReportId) return ((rptParsers[0].rptParser) ? rptParsers[0].rptParser : NULL); - for (uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - if (rptParsers[i].rptId == id) + for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { + if(rptParsers[i].rptId == id) return rptParsers[i].rptParser; } return NULL; @@ -90,16 +90,16 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { USBTRACE("HU Init\r\n"); - if (bAddress) + if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - if (!p->epinfo) { + if(!p->epinfo) { USBTRACE("epinfo\r\n"); return USB_ERROR_EPINFO_IS_NULL; } @@ -115,10 +115,10 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Get device descriptor rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); - if (!rcode) + if(!rcode) len = (buf[0] > constBufSize) ? constBufSize : buf[0]; - if (rcode) { + if(rcode) { // Restore p->epinfo p->epinfo = oldep_ptr; @@ -131,7 +131,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor @@ -140,7 +140,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -156,15 +156,15 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; - if (len) + if(len) rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - if (rcode) + if(rcode) goto FailGetDevDescr; num_of_conf = udd->bNumConfigurations; @@ -172,12 +172,12 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; USBTRACE2("NC:", num_of_conf); - for (uint8_t i = 0; i < num_of_conf; i++) { + for(uint8_t i = 0; i < num_of_conf; i++) { //HexDumper HexDump; ConfigDescParser confDescrParser(this); @@ -185,14 +185,14 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { //rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump); rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - if (rcode) + if(rcode) goto FailGetConfDescr; - if (bNumEP > 1) + if(bNumEP > 1) break; } // for - if (bNumEP < 2) + if(bNumEP < 2) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Assign epInfo to epinfo pointer @@ -203,16 +203,16 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); - if (rcode) + if(rcode) goto FailSetConfDescr; - for (uint8_t i = 0; i < bNumIface; i++) { - if (hidInterfaces[i].epIndex[epInterruptInIndex] == 0) + for(uint8_t i = 0; i < bNumIface; i++) { + if(hidInterfaces[i].epIndex[epInterruptInIndex] == 0) continue; rcode = SetIdle(hidInterfaces[i].bmInterface, 0, 0); - if (rcode && rcode != hrSTALL) + if(rcode && rcode != hrSTALL) goto FailSetIdle; } @@ -262,8 +262,8 @@ Fail: } HIDUniversal::HIDInterface* HIDUniversal::FindInterface(uint8_t iface, uint8_t alt, uint8_t proto) { - for (uint8_t i = 0; i < bNumIface && i < maxHidInterfaces; i++) - if (hidInterfaces[i].bmInterface == iface && hidInterfaces[i].bmAltSet == alt + for(uint8_t i = 0; i < bNumIface && i < maxHidInterfaces; i++) + if(hidInterfaces[i].bmInterface == iface && hidInterfaces[i].bmAltSet == alt && hidInterfaces[i].bmProtocol == proto) return hidInterfaces + i; return NULL; @@ -271,7 +271,7 @@ HIDUniversal::HIDInterface* HIDUniversal::FindInterface(uint8_t iface, uint8_t a void HIDUniversal::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { // If the first configuration satisfies, the others are not concidered. - if (bNumEP > 1 && conf != bConfNum) + if(bNumEP > 1 && conf != bConfNum) return; //ErrorMessage(PSTR("\r\nConf.Val"), conf); @@ -284,7 +284,7 @@ void HIDUniversal::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint HIDInterface *piface = FindInterface(iface, alt, proto); // Fill in interface structure in case of new interface - if (!piface) { + if(!piface) { piface = hidInterfaces + bNumIface; piface->bmInterface = iface; piface->bmAltSet = alt; @@ -292,12 +292,12 @@ void HIDUniversal::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint bNumIface++; } - if ((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) + if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) index = epInterruptInIndex; else index = epInterruptOutIndex; - if (index) { + if(index) { // Fill in the endpoint info structure epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F); epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize; @@ -323,34 +323,34 @@ uint8_t HIDUniversal::Release() { } bool HIDUniversal::BuffersIdentical(uint8_t len, uint8_t *buf1, uint8_t *buf2) { - for (uint8_t i = 0; i < len; i++) - if (buf1[i] != buf2[i]) + for(uint8_t i = 0; i < len; i++) + if(buf1[i] != buf2[i]) return false; return true; } void HIDUniversal::ZeroMemory(uint8_t len, uint8_t *buf) { - for (uint8_t i = 0; i < len; i++) + for(uint8_t i = 0; i < len; i++) buf[i] = 0; } void HIDUniversal::SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest) { - for (uint8_t i = 0; i < len; i++) + for(uint8_t i = 0; i < len; i++) dest[i] = src[i]; } uint8_t HIDUniversal::Poll() { uint8_t rcode = 0; - if (!bPollEnable) + if(!bPollEnable) return 0; - if (qNextPollTime <= millis()) { + if(qNextPollTime <= millis()) { qNextPollTime = millis() + 50; uint8_t buf[constBuffLen]; - for (uint8_t i = 0; i < bNumIface; i++) { + for(uint8_t i = 0; i < bNumIface; i++) { uint8_t index = hidInterfaces[i].epIndex[epInterruptInIndex]; uint16_t read = (uint16_t)epInfo[index].maxPktSize; @@ -358,32 +358,32 @@ uint8_t HIDUniversal::Poll() { uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[index].epAddr, &read, buf); - if (rcode) { - if (rcode != hrNAK) + if(rcode) { + if(rcode != hrNAK) USBTRACE3("(hiduniversal.h) Poll:", rcode, 0x81); return rcode; } - if (read > constBuffLen) + if(read > constBuffLen) read = constBuffLen; bool identical = BuffersIdentical(read, buf, prevBuf); SaveBuffer(read, buf, prevBuf); - if (identical) + if(identical) return 0; Notify(PSTR("\r\nBuf: "), 0x80); - for (uint8_t i = 0; i < read; i++) + for(uint8_t i = 0; i < read; i++) D_PrintHex (buf[i], 0x80); Notify(PSTR("\r\n"), 0x80); HIDReportParser *prs = GetReportParser(((bHasReportId) ? *buf : 0)); - if (prs) + if(prs) prs->Parse(this, bHasReportId, (uint8_t)read, buf); } } diff --git a/hiduniversal.h b/hiduniversal.h index e1ea26c4..0f6729e7 100644 --- a/hiduniversal.h +++ b/hiduniversal.h @@ -76,4 +76,4 @@ public: virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); }; -#endif // __HIDUNIVERSAL_H__ \ No newline at end of file +#endif // __HIDUNIVERSAL_H__ diff --git a/hidusagestr.h b/hidusagestr.h index 32ab0771..f99f0e39 100644 --- a/hidusagestr.h +++ b/hidusagestr.h @@ -974,4 +974,4 @@ const char pstrUsageSoftControlAdjust [] PROGMEM = "Soft Ctrl Adj"; //const char *medInstrTitles3[]; //const char *medInstrTitles4[]; -#endif //__HIDUSAGESTR_H__ \ No newline at end of file +#endif //__HIDUSAGESTR_H__ diff --git a/hidusagetitlearrays.cpp b/hidusagetitlearrays.cpp index 0aa1b9c7..8bdd41b5 100644 --- a/hidusagetitlearrays.cpp +++ b/hidusagetitlearrays.cpp @@ -1043,4 +1043,4 @@ e-mail : support@circuitsathome.com // pstrUsageSoftControlAdjust //}; -#endif // __HIDUSAGETITLEARRAYS_H__ \ No newline at end of file +#endif // __HIDUSAGETITLEARRAYS_H__ diff --git a/macros.h b/macros.h index c5ec6b8a..1f56814a 100644 --- a/macros.h +++ b/macros.h @@ -63,6 +63,7 @@ * Debug macros: Strings are stored in progmem (flash) instead of RAM. */ #define USBTRACE(s) (Notify(PSTR(s), 0x80)) +#define USBTRACE1(s,l) (Notify(PSTR(s), l)) #define USBTRACE2(s,r) (Notify(PSTR(s), 0x80), D_PrintHex((r), 0x80), Notify(PSTR("\r\n"), 0x80)) #define USBTRACE3(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l), Notify(PSTR("\r\n"), l)) diff --git a/masstorage.cpp b/masstorage.cpp index c4967880..19da7b19 100644 --- a/masstorage.cpp +++ b/masstorage.cpp @@ -17,7 +17,7 @@ const uint8_t BulkOnly::epInterruptInIndex = 3; * @return media capacity */ uint32_t BulkOnly::GetCapacity(uint8_t lun) { - if (LUNOk[lun]) + if(LUNOk[lun]) return CurrentCapacity[lun]; return 0LU; } @@ -29,7 +29,7 @@ uint32_t BulkOnly::GetCapacity(uint8_t lun) { * @return media sector size */ uint16_t BulkOnly::GetSectorSize(uint8_t lun) { - if (LUNOk[lun]) + if(LUNOk[lun]) return CurrentSectorSize[lun]; return 0U; } @@ -115,7 +115,7 @@ uint8_t BulkOnly::MediaCTL(uint8_t lun, uint8_t ctl) { Notify(PSTR("-----------------\r\n"), 0x80); uint8_t rcode = MASS_ERR_UNIT_NOT_READY; - if (bAddress) { + if(bAddress) { CDB6_t cdb = CDB6_t(SCSI_CMD_START_STOP_UNIT, lun, ctl & 0x03, 0); rcode = SCSITransaction6(&cdb, (uint16_t)0, NULL, (uint8_t)MASS_CMD_DIR_OUT); } else { @@ -135,7 +135,7 @@ uint8_t BulkOnly::MediaCTL(uint8_t lun, uint8_t ctl) { * @return 0 on success */ uint8_t BulkOnly::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf) { - if (!LUNOk[lun]) return MASS_ERR_NO_MEDIA; + if(!LUNOk[lun]) return MASS_ERR_NO_MEDIA; Notify(PSTR("\r\nRead LUN:\t"), 0x80); D_PrintHex (lun, 0x90); Notify(PSTR("\r\nLBA:\t\t"), 0x90); @@ -150,10 +150,10 @@ uint8_t BulkOnly::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t block again: uint8_t er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), buf, (uint8_t)MASS_CMD_DIR_IN); - if (er == MASS_ERR_STALL) { + if(er == MASS_ERR_STALL) { MediaCTL(lun, 1); delay(150); - if (!TestUnitReady(lun)) goto again; + if(!TestUnitReady(lun)) goto again; } return er; } @@ -169,8 +169,8 @@ again: * @return 0 on success */ uint8_t BulkOnly::Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t * buf) { - if (!LUNOk[lun]) return MASS_ERR_NO_MEDIA; - if (!WriteOk[lun]) return MASS_ERR_WRITE_PROTECTED; + if(!LUNOk[lun]) return MASS_ERR_NO_MEDIA; + if(!WriteOk[lun]) return MASS_ERR_WRITE_PROTECTED; Notify(PSTR("\r\nWrite LUN:\t"), 0x80); D_PrintHex (lun, 0x90); Notify(PSTR("\r\nLBA:\t\t"), 0x90); @@ -185,10 +185,10 @@ uint8_t BulkOnly::Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t bloc again: uint8_t er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), (void*)buf, (uint8_t)MASS_CMD_DIR_OUT); - if (er == MASS_ERR_WRITE_STALL) { + if(er == MASS_ERR_WRITE_STALL) { MediaCTL(lun, 1); delay(150); - if (!TestUnitReady(lun)) goto again; + if(!TestUnitReady(lun)) goto again; } return er; } @@ -213,7 +213,7 @@ bPollEnable(false), bLastUsbError(0) { ClearAllEP(); dCBWTag = 0; - if (pUsb) + if(pUsb) pUsb->RegisterDeviceClass(this); } @@ -245,17 +245,17 @@ uint8_t BulkOnly::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { AddressPool &addrPool = pUsb->GetAddressPool(); - if (bAddress) + if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; // // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); - if (!p) { + if(!p) { return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; } - if (!p->epinfo) { + if(!p->epinfo) { USBTRACE("epinfo\r\n"); return USB_ERROR_EPINFO_IS_NULL; } @@ -273,13 +273,13 @@ uint8_t BulkOnly::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { // Restore p->epinfo p->epinfo = oldep_ptr; - if (rcode) { + if(rcode) { goto FailGetDevDescr; } // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) + if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Extract Max Packet Size from the device descriptor @@ -315,14 +315,14 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { AddressPool &addrPool = pUsb->GetAddressPool(); UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; // Assign new address to the device delay(2000); rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { + if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; @@ -336,7 +336,7 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { p = addrPool.GetUsbDevicePtr(bAddress); - if (!p) + if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; @@ -344,12 +344,12 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if (rcode) + if(rcode) goto FailSetDevTblEntry; USBTRACE2("NC:", num_of_conf); - for (uint8_t i = 0; i < num_of_conf; i++) { + for(uint8_t i = 0; i < num_of_conf; i++) { ConfigDescParser< USB_CLASS_MASS_STORAGE, MASS_SUBCLASS_SCSI, MASS_PROTO_BBB, @@ -359,14 +359,14 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { rcode = pUsb->getConfDescr(bAddress, 0, i, &BulkOnlyParser); - if (rcode) + if(rcode) goto FailGetConfDescr; - if (bNumEP > 1) + if(bNumEP > 1) break; } - if (bNumEP < 3) + if(bNumEP < 3) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Assign epInfo to epinfo pointer @@ -377,38 +377,38 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); - if (rcode) + if(rcode) goto FailSetConfDescr; //Linux does a 1sec delay after this. delay(1000); rcode = GetMaxLUN(&bMaxLUN); - if (rcode) + if(rcode) goto FailGetMaxLUN; - if (bMaxLUN >= MASS_MAX_SUPPORTED_LUN) bMaxLUN = MASS_MAX_SUPPORTED_LUN - 1; + if(bMaxLUN >= MASS_MAX_SUPPORTED_LUN) bMaxLUN = MASS_MAX_SUPPORTED_LUN - 1; ErrorMessage (PSTR("MaxLUN"), bMaxLUN); delay(1000); // Delay a bit for slow firmware. - for (uint8_t lun = 0; lun <= bMaxLUN; lun++) { + for(uint8_t lun = 0; lun <= bMaxLUN; lun++) { InquiryResponse response; rcode = Inquiry(lun, sizeof (InquiryResponse), (uint8_t*) & response); - if (rcode) { + if(rcode) { ErrorMessage (PSTR("Inquiry"), rcode); } else { #if 0 printf("LUN %i `", lun); uint8_t *buf = response.VendorID; - for (int i = 0; i < 28; i++) printf("%c", buf[i]); + for(int i = 0; i < 28; i++) printf("%c", buf[i]); printf("'\r\nQualifier %1.1X ", response.PeripheralQualifier); printf("Device type %2.2X ", response.DeviceType); printf("RMB %1.1X ", response.Removable); printf("SSCS %1.1X ", response.SCCS); uint8_t sv = response.Version; printf("SCSI version %2.2X\r\nDevice conforms to ", sv); - switch (sv) { + switch(sv) { case 0: printf("No specific"); break; @@ -436,20 +436,20 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { printf(" standards.\r\n"); #endif uint8_t tries = 0xf0; - while ((rcode = TestUnitReady(lun))) { - if (rcode == 0x08) break; // break on no media, this is OK to do. + while((rcode = TestUnitReady(lun))) { + if(rcode == 0x08) break; // break on no media, this is OK to do. // try to lock media and spin up - if (tries < 14) { + if(tries < 14) { LockMedia(lun, 1); MediaCTL(lun, 1); // I actually have a USB stick that needs this! } else delay(2 * (tries + 1)); tries++; - if (!tries) break; + if(!tries) break; } - if (!rcode) { + if(!rcode) { delay(1000); LUNOk[lun] = CheckLUN(lun); - if (!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun); + if(!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun); } } } @@ -459,7 +459,7 @@ uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) { rcode = OnInit(); - if (rcode) + if(rcode) goto FailOnInit; #ifdef DEBUG_USB_HOST @@ -489,11 +489,11 @@ FailGetMaxLUN: goto Fail; #endif -//#ifdef DEBUG_USB_HOST -//FailInvalidSectorSize: -// USBTRACE("Sector Size is NOT VALID: "); -// goto Fail; -//#endif + //#ifdef DEBUG_USB_HOST + //FailInvalidSectorSize: + // USBTRACE("Sector Size is NOT VALID: "); + // goto Fail; + //#endif FailSetDevTblEntry: #ifdef DEBUG_USB_HOST @@ -532,10 +532,10 @@ void BulkOnly::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t uint8_t index; - if ((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) + if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) index = epInterruptInIndex; else - if ((pep->bmAttributes & 0x02) == 2) + if((pep->bmAttributes & 0x02) == 2) index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; else return; @@ -570,35 +570,35 @@ uint8_t BulkOnly::Release() { boolean BulkOnly::CheckLUN(uint8_t lun) { uint8_t rcode; Capacity capacity; - for (uint8_t i = 0; i < 8; i++) capacity.data[i] = 0; + for(uint8_t i = 0; i < 8; i++) capacity.data[i] = 0; rcode = ReadCapacity10(lun, (uint8_t*)capacity.data); - if (rcode) { + if(rcode) { //printf(">>>>>>>>>>>>>>>>ReadCapacity returned %i\r\n", rcode); return false; } ErrorMessage (PSTR(">>>>>>>>>>>>>>>>CAPACITY OK ON LUN"), lun); - for (uint8_t i = 0; i < 8 /*sizeof (Capacity)*/; i++) + for(uint8_t i = 0; i < 8 /*sizeof (Capacity)*/; i++) D_PrintHex (capacity.data[i], 0x80); Notify(PSTR("\r\n\r\n"), 0x80); // Only 512/1024/2048/4096 are valid values! uint32_t c = BMAKE32(capacity.data[4], capacity.data[5], capacity.data[6], capacity.data[7]); - if (c != 0x0200LU && c != 0x0400LU && c != 0x0800LU && c != 0x1000LU) { + if(c != 0x0200LU && c != 0x0400LU && c != 0x0800LU && c != 0x1000LU) { return false; } // Store capacity information. CurrentSectorSize[lun] = (uint16_t)(c); // & 0xFFFF); CurrentCapacity[lun] = BMAKE32(capacity.data[0], capacity.data[1], capacity.data[2], capacity.data[3]) + 1; - if (CurrentCapacity[lun] == /*0xffffffffLU */ 0x01LU || CurrentCapacity[lun] == 0x00LU) { + if(CurrentCapacity[lun] == /*0xffffffffLU */ 0x01LU || CurrentCapacity[lun] == 0x00LU) { // Buggy firmware will report 0xffffffff or 0 for no media - if (CurrentCapacity[lun]) + if(CurrentCapacity[lun]) ErrorMessage (PSTR(">>>>>>>>>>>>>>>>BUGGY FIRMWARE. CAPACITY FAIL ON LUN"), lun); return false; } delay(20); Page3F(lun); - if (!TestUnitReady(lun)) return true; + if(!TestUnitReady(lun)) return true; return false; } @@ -608,18 +608,18 @@ boolean BulkOnly::CheckLUN(uint8_t lun) { * Scan for media change on all LUNs */ void BulkOnly::CheckMedia() { - for (uint8_t lun = 0; lun <= bMaxLUN; lun++) { - if (TestUnitReady(lun)) { + for(uint8_t lun = 0; lun <= bMaxLUN; lun++) { + if(TestUnitReady(lun)) { LUNOk[lun] = false; continue; } - if (!LUNOk[lun]) + if(!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun); } #if 0 printf("}}}}}}}}}}}}}}}}STATUS "); - for (uint8_t lun = 0; lun <= bMaxLUN; lun++) { - if (LUNOk[lun]) + for(uint8_t lun = 0; lun <= bMaxLUN; lun++) { + if(LUNOk[lun]) printf("#"); else printf("."); } @@ -636,10 +636,10 @@ void BulkOnly::CheckMedia() { uint8_t BulkOnly::Poll() { //uint8_t rcode = 0; - if (!bPollEnable) + if(!bPollEnable) return 0; - if (qNextPollTime <= millis()) { + if(qNextPollTime <= millis()) { CheckMedia(); } //rcode = 0; @@ -664,7 +664,7 @@ uint8_t BulkOnly::Poll() { uint8_t BulkOnly::GetMaxLUN(uint8_t *plun) { uint8_t ret = pUsb->ctrlReq(bAddress, 0, bmREQ_MASSIN, MASS_REQ_GET_MAX_LUN, 0, 0, bIface, 1, 1, plun, NULL); - if (ret == hrSTALL) + if(ret == hrSTALL) *plun = 0; return 0; @@ -696,7 +696,7 @@ uint8_t BulkOnly::Inquiry(uint8_t lun, uint16_t bsize, uint8_t *buf) { */ uint8_t BulkOnly::TestUnitReady(uint8_t lun) { //SetCurLUN(lun); - if (!bAddress) + if(!bAddress) return MASS_ERR_UNIT_NOT_READY; Notify(PSTR("\r\nTestUnitReady\r\n"), 0x80); @@ -752,15 +752,15 @@ uint8_t BulkOnly::ReadCapacity10(uint8_t lun, uint8_t *buf) { */ uint8_t BulkOnly::Page3F(uint8_t lun) { uint8_t buf[192]; - for (int i = 0; i < 192; i++) { + for(int i = 0; i < 192; i++) { buf[i] = 0x00; } WriteOk[lun] = true; uint8_t rc = ModeSense6(lun, 0, 0x3f, 0, 192, buf); - if (!rc) { + if(!rc) { WriteOk[lun] = ((buf[2] & 0x80) == 0); Notify(PSTR("Mode Sense: "), 0x80); - for (int i = 0; i < 4; i++) { + for(int i = 0; i < 4; i++) { D_PrintHex (buf[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -803,15 +803,15 @@ uint8_t BulkOnly::RequestSense(uint8_t lun, uint16_t size, uint8_t *buf) { * @return */ uint8_t BulkOnly::ClearEpHalt(uint8_t index) { - if (index == 0) + if(index == 0) return 0; uint8_t ret = 0; - while ((ret = (pUsb->ctrlReq(bAddress, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_STANDARD | USB_SETUP_RECIPIENT_ENDPOINT, USB_REQUEST_CLEAR_FEATURE, USB_FEATURE_ENDPOINT_HALT, 0, ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr), 0, 0, NULL, NULL)) == 0x01)) + while((ret = (pUsb->ctrlReq(bAddress, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_STANDARD | USB_SETUP_RECIPIENT_ENDPOINT, USB_REQUEST_CLEAR_FEATURE, USB_FEATURE_ENDPOINT_HALT, 0, ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr), 0, 0, NULL, NULL)) == 0x01)) delay(6); - if (ret) { + if(ret) { ErrorMessage (PSTR("ClearEpHalt"), ret); ErrorMessage (PSTR("EP"), ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr)); return ret; @@ -827,7 +827,7 @@ uint8_t BulkOnly::ClearEpHalt(uint8_t index) { * */ void BulkOnly::Reset() { - while (pUsb->ctrlReq(bAddress, 0, bmREQ_MASSOUT, MASS_REQ_BOMSR, 0, 0, bIface, 0, 0, NULL, NULL) == 0x01) delay(6); + while(pUsb->ctrlReq(bAddress, 0, bmREQ_MASSOUT, MASS_REQ_BOMSR, 0, 0, bIface, 0, 0, NULL, NULL) == 0x01) delay(6); } /** @@ -855,7 +855,7 @@ uint8_t BulkOnly::ResetRecovery() { * Clear all EP data and clear all LUN status */ void BulkOnly::ClearAllEP() { - for (uint8_t i = 0; i < MASS_MAX_ENDPOINTS; i++) { + for(uint8_t i = 0; i < MASS_MAX_ENDPOINTS; i++) { epInfo[i].epAddr = 0; epInfo[i].maxPktSize = (i) ? 0 : 8; epInfo[i].epAttribs = 0; @@ -863,7 +863,7 @@ void BulkOnly::ClearAllEP() { epInfo[i].bmNakPower = USB_NAK_DEFAULT; } - for (uint8_t i = 0; i < MASS_MAX_SUPPORTED_LUN; i++) { + for(uint8_t i = 0; i < MASS_MAX_SUPPORTED_LUN; i++) { LUNOk[i] = false; WriteOk[i] = false; CurrentCapacity[i] = 0lu; @@ -888,11 +888,11 @@ void BulkOnly::ClearAllEP() { * @return */ bool BulkOnly::IsValidCSW(CommandStatusWrapper *pcsw, CommandBlockWrapperBase *pcbw) { - if (pcsw->dCSWSignature != MASS_CSW_SIGNATURE) { + if(pcsw->dCSWSignature != MASS_CSW_SIGNATURE) { Notify(PSTR("CSW:Sig error\r\n"), 0x80); return false; } - if (pcsw->dCSWTag != pcbw->dCBWTag) { + if(pcsw->dCSWTag != pcbw->dCBWTag) { Notify(PSTR("CSW:Wrong tag\r\n"), 0x80); return false; } @@ -912,12 +912,12 @@ uint8_t BulkOnly::HandleUsbError(uint8_t error, uint8_t index) { bLastUsbError = error; //if (error) //ClearEpHalt(index); - while (error && count) { - if (error != hrSUCCESS) { + while(error && count) { + if(error != hrSUCCESS) { ErrorMessage (PSTR("USB Error"), error); ErrorMessage (PSTR("Index"), index); } - switch (error) { + switch(error) { // case hrWRONGPID: case hrSUCCESS: return MASS_ERR_SUCCESS; @@ -927,15 +927,15 @@ uint8_t BulkOnly::HandleUsbError(uint8_t error, uint8_t index) { case hrTIMEOUT: case hrJERR: return MASS_ERR_DEVICE_DISCONNECTED; case hrSTALL: - if (index == 0) + if(index == 0) return MASS_ERR_STALL; ClearEpHalt(index); - if (index != epDataInIndex) + if(index != epDataInIndex) return MASS_ERR_WRITE_STALL; return MASS_ERR_STALL; case hrNAK: - if (index == 0) + if(index == 0) return MASS_ERR_UNIT_BUSY; return MASS_ERR_UNIT_BUSY; @@ -944,10 +944,10 @@ uint8_t BulkOnly::HandleUsbError(uint8_t error, uint8_t index) { // I have only ran into one device that has this firmware bug, and this is // the only clean way to get back into sync with the buggy device firmware. // --AJK - if (bAddress && bConfNum) { + if(bAddress && bConfNum) { error = pUsb->setConf(bAddress, 0, bConfNum); - if (error) + if(error) break; } return MASS_ERR_SUCCESS; @@ -999,33 +999,33 @@ uint8_t BulkOnly::Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void SetCurLUN(pcbw->bmCBWLUN); ErrorMessage (PSTR("CBW.dCBWTag"), pcbw->dCBWTag); - while ((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (CommandBlockWrapper), (uint8_t*)pcbw)) == hrBUSY) delay(1); + while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (CommandBlockWrapper), (uint8_t*)pcbw)) == hrBUSY) delay(1); ret = HandleUsbError(usberr, epDataOutIndex); //ret = HandleUsbError(pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (CommandBlockWrapper), (uint8_t*)pcbw), epDataOutIndex); - if (ret) { + if(ret) { ErrorMessage (PSTR("============================ CBW"), ret); } else { - if (bytes) { - if (!write) { + if(bytes) { + if(!write) { #if MS_WANT_PARSER - if (callback) { + if(callback) { uint8_t rbuf[bytes]; - while ((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, rbuf)) == hrBUSY) delay(1); - if (usberr == hrSUCCESS) ((USBReadParser*)buf)->Parse(bytes, rbuf, 0); + while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, rbuf)) == hrBUSY) delay(1); + if(usberr == hrSUCCESS) ((USBReadParser*)buf)->Parse(bytes, rbuf, 0); } else { #endif - while ((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*)buf)) == hrBUSY) delay(1); + while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*)buf)) == hrBUSY) delay(1); #if MS_WANT_PARSER } #endif ret = HandleUsbError(usberr, epDataInIndex); } else { - while ((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, bytes, (uint8_t*)buf)) == hrBUSY) delay(1); + while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, bytes, (uint8_t*)buf)) == hrBUSY) delay(1); ret = HandleUsbError(usberr, epDataOutIndex); } - if (ret) { + if(ret) { ErrorMessage (PSTR("============================ DAT"), ret); } } @@ -1034,13 +1034,13 @@ uint8_t BulkOnly::Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void { bytes = sizeof (CommandStatusWrapper); int tries = 2; - while (tries--) { - while ((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*) & csw)) == hrBUSY) delay(1); - if (!usberr) break; + while(tries--) { + while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*) & csw)) == hrBUSY) delay(1); + if(!usberr) break; ClearEpHalt(epDataInIndex); - if (tries) ResetRecovery(); + if(tries) ResetRecovery(); } - if (!ret) { + if(!ret) { Notify(PSTR("CBW:\t\tOK\r\n"), 0x80); Notify(PSTR("Data Stage:\tOK\r\n"), 0x80); } else { @@ -1049,11 +1049,11 @@ uint8_t BulkOnly::Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void return ret; } ret = HandleUsbError(usberr, epDataInIndex); - if (ret) { + if(ret) { ErrorMessage (PSTR("============================ CSW"), ret); } - if (usberr == hrSUCCESS) { - if (IsValidCSW(&csw, pcbw)) { + if(usberr == hrSUCCESS) { + if(IsValidCSW(&csw, pcbw)) { //ErrorMessage (PSTR("CSW.dCBWTag"), csw.dCSWTag); //ErrorMessage (PSTR("bCSWStatus"), csw.bCSWStatus); //ErrorMessage (PSTR("dCSWDataResidue"), csw.dCSWDataResidue); @@ -1082,7 +1082,7 @@ uint8_t BulkOnly::Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void * @return */ uint8_t BulkOnly::SetCurLUN(uint8_t lun) { - if (lun > bMaxLUN) + if(lun > bMaxLUN) return MASS_ERR_INVALID_LUN; bTheLUN = lun; return MASS_ERR_SUCCESS; @@ -1097,7 +1097,7 @@ uint8_t BulkOnly::SetCurLUN(uint8_t lun) { uint8_t BulkOnly::HandleSCSIError(uint8_t status) { uint8_t ret = 0; - switch (status) { + switch(status) { case 0: return MASS_ERR_SUCCESS; case 2: @@ -1113,13 +1113,13 @@ uint8_t BulkOnly::HandleSCSIError(uint8_t status) { ret = RequestSense(bTheLUN, sizeof (RequestSenseResponce), (uint8_t*) & rsp); - if (ret) { + if(ret) { return MASS_ERR_GENERAL_SCSI_ERROR; } ErrorMessage (PSTR("Response Code"), rsp.bResponseCode); - if (rsp.bResponseCode & 0x80) { + if(rsp.bResponseCode & 0x80) { Notify(PSTR("Information field: "), 0x80); - for (int i = 0; i < 4; i++) { + for(int i = 0; i < 4; i++) { D_PrintHex (rsp.CmdSpecificInformation[i], 0x80); Notify(PSTR(" "), 0x80); } @@ -1129,23 +1129,23 @@ uint8_t BulkOnly::HandleSCSIError(uint8_t status) { ErrorMessage (PSTR("Add Sense Code"), rsp.bAdditionalSenseCode); ErrorMessage (PSTR("Add Sense Qual"), rsp.bAdditionalSenseQualifier); // warning, this is not testing ASQ, only SK and ASC. - switch (rsp.bmSenseKey) { + switch(rsp.bmSenseKey) { case SCSI_S_UNIT_ATTENTION: - switch (rsp.bAdditionalSenseCode) { + switch(rsp.bAdditionalSenseCode) { case SCSI_ASC_MEDIA_CHANGED: return MASS_ERR_MEDIA_CHANGED; default: return MASS_ERR_UNIT_NOT_READY; } case SCSI_S_NOT_READY: - switch (rsp.bAdditionalSenseCode) { + switch(rsp.bAdditionalSenseCode) { case SCSI_ASC_MEDIUM_NOT_PRESENT: return MASS_ERR_NO_MEDIA; default: return MASS_ERR_UNIT_NOT_READY; } case SCSI_S_ILLEGAL_REQUEST: - switch (rsp.bAdditionalSenseCode) { + switch(rsp.bAdditionalSenseCode) { case SCSI_ASC_LBA_OUT_OF_RANGE: return MASS_ERR_BAD_LBA; default: @@ -1207,7 +1207,7 @@ void BulkOnly::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR * ep_ptr) { /* We won't be needing this... */ uint8_t BulkOnly::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, USBReadParser * prs) { #if MS_WANT_PARSER - if (!LUNOk[lun]) return MASS_ERR_NO_MEDIA; + if(!LUNOk[lun]) return MASS_ERR_NO_MEDIA; Notify(PSTR("\r\nRead (With parser)\r\n"), 0x80); Notify(PSTR("---------\r\n"), 0x80); diff --git a/masstorage.h b/masstorage.h index 6a1391a0..eb042eac 100644 --- a/masstorage.h +++ b/masstorage.h @@ -396,7 +396,7 @@ public: // Type punning can cause optimization problems and bugs. // Using reinterpret_cast to a dreinterpretifferent object is the proper way to do this. //(((BASICCDB_t *) CBWCB)->LUN) = cmd; - BASICCDB_t *x = reinterpret_cast (CBWCB); + BASICCDB_t *x = reinterpret_cast(CBWCB); x->LUN = cmd; } @@ -516,7 +516,7 @@ public: virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); virtual boolean DEVCLASSOK(uint8_t klass) { - return(klass == USB_CLASS_MASS_STORAGE); + return (klass == USB_CLASS_MASS_STORAGE); } uint8_t SCSITransaction6(CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir); diff --git a/max_LCD.cpp b/max_LCD.cpp index ce7ad683..db61ea3b 100644 --- a/max_LCD.cpp +++ b/max_LCD.cpp @@ -52,14 +52,14 @@ void Max_LCD::init() { } void Max_LCD::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) { - if (lines > 1) { + if(lines > 1) { _displayfunction |= LCD_2LINE; } _numlines = lines; _currline = 0; // for some 1 line displays you can select a 10 pixel high font - if ((dotsize != 0) && (lines == 1)) { + if((dotsize != 0) && (lines == 1)) { _displayfunction |= LCD_5x10DOTS; } @@ -123,7 +123,7 @@ void Max_LCD::home() { void Max_LCD::setCursor(uint8_t col, uint8_t row) { int row_offsets[] = {0x00, 0x40, 0x14, 0x54}; - if (row > _numlines) { + if(row > _numlines) { row = _numlines - 1; // we count rows starting w/0 } @@ -211,7 +211,7 @@ void Max_LCD::noAutoscroll(void) { void Max_LCD::createChar(uint8_t location, uint8_t charmap[]) { location &= 0x7; // we only have 8 locations 0-7 command(LCD_SETCGRAMADDR | (location << 3)); - for (int i = 0; i < 8; i++) { + for(int i = 0; i < 8; i++) { write(charmap[i]); } } @@ -224,11 +224,13 @@ inline void Max_LCD::command(uint8_t value) { } #if defined(ARDUINO) && ARDUINO >=100 + inline size_t Max_LCD::write(uint8_t value) { LCD_sendchar(value); return 1; // Assume success } #else + inline void Max_LCD::write(uint8_t value) { LCD_sendchar(value); } diff --git a/max_LCD.h b/max_LCD.h index 668ebb2d..48946a1f 100644 --- a/max_LCD.h +++ b/max_LCD.h @@ -62,8 +62,7 @@ e-mail : support@circuitsathome.com #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 -class Max_LCD : public Print -{ +class Max_LCD : public Print { USB *pUsb; public: @@ -104,4 +103,4 @@ private: uint8_t _numlines, _currline; }; -#endif \ No newline at end of file +#endif diff --git a/message.cpp b/message.cpp index 5965e51b..960a9fb4 100644 --- a/message.cpp +++ b/message.cpp @@ -22,7 +22,7 @@ e-mail : support@circuitsathome.com int UsbDEBUGlvl = 0x80; void E_Notifyc(char c, int lvl) { - if (UsbDEBUGlvl < lvl) return; + if(UsbDEBUGlvl < lvl) return; #if defined(ARDUINO) && ARDUINO >=100 USB_HOST_SERIAL.print(c); #else @@ -32,23 +32,23 @@ void E_Notifyc(char c, int lvl) { } void E_Notify(char const * msg, int lvl) { - if (UsbDEBUGlvl < lvl) return; - if (!msg) return; + if(UsbDEBUGlvl < lvl) return; + if(!msg) return; char c; - while ((c = pgm_read_byte(msg++))) E_Notifyc(c, lvl); + while((c = pgm_read_byte(msg++))) E_Notifyc(c, lvl); } void E_NotifyStr(char const * msg, int lvl) { - if (UsbDEBUGlvl < lvl) return; - if (!msg) return; + if(UsbDEBUGlvl < lvl) return; + if(!msg) return; char c; - while ((c = *msg++)) E_Notifyc(c, lvl); + while((c = *msg++)) E_Notifyc(c, lvl); } void E_Notify(uint8_t b, int lvl) { - if (UsbDEBUGlvl < lvl) return; + if(UsbDEBUGlvl < lvl) return; #if defined(ARDUINO) && ARDUINO >=100 USB_HOST_SERIAL.print(b); #else @@ -58,12 +58,13 @@ void E_Notify(uint8_t b, int lvl) { } void E_Notify(double d, int lvl) { - if (UsbDEBUGlvl < lvl) return; + if(UsbDEBUGlvl < lvl) return; USB_HOST_SERIAL.print(d); //USB_HOST_SERIAL.flush(); } #ifdef DEBUG_USB_HOST + void NotifyFailGetDevDescr(void) { Notify(PSTR("\r\ngetDevDescr "), 0x80); } @@ -71,6 +72,7 @@ void NotifyFailGetDevDescr(void) { void NotifyFailSetDevTblEntry(void) { Notify(PSTR("\r\nsetDevTblEn "), 0x80); } + void NotifyFailGetConfDescr(void) { Notify(PSTR("\r\ngetConf "), 0x80); } diff --git a/parsetools.cpp b/parsetools.cpp index 0918abef..02a7ee27 100644 --- a/parsetools.cpp +++ b/parsetools.cpp @@ -17,14 +17,14 @@ e-mail : support@circuitsathome.com #include "Usb.h" bool MultiByteValueParser::Parse(uint8_t **pp, uint16_t *pcntdn) { - if (!pBuf) { + if(!pBuf) { Notify(PSTR("Buffer pointer is NULL!\r\n"), 0x80); return false; } - for (; countDown && (*pcntdn); countDown--, (*pcntdn)--, (*pp)++) + for(; countDown && (*pcntdn); countDown--, (*pcntdn)--, (*pp)++) pBuf[valueSize - countDown] = (**pp); - if (countDown) + if(countDown) return false; countDown = valueSize; @@ -32,14 +32,14 @@ bool MultiByteValueParser::Parse(uint8_t **pp, uint16_t *pcntdn) { } bool PTPListParser::Parse(uint8_t **pp, uint16_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me) { - switch (nStage) { + switch(nStage) { case 0: pBuf->valueSize = lenSize; theParser.Initialize(pBuf); nStage = 1; case 1: - if (!theParser.Parse(pp, pcntdn)) + if(!theParser.Parse(pp, pcntdn)) return false; arLen = 0; @@ -53,11 +53,11 @@ bool PTPListParser::Parse(uint8_t **pp, uint16_t *pcntdn, PTP_ARRAY_EL_FUNC pf, nStage = 3; case 3: - for (; arLenCntdn; arLenCntdn--) { - if (!theParser.Parse(pp, pcntdn)) + for(; arLenCntdn; arLenCntdn--) { + if(!theParser.Parse(pp, pcntdn)) return false; - if (pf) + if(pf) pf(pBuf, (arLen - arLenCntdn), me); } diff --git a/parsetools.h b/parsetools.h index ab83c724..0e77de31 100644 --- a/parsetools.h +++ b/parsetools.h @@ -40,7 +40,7 @@ public: }; void Initialize(MultiValueBuffer * const pbuf) { - pBuf = (uint8_t*) pbuf->pValue; + pBuf = (uint8_t*)pbuf->pValue; countDown = valueSize = pbuf->valueSize; }; @@ -58,7 +58,7 @@ public: }; void Initialize(MultiValueBuffer *pbuf) { - pBuf = (uint8_t*) pbuf->pValue; + pBuf = (uint8_t*)pbuf->pValue; countDown = 0; }; @@ -73,7 +73,7 @@ public: if(!countDown) nStage = 0; }; - return(!countDown); + return (!countDown); }; }; diff --git a/printhex.h b/printhex.h index ed495ce9..369d7e1f 100644 --- a/printhex.h +++ b/printhex.h @@ -24,7 +24,7 @@ void E_Notifyc(char c, int lvl); template void PrintHex(T val, int lvl) { - int num_nibbles = sizeof(T) * 2; + int num_nibbles = sizeof (T) * 2; do { char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f); @@ -35,7 +35,7 @@ void PrintHex(T val, int lvl) { template void PrintBin(T val, int lvl) { - for(T mask = (((T) 1) << ((sizeof(T) << 3) - 1)); mask; mask >>= 1) + for(T mask = (((T)1) << ((sizeof (T) << 3) - 1)); mask; mask >>= 1) if(val & mask) E_Notifyc('1', lvl); else @@ -44,7 +44,7 @@ void PrintBin(T val, int lvl) { template void SerialPrintHex(T val) { - int num_nibbles = sizeof(T) * 2; + int num_nibbles = sizeof (T) * 2; do { char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f); @@ -55,7 +55,7 @@ void SerialPrintHex(T val) { template void PrintHex2(Print *prn, T val) { - T mask = (((T) 1) << (((sizeof(T) << 1) - 1) << 2)); + T mask = (((T)1) << (((sizeof (T) << 1) - 1) << 2)); while(mask > 1) { if(val < mask) @@ -63,19 +63,19 @@ void PrintHex2(Print *prn, T val) { mask >>= 4; } - prn->print((T) val, HEX); + prn->print((T)val, HEX); } template void D_PrintHex(T val, int lvl) { #ifdef DEBUG_USB_HOST - PrintHex(val, lvl); + PrintHex (val, lvl); #endif } template void D_PrintBin(T val, int lvl) { #ifdef DEBUG_USB_HOST - PrintBin(val, lvl); + PrintBin (val, lvl); #endif } diff --git a/sink_parser.h b/sink_parser.h index 033d024e..a23637d2 100644 --- a/sink_parser.h +++ b/sink_parser.h @@ -22,14 +22,19 @@ e-mail : support@circuitsathome.com extern int UsbDEBUGlvl; // This parser does absolutely nothing with the data, just swallows it. + template class SinkParser : public BASE_CLASS { - public: - SinkParser() {}; - void Initialize() {}; - void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) {}; + SinkParser() { + }; + + void Initialize() { + }; + + void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) { + }; }; diff --git a/usbhost.h b/usbhost.h index 90b4da5a..e0ddcf81 100644 --- a/usbhost.h +++ b/usbhost.h @@ -162,7 +162,7 @@ uint8_t* MAX3421e< SPI_SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* #endif SPI_SS::Set(); XMEM_RELEASE_SPI(); - return( data_p); + return ( data_p); } /* GPIO write */ /*GPIO byte is split between 2 registers, so two writes are needed to write one byte */ @@ -194,7 +194,7 @@ uint8_t MAX3421e< SPI_SS, INTR >::regRd(uint8_t reg) { uint8_t rv = SPDR; #endif XMEM_RELEASE_SPI(); - return(rv); + return (rv); } /* multiple-byte register read */ @@ -229,7 +229,7 @@ uint8_t* MAX3421e< SPI_SS, INTR >::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t* #endif SPI_SS::Set(); XMEM_RELEASE_SPI(); - return( data_p); + return ( data_p); } /* GPIO read. See gpioWr for explanation */ @@ -240,7 +240,7 @@ uint8_t MAX3421e< SPI_SS, INTR >::gpioRd() { gpin = regRd(rIOPINS2); //pins 4-7 gpin &= 0xf0; //clean lower nibble gpin |= (regRd(rIOPINS1) >> 4); //shift low bits and OR with upper from previous operation. - return( gpin); + return ( gpin); } /* reset MAX3421E. Returns number of cycles it took for PLL to stabilize after reset @@ -255,7 +255,7 @@ uint16_t MAX3421e< SPI_SS, INTR >::reset() { break; } } - return( i); + return ( i); } /* initialize MAX3421E. Set Host mode, pullups, and stuff. Returns 0 if success, -1 if not */ @@ -276,7 +276,7 @@ int8_t MAX3421e< SPI_SS, INTR >::Init() { regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL)); if(reset() == 0) { //OSCOKIRQ hasn't asserted in time - return( -1); + return ( -1); } regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); // set pull-downs, Host @@ -292,7 +292,7 @@ int8_t MAX3421e< SPI_SS, INTR >::Init() { regWr(rHIRQ, bmCONDETIRQ); //clear connection detect interrupt regWr(rCPUCTL, 0x01); //enable interrupt pin - return( 0); + return ( 0); } /* initialize MAX3421E. Set Host mode, pullups, and stuff. Returns 0 if success, -1 if not */ @@ -312,7 +312,7 @@ int8_t MAX3421e< SPI_SS, INTR >::Init(int mseconds) { regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL | GPX_VBDET)); if(reset() == 0) { //OSCOKIRQ hasn't asserted in time - return( -1); + return ( -1); } // Delay a minimum of 1 second to ensure any capacitors are drained. @@ -336,7 +336,7 @@ int8_t MAX3421e< SPI_SS, INTR >::Init(int mseconds) { // GPX pin on. This is done here so that busprobe will fail if we have a switch connected. regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL)); - return( 0); + return ( 0); } /* probe bus to determine device presence and speed and switch host to this speed */ @@ -391,7 +391,7 @@ uint8_t MAX3421e< SPI_SS, INTR >::Task(void) { // GpxHandler(); // } // usbSM(); //USB state machine - return( rcode); + return ( rcode); } template< typename SPI_SS, typename INTR > @@ -408,7 +408,7 @@ uint8_t MAX3421e< SPI_SS, INTR >::IntHandler() { } /* End HIRQ interrupts handling, clear serviced IRQs */ regWr(rHIRQ, HIRQ_sendback); - return( HIRQ_sendback); + return ( HIRQ_sendback); } //template< typename SPI_SS, typename INTR > //uint8_t MAX3421e< SPI_SS, INTR >::GpxHandler() diff --git a/usbhub.cpp b/usbhub.cpp index 0e49c401..82fc30f5 100644 --- a/usbhub.cpp +++ b/usbhub.cpp @@ -35,7 +35,7 @@ bPollEnable(false) { epInfo[1].epAttribs = 0; epInfo[1].bmNakPower = USB_NAK_NOWAIT; - if (pUsb) + if(pUsb) pUsb->RegisterDeviceClass(this); } @@ -57,133 +57,133 @@ uint8_t USBHub::Init(uint8_t parent, uint8_t port, bool lowspeed) { //switch (bInitState) { // case 0: - if (bAddress) - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; + if(bAddress) + return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); + // Get pointer to pseudo device with address 0 assigned + p = addrPool.GetUsbDevicePtr(0); - if (!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; + if(!p) + return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - if (!p->epinfo) - return USB_ERROR_EPINFO_IS_NULL; + if(!p->epinfo) + return USB_ERROR_EPINFO_IS_NULL; - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; + // Save old pointer to EP_RECORD of address 0 + oldep_ptr = p->epinfo; - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; + // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence + p->epinfo = epInfo; - p->lowspeed = lowspeed; + p->lowspeed = lowspeed; - // Get device descriptor - rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); + // Get device descriptor + rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); - p->lowspeed = false; + p->lowspeed = false; - if (!rcode) - len = (buf[0] > 32) ? 32 : buf[0]; + if(!rcode) + len = (buf[0] > 32) ? 32 : buf[0]; - if (rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - return rcode; - } + if(rcode) { + // Restore p->epinfo + p->epinfo = oldep_ptr; + return rcode; + } - // Extract device class from device descriptor - // If device class is not a hub return - if (udd->bDeviceClass != 0x09) - return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; + // Extract device class from device descriptor + // If device class is not a hub return + if(udd->bDeviceClass != 0x09) + return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, (udd->bDeviceClass == 0x09) ? true : false, port); + // Allocate new address according to device class + bAddress = addrPool.AllocAddress(parent, (udd->bDeviceClass == 0x09) ? true : false, port); - if (!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; + if(!bAddress) + return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; + // Extract Max Packet Size from the device descriptor + epInfo[0].maxPktSize = udd->bMaxPacketSize0; - // Assign new address to the device - rcode = pUsb->setAddr(0, 0, bAddress); + // Assign new address to the device + rcode = pUsb->setAddr(0, 0, bAddress); - if (rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - addrPool.FreeAddress(bAddress); - bAddress = 0; - return rcode; - } + if(rcode) { + // Restore p->epinfo + p->epinfo = oldep_ptr; + addrPool.FreeAddress(bAddress); + bAddress = 0; + return rcode; + } - //USBTRACE2("\r\nHub address: ", bAddress ); + //USBTRACE2("\r\nHub address: ", bAddress ); - // Restore p->epinfo - p->epinfo = oldep_ptr; + // Restore p->epinfo + p->epinfo = oldep_ptr; - if (len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); + if(len) + rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - if (rcode) - goto FailGetDevDescr; + if(rcode) + goto FailGetDevDescr; - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, 2, epInfo); + // Assign epInfo to epinfo pointer + rcode = pUsb->setEpInfoEntry(bAddress, 2, epInfo); - if (rcode) - goto FailSetDevTblEntry; + if(rcode) + goto FailSetDevTblEntry; // bInitState = 1; // case 1: - // Get hub descriptor - rcode = GetHubDescriptor(0, 8, buf); + // Get hub descriptor + rcode = GetHubDescriptor(0, 8, buf); - if (rcode) - goto FailGetHubDescr; + if(rcode) + goto FailGetHubDescr; - // Save number of ports for future use - bNbrPorts = hd->bNbrPorts; + // Save number of ports for future use + bNbrPorts = hd->bNbrPorts; // bInitState = 2; // case 2: - // Read configuration Descriptor in Order To Obtain Proper Configuration Value - rcode = pUsb->getConfDescr(bAddress, 0, 8, 0, buf); + // Read configuration Descriptor in Order To Obtain Proper Configuration Value + rcode = pUsb->getConfDescr(bAddress, 0, 8, 0, buf); - if (!rcode) { - cd_len = ucd->wTotalLength; - rcode = pUsb->getConfDescr(bAddress, 0, cd_len, 0, buf); - } - if (rcode) - goto FailGetConfDescr; + if(!rcode) { + cd_len = ucd->wTotalLength; + rcode = pUsb->getConfDescr(bAddress, 0, cd_len, 0, buf); + } + if(rcode) + goto FailGetConfDescr; - // The following code is of no practical use in real life applications. - // It only intended for the usb protocol sniffer to properly parse hub-class requests. - { - uint8_t buf2[24]; + // The following code is of no practical use in real life applications. + // It only intended for the usb protocol sniffer to properly parse hub-class requests. + { + uint8_t buf2[24]; - rcode = pUsb->getConfDescr(bAddress, 0, buf[0], 0, buf2); + rcode = pUsb->getConfDescr(bAddress, 0, buf[0], 0, buf2); - if (rcode) - goto FailGetConfDescr; - } + if(rcode) + goto FailGetConfDescr; + } - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, buf[5]); + // Set Configuration Value + rcode = pUsb->setConf(bAddress, 0, buf[5]); - if (rcode) - goto FailSetConfDescr; + if(rcode) + goto FailSetConfDescr; // bInitState = 3; // case 3: - // Power on all ports - for (uint8_t j = 1; j <= bNbrPorts; j++) - SetPortFeature(HUB_FEATURE_PORT_POWER, j, 0); //HubPortPowerOn(j); + // Power on all ports + for(uint8_t j = 1; j <= bNbrPorts; j++) + SetPortFeature(HUB_FEATURE_PORT_POWER, j, 0); //HubPortPowerOn(j); - pUsb->SetHubPreMask(); - bPollEnable = true; + pUsb->SetHubPreMask(); + bPollEnable = true; // bInitState = 0; //} //bInitState = 0; @@ -214,7 +214,7 @@ Fail: uint8_t USBHub::Release() { pUsb->GetAddressPool().FreeAddress(bAddress); - if (bAddress == 0x41) + if(bAddress == 0x41) pUsb->SetHubPreMask(); bAddress = 0; @@ -227,10 +227,10 @@ uint8_t USBHub::Release() { uint8_t USBHub::Poll() { uint8_t rcode = 0; - if (!bPollEnable) + if(!bPollEnable) return 0; - if (qNextPollTime <= millis()) { + if(qNextPollTime <= millis()) { rcode = CheckHubStatus(); qNextPollTime = millis() + 100; } @@ -244,7 +244,7 @@ uint8_t USBHub::CheckHubStatus() { rcode = pUsb->inTransfer(bAddress, 1, &read, buf); - if (rcode) + if(rcode) return rcode; //if (buf[0] & 0x01) // Hub Status Change @@ -258,36 +258,36 @@ uint8_t USBHub::CheckHubStatus() { // return rcode; // } //} - for (uint8_t port = 1, mask = 0x02; port < 8; mask <<= 1, port++) { - if (buf[0] & mask) { + for(uint8_t port = 1, mask = 0x02; port < 8; mask <<= 1, port++) { + if(buf[0] & mask) { HubEvent evt; evt.bmEvent = 0; rcode = GetPortStatus(port, 4, evt.evtBuff); - if (rcode) + if(rcode) continue; rcode = PortStatusChange(port, evt); - if (rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) + if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) return 0; - if (rcode) + if(rcode) return rcode; } } // for - for (uint8_t port = 1; port <= bNbrPorts; port++) { + for(uint8_t port = 1; port <= bNbrPorts; port++) { HubEvent evt; evt.bmEvent = 0; rcode = GetPortStatus(port, 4, evt.evtBuff); - if (rcode) + if(rcode) continue; - if ((evt.bmStatus & bmHUB_PORT_STATE_CHECK_DISABLED) != bmHUB_PORT_STATE_DISABLED) + if((evt.bmStatus & bmHUB_PORT_STATE_CHECK_DISABLED) != bmHUB_PORT_STATE_DISABLED) continue; // Emulate connection event for the port @@ -295,10 +295,10 @@ uint8_t USBHub::CheckHubStatus() { rcode = PortStatusChange(port, evt); - if (rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) + if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) return 0; - if (rcode) + if(rcode) return rcode; } // for return 0; @@ -314,10 +314,10 @@ void USBHub::ResetHubPort(uint8_t port) { SetPortFeature(HUB_FEATURE_PORT_RESET, port, 0); - for (int i = 0; i < 3; i++) { + for(int i = 0; i < 3; i++) { rcode = GetPortStatus(port, 4, evt.evtBuff); - if (rcode) break; // Some kind of error, bail. - if (evt.bmEvent == bmHUB_PORT_EVENT_RESET_COMPLETE || evt.bmEvent == bmHUB_PORT_EVENT_LS_RESET_COMPLETE) { + if(rcode) break; // Some kind of error, bail. + if(evt.bmEvent == bmHUB_PORT_EVENT_RESET_COMPLETE || evt.bmEvent == bmHUB_PORT_EVENT_LS_RESET_COMPLETE) { break; } delay(100); // simulate polling. @@ -328,11 +328,11 @@ void USBHub::ResetHubPort(uint8_t port) { } uint8_t USBHub::PortStatusChange(uint8_t port, HubEvent &evt) { - switch (evt.bmEvent) { + switch(evt.bmEvent) { // Device connected event case bmHUB_PORT_EVENT_CONNECT: case bmHUB_PORT_EVENT_LS_CONNECT: - if (bResetInitiated) + if(bResetInitiated) return 0; ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0); @@ -379,7 +379,7 @@ void PrintHubPortStatus(USBHub *hubptr, uint8_t addr, uint8_t port, bool print_c rcode = hubptr->GetPortStatus(port, 4, evt.evtBuff); - if (rcode) { + if(rcode) { USB_HOST_SERIAL.println("ERROR!"); return; } @@ -408,7 +408,7 @@ void PrintHubPortStatus(USBHub *hubptr, uint8_t addr, uint8_t port, bool print_c USB_HOST_SERIAL.print("INDICATOR:\t"); USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_INDICATOR) > 0, DEC); - if (!print_changes) + if(!print_changes) return; USB_HOST_SERIAL.println("\r\nChange"); diff --git a/usbhub.h b/usbhub.h index 2fc5ff64..aa1281b2 100644 --- a/usbhub.h +++ b/usbhub.h @@ -170,7 +170,7 @@ class USBHub : USBDeviceConfig { uint8_t bAddress; // address uint8_t bNbrPorts; // number of ports -// uint8_t bInitState; // initialization state variable + // uint8_t bInitState; // initialization state variable uint32_t qNextPollTime; // next poll time bool bPollEnable; // poll enable flag @@ -195,52 +195,56 @@ public: virtual uint8_t Release(); virtual uint8_t Poll(); virtual void ResetHubPort(uint8_t port); + virtual uint8_t GetAddress() { return bAddress; }; - virtual boolean DEVCLASSOK(uint8_t klass) { return (klass == 0x09); } + + virtual boolean DEVCLASSOK(uint8_t klass) { + return (klass == 0x09); + } }; // Clear Hub Feature inline uint8_t USBHub::ClearHubFeature(uint8_t fid) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_HUB_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_HUB_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); } // Clear Port Feature inline uint8_t USBHub::ClearPortFeature(uint8_t fid, uint8_t port, uint8_t sel) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_PORT_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, ((0x0000 | port) | (sel << 8)), 0, 0, NULL, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_PORT_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, ((0x0000 | port) | (sel << 8)), 0, 0, NULL, NULL)); } // Get Hub Descriptor inline uint8_t USBHub::GetHubDescriptor(uint8_t index, uint16_t nbytes, uint8_t *dataptr) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_DESCRIPTOR, USB_REQUEST_GET_DESCRIPTOR, index, 0x29, 0, nbytes, nbytes, dataptr, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_DESCRIPTOR, USB_REQUEST_GET_DESCRIPTOR, index, 0x29, 0, nbytes, nbytes, dataptr, NULL)); } // Get Hub Status inline uint8_t USBHub::GetHubStatus(uint16_t nbytes, uint8_t* dataptr) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_STATUS, USB_REQUEST_GET_STATUS, 0, 0, 0x0000, nbytes, nbytes, dataptr, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_STATUS, USB_REQUEST_GET_STATUS, 0, 0, 0x0000, nbytes, nbytes, dataptr, NULL)); } // Get Port Status inline uint8_t USBHub::GetPortStatus(uint8_t port, uint16_t nbytes, uint8_t* dataptr) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_PORT_STATUS, USB_REQUEST_GET_STATUS, 0, 0, port, nbytes, nbytes, dataptr, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_PORT_STATUS, USB_REQUEST_GET_STATUS, 0, 0, port, nbytes, nbytes, dataptr, NULL)); } // Set Hub Descriptor inline uint8_t USBHub::SetHubDescriptor(uint8_t port, uint16_t nbytes, uint8_t* dataptr) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_DESCRIPTOR, USB_REQUEST_SET_DESCRIPTOR, 0, 0, port, nbytes, nbytes, dataptr, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_DESCRIPTOR, USB_REQUEST_SET_DESCRIPTOR, 0, 0, port, nbytes, nbytes, dataptr, NULL)); } // Set Hub Feature inline uint8_t USBHub::SetHubFeature(uint8_t fid) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); } // Set Port Feature inline uint8_t USBHub::SetPortFeature(uint8_t fid, uint8_t port, uint8_t sel) { - return( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_PORT_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, (((0x0000 | sel) << 8) | port), 0, 0, NULL, NULL)); + return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_PORT_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, (((0x0000 | sel) << 8) | port), 0, 0, NULL, NULL)); } void PrintHubPortStatus(USB *usbptr, uint8_t addr, uint8_t port, bool print_changes = false); diff --git a/xboxEnums.h b/xboxEnums.h index adf60f9b..fa4b6c2c 100644 --- a/xboxEnums.h +++ b/xboxEnums.h @@ -61,4 +61,4 @@ const uint16_t XBOXBUTTONS[] PROGMEM = { 0x0008 // SYNC }; -#endif \ No newline at end of file +#endif From d29a00d7615988e6b0c350268a41c2b72751963a Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Wed, 25 Dec 2013 05:24:59 -0500 Subject: [PATCH 053/145] fix mid button and struct --- hidboot.cpp | 2 +- hidboot.h | 2 +- settings.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/hidboot.cpp b/hidboot.cpp index 4b62d423..c32443bb 100644 --- a/hidboot.cpp +++ b/hidboot.cpp @@ -85,7 +85,7 @@ void MouseReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *bu // event = true; } - if(prevState.mouseInfo.bmMiddleButton != prevState.mouseInfo.bmMiddleButton) { + if(prevState.mouseInfo.bmMiddleButton != pmi->bmMiddleButton) { if(pmi->bmMiddleButton) { OnMiddleButtonDown(pmi); } else { diff --git a/hidboot.h b/hidboot.h index 00c4d9db..2218eb9e 100644 --- a/hidboot.h +++ b/hidboot.h @@ -42,7 +42,7 @@ struct MOUSEINFO { uint8_t bmLeftButton : 1; uint8_t bmRightButton : 1; uint8_t bmMiddleButton : 1; - uint8_t bmDummy : 1; + uint8_t bmDummy : 5; }; int8_t dX; int8_t dY; diff --git a/settings.h b/settings.h index f7914b2a..5f876d9d 100644 --- a/settings.h +++ b/settings.h @@ -14,7 +14,7 @@ //////////////////////////////////////////////////////////////////////////////// /* Set this to 1 to activate serial debugging */ -#define ENABLE_UHS_DEBUGGING 0 +#define ENABLE_UHS_DEBUGGING 1 /* This can be used to select which serial port to use for debugging if * multiple serial ports are available. From 8a9f16ed38b532f33042a6afe5d0564231f62691 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 26 Dec 2013 11:21:31 -0500 Subject: [PATCH 054/145] HID BOOT Verified. Flick debug off. --- settings.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/settings.h b/settings.h index 5f876d9d..f7914b2a 100644 --- a/settings.h +++ b/settings.h @@ -14,7 +14,7 @@ //////////////////////////////////////////////////////////////////////////////// /* Set this to 1 to activate serial debugging */ -#define ENABLE_UHS_DEBUGGING 1 +#define ENABLE_UHS_DEBUGGING 0 /* This can be used to select which serial port to use for debugging if * multiple serial ports are available. From 3ee654bb125d6943feee0223f9c271a32ad99b9d Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Sat, 28 Dec 2013 14:43:21 -0500 Subject: [PATCH 055/145] Very small optimization. --- usbhost.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/usbhost.h b/usbhost.h index e0ddcf81..adfff592 100644 --- a/usbhost.h +++ b/usbhost.h @@ -153,9 +153,10 @@ uint8_t* MAX3421e< SPI_SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* data_p += nbytes; #else SPDR = (reg | 0x02); //set WR bit and send register number - while(nbytes--) { + while(nbytes) { while(!(SPSR & (1 << SPIF))); //check if previous byte was sent SPDR = (*data_p); // send next data byte + nbytes--; data_p++; // advance data pointer } while(!(SPSR & (1 << SPIF))); From 5426cb1fb6e3363bfd5f44504e00fdcfe8682162 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Sun, 29 Dec 2013 22:55:03 -0500 Subject: [PATCH 056/145] Fix annoying warning generated on newer GCC versions. --- examples/HID/USBHID_desc/USBHID_desc.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/HID/USBHID_desc/USBHID_desc.ino b/examples/HID/USBHID_desc/USBHID_desc.ino index d3558a8e..806936f9 100644 --- a/examples/HID/USBHID_desc/USBHID_desc.ino +++ b/examples/HID/USBHID_desc/USBHID_desc.ino @@ -24,10 +24,10 @@ uint8_t HIDUniversal2::OnInitSuccessful() HexDumper Hex; ReportDescParser Rpt; - if (rcode = GetReportDescr(0, &Hex)) + if ((rcode = GetReportDescr(0, &Hex))) goto FailGetReportDescr1; - if (rcode = GetReportDescr(0, &Rpt)) + if ((rcode = GetReportDescr(0, &Rpt))) goto FailGetReportDescr2; return 0; From 14fda1372c83b21854a563201e45844d0a1fe9cd Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Sun, 29 Dec 2013 23:53:24 -0500 Subject: [PATCH 057/145] Fix annoying warnings and provide an optimization. --- BTD.h | 16 ++++++++++++++++ BTHID.cpp | 3 ++- PS3BT.cpp | 3 ++- SPP.cpp | 3 ++- Wii.cpp | 3 ++- 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/BTD.h b/BTD.h index e870427d..e5b06499 100755 --- a/BTD.h +++ b/BTD.h @@ -191,6 +191,22 @@ #define PAIR 1 +/* acl_handle_ok or it's a new connection */ +#if 0 +#define UHS_ACL_HANDLE_OK(x, y) ((uint16_t)(x[0]) | (uint16_t)(x[1] << 8)) == (y | 0x2000U) +#else +/* + * Better implementation. + * o One place for this code, it is reused four times in the source. + * Perhaps it is better as a function. + * o This should be faster since the && operation can early exit, this means + * the shift would only be performed if the first byte matches. + * o Casting is eliminated. + * o How does this compare in code size? No difference. It is a free optimization. + */ +#define UHS_ACL_HANDLE_OK(x, y) ((x[0] == (y & 0xff)) && (x[1] == ((y >> 8) | 0x20))) +#endif + /** All Bluetooth services should inherit this class. */ class BluetoothService { public: diff --git a/BTHID.cpp b/BTHID.cpp index 39575aea..b240ec68 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -67,7 +67,8 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { } } } - if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + //if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if(UHS_ACL_HANDLE_OK(l2capinbuf, hci_handle)) { // acl_handle_ok or it's a new connection if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST diff --git a/PS3BT.cpp b/PS3BT.cpp index fbcb5dfc..103d71ae 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -250,7 +250,8 @@ void PS3BT::ACLData(uint8_t* ACLData) { } } } - if((ACLData[0] | (uint16_t)ACLData[1] << 8) == (hci_handle | 0x2000U)) { //acl_handle_ok + //if((ACLData[0] | (uint16_t)ACLData[1] << 8) == (hci_handle | 0x2000U)) { //acl_handle_ok + if(UHS_ACL_HANDLE_OK(ACLData, hci_handle)) { //acl_handle_ok memcpy(l2capinbuf, ACLData, BULK_MAXPKTSIZE); if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { diff --git a/SPP.cpp b/SPP.cpp index ff75c9cb..ef0cf216 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -97,7 +97,8 @@ void SPP::ACLData(uint8_t* l2capinbuf) { } } } - if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok + //if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok + if(UHS_ACL_HANDLE_OK(l2capinbuf, hci_handle)) { // acl_handle_ok if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST diff --git a/Wii.cpp b/Wii.cpp index 1fbd95f4..6a6f9f21 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -144,7 +144,8 @@ void WII::ACLData(uint8_t* l2capinbuf) { } } } - if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + //if((l2capinbuf[0] | (uint16_t)l2capinbuf[1] << 8) == (hci_handle | 0x2000U)) { // acl_handle_ok or it's a new connection + if(UHS_ACL_HANDLE_OK(l2capinbuf, hci_handle)) { // acl_handle_ok or it's a new connection if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { //l2cap_control - Channel ID for ACL-U if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) { #ifdef DEBUG_USB_HOST From 8ae6f8bb1d92db0052e9f81e7d90bc2d42433239 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 30 Dec 2013 16:05:50 +0100 Subject: [PATCH 058/145] Updated comments - especially in BTHID.h --- BTD.h | 2 +- BTHID.h | 25 ++++++++++++++++--------- PS3BT.h | 4 ++-- Wii.h | 6 +++--- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/BTD.h b/BTD.h index e5b06499..bacd38c3 100755 --- a/BTD.h +++ b/BTD.h @@ -286,7 +286,7 @@ public: */ virtual boolean DEVCLASSOK(uint8_t klass) { return (klass == USB_CLASS_WIRELESS_CTRL); - } + }; /** * Used by the USB core to check what this driver support. diff --git a/BTHID.h b/BTHID.h index e8842e6b..90fbf54f 100644 --- a/BTHID.h +++ b/BTHID.h @@ -42,11 +42,11 @@ public: * @param ACLData Incoming acldata. */ virtual void ACLData(uint8_t* ACLData); - /** Used to run part of the state maschine. */ + /** Used to run part of the state machine. */ virtual void Run(); /** Use this to reset the service. */ virtual void Reset(); - /** Used this to disconnect any of the controllers. */ + /** Used this to disconnect the devices. */ virtual void disconnect(); /**@}*/ @@ -60,24 +60,31 @@ public: return true; }; + /** + * Set HID protocol mode. + * @param mode HID protocol to use. Either HID_BOOT_PROTOCOL or HID_RPT_PROTOCOL. + */ void setProtocolMode(uint8_t mode) { protocolMode = mode; }; - /** Used to set the leds on a keyboard */ + /** + * Used to set the leds on a keyboard. + * @param data See KBDLEDS in hidboot.h + */ void setLeds(uint8_t data); /** True if a device is connected */ bool connected; - /** Call this to start the paring sequence with a controller */ + /** Call this to start the paring sequence with a device */ void pair(void) { if(pBtd) pBtd->pairWithHID(); }; /** - * Used to call your own function when the controller is successfully initialized. + * Used to call your own function when the device is successfully initialized. * @param funcOnInit Function to call. */ void attachOnInit(void (*funcOnInit)(void)) { @@ -87,28 +94,28 @@ public: private: BTD *pBtd; // Pointer to BTD instance - HIDReportParser *pRptParser[NUM_PARSERS]; + HIDReportParser *pRptParser[NUM_PARSERS]; // Pointer to HIDReportParsers. /** Set report protocol. */ void setProtocol(); uint8_t protocolMode; /** - * Called when the controller is successfully initialized. + * Called when a device is successfully initialized. * Use attachOnInit(void (*funcOnInit)(void)) to call your own function. * This is useful for instance if you want to set the LEDs in a specific way. */ void onInit() { if(pFuncOnInit) pFuncOnInit(); // Call the user function - } + }; void (*pFuncOnInit)(void); // Pointer to function called in onInit() void L2CAP_task(); // L2CAP state machine /* Variables filled from HCI event management */ uint16_t hci_handle; - bool activeConnection; // Used to indicate if it's already has established a connection + bool activeConnection; // Used to indicate if it already has established a connection /* Variables used by high level L2CAP task */ uint8_t l2cap_state; diff --git a/PS3BT.h b/PS3BT.h index ff441a2c..b8725b00 100644 --- a/PS3BT.h +++ b/PS3BT.h @@ -46,7 +46,7 @@ public: * @param ACLData Incoming acldata. */ virtual void ACLData(uint8_t* ACLData); - /** Used to run part of the state maschine. */ + /** Used to run part of the state machine. */ virtual void Run(); /** Use this to reset the service. */ virtual void Reset(); @@ -147,7 +147,7 @@ public: /** Turn all LEDs off. */ void setLedOff() { setLedRaw(0); - } + }; /** * Turn the specific ::LED off. * @param a The ::LED to turn off. diff --git a/Wii.h b/Wii.h index ead789c9..427242bb 100755 --- a/Wii.h +++ b/Wii.h @@ -63,7 +63,7 @@ public: * @param ACLData Incoming acldata. */ virtual void ACLData(uint8_t* ACLData); - /** Used to run part of the state maschine. */ + /** Used to run part of the state machine. */ virtual void Run(); /** Use this to reset the service. */ virtual void Reset(); @@ -90,7 +90,7 @@ public: void pair(void) { if(pBtd) pBtd->pairWithWiimote(); - } + }; /** * Used to read the joystick of the Nunchuck. * @param a Either ::HatX or ::HatY. @@ -152,7 +152,7 @@ public: /** Turn all LEDs off. */ void setLedOff() { setLedRaw(0); - } + }; /** * Turn the specific ::LED off. * @param a The ::LED to turn off. From 2283753ba1f2269f5cec79d398876fa3494811e7 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 30 Dec 2013 16:08:03 +0100 Subject: [PATCH 059/145] Check id values when GetReportParser and SetReportParser are called --- BTHID.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/BTHID.h b/BTHID.h index 90fbf54f..3e9c0394 100644 --- a/BTHID.h +++ b/BTHID.h @@ -51,11 +51,26 @@ public: /**@}*/ + /** + * Get HIDReportParser. + * @param id ID of parser. + * @return Returns the corresponding HIDReportParser. Returns NULL if id is not valid. + */ HIDReportParser *GetReportParser(uint8_t id) { + if (id >= NUM_PARSERS) + return NULL; return pRptParser[id]; }; + /** + * Set HIDReportParser to be used. + * @param id Id of parser. + * @param prs Pointer to HIDReportParser. + * @return Returns true if the HIDReportParser is set. False otherwise. + */ bool SetReportParser(uint8_t id, HIDReportParser *prs) { + if (id >= NUM_PARSERS) + return false; pRptParser[id] = prs; return true; }; From fcdf6abfa02893afb44de99e5548dd0ce6ed51e8 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 30 Dec 2013 16:11:19 +0100 Subject: [PATCH 060/145] Check protocol in setProtocol before sending it to the device --- BTHID.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index b240ec68..3a84ed2d 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -48,7 +48,7 @@ void BTHID::Reset() { l2cap_state = L2CAP_WAIT; } -void BTHID::disconnect() { // Use this void to disconnect any of the controllers +void BTHID::disconnect() { // Use this void to disconnect the device // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection pBtd->l2cap_disconnection_request(hci_handle, ++identifier, interrupt_scid, interrupt_dcid); Reset(); @@ -383,7 +383,13 @@ void BTHID::setProtocol() { Notify(PSTR("\r\nSet protocol mode: "), 0x80); D_PrintHex (protocolMode, 0x80); #endif - uint8_t command = 0x70 | protocolMode; // Set Protocol, see HID specs page 33 + if (protocolMode != HID_BOOT_PROTOCOL && protocolMode != HID_RPT_PROTOCOL) { +#ifdef DEBUG_USB_HOST + Notify(PSTR("\r\nNot a valid protocol mode. Using Boot protocol instead."), 0x80); +#endif + protocolMode = HID_BOOT_PROTOCOL; // Use Boot Protocol by default + } + uint8_t command = 0x70 | protocolMode; // Set Protocol, see Bluetooth HID specs page 33 pBtd->L2CAP_Command(hci_handle, &command, 1, control_scid[0], control_scid[1]); } From f676812f84b3212779365b9950927a01209e4045 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 30 Dec 2013 16:19:34 +0100 Subject: [PATCH 061/145] Code for the Wii IR camera needs to be activated in settings.h now Also cleaned up README.md a bit --- README.md | 17 +++++++++++----- Wii.h | 5 +---- WiiCameraReadme.md | 2 +- .../Bluetooth/WiiIRCamera/WiiIRCamera.ino | 2 +- settings.h | 20 ++++++++++++++----- 5 files changed, 30 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 59c98caf..95ba475a 100644 --- a/README.md +++ b/README.md @@ -86,8 +86,8 @@ The [BTD library](BTD.cpp) is a general purpose library for an ordinary Bluetoot 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. Some different examples can be found in the [example directory](examples/Bluetooth). -The BTD library will also make it possible to use multiple services at once, the following example sketch is an example of this: -. +The BTD library also makes it possible to use multiple services at once, the following example sketch is an example of this: +[PS3SPP.ino](examples/Bluetooth/PS3SPP/PS3SPP.ino). ### [BTHID library](BTHID.cpp) @@ -95,13 +95,15 @@ The [Bluetooth HID library](BTHID.cpp) allows you to connect HID devices via Blu Currently HID mice and keyboards are supported. -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: for more information. +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. ### [SPP library](SPP.cpp) 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. It has been tested successfully on Windows, Mac OS X, Linux, and Android. +Take a look at the [SPP.ino](examples/Bluetooth/SPP/SPP.ino) example for more information. + More information can be found at these blog posts: * @@ -116,7 +118,7 @@ These libraries consist of the [PS3BT](PS3BT.cpp) and [PS3USB](PS3USB.cpp). Thes 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 plugging the controller in via USB and letting the library set it automatically. -__Note:__ To obtain the address you have to plug in the Bluetooth dongle before connecting the controller, or alternatively you could set it in code like so: . +__Note:__ To obtain the address you have to plug in the Bluetooth dongle before connecting the controller, or alternatively you could set it in code like so: [PS3BT.ino#L20](examples/Bluetooth/PS3BT/PS3BT.ino#L20). For more information about the PS3 protocol see the official wiki: . @@ -195,12 +197,17 @@ WII Wii(&Btd); Then just press any button on the Wiimote and it will then connect to the dongle. -Take a look at the example for more information: . +Take a look at the example for more information: [Wii.ino](examples/Bluetooth/Wii/Wii.ino). Also take a look at the blog post: * +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). + +The [WiiIRCamera.ino](examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino) example shows how it can be used. + + All the information about the Wii controllers are from these sites: * diff --git a/Wii.h b/Wii.h index 427242bb..26c81fe5 100755 --- a/Wii.h +++ b/Wii.h @@ -23,9 +23,6 @@ #include "BTD.h" #include "controllerEnums.h" -/** You will have to uncomment this to use the IR camera */ -//#define WIICAMERA - /* Wii event flags */ #define WII_FLAG_MOTION_PLUS_CONNECTED 0x01 #define WII_FLAG_NUNCHUCK_CONNECTED 0x02 @@ -281,7 +278,7 @@ public: #ifdef WIICAMERA /** @name Wiimote IR camera functions - * You will have to uncomment #WIICAMERA in Wii.h to use the IR camera. + * You will have to set ENABLE_WII_IR_CAMERA in settings.h to 1 in order use the IR camera. */ /** Initialises the camera as per the steps from: http://wiibrew.org/wiki/Wiimote#IR_Camera */ void IRinitialize(); diff --git a/WiiCameraReadme.md b/WiiCameraReadme.md index d3fc11ae..2309b4f9 100644 --- a/WiiCameraReadme.md +++ b/WiiCameraReadme.md @@ -2,7 +2,7 @@ Please see for the complete capabili This library is large, if you run into memory problems when uploading to the Arduino, disable serial debugging. -To enable the IR camera code, uncomment \#define WIICAMERA in Wii.h. +To enable the IR camera code, simply set ```ENABLE_WII_IR_CAMERA``` to 1 in [settings.h](settings.h). This library implements the following settings: diff --git a/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino b/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino index 5e49fad1..e7ca456b 100644 --- a/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino +++ b/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino @@ -19,7 +19,7 @@ Otherwise, wire up a IR LED yourself. #endif #ifndef WIICAMERA // Used to check if WIICAMERA is defined -#error "Uncomment WIICAMERA in Wii.h to use this example" +#error "Please set ENABLE_WII_IR_CAMERA to 1 in settings.h" #endif USB Usb; diff --git a/settings.h b/settings.h index f7914b2a..424a5bcf 100644 --- a/settings.h +++ b/settings.h @@ -37,6 +37,13 @@ /* Set this to a one to use the xmem2 lock. This is needed for multitasking and threading */ #define USE_XMEM_SPI_LOCK 0 +//////////////////////////////////////////////////////////////////////////////// +// Wii IR camera +//////////////////////////////////////////////////////////////////////////////// + +/* Set this to 1 to activate code for the Wii IR camera */ +#define ENABLE_WII_IR_CAMERA 0 + //////////////////////////////////////////////////////////////////////////////// // MASS STORAGE //////////////////////////////////////////////////////////////////////////////// @@ -47,7 +54,6 @@ #define MASS_MAX_SUPPORTED_LUN 8 #endif - //////////////////////////////////////////////////////////////////////////////// // Set to 1 to use the faster spi4teensy3 driver. //////////////////////////////////////////////////////////////////////////////// @@ -62,10 +68,6 @@ // No user serviceable parts below this line. // DO NOT change anything below here unless you are a developer! -#if !defined(DEBUG_USB_HOST) && ENABLE_UHS_DEBUGGING -#define DEBUG_USB_HOST -#endif - // When will we drop support for the older bug-ridden stuff? #if defined(ARDUINO) && ARDUINO >=100 #include @@ -93,6 +95,14 @@ #endif #endif +#if !defined(DEBUG_USB_HOST) && ENABLE_UHS_DEBUGGING +#define DEBUG_USB_HOST +#endif + +#if !defined(WIICAMERA) && ENABLE_WII_IR_CAMERA +#define WIICAMERA +#endif + #if USE_XMEM_SPI_LOCK | defined(USE_MULTIPLE_APP_API) #include #else From ec38c7879949b6a61ae152960cde26c80729517b Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 30 Dec 2013 16:48:15 +0100 Subject: [PATCH 062/145] Added support for Joytech controller in XBOXRECV and Madcatz controllers in XBOXUSB --- XBOXRECV.cpp | 2 +- XBOXUSB.cpp | 2 +- XBOXUSB.h | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index 2db24c72..c4bf33b9 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -88,7 +88,7 @@ uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) { VID = udd->idVendor; PID = udd->idProduct; - if((VID != XBOX_VID && VID != MADCATZ_VID) || (PID != XBOX_WIRELESS_RECEIVER_PID && PID != XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID)) { // Check if it's a Xbox receiver using the Vendor ID and Product ID + if((VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_WIRELESS_RECEIVER_PID && PID != XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID)) { // Check if it's a Xbox receiver using the Vendor ID and Product ID #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nYou'll need a wireless receiver for this libary to work"), 0x80); #endif diff --git a/XBOXUSB.cpp b/XBOXUSB.cpp index cfbb2b34..89b5f260 100644 --- a/XBOXUSB.cpp +++ b/XBOXUSB.cpp @@ -105,7 +105,7 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nThis library only supports Xbox 360 controllers via USB"), 0x80); #endif goto FailUnknownDevice; - } else if(PID != XBOX_WIRED_PID && PID != GAMESTOP_WIRED_PID) // Check PID + } else if(PID != XBOX_WIRED_PID && PID != MADCATZ_WIRED_PID && PID != GAMESTOP_WIRED_PID) // Check PID goto FailUnknownDevice; // Allocate new address according to device class diff --git a/XBOXUSB.h b/XBOXUSB.h index a11d55a1..4df0ad0b 100644 --- a/XBOXUSB.h +++ b/XBOXUSB.h @@ -42,6 +42,7 @@ #define XBOX_WIRELESS_PID 0x028F // Wireless controller only support charging #define XBOX_WIRELESS_RECEIVER_PID 0x0719 // Microsoft Wireless Gaming Receiver #define XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID 0x0291 // Third party Wireless Gaming Receiver +#define MADCATZ_WIRED_PID 0xF016 // Mad Catz wired controller #define GAMESTOP_WIRED_PID 0x0401 // Gamestop wired controller #define XBOX_REPORT_BUFFER_SIZE 14 // Size of the input report buffer @@ -104,7 +105,7 @@ public: * @return Returns true if the device's VID and PID matches this driver. */ virtual boolean VIDPIDOK(uint16_t vid, uint16_t pid) { - return ((vid == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID || vid == GAMESTOP_VID) && (pid == XBOX_WIRED_PID || pid == GAMESTOP_WIRED_PID)); + return ((vid == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID || vid == GAMESTOP_VID) && (pid == XBOX_WIRED_PID || pid == MADCATZ_WIRED_PID || pid == GAMESTOP_WIRED_PID)); }; /**@}*/ From 257c96f5c173ef09c70045adbc2a77ca09abb47b Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 4 Jan 2014 13:43:49 +0100 Subject: [PATCH 063/145] Can now turn LED off by calling setLedOn(OFF) for all controllers Also renamed all enums, so they does not conflict with user code that easily --- PS3BT.cpp | 46 ++++++++------- PS3BT.h | 72 ++++++++++++------------ PS3Enums.h | 47 ++++++++-------- PS3USB.cpp | 42 +++++++------- PS3USB.h | 68 +++++++++++----------- Wii.cpp | 51 +++++++++-------- Wii.h | 40 ++++++------- XBOXOLD.cpp | 12 ++-- XBOXOLD.h | 19 +++---- XBOXRECV.cpp | 26 +++++---- XBOXRECV.h | 35 ++++++------ XBOXUSB.cpp | 24 ++++---- XBOXUSB.h | 37 ++++++------ controllerEnums.h | 29 +++++----- examples/Bluetooth/PS3Multi/PS3Multi.ino | 2 +- examples/Bluetooth/WiiMulti/WiiMulti.ino | 2 +- keywords.txt | 1 + xboxEnums.h | 11 ++-- 18 files changed, 294 insertions(+), 270 deletions(-) diff --git a/PS3BT.cpp b/PS3BT.cpp index 103d71ae..ba8e043b 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -49,26 +49,26 @@ pBtd(p) // pointer to USB class instance - mandatory Reset(); } -bool PS3BT::getButtonPress(Button b) { - return (ButtonState & pgm_read_dword(&BUTTONS[(uint8_t)b])); +bool PS3BT::getButtonPress(ButtonEnum b) { + return (ButtonState & pgm_read_dword(&PS3_BUTTONS[(uint8_t)b])); } -bool PS3BT::getButtonClick(Button b) { - uint32_t button = pgm_read_dword(&BUTTONS[(uint8_t)b]); +bool PS3BT::getButtonClick(ButtonEnum b) { + uint32_t button = pgm_read_dword(&PS3_BUTTONS[(uint8_t)b]); bool click = (ButtonClickState & button); ButtonClickState &= ~button; // Clear "click" event return click; } -uint8_t PS3BT::getAnalogButton(Button a) { - return (uint8_t)(l2capinbuf[pgm_read_byte(&ANALOGBUTTONS[(uint8_t)a])]); +uint8_t PS3BT::getAnalogButton(ButtonEnum a) { + return (uint8_t)(l2capinbuf[pgm_read_byte(&PS3_ANALOG_BUTTONS[(uint8_t)a])]); } -uint8_t PS3BT::getAnalogHat(AnalogHat a) { +uint8_t PS3BT::getAnalogHat(AnalogHatEnum a) { return (uint8_t)(l2capinbuf[(uint8_t)a + 15]); } -int16_t PS3BT::getSensor(Sensor a) { +int16_t PS3BT::getSensor(SensorEnum a) { if(PS3Connected) { if(a == aX || a == aY || a == aZ || a == gZ) return ((l2capinbuf[(uint16_t)a] << 8) | l2capinbuf[(uint16_t)a + 1]); @@ -85,7 +85,7 @@ int16_t PS3BT::getSensor(Sensor a) { return 0; } -double PS3BT::getAngle(Angle a) { +double PS3BT::getAngle(AngleEnum a) { double accXval, accYval, accZval; if(PS3Connected) { @@ -112,7 +112,7 @@ double PS3BT::getAngle(Angle a) { return (atan2(accXval, accZval) + PI) * RAD_TO_DEG; } -double PS3BT::get9DOFValues(Sensor a) { // Thanks to Manfred Piendl +double PS3BT::get9DOFValues(SensorEnum a) { // Thanks to Manfred Piendl if(!PS3MoveConnected) return 0; int16_t value = getSensor(a); @@ -156,7 +156,7 @@ String PS3BT::getTemperature() { return "Error"; } -bool PS3BT::getStatus(Status c) { +bool PS3BT::getStatus(StatusEnum c) { return (l2capinbuf[(uint16_t)c >> 8] == ((uint8_t)c & 0xff)); } @@ -544,7 +544,7 @@ void PS3BT::setRumbleOff() { HID_Command(HIDBuffer, HID_BUFFERSIZE); } -void PS3BT::setRumbleOn(Rumble mode) { +void PS3BT::setRumbleOn(RumbleEnum mode) { uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow if(mode == RumbleHigh) { power[0] = 0x00; @@ -566,18 +566,22 @@ void PS3BT::setLedRaw(uint8_t value) { HID_Command(HIDBuffer, HID_BUFFERSIZE); } -void PS3BT::setLedOff(LED a) { - HIDBuffer[11] &= ~((uint8_t)((pgm_read_byte(&LEDS[(uint8_t)a]) & 0x0f) << 1)); +void PS3BT::setLedOff(LEDEnum a) { + HIDBuffer[11] &= ~((uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1)); HID_Command(HIDBuffer, HID_BUFFERSIZE); } -void PS3BT::setLedOn(LED a) { - HIDBuffer[11] |= (uint8_t)((pgm_read_byte(&LEDS[(uint8_t)a]) & 0x0f) << 1); - HID_Command(HIDBuffer, HID_BUFFERSIZE); +void PS3BT::setLedOn(LEDEnum a) { + if(a == OFF) + setLedRaw(0); + else { + HIDBuffer[11] |= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1); + HID_Command(HIDBuffer, HID_BUFFERSIZE); + } } -void PS3BT::setLedToggle(LED a) { - HIDBuffer[11] ^= (uint8_t)((pgm_read_byte(&LEDS[(uint8_t)a]) & 0x0f) << 1); +void PS3BT::setLedToggle(LEDEnum a) { + HIDBuffer[11] ^= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1); HID_Command(HIDBuffer, HID_BUFFERSIZE); } @@ -602,7 +606,7 @@ void PS3BT::HIDMove_Command(uint8_t* data, uint8_t nbytes) { timerHID = millis(); } -void PS3BT::moveSetBulb(uint8_t r, uint8_t g, uint8_t b) { //Use this to set the Color using RGB values +void PS3BT::moveSetBulb(uint8_t r, uint8_t g, uint8_t b) { // Use this to set the Color using RGB values // Set the Bulb's values into the write buffer HIDMoveBuffer[3] = r; HIDMoveBuffer[4] = g; @@ -611,7 +615,7 @@ void PS3BT::moveSetBulb(uint8_t r, uint8_t g, uint8_t b) { //Use this to set the HIDMove_Command(HIDMoveBuffer, HID_BUFFERSIZE); } -void PS3BT::moveSetBulb(Colors color) { //Use this to set the Color using the predefined colors in enum +void PS3BT::moveSetBulb(ColorsEnum color) { // Use this to set the Color using the predefined colors in enum moveSetBulb((uint8_t)(color >> 16), (uint8_t)(color >> 8), (uint8_t)(color)); } diff --git a/PS3BT.h b/PS3BT.h index b8725b00..bd14f4e4 100644 --- a/PS3BT.h +++ b/PS3BT.h @@ -56,32 +56,34 @@ public: /** @name PS3 Controller functions */ /** - * getButtonPress(Button b) will return true as long as the button is held down. + * getButtonPress(ButtonEnum b) will return true as long as the button is held down. * - * While getButtonClick(Button b) will only return it once. + * While getButtonClick(ButtonEnum b) will only return it once. * - * So you instance if you need to increase a variable once you would use getButtonClick(Button b), - * but if you need to drive a robot forward you would use getButtonPress(Button b). + * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). + * @param b ::ButtonEnum to read. + * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press. */ - bool getButtonPress(Button b); - bool getButtonClick(Button b); + bool getButtonPress(ButtonEnum b); + bool getButtonClick(ButtonEnum b); /**@}*/ /** @name PS3 Controller functions */ /** * Used to get the analog value from button presses. - * @param a The ::Button to read. + * @param a The ::ButtonEnum to read. * The supported buttons are: * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2, * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T. * @return Analog value in the range of 0-255. */ - uint8_t getAnalogButton(Button a); + uint8_t getAnalogButton(ButtonEnum a); /** * Used to read the analog joystick. * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY. * @return Return the analog value in the range of 0-255. */ - uint8_t getAnalogHat(AnalogHat a); + uint8_t getAnalogHat(AnalogHatEnum a); /** * Used to read the sensors inside the Dualshock 3 and Move controller. * @param a @@ -90,47 +92,47 @@ public: * and a temperature sensor inside. * @return Return the raw sensor value. */ - int16_t getSensor(Sensor a); + int16_t getSensor(SensorEnum a); /** * Use this to get ::Pitch and ::Roll calculated using the accelerometer. * @param a Either ::Pitch or ::Roll. * @return Return the angle in the range of 0-360. */ - double getAngle(Angle a); + double getAngle(AngleEnum a); /** * Read the sensors inside the Move controller. * @param a ::aXmove, ::aYmove, ::aZmove, ::gXmove, ::gYmove, ::gZmove, ::mXmove, ::mYmove, and ::mXmove. * @return The value in SI units. */ - double get9DOFValues(Sensor a); + double get9DOFValues(SensorEnum a); /** - * Get the ::Status from the controller. - * @param c The ::Status you want to read. + * Get the status from the controller. + * @param c The ::StatusEnum you want to read. * @return True if correct and false if not. */ - bool getStatus(Status c); + bool getStatus(StatusEnum c); /** - * Read all the available ::Status from the controller. + * Read all the available ::StatusEnum from the controller. * @return One large string with all the information. */ String getStatusString(); /** * Read the temperature from the Move controller. - * @return The temperature in degrees celsius. + * @return The temperature in degrees Celsius. */ String getTemperature(); - /** Used to set all LEDs and ::Rumble off. */ + /** Used to set all LEDs and rumble off. */ void setAllOff(); - /** Turn off ::Rumble. */ + /** Turn off rumble. */ void setRumbleOff(); /** - * Turn on ::Rumble. + * Turn on rumble. * @param mode Either ::RumbleHigh or ::RumbleLow. */ - void setRumbleOn(Rumble mode); + void setRumbleOn(RumbleEnum mode); /** - * Turn on ::Rumble using custom duration and power. + * Turn on rumble using custom duration and power. * @param rightDuration The duration of the right/low rumble effect. * @param rightPower The intensity of the right/low rumble effect. * @param leftDuration The duration of the left/high rumble effect. @@ -139,8 +141,8 @@ public: void setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower); /** - * Set LED value without using the ::LED enum. - * @param value See: ::LED enum. + * Set LED value without using ::LEDEnum. + * @param value See: ::LEDEnum. */ void setLedRaw(uint8_t value); @@ -149,20 +151,20 @@ public: setLedRaw(0); }; /** - * Turn the specific ::LED off. - * @param a The ::LED to turn off. + * Turn the specific LED off. + * @param a The ::LEDEnum to turn off. */ - void setLedOff(LED a); + void setLedOff(LEDEnum a); /** - * Turn the specific ::LED on. - * @param a The ::LED to turn on. + * Turn the specific LED on. + * @param a The ::LEDEnum to turn on. */ - void setLedOn(LED a); + void setLedOn(LEDEnum a); /** - * Toggle the specific ::LED. - * @param a The ::LED to toggle. + * Toggle the specific LED. + * @param a The ::LEDEnum to toggle. */ - void setLedToggle(LED a); + void setLedToggle(LEDEnum a); /** * Use this to set the Color using RGB values. @@ -170,10 +172,10 @@ public: */ void moveSetBulb(uint8_t r, uint8_t g, uint8_t b); /** - * Use this to set the color using the predefined colors in ::Colors. + * Use this to set the color using the predefined colors in ::ColorsEnum. * @param color The desired color. */ - void moveSetBulb(Colors color); + void moveSetBulb(ColorsEnum color); /** * Set the rumble value inside the Move controller. * @param rumble The desired value in the range from 64-255. diff --git a/PS3Enums.h b/PS3Enums.h index 8565e572..befb087e 100644 --- a/PS3Enums.h +++ b/PS3Enums.h @@ -20,8 +20,11 @@ #include "controllerEnums.h" +/** Size of the output report buffer for the Dualshock and Navigation controllers */ +#define PS3_REPORT_BUFFER_SIZE 48 + /** Report buffer for all PS3 commands */ -const uint8_t PS3_REPORT_BUFFER[] PROGMEM = { +const uint8_t PS3_REPORT_BUFFER[PS3_REPORT_BUFFER_SIZE] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x27, 0x10, 0x00, 0x32, @@ -33,14 +36,12 @@ const uint8_t PS3_REPORT_BUFFER[] PROGMEM = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; -/** Size of the output report buffer for the Dualshock and Navigation controllers */ -#define PS3_REPORT_BUFFER_SIZE 48 - /** Size of the output report buffer for the Move Controller */ #define MOVE_REPORT_BUFFER_SIZE 7 /** Used to set the LEDs on the controllers */ -const uint8_t LEDS[] PROGMEM = { +const uint8_t PS3_LEDS[] PROGMEM = { + 0x00, // OFF 0x01, // LED1 0x02, // LED2 0x04, // LED3 @@ -51,15 +52,15 @@ const uint8_t LEDS[] PROGMEM = { 0x0C, // LED7 0x0D, // LED8 0x0E, // LED9 - 0x0F // LED10 + 0x0F, // LED10 }; /** * Buttons on the controllers * - * Note: that the location is shiftet 9 when it's connected via USB. + * Note: that the location is shifted 9 when it's connected via USB. */ -const uint32_t BUTTONS[] PROGMEM = { +const uint32_t PS3_BUTTONS[] PROGMEM = { 0x10, // UP 0x20, // RIGHT 0x40, // DOWN @@ -82,15 +83,15 @@ const uint32_t BUTTONS[] PROGMEM = { 0x010000, // PS 0x080000, // MOVE - covers 12 bits - we only need to read the top 8 - 0x100000 // T - covers 12 bits - we only need to read the top 8 + 0x100000, // T - covers 12 bits - we only need to read the top 8 }; /** * Analog buttons on the controllers * - * Note: that the location is shiftet 9 when it's connected via USB. + * Note: that the location is shifted 9 when it's connected via USB. */ -const uint8_t ANALOGBUTTONS[] PROGMEM = { +const uint8_t PS3_ANALOG_BUTTONS[] PROGMEM = { 23, // UP_ANALOG 24, // RIGHT_ANALOG 25, // DOWN_ANALOG @@ -108,11 +109,11 @@ const uint8_t ANALOGBUTTONS[] PROGMEM = { 0, 0, // Skip PS and MOVE // Playstation Move Controller - 15 // T_ANALOG - Both at byte 14 (last reading) and byte 15 (current reading) + 15, // T_ANALOG - Both at byte 14 (last reading) and byte 15 (current reading) }; /** Used to set the colors of the move controller. */ -enum Colors { +enum ColorsEnum { /** r = 255, g = 0, b = 0 */ Red = 0xFF0000, /** r = 0, g = 255, b = 0 */ @@ -136,9 +137,9 @@ enum Colors { /** * Sensors inside the Sixaxis Dualshock 3 and Move controller. * - * Note: that the location is shiftet 9 when it's connected via USB. + * Note: that the location is shifted 9 when it's connected via USB. */ -enum Sensor { +enum SensorEnum { /** Accelerometer x-axis */ aX = 50, /** Accelerometer y-axis */ @@ -174,13 +175,13 @@ enum Sensor { }; /** Used to get the angle calculated using the accelerometer. */ -enum Angle { +enum AngleEnum { Pitch = 0x01, Roll = 0x02, }; -enum Status { - // Note that the location is shiftet 9 when it's connected via USB +enum StatusEnum { + // Note that the location is shifted 9 when it's connected via USB // Byte location | bit location Plugged = (38 << 8) | 0x02, Unplugged = (38 << 8) | 0x03, @@ -201,13 +202,13 @@ enum Status { MoveHigh = (21 << 8) | 0x04, MoveFull = (21 << 8) | 0x05, - CableRumble = (40 << 8) | 0x10, //Opperating by USB and rumble is turned on - Cable = (40 << 8) | 0x12, //Opperating by USB and rumble is turned off - BluetoothRumble = (40 << 8) | 0x14, //Opperating by bluetooth and rumble is turned on - Bluetooth = (40 << 8) | 0x16, //Opperating by bluetooth and rumble is turned off + CableRumble = (40 << 8) | 0x10, // Operating by USB and rumble is turned on + Cable = (40 << 8) | 0x12, // Operating by USB and rumble is turned off + BluetoothRumble = (40 << 8) | 0x14, // Operating by Bluetooth and rumble is turned on + Bluetooth = (40 << 8) | 0x16, // Operating by Bluetooth and rumble is turned off }; -enum Rumble { +enum RumbleEnum { RumbleHigh = 0x10, RumbleLow = 0x20, }; diff --git a/PS3USB.cpp b/PS3USB.cpp index 25bfba4b..7a15bb37 100644 --- a/PS3USB.cpp +++ b/PS3USB.cpp @@ -312,30 +312,30 @@ void PS3USB::printReport() { // Uncomment "#define PRINTREPORT" to print the rep #endif } -bool PS3USB::getButtonPress(Button b) { - return (ButtonState & pgm_read_dword(&BUTTONS[(uint8_t)b])); +bool PS3USB::getButtonPress(ButtonEnum b) { + return (ButtonState & pgm_read_dword(&PS3_BUTTONS[(uint8_t)b])); } -bool PS3USB::getButtonClick(Button b) { - uint32_t button = pgm_read_dword(&BUTTONS[(uint8_t)b]); +bool PS3USB::getButtonClick(ButtonEnum b) { + uint32_t button = pgm_read_dword(&PS3_BUTTONS[(uint8_t)b]); bool click = (ButtonClickState & button); ButtonClickState &= ~button; // Clear "click" event return click; } -uint8_t PS3USB::getAnalogButton(Button a) { - return (uint8_t)(readBuf[(pgm_read_byte(&ANALOGBUTTONS[(uint8_t)a])) - 9]); +uint8_t PS3USB::getAnalogButton(ButtonEnum a) { + return (uint8_t)(readBuf[(pgm_read_byte(&PS3_ANALOG_BUTTONS[(uint8_t)a])) - 9]); } -uint8_t PS3USB::getAnalogHat(AnalogHat a) { +uint8_t PS3USB::getAnalogHat(AnalogHatEnum a) { return (uint8_t)(readBuf[((uint8_t)a + 6)]); } -uint16_t PS3USB::getSensor(Sensor a) { +uint16_t PS3USB::getSensor(SensorEnum a) { return ((readBuf[((uint16_t)a) - 9] << 8) | readBuf[((uint16_t)a + 1) - 9]); } -double PS3USB::getAngle(Angle a) { +double PS3USB::getAngle(AngleEnum a) { if(PS3Connected) { double accXval; double accYval; @@ -358,7 +358,7 @@ double PS3USB::getAngle(Angle a) { return 0; } -bool PS3USB::getStatus(Status c) { +bool PS3USB::getStatus(StatusEnum c) { return (readBuf[((uint16_t)c >> 8) - 9] == ((uint8_t)c & 0xff)); } @@ -419,7 +419,7 @@ void PS3USB::setRumbleOff() { PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE); } -void PS3USB::setRumbleOn(Rumble mode) { +void PS3USB::setRumbleOn(RumbleEnum mode) { if((mode & 0x30) > 0x00) { uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow if(mode == RumbleHigh) { @@ -443,18 +443,22 @@ void PS3USB::setLedRaw(uint8_t value) { PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE); } -void PS3USB::setLedOff(LED a) { - writeBuf[9] &= ~((uint8_t)((pgm_read_byte(&LEDS[(uint8_t)a]) & 0x0f) << 1)); +void PS3USB::setLedOff(LEDEnum a) { + writeBuf[9] &= ~((uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1)); PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE); } -void PS3USB::setLedOn(LED a) { - writeBuf[9] |= (uint8_t)((pgm_read_byte(&LEDS[(uint8_t)a]) & 0x0f) << 1); - PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE); +void PS3USB::setLedOn(LEDEnum a) { + if(a == OFF) + setLedRaw(0); + else { + writeBuf[9] |= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1); + PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE); + } } -void PS3USB::setLedToggle(LED a) { - writeBuf[9] ^= (uint8_t)((pgm_read_byte(&LEDS[(uint8_t)a]) & 0x0f) << 1); +void PS3USB::setLedToggle(LEDEnum a) { + writeBuf[9] ^= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1); PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE); } @@ -506,7 +510,7 @@ void PS3USB::moveSetBulb(uint8_t r, uint8_t g, uint8_t b) { // Use this to set t Move_Command(writeBuf, MOVE_REPORT_BUFFER_SIZE); } -void PS3USB::moveSetBulb(Colors color) { // Use this to set the Color using the predefined colors in "enums.h" +void PS3USB::moveSetBulb(ColorsEnum color) { // Use this to set the Color using the predefined colors in "enums.h" moveSetBulb((uint8_t)(color >> 16), (uint8_t)(color >> 8), (uint8_t)(color)); } diff --git a/PS3USB.h b/PS3USB.h index 9e40a2ea..dde40d5c 100644 --- a/PS3USB.h +++ b/PS3USB.h @@ -146,68 +146,70 @@ public: /** @name PS3 Controller functions */ /** - * getButtonPress(Button b) will return true as long as the button is held down. + * getButtonPress(ButtonEnum b) will return true as long as the button is held down. * - * While getButtonClick(Button b) will only return it once. + * While getButtonClick(ButtonEnum b) will only return it once. * - * So you instance if you need to increase a variable once you would use getButtonClick(Button b), - * but if you need to drive a robot forward you would use getButtonPress(Button b). + * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). + * @param b ::ButtonEnum to read. + * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press. */ - bool getButtonPress(Button b); - bool getButtonClick(Button b); + bool getButtonPress(ButtonEnum b); + bool getButtonClick(ButtonEnum b); /**@}*/ /** @name PS3 Controller functions */ /** * Used to get the analog value from button presses. - * @param a The ::Button to read. + * @param a The ::ButtonEnum to read. * The supported buttons are: * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2, * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T. * @return Analog value in the range of 0-255. */ - uint8_t getAnalogButton(Button a); + uint8_t getAnalogButton(ButtonEnum a); /** * Used to read the analog joystick. * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY. * @return Return the analog value in the range of 0-255. */ - uint8_t getAnalogHat(AnalogHat a); + uint8_t getAnalogHat(AnalogHatEnum a); /** * Used to read the sensors inside the Dualshock 3 controller. * @param a * The Dualshock 3 has a 3-axis accelerometer and a 1-axis gyro inside. * @return Return the raw sensor value. */ - uint16_t getSensor(Sensor a); + uint16_t getSensor(SensorEnum a); /** * Use this to get ::Pitch and ::Roll calculated using the accelerometer. * @param a Either ::Pitch or ::Roll. * @return Return the angle in the range of 0-360. */ - double getAngle(Angle a); + double getAngle(AngleEnum a); /** - * Get the ::Status from the controller. - * @param c The ::Status you want to read. + * Get the ::StatusEnum from the controller. + * @param c The ::StatusEnum you want to read. * @return True if correct and false if not. */ - bool getStatus(Status c); + bool getStatus(StatusEnum c); /** - * Read all the available ::Status from the controller. + * Read all the available ::StatusEnum from the controller. * @return One large string with all the information. */ String getStatusString(); - /** Used to set all LEDs and ::Rumble off. */ + /** Used to set all LEDs and rumble off. */ void setAllOff(); - /** Turn off ::Rumble. */ + /** Turn off rumble. */ void setRumbleOff(); /** - * Turn on ::Rumble. + * Turn on rumble. * @param mode Either ::RumbleHigh or ::RumbleLow. */ - void setRumbleOn(Rumble mode); + void setRumbleOn(RumbleEnum mode); /** - * Turn on ::Rumble using custom duration and power. + * Turn on rumble using custom duration and power. * @param rightDuration The duration of the right/low rumble effect. * @param rightPower The intensity of the right/low rumble effect. * @param leftDuration The duration of the left/high rumble effect. @@ -216,8 +218,8 @@ public: void setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower); /** - * Set LED value without using the ::LED enum. - * @param value See: ::LED enum. + * Set LED value without using the ::LEDEnum. + * @param value See: ::LEDEnum. */ void setLedRaw(uint8_t value); @@ -226,20 +228,20 @@ public: setLedRaw(0); } /** - * Turn the specific ::LED off. - * @param a The ::LED to turn off. + * Turn the specific ::LEDEnum off. + * @param a The ::LEDEnum to turn off. */ - void setLedOff(LED a); + void setLedOff(LEDEnum a); /** - * Turn the specific ::LED on. - * @param a The ::LED to turn on. + * Turn the specific ::LEDEnum on. + * @param a The ::LEDEnum to turn on. */ - void setLedOn(LED a); + void setLedOn(LEDEnum a); /** - * Toggle the specific ::LED. - * @param a The ::LED to toggle. + * Toggle the specific ::LEDEnum. + * @param a The ::LEDEnum to toggle. */ - void setLedToggle(LED a); + void setLedToggle(LEDEnum a); /** * Use this to set the Color using RGB values. @@ -247,10 +249,10 @@ public: */ void moveSetBulb(uint8_t r, uint8_t g, uint8_t b); /** - * Use this to set the color using the predefined colors in ::Colors. + * Use this to set the color using the predefined colors in ::ColorsEnum. * @param color The desired color. */ - void moveSetBulb(Colors color); + void moveSetBulb(ColorsEnum color); /** * Set the rumble value inside the Move controller. * @param rumble The desired value in the range from 64-255. diff --git a/Wii.cpp b/Wii.cpp index 6a6f9f21..62af423a 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -22,7 +22,8 @@ //#define EXTRADEBUG // Uncomment to get even more debugging data //#define PRINTREPORT // Uncomment to print the report send by the Wii controllers -const uint8_t LEDS[] PROGMEM = { +const uint8_t WII_LEDS[] PROGMEM = { + 0x00, // OFF 0x10, // LED1 0x20, // LED2 0x40, // LED3 @@ -33,10 +34,10 @@ const uint8_t LEDS[] PROGMEM = { 0xC0, // LED7 0xD0, // LED8 0xE0, // LED9 - 0xF0 // LED10 + 0xF0, // LED10 }; -const uint32_t BUTTONS[] PROGMEM = { +const uint32_t WII_BUTTONS[] PROGMEM = { 0x00008, // UP 0x00002, // RIGHT 0x00004, // DOWN @@ -53,9 +54,9 @@ const uint32_t BUTTONS[] PROGMEM = { 0x20000, // C 0x00400, // B - 0x00800 // A + 0x00800, // A }; -const uint32_t PROCONTROLLERBUTTONS[] PROGMEM = { +const uint32_t WII_PROCONTROLLER_BUTTONS[] PROGMEM = { 0x00100, // UP 0x00080, // RIGHT 0x00040, // DOWN @@ -78,7 +79,7 @@ const uint32_t PROCONTROLLERBUTTONS[] PROGMEM = { 0x00020, // L 0x00002, // R 0x08000, // ZL - 0x00400 // ZR + 0x00400, // ZR }; WII::WII(BTD *p, bool pair) : @@ -845,7 +846,7 @@ void WII::Run() { /************************************************************/ void WII::HID_Command(uint8_t* data, uint8_t nbytes) { if(motionPlusInside) - pBtd->L2CAP_Command(hci_handle, data, nbytes, interrupt_scid[0], interrupt_scid[1]); // It's the new wiimote with the Motion Plus Inside + pBtd->L2CAP_Command(hci_handle, data, nbytes, interrupt_scid[0], interrupt_scid[1]); // It's the new Wiimote with the Motion Plus Inside or Wii U Pro controller else pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); } @@ -880,21 +881,25 @@ void WII::setLedRaw(uint8_t value) { HID_Command(HIDBuffer, 3); } -void WII::setLedOff(LED a) { +void WII::setLedOff(LEDEnum a) { HIDBuffer[1] = 0x11; - HIDBuffer[2] &= ~(pgm_read_byte(&LEDS[(uint8_t)a])); + HIDBuffer[2] &= ~(pgm_read_byte(&WII_LEDS[(uint8_t)a])); HID_Command(HIDBuffer, 3); } -void WII::setLedOn(LED a) { - HIDBuffer[1] = 0x11; - HIDBuffer[2] |= pgm_read_byte(&LEDS[(uint8_t)a]); - HID_Command(HIDBuffer, 3); +void WII::setLedOn(LEDEnum a) { + if(a == OFF) + setLedRaw(0); + else { + HIDBuffer[1] = 0x11; + HIDBuffer[2] |= pgm_read_byte(&WII_LEDS[(uint8_t)a]); + HID_Command(HIDBuffer, 3); + } } -void WII::setLedToggle(LED a) { +void WII::setLedToggle(LEDEnum a) { HIDBuffer[1] = 0x11; - HIDBuffer[2] ^= pgm_read_byte(&LEDS[(uint8_t)a]); + HIDBuffer[2] ^= pgm_read_byte(&WII_LEDS[(uint8_t)a]); HID_Command(HIDBuffer, 3); } @@ -1033,25 +1038,25 @@ void WII::checkMotionPresent() { /************************************************************/ -bool WII::getButtonPress(Button b) { // Return true when a button is pressed +bool WII::getButtonPress(ButtonEnum b) { // Return true when a button is pressed if(wiiUProControllerConnected) - return (ButtonState & pgm_read_dword(&PROCONTROLLERBUTTONS[(uint8_t)b])); + return (ButtonState & pgm_read_dword(&WII_PROCONTROLLER_BUTTONS[(uint8_t)b])); else - return (ButtonState & pgm_read_dword(&BUTTONS[(uint8_t)b])); + return (ButtonState & pgm_read_dword(&WII_BUTTONS[(uint8_t)b])); } -bool WII::getButtonClick(Button b) { // Only return true when a button is clicked +bool WII::getButtonClick(ButtonEnum b) { // Only return true when a button is clicked uint32_t button; if(wiiUProControllerConnected) - button = pgm_read_dword(&PROCONTROLLERBUTTONS[(uint8_t)b]); + button = pgm_read_dword(&WII_PROCONTROLLER_BUTTONS[(uint8_t)b]); else - button = pgm_read_dword(&BUTTONS[(uint8_t)b]); + button = pgm_read_dword(&WII_BUTTONS[(uint8_t)b]); bool click = (ButtonClickState & button); ButtonClickState &= ~button; // clear "click" event return click; } -uint8_t WII::getAnalogHat(Hat a) { +uint8_t WII::getAnalogHat(HatEnum a) { if(!nunchuckConnected) return 127; // Return center position else { @@ -1063,7 +1068,7 @@ uint8_t WII::getAnalogHat(Hat a) { } } -uint16_t WII::getAnalogHat(AnalogHat a) { +uint16_t WII::getAnalogHat(AnalogHatEnum a) { if(!wiiUProControllerConnected) return 2000; else { diff --git a/Wii.h b/Wii.h index 26c81fe5..294cd7a2 100755 --- a/Wii.h +++ b/Wii.h @@ -32,7 +32,7 @@ #define wii_clear_flag(flag) (wii_event_flag &= ~(flag)) /** Enum used to read the joystick on the Nunchuck. */ -enum Hat { +enum HatEnum { /** Read the x-axis on the Nunchuck joystick. */ HatX = 0, /** Read the y-axis on the Nunchuck joystick. */ @@ -76,9 +76,11 @@ public: * * So you instance if you need to increase a variable once you would use getButtonClick(Button b), * but if you need to drive a robot forward you would use getButtonPress(Button b). + * @param b ::ButtonEnum to read. + * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press. */ - bool getButtonPress(Button b); - bool getButtonClick(Button b); + bool getButtonPress(ButtonEnum b); + bool getButtonClick(ButtonEnum b); /**@}*/ /** @name Wii Controller functions */ @@ -93,13 +95,13 @@ public: * @param a Either ::HatX or ::HatY. * @return Return the analog value in the range from approximately 25-230. */ - uint8_t getAnalogHat(Hat a); + uint8_t getAnalogHat(HatEnum a); /** * Used to read the joystick of the Wii U Pro Controller. * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY. * @return Return the analog value in the range from approximately 800-3200. */ - uint16_t getAnalogHat(AnalogHat a); + uint16_t getAnalogHat(AnalogHatEnum a); /** * Pitch calculated from the Wiimote. A complimentary filter is used if the Motion Plus is connected. @@ -141,8 +143,8 @@ public: void setRumbleToggle(); /** - * Set LED value without using the ::LED enum. - * @param value See: ::LED enum. + * Set LED value without using the ::LEDEnum. + * @param value See: ::LEDEnum. */ void setLedRaw(uint8_t value); @@ -151,26 +153,26 @@ public: setLedRaw(0); }; /** - * Turn the specific ::LED off. - * @param a The ::LED to turn off. + * Turn the specific ::LEDEnum off. + * @param a The ::LEDEnum to turn off. */ - void setLedOff(LED a); + void setLedOff(LEDEnum a); /** - * Turn the specific ::LED on. - * @param a The ::LED to turn on. + * Turn the specific ::LEDEnum on. + * @param a The ::LEDEnum to turn on. */ - void setLedOn(LED a); + void setLedOn(LEDEnum a); /** - * Toggle the specific ::LED. - * @param a The ::LED to toggle. + * Toggle the specific ::LEDEnum. + * @param a The ::LEDEnum to toggle. */ - void setLedToggle(LED a); + void setLedToggle(LEDEnum a); /** * This will set the LEDs, so the user can see which connections are active. * - * The first ::LED indicate that the Wiimote is connected, - * the second ::LED indicate indicate that a Motion Plus is also connected - * the third ::LED will indicate that a Nunchuck controller is also connected. + * The first ::LEDEnum indicate that the Wiimote is connected, + * the second ::LEDEnum indicate indicate that a Motion Plus is also connected + * the third ::LEDEnum will indicate that a Nunchuck controller is also connected. */ void setLedStatus(); diff --git a/XBOXOLD.cpp b/XBOXOLD.cpp index 7bde6133..298d5ab1 100644 --- a/XBOXOLD.cpp +++ b/XBOXOLD.cpp @@ -21,7 +21,7 @@ //#define PRINTREPORT // Uncomment to print the report send by the Xbox controller /** Buttons on the controllers */ -const uint8_t XBOXOLDBUTTONS[] PROGMEM = { +const uint8_t XBOXOLD_BUTTONS[] PROGMEM = { 0x01, // UP 0x08, // RIGHT 0x02, // DOWN @@ -291,15 +291,15 @@ void XBOXOLD::printReport(uint16_t length) { //Uncomment "#define PRINTREPORT" t #endif } -uint8_t XBOXOLD::getButtonPress(Button b) { - uint8_t button = pgm_read_byte(&XBOXOLDBUTTONS[(uint8_t)b]); +uint8_t XBOXOLD::getButtonPress(ButtonEnum b) { + uint8_t button = pgm_read_byte(&XBOXOLD_BUTTONS[(uint8_t)b]); if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons return buttonValues[button]; // Analog buttons return (ButtonState & button); // Digital buttons } -bool XBOXOLD::getButtonClick(Button b) { - uint8_t button = pgm_read_byte(&XBOXOLDBUTTONS[(uint8_t)b]); +bool XBOXOLD::getButtonClick(ButtonEnum b) { + uint8_t button = pgm_read_byte(&XBOXOLD_BUTTONS[(uint8_t)b]); if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) { // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons if(buttonClicked[button]) { buttonClicked[button] = false; @@ -313,7 +313,7 @@ bool XBOXOLD::getButtonClick(Button b) { return click; } -int16_t XBOXOLD::getAnalogHat(AnalogHat a) { +int16_t XBOXOLD::getAnalogHat(AnalogHatEnum a) { return hatValue[a]; } diff --git a/XBOXOLD.h b/XBOXOLD.h index 8b3fcce0..b3c0ccb2 100644 --- a/XBOXOLD.h +++ b/XBOXOLD.h @@ -106,18 +106,17 @@ public: /** @name Xbox Controller functions */ /** - * getButtonPress(Button b) will return true as long as the button is held down. + * getButtonPress(ButtonEnum b) will return true as long as the button is held down. * - * While getButtonClick(Button b) will only return it once. + * While getButtonClick(ButtonEnum b) will only return it once. * - * So you instance if you need to increase a variable once you would use getButtonClick(Button b), - * but if you need to drive a robot forward you would use getButtonPress(Button b). - * @param b ::Button to read. - * @return getButtonClick(Button b) will return a bool, but getButtonPress(Button b) - * will return a byte if reading ::L2 or ::R2. + * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). + * @param b ::ButtonEnum to read. + * @return getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a byte if reading ::L2 or ::R2. */ - uint8_t getButtonPress(Button b); - bool getButtonClick(Button b); + uint8_t getButtonPress(ButtonEnum b); + bool getButtonClick(ButtonEnum b); /**@}*/ /** @name Xbox Controller functions */ @@ -126,7 +125,7 @@ public: * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY. * @return Returns a signed 16-bit integer. */ - int16_t getAnalogHat(AnalogHat a); + int16_t getAnalogHat(AnalogHatEnum a); /** Turn rumble off the controller. */ void setRumbleOff() { diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index c4bf33b9..e70e322a 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -406,15 +406,15 @@ void XBOXRECV::printReport(uint8_t controller, uint8_t nBytes) { //Uncomment "#d #endif } -uint8_t XBOXRECV::getButtonPress(Button b, uint8_t controller) { +uint8_t XBOXRECV::getButtonPress(ButtonEnum b, uint8_t controller) { if(b == L2) // These are analog buttons return (uint8_t)(ButtonState[controller] >> 8); else if(b == R2) return (uint8_t)ButtonState[controller]; - return (bool)(ButtonState[controller] & ((uint32_t)pgm_read_word(&XBOXBUTTONS[(uint8_t)b]) << 16)); + return (bool)(ButtonState[controller] & ((uint32_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]) << 16)); } -bool XBOXRECV::getButtonClick(Button b, uint8_t controller) { +bool XBOXRECV::getButtonClick(ButtonEnum b, uint8_t controller) { if(b == L2) { if(L2Clicked[controller]) { L2Clicked[controller] = false; @@ -428,13 +428,13 @@ bool XBOXRECV::getButtonClick(Button b, uint8_t controller) { } return false; } - uint16_t button = pgm_read_word(&XBOXBUTTONS[(uint8_t)b]); + uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]); bool click = (ButtonClickState[controller] & button); ButtonClickState[controller] &= ~button; // clear "click" event return click; } -int16_t XBOXRECV::getAnalogHat(AnalogHat a, uint8_t controller) { +int16_t XBOXRECV::getAnalogHat(AnalogHatEnum a, uint8_t controller) { return hatValue[controller][a]; } @@ -512,16 +512,18 @@ void XBOXRECV::setLedRaw(uint8_t value, uint8_t controller) { XboxCommand(controller, writeBuf, 4); } -void XBOXRECV::setLedOn(LED led, uint8_t controller) { - if(led != ALL) // All LEDs can't be on a the same time - setLedRaw(pgm_read_byte(&XBOXLEDS[(uint8_t)led]) + 4, controller); +void XBOXRECV::setLedOn(LEDEnum led, uint8_t controller) { + if(led == OFF) + setLedRaw(0); + else if(led != ALL) // All LEDs can't be on a the same time + setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4); } -void XBOXRECV::setLedBlink(LED led, uint8_t controller) { - setLedRaw(pgm_read_byte(&XBOXLEDS[(uint8_t)led]), controller); +void XBOXRECV::setLedBlink(LEDEnum led, uint8_t controller) { + setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]), controller); } -void XBOXRECV::setLedMode(LEDMode ledMode, uint8_t controller) { // This function is used to do some speciel LED stuff the controller supports +void XBOXRECV::setLedMode(LEDModeEnum ledMode, uint8_t controller) { // This function is used to do some speciel LED stuff the controller supports setLedRaw((uint8_t)ledMode, controller); } @@ -567,7 +569,7 @@ void XBOXRECV::onInit(uint8_t controller) { if(pFuncOnInit) pFuncOnInit(); // Call the user function else { - LED led; + LEDEnum led; if(controller == 0) led = LED1; else if(controller == 1) diff --git a/XBOXRECV.h b/XBOXRECV.h index 25d7fe7f..41ebef47 100644 --- a/XBOXRECV.h +++ b/XBOXRECV.h @@ -120,19 +120,18 @@ public: /** @name Xbox Controller functions */ /** - * getButtonPress(uint8_t controller, Button b) will return true as long as the button is held down. + * getButtonPress(uint8_t controller, ButtonEnum b) will return true as long as the button is held down. * - * While getButtonClick(uint8_t controller, Button b) will only return it once. + * While getButtonClick(uint8_t controller, ButtonEnum b) will only return it once. * - * So you instance if you need to increase a variable once you would use getButtonClick(uint8_t controller, Button b), - * but if you need to drive a robot forward you would use getButtonPress(uint8_t controller, Button b). - * @param b ::Button to read. + * So you instance if you need to increase a variable once you would use getButtonClick(uint8_t controller, ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(uint8_t controller, ButtonEnum b). + * @param b ::ButtonEnum to read. * @param controller The controller to read from. Default to 0. - * @return getButtonClick(uint8_t controller, Button b) will return a bool, but getButtonPress(uint8_t controller, Button b) - * will return a byte if reading ::L2 or ::R2. + * @return getButtonClick(uint8_t controller, ButtonEnum b) will return a bool, while getButtonPress(uint8_t controller, ButtonEnum b) will return a byte if reading ::L2 or ::R2. */ - uint8_t getButtonPress(Button b, uint8_t controller = 0); - bool getButtonClick(Button b, uint8_t controller = 0); + uint8_t getButtonPress(ButtonEnum b, uint8_t controller = 0); + bool getButtonClick(ButtonEnum b, uint8_t controller = 0); /**@}*/ /** @name Xbox Controller functions */ @@ -142,7 +141,7 @@ public: * @param controller The controller to read from. Default to 0. * @return Returns a signed 16-bit integer. */ - int16_t getAnalogHat(AnalogHat a, uint8_t controller = 0); + int16_t getAnalogHat(AnalogHatEnum a, uint8_t controller = 0); /** * Used to disconnect any of the controllers. @@ -174,7 +173,7 @@ public: */ void setRumbleOn(uint8_t lValue, uint8_t rValue, uint8_t controller = 0); /** - * Set LED value. Without using the ::LED or ::LEDMode enum. + * Set LED value. Without using the ::LEDEnum or ::LEDMode enum. * @param value See: * setLedOff(uint8_t controller), setLedOn(uint8_t controller, LED l), * setLedBlink(uint8_t controller, LED l), and setLedMode(uint8_t controller, LEDMode lm). @@ -190,23 +189,23 @@ public: setLedRaw(0, controller); }; /** - * Turn on a LED by using the ::LED enum. - * @param l ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller. + * Turn on a LED by using ::LEDEnum. + * @param l ::OFF, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller. * @param controller The controller to write to. Default to 0. */ - void setLedOn(LED l, uint8_t controller = 0); + void setLedOn(LEDEnum l, uint8_t controller = 0); /** - * Turn on a LED by using the ::LED enum. + * Turn on a LED by using ::LEDEnum. * @param l ::ALL, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller. * @param controller The controller to write to. Default to 0. */ - void setLedBlink(LED l, uint8_t controller = 0); + void setLedBlink(LEDEnum l, uint8_t controller = 0); /** * Used to set special LED modes supported by the Xbox controller. - * @param lm See ::LEDMode. + * @param lm See ::LEDModeEnum. * @param controller The controller to write to. Default to 0. */ - void setLedMode(LEDMode lm, uint8_t controller = 0); + void setLedMode(LEDModeEnum lm, uint8_t controller = 0); /** * Used to get the battery level from the controller. * @param controller The controller to read from. Default to 0. diff --git a/XBOXUSB.cpp b/XBOXUSB.cpp index 89b5f260..8ee06d4f 100644 --- a/XBOXUSB.cpp +++ b/XBOXUSB.cpp @@ -279,15 +279,15 @@ void XBOXUSB::printReport() { //Uncomment "#define PRINTREPORT" to print the rep #endif } -uint8_t XBOXUSB::getButtonPress(Button b) { +uint8_t XBOXUSB::getButtonPress(ButtonEnum b) { if(b == L2) // These are analog buttons return (uint8_t)(ButtonState >> 8); else if(b == R2) return (uint8_t)ButtonState; - return (bool)(ButtonState & ((uint32_t)pgm_read_word(&XBOXBUTTONS[(uint8_t)b]) << 16)); + return (bool)(ButtonState & ((uint32_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]) << 16)); } -bool XBOXUSB::getButtonClick(Button b) { +bool XBOXUSB::getButtonClick(ButtonEnum b) { if(b == L2) { if(L2Clicked) { L2Clicked = false; @@ -301,13 +301,13 @@ bool XBOXUSB::getButtonClick(Button b) { } return false; } - uint16_t button = pgm_read_word(&XBOXBUTTONS[(uint8_t)b]); + uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]); bool click = (ButtonClickState & button); ButtonClickState &= ~button; // clear "click" event return click; } -int16_t XBOXUSB::getAnalogHat(AnalogHat a) { +int16_t XBOXUSB::getAnalogHat(AnalogHatEnum a) { return hatValue[a]; } @@ -325,16 +325,18 @@ void XBOXUSB::setLedRaw(uint8_t value) { XboxCommand(writeBuf, 3); } -void XBOXUSB::setLedOn(LED led) { - if(led != ALL) // All LEDs can't be on a the same time - setLedRaw((pgm_read_byte(&XBOXLEDS[(uint8_t)led])) + 4); +void XBOXUSB::setLedOn(LEDEnum led) { + if(led == OFF) + setLedRaw(0); + else if(led != ALL) // All LEDs can't be on a the same time + setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4); } -void XBOXUSB::setLedBlink(LED led) { - setLedRaw(pgm_read_byte(&XBOXLEDS[(uint8_t)led])); +void XBOXUSB::setLedBlink(LEDEnum led) { + setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led])); } -void XBOXUSB::setLedMode(LEDMode ledMode) { // This function is used to do some speciel LED stuff the controller supports +void XBOXUSB::setLedMode(LEDModeEnum ledMode) { // This function is used to do some special LED stuff the controller supports setLedRaw((uint8_t)ledMode); } diff --git a/XBOXUSB.h b/XBOXUSB.h index 4df0ad0b..2b358fad 100644 --- a/XBOXUSB.h +++ b/XBOXUSB.h @@ -111,18 +111,17 @@ public: /** @name Xbox Controller functions */ /** - * getButtonPress(Button b) will return true as long as the button is held down. + * getButtonPress(ButtonEnum b) will return true as long as the button is held down. * - * While getButtonClick(Button b) will only return it once. + * While getButtonClick(ButtonEnum b) will only return it once. * - * So you instance if you need to increase a variable once you would use getButtonClick(Button b), - * but if you need to drive a robot forward you would use getButtonPress(Button b). - * @param b ::Button to read. - * @return getButtonClick(Button b) will return a bool, but getButtonPress(Button b) - * will return a byte if reading ::L2 or ::R2. + * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). + * @param b ::ButtonEnum to read. + * @return getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a byte if reading ::L2 or ::R2. */ - uint8_t getButtonPress(Button b); - bool getButtonClick(Button b); + uint8_t getButtonPress(ButtonEnum b); + bool getButtonClick(ButtonEnum b); /**@}*/ /** @name Xbox Controller functions */ @@ -131,7 +130,7 @@ public: * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY. * @return Returns a signed 16-bit integer. */ - int16_t getAnalogHat(AnalogHat a); + int16_t getAnalogHat(AnalogHatEnum a); /** Turn rumble off and all the LEDs on the controller. */ void setAllOff() { @@ -150,10 +149,10 @@ public: */ void setRumbleOn(uint8_t lValue, uint8_t rValue); /** - * Set LED value. Without using the ::LED or ::LEDMode enum. + * Set LED value. Without using the ::LEDEnum or ::LEDMode enum. * @param value See: - * setLedOff(), setLedOn(LED l), - * setLedBlink(LED l), and setLedMode(LEDMode lm). + * setLedOff(), setLedOn(LEDEnum l), + * setLedBlink(LEDEnum l), and setLedMode(LEDModeEnum lm). */ void setLedRaw(uint8_t value); @@ -162,20 +161,20 @@ public: setLedRaw(0); }; /** - * Turn on a LED by using the ::LED enum. - * @param l ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller. + * Turn on a LED by using ::LEDEnum. + * @param l ::OFF, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller. */ - void setLedOn(LED l); + void setLedOn(LEDEnum l); /** - * Turn on a LED by using the ::LED enum. + * Turn on a LED by using ::LEDEnum. * @param l ::ALL, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller. */ - void setLedBlink(LED l); + void setLedBlink(LEDEnum l); /** * Used to set special LED modes supported by the Xbox controller. * @param lm See ::LEDMode. */ - void setLedMode(LEDMode lm); + void setLedMode(LEDModeEnum lm); /** * Used to call your own function when the controller is successfully initialized. diff --git a/controllerEnums.h b/controllerEnums.h index edb42987..b5129725 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -24,24 +24,25 @@ */ /** Enum used to turn on the LEDs on the different controllers. */ -enum LED { - LED1 = 0, - LED2 = 1, - LED3 = 2, - LED4 = 3, +enum LEDEnum { + OFF = 0, + LED1 = 1, + LED2 = 2, + LED3 = 3, + LED4 = 4, - LED5 = 4, - LED6 = 5, - LED7 = 6, - LED8 = 7, - LED9 = 8, - LED10 = 9, + LED5 = 5, + LED6 = 6, + LED7 = 7, + LED8 = 8, + LED9 = 9, + LED10 = 10, /** Used to blink all LEDs on the Xbox controller */ - ALL = 4, + ALL = 5, }; /** This enum is used to read all the different buttons on the different controllers */ -enum Button { +enum ButtonEnum { /**@{*/ /** These buttons are available on all the the controllers */ UP = 0, @@ -106,7 +107,7 @@ enum Button { }; /** Joysticks on the PS3 and Xbox controllers. */ -enum AnalogHat { +enum AnalogHatEnum { /** Left joystick x-axis */ LeftHatX = 0, /** Left joystick y-axis */ diff --git a/examples/Bluetooth/PS3Multi/PS3Multi.ino b/examples/Bluetooth/PS3Multi/PS3Multi.ino index dece1c98..20f0da8d 100644 --- a/examples/Bluetooth/PS3Multi/PS3Multi.ino +++ b/examples/Bluetooth/PS3Multi/PS3Multi.ino @@ -139,7 +139,7 @@ void onInit() { for (uint8_t i = 0; i < length; i++) { if ((PS3[i]->PS3Connected || PS3[i]->PS3NavigationConnected) && !oldControllerState[i]) { oldControllerState[i] = true; // Used to check which is the new controller - PS3[i]->setLedOn((LED)i); // Cast directly to LED enum - see: "controllerEnums.h" + PS3[i]->setLedOn((LEDEnum)(i + 1)); // Cast directly to LEDEnum - see: "controllerEnums.h" } } } diff --git a/examples/Bluetooth/WiiMulti/WiiMulti.ino b/examples/Bluetooth/WiiMulti/WiiMulti.ino index d99da9a4..08444f10 100644 --- a/examples/Bluetooth/WiiMulti/WiiMulti.ino +++ b/examples/Bluetooth/WiiMulti/WiiMulti.ino @@ -122,7 +122,7 @@ void onInit() { for (uint8_t i = 0; i < length; i++) { if (Wii[i]->wiimoteConnected && !oldControllerState[i]) { oldControllerState[i] = true; // Used to check which is the new controller - Wii[i]->setLedOn((LED)i); // Cast directly to LED enum - see: "controllerEnums.h" + Wii[i]->setLedOn((LEDEnum)(i + 1)); // Cast directly to LEDEnum - see: "controllerEnums.h" } } } diff --git a/keywords.txt b/keywords.txt index c4f5bd87..c04041ab 100644 --- a/keywords.txt +++ b/keywords.txt @@ -77,6 +77,7 @@ watingForConnection KEYWORD2 #################################################### # Constants and enums (LITERAL1) #################################################### +OFF LITERAL1 LED1 LITERAL1 LED2 LITERAL1 LED3 LITERAL1 diff --git a/xboxEnums.h b/xboxEnums.h index fa4b6c2c..84b137bb 100644 --- a/xboxEnums.h +++ b/xboxEnums.h @@ -21,7 +21,7 @@ #include "controllerEnums.h" /** Enum used to set special LED modes supported by the Xbox controller. */ -enum LEDMode { +enum LEDModeEnum { ROTATING = 0x0A, FASTBLINK = 0x0B, SLOWBLINK = 0x0C, @@ -29,15 +29,16 @@ enum LEDMode { }; /** Used to set the LEDs on the controllers */ -const uint8_t XBOXLEDS[] PROGMEM = { +const uint8_t XBOX_LEDS[] PROGMEM = { + 0x00, // OFF 0x02, // LED1 0x03, // LED2 0x04, // LED3 0x05, // LED4 - 0x01 // ALL - Used to blink all LEDs + 0x01, // ALL - Used to blink all LEDs }; /** Buttons on the controllers */ -const uint16_t XBOXBUTTONS[] PROGMEM = { +const uint16_t XBOX_BUTTONS[] PROGMEM = { 0x0100, // UP 0x0800, // RIGHT 0x0200, // DOWN @@ -58,7 +59,7 @@ const uint16_t XBOXBUTTONS[] PROGMEM = { 0x0080, // Y 0x0004, // XBOX - 0x0008 // SYNC + 0x0008, // SYNC }; #endif From 1f33f2bd087c1eee4ca528da5e3ca0e656088785 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 4 Jan 2014 14:14:22 +0100 Subject: [PATCH 064/145] Renamed getStatusString() to printStatusString() --- PS3BT.cpp | 18 +++------ PS3BT.h | 7 +--- PS3USB.cpp | 50 ++++++++++++------------ PS3USB.h | 7 +--- examples/Bluetooth/PS3BT/PS3BT.ino | 4 +- examples/Bluetooth/PS3Multi/PS3Multi.ino | 2 +- examples/Bluetooth/PS3SPP/PS3SPP.ino | 3 +- examples/PS3USB/PS3USB.ino | 2 +- keywords.txt | 2 +- 9 files changed, 40 insertions(+), 55 deletions(-) diff --git a/PS3BT.cpp b/PS3BT.cpp index ba8e043b..ba531c26 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -160,18 +160,17 @@ bool PS3BT::getStatus(StatusEnum c) { return (l2capinbuf[(uint16_t)c >> 8] == ((uint8_t)c & 0xff)); } -String PS3BT::getStatusString() { +void PS3BT::printStatusString() { + char statusOutput[100]; // Max string length plus null character if(PS3Connected || PS3NavigationConnected) { - char statusOutput[100]; // Max string length plus null character - strcpy_P(statusOutput, PSTR("ConnectionStatus: ")); if(getStatus(Plugged)) strcat_P(statusOutput, PSTR("Plugged")); else if(getStatus(Unplugged)) strcat_P(statusOutput, PSTR("Unplugged")); else strcat_P(statusOutput, PSTR("Error")); - strcat_P(statusOutput, PSTR(" - PowerRating: ")); + if(getStatus(Charging)) strcat_P(statusOutput, PSTR("Charging")); else if(getStatus(NotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); else if(getStatus(Shutdown)) strcat_P(statusOutput, PSTR("Shutdown")); @@ -188,12 +187,7 @@ String PS3BT::getStatusString() { else if(getStatus(BluetoothRumble)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is on")); else if(getStatus(Bluetooth)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is off")); else strcat_P(statusOutput, PSTR("Error")); - - return statusOutput; - } else if(PS3MoveConnected) { - char statusOutput[26]; // Max string length plus null character - strcpy_P(statusOutput, PSTR("PowerRating: ")); if(getStatus(MoveCharging)) strcat_P(statusOutput, PSTR("Charging")); @@ -204,10 +198,10 @@ String PS3BT::getStatusString() { else if(getStatus(MoveHigh)) strcat_P(statusOutput, PSTR("High")); else if(getStatus(MoveFull)) strcat_P(statusOutput, PSTR("Full")); else strcat_P(statusOutput, PSTR("Error")); - - return statusOutput; } else - return "Error"; + strcpy_P(statusOutput, PSTR("Error")); + + USB_HOST_SERIAL.write((uint8_t*)statusOutput, strlen(statusOutput)); } void PS3BT::Reset() { diff --git a/PS3BT.h b/PS3BT.h index bd14f4e4..7291c092 100644 --- a/PS3BT.h +++ b/PS3BT.h @@ -111,11 +111,8 @@ public: * @return True if correct and false if not. */ bool getStatus(StatusEnum c); - /** - * Read all the available ::StatusEnum from the controller. - * @return One large string with all the information. - */ - String getStatusString(); + /** Read all the available statuses from the controller and prints it as a nice formated string. */ + void printStatusString(); /** * Read the temperature from the Move controller. * @return The temperature in degrees Celsius. diff --git a/PS3USB.cpp b/PS3USB.cpp index 7a15bb37..fa865495 100644 --- a/PS3USB.cpp +++ b/PS3USB.cpp @@ -362,39 +362,37 @@ bool PS3USB::getStatus(StatusEnum c) { return (readBuf[((uint16_t)c >> 8) - 9] == ((uint8_t)c & 0xff)); } -String PS3USB::getStatusString() { +void PS3USB::printStatusString() { + char statusOutput[100]; // Max string length plus null character if(PS3Connected || PS3NavigationConnected) { - char statusOutput[100]; + strcpy_P(statusOutput, PSTR("ConnectionStatus: ")); - strcpy(statusOutput, "ConnectionStatus: "); + if(getStatus(Plugged)) strcat_P(statusOutput, PSTR("Plugged")); + else if(getStatus(Unplugged)) strcat_P(statusOutput, PSTR("Unplugged")); + else strcat_P(statusOutput, PSTR("Error")); - if(getStatus(Plugged)) strcat(statusOutput, "Plugged"); - else if(getStatus(Unplugged)) strcat(statusOutput, "Unplugged"); - else strcat(statusOutput, "Error"); + strcat_P(statusOutput, PSTR(" - PowerRating: ")); + if(getStatus(Charging)) strcat_P(statusOutput, PSTR("Charging")); + else if(getStatus(NotCharging)) strcat_P(statusOutput, PSTR("Not Charging")); + else if(getStatus(Shutdown)) strcat_P(statusOutput, PSTR("Shutdown")); + else if(getStatus(Dying)) strcat_P(statusOutput, PSTR("Dying")); + else if(getStatus(Low)) strcat_P(statusOutput, PSTR("Low")); + else if(getStatus(High)) strcat_P(statusOutput, PSTR("High")); + else if(getStatus(Full)) strcat_P(statusOutput, PSTR("Full")); + else strcat_P(statusOutput, PSTR("Error")); - strcat(statusOutput, " - PowerRating: "); + strcat_P(statusOutput, PSTR(" - WirelessStatus: ")); - if(getStatus(Charging)) strcat(statusOutput, "Charging"); - else if(getStatus(NotCharging)) strcat(statusOutput, "Not Charging"); - else if(getStatus(Shutdown)) strcat(statusOutput, "Shutdown"); - else if(getStatus(Dying)) strcat(statusOutput, "Dying"); - else if(getStatus(Low)) strcat(statusOutput, "Low"); - else if(getStatus(High)) strcat(statusOutput, "High"); - else if(getStatus(Full)) strcat(statusOutput, "Full"); - else strcat(statusOutput, "Error"); - - strcat(statusOutput, " - WirelessStatus: "); - - if(getStatus(CableRumble)) strcat(statusOutput, "Cable - Rumble is on"); - else if(getStatus(Cable)) strcat(statusOutput, "Cable - Rumble is off"); - else if(getStatus(BluetoothRumble)) strcat(statusOutput, "Bluetooth - Rumble is on"); - else if(getStatus(Bluetooth)) strcat(statusOutput, "Bluetooth - Rumble is off"); - else strcat(statusOutput, "Error"); - - return statusOutput; + if(getStatus(CableRumble)) strcat_P(statusOutput, PSTR("Cable - Rumble is on")); + else if(getStatus(Cable)) strcat_P(statusOutput, PSTR("Cable - Rumble is off")); + else if(getStatus(BluetoothRumble)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is on")); + else if(getStatus(Bluetooth)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is off")); + else strcat_P(statusOutput, PSTR("Error")); } else - return "Error"; + strcpy_P(statusOutput, PSTR("Error")); + + USB_HOST_SERIAL.write((uint8_t*)statusOutput, strlen(statusOutput)); } /* Playstation Sixaxis Dualshock and Navigation Controller commands */ diff --git a/PS3USB.h b/PS3USB.h index dde40d5c..5bbbdf2e 100644 --- a/PS3USB.h +++ b/PS3USB.h @@ -193,11 +193,8 @@ public: * @return True if correct and false if not. */ bool getStatus(StatusEnum c); - /** - * Read all the available ::StatusEnum from the controller. - * @return One large string with all the information. - */ - String getStatusString(); + /** Read all the available statuses from the controller and prints it as a nice formated string. */ + void printStatusString(); /** Used to set all LEDs and rumble off. */ void setAllOff(); diff --git a/examples/Bluetooth/PS3BT/PS3BT.ino b/examples/Bluetooth/PS3BT/PS3BT.ino index 87cc9939..3cb0ae7a 100644 --- a/examples/Bluetooth/PS3BT/PS3BT.ino +++ b/examples/Bluetooth/PS3BT/PS3BT.ino @@ -111,7 +111,7 @@ void loop() { if (PS3.getButtonClick(SELECT)) { Serial.print(F("\r\nSelect - ")); - Serial.print(PS3.getStatusString()); + PS3.printStatusString(); } if (PS3.getButtonClick(START)) { Serial.print(F("\r\nStart")); @@ -163,7 +163,7 @@ void loop() { PS3.moveSetBulb(Off); Serial.print(F("\r\nMove")); Serial.print(F(" - ")); - Serial.print(PS3.getStatusString()); + PS3.printStatusString(); } } if (printAngle) { diff --git a/examples/Bluetooth/PS3Multi/PS3Multi.ino b/examples/Bluetooth/PS3Multi/PS3Multi.ino index 20f0da8d..9ce39857 100644 --- a/examples/Bluetooth/PS3Multi/PS3Multi.ino +++ b/examples/Bluetooth/PS3Multi/PS3Multi.ino @@ -116,7 +116,7 @@ void loop() { if (PS3[i]->getButtonClick(SELECT)) { Serial.print(F("\r\nSelect - ")); - Serial.print(PS3[i]->getStatusString()); + PS3[i]->printStatusString(); } if (PS3[i]->getButtonClick(START)) { Serial.print(F("\r\nStart")); diff --git a/examples/Bluetooth/PS3SPP/PS3SPP.ino b/examples/Bluetooth/PS3SPP/PS3SPP.ino index ed346d90..6bc7afc6 100644 --- a/examples/Bluetooth/PS3SPP/PS3SPP.ino +++ b/examples/Bluetooth/PS3SPP/PS3SPP.ino @@ -141,8 +141,7 @@ void loop() { output += " - R3"; if (PS3.getButtonClick(SELECT)) { - output += " - Select - "; - output += PS3.getStatusString(); + output += " - Select"; } if (PS3.getButtonClick(START)) output += " - Start"; diff --git a/examples/PS3USB/PS3USB.ino b/examples/PS3USB/PS3USB.ino index e05f55b5..2db3afd5 100644 --- a/examples/PS3USB/PS3USB.ino +++ b/examples/PS3USB/PS3USB.ino @@ -96,7 +96,7 @@ void loop() { if (PS3.getButtonClick(SELECT)) { Serial.print(F("\r\nSelect - ")); - Serial.print(PS3.getStatusString()); + PS3.printStatusString(); } if (PS3.getButtonClick(START)) { Serial.print(F("\r\nStart")); diff --git a/keywords.txt b/keywords.txt index c04041ab..1c987a4e 100644 --- a/keywords.txt +++ b/keywords.txt @@ -52,7 +52,7 @@ getSensor KEYWORD2 getAngle KEYWORD2 get9DOFValues KEYWORD2 getStatus KEYWORD2 -getStatusString KEYWORD2 +printStatusString KEYWORD2 getTemperature KEYWORD2 disconnect KEYWORD2 From e9bd896ca2a8bc40bd3e6e628446d53a65e96837 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 10 Jan 2014 17:44:51 +0100 Subject: [PATCH 065/145] Added support for the PS4 controller via Bluetooth --- BTD.cpp | 43 ++++--- BTD.h | 3 + BTHID.cpp | 4 +- PS4BT.cpp | 117 +++++++++++++++++++ PS4BT.h | 176 +++++++++++++++++++++++++++++ controllerEnums.h | 6 + examples/Bluetooth/PS4BT/PS4BT.ino | 98 ++++++++++++++++ keywords.txt | 7 +- 8 files changed, 438 insertions(+), 16 deletions(-) create mode 100644 PS4BT.cpp create mode 100644 PS4BT.h create mode 100644 examples/Bluetooth/PS4BT/PS4BT.ino diff --git a/BTD.cpp b/BTD.cpp index 7fc278da..b646b160 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -302,6 +302,7 @@ void BTD::Initialize() { incomingWii = false; connectToHIDDevice = false; incomingHIDDevice = false; + incomingPS4 = false; bAddress = 0; // Clear device address bNumEP = 1; // Must have to be reset to 1 qNextPollTime = 0; // Reset next poll time @@ -434,7 +435,6 @@ void BTD::HCI_event_task() { #endif for(uint8_t i = 0; i < hcibuf[2]; i++) { uint8_t offset = 8 * hcibuf[2] + 3 * i; - uint8_t classOfDevice[3]; for(uint8_t j = 0; j < 3; j++) classOfDevice[j] = hcibuf[j + 4 + offset]; @@ -450,12 +450,14 @@ void BTD::HCI_event_task() { hci_set_flag(HCI_FLAG_DEVICE_FOUND); break; - } else if(pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC0)) { // Check if it is a mouse or keyboard - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html + } else if(pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html #ifdef DEBUG_USB_HOST if(classOfDevice[0] & 0x80) Notify(PSTR("\r\nMouse found"), 0x80); if(classOfDevice[0] & 0x40) Notify(PSTR("\r\nKeyboard found"), 0x80); + if(classOfDevice[0] & 0x08) + Notify(PSTR("\r\nGamepad found"), 0x80); #endif for(uint8_t j = 0; j < 6; j++) @@ -516,23 +518,28 @@ void BTD::HCI_event_task() { for(uint8_t i = 0; i < 6; i++) disc_bdaddr[i] = hcibuf[i + 2]; - if((hcibuf[9] & 0x05) && (hcibuf[8] & 0xC0)) { // Check if it is a mouse or keyboard + for(uint8_t i = 0; i < 3; i++) + classOfDevice[i] = hcibuf[i + 8]; + + if((classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad #ifdef DEBUG_USB_HOST - if(hcibuf[8] & 0x80) + if(classOfDevice[0] & 0x80) Notify(PSTR("\r\nMouse is connecting"), 0x80); - if(hcibuf[8] & 0x40) + if(classOfDevice[0] & 0x40) Notify(PSTR("\r\nKeyboard is connecting"), 0x80); + if(classOfDevice[0] & 0x08) + Notify(PSTR("\r\nGamepad is connecting"), 0x80); #endif incomingHIDDevice = true; } #ifdef EXTRADEBUG Notify(PSTR("\r\nClass of device: "), 0x80); - D_PrintHex (hcibuf[10], 0x80); + D_PrintHex (classOfDevice[2], 0x80); Notify(PSTR(" "), 0x80); - D_PrintHex (hcibuf[9], 0x80); + D_PrintHex (classOfDevice[1], 0x80); Notify(PSTR(" "), 0x80); - D_PrintHex (hcibuf[8], 0x80); + D_PrintHex (classOfDevice[0], 0x80); #endif hci_set_flag(HCI_FLAG_INCOMING_REQUEST); break; @@ -816,6 +823,12 @@ void BTD::HCI_task() { wiiUProController = false; } } + if(classOfDevice[2] == 0 && classOfDevice[1] == 0x25 && classOfDevice[0] == 0x08 && strncmp((const char*)remote_name, "Wireless Controller", 19) == 0) { +#ifdef DEBUG_USB_HOST + Notify(PSTR("\r\nPS4 controller is connecting"), 0x80); +#endif + incomingPS4 = true; + } if(pairWithWii && motionPlusInside) hci_state = HCI_CONNECT_DEVICE_STATE; else { @@ -835,6 +848,9 @@ void BTD::HCI_task() { } D_PrintHex (disc_bdaddr[0], 0x80); #endif + if(incomingPS4) + connectToHIDDevice = true; // We should always connect to the PS4 controller + // Clear these flags for a new connection l2capConnectionClaimed = false; sdpConnectionClaimed = false; @@ -866,6 +882,7 @@ void BTD::HCI_task() { connectToWii = incomingWii = pairWithWii = false; connectToHIDDevice = incomingHIDDevice = pairWithHIDDevice = false; + incomingPS4 = false; hci_state = HCI_SCANNING_STATE; } @@ -967,7 +984,7 @@ void BTD::hci_accept_connection() { hcibuf[6] = disc_bdaddr[3]; hcibuf[7] = disc_bdaddr[4]; hcibuf[8] = disc_bdaddr[5]; - hcibuf[9] = 0x00; //switch role to master + hcibuf[9] = 0x00; // Switch role to master HCI_Command(hcibuf, 10); } @@ -983,10 +1000,10 @@ void BTD::hci_remote_name() { hcibuf[6] = disc_bdaddr[3]; hcibuf[7] = disc_bdaddr[4]; hcibuf[8] = disc_bdaddr[5]; - hcibuf[9] = 0x01; //Page Scan Repetition Mode - hcibuf[10] = 0x00; //Reserved - hcibuf[11] = 0x00; //Clock offset - low byte - hcibuf[12] = 0x00; //Clock offset - high byte + hcibuf[9] = 0x01; // Page Scan Repetition Mode + hcibuf[10] = 0x00; // Reserved + hcibuf[11] = 0x00; // Clock offset - low byte + hcibuf[12] = 0x00; // Clock offset - high byte HCI_Command(hcibuf, 13); } diff --git a/BTD.h b/BTD.h index bacd38c3..0fa6de70 100755 --- a/BTD.h +++ b/BTD.h @@ -571,6 +571,9 @@ private: uint8_t pollInterval; bool bPollEnable; + bool incomingPS4; // True if a PS4 controller is connecting + uint8_t classOfDevice[3]; // Class of device of last device + /* Variables used by high level HCI task */ uint8_t hci_state; //current state of bluetooth hci connection uint16_t hci_counter; // counter used for bluetooth hci reset loops diff --git a/BTHID.cpp b/BTHID.cpp index 3a84ed2d..d6accb58 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -192,14 +192,14 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { case 0x01: // Keyboard events if(pRptParser[KEYBOARD_PARSER_ID]) { uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); - pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)length, &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance + pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance } break; case 0x02: // Mouse events if(pRptParser[MOUSE_PARSER_ID]) { uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); - pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)length, &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance + pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance } break; #ifdef DEBUG_USB_HOST diff --git a/PS4BT.cpp b/PS4BT.cpp new file mode 100644 index 00000000..abab9cfc --- /dev/null +++ b/PS4BT.cpp @@ -0,0 +1,117 @@ +/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved. + + This software may be distributed and modified under the terms of the GNU + General Public License version 2 (GPL2) as published by the Free Software + Foundation and appearing in the file GPL2.TXT included in the packaging of + this file. Please note that GPL2 Section 2[b] requires that all works based + on this software must also be made publicly available under the terms of + the GPL2 ("Copyleft"). + + Contact information + ------------------- + + Kristian Lauszus, TKJ Electronics + Web : http://www.tkjelectronics.com + e-mail : kristianl@tkjelectronics.com + */ + +#include "PS4BT.h" + +// To enable serial debugging see "settings.h" +//#define PRINTREPORT // Uncomment to print the report send by the PS4 Controller + +/** Buttons on the controller */ +const uint8_t PS4_BUTTONS[] PROGMEM = { + DPAD_UP, // UP + DPAD_RIGHT, // RIGHT + DPAD_DOWN, // DOWN + DPAD_LEFT, // LEFT + + 0x0C, // SHARE + 0x0D, // OPTIONS + 0x0E, // L3 + 0x0F, // R3 + + 0x0A, // L2 + 0x0B, // R2 + 0x08, // L1 + 0x09, // R1 + + 0x07, // TRIANGLE + 0x06, // CIRCLE + 0x05, // CROSS + 0x04, // SQUARE + + 0x10, // PS + 0x11, // KEYPAD +}; + +/** Analog buttons on the controller */ +const uint8_t PS4_ANALOG_BUTTONS[] PROGMEM = { + 0, 0, 0, 0, 0, 0, 0, 0, // Skip UP_ANALOG, RIGHT_ANALOG, DOWN_ANALOG, LEFT_ANALOG, SELECT, L3, R3 and START + 0, // L2_ANALOG + 1, // R2_ANALOG +}; + +bool PS4BT::checkDpad(PS4Buttons ps4Buttons, DPADEnum b) { + return ps4Buttons.dpad == b; +} + +bool PS4BT::getButtonPress(ButtonEnum b) { + uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); + if (b < 4) // Dpad + return checkDpad(ps4Data.btn, (DPADEnum)button); + else { + uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; + uint8_t mask = (1 << (button - 8 * index)); + return ps4Data.btn.val[index] & mask; + } +} + +bool PS4BT::getButtonClick(ButtonEnum b) { + uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); + if (b < 4) { // Dpad + if (checkDpad(buttonClickState, (DPADEnum)button)) { + buttonClickState.dpad = DPAD_OFF; + return true; + } + return false; + } else { + uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; + uint8_t mask = (1 << (button - 8 * index)); + + bool click = buttonClickState.val[index] & mask; + buttonClickState.val[index] &= ~mask; // Clear "click" event + return click; + } +} + +uint8_t PS4BT::getAnalogButton(ButtonEnum a) { + return (uint8_t)(ps4Data.trigger[pgm_read_byte(&PS4_ANALOG_BUTTONS[(uint8_t)a])]); +} + +uint8_t PS4BT::getAnalogHat(AnalogHatEnum a) { + return ps4Data.hatValue[(uint8_t)a]; +} + +void PS4BT::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { + if (len == sizeof(PS4Data) && buf) { + memcpy(&ps4Data, buf, len); + + for (uint8_t i = 0; i < sizeof(ps4Data.btn); i++) { + if (ps4Data.btn.val[i] != oldButtonState.val[i]) { + buttonClickState.val[i] = ps4Data.btn.val[i] & ~oldButtonState.val[i]; // Update click state variable + oldButtonState.val[i] = ps4Data.btn.val[i]; + if (i == 0) + buttonClickState.dpad = ps4Data.btn.dpad; // The DPAD buttons does not set the different bits, but set a value corresponding to the buttons pressed + } + } +#ifdef PRINTREPORT + for (uint8_t i = 0; i < len; i++) { + D_PrintHex (buf[i], 0x80); + Notify(PSTR(" "), 0x80); + } + Notify(PSTR("\r\n"), 0x80); +#endif + } +} \ No newline at end of file diff --git a/PS4BT.h b/PS4BT.h new file mode 100644 index 00000000..207cec4f --- /dev/null +++ b/PS4BT.h @@ -0,0 +1,176 @@ +/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved. + + This software may be distributed and modified under the terms of the GNU + General Public License version 2 (GPL2) as published by the Free Software + Foundation and appearing in the file GPL2.TXT included in the packaging of + this file. Please note that GPL2 Section 2[b] requires that all works based + on this software must also be made publicly available under the terms of + the GPL2 ("Copyleft"). + + Contact information + ------------------- + + Kristian Lauszus, TKJ Electronics + Web : http://www.tkjelectronics.com + e-mail : kristianl@tkjelectronics.com + */ + +#ifndef _ps4bt_h_ +#define _ps4bt_h_ + +#include "BTHID.h" +#include "PS3Enums.h" + +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, +}; + +union PS4Buttons { + struct { + uint8_t dpad : 4; + uint8_t square : 1; + uint8_t cross : 1; + uint8_t circle : 1; + uint8_t triangle : 1; + + uint8_t l1 : 1; + uint8_t r1 : 1; + uint8_t l2 : 1; + uint8_t r2 : 1; + uint8_t share : 1; + uint8_t options : 1; + uint8_t l3 : 1; + uint8_t r3 : 1; + + uint8_t ps : 1; + uint8_t keypad : 1; + uint8_t dummy : 6; + }; + uint8_t val[3]; +}; + +struct PS4Data { + uint8_t hatValue[4]; + PS4Buttons btn; + uint8_t trigger[2]; +}; + +/** This BluetoothService class implements support for the PS4 controller via Bluetooth. */ +class PS4BT : public HIDReportParser { +public: + /** + * Constructor for the PS4BT class. + * @param p Pointer to the BTD class instance. + */ + PS4BT(BTHID *p) : + pBthid(p) { + pBthid->SetReportParser(KEYBOARD_PARSER_ID, this); + Reset(); + }; + + virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf); + + /** @name PS4 Controller functions */ + /** + * getButtonPress(ButtonEnum b) will return true as long as the button is held down. + * + * While getButtonClick(ButtonEnum b) will only return it once. + * + * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). + * @param b ::ButtonEnum to read. + * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press. + */ + bool getButtonPress(ButtonEnum b); + bool getButtonClick(ButtonEnum b); + /**@}*/ + /** @name PS4 Controller functions */ + /** + * Used to get the analog value from button presses. + * @param a The ::ButtonEnum to read. + * The supported buttons are: + * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2, + * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T. + * @return Analog value in the range of 0-255. + */ + uint8_t getAnalogButton(ButtonEnum a); + + /** + * Used to read the analog joystick. + * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY. + * @return Return the analog value in the range of 0-255. + */ + uint8_t getAnalogHat(AnalogHatEnum a); + /**@}*/ + + /** True if a device is connected */ + bool connected() { + if (pBthid) + return pBthid->connected; + return false; + }; + + /** Used this to disconnect the devices. */ + void disconnect() { + if (pBthid) + pBthid->disconnect(); + }; + + /** Call this to start the paring sequence with a device */ + void pair(void) { + if (pBthid) + pBthid->pair(); + }; + + void Reset() { + uint8_t i; + for (0; i < sizeof(ps4Data.hatValue); i++) + ps4Data.hatValue[i] = 127; + for (0; i < sizeof(PS4Buttons); i++) { + ps4Data.btn.val[i] = 0; + oldButtonState.val[i] = 0; + } + for (0; i < sizeof(ps4Data.trigger); i++) + ps4Data.trigger[i] = 0; + + ps4Data.btn.dpad = DPAD_OFF; + oldButtonState.dpad = DPAD_OFF; + buttonClickState.dpad = DPAD_OFF; + }; + + /** + * Used to call your own function when the device is successfully initialized. + * @param funcOnInit Function to call. + */ + void attachOnInit(void (*funcOnInit)(void)) { + pFuncOnInit = funcOnInit; + }; + +private: + /** + * Called when a device is successfully initialized. + * Use attachOnInit(void (*funcOnInit)(void)) to call your own function. + * This is useful for instance if you want to set the LEDs in a specific way. + */ + void onInit() { + Reset(); + if(pFuncOnInit) + pFuncOnInit(); // Call the user function + }; + void (*pFuncOnInit)(void); // Pointer to function called in onInit() + + bool checkDpad(PS4Buttons ps4Buttons, DPADEnum b); // Used to check PS4 DPAD buttons + + BTHID *pBthid; // Pointer to BTHID instance + PS4Data ps4Data; + PS4Buttons oldButtonState, buttonClickState; +}; +#endif \ No newline at end of file diff --git a/controllerEnums.h b/controllerEnums.h index b5129725..700e50a2 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -94,6 +94,12 @@ enum ButtonEnum { T = 18, // Covers 12 bits - we only need to read the top 8 /**@}*/ + /** PS4 controllers buttons - SHARE and OPTIONS are present instead of SELECT and START */ + SHARE = 4, + OPTIONS = 5, + KEYPAD = 17, + /**@}*/ + /**@{*/ /** Xbox buttons */ BACK = 4, diff --git a/examples/Bluetooth/PS4BT/PS4BT.ino b/examples/Bluetooth/PS4BT/PS4BT.ino new file mode 100644 index 00000000..220014e2 --- /dev/null +++ b/examples/Bluetooth/PS4BT/PS4BT.ino @@ -0,0 +1,98 @@ +/* + Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus + For more information visit my blog: http://blog.tkjelectronics.dk/ or + send me an e-mail: kristianl@tkjelectronics.com + */ + +#include +#include + +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif + +USB Usb; +//USBHub Hub1(&Usb); // Some dongles have a hub inside +BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so + +/* You can create the instance of the BTHID class in two ways */ +// This will start an inquiry and then pair with the PS4 controller - you only have to do this once +BTHID bthid(&Btd, PAIR); + +// After that you can simply create the instance like so and then press the PS button on the device +//BTHID bthid(&Btd); + +PS4BT PS4(&bthid); // You should not modify this instance + +void setup() { + Serial.begin(115200); + while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection + if (Usb.Init() == -1) { + Serial.print(F("\r\nOSC did not start")); + while (1); // Halt + } + Serial.print(F("\r\nPS4 Bluetooth Library Started")); +} +void loop() { + Usb.Task(); + + if (PS4.connected()) { + if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117) { + Serial.print(F("\r\nLeftHatX: ")); + Serial.print(PS4.getAnalogHat(LeftHatX)); + Serial.print(F("\tLeftHatY: ")); + Serial.print(PS4.getAnalogHat(LeftHatY)); + Serial.print(F("\tRightHatX: ")); + Serial.print(PS4.getAnalogHat(RightHatX)); + Serial.print(F("\tRightHatY: ")); + Serial.print(PS4.getAnalogHat(RightHatY)); + } + + if (PS4.getAnalogButton(L2) || PS4.getAnalogButton(R2)) { // These are the only analog buttons on the PS4 controller + Serial.print(F("\r\nL2: ")); + Serial.print(PS4.getAnalogButton(L2)); + Serial.print(F("\tR2: ")); + Serial.print(PS4.getAnalogButton(R2)); + } + if (PS4.getButtonClick(PS)) { + Serial.print(F("\r\nPS")); + PS4.disconnect(); + } + else { + if (PS4.getButtonClick(TRIANGLE)) + Serial.print(F("\r\nTraingle")); + if (PS4.getButtonClick(CIRCLE)) + Serial.print(F("\r\nCircle")); + if (PS4.getButtonClick(CROSS)) + Serial.print(F("\r\nCross")); + if (PS4.getButtonClick(SQUARE)) + Serial.print(F("\r\nSquare")); + + if (PS4.getButtonClick(UP)) + Serial.print(F("\r\nUp")); + if (PS4.getButtonClick(RIGHT)) + Serial.print(F("\r\nRight")); + if (PS4.getButtonClick(DOWN)) + Serial.print(F("\r\nDown")); + if (PS4.getButtonClick(LEFT)) + Serial.print(F("\r\nLeft")); + + if (PS4.getButtonClick(L1)) + Serial.print(F("\r\nL1")); + if (PS4.getButtonClick(L3)) + Serial.print(F("\r\nL3")); + if (PS4.getButtonClick(R1)) + Serial.print(F("\r\nR1")); + if (PS4.getButtonClick(R3)) + Serial.print(F("\r\nR3")); + + if (PS4.getButtonClick(SHARE)) + Serial.print(F("\r\nShare")); + if (PS4.getButtonClick(OPTIONS)) + Serial.print(F("\r\nOptions")); + if (PS4.getButtonClick(KEYPAD)) + Serial.print(F("\r\nKeypad")); + } + } +} diff --git a/keywords.txt b/keywords.txt index 1c987a4e..4f3cd1a9 100644 --- a/keywords.txt +++ b/keywords.txt @@ -25,13 +25,14 @@ BTD KEYWORD1 Task KEYWORD2 #################################################### -# Syntax Coloring Map For PS3 Bluetooth/USB Library +# Syntax Coloring Map For PS3/PS4 Bluetooth/USB Library #################################################### #################################################### # Datatypes (KEYWORD1) #################################################### +PS4BT KEYWORD1 PS3BT KEYWORD1 PS3USB KEYWORD1 @@ -118,6 +119,10 @@ PS LITERAL1 MOVE LITERAL1 T LITERAL1 +SHARE LITERAL1 +OPTIONS LITERAL1 +KEYPAD LITERAL1 + LeftHatX LITERAL1 LeftHatY LITERAL1 RightHatX LITERAL1 From c98832a9e6c6903bff0a774f0e178abc9316935e Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 10 Jan 2014 18:07:28 +0100 Subject: [PATCH 066/145] Updated submodules --- examples/testusbhostFAT/Arduino_Makefile_master | 2 +- examples/testusbhostFAT/xmem2 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/testusbhostFAT/Arduino_Makefile_master b/examples/testusbhostFAT/Arduino_Makefile_master index 139b9c8b..1cacea4e 160000 --- a/examples/testusbhostFAT/Arduino_Makefile_master +++ b/examples/testusbhostFAT/Arduino_Makefile_master @@ -1 +1 @@ -Subproject commit 139b9c8be59a62e8fb1e8f983ac9bac2b9b9d582 +Subproject commit 1cacea4e8933b37b9f98528b2a831031f69905de diff --git a/examples/testusbhostFAT/xmem2 b/examples/testusbhostFAT/xmem2 index 9fe733d3..029e3dab 160000 --- a/examples/testusbhostFAT/xmem2 +++ b/examples/testusbhostFAT/xmem2 @@ -1 +1 @@ -Subproject commit 9fe733d35304dec1ebe750f5f13f868def2fcfe4 +Subproject commit 029e3dab4c885669cddaa59f3dc8fdc71d152792 From 3ea4b073f53ebeb6732afdd6767c5cb0610c46c5 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 10 Jan 2014 18:15:12 +0100 Subject: [PATCH 067/145] Updated documentation typo --- XBOXRECV.h | 2 +- XBOXUSB.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/XBOXRECV.h b/XBOXRECV.h index 41ebef47..c3964991 100644 --- a/XBOXRECV.h +++ b/XBOXRECV.h @@ -173,7 +173,7 @@ public: */ void setRumbleOn(uint8_t lValue, uint8_t rValue, uint8_t controller = 0); /** - * Set LED value. Without using the ::LEDEnum or ::LEDMode enum. + * Set LED value. Without using the ::LEDEnum or ::LEDModeEnum. * @param value See: * setLedOff(uint8_t controller), setLedOn(uint8_t controller, LED l), * setLedBlink(uint8_t controller, LED l), and setLedMode(uint8_t controller, LEDMode lm). diff --git a/XBOXUSB.h b/XBOXUSB.h index 2b358fad..c18ea248 100644 --- a/XBOXUSB.h +++ b/XBOXUSB.h @@ -149,7 +149,7 @@ public: */ void setRumbleOn(uint8_t lValue, uint8_t rValue); /** - * Set LED value. Without using the ::LEDEnum or ::LEDMode enum. + * Set LED value. Without using the ::LEDEnum or ::LEDModeEnum. * @param value See: * setLedOff(), setLedOn(LEDEnum l), * setLedBlink(LEDEnum l), and setLedMode(LEDModeEnum lm). @@ -172,7 +172,7 @@ public: void setLedBlink(LEDEnum l); /** * Used to set special LED modes supported by the Xbox controller. - * @param lm See ::LEDMode. + * @param lm See ::LEDModeEnum. */ void setLedMode(LEDModeEnum lm); From 50561533255416f80525a2cb5c7c58902daabd84 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 10 Jan 2014 18:23:22 +0100 Subject: [PATCH 068/145] Updated comment --- PS4BT.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/PS4BT.h b/PS4BT.h index 207cec4f..d6db3d2b 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -63,7 +63,10 @@ struct PS4Data { uint8_t trigger[2]; }; -/** This BluetoothService class implements support for the PS4 controller via Bluetooth. */ +/** + * This class implements support for the PS4 controller via Bluetooth. + * It uses the BTHID class for all the Bluetooth communication. + */ class PS4BT : public HIDReportParser { public: /** From 22efbd4d603c6fcb6281607080326ea2bfaf8727 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 12 Jan 2014 16:05:17 +0100 Subject: [PATCH 069/145] Added information about the PS4 library --- README.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 95ba475a..640c6764 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ For more information about the hardware see the [Hardware Manual](http://www.cir * __Alexei Glushchenko, Circuits@Home__ - * Developers of the USB Core, HID, FTDI, ADK, ACM, and PL2303 libraries * __Kristian Lauszus, TKJ Electronics__ - - * Developer of the [BTD](#bluetooth-libraries), [BTHID](#bthid-library), [SPP](#spp-library), [PS3](#ps3-library), [Wii](#wii-library), and [Xbox](#xbox-library) libraries + * Developer of the [BTD](#bluetooth-libraries), [BTHID](#bthid-library), [SPP](#spp-library), [PS4](#ps4-library), [PS3](#ps3-library), [Wii](#wii-library), and [Xbox](#xbox-library) libraries * __Andrew Kroll__ - * Major contributor to mass storage code @@ -97,6 +97,8 @@ Currently HID mice and keyboards are supported. 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. +The [PS4 library](#ps4-library) also uses this class to handle all Bluetooth communication. + ### [SPP library](SPP.cpp) 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. @@ -112,6 +114,20 @@ More information can be found at these blog posts: To implement the SPP protocol I used a Bluetooth sniffing tool called [PacketLogger](http://www.tkjelectronics.com/uploads/PacketLogger.zip) developed by Apple. It enables me to see the Bluetooth communication between my Mac and any device. +### PS4 Library + +This is the [PS4BT](PS4BT.cpp) library. It works with the official Sony PS4 controller via Bluetooth. + +The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) example shows how to easily read the buttons and joysticks on the controller. + +I still have not figured out how to read the touchpad, turn rumble on and off and set the color of the light, but hopefully I will figure that out soon. + +Before you can use the PS4 controller you will need to pair with it. + +Simply create the BTHID instance like so: ```BTHID bthid(&Btd, PAIR);``` and then hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode. + +It should then automatically pair the dongle with your controller. This only have to be done once. + ### PS3 Library 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. From 7469ff099e612e3d348b882a9fae37f5d5c280e4 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 12 Jan 2014 16:31:47 +0100 Subject: [PATCH 070/145] Typos, whitespace and some other cleanup stuff --- BTD.cpp | 8 +++--- BTD.h | 34 ++++++++++++------------ PS4BT.cpp | 12 ++++----- examples/Bluetooth/BTHID/BTHID.ino | 10 +++---- examples/Bluetooth/PS3BT/PS3BT.ino | 4 +-- examples/Bluetooth/PS3Multi/PS3Multi.ino | 2 +- examples/Bluetooth/PS3SPP/PS3SPP.ino | 4 +-- examples/Bluetooth/PS4BT/PS4BT.ino | 1 + 8 files changed, 38 insertions(+), 37 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index b646b160..9b0d8ab5 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -36,7 +36,7 @@ qNextPollTime(0), // Reset NextPollTime pollInterval(0), bPollEnable(false) // Don't start polling before dongle is connected { - for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) + for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) btService[i] = NULL; Initialize(); // Set all variables, endpoint structs etc. to default values @@ -293,7 +293,7 @@ void BTD::Initialize() { epInfo[i].epAttribs = 0; epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; } - for(i = 0; i < BTD_NUMSERVICES; i++) { + for(i = 0; i < BTD_NUM_SERVICES; i++) { if(btService[i]) btService[i]->Reset(); // Reset all Bluetooth services } @@ -898,7 +898,7 @@ void BTD::ACL_event_task() { if(!rcode) { // Check for errors if(length > 0) { // Check if any data was read - for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) { + for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) { if(btService[i]) btService[i]->ACLData(l2capinbuf); } @@ -910,7 +910,7 @@ void BTD::ACL_event_task() { D_PrintHex (rcode, 0x80); } #endif - for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) + for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) if(btService[i]) btService[i]->Run(); } diff --git a/BTD.h b/BTD.h index 0fa6de70..609b8c2a 100755 --- a/BTD.h +++ b/BTD.h @@ -187,7 +187,7 @@ #define WI_PROTOCOL_BT 0x01 // Bluetooth Programming Interface #define BTD_MAX_ENDPOINTS 4 -#define BTD_NUMSERVICES 4 // Max number of Bluetooth services - if you need more than 4 simply increase this number +#define BTD_NUM_SERVICES 4 // Max number of Bluetooth services - if you need more than 4 simply increase this number #define PAIR 1 @@ -237,7 +237,7 @@ public: /** @name USBDeviceConfig implementation */ /** - * Address assignment and basic initilization is done here. + * Address assignment and basic initialization is done here. * @param parent Hub number. * @param port Port number on the hub. * @param lowspeed Speed of the device. @@ -258,7 +258,7 @@ public: */ virtual uint8_t Release(); /** - * Poll the USB Input endpoins and run the state machines. + * Poll the USB Input endpoints and run the state machines. * @return 0 on success. */ virtual uint8_t Poll(); @@ -320,18 +320,18 @@ public: /** Disconnects both the L2CAP Channel and the HCI Connection for all Bluetooth services. */ void disconnect() { - for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) + for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) if(btService[i]) btService[i]->disconnect(); }; /** - * Register bluetooth dongle members/services. + * Register Bluetooth dongle members/services. * @param pService Pointer to BluetoothService class instance. - * @return The serice ID on succes or -1 on fail. + * @return The service ID on success or -1 on fail. */ int8_t registerServiceClass(BluetoothService *pService) { - for(uint8_t i = 0; i < BTD_NUMSERVICES; i++) { + for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) { if(!btService[i]) { btService[i] = pService; return i; // Return ID @@ -501,7 +501,7 @@ public: pairWithWii = true; hci_state = HCI_CHECK_DEVICE_SERVICE; }; - /** Used to only send the ACL data to the wiimote. */ + /** Used to only send the ACL data to the Wiimote. */ bool connectToWii; /** True if a Wiimote is connecting. */ bool incomingWii; @@ -517,7 +517,7 @@ public: pairWithHIDDevice = true; hci_state = HCI_CHECK_DEVICE_SERVICE; }; - /** Used to only send the ACL data to the wiimote. */ + /** Used to only send the ACL data to the Wiimote. */ bool connectToHIDDevice; /** True if a Wiimote is connecting. */ bool incomingHIDDevice; @@ -564,7 +564,7 @@ protected: private: void Initialize(); // Set all variables, endpoint structs etc. to default values - BluetoothService* btService[BTD_NUMSERVICES]; + BluetoothService *btService[BTD_NUM_SERVICES]; uint16_t PID, VID; // PID and VID of device connected @@ -575,15 +575,15 @@ private: uint8_t classOfDevice[3]; // Class of device of last device /* Variables used by high level HCI task */ - uint8_t hci_state; //current state of bluetooth hci connection - uint16_t hci_counter; // counter used for bluetooth hci reset loops - uint16_t hci_num_reset_loops; // this value indicate how many times it should read before trying to reset - uint16_t hci_event_flag; // hci flags of received bluetooth events + uint8_t hci_state; // Current state of Bluetooth HCI connection + uint16_t hci_counter; // Counter used for Bluetooth HCI reset loops + uint16_t hci_num_reset_loops; // This value indicate how many times it should read before trying to reset + uint16_t hci_event_flag; // HCI flags of received Bluetooth events uint8_t inquiry_counter; - uint8_t hcibuf[BULK_MAXPKTSIZE]; //General purpose buffer for hci data - uint8_t l2capinbuf[BULK_MAXPKTSIZE]; //General purpose buffer for l2cap in data - uint8_t l2capoutbuf[14]; //General purpose buffer for l2cap out data + uint8_t hcibuf[BULK_MAXPKTSIZE]; // General purpose buffer for HCI data + uint8_t l2capinbuf[BULK_MAXPKTSIZE]; // General purpose buffer for L2CAP in data + uint8_t l2capoutbuf[14]; // General purpose buffer for L2CAP out data /* State machines */ void HCI_event_task(); // Poll the HCI event pipe diff --git a/PS4BT.cpp b/PS4BT.cpp index abab9cfc..1459761e 100644 --- a/PS4BT.cpp +++ b/PS4BT.cpp @@ -48,9 +48,9 @@ const uint8_t PS4_BUTTONS[] PROGMEM = { /** Analog buttons on the controller */ const uint8_t PS4_ANALOG_BUTTONS[] PROGMEM = { - 0, 0, 0, 0, 0, 0, 0, 0, // Skip UP_ANALOG, RIGHT_ANALOG, DOWN_ANALOG, LEFT_ANALOG, SELECT, L3, R3 and START - 0, // L2_ANALOG - 1, // R2_ANALOG + 0, 0, 0, 0, 0, 0, 0, 0, // Skip UP, RIGHT, DOWN, LEFT, SHARE, OPTIONS, L3, and R3 + 0, // L2 + 1, // R2 }; bool PS4BT::checkDpad(PS4Buttons ps4Buttons, DPADEnum b) { @@ -59,7 +59,7 @@ bool PS4BT::checkDpad(PS4Buttons ps4Buttons, DPADEnum b) { bool PS4BT::getButtonPress(ButtonEnum b) { uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); - if (b < 4) // Dpad + if (b <= LEFT) // Dpad return checkDpad(ps4Data.btn, (DPADEnum)button); else { uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; @@ -70,7 +70,7 @@ bool PS4BT::getButtonPress(ButtonEnum b) { bool PS4BT::getButtonClick(ButtonEnum b) { uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); - if (b < 4) { // Dpad + if (b <= LEFT) { // Dpad if (checkDpad(buttonClickState, (DPADEnum)button)) { buttonClickState.dpad = DPAD_OFF; return true; @@ -87,7 +87,7 @@ bool PS4BT::getButtonClick(ButtonEnum b) { } uint8_t PS4BT::getAnalogButton(ButtonEnum a) { - return (uint8_t)(ps4Data.trigger[pgm_read_byte(&PS4_ANALOG_BUTTONS[(uint8_t)a])]); + return ps4Data.trigger[pgm_read_byte(&PS4_ANALOG_BUTTONS[(uint8_t)a])]; } uint8_t PS4BT::getAnalogHat(AnalogHatEnum a) { diff --git a/examples/Bluetooth/BTHID/BTHID.ino b/examples/Bluetooth/BTHID/BTHID.ino index a38411b5..fcfd686a 100644 --- a/examples/Bluetooth/BTHID/BTHID.ino +++ b/examples/Bluetooth/BTHID/BTHID.ino @@ -20,7 +20,7 @@ BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so /* You can create the instance of the class in two ways */ // This will start an inquiry and then pair with your device - you only have to do this once // If you are using a Bluetooth keyboard, then you should type in the password on the keypad and then press enter -BTHID hid(&Btd, PAIR, "0000"); +BTHID bthid(&Btd, PAIR, "0000"); // After that you can simply create the instance like so and then press any button on the device //BTHID hid(&Btd); @@ -36,13 +36,13 @@ void setup() { while (1); // Halt } - hid.SetReportParser(KEYBOARD_PARSER_ID, (HIDReportParser*)&keyboardPrs); - hid.SetReportParser(MOUSE_PARSER_ID, (HIDReportParser*)&mousePrs); + bthid.SetReportParser(KEYBOARD_PARSER_ID, (HIDReportParser*)&keyboardPrs); + bthid.SetReportParser(MOUSE_PARSER_ID, (HIDReportParser*)&mousePrs); // If "Boot Protocol Mode" does not work, then try "Report Protocol Mode" // If that does not work either, then uncomment PRINTREPORT in BTHID.cpp to see the raw report - hid.setProtocolMode(HID_BOOT_PROTOCOL); // Boot Protocol Mode - //hid.setProtocolMode(HID_RPT_PROTOCOL); // Report Protocol Mode + bthid.setProtocolMode(HID_BOOT_PROTOCOL); // Boot Protocol Mode + //bthid.setProtocolMode(HID_RPT_PROTOCOL); // Report Protocol Mode Serial.print(F("\r\nHID Bluetooth Library Started")); } diff --git a/examples/Bluetooth/PS3BT/PS3BT.ino b/examples/Bluetooth/PS3BT/PS3BT.ino index 3cb0ae7a..982eb384 100644 --- a/examples/Bluetooth/PS3BT/PS3BT.ino +++ b/examples/Bluetooth/PS3BT/PS3BT.ino @@ -17,7 +17,7 @@ USB Usb; BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so /* You can create the instance of the class in two ways */ PS3BT PS3(&Btd); // This will just create the instance -//PS3BT PS3(&Btd,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch +//PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch boolean printTemperature; boolean printAngle; @@ -52,7 +52,7 @@ void loop() { if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) { Serial.print(F("\r\nL2: ")); Serial.print(PS3.getAnalogButton(L2)); - if (!PS3.PS3NavigationConnected) { + if (PS3.PS3Connected) { Serial.print(F("\tR2: ")); Serial.print(PS3.getAnalogButton(R2)); } diff --git a/examples/Bluetooth/PS3Multi/PS3Multi.ino b/examples/Bluetooth/PS3Multi/PS3Multi.ino index 9ce39857..23e8cd9a 100644 --- a/examples/Bluetooth/PS3Multi/PS3Multi.ino +++ b/examples/Bluetooth/PS3Multi/PS3Multi.ino @@ -56,7 +56,7 @@ void loop() { if (PS3[i]->getAnalogButton(L2) || PS3[i]->getAnalogButton(R2)) { Serial.print(F("\r\nL2: ")); Serial.print(PS3[i]->getAnalogButton(L2)); - if (!PS3[i]->PS3NavigationConnected) { + if (PS3[i]->PS3Connected) { Serial.print(F("\tR2: ")); Serial.print(PS3[i]->getAnalogButton(R2)); } diff --git a/examples/Bluetooth/PS3SPP/PS3SPP.ino b/examples/Bluetooth/PS3SPP/PS3SPP.ino index 6bc7afc6..440ea79e 100644 --- a/examples/Bluetooth/PS3SPP/PS3SPP.ino +++ b/examples/Bluetooth/PS3SPP/PS3SPP.ino @@ -26,7 +26,7 @@ BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "0000" //SPP SerialBTBT(&Btd,"Lauszus's Arduino","0000"); // You can also set the name and pin like so PS3BT PS3(&Btd); // This will just create the instance -//PS3BT PS3(&Btd,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch +//PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch boolean firstMessage = true; String output = ""; // We will store the data in this string @@ -77,7 +77,7 @@ void loop() { output += "\r\n"; output += "L2: "; output += PS3.getAnalogButton(L2); - if (!PS3.PS3NavigationConnected) { + if (PS3.PS3Connected) { output += "\tR2: "; output += PS3.getAnalogButton(R2); } diff --git a/examples/Bluetooth/PS4BT/PS4BT.ino b/examples/Bluetooth/PS4BT/PS4BT.ino index 220014e2..6715b904 100644 --- a/examples/Bluetooth/PS4BT/PS4BT.ino +++ b/examples/Bluetooth/PS4BT/PS4BT.ino @@ -18,6 +18,7 @@ BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so /* You can create the instance of the BTHID class in two ways */ // This will start an inquiry and then pair with the PS4 controller - you only have to do this once +// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode BTHID bthid(&Btd, PAIR); // After that you can simply create the instance like so and then press the PS button on the device From c163228063e327616ed0be00812d08094388048c Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 12 Jan 2014 16:33:19 +0100 Subject: [PATCH 071/145] Renamed KEYPAD to TOUCHPAD --- PS4BT.cpp | 2 +- PS4BT.h | 2 +- controllerEnums.h | 2 +- examples/Bluetooth/PS4BT/PS4BT.ino | 4 ++-- keywords.txt | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/PS4BT.cpp b/PS4BT.cpp index 1459761e..a49195a2 100644 --- a/PS4BT.cpp +++ b/PS4BT.cpp @@ -43,7 +43,7 @@ const uint8_t PS4_BUTTONS[] PROGMEM = { 0x04, // SQUARE 0x10, // PS - 0x11, // KEYPAD + 0x11, // TOUCHPAD }; /** Analog buttons on the controller */ diff --git a/PS4BT.h b/PS4BT.h index d6db3d2b..379565d4 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -51,7 +51,7 @@ union PS4Buttons { uint8_t r3 : 1; uint8_t ps : 1; - uint8_t keypad : 1; + uint8_t touchpad : 1; uint8_t dummy : 6; }; uint8_t val[3]; diff --git a/controllerEnums.h b/controllerEnums.h index 700e50a2..2cc0b789 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -97,7 +97,7 @@ enum ButtonEnum { /** PS4 controllers buttons - SHARE and OPTIONS are present instead of SELECT and START */ SHARE = 4, OPTIONS = 5, - KEYPAD = 17, + TOUCHPAD = 17, /**@}*/ /**@{*/ diff --git a/examples/Bluetooth/PS4BT/PS4BT.ino b/examples/Bluetooth/PS4BT/PS4BT.ino index 6715b904..bf068876 100644 --- a/examples/Bluetooth/PS4BT/PS4BT.ino +++ b/examples/Bluetooth/PS4BT/PS4BT.ino @@ -92,8 +92,8 @@ void loop() { Serial.print(F("\r\nShare")); if (PS4.getButtonClick(OPTIONS)) Serial.print(F("\r\nOptions")); - if (PS4.getButtonClick(KEYPAD)) - Serial.print(F("\r\nKeypad")); + if (PS4.getButtonClick(TOUCHPAD)) + Serial.print(F("\r\nTouchpad")); } } } diff --git a/keywords.txt b/keywords.txt index 4f3cd1a9..a60fe5d8 100644 --- a/keywords.txt +++ b/keywords.txt @@ -121,7 +121,7 @@ T LITERAL1 SHARE LITERAL1 OPTIONS LITERAL1 -KEYPAD LITERAL1 +TOUCHPAD LITERAL1 LeftHatX LITERAL1 LeftHatY LITERAL1 From eea5c44b962baa5929363886e8788d6de7668d5a Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 12 Jan 2014 17:20:18 +0100 Subject: [PATCH 072/145] Now onInit() works with the PS4 library as well --- BTHID.cpp | 5 +++++ BTHID.h | 30 +++++++++++++++++++++++++++++- PS4BT.h | 34 +++++++++++++++++++--------------- 3 files changed, 53 insertions(+), 16 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index d6accb58..19cf024e 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -46,6 +46,11 @@ void BTHID::Reset() { activeConnection = false; l2cap_event_flag = 0; // Reset flags l2cap_state = L2CAP_WAIT; + + for(uint8_t i = 0; i < BTHID_NUM_SERVICES; i++) { + if(bthidService[i]) + bthidService[i]->Reset(); + } } void BTHID::disconnect() { // Use this void to disconnect the device diff --git a/BTHID.h b/BTHID.h index 3e9c0394..e4df8384 100644 --- a/BTHID.h +++ b/BTHID.h @@ -25,6 +25,14 @@ #define MOUSE_PARSER_ID 1 #define NUM_PARSERS 2 +#define BTHID_NUM_SERVICES 4 // Max number of Bluetooth HID services - if you need more than 4 simply increase this number + +class BTHIDService { +public: + virtual void onInit(); + virtual void Reset(); +}; + /** This BluetoothService class implements support for the HID keyboard and mice. */ class BTHID : public BluetoothService { public: @@ -106,10 +114,25 @@ public: pFuncOnInit = funcOnInit; }; + /** + * Register Bluetooth HID services. + * @param pService Pointer to BTHIDService class instance. + * @return The service ID on success or -1 on fail. + */ + int8_t registerServiceClass(BTHIDService *pService) { + for(uint8_t i = 0; i < BTHID_NUM_SERVICES; i++) { + if(!bthidService[i]) { + bthidService[i] = pService; + return i; // Return ID + } + } + return -1; // ErrorregisterServiceClass + }; + private: BTD *pBtd; // Pointer to BTD instance - HIDReportParser *pRptParser[NUM_PARSERS]; // Pointer to HIDReportParsers. + BTHIDService *bthidService[BTHID_NUM_SERVICES]; /** Set report protocol. */ void setProtocol(); @@ -123,6 +146,11 @@ private: void onInit() { if(pFuncOnInit) pFuncOnInit(); // Call the user function + + for(uint8_t i = 0; i < BTHID_NUM_SERVICES; i++) { + if(bthidService[i]) + bthidService[i]->onInit(); + } }; void (*pFuncOnInit)(void); // Pointer to function called in onInit() diff --git a/PS4BT.h b/PS4BT.h index 379565d4..3810225f 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -67,15 +67,16 @@ struct PS4Data { * This class implements support for the PS4 controller via Bluetooth. * It uses the BTHID class for all the Bluetooth communication. */ -class PS4BT : public HIDReportParser { +class PS4BT : public HIDReportParser, public BTHIDService { public: /** * Constructor for the PS4BT class. - * @param p Pointer to the BTD class instance. + * @param p Pointer to the BTHID class instance. */ PS4BT(BTHID *p) : pBthid(p) { pBthid->SetReportParser(KEYBOARD_PARSER_ID, this); + pBthid->registerServiceClass(this); // Register it as a Bluetooth HID service Reset(); }; @@ -133,7 +134,17 @@ public: pBthid->pair(); }; - void Reset() { + /** + * Used to call your own function when the device is successfully initialized. + * @param funcOnInit Function to call. + */ + void attachOnInit(void (*funcOnInit)(void)) { + pFuncOnInit = funcOnInit; + }; + + /** @name BTHIDService implementation */ + /** Used to reset the different buffers to there default values */ + virtual void Reset() { uint8_t i; for (0; i < sizeof(ps4Data.hatValue); i++) ps4Data.hatValue[i] = 127; @@ -149,25 +160,18 @@ public: buttonClickState.dpad = DPAD_OFF; }; - /** - * Used to call your own function when the device is successfully initialized. - * @param funcOnInit Function to call. - */ - void attachOnInit(void (*funcOnInit)(void)) { - pFuncOnInit = funcOnInit; - }; - -private: /** * Called when a device is successfully initialized. * Use attachOnInit(void (*funcOnInit)(void)) to call your own function. * This is useful for instance if you want to set the LEDs in a specific way. */ - void onInit() { - Reset(); - if(pFuncOnInit) + virtual void onInit() { + if (pFuncOnInit) pFuncOnInit(); // Call the user function }; + /**@}*/ + +private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() bool checkDpad(PS4Buttons ps4Buttons, DPADEnum b); // Used to check PS4 DPAD buttons From 3dd5b1ab1c4d4746609757ac9e0bf91dd167e59e Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 12 Jan 2014 18:15:13 +0100 Subject: [PATCH 073/145] Handle DPAD properly on the PS4 controller The DPAD got separate values for each case - see: DPADEnum in PS4BT.h. --- PS4BT.cpp | 61 +++++++++++++++++++++++++++++++++++++------------------ PS4BT.h | 6 ++++-- 2 files changed, 45 insertions(+), 22 deletions(-) diff --git a/PS4BT.cpp b/PS4BT.cpp index a49195a2..48f9f921 100644 --- a/PS4BT.cpp +++ b/PS4BT.cpp @@ -53,14 +53,25 @@ const uint8_t PS4_ANALOG_BUTTONS[] PROGMEM = { 1, // R2 }; -bool PS4BT::checkDpad(PS4Buttons ps4Buttons, DPADEnum b) { - return ps4Buttons.dpad == b; +bool PS4BT::checkDpad(DPADEnum b) { + switch (b) { + case DPAD_UP: + return ps4Data.btn.dpad == DPAD_LEFT_UP || ps4Data.btn.dpad == DPAD_UP || ps4Data.btn.dpad == DPAD_UP_RIGHT; + case DPAD_RIGHT: + return ps4Data.btn.dpad == DPAD_UP_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT_DOWN; + case DPAD_DOWN: + return ps4Data.btn.dpad == DPAD_RIGHT_DOWN || ps4Data.btn.dpad == DPAD_DOWN || ps4Data.btn.dpad == DPAD_DOWN_LEFT; + case DPAD_LEFT: + return ps4Data.btn.dpad == DPAD_DOWN_LEFT || ps4Data.btn.dpad == DPAD_LEFT || ps4Data.btn.dpad == DPAD_LEFT_UP; + default: + return false; + } } bool PS4BT::getButtonPress(ButtonEnum b) { uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); if (b <= LEFT) // Dpad - return checkDpad(ps4Data.btn, (DPADEnum)button); + return checkDpad((DPADEnum)button); else { uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; uint8_t mask = (1 << (button - 8 * index)); @@ -69,21 +80,18 @@ bool PS4BT::getButtonPress(ButtonEnum b) { } bool PS4BT::getButtonClick(ButtonEnum b) { - uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); - if (b <= LEFT) { // Dpad - if (checkDpad(buttonClickState, (DPADEnum)button)) { - buttonClickState.dpad = DPAD_OFF; - return true; - } - return false; - } else { - uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; - uint8_t mask = (1 << (button - 8 * index)); - - bool click = buttonClickState.val[index] & mask; - buttonClickState.val[index] &= ~mask; // Clear "click" event - return click; + uint8_t mask, index = 0; + if (b <= LEFT) // Dpad + mask = 1 << b; + else { + uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); + index = button < 8 ? 0 : button < 16 ? 1 : 2; + mask = (1 << (button - 8 * index)); } + + bool click = buttonClickState.val[index] & mask; + buttonClickState.val[index] &= ~mask; // Clear "click" event + return click; } uint8_t PS4BT::getAnalogButton(ButtonEnum a) { @@ -99,11 +107,24 @@ void PS4BT::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { memcpy(&ps4Data, buf, len); for (uint8_t i = 0; i < sizeof(ps4Data.btn); i++) { - if (ps4Data.btn.val[i] != oldButtonState.val[i]) { + if (ps4Data.btn.val[i] != oldButtonState.val[i]) { // Check if anything has changed buttonClickState.val[i] = ps4Data.btn.val[i] & ~oldButtonState.val[i]; // Update click state variable oldButtonState.val[i] = ps4Data.btn.val[i]; - if (i == 0) - buttonClickState.dpad = ps4Data.btn.dpad; // The DPAD buttons does not set the different bits, but set a value corresponding to the buttons pressed + if (i == 0) { // 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 + uint8_t newDpad = 0; + if (checkDpad(DPAD_UP)) + newDpad |= 1 << UP; + if (checkDpad(DPAD_RIGHT)) + newDpad |= 1 << RIGHT; + if (checkDpad(DPAD_DOWN)) + newDpad |= 1 << DOWN; + if (checkDpad(DPAD_LEFT)) + newDpad |= 1 << LEFT; + if (newDpad != oldDpad) { + buttonClickState.dpad = newDpad & ~oldDpad; // Override values + oldDpad = newDpad; + } + } } } #ifdef PRINTREPORT diff --git a/PS4BT.h b/PS4BT.h index 3810225f..dcf910e2 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -157,7 +157,8 @@ public: ps4Data.btn.dpad = DPAD_OFF; oldButtonState.dpad = DPAD_OFF; - buttonClickState.dpad = DPAD_OFF; + buttonClickState.dpad = 0; + oldDpad = 0; }; /** @@ -174,10 +175,11 @@ public: private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() - bool checkDpad(PS4Buttons ps4Buttons, DPADEnum b); // Used to check PS4 DPAD buttons + bool checkDpad(DPADEnum b); // Used to check PS4 DPAD buttons BTHID *pBthid; // Pointer to BTHID instance PS4Data ps4Data; PS4Buttons oldButtonState, buttonClickState; + uint8_t oldDpad; }; #endif \ No newline at end of file From 6ae41c436f1d50f1911f149e10c3fab18e845d49 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 12 Jan 2014 19:26:19 +0100 Subject: [PATCH 074/145] Fixed include --- PS4BT.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PS4BT.h b/PS4BT.h index dcf910e2..d328188b 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -19,7 +19,7 @@ #define _ps4bt_h_ #include "BTHID.h" -#include "PS3Enums.h" +#include "controllerEnums.h" enum DPADEnum { DPAD_UP = 0x0, From 2e4f9c852d29aab8b19c9f44bd30e4158f9c4a0c Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 14 Jan 2014 23:56:17 +0100 Subject: [PATCH 075/145] Added information about powered hub to FAQ --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 640c6764..157e84f4 100644 --- a/README.md +++ b/README.md @@ -236,4 +236,5 @@ All the information about the Wii controllers are from these sites: > When I plug my device into the USB connector nothing happens? -Try to connect a external power supply to the Arduino - this solves the problem in most cases. \ No newline at end of file +* Try to connect a external power supply to the Arduino - this solves the problem in most cases. +* You can also use a powered hub between the device and the USB Host Shield. You should then include the USB hub library: ```#include ``` and create the instance like so: ```USBHub Hub1(&Usb);```. \ No newline at end of file From 0c0541344752c9778e328ea17995c8ddc889b503 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 16 Jan 2014 18:56:42 +0100 Subject: [PATCH 076/145] Remote name buffer should be a char array --- BTD.cpp | 5 +---- BTD.h | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 9b0d8ab5..4de668d9 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -796,11 +796,8 @@ void BTD::HCI_task() { if(hci_check_flag(HCI_FLAG_REMOTE_NAME_COMPLETE)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nRemote Name: "), 0x80); - for(uint8_t i = 0; i < 30; i++) { - if(remote_name[i] == '\0') // End of string - break; + for(uint8_t i = 0; i < strlen(remote_name); i++) Notifyc(remote_name[i], 0x80); - } #endif if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) { incomingWii = true; diff --git a/BTD.h b/BTD.h index 609b8c2a..3a639abb 100755 --- a/BTD.h +++ b/BTD.h @@ -488,7 +488,7 @@ public: /** Last incoming devices Bluetooth address. */ uint8_t disc_bdaddr[6]; /** First 30 chars of last remote name. */ - uint8_t remote_name[30]; + char remote_name[30]; /** * The supported HCI Version read from the Bluetooth dongle. * Used by the PS3BT library to check the HCI Version of the Bluetooth dongle, From da2ee954453f48a815a33105fa6e060e52f421cb Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 18 Jan 2014 22:36:01 +0100 Subject: [PATCH 077/145] Added support for the PS4 controller via USB Also improved the PS4BT library --- BTHID.cpp | 19 +-- BTHID.h | 44 +++--- PS3Enums.h | 6 - PS4BT.h | 155 +++--------------- PS4BT.cpp => PS4Parser.cpp | 97 ++++-------- PS4Parser.h | 246 +++++++++++++++++++++++++++++ PS4USB.h | 87 ++++++++++ README.md | 12 +- controllerEnums.h | 6 + examples/Bluetooth/PS4BT/PS4BT.ino | 8 +- examples/PS4USB/PS4USB.ino | 107 +++++++++++++ hiduniversal.cpp | 14 +- hiduniversal.h | 11 ++ keywords.txt | 10 +- 14 files changed, 573 insertions(+), 249 deletions(-) rename PS4BT.cpp => PS4Parser.cpp (51%) create mode 100644 PS4Parser.h create mode 100644 PS4USB.h create mode 100644 examples/PS4USB/PS4USB.ino diff --git a/BTHID.cpp b/BTHID.cpp index 19cf024e..64d3a812 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -46,11 +46,7 @@ void BTHID::Reset() { activeConnection = false; l2cap_event_flag = 0; // Reset flags l2cap_state = L2CAP_WAIT; - - for(uint8_t i = 0; i < BTHID_NUM_SERVICES; i++) { - if(bthidService[i]) - bthidService[i]->Reset(); - } + ResetBTHID(); } void BTHID::disconnect() { // Use this void to disconnect the device @@ -193,19 +189,18 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { } #endif if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT + uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); + ParseBTHID(this, (uint8_t)(length - 1), &l2capinbuf[9]); + switch(l2capinbuf[9]) { - case 0x01: // Keyboard events - if(pRptParser[KEYBOARD_PARSER_ID]) { - uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); + case 0x01: // Keyboard or Joystick events + if(pRptParser[KEYBOARD_PARSER_ID]) pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance - } break; case 0x02: // Mouse events - if(pRptParser[MOUSE_PARSER_ID]) { - uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); + if(pRptParser[MOUSE_PARSER_ID]) pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance - } break; #ifdef DEBUG_USB_HOST default: diff --git a/BTHID.h b/BTHID.h index e4df8384..0dcd6a1e 100644 --- a/BTHID.h +++ b/BTHID.h @@ -25,14 +25,6 @@ #define MOUSE_PARSER_ID 1 #define NUM_PARSERS 2 -#define BTHID_NUM_SERVICES 4 // Max number of Bluetooth HID services - if you need more than 4 simply increase this number - -class BTHIDService { -public: - virtual void onInit(); - virtual void Reset(); -}; - /** This BluetoothService class implements support for the HID keyboard and mice. */ class BTHID : public BluetoothService { public: @@ -56,7 +48,6 @@ public: virtual void Reset(); /** Used this to disconnect the devices. */ virtual void disconnect(); - /**@}*/ /** @@ -114,25 +105,30 @@ public: pFuncOnInit = funcOnInit; }; +protected: + /** @name Overridable functions */ /** - * Register Bluetooth HID services. - * @param pService Pointer to BTHIDService class instance. - * @return The service ID on success or -1 on fail. + * Used to parse Bluetooth HID data to any class that inherits this class. + * @param bthid Pointer to this class. + * @param len The length of the incoming data. + * @param buf Pointer to the data buffer. */ - int8_t registerServiceClass(BTHIDService *pService) { - for(uint8_t i = 0; i < BTHID_NUM_SERVICES; i++) { - if(!bthidService[i]) { - bthidService[i] = pService; - return i; // Return ID - } - } - return -1; // ErrorregisterServiceClass + virtual void ParseBTHID(BTHID *bthid, uint8_t len, uint8_t *buf) { + return; }; + /** Called when a device is connected */ + virtual void OnInitBTHID() { + return; + }; + /** Used to reset any buffers in the class that inherits this */ + virtual void ResetBTHID() { + return; + } + /**@}*/ private: BTD *pBtd; // Pointer to BTD instance HIDReportParser *pRptParser[NUM_PARSERS]; // Pointer to HIDReportParsers. - BTHIDService *bthidService[BTHID_NUM_SERVICES]; /** Set report protocol. */ void setProtocol(); @@ -146,11 +142,7 @@ private: void onInit() { if(pFuncOnInit) pFuncOnInit(); // Call the user function - - for(uint8_t i = 0; i < BTHID_NUM_SERVICES; i++) { - if(bthidService[i]) - bthidService[i]->onInit(); - } + OnInitBTHID(); }; void (*pFuncOnInit)(void); // Pointer to function called in onInit() diff --git a/PS3Enums.h b/PS3Enums.h index befb087e..dca5bebe 100644 --- a/PS3Enums.h +++ b/PS3Enums.h @@ -174,12 +174,6 @@ enum SensorEnum { mYmove = 50, }; -/** Used to get the angle calculated using the accelerometer. */ -enum AngleEnum { - Pitch = 0x01, - Roll = 0x02, -}; - enum StatusEnum { // Note that the location is shifted 9 when it's connected via USB // Byte location | bit location diff --git a/PS4BT.h b/PS4BT.h index d328188b..a723cec8 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -19,119 +19,53 @@ #define _ps4bt_h_ #include "BTHID.h" -#include "controllerEnums.h" - -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, -}; - -union PS4Buttons { - struct { - uint8_t dpad : 4; - uint8_t square : 1; - uint8_t cross : 1; - uint8_t circle : 1; - uint8_t triangle : 1; - - uint8_t l1 : 1; - uint8_t r1 : 1; - uint8_t l2 : 1; - uint8_t r2 : 1; - uint8_t share : 1; - uint8_t options : 1; - uint8_t l3 : 1; - uint8_t r3 : 1; - - uint8_t ps : 1; - uint8_t touchpad : 1; - uint8_t dummy : 6; - }; - uint8_t val[3]; -}; - -struct PS4Data { - uint8_t hatValue[4]; - PS4Buttons btn; - uint8_t trigger[2]; -}; +#include "PS4Parser.h" /** * This class implements support for the PS4 controller via Bluetooth. * It uses the BTHID class for all the Bluetooth communication. */ -class PS4BT : public HIDReportParser, public BTHIDService { +class PS4BT : public BTHID, public PS4Parser { public: /** * Constructor for the PS4BT class. * @param p Pointer to the BTHID class instance. */ - PS4BT(BTHID *p) : - pBthid(p) { - pBthid->SetReportParser(KEYBOARD_PARSER_ID, this); - pBthid->registerServiceClass(this); // Register it as a Bluetooth HID service - Reset(); + PS4BT(BTD *p, bool pair = false, const char *pin = "0000") : + BTHID(p, pair, pin) { + PS4Parser::Reset(); }; - virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf); - - /** @name PS4 Controller functions */ + /** @name BTHID implementation */ /** - * getButtonPress(ButtonEnum b) will return true as long as the button is held down. - * - * While getButtonClick(ButtonEnum b) will only return it once. - * - * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), - * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). - * @param b ::ButtonEnum to read. - * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press. + * Used to parse Bluetooth HID data. + * @param bthid Pointer to the BTHID class. + * @param len The length of the incoming data. + * @param buf Pointer to the data buffer. */ - bool getButtonPress(ButtonEnum b); - bool getButtonClick(ButtonEnum b); - /**@}*/ - /** @name PS4 Controller functions */ - /** - * Used to get the analog value from button presses. - * @param a The ::ButtonEnum to read. - * The supported buttons are: - * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2, - * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T. - * @return Analog value in the range of 0-255. - */ - uint8_t getAnalogButton(ButtonEnum a); + virtual void ParseBTHID(BTHID *bthid, uint8_t len, uint8_t *buf) { + PS4Parser::Parse(len, buf); + }; /** - * Used to read the analog joystick. - * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY. - * @return Return the analog value in the range of 0-255. + * Called when a device is successfully initialized. + * Use attachOnInit(void (*funcOnInit)(void)) to call your own function. + * This is useful for instance if you want to set the LEDs in a specific way. */ - uint8_t getAnalogHat(AnalogHatEnum a); + virtual void OnInitBTHID() { + if (pFuncOnInit) + pFuncOnInit(); // Call the user function + }; + + /** Used to reset the different buffers to there default values */ + virtual void ResetBTHID() { + PS4Parser::Reset(); + }; /**@}*/ /** True if a device is connected */ bool connected() { - if (pBthid) - return pBthid->connected; - return false; - }; - - /** Used this to disconnect the devices. */ - void disconnect() { - if (pBthid) - pBthid->disconnect(); - }; - - /** Call this to start the paring sequence with a device */ - void pair(void) { - if (pBthid) - pBthid->pair(); + BTHID::connected; }; /** @@ -142,44 +76,7 @@ public: pFuncOnInit = funcOnInit; }; - /** @name BTHIDService implementation */ - /** Used to reset the different buffers to there default values */ - virtual void Reset() { - uint8_t i; - for (0; i < sizeof(ps4Data.hatValue); i++) - ps4Data.hatValue[i] = 127; - for (0; i < sizeof(PS4Buttons); i++) { - ps4Data.btn.val[i] = 0; - oldButtonState.val[i] = 0; - } - for (0; i < sizeof(ps4Data.trigger); i++) - ps4Data.trigger[i] = 0; - - ps4Data.btn.dpad = DPAD_OFF; - oldButtonState.dpad = DPAD_OFF; - buttonClickState.dpad = 0; - oldDpad = 0; - }; - - /** - * Called when a device is successfully initialized. - * Use attachOnInit(void (*funcOnInit)(void)) to call your own function. - * This is useful for instance if you want to set the LEDs in a specific way. - */ - virtual void onInit() { - if (pFuncOnInit) - pFuncOnInit(); // Call the user function - }; - /**@}*/ - private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() - - bool checkDpad(DPADEnum b); // Used to check PS4 DPAD buttons - - BTHID *pBthid; // Pointer to BTHID instance - PS4Data ps4Data; - PS4Buttons oldButtonState, buttonClickState; - uint8_t oldDpad; }; #endif \ No newline at end of file diff --git a/PS4BT.cpp b/PS4Parser.cpp similarity index 51% rename from PS4BT.cpp rename to PS4Parser.cpp index 48f9f921..16c1ee3d 100644 --- a/PS4BT.cpp +++ b/PS4Parser.cpp @@ -15,78 +15,45 @@ e-mail : kristianl@tkjelectronics.com */ -#include "PS4BT.h" +#include "PS4Parser.h" // To enable serial debugging see "settings.h" //#define PRINTREPORT // Uncomment to print the report send by the PS4 Controller -/** Buttons on the controller */ -const uint8_t PS4_BUTTONS[] PROGMEM = { - DPAD_UP, // UP - DPAD_RIGHT, // RIGHT - DPAD_DOWN, // DOWN - DPAD_LEFT, // LEFT - - 0x0C, // SHARE - 0x0D, // OPTIONS - 0x0E, // L3 - 0x0F, // R3 - - 0x0A, // L2 - 0x0B, // R2 - 0x08, // L1 - 0x09, // R1 - - 0x07, // TRIANGLE - 0x06, // CIRCLE - 0x05, // CROSS - 0x04, // SQUARE - - 0x10, // PS - 0x11, // TOUCHPAD -}; - -/** Analog buttons on the controller */ -const uint8_t PS4_ANALOG_BUTTONS[] PROGMEM = { - 0, 0, 0, 0, 0, 0, 0, 0, // Skip UP, RIGHT, DOWN, LEFT, SHARE, OPTIONS, L3, and R3 - 0, // L2 - 1, // R2 -}; - -bool PS4BT::checkDpad(DPADEnum b) { - switch (b) { - case DPAD_UP: - return ps4Data.btn.dpad == DPAD_LEFT_UP || ps4Data.btn.dpad == DPAD_UP || ps4Data.btn.dpad == DPAD_UP_RIGHT; - case DPAD_RIGHT: - return ps4Data.btn.dpad == DPAD_UP_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT_DOWN; - case DPAD_DOWN: - return ps4Data.btn.dpad == DPAD_RIGHT_DOWN || ps4Data.btn.dpad == DPAD_DOWN || ps4Data.btn.dpad == DPAD_DOWN_LEFT; - case DPAD_LEFT: - return ps4Data.btn.dpad == DPAD_DOWN_LEFT || ps4Data.btn.dpad == DPAD_LEFT || ps4Data.btn.dpad == DPAD_LEFT_UP; - default: - return false; - } +bool PS4Parser::checkDpad(ButtonEnum b) { + switch (b) { + case UP: + return ps4Data.btn.dpad == DPAD_LEFT_UP || ps4Data.btn.dpad == DPAD_UP || ps4Data.btn.dpad == DPAD_UP_RIGHT; + case RIGHT: + return ps4Data.btn.dpad == DPAD_UP_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT_DOWN; + case DOWN: + return ps4Data.btn.dpad == DPAD_RIGHT_DOWN || ps4Data.btn.dpad == DPAD_DOWN || ps4Data.btn.dpad == DPAD_DOWN_LEFT; + case LEFT: + return ps4Data.btn.dpad == DPAD_DOWN_LEFT || ps4Data.btn.dpad == DPAD_LEFT || ps4Data.btn.dpad == DPAD_LEFT_UP; + default: + return false; + } } -bool PS4BT::getButtonPress(ButtonEnum b) { - uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); +bool PS4Parser::getButtonPress(ButtonEnum b) { if (b <= LEFT) // Dpad - return checkDpad((DPADEnum)button); + return checkDpad(b); else { + uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; - uint8_t mask = (1 << (button - 8 * index)); + uint8_t mask = 1 << (button - 8 * index); return ps4Data.btn.val[index] & mask; } } -bool PS4BT::getButtonClick(ButtonEnum b) { +bool PS4Parser::getButtonClick(ButtonEnum b) { uint8_t mask, index = 0; if (b <= LEFT) // Dpad mask = 1 << b; else { uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); index = button < 8 ? 0 : button < 16 ? 1 : 2; - mask = (1 << (button - 8 * index)); + mask = 1 << (button - 8 * index); } bool click = buttonClickState.val[index] & mask; @@ -94,17 +61,21 @@ bool PS4BT::getButtonClick(ButtonEnum b) { return click; } -uint8_t PS4BT::getAnalogButton(ButtonEnum a) { - return ps4Data.trigger[pgm_read_byte(&PS4_ANALOG_BUTTONS[(uint8_t)a])]; +uint8_t PS4Parser::getAnalogButton(ButtonEnum a) { + if (a == L2) // These are the only analog buttons on the controller + return ps4Data.trigger[0]; + else if (a == R2) + return ps4Data.trigger[1]; + return 0; } -uint8_t PS4BT::getAnalogHat(AnalogHatEnum a) { +uint8_t PS4Parser::getAnalogHat(AnalogHatEnum a) { return ps4Data.hatValue[(uint8_t)a]; } -void PS4BT::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { - if (len == sizeof(PS4Data) && buf) { - memcpy(&ps4Data, buf, len); +void PS4Parser::Parse(uint8_t len, uint8_t *buf) { + if (len > 0 && buf) { + memcpy(&ps4Data, buf, min(len, sizeof(ps4Data))); for (uint8_t i = 0; i < sizeof(ps4Data.btn); i++) { if (ps4Data.btn.val[i] != oldButtonState.val[i]) { // Check if anything has changed @@ -112,13 +83,13 @@ void PS4BT::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { oldButtonState.val[i] = ps4Data.btn.val[i]; if (i == 0) { // 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 uint8_t newDpad = 0; - if (checkDpad(DPAD_UP)) + if (checkDpad(UP)) newDpad |= 1 << UP; - if (checkDpad(DPAD_RIGHT)) + if (checkDpad(RIGHT)) newDpad |= 1 << RIGHT; - if (checkDpad(DPAD_DOWN)) + if (checkDpad(DOWN)) newDpad |= 1 << DOWN; - if (checkDpad(DPAD_LEFT)) + if (checkDpad(LEFT)) newDpad |= 1 << LEFT; if (newDpad != oldDpad) { buttonClickState.dpad = newDpad & ~oldDpad; // Override values diff --git a/PS4Parser.h b/PS4Parser.h new file mode 100644 index 00000000..738cf89b --- /dev/null +++ b/PS4Parser.h @@ -0,0 +1,246 @@ +/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved. + + This software may be distributed and modified under the terms of the GNU + General Public License version 2 (GPL2) as published by the Free Software + Foundation and appearing in the file GPL2.TXT included in the packaging of + this file. Please note that GPL2 Section 2[b] requires that all works based + on this software must also be made publicly available under the terms of + the GPL2 ("Copyleft"). + + Contact information + ------------------- + + Kristian Lauszus, TKJ Electronics + Web : http://www.tkjelectronics.com + e-mail : kristianl@tkjelectronics.com + */ + +#ifndef _ps4parser_h_ +#define _ps4parser_h_ + +#include "hid.h" +#include "controllerEnums.h" + +/** Buttons on the controller */ +const uint8_t PS4_BUTTONS[] PROGMEM = { + UP, // UP + RIGHT, // RIGHT + DOWN, // DOWN + LEFT, // LEFT + + 0x0C, // SHARE + 0x0D, // OPTIONS + 0x0E, // L3 + 0x0F, // R3 + + 0x0A, // L2 + 0x0B, // R2 + 0x08, // L1 + 0x09, // R1 + + 0x07, // TRIANGLE + 0x06, // CIRCLE + 0x05, // CROSS + 0x04, // SQUARE + + 0x10, // PS + 0x11, // TOUCHPAD +}; + +union PS4Buttons { + struct { + uint8_t dpad : 4; + uint8_t square : 1; + uint8_t cross : 1; + uint8_t circle : 1; + uint8_t triangle : 1; + + uint8_t l1 : 1; + uint8_t r1 : 1; + uint8_t l2 : 1; + uint8_t r2 : 1; + uint8_t share : 1; + uint8_t options : 1; + uint8_t l3 : 1; + uint8_t r3 : 1; + + uint8_t ps : 1; + uint8_t touchpad : 1; + uint8_t timestamp : 6; // Only available via USB + }; + uint8_t val[3]; +}; + +struct touchpadXY { + uint8_t dummy; // I can not figure out what this data is for, it seems to change randomly, maybe a timestamp? + struct { + struct { + uint8_t counter : 7; // Increments every time a finger is touching the touchpad + uint8_t touching : 1; // The top bit is cleared if the finger is touching the touchpad + }; + struct { + uint16_t x : 12; + uint16_t y : 12; + }; + } finger[2]; // 0 = first finger, 1 = second finger +}; + +struct PS4Data { + /* Button and joystick values */ + uint8_t report_id; // Always 0x01 + uint8_t hatValue[4]; + PS4Buttons btn; + uint8_t trigger[2]; + + // I still need to figure out how to make the PS4 controller send out the rest of the data via Bluetooth + + /* Gyro and accelerometer values */ + uint8_t dummy[3]; // First two looks random, while the third one might be some kind of status + int16_t gyroY, gyroZ, gyroX; + int16_t accX, accZ, accY; + + /* The rest is data for the touchpad */ + uint8_t dummy2[9]; // Byte 5 looks like some kind of status (maybe battery status), bit 1 of byte 9 is set every time a finger is moving around the touchpad + touchpadXY xy[3]; // It looks like it sends out three coordinates each time, this is possible because the microcontroller inside the PS4 controller is much faster than the Bluetooth connection. + // The last data is read from the last position in the array while the oldest measurement is from the first position. + // The first position will also keep it's value after the finger is released, while the other two will set them to zero. + // Note that if you read fast enough from the device, then only the first one will contain any data. + + // The last three bytes are always: 0x00, 0x80, 0x00 +}; + +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, +}; + +enum PS4SensorEnum { + gX, gY, gZ, /** Gyro values */ + aX, aY, aZ, /** Accelerometer values */ +}; + +/** This class parses all the data sent by the PS4 controller */ +class PS4Parser { +public: + /** Constructor for the PS4Parser class. */ + PS4Parser() { + Reset(); + }; + + /** @name PS4 Controller functions */ + /** + * getButtonPress(ButtonEnum b) will return true as long as the button is held down. + * + * While getButtonClick(ButtonEnum b) will only return it once. + * + * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). + * @param b ::ButtonEnum to read. + * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press. + */ + bool getButtonPress(ButtonEnum b); + bool getButtonClick(ButtonEnum b); + /**@}*/ + /** @name PS4 Controller functions */ + /** + * Used to get the analog value from button presses. + * @param a The ::ButtonEnum to read. + * The supported buttons are: + * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2, + * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T. + * @return Analog value in the range of 0-255. + */ + uint8_t getAnalogButton(ButtonEnum a); + + /** + * Used to read the analog joystick. + * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY. + * @return Return the analog value in the range of 0-255. + */ + uint8_t getAnalogHat(AnalogHatEnum a); + /**@}*/ + + /** @name Only available via USB at the moment */ + uint16_t getX(uint8_t finger = 0, uint8_t xyId = 0) { + return ps4Data.xy[xyId].finger[finger].x; + }; + + uint16_t getY(uint8_t finger = 0, uint8_t xyId = 0) { + return ps4Data.xy[xyId].finger[finger].y; + }; + + uint8_t isTouching(uint8_t finger = 0, uint8_t xyId = 0) { + return !(ps4Data.xy[xyId].finger[finger].touching); // The bit is cleared every time when a finger is touching the touchpad + }; + + uint8_t getTouchCounter(uint8_t finger = 0, uint8_t xyId = 0) { + return ps4Data.xy[xyId].finger[finger].counter; + }; + + double getAngle(AngleEnum a) { + if(a == Pitch) + return (atan2(ps4Data.accY, ps4Data.accZ) + PI) * RAD_TO_DEG; + else + return (atan2(ps4Data.accX, ps4Data.accZ) + PI) * RAD_TO_DEG; + }; + + int16_t getSensor(PS4SensorEnum a) { + switch(a) { + case gX: + return ps4Data.gyroX; + case gY: + return ps4Data.gyroY; + case gZ: + return ps4Data.gyroZ; + case aX: + return ps4Data.accX; + case aY: + return ps4Data.accY; + case aZ: + return ps4Data.accZ; + default: + return 0; + } + }; + /**@}*/ + + /** Used to reset the different buffers to their default values */ + void Reset() { + uint8_t i; + for (i = 0; i < sizeof(ps4Data.hatValue); i++) + ps4Data.hatValue[i] = 127; + for (i = 0; i < sizeof(PS4Buttons); i++) { + ps4Data.btn.val[i] = 0; + oldButtonState.val[i] = 0; + } + for (i = 0; i < sizeof(ps4Data.trigger); i++) + ps4Data.trigger[i] = 0; + for (i = 0; i < sizeof(ps4Data.xy)/sizeof(ps4Data.xy[0]); i++) { + for (uint8_t j = 0; j < sizeof(ps4Data.xy[0].finger)/sizeof(ps4Data.xy[0].finger[0]); j++) + ps4Data.xy[i].finger[j].touching = 1; // The bit is cleared if the finger is touching the touchpad + } + + ps4Data.btn.dpad = DPAD_OFF; + oldButtonState.dpad = DPAD_OFF; + buttonClickState.dpad = 0; + oldDpad = 0; + }; + +protected: + void Parse(uint8_t len, uint8_t *buf); + +private: + bool checkDpad(ButtonEnum b); // Used to check PS4 DPAD buttons + + PS4Data ps4Data; + PS4Buttons oldButtonState, buttonClickState; + uint8_t oldDpad; +}; +#endif \ No newline at end of file diff --git a/PS4USB.h b/PS4USB.h new file mode 100644 index 00000000..a009071c --- /dev/null +++ b/PS4USB.h @@ -0,0 +1,87 @@ +/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved. + + This software may be distributed and modified under the terms of the GNU + General Public License version 2 (GPL2) as published by the Free Software + Foundation and appearing in the file GPL2.TXT included in the packaging of + this file. Please note that GPL2 Section 2[b] requires that all works based + on this software must also be made publicly available under the terms of + the GPL2 ("Copyleft"). + + Contact information + ------------------- + + Kristian Lauszus, TKJ Electronics + Web : http://www.tkjelectronics.com + e-mail : kristianl@tkjelectronics.com + */ + +#ifndef _ps4usb_h_ +#define _ps4usb_h_ + +#include "hiduniversal.h" +#include "PS4Parser.h" + +#define PS4_VID 0x054C // Sony Corporation +#define PS4_PID 0x05C4 // PS4 Controller + +/** + * This class implements support for the PS4 controller via USB. + * It uses the HIDUniversal class for all the USB communication. + */ +class PS4USB : public HIDUniversal, public PS4Parser { +public: + /** + * Constructor for the PS4USB class. + * @param p Pointer to the HIDUniversal class instance. + */ + PS4USB(USB *p) : + HIDUniversal(p) { + PS4Parser::Reset(); + }; + + /** @name HIDUniversal implementation */ + /** + * Used to parse USB HID data. + * @param hid Pointer to the HID class. + * @param is_rpt_id Only used for Hubs. + * @param len The length of the incoming data. + * @param buf Pointer to the data buffer. + */ + virtual void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { + if (HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID) + PS4Parser::Parse(len, buf); + }; + + /** + * Called when a device is successfully initialized. + * Use attachOnInit(void (*funcOnInit)(void)) to call your own function. + * This is useful for instance if you want to set the LEDs in a specific way. + */ + virtual uint8_t OnInitSuccessful() { + PS4Parser::Reset(); + if (HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID && pFuncOnInit) + pFuncOnInit(); // Call the user function + return 0; + }; + /**@}*/ + + /** + * Used to check if a PS4 controller is connected. + * @return Returns true if it is connected. + */ + bool connected() { + return HIDUniversal::isReady() && HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID; + }; + + /** + * Used to call your own function when the device is successfully initialized. + * @param funcOnInit Function to call. + */ + void attachOnInit(void (*funcOnInit)(void)) { + pFuncOnInit = funcOnInit; + }; + +private: + void (*pFuncOnInit)(void); // Pointer to function called in onInit() +}; +#endif \ No newline at end of file diff --git a/README.md b/README.md index 157e84f4..ab7e2b2a 100644 --- a/README.md +++ b/README.md @@ -116,15 +116,17 @@ It enables me to see the Bluetooth communication between my Mac and any device. ### PS4 Library -This is the [PS4BT](PS4BT.cpp) library. It works with the official Sony PS4 controller via Bluetooth. +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. -The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) example shows how to easily read the buttons and joysticks on the controller. +The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) and [PS4USB.ino](examples/PS4USB/PS4USB.ino) examples shows how to easily read the buttons and joysticks on the controller via Bluetooth and USB respectively. -I still have not figured out how to read the touchpad, turn rumble on and off and set the color of the light, but hopefully I will figure that out soon. +I still have not figured out how to turn rumble on and off and set the color of the light, but hopefully I will figure that out soon. -Before you can use the PS4 controller you will need to pair with it. +Also the gyro, accelerometer and touchpad values are still only available via USB at the moment. -Simply create the BTHID instance like so: ```BTHID bthid(&Btd, PAIR);``` and then hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode. +Before you can use the PS4 controller via Bluetooth you will need to pair with it. + +Simply create the PS4BT instance like so: ```PS4BT PS4(&Btd, PAIR);``` and then hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode. It should then automatically pair the dongle with your controller. This only have to be done once. diff --git a/controllerEnums.h b/controllerEnums.h index 2cc0b789..155588f2 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -124,4 +124,10 @@ enum AnalogHatEnum { RightHatY = 3, }; +/** Used to get the angle calculated using the PS3 controller and PS4 controller. */ +enum AngleEnum { + Pitch = 0x01, + Roll = 0x02, +}; + #endif diff --git a/examples/Bluetooth/PS4BT/PS4BT.ino b/examples/Bluetooth/PS4BT/PS4BT.ino index bf068876..924cdc1d 100644 --- a/examples/Bluetooth/PS4BT/PS4BT.ino +++ b/examples/Bluetooth/PS4BT/PS4BT.ino @@ -16,15 +16,13 @@ USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so -/* You can create the instance of the BTHID class in two ways */ +/* You can create the instance of the PS4BT class in two ways */ // This will start an inquiry and then pair with the PS4 controller - you only have to do this once // You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode -BTHID bthid(&Btd, PAIR); +PS4BT PS4(&Btd, PAIR); // After that you can simply create the instance like so and then press the PS button on the device -//BTHID bthid(&Btd); - -PS4BT PS4(&bthid); // You should not modify this instance +//PS4BT PS4(&Btd); void setup() { Serial.begin(115200); diff --git a/examples/PS4USB/PS4USB.ino b/examples/PS4USB/PS4USB.ino new file mode 100644 index 00000000..95a0e586 --- /dev/null +++ b/examples/PS4USB/PS4USB.ino @@ -0,0 +1,107 @@ +/* + Example sketch for the PS4 USB library - developed by Kristian Lauszus + For more information visit my blog: http://blog.tkjelectronics.dk/ or + send me an e-mail: kristianl@tkjelectronics.com + */ + +#include + +USB Usb; +PS4USB PS4(&Usb); + +boolean printAngle, printTouch; + +void setup() { + Serial.begin(115200); + while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection + if (Usb.Init() == -1) { + Serial.print(F("\r\nOSC did not start")); + while (1); // Halt + } + Serial.print(F("\r\nPS4 USB Library Started")); +} + +void loop() { + Usb.Task(); + + if (PS4.connected()) { + if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117) { + Serial.print(F("\r\nLeftHatX: ")); + Serial.print(PS4.getAnalogHat(LeftHatX)); + Serial.print(F("\tLeftHatY: ")); + Serial.print(PS4.getAnalogHat(LeftHatY)); + Serial.print(F("\tRightHatX: ")); + Serial.print(PS4.getAnalogHat(RightHatX)); + Serial.print(F("\tRightHatY: ")); + Serial.print(PS4.getAnalogHat(RightHatY)); + } + + if (PS4.getAnalogButton(L2) || PS4.getAnalogButton(R2)) { // These are the only analog buttons on the PS4 controller + Serial.print(F("\r\nL2: ")); + Serial.print(PS4.getAnalogButton(L2)); + Serial.print(F("\tR2: ")); + Serial.print(PS4.getAnalogButton(R2)); + } + + if (PS4.getButtonClick(PS)) + Serial.print(F("\r\nPS")); + if (PS4.getButtonClick(TRIANGLE)) + Serial.print(F("\r\nTraingle")); + if (PS4.getButtonClick(CIRCLE)) + Serial.print(F("\r\nCircle")); + if (PS4.getButtonClick(CROSS)) + Serial.print(F("\r\nCross")); + if (PS4.getButtonClick(SQUARE)) + Serial.print(F("\r\nSquare")); + + if (PS4.getButtonClick(UP)) + Serial.print(F("\r\nUp")); + if (PS4.getButtonClick(RIGHT)) + Serial.print(F("\r\nRight")); + if (PS4.getButtonClick(DOWN)) + Serial.print(F("\r\nDown")); + if (PS4.getButtonClick(LEFT)) + Serial.print(F("\r\nLeft")); + + if (PS4.getButtonClick(L1)) + Serial.print(F("\r\nL1")); + if (PS4.getButtonClick(L3)) + Serial.print(F("\r\nL3")); + if (PS4.getButtonClick(R1)) + Serial.print(F("\r\nR1")); + if (PS4.getButtonClick(R3)) + Serial.print(F("\r\nR3")); + + if (PS4.getButtonClick(SHARE)) + Serial.print(F("\r\nShare")); + if (PS4.getButtonClick(OPTIONS)) { + Serial.print(F("\r\nOptions")); + printAngle = !printAngle; + } + if (PS4.getButtonClick(TOUCHPAD)) { + Serial.print(F("\r\nTouchpad")); + printTouch = !printTouch; + } + + if (printAngle) { // Print angle calculated using the accelerometer only + Serial.print(F("\r\nPitch: ")); + Serial.print(PS4.getAngle(Pitch)); + Serial.print(F("\tRoll: ")); + Serial.print(PS4.getAngle(Roll)); + } + + if (printTouch) { // Print the x, y coordinates of the touchpad + if (PS4.isTouching(0) || PS4.isTouching(1)) // Print newline and carriage return if any of the fingers are touching the touchpad + Serial.print(F("\r\n")); + for (uint8_t i = 0; i < 2; i++) { // The touchpad track two fingers + if (PS4.isTouching(i)) { // Print the position of the finger if it is touching the touchpad + Serial.print(F("X")); Serial.print(i + 1); Serial.print(F(": ")); + Serial.print(PS4.getX(i)); + Serial.print(F("\tY")); Serial.print(i + 1); Serial.print(F(": ")); + Serial.print(PS4.getY(i)); + Serial.print(F("\t")); + } + } + } + } +} diff --git a/hiduniversal.cpp b/hiduniversal.cpp index fb19683f..4e866cb2 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -3,6 +3,7 @@ HIDUniversal::HIDUniversal(USB *p) : HID(p), qNextPollTime(0), +pollInterval(0), bPollEnable(false), bHasReportId(false) { Initialize(); @@ -47,6 +48,7 @@ void HIDUniversal::Initialize() { bNumEP = 1; bNumIface = 0; bConfNum = 0; + pollInterval = 0; ZeroMemory(constBuffLen, prevBuf); } @@ -167,6 +169,9 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { if(rcode) goto FailGetDevDescr; + VID = udd->idVendor; // Can be used by classes that inherits this class to check the VID and PID of the connected device + PID = udd->idProduct; + num_of_conf = udd->bNumConfigurations; // Assign epInfo to epinfo pointer @@ -198,7 +203,7 @@ uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - USBTRACE2("\r\nCnf:", bConfNum); + USBTRACE2("Cnf:", bConfNum); // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); @@ -307,6 +312,9 @@ void HIDUniversal::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint // Fill in the endpoint index list piface->epIndex[index] = bNumEP; //(pep->bEndpointAddress & 0x0F); + if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints + pollInterval = pep->bInterval; + bNumEP++; } //PrintEndpointDescriptor(pep); @@ -346,7 +354,7 @@ uint8_t HIDUniversal::Poll() { return 0; if(qNextPollTime <= millis()) { - qNextPollTime = millis() + 50; + qNextPollTime = millis() + pollInterval; uint8_t buf[constBuffLen]; @@ -381,6 +389,8 @@ uint8_t HIDUniversal::Poll() { Notify(PSTR("\r\n"), 0x80); + ParseHIDData(this, bHasReportId, (uint8_t)read, buf); + HIDReportParser *prs = GetReportParser(((bHasReportId) ? *buf : 0)); if(prs) diff --git a/hiduniversal.h b/hiduniversal.h index 0f6729e7..bfd1173b 100644 --- a/hiduniversal.h +++ b/hiduniversal.h @@ -35,6 +35,7 @@ class HIDUniversal : public HID { uint8_t bNumIface; // number of interfaces in the configuration uint8_t bNumEP; // total number of EP in the configuration uint32_t qNextPollTime; // next poll time + uint8_t pollInterval; bool bPollEnable; // poll enable flag static const uint16_t constBuffLen = 64; // event buffer length @@ -50,6 +51,8 @@ class HIDUniversal : public HID { protected: bool bHasReportId; + uint16_t PID, VID; // PID and VID of connected device + // HID implementation virtual HIDReportParser* GetReportParser(uint8_t id); @@ -57,6 +60,10 @@ protected: return 0; }; + virtual void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { + return; + }; + public: HIDUniversal(USB *p); @@ -72,6 +79,10 @@ public: return bAddress; }; + virtual bool isReady() { + return bPollEnable; + }; + // UsbConfigXtracter implementation virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); }; diff --git a/keywords.txt b/keywords.txt index a60fe5d8..786d4fa2 100644 --- a/keywords.txt +++ b/keywords.txt @@ -32,9 +32,10 @@ Task KEYWORD2 # Datatypes (KEYWORD1) #################################################### -PS4BT KEYWORD1 PS3BT KEYWORD1 PS3USB KEYWORD1 +PS4BT KEYWORD1 +PS4USB KEYWORD1 #################################################### # Methods and Functions (KEYWORD2) @@ -75,6 +76,11 @@ PS3NavigationConnected KEYWORD2 isReady KEYWORD2 watingForConnection KEYWORD2 +isTouching KEYWORD2 +getX KEYWORD2 +getY KEYWORD2 +getTouchCounter KEYWORD2 + #################################################### # Constants and enums (LITERAL1) #################################################### @@ -131,6 +137,8 @@ RightHatY LITERAL1 aX LITERAL1 aY LITERAL1 aZ LITERAL1 +gX LITERAL1 +gY LITERAL1 gZ LITERAL1 aXmove LITERAL1 aYmove LITERAL1 From 681c6684483738f1e40074e143a282418a298eaa Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 18 Jan 2014 22:50:05 +0100 Subject: [PATCH 078/145] Fixed conflict between PS3 and PS4 libraries --- PS3Enums.h | 46 ++-------------------------------------------- PS4Parser.h | 9 ++------- controllerEnums.h | 42 +++++++++++++++++++++++++++++++++++++++--- 3 files changed, 43 insertions(+), 54 deletions(-) diff --git a/PS3Enums.h b/PS3Enums.h index dca5bebe..7ee84293 100644 --- a/PS3Enums.h +++ b/PS3Enums.h @@ -56,8 +56,7 @@ const uint8_t PS3_LEDS[] PROGMEM = { }; /** - * Buttons on the controllers - * + * Buttons on the controllers. * Note: that the location is shifted 9 when it's connected via USB. */ const uint32_t PS3_BUTTONS[] PROGMEM = { @@ -87,8 +86,7 @@ const uint32_t PS3_BUTTONS[] PROGMEM = { }; /** - * Analog buttons on the controllers - * + * Analog buttons on the controllers. * Note: that the location is shifted 9 when it's connected via USB. */ const uint8_t PS3_ANALOG_BUTTONS[] PROGMEM = { @@ -134,46 +132,6 @@ enum ColorsEnum { Off = 0x00, }; -/** - * Sensors inside the Sixaxis Dualshock 3 and Move controller. - * - * Note: that the location is shifted 9 when it's connected via USB. - */ -enum SensorEnum { - /** Accelerometer x-axis */ - aX = 50, - /** Accelerometer y-axis */ - aY = 52, - /** Accelerometer z-axis */ - aZ = 54, - /** Gyro z-axis */ - gZ = 56, - - /** Accelerometer x-axis */ - aXmove = 28, - /** Accelerometer z-axis */ - aZmove = 30, - /** Accelerometer y-axis */ - aYmove = 32, - - /** Gyro x-axis */ - gXmove = 40, - /** Gyro z-axis */ - gZmove = 42, - /** Gyro y-axis */ - gYmove = 44, - - /** Temperature sensor */ - tempMove = 46, - - /** Magnetometer x-axis */ - mXmove = 47, - /** Magnetometer z-axis */ - mZmove = 49, - /** Magnetometer y-axis */ - mYmove = 50, -}; - enum StatusEnum { // Note that the location is shifted 9 when it's connected via USB // Byte location | bit location diff --git a/PS4Parser.h b/PS4Parser.h index 738cf89b..d3e28f88 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -121,11 +121,6 @@ enum DPADEnum { DPAD_OFF = 0x8, }; -enum PS4SensorEnum { - gX, gY, gZ, /** Gyro values */ - aX, aY, aZ, /** Accelerometer values */ -}; - /** This class parses all the data sent by the PS4 controller */ class PS4Parser { public: @@ -191,8 +186,8 @@ public: return (atan2(ps4Data.accX, ps4Data.accZ) + PI) * RAD_TO_DEG; }; - int16_t getSensor(PS4SensorEnum a) { - switch(a) { + int16_t getSensor(SensorEnum s) { + switch(s) { case gX: return ps4Data.gyroX; case gY: diff --git a/controllerEnums.h b/controllerEnums.h index 155588f2..0eae781d 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -18,9 +18,9 @@ #ifndef _controllerenums_h #define _controllerenums_h -/* - This header file is used to store different enums for the controllers, - This is necessary so all the different libraries can be used at once +/** + * This header file is used to store different enums for the controllers, + * This is necessary so all the different libraries can be used at once. */ /** Enum used to turn on the LEDs on the different controllers. */ @@ -124,6 +124,42 @@ enum AnalogHatEnum { RightHatY = 3, }; +/** + * Sensors inside the Sixaxis Dualshock 3, Move controller and PS4 controller. + * Note: that the location is shifted 9 when it's connected via USB on the PS3 controller. + */ +enum SensorEnum { + /** Accelerometer values */ + aX = 50, aY = 52, aZ = 54, + /** Gyro z-axis */ + gZ = 56, + gX, gY, // These are not available on the PS3 controller + + /** Accelerometer x-axis */ + aXmove = 28, + /** Accelerometer z-axis */ + aZmove = 30, + /** Accelerometer y-axis */ + aYmove = 32, + + /** Gyro x-axis */ + gXmove = 40, + /** Gyro z-axis */ + gZmove = 42, + /** Gyro y-axis */ + gYmove = 44, + + /** Temperature sensor */ + tempMove = 46, + + /** Magnetometer x-axis */ + mXmove = 47, + /** Magnetometer z-axis */ + mZmove = 49, + /** Magnetometer y-axis */ + mYmove = 50, +}; + /** Used to get the angle calculated using the PS3 controller and PS4 controller. */ enum AngleEnum { Pitch = 0x01, From ad7078d6adacb8d0edf2f521ed53d152d21d5c57 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 18 Jan 2014 23:51:20 +0100 Subject: [PATCH 079/145] Forgot return in connected() --- PS4BT.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PS4BT.h b/PS4BT.h index a723cec8..842adbac 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -65,7 +65,7 @@ public: /** True if a device is connected */ bool connected() { - BTHID::connected; + return BTHID::connected; }; /** From 06b859bb7fb7890bc96654fd7cc476d440df37d1 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 19 Jan 2014 00:11:48 +0100 Subject: [PATCH 080/145] Added links to blog posts --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index ab7e2b2a..4bda8002 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,8 @@ It uses the standard Boot protocol by default, but it is also able to use the Re The [PS4 library](#ps4-library) also uses this class to handle all Bluetooth communication. +For information see the following blog post: . + ### [SPP library](SPP.cpp) 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. @@ -130,6 +132,8 @@ Simply create the PS4BT instance like so: ```PS4BT PS4(&Btd, PAIR);``` and then It should then automatically pair the dongle with your controller. This only have to be done once. +For information see the following blog post: . + ### PS3 Library 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. From e781d6c554341fa0860dc9dfedc408ff7539c912 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 19 Jan 2014 16:58:29 +0100 Subject: [PATCH 081/145] Updated some comments and some other minor things --- BTHID.h | 2 +- PS4BT.h | 32 +++++++++++++----------- PS4Parser.cpp | 27 +++++++++++++-------- PS4Parser.h | 67 +++++++++++++++++++++++++++++++++++++++++++-------- PS4USB.h | 35 ++++++++++++++------------- 5 files changed, 111 insertions(+), 52 deletions(-) diff --git a/BTHID.h b/BTHID.h index 0dcd6a1e..07fd400d 100644 --- a/BTHID.h +++ b/BTHID.h @@ -25,7 +25,7 @@ #define MOUSE_PARSER_ID 1 #define NUM_PARSERS 2 -/** This BluetoothService class implements support for the HID keyboard and mice. */ +/** This BluetoothService class implements support for Bluetooth HID devices. */ class BTHID : public BluetoothService { public: /** diff --git a/PS4BT.h b/PS4BT.h index 842adbac..4183d2c0 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -29,13 +29,30 @@ class PS4BT : public BTHID, public PS4Parser { public: /** * Constructor for the PS4BT class. - * @param p Pointer to the BTHID class instance. + * @param p Pointer to the BTD class instance. */ PS4BT(BTD *p, bool pair = false, const char *pin = "0000") : BTHID(p, pair, pin) { PS4Parser::Reset(); }; + /** + * Used to check if a PS4 controller is connected. + * @return Returns true if it is connected. + */ + bool connected() { + return BTHID::connected; + }; + + /** + * Used to call your own function when the device is successfully initialized. + * @param funcOnInit Function to call. + */ + void attachOnInit(void (*funcOnInit)(void)) { + pFuncOnInit = funcOnInit; + }; + +protected: /** @name BTHID implementation */ /** * Used to parse Bluetooth HID data. @@ -63,19 +80,6 @@ public: }; /**@}*/ - /** True if a device is connected */ - bool connected() { - return BTHID::connected; - }; - - /** - * Used to call your own function when the device is successfully initialized. - * @param funcOnInit Function to call. - */ - void attachOnInit(void (*funcOnInit)(void)) { - pFuncOnInit = funcOnInit; - }; - private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() }; diff --git a/PS4Parser.cpp b/PS4Parser.cpp index 16c1ee3d..01624581 100644 --- a/PS4Parser.cpp +++ b/PS4Parser.cpp @@ -61,10 +61,10 @@ bool PS4Parser::getButtonClick(ButtonEnum b) { return click; } -uint8_t PS4Parser::getAnalogButton(ButtonEnum a) { - if (a == L2) // These are the only analog buttons on the controller +uint8_t PS4Parser::getAnalogButton(ButtonEnum b) { + if (b == L2) // These are the only analog buttons on the controller return ps4Data.trigger[0]; - else if (a == R2) + else if (b == R2) return ps4Data.trigger[1]; return 0; } @@ -75,7 +75,21 @@ uint8_t PS4Parser::getAnalogHat(AnalogHatEnum a) { void PS4Parser::Parse(uint8_t len, uint8_t *buf) { if (len > 0 && buf) { +#ifdef PRINTREPORT + for (uint8_t i = 0; i < len; i++) { + D_PrintHex (buf[i], 0x80); + Notify(PSTR(" "), 0x80); + } + Notify(PSTR("\r\n"), 0x80); +#endif + memcpy(&ps4Data, buf, min(len, sizeof(ps4Data))); + if (ps4Data.reportId != 0x01) { +#ifdef DEBUG_USB_HOST + Notify(PSTR("\r\nUnknown report id"), 0x80); +#endif + return; + } for (uint8_t i = 0; i < sizeof(ps4Data.btn); i++) { if (ps4Data.btn.val[i] != oldButtonState.val[i]) { // Check if anything has changed @@ -98,12 +112,5 @@ void PS4Parser::Parse(uint8_t len, uint8_t *buf) { } } } -#ifdef PRINTREPORT - for (uint8_t i = 0; i < len; i++) { - D_PrintHex (buf[i], 0x80); - Notify(PSTR(" "), 0x80); - } - Notify(PSTR("\r\n"), 0x80); -#endif } } \ No newline at end of file diff --git a/PS4Parser.h b/PS4Parser.h index d3e28f88..26f83576 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -18,7 +18,7 @@ #ifndef _ps4parser_h_ #define _ps4parser_h_ -#include "hid.h" +#include "Usb.h" #include "controllerEnums.h" /** Buttons on the controller */ @@ -87,7 +87,7 @@ struct touchpadXY { struct PS4Data { /* Button and joystick values */ - uint8_t report_id; // Always 0x01 + uint8_t reportId; // Always 0x01 uint8_t hatValue[4]; PS4Buttons btn; uint8_t trigger[2]; @@ -95,12 +95,12 @@ struct PS4Data { // I still need to figure out how to make the PS4 controller send out the rest of the data via Bluetooth /* Gyro and accelerometer values */ - uint8_t dummy[3]; // First two looks random, while the third one might be some kind of status + uint8_t dummy[3]; // First two looks random, while the third one might be some kind of status - it increments once in a while int16_t gyroY, gyroZ, gyroX; int16_t accX, accZ, accY; /* The rest is data for the touchpad */ - uint8_t dummy2[9]; // Byte 5 looks like some kind of status (maybe battery status), bit 1 of byte 9 is set every time a finger is moving around the touchpad + uint8_t dummy2[9]; // Byte 5 looks like some kind of status (maybe battery status), bit 1 of byte 8 is set every time a finger is moving around the touchpad touchpadXY xy[3]; // It looks like it sends out three coordinates each time, this is possible because the microcontroller inside the PS4 controller is much faster than the Bluetooth connection. // The last data is read from the last position in the array while the oldest measurement is from the first position. // The first position will also keep it's value after the finger is released, while the other two will set them to zero. @@ -152,7 +152,7 @@ public: * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T. * @return Analog value in the range of 0-255. */ - uint8_t getAnalogButton(ButtonEnum a); + uint8_t getAnalogButton(ButtonEnum b); /** * Used to read the analog joystick. @@ -163,22 +163,59 @@ public: /**@}*/ /** @name Only available via USB at the moment */ + /** + * Get the x-coordinate of the touchpad. Position 0 is in the top left. + * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used. + * @param xyId The controller sends out three packets with the same structure. + * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one. + * For that reason it will be set to 0 if the argument is omitted. + * @return Returns the x-coordinate of the finger. + */ uint16_t getX(uint8_t finger = 0, uint8_t xyId = 0) { return ps4Data.xy[xyId].finger[finger].x; }; + /** + * Get the y-coordinate of the touchpad. Position 0 is in the top left. + * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used. + * @param xyId The controller sends out three packets with the same structure. + * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one. + * For that reason it will be set to 0 if the argument is omitted. + * @return Returns the y-coordinate of the finger. + */ uint16_t getY(uint8_t finger = 0, uint8_t xyId = 0) { return ps4Data.xy[xyId].finger[finger].y; }; - uint8_t isTouching(uint8_t finger = 0, uint8_t xyId = 0) { - return !(ps4Data.xy[xyId].finger[finger].touching); // The bit is cleared every time when a finger is touching the touchpad + /** + * Returns whenever the user is toucing the touchpad. + * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used. + * @param xyId The controller sends out three packets with the same structure. + * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one. + * For that reason it will be set to 0 if the argument is omitted. + * @return Returns true if the specific finger is touching the touchpad. + */ + bool isTouching(uint8_t finger = 0, uint8_t xyId = 0) { + return !(ps4Data.xy[xyId].finger[finger].touching); // The bit is cleared when a finger is touching the touchpad }; + /** + * This counter increments every time a finger touches the touchpad. + * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used. + * @param xyId The controller sends out three packets with the same structure. + * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one. + * For that reason it will be set to 0 if the argument is omitted. + * @return Return the value of the counter, note that it is only a 7-bit value. + */ uint8_t getTouchCounter(uint8_t finger = 0, uint8_t xyId = 0) { return ps4Data.xy[xyId].finger[finger].counter; }; + /** + * Get the angle of the controller calculated using the accelerometer. + * @param a Either ::Pitch or ::Roll. + * @return Return the angle in the range of 0-360. + */ double getAngle(AngleEnum a) { if(a == Pitch) return (atan2(ps4Data.accY, ps4Data.accZ) + PI) * RAD_TO_DEG; @@ -186,6 +223,11 @@ public: return (atan2(ps4Data.accX, ps4Data.accZ) + PI) * RAD_TO_DEG; }; + /** + * Used to get the raw values from the 3-axis gyroscope and 3-axis accelerometer inside the PS4 controller. + * @param s The sensor to read. + * @return Returns the raw sensor reading. + */ int16_t getSensor(SensorEnum s) { switch(s) { case gX: @@ -206,6 +248,14 @@ public: }; /**@}*/ +protected: + /** + * Used to parse data sent from the PS4 controller. + * @param len Length of the data. + * @param buf Pointer to the data buffer. + */ + void Parse(uint8_t len, uint8_t *buf); + /** Used to reset the different buffers to their default values */ void Reset() { uint8_t i; @@ -228,9 +278,6 @@ public: oldDpad = 0; }; -protected: - void Parse(uint8_t len, uint8_t *buf); - private: bool checkDpad(ButtonEnum b); // Used to check PS4 DPAD buttons diff --git a/PS4USB.h b/PS4USB.h index a009071c..1ea2a421 100644 --- a/PS4USB.h +++ b/PS4USB.h @@ -32,13 +32,30 @@ class PS4USB : public HIDUniversal, public PS4Parser { public: /** * Constructor for the PS4USB class. - * @param p Pointer to the HIDUniversal class instance. + * @param p Pointer to the USB class instance. */ PS4USB(USB *p) : HIDUniversal(p) { PS4Parser::Reset(); }; + /** + * Used to check if a PS4 controller is connected. + * @return Returns true if it is connected. + */ + bool connected() { + return HIDUniversal::isReady() && HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID; + }; + + /** + * Used to call your own function when the device is successfully initialized. + * @param funcOnInit Function to call. + */ + void attachOnInit(void (*funcOnInit)(void)) { + pFuncOnInit = funcOnInit; + }; + +protected: /** @name HIDUniversal implementation */ /** * Used to parse USB HID data. @@ -65,22 +82,6 @@ public: }; /**@}*/ - /** - * Used to check if a PS4 controller is connected. - * @return Returns true if it is connected. - */ - bool connected() { - return HIDUniversal::isReady() && HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID; - }; - - /** - * Used to call your own function when the device is successfully initialized. - * @param funcOnInit Function to call. - */ - void attachOnInit(void (*funcOnInit)(void)) { - pFuncOnInit = funcOnInit; - }; - private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() }; From e2bf041286184b6ae2955a87674055a7ca238d95 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 19 Jan 2014 17:14:09 +0100 Subject: [PATCH 082/145] Updated some more comments --- PS4BT.h | 4 +++- PS4Parser.h | 2 +- Wii.h | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/PS4BT.h b/PS4BT.h index 4183d2c0..86b0ac47 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -29,7 +29,9 @@ class PS4BT : public BTHID, public PS4Parser { public: /** * Constructor for the PS4BT class. - * @param p Pointer to the BTD class instance. + * @param p Pointer to the BTD class instance. + * @param pair Set this to true in order to pair with the device. If the argument is omitted then it will not pair with it. One can use ::PAIR to set it to true. + * @param pin Write the pin to BTD#btdPin. If argument is omitted, then "0000" will be used. */ PS4BT(BTD *p, bool pair = false, const char *pin = "0000") : BTHID(p, pair, pin) { diff --git a/PS4Parser.h b/PS4Parser.h index 26f83576..ddd23161 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -146,7 +146,7 @@ public: /** @name PS4 Controller functions */ /** * Used to get the analog value from button presses. - * @param a The ::ButtonEnum to read. + * @param b The ::ButtonEnum to read. * The supported buttons are: * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2, * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T. diff --git a/Wii.h b/Wii.h index 294cd7a2..848dec93 100755 --- a/Wii.h +++ b/Wii.h @@ -280,7 +280,7 @@ public: #ifdef WIICAMERA /** @name Wiimote IR camera functions - * You will have to set ENABLE_WII_IR_CAMERA in settings.h to 1 in order use the IR camera. + * You will have to set ::ENABLE_WII_IR_CAMERA in settings.h to 1 in order use the IR camera. */ /** Initialises the camera as per the steps from: http://wiibrew.org/wiki/Wiimote#IR_Camera */ void IRinitialize(); From 2a1db31cf13551528390e02640b38f101ba576ce Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 22 Jan 2014 05:13:49 +0100 Subject: [PATCH 083/145] Can now read the IMU and touchpad values of the PS4 controller via Bluetooth as well Thanks to Frank Zhao - see: http://eleccelerator.com/wiki/index.php?title=DualShock_4#0x11 --- BTHID.cpp | 2 +- BTHID.h | 28 ++++++++++++++++----------- PS4BT.h | 13 +++++++++++++ PS4Parser.cpp | 13 +++++++++---- PS4Parser.h | 1 - README.md | 4 ++-- examples/Bluetooth/PS4BT/PS4BT.ino | 31 ++++++++++++++++++++++++++++-- 7 files changed, 71 insertions(+), 21 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index 64d3a812..37da8f04 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -202,7 +202,7 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { if(pRptParser[MOUSE_PARSER_ID]) pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance break; -#ifdef DEBUG_USB_HOST +#ifdef EXTRADEBUG default: Notify(PSTR("\r\nUnknown Report type: "), 0x80); D_PrintHex (l2capinbuf[9], 0x80); diff --git a/BTHID.h b/BTHID.h index 07fd400d..58b907a4 100644 --- a/BTHID.h +++ b/BTHID.h @@ -126,8 +126,20 @@ protected: } /**@}*/ + /** Pointer to BTD instance */ + BTD *pBtd; + + /** HCI Handle for connection */ + uint16_t hci_handle; + + /** L2CAP source CID for HID_Control */ + + uint8_t control_scid[2]; + + /** L2CAP source CID for HID_Interrupt */ + uint8_t interrupt_scid[2]; + private: - BTD *pBtd; // Pointer to BTD instance HIDReportParser *pRptParser[NUM_PARSERS]; // Pointer to HIDReportParsers. /** Set report protocol. */ @@ -148,19 +160,13 @@ private: void L2CAP_task(); // L2CAP state machine - /* Variables filled from HCI event management */ - uint16_t hci_handle; bool activeConnection; // Used to indicate if it already has established a connection - /* Variables used by high level L2CAP task */ + /* Variables used for L2CAP communication */ + uint8_t control_dcid[2]; // L2CAP device CID for HID_Control - Always 0x0070 + uint8_t interrupt_dcid[2]; // L2CAP device CID for HID_Interrupt - Always 0x0071 + uint8_t identifier; // Identifier for connection uint8_t l2cap_state; uint32_t l2cap_event_flag; // l2cap flags of received Bluetooth events - - /* L2CAP Channels */ - uint8_t control_scid[2]; // L2CAP source CID for HID_Control - uint8_t control_dcid[2]; // 0x0070 - uint8_t interrupt_scid[2]; // L2CAP source CID for HID_Interrupt - uint8_t interrupt_dcid[2]; // 0x0071 - uint8_t identifier; // Identifier for connection }; #endif diff --git a/PS4BT.h b/PS4BT.h index 86b0ac47..02399fcf 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -72,6 +72,7 @@ protected: * This is useful for instance if you want to set the LEDs in a specific way. */ virtual void OnInitBTHID() { + enable_sixaxis(); // Make the controller to send out the entire output report if (pFuncOnInit) pFuncOnInit(); // Call the user function }; @@ -84,5 +85,17 @@ protected: private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() + + void HID_Command(uint8_t *data, uint8_t nbytes) { + pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); + }; + + void enable_sixaxis() { // Command used to make the PS4 controller send out the entire output report + uint8_t buf[2]; + buf[0] = 0x43; // HID BT Get_report (0x40) | Report Type (Feature 0x03) + buf[1] = 0x02; // Report ID + + HID_Command(buf, 2); + }; }; #endif \ No newline at end of file diff --git a/PS4Parser.cpp b/PS4Parser.cpp index 01624581..f22784cd 100644 --- a/PS4Parser.cpp +++ b/PS4Parser.cpp @@ -76,17 +76,22 @@ uint8_t PS4Parser::getAnalogHat(AnalogHatEnum a) { void PS4Parser::Parse(uint8_t len, uint8_t *buf) { if (len > 0 && buf) { #ifdef PRINTREPORT + Notify(PSTR("\r\n"), 0x80); for (uint8_t i = 0; i < len; i++) { D_PrintHex (buf[i], 0x80); Notify(PSTR(" "), 0x80); } - Notify(PSTR("\r\n"), 0x80); #endif - memcpy(&ps4Data, buf, min(len, sizeof(ps4Data))); - if (ps4Data.reportId != 0x01) { + + if (buf[0] == 0x01) // Check report ID + memcpy(&ps4Data, buf + 1, min(len - 1, sizeof(ps4Data))); + else if (buf[0] == 0x11) // This report is send via Bluetooth, it has an offset of 2 compared to the USB data + memcpy(&ps4Data, buf + 3, min(len - 3, sizeof(ps4Data))); + else { #ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nUnknown report id"), 0x80); + Notify(PSTR("\r\nUnknown report id: "), 0x80); + D_PrintHex (buf[0], 0x80); #endif return; } diff --git a/PS4Parser.h b/PS4Parser.h index ddd23161..f5bc65e9 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -87,7 +87,6 @@ struct touchpadXY { struct PS4Data { /* Button and joystick values */ - uint8_t reportId; // Always 0x01 uint8_t hatValue[4]; PS4Buttons btn; uint8_t trigger[2]; diff --git a/README.md b/README.md index 4bda8002..b2a7dcc4 100644 --- a/README.md +++ b/README.md @@ -124,8 +124,6 @@ The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) and [PS4USB.ino](examples/PS I still have not figured out how to turn rumble on and off and set the color of the light, but hopefully I will figure that out soon. -Also the gyro, accelerometer and touchpad values are still only available via USB at the moment. - Before you can use the PS4 controller via Bluetooth you will need to pair with it. Simply create the PS4BT instance like so: ```PS4BT PS4(&Btd, PAIR);``` and then hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode. @@ -134,6 +132,8 @@ It should then automatically pair the dongle with your controller. This only hav For information see the following blog post: . +Also check out this excellent Wiki by Frank Zhao about the PS4 controller: . + ### PS3 Library 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. diff --git a/examples/Bluetooth/PS4BT/PS4BT.ino b/examples/Bluetooth/PS4BT/PS4BT.ino index 924cdc1d..0b850737 100644 --- a/examples/Bluetooth/PS4BT/PS4BT.ino +++ b/examples/Bluetooth/PS4BT/PS4BT.ino @@ -24,6 +24,8 @@ PS4BT PS4(&Btd, PAIR); // After that you can simply create the instance like so and then press the PS button on the device //PS4BT PS4(&Btd); +boolean printAngle, printTouch; + void setup() { Serial.begin(115200); while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection @@ -88,10 +90,35 @@ void loop() { if (PS4.getButtonClick(SHARE)) Serial.print(F("\r\nShare")); - if (PS4.getButtonClick(OPTIONS)) + if (PS4.getButtonClick(OPTIONS)) { Serial.print(F("\r\nOptions")); - if (PS4.getButtonClick(TOUCHPAD)) + printAngle = !printAngle; + } + if (PS4.getButtonClick(TOUCHPAD)) { Serial.print(F("\r\nTouchpad")); + printTouch = !printTouch; + } + + if (printAngle) { // Print angle calculated using the accelerometer only + Serial.print(F("\r\nPitch: ")); + Serial.print(PS4.getAngle(Pitch)); + Serial.print(F("\tRoll: ")); + Serial.print(PS4.getAngle(Roll)); + } + + if (printTouch) { // Print the x, y coordinates of the touchpad + if (PS4.isTouching(0) || PS4.isTouching(1)) // Print newline and carriage return if any of the fingers are touching the touchpad + Serial.print(F("\r\n")); + for (uint8_t i = 0; i < 2; i++) { // The touchpad track two fingers + if (PS4.isTouching(i)) { // Print the position of the finger if it is touching the touchpad + Serial.print(F("X")); Serial.print(i + 1); Serial.print(F(": ")); + Serial.print(PS4.getX(i)); + Serial.print(F("\tY")); Serial.print(i + 1); Serial.print(F(": ")); + Serial.print(PS4.getY(i)); + Serial.print(F("\t")); + } + } + } } } } From 876962afcef92327dbdd8d65570e216a30a742df Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 22 Jan 2014 06:31:27 +0100 Subject: [PATCH 084/145] Update comments --- PS4BT.h | 2 +- PS4Parser.h | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/PS4BT.h b/PS4BT.h index 02399fcf..33bb58ec 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -72,7 +72,7 @@ protected: * This is useful for instance if you want to set the LEDs in a specific way. */ virtual void OnInitBTHID() { - enable_sixaxis(); // Make the controller to send out the entire output report + enable_sixaxis(); // Make the controller send out the entire output report if (pFuncOnInit) pFuncOnInit(); // Call the user function }; diff --git a/PS4Parser.h b/PS4Parser.h index f5bc65e9..4c1d9d4b 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -66,7 +66,7 @@ union PS4Buttons { uint8_t ps : 1; uint8_t touchpad : 1; - uint8_t timestamp : 6; // Only available via USB + uint8_t reportCounter : 6; }; uint8_t val[3]; }; @@ -91,8 +91,6 @@ struct PS4Data { PS4Buttons btn; uint8_t trigger[2]; - // I still need to figure out how to make the PS4 controller send out the rest of the data via Bluetooth - /* Gyro and accelerometer values */ uint8_t dummy[3]; // First two looks random, while the third one might be some kind of status - it increments once in a while int16_t gyroY, gyroZ, gyroX; @@ -100,7 +98,7 @@ struct PS4Data { /* The rest is data for the touchpad */ uint8_t dummy2[9]; // Byte 5 looks like some kind of status (maybe battery status), bit 1 of byte 8 is set every time a finger is moving around the touchpad - touchpadXY xy[3]; // It looks like it sends out three coordinates each time, this is possible because the microcontroller inside the PS4 controller is much faster than the Bluetooth connection. + touchpadXY xy[3]; // It looks like it sends out three coordinates each time, this might be because the microcontroller inside the PS4 controller is much faster than the Bluetooth connection. // The last data is read from the last position in the array while the oldest measurement is from the first position. // The first position will also keep it's value after the finger is released, while the other two will set them to zero. // Note that if you read fast enough from the device, then only the first one will contain any data. @@ -159,9 +157,7 @@ public: * @return Return the analog value in the range of 0-255. */ uint8_t getAnalogHat(AnalogHatEnum a); - /**@}*/ - /** @name Only available via USB at the moment */ /** * Get the x-coordinate of the touchpad. Position 0 is in the top left. * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used. From 08abfd4268e7e927f9605019075f972d39e5b788 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 23 Jan 2014 10:38:00 +0100 Subject: [PATCH 085/145] Fixes #72 --- avrpins.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/avrpins.h b/avrpins.h index ca83a8a9..bdc99ba6 100644 --- a/avrpins.h +++ b/avrpins.h @@ -457,7 +457,7 @@ public: #define P2 Pe4 #define P3 Pe5 #define P4 Pg5 -#define P5 Pe5 +#define P5 Pe3 #define P6 Ph3 #define P7 Ph4 From 78062121325f99e1a068eed8f0fe7c76017b9c6a Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 3 Feb 2014 23:06:27 +0100 Subject: [PATCH 086/145] Removed some unnecessary functions and some other cleanup --- BTHID.cpp | 2 +- BTHID.h | 3 +-- PS4BT.h | 14 +------------- PS4Parser.h | 12 ++++-------- PS4USB.h | 4 ++-- 5 files changed, 9 insertions(+), 26 deletions(-) diff --git a/BTHID.cpp b/BTHID.cpp index 37da8f04..01f190a7 100644 --- a/BTHID.cpp +++ b/BTHID.cpp @@ -190,7 +190,7 @@ void BTHID::ACLData(uint8_t* l2capinbuf) { #endif if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); - ParseBTHID(this, (uint8_t)(length - 1), &l2capinbuf[9]); + ParseBTHIDData((uint8_t)(length - 1), &l2capinbuf[9]); switch(l2capinbuf[9]) { case 0x01: // Keyboard or Joystick events diff --git a/BTHID.h b/BTHID.h index 58b907a4..2419e58b 100644 --- a/BTHID.h +++ b/BTHID.h @@ -109,11 +109,10 @@ protected: /** @name Overridable functions */ /** * Used to parse Bluetooth HID data to any class that inherits this class. - * @param bthid Pointer to this class. * @param len The length of the incoming data. * @param buf Pointer to the data buffer. */ - virtual void ParseBTHID(BTHID *bthid, uint8_t len, uint8_t *buf) { + virtual void ParseBTHIDData(uint8_t len, uint8_t *buf) { return; }; /** Called when a device is connected */ diff --git a/PS4BT.h b/PS4BT.h index 33bb58ec..bd42786a 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -46,14 +46,6 @@ public: return BTHID::connected; }; - /** - * Used to call your own function when the device is successfully initialized. - * @param funcOnInit Function to call. - */ - void attachOnInit(void (*funcOnInit)(void)) { - pFuncOnInit = funcOnInit; - }; - protected: /** @name BTHID implementation */ /** @@ -62,7 +54,7 @@ protected: * @param len The length of the incoming data. * @param buf Pointer to the data buffer. */ - virtual void ParseBTHID(BTHID *bthid, uint8_t len, uint8_t *buf) { + virtual void ParseBTHIDData(uint8_t len, uint8_t *buf) { PS4Parser::Parse(len, buf); }; @@ -73,8 +65,6 @@ protected: */ virtual void OnInitBTHID() { enable_sixaxis(); // Make the controller send out the entire output report - if (pFuncOnInit) - pFuncOnInit(); // Call the user function }; /** Used to reset the different buffers to there default values */ @@ -84,8 +74,6 @@ protected: /**@}*/ private: - void (*pFuncOnInit)(void); // Pointer to function called in onInit() - void HID_Command(uint8_t *data, uint8_t nbytes) { pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); }; diff --git a/PS4Parser.h b/PS4Parser.h index 4c1d9d4b..cedbc0b4 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -74,14 +74,10 @@ union PS4Buttons { struct touchpadXY { uint8_t dummy; // I can not figure out what this data is for, it seems to change randomly, maybe a timestamp? struct { - struct { - uint8_t counter : 7; // Increments every time a finger is touching the touchpad - uint8_t touching : 1; // The top bit is cleared if the finger is touching the touchpad - }; - struct { - uint16_t x : 12; - uint16_t y : 12; - }; + uint8_t counter : 7; // Increments every time a finger is touching the touchpad + uint8_t touching : 1; // The top bit is cleared if the finger is touching the touchpad + uint16_t x : 12; + uint16_t y : 12; } finger[2]; // 0 = first finger, 1 = second finger }; diff --git a/PS4USB.h b/PS4USB.h index 1ea2a421..fcb514c3 100644 --- a/PS4USB.h +++ b/PS4USB.h @@ -21,8 +21,8 @@ #include "hiduniversal.h" #include "PS4Parser.h" -#define PS4_VID 0x054C // Sony Corporation -#define PS4_PID 0x05C4 // PS4 Controller +#define PS4_VID 0x054C // Sony Corporation +#define PS4_PID 0x05C4 // PS4 Controller /** * This class implements support for the PS4 controller via USB. From b25c7d2f3c674a430e5aa25e74b229475521ef88 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 3 Feb 2014 23:11:44 +0100 Subject: [PATCH 087/145] Made it easy to disable printing incoming data in hiduniversal --- hiduniversal.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hiduniversal.cpp b/hiduniversal.cpp index 4e866cb2..a2b4dc2e 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -381,14 +381,14 @@ uint8_t HIDUniversal::Poll() { if(identical) return 0; - +#if 1 Notify(PSTR("\r\nBuf: "), 0x80); for(uint8_t i = 0; i < read; i++) D_PrintHex (buf[i], 0x80); Notify(PSTR("\r\n"), 0x80); - +#endif ParseHIDData(this, bHasReportId, (uint8_t)read, buf); HIDReportParser *prs = GetReportParser(((bHasReportId) ? *buf : 0)); From 9b44357d044f13f29bd2e21a02cb74d21a3a40e0 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 16 Feb 2014 01:24:38 +0100 Subject: [PATCH 088/145] Added packed attribute to all structs in PS4Parser.h. This was needed for Teensy 3.x It was actually only necessary for finger in touchpadXY, but I added to all structs to prevent similar compile errors for future architectures --- PS4Parser.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/PS4Parser.h b/PS4Parser.h index cedbc0b4..1fe8ab2a 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -67,7 +67,7 @@ union PS4Buttons { uint8_t ps : 1; uint8_t touchpad : 1; uint8_t reportCounter : 6; - }; + } __attribute__((packed)); uint8_t val[3]; }; @@ -78,8 +78,8 @@ struct touchpadXY { uint8_t touching : 1; // The top bit is cleared if the finger is touching the touchpad uint16_t x : 12; uint16_t y : 12; - } finger[2]; // 0 = first finger, 1 = second finger -}; + } __attribute__((packed)) finger[2]; // 0 = first finger, 1 = second finger +} __attribute__((packed)); struct PS4Data { /* Button and joystick values */ @@ -100,7 +100,7 @@ struct PS4Data { // Note that if you read fast enough from the device, then only the first one will contain any data. // The last three bytes are always: 0x00, 0x80, 0x00 -}; +} __attribute__((packed)); enum DPADEnum { DPAD_UP = 0x0, From ac5d134f73a0296d26d23b86b4cde4b9cb2bcc59 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 16 Feb 2014 18:13:19 +0100 Subject: [PATCH 089/145] Added support for Afterglow wired Xbox controller --- XBOXUSB.cpp | 2 +- XBOXUSB.h | 23 ++++++++++++----------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/XBOXUSB.cpp b/XBOXUSB.cpp index 8ee06d4f..4128d231 100644 --- a/XBOXUSB.cpp +++ b/XBOXUSB.cpp @@ -105,7 +105,7 @@ uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) { Notify(PSTR("\r\nThis library only supports Xbox 360 controllers via USB"), 0x80); #endif goto FailUnknownDevice; - } else if(PID != XBOX_WIRED_PID && PID != MADCATZ_WIRED_PID && PID != GAMESTOP_WIRED_PID) // Check PID + } else if(PID != XBOX_WIRED_PID && PID != MADCATZ_WIRED_PID && PID != GAMESTOP_WIRED_PID && PID != AFTERGLOW_WIRED_PID) // Check PID goto FailUnknownDevice; // Allocate new address according to device class diff --git a/XBOXUSB.h b/XBOXUSB.h index c18ea248..aed330a2 100644 --- a/XBOXUSB.h +++ b/XBOXUSB.h @@ -33,17 +33,18 @@ #define XBOX_OUTPUT_PIPE 2 // PID and VID of the different devices -#define XBOX_VID 0x045E // Microsoft Corporation -#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz controllers -#define JOYTECH_VID 0x162E // For unofficial Joytech controllers -#define GAMESTOP_VID 0x0E6F // Gamestop controller +#define XBOX_VID 0x045E // Microsoft Corporation +#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz controllers +#define JOYTECH_VID 0x162E // For unofficial Joytech controllers +#define GAMESTOP_VID 0x0E6F // Gamestop controller -#define XBOX_WIRED_PID 0x028E // Microsoft 360 Wired controller -#define XBOX_WIRELESS_PID 0x028F // Wireless controller only support charging -#define XBOX_WIRELESS_RECEIVER_PID 0x0719 // Microsoft Wireless Gaming Receiver -#define XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID 0x0291 // Third party Wireless Gaming Receiver -#define MADCATZ_WIRED_PID 0xF016 // Mad Catz wired controller -#define GAMESTOP_WIRED_PID 0x0401 // Gamestop wired controller +#define XBOX_WIRED_PID 0x028E // Microsoft 360 Wired controller +#define XBOX_WIRELESS_PID 0x028F // Wireless controller only support charging +#define XBOX_WIRELESS_RECEIVER_PID 0x0719 // Microsoft Wireless Gaming Receiver +#define XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID 0x0291 // Third party Wireless Gaming Receiver +#define MADCATZ_WIRED_PID 0xF016 // Mad Catz wired controller +#define GAMESTOP_WIRED_PID 0x0401 // Gamestop wired controller +#define AFTERGLOW_WIRED_PID 0x0213 // Afterglow wired controller - it uses the same VID as a Gamestop controller #define XBOX_REPORT_BUFFER_SIZE 14 // Size of the input report buffer @@ -105,7 +106,7 @@ public: * @return Returns true if the device's VID and PID matches this driver. */ virtual boolean VIDPIDOK(uint16_t vid, uint16_t pid) { - return ((vid == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID || vid == GAMESTOP_VID) && (pid == XBOX_WIRED_PID || pid == MADCATZ_WIRED_PID || pid == GAMESTOP_WIRED_PID)); + return ((vid == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID || vid == GAMESTOP_VID) && (pid == XBOX_WIRED_PID || pid == MADCATZ_WIRED_PID || pid == GAMESTOP_WIRED_PID || pid == AFTERGLOW_WIRED_PID)); }; /**@}*/ From 6373ebe6ce1010b5242197149d33a9e1be2bc34d Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 17 Feb 2014 00:21:21 +0100 Subject: [PATCH 090/145] Can now set the rumble and light on the PS4 controller Still need to test it via USB --- PS3Enums.h | 27 ------------- PS4BT.h | 43 ++++++++++++++++++++ PS4Parser.cpp | 3 ++ PS4Parser.h | 83 ++++++++++++++++++++++++++++++++++++++ PS4USB.h | 36 +++++++++++++++-- README.md | 6 +-- controllerEnums.h | 27 +++++++++++++ examples/PS4USB/PS4USB.ino | 5 +++ hiduniversal.h | 8 ++-- keywords.txt | 1 + 10 files changed, 200 insertions(+), 39 deletions(-) diff --git a/PS3Enums.h b/PS3Enums.h index 7ee84293..77801945 100644 --- a/PS3Enums.h +++ b/PS3Enums.h @@ -110,28 +110,6 @@ const uint8_t PS3_ANALOG_BUTTONS[] PROGMEM = { 15, // T_ANALOG - Both at byte 14 (last reading) and byte 15 (current reading) }; -/** Used to set the colors of the move controller. */ -enum ColorsEnum { - /** r = 255, g = 0, b = 0 */ - Red = 0xFF0000, - /** r = 0, g = 255, b = 0 */ - Green = 0xFF00, - /** r = 0, g = 0, b = 255 */ - Blue = 0xFF, - - /** r = 255, g = 235, b = 4 */ - Yellow = 0xFFEB04, - /** r = 0, g = 255, b = 255 */ - Lightblue = 0xFFFF, - /** r = 255, g = 0, b = 255 */ - Purble = 0xFF00FF, - - /** r = 255, g = 255, b = 255 */ - White = 0xFFFFFF, - /** r = 0, g = 0, b = 0 */ - Off = 0x00, -}; - enum StatusEnum { // Note that the location is shifted 9 when it's connected via USB // Byte location | bit location @@ -160,9 +138,4 @@ enum StatusEnum { Bluetooth = (40 << 8) | 0x16, // Operating by Bluetooth and rumble is turned off }; -enum RumbleEnum { - RumbleHigh = 0x10, - RumbleLow = 0x20, -}; - #endif diff --git a/PS4BT.h b/PS4BT.h index bd42786a..129df6b1 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -46,6 +46,14 @@ public: return BTHID::connected; }; + /** + * Used to call your own function when the device is successfully initialized. + * @param funcOnInit Function to call. + */ + void attachOnInit(void (*funcOnInit)(void)) { + pFuncOnInit = funcOnInit; + }; + protected: /** @name BTHID implementation */ /** @@ -64,7 +72,12 @@ protected: * This is useful for instance if you want to set the LEDs in a specific way. */ virtual void OnInitBTHID() { + PS4Parser::Reset(); enable_sixaxis(); // Make the controller send out the entire output report + if (pFuncOnInit) + pFuncOnInit(); // Call the user function + else + setLed(Blue); }; /** Used to reset the different buffers to there default values */ @@ -74,6 +87,34 @@ protected: /**@}*/ private: + /** @name PS4Parser implementation */ + virtual void sendOutputReport(PS4Output *output) { // Source: https://github.com/chrippa/ds4drv + uint8_t buf[79]; + memset(buf, 0, sizeof(buf)); + + buf[0] = 0x52; // HID BT Set_report (0x50) | Report Type (Output 0x02) + buf[1] = 0x11; // Report ID + buf[2] = 0x80; + buf[4]= 0xFF; + + buf[7] = output->bigRumble; // Big Rumble + buf[8] = output->smallRumble; // Small rumble + + buf[9] = output->r; // Red + buf[10] = output->g; // Green + buf[11] = output->b; // Blue + + buf[12] = output->flashOn; // Time to flash bright (255 = 2.5 seconds) + buf[13] = output->flashOff; // Time to flash dark (255 = 2.5 seconds) + + output->reportChanged = false; + + // The PS4 console actually set the four last bytes to a CRC32 checksum, but it seems like it is actually not needed + + HID_Command(buf, sizeof(buf)); + }; + /**@}*/ + void HID_Command(uint8_t *data, uint8_t nbytes) { pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); }; @@ -85,5 +126,7 @@ private: HID_Command(buf, 2); }; + + void (*pFuncOnInit)(void); // Pointer to function called in onInit() }; #endif \ No newline at end of file diff --git a/PS4Parser.cpp b/PS4Parser.cpp index f22784cd..1a449adb 100644 --- a/PS4Parser.cpp +++ b/PS4Parser.cpp @@ -118,4 +118,7 @@ void PS4Parser::Parse(uint8_t len, uint8_t *buf) { } } } + + if (ps4Output.reportChanged) + sendOutputReport(&ps4Output); // Send output report } \ No newline at end of file diff --git a/PS4Parser.h b/PS4Parser.h index 1fe8ab2a..680edc83 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -102,6 +102,13 @@ struct PS4Data { // The last three bytes are always: 0x00, 0x80, 0x00 } __attribute__((packed)); +struct PS4Output { + uint8_t bigRumble, smallRumble; // Rumble + uint8_t r, g, b; // RGB + uint8_t flashOn, flashOff; // Time to flash bright/dark (255 = 2.5 seconds) + bool reportChanged; // The data is send when data is received from the controller +} __attribute__((packed)); + enum DPADEnum { DPAD_UP = 0x0, DPAD_UP_RIGHT = 0x1, @@ -237,6 +244,74 @@ public: return 0; } }; + + /** Turn both rumble and the LEDs off. */ + void setAllOff() { + setRumbleOff(); + setLedOff(); + }; + + /** Set rumble off. */ + void setRumbleOff() { + setRumbleOn(0, 0); + }; + + /** + * Turn on rumble. + * @param mode Either ::RumbleHigh or ::RumbleLow. + */ + void setRumbleOn(RumbleEnum mode) { + if (mode == RumbleLow) + setRumbleOn(0xFF, 0x00); + else + setRumbleOn(0x00, 0xFF); + }; + + /** + * Turn on rumble. + * @param bigRumble Value for big motor. + * @param smallRumble Value for small motor. + */ + void setRumbleOn(uint8_t bigRumble, uint8_t smallRumble) { + ps4Output.bigRumble = bigRumble; + ps4Output.smallRumble = smallRumble; + ps4Output.reportChanged = true; + }; + + /** Turn all LEDs off. */ + void setLedOff() { + setLed(0, 0, 0); + }; + + /** + * Use this to set the color using RGB values. + * @param r,g,b RGB value. + */ + void setLed(uint8_t r, uint8_t g, uint8_t b) { + ps4Output.r = r; + ps4Output.g = g; + ps4Output.b = b; + ps4Output.reportChanged = true; + }; + + /** + * Use this to set the color using the predefined colors in ::ColorsEnum. + * @param color The desired color. + */ + void setLed(ColorsEnum color) { + setLed((uint8_t)(color >> 16), (uint8_t)(color >> 8), (uint8_t)(color)); + }; + + /** + * Set the LEDs flash time. + * @param flashOn Time to flash bright (255 = 2.5 seconds). + * @param flashOff Time to flash dark (255 = 2.5 seconds). + */ + void setLedFlash(uint8_t flashOn, uint8_t flashOff) { + ps4Output.flashOn = flashOn; + ps4Output.flashOff = flashOff; + ps4Output.reportChanged = true; + }; /**@}*/ protected: @@ -267,13 +342,21 @@ protected: oldButtonState.dpad = DPAD_OFF; buttonClickState.dpad = 0; oldDpad = 0; + + ps4Output.bigRumble = ps4Output.smallRumble = 0; + ps4Output.r = ps4Output.g = ps4Output.b = 0; + ps4Output.flashOn = ps4Output.flashOff = 0; + ps4Output.reportChanged = false; }; + virtual void sendOutputReport(PS4Output *output) = 0; // This is overridden in PS4BT and PS4USB + private: bool checkDpad(ButtonEnum b); // Used to check PS4 DPAD buttons PS4Data ps4Data; PS4Buttons oldButtonState, buttonClickState; + PS4Output ps4Output; uint8_t oldDpad; }; #endif \ No newline at end of file diff --git a/PS4USB.h b/PS4USB.h index fcb514c3..d377b60d 100644 --- a/PS4USB.h +++ b/PS4USB.h @@ -75,14 +75,44 @@ protected: * This is useful for instance if you want to set the LEDs in a specific way. */ virtual uint8_t OnInitSuccessful() { - PS4Parser::Reset(); - if (HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID && pFuncOnInit) - pFuncOnInit(); // Call the user function + if (HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID) { + PS4Parser::Reset(); + if (pFuncOnInit) + pFuncOnInit(); // Call the user function + else + setLed(Blue); + }; return 0; }; /**@}*/ private: + /** @name PS4Parser implementation */ + virtual void sendOutputReport(PS4Output *output) { // Source: https://github.com/chrippa/ds4drv + uint8_t buf[32]; + memset(buf, 0, sizeof(buf)); + + buf[0] = 0x05; // Report ID + buf[1]= 0xFF; + + buf[4] = output->bigRumble; // Big Rumble + buf[5] = output->smallRumble; // Small rumble + + buf[6] = output->r; // Red + buf[7] = output->g; // Green + buf[8] = output->b; // Blue + + buf[9] = output->flashOn; // Time to flash bright (255 = 2.5 seconds) + buf[10] = output->flashOff; // Time to flash dark (255 = 2.5 seconds) + + output->reportChanged = false; + + // The PS4 console actually set the four last bytes to a CRC32 checksum, but it seems like it is actually not needed + + pUsb->outTransfer(bAddress, epInfo[ hidInterfaces[0].epIndex[epInterruptOutIndex] ].epAddr, sizeof(buf), buf); + }; + /**@}*/ + void (*pFuncOnInit)(void); // Pointer to function called in onInit() }; #endif \ No newline at end of file diff --git a/README.md b/README.md index b2a7dcc4..56152496 100644 --- a/README.md +++ b/README.md @@ -120,9 +120,7 @@ It enables me to see the Bluetooth communication between my Mac and any device. 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. -The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) and [PS4USB.ino](examples/PS4USB/PS4USB.ino) examples shows how to easily read the buttons and joysticks on the controller via Bluetooth and USB respectively. - -I still have not figured out how to turn rumble on and off and set the color of the light, but hopefully I will figure that out soon. +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. Before you can use the PS4 controller via Bluetooth you will need to pair with it. @@ -132,7 +130,7 @@ It should then automatically pair the dongle with your controller. This only hav For information see the following blog post: . -Also check out this excellent Wiki by Frank Zhao about the PS4 controller: . +Also check out this excellent Wiki by Frank Zhao about the PS4 controller: and this Linux driver: . ### PS3 Library diff --git a/controllerEnums.h b/controllerEnums.h index 0eae781d..295b6ae4 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -41,6 +41,33 @@ enum LEDEnum { ALL = 5, }; +/** Used to set the colors of the Move and PS4 controller. */ +enum ColorsEnum { + /** r = 255, g = 0, b = 0 */ + Red = 0xFF0000, + /** r = 0, g = 255, b = 0 */ + Green = 0xFF00, + /** r = 0, g = 0, b = 255 */ + Blue = 0xFF, + + /** r = 255, g = 235, b = 4 */ + Yellow = 0xFFEB04, + /** r = 0, g = 255, b = 255 */ + Lightblue = 0xFFFF, + /** r = 255, g = 0, b = 255 */ + Purble = 0xFF00FF, + + /** r = 255, g = 255, b = 255 */ + White = 0xFFFFFF, + /** r = 0, g = 0, b = 0 */ + Off = 0x00, +}; + +enum RumbleEnum { + RumbleHigh = 0x10, + RumbleLow = 0x20, +}; + /** This enum is used to read all the different buttons on the different controllers */ enum ButtonEnum { /**@{*/ diff --git a/examples/PS4USB/PS4USB.ino b/examples/PS4USB/PS4USB.ino index 95a0e586..c8dc5069 100644 --- a/examples/PS4USB/PS4USB.ino +++ b/examples/PS4USB/PS4USB.ino @@ -6,6 +6,11 @@ #include +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif + USB Usb; PS4USB PS4(&Usb); diff --git a/hiduniversal.h b/hiduniversal.h index bfd1173b..d97f4b8c 100644 --- a/hiduniversal.h +++ b/hiduniversal.h @@ -17,10 +17,7 @@ class HIDUniversal : public HID { // Returns HID class specific descriptor length by its type and order number uint16_t GetHidClassDescrLen(uint8_t type, uint8_t num); - EpInfo epInfo[totalEndpoints]; - struct HIDInterface { - struct { uint8_t bmInterface : 3; uint8_t bmAltSet : 3; @@ -29,8 +26,6 @@ class HIDUniversal : public HID { uint8_t epIndex[maxEpPerInterface]; }; - HIDInterface hidInterfaces[maxHidInterfaces]; - uint8_t bConfNum; // configuration number uint8_t bNumIface; // number of interfaces in the configuration uint8_t bNumEP; // total number of EP in the configuration @@ -49,6 +44,9 @@ class HIDUniversal : public HID { void SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest); protected: + EpInfo epInfo[totalEndpoints]; + HIDInterface hidInterfaces[maxHidInterfaces]; + bool bHasReportId; uint16_t PID, VID; // PID and VID of connected device diff --git a/keywords.txt b/keywords.txt index 786d4fa2..a13ff34d 100644 --- a/keywords.txt +++ b/keywords.txt @@ -64,6 +64,7 @@ setRumbleOn KEYWORD2 setLedOff KEYWORD2 setLedOn KEYWORD2 setLedToggle KEYWORD2 +setLedFlash KEYWORD2 moveSetBulb KEYWORD2 moveSetRumble KEYWORD2 From 2b69cfe15e18482a810f91a87726a48349e977c4 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 17 Feb 2014 00:27:46 +0100 Subject: [PATCH 091/145] Fixed indentation in PS4Parser.cpp --- PS4Parser.cpp | 128 +++++++++++++++++++++++++------------------------- 1 file changed, 64 insertions(+), 64 deletions(-) diff --git a/PS4Parser.cpp b/PS4Parser.cpp index 1a449adb..d8157f43 100644 --- a/PS4Parser.cpp +++ b/PS4Parser.cpp @@ -36,89 +36,89 @@ bool PS4Parser::checkDpad(ButtonEnum b) { } bool PS4Parser::getButtonPress(ButtonEnum b) { - if (b <= LEFT) // Dpad - return checkDpad(b); - else { - uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); - uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; - uint8_t mask = 1 << (button - 8 * index); - return ps4Data.btn.val[index] & mask; - } + if (b <= LEFT) // Dpad + return checkDpad(b); + else { + uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); + uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; + uint8_t mask = 1 << (button - 8 * index); + return ps4Data.btn.val[index] & mask; + } } bool PS4Parser::getButtonClick(ButtonEnum b) { - uint8_t mask, index = 0; - if (b <= LEFT) // Dpad - mask = 1 << b; - else { - uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); - index = button < 8 ? 0 : button < 16 ? 1 : 2; - mask = 1 << (button - 8 * index); - } + uint8_t mask, index = 0; + if (b <= LEFT) // Dpad + mask = 1 << b; + else { + uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); + index = button < 8 ? 0 : button < 16 ? 1 : 2; + mask = 1 << (button - 8 * index); + } - bool click = buttonClickState.val[index] & mask; - buttonClickState.val[index] &= ~mask; // Clear "click" event - return click; + bool click = buttonClickState.val[index] & mask; + buttonClickState.val[index] &= ~mask; // Clear "click" event + return click; } uint8_t PS4Parser::getAnalogButton(ButtonEnum b) { - if (b == L2) // These are the only analog buttons on the controller - return ps4Data.trigger[0]; - else if (b == R2) - return ps4Data.trigger[1]; - return 0; + if (b == L2) // These are the only analog buttons on the controller + return ps4Data.trigger[0]; + else if (b == R2) + return ps4Data.trigger[1]; + return 0; } uint8_t PS4Parser::getAnalogHat(AnalogHatEnum a) { - return ps4Data.hatValue[(uint8_t)a]; + return ps4Data.hatValue[(uint8_t)a]; } void PS4Parser::Parse(uint8_t len, uint8_t *buf) { - if (len > 0 && buf) { + if (len > 0 && buf) { #ifdef PRINTREPORT - Notify(PSTR("\r\n"), 0x80); - for (uint8_t i = 0; i < len; i++) { - D_PrintHex (buf[i], 0x80); - Notify(PSTR(" "), 0x80); - } + Notify(PSTR("\r\n"), 0x80); + for (uint8_t i = 0; i < len; i++) { + D_PrintHex (buf[i], 0x80); + Notify(PSTR(" "), 0x80); + } #endif - if (buf[0] == 0x01) // Check report ID - memcpy(&ps4Data, buf + 1, min(len - 1, sizeof(ps4Data))); - else if (buf[0] == 0x11) // This report is send via Bluetooth, it has an offset of 2 compared to the USB data - memcpy(&ps4Data, buf + 3, min(len - 3, sizeof(ps4Data))); - else { + if (buf[0] == 0x01) // Check report ID + memcpy(&ps4Data, buf + 1, min(len - 1, sizeof(ps4Data))); + else if (buf[0] == 0x11) // This report is send via Bluetooth, it has an offset of 2 compared to the USB data + memcpy(&ps4Data, buf + 3, min(len - 3, sizeof(ps4Data))); + else { #ifdef DEBUG_USB_HOST - Notify(PSTR("\r\nUnknown report id: "), 0x80); - D_PrintHex (buf[0], 0x80); + Notify(PSTR("\r\nUnknown report id: "), 0x80); + D_PrintHex (buf[0], 0x80); #endif - return; - } + return; + } - for (uint8_t i = 0; i < sizeof(ps4Data.btn); i++) { - if (ps4Data.btn.val[i] != oldButtonState.val[i]) { // Check if anything has changed - buttonClickState.val[i] = ps4Data.btn.val[i] & ~oldButtonState.val[i]; // Update click state variable - oldButtonState.val[i] = ps4Data.btn.val[i]; - if (i == 0) { // 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 - uint8_t newDpad = 0; - if (checkDpad(UP)) - newDpad |= 1 << UP; - if (checkDpad(RIGHT)) - newDpad |= 1 << RIGHT; - if (checkDpad(DOWN)) - newDpad |= 1 << DOWN; - if (checkDpad(LEFT)) - newDpad |= 1 << LEFT; - if (newDpad != oldDpad) { - buttonClickState.dpad = newDpad & ~oldDpad; // Override values - oldDpad = newDpad; - } - } - } - } - } + for (uint8_t i = 0; i < sizeof(ps4Data.btn); i++) { + if (ps4Data.btn.val[i] != oldButtonState.val[i]) { // Check if anything has changed + buttonClickState.val[i] = ps4Data.btn.val[i] & ~oldButtonState.val[i]; // Update click state variable + oldButtonState.val[i] = ps4Data.btn.val[i]; + if (i == 0) { // 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 + uint8_t newDpad = 0; + if (checkDpad(UP)) + newDpad |= 1 << UP; + if (checkDpad(RIGHT)) + newDpad |= 1 << RIGHT; + if (checkDpad(DOWN)) + newDpad |= 1 << DOWN; + if (checkDpad(LEFT)) + newDpad |= 1 << LEFT; + if (newDpad != oldDpad) { + buttonClickState.dpad = newDpad & ~oldDpad; // Override values + oldDpad = newDpad; + } + } + } + } + } - if (ps4Output.reportChanged) - sendOutputReport(&ps4Output); // Send output report + if (ps4Output.reportChanged) + sendOutputReport(&ps4Output); // Send output report } \ No newline at end of file From a21d1e7258b9a095f96ae87f53a16a0fa7e30287 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 17 Feb 2014 00:50:02 +0100 Subject: [PATCH 092/145] Cleanup No new code --- PS4BT.h | 10 +++++----- PS4Parser.h | 8 ++++++-- PS4USB.h | 2 +- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/PS4BT.h b/PS4BT.h index 129df6b1..85d70f48 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -86,7 +86,6 @@ protected: }; /**@}*/ -private: /** @name PS4Parser implementation */ virtual void sendOutputReport(PS4Output *output) { // Source: https://github.com/chrippa/ds4drv uint8_t buf[79]; @@ -115,10 +114,7 @@ private: }; /**@}*/ - void HID_Command(uint8_t *data, uint8_t nbytes) { - pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); - }; - +private: void enable_sixaxis() { // Command used to make the PS4 controller send out the entire output report uint8_t buf[2]; buf[0] = 0x43; // HID BT Get_report (0x40) | Report Type (Feature 0x03) @@ -127,6 +123,10 @@ private: HID_Command(buf, 2); }; + void HID_Command(uint8_t *data, uint8_t nbytes) { + pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); + }; + void (*pFuncOnInit)(void); // Pointer to function called in onInit() }; #endif \ No newline at end of file diff --git a/PS4Parser.h b/PS4Parser.h index 680edc83..acde9a65 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -215,7 +215,7 @@ public: * @return Return the angle in the range of 0-360. */ double getAngle(AngleEnum a) { - if(a == Pitch) + if (a == Pitch) return (atan2(ps4Data.accY, ps4Data.accZ) + PI) * RAD_TO_DEG; else return (atan2(ps4Data.accX, ps4Data.accZ) + PI) * RAD_TO_DEG; @@ -349,7 +349,11 @@ protected: ps4Output.reportChanged = false; }; - virtual void sendOutputReport(PS4Output *output) = 0; // This is overridden in PS4BT and PS4USB + /** + * Send the output to the PS4 controller. This is implemented in PS4BT.h and PS4USB.h. + * @param output Pointer to PS4Output buffer; + */ + virtual void sendOutputReport(PS4Output *output) = 0; private: bool checkDpad(ButtonEnum b); // Used to check PS4 DPAD buttons diff --git a/PS4USB.h b/PS4USB.h index d377b60d..019ea930 100644 --- a/PS4USB.h +++ b/PS4USB.h @@ -86,7 +86,6 @@ protected: }; /**@}*/ -private: /** @name PS4Parser implementation */ virtual void sendOutputReport(PS4Output *output) { // Source: https://github.com/chrippa/ds4drv uint8_t buf[32]; @@ -113,6 +112,7 @@ private: }; /**@}*/ +private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() }; #endif \ No newline at end of file From fcd6eb508475a9a614aa5c445bb0e35fd6fc3e71 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 17 Feb 2014 01:25:29 +0100 Subject: [PATCH 093/145] Improved the way PS4 buttons are read --- PS4Parser.cpp | 59 +++++++++++++++++++-------------------------------- PS4Parser.h | 12 +++++------ 2 files changed, 27 insertions(+), 44 deletions(-) diff --git a/PS4Parser.cpp b/PS4Parser.cpp index d8157f43..ca992866 100644 --- a/PS4Parser.cpp +++ b/PS4Parser.cpp @@ -38,26 +38,14 @@ bool PS4Parser::checkDpad(ButtonEnum b) { bool PS4Parser::getButtonPress(ButtonEnum b) { if (b <= LEFT) // Dpad return checkDpad(b); - else { - uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); - uint8_t index = button < 8 ? 0 : button < 16 ? 1 : 2; - uint8_t mask = 1 << (button - 8 * index); - return ps4Data.btn.val[index] & mask; - } + else + return ps4Data.btn.val & (1UL << pgm_read_byte(&PS4_BUTTONS[(uint8_t)b])); } bool PS4Parser::getButtonClick(ButtonEnum b) { - uint8_t mask, index = 0; - if (b <= LEFT) // Dpad - mask = 1 << b; - else { - uint8_t button = pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); - index = button < 8 ? 0 : button < 16 ? 1 : 2; - mask = 1 << (button - 8 * index); - } - - bool click = buttonClickState.val[index] & mask; - buttonClickState.val[index] &= ~mask; // Clear "click" event + uint32_t mask = 1UL << pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]); + bool click = buttonClickState.val & mask; + buttonClickState.val &= ~mask; // Clear "click" event return click; } @@ -83,7 +71,6 @@ void PS4Parser::Parse(uint8_t len, uint8_t *buf) { } #endif - if (buf[0] == 0x01) // Check report ID memcpy(&ps4Data, buf + 1, min(len - 1, sizeof(ps4Data))); else if (buf[0] == 0x11) // This report is send via Bluetooth, it has an offset of 2 compared to the USB data @@ -96,25 +83,23 @@ void PS4Parser::Parse(uint8_t len, uint8_t *buf) { return; } - for (uint8_t i = 0; i < sizeof(ps4Data.btn); i++) { - if (ps4Data.btn.val[i] != oldButtonState.val[i]) { // Check if anything has changed - buttonClickState.val[i] = ps4Data.btn.val[i] & ~oldButtonState.val[i]; // Update click state variable - oldButtonState.val[i] = ps4Data.btn.val[i]; - if (i == 0) { // 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 - uint8_t newDpad = 0; - if (checkDpad(UP)) - newDpad |= 1 << UP; - if (checkDpad(RIGHT)) - newDpad |= 1 << RIGHT; - if (checkDpad(DOWN)) - newDpad |= 1 << DOWN; - if (checkDpad(LEFT)) - newDpad |= 1 << LEFT; - if (newDpad != oldDpad) { - buttonClickState.dpad = newDpad & ~oldDpad; // Override values - oldDpad = newDpad; - } - } + if (ps4Data.btn.val != oldButtonState.val) { // Check if anything has changed + buttonClickState.val = ps4Data.btn.val & ~oldButtonState.val; // Update click state variable + oldButtonState.val = ps4Data.btn.val; + + // 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 + uint8_t newDpad = 0; + if (checkDpad(UP)) + newDpad |= 1 << UP; + if (checkDpad(RIGHT)) + newDpad |= 1 << RIGHT; + if (checkDpad(DOWN)) + newDpad |= 1 << DOWN; + if (checkDpad(LEFT)) + newDpad |= 1 << LEFT; + if (newDpad != oldDpad) { + buttonClickState.dpad = newDpad & ~oldDpad; // Override values + oldDpad = newDpad; } } } diff --git a/PS4Parser.h b/PS4Parser.h index acde9a65..2d8541be 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -68,8 +68,8 @@ union PS4Buttons { uint8_t touchpad : 1; uint8_t reportCounter : 6; } __attribute__((packed)); - uint8_t val[3]; -}; + uint32_t val : 24; +} __attribute__((packed)); struct touchpadXY { uint8_t dummy; // I can not figure out what this data is for, it seems to change randomly, maybe a timestamp? @@ -326,11 +326,9 @@ protected: void Reset() { uint8_t i; for (i = 0; i < sizeof(ps4Data.hatValue); i++) - ps4Data.hatValue[i] = 127; - for (i = 0; i < sizeof(PS4Buttons); i++) { - ps4Data.btn.val[i] = 0; - oldButtonState.val[i] = 0; - } + ps4Data.hatValue[i] = 127; // Center value + ps4Data.btn.val = 0; + oldButtonState.val = 0; for (i = 0; i < sizeof(ps4Data.trigger); i++) ps4Data.trigger[i] = 0; for (i = 0; i < sizeof(ps4Data.xy)/sizeof(ps4Data.xy[0]); i++) { From 37d59a63b252ccf370397d5d59a8f5746ef8b5e3 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 17 Feb 2014 17:39:15 +0100 Subject: [PATCH 094/145] bigRumble and smallRumble values were swapped --- PS4BT.h | 4 ++-- PS4Parser.h | 4 ++-- PS4USB.h | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/PS4BT.h b/PS4BT.h index 85d70f48..3c0aae12 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -96,8 +96,8 @@ protected: buf[2] = 0x80; buf[4]= 0xFF; - buf[7] = output->bigRumble; // Big Rumble - buf[8] = output->smallRumble; // Small rumble + buf[7] = output->smallRumble; // Small Rumble + buf[8] = output->bigRumble; // Big rumble buf[9] = output->r; // Red buf[10] = output->g; // Green diff --git a/PS4Parser.h b/PS4Parser.h index 2d8541be..093701e9 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -262,9 +262,9 @@ public: */ void setRumbleOn(RumbleEnum mode) { if (mode == RumbleLow) - setRumbleOn(0xFF, 0x00); - else setRumbleOn(0x00, 0xFF); + else + setRumbleOn(0xFF, 0x00); }; /** diff --git a/PS4USB.h b/PS4USB.h index 019ea930..ea38455a 100644 --- a/PS4USB.h +++ b/PS4USB.h @@ -94,8 +94,8 @@ protected: buf[0] = 0x05; // Report ID buf[1]= 0xFF; - buf[4] = output->bigRumble; // Big Rumble - buf[5] = output->smallRumble; // Small rumble + buf[4] = output->smallRumble; // Small Rumble + buf[5] = output->bigRumble; // Big rumble buf[6] = output->r; // Red buf[7] = output->g; // Green From 11a93eb06a74ed299c9bb72b02b155d8990778c7 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Sat, 22 Feb 2014 12:52:57 -0500 Subject: [PATCH 095/145] Teensy++2 support with xmem2 --- UsbCore.h | 4 ++++ avrpins.h | 3 ++- settings.h | 8 +++++++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/UsbCore.h b/UsbCore.h index 9a09d804..3ba0208a 100644 --- a/UsbCore.h +++ b/UsbCore.h @@ -18,7 +18,11 @@ #ifdef BOARD_BLACK_WIDDOW typedef MAX3421e MAX3421E; // Black Widow #elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)) +#if EXT_RAM +typedef MAX3421e MAX3421E; // Teensy++ 2.0 with XMEM2 +#else typedef MAX3421e MAX3421E; // Teensy++ 1.0 and 2.0 +#endif #elif defined(BOARD_MEGA_ADK) typedef MAX3421e MAX3421E; // Arduino Mega ADK #elif defined(ARDUINO_AVR_BALANDUINO) diff --git a/avrpins.h b/avrpins.h index ca83a8a9..c7e90af6 100644 --- a/avrpins.h +++ b/avrpins.h @@ -681,7 +681,8 @@ public: #define P8 Pa1 /* 8 - PA1 */ #define P9 Pa2 /* 9 - PA2 */ #define P10 Pa3 /* 10 - PA3 */ -#define P11 Pa4 /* 11 - PA4 */ +#define P11 Pa4 /* 11 digitalWrite(4, 0); + - PA4 */ #define P12 Pa5 /* 12 - PA5 */ #define P13 Pc1 /* 13 - PC1 */ #define P14 Pc0 /* 14 - PC0 */ diff --git a/settings.h b/settings.h index 424a5bcf..c6348aa8 100644 --- a/settings.h +++ b/settings.h @@ -103,13 +103,19 @@ #define WIICAMERA #endif -#if USE_XMEM_SPI_LOCK | defined(USE_MULTIPLE_APP_API) +#if USE_XMEM_SPI_LOCK || defined(USE_MULTIPLE_APP_API) #include #else #define XMEM_ACQUIRE_SPI() (void(0)) #define XMEM_RELEASE_SPI() (void(0)) #endif +#if !defined(EXT_RAM) && defined(EXT_RAM_STACK) || defined(EXT_RAM_HEAP) +#include +#else +#define EXT_RAM 0 +#endif + #if defined(__MK20DX128__) || defined(__MK20DX256__) #define USING_SPI4TEENSY3 USE_SPI4TEENSY3 #else From 39b6c3b124f95edbd173d0cb7ef7462aa9be5dbc Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 25 Feb 2014 11:47:59 +0100 Subject: [PATCH 096/145] Added support for the Arduino Due Untested --- UsbCore.h | 2 +- avrpins.h | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++- settings.h | 9 ++++++--- usbhost.h | 36 +++++++++++++++++++++++++++++------ 4 files changed, 91 insertions(+), 11 deletions(-) diff --git a/UsbCore.h b/UsbCore.h index 9a09d804..444700a6 100644 --- a/UsbCore.h +++ b/UsbCore.h @@ -24,7 +24,7 @@ typedef MAX3421e MAX3421E; // Arduino Mega ADK #elif defined(ARDUINO_AVR_BALANDUINO) typedef MAX3421e MAX3421E; // Balanduino #else -typedef MAX3421e MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo etc.) or Teensy 2.0 and 3.0 +typedef MAX3421e MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.) or Teensy 2.0 and 3.0 #endif /* Common setup data constant combinations */ diff --git a/avrpins.h b/avrpins.h index bdc99ba6..2bfcdc10 100644 --- a/avrpins.h +++ b/avrpins.h @@ -749,11 +749,13 @@ public: #endif // __AVR__ -#if defined(__arm__) && defined(CORE_TEENSY) +#if defined(__arm__) // pointers are 32 bits on ARM #define pgm_read_pointer(p) pgm_read_dword(p) +#if defined(CORE_TEENSY) && (defined(__MK20DX128__) || defined(__MK20DX256__)) + #include "core_pins.h" #include "avr_emulation.h" @@ -819,6 +821,57 @@ MAKE_PIN(P33, CORE_PIN33_PORTREG, CORE_PIN33_BIT, CORE_PIN33_CONFIG); #undef MAKE_PIN +#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) + +// Disable interrupts +// Enable the pull up resistor +// Set to INPUT +// Enable PIO + +// Disable interrupts +// Disable the pull up resistor +// Set to OUTPUT +// Enable PIO + +#define MAKE_PIN(className, baseReg, pinMask) \ +class className { \ +public: \ + static void Set() { \ + baseReg->PIO_SODR = pinMask; \ + } \ + static void Clear() { \ + baseReg->PIO_CODR = pinMask; \ + } \ + static void SetDirRead() { \ + baseReg->PIO_IDR = pinMask ; \ + baseReg->PIO_PUER = pinMask; \ + baseReg->PIO_ODR = pinMask; \ + baseReg->PIO_PER = pinMask; \ + } \ + static void SetDirWrite() { \ + baseReg->PIO_IDR = pinMask ; \ + baseReg->PIO_PUDR = pinMask; \ + baseReg->PIO_OER = pinMask; \ + baseReg->PIO_PER = pinMask; \ + } \ + static uint8_t IsSet() { \ + return baseReg->PIO_PDSR & pinMask; \ + } \ +}; + +MAKE_PIN(P9, PIOC, PIO_PC21); // INT +MAKE_PIN(P10, PIOC, PIO_PC29); // SS +MAKE_PIN(P74, PIOA, PIO_PA25); // MISO +MAKE_PIN(P75, PIOA, PIO_PA26); // MOSI +MAKE_PIN(P76, PIOA, PIO_PA27); // CLK + +#undef MAKE_PIN + +#else +#error "Please define board in avrpins.h" + +#endif + #endif // __arm__ #endif //_avrpins_h_ diff --git a/settings.h b/settings.h index 424a5bcf..c6d78ad4 100644 --- a/settings.h +++ b/settings.h @@ -68,7 +68,6 @@ // No user serviceable parts below this line. // DO NOT change anything below here unless you are a developer! -// When will we drop support for the older bug-ridden stuff? #if defined(ARDUINO) && ARDUINO >=100 #include #else @@ -79,7 +78,7 @@ #define F(str) (str) #endif -#ifdef __GNUC__ +#if defined(__GNUC__) && defined(__AVR__) #ifndef GCC_VERSION #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif @@ -110,10 +109,14 @@ #define XMEM_RELEASE_SPI() (void(0)) #endif -#if defined(__MK20DX128__) || defined(__MK20DX256__) +#if defined(CORE_TEENSY) && (defined(__MK20DX128__) || defined(__MK20DX256__)) #define USING_SPI4TEENSY3 USE_SPI4TEENSY3 #else #define USING_SPI4TEENSY3 0 #endif +#if defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) +#include // Use the Arduino SPI library for the Arduino Due +#endif + #endif /* SETTINGS_H */ diff --git a/usbhost.h b/usbhost.h index adfff592..e5cd4188 100644 --- a/usbhost.h +++ b/usbhost.h @@ -29,9 +29,8 @@ e-mail : support@circuitsathome.com /* SPI initialization */ template< typename SPI_CLK, typename SPI_MOSI, typename SPI_MISO, typename SPI_SS > class SPi { -#if USING_SPI4TEENSY3 public: - +#if USING_SPI4TEENSY3 static void init() { // spi4teensy3 inits everything for us, except /SS // CLK, MOSI and MISO are hard coded for now. @@ -40,10 +39,13 @@ public: SPI_SS::SetDirWrite(); SPI_SS::Set(); } - +#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) + static void init() { + SPI_SS::SetDirWrite(); + SPI_SS::Set(); + SPI.begin(); + } #else -public: - static void init() { //uint8_t tmp; SPI_CLK::SetDirWrite(); @@ -67,8 +69,10 @@ typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi; typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi; #elif defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) typedef SPi< Pb7, Pb5, Pb6, Pb4 > spi; -#elif defined(__MK20DX128__) || defined(__MK20DX256__) +#elif defined(CORE_TEENSY) && (defined(__MK20DX128__) || defined(__MK20DX256__)) typedef SPi< P13, P11, P12, P10 > spi; +#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) +typedef SPi< P76, P75, P74, P10 > spi; #else #error "No SPI entry in usbhost.h" #endif @@ -130,6 +134,9 @@ void MAX3421e< SPI_SS, INTR >::regWr(uint8_t reg, uint8_t data) { c[0] = reg | 0x02; c[1] = data; spi4teensy3::send(c, 2); +#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) + SPI.transfer(reg | 0x02); + SPI.transfer(data); #else SPDR = (reg | 0x02); while(!(SPSR & (1 << SPIF))); @@ -151,6 +158,13 @@ uint8_t* MAX3421e< SPI_SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* spi4teensy3::send(reg | 0x02); spi4teensy3::send(data_p, nbytes); data_p += nbytes; +#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) + SPI.transfer(reg | 0x02); + while(nbytes) { + SPI.transfer(*data_p); + nbytes--; + data_p++; // advance data pointer + } #else SPDR = (reg | 0x02); //set WR bit and send register number while(nbytes) { @@ -186,6 +200,10 @@ uint8_t MAX3421e< SPI_SS, INTR >::regRd(uint8_t reg) { spi4teensy3::send(reg); uint8_t rv = spi4teensy3::receive(); SPI_SS::Set(); +#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) + SPI.transfer(reg); + uint8_t rv = SPI.transfer(0); + SPI_SS::Set(); #else SPDR = reg; while(!(SPSR & (1 << SPIF))); @@ -208,6 +226,12 @@ uint8_t* MAX3421e< SPI_SS, INTR >::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t* spi4teensy3::send(reg); spi4teensy3::receive(data_p, nbytes); data_p += nbytes; +#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) + SPI.transfer(reg); + while(nbytes) { + *data_p++ = SPI.transfer(0); + nbytes--; + } #else SPDR = reg; while(!(SPSR & (1 << SPIF))); //wait From a24ecb57977e8aad850b7aed635c65b8e9397fc1 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 25 Feb 2014 19:32:49 +0100 Subject: [PATCH 097/145] Updated readme and some comments --- README.md | 5 +++-- avrpins.h | 18 ++++++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 56152496..80715680 100644 --- a/README.md +++ b/README.md @@ -66,8 +66,9 @@ By default serial debugging is disabled. To turn it on simply change ```ENABLE_U Currently the following boards are supported by the library: * All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.) -* Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, and Teensy 3.0) - * Note if you are using the Teensy 3.0 you should download this SPI library as well: . You should then add ```#include ``` to your .ino file. +* Arduino Due +* Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, and Teensy 3.x) + * Note if you are using the Teensy 3.x you should download this SPI library as well: . You should then add ```#include ``` to your .ino file. * Balanduino * Sanguino * Black Widdow diff --git a/avrpins.h b/avrpins.h index 2bfcdc10..e75042b2 100644 --- a/avrpins.h +++ b/avrpins.h @@ -823,15 +823,17 @@ MAKE_PIN(P33, CORE_PIN33_PORTREG, CORE_PIN33_BIT, CORE_PIN33_CONFIG); #elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__) -// Disable interrupts -// Enable the pull up resistor -// Set to INPUT -// Enable PIO +// SetDirRead: +// Disable interrupts +// Enable the pull up resistor +// Set to INPUT +// Enable PIO -// Disable interrupts -// Disable the pull up resistor -// Set to OUTPUT -// Enable PIO +// SetDirWrite: +// Disable interrupts +// Disable the pull up resistor +// Set to OUTPUT +// Enable PIO #define MAKE_PIN(className, baseReg, pinMask) \ class className { \ From 983a7d664fc5b89732e2dcfe75680684d1706270 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 25 Feb 2014 19:37:57 +0100 Subject: [PATCH 098/145] Added getLastMessageTime() - this is useful if you want to detect if the connection is lost with the PS3 controller Credit: Thomas Frederick --- PS3BT.cpp | 2 ++ PS3BT.h | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/PS3BT.cpp b/PS3BT.cpp index ba531c26..80b6dc3f 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -343,6 +343,8 @@ void PS3BT::ACLData(uint8_t* ACLData) { if(PS3Connected || PS3MoveConnected || PS3NavigationConnected) { /* Read Report */ if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT + lastMessageTime = millis(); // Store the last message time + if(PS3Connected || PS3NavigationConnected) ButtonState = (uint32_t)(l2capinbuf[11] | ((uint16_t)l2capinbuf[12] << 8) | ((uint32_t)l2capinbuf[13] << 16)); else if(PS3MoveConnected) diff --git a/PS3BT.h b/PS3BT.h index 7291c092..d07a4577 100644 --- a/PS3BT.h +++ b/PS3BT.h @@ -179,6 +179,11 @@ public: */ void moveSetRumble(uint8_t rumble); + /** Used to get the millis() of the last message */ + uint32_t getLastMessageTime() { + return lastMessageTime; + }; + /** * Used to call your own function when the controller is successfully initialized. * @param funcOnInit Function to call. @@ -214,10 +219,12 @@ private: uint8_t remote_name[30]; // First 30 chars of remote name bool activeConnection; // Used to indicate if it's already has established a connection - /* variables used by high level L2CAP task */ + /* Variables used by high level L2CAP task */ uint8_t l2cap_state; uint32_t l2cap_event_flag; // L2CAP flags of received Bluetooth events + uint32_t lastMessageTime; // Variable used to store the millis value of the last message. + unsigned long timer; uint32_t ButtonState; From ce81146f2b58fded9e08371fc2b3cbbcd8c57c5f Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 26 Feb 2014 23:43:40 +0100 Subject: [PATCH 099/145] Disable pull up resistor when using input on the Due --- avrpins.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/avrpins.h b/avrpins.h index e75042b2..d013851a 100644 --- a/avrpins.h +++ b/avrpins.h @@ -825,7 +825,7 @@ MAKE_PIN(P33, CORE_PIN33_PORTREG, CORE_PIN33_BIT, CORE_PIN33_CONFIG); // SetDirRead: // Disable interrupts -// Enable the pull up resistor +// Disable the pull up resistor // Set to INPUT // Enable PIO @@ -846,7 +846,7 @@ public: \ } \ static void SetDirRead() { \ baseReg->PIO_IDR = pinMask ; \ - baseReg->PIO_PUER = pinMask; \ + baseReg->PIO_PUDR = pinMask; \ baseReg->PIO_ODR = pinMask; \ baseReg->PIO_PER = pinMask; \ } \ From f8379baffea82490374c44cea7c8363704f28a5b Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 26 Feb 2014 23:46:21 +0100 Subject: [PATCH 100/145] Changed variable name from baseReg to pio --- avrpins.h | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/avrpins.h b/avrpins.h index d013851a..6e074b65 100644 --- a/avrpins.h +++ b/avrpins.h @@ -835,29 +835,29 @@ MAKE_PIN(P33, CORE_PIN33_PORTREG, CORE_PIN33_BIT, CORE_PIN33_CONFIG); // Set to OUTPUT // Enable PIO -#define MAKE_PIN(className, baseReg, pinMask) \ +#define MAKE_PIN(className, pio, pinMask) \ class className { \ public: \ static void Set() { \ - baseReg->PIO_SODR = pinMask; \ + pio->PIO_SODR = pinMask; \ } \ static void Clear() { \ - baseReg->PIO_CODR = pinMask; \ + pio->PIO_CODR = pinMask; \ } \ static void SetDirRead() { \ - baseReg->PIO_IDR = pinMask ; \ - baseReg->PIO_PUDR = pinMask; \ - baseReg->PIO_ODR = pinMask; \ - baseReg->PIO_PER = pinMask; \ + pio->PIO_IDR = pinMask ; \ + pio->PIO_PUDR = pinMask; \ + pio->PIO_ODR = pinMask; \ + pio->PIO_PER = pinMask; \ } \ static void SetDirWrite() { \ - baseReg->PIO_IDR = pinMask ; \ - baseReg->PIO_PUDR = pinMask; \ - baseReg->PIO_OER = pinMask; \ - baseReg->PIO_PER = pinMask; \ + pio->PIO_IDR = pinMask ; \ + pio->PIO_PUDR = pinMask; \ + pio->PIO_OER = pinMask; \ + pio->PIO_PER = pinMask; \ } \ static uint8_t IsSet() { \ - return baseReg->PIO_PDSR & pinMask; \ + return pio->PIO_PDSR & pinMask; \ } \ }; From d95bee640e3af3b99a36306c4616fe25d4bf848a Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 27 Feb 2014 03:10:46 -0500 Subject: [PATCH 101/145] Allow other lock implementations. --- settings.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/settings.h b/settings.h index c6348aa8..238ae905 100644 --- a/settings.h +++ b/settings.h @@ -103,12 +103,18 @@ #define WIICAMERA #endif +// To use some other locking (e.g. freertos), +// define XMEM_ACQUIRE_SPI and XMEM_RELEASE_SPI to point to your lock and unlock. +// NOTE: NO argument is passed. You have to do this within your routine for +// whatever you are using to lock and unlock. +#if !defined(XMEM_ACQUIRE_SPI) #if USE_XMEM_SPI_LOCK || defined(USE_MULTIPLE_APP_API) #include #else #define XMEM_ACQUIRE_SPI() (void(0)) #define XMEM_RELEASE_SPI() (void(0)) #endif +#endif #if !defined(EXT_RAM) && defined(EXT_RAM_STACK) || defined(EXT_RAM_HEAP) #include From d8cadc5744e4483ce2161f8fd0c163483e12a997 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 2 Mar 2014 16:35:16 +0100 Subject: [PATCH 102/145] Increase SPI speed on the Due to 21MHz --- usbhost.h | 1 + 1 file changed, 1 insertion(+) diff --git a/usbhost.h b/usbhost.h index e5cd4188..172742e5 100644 --- a/usbhost.h +++ b/usbhost.h @@ -44,6 +44,7 @@ public: SPI_SS::SetDirWrite(); SPI_SS::Set(); SPI.begin(); + SPI.setClockDivider(BOARD_SPI_DEFAULT_SS, 4); // Set speed to 84MHz/4=21MHz - the MAX3421E can handle up to 26MHz } #else static void init() { From 76b1c3fb323c5ccbf00199fa8e71aa84e3a6da15 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 3 Mar 2014 02:59:09 +0100 Subject: [PATCH 103/145] Added some syntax highlighting in the readme --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 80715680..b964c548 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Documentation for the library can be found at the following link: Date: Mon, 3 Mar 2014 19:46:08 -0500 Subject: [PATCH 104/145] Fix accidental comment paste. --- avrpins.h | 3 +-- examples/testusbhostFAT/testusbhostFAT.ino | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/avrpins.h b/avrpins.h index c7e90af6..ca83a8a9 100644 --- a/avrpins.h +++ b/avrpins.h @@ -681,8 +681,7 @@ public: #define P8 Pa1 /* 8 - PA1 */ #define P9 Pa2 /* 9 - PA2 */ #define P10 Pa3 /* 10 - PA3 */ -#define P11 Pa4 /* 11 digitalWrite(4, 0); - - PA4 */ +#define P11 Pa4 /* 11 - PA4 */ #define P12 Pa5 /* 12 - PA5 */ #define P13 Pc1 /* 13 - PC1 */ #define P14 Pc0 /* 14 - PC0 */ diff --git a/examples/testusbhostFAT/testusbhostFAT.ino b/examples/testusbhostFAT/testusbhostFAT.ino index 49713d36..f316a49b 100644 --- a/examples/testusbhostFAT/testusbhostFAT.ino +++ b/examples/testusbhostFAT/testusbhostFAT.ino @@ -503,7 +503,7 @@ void loop() { if (isfat(parts[cpart].type)) { Fats[cpart] = new PFAT(&sto[i], cpart, parts[cpart].firstSector); //int r = Fats[cpart]->Good(); - if (Fats[cpart]->Good()) { + if (Fats[cpart]->MountStatus()) { delete Fats[cpart]; Fats[cpart] = NULL; } else cpart++; @@ -514,7 +514,7 @@ void loop() { // try superblock Fats[cpart] = new PFAT(&sto[i], cpart, 0); //int r = Fats[cpart]->Good(); - if (Fats[cpart]->Good()) { + if (Fats[cpart]->MountStatus()) { //printf_P(PSTR("Superblock error %x\r\n"), r); delete Fats[cpart]; Fats[cpart] = NULL; From 4f978efe231b9a710b702b20ed2b8628406513a1 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 6 Mar 2014 19:25:35 +0100 Subject: [PATCH 105/145] Added information about the need to include the Arduino SPI library when using the Due --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b964c548..85ef87c7 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ By default serial debugging is disabled. To turn it on simply change ```ENABLE_U Currently the following boards are supported by the library: * All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.) + * If you are using the Arduino Due, then you must include the Arduino SPI library as well like so: ```#include ``` to your .ino file. * Arduino Due * Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, and Teensy 3.x) * Note if you are using the Teensy 3.x you should download this SPI library as well: . You should then add ```#include ``` to your .ino file. From a0661ef244d5d5fae8946236ba806de370a7aeb1 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 6 Mar 2014 19:32:17 +0100 Subject: [PATCH 106/145] Typo correction --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 85ef87c7..647a69a9 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ By default serial debugging is disabled. To turn it on simply change ```ENABLE_U Currently the following boards are supported by the library: * All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.) - * If you are using the Arduino Due, then you must include the Arduino SPI library as well like so: ```#include ``` to your .ino file. + * If you are using the Arduino Due, then you must include the Arduino SPI library like so: ```#include ``` in your .ino file. * Arduino Due * Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, and Teensy 3.x) * Note if you are using the Teensy 3.x you should download this SPI library as well: . You should then add ```#include ``` to your .ino file. From bb9fef05dbebc6200243ee471ca1c1f2e124d7c1 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 6 Mar 2014 21:48:48 +0100 Subject: [PATCH 107/145] Typo once again --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 647a69a9..883c661e 100644 --- a/README.md +++ b/README.md @@ -66,8 +66,8 @@ By default serial debugging is disabled. To turn it on simply change ```ENABLE_U Currently the following boards are supported by the library: * All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.) - * If you are using the Arduino Due, then you must include the Arduino SPI library like so: ```#include ``` in your .ino file. * Arduino Due + * If you are using the Arduino Due, then you must include the Arduino SPI library like so: ```#include ``` in your .ino file. * Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, and Teensy 3.x) * Note if you are using the Teensy 3.x you should download this SPI library as well: . You should then add ```#include ``` to your .ino file. * Balanduino From a042e5a8497f1457b39e38113b8b6a84aa643bb0 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 7 Mar 2014 02:12:39 +0100 Subject: [PATCH 108/145] Simplify how PS3 printStatusString prints the string --- PS3BT.cpp | 2 +- PS3USB.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/PS3BT.cpp b/PS3BT.cpp index 80b6dc3f..38d6c3dc 100644 --- a/PS3BT.cpp +++ b/PS3BT.cpp @@ -201,7 +201,7 @@ void PS3BT::printStatusString() { } else strcpy_P(statusOutput, PSTR("Error")); - USB_HOST_SERIAL.write((uint8_t*)statusOutput, strlen(statusOutput)); + USB_HOST_SERIAL.write(statusOutput); } void PS3BT::Reset() { diff --git a/PS3USB.cpp b/PS3USB.cpp index fa865495..7e6285a2 100644 --- a/PS3USB.cpp +++ b/PS3USB.cpp @@ -392,7 +392,7 @@ void PS3USB::printStatusString() { } else strcpy_P(statusOutput, PSTR("Error")); - USB_HOST_SERIAL.write((uint8_t*)statusOutput, strlen(statusOutput)); + USB_HOST_SERIAL.write(statusOutput); } /* Playstation Sixaxis Dualshock and Navigation Controller commands */ From 1ebce9b87752331a61971602b08048e569cdaa41 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 7 Mar 2014 02:17:47 +0100 Subject: [PATCH 109/145] Some files were missing copyright section --- UsbCore.h | 20 +++++++++++++++----- hid.cpp | 17 +++++++++++++++++ hidescriptorparser.cpp | 17 +++++++++++++++++ hiduniversal.cpp | 17 +++++++++++++++++ hiduniversal.h | 17 +++++++++++++++++ macros.h | 20 +++++++++++++++----- masstorage.cpp | 17 +++++++++++++++++ masstorage.h | 17 +++++++++++++++++ 8 files changed, 132 insertions(+), 10 deletions(-) diff --git a/UsbCore.h b/UsbCore.h index 6e6822d3..76d9d5ee 100644 --- a/UsbCore.h +++ b/UsbCore.h @@ -1,8 +1,18 @@ -/* - * File: UsbCore.h - * Author: xxxajk - * - * Created on September 29, 2013, 9:25 PM +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com */ #if !defined(_usb_h_) || defined(USBCORE_H) diff --git a/hid.cpp b/hid.cpp index c86f6b91..c3c425b8 100644 --- a/hid.cpp +++ b/hid.cpp @@ -1,3 +1,20 @@ +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com + */ + #include "hid.h" //get HID report descriptor diff --git a/hidescriptorparser.cpp b/hidescriptorparser.cpp index fd9d2d2d..f3040ce8 100644 --- a/hidescriptorparser.cpp +++ b/hidescriptorparser.cpp @@ -1,3 +1,20 @@ +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com + */ + #include "hidescriptorparser.h" const char * const ReportDescParserBase::usagePageTitles0[] PROGMEM = { diff --git a/hiduniversal.cpp b/hiduniversal.cpp index a2b4dc2e..c2f33533 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -1,3 +1,20 @@ +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com + */ + #include "hiduniversal.h" HIDUniversal::HIDUniversal(USB *p) : diff --git a/hiduniversal.h b/hiduniversal.h index d97f4b8c..3e090aa7 100644 --- a/hiduniversal.h +++ b/hiduniversal.h @@ -1,3 +1,20 @@ +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com + */ + #if !defined(__HIDUNIVERSAL_H__) #define __HIDUNIVERSAL_H__ diff --git a/macros.h b/macros.h index 1f56814a..51476830 100644 --- a/macros.h +++ b/macros.h @@ -1,8 +1,18 @@ -/* - * File: macros.h - * Author: AJK - * - * Created on September 23, 2013, 12:31 AM +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com */ #if !defined(_usb_h_) || defined(MACROS_H) diff --git a/masstorage.cpp b/masstorage.cpp index 19da7b19..41ee4258 100644 --- a/masstorage.cpp +++ b/masstorage.cpp @@ -1,3 +1,20 @@ +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com + */ + #include "masstorage.h" const uint8_t BulkOnly::epDataInIndex = 1; diff --git a/masstorage.h b/masstorage.h index eb042eac..176752fc 100644 --- a/masstorage.h +++ b/masstorage.h @@ -1,3 +1,20 @@ +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com + */ + #if !defined(__MASSTORAGE_H__) #define __MASSTORAGE_H__ From 62f8cbbc2506d30110d9b9afabe993c45421bbfa Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Fri, 7 Mar 2014 02:19:34 +0100 Subject: [PATCH 110/145] Do not set SS pin for the Due Let the Arduino SPI library take care of that --- usbhost.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usbhost.h b/usbhost.h index 172742e5..cf26c1f0 100644 --- a/usbhost.h +++ b/usbhost.h @@ -44,7 +44,7 @@ public: SPI_SS::SetDirWrite(); SPI_SS::Set(); SPI.begin(); - SPI.setClockDivider(BOARD_SPI_DEFAULT_SS, 4); // Set speed to 84MHz/4=21MHz - the MAX3421E can handle up to 26MHz + SPI.setClockDivider(4); // Set speed to 84MHz/4=21MHz - the MAX3421E can handle up to 26MHz } #else static void init() { From 2b31f96bcd278711846d33006edab7ec83639ea5 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 17 Mar 2014 15:48:37 +0100 Subject: [PATCH 111/145] Making it clearer how to get the PS4 controller into paring mode --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 883c661e..5d84471a 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) and [PS4USB.ino](examples/PS Before you can use the PS4 controller via Bluetooth you will need to pair with it. -Simply create the PS4BT instance like so: ```PS4BT PS4(&Btd, PAIR);``` and then hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode. +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 paring mode. It should then automatically pair the dongle with your controller. This only have to be done once. From 00ae0d138f5f276af912745d4e3b7e8425b01a4b Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 18 Mar 2014 18:29:47 +0100 Subject: [PATCH 112/145] Updated submodules --- examples/testusbhostFAT/RTClib | 2 +- examples/testusbhostFAT/generic_storage | 2 +- examples/testusbhostFAT/xmem2 | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index a4bd6f50..9108effe 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit a4bd6f500f70599847de60973371ee973d094a34 +Subproject commit 9108effe4d4e556198e3e7b95365d1c898680dae diff --git a/examples/testusbhostFAT/generic_storage b/examples/testusbhostFAT/generic_storage index 1d481775..ab85718a 160000 --- a/examples/testusbhostFAT/generic_storage +++ b/examples/testusbhostFAT/generic_storage @@ -1 +1 @@ -Subproject commit 1d481775b5096a172edf607062278a86e9618a15 +Subproject commit ab85718a917094391762b79140d8e3a03af136a4 diff --git a/examples/testusbhostFAT/xmem2 b/examples/testusbhostFAT/xmem2 index 029e3dab..dd85091a 160000 --- a/examples/testusbhostFAT/xmem2 +++ b/examples/testusbhostFAT/xmem2 @@ -1 +1 @@ -Subproject commit 029e3dab4c885669cddaa59f3dc8fdc71d152792 +Subproject commit dd85091abaca7cc6055ff515a5e42f32198380d2 From af2e8d5184d06047fa47a05ec1d56175a04c2576 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 18 Mar 2014 18:37:02 +0100 Subject: [PATCH 113/145] Removed files used for Netbeans project --- examples/HID/USBHIDBootKbdAndMouse/Makefile | 30 -------- .../nbproject/Package-Default.bash | 75 ------------------- .../nbproject/configurations.xml | 38 ---------- .../nbproject/project.xml | 23 ------ examples/HID/USBHIDJoystick/Makefile | 30 -------- .../nbproject/Package-Default.bash | 75 ------------------- .../nbproject/configurations.xml | 55 -------------- .../HID/USBHIDJoystick/nbproject/project.xml | 23 ------ examples/testusbhostFAT/avr-gdb.conf | 6 -- 9 files changed, 355 deletions(-) delete mode 100644 examples/HID/USBHIDBootKbdAndMouse/Makefile delete mode 100644 examples/HID/USBHIDBootKbdAndMouse/nbproject/Package-Default.bash delete mode 100644 examples/HID/USBHIDBootKbdAndMouse/nbproject/configurations.xml delete mode 100644 examples/HID/USBHIDBootKbdAndMouse/nbproject/project.xml delete mode 100644 examples/HID/USBHIDJoystick/Makefile delete mode 100644 examples/HID/USBHIDJoystick/nbproject/Package-Default.bash delete mode 100644 examples/HID/USBHIDJoystick/nbproject/configurations.xml delete mode 100644 examples/HID/USBHIDJoystick/nbproject/project.xml delete mode 100644 examples/testusbhostFAT/avr-gdb.conf diff --git a/examples/HID/USBHIDBootKbdAndMouse/Makefile b/examples/HID/USBHIDBootKbdAndMouse/Makefile deleted file mode 100644 index 253ecfb5..00000000 --- a/examples/HID/USBHIDBootKbdAndMouse/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -# -# These are set for a mega 1280 + quadram plus my serial patch. -# If you lack quadram, or want to disable LFN, just change _FS_TINY=1 _USE_LFN=0 -# -# If your board is a mega 2560 uncomment the following two lines -# BOARD = mega2560 -# PROGRAMMER = wiring -# ...and then comment out the following two lines -BOARD = mega -PROGRAMMER = arduino - -# set your Arduino tty port here -PORT = /dev/ttyUSB0 - - -# uncomment the next line to enable debugging -#EXTRA_FLAGS += -D DEBUG_USB_HOST=1 - -# -# Advanced debug on Serial3 -# - -# uncomment the next line to enable debug on Serial3 -#EXTRA_FLAGS += -D USB_HOST_SERIAL=Serial3 - -# The following are the libraries used. -LIB_DIRS = -LIB_DIRS += ../libraries/USB_Host_Shield_2_0 -# And finally, the part that brings everything together for you. -include ../Arduino_Makefile_master/_Makefile.master diff --git a/examples/HID/USBHIDBootKbdAndMouse/nbproject/Package-Default.bash b/examples/HID/USBHIDBootKbdAndMouse/nbproject/Package-Default.bash deleted file mode 100644 index 808a7e12..00000000 --- a/examples/HID/USBHIDBootKbdAndMouse/nbproject/Package-Default.bash +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -x - -# -# Generated - do not edit! -# - -# Macros -TOP=`pwd` -CND_PLATFORM=AVR-Linux-x86 -CND_CONF=Default -CND_DISTDIR=dist -CND_BUILDDIR=build -NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging -TMPDIRNAME=tmp-packaging -OUTPUT_PATH=MissingOutputInProject -OUTPUT_BASENAME=MissingOutputInProject -PACKAGE_TOP_DIR=USBHIDBootKbdAndMouse/ - -# Functions -function checkReturnCode -{ - rc=$? - if [ $rc != 0 ] - then - exit $rc - fi -} -function makeDirectory -# $1 directory path -# $2 permission (optional) -{ - mkdir -p "$1" - checkReturnCode - if [ "$2" != "" ] - then - chmod $2 "$1" - checkReturnCode - fi -} -function copyFileToTmpDir -# $1 from-file path -# $2 to-file path -# $3 permission -{ - cp "$1" "$2" - checkReturnCode - if [ "$3" != "" ] - then - chmod $3 "$2" - checkReturnCode - fi -} - -# Setup -cd "${TOP}" -mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package -rm -rf ${NBTMPDIR} -mkdir -p ${NBTMPDIR} - -# Copy files and create directories and links -cd "${TOP}" -makeDirectory "${NBTMPDIR}/USBHIDBootKbdAndMouse" -copyFileToTmpDir "${OUTPUT_PATH}" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755 - - -# Generate tar file -cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/USBHIDBootKbdAndMouse.tar -cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/USBHIDBootKbdAndMouse.tar * -checkReturnCode - -# Cleanup -cd "${TOP}" -rm -rf ${NBTMPDIR} diff --git a/examples/HID/USBHIDBootKbdAndMouse/nbproject/configurations.xml b/examples/HID/USBHIDBootKbdAndMouse/nbproject/configurations.xml deleted file mode 100644 index e19c68a4..00000000 --- a/examples/HID/USBHIDBootKbdAndMouse/nbproject/configurations.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - USBHIDBootKbdAndMouse_ino.cpp - - USBHIDBootKbdAndMouse.ino - - - Makefile - - - ^(nbproject)$ - - . - - Makefile - - - - LOCAL_SOURCES - default - - - - . - ${MAKE} -f Makefile - ${MAKE} -f Makefile clean - - - - - - diff --git a/examples/HID/USBHIDBootKbdAndMouse/nbproject/project.xml b/examples/HID/USBHIDBootKbdAndMouse/nbproject/project.xml deleted file mode 100644 index c831722a..00000000 --- a/examples/HID/USBHIDBootKbdAndMouse/nbproject/project.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - org.netbeans.modules.cnd.makeproject - - - USBHIDBootKbdAndMouse - - cpp,ino - - UTF-8 - - - . - - - - Default - 0 - - - - - diff --git a/examples/HID/USBHIDJoystick/Makefile b/examples/HID/USBHIDJoystick/Makefile deleted file mode 100644 index 253ecfb5..00000000 --- a/examples/HID/USBHIDJoystick/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -# -# These are set for a mega 1280 + quadram plus my serial patch. -# If you lack quadram, or want to disable LFN, just change _FS_TINY=1 _USE_LFN=0 -# -# If your board is a mega 2560 uncomment the following two lines -# BOARD = mega2560 -# PROGRAMMER = wiring -# ...and then comment out the following two lines -BOARD = mega -PROGRAMMER = arduino - -# set your Arduino tty port here -PORT = /dev/ttyUSB0 - - -# uncomment the next line to enable debugging -#EXTRA_FLAGS += -D DEBUG_USB_HOST=1 - -# -# Advanced debug on Serial3 -# - -# uncomment the next line to enable debug on Serial3 -#EXTRA_FLAGS += -D USB_HOST_SERIAL=Serial3 - -# The following are the libraries used. -LIB_DIRS = -LIB_DIRS += ../libraries/USB_Host_Shield_2_0 -# And finally, the part that brings everything together for you. -include ../Arduino_Makefile_master/_Makefile.master diff --git a/examples/HID/USBHIDJoystick/nbproject/Package-Default.bash b/examples/HID/USBHIDJoystick/nbproject/Package-Default.bash deleted file mode 100644 index 45e0f31e..00000000 --- a/examples/HID/USBHIDJoystick/nbproject/Package-Default.bash +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -x - -# -# Generated - do not edit! -# - -# Macros -TOP=`pwd` -CND_PLATFORM=AVR-Linux-x86 -CND_CONF=Default -CND_DISTDIR=dist -CND_BUILDDIR=build -NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging -TMPDIRNAME=tmp-packaging -OUTPUT_PATH=MissingOutputInProject -OUTPUT_BASENAME=MissingOutputInProject -PACKAGE_TOP_DIR=USBHIDJoystick/ - -# Functions -function checkReturnCode -{ - rc=$? - if [ $rc != 0 ] - then - exit $rc - fi -} -function makeDirectory -# $1 directory path -# $2 permission (optional) -{ - mkdir -p "$1" - checkReturnCode - if [ "$2" != "" ] - then - chmod $2 "$1" - checkReturnCode - fi -} -function copyFileToTmpDir -# $1 from-file path -# $2 to-file path -# $3 permission -{ - cp "$1" "$2" - checkReturnCode - if [ "$3" != "" ] - then - chmod $3 "$2" - checkReturnCode - fi -} - -# Setup -cd "${TOP}" -mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package -rm -rf ${NBTMPDIR} -mkdir -p ${NBTMPDIR} - -# Copy files and create directories and links -cd "${TOP}" -makeDirectory "${NBTMPDIR}/USBHIDJoystick" -copyFileToTmpDir "${OUTPUT_PATH}" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755 - - -# Generate tar file -cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/USBHIDJoystick.tar -cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/USBHIDJoystick.tar * -checkReturnCode - -# Cleanup -cd "${TOP}" -rm -rf ${NBTMPDIR} diff --git a/examples/HID/USBHIDJoystick/nbproject/configurations.xml b/examples/HID/USBHIDJoystick/nbproject/configurations.xml deleted file mode 100644 index 5bb562ca..00000000 --- a/examples/HID/USBHIDJoystick/nbproject/configurations.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - CDC.lst - HID.lst - HardwareSerial.lst - IPAddress.lst - Print.lst - Stream.lst - Tone.lst - USBCore.lst - WInterrupts.lst - WMath.lst - WString.lst - wiring.lst - wiring_analog.lst - wiring_digital.lst - wiring_pulse.lst - wiring_shift.lst - - USBHIDJoystick.ino - hidjoystickrptparser.cpp - hidjoystickrptparser.h - - - Makefile - - - ^(nbproject)$ - - . - - Makefile - - - - LOCAL_SOURCES - default - - - - . - ${MAKE} -f Makefile - ${MAKE} -f Makefile clean - - - - - - diff --git a/examples/HID/USBHIDJoystick/nbproject/project.xml b/examples/HID/USBHIDJoystick/nbproject/project.xml deleted file mode 100644 index b912fd91..00000000 --- a/examples/HID/USBHIDJoystick/nbproject/project.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - org.netbeans.modules.cnd.makeproject - - - USBHIDJoystick - - cpp,ino - h - UTF-8 - - - . - - - - Default - 0 - - - - - diff --git a/examples/testusbhostFAT/avr-gdb.conf b/examples/testusbhostFAT/avr-gdb.conf deleted file mode 100644 index 7ab686f2..00000000 --- a/examples/testusbhostFAT/avr-gdb.conf +++ /dev/null @@ -1,6 +0,0 @@ -file build/testusbhostFAT.elf -target remote localhost:4242 -set {int}0x802200 = 0xffff -set {int}0x802220 = 0x0000 -#graph display `x /3xh 0x802200` - From b3b476af331e17f94ba6203eefd00869720a7478 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 18 Mar 2014 18:37:36 +0100 Subject: [PATCH 114/145] Fixed debug message --- BTD.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BTD.cpp b/BTD.cpp index 4de668d9..f373c607 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -720,7 +720,7 @@ void BTD::HCI_task() { if(pairWithWii) Notify(PSTR("\r\nWII Wii(&Btd);"), 0x80); else - Notify(PSTR("\r\nBTHID hid(&Btd);"), 0x80); + Notify(PSTR("\r\nBTHID bthid(&Btd);"), 0x80); Notify(PSTR("\r\nAnd then press any button on the "), 0x80); if(pairWithWii) From 7569c19a763343f1f54574a64714d1c58815f73e Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 19 Mar 2014 18:06:44 +0100 Subject: [PATCH 115/145] Fixed comment The default pin was changed from 1234 to 0000 a while back --- examples/Bluetooth/SPP/SPP.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/Bluetooth/SPP/SPP.ino b/examples/Bluetooth/SPP/SPP.ino index 6a326a3d..d8276b7b 100644 --- a/examples/Bluetooth/SPP/SPP.ino +++ b/examples/Bluetooth/SPP/SPP.ino @@ -16,8 +16,8 @@ USB Usb; BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so /* You can create the instance of the class in two ways */ -SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "1234" -//SPP SerialBT(&Btd, "Lauszus's Arduino","0000"); // You can also set the name and pin like so +SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "0000" +//SPP SerialBT(&Btd, "Lauszus's Arduino", "1234"); // You can also set the name and pin like so boolean firstMessage = true; From 0be51b12e51537b83db96f71d1c43d9223d44ead Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Thu, 27 Mar 2014 02:45:49 +0100 Subject: [PATCH 116/145] Updated PS3 paring documentation --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5d84471a..43fde867 100644 --- a/README.md +++ b/README.md @@ -138,9 +138,11 @@ Also check out this excellent Wiki by Frank Zhao about the PS4 controller: . From 7e1feedbd1d23c06f09f6399f85f6e404e5e192a Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sat, 29 Mar 2014 00:54:51 +0100 Subject: [PATCH 117/145] Forgot copyright section in settings.h in 1ebce9b87752331a61971602b08048e569cdaa41 --- settings.h | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/settings.h b/settings.h index a69545e4..e3d0ed1d 100644 --- a/settings.h +++ b/settings.h @@ -1,8 +1,18 @@ -/* - * File: settings.h - * Author: xxxajk - * - * Created on September 23, 2013, 12:00 AM +/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. + +This software may be distributed and modified under the terms of the GNU +General Public License version 2 (GPL2) as published by the Free Software +Foundation and appearing in the file GPL2.TXT included in the packaging of +this file. Please note that GPL2 Section 2[b] requires that all works based +on this software must also be made publicly available under the terms of +the GPL2 ("Copyleft"). + +Contact information +------------------- + +Circuits At Home, LTD +Web : http://www.circuitsathome.com +e-mail : support@circuitsathome.com */ #ifndef USB_HOST_SHIELD_SETTINGS_H From d9dfa3cf35c9b7ee4935c8edc67c9c4577ec483d Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 6 Apr 2014 19:15:43 +0200 Subject: [PATCH 118/145] Show how to control the light and rumble inside the PS4 controller --- examples/Bluetooth/PS4BT/PS4BT.ino | 35 +++++++++++++++++++++++------- examples/PS4USB/PS4USB.ino | 34 ++++++++++++++++++++++------- 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/examples/Bluetooth/PS4BT/PS4BT.ino b/examples/Bluetooth/PS4BT/PS4BT.ino index 0b850737..e47cfae0 100644 --- a/examples/Bluetooth/PS4BT/PS4BT.ino +++ b/examples/Bluetooth/PS4BT/PS4BT.ino @@ -25,6 +25,7 @@ PS4BT PS4(&Btd, PAIR); //PS4BT PS4(&Btd); boolean printAngle, printTouch; +uint8_t oldL2Value, oldR2Value; void setup() { Serial.begin(115200); @@ -56,28 +57,46 @@ void loop() { Serial.print(F("\tR2: ")); Serial.print(PS4.getAnalogButton(R2)); } + if (PS4.getAnalogButton(L2) != oldL2Value || PS4.getAnalogButton(R2) != oldR2Value) // Only write value if it's different + PS4.setRumbleOn(PS4.getAnalogButton(L2), PS4.getAnalogButton(R2)); + oldL2Value = PS4.getAnalogButton(L2); + oldR2Value = PS4.getAnalogButton(R2); + if (PS4.getButtonClick(PS)) { Serial.print(F("\r\nPS")); PS4.disconnect(); } else { - if (PS4.getButtonClick(TRIANGLE)) + if (PS4.getButtonClick(TRIANGLE)) { Serial.print(F("\r\nTraingle")); - if (PS4.getButtonClick(CIRCLE)) + PS4.setRumbleOn(RumbleLow); + } + if (PS4.getButtonClick(CIRCLE)) { Serial.print(F("\r\nCircle")); - if (PS4.getButtonClick(CROSS)) + PS4.setRumbleOn(RumbleHigh); + } + if (PS4.getButtonClick(CROSS)) { Serial.print(F("\r\nCross")); - if (PS4.getButtonClick(SQUARE)) + PS4.setLedFlash(10, 10); // Set it to blink rapidly + } + if (PS4.getButtonClick(SQUARE)) { Serial.print(F("\r\nSquare")); + PS4.setLedFlash(0, 0); // Turn off blinking + } - if (PS4.getButtonClick(UP)) + if (PS4.getButtonClick(UP)) { Serial.print(F("\r\nUp")); - if (PS4.getButtonClick(RIGHT)) + PS4.setLed(Red); + } if (PS4.getButtonClick(RIGHT)) { Serial.print(F("\r\nRight")); - if (PS4.getButtonClick(DOWN)) + PS4.setLed(Blue); + } if (PS4.getButtonClick(DOWN)) { Serial.print(F("\r\nDown")); - if (PS4.getButtonClick(LEFT)) + PS4.setLed(Yellow); + } if (PS4.getButtonClick(LEFT)) { Serial.print(F("\r\nLeft")); + PS4.setLed(Green); + } if (PS4.getButtonClick(L1)) Serial.print(F("\r\nL1")); diff --git a/examples/PS4USB/PS4USB.ino b/examples/PS4USB/PS4USB.ino index c8dc5069..b3a2436b 100644 --- a/examples/PS4USB/PS4USB.ino +++ b/examples/PS4USB/PS4USB.ino @@ -15,6 +15,7 @@ USB Usb; PS4USB PS4(&Usb); boolean printAngle, printTouch; +uint8_t oldL2Value, oldR2Value; void setup() { Serial.begin(115200); @@ -47,26 +48,43 @@ void loop() { Serial.print(F("\tR2: ")); Serial.print(PS4.getAnalogButton(R2)); } + if (PS4.getAnalogButton(L2) != oldL2Value || PS4.getAnalogButton(R2) != oldR2Value) // Only write value if it's different + PS4.setRumbleOn(PS4.getAnalogButton(L2), PS4.getAnalogButton(R2)); + oldL2Value = PS4.getAnalogButton(L2); + oldR2Value = PS4.getAnalogButton(R2); if (PS4.getButtonClick(PS)) Serial.print(F("\r\nPS")); - if (PS4.getButtonClick(TRIANGLE)) + if (PS4.getButtonClick(TRIANGLE)) { Serial.print(F("\r\nTraingle")); - if (PS4.getButtonClick(CIRCLE)) + PS4.setRumbleOn(RumbleLow); + } + if (PS4.getButtonClick(CIRCLE)) { Serial.print(F("\r\nCircle")); - if (PS4.getButtonClick(CROSS)) + PS4.setRumbleOn(RumbleHigh); + } + if (PS4.getButtonClick(CROSS)) { Serial.print(F("\r\nCross")); - if (PS4.getButtonClick(SQUARE)) + PS4.setLedFlash(10, 10); // Set it to blink rapidly + } + if (PS4.getButtonClick(SQUARE)) { Serial.print(F("\r\nSquare")); + PS4.setLedFlash(0, 0); // Turn off blinking + } - if (PS4.getButtonClick(UP)) + if (PS4.getButtonClick(UP)) { Serial.print(F("\r\nUp")); - if (PS4.getButtonClick(RIGHT)) + PS4.setLed(Red); + } if (PS4.getButtonClick(RIGHT)) { Serial.print(F("\r\nRight")); - if (PS4.getButtonClick(DOWN)) + PS4.setLed(Blue); + } if (PS4.getButtonClick(DOWN)) { Serial.print(F("\r\nDown")); - if (PS4.getButtonClick(LEFT)) + PS4.setLed(Yellow); + } if (PS4.getButtonClick(LEFT)) { Serial.print(F("\r\nLeft")); + PS4.setLed(Green); + } if (PS4.getButtonClick(L1)) Serial.print(F("\r\nL1")); From 2c5f5e8c0964c1639265486b6fac17739a55f1d2 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 23 Apr 2014 23:40:47 +0200 Subject: [PATCH 119/145] Can now read battery level and usb, audio and mic status of PS4 controller Inspired by: https://github.com/chrippa/ds4drv/blob/master/ds4drv/device.py --- PS4Parser.h | 45 ++++++++++++++++++++++++++++++++++++++++++++- README.md | 2 +- keywords.txt | 4 ++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/PS4Parser.h b/PS4Parser.h index 093701e9..8b328342 100644 --- a/PS4Parser.h +++ b/PS4Parser.h @@ -81,6 +81,14 @@ struct touchpadXY { } __attribute__((packed)) finger[2]; // 0 = first finger, 1 = second finger } __attribute__((packed)); +struct PS4Status { + uint8_t battery : 4; + uint8_t usb : 1; + uint8_t audio : 1; + uint8_t mic : 1; + uint8_t unknown : 1; // Extension port? +} __attribute__((packed)); + struct PS4Data { /* Button and joystick values */ uint8_t hatValue[4]; @@ -92,8 +100,11 @@ struct PS4Data { int16_t gyroY, gyroZ, gyroX; int16_t accX, accZ, accY; + uint8_t dummy2[5]; + PS4Status status; + uint8_t dummy3[3]; + /* The rest is data for the touchpad */ - uint8_t dummy2[9]; // Byte 5 looks like some kind of status (maybe battery status), bit 1 of byte 8 is set every time a finger is moving around the touchpad touchpadXY xy[3]; // It looks like it sends out three coordinates each time, this might be because the microcontroller inside the PS4 controller is much faster than the Bluetooth connection. // The last data is read from the last position in the array while the oldest measurement is from the first position. // The first position will also keep it's value after the finger is released, while the other two will set them to zero. @@ -245,6 +256,38 @@ public: } }; + /** + * Return the battery level of the PS4 controller. + * @return The battery level in the range 0-15. + */ + uint8_t getBatteryLevel() { + return ps4Data.status.battery; + }; + + /** + * Use this to check if an USB cable is connected to the PS4 controller. + * @return Returns true if an USB cable is connected. + */ + bool getUsbStatus() { + return ps4Data.status.usb; + }; + + /** + * Use this to check if an audio jack cable is connected to the PS4 controller. + * @return Returns true if an audio jack cable is connected. + */ + bool getAudioStatus() { + return ps4Data.status.audio; + }; + + /** + * Use this to check if a microphone is connected to the PS4 controller. + * @return Returns true if a microphone is connected. + */ + bool getMicStatus() { + return ps4Data.status.mic; + }; + /** Turn both rumble and the LEDs off. */ void setAllOff() { setRumbleOff(); diff --git a/README.md b/README.md index 43fde867..35a786e5 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ It enables me to see the Bluetooth communication between my Mac and any device. 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. -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. +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. Before you can use the PS4 controller via Bluetooth you will need to pair with it. diff --git a/keywords.txt b/keywords.txt index a13ff34d..58496f4b 100644 --- a/keywords.txt +++ b/keywords.txt @@ -82,6 +82,10 @@ getX KEYWORD2 getY KEYWORD2 getTouchCounter KEYWORD2 +getUsbStatus KEYWORD2 +getAudioStatus KEYWORD2 +getMicStatus KEYWORD2 + #################################################### # Constants and enums (LITERAL1) #################################################### From e986282fa59c42368239e929e5bbb6079c4be448 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 28 Apr 2014 22:01:38 +0200 Subject: [PATCH 120/145] Forgot to call setLedRaw with the controller as the second argument in setLedOn --- XBOXRECV.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/XBOXRECV.cpp b/XBOXRECV.cpp index e70e322a..144a4aa4 100644 --- a/XBOXRECV.cpp +++ b/XBOXRECV.cpp @@ -514,9 +514,9 @@ void XBOXRECV::setLedRaw(uint8_t value, uint8_t controller) { void XBOXRECV::setLedOn(LEDEnum led, uint8_t controller) { if(led == OFF) - setLedRaw(0); + setLedRaw(0, controller); else if(led != ALL) // All LEDs can't be on a the same time - setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4); + setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4, controller); } void XBOXRECV::setLedBlink(LEDEnum led, uint8_t controller) { From 67cb06e858582cf642a6df062a891659574b62e9 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Wed, 21 May 2014 23:29:15 +0200 Subject: [PATCH 121/145] Add space between bytes printed for debugging --- hiduniversal.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/hiduniversal.cpp b/hiduniversal.cpp index c2f33533..3bd30339 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -401,8 +401,10 @@ uint8_t HIDUniversal::Poll() { #if 1 Notify(PSTR("\r\nBuf: "), 0x80); - for(uint8_t i = 0; i < read; i++) + for(uint8_t i = 0; i < read; i++) { D_PrintHex (buf[i], 0x80); + Notify(PSTR(" "), 0x80); + } Notify(PSTR("\r\n"), 0x80); #endif From b1ac5161757a2d97579a7a24507b87737c847d39 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 22 May 2014 01:33:01 -0400 Subject: [PATCH 122/145] Better/smaller EndpointXtract method, Removes buggy/unused/dead block of code. --- masstorage.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/masstorage.cpp b/masstorage.cpp index 19da7b19..90f76b3c 100644 --- a/masstorage.cpp +++ b/masstorage.cpp @@ -532,6 +532,20 @@ void BulkOnly::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t uint8_t index; +#if 1 + if((pep->bmAttributes & 0x02) == 2) { + index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; + // Fill in the endpoint info structure + epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); + epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize; + epInfo[index].epAttribs = 0; + + bNumEP++; + + PrintEndpointDescriptor(pep); + + } +#else if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) index = epInterruptInIndex; else @@ -548,6 +562,7 @@ void BulkOnly::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t bNumEP++; PrintEndpointDescriptor(pep); +#endif } /** From d56ed57495a9c8d01c4cd94653c5ea3d28ba60c6 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 22 May 2014 23:36:33 -0400 Subject: [PATCH 123/145] Fix 1 month rollover bug -- Lei Shi found this one in one place, I found the problem all over the library and patched them all. --- BTD.cpp | 2 +- Usb.cpp | 10 +- Wii.cpp | 4 +- examples/hub_demo/hub_demo.ino | 2 +- examples/pl2303/pl2303_gps/pl2303_gps.ino | 109 ++++++------ examples/testusbhostFAT/testusbhostFAT.ino | 182 ++++++++++----------- hidboot.h | 2 +- hiduniversal.cpp | 2 +- masstorage.cpp | 2 +- usbhub.cpp | 2 +- 10 files changed, 155 insertions(+), 162 deletions(-) diff --git a/BTD.cpp b/BTD.cpp index 4de668d9..1812f391 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -371,7 +371,7 @@ uint8_t BTD::Release() { uint8_t BTD::Poll() { if(!bPollEnable) return 0; - if(qNextPollTime <= millis()) { // Don't poll if shorter than polling interval + if((long)(millis() - qNextPollTime) >= 0L) { // Don't poll if shorter than polling interval qNextPollTime = millis() + pollInterval; // Set new poll time HCI_event_task(); // Poll the HCI event pipe HCI_task(); // HCI state machine diff --git a/Usb.cpp b/Usb.cpp index e21ca1fe..d75149d8 100644 --- a/Usb.cpp +++ b/Usb.cpp @@ -327,7 +327,7 @@ uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8 regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ rcode = (regRd(rHRSL) & 0x0f); - while(rcode && (timeout > millis())) { + while(rcode && ((long)(millis() - timeout) >= 0L)) { switch(rcode) { case hrNAK: nak_count++; @@ -380,11 +380,11 @@ uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) { uint8_t retry_count = 0; uint16_t nak_count = 0; - while(timeout > millis()) { + while((long)(millis() - timeout) >= 0L) { regWr(rHXFR, (token | ep)); //launch the transfer rcode = USB_ERROR_TRANSFER_TIMEOUT; - while(timeout > millis()) //wait for transfer completion + while((long)(millis() - timeout) >= 0L) //wait for transfer completion { tmpdata = regRd(rHIRQ); @@ -475,7 +475,7 @@ void USB::Task(void) //USB state machine case USB_DETACHED_SUBSTATE_ILLEGAL: //just sit here break; case USB_ATTACHED_SUBSTATE_SETTLE: //settle time for just attached device - if(delay < millis()) + if((long)(millis() - delay) >= 0L) usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE; else break; // don't fall through case USB_ATTACHED_SUBSTATE_RESET_DEVICE: @@ -502,7 +502,7 @@ void USB::Task(void) //USB state machine } break; case USB_ATTACHED_SUBSTATE_WAIT_RESET: - if(delay < millis()) usb_task_state = USB_STATE_CONFIGURING; + if((long)(millis() - delay) >= 0L) usb_task_state = USB_STATE_CONFIGURING; else break; // don't fall through case USB_STATE_CONFIGURING: diff --git a/Wii.cpp b/Wii.cpp index 62af423a..8106666b 100755 --- a/Wii.cpp +++ b/Wii.cpp @@ -657,7 +657,7 @@ void WII::L2CAP_task() { /* The next states are in run() */ case L2CAP_INTERRUPT_DISCONNECT: - if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) && millis() > timer) { + if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) && ((long)(millis() - timer) >= 0L)) { #ifdef DEBUG_USB_HOST Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80); #endif @@ -682,7 +682,7 @@ void WII::L2CAP_task() { } void WII::Run() { - if(l2cap_state == L2CAP_INTERRUPT_DISCONNECT && millis() > timer) + if(l2cap_state == L2CAP_INTERRUPT_DISCONNECT && ((long)(millis() - timer) >= 0L)) L2CAP_task(); // Call the rest of the disconnection routine after we have waited long enough switch(l2cap_state) { diff --git a/examples/hub_demo/hub_demo.ino b/examples/hub_demo/hub_demo.ino index 466ae4d7..bede0f4b 100644 --- a/examples/hub_demo/hub_demo.ino +++ b/examples/hub_demo/hub_demo.ino @@ -97,7 +97,7 @@ void loop() if( Usb.getUsbTaskState() == USB_STATE_RUNNING ) { - if (millis() >= next_time) + if ((next_time - millis()) >= 0L) { Usb.ForEachUsbDevice(&PrintAllDescriptors); Usb.ForEachUsbDevice(&PrintAllAddresses); diff --git a/examples/pl2303/pl2303_gps/pl2303_gps.ino b/examples/pl2303/pl2303_gps/pl2303_gps.ino index 9f33766a..908763c4 100644 --- a/examples/pl2303/pl2303_gps/pl2303_gps.ino +++ b/examples/pl2303/pl2303_gps/pl2303_gps.ino @@ -10,80 +10,75 @@ #include #endif -class PLAsyncOper : public CDCAsyncOper -{ +class PLAsyncOper : public CDCAsyncOper { public: - virtual uint8_t OnInit(ACM *pacm); + virtual uint8_t OnInit(ACM *pacm); }; -uint8_t PLAsyncOper::OnInit(ACM *pacm) -{ - uint8_t rcode; +uint8_t PLAsyncOper::OnInit(ACM *pacm) { + uint8_t rcode; - // Set DTR = 1 - rcode = pacm->SetControlLineState(1); + // Set DTR = 1 + rcode = pacm->SetControlLineState(1); + + if(rcode) { + ErrorMessage(PSTR("SetControlLineState"), rcode); + return rcode; + } + + LINE_CODING lc; + lc.dwDTERate = 4800; //default serial speed of GPS unit + lc.bCharFormat = 0; + lc.bParityType = 0; + lc.bDataBits = 8; + + rcode = pacm->SetLineCoding(&lc); + + if(rcode) + ErrorMessage(PSTR("SetLineCoding"), rcode); - if (rcode) - { - ErrorMessage(PSTR("SetControlLineState"), rcode); return rcode; - } - - LINE_CODING lc; - lc.dwDTERate = 4800; //default serial speed of GPS unit - lc.bCharFormat = 0; - lc.bParityType = 0; - lc.bDataBits = 8; - - rcode = pacm->SetLineCoding(&lc); - - if (rcode) - ErrorMessage(PSTR("SetLineCoding"), rcode); - - return rcode; } -USB Usb; -USBHub Hub(&Usb); -PLAsyncOper AsyncOper; -PL2303 Pl(&Usb, &AsyncOper); +USB Usb; +USBHub Hub(&Usb); +PLAsyncOper AsyncOper; +PL2303 Pl(&Usb, &AsyncOper); uint32_t read_delay; #define READ_DELAY 100 -void setup() -{ - Serial.begin( 115200 ); - while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection - Serial.println("Start"); +void setup() { + Serial.begin(115200); + while(!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection + Serial.println("Start"); - if (Usb.Init() == -1) - Serial.println("OSCOKIRQ failed to assert"); + if(Usb.Init() == -1) + Serial.println("OSCOKIRQ failed to assert"); - delay( 200 ); + delay(200); } -void loop() -{ -uint8_t rcode; -uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint -uint16_t rcvd = 64; +void loop() { + uint8_t rcode; + uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint + uint16_t rcvd = 64; - Usb.Task(); + Usb.Task(); - if( Pl.isReady()) { - /* reading the GPS */ - if( read_delay < millis() ){ - read_delay += READ_DELAY; - rcode = Pl.RcvData(&rcvd, buf); - if ( rcode && rcode != hrNAK ) - ErrorMessage(PSTR("Ret"), rcode); - if( rcvd ) { //more than zero bytes received - for( uint16_t i=0; i < rcvd; i++ ) { - Serial.print((char)buf[i]); //printing on the screen - }//for( uint16_t i=0; i < rcvd; i++... - }//if( rcvd - }//if( read_delay > millis()... - }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. + if(Pl.isReady()) { + /* reading the GPS */ + if((long)(millis() - read_delay) >= 0L) { + read_delay += READ_DELAY; + rcode = Pl.RcvData(&rcvd, buf); + if(rcode && rcode != hrNAK) + ErrorMessage(PSTR("Ret"), rcode); + if(rcvd) { //more than zero bytes received + for(uint16_t i = 0; i < rcvd; i++) { + Serial.print((char)buf[i]); //printing on the screen + }//for( uint16_t i=0; i < rcvd; i++... + }//if( rcvd + }//if( read_delay > millis()... + }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING.. } diff --git a/examples/testusbhostFAT/testusbhostFAT.ino b/examples/testusbhostFAT/testusbhostFAT.ino index f316a49b..c7110632 100644 --- a/examples/testusbhostFAT/testusbhostFAT.ino +++ b/examples/testusbhostFAT/testusbhostFAT.ino @@ -126,7 +126,7 @@ static int tty_std_putc(char c, FILE *t) { } static int tty_std_getc(FILE *t) { - while (!Serial.available()); + while(!Serial.available()); return Serial.read(); } @@ -140,18 +140,18 @@ extern "C" { int _write(int fd, const char *ptr, int len) { int j; - for (j = 0; j < len; j++) { - if (fd == 1) + for(j = 0; j < len; j++) { + if(fd == 1) Serial.write(*ptr++); - else if (fd == 2) + else if(fd == 2) USB_HOST_SERIAL.write(*ptr++); } return len; } int _read(int fd, char *ptr, int len) { - if (len > 0 && fd == 0) { - while (!Serial.available()); + if(len > 0 && fd == 0) { + while(!Serial.available()); *ptr = Serial.read(); return 1; } @@ -175,7 +175,7 @@ extern "C" { void setup() { boolean serr = false; - for (int i = 0; i < _VOLUMES; i++) { + for(int i = 0; i < _VOLUMES; i++) { Fats[i] = NULL; sto[i].private_data = new pvt_t; ((pvt_t *)sto[i].private_data)->B = 255; // impossible @@ -193,7 +193,7 @@ void setup() { // Initialize 'debug' serial port USB_HOST_SERIAL.begin(115200); // Do not start primary Serial port if already started. - if (bit_is_clear(UCSR0B, TXEN0)) { + if(bit_is_clear(UCSR0B, TXEN0)) { Serial.begin(115200); serr = true; } @@ -220,7 +220,7 @@ void setup() { analogWrite(LED_BUILTIN, 0); delay(500); #else - while (!Serial); + while(!Serial); #endif printf_P(PSTR("\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nStart\r\n")); @@ -236,7 +236,7 @@ void setup() { "Disabled" #endif "\r\n")); - if (serr) { + if(serr) { fprintf_P(stderr, PSTR("\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nStart\r\n")); fprintf_P(stderr, PSTR("Current UsbDEBUGlvl %02x\r\n"), UsbDEBUGlvl); fprintf_P(stderr, PSTR("Long filename support: " @@ -274,7 +274,7 @@ void setup() { // I want to be able to have slightly more control. // Besides, it is easier to initialize stuff... #if WANT_HUB_TEST - for (int i = 0; i < MAX_HUBS; i++) { + for(int i = 0; i < MAX_HUBS; i++) { Hubs[i] = new USBHub(&Usb); #if defined(AVR) printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap()); @@ -284,7 +284,7 @@ void setup() { // Initialize generic storage. This must be done before USB starts. InitStorage(); - while (Usb.Init(1000) == -1) { + while(Usb.Init(1000) == -1) { printf_P(PSTR("No USB HOST Shield?\r\n")); Notify(PSTR("OSC did not start."), 0x40); } @@ -316,7 +316,7 @@ void setup() { //printf("SPI_CTAR0 = %8.8X\r\n", ctar); uint32_t mcr = SPI0_MCR; - if (mcr & SPI_MCR_MDIS) { + if(mcr & SPI_MCR_MDIS) { SPI0_CTAR0 = ctar; } else { SPI0_MCR = mcr | SPI_MCR_MDIS | SPI_MCR_HALT; @@ -334,23 +334,23 @@ void serialEvent() { // . to increase by 16, , to decrease by 16 // e to flick VBUS // * to report debug level - if (Serial.available()) { + if(Serial.available()) { int inByte = Serial.read(); - switch (inByte) { + switch(inByte) { case '+': - if (UsbDEBUGlvl < 0xff) UsbDEBUGlvl++; + if(UsbDEBUGlvl < 0xff) UsbDEBUGlvl++; reportlvl = true; break; case '-': - if (UsbDEBUGlvl > 0x00) UsbDEBUGlvl--; + if(UsbDEBUGlvl > 0x00) UsbDEBUGlvl--; reportlvl = true; break; case '.': - if (UsbDEBUGlvl < 0xf0) UsbDEBUGlvl += 16; + if(UsbDEBUGlvl < 0xf0) UsbDEBUGlvl += 16; reportlvl = true; break; case ',': - if (UsbDEBUGlvl > 0x0f) UsbDEBUGlvl -= 16; + if(UsbDEBUGlvl > 0x0f) UsbDEBUGlvl -= 16; reportlvl = true; break; case '*': @@ -370,7 +370,7 @@ void serialEvent() { #if defined(AVR) ISR(TIMER3_COMPA_vect) { - if (millis() >= LEDnext_time) { + if(millis() >= LEDnext_time) { LEDnext_time = millis() + 30; // set the brightness of LED @@ -380,11 +380,11 @@ ISR(TIMER3_COMPA_vect) { brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: - if (brightness <= 0) { + if(brightness <= 0) { brightness = 0; fadeAmount = -fadeAmount; } - if (brightness >= 255) { + if(brightness >= 255) { brightness = 255; fadeAmount = -fadeAmount; } @@ -406,8 +406,8 @@ void loop() { #if defined(AVR) // Print a heap status report about every 10 seconds. - if (millis() >= HEAPnext_time) { - if (UsbDEBUGlvl > 0x50) { + if(millis() >= HEAPnext_time) { + if(UsbDEBUGlvl > 0x50) { printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap()); } HEAPnext_time = millis() + 10000; @@ -419,14 +419,14 @@ void loop() { #endif // Horrid! This sort of thing really belongs in an ISR, not here! // We also will be needing to test each hub port, we don't do this yet! - if (!change && !usbon && millis() >= usbon_time) { + if(!change && !usbon && millis() >= usbon_time) { change = true; usbon = true; } - if (change) { + if(change) { change = false; - if (usbon) { + if(usbon) { Usb.vbusPower(vbus_on); printf_P(PSTR("VBUS on\r\n")); } else { @@ -436,21 +436,21 @@ void loop() { } Usb.Task(); current_state = Usb.getUsbTaskState(); - if (current_state != last_state) { - if (UsbDEBUGlvl > 0x50) + if(current_state != last_state) { + if(UsbDEBUGlvl > 0x50) printf_P(PSTR("USB state = %x\r\n"), current_state); #if defined(AVR) - if (current_state == USB_STATE_RUNNING) { + if(current_state == USB_STATE_RUNNING) { fadeAmount = 30; } #endif - if (current_state == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) { + if(current_state == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) { #if defined(AVR) fadeAmount = 80; #endif partsready = false; - for (int i = 0; i < cpart; i++) { - if (Fats[i] != NULL) + for(int i = 0; i < cpart; i++) { + if(Fats[i] != NULL) delete Fats[i]; Fats[i] = NULL; } @@ -462,28 +462,27 @@ void loop() { } // only do any of this if usb is on - if (usbon) { - if (partsready && !fatready) { - if (cpart > 0) fatready = true; + if(usbon) { + if(partsready && !fatready) { + if(cpart > 0) fatready = true; } // This is horrible, and needs to be moved elsewhere! - for (int B = 0; B < MAX_USB_MS_DRIVERS; B++) { - if (!partsready && (Bulk[B]->GetAddress() != NULL)) { + for(int B = 0; B < MAX_USB_MS_DRIVERS; B++) { + if(!partsready && (Bulk[B]->GetAddress() != NULL)) { // Build a list. int ML = Bulk[B]->GetbMaxLUN(); //printf("MAXLUN = %i\r\n", ML); ML++; - for (int i = 0; i < ML; i++) { - if (Bulk[B]->LUNIsGood(i)) { + for(int i = 0; i < ML; i++) { + if(Bulk[B]->LUNIsGood(i)) { partsready = true; ((pvt_t *)(sto[i].private_data))->lun = i; ((pvt_t *)(sto[i].private_data))->B = B; - sto[i].Read = *PRead; - sto[i].Write = *PWrite; sto[i].Reads = *PReads; sto[i].Writes = *PWrites; sto[i].Status = *PStatus; + sto[i].Commit = *UHS_USB_BulkOnly_Commit; sto[i].TotalSectors = Bulk[B]->GetCapacity(i); sto[i].SectorSize = Bulk[B]->GetSectorSize(i); printf_P(PSTR("LUN:\t\t%u\r\n"), i); @@ -492,18 +491,18 @@ void loop() { // get the partition data... PT = new PCPartition; - if (!PT->Init(&sto[i])) { + if(!PT->Init(&sto[i])) { part_t *apart; - for (int j = 0; j < 4; j++) { + for(int j = 0; j < 4; j++) { apart = PT->GetPart(j); - if (apart != NULL && apart->type != 0x00) { + if(apart != NULL && apart->type != 0x00) { memcpy(&(parts[cpart]), apart, sizeof (part_t)); printf_P(PSTR("Partition %u type %#02x\r\n"), j, parts[cpart].type); // for now - if (isfat(parts[cpart].type)) { + if(isfat(parts[cpart].type)) { Fats[cpart] = new PFAT(&sto[i], cpart, parts[cpart].firstSector); //int r = Fats[cpart]->Good(); - if (Fats[cpart]->MountStatus()) { + if(Fats[cpart]->MountStatus()) { delete Fats[cpart]; Fats[cpart] = NULL; } else cpart++; @@ -514,7 +513,7 @@ void loop() { // try superblock Fats[cpart] = new PFAT(&sto[i], cpart, 0); //int r = Fats[cpart]->Good(); - if (Fats[cpart]->MountStatus()) { + if(Fats[cpart]->MountStatus()) { //printf_P(PSTR("Superblock error %x\r\n"), r); delete Fats[cpart]; Fats[cpart] = NULL; @@ -535,18 +534,18 @@ void loop() { } } - if (fatready) { - if (Fats[0] != NULL) { + if(fatready) { + if(Fats[0] != NULL) { struct Pvt * p; p = ((struct Pvt *)(Fats[0]->storage->private_data)); - if (!Bulk[p->B]->LUNIsGood(p->lun)) { + if(!Bulk[p->B]->LUNIsGood(p->lun)) { // media change #if defined(AVR) fadeAmount = 80; #endif partsready = false; - for (int i = 0; i < cpart; i++) { - if (Fats[i] != NULL) + for(int i = 0; i < cpart; i++) { + if(Fats[i] != NULL) delete Fats[i]; Fats[cpart] = NULL; } @@ -557,62 +556,61 @@ void loop() { } } - if (fatready) { + if(fatready) { FRESULT rc; /* Result code */ UINT bw, br, i; - if (!notified) { + if(!notified) { #if defined(AVR) fadeAmount = 5; #endif notified = true; printf_P(PSTR("\r\nOpen an existing file (message.txt).\r\n")); rc = f_open(&My_File_Object_x, "0:/MESSAGE.TXT", FA_READ); - if (rc) printf_P(PSTR("Error %i, message.txt not found.\r\n"), rc); + if(rc) printf_P(PSTR("Error %i, message.txt not found.\r\n"), rc); else { printf_P(PSTR("\r\nType the file content.\r\n")); - for (;;) { + for(;;) { rc = f_read(&My_File_Object_x, My_Buff_x, mbxs, &br); /* Read a chunk of file */ - if (rc || !br) break; /* Error or end of file */ - for (i = 0; i < br; i++) { + if(rc || !br) break; /* Error or end of file */ + for(i = 0; i < br; i++) { /* Type the data */ - if (My_Buff_x[i] == '\n') + if(My_Buff_x[i] == '\n') Serial.write('\r'); - if (My_Buff_x[i] != '\r') + if(My_Buff_x[i] != '\r') Serial.write(My_Buff_x[i]); Serial.flush(); } } - if (rc) { + if(rc) { f_close(&My_File_Object_x); goto out; } printf_P(PSTR("\r\nClose the file.\r\n")); rc = f_close(&My_File_Object_x); - if (rc) goto out; + if(rc) goto out; } printf_P(PSTR("\r\nCreate a new file (hello.txt).\r\n")); rc = f_open(&My_File_Object_x, "0:/Hello.TxT", FA_WRITE | FA_CREATE_ALWAYS); - if (rc) { + if(rc) { die(rc); goto outdir; } printf_P(PSTR("\r\nWrite a text data. (Hello world!)\r\n")); rc = f_write(&My_File_Object_x, "Hello world!\r\n", 14, &bw); - if (rc) { + if(rc) { goto out; } printf_P(PSTR("%u bytes written.\r\n"), bw); printf_P(PSTR("\r\nClose the file.\r\n")); rc = f_close(&My_File_Object_x); - if (rc) { + if(rc) { die(rc); goto out; } -outdir: - { +outdir:{ #if _USE_LFN char lfn[_MAX_LFN + 1]; FILINFO My_File_Info_Object_x; /* File information object */ @@ -621,7 +619,7 @@ outdir: DIR My_Dir_Object_x; /* Directory object */ printf_P(PSTR("\r\nOpen root directory.\r\n")); rc = f_opendir(&My_Dir_Object_x, "0:/"); - if (rc) { + if(rc) { die(rc); goto out; } @@ -630,46 +628,46 @@ outdir: #if defined(AVR) printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap()); #endif - for (;;) { + for(;;) { #if _USE_LFN My_File_Info_Object_x.lfsize = _MAX_LFN; #endif rc = f_readdir(&My_Dir_Object_x, &My_File_Info_Object_x); /* Read a directory item */ - if (rc || !My_File_Info_Object_x.fname[0]) break; /* Error or end of dir */ + if(rc || !My_File_Info_Object_x.fname[0]) break; /* Error or end of dir */ - if (My_File_Info_Object_x.fattrib & AM_DIR) { + if(My_File_Info_Object_x.fattrib & AM_DIR) { Serial.write('d'); } else { Serial.write('-'); } Serial.write('r'); - if (My_File_Info_Object_x.fattrib & AM_RDO) { + if(My_File_Info_Object_x.fattrib & AM_RDO) { Serial.write('-'); } else { Serial.write('w'); } - if (My_File_Info_Object_x.fattrib & AM_HID) { + if(My_File_Info_Object_x.fattrib & AM_HID) { Serial.write('h'); } else { Serial.write('-'); } - if (My_File_Info_Object_x.fattrib & AM_SYS) { + if(My_File_Info_Object_x.fattrib & AM_SYS) { Serial.write('s'); } else { Serial.write('-'); } - if (My_File_Info_Object_x.fattrib & AM_ARC) { + if(My_File_Info_Object_x.fattrib & AM_ARC) { Serial.write('a'); } else { Serial.write('-'); } #if _USE_LFN - if (*My_File_Info_Object_x.lfname) + if(*My_File_Info_Object_x.lfname) printf_P(PSTR(" %8lu %s (%s)\r\n"), My_File_Info_Object_x.fsize, My_File_Info_Object_x.fname, My_File_Info_Object_x.lfname); else #endif @@ -677,48 +675,48 @@ outdir: } } out: - if (rc) die(rc); + if(rc) die(rc); printf_P(PSTR("\r\nTest completed.\r\n")); } - if (runtest) { + if(runtest) { ULONG ii, wt, rt, start, end; runtest = false; f_unlink("0:/10MB.bin"); printf_P(PSTR("\r\nCreate a new 10MB test file (10MB.bin).\r\n")); rc = f_open(&My_File_Object_x, "0:/10MB.bin", FA_WRITE | FA_CREATE_ALWAYS); - if (rc) goto failed; - for (bw = 0; bw < mbxs; bw++) My_Buff_x[bw] = bw & 0xff; + if(rc) goto failed; + for(bw = 0; bw < mbxs; bw++) My_Buff_x[bw] = bw & 0xff; fflush(stdout); start = millis(); - while (start == millis()); - for (ii = 10485760LU / mbxs; ii > 0LU; ii--) { + while(start == millis()); + for(ii = 10485760LU / mbxs; ii > 0LU; ii--) { rc = f_write(&My_File_Object_x, My_Buff_x, mbxs, &bw); - if (rc || !bw) goto failed; + if(rc || !bw) goto failed; } rc = f_close(&My_File_Object_x); - if (rc) goto failed; + if(rc) goto failed; end = millis(); wt = (end - start) - 1; printf_P(PSTR("Time to write 10485760 bytes: %lu ms (%lu sec) \r\n"), wt, (500 + wt) / 1000UL); rc = f_open(&My_File_Object_x, "0:/10MB.bin", FA_READ); fflush(stdout); start = millis(); - while (start == millis()); - if (rc) goto failed; - for (;;) { + while(start == millis()); + if(rc) goto failed; + for(;;) { rc = f_read(&My_File_Object_x, My_Buff_x, mbxs, &bw); /* Read a chunk of file */ - if (rc || !bw) break; /* Error or end of file */ + if(rc || !bw) break; /* Error or end of file */ } end = millis(); - if (rc) goto failed; + if(rc) goto failed; rc = f_close(&My_File_Object_x); - if (rc) goto failed; + if(rc) goto failed; rt = (end - start) - 1; printf_P(PSTR("Time to read 10485760 bytes: %lu ms (%lu sec)\r\nDelete test file\r\n"), rt, (500 + rt) / 1000UL); failed: - if (rc) die(rc); + if(rc) die(rc); printf_P(PSTR("10MB timing test finished.\r\n")); } } diff --git a/hidboot.h b/hidboot.h index 2218eb9e..0326bf25 100644 --- a/hidboot.h +++ b/hidboot.h @@ -536,7 +536,7 @@ template uint8_t HIDBoot::Poll() { uint8_t rcode = 0; - if(bPollEnable && qNextPollTime <= millis()) { + if(bPollEnable && ((long)(millis() - qNextPollTime) >= 0L)) { // To-do: optimize manually, using the for loop only if needed. for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { diff --git a/hiduniversal.cpp b/hiduniversal.cpp index c2f33533..acc1b00c 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -370,7 +370,7 @@ uint8_t HIDUniversal::Poll() { if(!bPollEnable) return 0; - if(qNextPollTime <= millis()) { + if((long)(millis() - qNextPollTime) >= 0L) { qNextPollTime = millis() + pollInterval; uint8_t buf[constBuffLen]; diff --git a/masstorage.cpp b/masstorage.cpp index 3c014f89..ab9ad4ff 100644 --- a/masstorage.cpp +++ b/masstorage.cpp @@ -671,7 +671,7 @@ uint8_t BulkOnly::Poll() { if(!bPollEnable) return 0; - if(qNextPollTime <= millis()) { + if((long)(millis() - qNextPollTime) >= 0L) { CheckMedia(); } //rcode = 0; diff --git a/usbhub.cpp b/usbhub.cpp index 82fc30f5..a3ab21eb 100644 --- a/usbhub.cpp +++ b/usbhub.cpp @@ -230,7 +230,7 @@ uint8_t USBHub::Poll() { if(!bPollEnable) return 0; - if(qNextPollTime <= millis()) { + if(((long)(millis() - qNextPollTime) >= 0L)) { rcode = CheckHubStatus(); qNextPollTime = millis() + 100; } From a50baa8aecdc62fe23f212e92a2f29e75fe6cf74 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Fri, 23 May 2014 00:12:55 -0400 Subject: [PATCH 124/145] Merge in masters --- examples/testusbhostFAT/Arduino_Makefile_master | 2 +- examples/testusbhostFAT/RTClib | 2 +- examples/testusbhostFAT/generic_storage | 2 +- examples/testusbhostFAT/xmem2 | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/testusbhostFAT/Arduino_Makefile_master b/examples/testusbhostFAT/Arduino_Makefile_master index 1cacea4e..d35bb955 160000 --- a/examples/testusbhostFAT/Arduino_Makefile_master +++ b/examples/testusbhostFAT/Arduino_Makefile_master @@ -1 +1 @@ -Subproject commit 1cacea4e8933b37b9f98528b2a831031f69905de +Subproject commit d35bb955e3818f0c14e47c8a1998003da8dc1b5a diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index 9108effe..7fd6a306 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit 9108effe4d4e556198e3e7b95365d1c898680dae +Subproject commit 7fd6a306ca53d08bf53b2bbfc1b80eb056f2c55b diff --git a/examples/testusbhostFAT/generic_storage b/examples/testusbhostFAT/generic_storage index ab85718a..0b8e3076 160000 --- a/examples/testusbhostFAT/generic_storage +++ b/examples/testusbhostFAT/generic_storage @@ -1 +1 @@ -Subproject commit ab85718a917094391762b79140d8e3a03af136a4 +Subproject commit 0b8e3076b5a072251e01cfc6e6333b364d4e71e7 diff --git a/examples/testusbhostFAT/xmem2 b/examples/testusbhostFAT/xmem2 index dd85091a..2bf8f633 160000 --- a/examples/testusbhostFAT/xmem2 +++ b/examples/testusbhostFAT/xmem2 @@ -1 +1 @@ -Subproject commit dd85091abaca7cc6055ff515a5e42f32198380d2 +Subproject commit 2bf8f633e7f9bc5a7bf4c00f3f45c7b79484198e From f6244bbe59c46a176251125f07bca1b92daf4d6a Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Sat, 24 May 2014 00:31:26 -0400 Subject: [PATCH 125/145] bugfix --- Usb.cpp | 6 +++--- examples/hub_demo/hub_demo.ino | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Usb.cpp b/Usb.cpp index d75149d8..ca81cf99 100644 --- a/Usb.cpp +++ b/Usb.cpp @@ -327,7 +327,7 @@ uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8 regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ rcode = (regRd(rHRSL) & 0x0f); - while(rcode && ((long)(millis() - timeout) >= 0L)) { + while(rcode && ((long)(millis() - timeout) < 0L)) { switch(rcode) { case hrNAK: nak_count++; @@ -380,11 +380,11 @@ uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) { uint8_t retry_count = 0; uint16_t nak_count = 0; - while((long)(millis() - timeout) >= 0L) { + while((long)(millis() - timeout) < 0L) { regWr(rHXFR, (token | ep)); //launch the transfer rcode = USB_ERROR_TRANSFER_TIMEOUT; - while((long)(millis() - timeout) >= 0L) //wait for transfer completion + while((long)(millis() - timeout) < 0L) //wait for transfer completion { tmpdata = regRd(rHIRQ); diff --git a/examples/hub_demo/hub_demo.ino b/examples/hub_demo/hub_demo.ino index bede0f4b..329c6230 100644 --- a/examples/hub_demo/hub_demo.ino +++ b/examples/hub_demo/hub_demo.ino @@ -97,7 +97,7 @@ void loop() if( Usb.getUsbTaskState() == USB_STATE_RUNNING ) { - if ((next_time - millis()) >= 0L) + if ((millis() - next_time) >= 0L) { Usb.ForEachUsbDevice(&PrintAllDescriptors); Usb.ForEachUsbDevice(&PrintAllAddresses); From d9dac13225e806db5e445733c94c3e6c965d701c Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 27 May 2014 09:42:13 +0200 Subject: [PATCH 126/145] Updated testusbhostFAT example and submodules --- .../testusbhostFAT/Arduino_Makefile_master | 2 +- examples/testusbhostFAT/Makefile | 4 + examples/testusbhostFAT/RTClib | 2 +- examples/testusbhostFAT/generic_storage | 2 +- examples/testusbhostFAT/testusbhostFAT.ino | 340 +++++++++--------- examples/testusbhostFAT/xmem2 | 2 +- 6 files changed, 175 insertions(+), 177 deletions(-) mode change 100644 => 100755 examples/testusbhostFAT/testusbhostFAT.ino diff --git a/examples/testusbhostFAT/Arduino_Makefile_master b/examples/testusbhostFAT/Arduino_Makefile_master index 1cacea4e..d35bb955 160000 --- a/examples/testusbhostFAT/Arduino_Makefile_master +++ b/examples/testusbhostFAT/Arduino_Makefile_master @@ -1 +1 @@ -Subproject commit 1cacea4e8933b37b9f98528b2a831031f69905de +Subproject commit d35bb955e3818f0c14e47c8a1998003da8dc1b5a diff --git a/examples/testusbhostFAT/Makefile b/examples/testusbhostFAT/Makefile index 7e5ebaec..232d338e 100644 --- a/examples/testusbhostFAT/Makefile +++ b/examples/testusbhostFAT/Makefile @@ -9,6 +9,10 @@ BOARD = mega PROGRAMMER = arduino +#BOARD = teensypp2 +#BOARD = teensy3 +#BOARD = teensy31 + # set your Arduino tty port here PORT = /dev/ttyUSB0 diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index 9108effe..7fd6a306 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit 9108effe4d4e556198e3e7b95365d1c898680dae +Subproject commit 7fd6a306ca53d08bf53b2bbfc1b80eb056f2c55b diff --git a/examples/testusbhostFAT/generic_storage b/examples/testusbhostFAT/generic_storage index ab85718a..0b8e3076 160000 --- a/examples/testusbhostFAT/generic_storage +++ b/examples/testusbhostFAT/generic_storage @@ -1 +1 @@ -Subproject commit ab85718a917094391762b79140d8e3a03af136a4 +Subproject commit 0b8e3076b5a072251e01cfc6e6333b364d4e71e7 diff --git a/examples/testusbhostFAT/testusbhostFAT.ino b/examples/testusbhostFAT/testusbhostFAT.ino old mode 100644 new mode 100755 index f316a49b..70107963 --- a/examples/testusbhostFAT/testusbhostFAT.ino +++ b/examples/testusbhostFAT/testusbhostFAT.ino @@ -19,35 +19,39 @@ * */ +///////////////////////////////////////////////////////////// +// Please Note: // +// This section is for info with the Arduino IDE ONLY. // +// Unfortunately due to short sightedness of the Arduino // +// code team, that you must set the following in the // +// respective libraries. // +// Changing them here will have _NO_ effect! // +///////////////////////////////////////////////////////////// + +// Uncomment to enable debugging +//#define DEBUG_USB_HOST +// This is where stderr/USB debugging goes to +//#define USB_HOST_SERIAL Serial3 + +// If you have external memory, setting this to 0 enables FAT table caches. +// The 0 setting is recommended only if you have external memory. +//#define _FS_TINY 1 + +//#define _USE_LFN 3 +//#define EXT_RAM_STACK 1 +//#define EXT_RAM_HEAP 1 +//#define _MAX_SS 512 +///////////////////////////////////////////////////////////// +// End of Arduino IDE specific information // +///////////////////////////////////////////////////////////// + // You can set this to 0 if you are not using a USB hub. // It will save a little bit of flash and RAM. // Set to 1 if you want to use a hub. #define WANT_HUB_TEST 0 -///////////////////////////////////////////////////////////// -// Please Note: This section is for Arduino IDE ONLY. // -// Use of Make creates a flash image that is 3.3KB smaller // -///////////////////////////////////////////////////////////// -#ifndef USING_MAKEFILE -// Uncomment to enable debugging -//#define DEBUG_USB_HOST -// This is where stderr/USB debugging goes to -#define USB_HOST_SERIAL Serial3 -// If you have external memory, setting this to 0 enables FAT table caches. -// The 0 setting is recommended only if you have external memory. -#define _FS_TINY 1 - -// These you can safely leave alone. -#define _USE_LFN 3 -#define EXT_RAM_STACK 1 -#define EXT_RAM_HEAP 1 -#define _MAX_SS 512 -#endif -///////////////////////////////////////////////////////////// -// End of Arduino IDE specific hacks // -///////////////////////////////////////////////////////////// -#if defined(AVR) +#if defined(__AVR__) #include #else #include @@ -63,7 +67,7 @@ #include #include #include -#if defined(AVR) +#if defined(__AVR__) static FILE tty_stdio; static FILE tty_stderr; volatile uint32_t LEDnext_time; // fade timeout @@ -100,7 +104,7 @@ static storage_t sto[_VOLUMES]; #define mbxs 128 static uint8_t My_Buff_x[mbxs]; /* File read buffer */ -#if defined(AVR) +#if defined(__AVR__) #define prescale1 ((1 << WGM12) | (1 << CS10)) #define prescale8 ((1 << WGM12) | (1 << CS11)) @@ -126,7 +130,7 @@ static int tty_std_putc(char c, FILE *t) { } static int tty_std_getc(FILE *t) { - while (!Serial.available()); + while(!Serial.available()); return Serial.read(); } @@ -140,18 +144,18 @@ extern "C" { int _write(int fd, const char *ptr, int len) { int j; - for (j = 0; j < len; j++) { - if (fd == 1) + for(j = 0; j < len; j++) { + if(fd == 1) Serial.write(*ptr++); - else if (fd == 2) + else if(fd == 2) USB_HOST_SERIAL.write(*ptr++); } return len; } int _read(int fd, char *ptr, int len) { - if (len > 0 && fd == 0) { - while (!Serial.available()); + if(len > 0 && fd == 0) { + while(!Serial.available()); *ptr = Serial.read(); return 1; } @@ -175,7 +179,7 @@ extern "C" { void setup() { boolean serr = false; - for (int i = 0; i < _VOLUMES; i++) { + for(int i = 0; i < _VOLUMES; i++) { Fats[i] = NULL; sto[i].private_data = new pvt_t; ((pvt_t *)sto[i].private_data)->B = 255; // impossible @@ -184,7 +188,7 @@ void setup() { // minimum 0x00, maximum 0xff UsbDEBUGlvl = 0x51; -#if defined(AVR) +#if !defined(CORE_TEENSY) && defined(__AVR__) // make LED pin as an output: pinMode(LED_BUILTIN, OUTPUT); pinMode(2, OUTPUT); @@ -193,11 +197,23 @@ void setup() { // Initialize 'debug' serial port USB_HOST_SERIAL.begin(115200); // Do not start primary Serial port if already started. - if (bit_is_clear(UCSR0B, TXEN0)) { + if(bit_is_clear(UCSR0B, TXEN0)) { Serial.begin(115200); serr = true; } + + // Blink LED + delay(500); + analogWrite(LED_BUILTIN, 255); + delay(500); + analogWrite(LED_BUILTIN, 0); + delay(500); +#else + while(!Serial); + Serial.begin(115200); // On the Teensy 3.x we get a delay at least! +#endif +#if defined(__AVR__) // Set up stdio/stderr tty_stdio.put = tty_std_putc; tty_stdio.get = tty_std_getc; @@ -212,17 +228,7 @@ void setup() { stdout = &tty_stdio; stdin = &tty_stdio; stderr = &tty_stderr; - - // Blink LED - delay(500); - analogWrite(LED_BUILTIN, 255); - delay(500); - analogWrite(LED_BUILTIN, 0); - delay(500); -#else - while (!Serial); #endif - printf_P(PSTR("\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nStart\r\n")); printf_P(PSTR("Current UsbDEBUGlvl %02x\r\n"), UsbDEBUGlvl); printf_P(PSTR("'+' and '-' increase/decrease by 0x01\r\n")); @@ -236,7 +242,7 @@ void setup() { "Disabled" #endif "\r\n")); - if (serr) { + if(serr) { fprintf_P(stderr, PSTR("\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nStart\r\n")); fprintf_P(stderr, PSTR("Current UsbDEBUGlvl %02x\r\n"), UsbDEBUGlvl); fprintf_P(stderr, PSTR("Long filename support: " @@ -247,8 +253,8 @@ void setup() { #endif "\r\n")); } -#if defined(AVR) +#if !defined(CORE_TEENSY) && defined(__AVR__) analogWrite(LED_BUILTIN, 255); delay(500); analogWrite(LED_BUILTIN, 0); @@ -263,7 +269,7 @@ void setup() { delay(500); LEDnext_time = millis() + 1; -#ifdef EXT_RAM +#if EXT_RAM printf_P(PSTR("Total EXT RAM banks %i\r\n"), xmem::getTotalBanks()); #endif printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap()); @@ -274,22 +280,22 @@ void setup() { // I want to be able to have slightly more control. // Besides, it is easier to initialize stuff... #if WANT_HUB_TEST - for (int i = 0; i < MAX_HUBS; i++) { + for(int i = 0; i < MAX_HUBS; i++) { Hubs[i] = new USBHub(&Usb); -#if defined(AVR) +#if defined(__AVR__) printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap()); #endif } #endif // Initialize generic storage. This must be done before USB starts. - InitStorage(); + Init_Generic_Storage(); - while (Usb.Init(1000) == -1) { + while(Usb.Init(1000) == -1) { printf_P(PSTR("No USB HOST Shield?\r\n")); Notify(PSTR("OSC did not start."), 0x40); } -#if defined(AVR) +#if !defined(CORE_TEENSY) && defined(__AVR__) cli(); TCCR3A = 0; TCCR3B = 0; @@ -300,32 +306,10 @@ void setup() { sei(); HEAPnext_time = millis() + 10000; -#else -#if 0 - // - // On the teensy 3 we can raise the speed of SPI here. - // - // Default seen is 0xB8011001. - // - - uint32_t ctar = SPI0_CTAR0; - //printf("SPI_CTAR0 = %8.8X\r\n", ctar); - ctar &= 0x7FFCFFF0; // 1/4 fSYS, 12.5Mhz - //printf("SPI_CTAR0 = %8.8X\r\n", ctar); - ctar |= 0x80000000; // 1/2 fSYS 25Mhz - //printf("SPI_CTAR0 = %8.8X\r\n", ctar); - - uint32_t mcr = SPI0_MCR; - if (mcr & SPI_MCR_MDIS) { - SPI0_CTAR0 = ctar; - } else { - SPI0_MCR = mcr | SPI_MCR_MDIS | SPI_MCR_HALT; - SPI0_CTAR0 = ctar; - SPI0_MCR = mcr; - } #endif +#if defined(__AVR__) + HEAPnext_time = millis() + 10000; #endif - } void serialEvent() { @@ -334,23 +318,23 @@ void serialEvent() { // . to increase by 16, , to decrease by 16 // e to flick VBUS // * to report debug level - if (Serial.available()) { + if(Serial.available()) { int inByte = Serial.read(); - switch (inByte) { + switch(inByte) { case '+': - if (UsbDEBUGlvl < 0xff) UsbDEBUGlvl++; + if(UsbDEBUGlvl < 0xff) UsbDEBUGlvl++; reportlvl = true; break; case '-': - if (UsbDEBUGlvl > 0x00) UsbDEBUGlvl--; + if(UsbDEBUGlvl > 0x00) UsbDEBUGlvl--; reportlvl = true; break; case '.': - if (UsbDEBUGlvl < 0xf0) UsbDEBUGlvl += 16; + if(UsbDEBUGlvl < 0xf0) UsbDEBUGlvl += 16; reportlvl = true; break; case ',': - if (UsbDEBUGlvl > 0x0f) UsbDEBUGlvl -= 16; + if(UsbDEBUGlvl > 0x0f) UsbDEBUGlvl -= 16; reportlvl = true; break; case '*': @@ -367,10 +351,11 @@ void serialEvent() { } } -#if defined(AVR) +#if !defined(CORE_TEENSY) && defined(__AVR__) +// ALL teensy versions LACK PWM ON LED ISR(TIMER3_COMPA_vect) { - if (millis() >= LEDnext_time) { + if((long)(millis() - LEDnext_time) >= 0L) { LEDnext_time = millis() + 30; // set the brightness of LED @@ -380,11 +365,11 @@ ISR(TIMER3_COMPA_vect) { brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: - if (brightness <= 0) { + if(brightness <= 0) { brightness = 0; fadeAmount = -fadeAmount; } - if (brightness >= 255) { + if(brightness >= 255) { brightness = 255; fadeAmount = -fadeAmount; } @@ -404,29 +389,30 @@ void die(FRESULT rc) { void loop() { FIL My_File_Object_x; /* File object */ -#if defined(AVR) +#if defined(__AVR__) // Print a heap status report about every 10 seconds. - if (millis() >= HEAPnext_time) { - if (UsbDEBUGlvl > 0x50) { + if((long)(millis() - HEAPnext_time) >= 0L) { + if(UsbDEBUGlvl > 0x50) { printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap()); } HEAPnext_time = millis() + 10000; } TCCR3B = 0; -#else - // Arm suffers here, oh well... +#endif +#if defined(CORE_TEENSY) + // Teensy suffers here, oh well... serialEvent(); #endif // Horrid! This sort of thing really belongs in an ISR, not here! // We also will be needing to test each hub port, we don't do this yet! - if (!change && !usbon && millis() >= usbon_time) { + if(!change && !usbon && (long)(millis() - usbon_time) >= 0L) { change = true; usbon = true; } - if (change) { + if(change) { change = false; - if (usbon) { + if(usbon) { Usb.vbusPower(vbus_on); printf_P(PSTR("VBUS on\r\n")); } else { @@ -436,21 +422,21 @@ void loop() { } Usb.Task(); current_state = Usb.getUsbTaskState(); - if (current_state != last_state) { - if (UsbDEBUGlvl > 0x50) + if(current_state != last_state) { + if(UsbDEBUGlvl > 0x50) printf_P(PSTR("USB state = %x\r\n"), current_state); -#if defined(AVR) - if (current_state == USB_STATE_RUNNING) { +#if !defined(CORE_TEENSY) && defined(__AVR__) + if(current_state == USB_STATE_RUNNING) { fadeAmount = 30; } #endif - if (current_state == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) { -#if defined(AVR) + if(current_state == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) { +#if !defined(CORE_TEENSY) && defined(__AVR__) fadeAmount = 80; #endif partsready = false; - for (int i = 0; i < cpart; i++) { - if (Fats[i] != NULL) + for(int i = 0; i < cpart; i++) { + if(Fats[i] != NULL) delete Fats[i]; Fats[i] = NULL; } @@ -462,48 +448,48 @@ void loop() { } // only do any of this if usb is on - if (usbon) { - if (partsready && !fatready) { - if (cpart > 0) fatready = true; + if(usbon) { + if(partsready && !fatready) { + if(cpart > 0) fatready = true; } // This is horrible, and needs to be moved elsewhere! - for (int B = 0; B < MAX_USB_MS_DRIVERS; B++) { - if (!partsready && (Bulk[B]->GetAddress() != NULL)) { + for(int B = 0; B < MAX_USB_MS_DRIVERS; B++) { + if(!partsready && (UHS_USB_BulkOnly[B]->GetAddress() != NULL)) { // Build a list. - int ML = Bulk[B]->GetbMaxLUN(); + int ML = UHS_USB_BulkOnly[B]->GetbMaxLUN(); //printf("MAXLUN = %i\r\n", ML); ML++; - for (int i = 0; i < ML; i++) { - if (Bulk[B]->LUNIsGood(i)) { + for(int i = 0; i < ML; i++) { + if(UHS_USB_BulkOnly[B]->LUNIsGood(i)) { partsready = true; ((pvt_t *)(sto[i].private_data))->lun = i; ((pvt_t *)(sto[i].private_data))->B = B; - sto[i].Read = *PRead; - sto[i].Write = *PWrite; - sto[i].Reads = *PReads; - sto[i].Writes = *PWrites; - sto[i].Status = *PStatus; - sto[i].TotalSectors = Bulk[B]->GetCapacity(i); - sto[i].SectorSize = Bulk[B]->GetSectorSize(i); + sto[i].Reads = *UHS_USB_BulkOnly_Read; + sto[i].Writes = *UHS_USB_BulkOnly_Write; + sto[i].Status = *UHS_USB_BulkOnly_Status; + sto[i].Initialize = *UHS_USB_BulkOnly_Initialize; + sto[i].Commit = *UHS_USB_BulkOnly_Commit; + sto[i].TotalSectors = UHS_USB_BulkOnly[B]->GetCapacity(i); + sto[i].SectorSize = UHS_USB_BulkOnly[B]->GetSectorSize(i); printf_P(PSTR("LUN:\t\t%u\r\n"), i); printf_P(PSTR("Total Sectors:\t%08lx\t%lu\r\n"), sto[i].TotalSectors, sto[i].TotalSectors); printf_P(PSTR("Sector Size:\t%04x\t\t%u\r\n"), sto[i].SectorSize, sto[i].SectorSize); // get the partition data... PT = new PCPartition; - if (!PT->Init(&sto[i])) { + if(!PT->Init(&sto[i])) { part_t *apart; - for (int j = 0; j < 4; j++) { + for(int j = 0; j < 4; j++) { apart = PT->GetPart(j); - if (apart != NULL && apart->type != 0x00) { + if(apart != NULL && apart->type != 0x00) { memcpy(&(parts[cpart]), apart, sizeof (part_t)); printf_P(PSTR("Partition %u type %#02x\r\n"), j, parts[cpart].type); // for now - if (isfat(parts[cpart].type)) { + if(isfat(parts[cpart].type)) { Fats[cpart] = new PFAT(&sto[i], cpart, parts[cpart].firstSector); //int r = Fats[cpart]->Good(); - if (Fats[cpart]->MountStatus()) { + if(Fats[cpart]->MountStatus()) { delete Fats[cpart]; Fats[cpart] = NULL; } else cpart++; @@ -514,7 +500,7 @@ void loop() { // try superblock Fats[cpart] = new PFAT(&sto[i], cpart, 0); //int r = Fats[cpart]->Good(); - if (Fats[cpart]->MountStatus()) { + if(Fats[cpart]->MountStatus()) { //printf_P(PSTR("Superblock error %x\r\n"), r); delete Fats[cpart]; Fats[cpart] = NULL; @@ -523,10 +509,9 @@ void loop() { } delete PT; } else { - sto[i].Read = NULL; - sto[i].Write = NULL; sto[i].Writes = NULL; sto[i].Reads = NULL; + sto[i].Initialize = NULL; sto[i].TotalSectors = 0UL; sto[i].SectorSize = 0; } @@ -535,18 +520,18 @@ void loop() { } } - if (fatready) { - if (Fats[0] != NULL) { + if(fatready) { + if(Fats[0] != NULL) { struct Pvt * p; p = ((struct Pvt *)(Fats[0]->storage->private_data)); - if (!Bulk[p->B]->LUNIsGood(p->lun)) { + if(!UHS_USB_BulkOnly[p->B]->LUNIsGood(p->lun)) { // media change -#if defined(AVR) +#if !defined(CORE_TEENSY) && defined(__AVR__) fadeAmount = 80; #endif partsready = false; - for (int i = 0; i < cpart; i++) { - if (Fats[i] != NULL) + for(int i = 0; i < cpart; i++) { + if(Fats[i] != NULL) delete Fats[i]; Fats[cpart] = NULL; } @@ -557,62 +542,64 @@ void loop() { } } - if (fatready) { + if(fatready) { FRESULT rc; /* Result code */ UINT bw, br, i; - - if (!notified) { -#if defined(AVR) + if(!notified) { +#if !defined(CORE_TEENSY) && defined(__AVR__) fadeAmount = 5; #endif notified = true; + FATFS *fs = NULL; + for(int zz = 0; zz < _VOLUMES; zz++) { + if(Fats[zz]->volmap == 0) fs = Fats[zz]->ffs; + } printf_P(PSTR("\r\nOpen an existing file (message.txt).\r\n")); rc = f_open(&My_File_Object_x, "0:/MESSAGE.TXT", FA_READ); - if (rc) printf_P(PSTR("Error %i, message.txt not found.\r\n"), rc); + if(rc) printf_P(PSTR("Error %i, message.txt not found.\r\n"), rc); else { printf_P(PSTR("\r\nType the file content.\r\n")); - for (;;) { + for(;;) { rc = f_read(&My_File_Object_x, My_Buff_x, mbxs, &br); /* Read a chunk of file */ - if (rc || !br) break; /* Error or end of file */ - for (i = 0; i < br; i++) { + if(rc || !br) break; /* Error or end of file */ + for(i = 0; i < br; i++) { /* Type the data */ - if (My_Buff_x[i] == '\n') + if(My_Buff_x[i] == '\n') Serial.write('\r'); - if (My_Buff_x[i] != '\r') + if(My_Buff_x[i] != '\r') Serial.write(My_Buff_x[i]); Serial.flush(); } } - if (rc) { + if(rc) { f_close(&My_File_Object_x); goto out; } printf_P(PSTR("\r\nClose the file.\r\n")); rc = f_close(&My_File_Object_x); - if (rc) goto out; + if(rc) goto out; } printf_P(PSTR("\r\nCreate a new file (hello.txt).\r\n")); rc = f_open(&My_File_Object_x, "0:/Hello.TxT", FA_WRITE | FA_CREATE_ALWAYS); - if (rc) { + if(rc) { die(rc); goto outdir; } printf_P(PSTR("\r\nWrite a text data. (Hello world!)\r\n")); rc = f_write(&My_File_Object_x, "Hello world!\r\n", 14, &bw); - if (rc) { + if(rc) { goto out; } printf_P(PSTR("%u bytes written.\r\n"), bw); printf_P(PSTR("\r\nClose the file.\r\n")); rc = f_close(&My_File_Object_x); - if (rc) { + if(rc) { die(rc); goto out; } -outdir: - { +outdir:{ #if _USE_LFN char lfn[_MAX_LFN + 1]; FILINFO My_File_Info_Object_x; /* File information object */ @@ -621,55 +608,55 @@ outdir: DIR My_Dir_Object_x; /* Directory object */ printf_P(PSTR("\r\nOpen root directory.\r\n")); rc = f_opendir(&My_Dir_Object_x, "0:/"); - if (rc) { + if(rc) { die(rc); goto out; } printf_P(PSTR("\r\nDirectory listing...\r\n")); -#if defined(AVR) +#if defined(__AVR__) printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap()); #endif - for (;;) { + for(;;) { #if _USE_LFN My_File_Info_Object_x.lfsize = _MAX_LFN; #endif rc = f_readdir(&My_Dir_Object_x, &My_File_Info_Object_x); /* Read a directory item */ - if (rc || !My_File_Info_Object_x.fname[0]) break; /* Error or end of dir */ + if(rc || !My_File_Info_Object_x.fname[0]) break; /* Error or end of dir */ - if (My_File_Info_Object_x.fattrib & AM_DIR) { + if(My_File_Info_Object_x.fattrib & AM_DIR) { Serial.write('d'); } else { Serial.write('-'); } Serial.write('r'); - if (My_File_Info_Object_x.fattrib & AM_RDO) { + if(My_File_Info_Object_x.fattrib & AM_RDO) { Serial.write('-'); } else { Serial.write('w'); } - if (My_File_Info_Object_x.fattrib & AM_HID) { + if(My_File_Info_Object_x.fattrib & AM_HID) { Serial.write('h'); } else { Serial.write('-'); } - if (My_File_Info_Object_x.fattrib & AM_SYS) { + if(My_File_Info_Object_x.fattrib & AM_SYS) { Serial.write('s'); } else { Serial.write('-'); } - if (My_File_Info_Object_x.fattrib & AM_ARC) { + if(My_File_Info_Object_x.fattrib & AM_ARC) { Serial.write('a'); } else { Serial.write('-'); } #if _USE_LFN - if (*My_File_Info_Object_x.lfname) + if(*My_File_Info_Object_x.lfname) printf_P(PSTR(" %8lu %s (%s)\r\n"), My_File_Info_Object_x.fsize, My_File_Info_Object_x.fname, My_File_Info_Object_x.lfname); else #endif @@ -677,48 +664,55 @@ outdir: } } out: - if (rc) die(rc); + if(rc) die(rc); + + DISK_IOCTL(fs->drv, CTRL_COMMIT, 0); printf_P(PSTR("\r\nTest completed.\r\n")); } - if (runtest) { + if(runtest) { ULONG ii, wt, rt, start, end; + FATFS *fs = NULL; + for(int zz = 0; zz < _VOLUMES; zz++) { + if(Fats[zz]->volmap == 0) fs = Fats[zz]->ffs; + } runtest = false; f_unlink("0:/10MB.bin"); printf_P(PSTR("\r\nCreate a new 10MB test file (10MB.bin).\r\n")); rc = f_open(&My_File_Object_x, "0:/10MB.bin", FA_WRITE | FA_CREATE_ALWAYS); - if (rc) goto failed; - for (bw = 0; bw < mbxs; bw++) My_Buff_x[bw] = bw & 0xff; + if(rc) goto failed; + for(bw = 0; bw < mbxs; bw++) My_Buff_x[bw] = bw & 0xff; fflush(stdout); start = millis(); - while (start == millis()); - for (ii = 10485760LU / mbxs; ii > 0LU; ii--) { + while(start == millis()); + for(ii = 10485760LU / mbxs; ii > 0LU; ii--) { rc = f_write(&My_File_Object_x, My_Buff_x, mbxs, &bw); - if (rc || !bw) goto failed; + if(rc || !bw) goto failed; } rc = f_close(&My_File_Object_x); - if (rc) goto failed; + if(rc) goto failed; end = millis(); wt = (end - start) - 1; printf_P(PSTR("Time to write 10485760 bytes: %lu ms (%lu sec) \r\n"), wt, (500 + wt) / 1000UL); rc = f_open(&My_File_Object_x, "0:/10MB.bin", FA_READ); fflush(stdout); start = millis(); - while (start == millis()); - if (rc) goto failed; - for (;;) { + while(start == millis()); + if(rc) goto failed; + for(;;) { rc = f_read(&My_File_Object_x, My_Buff_x, mbxs, &bw); /* Read a chunk of file */ - if (rc || !bw) break; /* Error or end of file */ + if(rc || !bw) break; /* Error or end of file */ } end = millis(); - if (rc) goto failed; + if(rc) goto failed; rc = f_close(&My_File_Object_x); - if (rc) goto failed; + if(rc) goto failed; rt = (end - start) - 1; printf_P(PSTR("Time to read 10485760 bytes: %lu ms (%lu sec)\r\nDelete test file\r\n"), rt, (500 + rt) / 1000UL); failed: - if (rc) die(rc); + if(rc) die(rc); + DISK_IOCTL(fs->drv, CTRL_COMMIT, 0); printf_P(PSTR("10MB timing test finished.\r\n")); } } diff --git a/examples/testusbhostFAT/xmem2 b/examples/testusbhostFAT/xmem2 index dd85091a..2bf8f633 160000 --- a/examples/testusbhostFAT/xmem2 +++ b/examples/testusbhostFAT/xmem2 @@ -1 +1 @@ -Subproject commit dd85091abaca7cc6055ff515a5e42f32198380d2 +Subproject commit 2bf8f633e7f9bc5a7bf4c00f3f45c7b79484198e From 05bbfaad6f09baf3e15fbd61ce461b79ab2f0020 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Mon, 2 Jun 2014 10:48:29 -0400 Subject: [PATCH 127/145] Update heads --- examples/testusbhostFAT/RTClib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index 7fd6a306..31e9226c 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit 7fd6a306ca53d08bf53b2bbfc1b80eb056f2c55b +Subproject commit 31e9226c2098f9d516c4fe05befe07f542ee5740 From 7034b2d4aabaa80d67130a09bdb258f372522407 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Mon, 2 Jun 2014 17:37:54 -0400 Subject: [PATCH 128/145] Update heads --- examples/testusbhostFAT/RTClib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index 31e9226c..ce052844 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit 31e9226c2098f9d516c4fe05befe07f542ee5740 +Subproject commit ce052844c99801e4c6248aa5bf11b09c479a1ab6 From 2e4f3ad4da30f5d1d19644228a25dcea106cab42 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Mon, 9 Jun 2014 16:59:14 +0200 Subject: [PATCH 129/145] Updated comment --- PS4BT.h | 1 - 1 file changed, 1 deletion(-) diff --git a/PS4BT.h b/PS4BT.h index 3c0aae12..ff3168a3 100644 --- a/PS4BT.h +++ b/PS4BT.h @@ -58,7 +58,6 @@ protected: /** @name BTHID implementation */ /** * Used to parse Bluetooth HID data. - * @param bthid Pointer to the BTHID class. * @param len The length of the incoming data. * @param buf Pointer to the data buffer. */ From 5f1e4d5b7527fe072317b0b602dbe1e4dec442dc Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 12 Jun 2014 22:31:14 -0400 Subject: [PATCH 130/145] Update heads --- examples/testusbhostFAT/RTClib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index ce052844..ddc8ebef 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit ce052844c99801e4c6248aa5bf11b09c479a1ab6 +Subproject commit ddc8ebef0c311240b3068cdd4c03d64c0e72ee7d From 16689cdf1442e1575e3a66d576b45bd3035f8cbe Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Thu, 12 Jun 2014 23:12:43 -0400 Subject: [PATCH 131/145] Update heads --- examples/testusbhostFAT/RTClib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index ce052844..ddc8ebef 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit ce052844c99801e4c6248aa5bf11b09c479a1ab6 +Subproject commit ddc8ebef0c311240b3068cdd4c03d64c0e72ee7d From 577619552315e815c2ed007ac7076dd7190f3fea Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Tue, 24 Jun 2014 17:46:43 -0400 Subject: [PATCH 132/145] Update heads Tue Jun 24 21:46:25 UTC 2014 --- examples/testusbhostFAT/RTClib | 2 +- examples/testusbhostFAT/generic_storage | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/testusbhostFAT/RTClib b/examples/testusbhostFAT/RTClib index ddc8ebef..b119b97e 160000 --- a/examples/testusbhostFAT/RTClib +++ b/examples/testusbhostFAT/RTClib @@ -1 +1 @@ -Subproject commit ddc8ebef0c311240b3068cdd4c03d64c0e72ee7d +Subproject commit b119b97e1484a08aebcf24e070113d78c82fb023 diff --git a/examples/testusbhostFAT/generic_storage b/examples/testusbhostFAT/generic_storage index 0b8e3076..72b5bf46 160000 --- a/examples/testusbhostFAT/generic_storage +++ b/examples/testusbhostFAT/generic_storage @@ -1 +1 @@ -Subproject commit 0b8e3076b5a072251e01cfc6e6333b364d4e71e7 +Subproject commit 72b5bf467a1c2479ba7354ee4d864e382c167425 From 25117ab9260b64b1870c6982d73bc190e00b0313 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 29 Jun 2014 18:05:50 +0200 Subject: [PATCH 133/145] Added support for the Playstation Buzz controllers See #71 --- PSBuzz.cpp | 82 ++++++++++++++++ PSBuzz.h | 185 +++++++++++++++++++++++++++++++++++++ README.md | 13 ++- controllerEnums.h | 8 ++ examples/PSBuzz/PSBuzz.ino | 46 +++++++++ keywords.txt | 31 ++++++- 6 files changed, 362 insertions(+), 3 deletions(-) create mode 100644 PSBuzz.cpp create mode 100644 PSBuzz.h create mode 100644 examples/PSBuzz/PSBuzz.ino diff --git a/PSBuzz.cpp b/PSBuzz.cpp new file mode 100644 index 00000000..56ae618d --- /dev/null +++ b/PSBuzz.cpp @@ -0,0 +1,82 @@ +/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved. + + This software may be distributed and modified under the terms of the GNU + General Public License version 2 (GPL2) as published by the Free Software + Foundation and appearing in the file GPL2.TXT included in the packaging of + this file. Please note that GPL2 Section 2[b] requires that all works based + on this software must also be made publicly available under the terms of + the GPL2 ("Copyleft"). + + Contact information + ------------------- + + Kristian Lauszus, TKJ Electronics + Web : http://www.tkjelectronics.com + e-mail : kristianl@tkjelectronics.com + */ + +#include "PSBuzz.h" + +// To enable serial debugging see "settings.h" +//#define PRINTREPORT // Uncomment to print the report send by the PS Buzz Controllers + +void PSBuzz::ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { + if (HIDUniversal::VID == PSBUZZ_VID && HIDUniversal::PID == PSBUZZ_PID && len > 0 && buf) { +#ifdef PRINTREPORT + Notify(PSTR("\r\n"), 0x80); + for (uint8_t i = 0; i < len; i++) { + D_PrintHex (buf[i], 0x80); + Notify(PSTR(" "), 0x80); + } +#endif + memcpy(&psbuzzButtons, buf + 2, min(len - 2, sizeof(psbuzzButtons))); + + if (psbuzzButtons.val != oldButtonState.val) { // Check if anything has changed + buttonClickState.val = psbuzzButtons.val & ~oldButtonState.val; // Update click state variable + oldButtonState.val = psbuzzButtons.val; + } + } +}; + +uint8_t PSBuzz::OnInitSuccessful() { + if (HIDUniversal::VID == PSBUZZ_VID && HIDUniversal::PID == PSBUZZ_PID) { + Reset(); + if (pFuncOnInit) + pFuncOnInit(); // Call the user function + else + setLedOnAll(); // Turn the LED on, on all four controllers + }; + return 0; +}; + +bool PSBuzz::getButtonPress(ButtonEnum b, uint8_t controller) { + return psbuzzButtons.val & (1UL << (b + 5 * controller)); // Each controller uses 5 bits, so the value is shifted 5 for each controller +}; + +bool PSBuzz::getButtonClick(ButtonEnum b, uint8_t controller) { + uint32_t mask = (1UL << (b + 5 * controller)); // Each controller uses 5 bits, so the value is shifted 5 for each controller + bool click = buttonClickState.val & mask; + buttonClickState.val &= ~mask; // Clear "click" event + return click; +}; + +// Source: http://www.developerfusion.com/article/84338/making-usb-c-friendly/ and https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c +void PSBuzz::setLedRaw(bool value, uint8_t controller) { + ledState[controller] = value; // Save value for next time it is called + + uint8_t buf[7]; + buf[0] = 0x00; + buf[1] = ledState[0] ? 0xFF : 0x00; + buf[2] = ledState[1] ? 0xFF : 0x00; + buf[3] = ledState[2] ? 0xFF : 0x00; + buf[4] = ledState[3] ? 0xFF : 0x00; + buf[5] = 0x00; + buf[6] = 0x00; + + PSBuzz_Command(buf, sizeof(buf)); +}; + +void PSBuzz::PSBuzz_Command(uint8_t *data, uint16_t nbytes) { + // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x00), Report Type (Output 0x02), interface (0x00), datalength, datalength, data) + pUsb->ctrlReq(bAddress, epInfo[0].epAddr, bmREQ_HIDOUT, HID_REQUEST_SET_REPORT, 0x00, 0x02, 0x00, nbytes, nbytes, data, NULL); +}; \ No newline at end of file diff --git a/PSBuzz.h b/PSBuzz.h new file mode 100644 index 00000000..1d7859d2 --- /dev/null +++ b/PSBuzz.h @@ -0,0 +1,185 @@ +/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved. + + This software may be distributed and modified under the terms of the GNU + General Public License version 2 (GPL2) as published by the Free Software + Foundation and appearing in the file GPL2.TXT included in the packaging of + this file. Please note that GPL2 Section 2[b] requires that all works based + on this software must also be made publicly available under the terms of + the GPL2 ("Copyleft"). + + Contact information + ------------------- + + Kristian Lauszus, TKJ Electronics + Web : http://www.tkjelectronics.com + e-mail : kristianl@tkjelectronics.com + */ + +#ifndef _psbuzz_h_ +#define _psbuzz_h_ + +#include "hiduniversal.h" +#include "controllerEnums.h" + +#define PSBUZZ_VID 0x054C // Sony Corporation +#define PSBUZZ_PID 0x1000 // PS Buzz Controller + +/** Struct used to easily read the different buttons on the controllers */ +union PSBUZZButtons { + struct { + uint8_t red : 1; + uint8_t yellow : 1; + uint8_t green : 1; + uint8_t orange : 1; + uint8_t blue : 1; + } __attribute__((packed)) btn[4]; + uint32_t val : 20; +} __attribute__((packed)); + +/** + * This class implements support for the PS Buzz controllers via USB. + * It uses the HIDUniversal class for all the USB communication. + */ +class PSBuzz : public HIDUniversal { +public: + /** + * Constructor for the PSBuzz class. + * @param p Pointer to the USB class instance. + */ + PSBuzz(USB *p) : + HIDUniversal(p) { + Reset(); + }; + + /** + * Used to check if a PS Buzz controller is connected. + * @return Returns true if it is connected. + */ + bool connected() { + return HIDUniversal::isReady() && HIDUniversal::VID == PSBUZZ_VID && HIDUniversal::PID == PSBUZZ_PID; + }; + + /** + * Used to call your own function when the device is successfully initialized. + * @param funcOnInit Function to call. + */ + void attachOnInit(void (*funcOnInit)(void)) { + pFuncOnInit = funcOnInit; + }; + + /** @name PS Buzzer Controller functions */ + /** + * getButtonPress(ButtonEnum b) will return true as long as the button is held down. + * + * While getButtonClick(ButtonEnum b) will only return it once. + * + * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b), + * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b). + * @param b ::ButtonEnum to read. + * @param controller The controller to read from. Default to 0. + * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press. + */ + bool getButtonPress(ButtonEnum b, uint8_t controller = 0); + bool getButtonClick(ButtonEnum b, uint8_t controller = 0); + /**@}*/ + /** @name PS Buzzer Controller functions */ + /** + * Set LED value without using ::LEDEnum. + * @param value See: ::LEDEnum. + */ + /** + * Set LED values directly. + * @param value Used to set whenever the LED should be on or off + * @param controller The controller to control. Defaults to 0. + */ + void setLedRaw(bool value, uint8_t controller = 0); + + /** Turn all LEDs off. */ + void setLedOffAll() { + for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw + ledState[i] = false; // Just an easy way to set all four off at the same time + setLedRaw(false); // Turn the LED off, on all four controllers + }; + + /** + * Turn the LED off on a specific controller. + * @param controller The controller to turn off. Defaults to 0. + */ + void setLedOff(uint8_t controller = 0) { + setLedRaw(false, controller); + }; + + + /** Turn all LEDs on. */ + void setLedOnAll() { + for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw + ledState[i] = true; // Just an easy way to set all four off at the same time + setLedRaw(true); // Turn the LED on, on all four controllers + }; + + /** + * Turn the LED on on a specific controller. + * @param controller The controller to turn off. Defaults to 0. + */ + void setLedOn(uint8_t controller = 0) { + setLedRaw(true, controller); + }; + + /** + * Toggle the LED on a specific controller. + * @param controller The controller to turn off. Defaults to 0. + */ + void setLedToggle(uint8_t controller = 0) { + setLedRaw(!ledState[controller], controller); + }; + /**@}*/ + +protected: + /** @name HIDUniversal implementation */ + /** + * Used to parse USB HID data. + * @param hid Pointer to the HID class. + * @param is_rpt_id Only used for Hubs. + * @param len The length of the incoming data. + * @param buf Pointer to the data buffer. + */ + virtual void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf); + + /** + * Called when a device is successfully initialized. + * Use attachOnInit(void (*funcOnInit)(void)) to call your own function. + * This is useful for instance if you want to set the LEDs in a specific way. + */ + virtual uint8_t OnInitSuccessful(); + /**@}*/ + + /** Used to reset the different buffers to their default values */ + void Reset() { + psbuzzButtons.val = 0; + oldButtonState.val = 0; + buttonClickState.val = 0; + for (uint8_t i = 0; i < sizeof(ledState); i++) + ledState[i] = 0; + }; + + /** @name USBDeviceConfig implementation */ + /** + * Used by the USB core to check what this driver support. + * @param vid The device's VID. + * @param pid The device's PID. + * @return Returns true if the device's VID and PID matches this driver. + */ + virtual boolean VIDPIDOK(uint16_t vid, uint16_t pid) { + return (vid == PSBUZZ_VID && pid == PSBUZZ_PID); + }; + /**@}*/ + +private: + void (*pFuncOnInit)(void); // Pointer to function called in onInit() + + void PSBuzz_Command(uint8_t *data, uint16_t nbytes); + + PSBUZZButtons psbuzzButtons, oldButtonState, buttonClickState; + bool ledState[4]; +}; +#endif \ No newline at end of file diff --git a/README.md b/README.md index 35a786e5..2fc7305c 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ For more information about the hardware see the [Hardware Manual](http://www.cir * __Alexei Glushchenko, Circuits@Home__ - * Developers of the USB Core, HID, FTDI, ADK, ACM, and PL2303 libraries * __Kristian Lauszus, TKJ Electronics__ - - * Developer of the [BTD](#bluetooth-libraries), [BTHID](#bthid-library), [SPP](#spp-library), [PS4](#ps4-library), [PS3](#ps3-library), [Wii](#wii-library), and [Xbox](#xbox-library) libraries + * 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 * __Andrew Kroll__ - * Major contributor to mass storage code @@ -240,6 +240,17 @@ All the information about the Wii controllers are from these sites: * * The old library created by _Tomoyuki Tanaka_: also helped a lot. +### [PS Buzz Library](PSBuzz.cpp) + +This library implements support for the Playstation Buzz controllers via USB. + +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. + +More information about the controller can be found at the following sites: + +* http://www.developerfusion.com/article/84338/making-usb-c-friendly/ +* https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c + # FAQ > When I plug my device into the USB connector nothing happens? diff --git a/controllerEnums.h b/controllerEnums.h index 295b6ae4..0169c763 100644 --- a/controllerEnums.h +++ b/controllerEnums.h @@ -137,6 +137,14 @@ enum ButtonEnum { BLACK = 8, // Available on the original Xbox controller WHITE = 9, // Available on the original Xbox controller /**@}*/ + + /** PS Buzz controllers */ + RED = 0, + YELLOW = 1, + GREEN = 2, + ORANGE = 3, + BLUE = 4, + /**@}*/ }; /** Joysticks on the PS3 and Xbox controllers. */ diff --git a/examples/PSBuzz/PSBuzz.ino b/examples/PSBuzz/PSBuzz.ino new file mode 100644 index 00000000..6944cb6b --- /dev/null +++ b/examples/PSBuzz/PSBuzz.ino @@ -0,0 +1,46 @@ +/* + Example sketch for the Playstation Buzz library - developed by Kristian Lauszus + For more information visit my blog: http://blog.tkjelectronics.dk/ or + send me an e-mail: kristianl@tkjelectronics.com + */ + +#include + +// Satisfy IDE, which only needs to see the include statment in the ino. +#ifdef dobogusinclude +#include +#endif + +USB Usb; +PSBuzz Buzz(&Usb); + +void setup() { + Serial.begin(115200); + while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection + if (Usb.Init() == -1) { + Serial.print(F("\r\nOSC did not start")); + while (1); // Halt + } + Serial.println(F("\r\nPS Buzz Library Started")); +} + +void loop() { + Usb.Task(); + + if (Buzz.connected()) { + for (uint8_t i = 0; i < 4; i++) { + if (Buzz.getButtonClick(RED, i)) { + Buzz.setLedToggle(i); // Toggle the LED + Serial.println(F("RED")); + } + if (Buzz.getButtonClick(YELLOW, i)) + Serial.println(F("YELLOW")); + if (Buzz.getButtonClick(GREEN, i)) + Serial.println(F("GREEN")); + if (Buzz.getButtonClick(ORANGE, i)) + Serial.println(F("ORANGE")); + if (Buzz.getButtonClick(BLUE, i)) + Serial.println(F("BLUE")); + } + } +} diff --git a/keywords.txt b/keywords.txt index 58496f4b..c7bd007c 100644 --- a/keywords.txt +++ b/keywords.txt @@ -318,7 +318,7 @@ getIRy4 KEYWORD2 getIRs4 KEYWORD2 #################################################### -# Syntax Coloring Map For RFCOMM/SPP Library +# Syntax Coloring Map For BTHID Library #################################################### #################################################### @@ -331,4 +331,31 @@ BTHID KEYWORD1 # Methods and Functions (KEYWORD2) #################################################### SetReportParser KEYWORD2 -setProtocolMode KEYWORD2 \ No newline at end of file +setProtocolMode KEYWORD2 + +#################################################### +# Syntax Coloring Map For PS Buzz Library +#################################################### + +#################################################### +# Datatypes (KEYWORD1) +#################################################### + +PSBuzz KEYWORD1 + +#################################################### +# Methods and Functions (KEYWORD2) +#################################################### + +setLedOnAll KEYWORD2 +setLedOffAll KEYWORD2 + +#################################################### +# Constants and enums (LITERAL1) +#################################################### + +RED LITERAL1 +YELLOW LITERAL1 +GREEN LITERAL1 +ORANGE LITERAL1 +BLUE LITERAL1 \ No newline at end of file From dd600b489521dbf0102dd4f6135fdda6e4a42df3 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 29 Jun 2014 18:06:27 +0200 Subject: [PATCH 134/145] Don't print incoming serial data if debugging is on by default --- hiduniversal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hiduniversal.cpp b/hiduniversal.cpp index ad1ad190..e7a65e39 100644 --- a/hiduniversal.cpp +++ b/hiduniversal.cpp @@ -398,7 +398,7 @@ uint8_t HIDUniversal::Poll() { if(identical) return 0; -#if 1 +#if 0 Notify(PSTR("\r\nBuf: "), 0x80); for(uint8_t i = 0; i < read; i++) { From 6152175f487ad6c1d20ce6fa7e1e9955762fa812 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 29 Jun 2014 18:11:45 +0200 Subject: [PATCH 135/145] Added link to PSBuzz example --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2fc7305c..f9d0db0f 100644 --- a/README.md +++ b/README.md @@ -246,6 +246,8 @@ This library implements support for the Playstation Buzz controllers via USB. 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. +The example [PSBuzz.ino](examples/PSBuzz/PSBuzz.ino) shows how one can do this with just a few lines of code. + More information about the controller can be found at the following sites: * http://www.developerfusion.com/article/84338/making-usb-c-friendly/ From e78d880bb481edeff5a607f60e026e43521533c3 Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Mon, 30 Jun 2014 12:54:16 -0400 Subject: [PATCH 136/145] Update heads Mon Jun 30 16:53:58 UTC 2014 --- examples/testusbhostFAT/Arduino_Makefile_master | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testusbhostFAT/Arduino_Makefile_master b/examples/testusbhostFAT/Arduino_Makefile_master index d35bb955..1edd5f46 160000 --- a/examples/testusbhostFAT/Arduino_Makefile_master +++ b/examples/testusbhostFAT/Arduino_Makefile_master @@ -1 +1 @@ -Subproject commit d35bb955e3818f0c14e47c8a1998003da8dc1b5a +Subproject commit 1edd5f46188a6c4b68d6f9120fa72359a12e38f1 From c589731974816a5a145f1db800b515c4e33f0be4 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 1 Jul 2014 11:31:45 +0200 Subject: [PATCH 137/145] Added "Interface modifications" section to readme --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index f9d0db0f..21d3eaf5 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,26 @@ More information about the controller can be found at the following sites: * http://www.developerfusion.com/article/84338/making-usb-c-friendly/ * https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c +# Interface modifications + +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. + +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. + +After that you need modify the following entry in [UsbCore.h](UsbCore.h): + +```C++ +typedef MAX3421e MAX3421E; +``` + +For instance if you have rerouted SS to pin 7 it should read: + +```C++ +typedef MAX3421e MAX3421E; +``` + +See the "Interface modifications" section in the [hardware manual](https://www.circuitsathome.com/usb-host-shield-hardware-manual) for more information. + # FAQ > When I plug my device into the USB connector nothing happens? From efeb80855ec8cf64d31d140daf61c321e1550b45 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 1 Jul 2014 11:47:39 +0200 Subject: [PATCH 138/145] Added table of contents --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index 21d3eaf5..edb440a2 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,26 @@ For more information about the hardware see the [Hardware Manual](http://www.cir * __Andrew Kroll__ - * Major contributor to mass storage code +# Table of Contents + +* [How to include the library](#how-to-include-the-library) +* [How to use the library](#how-to-use-the-library) + * [Documentation](#documentation) + * [Enable debugging](#enable-debugging) + * [Boards](#boards) + * [Bluetooth libraries](#bluetooth-libraries) + * [BTHID library](#bthid-library) + * [SPP library](#spp-library) + * [PS4 Library](#ps4-library) + * [PS3 Library](#ps3-library) + * [Xbox Libraries](#xbox-libraries) + * [Xbox library](#xbox-library) + * [Xbox 360 Library](#xbox-360-library) + * [Wii library](#wii-library) + * [PS Buzz Library](#ps-buzz-library) +* [Interface modifications](#interface-modifications) +* [FAQ](#faq) + # How to include the library First download the library by clicking on the following link: . From 4a44c8f0392926c75ec539c7bc8d1f44c1b95b17 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 1 Jul 2014 13:17:56 +0200 Subject: [PATCH 139/145] Implemented VIDPIDOK in PS4USB --- PS4USB.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/PS4USB.h b/PS4USB.h index ea38455a..16dabad4 100644 --- a/PS4USB.h +++ b/PS4USB.h @@ -112,6 +112,18 @@ protected: }; /**@}*/ + /** @name USBDeviceConfig implementation */ + /** + * Used by the USB core to check what this driver support. + * @param vid The device's VID. + * @param pid The device's PID. + * @return Returns true if the device's VID and PID matches this driver. + */ + virtual boolean VIDPIDOK(uint16_t vid, uint16_t pid) { + return (vid == PS4_VID && pid == PS4_PID); + }; + /**@}*/ + private: void (*pFuncOnInit)(void); // Pointer to function called in onInit() }; From b82835c877adecf507312b742dd687e2ea03628f Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 1 Jul 2014 13:22:44 +0200 Subject: [PATCH 140/145] Break for loop if HID device is found --- BTD.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/BTD.cpp b/BTD.cpp index 2506cdf1..de83da95 100755 --- a/BTD.cpp +++ b/BTD.cpp @@ -464,6 +464,7 @@ void BTD::HCI_event_task() { disc_bdaddr[j] = hcibuf[j + 3 + 6 * i]; hci_set_flag(HCI_FLAG_DEVICE_FOUND); + break; } #ifdef EXTRADEBUG else { From 35bb596601954d80e03569f858e4ad6ce264adb8 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 1 Jul 2014 13:43:45 +0200 Subject: [PATCH 141/145] Cleaned up SPPMulti example --- examples/Bluetooth/SPPMulti/SPPMulti.ino | 33 ++++++++++-------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/examples/Bluetooth/SPPMulti/SPPMulti.ino b/examples/Bluetooth/SPPMulti/SPPMulti.ino index 262a2927..0304257e 100644 --- a/examples/Bluetooth/SPPMulti/SPPMulti.ino +++ b/examples/Bluetooth/SPPMulti/SPPMulti.ino @@ -6,7 +6,7 @@ #include #include -// Satisfy IDE, which only needs to see the include statment in the ino. +// Satisfy IDE, which only needs to see the include statement in the ino. #ifdef dobogusinclude #include #endif @@ -15,10 +15,11 @@ USB Usb; //USBHub Hub1(&Usb); // Some dongles have a hub inside BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so -SPP *SerialBT[2]; // We will use this pointer to store the two instance, you can easily make it larger if you like, but it will use a lot of RAM! -const uint8_t length = sizeof(SerialBT) / sizeof(SerialBT[0]); // Get the lenght of the array + +const uint8_t length = 2; // Set the number of instances here +SPP *SerialBT[length]; // We will use this pointer to store the instances, you can easily make it larger if you like, but it will use a lot of RAM! + boolean firstMessage[length] = { true }; // Set all to true -uint8_t buffer[50]; void setup() { for (uint8_t i = 0; i < length; i++) @@ -28,10 +29,11 @@ void setup() { while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection if (Usb.Init() == -1) { Serial.print(F("\r\nOSC did not start")); - while (1); //halt + while (1); // Halt } Serial.print(F("\r\nSPP Bluetooth Library Started")); } + void loop() { Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well @@ -47,22 +49,15 @@ void loop() { else firstMessage[i] = true; } + + // Set the connection you want to send to using the first character + // For instance "0Hello World" would send "Hello World" to connection 0 if (Serial.available()) { delay(10); // Wait for the rest of the data to arrive - uint8_t i = 0; - while (Serial.available() && i < sizeof(buffer)) // Read the data - buffer[i++] = Serial.read(); - /* - Set the connection you want to send to using the first character - For instace "0Hello World" would send "Hello World" to connection 0 - */ - uint8_t id = buffer[0] - '0'; // Convert from ASCII - if (id < length && i > 1) { // And then compare to length and make sure there is any text - if (SerialBT[id]->connected) { // Check if a device is actually connected - for (uint8_t i2 = 0; i2 < i - 1; i2++) // Don't include the first character - buffer[i2] = buffer[i2 + 1]; - SerialBT[id]->write(buffer, i - 1); // Send the data - } + uint8_t id = Serial.read() - '0'; // Convert from ASCII + if (id < length && SerialBT[id]->connected) { // Make sure that the id is valid and make sure that a device is actually connected + while (Serial.available()) // Check if data is available + SerialBT[id]->write(Serial.read()); // Send the data } } } From 6a9e574bf2b86f54050009ec128dca40947ccec7 Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 22 Apr 2014 16:54:41 +0200 Subject: [PATCH 142/145] Added comments for "SDP_ServiceSearchAttributeResponse" --- SPP.cpp | 155 ++++++++++++++++++++++++++++++-------------------------- 1 file changed, 84 insertions(+), 71 deletions(-) diff --git a/SPP.cpp b/SPP.cpp index ef0cf216..562a68ca 100644 --- a/SPP.cpp +++ b/SPP.cpp @@ -538,15 +538,15 @@ void SPP::serviceNotSupported(uint8_t transactionIDHigh, uint8_t transactionIDLo l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU; l2capoutbuf[1] = transactionIDHigh; l2capoutbuf[2] = transactionIDLow; - l2capoutbuf[3] = 0x00; // Parameter Length - l2capoutbuf[4] = 0x05; // Parameter Length - l2capoutbuf[5] = 0x00; // AttributeListsByteCount - l2capoutbuf[6] = 0x02; // AttributeListsByteCount + l2capoutbuf[3] = 0x00; // MSB Parameter Length + l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5 + l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount + l2capoutbuf[6] = 0x02; // LSB AttributeListsByteCount = 2 /* Attribute ID/Value Sequence: */ - l2capoutbuf[7] = 0x35; - l2capoutbuf[8] = 0x00; - l2capoutbuf[9] = 0x00; + l2capoutbuf[7] = 0x35; // Data element sequence - length in next byte + l2capoutbuf[8] = 0x00; // Length = 0 + l2capoutbuf[9] = 0x00; // No continuation state SDP_Command(l2capoutbuf, 10); } @@ -555,56 +555,60 @@ void SPP::serialPortResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLo l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU; l2capoutbuf[1] = transactionIDHigh; l2capoutbuf[2] = transactionIDLow; - l2capoutbuf[3] = 0x00; // Parameter Length - l2capoutbuf[4] = 0x2B; // Parameter Length - l2capoutbuf[5] = 0x00; // AttributeListsByteCount - l2capoutbuf[6] = 0x26; // AttributeListsByteCount + l2capoutbuf[3] = 0x00; // MSB Parameter Length + l2capoutbuf[4] = 0x2B; // LSB Parameter Length = 43 + l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount + l2capoutbuf[6] = 0x26; // LSB AttributeListsByteCount = 38 /* Attribute ID/Value Sequence: */ - l2capoutbuf[7] = 0x36; - l2capoutbuf[8] = 0x00; - l2capoutbuf[9] = 0x3C; - l2capoutbuf[10] = 0x36; - l2capoutbuf[11] = 0x00; + l2capoutbuf[7] = 0x36; // Data element sequence - length in next two bytes + l2capoutbuf[8] = 0x00; // MSB Length + l2capoutbuf[9] = 0x3C; // LSB Length = 60 - l2capoutbuf[12] = 0x39; - l2capoutbuf[13] = 0x09; - l2capoutbuf[14] = 0x00; - l2capoutbuf[15] = 0x00; - l2capoutbuf[16] = 0x0A; - l2capoutbuf[17] = 0x00; + l2capoutbuf[10] = 0x36; // Data element sequence - length in next two bytes + l2capoutbuf[11] = 0x00; // MSB Length + l2capoutbuf[12] = 0x39; // LSB Length = 57 + + l2capoutbuf[13] = 0x09; // Unsigned Integer - length 2 bytes + l2capoutbuf[14] = 0x00; // MSB ServiceRecordHandle + l2capoutbuf[15] = 0x00; // LSB ServiceRecordHandle + l2capoutbuf[16] = 0x0A; // Unsigned int - length 4 bytes + l2capoutbuf[17] = 0x00; // ServiceRecordHandle value - TODO: Is this related to HCI_Handle? l2capoutbuf[18] = 0x01; l2capoutbuf[19] = 0x00; l2capoutbuf[20] = 0x06; - l2capoutbuf[21] = 0x09; - l2capoutbuf[22] = 0x00; - l2capoutbuf[23] = 0x01; - l2capoutbuf[24] = 0x35; - l2capoutbuf[25] = 0x03; - l2capoutbuf[26] = 0x19; - l2capoutbuf[27] = 0x11; - l2capoutbuf[28] = 0x01; - l2capoutbuf[29] = 0x09; - l2capoutbuf[30] = 0x00; - l2capoutbuf[31] = 0x04; - l2capoutbuf[32] = 0x35; - l2capoutbuf[33] = 0x0C; - l2capoutbuf[34] = 0x35; - l2capoutbuf[35] = 0x03; - l2capoutbuf[36] = 0x19; - l2capoutbuf[37] = 0x01; - l2capoutbuf[38] = 0x00; - l2capoutbuf[39] = 0x35; - l2capoutbuf[40] = 0x05; - l2capoutbuf[41] = 0x19; - l2capoutbuf[42] = 0x00; - l2capoutbuf[43] = 0x03; + l2capoutbuf[21] = 0x09; // Unsigned Integer - length 2 bytes + l2capoutbuf[22] = 0x00; // MSB ServiceClassIDList + l2capoutbuf[23] = 0x01; // LSB ServiceClassIDList + l2capoutbuf[24] = 0x35; // Data element sequence - length in next byte + l2capoutbuf[25] = 0x03; // Length = 3 + l2capoutbuf[26] = 0x19; // UUID (universally unique identifier) - length = 2 bytes + l2capoutbuf[27] = 0x11; // MSB SerialPort + l2capoutbuf[28] = 0x01; // LSB SerialPort - l2capoutbuf[44] = 0x08; - l2capoutbuf[45] = 0x02; // Two extra bytes - l2capoutbuf[46] = 0x00; // 25 (0x19) more bytes to come - l2capoutbuf[47] = 0x19; + l2capoutbuf[29] = 0x09; // Unsigned Integer - length 2 bytes + l2capoutbuf[30] = 0x00; // MSB ProtocolDescriptorList + l2capoutbuf[31] = 0x04; // LSB ProtocolDescriptorList + l2capoutbuf[32] = 0x35; // Data element sequence - length in next byte + l2capoutbuf[33] = 0x0C; // Length = 12 + + l2capoutbuf[34] = 0x35; // Data element sequence - length in next byte + l2capoutbuf[35] = 0x03; // Length = 3 + l2capoutbuf[36] = 0x19; // UUID (universally unique identifier) - length = 2 bytes + l2capoutbuf[37] = 0x01; // MSB L2CAP + l2capoutbuf[38] = 0x00; // LSB L2CAP + + l2capoutbuf[39] = 0x35; // Data element sequence - length in next byte + l2capoutbuf[40] = 0x05; // Length = 5 + l2capoutbuf[41] = 0x19; // UUID (universally unique identifier) - length = 2 bytes + l2capoutbuf[42] = 0x00; // MSB RFCOMM + l2capoutbuf[43] = 0x03; // LSB RFCOMM + l2capoutbuf[44] = 0x08; // Unsigned Integer - length 1 byte + + l2capoutbuf[45] = 0x02; // ContinuationState - Two more bytes + l2capoutbuf[46] = 0x00; // MSB length + l2capoutbuf[47] = 0x19; // LSB length = 25 more bytes to come SDP_Command(l2capoutbuf, 48); } @@ -613,40 +617,49 @@ void SPP::serialPortResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLo l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU; l2capoutbuf[1] = transactionIDHigh; l2capoutbuf[2] = transactionIDLow; - l2capoutbuf[3] = 0x00; // Parameter Length - l2capoutbuf[4] = 0x1C; // Parameter Length - l2capoutbuf[5] = 0x00; // AttributeListsByteCount - l2capoutbuf[6] = 0x19; // AttributeListsByteCount + l2capoutbuf[3] = 0x00; // MSB Parameter Length + l2capoutbuf[4] = 0x1C; // LSB Parameter Length = 28 + l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount + l2capoutbuf[6] = 0x19; // LSB AttributeListsByteCount = 25 /* Attribute ID/Value Sequence: */ - l2capoutbuf[7] = 0x01; - l2capoutbuf[8] = 0x09; - l2capoutbuf[9] = 0x00; - l2capoutbuf[10] = 0x06; - l2capoutbuf[11] = 0x35; + l2capoutbuf[7] = 0x01; // Channel 1 - TODO: Try different values, so multiple servers can be used at once - l2capoutbuf[12] = 0x09; - l2capoutbuf[13] = 0x09; - l2capoutbuf[14] = 0x65; - l2capoutbuf[15] = 0x6E; - l2capoutbuf[16] = 0x09; - l2capoutbuf[17] = 0x00; - l2capoutbuf[18] = 0x6A; - l2capoutbuf[19] = 0x09; + l2capoutbuf[8] = 0x09; // Unsigned Integer - length 2 bytes + l2capoutbuf[9] = 0x00; // MSB LanguageBaseAttributeIDList + l2capoutbuf[10] = 0x06; // LSB LanguageBaseAttributeIDList + l2capoutbuf[11] = 0x35; // Data element sequence - length in next byte + l2capoutbuf[12] = 0x09; // Length = 9 + + // Identifier representing the natural language = en = English - see: "ISO 639:1988" + l2capoutbuf[13] = 0x09; // Unsigned Integer - length 2 bytes + l2capoutbuf[14] = 0x65; // 'e' + l2capoutbuf[15] = 0x6E; // 'n' + + // "The second element of each triplet contains an identifier that specifies a character encoding used for the language" + // Encoding is set to 106 (UTF-8) - see: http://www.iana.org/assignments/character-sets/character-sets.xhtml + l2capoutbuf[16] = 0x09; // Unsigned Integer - length 2 bytes + l2capoutbuf[17] = 0x00; // MSB of character encoding + l2capoutbuf[18] = 0x6A; // LSB of character encoding (106) + + // Attribute ID that serves as the base attribute ID for the natural language in the service record + // "To facilitate the retrieval of human-readable universal attributes in a principal language, the base attribute ID value for the primary language supported by a service record shall be 0x0100" + l2capoutbuf[19] = 0x09; // Unsigned Integer - length 2 bytes l2capoutbuf[20] = 0x01; l2capoutbuf[21] = 0x00; - l2capoutbuf[22] = 0x09; - l2capoutbuf[23] = 0x01; - l2capoutbuf[24] = 0x00; - l2capoutbuf[25] = 0x25; + l2capoutbuf[22] = 0x09; // Unsigned Integer - length 2 bytes + l2capoutbuf[23] = 0x01; // MSB ServiceDescription + l2capoutbuf[24] = 0x00; // LSB ServiceDescription + + l2capoutbuf[25] = 0x25; // Text string - length in next byte l2capoutbuf[26] = 0x05; // Name length l2capoutbuf[27] = 'T'; l2capoutbuf[28] = 'K'; l2capoutbuf[29] = 'J'; l2capoutbuf[30] = 'S'; l2capoutbuf[31] = 'P'; - l2capoutbuf[32] = 0x00; // No more data + l2capoutbuf[32] = 0x00; // No continuation state SDP_Command(l2capoutbuf, 33); } From f349d61dfcbe44661f72bbcc25b4b4b59db8e42a Mon Sep 17 00:00:00 2001 From: "Andrew J. Kroll" Date: Sat, 26 Jul 2014 18:41:25 -0400 Subject: [PATCH 143/145] Update heads Sat Jul 26 22:41:08 UTC 2014 --- examples/testusbhostFAT/Arduino_Makefile_master | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/testusbhostFAT/Arduino_Makefile_master b/examples/testusbhostFAT/Arduino_Makefile_master index 1edd5f46..7ada91a9 160000 --- a/examples/testusbhostFAT/Arduino_Makefile_master +++ b/examples/testusbhostFAT/Arduino_Makefile_master @@ -1 +1 @@ -Subproject commit 1edd5f46188a6c4b68d6f9120fa72359a12e38f1 +Subproject commit 7ada91a90027ccb7558b74087fb68d3940ecf64d From 94353f1720ce09b9847933e90c0b7e072cc2945f Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Sun, 3 Aug 2014 17:52:47 +0200 Subject: [PATCH 144/145] Added missing pins defines for Arduino Due --- avrpins.h | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/avrpins.h b/avrpins.h index 6e074b65..c59e9c52 100644 --- a/avrpins.h +++ b/avrpins.h @@ -861,11 +861,87 @@ public: \ } \ }; -MAKE_PIN(P9, PIOC, PIO_PC21); // INT -MAKE_PIN(P10, PIOC, PIO_PC29); // SS +// See: http://arduino.cc/en/Hacking/PinMappingSAM3X and variant.cpp + +MAKE_PIN(P0, PIOA, PIO_PA8); +MAKE_PIN(P1, PIOA, PIO_PA9); +MAKE_PIN(P2, PIOB, PIO_PB25); +MAKE_PIN(P3, PIOC, PIO_PC28); +MAKE_PIN(P4, PIOC, PIO_PC26); +MAKE_PIN(P5, PIOC, PIO_PC25); +MAKE_PIN(P6, PIOC, PIO_PC24); +MAKE_PIN(P7, PIOC, PIO_PC23); +MAKE_PIN(P8, PIOC, PIO_PC22); +MAKE_PIN(P9, PIOC, PIO_PC21); +MAKE_PIN(P10, PIOC, PIO_PC29); +MAKE_PIN(P11, PIOD, PIO_PD7); +MAKE_PIN(P12, PIOD, PIO_PD8); +MAKE_PIN(P13, PIOB, PIO_PB27); +MAKE_PIN(P14, PIOD, PIO_PD4); +MAKE_PIN(P15, PIOD, PIO_PD5); +MAKE_PIN(P16, PIOA, PIO_PA13); +MAKE_PIN(P17, PIOA, PIO_PA12); +MAKE_PIN(P18, PIOA, PIO_PA11); +MAKE_PIN(P19, PIOA, PIO_PA10); +MAKE_PIN(P20, PIOB, PIO_PB12); +MAKE_PIN(P21, PIOB, PIO_PB13); +MAKE_PIN(P22, PIOB, PIO_PB26); +MAKE_PIN(P23, PIOA, PIO_PA14); +MAKE_PIN(P24, PIOA, PIO_PA15); +MAKE_PIN(P25, PIOD, PIO_PD0); +MAKE_PIN(P26, PIOD, PIO_PD1); +MAKE_PIN(P27, PIOD, PIO_PD2); +MAKE_PIN(P28, PIOD, PIO_PD3); +MAKE_PIN(P29, PIOD, PIO_PD6); +MAKE_PIN(P30, PIOD, PIO_PD9); +MAKE_PIN(P31, PIOA, PIO_PA7); +MAKE_PIN(P32, PIOD, PIO_PD10); +MAKE_PIN(P33, PIOC, PIO_PC1); +MAKE_PIN(P34, PIOC, PIO_PC2); +MAKE_PIN(P35, PIOC, PIO_PC3); +MAKE_PIN(P36, PIOC, PIO_PC4); +MAKE_PIN(P37, PIOC, PIO_PC5); +MAKE_PIN(P38, PIOC, PIO_PC6); +MAKE_PIN(P39, PIOC, PIO_PC7); +MAKE_PIN(P40, PIOC, PIO_PC8); +MAKE_PIN(P41, PIOC, PIO_PC9); +MAKE_PIN(P42, PIOA, PIO_PA19); +MAKE_PIN(P43, PIOA, PIO_PA20); +MAKE_PIN(P44, PIOC, PIO_PC19); +MAKE_PIN(P45, PIOC, PIO_PC18); +MAKE_PIN(P46, PIOC, PIO_PC17); +MAKE_PIN(P47, PIOC, PIO_PC16); +MAKE_PIN(P48, PIOC, PIO_PC15); +MAKE_PIN(P49, PIOC, PIO_PC14); +MAKE_PIN(P50, PIOC, PIO_PC13); +MAKE_PIN(P51, PIOC, PIO_PC12); +MAKE_PIN(P52, PIOB, PIO_PB21); +MAKE_PIN(P53, PIOB, PIO_PB14); +MAKE_PIN(P54, PIOA, PIO_PA16); +MAKE_PIN(P55, PIOA, PIO_PA24); +MAKE_PIN(P56, PIOA, PIO_PA23); +MAKE_PIN(P57, PIOA, PIO_PA22); +MAKE_PIN(P58, PIOA, PIO_PA6); +MAKE_PIN(P59, PIOA, PIO_PA4); +MAKE_PIN(P60, PIOA, PIO_PA3); +MAKE_PIN(P61, PIOA, PIO_PA2); +MAKE_PIN(P62, PIOB, PIO_PB17); +MAKE_PIN(P63, PIOB, PIO_PB18); +MAKE_PIN(P64, PIOB, PIO_PB19); +MAKE_PIN(P65, PIOB, PIO_PB20); +MAKE_PIN(P66, PIOB, PIO_PB15); +MAKE_PIN(P67, PIOB, PIO_PB16); +MAKE_PIN(P68, PIOA, PIO_PA1); +MAKE_PIN(P69, PIOA, PIO_PA0); +MAKE_PIN(P70, PIOA, PIO_PA17); +MAKE_PIN(P71, PIOA, PIO_PA18); +MAKE_PIN(P72, PIOC, PIO_PC30); +MAKE_PIN(P73, PIOA, PIO_PA21); MAKE_PIN(P74, PIOA, PIO_PA25); // MISO MAKE_PIN(P75, PIOA, PIO_PA26); // MOSI MAKE_PIN(P76, PIOA, PIO_PA27); // CLK +MAKE_PIN(P77, PIOA, PIO_PA28); +MAKE_PIN(P78, PIOB, PIO_PB23); // Unconnected #undef MAKE_PIN From d35b83e5a536499d52cd33c27ba610847066bf3d Mon Sep 17 00:00:00 2001 From: Kristian Lauszus Date: Tue, 19 Aug 2014 22:57:18 -0700 Subject: [PATCH 145/145] Support new revision of Balanduino PCB --- avrpins.h | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/avrpins.h b/avrpins.h index c59e9c52..da80349d 100644 --- a/avrpins.h +++ b/avrpins.h @@ -672,10 +672,19 @@ public: // http://balanduino.net/ #define P0 Pd0 /* 0 - PD0 */ #define P1 Pd1 /* 1 - PD1 */ -#define P2 Pb2 /* 2 - PB2 */ -#define P3 Pd6 /* 3 - PD6 */ -#define P4 Pd7 /* 4 - PD7 */ -#define P5 Pb3 /* 5 - PB3 */ + +#if BALANDUINO_REVISION < 13 + #define P2 Pb2 /* 2 - PB2 */ + #define P3 Pd6 /* 3 - PD6 */ + #define P4 Pd7 /* 4 - PD7 */ + #define P5 Pb3 /* 5 - PB3 */ +#else + #define P2 Pd2 /* 2 - PD2 */ + #define P3 Pd3 /* 3 - PD3 */ + #define P4 Pd6 /* 4 - PD6 */ + #define P5 Pd7 /* 5 - PD7 */ +#endif + #define P6 Pb4 /* 6 - PB4 */ #define P7 Pa0 /* 7 - PA0 */ #define P8 Pa1 /* 8 - PA1 */ @@ -685,8 +694,15 @@ public: #define P12 Pa5 /* 12 - PA5 */ #define P13 Pc1 /* 13 - PC1 */ #define P14 Pc0 /* 14 - PC0 */ -#define P15 Pd2 /* 15 - PD2 */ -#define P16 Pd3 /* 16 - PD3 */ + +#if BALANDUINO_REVISION < 13 + #define P15 Pd2 /* 15 - PD2 */ + #define P16 Pd3 /* 16 - PD3 */ +#else + #define P15 Pb2 /* 15 - PB2 */ + #define P16 Pb3 /* 16 - PB2 */ +#endif + #define P17 Pd4 /* 17 - PD4 */ #define P18 Pd5 /* 18 - PD5 */ #define P19 Pc2 /* 19 - PC2 */