nitial commit.

This commit is contained in:
Manfred Amann 2019-05-10 15:39:26 +02:00
parent cf3222d4a4
commit 86dcaee84d
165 changed files with 38338 additions and 267 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

View File

@ -1,299 +1,254 @@
#define IIKEYB_D0 4
#define IIKEYB_D1 5
#define IIKEYB_D2 6
#define IIKEYB_D3 7
#define IIKEYB_D4 8
#define IIKEYB_D5 9
#define IIKEYB_D6 10
#include "II_Encoder.h"
#include <hidboot.h>
#include <usbhub.h>
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
#include <avr/pgmspace.h>
#include "layoutmemory.h"
#include "backlog.h"
#define IIKEYB_RESET 11
#define IIKEYB_STRB 12
const char string_0[] PROGMEM = " .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. ";
const char string_1[] PROGMEM = "| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. | | .--------------. || .--------------. |";
const char string_2[] PROGMEM = "| | __ | || | ______ | || | ______ | || | _____ | || | _________ | | | | _____ | || | _____ | |";
const char string_3[] PROGMEM = "| | / \\ | || | |_ __ \\ | || | |_ __ \\ | || | |_ _| | || | |_ ___ | | | | | |_ _| | || | |_ _| | |";
const char string_4[] PROGMEM = "| | / /\\ \\ | || | | |__) | | || | | |__) | | || | | | | || | | |_ \\_| | | | | | | | || | | | | |";
const char string_5[] PROGMEM = "| | / ____ \\ | || | | ___/ | || | | ___/ | || | | | _ | || | | _| _ | | | | | | | || | | | | |";
const char string_6[] PROGMEM = "| | _/ / \\ \\_ | || | _| |_ | || | _| |_ | || | _| |__/ | | || | _| |___/ | | | | | _| |_ | || | _| |_ | |";
const char string_7[] PROGMEM = "| ||____| |____|| || | |_____| | || | |_____| | || | |________| | || | |_________| | | | | |_____| | || | |_____| | |";
const char string_8[] PROGMEM = "| | | || | | || | | || | | || | | | | | | || | | |";
const char string_9[] PROGMEM = "| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' | | '--------------' || '--------------' |";
const char string_A[] PROGMEM = "'----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' ";
void setupIO()
const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5, string_6, string_7, string_8, string_9, string_A};
char buffer[145]; // make sure this is large enough for the largest string it must hold
II_Encoder KeyEncoder;
KeyLayout CurrLayout;
Backlog StringBackLog;
class KbdRptParser : public KeyboardReportParser
{ void PrintKey(uint8_t mod, uint8_t key);
protected:
void OnControlKeysChanged(uint8_t before, uint8_t after);
void OnKeyDown (uint8_t mod, uint8_t key);
void OnKeyUp (uint8_t mod, uint8_t key);
void OnKeyPressed(uint8_t key);
public:
bool bDebugPrint;
};
void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
pinMode(IIKEYB_D0, OUTPUT);
pinMode(IIKEYB_D1, OUTPUT);
pinMode(IIKEYB_D2, OUTPUT);
pinMode(IIKEYB_D3, OUTPUT);
pinMode(IIKEYB_D4, OUTPUT);
pinMode(IIKEYB_D5, OUTPUT);
pinMode(IIKEYB_D6, OUTPUT);
pinMode(IIKEYB_RESET, INPUT_PULLUP);
pinMode(IIKEYB_STRB, OUTPUT);
digitalWrite(IIKEYB_D0, LOW);
digitalWrite(IIKEYB_D1, LOW);
digitalWrite(IIKEYB_D2, LOW);
digitalWrite(IIKEYB_D3, LOW);
digitalWrite(IIKEYB_D4, LOW);
digitalWrite(IIKEYB_D5, LOW);
digitalWrite(IIKEYB_D6, LOW);
digitalWrite(IIKEYB_RESET, HIGH);
digitalWrite(IIKEYB_STRB, HIGH);
}
void II_Reset(void)
{
pinMode(IIKEYB_RESET, OUTPUT);
pinMode(IIKEYB_RESET, LOW);
delay(10);
pinMode(IIKEYB_RESET, INPUT_PULLUP);
digitalWrite(IIKEYB_RESET, HIGH);
}
int II_putchar(int bOutput)
{
if (10 == bOutput)
bOutput = '\r';
if (0x0D == bOutput)
bOutput = '\r';
if (bOutput & 0b00000001)
digitalWrite(IIKEYB_D0, HIGH);
else
digitalWrite(IIKEYB_D0, LOW);
if (bOutput & 0b00000010)
digitalWrite(IIKEYB_D1, HIGH);
else
digitalWrite(IIKEYB_D1, LOW);
if (bOutput & 0b00000100)
digitalWrite(IIKEYB_D2, HIGH);
else
digitalWrite(IIKEYB_D2, LOW);
if (bOutput & 0b00001000)
digitalWrite(IIKEYB_D3, HIGH);
else
digitalWrite(IIKEYB_D3, LOW);
if (bOutput & 0b00010000)
digitalWrite(IIKEYB_D4, HIGH);
else
digitalWrite(IIKEYB_D4, LOW);
if (bOutput & 0b00100000)
digitalWrite(IIKEYB_D5, HIGH);
else
digitalWrite(IIKEYB_D5, LOW);
if (bOutput & 0b01000000)
digitalWrite(IIKEYB_D6, HIGH);
else
digitalWrite(IIKEYB_D6, LOW);
pinMode(IIKEYB_STRB, HIGH);
delay(1);
pinMode(IIKEYB_STRB, LOW);
delay(10);
return (bOutput);
}
int II_puts(const char *string)
{
int i = 0;
while (string[i]) //standard c idiom for looping through a null-terminated string
MODIFIERKEYS mod;
*((uint8_t*)&mod) = m;
if (bDebugPrint)
{
if ( II_putchar(string[i]) == EOF) //if we got the EOF value from writing the char
{
return EOF;
}
i++;
Serial.print((mod.bmLeftCtrl == 1) ? "C" : " ");
Serial.print((mod.bmLeftShift == 1) ? "S" : " ");
Serial.print((mod.bmLeftAlt == 1) ? "A" : " ");
Serial.print((mod.bmLeftGUI == 1) ? "G" : " ");
Serial.print(" >");
PrintHex<uint8_t>(key, 0x80);
Serial.print("< ");
Serial.print((mod.bmRightCtrl == 1) ? "C" : " ");
Serial.print((mod.bmRightShift == 1) ? "S" : " ");
Serial.print((mod.bmRightAlt == 1) ? "A" : " ");
Serial.println((mod.bmRightGUI == 1) ? "G" : " ");
}
};
void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
//Serial.print("DN ");
//PrintKey(mod, key);
uint8_t c = OemToAscii(mod, key);
if (bDebugPrint)
{
Serial.print("MOD: ");
Serial.print(mod, HEX);
Serial.print(" KEY: ");
Serial.println(key, HEX);
}
if (II_putchar('\r') == EOF) //this will occur right after we quit due to the null terminated character.
if (0x52 == key) //Arrow UP
{
return EOF;
StringBackLog.OneBack();
}
else if (0x51 == key) //Arrow DOWN
{
StringBackLog.OneForeward();
}
else if (c)
{
OnKeyPressed(c);
}
return 1; //to meet spec.
}
char *convert(unsigned int num, int base)
void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after)
{
static char Representation[] = "0123456789ABCDEF";
static char buffer[50];
char *ptr;
ptr = &buffer[49];
*ptr = '\0';
MODIFIERKEYS beforeMod;
*((uint8_t*)&beforeMod) = before;
do
{
*--ptr = Representation[num % base];
num /= base;
} while (num != 0);
MODIFIERKEYS afterMod;
*((uint8_t*)&afterMod) = after;
return (ptr);
}
void II_printf(char* format, ...)
{
char *traverse;
unsigned int i;
char *s;
//Module 1: Initializing Myprintf's arguments
va_list arg;
va_start(arg, format);
for (traverse = format; *traverse != '\0'; traverse++)
{
while ( *traverse != '%' )
{
II_putchar(*traverse);
traverse++;
}
traverse++;
//Module 2: Fetching and executing arguments
switch (*traverse)
{
case 'c' : i = va_arg(arg, int); //Fetch char argument
II_putchar(i);
break;
case 'd' : i = va_arg(arg, int); //Fetch Decimal/Integer argument
if (i < 0)
{
i = -i;
II_putchar('-');
}
II_puts(convert(i, 10));
break;
case 'o': i = va_arg(arg, unsigned int); //Fetch Octal representation
II_puts(convert(i, 8));
break;
case 's': s = va_arg(arg, char *); //Fetch string
II_puts(s);
break;
case 'x': i = va_arg(arg, unsigned int); //Fetch Hexadecimal representation
II_puts(convert(i, 16));
break;
}
if (beforeMod.bmLeftCtrl != afterMod.bmLeftCtrl) {
if (bDebugPrint)
Serial.println("LeftCtrl changed");
}
if (beforeMod.bmLeftShift != afterMod.bmLeftShift) {
if (bDebugPrint)
Serial.println("LeftShift changed");
}
if (beforeMod.bmLeftAlt != afterMod.bmLeftAlt) {
if (bDebugPrint)
Serial.println("LeftAlt changed");
}
if (beforeMod.bmLeftGUI != afterMod.bmLeftGUI) {
if (bDebugPrint)
Serial.println("LeftGUI changed");
}
if (beforeMod.bmRightCtrl != afterMod.bmRightCtrl) {
if (bDebugPrint)
Serial.println("RightCtrl changed");
}
if (beforeMod.bmRightShift != afterMod.bmRightShift) {
if (bDebugPrint)
Serial.println("RightShift changed");
}
if (beforeMod.bmRightAlt != afterMod.bmRightAlt) {
if (bDebugPrint)
Serial.println("RightAlt changed");
}
if (beforeMod.bmRightGUI != afterMod.bmRightGUI) {
if (bDebugPrint)
Serial.println("RightGUI changed");
}
//Module 3: Closing argument list to necessary clean-up
va_end(arg);
}
void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
//Serial.print("UP ");
//PrintKey(mod, key);
}
void KbdRptParser::OnKeyPressed(uint8_t key)
{
if (bDebugPrint)
{
Serial.print("ASCII: ");
Serial.print((char)key);
Serial.print(" ");
Serial.println((char)key, HEX);
}
else
{
StringBackLog.addchar((char)key);
if (0x0D == key)
Serial.println();
else
Serial.print((char)key);
}
if (0x11 == key)
{
if (bDebugPrint)
Serial.print("Reset");
KeyEncoder.Reset();
}
else if (0x12 == key)
{
CurrLayout.Toggle();
SetLayout(CurrLayout.Get());
}
else
KeyEncoder.IIputchar((char)key);
};
USB Usb;
//USBHub Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
KbdRptParser Prs;
/*! \brief Wrapper for callback use.
*/
int IIputsWrapper(const char *string)
{
KeyEncoder.IIputchar(string);
}
/*! \brief Print a welcome message
Prints some nice ASCII art through the arduino terminal as a welcome.
*/
void print_welcome_msg(void)
{
Serial.println("");
Serial.println("Welcome to:");
Serial.println("");
for (int i = 0; i < 11; i++) {
strcpy_P(buffer, (char *)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy.
Serial.println(buffer);
}
Serial.println("");
Serial.println("USB-Keyboard interface.");
Serial.println("");
};
/*! \brief The Arduino setup functiopn.
Called once at startup.
*/
void setup()
{
Serial.begin(115200);
setupIO();
Serial.println("Apple II Keyboard started");
Prs.bDebugPrint = false;
II_puts(" ");
Serial.begin( 115200 );
#if !defined(__MIPSEL__)
while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
print_welcome_msg();
while (Serial.available() == 0) {}
CurrLayout.Init();
if (Usb.Init() == -1)
Serial.println("OSC did not start.c");
delay( 200 );
HidKeyboard.SetReportParser(0, &Prs);
KeyEncoder.begin();
//KeyEncoder.IIputs(" ");
Prs.SetLayout(CurrLayout.Get());
StringBackLog.SetPuts(&IIputsWrapper);
//II_monitor();
}
char* monitorcode[40];
void II_monitor(void)
{
II_puts("call -151");
delay(500);
monitorcode[0] = "0: 00 0A 00 40 00 00 00 00";
monitorcode[1] = "8: 00 00 00 00 00 00 00 00";
monitorcode[2] = "800: A9 00 85 07 A9 00 A8 AA";
monitorcode[3] = "808: 85 06 A5 00 85 04 A5 01";
monitorcode[4] = "810: 85 05 C0 04 D0 04 A5 04";
monitorcode[5] = "818: 85 06 C0 05 D0 04 A5 05";
monitorcode[6] = "820: 85 06 A5 06 81 04 A1 04";
monitorcode[7] = "828: C5 06 D0 2E E6 04 D0 02";
monitorcode[8] = "830: E6 05 A5 02 C5 04 D0 04";
monitorcode[9] = "838: A5 03 C5 05 D0 D4 A5 00";
monitorcode[10] = "840: 85 04 A5 01 85 05 C0 04";
monitorcode[11] = "848: D0 04 A5 04 85 06 C0 05";
monitorcode[12] = "850: D0 04 A5 05 85 06 A1 04";
monitorcode[13] = "858: C5 06 D0 69 E6 04 D0 02";
monitorcode[14] = "860: E6 05 A5 02 C5 04 D0 04";
monitorcode[15] = "868: A5 03 C5 05 D0 D8 C0 00";
monitorcode[16] = "870: D0 08 A9 FF 85 06 C8 4C";
monitorcode[17] = "878: 0A 08 C0 01 D0 04 A9 01";
monitorcode[18] = "880: D0 F2 C0 02 D0 08 06 06";
monitorcode[19] = "888: 90 ED A9 7F D0 E6 C0 03";
monitorcode[20] = "890: D0 08 38 66 06 B0 E0 C8";
monitorcode[21] = "898: D0 DD C0 04 F0 F9 A9 50";
monitorcode[22] = "8A0: 20 EC 08 A9 41 20 EC 08";
monitorcode[23] = "8A8: A9 53 20 EC 08 A9 53 20";
monitorcode[24] = "8B0: EC 08 20 1E 09 E6 07 A5";
monitorcode[25] = "8B8: 07 20 F2 08 20 13 09 EA";
monitorcode[26] = "8C0: EA EA 4C 04 08 48 98 20";
monitorcode[27] = "8C8: F2 08 20 1E 09 A5 05 20";
monitorcode[28] = "8D0: F2 08 A5 04 20 F2 08 20";
monitorcode[29] = "8D8: 1E 09 A5 06 20 F2 08 20";
monitorcode[30] = "8E0: 1E 09 68 20 F2 08 20 13";
monitorcode[31] = "8E8: 09 00 EA EA 09 80 20 F0";
monitorcode[32] = "8F0: FD 60 48 4A 4A 4A 4A 29";
monitorcode[33] = "8F8: 0F 09 30 C9 3A 90 02 69";
monitorcode[34] = "900: 06 20 EC 08 68 29 0F 09";
monitorcode[35] = "908: 30 C9 3A 90 02 69 06 20";
monitorcode[36] = "910: EC 08 60 A9 0D 20 EC 08";
monitorcode[37] = "918: A9 0A 20 EC 08 60 A9 20";
monitorcode[38] = "920: 20 EC 08 60";
//monitorcode[39] = "0: 00 E0 00 F0"; //Setup E000 to EFFF
monitorcode[39] = "0: 00 40 00 40"; //Setup 4000 to 7FFF
for (int i = 0; i < 40; i++)
{
II_puts(monitorcode[i]);
delay(50);
}
}
/*! \brief The Arduino mainloop.
Only the USB Task is polled here.
*/
void loop()
{
int incomingByte = 0;
int II_Byte = 0;
while (Serial.available() == 0) {}
incomingByte = Serial.read();
II_Byte = incomingByte;
if (10 == incomingByte)
II_Byte = '\r';
if (0x0D == incomingByte)
II_Byte = '\r';
if (28 == incomingByte)
II_Byte = 0x08;
if (29 == incomingByte)
II_Byte = 0x15;
#if 0
Serial.print("Received Value: 0x");
Serial.print(incomingByte, HEX);
Serial.print(" Wich shows as '");
Serial.write(incomingByte);
Serial.print("'. Sent as: 0x");
Serial.print(II_Byte, HEX);
Serial.println("' to Apple II");
#endif
Serial.write(II_Byte);
II_putchar(II_Byte);
Usb.Task();
}

179
II_Encoder.cpp Normal file
View File

@ -0,0 +1,179 @@
/*! \file II_Encoder.cpp
* \brief Output ASCII in parallel form to Apple II keyboard connector.
*
* Takes a ASCII character or string and sets the IO Pins accordingly for APPLE II keayboard Input.
*/
#include "Arduino.h"
#include "II_Encoder.h"
void II_Encoder::begin(void)
{
pinMode(IIKEYB_D0, OUTPUT);
pinMode(IIKEYB_D1, OUTPUT);
pinMode(IIKEYB_D2, OUTPUT);
pinMode(IIKEYB_D3, OUTPUT);
pinMode(IIKEYB_D4, OUTPUT);
pinMode(IIKEYB_D5, OUTPUT);
pinMode(IIKEYB_D6, OUTPUT);
pinMode(IIKEYB_RESET, INPUT_PULLUP);
pinMode(IIKEYB_STRB, OUTPUT);
digitalWrite(IIKEYB_D0, LOW);
digitalWrite(IIKEYB_D1, LOW);
digitalWrite(IIKEYB_D2, LOW);
digitalWrite(IIKEYB_D3, LOW);
digitalWrite(IIKEYB_D4, LOW);
digitalWrite(IIKEYB_D5, LOW);
digitalWrite(IIKEYB_D6, LOW);
digitalWrite(IIKEYB_RESET, HIGH);
digitalWrite(IIKEYB_STRB, HIGH);
}
void II_Encoder::Reset(void)
{
pinMode(IIKEYB_RESET, OUTPUT);
digitalWrite(IIKEYB_RESET, LOW);
delay(10);
pinMode(IIKEYB_RESET, INPUT_PULLUP);
digitalWrite(IIKEYB_RESET, HIGH);
}
int II_Encoder::IIputchar(int bOutput)
{
if (bOutput & 0b00000001)
digitalWrite(IIKEYB_D0, HIGH);
else
digitalWrite(IIKEYB_D0, LOW);
if (bOutput & 0b00000010)
digitalWrite(IIKEYB_D1, HIGH);
else
digitalWrite(IIKEYB_D1, LOW);
if (bOutput & 0b00000100)
digitalWrite(IIKEYB_D2, HIGH);
else
digitalWrite(IIKEYB_D2, LOW);
if (bOutput & 0b00001000)
digitalWrite(IIKEYB_D3, HIGH);
else
digitalWrite(IIKEYB_D3, LOW);
if (bOutput & 0b00010000)
digitalWrite(IIKEYB_D4, HIGH);
else
digitalWrite(IIKEYB_D4, LOW);
if (bOutput & 0b00100000)
digitalWrite(IIKEYB_D5, HIGH);
else
digitalWrite(IIKEYB_D5, LOW);
if (bOutput & 0b01000000)
digitalWrite(IIKEYB_D6, HIGH);
else
digitalWrite(IIKEYB_D6, LOW);
pinMode(IIKEYB_STRB, HIGH);
delay(1);
pinMode(IIKEYB_STRB, LOW);
delay(10);
return (bOutput);
}
int II_Encoder::IIputs(const char *string)
{
int i = 0;
while (string[i]) //standard c idiom for looping through a null-terminated string
{
if (IIputchar(string[i]) == EOF) //if we got the EOF value from writing the char
{
return EOF;
}
i++;
}
if (IIputchar('\r') == EOF) //this will occur right after we quit due to the null terminated character.
{
return EOF;
}
return 1; //to meet spec.
}
char *II_Encoder::convert(unsigned int num, const int base, char *ptr)
{
static char Representation[] = "0123456789ABCDEF";
*ptr = '\0';
do
{
*--ptr = Representation[num % base];
num /= base;
} while (num != 0);
return (ptr);
}
void II_Encoder::IIprintf(char* format, ...)
{
char *traverse;
unsigned int i;
char *s;
char pBuffer[25];
//Module 1: Initializing Myprintf's arguments
va_list arg;
va_start(arg, format);
for (traverse = format; *traverse != '\0'; traverse++)
{
while ( *traverse != '%' )
{
IIputchar(*traverse);
traverse++;
}
traverse++;
//Module 2: Fetching and executing arguments
switch (*traverse)
{
case 'c' : i = va_arg(arg, int); //Fetch char argument
IIputchar(i);
break;
case 'd' : i = va_arg(arg, int); //Fetch Decimal/Integer argument
if (i < 0)
{
i = -i;
IIputchar('-');
}
IIputs(convert(i, 10, pBuffer));
break;
case 'o': i = va_arg(arg, unsigned int); //Fetch Octal representation
IIputs(convert(i, 8, pBuffer));
break;
case 's': s = va_arg(arg, char *); //Fetch string
IIputs(s);
break;
case 'x': i = va_arg(arg, unsigned int); //Fetch Hexadecimal representation
IIputs(convert(i, 16, pBuffer));
break;
}
}
//Module 3: Closing argument list to necessary clean-up
va_end(arg);
}

27
II_Encoder.h Normal file
View File

@ -0,0 +1,27 @@
#pragma once
//Arduino Pin definitioin for Keyboard Interface
#define IIKEYB_D0 A2
#define IIKEYB_D1 A3
#define IIKEYB_D2 A0
#define IIKEYB_D3 A1
#define IIKEYB_D4 7
#define IIKEYB_D5 6
#define IIKEYB_D6 8
#define IIKEYB_RESET 5
#define IIKEYB_STRB 4
class II_Encoder
{
public:
void begin(void);
void Reset(void);
int IIputchar(int bOutput);
int IIputs(const char *string);
void IIprintf(char* format, ...);
char *convert(unsigned int num, const int base, char *ptr);
};

191
backlog.cpp Normal file
View File

@ -0,0 +1,191 @@
#include "Arduino.h"
#include "backlog.h"
/*! \brief Constructor, init everything to zero.
*/
Backlog::Backlog()
{
pCurrentInputString = NULL;
pputs = NULL;
BacklogOutputPointer = 0;
for (int i = 0; i < BACKLOG_STEPS; i++)
StringBacklog[i] = NULL;
}
/*! \brief Set the puts callback.
Set the puts callback function, in our case the output to the II keyb interface.
*/
void Backlog::SetPuts(int (*pputs_funcp)(const char *string))
{
pputs = pputs_funcp;
}
/*! \brief Erase the current input on the screen.
The current typed input is erased with backspaces.
*/
void Backlog::EraseCurrent(void)
{
uint16_t bufferlen = strlen(pCurrentInputString);
for (int i = 0; i < bufferlen; i++)
{
if (pputs)
{
pputs(0x08); //Backspace
delay(CHAR_OUT_DELAY);
}
}
}
/*! \brief Output the current string vie puts.
The current active string ist typed to the screen via puts.
*/
void Backlog::OutputCurrent(void)
{
uint16_t bufferlen = strlen(pCurrentInputString);
for (int i = 0; i < bufferlen; i++)
{
if (pputs)
{
pputs(pCurrentInputString[i]);
delay(CHAR_OUT_DELAY);
}
}
}
/*! \brief Go one string back in the backlog.
Erases the current input from the screen and goes one back ion the log.
*/
void Backlog::OneBack(void)
{
uint8_t uiNewIndex = BacklogOutputPointer;
ChangeToIndex(uiNewIndex);
uiNewIndex++;
if (uiNewIndex > BACKLOG_STEPS - 1)
uiNewIndex = BACKLOG_STEPS - 1;
BacklogOutputPointer = uiNewIndex;
}
/*! \brief Go one string forward in the backlog.
Erases the current input from the screen and goes one foreward ion the log.
*/
void Backlog::OneForeward(void)
{
uint8_t uiNewIndex = BacklogOutputPointer;
if (uiNewIndex)
uiNewIndex--;
ChangeToIndex(uiNewIndex);
BacklogOutputPointer = uiNewIndex;
}
/*! \brief Change the screen to a specific index from the backlog.
Changes the active display to a specific string from the backlog.
*/
void Backlog::ChangeToIndex(uint8_t uiNewIndex)
{
EraseCurrent();
delete pCurrentInputString;
if (StringBacklog[uiNewIndex])
{
pCurrentInputString = new char[BUFFER_STEPS + (BUFFER_STEPS * (strlen(StringBacklog[uiNewIndex]) / BUFFER_STEPS)) ];
strcpy(pCurrentInputString, StringBacklog[uiNewIndex]);
OutputCurrent();
}
}
/*! \brief Stores the current string in the backlog.
The current string is stored in the backlog and the log is advanced one step.
*/
void Backlog::BacklogCurrString(void)
{
BacklogOutputPointer = 0;
if (StringBacklog[BACKLOG_STEPS - 1])
delete StringBacklog[BACKLOG_STEPS - 1];
for (int i = BACKLOG_STEPS - 1; i > 0; i--)
{
StringBacklog[i] = StringBacklog[i - 1];
}
StringBacklog[0] = pCurrentInputString;
pCurrentInputString = NULL;
#if 0
Serial.println("Current Backlog:");
for (int i = 0; i < BACKLOG_STEPS; i++)
{
if (StringBacklog[i])
Serial.println(StringBacklog[i]);
}
#endif
}
/*! \brief If the current typed string exceeds BUFFER_STEPS the buffer is increased.
*
If the current string gets bigger than BUFFER_STEPS another BUFFER_STEPS is added.
*/
void Backlog::IncreaseBuffer(void)
{
if (NULL == pCurrentInputString)
{
pCurrentInputString = new char[BUFFER_STEPS];
memset(pCurrentInputString, 0, BUFFER_STEPS);
}
else
{
uint16_t bufferlen = strlen(pCurrentInputString);
if (((bufferlen % BUFFER_STEPS) == (BUFFER_STEPS - 2)) && (bufferlen > 0))
{
char *pnewCurrentInputString = new char[bufferlen + BUFFER_STEPS];
memcpy(pnewCurrentInputString, pCurrentInputString, bufferlen + 1);
delete [] pCurrentInputString;
pCurrentInputString = pnewCurrentInputString;
}
}
}
/*! \brief Add one typed char to the current input string.
*
On char is added, or if 0x0d is received, the string is stored and the backlog advanced.
*/
void Backlog::addchar(char c)
{
IncreaseBuffer();
if (0x0d == c) // Finished
{
BacklogCurrString();
}
else if (0x08 == c) // Backspace)
{
uint16_t bufferlen = strlen(pCurrentInputString);
if (bufferlen)
pCurrentInputString[bufferlen - 1] = 0x00;
}
else
{
uint16_t bufferlen = strlen(pCurrentInputString);
pCurrentInputString[bufferlen] = c;
pCurrentInputString[bufferlen + 1] = 0x00;
}
}

35
backlog.h Normal file
View File

@ -0,0 +1,35 @@
/*! \file backlog.h
* \brief Provides BASH like command backlog.
*
* With the Arrow Up / Down keys the last commands can be recalled and used.
*/
#pragma once
#define BUFFER_STEPS 40
#define BACKLOG_STEPS 10
#define CHAR_OUT_DELAY 10
class Backlog
{
private:
uint8_t BacklogOutputPointer;
char* StringBacklog[BACKLOG_STEPS];
char* pCurrentInputString;
void IncreaseBuffer(void);
void BacklogCurrString(void);
int (*pputs)(const char *string);
void EraseCurrent(void);
void OutputCurrent(void);
void ChangeToIndex(uint8_t uiNewIndex);
public:
Backlog();
void addchar(char c);
void SetPuts(int (*pputs_funcp)(const char *string));
void OneBack(void);
void OneForeward(void);
};

96
layoutmemory.cpp Normal file
View File

@ -0,0 +1,96 @@
#include "Arduino.h"
#include <EEPROM.h>
#include "layoutmemory.h"
#define MAX_KEYB_LAYOUT_ID 1
/*! \brief Only init variables
*/
KeyLayout::KeyLayout()
{
uiCurrentKeyboardLayout = 0xFF;
}
/*! \brief Init function, not to be called from constructor.
Restores settings from eeprom.
*/
void KeyLayout::Init(void)
{
Restore();
}
/*! \brief Print current selected layout namew.
*/
void KeyLayout::Print(void)
{
Serial.print("Keyboard Layout is: ");
switch (uiCurrentKeyboardLayout)
{
case 0:
Serial.println("US");
break;
case 1:
Serial.println("DE");
break;
default:
Serial.println(uiCurrentKeyboardLayout, HEX);
break;
}
}
/*! \brief Stores current active layout to eeprom.
*/
void KeyLayout::Store(void)
{
EEPROM.write(0, uiCurrentKeyboardLayout);
}
/*! \brief Restores active layout from eeprom.
*/
void KeyLayout::Restore(void)
{
Set(EEPROM.read(0));
}
/*! \brief Select new layout.
Switch to the next layout and back to 0 if the MAX_KEYB_LAYOUT_ID is reached.
*/
void KeyLayout::Toggle(void)
{
Set(uiCurrentKeyboardLayout + 1);
}
/*! \brief Set the active layout direct..
Sets the active layout and thecks the range.
*/
void KeyLayout::Set(uint8_t uiLayoutID)
{
if (uiLayoutID > MAX_KEYB_LAYOUT_ID)
uiLayoutID = 0;
if (uiCurrentKeyboardLayout != uiLayoutID)
{
uiCurrentKeyboardLayout = uiLayoutID;
Store();
Print();
}
}
/*! \brief Returns the current active layout.
*/
uint8_t KeyLayout::Get(void)
{
return uiCurrentKeyboardLayout;
}

26
layoutmemory.h Normal file
View File

@ -0,0 +1,26 @@
/*! \file layoutmemory.h
* \brief Handles selection of multiple keyboard layout.
*
* Toggles the keyboard layout WIN+SPace as a trigger e.g. and stores the current layout in eeprom.
*/
#pragma once
class KeyLayout
{
public:
KeyLayout();
void Init(void);
void Restore(void);
void Store(void);
void Print(void);
void Toggle(void);
void Set(uint8_t uiLayoutID);
uint8_t Get(void);
private:
uint8_t uiCurrentKeyboardLayout;//ID of the current active keyboard Layout
};

BIN
libraries/.DS_Store vendored Normal file

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,624 @@
/* Copyright (C) 2012 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 _btd_h_
#define _btd_h_
#include "Usb.h"
#include "usbhid.h"
//PID and VID of the Sony PS3 devices
#define PS3_VID 0x054C // Sony Corporation
#define PS3_PID 0x0268 // PS3 Controller DualShock 3
#define PS3NAVIGATION_PID 0x042F // Navigation controller
#define PS3MOVE_PID 0x03D5 // Motion controller
// These dongles do not present themselves correctly, so we have to check for them manually
#define IOGEAR_GBU521_VID 0x0A5C
#define IOGEAR_GBU521_PID 0x21E8
#define BELKIN_F8T065BF_VID 0x050D
#define BELKIN_F8T065BF_PID 0x065A
/* Bluetooth dongle data taken from descriptors */
#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
/* Bluetooth HCI states for hci_task() */
#define HCI_INIT_STATE 0
#define HCI_RESET_STATE 1
#define HCI_CLASS_STATE 2
#define HCI_BDADDR_STATE 3
#define HCI_LOCAL_VERSION_STATE 4
#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 device
#define HCI_CONNECT_DEVICE_STATE 8
#define HCI_CONNECTED_DEVICE_STATE 9
#define HCI_SCANNING_STATE 10
#define HCI_CONNECT_IN_STATE 11
#define HCI_REMOTE_NAME_STATE 12
#define HCI_CONNECTED_STATE 13
#define HCI_DISABLE_SCAN_STATE 14
#define HCI_DONE_STATE 15
#define HCI_DISCONNECT_STATE 16
/* HCI event flags*/
#define HCI_FLAG_CMD_COMPLETE (1UL << 0)
#define HCI_FLAG_CONNECT_COMPLETE (1UL << 1)
#define HCI_FLAG_DISCONNECT_COMPLETE (1UL << 2)
#define HCI_FLAG_REMOTE_NAME_COMPLETE (1UL << 3)
#define HCI_FLAG_INCOMING_REQUEST (1UL << 4)
#define HCI_FLAG_READ_BDADDR (1UL << 5)
#define HCI_FLAG_READ_VERSION (1UL << 6)
#define HCI_FLAG_DEVICE_FOUND (1UL << 7)
#define HCI_FLAG_CONNECT_EVENT (1UL << 8)
/* 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
#define EV_INQUIRY_RESULT 0x02
#define EV_CONNECT_COMPLETE 0x03
#define EV_INCOMING_CONNECT 0x04
#define EV_DISCONNECT_COMPLETE 0x05
#define EV_AUTHENTICATION_COMPLETE 0x06
#define EV_REMOTE_NAME_COMPLETE 0x07
#define EV_ENCRYPTION_CHANGE 0x08
#define EV_CHANGE_CONNECTION_LINK 0x09
#define EV_ROLE_CHANGED 0x12
#define EV_NUM_COMPLETE_PKT 0x13
#define EV_PIN_CODE_REQUEST 0x16
#define EV_LINK_KEY_REQUEST 0x17
#define EV_LINK_KEY_NOTIFICATION 0x18
#define EV_DATA_BUFFER_OVERFLOW 0x1A
#define EV_MAX_SLOTS_CHANGE 0x1B
#define EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE 0x0C
#define EV_QOS_SETUP_COMPLETE 0x0D
#define EV_COMMAND_COMPLETE 0x0E
#define EV_COMMAND_STATUS 0x0F
#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_SUCCESS 11
/* Used for RFCOMM channel */
#define L2CAP_RFCOMM_WAIT 12
#define L2CAP_RFCOMM_SUCCESS 13
#define L2CAP_DISCONNECT_RESPONSE 14 // Used for both SDP and RFCOMM channel
/* Bluetooth states used by some drivers */
#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 (1UL << 0)
#define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS (1UL << 1)
#define L2CAP_FLAG_CONTROL_CONNECTED (1UL << 2)
#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE (1UL << 3)
/* L2CAP event flags for HID Interrupt channel */
#define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST (1UL << 4)
#define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS (1UL << 5)
#define L2CAP_FLAG_INTERRUPT_CONNECTED (1UL << 6)
#define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE (1UL << 7)
/* L2CAP event flags for SDP channel */
#define L2CAP_FLAG_CONNECTION_SDP_REQUEST (1UL << 8)
#define L2CAP_FLAG_CONFIG_SDP_SUCCESS (1UL << 9)
#define L2CAP_FLAG_DISCONNECT_SDP_REQUEST (1UL << 10)
/* L2CAP event flags for RFCOMM channel */
#define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST (1UL << 11)
#define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS (1UL << 12)
#define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST (1UL << 13)
#define L2CAP_FLAG_DISCONNECT_RESPONSE (1UL << 14)
/* 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))
/* L2CAP signaling commands */
#define L2CAP_CMD_COMMAND_REJECT 0x01
#define L2CAP_CMD_CONNECTION_REQUEST 0x02
#define L2CAP_CMD_CONNECTION_RESPONSE 0x03
#define L2CAP_CMD_CONFIG_REQUEST 0x04
#define L2CAP_CMD_CONFIG_RESPONSE 0x05
#define L2CAP_CMD_DISCONNECT_REQUEST 0x06
#define L2CAP_CMD_DISCONNECT_RESPONSE 0x07
#define L2CAP_CMD_INFORMATION_REQUEST 0x0A
#define L2CAP_CMD_INFORMATION_RESPONSE 0x0B
// Used For Connection Response - Remember to Include High Byte
#define PENDING 0x01
#define SUCCESSFUL 0x00
/* Bluetooth L2CAP PSM - see http://www.bluetooth.org/Technical/AssignedNumbers/logical_link.htm */
#define SDP_PSM 0x01 // Service Discovery Protocol PSM Value
#define RFCOMM_PSM 0x03 // RFCOMM PSM Value
#define HID_CTRL_PSM 0x11 // HID_Control PSM Value
#define HID_INTR_PSM 0x13 // HID_Interrupt PSM Value
// Used to determine if it is a Bluetooth dongle
#define WI_SUBCLASS_RF 0x01 // RF Controller
#define WI_PROTOCOL_BT 0x01 // Bluetooth Programming Interface
#define BTD_MAX_ENDPOINTS 4
#define BTD_NUM_SERVICES 4 // Max number of Bluetooth services - if you need more than 4 simply increase this number
#define PAIR 1
class BluetoothService;
/**
* The Bluetooth Dongle class will take care of all the USB communication
* and then pass the data to the BluetoothService classes.
*/
class BTD : public USBDeviceConfig, public UsbConfigXtracter {
public:
/**
* Constructor for the BTD class.
* @param p Pointer to USB class instance.
*/
BTD(USB *p);
/** @name USBDeviceConfig implementation */
/**
* 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.
* @return 0 on success.
*/
uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
/**
* Initialize the Bluetooth dongle.
* @param parent Hub number.
* @param port Port number on the hub.
* @param lowspeed Speed of the device.
* @return 0 on success.
*/
uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
/**
* Release the USB device.
* @return 0 on success.
*/
uint8_t Release();
/**
* Poll the USB Input endpoints and run the state machines.
* @return 0 on success.
*/
uint8_t Poll();
/**
* Get the device address.
* @return The device address.
*/
virtual uint8_t GetAddress() {
return bAddress;
};
/**
* Used to check if the dongle has been initialized.
* @return True if it's ready.
*/
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 bool DEVCLASSOK(uint8_t klass) {
return (klass == USB_CLASS_WIRELESS_CTRL);
};
/**
* Used by the USB core to check what this driver support.
* Used to set the Bluetooth address into the PS3 controllers.
* @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 bool VIDPIDOK(uint16_t vid, uint16_t pid) {
if((vid == IOGEAR_GBU521_VID && pid == IOGEAR_GBU521_PID) || (vid == BELKIN_F8T065BF_VID && pid == BELKIN_F8T065BF_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))
return true;
}
return false;
};
/**@}*/
/** @name UsbConfigXtracter implementation */
/**
* UsbConfigXtracter implementation, used to extract endpoint information.
* @param conf Configuration value.
* @param iface Interface number.
* @param alt Alternate setting.
* @param proto Interface Protocol.
* @param ep Endpoint Descriptor.
*/
void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
/**@}*/
/** Disconnects both the L2CAP Channel and the HCI Connection for all Bluetooth services. */
void disconnect();
/**
* Register Bluetooth dongle members/services.
* @param pService Pointer to BluetoothService class instance.
* @return The service ID on success or -1 on fail.
*/
int8_t registerBluetoothService(BluetoothService *pService) {
for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
if(!btService[i]) {
btService[i] = pService;
return i; // Return ID
}
}
return -1; // Error registering BluetoothService
};
/** @name HCI Commands */
/**
* Used to send a HCI Command.
* @param data Data to send.
* @param nbytes Number of bytes to send.
*/
void HCI_Command(uint8_t* data, uint16_t nbytes);
/** Reset the Bluetooth dongle. */
void hci_reset();
/** Read the Bluetooth address of the dongle. */
void hci_read_bdaddr();
/** Read the HCI Version of the Bluetooth dongle. */
void hci_read_local_version_information();
/**
* Set the local name of the Bluetooth dongle.
* @param name Desired name.
*/
void hci_set_local_name(const char* name);
/** Enable visibility to other Bluetooth devices. */
void hci_write_scan_enable();
/** Disable visibility to other Bluetooth devices. */
void hci_write_scan_disable();
/** Read the remote devices name. */
void hci_remote_name();
/** Accept the connection with the Bluetooth device. */
void hci_accept_connection();
/**
* Disconnect the HCI connection.
* @param handle The HCI Handle for the connection.
*/
void hci_disconnect(uint16_t handle);
/**
* Respond with the pin for the connection.
* The pin is automatically set for the Wii library,
* but can be customized for the SPP library.
*/
void hci_pin_code_request_reply();
/** Respons when no pin was set. */
void hci_pin_code_negative_request_reply();
/**
* Command is used to reply to a Link Key Request event from the BR/EDR Controller
* if the Host does not have a stored Link Key for the connection.
*/
void hci_link_key_request_negative_reply();
/** Used to try to authenticate with the remote device. */
void hci_authentication_request();
/** Start a HCI inquiry. */
void hci_inquiry();
/** Cancel a HCI inquiry. */
void hci_inquiry_cancel();
/** Connect to last device communicated with. */
void hci_connect();
/**
* Connect to device.
* @param bdaddr Bluetooth address of the device.
*/
void hci_connect(uint8_t *bdaddr);
/** Used to a set the class of the device. */
void hci_write_class_of_device();
/**@}*/
/** @name L2CAP Commands */
/**
* Used to send L2CAP Commands.
* @param handle HCI Handle.
* @param data Data to send.
* @param nbytes Number of bytes to send.
* @param channelLow,channelHigh Low and high byte of channel to send to.
* If argument is omitted then the Standard L2CAP header: Channel ID (0x01) for ACL-U will be used.
*/
void L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00);
/**
* L2CAP Connection Request.
* @param handle HCI handle.
* @param rxid Identifier.
* @param scid Source Channel Identifier.
* @param psm Protocol/Service Multiplexer - see: https://www.bluetooth.org/Technical/AssignedNumbers/logical_link.htm.
*/
void l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm);
/**
* L2CAP Connection Response.
* @param handle HCI handle.
* @param rxid Identifier.
* @param dcid Destination Channel Identifier.
* @param scid Source Channel Identifier.
* @param result Result - First send ::PENDING and then ::SUCCESSFUL.
*/
void l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result);
/**
* L2CAP Config Request.
* @param handle HCI Handle.
* @param rxid Identifier.
* @param dcid Destination Channel Identifier.
*/
void l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid);
/**
* L2CAP Config Response.
* @param handle HCI Handle.
* @param rxid Identifier.
* @param scid Source Channel Identifier.
*/
void l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid);
/**
* L2CAP Disconnection Request.
* @param handle HCI Handle.
* @param rxid Identifier.
* @param dcid Device Channel Identifier.
* @param scid Source Channel Identifier.
*/
void l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
/**
* L2CAP Disconnection Response.
* @param handle HCI Handle.
* @param rxid Identifier.
* @param dcid Device Channel Identifier.
* @param scid Source Channel Identifier.
*/
void l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
/**
* L2CAP Information Response.
* @param handle HCI Handle.
* @param rxid Identifier.
* @param infoTypeLow,infoTypeHigh Infotype.
*/
void l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh);
/**@}*/
/** Use this to see if it is waiting for a incoming connection. */
bool waitingForConnection;
/** This is used by the service to know when to store the device information. */
bool l2capConnectionClaimed;
/** This is used by the SPP library to claim the current SDP incoming request. */
bool sdpConnectionClaimed;
/** This is used by the SPP library to claim the current RFCOMM incoming request. */
bool rfcommConnectionClaimed;
/** 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 and BTHID library. */
const char* btdPin;
/** The bluetooth dongles Bluetooth address. */
uint8_t my_bdaddr[6];
/** HCI handle for the last connection. */
uint16_t hci_handle;
/** Last incoming devices Bluetooth address. */
uint8_t disc_bdaddr[6];
/** First 30 chars of last remote name. */
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,
* it should be at least 3 to work properly with the library.
*/
uint8_t hci_version;
/** Call this function to pair with a Wiimote */
void pairWithWiimote() {
pairWithWii = true;
hci_state = HCI_CHECK_DEVICE_SERVICE;
};
/** Used to only send the ACL data to the Wiimote. */
bool connectToWii;
/** True if a Wiimote is connecting. */
bool incomingWii;
/** True when it should pair with a Wiimote. */
bool pairWithWii;
/** True if it's the new Wiimote with the Motion Plus Inside or a Wii U Pro Controller. */
bool motionPlusInside;
/** True if it's a Wii U Pro Controller. */
bool wiiUProController;
/** Call this function to pair with a HID device */
void pairWithHID() {
waitingForConnection = false;
pairWithHIDDevice = true;
hci_state = HCI_CHECK_DEVICE_SERVICE;
};
/** Used to only send the ACL data to the HID device. */
bool connectToHIDDevice;
/** True if a HID device is connecting. */
bool incomingHIDDevice;
/** True when it should pair with a device like a mouse or keyboard. */
bool pairWithHIDDevice;
/**
* Read the poll interval taken from the endpoint descriptors.
* @return The poll interval in ms.
*/
uint8_t readPollInterval() {
return pollInterval;
};
protected:
/** Pointer to USB class instance. */
USB *pUsb;
/** Device address. */
uint8_t bAddress;
/** Endpoint info structure. */
EpInfo epInfo[BTD_MAX_ENDPOINTS];
/** Configuration number. */
uint8_t bConfNum;
/** Total number of endpoints in the configuration. */
uint8_t bNumEP;
/** Next poll time based on poll interval taken from the USB descriptor. */
uint32_t qNextPollTime;
/** Bluetooth dongle control endpoint. */
static const uint8_t BTD_CONTROL_PIPE;
/** HCI event endpoint index. */
static const uint8_t BTD_EVENT_PIPE;
/** ACL In endpoint index. */
static const uint8_t BTD_DATAIN_PIPE;
/** ACL Out endpoint index. */
static const uint8_t BTD_DATAOUT_PIPE;
/**
* Used to print the USB Endpoint Descriptor.
* @param ep_ptr Pointer to USB Endpoint Descriptor.
*/
void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
private:
void Initialize(); // Set all variables, endpoint structs etc. to default values
BluetoothService *btService[BTD_NUM_SERVICES];
uint16_t PID, VID; // PID and VID of device connected
uint8_t pollInterval;
bool bPollEnable;
bool pairWiiUsingSync; // True if pairing was done using the Wii SYNC button.
bool checkRemoteName; // Used to check remote device's name before connecting.
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
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
/* State machines */
void HCI_event_task(); // Poll the HCI event pipe
void HCI_task(); // HCI state machine
void ACL_event_task(); // ACL input pipe
/* Used to set the Bluetooth Address internally to the PS3 Controllers */
void setBdaddr(uint8_t* BDADDR);
void setMoveBdaddr(uint8_t* BDADDR);
};
/** All Bluetooth services should inherit this class. */
class BluetoothService {
public:
BluetoothService(BTD *p) : pBtd(p) {
if(pBtd)
pBtd->registerBluetoothService(this); // Register it as a Bluetooth service
};
/**
* Used to pass acldata to the Bluetooth service.
* @param ACLData Pointer to the incoming acldata.
*/
virtual void ACLData(uint8_t* ACLData) = 0;
/** Used to run the different state machines in the Bluetooth service. */
virtual void Run() = 0;
/** Used to reset the Bluetooth service. */
virtual void Reset() = 0;
/** Used to disconnect both the L2CAP Channel and the HCI Connection for the Bluetooth service. */
virtual void disconnect() = 0;
/**
* Used to call your own function when the device is successfully initialized.
* @param funcOnInit Function to call.
*/
void attachOnInit(void (*funcOnInit)(void)) {
pFuncOnInit = funcOnInit; // TODO: This really belong in a class of it's own as it is repeated several times
};
protected:
/**
* 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() = 0;
/** Used to check if the incoming L2CAP data matches the HCI Handle */
bool checkHciHandle(uint8_t *buf, uint16_t handle) {
return (buf[0] == (handle & 0xFF)) && (buf[1] == ((handle >> 8) | 0x20));
}
/** Pointer to function called in onInit(). */
void (*pFuncOnInit)(void);
/** Pointer to BTD instance. */
BTD *pBtd;
/** The HCI Handle for the connection. */
uint16_t hci_handle;
/** L2CAP flags of received Bluetooth events. */
uint32_t l2cap_event_flag;
/** Identifier for L2CAP commands. */
uint8_t identifier;
};
#endif

View File

@ -0,0 +1,399 @@
/* Copyright (C) 2013 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 "BTHID.h"
// To enable serial debugging see "settings.h"
//#define EXTRADEBUG // Uncomment to get even more debugging data
//#define PRINTREPORT // Uncomment to print the report send by the HID device
BTHID::BTHID(BTD *p, bool pair, const char *pin) :
BluetoothService(p), // Pointer to USB class instance - mandatory
protocolMode(USB_HID_BOOT_PROTOCOL) {
for(uint8_t i = 0; i < NUM_PARSERS; i++)
pRptParser[i] = NULL;
pBtd->pairWithHIDDevice = pair;
pBtd->btdPin = pin;
/* Set device cid for the control and intterrupt channelse - LSB */
control_dcid[0] = 0x70; // 0x0070
control_dcid[1] = 0x00;
interrupt_dcid[0] = 0x71; // 0x0071
interrupt_dcid[1] = 0x00;
Reset();
}
void BTHID::Reset() {
connected = false;
activeConnection = false;
l2cap_event_flag = 0; // Reset flags
l2cap_state = L2CAP_WAIT;
ResetBTHID();
}
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();
l2cap_state = L2CAP_INTERRUPT_DISCONNECT;
}
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) {
pBtd->incomingHIDDevice = false;
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;
}
}
}
if(checkHciHandle(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
Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (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]) {
//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]) {
//Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80);
identifier = l2capinbuf[9];
interrupt_scid[0] = l2capinbuf[12];
interrupt_scid[1] = l2capinbuf[13];
l2cap_set_flag(L2CAP_FLAG_INTERRUPT_CONNECTED);
}
}
} else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
#ifdef EXTRADEBUG
Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
Notify(PSTR(" SCID: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
Notify(PSTR(" Identifier: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
#endif
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) {
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]) {
//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]) {
//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]) {
//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]) {
//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]) {
#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]) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80);
#endif
identifier = l2capinbuf[9];
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]) {
//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]) {
//Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80);
identifier = l2capinbuf[9];
l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE);
}
}
#ifdef EXTRADEBUG
else {
identifier = l2capinbuf[9];
Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
}
#endif
} 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++) {
D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
Notify(PSTR(" "), 0x80);
}
#endif
if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT
uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]);
ParseBTHIDData((uint8_t)(length - 1), &l2capinbuf[9]);
switch(l2capinbuf[9]) {
case 0x01: // Keyboard or Joystick events
if(pRptParser[KEYBOARD_PARSER_ID])
pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast<USBHID *>(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])
pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast<USBHID *>(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance
break;
#ifdef EXTRADEBUG
default:
Notify(PSTR("\r\nUnknown Report type: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
break;
#endif
}
}
} 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++) {
D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
Notify(PSTR(" "), 0x80);
}
#endif
}
#ifdef EXTRADEBUG
else {
Notify(PSTR("\r\nUnsupported L2CAP Data - Channel ID: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[7], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[6], 0x80);
Notify(PSTR("\r\nData: "), 0x80);
Notify(PSTR("\r\n"), 0x80);
for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
Notify(PSTR(" "), 0x80);
}
}
#endif
L2CAP_task();
}
}
void BTHID::L2CAP_task() {
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)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80);
#endif
setProtocol(); // Set protocol before establishing HID interrupt channel
l2cap_state = L2CAP_INTERRUPT_SETUP;
}
break;
case L2CAP_INTERRUPT_SETUP:
if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80);
#endif
pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, PENDING);
delay(1);
pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, SUCCESSFUL);
identifier++;
delay(1);
pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
}
break;
/* These states are used if the Arduino is the host */
case L2CAP_CONTROL_CONNECT_REQUEST:
if(l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSend HID Control Config Request"), 0x80);
#endif
identifier++;
pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
l2cap_state = L2CAP_CONTROL_CONFIG_REQUEST;
}
break;
case L2CAP_CONTROL_CONFIG_REQUEST:
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
Notify(PSTR("\r\nSend HID Interrupt Connection Request"), 0x80);
#endif
identifier++;
pBtd->l2cap_connection_request(hci_handle, identifier, interrupt_dcid, HID_INTR_PSM);
l2cap_state = L2CAP_INTERRUPT_CONNECT_REQUEST;
}
break;
case L2CAP_INTERRUPT_CONNECT_REQUEST:
if(l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80);
#endif
identifier++;
pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
}
break;
case L2CAP_INTERRUPT_CONFIG_REQUEST:
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
pBtd->connectToHIDDevice = false;
pBtd->pairWithHIDDevice = false;
connected = true;
onInit();
l2cap_state = L2CAP_DONE;
}
break;
case L2CAP_DONE:
break;
case L2CAP_INTERRUPT_DISCONNECT:
if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80);
#endif
identifier++;
pBtd->l2cap_disconnection_request(hci_handle, identifier, control_scid, control_dcid);
l2cap_state = L2CAP_CONTROL_DISCONNECT;
}
break;
case L2CAP_CONTROL_DISCONNECT:
if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nDisconnected Control Channel"), 0x80);
#endif
pBtd->hci_disconnect(hci_handle);
hci_handle = -1; // Reset handle
l2cap_event_flag = 0; // Reset flags
l2cap_state = L2CAP_WAIT;
}
break;
}
}
void BTHID::Run() {
switch(l2cap_state) {
case L2CAP_WAIT:
if(pBtd->connectToHIDDevice && !pBtd->l2capConnectionClaimed && !connected && !activeConnection) {
pBtd->l2capConnectionClaimed = true;
activeConnection = true;
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSend HID Control Connection Request"), 0x80);
#endif
hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
l2cap_event_flag = 0; // Reset flags
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)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80);
#endif
pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, PENDING);
delay(1);
pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, SUCCESSFUL);
identifier++;
delay(1);
pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
l2cap_state = L2CAP_CONTROL_SUCCESS;
}
break;
}
}
/************************************************************/
/* HID Commands */
/************************************************************/
void BTHID::setProtocol() {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSet protocol mode: "), 0x80);
D_PrintHex<uint8_t > (protocolMode, 0x80);
#endif
if (protocolMode != USB_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 = USB_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]);
}
void BTHID::setLeds(uint8_t data) {
uint8_t buf[3];
buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
buf[1] = 0x01; // Report ID
buf[2] = data;
pBtd->L2CAP_Command(hci_handle, buf, 3, interrupt_scid[0], interrupt_scid[1]);
}

View File

@ -0,0 +1,160 @@
/* Copyright (C) 2013 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 _bthid_h_
#define _bthid_h_
#include "BTD.h"
#include "hidboot.h"
#define KEYBOARD_PARSER_ID 0
#define MOUSE_PARSER_ID 1
#define NUM_PARSERS 2
/** This BluetoothService class implements support for Bluetooth HID devices. */
class BTHID : public BluetoothService {
public:
/**
* Constructor for the BTHID class.
* @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.
*/
BTHID(BTD *p, bool pair = false, const char *pin = "0000");
/** @name BluetoothService implementation */
/** Used this to disconnect the devices. */
void disconnect();
/**@}*/
/**
* 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;
};
/**
* Set HID protocol mode.
* @param mode HID protocol to use. Either USB_HID_BOOT_PROTOCOL or HID_RPT_PROTOCOL.
*/
void setProtocolMode(uint8_t mode) {
protocolMode = mode;
};
/**@{*/
/**
* Used to set the leds on a keyboard.
* @param data See ::KBDLEDS in hidboot.h
*/
void setLeds(struct KBDLEDS data) {
setLeds(*((uint8_t*)&data));
};
void setLeds(uint8_t data);
/**@}*/
/** True if a device is connected */
bool connected;
/** Call this to start the pairing sequence with a device */
void pair(void) {
if(pBtd)
pBtd->pairWithHID();
};
protected:
/** @name BluetoothService implementation */
/**
* Used to pass acldata to the services.
* @param ACLData Incoming acldata.
*/
void ACLData(uint8_t* ACLData);
/** Used to run part of the state machine. */
void Run();
/** Use this to reset the service. */
void Reset();
/**
* 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
OnInitBTHID();
};
/**@}*/
/** @name Overridable functions */
/**
* Used to parse Bluetooth HID data to any class that inherits this class.
* @param len The length of the incoming data.
* @param buf Pointer to the data buffer.
*/
virtual void ParseBTHIDData(uint8_t len __attribute__((unused)), uint8_t *buf __attribute__((unused))) {
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;
}
/**@}*/
/** L2CAP source CID for HID_Control */
uint8_t control_scid[2];
/** L2CAP source CID for HID_Interrupt */
uint8_t interrupt_scid[2];
private:
HIDReportParser *pRptParser[NUM_PARSERS]; // Pointer to HIDReportParsers.
/** Set report protocol. */
void setProtocol();
uint8_t protocolMode;
void L2CAP_task(); // L2CAP state machine
bool activeConnection; // Used to indicate if it already has established a connection
/* 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 l2cap_state;
};
#endif

View File

@ -0,0 +1,637 @@
/* Copyright (C) 2012 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 "PS3BT.h"
// To enable serial debugging see "settings.h"
//#define EXTRADEBUG // Uncomment to get even more debugging data
//#define PRINTREPORT // Uncomment to print the report send by the PS3 Controllers
PS3BT::PS3BT(BTD *p, uint8_t btadr5, uint8_t btadr4, uint8_t btadr3, uint8_t btadr2, uint8_t btadr1, uint8_t btadr0) :
BluetoothService(p) // Pointer to USB class instance - mandatory
{
pBtd->my_bdaddr[5] = btadr5; // Change to your dongle's Bluetooth address instead
pBtd->my_bdaddr[4] = btadr4;
pBtd->my_bdaddr[3] = btadr3;
pBtd->my_bdaddr[2] = btadr2;
pBtd->my_bdaddr[1] = btadr1;
pBtd->my_bdaddr[0] = btadr0;
HIDBuffer[0] = 0x52; // HID BT Set_report (0x50) | Report Type (Output 0x02)
HIDBuffer[1] = 0x01; // Report ID
// Needed for PS3 Move Controller commands to work via bluetooth
HIDMoveBuffer[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
HIDMoveBuffer[1] = 0x02; // Report ID
/* Set device cid for the control and intterrupt channelse - LSB */
control_dcid[0] = 0x40; // 0x0040
control_dcid[1] = 0x00;
interrupt_dcid[0] = 0x41; // 0x0041
interrupt_dcid[1] = 0x00;
Reset();
}
bool PS3BT::getButtonPress(ButtonEnum b) {
return (ButtonState & pgm_read_dword(&PS3_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(ButtonEnum a) {
return (uint8_t)(l2capinbuf[pgm_read_byte(&PS3_ANALOG_BUTTONS[(uint8_t)a])]);
}
uint8_t PS3BT::getAnalogHat(AnalogHatEnum a) {
return (uint8_t)(l2capinbuf[(uint8_t)a + 15]);
}
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]);
else
return 0;
} 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
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));
} else
return 0;
}
float PS3BT::getAngle(AngleEnum a) {
float accXval, accYval, accZval;
if(PS3Connected) {
// Data for the Kionix KXPC4 used in the DualShock 3
const float zeroG = 511.5f; // 1.65/3.3*1023 (1.65V)
accXval = -((float)getSensor(aX) - zeroG);
accYval = -((float)getSensor(aY) - zeroG);
accZval = -((float)getSensor(aZ) - zeroG);
} else if(PS3MoveConnected) {
// It's a Kionix KXSC4 inside the Motion controller
const uint16_t zeroG = 0x8000;
accXval = -(int16_t)(getSensor(aXmove) - zeroG);
accYval = (int16_t)(getSensor(aYmove) - zeroG);
accZval = (int16_t)(getSensor(aZmove) - zeroG);
} else
return 0;
// 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)
return (atan2f(accYval, accZval) + PI) * RAD_TO_DEG;
else
return (atan2f(accXval, accZval) + PI) * RAD_TO_DEG;
}
float PS3BT::get9DOFValues(SensorEnum a) { // Thanks to Manfred Piendl
if(!PS3MoveConnected)
return 0;
int16_t value = getSensor(a);
if(a == mXmove || a == mYmove || a == mZmove) {
if(value > 2047)
value -= 0x1000;
return (float)value / 3.2f; // unit: muT = 10^(-6) Tesla
} else if(a == aXmove || a == aYmove || a == aZmove) {
if(value < 0)
value += 0x8000;
else
value -= 0x8000;
return (float)value / 442.0f; // unit: m/(s^2)
} else if(a == gXmove || a == gYmove || a == gZmove) {
if(value < 0)
value += 0x8000;
else
value -= 0x8000;
if(a == gXmove)
return (float)value / 11.6f; // unit: deg/s
else if(a == gYmove)
return (float)value / 11.2f; // unit: deg/s
else // gZmove
return (float)value / 9.6f; // unit: deg/s
} else
return 0;
}
String PS3BT::getTemperature() {
if(PS3MoveConnected) {
int16_t input = getSensor(tempMove);
String output = String(input / 100);
output += ".";
if(input % 100 < 10)
output += "0";
output += String(input % 100);
return output;
} else
return "Error";
}
bool PS3BT::getStatus(StatusEnum c) {
return (l2capinbuf[(uint16_t)c >> 8] == ((uint8_t)c & 0xff));
}
void PS3BT::printStatusString() {
char statusOutput[102]; // Max string length plus null character
if(PS3Connected || PS3NavigationConnected) {
strcpy_P(statusOutput, PSTR("\r\nConnectionStatus: "));
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"));
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"));
else strcat_P(statusOutput, PSTR("Error"));
} else if(PS3MoveConnected) {
strcpy_P(statusOutput, PSTR("\r\nPowerRating: "));
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"));
} else
strcpy_P(statusOutput, PSTR("\r\nError"));
USB_HOST_SERIAL.write(statusOutput);
}
void PS3BT::Reset() {
PS3Connected = false;
PS3MoveConnected = false;
PS3NavigationConnected = false;
activeConnection = false;
l2cap_event_flag = 0; // Reset flags
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++)
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 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;
}
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) {
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;
remote_name_first = pBtd->remote_name[0]; // Store the first letter in remote name for the connection
#ifdef DEBUG_USB_HOST
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);
}
#endif
}
}
}
if(checkHciHandle(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) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
Notify(PSTR(" Data: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
#endif
} else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
#ifdef EXTRADEBUG
Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
Notify(PSTR(" SCID: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
Notify(PSTR(" Identifier: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
#endif
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) {
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]) {
//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]) {
//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]) {
//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]) {
//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]) {
#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]) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80);
#endif
identifier = l2capinbuf[9];
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]) {
//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]) {
//Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80);
identifier = l2capinbuf[9];
l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE);
}
}
#ifdef EXTRADEBUG
else {
Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
}
#endif
} else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt
//Notify(PSTR("\r\nL2CAP Interrupt"), 0x80);
if(PS3Connected || PS3MoveConnected || PS3NavigationConnected) {
/* Read Report */
if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT
lastMessageTime = (uint32_t)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)
ButtonState = (uint32_t)(l2capinbuf[10] | ((uint16_t)l2capinbuf[11] << 8) | ((uint32_t)l2capinbuf[12] << 16));
//Notify(PSTR("\r\nButtonState", 0x80);
//PrintHex<uint32_t>(ButtonState, 0x80);
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++) {
D_PrintHex<uint8_t > (l2capinbuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
Notify(PSTR("\r\n"), 0x80);
#endif
}
}
}
L2CAP_task();
}
}
void PS3BT::L2CAP_task() {
switch(l2cap_state) {
case L2CAP_WAIT:
if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80);
#endif
pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, PENDING);
delay(1);
pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, SUCCESSFUL);
identifier++;
delay(1);
pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
l2cap_state = L2CAP_CONTROL_SUCCESS;
}
break;
case L2CAP_CONTROL_SUCCESS:
if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80);
#endif
l2cap_state = L2CAP_INTERRUPT_SETUP;
}
break;
case L2CAP_INTERRUPT_SETUP:
if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80);
#endif
pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, PENDING);
delay(1);
pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, SUCCESSFUL);
identifier++;
delay(1);
pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
}
break;
case L2CAP_INTERRUPT_CONFIG_REQUEST:
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_first == '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
l2cap_state = PS3_ENABLE_SIXAXIS;
timer = (uint32_t)millis();
}
break;
/* These states are handled in Run() */
case L2CAP_INTERRUPT_DISCONNECT:
if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80);
#endif
identifier++;
pBtd->l2cap_disconnection_request(hci_handle, identifier, control_scid, control_dcid);
l2cap_state = L2CAP_CONTROL_DISCONNECT;
}
break;
case L2CAP_CONTROL_DISCONNECT:
if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nDisconnected Control Channel"), 0x80);
#endif
pBtd->hci_disconnect(hci_handle);
hci_handle = -1; // Reset handle
l2cap_event_flag = 0; // Reset flags
l2cap_state = L2CAP_WAIT;
}
break;
}
}
void PS3BT::Run() {
switch(l2cap_state) {
case PS3_ENABLE_SIXAXIS:
if((int32_t)((uint32_t)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 = TURN_ON_LED;
timer = (uint32_t)millis();
}
break;
case TURN_ON_LED:
if((int32_t)((uint32_t)millis() - timer) > 1000) { // loop 1 second before sending the command
if(remote_name_first == '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_first == '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_first == 'M') { // First letter in Motion Controller ('M')
timer = (uint32_t)millis();
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nMotion Controller Enabled\r\n"), 0x80);
#endif
PS3MoveConnected = true;
}
ButtonState = 0; // Clear all values
OldButtonState = 0;
ButtonClickState = 0;
onInit(); // Turn on the LED on the controller
l2cap_state = L2CAP_DONE;
}
break;
case L2CAP_DONE:
if(PS3MoveConnected) { // The Bulb and rumble values, has to be send at approximately every 5th second for it to stay on
if((int32_t)((uint32_t)millis() - timer) > 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
timer = (uint32_t)millis();
}
}
break;
}
}
/************************************************************/
/* HID Commands */
/************************************************************/
// Playstation Sixaxis Dualshock and Navigation Controller commands
void PS3BT::HID_Command(uint8_t* data, uint8_t nbytes) {
if((int32_t)((uint32_t)millis() - timerHID) <= 150) // Check if is has been more than 150ms since last command
delay((uint32_t)(150 - ((uint32_t)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 = (uint32_t)millis();
}
void PS3BT::setAllOff() {
HIDBuffer[3] = 0x00; // Rumble bytes
HIDBuffer[4] = 0x00;
HIDBuffer[5] = 0x00;
HIDBuffer[6] = 0x00;
HIDBuffer[11] = 0x00; // LED byte
HID_Command(HIDBuffer, HID_BUFFERSIZE);
}
void PS3BT::setRumbleOff() {
uint8_t rumbleBuf[HID_BUFFERSIZE];
memcpy(rumbleBuf, HIDBuffer, HID_BUFFERSIZE);
rumbleBuf[3] = 0x00;
rumbleBuf[4] = 0x00;
rumbleBuf[5] = 0x00;
rumbleBuf[6] = 0x00;
HID_Command(rumbleBuf, HID_BUFFERSIZE);
}
void PS3BT::setRumbleOn(RumbleEnum mode) {
uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow
if(mode == RumbleHigh) {
power[0] = 0x00;
power[1] = 0xff;
}
setRumbleOn(0xfe, power[0], 0xfe, power[1]);
}
void PS3BT::setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower) {
uint8_t rumbleBuf[HID_BUFFERSIZE];
memcpy(rumbleBuf, HIDBuffer, HID_BUFFERSIZE);
rumbleBuf[3] = rightDuration;
rumbleBuf[4] = rightPower;
rumbleBuf[5] = leftDuration;
rumbleBuf[6] = leftPower;
HID_Command(rumbleBuf, HID_BUFFERSIZE);
}
void PS3BT::setLedRaw(uint8_t value) {
HIDBuffer[11] = value << 1;
HID_Command(HIDBuffer, HID_BUFFERSIZE);
}
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(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(LEDEnum a) {
HIDBuffer[11] ^= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1);
HID_Command(HIDBuffer, HID_BUFFERSIZE);
}
void PS3BT::enable_sixaxis() { // Command used to enable the Dualshock 3 and Navigation controller to send data via Bluetooth
uint8_t cmd_buf[6];
cmd_buf[0] = 0x53; // HID BT Set_report (0x50) | Report Type (Feature 0x03)
cmd_buf[1] = 0xF4; // Report ID
cmd_buf[2] = 0x42; // Special PS3 Controller enable commands
cmd_buf[3] = 0x03;
cmd_buf[4] = 0x00;
cmd_buf[5] = 0x00;
HID_Command(cmd_buf, 6);
}
// Playstation Move Controller commands
void PS3BT::HIDMove_Command(uint8_t* data, uint8_t nbytes) {
if((int32_t)((uint32_t)millis() - timerHID) <= 150)// Check if is has been less than 150ms since last command
delay((uint32_t)(150 - ((uint32_t)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 = (uint32_t)millis();
}
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;
HIDMoveBuffer[5] = b;
HIDMove_Command(HIDMoveBuffer, HID_BUFFERSIZE);
}
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));
}
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)
Notify(PSTR("\r\nThe rumble value has to at least 64, or approximately 25%"), 0x80);
#endif
// Set the rumble value into the write buffer
HIDMoveBuffer[7] = rumble;
HIDMove_Command(HIDMoveBuffer, HID_BUFFERSIZE);
}
void PS3BT::onInit() {
if(pFuncOnInit)
pFuncOnInit(); // Call the user function
else {
if(PS3MoveConnected)
moveSetBulb(Red);
else // Dualshock 3 or Navigation controller
setLedOn(static_cast<LEDEnum>(LED1));
}
}

View File

@ -0,0 +1,240 @@
/* Copyright (C) 2012 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 _ps3bt_h_
#define _ps3bt_h_
#include "BTD.h"
#include "PS3Enums.h"
#define HID_BUFFERSIZE 50 // Size of the buffer for the Playstation Motion Controller
/**
* This BluetoothService class implements support for all the official PS3 Controllers:
* Dualshock 3, Navigation or a Motion controller via Bluetooth.
*
* Information about the protocol can be found at the wiki: https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information.
*/
class PS3BT : public BluetoothService {
public:
/**
* Constructor for the PS3BT class.
* @param pBtd Pointer to BTD class instance.
* @param btadr5,btadr4,btadr3,btadr2,btadr1,btadr0
* Pass your dongles Bluetooth address into the constructor,
* This will set BTD#my_bdaddr, so you don't have to plug in the dongle before pairing with your controller.
*/
PS3BT(BTD *pBtd, uint8_t btadr5 = 0, uint8_t btadr4 = 0, uint8_t btadr3 = 0, uint8_t btadr2 = 0, uint8_t btadr1 = 0, uint8_t btadr0 = 0);
/** @name BluetoothService implementation */
/** Used this to disconnect any of the controllers. */
void disconnect();
/**@}*/
/** @name PS3 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 PS3 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);
/**
* Used to read the sensors inside the Dualshock 3 and Move controller.
* @param a
* The Dualshock 3 has a 3-axis accelerometer and a 1-axis gyro inside.
* The Move controller has a 3-axis accelerometer, a 3-axis gyro, a 3-axis magnetometer
* and a temperature sensor inside.
* @return Return the raw sensor value.
*/
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.
*/
float 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.
*/
float get9DOFValues(SensorEnum a);
/**
* Get the status from the controller.
* @param c The ::StatusEnum you want to read.
* @return True if correct and false if not.
*/
bool getStatus(StatusEnum c);
/** 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.
*/
String getTemperature();
/** Used to set all LEDs and rumble off. */
void setAllOff();
/** Turn off rumble. */
void setRumbleOff();
/**
* Turn on rumble.
* @param mode Either ::RumbleHigh or ::RumbleLow.
*/
void setRumbleOn(RumbleEnum mode);
/**
* 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.
* @param leftPower The intensity of the left/high rumble effect.
*/
void setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower);
/**
* Set LED value without using ::LEDEnum.
* @param value See: ::LEDEnum.
*/
void setLedRaw(uint8_t value);
/** Turn all LEDs off. */
void setLedOff() {
setLedRaw(0);
};
/**
* Turn the specific LED off.
* @param a The ::LEDEnum to turn off.
*/
void setLedOff(LEDEnum a);
/**
* Turn the specific LED on.
* @param a The ::LEDEnum to turn on.
*/
void setLedOn(LEDEnum a);
/**
* Toggle the specific LED.
* @param a The ::LEDEnum to toggle.
*/
void setLedToggle(LEDEnum a);
/**
* Use this to set the Color using RGB values.
* @param r,g,b RGB value.
*/
void moveSetBulb(uint8_t r, uint8_t g, uint8_t b);
/**
* Use this to set the color using the predefined colors in ::ColorsEnum.
* @param color The desired color.
*/
void moveSetBulb(ColorsEnum color);
/**
* Set the rumble value inside the Move controller.
* @param rumble The desired value in the range from 64-255.
*/
void moveSetRumble(uint8_t rumble);
/** Used to get the millis() of the last message */
uint32_t getLastMessageTime() {
return lastMessageTime;
};
/**@}*/
/** Variable used to indicate if the normal Playstation controller is successfully connected. */
bool PS3Connected;
/** Variable used to indicate if the Move controller is successfully connected. */
bool PS3MoveConnected;
/** Variable used to indicate if the Navigation controller is successfully connected. */
bool PS3NavigationConnected;
protected:
/** @name BluetoothService implementation */
/**
* Used to pass acldata to the services.
* @param ACLData Incoming acldata.
*/
void ACLData(uint8_t* ACLData);
/** Used to run part of the state machine. */
void Run();
/** Use this to reset the service. */
void Reset();
/**
* Called when the controller 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();
/**@}*/
private:
void L2CAP_task(); // L2CAP state machine
/* Variables filled from HCI event management */
char remote_name_first; // First letter in remote name
bool activeConnection; // Used to indicate if it's already has established a connection
/* Variables used by high level L2CAP task */
uint8_t l2cap_state;
uint32_t lastMessageTime; // Variable used to store the millis value of the last message.
uint32_t ButtonState;
uint32_t OldButtonState;
uint32_t ButtonClickState;
uint32_t timer; // Timer used to limit time between messages and also used to continuously set PS3 Move controller Bulb and rumble values
uint32_t timerHID; // Timer used see if there has to be a delay before a new HID command
uint8_t l2capinbuf[BULK_MAXPKTSIZE]; // General purpose buffer for L2CAP in data
uint8_t HIDBuffer[HID_BUFFERSIZE]; // Used to store HID commands
uint8_t HIDMoveBuffer[HID_BUFFERSIZE]; // Used to store HID commands for the Move controller
/* L2CAP Channels */
uint8_t control_scid[2]; // L2CAP source CID for HID_Control
uint8_t control_dcid[2]; // 0x0040
uint8_t interrupt_scid[2]; // L2CAP source CID for HID_Interrupt
uint8_t interrupt_dcid[2]; // 0x0041
/* HID Commands */
void HID_Command(uint8_t* data, uint8_t nbytes);
void HIDMove_Command(uint8_t* data, uint8_t nbytes);
void enable_sixaxis(); // Command used to enable the Dualshock 3 and Navigation controller to send data via Bluetooth
};
#endif

View File

@ -0,0 +1,141 @@
/* Copyright (C) 2012 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 _ps3enums_h
#define _ps3enums_h
#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[PS3_REPORT_BUFFER_SIZE] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0x27, 0x10, 0x00, 0x32,
0xff, 0x27, 0x10, 0x00, 0x32,
0xff, 0x27, 0x10, 0x00, 0x32,
0xff, 0x27, 0x10, 0x00, 0x32,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/** 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 PS3_LEDS[] PROGMEM = {
0x00, // OFF
0x01, // LED1
0x02, // LED2
0x04, // LED3
0x08, // LED4
0x09, // LED5
0x0A, // LED6
0x0C, // LED7
0x0D, // LED8
0x0E, // LED9
0x0F, // LED10
};
/**
* Buttons on the controllers.
* <B>Note:</B> that the location is shifted 9 when it's connected via USB.
*/
const uint32_t PS3_BUTTONS[] PROGMEM = {
0x10, // UP
0x20, // RIGHT
0x40, // DOWN
0x80, // LEFT
0x01, // SELECT
0x08, // START
0x02, // L3
0x04, // R3
0x0100, // L2
0x0200, // R2
0x0400, // L1
0x0800, // R1
0x1000, // TRIANGLE
0x2000, // CIRCLE
0x4000, // CROSS
0x8000, // SQUARE
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
};
/**
* Analog buttons on the controllers.
* <B>Note:</B> that the location is shifted 9 when it's connected via USB.
*/
const uint8_t PS3_ANALOG_BUTTONS[] PROGMEM = {
23, // UP_ANALOG
24, // RIGHT_ANALOG
25, // DOWN_ANALOG
26, // LEFT_ANALOG
0, 0, 0, 0, // Skip SELECT, L3, R3 and START
27, // L2_ANALOG
28, // R2_ANALOG
29, // L1_ANALOG
30, // R1_ANALOG
31, // TRIANGLE_ANALOG
32, // CIRCLE_ANALOG
33, // CROSS_ANALOG
34, // SQUARE_ANALOG
0, 0, // Skip PS and MOVE
// Playstation Move Controller
15, // T_ANALOG - Both at byte 14 (last reading) and byte 15 (current reading)
};
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,
Charging = (39 << 8) | 0xEE,
NotCharging = (39 << 8) | 0xF1,
Shutdown = (39 << 8) | 0x01,
Dying = (39 << 8) | 0x02,
Low = (39 << 8) | 0x03,
High = (39 << 8) | 0x04,
Full = (39 << 8) | 0x05,
MoveCharging = (21 << 8) | 0xEE,
MoveNotCharging = (21 << 8) | 0xF1,
MoveShutdown = (21 << 8) | 0x01,
MoveDying = (21 << 8) | 0x02,
MoveLow = (21 << 8) | 0x03,
MoveHigh = (21 << 8) | 0x04,
MoveFull = (21 << 8) | 0x05,
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
};
#endif

View File

@ -0,0 +1,574 @@
/* Copyright (C) 2012 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 "PS3USB.h"
// To enable serial debugging see "settings.h"
//#define EXTRADEBUG // Uncomment to get even more debugging data
//#define PRINTREPORT // Uncomment to print the report send by the PS3 Controllers
PS3USB::PS3USB(USB *p, uint8_t btadr5, uint8_t btadr4, uint8_t btadr3, uint8_t btadr2, uint8_t btadr1, uint8_t btadr0) :
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++) {
epInfo[i].epAddr = 0;
epInfo[i].maxPktSize = (i) ? 0 : 8;
epInfo[i].bmSndToggle = 0;
epInfo[i].bmRcvToggle = 0;
epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
}
if(pUsb) // register in USB subsystem
pUsb->RegisterDeviceClass(this); //set devConfig[] entry
my_bdaddr[5] = btadr5; // Change to your dongle's Bluetooth address instead
my_bdaddr[4] = btadr4;
my_bdaddr[3] = btadr3;
my_bdaddr[2] = btadr2;
my_bdaddr[1] = btadr1;
my_bdaddr[0] = btadr0;
}
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<USB_DEVICE_DESCRIPTOR*>(buf);
uint8_t rcode;
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
uint16_t PID;
uint16_t VID;
// get memory address of USB device address pool
AddressPool &addrPool = pUsb->GetAddressPool();
#ifdef EXTRADEBUG
Notify(PSTR("\r\nPS3USB Init"), 0x80);
#endif
// check if address has already been assigned to an instance
if(bAddress) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nAddress in use"), 0x80);
#endif
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
}
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
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) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nepinfo is null"), 0x80);
#endif
return USB_ERROR_EPINFO_IS_NULL;
}
// 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;
p->lowspeed = lowspeed;
// Get device descriptor
rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
// Restore p->epinfo
p->epinfo = oldep_ptr;
if(rcode)
goto FailGetDevDescr;
VID = udd->idVendor;
PID = udd->idProduct;
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)
return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
// Extract Max Packet Size from device descriptor
epInfo[0].maxPktSize = udd->bMaxPacketSize0;
// Assign new address to the device
rcode = pUsb->setAddr(0, 0, bAddress);
if(rcode) {
p->lowspeed = false;
addrPool.FreeAddress(bAddress);
bAddress = 0;
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nsetAddr: "), 0x80);
D_PrintHex<uint8_t > (rcode, 0x80);
#endif
return rcode;
}
#ifdef EXTRADEBUG
Notify(PSTR("\r\nAddr: "), 0x80);
D_PrintHex<uint8_t > (bAddress, 0x80);
#endif
//delay(300); // Spec says you should wait at least 200ms
p->lowspeed = false;
//get pointer to assigned address record
p = addrPool.GetUsbDevicePtr(bAddress);
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)
goto FailSetDevTblEntry;
/* The application will work in reduced host mode, so we can save program and data
memory space. After verifying the PID and VID we will use known values for the
configuration values for device, interface, endpoints and HID for the PS3 Controllers */
/* Initialize data structures for endpoints of device */
epInfo[ PS3_OUTPUT_PIPE ].epAddr = 0x02; // PS3 output endpoint
epInfo[ PS3_OUTPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_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 = 0;
epInfo[ PS3_OUTPUT_PIPE ].bmRcvToggle = 0;
epInfo[ PS3_INPUT_PIPE ].epAddr = 0x01; // PS3 report endpoint
epInfo[ PS3_INPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_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 = 0;
epInfo[ PS3_INPUT_PIPE ].bmRcvToggle = 0;
rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
if(rcode)
goto FailSetDevTblEntry;
delay(200); //Give time for address change
rcode = pUsb->setConf(bAddress, epInfo[ PS3_CONTROL_PIPE ].epAddr, 1);
if(rcode)
goto FailSetConfDescr;
if(PID == PS3_PID || PID == PS3NAVIGATION_PID) {
if(PID == PS3_PID) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80);
#endif
PS3Connected = true;
} else { // must be a navigation controller
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nNavigation Controller Connected"), 0x80);
#endif
PS3NavigationConnected = true;
}
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++)
writeBuf[i] = pgm_read_byte(&PS3_REPORT_BUFFER[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
Notify(PSTR("\r\nMotion Controller Connected"), 0x80);
#endif
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)
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--) {
D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
Notify(PSTR(":"), 0x80);
}
D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
#endif
}
onInit();
bPollEnable = true;
Notify(PSTR("\r\n"), 0x80);
timer = (uint32_t)millis();
return 0; // Successful configuration
/* Diagnostic messages */
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr();
goto Fail;
#endif
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry();
goto Fail;
#endif
FailSetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailSetConfDescr();
#endif
goto Fail;
FailUnknownDevice:
#ifdef DEBUG_USB_HOST
NotifyFailUnknownDevice(VID, PID);
#endif
rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
Fail:
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nPS3 Init Failed, error code: "), 0x80);
NotifyFail(rcode);
#endif
Release();
return rcode;
}
/* Performs a cleanup after failed Init() attempt */
uint8_t PS3USB::Release() {
PS3Connected = false;
PS3MoveConnected = false;
PS3NavigationConnected = false;
pUsb->GetAddressPool().FreeAddress(bAddress);
bAddress = 0;
bPollEnable = false;
return 0;
}
uint8_t PS3USB::Poll() {
if(!bPollEnable)
return 0;
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((int32_t)((uint32_t)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((int32_t)((uint32_t)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 = (uint32_t)millis();
}
}
return 0;
}
void PS3USB::readReport() {
ButtonState = (uint32_t)(readBuf[2] | ((uint16_t)readBuf[3] << 8) | ((uint32_t)readBuf[4] << 16));
//Notify(PSTR("\r\nButtonState", 0x80);
//PrintHex<uint32_t>(ButtonState, 0x80);
if(ButtonState != OldButtonState) {
ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
OldButtonState = ButtonState;
}
}
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++) {
D_PrintHex<uint8_t > (readBuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
Notify(PSTR("\r\n"), 0x80);
#endif
}
bool PS3USB::getButtonPress(ButtonEnum b) {
return (ButtonState & pgm_read_dword(&PS3_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(ButtonEnum a) {
return (uint8_t)(readBuf[(pgm_read_byte(&PS3_ANALOG_BUTTONS[(uint8_t)a])) - 9]);
}
uint8_t PS3USB::getAnalogHat(AnalogHatEnum a) {
return (uint8_t)(readBuf[((uint8_t)a + 6)]);
}
uint16_t PS3USB::getSensor(SensorEnum a) {
return ((readBuf[((uint16_t)a) - 9] << 8) | readBuf[((uint16_t)a + 1) - 9]);
}
float PS3USB::getAngle(AngleEnum a) {
if(PS3Connected) {
float accXval, accYval, accZval;
// Data for the Kionix KXPC4 used in the DualShock 3
const float zeroG = 511.5f; // 1.65/3.3*1023 (1,65V)
accXval = -((float)getSensor(aX) - zeroG);
accYval = -((float)getSensor(aY) - zeroG);
accZval = -((float)getSensor(aZ) - zeroG);
// 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)
return (atan2f(accYval, accZval) + PI) * RAD_TO_DEG;
else
return (atan2f(accXval, accZval) + PI) * RAD_TO_DEG;
} else
return 0;
}
bool PS3USB::getStatus(StatusEnum c) {
return (readBuf[((uint16_t)c >> 8) - 9] == ((uint8_t)c & 0xff));
}
void PS3USB::printStatusString() {
char statusOutput[102]; // Max string length plus null character
if(PS3Connected || PS3NavigationConnected) {
strcpy_P(statusOutput, PSTR("\r\nConnectionStatus: "));
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"));
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"));
else strcat_P(statusOutput, PSTR("Error"));
} else
strcpy_P(statusOutput, PSTR("\r\nError"));
USB_HOST_SERIAL.write(statusOutput);
}
/* Playstation Sixaxis Dualshock and Navigation Controller commands */
void PS3USB::PS3_Command(uint8_t *data, uint16_t nbytes) {
// bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x01), Report Type (Output 0x02), interface (0x00), datalength, datalength, data)
pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x01, 0x02, 0x00, nbytes, nbytes, data, NULL);
}
void PS3USB::setAllOff() {
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);
}
void PS3USB::setRumbleOff() {
uint8_t rumbleBuf[EP_MAXPKTSIZE];
memcpy(rumbleBuf, writeBuf, EP_MAXPKTSIZE);
rumbleBuf[1] = 0x00;
rumbleBuf[2] = 0x00; // Low mode off
rumbleBuf[3] = 0x00;
rumbleBuf[4] = 0x00; // High mode off
PS3_Command(rumbleBuf, PS3_REPORT_BUFFER_SIZE);
}
void PS3USB::setRumbleOn(RumbleEnum mode) {
if((mode & 0x30) > 0x00) {
uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow
if(mode == RumbleHigh) {
power[0] = 0x00;
power[1] = 0xff;
}
setRumbleOn(0xfe, power[0], 0xfe, power[1]);
}
}
void PS3USB::setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower) {
uint8_t rumbleBuf[EP_MAXPKTSIZE];
memcpy(rumbleBuf, writeBuf, EP_MAXPKTSIZE);
rumbleBuf[1] = rightDuration;
rumbleBuf[2] = rightPower;
rumbleBuf[3] = leftDuration;
rumbleBuf[4] = leftPower;
PS3_Command(rumbleBuf, PS3_REPORT_BUFFER_SIZE);
}
void PS3USB::setLedRaw(uint8_t value) {
writeBuf[9] = value << 1;
PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
}
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(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(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::setBdaddr(uint8_t *bdaddr) {
/* Set the internal Bluetooth address */
uint8_t buf[8];
buf[0] = 0x01;
buf[1] = 0x00;
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
pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
}
void PS3USB::getBdaddr(uint8_t *bdaddr) {
uint8_t buf[8];
// 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++)
bdaddr[5 - i] = buf[i + 2]; // Copy into buffer reversed, so it is LSB first
}
void PS3USB::enable_sixaxis() { // Command used to enable the Dualshock 3 and Navigation controller to send data via USB
uint8_t cmd_buf[4];
cmd_buf[0] = 0x42; // Special PS3 Controller enable commands
cmd_buf[1] = 0x0c;
cmd_buf[2] = 0x00;
cmd_buf[3] = 0x00;
// bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0xF4), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data)
pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF4, 0x03, 0x00, 4, 4, cmd_buf, NULL);
}
/* Playstation Move Controller commands */
void PS3USB::Move_Command(uint8_t *data, uint16_t nbytes) {
pUsb->outTransfer(bAddress, epInfo[ PS3_OUTPUT_PIPE ].epAddr, nbytes, data);
}
void PS3USB::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
writeBuf[2] = r;
writeBuf[3] = g;
writeBuf[4] = b;
Move_Command(writeBuf, MOVE_REPORT_BUFFER_SIZE);
}
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));
}
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)
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
Move_Command(writeBuf, MOVE_REPORT_BUFFER_SIZE);
}
void PS3USB::setMoveBdaddr(uint8_t *bdaddr) {
/* Set the internal Bluetooth address */
uint8_t buf[11];
buf[0] = 0x05;
buf[7] = 0x10;
buf[8] = 0x01;
buf[9] = 0x02;
buf[10] = 0x12;
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
pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
}
void PS3USB::getMoveBdaddr(uint8_t *bdaddr) {
uint8_t buf[16];
// 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++)
bdaddr[i] = buf[10 + i];
}
void PS3USB::getMoveCalibration(uint8_t *data) {
uint8_t buf[49];
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(uint8_t j = 0; j < 49; j++)
data[49 * i + j] = buf[j];
}
}
void PS3USB::onInit() {
if(pFuncOnInit)
pFuncOnInit(); // Call the user function
else {
if(PS3MoveConnected)
moveSetBulb(Red);
else // Dualshock 3 or Navigation controller
setLedOn(static_cast<LEDEnum>(LED1));
}
}

View File

@ -0,0 +1,303 @@
/* Copyright (C) 2012 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 _ps3usb_h_
#define _ps3usb_h_
#include "Usb.h"
#include "usbhid.h"
#include "PS3Enums.h"
/* PS3 data taken from descriptors */
#define EP_MAXPKTSIZE 64 // max size for data via USB
/* Names we give to the 3 ps3 pipes - this is only used for setting the bluetooth address into the ps3 controllers */
#define PS3_CONTROL_PIPE 0
#define PS3_OUTPUT_PIPE 1
#define PS3_INPUT_PIPE 2
//PID and VID of the different devices
#define PS3_VID 0x054C // Sony Corporation
#define PS3_PID 0x0268 // PS3 Controller DualShock 3
#define PS3NAVIGATION_PID 0x042F // Navigation controller
#define PS3MOVE_PID 0x03D5 // Motion controller
#define PS3_MAX_ENDPOINTS 3
/**
* This class implements support for all the official PS3 Controllers:
* Dualshock 3, Navigation or a Motion controller via USB.
*
* One can only set the color of the bulb, set the rumble, set and get the bluetooth address and calibrate the magnetometer via USB on the Move controller.
*
* Information about the protocol can be found at the wiki: https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information.
*/
class PS3USB : public USBDeviceConfig {
public:
/**
* Constructor for the PS3USB class.
* @param pUsb Pointer to USB class instance.
* @param btadr5,btadr4,btadr3,btadr2,btadr1,btadr0
* Pass your dongles Bluetooth address into the constructor,
* so you are able to pair the controller with a Bluetooth dongle.
*/
PS3USB(USB *pUsb, uint8_t btadr5 = 0, uint8_t btadr4 = 0, uint8_t btadr3 = 0, uint8_t btadr2 = 0, uint8_t btadr1 = 0, uint8_t btadr0 = 0);
/** @name USBDeviceConfig implementation */
/**
* Initialize the PS3 Controller.
* @param parent Hub number.
* @param port Port number on the hub.
* @param lowspeed Speed of the device.
* @return 0 on success.
*/
uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
/**
* Release the USB device.
* @return 0 on success.
*/
uint8_t Release();
/**
* Poll the USB Input endpoins and run the state machines.
* @return 0 on success.
*/
uint8_t Poll();
/**
* Get the device address.
* @return The device address.
*/
virtual uint8_t GetAddress() {
return bAddress;
};
/**
* Used to check if the controller has been initialized.
* @return True if it's ready.
*/
virtual bool isReady() {
return bPollEnable;
};
/**
* 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 bool VIDPIDOK(uint16_t vid, uint16_t pid) {
return (vid == PS3_VID && (pid == PS3_PID || pid == PS3NAVIGATION_PID || pid == PS3MOVE_PID));
};
/**@}*/
/**
* Used to set the Bluetooth address inside the Dualshock 3 and Navigation controller.
* Set using LSB first.
* @param bdaddr Your dongles Bluetooth address.
*/
void setBdaddr(uint8_t *bdaddr);
/**
* Used to get the Bluetooth address inside the Dualshock 3 and Navigation controller.
* Will return LSB first.
* @param bdaddr Your dongles Bluetooth address.
*/
void getBdaddr(uint8_t *bdaddr);
/**
* Used to set the Bluetooth address inside the Move controller.
* Set using LSB first.
* @param bdaddr Your dongles Bluetooth address.
*/
void setMoveBdaddr(uint8_t *bdaddr);
/**
* Used to get the Bluetooth address inside the Move controller.
* Will return LSB first.
* @param bdaddr Your dongles Bluetooth address.
*/
void getMoveBdaddr(uint8_t *bdaddr);
/**
* Used to get the calibration data inside the Move controller.
* @param data Buffer to store data in. Must be at least 147 bytes
*/
void getMoveCalibration(uint8_t *data);
/** @name PS3 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 PS3 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);
/**
* 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(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.
*/
float getAngle(AngleEnum a);
/**
* Get the ::StatusEnum from the controller.
* @param c The ::StatusEnum you want to read.
* @return True if correct and false if not.
*/
bool getStatus(StatusEnum c);
/** 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();
/** Turn off rumble. */
void setRumbleOff();
/**
* Turn on rumble.
* @param mode Either ::RumbleHigh or ::RumbleLow.
*/
void setRumbleOn(RumbleEnum mode);
/**
* 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.
* @param leftPower The intensity of the left/high rumble effect.
*/
void setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower);
/**
* Set LED value without using the ::LEDEnum.
* @param value See: ::LEDEnum.
*/
void setLedRaw(uint8_t value);
/** Turn all LEDs off. */
void setLedOff() {
setLedRaw(0);
}
/**
* Turn the specific ::LEDEnum off.
* @param a The ::LEDEnum to turn off.
*/
void setLedOff(LEDEnum a);
/**
* Turn the specific ::LEDEnum on.
* @param a The ::LEDEnum to turn on.
*/
void setLedOn(LEDEnum a);
/**
* Toggle the specific ::LEDEnum.
* @param a The ::LEDEnum to toggle.
*/
void setLedToggle(LEDEnum a);
/**
* Use this to set the Color using RGB values.
* @param r,g,b RGB value.
*/
void moveSetBulb(uint8_t r, uint8_t g, uint8_t b);
/**
* Use this to set the color using the predefined colors in ::ColorsEnum.
* @param color The desired color.
*/
void moveSetBulb(ColorsEnum color);
/**
* Set the rumble value inside the Move controller.
* @param rumble The desired value in the range from 64-255.
*/
void moveSetRumble(uint8_t rumble);
/**
* Used to call your own function when the controller is successfully initialized.
* @param funcOnInit Function to call.
*/
void attachOnInit(void (*funcOnInit)(void)) {
pFuncOnInit = funcOnInit;
};
/**@}*/
/** Variable used to indicate if the normal playstation controller is successfully connected. */
bool PS3Connected;
/** Variable used to indicate if the move controller is successfully connected. */
bool PS3MoveConnected;
/** Variable used to indicate if the navigation controller is successfully connected. */
bool PS3NavigationConnected;
protected:
/** Pointer to USB class instance. */
USB *pUsb;
/** Device address. */
uint8_t bAddress;
/** Endpoint info structure. */
EpInfo epInfo[PS3_MAX_ENDPOINTS];
private:
/**
* Called when the controller 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();
void (*pFuncOnInit)(void); // Pointer to function called in onInit()
bool bPollEnable;
uint32_t timer; // used to continuously set PS3 Move controller Bulb and rumble values
uint32_t ButtonState;
uint32_t OldButtonState;
uint32_t ButtonClickState;
uint8_t my_bdaddr[6]; // Change to your dongles Bluetooth address in the constructor
uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
uint8_t writeBuf[EP_MAXPKTSIZE]; // General purpose buffer for output data
void readReport(); // read incoming data
void printReport(); // print incoming date - Uncomment for debugging
/* Private commands */
void PS3_Command(uint8_t *data, uint16_t nbytes);
void enable_sixaxis(); // Command used to enable the Dualshock 3 and Navigation controller to send data via USB
void Move_Command(uint8_t *data, uint16_t nbytes);
};
#endif

View File

@ -0,0 +1,121 @@
/* 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 "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 BTHID, public PS4Parser {
public:
/**
* Constructor for the PS4BT class.
* @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) {
PS4Parser::Reset();
};
/**
* Used to check if a PS4 controller is connected.
* @return Returns true if it is connected.
*/
bool connected() {
return BTHID::connected;
};
protected:
/** @name BTHID implementation */
/**
* Used to parse Bluetooth HID data.
* @param len The length of the incoming data.
* @param buf Pointer to the data buffer.
*/
virtual void ParseBTHIDData(uint8_t len, uint8_t *buf) {
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 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 */
virtual void ResetBTHID() {
PS4Parser::Reset();
};
/**@}*/
/** @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->smallRumble; // Small Rumble
buf[8] = output->bigRumble; // Big 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));
};
/**@}*/
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)
buf[1] = 0x02; // Report ID
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]);
};
};
#endif

View File

@ -0,0 +1,153 @@
/* 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 "PS4Parser.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,
};
// To enable serial debugging see "settings.h"
//#define PRINTREPORT // Uncomment to print the report send by the PS4 Controller
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 PS4Parser::getButtonPress(ButtonEnum b) {
if (b <= LEFT) // Dpad
return checkDpad(b);
else
return ps4Data.btn.val & (1UL << pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]));
}
bool PS4Parser::getButtonClick(ButtonEnum b) {
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;
}
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;
}
uint8_t PS4Parser::getAnalogHat(AnalogHatEnum a) {
return ps4Data.hatValue[(uint8_t)a];
}
void PS4Parser::Parse(uint8_t len, uint8_t *buf) {
if (len > 1 && buf) {
#ifdef PRINTREPORT
Notify(PSTR("\r\n"), 0x80);
for (uint8_t i = 0; i < len; i++) {
D_PrintHex<uint8_t > (buf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
#endif
if (buf[0] == 0x01) // Check report ID
memcpy(&ps4Data, buf + 1, min((uint8_t)(len - 1), MFK_CASTUINT8T sizeof(ps4Data)));
else if (buf[0] == 0x11) { // This report is send via Bluetooth, it has an offset of 2 compared to the USB data
if (len < 4) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nReport is too short: "), 0x80);
D_PrintHex<uint8_t > (len, 0x80);
#endif
return;
}
memcpy(&ps4Data, buf + 3, min((uint8_t)(len - 3), MFK_CASTUINT8T sizeof(ps4Data)));
} else {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nUnknown report id: "), 0x80);
D_PrintHex<uint8_t > (buf[0], 0x80);
#endif
return;
}
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;
}
}
}
if (ps4Output.reportChanged)
sendOutputReport(&ps4Output); // Send output report
}
void PS4Parser::Reset() {
uint8_t i;
for (i = 0; i < sizeof(ps4Data.hatValue); i++)
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++) {
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;
ps4Output.bigRumble = ps4Output.smallRumble = 0;
ps4Output.r = ps4Output.g = ps4Output.b = 0;
ps4Output.flashOn = ps4Output.flashOff = 0;
ps4Output.reportChanged = false;
};

View File

@ -0,0 +1,373 @@
/* 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 "Usb.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 reportCounter : 6;
} __attribute__((packed));
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?
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
uint16_t x : 12;
uint16_t y : 12;
} __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];
PS4Buttons btn;
uint8_t trigger[2];
/* 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;
int16_t accX, accZ, accY;
uint8_t dummy2[5];
PS4Status status;
uint8_t dummy3[3];
/* The rest is data for 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.
// 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));
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));
/** 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 b 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 b);
/**
* 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);
/**
* 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;
};
/**
* 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.
*/
float getAngle(AngleEnum a) {
if (a == Pitch)
return (atan2f(ps4Data.accY, ps4Data.accZ) + PI) * RAD_TO_DEG;
else
return (atan2f(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:
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;
}
};
/**
* 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();
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(0x00, 0xFF);
else
setRumbleOn(0xFF, 0x00);
};
/**
* 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:
/**
* 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();
/**
* 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
PS4Data ps4Data;
PS4Buttons oldButtonState, buttonClickState;
PS4Output ps4Output;
uint8_t oldDpad;
};
#endif

View File

@ -0,0 +1,131 @@
/* 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
#define PS4_PID_SLIM 0x09CC // PS4 Slim 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 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 || HIDUniversal::PID == PS4_PID_SLIM);
};
/**
* 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.
* @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(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
if (HIDUniversal::VID == PS4_VID && (HIDUniversal::PID == PS4_PID || HIDUniversal::PID == PS4_PID_SLIM))
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() {
if (HIDUniversal::VID == PS4_VID && (HIDUniversal::PID == PS4_PID || HIDUniversal::PID == PS4_PID_SLIM)) {
PS4Parser::Reset();
if (pFuncOnInit)
pFuncOnInit(); // Call the user function
else
setLed(Blue);
};
return 0;
};
/**@}*/
/** @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->smallRumble; // Small Rumble
buf[5] = output->bigRumble; // Big 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);
};
/**@}*/
/** @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 bool VIDPIDOK(uint16_t vid, uint16_t pid) {
return (vid == PS4_VID && (pid == PS4_PID || HIDUniversal::PID == PS4_PID_SLIM));
};
/**@}*/
private:
void (*pFuncOnInit)(void); // Pointer to function called in onInit()
};
#endif

View File

@ -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(USBHID *hid __attribute__((unused)), bool is_rpt_id __attribute__((unused)), uint8_t len, uint8_t *buf) {
if (HIDUniversal::VID == PSBUZZ_VID && HIDUniversal::PID == PSBUZZ_PID && len > 2 && buf) {
#ifdef PRINTREPORT
Notify(PSTR("\r\n"), 0x80);
for (uint8_t i = 0; i < len; i++) {
D_PrintHex<uint8_t > (buf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
#endif
memcpy(&psbuzzButtons, buf + 2, min((uint8_t)(len - 2), MFK_CASTUINT8T 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_HID_OUT, HID_REQUEST_SET_REPORT, 0x00, 0x02, 0x00, nbytes, nbytes, data, NULL);
};

View File

@ -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.
*/
void ParseHIDData(USBHID *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.
*/
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 bool 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

View File

@ -0,0 +1,380 @@
# USB Host Library Rev.2.0
The code is released under the GNU General Public License.
__________
[![Build Status](https://travis-ci.org/felis/USB_Host_Shield_2.0.svg?branch=master)](https://travis-ci.org/felis/USB_Host_Shield_2.0)
# Summary
This is Revision 2.0 of MAX3421E-based USB Host Shield Library for AVR's.
Project main web site is: <http://www.circuitsathome.com>.
Some information can also be found at: <http://blog.tkjelectronics.dk/>.
The shield can be purchased at the main site: <http://www.circuitsathome.com/products-page/arduino-shields> or from [TKJ Electronics](http://tkjelectronics.com/): <http://shop.tkjelectronics.dk/product_info.php?products_id=43>.
![USB Host Shield](http://shop.tkjelectronics.dk/images/USB_Host_Shield1.jpg)
For more information about the hardware see the [Hardware Manual](http://www.circuitsathome.com/usb-host-shield-hardware-manual).
# Developed By
* __Oleg Mazurov, Circuits@Home__ - <mazurov@circuitsathome.com>
* __Alexei Glushchenko, Circuits@Home__ - <alex-gl@mail.ru>
* Developers of the USB Core, HID, FTDI, ADK, ACM, and PL2303 libraries
* __Kristian Lauszus, TKJ Electronics__ - <kristianl@tkjelectronics.com>
* 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__ - <xxxajk@gmail.com>
* Major contributor to mass storage code
* __guruthree__
* [Xbox ONE](#xbox-one-library) controller support
* __Yuuichi Akagawa__ - [@YuuichiAkagawa](https://twitter.com/yuuichiakagawa)
* Developer of the [MIDI](#midi-library) library
# Donate
Help yourself by helping us support you! Many thousands of hours have been spent developing the USB Host Shield library. Since you find it useful, please consider donating via the button below. Donations will allow us to support you by ensuring hardware that you have can be acquired in order to add support for your microcontroller board.
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=donate@circuitsathome.com&amp;lc=US&amp;item_name=Donate%20to%20the%20USB%20Host%20Library%20project&amp;no_note=0&amp;currency_code=USD&amp;bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHostedGuest"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" alt="PayPal - The safer, easier way to pay online!" /></a>
# Table of Contents
* [How to include the library](#how-to-include-the-library)
* [Arduino Library Manager](#arduino-library-manager)
* [Manual installation](#manual-installation)
* [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)
* [Xbox ONE Library](#xbox-one-library)
* [Wii library](#wii-library)
* [PS Buzz Library](#ps-buzz-library)
* [HID Libraries](#hid-libraries)
* [MIDI Library](#midi-library)
* [Interface modifications](#interface-modifications)
* [FAQ](#faq)
# How to include the library
### Arduino Library Manager
First install Arduino IDE version 1.6.2 or newer, then simply use the Arduino Library Manager to install the library.
Please see the following page for instructions: <http://www.arduino.cc/en/Guide/Libraries#toc3>.
### Manual installation
First download the library by clicking on the following link: <https://github.com/felis/USB_Host_Shield_2.0/archive/master.zip>.
Then uncompress the zip folder and rename the directory to "USB\_Host\_Shield\_20", as any special characters are not supported by the Arduino IDE.
Now open up the Arduino IDE and open "File>Preferences". There you will see the location of your sketchbook. Open that directory and create a directory called "libraries" inside that directory.
Now move the "USB\_Host\_Shield\_20" directory to the "libraries" directory.
The final structure should look like this:
* Arduino/
* libraries/
* USB\_Host\_Shield\_20/
Now quit the Arduino IDE and reopen it.
Now you should be able to go open all the examples codes by navigating to "File>Examples>USB\_Host\_Shield\_20" and then select the example you will like to open.
For more information visit the following sites: <http://arduino.cc/en/Guide/Libraries> and <https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use>.
# How to use the library
### Documentation
Documentation for the library can be found at the following link: <http://felis.github.com/USB_Host_Shield_2.0/>.
### Enable debugging
By default serial debugging is disabled. To turn it on simply change ```ENABLE_UHS_DEBUGGING``` to 1 in [settings.h](settings.h) like so:
```C++
#define ENABLE_UHS_DEBUGGING 1
```
### Boards
Currently the following boards are supported by the library:
* All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.)
* Arduino Due, Intel Galileo, Intel Galileo 2, and Intel Edison
* Note that the Intel Galileo uses pin 2 and 3 as INT and SS pin respectively by default, so some modifications to the shield are needed. See the "Interface modifications" section in the [hardware manual](https://www.circuitsathome.com/usb-host-shield-hardware-manual) for more information.
* Note native USB host is not supported on any of these platforms. You will have to use the shield for now.
* Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, Teensy 3.x, and Teensy LC)
* Note if you are using the Teensy 3.x you should download this SPI library as well: <https://github.com/xxxajk/spi4teensy3>. You should then add ```#include <spi4teensy3.h>``` to your .ino file.
* Balanduino
* Sanguino
* Black Widdow
* RedBearLab nRF51822
* Digilent chipKIT
* Please see: <http://www.circuitsathome.com/mcu/usb/running-usb-host-code-on-digilent-chipkit-board>.
* STM32F4
* Currently the [NUCLEO-F446RE](http://www.st.com/web/catalog/tools/FM116/SC959/SS1532/LN1847/PF262063) is supported featuring the STM32F446. Take a look at the following example code: <https://github.com/Lauszus/Nucleo_F446RE_USBHost>.
* ESP8266 is supported using the [ESP8266 Arduino core](https://github.com/esp8266/Arduino)
* Note it uses pin 15 and 5 for SS and INT respectively
* Also please be aware that:
* GPIO16 is **NOT** usable, as it will be used for some other purposes. For example, reset the SoC itself from sleep mode.
* GPIO6 to 11 is also **NOT** usable, as they are used to connect SPI flash chip and it is used for storing the executable binary content.
* ESP32 is supported using the [arduino-esp32](https://github.com/espressif/arduino-esp32/)
* GPIO5 : SS, GPIO17 : INT, GPIO18 : SCK, GPIO19 : MISO, GPIO23 : MOSI
The following boards need to be activated manually in [settings.h](settings.h):
* Arduino Mega ADK
* If you are using Arduino 1.5.5 or newer there is no need to activate the Arduino Mega ADK manually
* Black Widdow
Simply set the corresponding value to 1 instead of 0.
### [Bluetooth libraries](BTD.cpp)
The [BTD library](BTD.cpp) is a general purpose library for an ordinary Bluetooth dongle.
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 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)
The [Bluetooth HID library](BTHID.cpp) allows you to connect HID devices via Bluetooth to the USB Host Shield.
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.
For information see the following blog post: <http://blog.tkjelectronics.dk/2013/12/bluetooth-hid-devices-now-supported-by-the-usb-host-library/>.
### [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:
* <http://www.circuitsathome.com/mcu/bluetooth-rfcommspp-service-support-for-usb-host-2-0-library-released>
* <http://blog.tkjelectronics.dk/2012/07/rfcommspp-library-for-arduino/>
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
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 and get the battery level.
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 Share button and then hold down the PS without releasing the Share button. The PS4 controller will then start to blink rapidly indicating that it is in pairing mode.
It should then automatically pair the dongle with your controller. This only have to be done once.
For information see the following blog post: <http://blog.tkjelectronics.dk/2014/01/ps4-controller-now-supported-by-the-usb-host-library/>.
Also check out this excellent Wiki by Frank Zhao about the PS4 controller: <http://eleccelerator.com/wiki/index.php?title=DualShock_4> and this Linux driver: <https://github.com/chrippa/ds4drv>.
### 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.
In order to use your Playstation controller via Bluetooth you have to set the Bluetooth address of the dongle internally to your PS3 Controller. This can be achieved by first plugging in the Bluetooth dongle and wait a few seconds. Now plug in the controller via USB and wait until the LEDs start to flash. The library has now written the Bluetooth address of the dongle to the PS3 controller.
Finally simply plug in the Bluetooth dongle again and press PS on the PS3 controller. After a few seconds it should be connected to the dongle and ready to use.
__Note:__ You will have to plug in the Bluetooth dongle before connecting the controller, as the library needs to read the address of the dongle. Alternatively you could set it in code like so: [PS3BT.ino#L20](examples/Bluetooth/PS3BT/PS3BT.ino#L20).
For more information about the PS3 protocol see the official wiki: <https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information>.
Also take a look at the blog posts:
* <http://blog.tkjelectronics.dk/2012/01/ps3-controller-bt-library-for-arduino/>
* <http://www.circuitsathome.com/mcu/sony-ps3-controller-support-added-to-usb-host-library>
* <http://www.circuitsathome.com/mcu/arduino/interfacing-ps3-controllers-via-usb>
A special thanks go to the following people:
1. _Richard Ibbotson_ who made this excellent guide: <http://www.circuitsathome.com/mcu/ps3-and-wiimote-game-controllers-on-the-arduino-host-shield-part>
2. _Tomoyuki Tanaka_ for releasing his code for the Arduino USB Host shield connected to the wiimote: <http://www.circuitsathome.com/mcu/rc-car-controlled-by-wii-remote-on-arduino>
Also a big thanks all the people behind these sites about the Motion controller:
* <http://thp.io/2010/psmove/>
* <http://www.copenhagengamecollective.org/unimove/>
* <https://github.com/thp/psmoveapi>
* <http://code.google.com/p/moveonpc/>
### Xbox Libraries
The library supports both the original Xbox controller via USB and the Xbox 360 controller both via USB and wirelessly.
#### Xbox library
The [XBOXOLD](XBOXOLD.cpp) class implements support for the original Xbox controller via USB.
All the information are from the following sites:
* <https://github.com/torvalds/linux/blob/master/Documentation/input/xpad.txt>
* <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
* <http://euc.jp/periphs/xbox-controller.ja.html>
* <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL#L15>
#### Xbox 360 Library
The library support one Xbox 360 via USB or up to four Xbox 360 controllers wirelessly by using a [Xbox 360 wireless receiver](http://blog.tkjelectronics.dk/wp-content/uploads/xbox360-wireless-receiver.jpg).
To use it via USB use the [XBOXUSB](XBOXUSB.cpp) library or to use it wirelessly use the [XBOXRECV](XBOXRECV.cpp) library.
__Note that a Wireless controller can NOT be used via USB!__
Examples code can be found in the [examples directory](examples/Xbox).
Also see the following blog posts:
* <http://www.circuitsathome.com/mcu/xbox360-controller-support-added-to-usb-host-shield-2-0-library>
* <http://blog.tkjelectronics.dk/2012/07/xbox-360-controller-support-added-to-the-usb-host-library/>
* <http://blog.tkjelectronics.dk/2012/12/xbox-360-receiver-added-to-the-usb-host-library/>
All the information regarding the Xbox 360 controller protocol are form these sites:
* <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/UsbInfo>
* <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/WirelessUsbInfo>
* <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL>
#### Xbox ONE Library
An Xbox ONE controller is supported via USB in the [XBOXONE](XBOXONE.cpp) class. It is heavily based on the 360 library above. In addition to cross referencing the above, information on the protocol was found at:
* <https://github.com/quantus/xbox-one-controller-protocol>
* <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
* <https://github.com/kylelemons/xbox/blob/master/xbox.go>
### [Wii library](Wii.cpp)
The [Wii](Wii.cpp) library support the Wiimote, but also the Nunchuch and Motion Plus extensions via Bluetooth. The Wii U Pro Controller and Wii Balance Board are also supported via Bluetooth.
First you have to pair with the controller, this is done automatically by the library if you create the instance like so:
```C++
WII Wii(&Btd, PAIR);
```
And then press 1 & 2 at once on the Wiimote or the SYNC buttons if you are using a Wii U Pro Controller or a Wii Balance Board.
After that you can simply create the instance like so:
```C++
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: [Wii.ino](examples/Bluetooth/Wii/Wii.ino).
Also take a look at the blog post:
* <http://blog.tkjelectronics.dk/2012/08/wiimote-added-to-usb-host-library/>
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:
* <http://wiibrew.org/wiki/Wiimote>
* <http://wiibrew.org/wiki/Wiimote/Extension_Controllers>
* <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Nunchuck>
* <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Wii_Motion_Plus>
* <http://wiibrew.org/wiki/Wii_Balance_Board>
* The old library created by _Tomoyuki Tanaka_: <https://github.com/moyuchin/WiiRemote_on_Arduino> 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.
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/
* https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c
### HID Libraries
HID devices are also supported by the library. However these require you to write your own driver. A few example are provided in the [examples/HID](examples/HID) directory. Including an example for the [SteelSeries SRW-S1 Steering Wheel](examples/HID/SRWS1/SRWS1.ino).
### [MIDI Library](usbh_midi.cpp)
The library support MIDI devices.
You can convert USB MIDI keyboard to legacy serial MIDI.
* [USB_MIDI_converter.ino](examples/USBH_MIDI/USB_MIDI_converter/USB_MIDI_converter.ino)
* [USB_MIDI_converter_multi.ino](examples/USBH_MIDI/USB_MIDI_converter_multi/USB_MIDI_converter_multi.ino)
For information see the following page: <http://yuuichiakagawa.github.io/USBH_MIDI/>.
# 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.
Note this means that it uses pin 13, 12, 11 on an Arduino Uno, so these pins can not be used for anything else than SPI communication!
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<P10, P9> MAX3421E;
```
For instance if you have rerouted SS to pin 7 it should read:
```C++
typedef MAX3421e<P7, P9> 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?
* 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 <usbhub.h>``` and create the instance like so: ```USBHub Hub1(&Usb);```.
> When I connecting my PS3 controller I get a output like this:
```
Dualshock 3 Controller Enabled
LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
```
* This means that your dongle does not support 2.0+EDR, so you will need another dongle. Please see the following [list](https://github.com/felis/USB_Host_Shield_2.0/wiki/Bluetooth-dongles) for tested working dongles.
> When compiling I am getting the following error: "fatal error: SPI.h: No such file or directory".
* Please make sure to include the SPI library like so: ```#include <SPI.h>``` in your .ino file.

View File

@ -0,0 +1,829 @@
/* Copyright (C) 2012 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 "SPP.h"
// To enable serial debugging see "settings.h"
//#define EXTRADEBUG // Uncomment to get even more debugging data
//#define PRINTREPORT // Uncomment to print the report sent to the Arduino
/*
* CRC (reversed crc) lookup table as calculated by the table generator in ETSI TS 101 369 V6.3.0.
*/
const uint8_t rfcomm_crc_table[256] PROGMEM = {/* reversed, 8-bit, poly=0x07 */
0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75, 0x0E, 0x9F, 0xED, 0x7C, 0x09, 0x98, 0xEA, 0x7B,
0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, 0xF8, 0x69, 0x12, 0x83, 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67,
0x38, 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, 0x4D, 0x36, 0xA7, 0xD5, 0x44, 0x31, 0xA0, 0xD2, 0x43,
0x24, 0xB5, 0xC7, 0x56, 0x23, 0xB2, 0xC0, 0x51, 0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F,
0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05, 0x7E, 0xEF, 0x9D, 0x0C, 0x79, 0xE8, 0x9A, 0x0B,
0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, 0x88, 0x19, 0x62, 0xF3, 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17,
0x48, 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, 0x3D, 0x46, 0xD7, 0xA5, 0x34, 0x41, 0xD0, 0xA2, 0x33,
0x54, 0xC5, 0xB7, 0x26, 0x53, 0xC2, 0xB0, 0x21, 0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F,
0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95, 0xEE, 0x7F, 0x0D, 0x9C, 0xE9, 0x78, 0x0A, 0x9B,
0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, 0x18, 0x89, 0xF2, 0x63, 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87,
0xD8, 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, 0xAD, 0xD6, 0x47, 0x35, 0xA4, 0xD1, 0x40, 0x32, 0xA3,
0xC4, 0x55, 0x27, 0xB6, 0xC3, 0x52, 0x20, 0xB1, 0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF,
0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5, 0x9E, 0x0F, 0x7D, 0xEC, 0x99, 0x08, 0x7A, 0xEB,
0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, 0x68, 0xF9, 0x82, 0x13, 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7,
0xA8, 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, 0xDD, 0xA6, 0x37, 0x45, 0xD4, 0xA1, 0x30, 0x42, 0xD3,
0xB4, 0x25, 0x57, 0xC6, 0xB3, 0x22, 0x50, 0xC1, 0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF
};
SPP::SPP(BTD *p, const char* name, const char* pin) :
BluetoothService(p) // Pointer to BTD class instance - mandatory
{
pBtd->btdName = name;
pBtd->btdPin = pin;
/* Set device cid for the SDP and RFCOMM channelse */
sdp_dcid[0] = 0x50; // 0x0050
sdp_dcid[1] = 0x00;
rfcomm_dcid[0] = 0x51; // 0x0051
rfcomm_dcid[1] = 0x00;
Reset();
}
void SPP::Reset() {
connected = false;
RFCOMMConnected = false;
SDPConnected = false;
waitForLastCommand = false;
l2cap_sdp_state = L2CAP_SDP_WAIT;
l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT;
l2cap_event_flag = 0;
sppIndex = 0;
creditSent = false;
}
void SPP::disconnect() {
connected = false;
// First the two L2CAP channels has to be disconnected and then the HCI connection
if(RFCOMMConnected)
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, ++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) {
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) {
pBtd->rfcommConnectionClaimed = true;
hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; // Reset state
}
}
}
if(checkHciHandle(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
Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
Notify(PSTR(" Data: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
#endif
} else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
#ifdef EXTRADEBUG
Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
Notify(PSTR(" SCID: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
Notify(PSTR(" Identifier: "), 0x80);
D_PrintHex<uint8_t > (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
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) { // ----- || -----
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]) {
//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]) {
//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]) {
//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]) {
//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]) {
//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]) {
//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]) {
//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]) {
//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) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nInformation request"), 0x80);
#endif
identifier = l2capinbuf[9];
pBtd->l2cap_information_response(hci_handle, identifier, l2capinbuf[12], l2capinbuf[13]);
}
#ifdef EXTRADEBUG
else {
Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
D_PrintHex<uint8_t > (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) {
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) {
l2capResponse1(l2capinbuf[9], l2capinbuf[10]);
firstMessage = false;
} else {
l2capResponse2(l2capinbuf[9], l2capinbuf[10]); // L2CAP continuation state
firstMessage = true;
}
} else
serviceNotSupported(l2capinbuf[9], l2capinbuf[10]); // The service is not supported
#ifdef EXTRADEBUG
Notify(PSTR("\r\nUUID: "), 0x80);
uint16_t uuid;
if((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000) // Check if it's sending the UUID as a 128-bit UUID
uuid = (l2capinbuf[18] << 8 | l2capinbuf[19]);
else // Short UUID
uuid = (l2capinbuf[16] << 8 | l2capinbuf[17]);
D_PrintHex<uint16_t > (uuid, 0x80);
Notify(PSTR("\r\nLength: "), 0x80);
uint16_t length = l2capinbuf[11] << 8 | l2capinbuf[12];
D_PrintHex<uint16_t > (length, 0x80);
Notify(PSTR("\r\nData: "), 0x80);
for(uint8_t i = 0; i < length; i++) {
D_PrintHex<uint8_t > (l2capinbuf[13 + i], 0x80);
Notify(PSTR(" "), 0x80);
}
#endif
}
#ifdef EXTRADEBUG
else {
Notify(PSTR("\r\nUnknown PDU: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
}
#endif
} 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)
rfcommChannelConnection = rfcommChannel;
#ifdef EXTRADEBUG
Notify(PSTR("\r\nRFCOMM Channel: "), 0x80);
D_PrintHex<uint8_t > (rfcommChannel >> 3, 0x80);
Notify(PSTR(" Direction: "), 0x80);
D_PrintHex<uint8_t > (rfcommDirection >> 2, 0x80);
Notify(PSTR(" CommandResponse: "), 0x80);
D_PrintHex<uint8_t > (rfcommCommandResponse >> 1, 0x80);
Notify(PSTR(" ChannelType: "), 0x80);
D_PrintHex<uint8_t > (rfcommChannelType, 0x80);
Notify(PSTR(" PF_BIT: "), 0x80);
D_PrintHex<uint8_t > (rfcommPfBit, 0x80);
#endif
if(rfcommChannelType == RFCOMM_DISC) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nReceived Disconnect RFCOMM Command on channel: "), 0x80);
D_PrintHex<uint8_t > (rfcommChannel >> 3, 0x80);
#endif
connected = false;
sendRfcomm(rfcommChannel, rfcommDirection, rfcommCommandResponse, RFCOMM_UA, rfcommPfBit, rfcommbuf, 0x00); // UA Command
}
if(connected) {
/* Read the incoming message */
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])) {
uint8_t i = 0;
for(; i < length; i++) {
if(rfcommAvailable + i >= sizeof (rfcommDataBuffer)) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nWarning: Buffer is full!"), 0x80);
#endif
break;
}
rfcommDataBuffer[rfcommAvailable + i] = l2capinbuf[11 + i + offset];
}
rfcommAvailable += i;
#ifdef EXTRADEBUG
Notify(PSTR("\r\nRFCOMM Data Available: "), 0x80);
Notify(rfcommAvailable, 0x80);
if(offset) {
Notify(PSTR(" - Credit: 0x"), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[11], 0x80);
}
#endif
}
#ifdef DEBUG_USB_HOST
else
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++)
Notifyc(l2capinbuf[i + 11 + offset], 0x80);
#endif
} 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
rfcommbuf[0] = BT_RFCOMM_RPN_RSP; // Command
rfcommbuf[1] = l2capinbuf[12]; // Length and shiftet like so: length << 1 | 1
rfcommbuf[2] = l2capinbuf[13]; // Channel: channel << 1 | 1
rfcommbuf[3] = l2capinbuf[14]; // Pre difined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
rfcommbuf[4] = l2capinbuf[15]; // Priority
rfcommbuf[5] = l2capinbuf[16]; // Timer
rfcommbuf[6] = l2capinbuf[17]; // Max Fram Size LSB
rfcommbuf[7] = l2capinbuf[18]; // Max Fram Size MSB
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
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSend UIH Modem Status Response"), 0x80);
#endif
rfcommbuf[0] = BT_RFCOMM_MSC_RSP; // UIH Modem Status Response
rfcommbuf[1] = 2 << 1 | 1; // Length and shiftet like so: length << 1 | 1
rfcommbuf[2] = l2capinbuf[13]; // Channel: (1 << 0) | (1 << 1) | (0 << 2) | (channel << 3)
rfcommbuf[3] = l2capinbuf[14];
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
#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
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nReceived UIH Parameter Negotiation Command"), 0x80);
#endif
rfcommbuf[0] = BT_RFCOMM_PN_RSP; // UIH Parameter Negotiation Response
rfcommbuf[1] = l2capinbuf[12]; // Length and shiftet like so: length << 1 | 1
rfcommbuf[2] = l2capinbuf[13]; // Channel: channel << 1 | 1
rfcommbuf[3] = 0xE0; // Pre difined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
rfcommbuf[4] = 0x00; // Priority
rfcommbuf[5] = 0x00; // Timer
rfcommbuf[6] = BULK_MAXPKTSIZE - 14; // Max Fram Size LSB - set to the size of received data (50)
rfcommbuf[7] = 0x00; // Max Fram Size MSB
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
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSend UIH Modem Status Response"), 0x80);
#endif
rfcommbuf[0] = BT_RFCOMM_MSC_RSP; // UIH Modem Status Response
rfcommbuf[1] = 2 << 1 | 1; // Length and shiftet like so: length << 1 | 1
rfcommbuf[2] = l2capinbuf[13]; // Channel: (1 << 0) | (1 << 1) | (0 << 2) | (channel << 3)
rfcommbuf[3] = l2capinbuf[14];
sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x04);
delay(1);
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSend UIH Modem Status Command"), 0x80);
#endif
rfcommbuf[0] = BT_RFCOMM_MSC_CMD; // UIH Modem Status Command
rfcommbuf[1] = 2 << 1 | 1; // Length and shiftet like so: length << 1 | 1
rfcommbuf[2] = l2capinbuf[13]; // Channel: (1 << 0) | (1 << 1) | (0 << 2) | (channel << 3)
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) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nSend UIH Command with credit"), 0x80);
#endif
sendRfcommCredit(rfcommChannelConnection, rfcommDirection, 0, RFCOMM_UIH, 0x10, sizeof (rfcommDataBuffer)); // Send credit
creditSent = true;
timer = (uint32_t)millis();
waitForLastCommand = true;
}
} 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
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nReceived UIH Remote Port Negotiation Command"), 0x80);
#endif
rfcommbuf[0] = BT_RFCOMM_RPN_RSP; // Command
rfcommbuf[1] = l2capinbuf[12]; // Length and shiftet like so: length << 1 | 1
rfcommbuf[2] = l2capinbuf[13]; // Channel: channel << 1 | 1
rfcommbuf[3] = l2capinbuf[14]; // Pre difined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
rfcommbuf[4] = l2capinbuf[15]; // Priority
rfcommbuf[5] = l2capinbuf[16]; // Timer
rfcommbuf[6] = l2capinbuf[17]; // Max Fram Size LSB
rfcommbuf[7] = l2capinbuf[18]; // Max Fram Size MSB
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
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nRFCOMM Connection is now established\r\n"), 0x80);
#endif
onInit();
}
#ifdef EXTRADEBUG
else if(rfcommChannelType != RFCOMM_DISC) {
Notify(PSTR("\r\nUnsupported RFCOMM Data - ChannelType: "), 0x80);
D_PrintHex<uint8_t > (rfcommChannelType, 0x80);
Notify(PSTR(" Command: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[11], 0x80);
}
#endif
}
}
#ifdef EXTRADEBUG
else {
Notify(PSTR("\r\nUnsupported L2CAP Data - Channel ID: "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[7], 0x80);
Notify(PSTR(" "), 0x80);
D_PrintHex<uint8_t > (l2capinbuf[6], 0x80);
}
#endif
SDP_task();
RFCOMM_task();
}
}
void SPP::Run() {
if(waitForLastCommand && (int32_t)((uint32_t)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
onInit();
}
send(); // Send all bytes currently in the buffer
}
void SPP::onInit() {
creditSent = false;
waitForLastCommand = false;
connected = true; // The RFCOMM channel is now established
sppIndex = 0;
if(pFuncOnInit)
pFuncOnInit(); // Call the user function
};
void SPP::SDP_task() {
switch(l2cap_sdp_state) {
case L2CAP_SDP_WAIT:
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
pBtd->l2cap_connection_response(hci_handle, identifier, sdp_dcid, sdp_scid, PENDING);
delay(1);
pBtd->l2cap_connection_response(hci_handle, identifier, sdp_dcid, sdp_scid, SUCCESSFUL);
identifier++;
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:
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
firstMessage = true; // Reset bool
SDPConnected = true;
l2cap_sdp_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
pBtd->hci_disconnect(hci_handle);
hci_handle = -1; // Reset handle
Reset();
}
break;
}
}
void SPP::RFCOMM_task() {
switch(l2cap_rfcomm_state) {
case L2CAP_RFCOMM_WAIT:
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
pBtd->l2cap_connection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid, PENDING);
delay(1);
pBtd->l2cap_connection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid, SUCCESSFUL);
identifier++;
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:
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
rfcommAvailable = 0; // Reset number of bytes available
bytesRead = 0; // Reset number of bytes received
RFCOMMConnected = true;
l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT;
}
break;
}
}
/************************************************************/
/* SDP Commands */
/************************************************************/
void SPP::SDP_Command(uint8_t* data, uint8_t nbytes) { // See page 223 in the Bluetooth specs
pBtd->L2CAP_Command(hci_handle, data, nbytes, sdp_scid[0], sdp_scid[1]);
}
void SPP::serviceNotSupported(uint8_t transactionIDHigh, uint8_t transactionIDLow) { // See page 235 in the Bluetooth specs
l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU;
l2capoutbuf[1] = transactionIDHigh;
l2capoutbuf[2] = transactionIDLow;
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; // Data element sequence - length in next byte
l2capoutbuf[8] = 0x00; // Length = 0
l2capoutbuf[9] = 0x00; // No continuation state
SDP_Command(l2capoutbuf, 10);
}
void SPP::serialPortResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU;
l2capoutbuf[1] = transactionIDHigh;
l2capoutbuf[2] = transactionIDLow;
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; // Data element sequence - length in next two bytes
l2capoutbuf[8] = 0x00; // MSB Length
l2capoutbuf[9] = 0x3C; // LSB Length = 60
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; // 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[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);
}
void SPP::serialPortResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU;
l2capoutbuf[1] = transactionIDHigh;
l2capoutbuf[2] = transactionIDLow;
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; // Channel 1 - TODO: Try different values, so multiple servers can be used at once
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; // 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 continuation state
SDP_Command(l2capoutbuf, 33);
}
void SPP::l2capResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
serialPortResponse1(transactionIDHigh, transactionIDLow); // These has to send all the supported functions, since it only supports virtual serialport it just sends the message again
}
void SPP::l2capResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
serialPortResponse2(transactionIDHigh, transactionIDLow); // Same data as serialPortResponse2
}
/************************************************************/
/* RFCOMM Commands */
/************************************************************/
void SPP::RFCOMM_Command(uint8_t* data, uint8_t nbytes) {
pBtd->L2CAP_Command(hci_handle, data, nbytes, rfcomm_scid[0], rfcomm_scid[1]);
}
void SPP::sendRfcomm(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t* data, uint8_t length) {
l2capoutbuf[0] = channel | direction | CR | extendAddress; // RFCOMM Address
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++)
l2capoutbuf[i + 3] = data[i];
l2capoutbuf[i + 3] = calcFcs(l2capoutbuf);
#ifdef EXTRADEBUG
Notify(PSTR(" - RFCOMM Data: "), 0x80);
for(i = 0; i < length + 4; i++) {
D_PrintHex<uint8_t > (l2capoutbuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
#endif
RFCOMM_Command(l2capoutbuf, length + 4);
}
void SPP::sendRfcommCredit(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t credit) {
l2capoutbuf[0] = channel | direction | CR | extendAddress; // RFCOMM Address
l2capoutbuf[1] = channelType | pfBit; // RFCOMM Control
l2capoutbuf[2] = 0x01; // Length = 0
l2capoutbuf[3] = credit; // Credit
l2capoutbuf[4] = calcFcs(l2capoutbuf);
#ifdef EXTRADEBUG
Notify(PSTR(" - RFCOMM Credit Data: "), 0x80);
for(uint8_t i = 0; i < 5; i++) {
D_PrintHex<uint8_t > (l2capoutbuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
#endif
RFCOMM_Command(l2capoutbuf, 5);
}
/* CRC on 2 bytes */
uint8_t SPP::crc(uint8_t *data) {
return (pgm_read_byte(&rfcomm_crc_table[pgm_read_byte(&rfcomm_crc_table[0xFF ^ data[0]]) ^ data[1]]));
}
/* Calculate FCS */
uint8_t SPP::calcFcs(uint8_t *data) {
uint8_t temp = crc(data);
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
}
/* Check FCS */
bool SPP::checkFcs(uint8_t *data, uint8_t fcs) {
uint8_t temp = crc(data);
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]))
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() {
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
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
length = sizeof (l2capoutbuf) - 4;
else
length = sppIndex;
l2capoutbuf[2] = length << 1 | 1; // Length
uint8_t i = 0;
for(; i < length; i++)
l2capoutbuf[i + 3] = sppOutputBuffer[i + offset];
l2capoutbuf[i + 3] = calcFcs(l2capoutbuf); // Calculate checksum
RFCOMM_Command(l2capoutbuf, length + 4);
sppIndex -= length;
offset += length; // Increment the offset
}
}
int SPP::available(void) {
return rfcommAvailable;
};
void SPP::discard(void) {
rfcommAvailable = 0;
}
int SPP::peek(void) {
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
return -1;
uint8_t output = rfcommDataBuffer[0];
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
bytesRead = 0;
sendRfcommCredit(rfcommChannelConnection, rfcommDirection, 0, RFCOMM_UIH, 0x10, sizeof (rfcommDataBuffer)); // Send more credit
#ifdef EXTRADEBUG
Notify(PSTR("\r\nSent "), 0x80);
Notify((uint8_t)sizeof (rfcommDataBuffer), 0x80);
Notify(PSTR(" more credit"), 0x80);
#endif
}
return output;
}

View File

@ -0,0 +1,227 @@
/* Copyright (C) 2012 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 _spp_h_
#define _spp_h_
#include "BTD.h"
/* 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
#define SERIALPORT_UUID 0x1101 // See http://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
#define L2CAP_UUID 0x0100
/* Used for RFCOMM */
#define RFCOMM_SABM 0x2F
#define RFCOMM_UA 0x63
#define RFCOMM_UIH 0xEF
//#define RFCOMM_DM 0x0F
#define RFCOMM_DISC 0x43
#define extendAddress 0x01 // Always 1
// Multiplexer message types
#define BT_RFCOMM_PN_CMD 0x83
#define BT_RFCOMM_PN_RSP 0x81
#define BT_RFCOMM_MSC_CMD 0xE3
#define BT_RFCOMM_MSC_RSP 0xE1
#define BT_RFCOMM_RPN_CMD 0x93
#define BT_RFCOMM_RPN_RSP 0x91
/*
#define BT_RFCOMM_TEST_CMD 0x23
#define BT_RFCOMM_TEST_RSP 0x21
#define BT_RFCOMM_FCON_CMD 0xA3
#define BT_RFCOMM_FCON_RSP 0xA1
#define BT_RFCOMM_FCOFF_CMD 0x63
#define BT_RFCOMM_FCOFF_RSP 0x61
#define BT_RFCOMM_RLS_CMD 0x53
#define BT_RFCOMM_RLS_RSP 0x51
#define BT_RFCOMM_NSC_RSP 0x11
*/
/**
* 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 and stream functions.
*/
class SPP : public BluetoothService, public Stream {
public:
/**
* Constructor for the SPP class.
* @param p Pointer to BTD class instance.
* @param name Set the name to BTD#btdName. If argument is omitted, then "Arduino" will be used.
* @param pin Write the pin to BTD#btdPin. If argument is omitted, then "0000" will be used.
*/
SPP(BTD *p, const char *name = "Arduino", const char *pin = "0000");
/** @name BluetoothService implementation */
/** Used this to disconnect the virtual serial port. */
void disconnect();
/**@}*/
/**
* Used to provide Boolean tests for the class.
* @return Return true if SPP communication is connected.
*/
operator bool() {
return connected;
}
/** Variable used to indicate if the connection is established. */
bool connected;
/** @name Serial port profile (SPP) Print functions */
/**
* Get number of bytes waiting to be read.
* @return Return the number of bytes ready to be read.
*/
int available(void);
/** Send out all bytes in the buffer. */
void flush(void) {
send();
};
/**
* Used to read the next value in the buffer without advancing to the next one.
* @return Return the byte. Will return -1 if no bytes are available.
*/
int peek(void);
/**
* Used to read the buffer.
* @return Return the byte. Will return -1 if no bytes are available.
*/
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.
* @return Return the number of bytes written.
*/
size_t 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.
* @return Return the number of bytes written.
*/
size_t write(const uint8_t* data, size_t size);
/** Pull in write(const char *str) from Print */
#if !defined(RBL_NRF51822)
using Print::write;
#endif
#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.
*/
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.
*/
void write(const uint8_t* data, size_t size);
#endif
/** Discard all the bytes in the buffer. */
void discard(void);
/**
* This will send all the bytes in the buffer.
* This is called whenever Usb.Task() is called,
* but can also be called via this function.
*/
void send(void);
/**@}*/
protected:
/** @name BluetoothService implementation */
/**
* Used to pass acldata to the services.
* @param ACLData Incoming acldata.
*/
void ACLData(uint8_t* ACLData);
/** Used to establish the connection automatically. */
void Run();
/** Use this to reset the service. */
void Reset();
/**
* 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();
/**@}*/
private:
/* Set true when a channel is created */
bool SDPConnected;
bool RFCOMMConnected;
/* Variables used by L2CAP state machines */
uint8_t l2cap_sdp_state;
uint8_t l2cap_rfcomm_state;
uint8_t l2capoutbuf[BULK_MAXPKTSIZE]; // General purpose buffer for l2cap out data
uint8_t rfcommbuf[10]; // Buffer for RFCOMM Commands
/* L2CAP Channels */
uint8_t sdp_scid[2]; // L2CAP source CID for SDP
uint8_t sdp_dcid[2]; // 0x0050
uint8_t rfcomm_scid[2]; // L2CAP source CID for RFCOMM
uint8_t rfcomm_dcid[2]; // 0x0051
/* RFCOMM Variables */
uint8_t rfcommChannel;
uint8_t rfcommChannelConnection; // This is the channel the SPP channel will be running at
uint8_t rfcommDirection;
uint8_t rfcommCommandResponse;
uint8_t rfcommChannelType;
uint8_t rfcommPfBit;
uint32_t timer;
bool waitForLastCommand;
bool creditSent;
uint8_t rfcommDataBuffer[100]; // Create a 100 sized buffer for incoming data
uint8_t sppOutputBuffer[100]; // Create a 100 sized buffer for outgoing SPP data
uint8_t sppIndex;
uint8_t rfcommAvailable;
bool firstMessage; // Used to see if it's the first SDP request received
uint8_t bytesRead; // Counter to see when it's time to send more credit
/* State machines */
void SDP_task(); // SDP state machine
void RFCOMM_task(); // RFCOMM state machine
/* SDP Commands */
void SDP_Command(uint8_t *data, uint8_t nbytes);
void serviceNotSupported(uint8_t transactionIDHigh, uint8_t transactionIDLow);
void serialPortResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow);
void serialPortResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow);
void l2capResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow);
void l2capResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow);
/* RFCOMM Commands */
void RFCOMM_Command(uint8_t *data, uint8_t nbytes);
void sendRfcomm(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t *data, uint8_t length);
void sendRfcommCredit(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t credit);
uint8_t calcFcs(uint8_t *data);
bool checkFcs(uint8_t *data, uint8_t fcs);
uint8_t crc(uint8_t *data);
};
#endif

View File

@ -0,0 +1,820 @@
/* 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
*/
/* USB functions */
#include "Usb.h"
static uint8_t usb_error = 0;
static uint8_t usb_task_state;
/* constructor */
USB::USB() : bmHubPre(0) {
usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; //set up state machine
init();
}
/* Initialize data structures */
void USB::init() {
//devConfigIndex = 0;
bmHubPre = 0;
}
uint8_t USB::getUsbTaskState(void) {
return ( usb_task_state);
}
void USB::setUsbTaskState(uint8_t state) {
usb_task_state = state;
}
EpInfo* USB::getEpInfoEntry(uint8_t addr, uint8_t ep) {
UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
if(!p || !p->epinfo)
return NULL;
EpInfo *pep = p->epinfo;
for(uint8_t i = 0; i < p->epcount; i++) {
if((pep)->epAddr == ep)
return pep;
pep++;
}
return NULL;
}
/* set device table entry */
/* 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)
return USB_ERROR_INVALID_ARGUMENT;
UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
p->address.devAddress = addr;
p->epinfo = eprecord_ptr;
p->epcount = epcount;
return 0;
}
uint8_t USB::SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t *nak_limit) {
UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
if(!p->epinfo)
return USB_ERROR_EPINFO_IS_NULL;
*ppep = getEpInfoEntry(addr, ep);
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));
(*nak_limit)--;
/*
USBTRACE2("\r\nAddress: ", addr);
USBTRACE2(" EP: ", ep);
USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower);
USBTRACE2(" NAK Limit: ", nak_limit);
USBTRACE("\r\n");
*/
regWr(rPERADDR, addr); //set peripheral address
uint8_t mode = regRd(rMODE);
//Serial.print("\r\nMode: ");
//Serial.println( mode, HEX);
//Serial.print("\r\nLS: ");
//Serial.println(p->lowspeed, HEX);
// Set bmLOWSPEED and bmHUBPRE in case of low-speed device, reset them otherwise
regWr(rMODE, (p->lowspeed) ? mode | bmLOWSPEED | bmHubPre : mode & ~(bmHUBPRE | bmLOWSPEED));
return 0;
}
/* Control transfer. Sets address, endpoint, fills control packet with necessary data, dispatches control packet, and initiates bulk IN transfer, */
/* depending on request. Actual requests are defined as inlines */
/* return codes: */
/* 00 = success */
/* 01-0f = non-zero HRSLT */
uint8_t USB::ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi,
uint16_t wInd, uint16_t total, uint16_t nbytes, uint8_t* dataptr, USBReadParser *p) {
bool direction = false; //request direction, IN or OUT
uint8_t rcode;
SETUP_PKT setup_pkt;
EpInfo *pep = NULL;
uint16_t nak_limit = 0;
rcode = SetAddress(addr, ep, &pep, &nak_limit);
if(rcode)
return rcode;
direction = ((bmReqType & 0x80) > 0);
/* fill in setup packet */
setup_pkt.ReqType_u.bmRequestType = bmReqType;
setup_pkt.bRequest = bRequest;
setup_pkt.wVal_u.wValueLo = wValLo;
setup_pkt.wVal_u.wValueHi = wValHi;
setup_pkt.wIndex = wInd;
setup_pkt.wLength = total;
bytesWr(rSUDFIFO, 8, (uint8_t*) & setup_pkt); //transfer to setup packet FIFO
rcode = dispatchPkt(tokSETUP, ep, nak_limit); //dispatch packet
if(rcode) //return HRSLT if not zero
return ( rcode);
if(dataptr != NULL) //data stage, if present
{
if(direction) //IN transfer
{
uint16_t left = total;
pep->bmRcvToggle = 1; //bmRCVTOG1;
while(left) {
// Bytes read into buffer
uint16_t read = nbytes;
//uint16_t read = (left<nbytes) ? left : nbytes;
rcode = InTransfer(pep, nak_limit, &read, dataptr);
if(rcode == hrTOGERR) {
// yes, we flip it wrong here so that next time it is actually correct!
pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
continue;
}
if(rcode)
return rcode;
// Invoke callback function if inTransfer completed successfully and callback function pointer is specified
if(!rcode && p)
((USBReadParser*)p)->Parse(read, dataptr, total - left);
left -= read;
if(read < nbytes)
break;
}
} else //OUT transfer
{
pep->bmSndToggle = 1; //bmSNDTOG1;
rcode = OutTransfer(pep, nak_limit, nbytes, dataptr);
}
if(rcode) //return error
return ( rcode);
}
// Status stage
return dispatchPkt((direction) ? tokOUTHS : tokINHS, ep, nak_limit); //GET if direction
}
/* IN transfer to arbitrary endpoint. Assumes PERADDR is set. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */
/* Keep sending INs and writes data to memory area pointed by 'data' */
/* rcode 0 if no errors. rcode 01-0f is relayed from dispatchPkt(). Rcode f0 means RCVDAVIRQ error,
fe USB xfer timeout */
uint8_t USB::inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t* data, uint8_t bInterval /*= 0*/) {
EpInfo *pep = NULL;
uint16_t nak_limit = 0;
uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit);
if(rcode) {
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, bInterval);
}
uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t* data, uint8_t bInterval /*= 0*/) {
uint8_t rcode = 0;
uint8_t pktsize;
uint16_t nbytes = *nbytesptr;
//printf("Requesting %i bytes ", nbytes);
uint8_t maxpktsize = pep->maxPktSize;
*nbytesptr = 0;
regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value
// 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) {
// yes, we flip it wrong here so that next time it is actually correct!
pep->bmRcvToggle = (regRd(rHRSL) & bmRCVTOGRD) ? 0 : 1;
regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value
continue;
}
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) {
//printf(">>>>>>>> Problem! NO RCVDAVIRQ!\r\n");
rcode = 0xf0; //receive error
break;
}
pktsize = regRd(rRCVBC); //number of received bytes
//printf("Got %i bytes \r\n", pktsize);
// This would be OK, but...
//assert(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);
pktsize = nbytes;
}
int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr);
if(mem_left < 0)
mem_left = 0;
data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data);
regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer
*nbytesptr += pktsize; // add this packet's byte count to total transfer length
/* 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?
{
// Save toggle value
pep->bmRcvToggle = ((regRd(rHRSL) & bmRCVTOGRD)) ? 1 : 0;
//printf("\r\n");
rcode = 0;
break;
} else if(bInterval > 0)
delay(bInterval); // Delay according to polling interval
} //while( 1 )
return ( rcode);
}
/* OUT transfer to arbitrary endpoint. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */
/* Handles NAK bug per Maxim Application Note 4000 for single buffer transfer */
/* rcode 0 if no errors. rcode 01-0f is relayed from HRSL */
uint8_t USB::outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* data) {
EpInfo *pep = NULL;
uint16_t nak_limit = 0;
uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit);
if(rcode)
return rcode;
return OutTransfer(pep, nak_limit, nbytes, data);
}
uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data) {
uint8_t rcode = hrSUCCESS, retry_count;
uint8_t *data_p = data; //local copy of the data pointer
uint16_t bytes_tosend, nak_count;
uint16_t bytes_left = nbytes;
uint8_t maxpktsize = pep->maxPktSize;
if(maxpktsize < 1 || maxpktsize > 64)
return USB_ERROR_INVALID_MAX_PKT_SIZE;
uint32_t timeout = (uint32_t)millis() + USB_XFER_TIMEOUT;
regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); //set toggle value
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
regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ
rcode = (regRd(rHRSL) & 0x0f);
while(rcode && ((int32_t)((uint32_t)millis() - timeout) < 0L)) {
switch(rcode) {
case hrNAK:
nak_count++;
if(nak_limit && (nak_count == nak_limit))
goto breakout;
//return ( rcode);
break;
case hrTIMEOUT:
retry_count++;
if(retry_count == USB_RETRY_LIMIT)
goto breakout;
//return ( rcode);
break;
case hrTOGERR:
// yes, we flip it wrong here so that next time it is actually correct!
pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); //set toggle value
break;
default:
goto breakout;
}//switch( rcode
/* process NAK according to Host out NAK bug */
regWr(rSNDBC, 0);
regWr(rSNDFIFO, *data_p);
regWr(rSNDBC, bytes_tosend);
regWr(rHXFR, (tokOUT | pep->epAddr)); //dispatch packet
while(!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ
regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ
rcode = (regRd(rHRSL) & 0x0f);
}//while( rcode && ....
bytes_left -= bytes_tosend;
data_p += bytes_tosend;
}//while( bytes_left...
breakout:
pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 1 : 0; //bmSNDTOG1 : bmSNDTOG0; //update toggle
return ( rcode); //should be 0 in all cases
}
/* dispatch USB packet. Assumes peripheral address is set and relevant buffer is loaded/empty */
/* If NAK, tries to re-send up to nak_limit times */
/* If nak_limit == 0, do not count NAKs, exit after timeout */
/* If bus timeout, re-sends up to USB_RETRY_LIMIT times */
/* return codes 0x00-0x0f are HRSLT( 0x00 being success ), 0xff means timeout */
uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) {
uint32_t timeout = (uint32_t)millis() + USB_XFER_TIMEOUT;
uint8_t tmpdata;
uint8_t rcode = hrSUCCESS;
uint8_t retry_count = 0;
uint16_t nak_count = 0;
while((int32_t)((uint32_t)millis() - timeout) < 0L) {
#if defined(ESP8266) || defined(ESP32)
yield(); // needed in order to reset the watchdog timer on the ESP8266
#endif
regWr(rHXFR, (token | ep)); //launch the transfer
rcode = USB_ERROR_TRANSFER_TIMEOUT;
while((int32_t)((uint32_t)millis() - timeout) < 0L) //wait for transfer completion
{
#if defined(ESP8266) || defined(ESP32)
yield(); // needed in order to reset the watchdog timer on the ESP8266
#endif
tmpdata = regRd(rHIRQ);
if(tmpdata & bmHXFRDNIRQ) {
regWr(rHIRQ, bmHXFRDNIRQ); //clear the interrupt
rcode = 0x00;
break;
}//if( tmpdata & bmHXFRDNIRQ
}//while ( millis() < timeout
//if (rcode != 0x00) //exit if timeout
// return ( rcode);
rcode = (regRd(rHRSL) & 0x0f); //analyze transfer result
switch(rcode) {
case hrNAK:
nak_count++;
if(nak_limit && (nak_count == nak_limit))
return (rcode);
break;
case hrTIMEOUT:
retry_count++;
if(retry_count == USB_RETRY_LIMIT)
return (rcode);
break;
default:
return (rcode);
}//switch( rcode
}//while( timeout > millis()
return ( rcode);
}
/* USB main task. Performs enumeration/cleanup */
void USB::Task(void) //USB state machine
{
uint8_t rcode;
uint8_t tmpdata;
static uint32_t delay = 0;
//USB_DEVICE_DESCRIPTOR buf;
bool lowspeed = false;
MAX3421E::Task();
tmpdata = getVbusState();
/* modify USB task state if Vbus changed */
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)
usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE;
lowspeed = false;
break;
case LSHOST:
lowspeed = true;
//intentional fallthrough
case FSHOST: //attached
if((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) {
delay = (uint32_t)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])
rcode = devConfig[i]->Poll();
switch(usb_task_state) {
case USB_DETACHED_SUBSTATE_INITIALIZE:
init();
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;
break;
case USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE: //just sit here
break;
case USB_DETACHED_SUBSTATE_ILLEGAL: //just sit here
break;
case USB_ATTACHED_SUBSTATE_SETTLE: //settle time for just attached device
if((int32_t)((uint32_t)millis() - delay) >= 0L)
usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE;
else break; // don't fall through
case USB_ATTACHED_SUBSTATE_RESET_DEVICE:
regWr(rHCTL, bmBUSRST); //issue bus reset
usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE;
break;
case USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE:
if((regRd(rHCTL) & bmBUSRST) == 0) {
tmpdata = regRd(rMODE) | bmSOFKAENAB; //start SOF generation
regWr(rMODE, tmpdata);
usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_SOF;
//delay = (uint32_t)millis() + 20; //20ms wait after reset per USB spec
}
break;
case USB_ATTACHED_SUBSTATE_WAIT_SOF: //todo: change check order
if(regRd(rHIRQ) & bmFRAMEIRQ) {
//when first SOF received _and_ 20ms has passed we can continue
/*
if (delay < (uint32_t)millis()) //20ms passed
usb_task_state = USB_STATE_CONFIGURING;
*/
usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET;
delay = (uint32_t)millis() + 20;
}
break;
case USB_ATTACHED_SUBSTATE_WAIT_RESET:
if((int32_t)((uint32_t)millis() - delay) >= 0L) usb_task_state = USB_STATE_CONFIGURING;
else break; // don't fall through
case USB_STATE_CONFIGURING:
//Serial.print("\r\nConf.LS: ");
//Serial.println(lowspeed, HEX);
rcode = Configuring(0, 0, lowspeed);
if(rcode) {
if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) {
usb_error = rcode;
usb_task_state = USB_STATE_ERROR;
}
} else
usb_task_state = USB_STATE_RUNNING;
break;
case USB_STATE_RUNNING:
break;
case USB_STATE_ERROR:
//MAX3421E::Init();
break;
} // switch( usb_task_state )
}
uint8_t USB::DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed) {
//uint8_t buf[12];
uint8_t rcode;
UsbDevice *p0 = NULL, *p = NULL;
// Get pointer to pseudo device with address 0 assigned
p0 = addrPool.GetUsbDevicePtr(0);
if(!p0)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
if(!p0->epinfo)
return USB_ERROR_EPINFO_IS_NULL;
p0->lowspeed = (lowspeed) ? true : false;
// Allocate new address according to device class
uint8_t bAddress = addrPool.AllocAddress(parent, false, port);
if(!bAddress)
return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
p = addrPool.GetUsbDevicePtr(bAddress);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
p->lowspeed = lowspeed;
// Assign new address to the device
rcode = setAddr(0, 0, bAddress);
if(rcode) {
addrPool.FreeAddress(bAddress);
bAddress = 0;
return rcode;
}
return 0;
};
uint8_t USB::AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lowspeed) {
//printf("AttemptConfig: parent = %i, port = %i\r\n", parent, port);
uint8_t retries = 0;
again:
uint8_t rcode = devConfig[driver]->ConfigureDevice(parent, port, lowspeed);
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.
} else {
// 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
delay(100);
retries++;
goto again;
} 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
delay(100);
retries++;
goto again;
}
if(rcode) {
// Issue a bus reset, because the device may be in a limbo state
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.
} else {
// reset parent port
devConfig[parent]->ResetHubPort(port);
}
}
return rcode;
}
/*
* This is broken. We need to enumerate differently.
* It causes major problems with several devices if detected in an unexpected order.
*
*
* Oleg - I wouldn't do anything before the newly connected device is considered sane.
* i.e.(delays are not indicated for brevity):
* 1. reset
* 2. GetDevDescr();
* 3a. If ACK, continue with allocating address, addressing, etc.
* 3b. Else reset again, count resets, stop at some number (5?).
* 4. When max.number of resets is reached, toggle power/fail
* If desired, this could be modified by performing two resets with GetDevDescr() in the middle - however, from my experience, if a device answers to GDD()
* it doesn't need to be reset again
* New steps proposal:
* 1: get address pool instance. exit on fail
* 2: pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf). exit on fail.
* 3: bus reset, 100ms delay
* 4: set address
* 5: pUsb->setEpInfoEntry(bAddress, 1, epInfo), exit on fail
* 6: while (configurations) {
* for(each configuration) {
* for (each driver) {
* 6a: Ask device if it likes configuration. Returns 0 on OK.
* If successful, the driver configured device.
* The driver now owns the endpoints, and takes over managing them.
* The following will need codes:
* Everything went well, instance consumed, exit with success.
* Instance already in use, ignore it, try next driver.
* Not a supported device, ignore it, try next driver.
* Not a supported configuration for this device, ignore it, try next driver.
* Could not configure device, fatal, exit with fail.
* }
* }
* }
* 7: for(each driver) {
* 7a: Ask device if it knows this VID/PID. Acts exactly like 6a, but using VID/PID
* 8: if we get here, no driver likes the device plugged in, so exit failure.
*
*/
uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) {
//uint8_t bAddress = 0;
//printf("Configuring: parent = %i, port = %i\r\n", parent, port);
uint8_t devConfigIndex;
uint8_t rcode = 0;
uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
USB_DEVICE_DESCRIPTOR *udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR *>(buf);
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
EpInfo epInfo;
epInfo.epAddr = 0;
epInfo.maxPktSize = 8;
epInfo.bmSndToggle = 0;
epInfo.bmRcvToggle = 0;
epInfo.bmNakPower = USB_NAK_MAX_POWER;
//delay(2000);
AddressPool &addrPool = GetAddressPool();
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
if(!p) {
//printf("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n");
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
}
// 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;
p->lowspeed = lowspeed;
// Get device descriptor
rcode = getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf);
// Restore p->epinfo
p->epinfo = oldep_ptr;
if(rcode) {
//printf("Configuring error: Can't get USB_DEVICE_DESCRIPTOR\r\n");
return rcode;
}
// to-do?
// Allocate new address according to device class
//bAddress = addrPool.AllocAddress(parent, false, port);
uint16_t vid = udd->idVendor;
uint16_t pid = udd->idProduct;
uint8_t klass = udd->bDeviceClass;
uint8_t subklass = udd->bDeviceSubClass;
// Attempt to configure if VID/PID or device class matches with a driver
// Qualify with subclass too.
//
// VID/PID & class tests default to false for drivers not yet ported
// subclass defaults to true, so you don't have to define it if you don't have to.
//
for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) {
if(!devConfig[devConfigIndex]) continue; // no driver
if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed
if(devConfig[devConfigIndex]->DEVSUBCLASSOK(subklass) && (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass))) {
rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed);
if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED)
break;
}
}
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]->DEVSUBCLASSOK(subklass) && (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);