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);
MODIFIERKEYS mod;
*((uint8_t*)&mod) = m;
if (bDebugPrint)
{
Serial.print((mod.bmLeftCtrl == 1) ? "C" : " ");
Serial.print((mod.bmLeftShift == 1) ? "S" : " ");
Serial.print((mod.bmLeftAlt == 1) ? "A" : " ");
Serial.print((mod.bmLeftGUI == 1) ? "G" : " ");
pinMode(IIKEYB_RESET, INPUT_PULLUP);
pinMode(IIKEYB_STRB, OUTPUT);
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" : " ");
}
};
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);
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);
}
digitalWrite(IIKEYB_RESET, HIGH);
digitalWrite(IIKEYB_STRB, HIGH);
if (0x52 == key) //Arrow UP
{
StringBackLog.OneBack();
}
else if (0x51 == key) //Arrow DOWN
{
StringBackLog.OneForeward();
}
else if (c)
{
OnKeyPressed(c);
}
}
void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after)
{
MODIFIERKEYS beforeMod;
*((uint8_t*)&beforeMod) = before;
MODIFIERKEYS afterMod;
*((uint8_t*)&afterMod) = after;
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");
}
}
void II_Reset(void)
void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
pinMode(IIKEYB_RESET, OUTPUT);
pinMode(IIKEYB_RESET, LOW);
delay(10);
pinMode(IIKEYB_RESET, INPUT_PULLUP);
digitalWrite(IIKEYB_RESET, HIGH);
//Serial.print("UP ");
//PrintKey(mod, key);
}
int II_putchar(int bOutput)
void KbdRptParser::OnKeyPressed(uint8_t key)
{
if (10 == bOutput)
bOutput = '\r';
if (0x0D == bOutput)
bOutput = '\r';
if (bOutput & 0b00000001)
digitalWrite(IIKEYB_D0, HIGH);
if (bDebugPrint)
{
Serial.print("ASCII: ");
Serial.print((char)key);
Serial.print(" ");
Serial.println((char)key, HEX);
}
else
digitalWrite(IIKEYB_D0, LOW);
{
StringBackLog.addchar((char)key);
if (bOutput & 0b00000010)
digitalWrite(IIKEYB_D1, HIGH);
if (0x0D == key)
Serial.println();
else
digitalWrite(IIKEYB_D1, LOW);
Serial.print((char)key);
}
if (bOutput & 0b00000100)
digitalWrite(IIKEYB_D2, HIGH);
if (0x11 == key)
{
if (bDebugPrint)
Serial.print("Reset");
KeyEncoder.Reset();
}
else if (0x12 == key)
{
CurrLayout.Toggle();
SetLayout(CurrLayout.Get());
}
else
digitalWrite(IIKEYB_D2, LOW);
KeyEncoder.IIputchar((char)key);
};
if (bOutput & 0b00001000)
digitalWrite(IIKEYB_D3, HIGH);
else
digitalWrite(IIKEYB_D3, LOW);
USB Usb;
//USBHub Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
if (bOutput & 0b00010000)
digitalWrite(IIKEYB_D4, HIGH);
else
digitalWrite(IIKEYB_D4, LOW);
KbdRptParser Prs;
if (bOutput & 0b00100000)
digitalWrite(IIKEYB_D5, HIGH);
else
digitalWrite(IIKEYB_D5, LOW);
/*! \brief Wrapper for callback use.
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 IIputsWrapper(const char *string)
{
KeyEncoder.IIputchar(string);
}
int II_puts(const char *string)
/*! \brief Print a welcome message
Prints some nice ASCII art through the arduino terminal as a welcome.
*/
void print_welcome_msg(void)
{
int i = 0;
while (string[i]) //standard c idiom for looping through a null-terminated string
{
if ( II_putchar(string[i]) == EOF) //if we got the EOF value from writing the char
{
return EOF;
}
i++;
}
if (II_putchar('\r') == EOF) //this will occur right after we quit due to the null terminated character.
{
return EOF;
}
return 1; //to meet spec.
}
char *convert(unsigned int num, int base)
{
static char Representation[] = "0123456789ABCDEF";
static char buffer[50];
char *ptr;
ptr = &buffer[49];
*ptr = '\0';
do
{
*--ptr = Representation[num % base];
num /= base;
} while (num != 0);
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;
}
}
//Module 3: Closing argument list to necessary clean-up
va_end(arg);
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()
{
Prs.bDebugPrint = false;
Serial.begin( 115200 );
setupIO();
Serial.println("Apple II Keyboard started");
#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();
II_puts(" ");
CurrLayout.Init();
while (Serial.available() == 0) {}
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);
//printf("ERROR ENUMERATING %2.2x\r\n", rcode);
if(!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) {
// in case of an error dev_index should be reset to 0
// in order to start from the very beginning the
// next time the program gets here
//if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE)
// devConfigIndex = 0;
return rcode;
}
}
// if we get here that means that the device class is not supported by any of registered classes
rcode = DefaultAddressing(parent, port, lowspeed);
return rcode;
}
uint8_t USB::ReleaseDevice(uint8_t addr) {
if(!addr)
return 0;
for(uint8_t i = 0; i < USB_NUMDEVICES; i++) {
if(!devConfig[i]) continue;
if(devConfig[i]->GetAddress() == addr)
return devConfig[i]->Release();
}
return 0;
}
#if 1 //!defined(USB_METHODS_INLINE)
//get device descriptor
uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) {
return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, nbytes, dataptr, NULL));
}
//get configuration descriptor
uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) {
return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, nbytes, dataptr, NULL));
}
/* Requests Configuration Descriptor. Sends two Get Conf Descr requests. The first one gets the total length of all descriptors, then the second one requests this
total length. The length of the first request can be shorter ( 4 bytes ), however, there are devices which won't work unless this length is set to 9 */
uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p) {
const uint8_t bufSize = 64;
uint8_t buf[bufSize];
USB_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast<USB_CONFIGURATION_DESCRIPTOR *>(buf);
uint8_t ret = getConfDescr(addr, ep, 9, conf, buf);
if(ret)
return ret;
uint16_t total = ucd->wTotalLength;
//USBTRACE2("\r\ntotal conf.size:", total);
return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, total, bufSize, buf, p));
}
//get string descriptor
uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t ns, uint8_t index, uint16_t langid, uint8_t* dataptr) {
return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, ns, ns, dataptr, NULL));
}
//set address
uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) {
uint8_t rcode = ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL);
//delay(2); //per USB 2.0 sect.9.2.6.3
delay(300); // Older spec says you should wait at least 200ms
return rcode;
//return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL));
}
//set configuration
uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) {
return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL));
}
#endif // defined(USB_METHODS_INLINE)

View File

@ -0,0 +1,41 @@
/* 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 */
#ifndef _usb_h_
#define _usb_h_
// WARNING: Do not change the order of includes, or stuff will break!
#include <inttypes.h>
#include <stddef.h>
#include <stdio.h>
// None of these should ever be included by a driver, or a user's sketch.
#include "settings.h"
#include "printhex.h"
#include "message.h"
#include "hexdump.h"
#include "sink_parser.h"
#include "max3421e.h"
#include "address.h"
#include "avrpins.h"
#include "usb_ch9.h"
#include "usbhost.h"
#include "UsbCore.h"
#include "parsetools.h"
#include "confdescparser.h"
#endif //_usb_h_

View File

@ -0,0 +1,302 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#if !defined(_usb_h_) || defined(USBCORE_H)
#error "Never include UsbCore.h directly; include Usb.h instead"
#else
#define USBCORE_H
// Not used anymore? If anyone uses this, please let us know so that this may be
// moved to the proper place, settings.h.
//#define USB_METHODS_INLINE
/* shield pins. First parameter - SS pin, second parameter - INT pin */
#ifdef BOARD_BLACK_WIDDOW
typedef MAX3421e<P6, P3> MAX3421E; // Black Widow
#elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__))
#if EXT_RAM
typedef MAX3421e<P20, P7> MAX3421E; // Teensy++ 2.0 with XMEM2
#else
typedef MAX3421e<P9, P8> MAX3421E; // Teensy++ 1.0 and 2.0
#endif
#elif defined(BOARD_MEGA_ADK)
typedef MAX3421e<P53, P54> MAX3421E; // Arduino Mega ADK
#elif defined(ARDUINO_AVR_BALANDUINO)
typedef MAX3421e<P20, P19> MAX3421E; // Balanduino
#elif defined(__ARDUINO_X86__) && PLATFORM_ID == 0x06
typedef MAX3421e<P3, P2> MAX3421E; // The Intel Galileo supports much faster read and write speed at pin 2 and 3
#elif defined(ESP8266)
typedef MAX3421e<P15, P5> MAX3421E; // ESP8266 boards
#elif defined(ESP32)
typedef MAX3421e<P5, P17> MAX3421E; // ESP32 boards
#else
typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.x
#endif
/* Common setup data constant combinations */
#define bmREQ_GET_DESCR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //get descriptor request type
#define bmREQ_SET USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //set request type for all but 'set feature' and 'set interface'
#define bmREQ_CL_GET_INTF USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE //get interface request type
// D7 data transfer direction (0 - host-to-device, 1 - device-to-host)
// D6-5 Type (0- standard, 1 - class, 2 - vendor, 3 - reserved)
// D4-0 Recipient (0 - device, 1 - interface, 2 - endpoint, 3 - other, 4..31 - reserved)
// USB Device Classes
#define USB_CLASS_USE_CLASS_INFO 0x00 // Use Class Info in the Interface Descriptors
#define USB_CLASS_AUDIO 0x01 // Audio
#define USB_CLASS_COM_AND_CDC_CTRL 0x02 // Communications and CDC Control
#define USB_CLASS_HID 0x03 // HID
#define USB_CLASS_PHYSICAL 0x05 // Physical
#define USB_CLASS_IMAGE 0x06 // Image
#define USB_CLASS_PRINTER 0x07 // Printer
#define USB_CLASS_MASS_STORAGE 0x08 // Mass Storage
#define USB_CLASS_HUB 0x09 // Hub
#define USB_CLASS_CDC_DATA 0x0a // CDC-Data
#define USB_CLASS_SMART_CARD 0x0b // Smart-Card
#define USB_CLASS_CONTENT_SECURITY 0x0d // Content Security
#define USB_CLASS_VIDEO 0x0e // Video
#define USB_CLASS_PERSONAL_HEALTH 0x0f // Personal Healthcare
#define USB_CLASS_DIAGNOSTIC_DEVICE 0xdc // Diagnostic Device
#define USB_CLASS_WIRELESS_CTRL 0xe0 // Wireless Controller
#define USB_CLASS_MISC 0xef // Miscellaneous
#define USB_CLASS_APP_SPECIFIC 0xfe // Application Specific
#define USB_CLASS_VENDOR_SPECIFIC 0xff // Vendor Specific
// Additional Error Codes
#define USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED 0xD1
#define USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE 0xD2
#define USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS 0xD3
#define USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL 0xD4
#define USB_ERROR_HUB_ADDRESS_OVERFLOW 0xD5
#define USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL 0xD6
#define USB_ERROR_EPINFO_IS_NULL 0xD7
#define USB_ERROR_INVALID_ARGUMENT 0xD8
#define USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE 0xD9
#define USB_ERROR_INVALID_MAX_PKT_SIZE 0xDA
#define USB_ERROR_EP_NOT_FOUND_IN_TBL 0xDB
#define USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET 0xE0
#define USB_ERROR_FailGetDevDescr 0xE1
#define USB_ERROR_FailSetDevTblEntry 0xE2
#define USB_ERROR_FailGetConfDescr 0xE3
#define USB_ERROR_TRANSFER_TIMEOUT 0xFF
#define USB_XFER_TIMEOUT 5000 // (5000) USB transfer timeout in milliseconds, per section 9.2.6.1 of USB 2.0 spec
//#define USB_NAK_LIMIT 32000 // NAK limit for a transfer. 0 means NAKs are not counted
#define USB_RETRY_LIMIT 3 // 3 retry limit for a transfer
#define USB_SETTLE_DELAY 200 // settle delay in milliseconds
#define USB_NUMDEVICES 16 //number of USB devices
//#define HUB_MAX_HUBS 7 // maximum number of hubs that can be attached to the host controller
#define HUB_PORT_RESET_DELAY 20 // hub port reset delay 10 ms recomended, can be up to 20 ms
/* USB state machine states */
#define USB_STATE_MASK 0xf0
#define USB_STATE_DETACHED 0x10
#define USB_DETACHED_SUBSTATE_INITIALIZE 0x11
#define USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE 0x12
#define USB_DETACHED_SUBSTATE_ILLEGAL 0x13
#define USB_ATTACHED_SUBSTATE_SETTLE 0x20
#define USB_ATTACHED_SUBSTATE_RESET_DEVICE 0x30
#define USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE 0x40
#define USB_ATTACHED_SUBSTATE_WAIT_SOF 0x50
#define USB_ATTACHED_SUBSTATE_WAIT_RESET 0x51
#define USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE 0x60
#define USB_STATE_ADDRESSING 0x70
#define USB_STATE_CONFIGURING 0x80
#define USB_STATE_RUNNING 0x90
#define USB_STATE_ERROR 0xa0
class USBDeviceConfig {
public:
virtual uint8_t Init(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed __attribute__((unused))) {
return 0;
}
virtual uint8_t ConfigureDevice(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed __attribute__((unused))) {
return 0;
}
virtual uint8_t Release() {
return 0;
}
virtual uint8_t Poll() {
return 0;
}
virtual uint8_t GetAddress() {
return 0;
}
virtual void ResetHubPort(uint8_t port __attribute__((unused))) {
return;
} // Note used for hubs only!
virtual bool VIDPIDOK(uint16_t vid __attribute__((unused)), uint16_t pid __attribute__((unused))) {
return false;
}
virtual bool DEVCLASSOK(uint8_t klass __attribute__((unused))) {
return false;
}
virtual bool DEVSUBCLASSOK(uint8_t subklass __attribute__((unused))) {
return true;
}
};
/* USB Setup Packet Structure */
typedef struct {
union { // offset description
uint8_t bmRequestType; // 0 Bit-map of request type
struct {
uint8_t recipient : 5; // Recipient of the request
uint8_t type : 2; // Type of request
uint8_t direction : 1; // Direction of data X-fer
} __attribute__((packed));
} ReqType_u;
uint8_t bRequest; // 1 Request
union {
uint16_t wValue; // 2 Depends on bRequest
struct {
uint8_t wValueLo;
uint8_t wValueHi;
} __attribute__((packed));
} wVal_u;
uint16_t wIndex; // 4 Depends on bRequest
uint16_t wLength; // 6 Depends on bRequest
} __attribute__((packed)) SETUP_PKT, *PSETUP_PKT;
// Base class for incoming data parser
class USBReadParser {
public:
virtual void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset) = 0;
};
class USB : public MAX3421E {
AddressPoolImpl<USB_NUMDEVICES> addrPool;
USBDeviceConfig* devConfig[USB_NUMDEVICES];
uint8_t bmHubPre;
public:
USB(void);
void SetHubPreMask() {
bmHubPre |= bmHUBPRE;
};
void ResetHubPreMask() {
bmHubPre &= (~bmHUBPRE);
};
AddressPool& GetAddressPool() {
return (AddressPool&)addrPool;
};
uint8_t RegisterDeviceClass(USBDeviceConfig *pdev) {
for(uint8_t i = 0; i < USB_NUMDEVICES; i++) {
if(!devConfig[i]) {
devConfig[i] = pdev;
return 0;
}
}
return USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS;
};
void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) {
addrPool.ForEachUsbDevice(pfunc);
};
uint8_t getUsbTaskState(void);
void setUsbTaskState(uint8_t state);
EpInfo* getEpInfoEntry(uint8_t addr, uint8_t ep);
uint8_t setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr);
/* Control requests */
uint8_t getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr);
uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr);
uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p);
uint8_t getStrDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t index, uint16_t langid, uint8_t* dataptr);
uint8_t setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr);
uint8_t setConf(uint8_t addr, uint8_t ep, uint8_t conf_value);
/**/
uint8_t ctrlData(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr, bool direction);
uint8_t ctrlStatus(uint8_t ep, bool direction, uint16_t nak_limit);
uint8_t inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t* data, uint8_t bInterval = 0);
uint8_t outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* data);
uint8_t dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit);
void Task(void);
uint8_t DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed);
uint8_t Configuring(uint8_t parent, uint8_t port, bool lowspeed);
uint8_t ReleaseDevice(uint8_t addr);
uint8_t ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi,
uint16_t wInd, uint16_t total, uint16_t nbytes, uint8_t* dataptr, USBReadParser *p);
private:
void init();
uint8_t SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t *nak_limit);
uint8_t OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data);
uint8_t InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t *data, uint8_t bInterval = 0);
uint8_t AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lowspeed);
};
#if 0 //defined(USB_METHODS_INLINE)
//get device descriptor
inline uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) {
return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, dataptr));
}
//get configuration descriptor
inline uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) {
return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, dataptr));
}
//get string descriptor
inline uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t nuint8_ts, uint8_t index, uint16_t langid, uint8_t* dataptr) {
return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nuint8_ts, dataptr));
}
//set address
inline uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) {
return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, NULL));
}
//set configuration
inline uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) {
return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, NULL));
}
#endif // defined(USB_METHODS_INLINE)
#endif /* USBCORE_H */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,518 @@
/* 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
IR camera support added by Allan Glover (adglover9.81@gmail.com) and Kristian Lauszus
*/
#ifndef _wii_h_
#define _wii_h_
#include "BTD.h"
#include "controllerEnums.h"
/* Wii event flags */
#define WII_FLAG_MOTION_PLUS_CONNECTED (1 << 0)
#define WII_FLAG_NUNCHUCK_CONNECTED (1 << 1)
#define WII_FLAG_CALIBRATE_BALANCE_BOARD (1 << 2)
#define wii_check_flag(flag) (wii_event_flag & (flag))
#define wii_set_flag(flag) (wii_event_flag |= (flag))
#define wii_clear_flag(flag) (wii_event_flag &= ~(flag))
/** Enum used to read the joystick on the Nunchuck. */
enum HatEnum {
/** Read the x-axis on the Nunchuck joystick. */
HatX = 0,
/** Read the y-axis on the Nunchuck joystick. */
HatY = 1,
};
/** Enum used to read the weight on Wii Balance Board. */
enum BalanceBoardEnum {
TopRight = 0,
BotRight = 1,
TopLeft = 2,
BotLeft = 3,
};
/**
* This BluetoothService class implements support for the Wiimote including the Nunchuck and Motion Plus extension.
*
* It also support the Wii U Pro Controller.
*/
class WII : public BluetoothService {
public:
/**
* Constructor for the WII class.
* @param p Pointer to BTD class instance.
* @param pair Set this to true in order to pair with the Wiimote. If the argument is omitted then it won't pair with it.
* One can use ::PAIR to set it to true.
*/
WII(BTD *p, bool pair = false);
/** @name BluetoothService implementation */
/** Used this to disconnect any of the controllers. */
void disconnect();
/**@}*/
/** @name Wii Controller functions */
/**
* getButtonPress(Button b) will return true as long as the button is held down.
*
* While getButtonClick(Button b) will only return it once.
*
* So you instance if you need to increase a variable once you would use getButtonClick(Button b),
* but if you need to drive a robot forward you would use getButtonPress(Button b).
* @param b ::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 Wii Controller functions */
/** Call this to start the pairing sequence with a controller */
void pair(void) {
if(pBtd)
pBtd->pairWithWiimote();
};
/**
* Used to read the joystick of the Nunchuck.
* @param a Either ::HatX or ::HatY.
* @return Return the analog value in the range from approximately 25-230.
*/
uint8_t getAnalogHat(HatEnum a);
/**
* Used to read the joystick of the Wii U Pro Controller.
* @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
* @return Return the analog value in the range from approximately 800-3200.
*/
uint16_t getAnalogHat(AnalogHatEnum a);
/**
* Pitch calculated from the Wiimote. A complimentary filter is used if the Motion Plus is connected.
* @return Pitch in the range from 0-360.
*/
float getPitch() {
if(motionPlusConnected)
return compPitch;
return getWiimotePitch();
};
/**
* Roll calculated from the Wiimote. A complimentary filter is used if the Motion Plus is connected.
* @return Roll in the range from 0-360.
*/
float getRoll() {
if(motionPlusConnected)
return compRoll;
return getWiimoteRoll();
};
/**
* This is the yaw calculated by the gyro.
*
* <B>NOTE:</B> This angle will drift a lot and is only available if the Motion Plus extension is connected.
* @return The angle calculated using the gyro.
*/
float getYaw() {
return gyroYaw;
};
/** Used to set all LEDs and rumble off. */
void setAllOff();
/** Turn off rumble. */
void setRumbleOff();
/** Turn on rumble. */
void setRumbleOn();
/** Toggle rumble. */
void setRumbleToggle();
/**
* 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);
/**
* This will set the LEDs, so the user can see which connections are active.
*
* The first ::LEDEnum indicate that the Wiimote is connected,
* the second ::LEDEnum indicate indicate that a Motion Plus is also connected
* the third ::LEDEnum will indicate that a Nunchuck controller is also connected.
*/
void setLedStatus();
/**
* Return the battery level of the Wiimote.
* @return The battery level in the range 0-255.
*/
uint8_t getBatteryLevel();
/**
* Return the Wiimote state.
* @return See: http://wiibrew.org/wiki/Wiimote#0x20:_Status.
*/
uint8_t getWiiState() {
return wiiState;
};
/**@}*/
/**@{*/
/** Variable used to indicate if a Wiimote is connected. */
bool wiimoteConnected;
/** Variable used to indicate if a Nunchuck controller is connected. */
bool nunchuckConnected;
/** Variable used to indicate if a Nunchuck controller is connected. */
bool motionPlusConnected;
/** Variable used to indicate if a Wii U Pro controller is connected. */
bool wiiUProControllerConnected;
/** Variable used to indicate if a Wii Balance Board is connected. */
bool wiiBalanceBoardConnected;
/**@}*/
/* IMU Data, might be usefull if you need to do something more advanced than just calculating the angle */
/**@{*/
/** Pitch and roll calculated from the accelerometer inside the Wiimote. */
float getWiimotePitch() {
return (atan2f(accYwiimote, accZwiimote) + PI) * RAD_TO_DEG;
};
float getWiimoteRoll() {
return (atan2f(accXwiimote, accZwiimote) + PI) * RAD_TO_DEG;
};
/**@}*/
/**@{*/
/** Pitch and roll calculated from the accelerometer inside the Nunchuck. */
float getNunchuckPitch() {
return (atan2f(accYnunchuck, accZnunchuck) + PI) * RAD_TO_DEG;
};
float getNunchuckRoll() {
return (atan2f(accXnunchuck, accZnunchuck) + PI) * RAD_TO_DEG;
};
/**@}*/
/**@{*/
/** Accelerometer values used to calculate pitch and roll. */
int16_t accXwiimote, accYwiimote, accZwiimote;
int16_t accXnunchuck, accYnunchuck, accZnunchuck;
/**@}*/
/* Variables for the gyro inside the Motion Plus */
/** This is the pitch calculated by the gyro - use this to tune WII#pitchGyroScale. */
float gyroPitch;
/** This is the roll calculated by the gyro - use this to tune WII#rollGyroScale. */
float gyroRoll;
/** This is the yaw calculated by the gyro - use this to tune WII#yawGyroScale. */
float gyroYaw;
/**@{*/
/** The speed in deg/s from the gyro. */
float pitchGyroSpeed;
float rollGyroSpeed;
float yawGyroSpeed;
/**@}*/
/**@{*/
/** You might need to fine-tune these values. */
uint16_t pitchGyroScale;
uint16_t rollGyroScale;
uint16_t yawGyroScale;
/**@}*/
/**@{*/
/** Raw value read directly from the Motion Plus. */
int16_t gyroYawRaw;
int16_t gyroRollRaw;
int16_t gyroPitchRaw;
/**@}*/
/**@{*/
/** These values are set when the controller is first initialized. */
int16_t gyroYawZero;
int16_t gyroRollZero;
int16_t gyroPitchZero;
/**@}*/
/** @name Wii Balance Board functions */
/**
* Used to get the weight at the specific position on the Wii Balance Board.
* @param pos ::BalanceBoardEnum to read from.
* @return Returns the weight in kg.
*/
float getWeight(BalanceBoardEnum pos);
/**
* Used to get total weight on the Wii Balance Board.
* @return Returns the weight in kg.
*/
float getTotalWeight();
/**
* Used to get the raw reading at the specific position on the Wii Balance Board.
* @param pos ::BalanceBoardEnum to read from.
* @return Returns the raw reading.
*/
uint16_t getWeightRaw(BalanceBoardEnum pos) {
return wiiBalanceBoardRaw[pos];
};
/**@}*/
#ifdef WIICAMERA
/** @name Wiimote IR camera functions
* You will have to set ::ENABLE_WII_IR_CAMERA in settings.h to 1 in order use the IR camera.
*/
/** Initialises the camera as per the steps from: http://wiibrew.org/wiki/Wiimote#IR_Camera */
void IRinitialize();
/**
* IR object 1 x-position read from the Wii IR camera.
* @return The x-position of the object in the range 0-1023.
*/
uint16_t getIRx1() {
return IR_object_x1;
};
/**
* IR object 1 y-position read from the Wii IR camera.
* @return The y-position of the object in the range 0-767.
*/
uint16_t getIRy1() {
return IR_object_y1;
};
/**
* IR object 1 size read from the Wii IR camera.
* @return The size of the object in the range 0-15.
*/
uint8_t getIRs1() {
return IR_object_s1;
};
/**
* IR object 2 x-position read from the Wii IR camera.
* @return The x-position of the object in the range 0-1023.
*/
uint16_t getIRx2() {
return IR_object_x2;
};
/**
* IR object 2 y-position read from the Wii IR camera.
* @return The y-position of the object in the range 0-767.
*/
uint16_t getIRy2() {
return IR_object_y2;
};
/**
* IR object 2 size read from the Wii IR camera.
* @return The size of the object in the range 0-15.
*/
uint8_t getIRs2() {
return IR_object_s2;
};
/**
* IR object 3 x-position read from the Wii IR camera.
* @return The x-position of the object in the range 0-1023.
*/
uint16_t getIRx3() {
return IR_object_x3;
};
/**
* IR object 3 y-position read from the Wii IR camera.
* @return The y-position of the object in the range 0-767.
*/
uint16_t getIRy3() {
return IR_object_y3;
};
/**
* IR object 3 size read from the Wii IR camera.
* @return The size of the object in the range 0-15.
*/
uint8_t getIRs3() {
return IR_object_s3;
};
/**
* IR object 4 x-position read from the Wii IR camera.
* @return The x-position of the object in the range 0-1023.
*/
uint16_t getIRx4() {
return IR_object_x4;
};
/**
* IR object 4 y-position read from the Wii IR camera.
* @return The y-position of the object in the range 0-767.
*/
uint16_t getIRy4() {
return IR_object_y4;
};
/**
* IR object 4 size read from the Wii IR camera.
* @return The size of the object in the range 0-15.
*/
uint8_t getIRs4() {
return IR_object_s4;
};
/**
* Use this to check if the camera is enabled or not.
* If not call WII#IRinitialize to initialize the IR camera.
* @return True if it's enabled, false if not.
*/
bool isIRCameraEnabled() {
return (wiiState & 0x08);
};
/**@}*/
#endif
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 */
bool activeConnection; // Used to indicate if it's already has established a connection
/* Variables used by high level L2CAP task */
uint8_t l2cap_state;
uint8_t wii_event_flag; // Used for Wii flags
uint32_t ButtonState;
uint32_t OldButtonState;
uint32_t ButtonClickState;
uint16_t hatValues[4];
uint8_t HIDBuffer[3]; // Used to store HID commands
uint16_t stateCounter;
bool unknownExtensionConnected;
bool extensionConnected;
bool checkBatteryLevel; // Set to true when getBatteryLevel() is called otherwise if should be false
bool motionPlusInside; // True if it's a new Wiimote with the Motion Plus extension build into it
/* L2CAP Channels */
uint8_t control_scid[2]; // L2CAP source CID for HID_Control
uint8_t control_dcid[2]; // 0x0060
uint8_t interrupt_scid[2]; // L2CAP source CID for HID_Interrupt
uint8_t interrupt_dcid[2]; // 0x0061
/* HID Commands */
void HID_Command(uint8_t* data, uint8_t nbytes);
void setReportMode(bool continuous, uint8_t mode);
void writeData(uint32_t offset, uint8_t size, uint8_t* data);
void initExtension1();
void initExtension2();
void statusRequest(); // Used to update the Wiimote state and battery level
void readData(uint32_t offset, uint16_t size, bool EEPROM);
void readExtensionType();
void readCalData();
void readWiiBalanceBoardCalibration(); // Used by the library to read the Wii Balance Board calibration values
void checkMotionPresent(); // Used to see if a Motion Plus is connected to the Wiimote
void initMotionPlus();
void activateMotionPlus();
uint16_t wiiBalanceBoardRaw[4]; // Wii Balance Board raw values
uint16_t wiiBalanceBoardCal[3][4]; // Wii Balance Board calibration values
float compPitch; // Fusioned angle using a complimentary filter if the Motion Plus is connected
float compRoll; // Fusioned angle using a complimentary filter if the Motion Plus is connected
bool activateNunchuck;
bool motionValuesReset; // This bool is true when the gyro values has been reset
uint32_t timer;
uint8_t wiiState; // Stores the value in l2capinbuf[12] - (0x01: Battery is nearly empty), (0x02: An Extension Controller is connected), (0x04: Speaker enabled), (0x08: IR enabled), (0x10: LED1, 0x20: LED2, 0x40: LED3, 0x80: LED4)
uint8_t batteryLevel;
#ifdef WIICAMERA
/* Private function and variables for the readings from the IR Camera */
void enableIRCamera1(); // Sets bit 2 of output report 13
void enableIRCamera2(); // Sets bit 2 of output report 1A
void writeSensitivityBlock1();
void writeSensitivityBlock2();
void write0x08Value();
void setWiiModeNumber(uint8_t mode_number);
uint16_t IR_object_x1; // IR x position 10 bits
uint16_t IR_object_y1; // IR y position 10 bits
uint8_t IR_object_s1; // IR size value
uint16_t IR_object_x2;
uint16_t IR_object_y2;
uint8_t IR_object_s2;
uint16_t IR_object_x3; // IR x position 10 bits
uint16_t IR_object_y3; // IR y position 10 bits
uint8_t IR_object_s3; // IR size value
uint16_t IR_object_x4;
uint16_t IR_object_y4;
uint8_t IR_object_s4;
#endif
};
#endif

View File

@ -0,0 +1,13 @@
Please see <http://wiibrew.org/wiki/Wiimote#IR_Camera> for the complete capabilities of the Wii camera. The IR camera code was written based on the above website and with support from Kristian Lauszus.
This library is large, if you run into memory problems when uploading to the Arduino, disable serial debugging.
To enable the IR camera code, simply set ```ENABLE_WII_IR_CAMERA``` to 1 in [settings.h](settings.h).
This library implements the following settings:
* Report sensitivity mode: 00 00 00 00 00 00 90 00 41 40 00 Suggested by inio (high sensitivity)
* Data Format: Extended mode (0x03). Full mode is not working yet. The output reports 0x3e and 0x3f need tampering with
* In this mode the camera outputs x and y coordinates and a size dimension for the 4 brightest points.
Again, read through <http://wiibrew.org/wiki/Wiimote#IR_Camera> to get an understanding of the camera and its settings.

View File

@ -0,0 +1,338 @@
/* 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 "XBOXOLD.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 Xbox controller
/** Buttons on the controllers */
const uint8_t XBOXOLD_BUTTONS[] PROGMEM = {
0x01, // UP
0x08, // RIGHT
0x02, // DOWN
0x04, // LEFT
0x20, // BACK
0x10, // START
0x40, // L3
0x80, // R3
// A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons
4, // BLACK
5, // WHTIE
6, // L1
7, // R1
1, // B
0, // A
2, // X
3, // Y
};
XBOXOLD::XBOXOLD(USB *p) :
pUsb(p), // pointer to USB class instance - mandatory
bAddress(0), // device address - mandatory
bPollEnable(false) { // don't start polling before dongle is connected
for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) {
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
}
uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) {
uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<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\nXBOXUSB 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 != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_OLD_PID1 && PID != XBOX_OLD_PID2 && PID != XBOX_OLD_PID3 && PID != XBOX_OLD_PID4)) // Check if VID and PID match
goto FailUnknownDevice;
// Allocate new address according to device class
bAddress = addrPool.AllocAddress(parent, false, port);
if(!bAddress)
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 VID we will use known values for the
configuration values for device, interface, endpoints and HID for the XBOX controllers */
/* Initialize data structures for endpoints of device */
epInfo[ XBOX_INPUT_PIPE ].epAddr = 0x01; // XBOX report endpoint
epInfo[ XBOX_INPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = 0;
epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE ].epAddr = 0x02; // XBOX output endpoint
epInfo[ XBOX_OUTPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = 0;
epInfo[ XBOX_OUTPUT_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[ XBOX_CONTROL_PIPE ].epAddr, 1);
if(rcode)
goto FailSetConfDescr;
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nXbox Controller Connected\r\n"), 0x80);
#endif
if(pFuncOnInit)
pFuncOnInit(); // Call the user function
XboxConnected = true;
bPollEnable = true;
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\nXbox Init Failed, error code: "), 0x80);
NotifyFail(rcode);
#endif
Release();
return rcode;
}
/* Performs a cleanup after failed Init() attempt */
uint8_t XBOXOLD::Release() {
XboxConnected = false;
pUsb->GetAddressPool().FreeAddress(bAddress);
bAddress = 0;
bPollEnable = false;
return 0;
}
uint8_t XBOXOLD::Poll() {
if(!bPollEnable)
return 0;
uint16_t BUFFER_SIZE = EP_MAXPKTSIZE;
pUsb->inTransfer(bAddress, epInfo[ XBOX_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1
readReport();
#ifdef PRINTREPORT
printReport(BUFFER_SIZE); // Uncomment "#define PRINTREPORT" to print the report send by the Xbox controller
#endif
return 0;
}
void XBOXOLD::readReport() {
ButtonState = readBuf[2];
for(uint8_t i = 0; i < sizeof (buttonValues); i++)
buttonValues[i] = readBuf[i + 4]; // A, B, X, Y, BLACK, WHITE, L1, and R1
hatValue[LeftHatX] = (int16_t)(((uint16_t)readBuf[12] << 8) | readBuf[13]);
hatValue[LeftHatY] = (int16_t)(((uint16_t)readBuf[14] << 8) | readBuf[15]);
hatValue[RightHatX] = (int16_t)(((uint16_t)readBuf[16] << 8) | readBuf[17]);
hatValue[RightHatY] = (int16_t)(((uint16_t)readBuf[18] << 8) | readBuf[19]);
//Notify(PSTR("\r\nButtonState"), 0x80);
//PrintHex<uint8_t>(ButtonState, 0x80);
if(ButtonState != OldButtonState || memcmp(buttonValues, oldButtonValues, sizeof (buttonValues)) != 0) {
ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
OldButtonState = ButtonState;
for(uint8_t i = 0; i < sizeof (buttonValues); i++) {
if(oldButtonValues[i] == 0 && buttonValues[i] != 0)
buttonClicked[i] = true; // Update A, B, X, Y, BLACK, WHITE, L1, and R1 click state
oldButtonValues[i] = buttonValues[i];
}
}
}
void XBOXOLD::printReport(uint16_t length __attribute__((unused))) { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox controller
#ifdef PRINTREPORT
if(readBuf == NULL)
return;
for(uint8_t i = 0; i < length; i++) {
D_PrintHex<uint8_t > (readBuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
Notify(PSTR("\r\n"), 0x80);
#endif
}
uint8_t XBOXOLD::getButtonPress(ButtonEnum b) {
uint8_t button = pgm_read_byte(&XBOXOLD_BUTTONS[(uint8_t)b]);
if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons
return buttonValues[button]; // Analog buttons
return (ButtonState & button); // Digital buttons
}
bool XBOXOLD::getButtonClick(ButtonEnum b) {
uint8_t button = pgm_read_byte(&XBOXOLD_BUTTONS[(uint8_t)b]);
if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) { // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons
if(buttonClicked[button]) {
buttonClicked[button] = false;
return true;
}
return false;
}
bool click = (ButtonClickState & button);
ButtonClickState &= ~button; // clear "click" event
return click;
}
int16_t XBOXOLD::getAnalogHat(AnalogHatEnum a) {
return hatValue[a];
}
/* Xbox Controller commands */
void XBOXOLD::XboxCommand(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[XBOX_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x00, 0x02, 0x00, nbytes, nbytes, data, NULL);
}
void XBOXOLD::setRumbleOn(uint8_t lValue, uint8_t rValue) {
uint8_t writeBuf[6];
writeBuf[0] = 0x00;
writeBuf[1] = 0x06;
writeBuf[2] = 0x00;
writeBuf[3] = rValue; // small weight
writeBuf[4] = 0x00;
writeBuf[5] = lValue; // big weight
XboxCommand(writeBuf, 6);
}

View File

@ -0,0 +1,185 @@
/* 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 _xboxold_h_
#define _xboxold_h_
#include "Usb.h"
#include "usbhid.h"
#include "controllerEnums.h"
/* Data Xbox taken from descriptors */
#define EP_MAXPKTSIZE 32 // Max size for data via USB
/* Names we give to the 3 Xbox pipes */
#define XBOX_CONTROL_PIPE 0
#define XBOX_INPUT_PIPE 1
#define XBOX_OUTPUT_PIPE 2
// PID and VID of the different devices
#define XBOX_VID 0x045E // Microsoft Corporation
#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz controllers
#define JOYTECH_VID 0x162E // For unofficial Joytech controllers
#define XBOX_OLD_PID1 0x0202 // Original Microsoft Xbox controller (US)
#define XBOX_OLD_PID2 0x0285 // Original Microsoft Xbox controller (Japan)
#define XBOX_OLD_PID3 0x0287 // Microsoft Microsoft Xbox Controller S
#define XBOX_OLD_PID4 0x0289 // Smaller Microsoft Xbox controller (US)
#define XBOX_MAX_ENDPOINTS 3
/** This class implements support for a the original Xbox controller via USB. */
class XBOXOLD : public USBDeviceConfig {
public:
/**
* Constructor for the XBOXOLD class.
* @param pUsb Pointer to USB class instance.
*/
XBOXOLD(USB *pUsb);
/** @name USBDeviceConfig implementation */
/**
* Initialize the Xbox 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 == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID) && (pid == XBOX_OLD_PID1 || pid == XBOX_OLD_PID2 || pid == XBOX_OLD_PID3 || pid == XBOX_OLD_PID4));
};
/**@}*/
/** @name Xbox 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 getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a byte if reading ::L2 or ::R2.
*/
uint8_t getButtonPress(ButtonEnum b);
bool getButtonClick(ButtonEnum b);
/**@}*/
/** @name Xbox Controller functions */
/**
* Return the analog value from the joysticks on the controller.
* @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
* @return Returns a signed 16-bit integer.
*/
int16_t getAnalogHat(AnalogHatEnum a);
/** Turn rumble off the controller. */
void setRumbleOff() {
setRumbleOn(0, 0);
};
/**
* Turn rumble on.
* @param lValue Left motor (big weight) inside the controller.
* @param rValue Right motor (small weight) inside the controller.
*/
void setRumbleOn(uint8_t lValue, uint8_t rValue);
/**
* Used to call your own function when the controller is successfully initialized.
* @param funcOnInit Function to call.
*/
void attachOnInit(void (*funcOnInit)(void)) {
pFuncOnInit = funcOnInit;
};
/**@}*/
/** True if a Xbox controller is connected. */
bool XboxConnected;
protected:
/** Pointer to USB class instance. */
USB *pUsb;
/** Device address. */
uint8_t bAddress;
/** Endpoint info structure. */
EpInfo epInfo[XBOX_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 (*pFuncOnInit)(void); // Pointer to function called in onInit()
bool bPollEnable;
/* Variables to store the digital buttons */
uint8_t ButtonState;
uint8_t OldButtonState;
uint8_t ButtonClickState;
/* Variables to store the analog buttons */
uint8_t buttonValues[8]; // A, B, X, Y, BLACK, WHITE, L1, and R1
uint8_t oldButtonValues[8];
bool buttonClicked[8];
int16_t hatValue[4]; // Joystick values
uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
void readReport(); // Read incoming data
void printReport(uint16_t length); // Print incoming date
/* Private commands */
void XboxCommand(uint8_t* data, uint16_t nbytes);
};
#endif

View File

@ -0,0 +1,484 @@
/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
Copyright (C) 2015 guruthree
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
guruthree
Web : https://github.com/guruthree/
*/
#include "XBOXONE.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 Xbox ONE Controller
XBOXONE::XBOXONE(USB *p) :
pUsb(p), // pointer to USB class instance - mandatory
bAddress(0), // device address - mandatory
bNumEP(1), // If config descriptor needs to be parsed
qNextPollTime(0), // Reset NextPollTime
pollInterval(0),
bPollEnable(false) { // don't start polling before dongle is connected
for(uint8_t i = 0; i < XBOX_ONE_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
}
uint8_t XBOXONE::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, VID;
uint8_t num_of_conf; // Number of configurations
// get memory address of USB device address pool
AddressPool &addrPool = pUsb->GetAddressPool();
#ifdef EXTRADEBUG
Notify(PSTR("\r\nXBOXONE 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(!VIDPIDOK(VID, PID)) // Check VID
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;
num_of_conf = udd->bNumConfigurations; // Number of configurations
USBTRACE2("NC:", num_of_conf);
// Check if attached device is a Xbox One controller and fill endpoint data structure
for(uint8_t i = 0; i < num_of_conf; i++) {
ConfigDescParser<0, 0, 0, 0> confDescrParser(this); // Allow all devices, as we have already verified that it is a Xbox One controller from the VID and PID
rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
if(rcode) // Check error code
goto FailGetConfDescr;
if(bNumEP >= XBOX_ONE_MAX_ENDPOINTS) // All endpoints extracted
break;
}
if(bNumEP < XBOX_ONE_MAX_ENDPOINTS)
goto FailUnknownDevice;
rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
if(rcode)
goto FailSetDevTblEntry;
delay(200); // Give time for address change
rcode = pUsb->setConf(bAddress, epInfo[ XBOX_ONE_CONTROL_PIPE ].epAddr, bConfNum);
if(rcode)
goto FailSetConfDescr;
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nXbox One Controller Connected\r\n"), 0x80);
#endif
delay(200); // let things settle
// Initialize the controller for input
cmdCounter = 0; // Reset the counter used when sending out the commands
uint8_t writeBuf[5];
writeBuf[0] = 0x05;
writeBuf[1] = 0x20;
// Byte 2 is set in "XboxCommand"
writeBuf[3] = 0x01;
writeBuf[4] = 0x00;
rcode = XboxCommand(writeBuf, 5);
if (rcode)
goto Fail;
onInit();
XboxOneConnected = true;
bPollEnable = true;
return 0; // Successful configuration
/* Diagnostic messages */
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr();
goto Fail;
#endif
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry();
goto Fail;
#endif
FailGetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetConfDescr();
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\nXbox One Init Failed, error code: "), 0x80);
NotifyFail(rcode);
#endif
Release();
return rcode;
}
/* Extracts endpoint information from config descriptor */
void XBOXONE::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
bConfNum = conf;
uint8_t index;
if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_INTERRUPT) { // Interrupt endpoint
index = (pep->bEndpointAddress & 0x80) == 0x80 ? XBOX_ONE_INPUT_PIPE : XBOX_ONE_OUTPUT_PIPE; // Set the endpoint index
} else
return;
// Fill the rest of endpoint data structure
epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
#ifdef EXTRADEBUG
PrintEndpointDescriptor(pep);
#endif
if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints
pollInterval = pep->bInterval;
bNumEP++;
}
void XBOXONE::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
#ifdef EXTRADEBUG
Notify(PSTR("\r\nEndpoint descriptor:"), 0x80);
Notify(PSTR("\r\nLength:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
Notify(PSTR("\r\nType:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
Notify(PSTR("\r\nAddress:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
Notify(PSTR("\r\nAttributes:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
#endif
}
/* Performs a cleanup after failed Init() attempt */
uint8_t XBOXONE::Release() {
XboxOneConnected = false;
pUsb->GetAddressPool().FreeAddress(bAddress);
bAddress = 0; // Clear device address
bNumEP = 1; // Must have to be reset to 1
qNextPollTime = 0; // Reset next poll time
pollInterval = 0;
bPollEnable = false;
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nXbox One Controller Disconnected\r\n"), 0x80);
#endif
return 0;
}
uint8_t XBOXONE::Poll() {
uint8_t rcode = 0;
if(!bPollEnable)
return 0;
if((int32_t)((uint32_t)millis() - qNextPollTime) >= 0L) { // Do not poll if shorter than polling interval
qNextPollTime = (uint32_t)millis() + pollInterval; // Set new poll time
uint16_t length = (uint16_t)epInfo[ XBOX_ONE_INPUT_PIPE ].maxPktSize; // Read the maximum packet size from the endpoint
uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ XBOX_ONE_INPUT_PIPE ].epAddr, &length, readBuf, pollInterval);
if(!rcode) {
readReport();
#ifdef PRINTREPORT // Uncomment "#define PRINTREPORT" to print the report send by the Xbox ONE Controller
for(uint8_t i = 0; i < length; i++) {
D_PrintHex<uint8_t > (readBuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
Notify(PSTR("\r\n"), 0x80);
#endif
}
#ifdef DEBUG_USB_HOST
else if(rcode != hrNAK) { // Not a matter of no update to send
Notify(PSTR("\r\nXbox One Poll Failed, error code: "), 0x80);
NotifyFail(rcode);
}
#endif
}
return rcode;
}
void XBOXONE::readReport() {
if(readBuf[0] == 0x07) {
// The XBOX button has a separate message
if(readBuf[4] == 1)
ButtonState |= pgm_read_word(&XBOX_BUTTONS[XBOX]);
else
ButtonState &= ~pgm_read_word(&XBOX_BUTTONS[XBOX]);
if(ButtonState != OldButtonState) {
ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
OldButtonState = ButtonState;
}
}
if(readBuf[0] != 0x20) { // Check if it's the correct report, otherwise return - the controller also sends different status reports
#ifdef EXTRADEBUG
Notify(PSTR("\r\nXbox Poll: "), 0x80);
D_PrintHex<uint8_t > (readBuf[0], 0x80); // 0x03 is a heart beat report!
#endif
return;
}
uint16_t xbox = ButtonState & pgm_read_word(&XBOX_BUTTONS[XBOX]); // Since the XBOX button is separate, save it and add it back in
// xbox button from before, dpad, abxy, start/back, sync, stick click, shoulder buttons
ButtonState = xbox | (((uint16_t)readBuf[5] & 0xF) << 8) | (readBuf[4] & 0xF0) | (((uint16_t)readBuf[4] & 0x0C) << 10) | ((readBuf[4] & 0x01) << 3) | (((uint16_t)readBuf[5] & 0xC0) << 8) | ((readBuf[5] & 0x30) >> 4);
triggerValue[0] = (uint16_t)(((uint16_t)readBuf[7] << 8) | readBuf[6]);
triggerValue[1] = (uint16_t)(((uint16_t)readBuf[9] << 8) | readBuf[8]);
hatValue[LeftHatX] = (int16_t)(((uint16_t)readBuf[11] << 8) | readBuf[10]);
hatValue[LeftHatY] = (int16_t)(((uint16_t)readBuf[13] << 8) | readBuf[12]);
hatValue[RightHatX] = (int16_t)(((uint16_t)readBuf[15] << 8) | readBuf[14]);
hatValue[RightHatY] = (int16_t)(((uint16_t)readBuf[17] << 8) | readBuf[16]);
//Notify(PSTR("\r\nButtonState"), 0x80);
//PrintHex<uint16_t>(ButtonState, 0x80);
if(ButtonState != OldButtonState) {
ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
OldButtonState = ButtonState;
}
// Handle click detection for triggers
if(triggerValue[0] != 0 && triggerValueOld[0] == 0)
L2Clicked = true;
triggerValueOld[0] = triggerValue[0];
if(triggerValue[1] != 0 && triggerValueOld[1] == 0)
R2Clicked = true;
triggerValueOld[1] = triggerValue[1];
}
uint16_t XBOXONE::getButtonPress(ButtonEnum b) {
if(b == L2) // These are analog buttons
return triggerValue[0];
else if(b == R2)
return triggerValue[1];
return (bool)(ButtonState & ((uint16_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b])));
}
bool XBOXONE::getButtonClick(ButtonEnum b) {
if(b == L2) {
if(L2Clicked) {
L2Clicked = false;
return true;
}
return false;
} else if(b == R2) {
if(R2Clicked) {
R2Clicked = false;
return true;
}
return false;
}
uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]);
bool click = (ButtonClickState & button);
ButtonClickState &= ~button; // Clear "click" event
return click;
}
int16_t XBOXONE::getAnalogHat(AnalogHatEnum a) {
return hatValue[a];
}
/* Xbox Controller commands */
uint8_t XBOXONE::XboxCommand(uint8_t* data, uint16_t nbytes) {
data[2] = cmdCounter++; // Increment the output command counter
uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ XBOX_ONE_OUTPUT_PIPE ].epAddr, nbytes, data);
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nXboxCommand, Return: "), 0x80);
D_PrintHex<uint8_t > (rcode, 0x80);
#endif
return rcode;
}
// The Xbox One packets are described at: https://github.com/quantus/xbox-one-controller-protocol
void XBOXONE::onInit() {
// A short buzz to show the controller is active
uint8_t writeBuf[13];
// Activate rumble
writeBuf[0] = 0x09;
writeBuf[1] = 0x00;
// Byte 2 is set in "XboxCommand"
// Single rumble effect
writeBuf[3] = 0x09; // Substructure (what substructure rest of this packet has)
writeBuf[4] = 0x00; // Mode
writeBuf[5] = 0x0F; // Rumble mask (what motors are activated) (0000 lT rT L R)
writeBuf[6] = 0x04; // lT force
writeBuf[7] = 0x04; // rT force
writeBuf[8] = 0x20; // L force
writeBuf[9] = 0x20; // R force
writeBuf[10] = 0x80; // Length of pulse
writeBuf[11] = 0x00; // Off period
writeBuf[12] = 0x00; // Repeat count
XboxCommand(writeBuf, 13);
if(pFuncOnInit)
pFuncOnInit(); // Call the user function
}
void XBOXONE::setRumbleOff() {
uint8_t writeBuf[13];
// Activate rumble
writeBuf[0] = 0x09;
writeBuf[1] = 0x00;
// Byte 2 is set in "XboxCommand"
// Continuous rumble effect
writeBuf[3] = 0x09; // Substructure (what substructure rest of this packet has)
writeBuf[4] = 0x00; // Mode
writeBuf[5] = 0x0F; // Rumble mask (what motors are activated) (0000 lT rT L R)
writeBuf[6] = 0x00; // lT force
writeBuf[7] = 0x00; // rT force
writeBuf[8] = 0x00; // L force
writeBuf[9] = 0x00; // R force
writeBuf[10] = 0x00; // On period
writeBuf[11] = 0x00; // Off period
writeBuf[12] = 0x00; // Repeat count
XboxCommand(writeBuf, 13);
}
void XBOXONE::setRumbleOn(uint8_t leftTrigger, uint8_t rightTrigger, uint8_t leftMotor, uint8_t rightMotor) {
uint8_t writeBuf[13];
// Activate rumble
writeBuf[0] = 0x09;
writeBuf[1] = 0x00;
// Byte 2 is set in "XboxCommand"
// Continuous rumble effect
writeBuf[3] = 0x09; // Substructure (what substructure rest of this packet has)
writeBuf[4] = 0x00; // Mode
writeBuf[5] = 0x0F; // Rumble mask (what motors are activated) (0000 lT rT L R)
writeBuf[6] = leftTrigger; // lT force
writeBuf[7] = rightTrigger; // rT force
writeBuf[8] = leftMotor; // L force
writeBuf[9] = rightMotor; // R force
writeBuf[10] = 0xFF; // On period
writeBuf[11] = 0x00; // Off period
writeBuf[12] = 0xFF; // Repeat count
XboxCommand(writeBuf, 13);
}

View File

@ -0,0 +1,239 @@
/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
Copyright (C) 2015 guruthree
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
guruthree
Web : https://github.com/guruthree/
*/
#ifndef _xboxone_h_
#define _xboxone_h_
#include "Usb.h"
#include "xboxEnums.h"
/* Xbox One data taken from descriptors */
#define XBOX_ONE_EP_MAXPKTSIZE 64 // Max size for data via USB
/* Names we give to the 3 XboxONE pipes */
#define XBOX_ONE_CONTROL_PIPE 0
#define XBOX_ONE_OUTPUT_PIPE 1
#define XBOX_ONE_INPUT_PIPE 2
#define XBOX_ONE_MAX_ENDPOINTS 3
// PID and VID of the different versions of the controller - see: https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c
// Official controllers
#define XBOX_VID1 0x045E // Microsoft Corporation
#define XBOX_ONE_PID1 0x02D1 // Microsoft X-Box One pad
#define XBOX_ONE_PID2 0x02DD // Microsoft X-Box One pad (Firmware 2015)
#define XBOX_ONE_PID3 0x02E3 // Microsoft X-Box One Elite pad
#define XBOX_ONE_PID4 0x02EA // Microsoft X-Box One S pad
// Unofficial controllers
#define XBOX_VID2 0x0738 // Mad Catz
#define XBOX_VID3 0x0E6F // Afterglow
#define XBOX_VID4 0x0F0D // HORIPAD ONE
#define XBOX_VID5 0x1532 // Razer
#define XBOX_VID6 0x24C6 // PowerA
#define XBOX_ONE_PID5 0x4A01 // Mad Catz FightStick TE 2 - might have different mapping for triggers?
#define XBOX_ONE_PID6 0x0139 // Afterglow Prismatic Wired Controller
#define XBOX_ONE_PID7 0x0146 // Rock Candy Wired Controller for Xbox One
#define XBOX_ONE_PID8 0x0067 // HORIPAD ONE
#define XBOX_ONE_PID9 0x0A03 // Razer Wildcat
#define XBOX_ONE_PID10 0x541A // PowerA Xbox One Mini Wired Controller
#define XBOX_ONE_PID11 0x542A // Xbox ONE spectra
#define XBOX_ONE_PID12 0x543A // PowerA Xbox One wired controller
/** This class implements support for a Xbox ONE controller connected via USB. */
class XBOXONE : public USBDeviceConfig, public UsbConfigXtracter {
public:
/**
* Constructor for the XBOXONE class.
* @param pUsb Pointer to USB class instance.
*/
XBOXONE(USB *pUsb);
/** @name USBDeviceConfig implementation */
/**
* Initialize the Xbox Controller.
* @param parent Hub number.
* @param port Port number on the hub.
* @param lowspeed Speed of the device.
* @return 0 on success.
*/
virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
/**
* Release the USB device.
* @return 0 on success.
*/
virtual uint8_t Release();
/**
* Poll the USB Input endpoins and run the state machines.
* @return 0 on success.
*/
virtual 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;
};
/**
* Read the poll interval taken from the endpoint descriptors.
* @return The poll interval in ms.
*/
uint8_t readPollInterval() {
return pollInterval;
};
/**
* 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 == XBOX_VID1 || vid == XBOX_VID2 || vid == XBOX_VID3 || vid == XBOX_VID4 || vid == XBOX_VID5 || vid == XBOX_VID6) &&
(pid == XBOX_ONE_PID1 || pid == XBOX_ONE_PID2 || pid == XBOX_ONE_PID3 || pid == XBOX_ONE_PID4 ||
pid == XBOX_ONE_PID5 || pid == XBOX_ONE_PID6 || pid == XBOX_ONE_PID7 || pid == XBOX_ONE_PID8 ||
pid == XBOX_ONE_PID9 || pid == XBOX_ONE_PID10 || pid == XBOX_ONE_PID11 || pid == XBOX_ONE_PID12));
};
/**@}*/
/** @name Xbox 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 getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a word if reading ::L2 or ::R2.
*/
uint16_t getButtonPress(ButtonEnum b);
bool getButtonClick(ButtonEnum b);
/**
* Return the analog value from the joysticks on the controller.
* @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
* @return Returns a signed 16-bit integer.
*/
int16_t getAnalogHat(AnalogHatEnum a);
/**
* Used to call your own function when the controller is successfully initialized.
* @param funcOnInit Function to call.
*/
void attachOnInit(void (*funcOnInit)(void)) {
pFuncOnInit = funcOnInit;
};
/** Used to set the rumble off. */
void setRumbleOff();
/**
* Used to turn on rumble continuously.
* @param leftTrigger Left trigger force.
* @param rightTrigger Right trigger force.
* @param leftMotor Left motor force.
* @param rightMotor Right motor force.
*/
void setRumbleOn(uint8_t leftTrigger, uint8_t rightTrigger, uint8_t leftMotor, uint8_t rightMotor);
/**@}*/
/** True if a Xbox ONE controller is connected. */
bool XboxOneConnected;
protected:
/** Pointer to USB class instance. */
USB *pUsb;
/** Device address. */
uint8_t bAddress;
/** Endpoint info structure. */
EpInfo epInfo[XBOX_ONE_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;
/** @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);
/**@}*/
/**
* Used to print the USB Endpoint Descriptor.
* @param ep_ptr Pointer to USB Endpoint Descriptor.
*/
void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
private:
/**
* Called when the controller is successfully initialized.
* Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
*/
void onInit();
void (*pFuncOnInit)(void); // Pointer to function called in onInit()
uint8_t pollInterval;
bool bPollEnable;
/* Variables to store the buttons */
uint16_t ButtonState;
uint16_t OldButtonState;
uint16_t ButtonClickState;
int16_t hatValue[4];
uint16_t triggerValue[2];
uint16_t triggerValueOld[2];
bool L2Clicked; // These buttons are analog, so we use we use these bools to check if they where clicked or not
bool R2Clicked;
uint8_t readBuf[XBOX_ONE_EP_MAXPKTSIZE]; // General purpose buffer for input data
uint8_t cmdCounter;
void readReport(); // Used to read the incoming data
/* Private commands */
uint8_t XboxCommand(uint8_t* data, uint16_t nbytes);
};
#endif

View File

@ -0,0 +1,584 @@
/* 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
getBatteryLevel and checkStatus functions made by timstamp.co.uk found using BusHound from Perisoft.net
*/
#include "XBOXRECV.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 Xbox 360 Controller
XBOXRECV::XBOXRECV(USB *p) :
pUsb(p), // pointer to USB class instance - mandatory
bAddress(0), // device address - mandatory
bPollEnable(false) { // don't start polling before dongle is connected
for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) {
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
}
uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
uint8_t buf[constBufSize];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
uint8_t rcode;
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
uint16_t PID, VID;
AddressPool &addrPool = pUsb->GetAddressPool(); // Get memory address of USB device address pool
#ifdef EXTRADEBUG
Notify(PSTR("\r\nXBOXRECV Init"), 0x80);
#endif
if(bAddress) { // Check if address has already been assigned to an instance
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nAddress in use"), 0x80);
#endif
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
}
p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned
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;
}
oldep_ptr = p->epinfo; // Save old pointer to EP_RECORD of address 0
p->epinfo = epInfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
p->lowspeed = lowspeed;
rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
p->epinfo = oldep_ptr; // Restore p->epinfo
if(rcode)
goto FailGetDevDescr;
VID = udd->idVendor;
PID = udd->idProduct;
if((VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_WIRELESS_RECEIVER_PID && PID != XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID)) { // Check if it's a Xbox receiver using the Vendor ID and Product ID
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nYou'll need a wireless receiver for this libary to work"), 0x80);
#endif
goto FailUnknownDevice;
}
bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class
if(!bAddress) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nOut of address space"), 0x80);
#endif
return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
}
epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor
delay(20); // Wait a little before resetting device
return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET;
/* Diagnostic messages */
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr(rcode);
#endif
if(rcode != hrJERR)
rcode = USB_ERROR_FailGetDevDescr;
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\nXbox 360 Init Failed, error code: "), 0x80);
NotifyFail(rcode);
#endif
Release();
return rcode;
};
uint8_t XBOXRECV::Init(uint8_t parent __attribute__((unused)), uint8_t port __attribute__((unused)), bool lowspeed) {
uint8_t rcode;
AddressPool &addrPool = pUsb->GetAddressPool();
#ifdef EXTRADEBUG
Notify(PSTR("\r\nBTD Init"), 0x80);
#endif
UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
if(!p) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nAddress not found"), 0x80);
#endif
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
}
delay(300); // Assign new address to the device
rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device
if(rcode) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nsetAddr: "), 0x80);
D_PrintHex<uint8_t > (rcode, 0x80);
#endif
p->lowspeed = false;
goto Fail;
}
#ifdef EXTRADEBUG
Notify(PSTR("\r\nAddr: "), 0x80);
D_PrintHex<uint8_t > (bAddress, 0x80);
#endif
p->lowspeed = false;
p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
if(!p) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nAddress not found"), 0x80);
#endif
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
}
p->lowspeed = lowspeed;
rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known
if(rcode)
goto FailSetDevTblEntry;
/* The application will work in reduced host mode, so we can save program and data
memory space. After verifying the VID we will use known values for the
configuration values for device, interface, endpoints and HID for the XBOX360 Wireless receiver */
/* Initialize data structures for endpoints of device */
epInfo[ XBOX_INPUT_PIPE_1 ].epAddr = 0x01; // XBOX 360 report endpoint - poll interval 1ms
epInfo[ XBOX_INPUT_PIPE_1 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_INPUT_PIPE_1 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_INPUT_PIPE_1 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_INPUT_PIPE_1 ].bmSndToggle = 0;
epInfo[ XBOX_INPUT_PIPE_1 ].bmRcvToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_1 ].epAddr = 0x01; // XBOX 360 output endpoint - poll interval 8ms
epInfo[ XBOX_OUTPUT_PIPE_1 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_OUTPUT_PIPE_1 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_OUTPUT_PIPE_1 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_OUTPUT_PIPE_1 ].bmSndToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_1 ].bmRcvToggle = 0;
epInfo[ XBOX_INPUT_PIPE_2 ].epAddr = 0x03; // XBOX 360 report endpoint - poll interval 1ms
epInfo[ XBOX_INPUT_PIPE_2 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_INPUT_PIPE_2 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_INPUT_PIPE_2 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_INPUT_PIPE_2 ].bmSndToggle = 0;
epInfo[ XBOX_INPUT_PIPE_2 ].bmRcvToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_2 ].epAddr = 0x03; // XBOX 360 output endpoint - poll interval 8ms
epInfo[ XBOX_OUTPUT_PIPE_2 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_OUTPUT_PIPE_2 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_OUTPUT_PIPE_2 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_OUTPUT_PIPE_2 ].bmSndToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_2 ].bmRcvToggle = 0;
epInfo[ XBOX_INPUT_PIPE_3 ].epAddr = 0x05; // XBOX 360 report endpoint - poll interval 1ms
epInfo[ XBOX_INPUT_PIPE_3 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_INPUT_PIPE_3 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_INPUT_PIPE_3 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_INPUT_PIPE_3 ].bmSndToggle = 0;
epInfo[ XBOX_INPUT_PIPE_3 ].bmRcvToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_3 ].epAddr = 0x05; // XBOX 360 output endpoint - poll interval 8ms
epInfo[ XBOX_OUTPUT_PIPE_3 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_OUTPUT_PIPE_3 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_OUTPUT_PIPE_3 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_OUTPUT_PIPE_3 ].bmSndToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_3 ].bmRcvToggle = 0;
epInfo[ XBOX_INPUT_PIPE_4 ].epAddr = 0x07; // XBOX 360 report endpoint - poll interval 1ms
epInfo[ XBOX_INPUT_PIPE_4 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_INPUT_PIPE_4 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_INPUT_PIPE_4 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_INPUT_PIPE_4 ].bmSndToggle = 0;
epInfo[ XBOX_INPUT_PIPE_4 ].bmRcvToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_4 ].epAddr = 0x07; // XBOX 360 output endpoint - poll interval 8ms
epInfo[ XBOX_OUTPUT_PIPE_4 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_OUTPUT_PIPE_4 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_OUTPUT_PIPE_4 ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_OUTPUT_PIPE_4 ].bmSndToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE_4 ].bmRcvToggle = 0;
rcode = pUsb->setEpInfoEntry(bAddress, 9, epInfo);
if(rcode)
goto FailSetDevTblEntry;
delay(200); //Give time for address change
rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1);
if(rcode)
goto FailSetConfDescr;
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nXbox Wireless Receiver Connected\r\n"), 0x80);
#endif
XboxReceiverConnected = true;
bPollEnable = true;
checkStatusTimer = 0; // Reset timer
return 0; // Successful configuration
/* Diagnostic messages */
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry();
goto Fail;
#endif
FailSetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailSetConfDescr();
#endif
Fail:
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80);
NotifyFail(rcode);
#endif
Release();
return rcode;
}
/* Performs a cleanup after failed Init() attempt */
uint8_t XBOXRECV::Release() {
XboxReceiverConnected = false;
for(uint8_t i = 0; i < 4; i++)
Xbox360Connected[i] = 0x00;
pUsb->GetAddressPool().FreeAddress(bAddress);
bAddress = 0;
bPollEnable = false;
return 0;
}
uint8_t XBOXRECV::Poll() {
if(!bPollEnable)
return 0;
if(!checkStatusTimer || ((int32_t)((uint32_t)millis() - checkStatusTimer) > 3000)) { // Run checkStatus every 3 seconds
checkStatusTimer = (uint32_t)millis();
checkStatus();
}
uint8_t inputPipe;
uint16_t bufferSize;
for(uint8_t i = 0; i < 4; i++) {
if(i == 0)
inputPipe = XBOX_INPUT_PIPE_1;
else if(i == 1)
inputPipe = XBOX_INPUT_PIPE_2;
else if(i == 2)
inputPipe = XBOX_INPUT_PIPE_3;
else
inputPipe = XBOX_INPUT_PIPE_4;
bufferSize = EP_MAXPKTSIZE; // This is the maximum number of bytes we want to receive
pUsb->inTransfer(bAddress, epInfo[ inputPipe ].epAddr, &bufferSize, readBuf);
if(bufferSize > 0) { // The number of received bytes
#ifdef EXTRADEBUG
Notify(PSTR("Bytes Received: "), 0x80);
D_PrintHex<uint16_t > (bufferSize, 0x80);
Notify(PSTR("\r\n"), 0x80);
#endif
readReport(i);
#ifdef PRINTREPORT
printReport(i, bufferSize); // Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
#endif
}
}
return 0;
}
void XBOXRECV::readReport(uint8_t controller) {
if(readBuf == NULL)
return;
// This report is send when a controller is connected and disconnected
if(readBuf[0] == 0x08 && readBuf[1] != Xbox360Connected[controller]) {
Xbox360Connected[controller] = readBuf[1];
#ifdef DEBUG_USB_HOST
Notify(PSTR("Controller "), 0x80);
Notify(controller, 0x80);
#endif
if(Xbox360Connected[controller]) {
#ifdef DEBUG_USB_HOST
const char* str = 0;
switch(readBuf[1]) {
case 0x80: str = PSTR(" as controller\r\n");
break;
case 0x40: str = PSTR(" as headset\r\n");
break;
case 0xC0: str = PSTR(" as controller+headset\r\n");
break;
}
Notify(PSTR(": connected"), 0x80);
Notify(str, 0x80);
#endif
onInit(controller);
}
#ifdef DEBUG_USB_HOST
else
Notify(PSTR(": disconnected\r\n"), 0x80);
#endif
return;
}
// Controller status report
if(readBuf[1] == 0x00 && readBuf[3] & 0x13 && readBuf[4] >= 0x22) {
controllerStatus[controller] = ((uint16_t)readBuf[3] << 8) | readBuf[4];
return;
}
if(readBuf[1] != 0x01) // Check if it's the correct report - the receiver also sends different status reports
return;
// A controller must be connected if it's sending data
if(!Xbox360Connected[controller])
Xbox360Connected[controller] |= 0x80;
ButtonState[controller] = (uint32_t)(readBuf[9] | ((uint16_t)readBuf[8] << 8) | ((uint32_t)readBuf[7] << 16) | ((uint32_t)readBuf[6] << 24));
hatValue[controller][LeftHatX] = (int16_t)(((uint16_t)readBuf[11] << 8) | readBuf[10]);
hatValue[controller][LeftHatY] = (int16_t)(((uint16_t)readBuf[13] << 8) | readBuf[12]);
hatValue[controller][RightHatX] = (int16_t)(((uint16_t)readBuf[15] << 8) | readBuf[14]);
hatValue[controller][RightHatY] = (int16_t)(((uint16_t)readBuf[17] << 8) | readBuf[16]);
//Notify(PSTR("\r\nButtonState: "), 0x80);
//PrintHex<uint32_t>(ButtonState[controller], 0x80);
if(ButtonState[controller] != OldButtonState[controller]) {
buttonStateChanged[controller] = true;
ButtonClickState[controller] = (ButtonState[controller] >> 16) & ((~OldButtonState[controller]) >> 16); // Update click state variable, but don't include the two trigger buttons L2 and R2
if(((uint8_t)OldButtonState[controller]) == 0 && ((uint8_t)ButtonState[controller]) != 0) // The L2 and R2 buttons are special as they are analog buttons
R2Clicked[controller] = true;
if((uint8_t)(OldButtonState[controller] >> 8) == 0 && (uint8_t)(ButtonState[controller] >> 8) != 0)
L2Clicked[controller] = true;
OldButtonState[controller] = ButtonState[controller];
}
}
void XBOXRECV::printReport(uint8_t controller __attribute__((unused)), uint8_t nBytes __attribute__((unused))) { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
#ifdef PRINTREPORT
if(readBuf == NULL)
return;
Notify(PSTR("Controller "), 0x80);
Notify(controller, 0x80);
Notify(PSTR(": "), 0x80);
for(uint8_t i = 0; i < nBytes; i++) {
D_PrintHex<uint8_t > (readBuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
Notify(PSTR("\r\n"), 0x80);
#endif
}
uint8_t XBOXRECV::getButtonPress(ButtonEnum b, uint8_t controller) {
if(b == L2) // These are analog buttons
return (uint8_t)(ButtonState[controller] >> 8);
else if(b == R2)
return (uint8_t)ButtonState[controller];
return (bool)(ButtonState[controller] & ((uint32_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]) << 16));
}
bool XBOXRECV::getButtonClick(ButtonEnum b, uint8_t controller) {
if(b == L2) {
if(L2Clicked[controller]) {
L2Clicked[controller] = false;
return true;
}
return false;
} else if(b == R2) {
if(R2Clicked[controller]) {
R2Clicked[controller] = false;
return true;
}
return false;
}
uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]);
bool click = (ButtonClickState[controller] & button);
ButtonClickState[controller] &= ~button; // clear "click" event
return click;
}
int16_t XBOXRECV::getAnalogHat(AnalogHatEnum a, uint8_t controller) {
return hatValue[controller][a];
}
bool XBOXRECV::buttonChanged(uint8_t controller) {
bool state = buttonStateChanged[controller];
buttonStateChanged[controller] = false;
return state;
}
/*
ControllerStatus Breakdown
ControllerStatus[controller] & 0x0001 // 0
ControllerStatus[controller] & 0x0002 // normal batteries, no rechargeable battery pack
ControllerStatus[controller] & 0x0004 // controller starting up / settling
ControllerStatus[controller] & 0x0008 // headset adapter plugged in, but no headphones connected (mute?)
ControllerStatus[controller] & 0x0010 // 0
ControllerStatus[controller] & 0x0020 // 1
ControllerStatus[controller] & 0x0040 // battery level (high bit)
ControllerStatus[controller] & 0x0080 // battery level (low bit)
ControllerStatus[controller] & 0x0100 // 1
ControllerStatus[controller] & 0x0200 // 1
ControllerStatus[controller] & 0x0400 // headset adapter plugged in
ControllerStatus[controller] & 0x0800 // 0
ControllerStatus[controller] & 0x1000 // 1
ControllerStatus[controller] & 0x2000 // 0
ControllerStatus[controller] & 0x4000 // 0
ControllerStatus[controller] & 0x8000 // 0
*/
uint8_t XBOXRECV::getBatteryLevel(uint8_t controller) {
return ((controllerStatus[controller] & 0x00C0) >> 6);
}
void XBOXRECV::XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes) {
#ifdef EXTRADEBUG
uint8_t rcode;
#endif
uint8_t outputPipe;
switch(controller) {
case 0: outputPipe = XBOX_OUTPUT_PIPE_1;
break;
case 1: outputPipe = XBOX_OUTPUT_PIPE_2;
break;
case 2: outputPipe = XBOX_OUTPUT_PIPE_3;
break;
case 3: outputPipe = XBOX_OUTPUT_PIPE_4;
break;
default:
return;
}
#ifdef EXTRADEBUG
rcode =
#endif
pUsb->outTransfer(bAddress, epInfo[ outputPipe ].epAddr, nbytes, data);
#ifdef EXTRADEBUG
if(rcode)
Notify(PSTR("Error sending Xbox message\r\n"), 0x80);
#endif
}
void XBOXRECV::disconnect(uint8_t controller) {
writeBuf[0] = 0x00;
writeBuf[1] = 0x00;
writeBuf[2] = 0x08;
writeBuf[3] = 0xC0;
XboxCommand(controller, writeBuf, 4);
}
void XBOXRECV::setLedRaw(uint8_t value, uint8_t controller) {
writeBuf[0] = 0x00;
writeBuf[1] = 0x00;
writeBuf[2] = 0x08;
writeBuf[3] = value | 0x40;
XboxCommand(controller, writeBuf, 4);
}
void XBOXRECV::setLedOn(LEDEnum led, uint8_t controller) {
if(led == OFF)
setLedRaw(0, controller);
else if(led != ALL) // All LEDs can't be on a the same time
setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4, controller);
}
void XBOXRECV::setLedBlink(LEDEnum led, uint8_t controller) {
setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]), controller);
}
void XBOXRECV::setLedMode(LEDModeEnum ledMode, uint8_t controller) { // This function is used to do some speciel LED stuff the controller supports
setLedRaw((uint8_t)ledMode, controller);
}
/* PC runs this at interval of approx 2 seconds
Thanks to BusHound from Perisoft.net for the Windows USB Analysis output
Found by timstamp.co.uk
*/
void XBOXRECV::checkStatus() {
if(!bPollEnable)
return;
// Get controller info
writeBuf[0] = 0x08;
writeBuf[1] = 0x00;
writeBuf[2] = 0x0f;
writeBuf[3] = 0xc0;
for(uint8_t i = 0; i < 4; i++) {
XboxCommand(i, writeBuf, 4);
}
// Get battery status
writeBuf[0] = 0x00;
writeBuf[1] = 0x00;
writeBuf[2] = 0x00;
writeBuf[3] = 0x40;
for(uint8_t i = 0; i < 4; i++) {
if(Xbox360Connected[i])
XboxCommand(i, writeBuf, 4);
}
}
void XBOXRECV::setRumbleOn(uint8_t lValue, uint8_t rValue, uint8_t controller) {
writeBuf[0] = 0x00;
writeBuf[1] = 0x01;
writeBuf[2] = 0x0f;
writeBuf[3] = 0xc0;
writeBuf[4] = 0x00;
writeBuf[5] = lValue; // big weight
writeBuf[6] = rValue; // small weight
XboxCommand(controller, writeBuf, 7);
}
void XBOXRECV::onInit(uint8_t controller) {
if(pFuncOnInit)
pFuncOnInit(); // Call the user function
else {
LEDEnum led;
if(controller == 0)
led = static_cast<LEDEnum>(LED1);
else if(controller == 1)
led = static_cast<LEDEnum>(LED2);
else if(controller == 2)
led = static_cast<LEDEnum>(LED3);
else
led = static_cast<LEDEnum>(LED4);
setLedOn(led, controller);
}
}

View File

@ -0,0 +1,276 @@
/* 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
getBatteryLevel and checkStatus functions made by timstamp.co.uk found using BusHound from Perisoft.net
*/
#ifndef _xboxrecv_h_
#define _xboxrecv_h_
#include "Usb.h"
#include "xboxEnums.h"
/* Data Xbox 360 taken from descriptors */
#define EP_MAXPKTSIZE 32 // max size for data via USB
/* Names we give to the 9 Xbox360 pipes */
#define XBOX_CONTROL_PIPE 0
#define XBOX_INPUT_PIPE_1 1
#define XBOX_OUTPUT_PIPE_1 2
#define XBOX_INPUT_PIPE_2 3
#define XBOX_OUTPUT_PIPE_2 4
#define XBOX_INPUT_PIPE_3 5
#define XBOX_OUTPUT_PIPE_3 6
#define XBOX_INPUT_PIPE_4 7
#define XBOX_OUTPUT_PIPE_4 8
// PID and VID of the different devices
#define XBOX_VID 0x045E // Microsoft Corporation
#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz receivers
#define JOYTECH_VID 0x162E // For unofficial Joytech controllers
#define XBOX_WIRELESS_RECEIVER_PID 0x0719 // Microsoft Wireless Gaming Receiver
#define XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID 0x0291 // Third party Wireless Gaming Receiver
#define XBOX_MAX_ENDPOINTS 9
/**
* This class implements support for a Xbox Wireless receiver.
*
* Up to four controllers can connect to one receiver, if more is needed one can use a second receiver via the USBHub class.
*/
class XBOXRECV : public USBDeviceConfig {
public:
/**
* Constructor for the XBOXRECV class.
* @param pUsb Pointer to USB class instance.
*/
XBOXRECV(USB *pUsb);
/** @name USBDeviceConfig implementation */
/**
* Address assignment and basic initilization 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 Xbox wireless receiver.
* @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 == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID) && (pid == XBOX_WIRELESS_RECEIVER_PID || pid == XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID));
};
/**@}*/
/** @name Xbox Controller functions */
/**
* getButtonPress(uint8_t controller, ButtonEnum b) will return true as long as the button is held down.
*
* While getButtonClick(uint8_t controller, ButtonEnum b) will only return it once.
*
* So you instance if you need to increase a variable once you would use getButtonClick(uint8_t controller, ButtonEnum b),
* but if you need to drive a robot forward you would use getButtonPress(uint8_t controller, ButtonEnum b).
* @param b ::ButtonEnum to read.
* @param controller The controller to read from. Default to 0.
* @return getButtonClick(uint8_t controller, ButtonEnum b) will return a bool, while getButtonPress(uint8_t controller, ButtonEnum b) will return a byte if reading ::L2 or ::R2.
*/
uint8_t getButtonPress(ButtonEnum b, uint8_t controller = 0);
bool getButtonClick(ButtonEnum b, uint8_t controller = 0);
/**@}*/
/** @name Xbox Controller functions */
/**
* Return the analog value from the joysticks on the controller.
* @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
* @param controller The controller to read from. Default to 0.
* @return Returns a signed 16-bit integer.
*/
int16_t getAnalogHat(AnalogHatEnum a, uint8_t controller = 0);
/**
* Used to disconnect any of the controllers.
* @param controller The controller to disconnect. Default to 0.
*/
void disconnect(uint8_t controller = 0);
/**
* Turn rumble off and all the LEDs on the specific controller.
* @param controller The controller to write to. Default to 0.
*/
void setAllOff(uint8_t controller = 0) {
setRumbleOn(0, 0, controller);
setLedOff(controller);
};
/**
* Turn rumble off the specific controller.
* @param controller The controller to write to. Default to 0.
*/
void setRumbleOff(uint8_t controller = 0) {
setRumbleOn(0, 0, controller);
};
/**
* Turn rumble on.
* @param lValue Left motor (big weight) inside the controller.
* @param rValue Right motor (small weight) inside the controller.
* @param controller The controller to write to. Default to 0.
*/
void setRumbleOn(uint8_t lValue, uint8_t rValue, uint8_t controller = 0);
/**
* Set LED value. Without using the ::LEDEnum or ::LEDModeEnum.
* @param value See:
* setLedOff(uint8_t controller), setLedOn(uint8_t controller, LED l),
* setLedBlink(uint8_t controller, LED l), and setLedMode(uint8_t controller, LEDMode lm).
* @param controller The controller to write to. Default to 0.
*/
void setLedRaw(uint8_t value, uint8_t controller = 0);
/**
* Turn all LEDs off the specific controller.
* @param controller The controller to write to. Default to 0.
*/
void setLedOff(uint8_t controller = 0) {
setLedRaw(0, controller);
};
/**
* Turn on a LED by using ::LEDEnum.
* @param l ::OFF, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
* @param controller The controller to write to. Default to 0.
*/
void setLedOn(LEDEnum l, uint8_t controller = 0);
/**
* Turn on a LED by using ::LEDEnum.
* @param l ::ALL, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
* @param controller The controller to write to. Default to 0.
*/
void setLedBlink(LEDEnum l, uint8_t controller = 0);
/**
* Used to set special LED modes supported by the Xbox controller.
* @param lm See ::LEDModeEnum.
* @param controller The controller to write to. Default to 0.
*/
void setLedMode(LEDModeEnum lm, uint8_t controller = 0);
/**
* Used to get the battery level from the controller.
* @param controller The controller to read from. Default to 0.
* @return Returns the battery level as an integer in the range of 0-3.
*/
uint8_t getBatteryLevel(uint8_t controller = 0);
/**
* Used to check if a button has changed.
* @param controller The controller to read from. Default to 0.
* @return True if a button has changed.
*/
bool buttonChanged(uint8_t controller = 0);
/**
* Used to call your own function when the controller is successfully initialized.
* @param funcOnInit Function to call.
*/
void attachOnInit(void (*funcOnInit)(void)) {
pFuncOnInit = funcOnInit;
};
/**@}*/
/** True if a wireless receiver is connected. */
bool XboxReceiverConnected;
/** Variable used to indicate if the XBOX 360 controller is successfully connected. */
uint8_t Xbox360Connected[4];
protected:
/** Pointer to USB class instance. */
USB *pUsb;
/** Device address. */
uint8_t bAddress;
/** Endpoint info structure. */
EpInfo epInfo[XBOX_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.
* @param controller The initialized controller.
*/
void onInit(uint8_t controller);
void (*pFuncOnInit)(void); // Pointer to function called in onInit()
bool bPollEnable;
/* Variables to store the buttons */
uint32_t ButtonState[4];
uint32_t OldButtonState[4];
uint16_t ButtonClickState[4];
int16_t hatValue[4][4];
uint16_t controllerStatus[4];
bool buttonStateChanged[4]; // True if a button has changed
bool L2Clicked[4]; // These buttons are analog, so we use we use these bools to check if they where clicked or not
bool R2Clicked[4];
uint32_t checkStatusTimer; // Timing for checkStatus() signals
uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
uint8_t writeBuf[7]; // General purpose buffer for output data
void readReport(uint8_t controller); // read incoming data
void printReport(uint8_t controller, uint8_t nBytes); // print incoming date - Uncomment for debugging
/* Private commands */
void XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes);
void checkStatus();
};
#endif

View File

@ -0,0 +1,362 @@
/* 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 "XBOXUSB.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 Xbox 360 Controller
XBOXUSB::XBOXUSB(USB *p) :
pUsb(p), // pointer to USB class instance - mandatory
bAddress(0), // device address - mandatory
bPollEnable(false) { // don't start polling before dongle is connected
for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) {
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
}
uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) {
uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<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\nXBOXUSB 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 != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID && VID != GAMESTOP_VID) // Check VID
goto FailUnknownDevice;
if(PID == XBOX_WIRELESS_PID) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nYou have plugged in a wireless Xbox 360 controller - it doesn't support USB communication"), 0x80);
#endif
goto FailUnknownDevice;
} else if(PID == XBOX_WIRELESS_RECEIVER_PID || PID == XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID) {
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nThis library only supports Xbox 360 controllers via USB"), 0x80);
#endif
goto FailUnknownDevice;
} else if(PID != XBOX_WIRED_PID && PID != MADCATZ_WIRED_PID && PID != GAMESTOP_WIRED_PID && PID != AFTERGLOW_WIRED_PID && PID != JOYTECH_WIRED_PID) // Check 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 VID we will use known values for the
configuration values for device, interface, endpoints and HID for the XBOX360 Controllers */
/* Initialize data structures for endpoints of device */
epInfo[ XBOX_INPUT_PIPE ].epAddr = 0x01; // XBOX 360 report endpoint
epInfo[ XBOX_INPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = 0;
epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = 0;
epInfo[ XBOX_OUTPUT_PIPE ].epAddr = 0x02; // XBOX 360 output endpoint
epInfo[ XBOX_OUTPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
epInfo[ XBOX_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
epInfo[ XBOX_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = 0;
epInfo[ XBOX_OUTPUT_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[ XBOX_CONTROL_PIPE ].epAddr, 1);
if(rcode)
goto FailSetConfDescr;
#ifdef DEBUG_USB_HOST
Notify(PSTR("\r\nXbox 360 Controller Connected\r\n"), 0x80);
#endif
onInit();
Xbox360Connected = true;
bPollEnable = true;
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\nXbox 360 Init Failed, error code: "), 0x80);
NotifyFail(rcode);
#endif
Release();
return rcode;
}
/* Performs a cleanup after failed Init() attempt */
uint8_t XBOXUSB::Release() {
Xbox360Connected = false;
pUsb->GetAddressPool().FreeAddress(bAddress);
bAddress = 0;
bPollEnable = false;
return 0;
}
uint8_t XBOXUSB::Poll() {
if(!bPollEnable)
return 0;
uint16_t BUFFER_SIZE = EP_MAXPKTSIZE;
pUsb->inTransfer(bAddress, epInfo[ XBOX_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1
readReport();
#ifdef PRINTREPORT
printReport(); // Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
#endif
return 0;
}
void XBOXUSB::readReport() {
if(readBuf == NULL)
return;
if(readBuf[0] != 0x00 || readBuf[1] != 0x14) { // Check if it's the correct report - the controller also sends different status reports
return;
}
ButtonState = (uint32_t)(readBuf[5] | ((uint16_t)readBuf[4] << 8) | ((uint32_t)readBuf[3] << 16) | ((uint32_t)readBuf[2] << 24));
hatValue[LeftHatX] = (int16_t)(((uint16_t)readBuf[7] << 8) | readBuf[6]);
hatValue[LeftHatY] = (int16_t)(((uint16_t)readBuf[9] << 8) | readBuf[8]);
hatValue[RightHatX] = (int16_t)(((uint16_t)readBuf[11] << 8) | readBuf[10]);
hatValue[RightHatY] = (int16_t)(((uint16_t)readBuf[13] << 8) | readBuf[12]);
//Notify(PSTR("\r\nButtonState"), 0x80);
//PrintHex<uint32_t>(ButtonState, 0x80);
if(ButtonState != OldButtonState) {
ButtonClickState = (ButtonState >> 16) & ((~OldButtonState) >> 16); // Update click state variable, but don't include the two trigger buttons L2 and R2
if(((uint8_t)OldButtonState) == 0 && ((uint8_t)ButtonState) != 0) // The L2 and R2 buttons are special as they are analog buttons
R2Clicked = true;
if((uint8_t)(OldButtonState >> 8) == 0 && (uint8_t)(ButtonState >> 8) != 0)
L2Clicked = true;
OldButtonState = ButtonState;
}
}
void XBOXUSB::printReport() { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
#ifdef PRINTREPORT
if(readBuf == NULL)
return;
for(uint8_t i = 0; i < XBOX_REPORT_BUFFER_SIZE; i++) {
D_PrintHex<uint8_t > (readBuf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
Notify(PSTR("\r\n"), 0x80);
#endif
}
uint8_t XBOXUSB::getButtonPress(ButtonEnum b) {
if(b == L2) // These are analog buttons
return (uint8_t)(ButtonState >> 8);
else if(b == R2)
return (uint8_t)ButtonState;
return (bool)(ButtonState & ((uint32_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]) << 16));
}
bool XBOXUSB::getButtonClick(ButtonEnum b) {
if(b == L2) {
if(L2Clicked) {
L2Clicked = false;
return true;
}
return false;
} else if(b == R2) {
if(R2Clicked) {
R2Clicked = false;
return true;
}
return false;
}
uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]);
bool click = (ButtonClickState & button);
ButtonClickState &= ~button; // clear "click" event
return click;
}
int16_t XBOXUSB::getAnalogHat(AnalogHatEnum a) {
return hatValue[a];
}
/* Xbox Controller commands */
void XBOXUSB::XboxCommand(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[XBOX_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x00, 0x02, 0x00, nbytes, nbytes, data, NULL);
}
void XBOXUSB::setLedRaw(uint8_t value) {
writeBuf[0] = 0x01;
writeBuf[1] = 0x03;
writeBuf[2] = value;
XboxCommand(writeBuf, 3);
}
void XBOXUSB::setLedOn(LEDEnum led) {
if(led == OFF)
setLedRaw(0);
else if(led != ALL) // All LEDs can't be on a the same time
setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4);
}
void XBOXUSB::setLedBlink(LEDEnum led) {
setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]));
}
void XBOXUSB::setLedMode(LEDModeEnum ledMode) { // This function is used to do some special LED stuff the controller supports
setLedRaw((uint8_t)ledMode);
}
void XBOXUSB::setRumbleOn(uint8_t lValue, uint8_t rValue) {
writeBuf[0] = 0x00;
writeBuf[1] = 0x08;
writeBuf[2] = 0x00;
writeBuf[3] = lValue; // big weight
writeBuf[4] = rValue; // small weight
writeBuf[5] = 0x00;
writeBuf[6] = 0x00;
writeBuf[7] = 0x00;
XboxCommand(writeBuf, 8);
}
void XBOXUSB::onInit() {
if(pFuncOnInit)
pFuncOnInit(); // Call the user function
else
setLedOn(static_cast<LEDEnum>(LED1));
}

View File

@ -0,0 +1,225 @@
/* 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 _xboxusb_h_
#define _xboxusb_h_
#include "Usb.h"
#include "usbhid.h"
#include "xboxEnums.h"
/* Data Xbox 360 taken from descriptors */
#define EP_MAXPKTSIZE 32 // max size for data via USB
/* Names we give to the 3 Xbox360 pipes */
#define XBOX_CONTROL_PIPE 0
#define XBOX_INPUT_PIPE 1
#define XBOX_OUTPUT_PIPE 2
// PID and VID of the different devices
#define XBOX_VID 0x045E // Microsoft Corporation
#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz controllers
#define JOYTECH_VID 0x162E // For unofficial Joytech controllers
#define GAMESTOP_VID 0x0E6F // Gamestop controller
#define XBOX_WIRED_PID 0x028E // Microsoft 360 Wired controller
#define XBOX_WIRELESS_PID 0x028F // Wireless controller only support charging
#define XBOX_WIRELESS_RECEIVER_PID 0x0719 // Microsoft Wireless Gaming Receiver
#define XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID 0x0291 // Third party Wireless Gaming Receiver
#define MADCATZ_WIRED_PID 0xF016 // Mad Catz wired controller
#define JOYTECH_WIRED_PID 0xBEEF // For Joytech wired controller
#define GAMESTOP_WIRED_PID 0x0401 // Gamestop wired controller
#define AFTERGLOW_WIRED_PID 0x0213 // Afterglow wired controller - it uses the same VID as a Gamestop controller
#define XBOX_REPORT_BUFFER_SIZE 14 // Size of the input report buffer
#define XBOX_MAX_ENDPOINTS 3
/** This class implements support for a Xbox wired controller via USB. */
class XBOXUSB : public USBDeviceConfig {
public:
/**
* Constructor for the XBOXUSB class.
* @param pUsb Pointer to USB class instance.
*/
XBOXUSB(USB *pUsb);
/** @name USBDeviceConfig implementation */
/**
* Initialize the Xbox 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 == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID || vid == GAMESTOP_VID) && (pid == XBOX_WIRED_PID || pid == MADCATZ_WIRED_PID || pid == GAMESTOP_WIRED_PID || pid == AFTERGLOW_WIRED_PID || pid == JOYTECH_WIRED_PID));
};
/**@}*/
/** @name Xbox 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 getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a byte if reading ::L2 or ::R2.
*/
uint8_t getButtonPress(ButtonEnum b);
bool getButtonClick(ButtonEnum b);
/**@}*/
/** @name Xbox Controller functions */
/**
* Return the analog value from the joysticks on the controller.
* @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
* @return Returns a signed 16-bit integer.
*/
int16_t getAnalogHat(AnalogHatEnum a);
/** Turn rumble off and all the LEDs on the controller. */
void setAllOff() {
setRumbleOn(0, 0);
setLedRaw(0);
};
/** Turn rumble off the controller. */
void setRumbleOff() {
setRumbleOn(0, 0);
};
/**
* Turn rumble on.
* @param lValue Left motor (big weight) inside the controller.
* @param rValue Right motor (small weight) inside the controller.
*/
void setRumbleOn(uint8_t lValue, uint8_t rValue);
/**
* Set LED value. Without using the ::LEDEnum or ::LEDModeEnum.
* @param value See:
* setLedOff(), setLedOn(LEDEnum l),
* setLedBlink(LEDEnum l), and setLedMode(LEDModeEnum lm).
*/
void setLedRaw(uint8_t value);
/** Turn all LEDs off the controller. */
void setLedOff() {
setLedRaw(0);
};
/**
* Turn on a LED by using ::LEDEnum.
* @param l ::OFF, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
*/
void setLedOn(LEDEnum l);
/**
* Turn on a LED by using ::LEDEnum.
* @param l ::ALL, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
*/
void setLedBlink(LEDEnum l);
/**
* Used to set special LED modes supported by the Xbox controller.
* @param lm See ::LEDModeEnum.
*/
void setLedMode(LEDModeEnum lm);
/**
* Used to call your own function when the controller is successfully initialized.
* @param funcOnInit Function to call.
*/
void attachOnInit(void (*funcOnInit)(void)) {
pFuncOnInit = funcOnInit;
};
/**@}*/
/** True if a Xbox 360 controller is connected. */
bool Xbox360Connected;
protected:
/** Pointer to USB class instance. */
USB *pUsb;
/** Device address. */
uint8_t bAddress;
/** Endpoint info structure. */
EpInfo epInfo[XBOX_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;
/* Variables to store the buttons */
uint32_t ButtonState;
uint32_t OldButtonState;
uint16_t ButtonClickState;
int16_t hatValue[4];
uint16_t controllerStatus;
bool L2Clicked; // These buttons are analog, so we use we use these bools to check if they where clicked or not
bool R2Clicked;
uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
uint8_t writeBuf[8]; // General purpose buffer for output data
void readReport(); // read incoming data
void printReport(); // print incoming date - Uncomment for debugging
/* Private commands */
void XboxCommand(uint8_t* data, uint16_t nbytes);
};
#endif

View File

@ -0,0 +1,283 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#if !defined(_usb_h_) || defined(__ADDRESS_H__)
#error "Never include address.h directly; include Usb.h instead"
#else
#define __ADDRESS_H__
/* NAK powers. To save space in endpoint data structure, amount of retries before giving up and returning 0x4 is stored in */
/* bmNakPower as a power of 2. The actual nak_limit is then calculated as nak_limit = ( 2^bmNakPower - 1) */
#define USB_NAK_MAX_POWER 15 //NAK binary order maximum value
#define USB_NAK_DEFAULT 14 //default 32K-1 NAKs before giving up
#define USB_NAK_NOWAIT 1 //Single NAK stops transfer
#define USB_NAK_NONAK 0 //Do not count NAKs, stop retrying after USB Timeout
struct EpInfo {
uint8_t epAddr; // Endpoint address
uint8_t maxPktSize; // Maximum packet size
union {
uint8_t epAttribs;
struct {
uint8_t bmSndToggle : 1; // Send toggle, when zero bmSNDTOG0, bmSNDTOG1 otherwise
uint8_t bmRcvToggle : 1; // Send toggle, when zero bmRCVTOG0, bmRCVTOG1 otherwise
uint8_t bmNakPower : 6; // Binary order for NAK_LIMIT value
} __attribute__((packed));
};
} __attribute__((packed));
// 7 6 5 4 3 2 1 0
// ---------------------------------
// | | H | P | P | P | A | A | A |
// ---------------------------------
//
// H - if 1 the address is a hub address
// P - parent hub address
// A - device address / port number in case of hub
//
struct UsbDeviceAddress {
union {
struct {
uint8_t bmAddress : 3; // device address/port number
uint8_t bmParent : 3; // parent hub address
uint8_t bmHub : 1; // hub flag
uint8_t bmReserved : 1; // reserved, must be zero
} __attribute__((packed));
uint8_t devAddress;
};
} __attribute__((packed));
#define bmUSB_DEV_ADDR_ADDRESS 0x07
#define bmUSB_DEV_ADDR_PARENT 0x38
#define bmUSB_DEV_ADDR_HUB 0x40
struct UsbDevice {
EpInfo *epinfo; // endpoint info pointer
UsbDeviceAddress address;
uint8_t epcount; // number of endpoints
bool lowspeed; // indicates if a device is the low speed one
// uint8_t devclass; // device class
} __attribute__((packed));
class AddressPool {
public:
virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) = 0;
virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) = 0;
virtual void FreeAddress(uint8_t addr) = 0;
};
typedef void (*UsbDeviceHandleFunc)(UsbDevice *pdev);
#define ADDR_ERROR_INVALID_INDEX 0xFF
#define ADDR_ERROR_INVALID_ADDRESS 0xFF
template <const uint8_t MAX_DEVICES_ALLOWED>
class AddressPoolImpl : public AddressPool {
EpInfo dev0ep; //Endpoint data structure used during enumeration for uninitialized device
uint8_t hubCounter; // hub counter is kept
// in order to avoid hub address duplication
UsbDevice thePool[MAX_DEVICES_ALLOWED];
// Initializes address pool entry
void InitEntry(uint8_t index) {
thePool[index].address.devAddress = 0;
thePool[index].epcount = 1;
thePool[index].lowspeed = 0;
thePool[index].epinfo = &dev0ep;
};
// Returns thePool index for a given address
uint8_t FindAddressIndex(uint8_t address = 0) {
for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) {
if(thePool[i].address.devAddress == address)
return i;
}
return 0;
};
// Returns thePool child index for a given parent
uint8_t FindChildIndex(UsbDeviceAddress addr, uint8_t start = 1) {
for(uint8_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) {
if(thePool[i].address.bmParent == addr.bmAddress)
return i;
}
return 0;
};
// Frees address entry specified by index parameter
void FreeAddressByIndex(uint8_t index) {
// Zero field is reserved and should not be affected
if(index == 0)
return;
UsbDeviceAddress uda = thePool[index].address;
// If a hub was switched off all port addresses should be freed
if(uda.bmHub == 1) {
for(uint8_t i = 1; (i = FindChildIndex(uda, i));)
FreeAddressByIndex(i);
// If the hub had the last allocated address, hubCounter should be decremented
if(hubCounter == uda.bmAddress)
hubCounter--;
}
InitEntry(index);
}
// Initializes the whole address pool at once
void InitAllAddresses() {
for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++)
InitEntry(i);
hubCounter = 0;
};
public:
AddressPoolImpl() : hubCounter(0) {
// Zero address is reserved
InitEntry(0);
thePool[0].address.devAddress = 0;
thePool[0].epinfo = &dev0ep;
dev0ep.epAddr = 0;
dev0ep.maxPktSize = 8;
dev0ep.bmSndToggle = 0; // Set DATA0/1 toggles to 0
dev0ep.bmRcvToggle = 0;
dev0ep.bmNakPower = USB_NAK_MAX_POWER;
InitAllAddresses();
};
// Returns a pointer to a specified address entry
virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) {
if(!addr)
return thePool;
uint8_t index = FindAddressIndex(addr);
return (!index) ? NULL : thePool + index;
};
// Performs an operation specified by pfunc for each addressed device
void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) {
if(!pfunc)
return;
for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++)
if(thePool[i].address.devAddress)
pfunc(thePool + i);
};
// Allocates new address
virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) {
/* if (parent != 0 && port == 0)
USB_HOST_SERIAL.println("PRT:0"); */
UsbDeviceAddress _parent;
_parent.devAddress = parent;
if(_parent.bmReserved || port > 7)
//if(parent > 127 || port > 7)
return 0;
if(is_hub && hubCounter == 7)
return 0;
// finds first empty address entry starting from one
uint8_t index = FindAddressIndex(0);
if(!index) // if empty entry is not found
return 0;
if(_parent.devAddress == 0) {
if(is_hub) {
thePool[index].address.devAddress = 0x41;
hubCounter++;
} else
thePool[index].address.devAddress = 1;
return thePool[index].address.devAddress;
}
UsbDeviceAddress addr;
addr.devAddress = 0; // Ensure all bits are zero
addr.bmParent = _parent.bmAddress;
if(is_hub) {
addr.bmHub = 1;
addr.bmAddress = ++hubCounter;
} else {
addr.bmHub = 0;
addr.bmAddress = port;
}
thePool[index].address = addr;
/*
USB_HOST_SERIAL.print("Addr:");
USB_HOST_SERIAL.print(addr.bmHub, HEX);
USB_HOST_SERIAL.print(".");
USB_HOST_SERIAL.print(addr.bmParent, HEX);
USB_HOST_SERIAL.print(".");
USB_HOST_SERIAL.println(addr.bmAddress, HEX);
*/
return thePool[index].address.devAddress;
};
// Empties pool entry
virtual void FreeAddress(uint8_t addr) {
// if the root hub is disconnected all the addresses should be initialized
if(addr == 0x41) {
InitAllAddresses();
return;
}
uint8_t index = FindAddressIndex(addr);
FreeAddressByIndex(index);
};
// Returns number of hubs attached
// It can be rather helpfull to find out if there are hubs attached than getting the exact number of hubs.
//uint8_t GetNumHubs()
//{
// return hubCounter;
//};
//uint8_t GetNumDevices()
//{
// uint8_t counter = 0;
// for (uint8_t i=1; i<MAX_DEVICES_ALLOWED; i++)
// if (thePool[i].address != 0);
// counter ++;
// return counter;
//};
};
#endif // __ADDRESS_H__

View File

@ -0,0 +1,372 @@
/* 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
*/
/* Google ADK interface */
#include "adk.h"
const uint8_t ADK::epDataInIndex = 1;
const uint8_t ADK::epDataOutIndex = 2;
ADK::ADK(USB *p, const char* manufacturer,
const char* model,
const char* description,
const char* version,
const char* uri,
const char* serial) :
/* ADK ID Strings */
manufacturer(manufacturer),
model(model),
description(description),
version(version),
uri(uri),
serial(serial),
pUsb(p), //pointer to USB class instance - mandatory
bAddress(0), //device address - mandatory
bConfNum(0), //configuration number
bNumEP(1), //if config descriptor needs to be parsed
ready(false) {
// initialize endpoint data structures
for(uint8_t i = 0; i < ADK_MAX_ENDPOINTS; i++) {
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;
}//for(uint8_t i=0; i<ADK_MAX_ENDPOINTS; i++...
// register in USB subsystem
if(pUsb) {
pUsb->RegisterDeviceClass(this); //set devConfig[] entry
}
}
uint8_t ADK::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
return Init(parent, port, lowspeed); // Just call Init. Yes, really!
}
/* Connection initialization of an Android phone */
uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) {
uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
uint8_t rcode;
uint8_t num_of_conf; // number of configurations
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
// get memory address of USB device address pool
AddressPool &addrPool = pUsb->GetAddressPool();
USBTRACE("\r\nADK Init");
// check if address has already been assigned to an instance
if(bAddress) {
USBTRACE("\r\nAddress in use");
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
}
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
if(!p) {
USBTRACE("\r\nAddress not found");
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
}
if(!p->epinfo) {
USBTRACE("epinfo is null\r\n");
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);
// Restore p->epinfo
p->epinfo = oldep_ptr;
if(rcode) {
goto FailGetDevDescr;
}
// Allocate new address according to device class
bAddress = addrPool.AllocAddress(parent, false, port);
// 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;
//USBTRACE2("setAddr:",rcode);
return rcode;
}//if (rcode...
//USBTRACE2("\r\nAddr:", bAddress);
// Spec says you should wait at least 200ms.
//delay(300);
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;
}
//check if ADK device is already in accessory mode; if yes, configure and exit
if(udd->idVendor == ADK_VID &&
(udd->idProduct == ADK_PID || udd->idProduct == ADB_PID)) {
USBTRACE("\r\nAcc.mode device detected");
/* go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */
num_of_conf = udd->bNumConfigurations;
//USBTRACE2("\r\nNC:",num_of_conf);
for(uint8_t i = 0; i < num_of_conf; i++) {
ConfigDescParser < 0, 0, 0, 0 > confDescrParser(this);
delay(1);
rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
#if defined(XOOM)
//added by Jaylen Scott Vanorden
if(rcode) {
USBTRACE2("\r\nGot 1st bad code for config: ", rcode);
// Try once more
rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
}
#endif
if(rcode) {
goto FailGetConfDescr;
}
if(bNumEP > 2) {
break;
}
} // for (uint8_t i=0; i<num_of_conf; i++...
if(bNumEP == 3) {
// Assign epInfo to epinfo pointer - this time all 3 endpoins
rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
if(rcode) {
goto FailSetDevTblEntry;
}
}
// Set Configuration Value
rcode = pUsb->setConf(bAddress, 0, bConfNum);
if(rcode) {
goto FailSetConfDescr;
}
/* print endpoint structure */
/*
USBTRACE("\r\nEndpoint Structure:");
USBTRACE("\r\nEP0:");
USBTRACE2("\r\nAddr: ", epInfo[0].epAddr);
USBTRACE2("\r\nMax.pkt.size: ", epInfo[0].maxPktSize);
USBTRACE2("\r\nAttr: ", epInfo[0].epAttribs);
USBTRACE("\r\nEpout:");
USBTRACE2("\r\nAddr: ", epInfo[epDataOutIndex].epAddr);
USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataOutIndex].maxPktSize);
USBTRACE2("\r\nAttr: ", epInfo[epDataOutIndex].epAttribs);
USBTRACE("\r\nEpin:");
USBTRACE2("\r\nAddr: ", epInfo[epDataInIndex].epAddr);
USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataInIndex].maxPktSize);
USBTRACE2("\r\nAttr: ", epInfo[epDataInIndex].epAttribs);
*/
USBTRACE("\r\nConfiguration successful");
ready = true;
return 0; //successful configuration
}//if( buf->idVendor == ADK_VID...
//probe device - get accessory protocol revision
{
uint16_t adkproto = -1;
delay(1);
rcode = getProto((uint8_t*) & adkproto);
#if defined(XOOM)
//added by Jaylen Scott Vanorden
if(rcode) {
USBTRACE2("\r\nGot 1st bad code for proto: ", rcode);
// Try once more
rcode = getProto((uint8_t*) & adkproto);
}
#endif
if(rcode) {
goto FailGetProto; //init fails
}
USBTRACE2("\r\nADK protocol rev. ", adkproto);
}
delay(100);
//sending ID strings
sendStr(ACCESSORY_STRING_MANUFACTURER, manufacturer);
delay(10);
sendStr(ACCESSORY_STRING_MODEL, model);
delay(10);
sendStr(ACCESSORY_STRING_DESCRIPTION, description);
delay(10);
sendStr(ACCESSORY_STRING_VERSION, version);
delay(10);
sendStr(ACCESSORY_STRING_URI, uri);
delay(10);
sendStr(ACCESSORY_STRING_SERIAL, serial);
delay(100);
//switch to accessory mode
//the Android phone will reset
rcode = switchAcc();
if(rcode) {
goto FailSwAcc; //init fails
}
rcode = USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET;
delay(100); // Give Android a chance to do its reset. This is a guess, and possibly could be lower.
goto SwAttempt; //switch to accessory mode attempted
/* diagnostic messages */
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr(rcode);
goto Fail;
#endif
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry(rcode);
goto Fail;
#endif
FailGetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetConfDescr(rcode);
goto Fail;
#endif
FailSetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailSetConfDescr(rcode);
goto Fail;
#endif
FailGetProto:
#ifdef DEBUG_USB_HOST
USBTRACE("\r\ngetProto:");
goto Fail;
#endif
FailSwAcc:
#ifdef DEBUG_USB_HOST
USBTRACE("\r\nswAcc:");
goto Fail;
#endif
//FailOnInit:
// USBTRACE("OnInit:");
// goto Fail;
//
SwAttempt:
#ifdef DEBUG_USB_HOST
USBTRACE("\r\nAccessory mode switch attempt");
Fail:
#endif
//USBTRACE2("\r\nADK Init Failed, error code: ", rcode);
//NotifyFail(rcode);
Release();
return rcode;
}
/* Extracts bulk-IN and bulk-OUT endpoint information from config descriptor */
void ADK::EndpointXtract(uint8_t conf, uint8_t iface __attribute__((unused)), uint8_t alt __attribute__((unused)), uint8_t proto __attribute__((unused)), const USB_ENDPOINT_DESCRIPTOR *pep) {
//ErrorMessage<uint8_t>(PSTR("Conf.Val"), conf);
//ErrorMessage<uint8_t>(PSTR("Iface Num"), iface);
//ErrorMessage<uint8_t>(PSTR("Alt.Set"), alt);
//added by Yuuichi Akagawa
if(bNumEP == 3) {
return;
}
bConfNum = conf;
if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_BULK) {
uint8_t index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
// Fill in the endpoint info structure
epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
bNumEP++;
//PrintEndpointDescriptor(pep);
}
}
/* Performs a cleanup after failed Init() attempt */
uint8_t ADK::Release() {
pUsb->GetAddressPool().FreeAddress(bAddress);
bNumEP = 1; //must have to be reset to 1
bAddress = 0;
ready = false;
return 0;
}
uint8_t ADK::RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr) {
//USBTRACE2("\r\nAddr: ", bAddress );
//USBTRACE2("\r\nEP: ",epInfo[epDataInIndex].epAddr);
return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr);
}
uint8_t ADK::SndData(uint16_t nbytes, uint8_t *dataptr) {
return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr);
}
void ADK::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
Notify(PSTR("Endpoint descriptor:"), 0x80);
Notify(PSTR("\r\nLength:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
Notify(PSTR("\r\nType:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
Notify(PSTR("\r\nAddress:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
Notify(PSTR("\r\nAttributes:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
Notify(PSTR("\r\n"), 0x80);
}

View File

@ -0,0 +1,140 @@
/* 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
*/
/* Google ADK interface support header */
#if !defined(_ADK_H_)
#define _ADK_H_
#include "Usb.h"
#define ADK_VID 0x18D1
#define ADK_PID 0x2D00
#define ADB_PID 0x2D01
#define XOOM //enables repeating getProto() and getConf() attempts
//necessary for slow devices such as Motorola XOOM
//defined by default, can be commented out to save memory
/* requests */
#define ADK_GETPROTO 51 //check USB accessory protocol version
#define ADK_SENDSTR 52 //send identifying string
#define ADK_ACCSTART 53 //start device in accessory mode
#define bmREQ_ADK_GET USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE
#define bmREQ_ADK_SEND USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE
#define ACCESSORY_STRING_MANUFACTURER 0
#define ACCESSORY_STRING_MODEL 1
#define ACCESSORY_STRING_DESCRIPTION 2
#define ACCESSORY_STRING_VERSION 3
#define ACCESSORY_STRING_URI 4
#define ACCESSORY_STRING_SERIAL 5
#define ADK_MAX_ENDPOINTS 3 //endpoint 0, bulk_IN, bulk_OUT
class ADK;
class ADK : public USBDeviceConfig, public UsbConfigXtracter {
private:
/* ID strings */
const char* manufacturer;
const char* model;
const char* description;
const char* version;
const char* uri;
const char* serial;
/* ADK proprietary requests */
uint8_t getProto(uint8_t* adkproto);
uint8_t sendStr(uint8_t index, const char* str);
uint8_t switchAcc(void);
protected:
static const uint8_t epDataInIndex; // DataIn endpoint index
static const uint8_t epDataOutIndex; // DataOUT endpoint index
/* mandatory members */
USB *pUsb;
uint8_t bAddress;
uint8_t bConfNum; // configuration number
uint8_t bNumEP; // total number of EP in the configuration
bool ready;
/* Endpoint data structure */
EpInfo epInfo[ADK_MAX_ENDPOINTS];
void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
public:
ADK(USB *pUsb, const char* manufacturer,
const char* model,
const char* description,
const char* version,
const char* uri,
const char* serial);
// Methods for receiving and sending data
uint8_t RcvData(uint16_t *nbytesptr, uint8_t *dataptr);
uint8_t SndData(uint16_t nbytes, uint8_t *dataptr);
// USBDeviceConfig implementation
uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
uint8_t Release();
virtual uint8_t Poll() {
return 0;
};
virtual uint8_t GetAddress() {
return bAddress;
};
virtual bool isReady() {
return ready;
};
virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
return (vid == ADK_VID && (pid == ADK_PID || pid == ADB_PID));
};
//UsbConfigXtracter implementation
void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
}; //class ADK : public USBDeviceConfig ...
/* get ADK protocol version */
/* returns 2 bytes in *adkproto */
inline uint8_t ADK::getProto(uint8_t* adkproto) {
return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_GET, ADK_GETPROTO, 0, 0, 0, 2, 2, adkproto, NULL));
}
/* send ADK string */
inline uint8_t ADK::sendStr(uint8_t index, const char* str) {
return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_SENDSTR, 0, 0, index, strlen(str) + 1, strlen(str) + 1, (uint8_t*)str, NULL));
}
/* switch to accessory mode */
inline uint8_t ADK::switchAcc(void) {
return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_ACCSTART, 0, 0, 0, 0, 0, NULL, NULL));
}
#endif // _ADK_H_

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,211 @@
/* Copyright (C) 2015 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#include "cdc_XR21B1411.h"
XR21B1411::XR21B1411(USB *p, CDCAsyncOper *pasync) :
ACM(p, pasync) {
// Is this needed??
_enhanced_status = enhanced_features(); // Set up features
}
uint8_t XR21B1411::Init(uint8_t parent, uint8_t port, bool lowspeed) {
const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
uint8_t buf[constBufSize];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
uint8_t rcode;
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
uint8_t num_of_conf; // number of configurations
AddressPool &addrPool = pUsb->GetAddressPool();
USBTRACE("XR Init\r\n");
if(bAddress)
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
if(!p->epinfo) {
USBTRACE("epinfo\r\n");
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, constBufSize, (uint8_t*)buf);
// Restore p->epinfo
p->epinfo = oldep_ptr;
if(rcode)
goto FailGetDevDescr;
// 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 the 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;
USBTRACE2("setAddr:", rcode);
return rcode;
}
USBTRACE2("Addr:", bAddress);
p->lowspeed = false;
p = addrPool.GetUsbDevicePtr(bAddress);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
p->lowspeed = lowspeed;
num_of_conf = udd->bNumConfigurations;
if((((udd->idVendor != 0x2890U) || (udd->idProduct != 0x0201U)) && ((udd->idVendor != 0x04e2U) || (udd->idProduct != 0x1411U))))
return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
if(rcode)
goto FailSetDevTblEntry;
USBTRACE2("NC:", num_of_conf);
for(uint8_t i = 0; i < num_of_conf; i++) {
ConfigDescParser< USB_CLASS_COM_AND_CDC_CTRL,
CDC_SUBCLASS_ACM,
CDC_PROTOCOL_ITU_T_V_250,
CP_MASK_COMPARE_CLASS |
CP_MASK_COMPARE_SUBCLASS |
CP_MASK_COMPARE_PROTOCOL > CdcControlParser(this);
ConfigDescParser<USB_CLASS_CDC_DATA, 0, 0,
CP_MASK_COMPARE_CLASS> CdcDataParser(this);
rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcControlParser);
if(rcode)
goto FailGetConfDescr;
rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcDataParser);
if(rcode)
goto FailGetConfDescr;
if(bNumEP > 1)
break;
} // for
if(bNumEP < 4)
return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
USBTRACE2("Conf:", bConfNum);
// Set Configuration Value
rcode = pUsb->setConf(bAddress, 0, bConfNum);
if(rcode)
goto FailSetConfDescr;
// Set up features status
_enhanced_status = enhanced_features();
half_duplex(false);
autoflowRTS(false);
autoflowDSR(false);
autoflowXON(false);
wide(false); // Always false, because this is only available in custom mode.
rcode = pAsync->OnInit(this);
if(rcode)
goto FailOnInit;
USBTRACE("XR configured\r\n");
ready = true;
//bPollEnable = true;
//USBTRACE("Poll enabled\r\n");
return 0;
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr();
goto Fail;
#endif
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry();
goto Fail;
#endif
FailGetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetConfDescr();
goto Fail;
#endif
FailSetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailSetConfDescr();
goto Fail;
#endif
FailOnInit:
#ifdef DEBUG_USB_HOST
USBTRACE("OnInit:");
#endif
#ifdef DEBUG_USB_HOST
Fail:
NotifyFail(rcode);
#endif
Release();
return rcode;
}

View File

@ -0,0 +1,272 @@
/* Copyright (C) 2015 Andrew J. Kroll
and
Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#if !defined(__CDC_XR21B1411_H__)
#define __CDC_XR21B1411_H__
#include "cdcacm.h"
#define XR_REG_CUSTOM_DRIVER (0x020DU) // DRIVER SELECT
#define XR_REG_CUSTOM_DRIVER_ACTIVE (0x0001U) // 0: CDC 1: CUSTOM
#define XR_REG_ACM_FLOW_CTL (0x0216U) // FLOW CONTROL REGISTER CDCACM MODE
#define XR_REG_FLOW_CTL (0x0C06U) // FLOW CONTROL REGISTER CUSTOM MODE
#define XR_REG_FLOW_CTL_HALF_DPLX (0x0008U) // 0:FULL DUPLEX 1:HALF DUPLEX
#define XR_REG_FLOW_CTL_MODE_MASK (0x0007U) // MODE BITMASK
#define XR_REG_FLOW_CTL_NONE (0x0000U) // NO FLOW CONTROL
#define XR_REG_FLOW_CTL_HW (0x0001U) // HARDWARE FLOW CONTROL
#define XR_REG_FLOW_CTL_SW (0x0002U) // SOFTWARE FLOW CONTROL
#define XR_REG_FLOW_CTL_MMMRX (0x0003U) // MULTIDROP RX UPON ADDRESS MATCH
#define XR_REG_FLOW_CTL_MMMRXTX (0x0004U) // MULTIDROP RX/TX UPON ADDRESS MATCH
#define XR_REG_ACM_GPIO_MODE (0x0217U) // GPIO MODE REGISTER IN CDCACM MODE
#define XR_REG_GPIO_MODE (0x0C0CU) // GPIO MODE REGISTER IN CUSTOM MODE
#define XR_REG_GPIO_MODE_GPIO (0x0000U) // ALL GPIO PINS ACM PROGRAMMABLE
#define XR_REG_GPIO_MODE_FC_RTSCTS (0x0001U) // AUTO RTSCTS HW FC (GPIO 4/5)
#define XR_REG_GPIO_MODE_FC_DTRDSR (0x0002U) // AUTO DTRDSR HW FC (GPIO 2/3)
#define XR_REG_GPIO_MODE_ATE (0x0003U) // AUTO TRANSCEIVER ENABLE DURING TX (GPIO 5)
#define XR_REG_GPIO_MODE_ATE_ADDRESS (0x0004U) // AUTO TRANSCEIVER ENABLE ON ADDRESS MATCH (GPIO 5)
#define XR_REG_ACM_GPIO_DIR (0x0218U) // GPIO DIRECTION REGISTER CDCACM MODE, 0:IN 1:OUT
#define XR_REG_GPIO_DIR (0x0C0DU) // GPIO DIRECTION REGISTER CUSTOM MODE, 0:IN 1:OUT
#define XR_REG_ACM_GPIO_INT (0x0219U) // GPIO PIN CHANGE INTERRUPT ENABLE CDCACM MODE, 0: ENABLED 1: DISABLED
#define XR_REG_GPIO_INT (0x0C11U) // GPIO PIN CHANGE INTERRUPT ENABLE CUSTOM MODE, 0: ENABLED 1: DISABLED
#define XR_REG_GPIO_MASK (0x001FU) // GPIO REGISTERS BITMASK
#define XR_REG_UART_ENABLE (0x0C00U) // UART I/O ENABLE REGISTER
#define XR_REG_UART_ENABLE_RX (0x0002U) // 0:DISABLED 1:ENABLED
#define XR_REG_UART_ENABLE_TX (0x0001U) // 0:DISABLED 1:ENABLED
#define XR_REG_ERROR_STATUS (0x0C09U) // ERROR STATUS REGISTER
#define XR_REG_ERROR_STATUS_MASK (0x00F8U) // ERROR STATUS BITMASK
#define XR_REG_ERROR_STATUS_ERROR (0x0070U) // ERROR STATUS ERROR BITMASK
#define XR_REG_ERROR_STATUS_BREAK (0x0008U) // BREAK HAS BEEN DETECTED
#define XR_REG_ERROR_STATUS_OVERRUN (0x0010U) // RX OVERRUN ERROR
#define XR_REG_ERROR_STATUS_PARITY (0x0020U) // PARITY ERROR
#define XR_REG_ERROR_STATUS_FRAME (0x0040U) // FRAMING ERROR
#define XR_REG_ERROR_STATUS_BREAKING (0x0080U) // BREAK IS BEING DETECTED
#define XR_REG_TX_BREAK (0x0C0AU) // TRANSMIT BREAK. 0X0001-0XFFE TIME IN MS, 0X0000 STOP, 0X0FFF BREAK ON
#define XR_REG_XCVR_EN_DELAY (0x0C0BU) // TURN-ARROUND DELAY IN BIT-TIMES 0X0000-0X000F
#define XR_REG_GPIO_SET (0x0C0EU) // 1:SET GPIO PIN
#define XR_REG_GPIO_CLR (0x0C0FU) // 1:CLEAR GPIO PIN
#define XR_REG_GPIO_STATUS (0x0C10U) // READ GPIO PINS
#define XR_REG_CUSTOMISED_INT (0x0C12U) // 0:STANDARD 1:CUSTOM SEE DATA SHEET
#define XR_REG_PIN_PULLUP_ENABLE (0x0C14U) // 0:DISABLE 1:ENABLE, BITS 0-5:GPIO, 6:RX 7:TX
#define XR_REG_PIN_PULLDOWN_ENABLE (0x0C15U) // 0:DISABLE 1:ENABLE, BITS 0-5:GPIO, 6:RX 7:TX
#define XR_REG_LOOPBACK (0x0C16U) // 0:DISABLE 1:ENABLE, SEE DATA SHEET
#define XR_REG_RX_FIFO_LATENCY (0x0CC2U) // FIFO LATENCY REGISTER
#define XR_REG_RX_FIFO_LATENCY_ENABLE (0x0001U) //
#define XR_REG_WIDE_MODE (0x0D02U)
#define XR_REG_WIDE_MODE_ENABLE (0x0001U)
#define XR_REG_XON_CHAR (0x0C07U)
#define XR_REG_XOFF_CHAR (0x0C08U)
#define XR_REG_TX_FIFO_RESET (0x0C80U) // 1: RESET, SELF-CLEARING
#define XR_REG_TX_FIFO_COUNT (0x0C81U) // READ-ONLY
#define XR_REG_RX_FIFO_RESET (0x0CC0U) // 1: RESET, SELF-CLEARING
#define XR_REG_RX_FIFO_COUNT (0x0CC1U) // READ-ONLY
#define XR_WRITE_REQUEST_TYPE (0x40U)
#define XR_READ_REQUEST_TYPE (0xC0U)
#define XR_MAX_ENDPOINTS 4
class XR21B1411 : public ACM {
protected:
public:
XR21B1411(USB *pusb, CDCAsyncOper *pasync);
/**
* 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 == 0x2890U) && (pid == 0x0201U)) || ((vid == 0x04e2U) && (pid == 0x1411U)));
};
uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
virtual tty_features enhanced_features(void) {
tty_features rv;
rv.enhanced = true;
rv.autoflow_RTS = true;
rv.autoflow_DSR = true;
rv.autoflow_XON = true;
rv.half_duplex = true;
rv.wide = true;
return rv;
};
uint8_t read_register(uint16_t reg, uint16_t *val) {
return (pUsb->ctrlReq(bAddress, 0, XR_READ_REQUEST_TYPE, 1, 0, 0, reg, 2, 2, (uint8_t *)val, NULL));
}
uint8_t write_register(uint16_t reg, uint16_t val) {
return (pUsb->ctrlReq(bAddress, 0, XR_WRITE_REQUEST_TYPE, 0, BGRAB0(val), BGRAB1(val), reg, 0, 0, NULL, NULL));
}
////////////////////////////////////////////////////////////////////////
// The following methods set the CDC-ACM defaults.
////////////////////////////////////////////////////////////////////////
virtual void autoflowRTS(bool s) {
uint16_t val;
uint8_t rval;
rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
if(!rval) {
if(s) {
val &= XR_REG_FLOW_CTL_HALF_DPLX;
val |= XR_REG_FLOW_CTL_HW;
} else {
val &= XR_REG_FLOW_CTL_HALF_DPLX;
}
rval = write_register(XR_REG_ACM_FLOW_CTL, val);
if(!rval) {
rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_GPIO);
if(!rval) {
// ACM commands apply the new settings.
LINE_CODING LCT;
rval = GetLineCoding(&LCT);
if(!rval) {
rval = SetLineCoding(&LCT);
if(!rval) {
_enhanced_status.autoflow_XON = false;
_enhanced_status.autoflow_DSR = false;
_enhanced_status.autoflow_RTS = s;
}
}
}
}
}
};
virtual void autoflowDSR(bool s) {
uint16_t val;
uint8_t rval;
rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
if(!rval) {
if(s) {
val &= XR_REG_FLOW_CTL_HALF_DPLX;
val |= XR_REG_FLOW_CTL_HW;
} else {
val &= XR_REG_FLOW_CTL_HALF_DPLX;
}
rval = write_register(XR_REG_ACM_FLOW_CTL, val);
if(!rval) {
if(s) {
rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_FC_DTRDSR);
} else {
rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_GPIO);
}
if(!rval) {
// ACM commands apply the new settings.
LINE_CODING LCT;
rval = GetLineCoding(&LCT);
if(!rval) {
rval = SetLineCoding(&LCT);
if(!rval) {
_enhanced_status.autoflow_XON = false;
_enhanced_status.autoflow_RTS = false;
_enhanced_status.autoflow_DSR = s;
}
}
}
}
}
};
virtual void autoflowXON(bool s) {
// NOTE: hardware defaults to the normal XON/XOFF
uint16_t val;
uint8_t rval;
rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
if(!rval) {
if(s) {
val &= XR_REG_FLOW_CTL_HALF_DPLX;
val |= XR_REG_FLOW_CTL_SW;
} else {
val &= XR_REG_FLOW_CTL_HALF_DPLX;
}
rval = write_register(XR_REG_ACM_FLOW_CTL, val);
if(!rval) {
rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_GPIO);
if(!rval) {
// ACM commands apply the new settings.
LINE_CODING LCT;
rval = GetLineCoding(&LCT);
if(!rval) {
rval = SetLineCoding(&LCT);
if(!rval) {
_enhanced_status.autoflow_RTS = false;
_enhanced_status.autoflow_DSR = false;
_enhanced_status.autoflow_XON = s;
}
}
}
}
}
};
virtual void half_duplex(bool s) {
uint16_t val;
uint8_t rval;
rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
if(!rval) {
if(s) {
val |= XR_REG_FLOW_CTL_HALF_DPLX;
} else {
val &= XR_REG_FLOW_CTL_MODE_MASK;
}
rval = write_register(XR_REG_ACM_FLOW_CTL, val);
if(!rval) {
// ACM commands apply the new settings.
LINE_CODING LCT;
rval = GetLineCoding(&LCT);
if(!rval) {
rval = SetLineCoding(&LCT);
if(!rval) {
_enhanced_status.half_duplex = s;
}
}
}
}
};
};
#endif // __CDCPROLIFIC_H__

View File

@ -0,0 +1,367 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#include "cdcacm.h"
const uint8_t ACM::epDataInIndex = 1;
const uint8_t ACM::epDataOutIndex = 2;
const uint8_t ACM::epInterruptInIndex = 3;
ACM::ACM(USB *p, CDCAsyncOper *pasync) :
pUsb(p),
pAsync(pasync),
bAddress(0),
bControlIface(0),
bDataIface(0),
bNumEP(1),
qNextPollTime(0),
bPollEnable(false),
ready(false) {
_enhanced_status = enhanced_features(); // Set up features
for(uint8_t i = 0; i < ACM_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 == epDataInIndex) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
}
if(pUsb)
pUsb->RegisterDeviceClass(this);
}
uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) {
const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
uint8_t buf[constBufSize];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
uint8_t rcode;
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
uint8_t num_of_conf; // number of configurations
AddressPool &addrPool = pUsb->GetAddressPool();
USBTRACE("ACM Init\r\n");
if(bAddress)
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
if(!p->epinfo) {
USBTRACE("epinfo\r\n");
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, constBufSize, (uint8_t*)buf);
// Restore p->epinfo
p->epinfo = oldep_ptr;
if(rcode)
goto FailGetDevDescr;
// 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 the 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;
USBTRACE2("setAddr:", rcode);
return rcode;
}
USBTRACE2("Addr:", bAddress);
p->lowspeed = false;
p = addrPool.GetUsbDevicePtr(bAddress);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
p->lowspeed = lowspeed;
num_of_conf = udd->bNumConfigurations;
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
if(rcode)
goto FailSetDevTblEntry;
USBTRACE2("NC:", num_of_conf);
for(uint8_t i = 0; i < num_of_conf; i++) {
ConfigDescParser< USB_CLASS_COM_AND_CDC_CTRL,
CDC_SUBCLASS_ACM,
CDC_PROTOCOL_ITU_T_V_250,
CP_MASK_COMPARE_CLASS |
CP_MASK_COMPARE_SUBCLASS |
CP_MASK_COMPARE_PROTOCOL > CdcControlParser(this);
ConfigDescParser<USB_CLASS_CDC_DATA, 0, 0,
CP_MASK_COMPARE_CLASS> CdcDataParser(this);
rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcControlParser);
if(rcode)
goto FailGetConfDescr;
rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcDataParser);
if(rcode)
goto FailGetConfDescr;
if(bNumEP > 1)
break;
} // for
if(bNumEP < 4)
return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
USBTRACE2("Conf:", bConfNum);
// Set Configuration Value
rcode = pUsb->setConf(bAddress, 0, bConfNum);
if(rcode)
goto FailSetConfDescr;
// Set up features status
_enhanced_status = enhanced_features();
half_duplex(false);
autoflowRTS(false);
autoflowDSR(false);
autoflowXON(false);
wide(false); // Always false, because this is only available in custom mode.
rcode = pAsync->OnInit(this);
if(rcode)
goto FailOnInit;
USBTRACE("ACM configured\r\n");
ready = true;
//bPollEnable = true;
//USBTRACE("Poll enabled\r\n");
return 0;
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr();
goto Fail;
#endif
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry();
goto Fail;
#endif
FailGetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetConfDescr();
goto Fail;
#endif
FailSetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailSetConfDescr();
goto Fail;
#endif
FailOnInit:
#ifdef DEBUG_USB_HOST
USBTRACE("OnInit:");
#endif
#ifdef DEBUG_USB_HOST
Fail:
NotifyFail(rcode);
#endif
Release();
return rcode;
}
void ACM::EndpointXtract(uint8_t conf, uint8_t iface __attribute__((unused)), uint8_t alt __attribute__((unused)), uint8_t proto __attribute__((unused)), const USB_ENDPOINT_DESCRIPTOR *pep) {
//ErrorMessage<uint8_t > (PSTR("Conf.Val"), conf);
//ErrorMessage<uint8_t > (PSTR("Iface Num"), iface);
//ErrorMessage<uint8_t > (PSTR("Alt.Set"), alt);
bConfNum = conf;
uint8_t index;
if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_INTERRUPT && (pep->bEndpointAddress & 0x80) == 0x80)
index = epInterruptInIndex;
else if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_BULK)
index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
else
return;
// Fill in the endpoint info structure
epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
epInfo[index].bmSndToggle = 0;
epInfo[index].bmRcvToggle = 0;
bNumEP++;
PrintEndpointDescriptor(pep);
}
uint8_t ACM::Release() {
ready = false;
pUsb->GetAddressPool().FreeAddress(bAddress);
bControlIface = 0;
bDataIface = 0;
bNumEP = 1;
bAddress = 0;
qNextPollTime = 0;
bPollEnable = false;
return 0;
}
uint8_t ACM::Poll() {
//uint8_t rcode = 0;
//if(!bPollEnable)
// return 0;
//return rcode;
return 0;
}
uint8_t ACM::RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr) {
uint8_t rv = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::SndData(uint16_t nbytes, uint8_t *dataptr) {
uint8_t rv = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::SetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr) {
uint8_t rv = ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SET_COMM_FEATURE, (fid & 0xff), (fid >> 8), bControlIface, nbytes, nbytes, dataptr, NULL));
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::GetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr) {
uint8_t rv = ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCIN, CDC_GET_COMM_FEATURE, (fid & 0xff), (fid >> 8), bControlIface, nbytes, nbytes, dataptr, NULL));
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::ClearCommFeature(uint16_t fid) {
uint8_t rv = ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_CLEAR_COMM_FEATURE, (fid & 0xff), (fid >> 8), bControlIface, 0, 0, NULL, NULL));
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::SetLineCoding(const LINE_CODING *dataptr) {
uint8_t rv = ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SET_LINE_CODING, 0x00, 0x00, bControlIface, sizeof (LINE_CODING), sizeof (LINE_CODING), (uint8_t*)dataptr, NULL));
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::GetLineCoding(LINE_CODING *dataptr) {
uint8_t rv = ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCIN, CDC_GET_LINE_CODING, 0x00, 0x00, bControlIface, sizeof (LINE_CODING), sizeof (LINE_CODING), (uint8_t*)dataptr, NULL));
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::SetControlLineState(uint8_t state) {
uint8_t rv = ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SET_CONTROL_LINE_STATE, state, 0, bControlIface, 0, 0, NULL, NULL));
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t ACM::SendBreak(uint16_t duration) {
uint8_t rv = ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SEND_BREAK, (duration & 0xff), (duration >> 8), bControlIface, 0, 0, NULL, NULL));
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
void ACM::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
Notify(PSTR("Endpoint descriptor:"), 0x80);
Notify(PSTR("\r\nLength:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
Notify(PSTR("\r\nType:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
Notify(PSTR("\r\nAddress:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
Notify(PSTR("\r\nAttributes:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
Notify(PSTR("\r\n"), 0x80);
}

View File

@ -0,0 +1,251 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#if !defined(__CDCACM_H__)
#define __CDCACM_H__
#include "Usb.h"
#define bmREQ_CDCOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
#define bmREQ_CDCIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
// CDC Subclass Constants
#define CDC_SUBCLASS_DLCM 0x01 // Direct Line Control Model
#define CDC_SUBCLASS_ACM 0x02 // Abstract Control Model
#define CDC_SUBCLASS_TCM 0x03 // Telephone Control Model
#define CDC_SUBCLASS_MCCM 0x04 // Multi Channel Control Model
#define CDC_SUBCLASS_CAPI 0x05 // CAPI Control Model
#define CDC_SUBCLASS_ETHERNET 0x06 // Ethernet Network Control Model
#define CDC_SUBCLASS_ATM 0x07 // ATM Network Control Model
#define CDC_SUBCLASS_WIRELESS_HANDSET 0x08 // Wireless Handset Control Model
#define CDC_SUBCLASS_DEVICE_MANAGEMENT 0x09 // Device Management
#define CDC_SUBCLASS_MOBILE_DIRECT_LINE 0x0A // Mobile Direct Line Model
#define CDC_SUBCLASS_OBEX 0x0B // OBEX
#define CDC_SUBCLASS_ETHERNET_EMU 0x0C // Ethernet Emulation Model
// Communication Interface Class Control Protocol Codes
#define CDC_PROTOCOL_ITU_T_V_250 0x01 // AT Commands defined by ITU-T V.250
#define CDC_PROTOCOL_PCCA_101 0x02 // AT Commands defined by PCCA-101
#define CDC_PROTOCOL_PCCA_101_O 0x03 // AT Commands defined by PCCA-101 & Annex O
#define CDC_PROTOCOL_GSM_7_07 0x04 // AT Commands defined by GSM 7.07
#define CDC_PROTOCOL_3GPP_27_07 0x05 // AT Commands defined by 3GPP 27.007
#define CDC_PROTOCOL_C_S0017_0 0x06 // AT Commands defined by TIA for CDMA
#define CDC_PROTOCOL_USB_EEM 0x07 // Ethernet Emulation Model
// CDC Commands defined by CDC 1.2
#define CDC_SEND_ENCAPSULATED_COMMAND 0x00
#define CDC_GET_ENCAPSULATED_RESPONSE 0x01
// CDC Commands defined by PSTN 1.2
#define CDC_SET_COMM_FEATURE 0x02
#define CDC_GET_COMM_FEATURE 0x03
#define CDC_CLEAR_COMM_FEATURE 0x04
#define CDC_SET_AUX_LINE_STATE 0x10
#define CDC_SET_HOOK_STATE 0x11
#define CDC_PULSE_SETUP 0x12
#define CDC_SEND_PULSE 0x13
#define CDC_SET_PULSE_TIME 0x14
#define CDC_RING_AUX_JACK 0x15
#define CDC_SET_LINE_CODING 0x20
#define CDC_GET_LINE_CODING 0x21
#define CDC_SET_CONTROL_LINE_STATE 0x22
#define CDC_SEND_BREAK 0x23
#define CDC_SET_RINGER_PARMS 0x30
#define CDC_GET_RINGER_PARMS 0x31
#define CDC_SET_OPERATION_PARMS 0x32
#define CDC_GET_OPERATION_PARMS 0x33
#define CDC_SET_LINE_PARMS 0x34
#define CDC_GET_LINE_PARMS 0x35
#define CDC_DIAL_DIGITS 0x36
//Class-Specific Notification Codes
#define NETWORK_CONNECTION 0x00
#define RESPONSE_AVAILABLE 0x01
#define AUX_JACK_HOOK_STATE 0x08
#define RING_DETECT 0x09
#define SERIAL_STATE 0x20
#define CALL_STATE_CHANGE 0x28
#define LINE_STATE_CHANGE 0x29
#define CONNECTION_SPEED_CHANGE 0x2a
// CDC Functional Descriptor Structures
typedef struct {
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmCapabilities;
uint8_t bDataInterface;
} CALL_MGMNT_FUNC_DESCR;
typedef struct {
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bmCapabilities;
} ACM_FUNC_DESCR, DLM_FUNC_DESCR, TEL_OPER_MODES_FUNC_DESCR,
TEL_CALL_STATE_REP_CPBL_FUNC_DESCR;
typedef struct {
uint8_t bFunctionLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
uint8_t bRingerVolSteps;
uint8_t bNumRingerPatterns;
} TEL_RINGER_FUNC_DESCR;
typedef struct {
uint32_t dwDTERate; // Data Terminal Rate in bits per second
uint8_t bCharFormat; // 0 - 1 stop bit, 1 - 1.5 stop bits, 2 - 2 stop bits
uint8_t bParityType; // 0 - None, 1 - Odd, 2 - Even, 3 - Mark, 4 - Space
uint8_t bDataBits; // Data bits (5, 6, 7, 8 or 16)
} LINE_CODING;
typedef struct {
uint8_t bmRequestType; // 0xa1 for class-specific notifications
uint8_t bNotification;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
uint16_t bmState; //UART state bitmap for SERIAL_STATE, other notifications variable length
} CLASS_NOTIFICATION;
class ACM;
class CDCAsyncOper {
public:
virtual uint8_t OnInit(ACM *pacm __attribute__((unused))) {
return 0;
};
//virtual void OnDataRcvd(ACM *pacm, uint8_t nbytes, uint8_t *dataptr) = 0;
//virtual void OnDisconnected(ACM *pacm) = 0;
};
/**
* This structure is used to report the extended capabilities of the connected device.
* It is also used to report the current status.
* Regular CDC-ACM reports all as false.
*/
typedef struct {
union {
uint8_t tty;
struct {
bool enhanced : 1; // Do we have the ability to set/clear any features?
// Status and 8th bit in data stream.
// Presence only indicates feature is available, but this isn't used for CDC-ACM.
bool wide : 1;
bool autoflow_RTS : 1; // Has autoflow on RTS/CTS
bool autoflow_DSR : 1; // Has autoflow on DTR/DSR
bool autoflow_XON : 1; // Has autoflow XON/XOFF
bool half_duplex : 1; // Has half-duplex capability.
} __attribute__((packed));
};
} tty_features;
#define ACM_MAX_ENDPOINTS 4
class ACM : public USBDeviceConfig, public UsbConfigXtracter {
protected:
USB *pUsb;
CDCAsyncOper *pAsync;
uint8_t bAddress;
uint8_t bConfNum; // configuration number
uint8_t bControlIface; // Control interface value
uint8_t bDataIface; // Data interface value
uint8_t bNumEP; // total number of EP in the configuration
uint32_t qNextPollTime; // next poll time
volatile bool bPollEnable; // poll enable flag
volatile bool ready; //device ready indicator
tty_features _enhanced_status; // current status
void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
public:
static const uint8_t epDataInIndex; // DataIn endpoint index
static const uint8_t epDataOutIndex; // DataOUT endpoint index
static const uint8_t epInterruptInIndex; // InterruptIN endpoint index
EpInfo epInfo[ACM_MAX_ENDPOINTS];
ACM(USB *pusb, CDCAsyncOper *pasync);
uint8_t SetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr);
uint8_t GetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr);
uint8_t ClearCommFeature(uint16_t fid);
uint8_t SetLineCoding(const LINE_CODING *dataptr);
uint8_t GetLineCoding(LINE_CODING *dataptr);
uint8_t SetControlLineState(uint8_t state);
uint8_t SendBreak(uint16_t duration);
uint8_t GetNotif(uint16_t *bytes_rcvd, uint8_t *dataptr);
// Methods for receiving and sending data
uint8_t RcvData(uint16_t *nbytesptr, uint8_t *dataptr);
uint8_t SndData(uint16_t nbytes, uint8_t *dataptr);
// USBDeviceConfig implementation
uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
uint8_t Release();
uint8_t Poll();
bool available(void) {
return false;
};
virtual uint8_t GetAddress() {
return bAddress;
};
virtual bool isReady() {
return ready;
};
virtual tty_features enhanced_status(void) {
return _enhanced_status;
};
virtual tty_features enhanced_features(void) {
tty_features rv;
rv.enhanced = false;
rv.autoflow_RTS = false;
rv.autoflow_DSR = false;
rv.autoflow_XON = false;
rv.half_duplex = false;
rv.wide = false;
return rv;
};
virtual void autoflowRTS(bool s __attribute__((unused))) {
};
virtual void autoflowDSR(bool s __attribute__((unused))) {
};
virtual void autoflowXON(bool s __attribute__((unused))) {
};
virtual void half_duplex(bool s __attribute__((unused))) {
};
virtual void wide(bool s __attribute__((unused))) {
};
// UsbConfigXtracter implementation
void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
};
#endif // __CDCACM_H__

View File

@ -0,0 +1,371 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#include "cdcftdi.h"
const uint8_t FTDI::epDataInIndex = 1;
const uint8_t FTDI::epDataOutIndex = 2;
const uint8_t FTDI::epInterruptInIndex = 3;
FTDI::FTDI(USB *p, FTDIAsyncOper *pasync, uint16_t idProduct) :
pAsync(pasync),
pUsb(p),
bAddress(0),
bNumEP(1),
wFTDIType(0),
wIdProduct(idProduct) {
for(uint8_t i = 0; i < FTDI_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==epDataInIndex) ? USB_NAK_NOWAIT: USB_NAK_MAX_POWER;
}
if(pUsb)
pUsb->RegisterDeviceClass(this);
}
uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) {
const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
uint8_t buf[constBufSize];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
uint8_t rcode;
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
uint8_t num_of_conf; // number of configurations
AddressPool &addrPool = pUsb->GetAddressPool();
USBTRACE("FTDI Init\r\n");
if(bAddress) {
USBTRACE("FTDI CLASS IN USE??\r\n");
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
}
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
if(!p) {
USBTRACE("FTDI NO ADDRESS??\r\n");
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
}
if(!p->epinfo) {
USBTRACE("epinfo\r\n");
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), buf);
// Restore p->epinfo
p->epinfo = oldep_ptr;
if(rcode) {
goto FailGetDevDescr;
}
if(udd->idVendor != FTDI_VID || udd->idProduct != wIdProduct)
{
USBTRACE("FTDI Init: Product not supported\r\n");
USBTRACE2("Expected VID:", FTDI_VID);
USBTRACE2("Found VID:", udd->idVendor);
USBTRACE2("Expected PID:", wIdProduct);
USBTRACE2("Found PID:", udd->idProduct);
return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
}
// Save type of FTDI chip
wFTDIType = udd->bcdDevice;
// 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 the 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;
USBTRACE2("setAddr:", rcode);
return rcode;
}
USBTRACE2("Addr:", bAddress);
p->lowspeed = false;
p = addrPool.GetUsbDevicePtr(bAddress);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
p->lowspeed = lowspeed;
num_of_conf = udd->bNumConfigurations;
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
if(rcode)
goto FailSetDevTblEntry;
USBTRACE2("NC:", num_of_conf);
for(uint8_t i = 0; i < num_of_conf; i++) {
ConfigDescParser < 0xFF, 0xFF, 0xFF, CP_MASK_COMPARE_ALL> confDescrParser(this);
// This interferes with serial output, and should be opt-in for debugging.
//HexDumper<USBReadParser, uint16_t, uint16_t> HexDump;
//rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump);
//if(rcode)
// goto FailGetConfDescr;
rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
if(rcode)
goto FailGetConfDescr;
if(bNumEP > 1)
break;
} // for
if(bNumEP < 2)
return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
USBTRACE2("NumEP:", bNumEP);
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
USBTRACE2("Conf:", bConfNum);
// Set Configuration Value
rcode = pUsb->setConf(bAddress, 0, bConfNum);
if(rcode)
goto FailSetConfDescr;
rcode = pAsync->OnInit(this);
if(rcode)
goto FailOnInit;
USBTRACE("FTDI configured\r\n");
ready = true;
return 0;
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr();
goto Fail;
#endif
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry();
goto Fail;
#endif
FailGetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetConfDescr();
goto Fail;
#endif
FailSetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailSetConfDescr();
goto Fail;
#endif
FailOnInit:
#ifdef DEBUG_USB_HOST
USBTRACE("OnInit:");
Fail:
NotifyFail(rcode);
#endif
Release();
return rcode;
}
void FTDI::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto __attribute__((unused)), const USB_ENDPOINT_DESCRIPTOR *pep) {
ErrorMessage<uint8_t > (PSTR("Conf.Val"), conf);
ErrorMessage<uint8_t > (PSTR("Iface Num"), iface);
ErrorMessage<uint8_t > (PSTR("Alt.Set"), alt);
bConfNum = conf;
uint8_t index;
if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_INTERRUPT && (pep->bEndpointAddress & 0x80) == 0x80)
index = epInterruptInIndex;
else if((pep->bmAttributes & bmUSB_TRANSFER_TYPE) == USB_TRANSFER_TYPE_BULK)
index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
else
return;
// Fill in the endpoint info structure
epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
epInfo[index].bmSndToggle = 0;
epInfo[index].bmRcvToggle = 0;
bNumEP++;
PrintEndpointDescriptor(pep);
}
uint8_t FTDI::Release() {
pUsb->GetAddressPool().FreeAddress(bAddress);
bAddress = 0;
bNumEP = 1;
qNextPollTime = 0;
bPollEnable = false;
ready = false;
return pAsync->OnRelease(this);
}
uint8_t FTDI::Poll() {
uint8_t rcode = 0;
//if (!bPollEnable)
// return 0;
//if (qNextPollTime <= (uint32_t)millis())
//{
// USB_HOST_SERIAL.println(bAddress, HEX);
// qNextPollTime = (uint32_t)millis() + 100;
//}
return rcode;
}
uint8_t FTDI::SetBaudRate(uint32_t baud) {
uint16_t baud_value, baud_index = 0;
uint32_t divisor3;
divisor3 = 48000000 / 2 / baud; // divisor shifted 3 bits to the left
if(wFTDIType == FT232AM) {
if((divisor3 & 0x7) == 7)
divisor3++; // round x.7/8 up to x+1
baud_value = divisor3 >> 3;
divisor3 &= 0x7;
if(divisor3 == 1) baud_value |= 0xc000;
else // 0.125
if(divisor3 >= 4) baud_value |= 0x4000;
else // 0.5
if(divisor3 != 0) baud_value |= 0x8000; // 0.25
if(baud_value == 1) baud_value = 0; /* special case for maximum baud rate */
} else {
static const uint8_t divfrac [8] = {0, 3, 2, 0, 1, 1, 2, 3};
static const uint8_t divindex[8] = {0, 0, 0, 1, 0, 1, 1, 1};
baud_value = divisor3 >> 3;
baud_value |= divfrac [divisor3 & 0x7] << 14;
baud_index = divindex[divisor3 & 0x7];
/* Deal with special cases for highest baud rates. */
if(baud_value == 1) baud_value = 0;
else // 1.0
if(baud_value == 0x4001) baud_value = 1; // 1.5
}
USBTRACE2("baud_value:", baud_value);
USBTRACE2("baud_index:", baud_index);
uint8_t rv = pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_SET_BAUD_RATE, baud_value & 0xff, baud_value >> 8, baud_index, 0, 0, NULL, NULL);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t FTDI::SetModemControl(uint16_t signal) {
uint8_t rv = pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_MODEM_CTRL, signal & 0xff, signal >> 8, 0, 0, 0, NULL, NULL);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t FTDI::SetFlowControl(uint8_t protocol, uint8_t xon, uint8_t xoff) {
uint8_t rv = pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_SET_FLOW_CTRL, xon, xoff, protocol << 8, 0, 0, NULL, NULL);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t FTDI::SetData(uint16_t databm) {
uint8_t rv = pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_SET_DATA, databm & 0xff, databm >> 8, 0, 0, 0, NULL, NULL);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t FTDI::RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr) {
uint8_t rv = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
uint8_t FTDI::SndData(uint16_t nbytes, uint8_t *dataptr) {
uint8_t rv = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr);
if(rv && rv != hrNAK) {
Release();
}
return rv;
}
void FTDI::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
Notify(PSTR("Endpoint descriptor:"), 0x80);
Notify(PSTR("\r\nLength:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
Notify(PSTR("\r\nType:\t\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
Notify(PSTR("\r\nAddress:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
Notify(PSTR("\r\nAttributes:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
Notify(PSTR("\r\n"), 0x80);
}

View File

@ -0,0 +1,150 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#if !defined(__CDCFTDI_H__)
#define __CDCFTDI_H__
#include "Usb.h"
#define bmREQ_FTDI_OUT 0x40
#define bmREQ_FTDI_IN 0xc0
//#define bmREQ_FTDI_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
//#define bmREQ_FTDI_IN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
#define FTDI_VID 0x0403 // FTDI VID
#define FTDI_PID 0x6001 // FTDI PID
#define FT232AM 0x0200
#define FT232BM 0x0400
#define FT2232 0x0500
#define FT232R 0x0600
// Commands
#define FTDI_SIO_RESET 0 /* Reset the port */
#define FTDI_SIO_MODEM_CTRL 1 /* Set the modem control register */
#define FTDI_SIO_SET_FLOW_CTRL 2 /* Set flow control register */
#define FTDI_SIO_SET_BAUD_RATE 3 /* Set baud rate */
#define FTDI_SIO_SET_DATA 4 /* Set the data characteristics of the port */
#define FTDI_SIO_GET_MODEM_STATUS 5 /* Retrieve current value of modem status register */
#define FTDI_SIO_SET_EVENT_CHAR 6 /* Set the event character */
#define FTDI_SIO_SET_ERROR_CHAR 7 /* Set the error character */
#define FTDI_SIO_RESET_SIO 0
#define FTDI_SIO_RESET_PURGE_RX 1
#define FTDI_SIO_RESET_PURGE_TX 2
#define FTDI_SIO_SET_DATA_PARITY_NONE (0x0 << 8 )
#define FTDI_SIO_SET_DATA_PARITY_ODD (0x1 << 8 )
#define FTDI_SIO_SET_DATA_PARITY_EVEN (0x2 << 8 )
#define FTDI_SIO_SET_DATA_PARITY_MARK (0x3 << 8 )
#define FTDI_SIO_SET_DATA_PARITY_SPACE (0x4 << 8 )
#define FTDI_SIO_SET_DATA_STOP_BITS_1 (0x0 << 11)
#define FTDI_SIO_SET_DATA_STOP_BITS_15 (0x1 << 11)
#define FTDI_SIO_SET_DATA_STOP_BITS_2 (0x2 << 11)
#define FTDI_SIO_SET_BREAK (0x1 << 14)
#define FTDI_SIO_SET_DTR_MASK 0x1
#define FTDI_SIO_SET_DTR_HIGH ( 1 | ( FTDI_SIO_SET_DTR_MASK << 8))
#define FTDI_SIO_SET_DTR_LOW ( 0 | ( FTDI_SIO_SET_DTR_MASK << 8))
#define FTDI_SIO_SET_RTS_MASK 0x2
#define FTDI_SIO_SET_RTS_HIGH ( 2 | ( FTDI_SIO_SET_RTS_MASK << 8 ))
#define FTDI_SIO_SET_RTS_LOW ( 0 | ( FTDI_SIO_SET_RTS_MASK << 8 ))
#define FTDI_SIO_DISABLE_FLOW_CTRL 0x0
#define FTDI_SIO_RTS_CTS_HS (0x1 << 8)
#define FTDI_SIO_DTR_DSR_HS (0x2 << 8)
#define FTDI_SIO_XON_XOFF_HS (0x4 << 8)
#define FTDI_SIO_CTS_MASK 0x10
#define FTDI_SIO_DSR_MASK 0x20
#define FTDI_SIO_RI_MASK 0x40
#define FTDI_SIO_RLSD_MASK 0x80
class FTDI;
class FTDIAsyncOper {
public:
virtual uint8_t OnInit(FTDI *pftdi __attribute__((unused))) {
return 0;
};
virtual uint8_t OnRelease(FTDI *pftdi __attribute__((unused))) {
return 0;
};
};
// Only single port chips are currently supported by the library,
// so only three endpoints are allocated.
#define FTDI_MAX_ENDPOINTS 3
class FTDI : public USBDeviceConfig, public UsbConfigXtracter {
static const uint8_t epDataInIndex; // DataIn endpoint index
static const uint8_t epDataOutIndex; // DataOUT endpoint index
static const uint8_t epInterruptInIndex; // InterruptIN endpoint index
FTDIAsyncOper *pAsync;
USB *pUsb;
uint8_t bAddress;
uint8_t bConfNum; // configuration number
uint8_t bNumIface; // number of interfaces in the configuration
uint8_t bNumEP; // total number of EP in the configuration
uint32_t qNextPollTime; // next poll time
volatile bool bPollEnable; // poll enable flag
volatile bool ready; //device ready indicator
uint16_t wFTDIType; // Type of FTDI chip
uint16_t wIdProduct; // expected PID
EpInfo epInfo[FTDI_MAX_ENDPOINTS];
void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
public:
FTDI(USB *pusb, FTDIAsyncOper *pasync, uint16_t idProduct = FTDI_PID);
uint8_t SetBaudRate(uint32_t baud);
uint8_t SetModemControl(uint16_t control);
uint8_t SetFlowControl(uint8_t protocol, uint8_t xon = 0x11, uint8_t xoff = 0x13);
uint8_t SetData(uint16_t databm);
// Methods for recieving and sending data
uint8_t RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr);
uint8_t SndData(uint16_t nbytes, uint8_t *dataptr);
// USBDeviceConfig implementation
uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
uint8_t Release();
uint8_t Poll();
virtual uint8_t GetAddress() {
return bAddress;
};
// UsbConfigXtracter implementation
void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
return (vid == FTDI_VID && pid == FTDI_PID);
}
virtual bool isReady() {
return ready;
};
};
#endif // __CDCFTDI_H__

View File

@ -0,0 +1,247 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#include "cdcprolific.h"
PL2303::PL2303(USB *p, CDCAsyncOper *pasync) :
ACM(p, pasync),
wPLType(0) {
}
uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) {
const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
uint8_t buf[constBufSize];
USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
uint8_t rcode;
UsbDevice *p = NULL;
EpInfo *oldep_ptr = NULL;
uint8_t num_of_conf; // number of configurations
#ifdef PL2303_COMPAT
enum pl2303_type pltype = unknown;
#endif
AddressPool &addrPool = pUsb->GetAddressPool();
USBTRACE("PL Init\r\n");
if(bAddress)
return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
// Get pointer to pseudo device with address 0 assigned
p = addrPool.GetUsbDevicePtr(0);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
if(!p->epinfo) {
USBTRACE("epinfo\r\n");
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);
// Restore p->epinfo
p->epinfo = oldep_ptr;
if(rcode)
goto FailGetDevDescr;
if(udd->idVendor != PL_VID && CHECK_PID(udd->idProduct))
return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
/* determine chip variant */
#ifdef PL2303_COMPAT
if(udd->bDeviceClass == 0x02 )
pltype = type_0;
else if(udd->bMaxPacketSize0 == 0x40 )
pltype = rev_HX;
else if(udd->bDeviceClass == 0x00)
pltype = type_1;
else if(udd->bDeviceClass == 0xff)
pltype = type_1;
#endif
// Save type of PL chip
wPLType = udd->bcdDevice;
// 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 the 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;
USBTRACE2("setAddr:", rcode);
return rcode;
}
USBTRACE2("Addr:", bAddress);
p->lowspeed = false;
p = addrPool.GetUsbDevicePtr(bAddress);
if(!p)
return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
p->lowspeed = lowspeed;
num_of_conf = udd->bNumConfigurations;
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
if(rcode)
goto FailSetDevTblEntry;
USBTRACE2("NC:", num_of_conf);
for(uint8_t i = 0; i < num_of_conf; i++) {
HexDumper<USBReadParser, uint16_t, uint16_t> HexDump;
ConfigDescParser < 0xFF, 0, 0, CP_MASK_COMPARE_CLASS> confDescrParser(this);
rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump);
if(rcode)
goto FailGetConfDescr;
rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
if(rcode)
goto FailGetConfDescr;
if(bNumEP > 1)
break;
} // for
if(bNumEP < 2)
return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
// Assign epInfo to epinfo pointer
rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
USBTRACE2("Conf:", bConfNum);
// Set Configuration Value
rcode = pUsb->setConf(bAddress, 0, bConfNum);
if(rcode)
goto FailSetConfDescr;
#ifdef PL2303_COMPAT
/* Shamanic dance - sending Prolific init data as-is */
vendorRead( 0x84, 0x84, 0, buf );
vendorWrite( 0x04, 0x04, 0 );
vendorRead( 0x84, 0x84, 0, buf );
vendorRead( 0x83, 0x83, 0, buf );
vendorRead( 0x84, 0x84, 0, buf );
vendorWrite( 0x04, 0x04, 1 );
vendorRead( 0x84, 0x84, 0, buf);
vendorRead( 0x83, 0x83, 0, buf);
vendorWrite( 0, 0, 1 );
vendorWrite( 1, 0, 0 );
if( pltype == rev_HX ) {
vendorWrite( 2, 0, 0x44 );
vendorWrite( 0x06, 0x06, 0 ); // From W7 init
}
else {
vendorWrite( 2, 0, 0x24 );
}
/* Shamanic dance end */
#endif
/* Calling post-init callback */
rcode = pAsync->OnInit(this);
if(rcode)
goto FailOnInit;
USBTRACE("PL configured\r\n");
//bPollEnable = true;
ready = true;
return 0;
FailGetDevDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetDevDescr();
goto Fail;
#endif
FailSetDevTblEntry:
#ifdef DEBUG_USB_HOST
NotifyFailSetDevTblEntry();
goto Fail;
#endif
FailGetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailGetConfDescr();
goto Fail;
#endif
FailSetConfDescr:
#ifdef DEBUG_USB_HOST
NotifyFailSetConfDescr();
goto Fail;
#endif
FailOnInit:
#ifdef DEBUG_USB_HOST
USBTRACE("OnInit:");
#endif
#ifdef DEBUG_USB_HOST
Fail:
NotifyFail(rcode);
#endif
Release();
return rcode;
}
//uint8_t PL::Poll()
//{
// uint8_t rcode = 0;
//
// //if (!bPollEnable)
// // return 0;
//
// //if (qNextPollTime <= (uint32_t)millis())
// //{
// // USB_HOST_SERIAL.println(bAddress, HEX);
//
// // qNextPollTime = (uint32_t)millis() + 100;
// //}
// return rcode;
//}

View File

@ -0,0 +1,159 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#if !defined(__CDCPROLIFIC_H__)
#define __CDCPROLIFIC_H__
#include "cdcacm.h"
//#define PL2303_COMPAT // Uncomment it if you have compatibility problems
#define PL_VID 0x067B
#define CHECK_PID(pid) ( pid != 0x2303 && pid != 0x0609 )
//#define PL_PID 0x0609
#define PROLIFIC_REV_H 0x0202
#define PROLIFIC_REV_X 0x0300
#define PROLIFIC_REV_HX_CHIP_D 0x0400
#define PROLIFIC_REV_1 0x0001
#define kXOnChar '\x11'
#define kXOffChar '\x13'
#define SPECIAL_SHIFT (5)
#define SPECIAL_MASK ((1<<SPECIAL_SHIFT) - 1)
#define STATE_ALL ( PD_RS232_S_MASK | PD_S_MASK )
#define FLOW_RX_AUTO ( PD_RS232_A_RFR | PD_RS232_A_DTR | PD_RS232_A_RXO )
#define FLOW_TX_AUTO ( PD_RS232_A_CTS | PD_RS232_A_DSR | PD_RS232_A_TXO | PD_RS232_A_DCD )
#define CAN_BE_AUTO ( FLOW_RX_AUTO | FLOW_TX_AUTO )
#define CAN_NOTIFY ( PD_RS232_N_MASK )
#define EXTERNAL_MASK ( PD_S_MASK | (PD_RS232_S_MASK & ~PD_RS232_S_LOOP) )
#define INTERNAL_DELAY ( PD_RS232_S_LOOP )
#define DEFAULT_AUTO ( PD_RS232_A_DTR | PD_RS232_A_RFR | PD_RS232_A_CTS | PD_RS232_A_DSR )
#define DEFAULT_NOTIFY 0x00
#define DEFAULT_STATE ( PD_S_TX_ENABLE | PD_S_RX_ENABLE | PD_RS232_A_TXO | PD_RS232_A_RXO )
#define CONTINUE_SEND 1
#define PAUSE_SEND 2
#define kRxAutoFlow ((UInt32)( PD_RS232_A_RFR | PD_RS232_A_DTR | PD_RS232_A_RXO ))
#define kTxAutoFlow ((UInt32)( PD_RS232_A_CTS | PD_RS232_A_DSR | PD_RS232_A_TXO | PD_RS232_A_DCD ))
#define kControl_StateMask ((UInt32)( PD_RS232_S_CTS | PD_RS232_S_DSR | PD_RS232_S_CAR | PD_RS232_S_RI ))
#define kRxQueueState ((UInt32)( PD_S_RXQ_EMPTY | PD_S_RXQ_LOW_WATER | PD_S_RXQ_HIGH_WATER | PD_S_RXQ_FULL ))
#define kTxQueueState ((UInt32)( PD_S_TXQ_EMPTY | PD_S_TXQ_LOW_WATER | PD_S_TXQ_HIGH_WATER | PD_S_TXQ_FULL ))
#define kCONTROL_DTR 0x01
#define kCONTROL_RTS 0x02
#define kStateTransientMask 0x74
#define kBreakError 0x04
#define kFrameError 0x10
#define kParityError 0x20
#define kOverrunError 0x40
#define kCTS 0x80
#define kDSR 0x02
#define kRI 0x08
#define kDCD 0x01
#define kHandshakeInMask ((UInt32)( PD_RS232_S_CTS | PD_RS232_S_DSR | PD_RS232_S_CAR | PD_RS232_S_RI ))
#define VENDOR_WRITE_REQUEST_TYPE 0x40
#define VENDOR_WRITE_REQUEST 0x01
#define VENDOR_READ_REQUEST_TYPE 0xc0
#define VENDOR_READ_REQUEST 0x01
// Device Configuration Registers (DCR0, DCR1, DCR2)
#define SET_DCR0 0x00
#define GET_DCR0 0x80
#define DCR0_INIT 0x01
#define DCR0_INIT_H 0x41
#define DCR0_INIT_X 0x61
#define SET_DCR1 0x01
#define GET_DCR1 0x81
#define DCR1_INIT_H 0x80
#define DCR1_INIT_X 0x00
#define SET_DCR2 0x02
#define GET_DCR2 0x82
#define DCR2_INIT_H 0x24
#define DCR2_INIT_X 0x44
// On-chip Data Buffers:
#define RESET_DOWNSTREAM_DATA_PIPE 0x08
#define RESET_UPSTREAM_DATA_PIPE 0x09
#define PL_MAX_ENDPOINTS 4
enum tXO_State {
kXOnSent = -2,
kXOffSent = -1,
kXO_Idle = 0,
kXOffNeeded = 1,
kXOnNeeded = 2
};
enum pl2303_type {
unknown,
type_0, /* don't know the difference between type 0 and */
type_1, /* type 1, until someone from prolific tells us... */
rev_X,
rev_HX, /* HX version of the pl2303 chip */
rev_H
};
class PL2303 : public ACM {
uint16_t wPLType; // Type of chip
public:
PL2303(USB *pusb, CDCAsyncOper *pasync);
// USBDeviceConfig implementation
uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
//virtual uint8_t Release();
//virtual uint8_t Poll();
//virtual uint8_t GetAddress() { return bAddress; };
//// UsbConfigXtracter implementation
//virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
#ifdef PL2303_COMPAT
private:
/* Prolific proprietary requests */
uint8_t vendorRead( uint8_t val_lo, uint8_t val_hi, uint16_t index, uint8_t* buf );
uint8_t vendorWrite( uint8_t val_lo, uint8_t val_hi, uint8_t index );
#endif
};
#ifdef PL2303_COMPAT
/* vendor read request */
inline uint8_t PL2303::vendorRead( uint8_t val_lo, uint8_t val_hi, uint16_t index, uint8_t* buf )
{
return( pUsb->ctrlReq(bAddress, 0, VENDOR_READ_REQUEST_TYPE, VENDOR_READ_REQUEST, val_lo, val_hi, index, 1, 1, buf, NULL ));
}
/* vendor write request */
inline uint8_t PL2303::vendorWrite( uint8_t val_lo, uint8_t val_hi, uint8_t index )
{
return( pUsb->ctrlReq(bAddress, 0, VENDOR_WRITE_REQUEST_TYPE, VENDOR_WRITE_REQUEST, val_lo, val_hi, index, 0, 0, NULL, NULL ));
}
#endif
#endif // __CDCPROLIFIC_H__

View File

@ -0,0 +1,210 @@
/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
This software may be distributed and modified under the terms of the GNU
General Public License version 2 (GPL2) as published by the Free Software
Foundation and appearing in the file GPL2.TXT included in the packaging of
this file. Please note that GPL2 Section 2[b] requires that all works based
on this software must also be made publicly available under the terms of
the GPL2 ("Copyleft").
Contact information
-------------------
Circuits At Home, LTD
Web : http://www.circuitsathome.com
e-mail : support@circuitsathome.com
*/
#if !defined(_usb_h_) || defined(__CONFDESCPARSER_H__)
#error "Never include confdescparser.h directly; include Usb.h instead"
#else
#define __CONFDESCPARSER_H__
class UsbConfigXtracter {
public:
//virtual void ConfigXtract(const USB_CONFIGURATION_DESCRIPTOR *conf) = 0;
//virtual void InterfaceXtract(uint8_t conf, const USB_INTERFACE_DESCRIPTOR *iface) = 0;
virtual void EndpointXtract(uint8_t conf __attribute__((unused)), uint8_t iface __attribute__((unused)), uint8_t alt __attribute__((unused)), uint8_t proto __attribute__((unused)), const USB_ENDPOINT_DESCRIPTOR *ep __attribute__((unused))) {
};
};
#define CP_MASK_COMPARE_CLASS 1
#define CP_MASK_COMPARE_SUBCLASS 2
#define CP_MASK_COMPARE_PROTOCOL 4
#define CP_MASK_COMPARE_ALL 7
// Configuration Descriptor Parser Class Template
template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
class ConfigDescParser : public USBReadParser {
UsbConfigXtracter *theXtractor;
MultiValueBuffer theBuffer;
MultiByteValueParser valParser;
ByteSkipper theSkipper;
uint8_t varBuffer[16 /*sizeof(USB_CONFIGURATION_DESCRIPTOR)*/];
uint8_t stateParseDescr; // ParseDescriptor state
uint8_t dscrLen; // Descriptor length
uint8_t dscrType; // Descriptor type
bool isGoodInterface; // Apropriate interface flag
uint8_t confValue; // Configuration value
uint8_t protoValue; // Protocol value
uint8_t ifaceNumber; // Interface number
uint8_t ifaceAltSet; // Interface alternate settings
bool UseOr;
bool ParseDescriptor(uint8_t **pp, uint16_t *pcntdn);
void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc);
public:
void SetOR(void) {
UseOr = true;
}
ConfigDescParser(UsbConfigXtracter *xtractor);
void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset);
};
template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::ConfigDescParser(UsbConfigXtracter *xtractor) :
theXtractor(xtractor),
stateParseDescr(0),
dscrLen(0),
dscrType(0),
UseOr(false) {
theBuffer.pValue = varBuffer;
valParser.Initialize(&theBuffer);
theSkipper.Initialize(&theBuffer);
};
template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
void ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset __attribute__((unused))) {
uint16_t cntdn = (uint16_t)len;
uint8_t *p = (uint8_t*)pbuf;
while(cntdn)
if(!ParseDescriptor(&p, &cntdn))
return;
}
/* Parser for the configuration descriptor. Takes values for class, subclass, protocol fields in interface descriptor and
compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */
template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
bool ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::ParseDescriptor(uint8_t **pp, uint16_t *pcntdn) {
USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast<USB_CONFIGURATION_DESCRIPTOR*>(varBuffer);
USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast<USB_INTERFACE_DESCRIPTOR*>(varBuffer);
switch(stateParseDescr) {
case 0:
theBuffer.valueSize = 2;
valParser.Initialize(&theBuffer);
stateParseDescr = 1;
case 1:
if(!valParser.Parse(pp, pcntdn))
return false;
dscrLen = *((uint8_t*)theBuffer.pValue);
dscrType = *((uint8_t*)theBuffer.pValue + 1);
stateParseDescr = 2;
case 2:
// This is a sort of hack. Assuming that two bytes are all ready in the buffer
// the pointer is positioned two bytes ahead in order for the rest of descriptor
// to be read right after the size and the type fields.
// This should be used carefully. varBuffer should be used directly to handle data
// in the buffer.
theBuffer.pValue = varBuffer + 2;
stateParseDescr = 3;
case 3:
switch(dscrType) {
case USB_DESCRIPTOR_INTERFACE:
isGoodInterface = false;
break;
case USB_DESCRIPTOR_CONFIGURATION:
case USB_DESCRIPTOR_ENDPOINT:
case HID_DESCRIPTOR_HID:
break;
}
theBuffer.valueSize = dscrLen - 2;
valParser.Initialize(&theBuffer);
stateParseDescr = 4;
case 4:
switch(dscrType) {
case USB_DESCRIPTOR_CONFIGURATION:
if(!valParser.Parse(pp, pcntdn))
return false;
confValue = ucd->bConfigurationValue;
break;
case USB_DESCRIPTOR_INTERFACE:
if(!valParser.Parse(pp, pcntdn))
return false;
if((MASK & CP_MASK_COMPARE_CLASS) && uid->bInterfaceClass != CLASS_ID)
break;
if((MASK & CP_MASK_COMPARE_SUBCLASS) && uid->bInterfaceSubClass != SUBCLASS_ID)
break;
if(UseOr) {
if((!((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol)))
break;
} else {
if((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID)
break;
}
isGoodInterface = true;
ifaceNumber = uid->bInterfaceNumber;
ifaceAltSet = uid->bAlternateSetting;
protoValue = uid->bInterfaceProtocol;
break;
case USB_DESCRIPTOR_ENDPOINT:
if(!valParser.Parse(pp, pcntdn))
return false;
if(isGoodInterface)
if(theXtractor)
theXtractor->EndpointXtract(confValue, ifaceNumber, ifaceAltSet, protoValue, (USB_ENDPOINT_DESCRIPTOR*)varBuffer);
break;
//case HID_DESCRIPTOR_HID:
// if (!valParser.Parse(pp, pcntdn))
// return false;
// PrintHidDescriptor((const USB_HID_DESCRIPTOR*)varBuffer);
// break;
default:
if(!theSkipper.Skip(pp, pcntdn, dscrLen - 2))
return false;
}
theBuffer.pValue = varBuffer;
stateParseDescr = 0;
}
return true;
}
template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
void ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) {
Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80);
Notify(PSTR("bDescLength:\t\t"), 0x80);
PrintHex<uint8_t > (pDesc->bLength, 0x80);
Notify(PSTR("\r\nbDescriptorType:\t"), 0x80);
PrintHex<uint8_t > (pDesc->bDescriptorType, 0x80);
Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80);
PrintHex<uint16_t > (pDesc->bcdHID, 0x80);
Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80);
PrintHex<uint8_t > (pDesc->bCountryCode, 0x80);
Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80);
PrintHex<uint8_t > (pDesc->bNumDescriptors, 0x80);
for(uint8_t i = 0; i < pDesc->bNumDescriptors; i++) {
HID_CLASS_DESCRIPTOR_LEN_AND_TYPE *pLT = (HID_CLASS_DESCRIPTOR_LEN_AND_TYPE*)&(pDesc->bDescrType);
Notify(PSTR("\r\nbDescrType:\t\t"), 0x80);
PrintHex<uint8_t > (pLT[i].bDescrType, 0x80);
Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80);
PrintHex<uint16_t > (pLT[i].wDescriptorLength, 0x80);
}
Notify(PSTR("\r\n"), 0x80);
}
#endif // __CONFDESCPARSER_H__

View File

@ -0,0 +1,210 @@
/* 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 _controllerenums_h
#define _controllerenums_h
#if defined(ESP32)
#undef PS
#endif
/**
* This header file is used to store different enums for the controllers,
* This is necessary so all the different libraries can be used at once.
*/
/** Enum used to turn on the LEDs on the different controllers. */
enum LEDEnum {
OFF = 0,
#ifndef RBL_NRF51822
LED1 = 1,
LED2 = 2,
LED3 = 3,
LED4 = 4,
#endif
LED5 = 5,
LED6 = 6,
LED7 = 7,
LED8 = 8,
LED9 = 9,
LED10 = 10,
/** Used to blink all LEDs on the Xbox controller */
ALL = 5,
};
/** Used to set the colors of the Move and PS4 controller. */
enum ColorsEnum {
/** r = 255, g = 0, b = 0 */
Red = 0xFF0000,
/** r = 0, g = 255, b = 0 */
Green = 0xFF00,
/** r = 0, g = 0, b = 255 */
Blue = 0xFF,
/** r = 255, g = 235, b = 4 */
Yellow = 0xFFEB04,
/** r = 0, g = 255, b = 255 */
Lightblue = 0xFFFF,
/** r = 255, g = 0, b = 255 */
Purple = 0xFF00FF,
Purble = 0xFF00FF,
/** r = 255, g = 255, b = 255 */
White = 0xFFFFFF,
/** r = 0, g = 0, b = 0 */
Off = 0x00,
};
enum RumbleEnum {
RumbleHigh = 0x10,
RumbleLow = 0x20,
};
/** This enum is used to read all the different buttons on the different controllers */
enum ButtonEnum {
/**@{*/
/** These buttons are available on all the the controllers */
UP = 0,
RIGHT = 1,
DOWN = 2,
LEFT = 3,
/**@}*/
/**@{*/
/** Wii buttons */
PLUS = 5,
TWO = 6,
ONE = 7,
MINUS = 8,
HOME = 9,
Z = 10,
C = 11,
B = 12,
A = 13,
/**@}*/
/**@{*/
/** These are only available on the Wii U Pro Controller */
L = 16,
R = 17,
ZL = 18,
ZR = 19,
/**@}*/
/**@{*/
/** PS3 controllers buttons */
SELECT = 4,
START = 5,
L3 = 6,
R3 = 7,
L2 = 8,
R2 = 9,
L1 = 10,
R1 = 11,
TRIANGLE = 12,
CIRCLE = 13,
CROSS = 14,
SQUARE = 15,
PS = 16,
MOVE = 17, // Covers 12 bits - we only need to read the top 8
T = 18, // Covers 12 bits - we only need to read the top 8
/**@}*/
/** PS4 controllers buttons - SHARE and OPTIONS are present instead of SELECT and START */
SHARE = 4,
OPTIONS = 5,
TOUCHPAD = 17,
/**@}*/
/**@{*/
/** Xbox buttons */
BACK = 4,
X = 14,
Y = 15,
XBOX = 16,
SYNC = 17,
BLACK = 8, // Available on the original Xbox controller
WHITE = 9, // Available on the original Xbox controller
/**@}*/
/** PS Buzz controllers */
RED = 0,
YELLOW = 1,
GREEN = 2,
ORANGE = 3,
BLUE = 4,
/**@}*/
};
/** Joysticks on the PS3 and Xbox controllers. */
enum AnalogHatEnum {
/** Left joystick x-axis */
LeftHatX = 0,
/** Left joystick y-axis */
LeftHatY = 1,
/** Right joystick x-axis */
RightHatX = 2,
/** Right joystick y-axis */
RightHatY = 3,
};
/**
* Sensors inside the Sixaxis Dualshock 3, Move controller and PS4 controller.
* <B>Note:</B> that the location is shifted 9 when it's connected via USB on the PS3 controller.
*/
enum SensorEnum {
/** Accelerometer values */
aX = 50, aY = 52, aZ = 54,
/** Gyro z-axis */
gZ = 56,
gX, gY, // These are not available on the PS3 controller
/** Accelerometer x-axis */
aXmove = 28,
/** Accelerometer z-axis */
aZmove = 30,
/** Accelerometer y-axis */
aYmove = 32,
/** Gyro x-axis */
gXmove = 40,
/** Gyro z-axis */
gZmove = 42,
/** Gyro y-axis */
gYmove = 44,
/** Temperature sensor */
tempMove = 46,
/** Magnetometer x-axis */
mXmove = 47,
/** Magnetometer z-axis */
mZmove = 49,
/** Magnetometer y-axis */
mYmove = 50,
};
/** Used to get the angle calculated using the PS3 controller and PS4 controller. */
enum AngleEnum {
Pitch = 0x01,
Roll = 0x02,
};
#endif

View File

@ -0,0 +1,55 @@
/*
Example sketch for the HID Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <BTHID.h>
#include <usbhub.h>
#include "KeyboardParser.h"
#include "MouseParser.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
// This will start an inquiry and then pair with your device - you only have to do this once
// If you are using a Bluetooth keyboard, then you should type in the password on the keypad and then press enter
BTHID bthid(&Btd, PAIR, "0000");
// After that you can simply create the instance like so and then press any button on the device
//BTHID hid(&Btd);
KbdRptParser keyboardPrs;
MouseRptParser mousePrs;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); // Halt
}
bthid.SetReportParser(KEYBOARD_PARSER_ID, &keyboardPrs);
bthid.SetReportParser(MOUSE_PARSER_ID, &mousePrs);
// If "Boot Protocol Mode" does not work, then try "Report Protocol Mode"
// If that does not work either, then uncomment PRINTREPORT in BTHID.cpp to see the raw report
bthid.setProtocolMode(USB_HID_BOOT_PROTOCOL); // Boot Protocol Mode
//bthid.setProtocolMode(HID_RPT_PROTOCOL); // Report Protocol Mode
Serial.print(F("\r\nHID Bluetooth Library Started"));
}
void loop() {
Usb.Task();
}

View File

@ -0,0 +1,105 @@
#ifndef __kbdrptparser_h_
#define __kbdrptparser_h_
class KbdRptParser : public KeyboardReportParser {
protected:
virtual uint8_t HandleLockingKeys(USBHID *hid, uint8_t key);
virtual void OnControlKeysChanged(uint8_t before, uint8_t after);
virtual void OnKeyDown(uint8_t mod, uint8_t key);
virtual void OnKeyUp(uint8_t mod, uint8_t key);
virtual void OnKeyPressed(uint8_t key);
private:
void PrintKey(uint8_t mod, uint8_t key);
};
uint8_t KbdRptParser::HandleLockingKeys(USBHID *hid, uint8_t key) {
uint8_t old_keys = kbdLockingKeys.bLeds;
switch (key) {
case UHS_HID_BOOT_KEY_NUM_LOCK:
Serial.println(F("Num lock"));
kbdLockingKeys.kbdLeds.bmNumLock = ~kbdLockingKeys.kbdLeds.bmNumLock;
break;
case UHS_HID_BOOT_KEY_CAPS_LOCK:
Serial.println(F("Caps lock"));
kbdLockingKeys.kbdLeds.bmCapsLock = ~kbdLockingKeys.kbdLeds.bmCapsLock;
break;
case UHS_HID_BOOT_KEY_SCROLL_LOCK:
Serial.println(F("Scroll lock"));
kbdLockingKeys.kbdLeds.bmScrollLock = ~kbdLockingKeys.kbdLeds.bmScrollLock;
break;
}
if (old_keys != kbdLockingKeys.bLeds && hid) {
BTHID *pBTHID = reinterpret_cast<BTHID *> (hid); // A cast the other way around is done in BTHID.cpp
pBTHID->setLeds(kbdLockingKeys.bLeds); // Update the LEDs on the keyboard
}
return 0;
};
void KbdRptParser::PrintKey(uint8_t m, uint8_t key) {
MODIFIERKEYS mod;
*((uint8_t*)&mod) = m;
Serial.print((mod.bmLeftCtrl == 1) ? F("C") : F(" "));
Serial.print((mod.bmLeftShift == 1) ? F("S") : F(" "));
Serial.print((mod.bmLeftAlt == 1) ? F("A") : F(" "));
Serial.print((mod.bmLeftGUI == 1) ? F("G") : F(" "));
Serial.print(F(" >"));
PrintHex<uint8_t>(key, 0x80);
Serial.print(F("< "));
Serial.print((mod.bmRightCtrl == 1) ? F("C") : F(" "));
Serial.print((mod.bmRightShift == 1) ? F("S") : F(" "));
Serial.print((mod.bmRightAlt == 1) ? F("A") : F(" "));
Serial.println((mod.bmRightGUI == 1) ? F("G") : F(" "));
};
void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key) {
Serial.print(F("DN "));
PrintKey(mod, key);
uint8_t c = OemToAscii(mod, key);
if (c)
OnKeyPressed(c);
};
void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after) {
MODIFIERKEYS beforeMod;
*((uint8_t*)&beforeMod) = before;
MODIFIERKEYS afterMod;
*((uint8_t*)&afterMod) = after;
if (beforeMod.bmLeftCtrl != afterMod.bmLeftCtrl)
Serial.println(F("LeftCtrl changed"));
if (beforeMod.bmLeftShift != afterMod.bmLeftShift)
Serial.println(F("LeftShift changed"));
if (beforeMod.bmLeftAlt != afterMod.bmLeftAlt)
Serial.println(F("LeftAlt changed"));
if (beforeMod.bmLeftGUI != afterMod.bmLeftGUI)
Serial.println(F("LeftGUI changed"));
if (beforeMod.bmRightCtrl != afterMod.bmRightCtrl)
Serial.println(F("RightCtrl changed"));
if (beforeMod.bmRightShift != afterMod.bmRightShift)
Serial.println(F("RightShift changed"));
if (beforeMod.bmRightAlt != afterMod.bmRightAlt)
Serial.println(F("RightAlt changed"));
if (beforeMod.bmRightGUI != afterMod.bmRightGUI)
Serial.println(F("RightGUI changed"));
};
void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key) {
Serial.print(F("UP "));
PrintKey(mod, key);
};
void KbdRptParser::OnKeyPressed(uint8_t key) {
Serial.print(F("ASCII: "));
Serial.println((char)key);
};
#endif

View File

@ -0,0 +1,46 @@
#ifndef __mouserptparser_h__
#define __mouserptparser_h__
class MouseRptParser : public MouseReportParser {
protected:
virtual void OnMouseMove(MOUSEINFO *mi);
virtual void OnLeftButtonUp(MOUSEINFO *mi);
virtual void OnLeftButtonDown(MOUSEINFO *mi);
virtual void OnRightButtonUp(MOUSEINFO *mi);
virtual void OnRightButtonDown(MOUSEINFO *mi);
virtual void OnMiddleButtonUp(MOUSEINFO *mi);
virtual void OnMiddleButtonDown(MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi) {
Serial.print(F("dx="));
Serial.print(mi->dX, DEC);
Serial.print(F(" dy="));
Serial.println(mi->dY, DEC);
};
void MouseRptParser::OnLeftButtonUp(MOUSEINFO *mi) {
Serial.println(F("L Butt Up"));
};
void MouseRptParser::OnLeftButtonDown(MOUSEINFO *mi) {
Serial.println(F("L Butt Dn"));
};
void MouseRptParser::OnRightButtonUp(MOUSEINFO *mi) {
Serial.println(F("R Butt Up"));
};
void MouseRptParser::OnRightButtonDown(MOUSEINFO *mi) {
Serial.println(F("R Butt Dn"));
};
void MouseRptParser::OnMiddleButtonUp(MOUSEINFO *mi) {
Serial.println(F("M Butt Up"));
};
void MouseRptParser::OnMiddleButtonDown(MOUSEINFO *mi) {
Serial.println(F("M Butt Dn"));
};
#endif

View File

@ -0,0 +1,192 @@
/*
Example sketch for the PS3 Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <PS3BT.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
PS3BT PS3(&Btd); // This will just create the instance
//PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch
bool printTemperature, printAngle;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nPS3 Bluetooth Library Started"));
}
void loop() {
Usb.Task();
if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
Serial.print(F("\r\nLeftHatX: "));
Serial.print(PS3.getAnalogHat(LeftHatX));
Serial.print(F("\tLeftHatY: "));
Serial.print(PS3.getAnalogHat(LeftHatY));
if (PS3.PS3Connected) { // The Navigation controller only have one joystick
Serial.print(F("\tRightHatX: "));
Serial.print(PS3.getAnalogHat(RightHatX));
Serial.print(F("\tRightHatY: "));
Serial.print(PS3.getAnalogHat(RightHatY));
}
}
// Analog button values can be read from almost all buttons
if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
Serial.print(F("\r\nL2: "));
Serial.print(PS3.getAnalogButton(L2));
if (PS3.PS3Connected) {
Serial.print(F("\tR2: "));
Serial.print(PS3.getAnalogButton(R2));
}
}
if (PS3.getButtonClick(PS)) {
Serial.print(F("\r\nPS"));
PS3.disconnect();
}
else {
if (PS3.getButtonClick(TRIANGLE)) {
Serial.print(F("\r\nTraingle"));
PS3.setRumbleOn(RumbleLow);
}
if (PS3.getButtonClick(CIRCLE)) {
Serial.print(F("\r\nCircle"));
PS3.setRumbleOn(RumbleHigh);
}
if (PS3.getButtonClick(CROSS))
Serial.print(F("\r\nCross"));
if (PS3.getButtonClick(SQUARE))
Serial.print(F("\r\nSquare"));
if (PS3.getButtonClick(UP)) {
Serial.print(F("\r\nUp"));
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED4);
}
}
if (PS3.getButtonClick(RIGHT)) {
Serial.print(F("\r\nRight"));
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED1);
}
}
if (PS3.getButtonClick(DOWN)) {
Serial.print(F("\r\nDown"));
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED2);
}
}
if (PS3.getButtonClick(LEFT)) {
Serial.print(F("\r\nLeft"));
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED3);
}
}
if (PS3.getButtonClick(L1))
Serial.print(F("\r\nL1"));
if (PS3.getButtonClick(L3))
Serial.print(F("\r\nL3"));
if (PS3.getButtonClick(R1))
Serial.print(F("\r\nR1"));
if (PS3.getButtonClick(R3))
Serial.print(F("\r\nR3"));
if (PS3.getButtonClick(SELECT)) {
Serial.print(F("\r\nSelect - "));
PS3.printStatusString();
}
if (PS3.getButtonClick(START)) {
Serial.print(F("\r\nStart"));
printAngle = !printAngle;
}
}
#if 0 // Set this to 1 in order to see the angle of the controller
if (printAngle) {
Serial.print(F("\r\nPitch: "));
Serial.print(PS3.getAngle(Pitch));
Serial.print(F("\tRoll: "));
Serial.print(PS3.getAngle(Roll));
}
#endif
}
#if 0 // Set this to 1 in order to enable support for the Playstation Move controller
else if (PS3.PS3MoveConnected) {
if (PS3.getAnalogButton(T)) {
Serial.print(F("\r\nT: "));
Serial.print(PS3.getAnalogButton(T));
}
if (PS3.getButtonClick(PS)) {
Serial.print(F("\r\nPS"));
PS3.disconnect();
}
else {
if (PS3.getButtonClick(SELECT)) {
Serial.print(F("\r\nSelect"));
printTemperature = !printTemperature;
}
if (PS3.getButtonClick(START)) {
Serial.print(F("\r\nStart"));
printAngle = !printAngle;
}
if (PS3.getButtonClick(TRIANGLE)) {
Serial.print(F("\r\nTriangle"));
PS3.moveSetBulb(Red);
}
if (PS3.getButtonClick(CIRCLE)) {
Serial.print(F("\r\nCircle"));
PS3.moveSetBulb(Green);
}
if (PS3.getButtonClick(SQUARE)) {
Serial.print(F("\r\nSquare"));
PS3.moveSetBulb(Blue);
}
if (PS3.getButtonClick(CROSS)) {
Serial.print(F("\r\nCross"));
PS3.moveSetBulb(Yellow);
}
if (PS3.getButtonClick(MOVE)) {
PS3.moveSetBulb(Off);
Serial.print(F("\r\nMove"));
Serial.print(F(" - "));
PS3.printStatusString();
}
}
if (printAngle) {
Serial.print(F("\r\nPitch: "));
Serial.print(PS3.getAngle(Pitch));
Serial.print(F("\tRoll: "));
Serial.print(PS3.getAngle(Roll));
}
else if (printTemperature) {
Serial.print(F("\r\nTemperature: "));
Serial.print(PS3.getTemperature());
}
}
#endif
}

View File

@ -0,0 +1,149 @@
/*
Example sketch for the PS3 Bluetooth library - developed by Kristian Lauszus
This example show how one can use multiple controllers with the library
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <PS3BT.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
PS3BT *PS3[2]; // We will use this pointer to store the two instance, you can easily make it larger if you like, but it will use a lot of RAM!
const uint8_t length = sizeof(PS3) / sizeof(PS3[0]); // Get the lenght of the array
bool printAngle[length];
bool oldControllerState[length];
void setup() {
for (uint8_t i = 0; i < length; i++) {
PS3[i] = new PS3BT(&Btd); // Create the instances
PS3[i]->attachOnInit(onInit); // onInit() is called upon a new connection - you can call the function whatever you like
}
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nPS3 Bluetooth Library Started"));
}
void loop() {
Usb.Task();
for (uint8_t i = 0; i < length; i++) {
if (PS3[i]->PS3Connected || PS3[i]->PS3NavigationConnected) {
if (PS3[i]->getAnalogHat(LeftHatX) > 137 || PS3[i]->getAnalogHat(LeftHatX) < 117 || PS3[i]->getAnalogHat(LeftHatY) > 137 || PS3[i]->getAnalogHat(LeftHatY) < 117 || PS3[i]->getAnalogHat(RightHatX) > 137 || PS3[i]->getAnalogHat(RightHatX) < 117 || PS3[i]->getAnalogHat(RightHatY) > 137 || PS3[i]->getAnalogHat(RightHatY) < 117) {
Serial.print(F("\r\nLeftHatX: "));
Serial.print(PS3[i]->getAnalogHat(LeftHatX));
Serial.print(F("\tLeftHatY: "));
Serial.print(PS3[i]->getAnalogHat(LeftHatY));
if (PS3[i]->PS3Connected) { // The Navigation controller only have one joystick
Serial.print(F("\tRightHatX: "));
Serial.print(PS3[i]->getAnalogHat(RightHatX));
Serial.print(F("\tRightHatY: "));
Serial.print(PS3[i]->getAnalogHat(RightHatY));
}
}
//Analog button values can be read from almost all buttons
if (PS3[i]->getAnalogButton(L2) || PS3[i]->getAnalogButton(R2)) {
Serial.print(F("\r\nL2: "));
Serial.print(PS3[i]->getAnalogButton(L2));
if (PS3[i]->PS3Connected) {
Serial.print(F("\tR2: "));
Serial.print(PS3[i]->getAnalogButton(R2));
}
}
if (PS3[i]->getButtonClick(PS)) {
Serial.print(F("\r\nPS"));
PS3[i]->disconnect();
oldControllerState[i] = false; // Reset value
}
else {
if (PS3[i]->getButtonClick(TRIANGLE))
Serial.print(F("\r\nTraingle"));
if (PS3[i]->getButtonClick(CIRCLE))
Serial.print(F("\r\nCircle"));
if (PS3[i]->getButtonClick(CROSS))
Serial.print(F("\r\nCross"));
if (PS3[i]->getButtonClick(SQUARE))
Serial.print(F("\r\nSquare"));
if (PS3[i]->getButtonClick(UP)) {
Serial.print(F("\r\nUp"));
if (PS3[i]->PS3Connected) {
PS3[i]->setLedOff();
PS3[i]->setLedOn(LED4);
}
}
if (PS3[i]->getButtonClick(RIGHT)) {
Serial.print(F("\r\nRight"));
if (PS3[i]->PS3Connected) {
PS3[i]->setLedOff();
PS3[i]->setLedOn(LED1);
}
}
if (PS3[i]->getButtonClick(DOWN)) {
Serial.print(F("\r\nDown"));
if (PS3[i]->PS3Connected) {
PS3[i]->setLedOff();
PS3[i]->setLedOn(LED2);
}
}
if (PS3[i]->getButtonClick(LEFT)) {
Serial.print(F("\r\nLeft"));
if (PS3[i]->PS3Connected) {
PS3[i]->setLedOff();
PS3[i]->setLedOn(LED3);
}
}
if (PS3[i]->getButtonClick(L1))
Serial.print(F("\r\nL1"));
if (PS3[i]->getButtonClick(L3))
Serial.print(F("\r\nL3"));
if (PS3[i]->getButtonClick(R1))
Serial.print(F("\r\nR1"));
if (PS3[i]->getButtonClick(R3))
Serial.print(F("\r\nR3"));
if (PS3[i]->getButtonClick(SELECT)) {
Serial.print(F("\r\nSelect - "));
PS3[i]->printStatusString();
}
if (PS3[i]->getButtonClick(START)) {
Serial.print(F("\r\nStart"));
printAngle[i] = !printAngle[i];
}
}
if (printAngle[i]) {
Serial.print(F("\r\nPitch: "));
Serial.print(PS3[i]->getAngle(Pitch));
Serial.print(F("\tRoll: "));
Serial.print(PS3[i]->getAngle(Roll));
}
}
/* I have removed the PS3 Move code as an Uno will run out of RAM if it's included */
//else if(PS3[i]->PS3MoveConnected) {
}
}
void onInit() {
for (uint8_t i = 0; i < length; i++) {
if ((PS3[i]->PS3Connected || PS3[i]->PS3NavigationConnected) && !oldControllerState[i]) {
oldControllerState[i] = true; // Used to check which is the new controller
PS3[i]->setLedOn((LEDEnum)(i + 1)); // Cast directly to LEDEnum - see: "controllerEnums.h"
}
}
}

View File

@ -0,0 +1,162 @@
/*
Example sketch for the Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
This example show how one can combine all the difference Bluetooth services in one single code.
Note:
You will need a Arduino Mega 1280/2560 to run this sketch,
as a normal Arduino (Uno, Duemilanove etc.) doesn't have enough SRAM and FLASH
*/
#include <PS3BT.h>
#include <SPP.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instances of the bluetooth services in two ways */
SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "0000"
//SPP SerialBTBT(&Btd,"Lauszus's Arduino","0000"); // You can also set the name and pin like so
PS3BT PS3(&Btd); // This will just create the instance
//PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch
bool firstMessage = true;
String output = ""; // We will store the data in this string
void setup() {
Serial.begin(115200); // This wil lprint the debugging from the libraries
#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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nBluetooth Library Started"));
output.reserve(200); // Reserve 200 bytes for the output string
}
void loop() {
Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well
if (SerialBT.connected) {
if (firstMessage) {
firstMessage = false;
SerialBT.println(F("Hello from Arduino")); // Send welcome message
}
if (Serial.available())
SerialBT.write(Serial.read());
if (SerialBT.available())
Serial.write(SerialBT.read());
}
else
firstMessage = true;
if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
output = ""; // Reset output string
if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
output += "LeftHatX: ";
output += PS3.getAnalogHat(LeftHatX);
output += "\tLeftHatY: ";
output += PS3.getAnalogHat(LeftHatY);
if (PS3.PS3Connected) { // The Navigation controller only have one joystick
output += "\tRightHatX: ";
output += PS3.getAnalogHat(RightHatX);
output += "\tRightHatY: ";
output += PS3.getAnalogHat(RightHatY);
}
}
//Analog button values can be read from almost all buttons
if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
if (output != "")
output += "\r\n";
output += "L2: ";
output += PS3.getAnalogButton(L2);
if (PS3.PS3Connected) {
output += "\tR2: ";
output += PS3.getAnalogButton(R2);
}
}
if (output != "") {
Serial.println(output);
if (SerialBT.connected)
SerialBT.println(output);
output = ""; // Reset output string
}
if (PS3.getButtonClick(PS)) {
output += " - PS";
PS3.disconnect();
}
else {
if (PS3.getButtonClick(TRIANGLE))
output += " - Traingle";
if (PS3.getButtonClick(CIRCLE))
output += " - Circle";
if (PS3.getButtonClick(CROSS))
output += " - Cross";
if (PS3.getButtonClick(SQUARE))
output += " - Square";
if (PS3.getButtonClick(UP)) {
output += " - Up";
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED4);
}
}
if (PS3.getButtonClick(RIGHT)) {
output += " - Right";
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED1);
}
}
if (PS3.getButtonClick(DOWN)) {
output += " - Down";
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED2);
}
}
if (PS3.getButtonClick(LEFT)) {
output += " - Left";
if (PS3.PS3Connected) {
PS3.setLedOff();
PS3.setLedOn(LED3);
}
}
if (PS3.getButtonClick(L1))
output += " - L1";
if (PS3.getButtonClick(L3))
output += " - L3";
if (PS3.getButtonClick(R1))
output += " - R1";
if (PS3.getButtonClick(R3))
output += " - R3";
if (PS3.getButtonClick(SELECT)) {
output += " - Select";
}
if (PS3.getButtonClick(START))
output += " - Start";
if (output != "") {
String string = "PS3 Controller" + output;
Serial.println(string);
if (SerialBT.connected)
SerialBT.println(string);
}
}
delay(10);
}
}

View File

@ -0,0 +1,146 @@
/*
Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <PS4BT.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the PS4BT class in two ways */
// This will start an inquiry and then pair with the PS4 controller - you only have to do this once
// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in pairing mode
PS4BT PS4(&Btd, PAIR);
// After that you can simply create the instance like so and then press the PS button on the device
//PS4BT PS4(&Btd);
bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); // Halt
}
Serial.print(F("\r\nPS4 Bluetooth Library Started"));
}
void loop() {
Usb.Task();
if (PS4.connected()) {
if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117) {
Serial.print(F("\r\nLeftHatX: "));
Serial.print(PS4.getAnalogHat(LeftHatX));
Serial.print(F("\tLeftHatY: "));
Serial.print(PS4.getAnalogHat(LeftHatY));
Serial.print(F("\tRightHatX: "));
Serial.print(PS4.getAnalogHat(RightHatX));
Serial.print(F("\tRightHatY: "));
Serial.print(PS4.getAnalogHat(RightHatY));
}
if (PS4.getAnalogButton(L2) || PS4.getAnalogButton(R2)) { // These are the only analog buttons on the PS4 controller
Serial.print(F("\r\nL2: "));
Serial.print(PS4.getAnalogButton(L2));
Serial.print(F("\tR2: "));
Serial.print(PS4.getAnalogButton(R2));
}
if (PS4.getAnalogButton(L2) != oldL2Value || PS4.getAnalogButton(R2) != oldR2Value) // Only write value if it's different
PS4.setRumbleOn(PS4.getAnalogButton(L2), PS4.getAnalogButton(R2));
oldL2Value = PS4.getAnalogButton(L2);
oldR2Value = PS4.getAnalogButton(R2);
if (PS4.getButtonClick(PS)) {
Serial.print(F("\r\nPS"));
PS4.disconnect();
}
else {
if (PS4.getButtonClick(TRIANGLE)) {
Serial.print(F("\r\nTraingle"));
PS4.setRumbleOn(RumbleLow);
}
if (PS4.getButtonClick(CIRCLE)) {
Serial.print(F("\r\nCircle"));
PS4.setRumbleOn(RumbleHigh);
}
if (PS4.getButtonClick(CROSS)) {
Serial.print(F("\r\nCross"));
PS4.setLedFlash(10, 10); // Set it to blink rapidly
}
if (PS4.getButtonClick(SQUARE)) {
Serial.print(F("\r\nSquare"));
PS4.setLedFlash(0, 0); // Turn off blinking
}
if (PS4.getButtonClick(UP)) {
Serial.print(F("\r\nUp"));
PS4.setLed(Red);
} if (PS4.getButtonClick(RIGHT)) {
Serial.print(F("\r\nRight"));
PS4.setLed(Blue);
} if (PS4.getButtonClick(DOWN)) {
Serial.print(F("\r\nDown"));
PS4.setLed(Yellow);
} if (PS4.getButtonClick(LEFT)) {
Serial.print(F("\r\nLeft"));
PS4.setLed(Green);
}
if (PS4.getButtonClick(L1))
Serial.print(F("\r\nL1"));
if (PS4.getButtonClick(L3))
Serial.print(F("\r\nL3"));
if (PS4.getButtonClick(R1))
Serial.print(F("\r\nR1"));
if (PS4.getButtonClick(R3))
Serial.print(F("\r\nR3"));
if (PS4.getButtonClick(SHARE))
Serial.print(F("\r\nShare"));
if (PS4.getButtonClick(OPTIONS)) {
Serial.print(F("\r\nOptions"));
printAngle = !printAngle;
}
if (PS4.getButtonClick(TOUCHPAD)) {
Serial.print(F("\r\nTouchpad"));
printTouch = !printTouch;
}
if (printAngle) { // Print angle calculated using the accelerometer only
Serial.print(F("\r\nPitch: "));
Serial.print(PS4.getAngle(Pitch));
Serial.print(F("\tRoll: "));
Serial.print(PS4.getAngle(Roll));
}
if (printTouch) { // Print the x, y coordinates of the touchpad
if (PS4.isTouching(0) || PS4.isTouching(1)) // Print newline and carriage return if any of the fingers are touching the touchpad
Serial.print(F("\r\n"));
for (uint8_t i = 0; i < 2; i++) { // The touchpad track two fingers
if (PS4.isTouching(i)) { // Print the position of the finger if it is touching the touchpad
Serial.print(F("X")); Serial.print(i + 1); Serial.print(F(": "));
Serial.print(PS4.getX(i));
Serial.print(F("\tY")); Serial.print(i + 1); Serial.print(F(": "));
Serial.print(PS4.getY(i));
Serial.print(F("\t"));
}
}
}
}
}
}

View File

@ -0,0 +1,52 @@
/*
Example sketch for the RFCOMM/SPP Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <SPP.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "0000"
//SPP SerialBT(&Btd, "Lauszus's Arduino", "1234"); // You can also set the name and pin like so
bool firstMessage = true;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nSPP Bluetooth Library Started"));
}
void loop() {
Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well
if (SerialBT.connected) {
if (firstMessage) {
firstMessage = false;
SerialBT.println(F("Hello from Arduino")); // Send welcome message
}
if (Serial.available())
SerialBT.write(Serial.read());
if (SerialBT.available())
Serial.write(SerialBT.read());
}
else
firstMessage = true;
}

View File

@ -0,0 +1,67 @@
/*
Example sketch for the RFCOMM/SPP Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <SPP.h>
#include <usbhub.h>
// Satisfy IDE, which only needs to see the include statment in the ino.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
const uint8_t length = 2; // Set the number of instances here
SPP *SerialBT[length]; // We will use this pointer to store the instances, you can easily make it larger if you like, but it will use a lot of RAM!
bool firstMessage[length] = { true }; // Set all to true
void setup() {
for (uint8_t i = 0; i < length; i++)
SerialBT[i] = new SPP(&Btd); // This will set the name to the default: "Arduino" and the pin to "0000" for all connections
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); // Halt
}
Serial.print(F("\r\nSPP Bluetooth Library Started"));
}
void loop() {
Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well
for (uint8_t i = 0; i < length; i++) {
if (SerialBT[i]->connected) {
if (firstMessage[i]) {
firstMessage[i] = false;
SerialBT[i]->println(F("Hello from Arduino")); // Send welcome message
}
if (SerialBT[i]->available())
Serial.write(SerialBT[i]->read());
}
else
firstMessage[i] = true;
}
// Set the connection you want to send to using the first character
// For instance "0Hello World" would send "Hello World" to connection 0
if (Serial.available()) {
delay(10); // Wait for the rest of the data to arrive
uint8_t id = Serial.read() - '0'; // Convert from ASCII
if (id < length && SerialBT[id]->connected) { // Make sure that the id is valid and make sure that a device is actually connected
while (Serial.available()) // Check if data is available
SerialBT[id]->write(Serial.read()); // Send the data
}
}
}

View File

@ -0,0 +1,118 @@
/*
Example sketch for the Wiimote Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <Wii.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wiimote - you only have to do this once
//WII Wii(&Btd); // After that you can simply create the instance like so and then press any button on the Wiimote
bool printAngle;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nWiimote Bluetooth Library Started"));
}
void loop() {
Usb.Task();
if (Wii.wiimoteConnected) {
if (Wii.getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
Serial.print(F("\r\nHOME"));
Wii.disconnect();
}
else {
if (Wii.getButtonClick(LEFT)) {
Wii.setLedOff();
Wii.setLedOn(LED1);
Serial.print(F("\r\nLeft"));
}
if (Wii.getButtonClick(RIGHT)) {
Wii.setLedOff();
Wii.setLedOn(LED3);
Serial.print(F("\r\nRight"));
}
if (Wii.getButtonClick(DOWN)) {
Wii.setLedOff();
Wii.setLedOn(LED4);
Serial.print(F("\r\nDown"));
}
if (Wii.getButtonClick(UP)) {
Wii.setLedOff();
Wii.setLedOn(LED2);
Serial.print(F("\r\nUp"));
}
if (Wii.getButtonClick(PLUS))
Serial.print(F("\r\nPlus"));
if (Wii.getButtonClick(MINUS))
Serial.print(F("\r\nMinus"));
if (Wii.getButtonClick(ONE))
Serial.print(F("\r\nOne"));
if (Wii.getButtonClick(TWO))
Serial.print(F("\r\nTwo"));
if (Wii.getButtonClick(A)) {
printAngle = !printAngle;
Serial.print(F("\r\nA"));
}
if (Wii.getButtonClick(B)) {
Wii.setRumbleToggle();
Serial.print(F("\r\nB"));
}
}
#if 0 // Set this to 1 in order to see the angle of the controllers
if (printAngle) {
Serial.print(F("\r\nPitch: "));
Serial.print(Wii.getPitch());
Serial.print(F("\tRoll: "));
Serial.print(Wii.getRoll());
if (Wii.motionPlusConnected) {
Serial.print(F("\tYaw: "));
Serial.print(Wii.getYaw());
}
if (Wii.nunchuckConnected) {
Serial.print(F("\tNunchuck Pitch: "));
Serial.print(Wii.getNunchuckPitch());
Serial.print(F("\tNunchuck Roll: "));
Serial.print(Wii.getNunchuckRoll());
}
}
#endif
}
#if 0 // Set this to 1 if you are using a Nunchuck controller
if (Wii.nunchuckConnected) {
if (Wii.getButtonClick(Z))
Serial.print(F("\r\nZ"));
if (Wii.getButtonClick(C))
Serial.print(F("\r\nC"));
if (Wii.getAnalogHat(HatX) > 137 || Wii.getAnalogHat(HatX) < 117 || Wii.getAnalogHat(HatY) > 137 || Wii.getAnalogHat(HatY) < 117) {
Serial.print(F("\r\nHatX: "));
Serial.print(Wii.getAnalogHat(HatX));
Serial.print(F("\tHatY: "));
Serial.print(Wii.getAnalogHat(HatY));
}
}
#endif
}

View File

@ -0,0 +1,51 @@
/*
Example sketch for the Wii Balance Board Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <Wii.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wii Balance Board - you only have to do this once
//WII Wii(&Btd); // After that you can simply create the instance like so and then press the power button on the Wii Balance Board
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nWii Balance Board Bluetooth Library Started"));
}
void loop() {
Usb.Task();
if (Wii.wiiBalanceBoardConnected) {
Serial.print(F("\r\nWeight: "));
for (uint8_t i = 0; i < 4; i++) {
Serial.print(Wii.getWeight((BalanceBoardEnum)i));
Serial.print(F("\t"));
}
Serial.print(F("Total Weight: "));
Serial.print(Wii.getTotalWeight());
if (Wii.getButtonClick(A)) {
Serial.print(F("\r\nA"));
//Wii.setLedToggle(LED1); // The Wii Balance Board has one LED as well
Wii.disconnect();
}
}
}

View File

@ -0,0 +1,133 @@
/*
Example sketch for the Wii libary showing the IR camera functionality. This example
is for the Bluetooth Wii library developed for the USB shield from Circuits@Home
Created by Allan Glover and Kristian Lauszus.
Contact Kristian: http://blog.tkjelectronics.dk/ or send an email at kristianl@tkjelectronics.com.
Contact Allan at adglover9.81@gmail.com
To test the Wiimote IR camera, you will need access to an IR source. Sunlight will work but is not ideal.
The simpleist solution is to use the Wii sensor bar, i.e. emitter bar, supplied by the Wii system.
Otherwise, wire up a IR LED yourself.
*/
#include <Wii.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>
#ifndef WIICAMERA // Used to check if WIICAMERA is defined
#error "Please set ENABLE_WII_IR_CAMERA to 1 in settings.h"
#endif
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wiimote - you only have to do this once
//WII Wii(&Btd); // After the Wiimote pairs once with the line of code above, you can simply create the instance like so and re upload and then press any button on the Wiimote
bool printAngle;
uint8_t printObjects;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nWiimote Bluetooth Library Started"));
}
void loop() {
Usb.Task();
if (Wii.wiimoteConnected) {
if (Wii.getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
Serial.print(F("\r\nHOME"));
Wii.disconnect();
}
else {
if (Wii.getButtonClick(ONE))
Wii.IRinitialize(); // Run the initialisation sequence
if (Wii.getButtonClick(MINUS) || Wii.getButtonClick(PLUS)) {
if (!Wii.isIRCameraEnabled())
Serial.print(F("\r\nEnable IR camera first"));
else {
if (Wii.getButtonPress(MINUS)) { // getButtonClick will only return true once
if (printObjects > 0)
printObjects--;
}
else {
if (printObjects < 4)
printObjects++;
}
Serial.print(F("\r\nTracking "));
Serial.print(printObjects);
Serial.print(F(" objects"));
}
}
if (Wii.getButtonClick(A)) {
printAngle = !printAngle;
Serial.print(F("\r\nA"));
}
if (Wii.getButtonClick(B)) {
Serial.print(F("\r\nBattery level: "));
Serial.print(Wii.getBatteryLevel()); // You can get the battery level as well
}
}
if (printObjects > 0) {
if (Wii.getIRx1() != 0x3FF || Wii.getIRy1() != 0x3FF || Wii.getIRs1() != 0) { // Only print if the IR camera is actually seeing something
Serial.print(F("\r\nx1: "));
Serial.print(Wii.getIRx1());
Serial.print(F("\ty1: "));
Serial.print(Wii.getIRy1());
Serial.print(F("\ts1:"));
Serial.print(Wii.getIRs1());
}
if (printObjects > 1) {
if (Wii.getIRx2() != 0x3FF || Wii.getIRy2() != 0x3FF || Wii.getIRs2() != 0) {
Serial.print(F("\r\nx2: "));
Serial.print(Wii.getIRx2());
Serial.print(F("\ty2: "));
Serial.print(Wii.getIRy2());
Serial.print(F("\ts2:"));
Serial.print(Wii.getIRs2());
}
if (printObjects > 2) {
if (Wii.getIRx3() != 0x3FF || Wii.getIRy3() != 0x3FF || Wii.getIRs3() != 0) {
Serial.print(F("\r\nx3: "));
Serial.print(Wii.getIRx3());
Serial.print(F("\ty3: "));
Serial.print(Wii.getIRy3());
Serial.print(F("\ts3:"));
Serial.print(Wii.getIRs3());
}
if (printObjects > 3) {
if (Wii.getIRx4() != 0x3FF || Wii.getIRy4() != 0x3FF || Wii.getIRs4() != 0) {
Serial.print(F("\r\nx4: "));
Serial.print(Wii.getIRx4());
Serial.print(F("\ty4: "));
Serial.print(Wii.getIRy4());
Serial.print(F("\ts4:"));
Serial.print(Wii.getIRs4());
}
}
}
}
}
if (printAngle) { // There is no extension bytes available, so the MotionPlus or Nunchuck can't be read
Serial.print(F("\r\nPitch: "));
Serial.print(Wii.getPitch());
Serial.print(F("\tRoll: "));
Serial.print(Wii.getRoll());
}
}
}

View File

@ -0,0 +1,132 @@
/*
Example sketch for the Wiimote Bluetooth library - developed by Kristian Lauszus
This example show how one can use multiple controllers with the library
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <Wii.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
WII *Wii[2]; // We will use this pointer to store the two instance, you can easily make it larger if you like, but it will use a lot of RAM!
const uint8_t length = sizeof(Wii) / sizeof(Wii[0]); // Get the lenght of the array
bool printAngle[length];
bool oldControllerState[length];
void setup() {
for (uint8_t i = 0; i < length; i++) {
Wii[i] = new WII(&Btd); // You will have to pair each controller with the dongle before you can define the instances like so, just add PAIR as the second argument
Wii[i]->attachOnInit(onInit); // onInit() is called upon a new connection - you can call the function whatever you like
}
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nWiimote Bluetooth Library Started"));
}
void loop() {
Usb.Task();
for (uint8_t i = 0; i < length; i++) {
if (Wii[i]->wiimoteConnected) {
if (Wii[i]->getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
Serial.print(F("\r\nHOME"));
Wii[i]->disconnect();
oldControllerState[i] = false; // Reset value
}
else {
if (Wii[i]->getButtonClick(LEFT)) {
Wii[i]->setLedOff();
Wii[i]->setLedOn(LED1);
Serial.print(F("\r\nLeft"));
}
if (Wii[i]->getButtonClick(RIGHT)) {
Wii[i]->setLedOff();
Wii[i]->setLedOn(LED3);
Serial.print(F("\r\nRight"));
}
if (Wii[i]->getButtonClick(DOWN)) {
Wii[i]->setLedOff();
Wii[i]->setLedOn(LED4);
Serial.print(F("\r\nDown"));
}
if (Wii[i]->getButtonClick(UP)) {
Wii[i]->setLedOff();
Wii[i]->setLedOn(LED2);
Serial.print(F("\r\nUp"));
}
if (Wii[i]->getButtonClick(PLUS))
Serial.print(F("\r\nPlus"));
if (Wii[i]->getButtonClick(MINUS))
Serial.print(F("\r\nMinus"));
if (Wii[i]->getButtonClick(ONE))
Serial.print(F("\r\nOne"));
if (Wii[i]->getButtonClick(TWO))
Serial.print(F("\r\nTwo"));
if (Wii[i]->getButtonClick(A)) {
printAngle[i] = !printAngle[i];
Serial.print(F("\r\nA"));
}
if (Wii[i]->getButtonClick(B)) {
Wii[i]->setRumbleToggle();
Serial.print(F("\r\nB"));
}
}
if (printAngle[i]) {
Serial.print(F("\r\nPitch: "));
Serial.print(Wii[i]->getPitch());
Serial.print(F("\tRoll: "));
Serial.print(Wii[i]->getRoll());
if (Wii[i]->motionPlusConnected) {
Serial.print(F("\tYaw: "));
Serial.print(Wii[i]->getYaw());
}
if (Wii[i]->nunchuckConnected) {
Serial.print(F("\tNunchuck Pitch: "));
Serial.print(Wii[i]->getNunchuckPitch());
Serial.print(F("\tNunchuck Roll: "));
Serial.print(Wii[i]->getNunchuckRoll());
}
}
}
if (Wii[i]->nunchuckConnected) {
if (Wii[i]->getButtonClick(Z))
Serial.print(F("\r\nZ"));
if (Wii[i]->getButtonClick(C))
Serial.print(F("\r\nC"));
if (Wii[i]->getAnalogHat(HatX) > 137 || Wii[i]->getAnalogHat(HatX) < 117 || Wii[i]->getAnalogHat(HatY) > 137 || Wii[i]->getAnalogHat(HatY) < 117) {
Serial.print(F("\r\nHatX: "));
Serial.print(Wii[i]->getAnalogHat(HatX));
Serial.print(F("\tHatY: "));
Serial.print(Wii[i]->getAnalogHat(HatY));
}
}
}
}
void onInit() {
for (uint8_t i = 0; i < length; i++) {
if (Wii[i]->wiimoteConnected && !oldControllerState[i]) {
oldControllerState[i] = true; // Used to check which is the new controller
Wii[i]->setLedOn((LEDEnum)(i + 1)); // Cast directly to LEDEnum - see: "controllerEnums.h"
}
}
}

View File

@ -0,0 +1,104 @@
/*
Example sketch for the Wiimote Bluetooth library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <Wii.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>
USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
/* You can create the instance of the class in two ways */
WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wiimote - you only have to do this once
//WII Wii(&Btd); // After that you can simply create the instance like so and then press any button on the Wiimote
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nWiimote Bluetooth Library Started"));
}
void loop() {
Usb.Task();
if (Wii.wiiUProControllerConnected) {
if (Wii.getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
Serial.print(F("\r\nHome"));
Wii.disconnect();
}
else {
if (Wii.getButtonClick(LEFT)) {
Wii.setLedOff();
Wii.setLedOn(LED1);
Serial.print(F("\r\nLeft"));
}
if (Wii.getButtonClick(RIGHT)) {
Wii.setLedOff();
Wii.setLedOn(LED3);
Serial.print(F("\r\nRight"));
}
if (Wii.getButtonClick(DOWN)) {
Wii.setLedOff();
Wii.setLedOn(LED4);
Serial.print(F("\r\nDown"));
}
if (Wii.getButtonClick(UP)) {
Wii.setLedOff();
Wii.setLedOn(LED2);
Serial.print(F("\r\nUp"));
}
if (Wii.getButtonClick(PLUS))
Serial.print(F("\r\nPlus"));
if (Wii.getButtonClick(MINUS))
Serial.print(F("\r\nMinus"));
if (Wii.getButtonClick(A))
Serial.print(F("\r\nA"));
if (Wii.getButtonClick(B)) {
Wii.setRumbleToggle();
Serial.print(F("\r\nB"));
}
if (Wii.getButtonClick(X))
Serial.print(F("\r\nX"));
if (Wii.getButtonClick(Y))
Serial.print(F("\r\nY"));
if (Wii.getButtonClick(L))
Serial.print(F("\r\nL"));
if (Wii.getButtonClick(R))
Serial.print(F("\r\nR"));
if (Wii.getButtonClick(ZL))
Serial.print(F("\r\nZL"));
if (Wii.getButtonClick(ZR))
Serial.print(F("\r\nZR"));
if (Wii.getButtonClick(L3))
Serial.print(F("\r\nL3"));
if (Wii.getButtonClick(R3))
Serial.print(F("\r\nR3"));
}
if (Wii.getAnalogHat(LeftHatX) > 2200 || Wii.getAnalogHat(LeftHatX) < 1800 || Wii.getAnalogHat(LeftHatY) > 2200 || Wii.getAnalogHat(LeftHatY) < 1800 || Wii.getAnalogHat(RightHatX) > 2200 || Wii.getAnalogHat(RightHatX) < 1800 || Wii.getAnalogHat(RightHatY) > 2200 || Wii.getAnalogHat(RightHatY) < 1800) {
Serial.print(F("\r\nLeftHatX: "));
Serial.print(Wii.getAnalogHat(LeftHatX));
Serial.print(F("\tLeftHatY: "));
Serial.print(Wii.getAnalogHat(LeftHatY));
Serial.print(F("\tRightHatX: "));
Serial.print(Wii.getAnalogHat(RightHatX));
Serial.print(F("\tRightHatY: "));
Serial.print(Wii.getAnalogHat(RightHatY));
}
}
}

View File

@ -0,0 +1,49 @@
/* Copyright (C) 2016 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 "SRWS1.h"
void SRWS1::ParseHIDData(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
if (HIDUniversal::VID != STEELSERIES_VID || HIDUniversal::PID != STEELSERIES_SRWS1_PID) // Make sure the right device is actually connected
return;
#if 0
if (len && buf) {
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(&srws1Data, buf, min(len, MFK_CASTUINT8T sizeof(srws1Data)));
static SRWS1DataButtons oldButtonState;
if (srws1Data.btn.val != oldButtonState.val) { // Check if anything has changed
buttonClickState.val = srws1Data.btn.val & ~oldButtonState.val; // Update click state variable
oldButtonState.val = srws1Data.btn.val;
}
}
// See: https://github.com/torvalds/linux/blob/master/drivers/hid/hid-steelseries.c
void SRWS1::setLeds(uint16_t leds) {
uint8_t buf[3];
buf[0] = 0x40; // Report ID
buf[1] = leds & 0xFF;
buf[2] = (leds >> 8) & 0x7F;
pUsb->outTransfer(bAddress, epInfo[ hidInterfaces[0].epIndex[epInterruptOutIndex] ].epAddr, sizeof(buf), buf);
}

View File

@ -0,0 +1,95 @@
/* Copyright (C) 2016 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 __srws1_h__
#define __srws1_h__
#include <hiduniversal.h>
#define STEELSERIES_VID 0x1038
#define STEELSERIES_SRWS1_PID 0x1410
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 = 0xF,
};
union SRWS1DataButtons {
struct {
uint8_t dpad : 4;
uint8_t dummy : 3;
uint8_t select : 1;
uint8_t back : 1;
uint8_t lookLeft : 1;
uint8_t lights : 1;
uint8_t lookBack : 1;
uint8_t rearBrakeBalance : 1;
uint8_t frontBrakeBalance : 1;
uint8_t requestPit : 1;
uint8_t leftGear : 1;
uint8_t camera : 1;
uint8_t lookRight : 1;
uint8_t boost : 1;
uint8_t horn : 1;
uint8_t hud : 1;
uint8_t launchControl : 1;
uint8_t speedLimiter : 1;
uint8_t rightGear : 1;
} __attribute__((packed));
uint32_t val : 24;
} __attribute__((packed));
struct SRWS1Data {
int16_t tilt; // Range [-1800:1800]
uint16_t rightTrigger : 12; // Range [0:1023] i.e. only 10 bits
uint16_t leftTrigger : 12; // Range [0:1023] i.e. only 10 bits
SRWS1DataButtons btn;
uint8_t assists : 4;
uint8_t steeringSensitivity : 4;
uint8_t assistValues : 4;
} __attribute__((packed));
class SRWS1 : public HIDUniversal {
public:
SRWS1(USB *p) : HIDUniversal(p) {};
bool connected() {
return HIDUniversal::isReady() && HIDUniversal::VID == STEELSERIES_VID && HIDUniversal::PID == STEELSERIES_SRWS1_PID;
};
void setLeds(uint16_t leds);
SRWS1Data srws1Data;
SRWS1DataButtons buttonClickState;
private:
void ParseHIDData(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf); // Called by the HIDUniversal library
uint8_t OnInitSuccessful() { // Called by the HIDUniversal library on success
if (HIDUniversal::VID != STEELSERIES_VID || HIDUniversal::PID != STEELSERIES_SRWS1_PID) // Make sure the right device is actually connected
return 1;
setLeds(0);
return 0;
};
};
#endif

View File

@ -0,0 +1,180 @@
/*
Example sketch for the SteelSeries SRW-S1 Steering Wheel - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <SPI.h>
#include "SRWS1.h"
USB Usb;
SRWS1 srw1(&Usb);
bool printTilt;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); // Halt
}
Serial.println(F("\r\nSteelSeries SRW-S1 Steering Wheel example started"));
}
void loop() {
Usb.Task();
if (srw1.connected()) {
if (printTilt) { // Show tilt angle using the LEDs
srw1.setLeds(1 << map(srw1.srws1Data.tilt, -1800, 1800, 0, 14)); // Turn on a LED according to tilt value
Serial.println(srw1.srws1Data.tilt);
} else { // Show strobe light effect
static uint32_t timer;
if ((int32_t)((uint32_t)millis() - timer) > 12) {
timer = (uint32_t)millis(); // Reset timer
static uint16_t leds = 0;
//PrintHex<uint16_t > (leds, 0x80); Serial.println();
srw1.setLeds(leds); // Update LEDs
static bool dirUp = true;
if (dirUp) {
leds <<= 1;
if (leds == 0x8000) // All are actually turned off, as there is only 15 LEDs
dirUp = false; // If we have reached the end i.e. all LEDs are off, then change direction
else if (!(leds & 0x8000)) // If last bit is not set, then set the lowest bit
leds |= 1; // Set lowest bit
} else {
leds >>= 1;
if (leds == 0) // Check if all LEDs are off
dirUp = true; // If all LEDs are off, then repeat the sequence
else if (!(leds & 0x1)) // If last bit is not set, then set the top bit
leds |= 1 << 15; // Set top bit
}
}
}
if (srw1.srws1Data.leftTrigger) {
Serial.print(F("L2: "));
Serial.println(srw1.srws1Data.leftTrigger);
}
if (srw1.srws1Data.rightTrigger) {
Serial.print(F("R2: "));
Serial.println(srw1.srws1Data.rightTrigger);
}
if (srw1.buttonClickState.select) {
srw1.buttonClickState.select = 0; // Clear event
Serial.println(F("Select"));
printTilt = !printTilt; // Print tilt value & show it using the LEDs as well
}
if (srw1.buttonClickState.back) {
srw1.buttonClickState.back = 0; // Clear event
Serial.println(F("Back"));
}
if (srw1.buttonClickState.lookLeft) {
srw1.buttonClickState.lookLeft = 0; // Clear event
Serial.println(F("Look Left"));
}
if (srw1.buttonClickState.lights) {
srw1.buttonClickState.lights = 0; // Clear event
Serial.println(F("Lights"));
}
if (srw1.buttonClickState.lookBack) {
srw1.buttonClickState.lookBack = 0; // Clear event
Serial.println(F("Look Back"));
}
if (srw1.buttonClickState.rearBrakeBalance) {
srw1.buttonClickState.rearBrakeBalance = 0; // Clear event
Serial.println(F("R. Brake Balance"));
}
if (srw1.buttonClickState.frontBrakeBalance) {
srw1.buttonClickState.frontBrakeBalance = 0; // Clear event
Serial.println(F("F. Brake Balance"));
}
if (srw1.buttonClickState.requestPit) {
srw1.buttonClickState.requestPit = 0; // Clear event
Serial.println(F("Request Pit"));
}
if (srw1.buttonClickState.leftGear) {
srw1.buttonClickState.leftGear = 0; // Clear event
Serial.println(F("Left Gear"));
}
if (srw1.buttonClickState.camera) {
srw1.buttonClickState.camera = 0; // Clear event
Serial.println(F("Camera"));
}
if (srw1.buttonClickState.lookRight) {
srw1.buttonClickState.lookRight = 0; // Clear event
Serial.println(F("Look right"));
}
if (srw1.buttonClickState.boost) {
srw1.buttonClickState.boost = 0; // Clear event
Serial.println(F("Boost"));
}
if (srw1.buttonClickState.horn) {
srw1.buttonClickState.horn = 0; // Clear event
Serial.println(F("Horn"));
}
if (srw1.buttonClickState.hud) {
srw1.buttonClickState.hud = 0; // Clear event
Serial.println(F("HUD"));
}
if (srw1.buttonClickState.launchControl) {
srw1.buttonClickState.launchControl = 0; // Clear event
Serial.println(F("Launch Control"));
}
if (srw1.buttonClickState.speedLimiter) {
srw1.buttonClickState.speedLimiter = 0; // Clear event
Serial.println(F("Speed Limiter"));
}
if (srw1.buttonClickState.rightGear) {
srw1.buttonClickState.rightGear = 0; // Clear event
Serial.println(F("Right gear"));
}
if (srw1.srws1Data.assists) Serial.println(srw1.srws1Data.assists);
if (srw1.srws1Data.steeringSensitivity) Serial.println(srw1.srws1Data.steeringSensitivity);
if (srw1.srws1Data.assistValues) Serial.println(srw1.srws1Data.assistValues);
switch (srw1.srws1Data.btn.dpad) {
case DPAD_UP:
Serial.println(F("Up"));
break;
case DPAD_UP_RIGHT:
Serial.println(F("UP & right"));
break;
case DPAD_RIGHT:
Serial.println(F("Right"));
break;
case DPAD_RIGHT_DOWN:
Serial.println(F("Right & down"));
break;
case DPAD_DOWN:
Serial.println(F("Down"));
break;
case DPAD_DOWN_LEFT:
Serial.println(F("Down & left"));
break;
case DPAD_LEFT:
Serial.println(F("Left"));
break;
case DPAD_LEFT_UP:
Serial.println(F("Left & up"));
break;
case DPAD_OFF:
break;
default:
Serial.print(F("Unknown state: "));
PrintHex<uint8_t > (srw1.srws1Data.btn.dpad, 0x80);
Serial.println();
break;
}
}
}

View File

@ -0,0 +1,125 @@
#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>
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);
};
void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
MODIFIERKEYS mod;
*((uint8_t*)&mod) = m;
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 (c)
OnKeyPressed(c);
}
void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after) {
MODIFIERKEYS beforeMod;
*((uint8_t*)&beforeMod) = before;
MODIFIERKEYS afterMod;
*((uint8_t*)&afterMod) = after;
if (beforeMod.bmLeftCtrl != afterMod.bmLeftCtrl) {
Serial.println("LeftCtrl changed");
}
if (beforeMod.bmLeftShift != afterMod.bmLeftShift) {
Serial.println("LeftShift changed");
}
if (beforeMod.bmLeftAlt != afterMod.bmLeftAlt) {
Serial.println("LeftAlt changed");
}
if (beforeMod.bmLeftGUI != afterMod.bmLeftGUI) {
Serial.println("LeftGUI changed");
}
if (beforeMod.bmRightCtrl != afterMod.bmRightCtrl) {
Serial.println("RightCtrl changed");
}
if (beforeMod.bmRightShift != afterMod.bmRightShift) {
Serial.println("RightShift changed");
}
if (beforeMod.bmRightAlt != afterMod.bmRightAlt) {
Serial.println("RightAlt changed");
}
if (beforeMod.bmRightGUI != afterMod.bmRightGUI) {
Serial.println("RightGUI changed");
}
}
void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
Serial.print("UP ");
PrintKey(mod, key);
}
void KbdRptParser::OnKeyPressed(uint8_t key)
{
Serial.print("ASCII: ");
Serial.println((char)key);
};
USB Usb;
//USBHub Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
KbdRptParser Prs;
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay( 200 );
HidKeyboard.SetReportParser(0, &Prs);
}
void loop()
{
Usb.Task();
}

View File

@ -0,0 +1,174 @@
#include <hidboot.h>
#include <usbhub.h>
// Satisfy IDE, which only needs to see the include statment in the ino.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
class MouseRptParser : public MouseReportParser
{
protected:
void OnMouseMove(MOUSEINFO *mi);
void OnLeftButtonUp(MOUSEINFO *mi);
void OnLeftButtonDown(MOUSEINFO *mi);
void OnRightButtonUp(MOUSEINFO *mi);
void OnRightButtonDown(MOUSEINFO *mi);
void OnMiddleButtonUp(MOUSEINFO *mi);
void OnMiddleButtonDown(MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{
Serial.print("dx=");
Serial.print(mi->dX, DEC);
Serial.print(" dy=");
Serial.println(mi->dY, DEC);
};
void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
{
Serial.println("L Butt Up");
};
void MouseRptParser::OnLeftButtonDown (MOUSEINFO *mi)
{
Serial.println("L Butt Dn");
};
void MouseRptParser::OnRightButtonUp (MOUSEINFO *mi)
{
Serial.println("R Butt Up");
};
void MouseRptParser::OnRightButtonDown (MOUSEINFO *mi)
{
Serial.println("R Butt Dn");
};
void MouseRptParser::OnMiddleButtonUp (MOUSEINFO *mi)
{
Serial.println("M Butt Up");
};
void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
{
Serial.println("M Butt Dn");
};
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);
};
void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
MODIFIERKEYS mod;
*((uint8_t*)&mod) = m;
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 (c)
OnKeyPressed(c);
}
void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after) {
MODIFIERKEYS beforeMod;
*((uint8_t*)&beforeMod) = before;
MODIFIERKEYS afterMod;
*((uint8_t*)&afterMod) = after;
if (beforeMod.bmLeftCtrl != afterMod.bmLeftCtrl) {
Serial.println("LeftCtrl changed");
}
if (beforeMod.bmLeftShift != afterMod.bmLeftShift) {
Serial.println("LeftShift changed");
}
if (beforeMod.bmLeftAlt != afterMod.bmLeftAlt) {
Serial.println("LeftAlt changed");
}
if (beforeMod.bmLeftGUI != afterMod.bmLeftGUI) {
Serial.println("LeftGUI changed");
}
if (beforeMod.bmRightCtrl != afterMod.bmRightCtrl) {
Serial.println("RightCtrl changed");
}
if (beforeMod.bmRightShift != afterMod.bmRightShift) {
Serial.println("RightShift changed");
}
if (beforeMod.bmRightAlt != afterMod.bmRightAlt) {
Serial.println("RightAlt changed");
}
if (beforeMod.bmRightGUI != afterMod.bmRightGUI) {
Serial.println("RightGUI changed");
}
}
void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
Serial.print("UP ");
PrintKey(mod, key);
}
void KbdRptParser::OnKeyPressed(uint8_t key)
{
Serial.print("ASCII: ");
Serial.println((char)key);
};
USB Usb;
USBHub Hub(&Usb);
HIDBoot < USB_HID_PROTOCOL_KEYBOARD | USB_HID_PROTOCOL_MOUSE > HidComposite(&Usb);
HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE> HidMouse(&Usb);
KbdRptParser KbdPrs;
MouseRptParser MousePrs;
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay( 200 );
HidComposite.SetReportParser(0, &KbdPrs);
HidComposite.SetReportParser(1, &MousePrs);
HidKeyboard.SetReportParser(0, &KbdPrs);
HidMouse.SetReportParser(0, &MousePrs);
}
void loop()
{
Usb.Task();
}

View File

@ -0,0 +1,79 @@
#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>
class MouseRptParser : public MouseReportParser
{
protected:
void OnMouseMove (MOUSEINFO *mi);
void OnLeftButtonUp (MOUSEINFO *mi);
void OnLeftButtonDown (MOUSEINFO *mi);
void OnRightButtonUp (MOUSEINFO *mi);
void OnRightButtonDown (MOUSEINFO *mi);
void OnMiddleButtonUp (MOUSEINFO *mi);
void OnMiddleButtonDown (MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{
Serial.print("dx=");
Serial.print(mi->dX, DEC);
Serial.print(" dy=");
Serial.println(mi->dY, DEC);
};
void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
{
Serial.println("L Butt Up");
};
void MouseRptParser::OnLeftButtonDown (MOUSEINFO *mi)
{
Serial.println("L Butt Dn");
};
void MouseRptParser::OnRightButtonUp (MOUSEINFO *mi)
{
Serial.println("R Butt Up");
};
void MouseRptParser::OnRightButtonDown (MOUSEINFO *mi)
{
Serial.println("R Butt Dn");
};
void MouseRptParser::OnMiddleButtonUp (MOUSEINFO *mi)
{
Serial.println("M Butt Up");
};
void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
{
Serial.println("M Butt Dn");
};
USB Usb;
USBHub Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE> HidMouse(&Usb);
MouseRptParser Prs;
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay( 200 );
HidMouse.SetReportParser(0, &Prs);
}
void loop()
{
Usb.Task();
}

View File

@ -0,0 +1,38 @@
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>
// Satisfy IDE, which only needs to see the include statment in the ino.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
#include "hidjoystickrptparser.h"
USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid(&Usb);
JoystickEvents JoyEvents;
JoystickReportParser Joy(&JoyEvents);
void setup() {
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay(200);
if (!Hid.SetReportParser(0, &Joy))
ErrorMessage<uint8_t > (PSTR("SetReportParser"), 1);
}
void loop() {
Usb.Task();
}

View File

@ -0,0 +1,85 @@
#include "hidjoystickrptparser.h"
JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
joyEvents(evt),
oldHat(0xDE),
oldButtons(0) {
for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++)
oldPad[i] = 0xD;
}
void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
bool match = true;
// Checking if there are changes in report since the method was last called
for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++)
if (buf[i] != oldPad[i]) {
match = false;
break;
}
// Calling Game Pad event handler
if (!match && joyEvents) {
joyEvents->OnGamePadChanged((const GamePadEventData*)buf);
for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++) oldPad[i] = buf[i];
}
uint8_t hat = (buf[5] & 0xF);
// Calling Hat Switch event handler
if (hat != oldHat && joyEvents) {
joyEvents->OnHatSwitch(hat);
oldHat = hat;
}
uint16_t buttons = (0x0000 | buf[6]);
buttons <<= 4;
buttons |= (buf[5] >> 4);
uint16_t changes = (buttons ^ oldButtons);
// Calling Button Event Handler for every button changed
if (changes) {
for (uint8_t i = 0; i < 0x0C; i++) {
uint16_t mask = (0x0001 << i);
if (((mask & changes) > 0) && joyEvents) {
if ((buttons & mask) > 0)
joyEvents->OnButtonDn(i + 1);
else
joyEvents->OnButtonUp(i + 1);
}
}
oldButtons = buttons;
}
}
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt) {
Serial.print("X1: ");
PrintHex<uint8_t > (evt->X, 0x80);
Serial.print("\tY1: ");
PrintHex<uint8_t > (evt->Y, 0x80);
Serial.print("\tX2: ");
PrintHex<uint8_t > (evt->Z1, 0x80);
Serial.print("\tY2: ");
PrintHex<uint8_t > (evt->Z2, 0x80);
Serial.print("\tRz: ");
PrintHex<uint8_t > (evt->Rz, 0x80);
Serial.println("");
}
void JoystickEvents::OnHatSwitch(uint8_t hat) {
Serial.print("Hat Switch: ");
PrintHex<uint8_t > (hat, 0x80);
Serial.println("");
}
void JoystickEvents::OnButtonUp(uint8_t but_id) {
Serial.print("Up: ");
Serial.println(but_id, DEC);
}
void JoystickEvents::OnButtonDn(uint8_t but_id) {
Serial.print("Dn: ");
Serial.println(but_id, DEC);
}

View File

@ -0,0 +1,33 @@
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__
#include <usbhid.h>
struct GamePadEventData {
uint8_t X, Y, Z1, Z2, Rz;
};
class JoystickEvents {
public:
virtual void OnGamePadChanged(const GamePadEventData *evt);
virtual void OnHatSwitch(uint8_t hat);
virtual void OnButtonUp(uint8_t but_id);
virtual void OnButtonDn(uint8_t but_id);
};
#define RPT_GEMEPAD_LEN 5
class JoystickReportParser : public HIDReportParser {
JoystickEvents *joyEvents;
uint8_t oldPad[RPT_GEMEPAD_LEN];
uint8_t oldHat;
uint16_t oldButtons;
public:
JoystickReportParser(JoystickEvents *evt);
virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};
#endif // __HIDJOYSTICKRPTPARSER_H__

View File

@ -0,0 +1,68 @@
#include <hidcomposite.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>
// Override HIDComposite to be able to select which interface we want to hook into
class HIDSelector : public HIDComposite
{
public:
HIDSelector(USB *p) : HIDComposite(p) {};
protected:
void ParseHIDData(USBHID *hid, uint8_t ep, bool is_rpt_id, uint8_t len, uint8_t *buf); // Called by the HIDComposite library
bool SelectInterface(uint8_t iface, uint8_t proto);
};
// Return true for the interface we want to hook into
bool HIDSelector::SelectInterface(uint8_t iface, uint8_t proto)
{
if (proto != 0)
return true;
return false;
}
// Will be called for all HID data received from the USB interface
void HIDSelector::ParseHIDData(USBHID *hid, uint8_t ep, bool is_rpt_id, uint8_t len, uint8_t *buf) {
#if 1
if (len && buf) {
Notify(PSTR("\r\n"), 0x80);
for (uint8_t i = 0; i < len; i++) {
D_PrintHex<uint8_t > (buf[i], 0x80);
Notify(PSTR(" "), 0x80);
}
}
#endif
}
USB Usb;
//USBHub Hub(&Usb);
HIDSelector hidSelector(&Usb);
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
// Set this to higher values to enable more debug information
// minimum 0x00, maximum 0xff, default 0x80
UsbDEBUGlvl = 0xff;
delay( 200 );
}
void loop()
{
Usb.Task();
}

View File

@ -0,0 +1,77 @@
#include <usbhid.h>
#include <hiduniversal.h>
#include <hidescriptorparser.h>
#include <usbhub.h>
#include "pgmstrings.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
class HIDUniversal2 : public HIDUniversal
{
public:
HIDUniversal2(USB *usb) : HIDUniversal(usb) {};
protected:
uint8_t OnInitSuccessful();
};
uint8_t HIDUniversal2::OnInitSuccessful()
{
uint8_t rcode;
HexDumper<USBReadParser, uint16_t, uint16_t> Hex;
ReportDescParser Rpt;
if ((rcode = GetReportDescr(0, &Hex)))
goto FailGetReportDescr1;
if ((rcode = GetReportDescr(0, &Rpt)))
goto FailGetReportDescr2;
return 0;
FailGetReportDescr1:
USBTRACE("GetReportDescr1:");
goto Fail;
FailGetReportDescr2:
USBTRACE("GetReportDescr2:");
goto Fail;
Fail:
Serial.println(rcode, HEX);
Release();
return rcode;
}
USB Usb;
//USBHub Hub(&Usb);
HIDUniversal2 Hid(&Usb);
UniversalReportParser Uni;
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay( 200 );
if (!Hid.SetReportParser(0, &Uni))
ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1 );
}
void loop()
{
Usb.Task();
}

View File

@ -0,0 +1,52 @@
#if !defined(__PGMSTRINGS_H__)
#define __PGMSTRINGS_H__
#define LOBYTE(x) ((char*)(&(x)))[0]
#define HIBYTE(x) ((char*)(&(x)))[1]
#define BUFSIZE 256 //buffer size
/* Print strings in Program Memory */
const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t";
const char Dev_Header_str[] PROGMEM ="\r\nDevice descriptor: ";
const char Dev_Length_str[] PROGMEM ="\r\nDescriptor Length:\t";
const char Dev_Type_str[] PROGMEM ="\r\nDescriptor type:\t";
const char Dev_Version_str[] PROGMEM ="\r\nUSB version:\t\t";
const char Dev_Class_str[] PROGMEM ="\r\nDevice class:\t\t";
const char Dev_Subclass_str[] PROGMEM ="\r\nDevice Subclass:\t";
const char Dev_Protocol_str[] PROGMEM ="\r\nDevice Protocol:\t";
const char Dev_Pktsize_str[] PROGMEM ="\r\nMax.packet size:\t";
const char Dev_Vendor_str[] PROGMEM ="\r\nVendor ID:\t\t";
const char Dev_Product_str[] PROGMEM ="\r\nProduct ID:\t\t";
const char Dev_Revision_str[] PROGMEM ="\r\nRevision ID:\t\t";
const char Dev_Mfg_str[] PROGMEM ="\r\nMfg.string index:\t";
const char Dev_Prod_str[] PROGMEM ="\r\nProd.string index:\t";
const char Dev_Serial_str[] PROGMEM ="\r\nSerial number index:\t";
const char Dev_Nconf_str[] PROGMEM ="\r\nNumber of conf.:\t";
const char Conf_Trunc_str[] PROGMEM ="Total length truncated to 256 bytes";
const char Conf_Header_str[] PROGMEM ="\r\nConfiguration descriptor:";
const char Conf_Totlen_str[] PROGMEM ="\r\nTotal length:\t\t";
const char Conf_Nint_str[] PROGMEM ="\r\nNum.intf:\t\t";
const char Conf_Value_str[] PROGMEM ="\r\nConf.value:\t\t";
const char Conf_String_str[] PROGMEM ="\r\nConf.string:\t\t";
const char Conf_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
const char Conf_Pwr_str[] PROGMEM ="\r\nMax.pwr:\t\t";
const char Int_Header_str[] PROGMEM ="\r\n\r\nInterface descriptor:";
const char Int_Number_str[] PROGMEM ="\r\nIntf.number:\t\t";
const char Int_Alt_str[] PROGMEM ="\r\nAlt.:\t\t\t";
const char Int_Endpoints_str[] PROGMEM ="\r\nEndpoints:\t\t";
const char Int_Class_str[] PROGMEM ="\r\nIntf. Class:\t\t";
const char Int_Subclass_str[] PROGMEM ="\r\nIntf. Subclass:\t\t";
const char Int_Protocol_str[] PROGMEM ="\r\nIntf. Protocol:\t\t";
const char Int_String_str[] PROGMEM ="\r\nIntf.string:\t\t";
const char End_Header_str[] PROGMEM ="\r\n\r\nEndpoint descriptor:";
const char End_Address_str[] PROGMEM ="\r\nEndpoint address:\t";
const char End_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
const char End_Pktsize_str[] PROGMEM ="\r\nMax.pkt size:\t\t";
const char End_Interval_str[] PROGMEM ="\r\nPolling interval:\t";
const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:";
const char Unk_Length_str[] PROGMEM ="\r\nLength:\t\t";
const char Unk_Type_str[] PROGMEM ="\r\nType:\t\t";
const char Unk_Contents_str[] PROGMEM ="\r\nContents:\t";
#endif // __PGMSTRINGS_H__

View File

@ -0,0 +1,42 @@
/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include "le3dp_rptparser.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid(&Usb);
JoystickEvents JoyEvents;
JoystickReportParser Joy(&JoyEvents);
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay( 200 );
if (!Hid.SetReportParser(0, &Joy))
ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1 );
}
void loop()
{
Usb.Task();
}

View File

@ -0,0 +1,43 @@
#include "le3dp_rptparser.h"
JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
joyEvents(evt)
{}
void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
bool match = true;
// Checking if there are changes in report since the method was last called
for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
if( buf[i] != oldPad[i] ) {
match = false;
break;
}
}
// Calling Game Pad event handler
if (!match && joyEvents) {
joyEvents->OnGamePadChanged((const GamePadEventData*)buf);
for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
}
}
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
Serial.print("X: ");
PrintHex<uint16_t>(evt->x, 0x80);
Serial.print(" Y: ");
PrintHex<uint16_t>(evt->y, 0x80);
Serial.print(" Hat Switch: ");
PrintHex<uint8_t>(evt->hat, 0x80);
Serial.print(" Twist: ");
PrintHex<uint8_t>(evt->twist, 0x80);
Serial.print(" Slider: ");
PrintHex<uint8_t>(evt->slider, 0x80);
Serial.print(" Buttons A: ");
PrintHex<uint8_t>(evt->buttons_a, 0x80);
Serial.print(" Buttons B: ");
PrintHex<uint8_t>(evt->buttons_b, 0x80);
Serial.println("");
}

View File

@ -0,0 +1,42 @@
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__
#include <usbhid.h>
struct GamePadEventData
{
union { //axes and hut switch
uint32_t axes;
struct {
uint32_t x : 10;
uint32_t y : 10;
uint32_t hat : 4;
uint32_t twist : 8;
};
};
uint8_t buttons_a;
uint8_t slider;
uint8_t buttons_b;
};
class JoystickEvents
{
public:
virtual void OnGamePadChanged(const GamePadEventData *evt);
};
#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)
class JoystickReportParser : public HIDReportParser
{
JoystickEvents *joyEvents;
uint8_t oldPad[RPT_GAMEPAD_LEN];
public:
JoystickReportParser(JoystickEvents *evt);
virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};
#endif // __HIDJOYSTICKRPTPARSER_H__

View File

@ -0,0 +1,51 @@
/* Digital Scale Output. Written for Stamps.com Model 510 */
/* 5lb Digital Scale; any HID scale with Usage page 0x8d should work */
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include "scale_rptparser.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid(&Usb);
Max_LCD LCD(&Usb);
ScaleEvents ScaleEvents(&LCD);
ScaleReportParser Scale(&ScaleEvents);
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
// set up the LCD's number of rows and columns:
LCD.begin(16, 2);
LCD.clear();
LCD.home();
LCD.setCursor(0,0);
LCD.write('R');
delay( 200 );
if (!Hid.SetReportParser(0, &Scale))
ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1 );
}
void loop()
{
Usb.Task();
}

View File

@ -0,0 +1,153 @@
/* Parser for standard HID scale (usage page 0x8d) data input report (ID 3) */
#ifdef ARDUINO_SAM_DUE
#include <avr/dtostrf.h>
#endif
#include "scale_rptparser.h"
const char* UNITS[13] = {
"units", // unknown unit
"mg", // milligram
"g", // gram
"kg", // kilogram
"cd", // carat
"taels", // lian
"gr", // grain
"dwt", // pennyweight
"tonnes", // metric tons
"tons", // avoir ton
"ozt", // troy ounce
"oz", // ounce
"lbs" // pound
};
ScaleReportParser::ScaleReportParser(ScaleEvents *evt) :
scaleEvents(evt)
{}
void ScaleReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
bool match = true;
// Checking if there are changes in report since the method was last called
for (uint8_t i=0; i<RPT_SCALE_LEN; i++) {
if( buf[i] != oldScale[i] ) {
match = false;
break;
}
}
// Calling Game Pad event handler
if (!match && scaleEvents) {
scaleEvents->OnScaleChanged((const ScaleEventData*)buf);
for (uint8_t i=0; i<RPT_SCALE_LEN; i++) oldScale[i] = buf[i];
}
}
ScaleEvents::ScaleEvents( Max_LCD* pLCD ) :
pLcd( pLCD )
{}
void ScaleEvents::LcdPrint( const char* str )
{
while( *str ) {
pLcd->write( *str++ );
}
}
void ScaleEvents::OnScaleChanged(const ScaleEventData *evt)
{
pLcd->clear();
pLcd->home();
pLcd->setCursor(0,0);
if( evt->reportID != 3 ) {
const char inv_report[]="Invalid report!";
Serial.println(inv_report);
LcdPrint(inv_report);
return;
}//if( evt->reportID != 3...
switch( evt->status ) {
case REPORT_FAULT:
Serial.println(F("Report fault"));
break;
case ZEROED:
Serial.println(F("Scale zero set"));
break;
case WEIGHING: {
const char progress[] = "Weighing...";
Serial.println(progress);
LcdPrint(progress);
break;
}
case WEIGHT_VALID: {
char buf[10];
double weight = evt->weight * pow( 10, evt->exp );
Serial.print(F("Weight: "));
Serial.print( weight );
Serial.print(F(" "));
Serial.println( UNITS[ evt->unit ]);
LcdPrint("Weight: ");
dtostrf( weight, 4, 2, buf );
LcdPrint( buf );
LcdPrint( UNITS[ evt->unit ]);
break;
}//case WEIGHT_VALID...
case WEIGHT_NEGATIVE: {
const char negweight[] = "Negative weight";
Serial.println(negweight);
LcdPrint(negweight);
break;
}
case OVERWEIGHT: {
const char overweight[] = "Max.weight reached";
Serial.println(overweight);
LcdPrint( overweight );
break;
}
case CALIBRATE_ME:
Serial.println(F("Scale calibration required"));
break;
case ZERO_ME:
Serial.println(F("Scale zeroing required"));
break;
default:
Serial.print(F("Undefined status code: "));
Serial.println( evt->status );
break;
}//switch( evt->status...
}

View File

@ -0,0 +1,55 @@
#if !defined(__SCALERPTPARSER_H__)
#define __SCALERPTPARSER_H__
#include <max_LCD.h>
#include <usbhid.h>
/* Scale status constants */
#define REPORT_FAULT 0x01
#define ZEROED 0x02
#define WEIGHING 0x03
#define WEIGHT_VALID 0x04
#define WEIGHT_NEGATIVE 0x05
#define OVERWEIGHT 0x06
#define CALIBRATE_ME 0x07
#define ZERO_ME 0x08
/* input data report */
struct ScaleEventData
{
uint8_t reportID; //must be 3
uint8_t status;
uint8_t unit;
int8_t exp; //scale factor for the weight
uint16_t weight; //
};
class ScaleEvents
{
Max_LCD* pLcd;
void LcdPrint( const char* str );
public:
ScaleEvents( Max_LCD* pLCD );
virtual void OnScaleChanged(const ScaleEventData *evt);
};
#define RPT_SCALE_LEN sizeof(ScaleEventData)/sizeof(uint8_t)
class ScaleReportParser : public HIDReportParser
{
ScaleEvents *scaleEvents;
uint8_t oldScale[RPT_SCALE_LEN];
public:
ScaleReportParser(ScaleEvents *evt);
virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};
#endif // __SCALERPTPARSER_H__

View File

@ -0,0 +1,148 @@
/*
Example sketch for the PS3 USB library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <PS3USB.h>
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
//PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch
bool printAngle;
uint8_t state = 0;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nPS3 USB Library Started"));
}
void loop() {
Usb.Task();
if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
Serial.print(F("\r\nLeftHatX: "));
Serial.print(PS3.getAnalogHat(LeftHatX));
Serial.print(F("\tLeftHatY: "));
Serial.print(PS3.getAnalogHat(LeftHatY));
if (PS3.PS3Connected) { // The Navigation controller only have one joystick
Serial.print(F("\tRightHatX: "));
Serial.print(PS3.getAnalogHat(RightHatX));
Serial.print(F("\tRightHatY: "));
Serial.print(PS3.getAnalogHat(RightHatY));
}
}
// Analog button values can be read from almost all buttons
if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
Serial.print(F("\r\nL2: "));
Serial.print(PS3.getAnalogButton(L2));
if (!PS3.PS3NavigationConnected) {
Serial.print(F("\tR2: "));
Serial.print(PS3.getAnalogButton(R2));
}
}
if (PS3.getButtonClick(PS))
Serial.print(F("\r\nPS"));
if (PS3.getButtonClick(TRIANGLE))
Serial.print(F("\r\nTraingle"));
if (PS3.getButtonClick(CIRCLE))
Serial.print(F("\r\nCircle"));
if (PS3.getButtonClick(CROSS))
Serial.print(F("\r\nCross"));
if (PS3.getButtonClick(SQUARE))
Serial.print(F("\r\nSquare"));
if (PS3.getButtonClick(UP)) {
Serial.print(F("\r\nUp"));
PS3.setLedOff();
PS3.setLedOn(LED4);
}
if (PS3.getButtonClick(RIGHT)) {
Serial.print(F("\r\nRight"));
PS3.setLedOff();
PS3.setLedOn(LED1);
}
if (PS3.getButtonClick(DOWN)) {
Serial.print(F("\r\nDown"));
PS3.setLedOff();
PS3.setLedOn(LED2);
}
if (PS3.getButtonClick(LEFT)) {
Serial.print(F("\r\nLeft"));
PS3.setLedOff();
PS3.setLedOn(LED3);
}
if (PS3.getButtonClick(L1))
Serial.print(F("\r\nL1"));
if (PS3.getButtonClick(L3))
Serial.print(F("\r\nL3"));
if (PS3.getButtonClick(R1))
Serial.print(F("\r\nR1"));
if (PS3.getButtonClick(R3))
Serial.print(F("\r\nR3"));
if (PS3.getButtonClick(SELECT)) {
Serial.print(F("\r\nSelect - "));
PS3.printStatusString();
}
if (PS3.getButtonClick(START)) {
Serial.print(F("\r\nStart"));
printAngle = !printAngle;
}
if (printAngle) {
Serial.print(F("\r\nPitch: "));
Serial.print(PS3.getAngle(Pitch));
Serial.print(F("\tRoll: "));
Serial.print(PS3.getAngle(Roll));
}
}
else if (PS3.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 (state == 0) {
PS3.moveSetRumble(0);
PS3.moveSetBulb(Off);
} else if (state == 1) {
PS3.moveSetRumble(75);
PS3.moveSetBulb(Red);
} else if (state == 2) {
PS3.moveSetRumble(125);
PS3.moveSetBulb(Green);
} else if (state == 3) {
PS3.moveSetRumble(150);
PS3.moveSetBulb(Blue);
} else if (state == 4) {
PS3.moveSetRumble(175);
PS3.moveSetBulb(Yellow);
} else if (state == 5) {
PS3.moveSetRumble(200);
PS3.moveSetBulb(Lightblue);
} else if (state == 6) {
PS3.moveSetRumble(225);
PS3.moveSetBulb(Purple);
} else if (state == 7) {
PS3.moveSetRumble(250);
PS3.moveSetBulb(White);
}
state++;
if (state > 7)
state = 0;
delay(1000);
}
}

View File

@ -0,0 +1,133 @@
/*
Example sketch for the PS4 USB library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <PS4USB.h>
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
PS4USB PS4(&Usb);
bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); // Halt
}
Serial.print(F("\r\nPS4 USB Library Started"));
}
void loop() {
Usb.Task();
if (PS4.connected()) {
if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117) {
Serial.print(F("\r\nLeftHatX: "));
Serial.print(PS4.getAnalogHat(LeftHatX));
Serial.print(F("\tLeftHatY: "));
Serial.print(PS4.getAnalogHat(LeftHatY));
Serial.print(F("\tRightHatX: "));
Serial.print(PS4.getAnalogHat(RightHatX));
Serial.print(F("\tRightHatY: "));
Serial.print(PS4.getAnalogHat(RightHatY));
}
if (PS4.getAnalogButton(L2) || PS4.getAnalogButton(R2)) { // These are the only analog buttons on the PS4 controller
Serial.print(F("\r\nL2: "));
Serial.print(PS4.getAnalogButton(L2));
Serial.print(F("\tR2: "));
Serial.print(PS4.getAnalogButton(R2));
}
if (PS4.getAnalogButton(L2) != oldL2Value || PS4.getAnalogButton(R2) != oldR2Value) // Only write value if it's different
PS4.setRumbleOn(PS4.getAnalogButton(L2), PS4.getAnalogButton(R2));
oldL2Value = PS4.getAnalogButton(L2);
oldR2Value = PS4.getAnalogButton(R2);
if (PS4.getButtonClick(PS))
Serial.print(F("\r\nPS"));
if (PS4.getButtonClick(TRIANGLE)) {
Serial.print(F("\r\nTraingle"));
PS4.setRumbleOn(RumbleLow);
}
if (PS4.getButtonClick(CIRCLE)) {
Serial.print(F("\r\nCircle"));
PS4.setRumbleOn(RumbleHigh);
}
if (PS4.getButtonClick(CROSS)) {
Serial.print(F("\r\nCross"));
PS4.setLedFlash(10, 10); // Set it to blink rapidly
}
if (PS4.getButtonClick(SQUARE)) {
Serial.print(F("\r\nSquare"));
PS4.setLedFlash(0, 0); // Turn off blinking
}
if (PS4.getButtonClick(UP)) {
Serial.print(F("\r\nUp"));
PS4.setLed(Red);
} if (PS4.getButtonClick(RIGHT)) {
Serial.print(F("\r\nRight"));
PS4.setLed(Blue);
} if (PS4.getButtonClick(DOWN)) {
Serial.print(F("\r\nDown"));
PS4.setLed(Yellow);
} if (PS4.getButtonClick(LEFT)) {
Serial.print(F("\r\nLeft"));
PS4.setLed(Green);
}
if (PS4.getButtonClick(L1))
Serial.print(F("\r\nL1"));
if (PS4.getButtonClick(L3))
Serial.print(F("\r\nL3"));
if (PS4.getButtonClick(R1))
Serial.print(F("\r\nR1"));
if (PS4.getButtonClick(R3))
Serial.print(F("\r\nR3"));
if (PS4.getButtonClick(SHARE))
Serial.print(F("\r\nShare"));
if (PS4.getButtonClick(OPTIONS)) {
Serial.print(F("\r\nOptions"));
printAngle = !printAngle;
}
if (PS4.getButtonClick(TOUCHPAD)) {
Serial.print(F("\r\nTouchpad"));
printTouch = !printTouch;
}
if (printAngle) { // Print angle calculated using the accelerometer only
Serial.print(F("\r\nPitch: "));
Serial.print(PS4.getAngle(Pitch));
Serial.print(F("\tRoll: "));
Serial.print(PS4.getAngle(Roll));
}
if (printTouch) { // Print the x, y coordinates of the touchpad
if (PS4.isTouching(0) || PS4.isTouching(1)) // Print newline and carriage return if any of the fingers are touching the touchpad
Serial.print(F("\r\n"));
for (uint8_t i = 0; i < 2; i++) { // The touchpad track two fingers
if (PS4.isTouching(i)) { // Print the position of the finger if it is touching the touchpad
Serial.print(F("X")); Serial.print(i + 1); Serial.print(F(": "));
Serial.print(PS4.getX(i));
Serial.print(F("\tY")); Serial.print(i + 1); Serial.print(F(": "));
Serial.print(PS4.getY(i));
Serial.print(F("\t"));
}
}
}
}
}

View File

@ -0,0 +1,49 @@
/*
Example sketch for the Playstation Buzz library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <PSBuzz.h>
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
PSBuzz Buzz(&Usb);
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); // Halt
}
Serial.println(F("\r\nPS Buzz Library Started"));
}
void loop() {
Usb.Task();
if (Buzz.connected()) {
for (uint8_t i = 0; i < 4; i++) {
if (Buzz.getButtonClick(RED, i)) {
Buzz.setLedToggle(i); // Toggle the LED
Serial.println(F("RED"));
}
if (Buzz.getButtonClick(YELLOW, i))
Serial.println(F("YELLOW"));
if (Buzz.getButtonClick(GREEN, i))
Serial.println(F("GREEN"));
if (Buzz.getButtonClick(ORANGE, i))
Serial.println(F("ORANGE"));
if (Buzz.getButtonClick(BLUE, i))
Serial.println(F("BLUE"));
}
}
}

View File

@ -0,0 +1,97 @@
/*
*******************************************************************************
* USB-MIDI dump utility
* Copyright (C) 2013-2017 Yuuichi Akagawa
*
* for use with USB Host Shield 2.0 from Circuitsathome.com
* https://github.com/felis/USB_Host_Shield_2.0
*
* This is sample program. Do not expect perfect behavior.
*******************************************************************************
*/
#include <usbh_midi.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>
USB Usb;
//USBHub Hub(&Usb);
USBH_MIDI Midi(&Usb);
void MIDI_poll();
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime);
boolean bFirst;
uint16_t pid, vid;
void setup()
{
bFirst = true;
vid = pid = 0;
Serial.begin(115200);
if (Usb.Init() == -1) {
while (1); //halt
}//if (Usb.Init() == -1...
delay( 200 );
}
void loop()
{
Usb.Task();
//uint32_t t1 = (uint32_t)micros();
if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
{
MIDI_poll();
}
//delay(1ms)
//doDelay(t1, (uint32_t)micros(), 1000);
}
// Poll USB MIDI Controler and send to serial MIDI
void MIDI_poll()
{
char buf[20];
uint8_t bufMidi[64];
uint16_t rcvd;
if (Midi.vid != vid || Midi.pid != pid) {
sprintf(buf, "VID:%04X, PID:%04X", Midi.vid, Midi.pid);
Serial.println(buf);
vid = Midi.vid;
pid = Midi.pid;
}
if (Midi.RecvData( &rcvd, bufMidi) == 0 ) {
uint32_t time = (uint32_t)millis();
sprintf(buf, "%04X%04X: ", (uint16_t)(time >> 16), (uint16_t)(time & 0xFFFF)); // Split variable to prevent warnings on the ESP8266 platform
Serial.print(buf);
Serial.print(rcvd);
Serial.print(':');
for (int i = 0; i < 64; i++) {
sprintf(buf, " %02X", bufMidi[i]);
Serial.print(buf);
}
Serial.println("");
}
}
// Delay time (max 16383 us)
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime)
{
uint32_t t3;
if ( t1 > t2 ) {
t3 = (0xFFFFFFFF - t1 + t2);
} else {
t3 = t2 - t1;
}
if ( t3 < delayTime ) {
delayMicroseconds(delayTime - t3);
}
}

View File

@ -0,0 +1,90 @@
/*
*******************************************************************************
* USB-MIDI to Legacy Serial MIDI converter
* Copyright (C) 2012-2017 Yuuichi Akagawa
*
* Idea from LPK25 USB-MIDI to Serial MIDI converter
* by Collin Cunningham - makezine.com, narbotic.com
*
* This is sample program. Do not expect perfect behavior.
*******************************************************************************
*/
#include <usbh_midi.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>
#ifdef USBCON
#define _MIDI_SERIAL_PORT Serial1
#else
#define _MIDI_SERIAL_PORT Serial
#endif
//////////////////////////
// MIDI Pin assign
// 2 : GND
// 4 : +5V(Vcc) with 220ohm
// 5 : TX
//////////////////////////
USB Usb;
USBH_MIDI Midi(&Usb);
void MIDI_poll();
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime);
void setup()
{
_MIDI_SERIAL_PORT.begin(31250);
if (Usb.Init() == -1) {
while (1); //halt
}//if (Usb.Init() == -1...
delay( 200 );
}
void loop()
{
Usb.Task();
uint32_t t1 = (uint32_t)micros();
if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
{
MIDI_poll();
}
//delay(1ms)
doDelay(t1, (uint32_t)micros(), 1000);
}
// Poll USB MIDI Controler and send to serial MIDI
void MIDI_poll()
{
uint8_t outBuf[ 3 ];
uint8_t size;
do {
if ( (size = Midi.RecvData(outBuf)) > 0 ) {
//MIDI Output
_MIDI_SERIAL_PORT.write(outBuf, size);
}
} while (size > 0);
}
// Delay time (max 16383 us)
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime)
{
uint32_t t3;
if ( t1 > t2 ) {
t3 = (0xFFFFFFFF - t1 + t2);
} else {
t3 = t2 - t1;
}
if ( t3 < delayTime ) {
delayMicroseconds(delayTime - t3);
}
}

View File

@ -0,0 +1,98 @@
/*
*******************************************************************************
* USB-MIDI to Legacy Serial MIDI converter
* Copyright (C) 2012-2017 Yuuichi Akagawa
*
* Idea from LPK25 USB-MIDI to Serial MIDI converter
* by Collin Cunningham - makezine.com, narbotic.com
*
* This is sample program. Do not expect perfect behavior.
*******************************************************************************
*/
#include <usbh_midi.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>
#ifdef USBCON
#define _MIDI_SERIAL_PORT Serial1
#else
#define _MIDI_SERIAL_PORT Serial
#endif
//////////////////////////
// MIDI Pin assign
// 2 : GND
// 4 : +5V(Vcc) with 220ohm
// 5 : TX
//////////////////////////
USB Usb;
USBHub Hub1(&Usb);
USBH_MIDI Midi1(&Usb);
USBH_MIDI Midi2(&Usb);
void MIDI_poll();
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime);
void setup()
{
_MIDI_SERIAL_PORT.begin(31250);
if (Usb.Init() == -1) {
while (1); //halt
}//if (Usb.Init() == -1...
delay( 200 );
}
void loop()
{
Usb.Task();
uint32_t t1 = (uint32_t)micros();
if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
{
MIDI_poll();
}
//delay(1ms)
doDelay(t1, (uint32_t)micros(), 1000);
}
// Poll USB MIDI Controler and send to serial MIDI
void MIDI_poll()
{
uint8_t outBuf[ 3 ];
uint8_t size;
do {
if ( (size = Midi1.RecvData(outBuf)) > 0 ) {
//MIDI Output
_MIDI_SERIAL_PORT.write(outBuf, size);
}
} while (size > 0);
do {
if ( (size = Midi2.RecvData(outBuf)) > 0 ) {
//MIDI Output
_MIDI_SERIAL_PORT.write(outBuf, size);
}
} while (size > 0);
}
// Delay time (max 16383 us)
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime)
{
uint32_t t3;
if ( t1 > t2 ) {
t3 = (0xFFFFFFFF - t1 + t2);
} else {
t3 = t2 - t1;
}
if ( t3 < delayTime ) {
delayMicroseconds(delayTime - t3);
}
}

View File

@ -0,0 +1,159 @@
/*
*******************************************************************************
* Legacy Serial MIDI and USB Host bidirectional converter
* Copyright (C) 2013-2017 Yuuichi Akagawa
*
* for use with Arduino MIDI library
* https://github.com/FortySevenEffects/arduino_midi_library/
*
* Note:
* - If you want use with Leonardo, you must choose Arduino MIDI library v4.0 or higher.
* - This is sample program. Do not expect perfect behavior.
*******************************************************************************
*/
#include <MIDI.h>
#include <usbh_midi.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>
//Arduino MIDI library v4.2 compatibility
#ifdef MIDI_CREATE_DEFAULT_INSTANCE
MIDI_CREATE_DEFAULT_INSTANCE();
#endif
#ifdef USBCON
#define _MIDI_SERIAL_PORT Serial1
#else
#define _MIDI_SERIAL_PORT Serial
#endif
//////////////////////////
// MIDI Pin assign
// 2 : GND
// 4 : +5V(Vcc) with 220ohm
// 5 : TX
//////////////////////////
USB Usb;
USBH_MIDI Midi(&Usb);
void MIDI_poll();
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime);
//If you want handle System Exclusive message, enable this #define otherwise comment out it.
#define USBH_MIDI_SYSEX_ENABLE
#ifdef USBH_MIDI_SYSEX_ENABLE
//SysEx:
void handle_sysex( byte* sysexmsg, unsigned sizeofsysex) {
Midi.SendSysEx(sysexmsg, sizeofsysex);
}
#endif
void setup()
{
MIDI.begin(MIDI_CHANNEL_OMNI);
#ifdef USBH_MIDI_SYSEX_ENABLE
MIDI.setHandleSystemExclusive(handle_sysex);
#endif
if (Usb.Init() == -1) {
while (1); //halt
}//if (Usb.Init() == -1...
delay( 200 );
}
void loop()
{
uint8_t msg[4];
Usb.Task();
uint32_t t1 = (uint32_t)micros();
if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
{
MIDI_poll();
if (MIDI.read()) {
msg[0] = MIDI.getType();
switch (msg[0]) {
case midi::ActiveSensing :
break;
case midi::SystemExclusive :
//SysEx is handled by event.
break;
default :
msg[1] = MIDI.getData1();
msg[2] = MIDI.getData2();
Midi.SendData(msg, 0);
break;
}
}
}
//delay(1ms)
doDelay(t1, (uint32_t)micros(), 1000);
}
// Poll USB MIDI Controler and send to serial MIDI
void MIDI_poll()
{
uint8_t size;
#ifdef USBH_MIDI_SYSEX_ENABLE
uint8_t recvBuf[MIDI_EVENT_PACKET_SIZE];
uint8_t rcode = 0; //return code
uint16_t rcvd;
uint8_t readPtr = 0;
rcode = Midi.RecvData( &rcvd, recvBuf);
//data check
if (rcode != 0) return;
if ( recvBuf[0] == 0 && recvBuf[1] == 0 && recvBuf[2] == 0 && recvBuf[3] == 0 ) {
return ;
}
uint8_t *p = recvBuf;
while (readPtr < MIDI_EVENT_PACKET_SIZE) {
if (*p == 0 && *(p + 1) == 0) break; //data end
uint8_t outbuf[3];
uint8_t rc = Midi.extractSysExData(p, outbuf);
if ( rc == 0 ) {
p++;
size = Midi.lookupMsgSize(*p);
_MIDI_SERIAL_PORT.write(p, size);
p += 3;
} else {
_MIDI_SERIAL_PORT.write(outbuf, rc);
p += 4;
}
readPtr += 4;
}
#else
uint8_t outBuf[3];
do {
if ( (size = Midi.RecvData(outBuf)) > 0 ) {
//MIDI Output
_MIDI_SERIAL_PORT.write(outBuf, size);
}
} while (size > 0);
#endif
}
// Delay time (max 16383 us)
void doDelay(uint32_t t1, uint32_t t2, uint32_t delayTime)
{
uint32_t t3;
if ( t1 > t2 ) {
t3 = (0xFFFFFFFF - t1 + t2);
} else {
t3 = t2 - t1;
}
if ( t3 < delayTime ) {
delayMicroseconds(delayTime - t3);
}
}

View File

@ -0,0 +1,93 @@
/*
*******************************************************************************
* eVY1 Shield sample - Say 'Konnichiwa'
* Copyright (C) 2014-2016 Yuuichi Akagawa
*
* This is sample program. Do not expect perfect behavior.
*******************************************************************************
*/
#include <usbh_midi.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>
USB Usb;
//USBHub Hub(&Usb);
USBH_MIDI Midi(&Usb);
void MIDI_poll();
void noteOn(uint8_t note);
void noteOff(uint8_t note);
uint16_t pid, vid;
uint8_t exdata[] = {
0xf0, 0x43, 0x79, 0x09, 0x00, 0x50, 0x10,
'k', ' ', 'o', ',', //Ko
'N', '\\', ',', //N
'J', ' ', 'i', ',', //Ni
't', 'S', ' ', 'i', ',', //Chi
'w', ' ', 'a', //Wa
0x00, 0xf7
};
void setup()
{
vid = pid = 0;
Serial.begin(115200);
if (Usb.Init() == -1) {
while (1); //halt
}//if (Usb.Init() == -1...
delay( 200 );
}
void loop()
{
Usb.Task();
if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
{
MIDI_poll();
noteOn(0x3f);
delay(400);
noteOff(0x3f);
delay(100);
}
}
// Poll USB MIDI Controler
void MIDI_poll()
{
uint8_t inBuf[ 3 ];
//first call?
if (Midi.vid != vid || Midi.pid != pid) {
vid = Midi.vid; pid = Midi.pid;
Midi.SendSysEx(exdata, sizeof(exdata));
delay(500);
}
Midi.RecvData(inBuf);
}
//note On
void noteOn(uint8_t note)
{
uint8_t buf[3];
buf[0] = 0x90;
buf[1] = note;
buf[2] = 0x7f;
Midi.SendData(buf);
}
//note Off
void noteOff(uint8_t note)
{
uint8_t buf[3];
buf[0] = 0x80;
buf[1] = note;
buf[2] = 0x00;
Midi.SendData(buf);
}

View File

@ -0,0 +1,346 @@
#include <usbhub.h>
#include "pgmstrings.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
//USBHub Hub1(&Usb);
//USBHub Hub2(&Usb);
//USBHub Hub3(&Usb);
//USBHub Hub4(&Usb);
//USBHub Hub5(&Usb);
//USBHub Hub6(&Usb);
//USBHub Hub7(&Usb);
void PrintAllAddresses(UsbDevice *pdev)
{
UsbDeviceAddress adr;
adr.devAddress = pdev->address.devAddress;
Serial.print("\r\nAddr:");
Serial.print(adr.devAddress, HEX);
Serial.print("(");
Serial.print(adr.bmHub, HEX);
Serial.print(".");
Serial.print(adr.bmParent, HEX);
Serial.print(".");
Serial.print(adr.bmAddress, HEX);
Serial.println(")");
}
void PrintAddress(uint8_t addr)
{
UsbDeviceAddress adr;
adr.devAddress = addr;
Serial.print("\r\nADDR:\t");
Serial.println(adr.devAddress, HEX);
Serial.print("DEV:\t");
Serial.println(adr.bmAddress, HEX);
Serial.print("PRNT:\t");
Serial.println(adr.bmParent, HEX);
Serial.print("HUB:\t");
Serial.println(adr.bmHub, HEX);
}
void setup()
{
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
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("OSC did not start.");
delay( 200 );
}
uint8_t getdevdescr( uint8_t addr, uint8_t &num_conf );
void PrintDescriptors(uint8_t addr)
{
uint8_t rcode = 0;
uint8_t num_conf = 0;
rcode = getdevdescr( (uint8_t)addr, num_conf );
if ( rcode )
{
printProgStr(Gen_Error_str);
print_hex( rcode, 8 );
}
Serial.print("\r\n");
for (int i = 0; i < num_conf; i++)
{
rcode = getconfdescr( addr, i ); // get configuration descriptor
if ( rcode )
{
printProgStr(Gen_Error_str);
print_hex(rcode, 8);
}
Serial.println("\r\n");
}
}
void PrintAllDescriptors(UsbDevice *pdev)
{
Serial.println("\r\n");
print_hex(pdev->address.devAddress, 8);
Serial.println("\r\n--");
PrintDescriptors( pdev->address.devAddress );
}
void loop()
{
Usb.Task();
if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
{
Usb.ForEachUsbDevice(&PrintAllDescriptors);
Usb.ForEachUsbDevice(&PrintAllAddresses);
while ( 1 ) { // stop
#ifdef ESP8266
yield(); // needed in order to reset the watchdog timer on the ESP8266
#endif
}
}
}
uint8_t getdevdescr( uint8_t addr, uint8_t &num_conf )
{
USB_DEVICE_DESCRIPTOR buf;
uint8_t rcode;
rcode = Usb.getDevDescr( addr, 0, 0x12, ( uint8_t *)&buf );
if ( rcode ) {
return ( rcode );
}
printProgStr(Dev_Header_str);
printProgStr(Dev_Length_str);
print_hex( buf.bLength, 8 );
printProgStr(Dev_Type_str);
print_hex( buf.bDescriptorType, 8 );
printProgStr(Dev_Version_str);
print_hex( buf.bcdUSB, 16 );
printProgStr(Dev_Class_str);
print_hex( buf.bDeviceClass, 8 );
printProgStr(Dev_Subclass_str);
print_hex( buf.bDeviceSubClass, 8 );
printProgStr(Dev_Protocol_str);
print_hex( buf.bDeviceProtocol, 8 );
printProgStr(Dev_Pktsize_str);
print_hex( buf.bMaxPacketSize0, 8 );
printProgStr(Dev_Vendor_str);
print_hex( buf.idVendor, 16 );
printProgStr(Dev_Product_str);
print_hex( buf.idProduct, 16 );
printProgStr(Dev_Revision_str);
print_hex( buf.bcdDevice, 16 );
printProgStr(Dev_Mfg_str);
print_hex( buf.iManufacturer, 8 );
printProgStr(Dev_Prod_str);
print_hex( buf.iProduct, 8 );
printProgStr(Dev_Serial_str);
print_hex( buf.iSerialNumber, 8 );
printProgStr(Dev_Nconf_str);
print_hex( buf.bNumConfigurations, 8 );
num_conf = buf.bNumConfigurations;
return ( 0 );
}
void printhubdescr(uint8_t *descrptr, uint8_t addr)
{
HubDescriptor *pHub = (HubDescriptor*) descrptr;
uint8_t len = *((uint8_t*)descrptr);
printProgStr(PSTR("\r\n\r\nHub Descriptor:\r\n"));
printProgStr(PSTR("bDescLength:\t\t"));
Serial.println(pHub->bDescLength, HEX);
printProgStr(PSTR("bDescriptorType:\t"));
Serial.println(pHub->bDescriptorType, HEX);
printProgStr(PSTR("bNbrPorts:\t\t"));
Serial.println(pHub->bNbrPorts, HEX);
printProgStr(PSTR("LogPwrSwitchMode:\t"));
Serial.println(pHub->LogPwrSwitchMode, BIN);
printProgStr(PSTR("CompoundDevice:\t\t"));
Serial.println(pHub->CompoundDevice, BIN);
printProgStr(PSTR("OverCurrentProtectMode:\t"));
Serial.println(pHub->OverCurrentProtectMode, BIN);
printProgStr(PSTR("TTThinkTime:\t\t"));
Serial.println(pHub->TTThinkTime, BIN);
printProgStr(PSTR("PortIndicatorsSupported:"));
Serial.println(pHub->PortIndicatorsSupported, BIN);
printProgStr(PSTR("Reserved:\t\t"));
Serial.println(pHub->Reserved, HEX);
printProgStr(PSTR("bPwrOn2PwrGood:\t\t"));
Serial.println(pHub->bPwrOn2PwrGood, HEX);
printProgStr(PSTR("bHubContrCurrent:\t"));
Serial.println(pHub->bHubContrCurrent, HEX);
for (uint8_t i = 7; i < len; i++)
print_hex(descrptr[i], 8);
//for (uint8_t i=1; i<=pHub->bNbrPorts; i++)
// PrintHubPortStatus(&Usb, addr, i, 1);
}
uint8_t getconfdescr( uint8_t addr, uint8_t conf )
{
uint8_t buf[ BUFSIZE ];
uint8_t* buf_ptr = buf;
uint8_t rcode;
uint8_t descr_length;
uint8_t descr_type;
uint16_t total_length;
rcode = Usb.getConfDescr( addr, 0, 4, conf, buf ); //get total length
LOBYTE( total_length ) = buf[ 2 ];
HIBYTE( total_length ) = buf[ 3 ];
if ( total_length > 256 ) { //check if total length is larger than buffer
printProgStr(Conf_Trunc_str);
total_length = 256;
}
rcode = Usb.getConfDescr( addr, 0, total_length, conf, buf ); //get the whole descriptor
while ( buf_ptr < buf + total_length ) { //parsing descriptors
descr_length = *( buf_ptr );
descr_type = *( buf_ptr + 1 );
switch ( descr_type ) {
case ( USB_DESCRIPTOR_CONFIGURATION ):
printconfdescr( buf_ptr );
break;
case ( USB_DESCRIPTOR_INTERFACE ):
printintfdescr( buf_ptr );
break;
case ( USB_DESCRIPTOR_ENDPOINT ):
printepdescr( buf_ptr );
break;
case 0x29:
printhubdescr( buf_ptr, addr );
break;
default:
printunkdescr( buf_ptr );
break;
}//switch( descr_type
buf_ptr = ( buf_ptr + descr_length ); //advance buffer pointer
}//while( buf_ptr <=...
return ( rcode );
}
/* prints hex numbers with leading zeroes */
// copyright, Peter H Anderson, Baltimore, MD, Nov, '07
// source: http://www.phanderson.com/arduino/arduino_display.html
void print_hex(int v, int num_places)
{
int mask = 0, n, num_nibbles, digit;
for (n = 1; n <= num_places; n++) {
mask = (mask << 1) | 0x0001;
}
v = v & mask; // truncate v to specified number of places
num_nibbles = num_places / 4;
if ((num_places % 4) != 0) {
++num_nibbles;
}
do {
digit = ((v >> (num_nibbles - 1) * 4)) & 0x0f;
Serial.print(digit, HEX);
}
while (--num_nibbles);
}
/* function to print configuration descriptor */
void printconfdescr( uint8_t* descr_ptr )
{
USB_CONFIGURATION_DESCRIPTOR* conf_ptr = ( USB_CONFIGURATION_DESCRIPTOR* )descr_ptr;
printProgStr(Conf_Header_str);
printProgStr(Conf_Totlen_str);
print_hex( conf_ptr->wTotalLength, 16 );
printProgStr(Conf_Nint_str);
print_hex( conf_ptr->bNumInterfaces, 8 );
printProgStr(Conf_Value_str);
print_hex( conf_ptr->bConfigurationValue, 8 );
printProgStr(Conf_String_str);
print_hex( conf_ptr->iConfiguration, 8 );
printProgStr(Conf_Attr_str);
print_hex( conf_ptr->bmAttributes, 8 );
printProgStr(Conf_Pwr_str);
print_hex( conf_ptr->bMaxPower, 8 );
return;
}
/* function to print interface descriptor */
void printintfdescr( uint8_t* descr_ptr )
{
USB_INTERFACE_DESCRIPTOR* intf_ptr = ( USB_INTERFACE_DESCRIPTOR* )descr_ptr;
printProgStr(Int_Header_str);
printProgStr(Int_Number_str);
print_hex( intf_ptr->bInterfaceNumber, 8 );
printProgStr(Int_Alt_str);
print_hex( intf_ptr->bAlternateSetting, 8 );
printProgStr(Int_Endpoints_str);
print_hex( intf_ptr->bNumEndpoints, 8 );
printProgStr(Int_Class_str);
print_hex( intf_ptr->bInterfaceClass, 8 );
printProgStr(Int_Subclass_str);
print_hex( intf_ptr->bInterfaceSubClass, 8 );
printProgStr(Int_Protocol_str);
print_hex( intf_ptr->bInterfaceProtocol, 8 );
printProgStr(Int_String_str);
print_hex( intf_ptr->iInterface, 8 );
return;
}
/* function to print endpoint descriptor */
void printepdescr( uint8_t* descr_ptr )
{
USB_ENDPOINT_DESCRIPTOR* ep_ptr = ( USB_ENDPOINT_DESCRIPTOR* )descr_ptr;
printProgStr(End_Header_str);
printProgStr(End_Address_str);
print_hex( ep_ptr->bEndpointAddress, 8 );
printProgStr(End_Attr_str);
print_hex( ep_ptr->bmAttributes, 8 );
printProgStr(End_Pktsize_str);
print_hex( ep_ptr->wMaxPacketSize, 16 );
printProgStr(End_Interval_str);
print_hex( ep_ptr->bInterval, 8 );
return;
}
/*function to print unknown descriptor */
void printunkdescr( uint8_t* descr_ptr )
{
uint8_t length = *descr_ptr;
uint8_t i;
printProgStr(Unk_Header_str);
printProgStr(Unk_Length_str);
print_hex( *descr_ptr, 8 );
printProgStr(Unk_Type_str);
print_hex( *(descr_ptr + 1 ), 8 );
printProgStr(Unk_Contents_str);
descr_ptr += 2;
for ( i = 0; i < length; i++ ) {
print_hex( *descr_ptr, 8 );
descr_ptr++;
}
}
/* Print a string from Program Memory directly to save RAM */
void printProgStr(const char* str)
{
char c;
if (!str) return;
while ((c = pgm_read_byte(str++)))
Serial.print(c);
}

View File

@ -0,0 +1,52 @@
#if !defined(__PGMSTRINGS_H__)
#define __PGMSTRINGS_H__
#define LOBYTE(x) ((char*)(&(x)))[0]
#define HIBYTE(x) ((char*)(&(x)))[1]
#define BUFSIZE 256 //buffer size
/* Print strings in Program Memory */
const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t";
const char Dev_Header_str[] PROGMEM ="\r\nDevice descriptor: ";
const char Dev_Length_str[] PROGMEM ="\r\nDescriptor Length:\t";
const char Dev_Type_str[] PROGMEM ="\r\nDescriptor type:\t";
const char Dev_Version_str[] PROGMEM ="\r\nUSB version:\t\t";
const char Dev_Class_str[] PROGMEM ="\r\nDevice class:\t\t";
const char Dev_Subclass_str[] PROGMEM ="\r\nDevice Subclass:\t";
const char Dev_Protocol_str[] PROGMEM ="\r\nDevice Protocol:\t";
const char Dev_Pktsize_str[] PROGMEM ="\r\nMax.packet size:\t";
const char Dev_Vendor_str[] PROGMEM ="\r\nVendor ID:\t\t";
const char Dev_Product_str[] PROGMEM ="\r\nProduct ID:\t\t";
const char Dev_Revision_str[] PROGMEM ="\r\nRevision ID:\t\t";
const char Dev_Mfg_str[] PROGMEM ="\r\nMfg.string index:\t";
const char Dev_Prod_str[] PROGMEM ="\r\nProd.string index:\t";
const char Dev_Serial_str[] PROGMEM ="\r\nSerial number index:\t";
const char Dev_Nconf_str[] PROGMEM ="\r\nNumber of conf.:\t";
const char Conf_Trunc_str[] PROGMEM ="Total length truncated to 256 bytes";
const char Conf_Header_str[] PROGMEM ="\r\nConfiguration descriptor:";
const char Conf_Totlen_str[] PROGMEM ="\r\nTotal length:\t\t";
const char Conf_Nint_str[] PROGMEM ="\r\nNum.intf:\t\t";
const char Conf_Value_str[] PROGMEM ="\r\nConf.value:\t\t";
const char Conf_String_str[] PROGMEM ="\r\nConf.string:\t\t";
const char Conf_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
const char Conf_Pwr_str[] PROGMEM ="\r\nMax.pwr:\t\t";
const char Int_Header_str[] PROGMEM ="\r\n\r\nInterface descriptor:";
const char Int_Number_str[] PROGMEM ="\r\nIntf.number:\t\t";
const char Int_Alt_str[] PROGMEM ="\r\nAlt.:\t\t\t";
const char Int_Endpoints_str[] PROGMEM ="\r\nEndpoints:\t\t";
const char Int_Class_str[] PROGMEM ="\r\nIntf. Class:\t\t";
const char Int_Subclass_str[] PROGMEM ="\r\nIntf. Subclass:\t\t";
const char Int_Protocol_str[] PROGMEM ="\r\nIntf. Protocol:\t\t";
const char Int_String_str[] PROGMEM ="\r\nIntf.string:\t\t";
const char End_Header_str[] PROGMEM ="\r\n\r\nEndpoint descriptor:";
const char End_Address_str[] PROGMEM ="\r\nEndpoint address:\t";
const char End_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
const char End_Pktsize_str[] PROGMEM ="\r\nMax.pkt size:\t\t";
const char End_Interval_str[] PROGMEM ="\r\nPolling interval:\t";
const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:";
const char Unk_Length_str[] PROGMEM ="\r\nLength:\t\t";
const char Unk_Type_str[] PROGMEM ="\r\nType:\t\t";
const char Unk_Contents_str[] PROGMEM ="\r\nContents:\t";
#endif // __PGMSTRINGS_H__

View File

@ -0,0 +1,110 @@
/*
Example sketch for the original Xbox library - developed by Kristian Lauszus
For more information visit my blog: http://blog.tkjelectronics.dk/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <XBOXOLD.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>
USB Usb;
USBHub Hub1(&Usb); // The controller has a built in hub, so this instance is needed
XBOXOLD Xbox(&Usb);
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); // halt
}
Serial.print(F("\r\nXBOX Library Started"));
}
void loop() {
Usb.Task();
if (Xbox.XboxConnected) {
if (Xbox.getButtonPress(BLACK) || Xbox.getButtonPress(WHITE)) {
Serial.print("BLACK: ");
Serial.print(Xbox.getButtonPress(BLACK));
Serial.print("\tWHITE: ");
Serial.println(Xbox.getButtonPress(WHITE));
Xbox.setRumbleOn(Xbox.getButtonPress(BLACK), Xbox.getButtonPress(WHITE));
} else
Xbox.setRumbleOn(0, 0);
if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500 || Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500 || Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500 || Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500) {
Serial.print(F("LeftHatX: "));
Serial.print(Xbox.getAnalogHat(LeftHatX));
Serial.print("\t");
}
if (Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500) {
Serial.print(F("LeftHatY: "));
Serial.print(Xbox.getAnalogHat(LeftHatY));
Serial.print("\t");
}
if (Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500) {
Serial.print(F("RightHatX: "));
Serial.print(Xbox.getAnalogHat(RightHatX));
Serial.print("\t");
}
if (Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
Serial.print(F("RightHatY: "));
Serial.print(Xbox.getAnalogHat(RightHatY));
}
Serial.println();
}
if (Xbox.getButtonClick(UP))
Serial.println(F("Up"));
if (Xbox.getButtonClick(DOWN))
Serial.println(F("Down"));
if (Xbox.getButtonClick(LEFT))
Serial.println(F("Left"));
if (Xbox.getButtonClick(RIGHT))
Serial.println(F("Right"));
if (Xbox.getButtonClick(START))
Serial.println(F("Start"));
if (Xbox.getButtonClick(BACK))
Serial.println(F("Back"));
if (Xbox.getButtonClick(L3))
Serial.println(F("L3"));
if (Xbox.getButtonClick(R3))
Serial.println(F("R3"));
if (Xbox.getButtonPress(A)) {
Serial.print(F("A: "));
Serial.println(Xbox.getButtonPress(A));
}
if (Xbox.getButtonPress(B)) {
Serial.print(F("B: "));
Serial.println(Xbox.getButtonPress(B));
}
if (Xbox.getButtonPress(X)) {
Serial.print(F("X: "));
Serial.println(Xbox.getButtonPress(X));
}
if (Xbox.getButtonPress(Y)) {
Serial.print(F("Y: "));
Serial.println(Xbox.getButtonPress(Y));
}
if (Xbox.getButtonPress(L1)) {
Serial.print(F("L1: "));
Serial.println(Xbox.getButtonPress(L1));
}
if (Xbox.getButtonPress(R1)) {
Serial.print(F("R1: "));
Serial.println(Xbox.getButtonPress(R1));
}
}
delay(1);
}

View File

@ -0,0 +1,121 @@
/*
Example sketch for the Xbox ONE USB library - by guruthree, based on work by
Kristian Lauszus.
*/
#include <XBOXONE.h>
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
XBOXONE Xbox(&Usb);
void setup() {
Serial.begin(115200);
while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nXBOX USB Library Started"));
}
void loop() {
Usb.Task();
if (Xbox.XboxOneConnected) {
if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500 || Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500 || Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500 || Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500) {
Serial.print(F("LeftHatX: "));
Serial.print(Xbox.getAnalogHat(LeftHatX));
Serial.print("\t");
}
if (Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500) {
Serial.print(F("LeftHatY: "));
Serial.print(Xbox.getAnalogHat(LeftHatY));
Serial.print("\t");
}
if (Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500) {
Serial.print(F("RightHatX: "));
Serial.print(Xbox.getAnalogHat(RightHatX));
Serial.print("\t");
}
if (Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
Serial.print(F("RightHatY: "));
Serial.print(Xbox.getAnalogHat(RightHatY));
}
Serial.println();
}
if (Xbox.getButtonPress(L2) > 0 || Xbox.getButtonPress(R2) > 0) {
if (Xbox.getButtonPress(L2) > 0) {
Serial.print(F("L2: "));
Serial.print(Xbox.getButtonPress(L2));
Serial.print("\t");
}
if (Xbox.getButtonPress(R2) > 0) {
Serial.print(F("R2: "));
Serial.print(Xbox.getButtonPress(R2));
Serial.print("\t");
}
Serial.println();
}
// Set rumble effect
static uint16_t oldL2Value, oldR2Value;
if (Xbox.getButtonPress(L2) != oldL2Value || Xbox.getButtonPress(R2) != oldR2Value) {
oldL2Value = Xbox.getButtonPress(L2);
oldR2Value = Xbox.getButtonPress(R2);
uint8_t leftRumble = map(oldL2Value, 0, 1023, 0, 255); // Map the trigger values into a byte
uint8_t rightRumble = map(oldR2Value, 0, 1023, 0, 255);
if (leftRumble > 0 || rightRumble > 0)
Xbox.setRumbleOn(leftRumble, rightRumble, leftRumble, rightRumble);
else
Xbox.setRumbleOff();
}
if (Xbox.getButtonClick(UP))
Serial.println(F("Up"));
if (Xbox.getButtonClick(DOWN))
Serial.println(F("Down"));
if (Xbox.getButtonClick(LEFT))
Serial.println(F("Left"));
if (Xbox.getButtonClick(RIGHT))
Serial.println(F("Right"));
if (Xbox.getButtonClick(START))
Serial.println(F("Start"));
if (Xbox.getButtonClick(BACK))
Serial.println(F("Back"));
if (Xbox.getButtonClick(XBOX))
Serial.println(F("Xbox"));
if (Xbox.getButtonClick(SYNC))
Serial.println(F("Sync"));
if (Xbox.getButtonClick(L1))
Serial.println(F("L1"));
if (Xbox.getButtonClick(R1))
Serial.println(F("R1"));
if (Xbox.getButtonClick(L2))
Serial.println(F("L2"));
if (Xbox.getButtonClick(R2))
Serial.println(F("R2"));
if (Xbox.getButtonClick(L3))
Serial.println(F("L3"));
if (Xbox.getButtonClick(R3))
Serial.println(F("R3"));
if (Xbox.getButtonClick(A))
Serial.println(F("A"));
if (Xbox.getButtonClick(B))
Serial.println(F("B"));
if (Xbox.getButtonClick(X))
Serial.println(F("X"));
if (Xbox.getButtonClick(Y))
Serial.println(F("Y"));
}
delay(1);
}

View File

@ -0,0 +1,122 @@
/*
Example sketch for the Xbox Wireless Reciver library - developed by Kristian Lauszus
It supports up to four controllers wirelessly
For more information see the blog post: http://blog.tkjelectronics.dk/2012/12/xbox-360-receiver-added-to-the-usb-host-library/ or
send me an e-mail: kristianl@tkjelectronics.com
*/
#include <XBOXRECV.h>
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
USB Usb;
XBOXRECV Xbox(&Usb);
void setup() {
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
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nXbox Wireless Receiver Library Started"));
}
void loop() {
Usb.Task();
if (Xbox.XboxReceiverConnected) {
for (uint8_t i = 0; i < 4; i++) {
if (Xbox.Xbox360Connected[i]) {
if (Xbox.getButtonPress(L2, i) || Xbox.getButtonPress(R2, i)) {
Serial.print("L2: ");
Serial.print(Xbox.getButtonPress(L2, i));
Serial.print("\tR2: ");
Serial.println(Xbox.getButtonPress(R2, i));
Xbox.setRumbleOn(Xbox.getButtonPress(L2, i), Xbox.getButtonPress(R2, i), i);
}
if (Xbox.getAnalogHat(LeftHatX, i) > 7500 || Xbox.getAnalogHat(LeftHatX, i) < -7500 || Xbox.getAnalogHat(LeftHatY, i) > 7500 || Xbox.getAnalogHat(LeftHatY, i) < -7500 || Xbox.getAnalogHat(RightHatX, i) > 7500 || Xbox.getAnalogHat(RightHatX, i) < -7500 || Xbox.getAnalogHat(RightHatY, i) > 7500 || Xbox.getAnalogHat(RightHatY, i) < -7500) {
if (Xbox.getAnalogHat(LeftHatX, i) > 7500 || Xbox.getAnalogHat(LeftHatX, i) < -7500) {
Serial.print(F("LeftHatX: "));
Serial.print(Xbox.getAnalogHat(LeftHatX, i));
Serial.print("\t");
}
if (Xbox.getAnalogHat(LeftHatY, i) > 7500 || Xbox.getAnalogHat(LeftHatY, i) < -7500) {
Serial.print(F("LeftHatY: "));
Serial.print(Xbox.getAnalogHat(LeftHatY, i));
Serial.print("\t");
}
if (Xbox.getAnalogHat(RightHatX, i) > 7500 || Xbox.getAnalogHat(RightHatX, i) < -7500) {
Serial.print(F("RightHatX: "));
Serial.print(Xbox.getAnalogHat(RightHatX, i));
Serial.print("\t");
}
if (Xbox.getAnalogHat(RightHatY, i) > 7500 || Xbox.getAnalogHat(RightHatY, i) < -7500) {
Serial.print(F("RightHatY: "));
Serial.print(Xbox.getAnalogHat(RightHatY, i));
}
Serial.println();
}
if (Xbox.getButtonClick(UP, i)) {
Xbox.setLedOn(LED1, i);
Serial.println(F("Up"));
}
if (Xbox.getButtonClick(DOWN, i)) {
Xbox.setLedOn(LED4, i);
Serial.println(F("Down"));
}
if (Xbox.getButtonClick(LEFT, i)) {
Xbox.setLedOn(LED3, i);
Serial.println(F("Left"));
}
if (Xbox.getButtonClick(RIGHT, i)) {
Xbox.setLedOn(LED2, i);
Serial.println(F("Right"));
}
if (Xbox.getButtonClick(START, i)) {
Xbox.setLedMode(ALTERNATING, i);
Serial.println(F("Start"));
}
if (Xbox.getButtonClick(BACK, i)) {
Xbox.setLedBlink(ALL, i);
Serial.println(F("Back"));
}
if (Xbox.getButtonClick(L3, i))
Serial.println(F("L3"));
if (Xbox.getButtonClick(R3, i))
Serial.println(F("R3"));
if (Xbox.getButtonClick(L1, i))
Serial.println(F("L1"));
if (Xbox.getButtonClick(R1, i))
Serial.println(F("R1"));
if (Xbox.getButtonClick(XBOX, i)) {
Xbox.setLedMode(ROTATING, i);
Serial.print(F("Xbox (Battery: "));
Serial.print(Xbox.getBatteryLevel(i)); // The battery level in the range 0-3
Serial.println(F(")"));
}
if (Xbox.getButtonClick(SYNC, i)) {
Serial.println(F("Sync"));
Xbox.disconnect(i);
}
if (Xbox.getButtonClick(A, i))
Serial.println(F("A"));
if (Xbox.getButtonClick(B, i))
Serial.println(F("B"));
if (Xbox.getButtonClick(X, i))
Serial.println(F("X"));
if (Xbox.getButtonClick(Y, i))
Serial.println(F("Y"));
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More