新增xbox手柄测试文件

This commit is contained in:
myperworld committed 2025-10-21 09:33:18 +08:00
1 parent 78219e6a1f
commit 45d8bc4e32
421 files changed
+174127

No files matched your search

@@ -0,0 +1,158 @@
#include "XboxControllerNotificationParser.h"
#define XBOX_CONTROLLER_INDEX_BUTTONS_DIR 12
#define XBOX_CONTROLLER_INDEX_BUTTONS_MAIN 13
#define XBOX_CONTROLLER_INDEX_BUTTONS_CENTER 14
#define XBOX_CONTROLLER_INDEX_BUTTONS_SHARE 15
XboxControllerNotificationParser::XboxControllerNotificationParser() {
btnA = btnB = btnX = btnY = false;
btnShare = btnStart = btnSelect = btnXbox = false;
btnLB = btnRB = btnLS = btnRS = false;
btnDirUp = btnDirLeft = btnDirRight = btnDirDown = false;
joyLHori = joyLVert = joyRHori = joyRVert = 0xffff / 2;
trigLT = trigRT = 0;
}
uint8_t XboxControllerNotificationParser::update(uint8_t* data, size_t length) {
if (length != expectedDataLen) {
return XBOX_CONTROLLER_ERROR_INVALID_LENGTH;
}
for (uint8_t i = 0; i < expectedDataLen; i++)
{
rx_buf[i]=data[i];
}
uint8_t btnBits;
btnBits = data[XBOX_CONTROLLER_INDEX_BUTTONS_MAIN];
btnA = btnBits & 0b00000001;
btnB = btnBits & 0b00000010;
btnX = btnBits & 0b00001000;
btnY = btnBits & 0b00010000;
btnLB = btnBits & 0b01000000;
btnRB = btnBits & 0b10000000;
btnBits = data[XBOX_CONTROLLER_INDEX_BUTTONS_CENTER];
btnSelect = btnBits & 0b00000100;
btnStart = btnBits & 0b00001000;
btnXbox = btnBits & 0b00010000;
btnLS = btnBits & 0b00100000;
btnRS = btnBits & 0b01000000;
btnBits = data[XBOX_CONTROLLER_INDEX_BUTTONS_SHARE];
btnShare = btnBits & 0b00000001;
btnBits = data[XBOX_CONTROLLER_INDEX_BUTTONS_DIR];
btnDirUp = btnBits == 1 || btnBits == 2 || btnBits == 8;
btnDirRight = 2 <= btnBits && btnBits <= 4;
btnDirDown = 4 <= btnBits && btnBits <= 6;
btnDirLeft = 6 <= btnBits && btnBits <= 8;
joyLHori = (uint16_t)data[0] | ((uint16_t)data[1] << 8);
joyLVert = (uint16_t)data[2] | ((uint16_t)data[3] << 8);
joyRHori = (uint16_t)data[4] | ((uint16_t)data[5] << 8);
joyRVert = (uint16_t)data[6] | ((uint16_t)data[7] << 8);
trigLT = (uint16_t)data[8] | ((uint16_t)data[9] << 8);
trigRT = (uint16_t)data[10] | ((uint16_t)data[11] << 8);
return 0;
}
void XboxControllerNotificationParser::convertU16TU8Arr(uint16_t vU16,
uint8_t* data) {
data[0] = vU16 & 0xff;
data[1] = vU16 >> 8;
}
uint8_t XboxControllerNotificationParser::toArr(uint8_t* data, size_t length) {
if (length < expectedDataLen) {
return XBOX_CONTROLLER_ERROR_INVALID_LENGTH;
}
convertU16TU8Arr(joyLHori, &data[0]);
convertU16TU8Arr(joyLVert, &data[2]);
convertU16TU8Arr(joyRHori, &data[4]);
convertU16TU8Arr(joyRVert, &data[6]);
convertU16TU8Arr(trigLT, &data[8]);
convertU16TU8Arr(trigRT, &data[10]);
{
uint8_t btnBits = 0;
if (btnA) btnBits |= 0b00000001;
if (btnB) btnBits |= 0b00000010;
if (btnX) btnBits |= 0b00001000;
if (btnY) btnBits |= 0b00010000;
if (btnLB) btnBits |= 0b01000000;
if (btnRB) btnBits |= 0b10000000;
data[XBOX_CONTROLLER_INDEX_BUTTONS_MAIN] = btnBits;
}
{
uint8_t btnBits = 0;
if (btnSelect) btnBits |= 0b00000100;
if (btnStart) btnBits |= 0b00001000;
if (btnXbox) btnBits |= 0b00010000;
if (btnLS) btnBits |= 0b00100000;
if (btnRS) btnBits |= 0b01000000;
data[XBOX_CONTROLLER_INDEX_BUTTONS_CENTER] = btnBits;
}
{
uint8_t btnBits = 0;
if (btnShare) btnBits |= 0b00000001;
data[XBOX_CONTROLLER_INDEX_BUTTONS_SHARE] = btnBits;
}
{
uint8_t btnBits = 0;
if (btnDirUp) {
if (btnDirRight) {
btnBits = 2;
} else if (btnDirLeft) {
btnBits = 8;
} else {
btnBits = 1;
}
} else if (btnDirDown) {
if (btnDirRight) {
btnBits = 4;
} else if (btnDirLeft) {
btnBits = 6;
} else {
btnBits = 5;
}
} else {
if (btnDirRight) {
btnBits = 3;
} else if (btnDirLeft) {
btnBits = 7;
} else {
btnBits = 0;
}
}
data[XBOX_CONTROLLER_INDEX_BUTTONS_DIR] = btnBits;
}
return 0;
}
String XboxControllerNotificationParser::toString() {
// clang-format off
String str = String("") +
"btnY: " + String(btnY) + " " +
"btnX: " + String(btnX) + " " +
"btnB: " + String(btnB) + " " +
"btnA: " + String(btnA) + " " +
"btnLB: " + String(btnLB) + " " +
"btnRB: " + String(btnRB) + "\n" +
"btnSelect: " + String(btnSelect) + " " +
"btnStart: " + String(btnStart) + " " +
"btnXbox: " + String(btnXbox) + " " +
"btnShare: " + String(btnShare) + " " +
"btnLS: " + String(btnLS) + " " +
"btnRS: " + String(btnRS) + "\n" +
"btnDirUp: " + String(btnDirUp) + " " +
"btnDirRight: " + String(btnDirRight) + " " +
"btnDirDown: " + String(btnDirDown) + " " +
"btnDirLeft: " + String(btnDirLeft) + "\n"
"joyLHori: " + String(joyLHori) + "\n" +
"joyLVert: " + String(joyLVert) + "\n" +
"joyRHori: " + String(joyRHori) + "\n" +
"joyRVert: " + String(joyRVert) + "\n" +
"trigLT: " + String(trigLT) + "\n" +
"trigRT: " + String(trigRT) + "\n";
// clang-format on
return str;
}
@@ -0,0 +1,36 @@
#ifndef __XBOX_CONTROLLER_NOTIFICATION_PARSER_H__
#define __XBOX_CONTROLLER_NOTIFICATION_PARSER_H__
#include <Arduino.h>
#define XBOX_CONTROLLER_ERROR_INVALID_LENGTH 1
class XboxControllerNotificationParser {
public:
XboxControllerNotificationParser();
bool btnA, btnB, btnX, btnY;
bool btnShare, btnStart, btnSelect, btnXbox;
// side top button
bool btnLB, btnRB;
// button on joy stick
bool btnLS, btnRS;
bool btnDirUp, btnDirLeft, btnDirRight, btnDirDown;
uint16_t joyLHori = maxJoy / 2;
uint16_t joyLVert = maxJoy / 2;
uint16_t joyRHori = maxJoy / 2;
uint16_t joyRVert = maxJoy / 2;
uint16_t trigLT, trigRT;
uint8_t update(uint8_t* data, size_t length);
uint8_t toArr(uint8_t* data, size_t length);
String toString();
static const size_t expectedDataLen = 16;
static const uint16_t maxJoy = 0xffff;
static const uint16_t maxTrig = 0x3ff;
uint8_t rx_buf[expectedDataLen];
private:
static void convertU16TU8Arr(uint16_t vU16, uint8_t* data);
};
#endif
@@ -0,0 +1,553 @@
#pragma once
#include <NimBLEDevice.h>
#include <XboxControllerNotificationParser.h>
#include <XboxSeriesXHIDReportBuilder_asukiaaa.hpp>
// #define XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL Serial
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
const unsigned long printInterval = 100UL;
#endif
namespace XboxSeriesXControllerESP32_asukiaaa {
static NimBLEUUID uuidServiceGeneral("1801");
static NimBLEUUID uuidServiceBattery("180f");
static NimBLEUUID uuidServiceHid("1812");
static NimBLEUUID uuidCharaReport("2a4d");
static NimBLEUUID uuidCharaPnp("2a50");
static NimBLEUUID uuidCharaHidInformation("2a4a");
static NimBLEUUID uuidCharaPeripheralAppearance("2a01");
static NimBLEUUID uuidCharaPeripheralControlParameters("2a04");
static NimBLEAdvertisedDevice* advDevice;
static NimBLEClient* pConnectedClient = nullptr;
static const uint16_t controllerAppearance = 964;
static const String controllerManufacturerDataNormal = "060000";
static const String controllerManufacturerDataSearching = "0600030080";
enum class ConnectionState : uint8_t {
Connected = 0,
WaitingForFirstNotification = 1,
Found = 2,
Scanning = 3,
};
class ClientCallbacks : public NimBLEClientCallbacks {
public:
ConnectionState* pConnectionState;
ClientCallbacks(ConnectionState* pConnectionState) {
this->pConnectionState = pConnectionState;
}
void onConnect(NimBLEClient* pClient) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("Connected");
#endif
*pConnectionState = ConnectionState::WaitingForFirstNotification;
// pClient->updateConnParams(120,120,0,60);
};
void onDisconnect(NimBLEClient* pClient) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.print(
pClient->getPeerAddress().toString().c_str());
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(" Disconnected");
#endif
*pConnectionState = ConnectionState::Scanning;
pConnectedClient = nullptr;
};
/********************* Security handled here **********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyRequest() {
// Serial.println("Client Passkey Request");
/** return the passkey to send to the server */
return 0;
};
bool onConfirmPIN(uint32_t pass_key) {
// Serial.print("The passkey YES/NO number: ");
// Serial.println(pass_key);
/** Return false if passkeys don't match. */
return true;
};
/** Pairing process complete, we can check the results in ble_gap_conn_desc */
void onAuthenticationComplete(ble_gap_conn_desc* desc) {
// Serial.println("onAuthenticationComplete");
if (!desc->sec_state.encrypted) {
// Serial.println("Encrypt connection failed - disconnecting");
/** Find the client with the connection handle provided in desc */
NimBLEDevice::getClientByID(desc->conn_handle)->disconnect();
return;
}
};
};
/** Define a class to handle the callbacks when advertisments are received */
class AdvertisedDeviceCallbacks : public NimBLEAdvertisedDeviceCallbacks {
public:
AdvertisedDeviceCallbacks(String strTargetDeviceAddress,
ConnectionState* pConnectionState) {
if (strTargetDeviceAddress != "") {
this->targetDeviceAddress =
new NimBLEAddress(strTargetDeviceAddress.c_str());
}
this->pConnectionState = pConnectionState;
}
private:
NimBLEAddress* targetDeviceAddress = nullptr;
ConnectionState* pConnectionState;
void onResult(NimBLEAdvertisedDevice* advertisedDevice) {
int rssi = advertisedDevice->getRSSI();
if(rssi > -45)
{
Serial.printf("Strong device found: address=%s, RSSI=%d\n",
advertisedDevice->getAddress().toString().c_str(), rssi);
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.print("Advertised Device found: ");
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
advertisedDevice->toString().c_str());
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf(
"name:%s, address:%s\n", advertisedDevice->getName().c_str(),
advertisedDevice->getAddress().toString().c_str());
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf(
"uuidService:%s\n",
advertisedDevice->haveServiceUUID()
? advertisedDevice->getServiceUUID().toString().c_str()
: "none");
#endif
char* pHex = NimBLEUtils::buildHexData(
nullptr, (uint8_t*)advertisedDevice->getManufacturerData().data(),
advertisedDevice->getManufacturerData().length());
if ((targetDeviceAddress != nullptr &&
advertisedDevice->getAddress().equals(*targetDeviceAddress)) ||
(targetDeviceAddress == nullptr &&
advertisedDevice->getAppearance() == controllerAppearance &&
(strcmp(pHex, controllerManufacturerDataNormal.c_str()) == 0 ||
strcmp(pHex, controllerManufacturerDataSearching.c_str()) == 0) &&
advertisedDevice->getServiceUUID().equals(uuidServiceHid)))
// if (advertisedDevice->isAdvertisingService(uuidServiceHid))
{
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("Found target");
#endif
/** stop scan before connecting */
// NimBLEDevice::getScan()->stop();
/** Save the device reference in a global for the client to use*/
*pConnectionState = ConnectionState::Found;
advDevice = advertisedDevice;
}
};
};
class Core {
public:
Core(String targetDeviceAddress = "") {
this->advDeviceCBs =
new AdvertisedDeviceCallbacks(targetDeviceAddress, &connectionState);
this->clientCBs = new ClientCallbacks(&connectionState);
}
AdvertisedDeviceCallbacks* advDeviceCBs;
ClientCallbacks* clientCBs;
uint8_t battery = 0;
static const int deviceAddressLen = 6;
uint8_t deviceAddressArr[deviceAddressLen];
void begin() {
NimBLEDevice::setScanFilterMode(CONFIG_BTDM_SCAN_DUPL_TYPE_DEVICE);
// NimBLEDevice::setScanDuplicateCacheSize(200);
NimBLEDevice::init("");
NimBLEDevice::setOwnAddrType(BLE_OWN_ADDR_PUBLIC);
NimBLEDevice::setSecurityAuth(true, false, false);
NimBLEDevice::setPower(ESP_PWR_LVL_P9); /* +9db */
}
void writeHIDReport(uint8_t* dataArr, size_t dataLen) {
if (pConnectedClient == nullptr) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("no connnected client");
#endif
return;
}
NimBLEClient* pClient = pConnectedClient;
auto pService = pClient->getService(uuidServiceHid);
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(pService->toString().c_str());
#endif
for (auto pChara : *pService->getCharacteristics()) {
if (pChara->canWrite()) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
"canWrite " + String(pChara->canWrite()));
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
pChara->toString().c_str());
writeWithComment(pChara, dataArr, dataLen);
#else
pChara->writeValue(dataArr, dataLen, false);
#endif
}
}
}
void writeHIDReport(
const XboxSeriesXHIDReportBuilder_asukiaaa::ReportBase& repo) {
writeHIDReport((uint8_t*)repo.arr8t, repo.arr8tLen);
}
void writeHIDReport(
const XboxSeriesXHIDReportBuilder_asukiaaa::ReportBeforeUnion&
repoBeforeUnion) {
XboxSeriesXHIDReportBuilder_asukiaaa::ReportBase repo;
repo.v = repoBeforeUnion;
writeHIDReport((uint8_t*)repo.arr8t, repo.arr8tLen);
}
void onLoop() {
if (!isConnected()) {
if (advDevice != nullptr) {
auto connectionResult = connectToServer(advDevice);
if (!connectionResult || !isConnected()) {
NimBLEDevice::deleteBond(advDevice->getAddress());
++countFailedConnection;
// reset();
connectionState = ConnectionState::Scanning;
} else {
countFailedConnection = 0;
}
advDevice = nullptr;
} else if (!isScanning()) {
// reset();
startScan();
}
}
}
String buildDeviceAddressStr() {
char buffer[18];
auto addr = deviceAddressArr;
snprintf(buffer, sizeof(buffer), "%02x:%02x:%02x:%02x:%02x:%02x", addr[5],
addr[4], addr[3], addr[2], addr[1], addr[0]);
return String(buffer);
}
void startScan() {
connectionState = ConnectionState::Scanning;
auto pScan = NimBLEDevice::getScan();
// pScan->clearResults();
// pScan->clearDuplicateCache();
pScan->setDuplicateFilter(false);
pScan->setAdvertisedDeviceCallbacks(advDeviceCBs);
// pScan->setActiveScan(true);
pScan->setInterval(97);
pScan->setWindow(97);
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("Start scan");
#endif
// assign scanCompleteCB to scan on other thread
pScan->start(scanTime, &Core::scanCompleteCB, false);
}
XboxControllerNotificationParser xboxNotif;
bool isWaitingForFirstNotification() {
return connectionState == ConnectionState::WaitingForFirstNotification;
}
bool isConnected() {
return connectionState == ConnectionState::WaitingForFirstNotification ||
connectionState == ConnectionState::Connected;
}
unsigned long getReceiveNotificationAt() { return receivedNotificationAt; }
uint8_t getCountFailedConnection() { return countFailedConnection; }
private:
ConnectionState connectionState = ConnectionState::Scanning;
unsigned long receivedNotificationAt = 0;
uint32_t scanTime = 4; /** 0 = scan forever */
uint8_t countFailedConnection = 0;
uint8_t retryCountInOneConnection = 3;
unsigned long retryIntervalMs = 100;
NimBLEClient* pClient = nullptr;
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
static void writeWithComment(NimBLERemoteCharacteristic* pChara,
uint8_t* data, size_t len) {
Serial.println("send(print from addr 0) ");
for (int i = 0; i < len; ++i) {
Serial.print(data[i]);
Serial.print(" ");
}
if (pChara->writeValue(data, len, true)) {
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("suceeded in writing");
} else {
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("failed writing");
}
}
#endif
static void readAndPrint(NimBLERemoteCharacteristic* pChara) {
auto str = pChara->readValue();
if (str.size() == 0) {
str = pChara->readValue();
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
printValue(str);
#endif
}
bool isScanning() { return NimBLEDevice::getScan()->isScanning(); }
// void reset() {
// NimBLEDevice::deinit(true);
// delay(500);
// begin();
// delay(500);
// }
/** Handles the provisioning of clients and connects / interfaces with the
* server */
bool connectToServer(NimBLEAdvertisedDevice* advDevice) {
NimBLEClient* pClient = nullptr;
/** Check if we have a client we should reuse first **/
if (NimBLEDevice::getClientListSize()) {
pClient = NimBLEDevice::getClientByPeerAddress(advDevice->getAddress());
if (pClient) {
pClient->connect();
}
}
/** No client to reuse? Create a new one. */
if (!pClient) {
if (NimBLEDevice::getClientListSize() >= NIMBLE_MAX_CONNECTIONS) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
"Max clients reached - no more connections available");
#endif
return false;
}
pClient = NimBLEDevice::createClient();
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("New client created");
#endif
// default values
// pClient->setConnectionParams(
// BLE_GAP_INITIAL_CONN_ITVL_MIN, BLE_GAP_INITIAL_CONN_ITVL_MAX,
// BLE_GAP_INITIAL_CONN_LATENCY, BLE_GAP_INITIAL_SUPERVISION_TIMEOUT,
// 16, 16);
// pClient->setConnectionParams(
// BLE_GAP_INITIAL_CONN_ITVL_MIN, BLE_GAP_INITIAL_CONN_ITVL_MAX,
// BLE_GAP_INITIAL_CONN_LATENCY, BLE_GAP_INITIAL_SUPERVISION_TIMEOUT,
// 100, 100);
pClient->setClientCallbacks(clientCBs, true);
pClient->connect(advDevice, true);
}
int retryCount = retryCountInOneConnection;
while (!pClient->isConnected()) {
if (retryCount <= 0) {
return false;
} else {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("Try connection. left: " +
String(retryCount));
#endif
}
// NimBLEDevice::getScan()->stop();
// pClient->disconnect();
delay(retryIntervalMs);
// Serial.println(pClient->toString().c_str());
pClient->connect(true);
--retryCount;
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.print("Connected to: ");
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
pClient->getPeerAddress().toString().c_str());
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.print("RSSI: ");
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(pClient->getRssi());
#endif
// pClient->discoverAttributes();
bool result = afterConnect(pClient);
if (!result) {
return result;
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("Done with this device!");
#endif
pConnectedClient = pClient;
return true;
}
bool afterConnect(NimBLEClient* pClient) {
memcpy(deviceAddressArr, pClient->getPeerAddress().getNative(),
deviceAddressLen);
for (auto pService : *pClient->getServices(true)) {
auto sUuid = pService->getUUID();
if (!sUuid.equals(uuidServiceHid) && !sUuid.equals(uuidServiceBattery)) {
continue; // skip
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
pService->toString().c_str());
#endif
for (auto pChara : *pService->getCharacteristics(true)) {
charaHandle(pChara);
charaSubscribeNotification(pChara);
}
}
return true;
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
void charaPrintId(NimBLERemoteCharacteristic* pChara) {
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf(
"s:%s c:%s h:%d",
pChara->getRemoteService()->getUUID().toString().c_str(),
pChara->getUUID().toString().c_str(), pChara->getHandle());
}
static void printValue(std::__cxx11::string str) {
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf("str: %s\n", str.c_str());
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf("hex:");
for (auto v : str) {
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf(" %02x", v);
}
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("");
}
#endif
void charaHandle(NimBLERemoteCharacteristic* pChara) {
if (pChara->canWrite()) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
charaPrintId(pChara);
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(" canWrite");
#endif
}
if (pChara->canRead()) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
charaPrintId(pChara);
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(" canRead");
#endif
// Reading value is required for subscribe
auto str = pChara->readValue();
if (str.size() == 0) {
str = pChara->readValue();
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
printValue(str);
#endif
}
}
void charaSubscribeNotification(NimBLERemoteCharacteristic* pChara) {
if (pChara->canNotify()) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
charaPrintId(pChara);
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(" canNotify ");
#endif
if (pChara->subscribe(
true,
std::bind(&Core::notifyCB, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3,
std::placeholders::_4),
true)) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
"succeeded in subscribing");
#endif
} else {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("failed subscribing");
#endif
}
}
}
void notifyCB(NimBLERemoteCharacteristic* pRemoteCharacteristic,
uint8_t* pData, size_t length, bool isNotify) {
auto sUuid = pRemoteCharacteristic->getRemoteService()->getUUID();
if (connectionState != ConnectionState::Connected) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
"Received first notification");
#endif
connectionState = ConnectionState::Connected;
}
if (sUuid.equals(uuidServiceHid)) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
static bool isPrinting = false;
static unsigned long printedAt = 0;
if (isPrinting || millis() - printedAt < printInterval) return;
isPrinting = true;
std::string str = (isNotify == true) ? "Notification" : "Indication";
str += " from ";
/** NimBLEAddress and NimBLEUUID have std::string operators */
str += std::string(pRemoteCharacteristic->getRemoteService()
->getClient()
->getPeerAddress());
str += ": Service = " +
std::string(pRemoteCharacteristic->getRemoteService()->getUUID());
str +=
", Characteristic = " + std::string(pRemoteCharacteristic->getUUID());
// str += ", Value = " + std::string((char*)pData, length);
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(str.c_str());
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.print("value: ");
for (int i = 0; i < length; ++i) {
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf(" %02x", pData[i]);
}
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("");
#endif
xboxNotif.update(pData, length);
receivedNotificationAt = millis();
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
// XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.print(xboxNotif.toString());
printedAt = millis();
isPrinting = false;
#endif
} else {
if (sUuid.equals(uuidServiceBattery)) {
battery = pData[0];
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("battery notification");
#endif
} else {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf("s:%s",
sUuid.toString().c_str());
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println(
"not handled notification");
#endif
}
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
for (int i = 0; i < length; ++i) {
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.printf(" %02x", pData[i]);
}
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("");
#endif
}
}
static void scanCompleteCB(NimBLEScanResults results) {
#ifdef XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL
XBOX_SERIES_X_CONTROLLER_DEBUG_SERIAL.println("Scan Ended");
#endif
}
};
}; // namespace XboxSeriesXControllerESP32_asukiaaa
@@ -0,0 +1,73 @@
#pragma once
namespace XboxSeriesXHIDReportBuilder_asukiaaa {
struct InfoSelect {
uint8_t center : 1;
uint8_t shake : 1;
uint8_t right : 1;
uint8_t left : 1;
uint8_t _unkown_bit_4 : 1;
uint8_t _unkown_bit_5 : 1;
uint8_t _unkown_bit_6 : 1;
uint8_t _unkown_bit_7 : 1;
};
// 0 to 0x64 (100), over 0x64 becomes 0x64
struct InfoPower {
uint8_t left;
uint8_t right;
uint8_t shake;
uint8_t center;
};
struct ReportBeforeUnion {
InfoSelect select;
InfoPower power;
// value * 0.01 seconds, max 2.55 seconds
uint8_t timeActive;
uint8_t timeSilent;
// max 0xff
uint8_t countRepeat;
};
class ReportBase {
public:
static const size_t arr8tLen = 8;
union {
ReportBeforeUnion v;
uint8_t arr8t[arr8tLen];
};
ReportBase() { setFullPowerFor1Sec(); }
void setFullPowerFor1Sec() {
v.select.center = true;
v.select.left = true;
v.select.right = true;
v.select.shake = false;
v.power.center = 30;
// v.power.left = 30;
// v.power.right = 30;
// v.power.shake = 30;
// v.timeActive = 30;
v.timeSilent = 0;
v.countRepeat = 0;
}
void setAllOff() {
v.select.center = false;
v.select.left = false;
v.select.right = false;
v.select.shake = false;
v.power.center = 0;
v.power.left = 0;
v.power.right = 0;
v.power.shake = 0;
v.timeActive = 0;
v.timeSilent = 0;
v.countRepeat = 0;
}
};
} // namespace XboxSeriesXHIDReportBuilder_asukiaaa
+141
View File
@@ -0,0 +1,141 @@
#include <Arduino.h>
#include <XboxSeriesXControllerESP32_asukiaaa.hpp>
// 替换为自己的手柄蓝牙MAC地址
XboxSeriesXControllerESP32_asukiaaa::Core xboxController("0a:27:12:5c:71:79");
XboxSeriesXHIDReportBuilder_asukiaaa::ReportBase repo;
// 摇杆默认中间值范围(32767-32768)
const int JOY_DEFAULT_MIN = 32767;
const int JOY_DEFAULT_MAX = 32768;
void XboxKeyVibration()
{
repo.setAllOff();
repo.v.select.center = true;
repo.v.select.left = true;
repo.v.select.right = true;
repo.v.select.shake = true;
repo.v.power.center = 60;
repo.v.power.shake = 60;
repo.v.timeActive = 10;
xboxController.writeHIDReport(repo);
delay(500);
repo.v.power.center = 0;
repo.v.power.shake = 0;
xboxController.writeHIDReport(repo);
}
void XboxtrigRTVibration()
{
static uint16_t TrigMax = XboxControllerNotificationParser::maxTrig;
repo.setAllOff();
repo.v.select.center = true;
repo.v.select.left = true;
repo.v.select.right = true;
repo.v.select.shake = true;
uint8_t power = (uint8_t)((float)xboxController.xboxNotif.trigRT / (float)TrigMax * 100);
Serial.print("trigRT:" + String(xboxController.xboxNotif.trigRT));
Serial.print(",TrigMax:" + String(TrigMax));
Serial.println(",power:" + String(power));
repo.v.power.center = power;
repo.v.power.shake = power;
repo.v.power.center = power;
repo.v.power.shake = power;
repo.v.timeActive = 10;
xboxController.writeHIDReport(repo);
delay(500);
repo.v.power.center = 0;
repo.v.power.shake = 0;
xboxController.writeHIDReport(repo);
}
// 优化的输出函数:只显示触发的按键和非默认值的摇杆
void process_xbox_status() {
String output = "";
// 处理按键(默认0,值为1时显示)
if (xboxController.xboxNotif.btnY) output += "btnY:1, ";
if (xboxController.xboxNotif.btnX) output += "btnX:1, ";
if (xboxController.xboxNotif.btnB) output += "btnB:1, ";
if (xboxController.xboxNotif.btnA) output += "btnA:1, ";
if (xboxController.xboxNotif.btnLB) output += "btnLB:1, ";
if (xboxController.xboxNotif.btnRB) output += "btnRB:1, ";
if (xboxController.xboxNotif.btnSelect) output += "btnSelect:1, ";
if (xboxController.xboxNotif.btnStart) output += "btnStart:1, ";
if (xboxController.xboxNotif.btnXbox) output += "btnXbox:1, ";
if (xboxController.xboxNotif.btnShare) output += "btnShare:1, ";
if (xboxController.xboxNotif.btnLS) output += "btnLS:1, ";
if (xboxController.xboxNotif.btnRS) output += "btnRS:1, ";
if (xboxController.xboxNotif.btnDirUp) output += "btnDirUp:1, ";
if (xboxController.xboxNotif.btnDirRight) output += "btnDirRight:1, ";
if (xboxController.xboxNotif.btnDirDown) output += "btnDirDown:1, ";
if (xboxController.xboxNotif.btnDirLeft) output += "btnDirLeft:1, ";
// 处理摇杆(不在默认范围时显示)
if (xboxController.xboxNotif.joyLHori < JOY_DEFAULT_MIN || xboxController.xboxNotif.joyLHori > JOY_DEFAULT_MAX)
output += "joyLHori:" + String(xboxController.xboxNotif.joyLHori) + ", ";
if (xboxController.xboxNotif.joyLVert < JOY_DEFAULT_MIN || xboxController.xboxNotif.joyLVert > JOY_DEFAULT_MAX)
output += "joyLVert:" + String(xboxController.xboxNotif.joyLVert) + ", ";
if (xboxController.xboxNotif.joyRHori < JOY_DEFAULT_MIN || xboxController.xboxNotif.joyRHori > JOY_DEFAULT_MAX)
output += "joyRHori:" + String(xboxController.xboxNotif.joyRHori) + ", ";
if (xboxController.xboxNotif.joyRVert < JOY_DEFAULT_MIN || xboxController.xboxNotif.joyRVert > JOY_DEFAULT_MAX)
output += "joyRVert:" + String(xboxController.xboxNotif.joyRVert) + ", ";
// 处理扳机键(扳机键默认0,有值时显示)
if (xboxController.xboxNotif.trigLT > 0)
output += "trigLT:" + String(xboxController.xboxNotif.trigLT) + ", ";
if (xboxController.xboxNotif.trigRT > 0)
output += "trigRT:" + String(xboxController.xboxNotif.trigRT) + ", ";
// 移除末尾多余的逗号和空格,有内容才输出
if (output.length() > 0) {
output.remove(output.length() - 2);
Serial.println(output);
}
}
void process_xbox_notif(){
xboxController.onLoop();
if (xboxController.isConnected()){
if (xboxController.isWaitingForFirstNotification()){
Serial.println("waiting for first xbox notification");
}else{
process_xbox_status(); // 使用优化后的输出函数
// btnA的振动功能
static int lastBtnA = 0;
if (xboxController.xboxNotif.btnA && lastBtnA == 0) {
XboxKeyVibration();
}
lastBtnA = xboxController.xboxNotif.btnA;
// trigRT 根据扳机键按压力度调整振动力度
if (xboxController.xboxNotif.trigRT > 0) {
XboxtrigRTVibration();
}
}
}
else{
Serial.println("xbox not connected");
}
}
void setup(){
Serial.begin(115200);
Serial.println("Starting NimBLE Client");
xboxController.begin();
}
void loop(){
process_xbox_notif();
delay(50); // 适当增加延迟,减少输出频率
}