- Dual-Core Architecture: Dedicated 1000Hz USB gaming pipeline on Core 1 and BLE/Wi-Fi/Web telemetry on Core 0. - Multi-Input BLE Host: Parsers for Xbox Wireless, Google Stadia, 8BitDo (Ultimate/Pro2/SN30), and Generic HOGP gamepads. - Multi-Console USB Emulation: Nintendo Switch, PC DirectInput, PS3, PS4, Xbox 360 (libxsm3 cryptographic challenge-response), Original Xbox, and Couch Mouse/Keyboard. - Onboard Web Portal & Captive Portal: Real-time SVG gamepad visualizer, stick deadzone calibration, button combo remapping, and Wi-Fi manager. - Low-Latency Radio Management: Interactive SoftAP toggle to drop to 0-latency gaming mode. - Dual OTA Firmware Flashing: Browser-based wireless firmware updater and automated Python OTA script. - Strict Build Quality: Clean build under -Wall -Wextra with zero warnings or errors. - Versioning & Licensing: Semantic Versioning v1.0.0 and GNU GPLv3 with Commercial Restrictions.
937 lines
35 KiB
C
937 lines
35 KiB
C
#include "ble_hid_host.h"
|
|
#include "controller_parser.h"
|
|
#include "parsers/parser_xbox_ble.h"
|
|
#include "parsers/parser_stadia.h"
|
|
#include "parsers/parser_8bitdo.h"
|
|
#include "parsers/parser_generic_hogp.h"
|
|
#include "status_led.h"
|
|
#include "profile_manager.h"
|
|
|
|
#include "nimble/nimble_port.h"
|
|
#include "nimble/nimble_port_freertos.h"
|
|
#include "host/ble_hs.h"
|
|
#include "host/ble_store.h"
|
|
#include "host/util/util.h"
|
|
#include "services/gap/ble_svc_gap.h"
|
|
#include "esp_log.h"
|
|
#include "nvs_flash.h"
|
|
#include "nvs.h"
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
extern void ble_store_config_init(void);
|
|
|
|
static const char *TAG = "BLE_HID_HOST";
|
|
|
|
static ble_report_cb_t s_report_cb = NULL;
|
|
static bool s_is_connected = false;
|
|
static uint16_t s_conn_handle = BLE_HS_CONN_HANDLE_NONE;
|
|
static ble_addr_t s_connected_addr;
|
|
static bool s_has_connected_addr = false;
|
|
static char s_device_name[64] = "Unknown Gamepad";
|
|
static controller_type_t s_active_controller_type = CONTROLLER_TYPE_GENERIC_HOGP;
|
|
|
|
/* Output Report (Rumble) state */
|
|
#define MAX_OUTPUT_CHRS 4
|
|
static uint16_t s_output_handles[MAX_OUTPUT_CHRS];
|
|
static uint8_t s_output_props[MAX_OUTPUT_CHRS];
|
|
static int s_output_handle_count = 0;
|
|
static uint16_t s_output_report_handle = 0;
|
|
static uint8_t s_output_report_prop = 0;
|
|
static uint8_t s_last_strong = 0;
|
|
static uint8_t s_last_weak = 0;
|
|
static uint32_t s_last_rumble_send_ticks = 0;
|
|
|
|
/* Helper functions for peer device persistence */
|
|
static void mac_to_str(const uint8_t *val, char *out, size_t out_len)
|
|
{
|
|
snprintf(out, out_len, "%02x:%02x:%02x:%02x:%02x:%02x",
|
|
val[5], val[4], val[3], val[2], val[1], val[0]);
|
|
}
|
|
|
|
static void mac_to_key(const uint8_t *val, char *out, size_t out_len)
|
|
{
|
|
snprintf(out, out_len, "%02x%02x%02x%02x%02x%02x",
|
|
val[5], val[4], val[3], val[2], val[1], val[0]);
|
|
}
|
|
|
|
static bool str_to_mac(const char *str, uint8_t *val)
|
|
{
|
|
unsigned int m[6];
|
|
if (sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
|
|
&m[5], &m[4], &m[3], &m[2], &m[1], &m[0]) == 6) {
|
|
for (int i = 0; i < 6; i++) val[i] = (uint8_t)m[i];
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
typedef struct __attribute__((packed)) {
|
|
char name[32];
|
|
uint8_t type;
|
|
} peer_nvs_meta_t;
|
|
|
|
static void save_peer_meta(const uint8_t *mac_val, const char *name, uint8_t type)
|
|
{
|
|
nvs_handle_t h;
|
|
if (nvs_open("ble_peers", NVS_READWRITE, &h) == ESP_OK) {
|
|
char key[16];
|
|
mac_to_key(mac_val, key, sizeof(key));
|
|
peer_nvs_meta_t meta = {0};
|
|
strncpy(meta.name, name, sizeof(meta.name) - 1);
|
|
meta.type = type;
|
|
nvs_set_blob(h, key, &meta, sizeof(meta));
|
|
nvs_commit(h);
|
|
nvs_close(h);
|
|
}
|
|
}
|
|
|
|
static bool load_peer_meta(const uint8_t *mac_val, char *out_name, size_t max_name, uint8_t *out_type)
|
|
{
|
|
nvs_handle_t h;
|
|
if (nvs_open("ble_peers", NVS_READONLY, &h) == ESP_OK) {
|
|
char key[16];
|
|
mac_to_key(mac_val, key, sizeof(key));
|
|
peer_nvs_meta_t meta;
|
|
size_t sz = sizeof(meta);
|
|
if (nvs_get_blob(h, key, &meta, &sz) == ESP_OK) {
|
|
strncpy(out_name, meta.name, max_name - 1);
|
|
out_name[max_name - 1] = '\0';
|
|
if (out_type) *out_type = meta.type;
|
|
nvs_close(h);
|
|
return true;
|
|
}
|
|
nvs_close(h);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static void erase_peer_meta(const uint8_t *mac_val)
|
|
{
|
|
nvs_handle_t h;
|
|
if (nvs_open("ble_peers", NVS_READWRITE, &h) == ESP_OK) {
|
|
char key[16];
|
|
mac_to_key(mac_val, key, sizeof(key));
|
|
nvs_erase_key(h, key);
|
|
nvs_commit(h);
|
|
nvs_close(h);
|
|
}
|
|
}
|
|
|
|
/* Xbox Wireless Controller BLE Force Feedback Report (Report ID 0x03) */
|
|
typedef struct __attribute__((packed)) {
|
|
uint8_t report_id; /* 0x03 */
|
|
uint8_t enable; /* 0x0C (Bit 2: Strong, Bit 3: Weak) */
|
|
uint8_t magnitude_lt; /* 0-100 */
|
|
uint8_t magnitude_rt; /* 0-100 */
|
|
uint8_t magnitude_strong; /* 0-100 (Left heavy motor) */
|
|
uint8_t magnitude_weak; /* 0-100 (Right light motor) */
|
|
uint8_t duration_10ms; /* 0xFF = ~2.55s sustain */
|
|
uint8_t start_delay_10ms; /* 0x00 */
|
|
uint8_t loop_count; /* 0x00 */
|
|
} xbox_ble_ff_report_t;
|
|
|
|
/* Standard UUIDs */
|
|
static const ble_uuid16_t s_hid_svc_uuid = BLE_UUID16_INIT(0x1812); /* Human Interface Device */
|
|
static const ble_uuid16_t s_hid_report_uuid = BLE_UUID16_INIT(0x2A4D); /* HID Report */
|
|
static const ble_uuid16_t s_bas_svc_uuid = BLE_UUID16_INIT(0x180F); /* Battery Service */
|
|
static const ble_uuid16_t s_bas_level_uuid = BLE_UUID16_INIT(0x2A19); /* Battery Level */
|
|
static const ble_uuid16_t s_cccd_uuid = BLE_UUID16_INIT(0x2902); /* Client Characteristic Configuration */
|
|
|
|
static uint16_t s_bas_val_handle = 0;
|
|
static uint16_t s_bas_cccd_handle = 0;
|
|
static int8_t s_battery_level = -1;
|
|
|
|
static int ble_gap_event(struct ble_gap_event *event, void *arg);
|
|
static void ble_scan_start(void);
|
|
static int on_disc_bas_svc(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
const struct ble_gatt_svc *svc, void *arg);
|
|
|
|
bool ble_hid_host_is_connected(void)
|
|
{
|
|
return s_is_connected;
|
|
}
|
|
|
|
const char *ble_hid_host_get_device_name(void)
|
|
{
|
|
return s_device_name;
|
|
}
|
|
|
|
static void parse_and_dispatch_report(const uint8_t *data, size_t len)
|
|
{
|
|
controller_state_t state;
|
|
bool parsed = false;
|
|
|
|
if (s_active_controller_type == CONTROLLER_TYPE_XBOX_BLE) {
|
|
parsed = parser_xbox_ble_parse(data, len, &state);
|
|
} else if (s_active_controller_type == CONTROLLER_TYPE_STADIA) {
|
|
parsed = parser_stadia_parse(data, len, &state);
|
|
} else if (s_active_controller_type == CONTROLLER_TYPE_8BITDO) {
|
|
parsed = parser_8bitdo_parse(data, len, &state);
|
|
} else {
|
|
/* Auto-probe: 8BitDo -> Stadia -> Xbox -> Generic */
|
|
parsed = parser_8bitdo_parse(data, len, &state);
|
|
if (!parsed) {
|
|
parsed = parser_stadia_parse(data, len, &state);
|
|
}
|
|
if (!parsed) {
|
|
parsed = parser_xbox_ble_parse(data, len, &state);
|
|
}
|
|
if (!parsed) {
|
|
parsed = parser_generic_hogp_parse(data, len, &state);
|
|
}
|
|
}
|
|
|
|
if (parsed) {
|
|
/* Monitor button combos for profile switching */
|
|
profile_manager_process_state(&state);
|
|
|
|
/* Dispatch to USB output */
|
|
if (s_report_cb) {
|
|
s_report_cb(&state);
|
|
}
|
|
}
|
|
}
|
|
|
|
#define MAX_REPORT_CHRS 8
|
|
typedef struct {
|
|
uint16_t val_handle;
|
|
uint16_t end_handle;
|
|
uint16_t cccd_handle;
|
|
} report_chr_t;
|
|
|
|
static report_chr_t s_report_chrs[MAX_REPORT_CHRS];
|
|
static int s_report_chr_count = 0;
|
|
static int s_sub_idx = 0;
|
|
|
|
static void subscribe_next_report_cccd(uint16_t conn_handle);
|
|
|
|
static int on_cccd_write_done(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
struct ble_gatt_attr *attr, void *arg)
|
|
{
|
|
if (error->status == 0) {
|
|
ESP_LOGI(TAG, "Subscribed successfully to report %d/%d (handle=%d)",
|
|
s_sub_idx + 1, s_report_chr_count, s_report_chrs[s_sub_idx].val_handle);
|
|
} else {
|
|
ESP_LOGW(TAG, "Failed to write CCCD at idx %d, status=%d", s_sub_idx, error->status);
|
|
}
|
|
s_sub_idx++;
|
|
subscribe_next_report_cccd(conn_handle);
|
|
return 0;
|
|
}
|
|
|
|
/* GATT Characteristic Descriptor Discovery (Enabling CCCD Notifications) */
|
|
static int on_disc_dscs(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
uint16_t chr_val_handle, const struct ble_gatt_dsc *dsc, void *arg)
|
|
{
|
|
if (error->status == 0 && dsc != NULL) {
|
|
if (ble_uuid_cmp(&dsc->uuid.u, &s_cccd_uuid.u) == 0) {
|
|
ESP_LOGI(TAG, "Found CCCD at handle %d for chr val_handle %d", dsc->handle, chr_val_handle);
|
|
if (s_sub_idx < s_report_chr_count) {
|
|
s_report_chrs[s_sub_idx].cccd_handle = dsc->handle;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* Descriptor discovery finished for this characteristic */
|
|
if (s_sub_idx < s_report_chr_count && s_report_chrs[s_sub_idx].cccd_handle != 0) {
|
|
uint16_t cccd = s_report_chrs[s_sub_idx].cccd_handle;
|
|
ESP_LOGI(TAG, "Writing CCCD at handle %d to enable notifications...", cccd);
|
|
uint8_t value[2] = {0x01, 0x00}; /* Enable Notifications */
|
|
ble_gattc_write_flat(conn_handle, cccd, value, sizeof(value), on_cccd_write_done, NULL);
|
|
} else {
|
|
/* No CCCD found for this characteristic, advance to next */
|
|
s_sub_idx++;
|
|
subscribe_next_report_cccd(conn_handle);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static void subscribe_next_report_cccd(uint16_t conn_handle)
|
|
{
|
|
if (s_sub_idx >= s_report_chr_count) {
|
|
ESP_LOGI(TAG, "All %d HID Report characteristics subscribed! Discovering Battery Service...", s_report_chr_count);
|
|
ble_gattc_disc_svc_by_uuid(conn_handle, &s_bas_svc_uuid.u, on_disc_bas_svc, NULL);
|
|
return;
|
|
}
|
|
|
|
uint16_t start = s_report_chrs[s_sub_idx].val_handle;
|
|
uint16_t end = s_report_chrs[s_sub_idx].end_handle;
|
|
if (end < start) end = start + 4;
|
|
|
|
ESP_LOGI(TAG, "Discovering descriptors for chr %d/%d (val_handle=%d, end_handle=%d)...",
|
|
s_sub_idx + 1, s_report_chr_count, start, end);
|
|
ble_gattc_disc_all_dscs(conn_handle, start, end, on_disc_dscs, NULL);
|
|
}
|
|
|
|
/* GATT Characteristic Discovery */
|
|
static int on_disc_chars(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
const struct ble_gatt_chr *chr, void *arg)
|
|
{
|
|
if (error->status == 0 && chr != NULL) {
|
|
if (ble_uuid_cmp(&chr->uuid.u, &s_hid_report_uuid.u) == 0) {
|
|
ESP_LOGI(TAG, "Discovered HID Report characteristic (val_handle=%d, def_handle=%d, props=0x%02x)",
|
|
chr->val_handle, chr->def_handle, chr->properties);
|
|
|
|
/* If characteristic has WRITE or WRITE_NO_RSP, save as Rumble Output Report handle */
|
|
if (chr->properties & (BLE_GATT_CHR_PROP_WRITE | BLE_GATT_CHR_PROP_WRITE_NO_RSP)) {
|
|
if (s_output_handle_count < MAX_OUTPUT_CHRS) {
|
|
s_output_handles[s_output_handle_count] = chr->val_handle;
|
|
s_output_props[s_output_handle_count] = chr->properties;
|
|
s_output_handle_count++;
|
|
}
|
|
s_output_report_handle = chr->val_handle;
|
|
s_output_report_prop = chr->properties;
|
|
ESP_LOGI(TAG, "==> Identified Rumble Output Report characteristic #%d (val_handle=%d, props=0x%02x)",
|
|
s_output_handle_count, chr->val_handle, chr->properties);
|
|
}
|
|
|
|
/* If characteristic has NOTIFY, save for CCCD subscription */
|
|
if (chr->properties & BLE_GATT_CHR_PROP_NOTIFY) {
|
|
if (s_report_chr_count < MAX_REPORT_CHRS) {
|
|
s_report_chrs[s_report_chr_count].val_handle = chr->val_handle;
|
|
s_report_chrs[s_report_chr_count].end_handle = chr->val_handle + 4;
|
|
s_report_chrs[s_report_chr_count].cccd_handle = 0;
|
|
s_report_chr_count++;
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* Characteristic discovery complete for this service */
|
|
ESP_LOGI(TAG, "Characteristic discovery finished. Subscribing to %d report characteristics (found %d output handles)...",
|
|
s_report_chr_count, s_output_handle_count);
|
|
s_sub_idx = 0;
|
|
subscribe_next_report_cccd(conn_handle);
|
|
return 0;
|
|
}
|
|
|
|
/* GATT Service Discovery */
|
|
static int on_disc_svc(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
const struct ble_gatt_svc *svc, void *arg)
|
|
{
|
|
if (error->status == 0 && svc != NULL) {
|
|
ESP_LOGI(TAG, "Discovered HID Service: start=%d, end=%d", svc->start_handle, svc->end_handle);
|
|
s_report_chr_count = 0;
|
|
s_sub_idx = 0;
|
|
s_output_handle_count = 0;
|
|
s_output_report_handle = 0;
|
|
s_output_report_prop = 0;
|
|
ble_gattc_disc_all_chrs(conn_handle, svc->start_handle, svc->end_handle, on_disc_chars, NULL);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Battery Service (0x180F) & Battery Level (0x2A19) Telemetry */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
static int on_bas_read(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
struct ble_gatt_attr *attr, void *arg)
|
|
{
|
|
if (error->status == 0 && attr != NULL && attr->om != NULL) {
|
|
uint8_t level = 0;
|
|
os_mbuf_copydata(attr->om, 0, 1, &level);
|
|
if (level <= 100) {
|
|
s_battery_level = (int8_t)level;
|
|
ESP_LOGI(TAG, "Controller Battery Level: %d%%", s_battery_level);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int on_bas_cccd_write_done(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
struct ble_gatt_attr *attr, void *arg)
|
|
{
|
|
if (error->status == 0) {
|
|
ESP_LOGI(TAG, "Subscribed to Battery Level notifications (CCCD handle=%d)", s_bas_cccd_handle);
|
|
}
|
|
if (s_bas_val_handle != 0) {
|
|
ble_gattc_read(conn_handle, s_bas_val_handle, on_bas_read, NULL);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int on_disc_bas_dscs(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
uint16_t chr_val_handle, const struct ble_gatt_dsc *dsc, void *arg)
|
|
{
|
|
if (error->status == 0 && dsc != NULL) {
|
|
if (ble_uuid_cmp(&dsc->uuid.u, &s_cccd_uuid.u) == 0) {
|
|
s_bas_cccd_handle = dsc->handle;
|
|
ESP_LOGI(TAG, "Found Battery CCCD at handle %d", dsc->handle);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
if (s_bas_cccd_handle != 0) {
|
|
uint8_t value[2] = {0x01, 0x00};
|
|
ble_gattc_write_flat(conn_handle, s_bas_cccd_handle, value, sizeof(value), on_bas_cccd_write_done, NULL);
|
|
} else if (s_bas_val_handle != 0) {
|
|
ble_gattc_read(conn_handle, s_bas_val_handle, on_bas_read, NULL);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int on_disc_bas_chars(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
const struct ble_gatt_chr *chr, void *arg)
|
|
{
|
|
if (error->status == 0 && chr != NULL) {
|
|
if (ble_uuid_cmp(&chr->uuid.u, &s_bas_level_uuid.u) == 0) {
|
|
s_bas_val_handle = chr->val_handle;
|
|
ESP_LOGI(TAG, "Discovered Battery Level characteristic (val_handle=%d, props=0x%02x)",
|
|
chr->val_handle, chr->properties);
|
|
if (chr->properties & BLE_GATT_CHR_PROP_NOTIFY) {
|
|
ble_gattc_disc_all_dscs(conn_handle, chr->val_handle, chr->val_handle + 2, on_disc_bas_dscs, NULL);
|
|
} else {
|
|
ble_gattc_read(conn_handle, s_bas_val_handle, on_bas_read, NULL);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int on_disc_bas_svc(uint16_t conn_handle, const struct ble_gatt_error *error,
|
|
const struct ble_gatt_svc *svc, void *arg)
|
|
{
|
|
if (error->status == 0 && svc != NULL) {
|
|
ESP_LOGI(TAG, "Discovered Battery Service: start=%d, end=%d", svc->start_handle, svc->end_handle);
|
|
s_bas_val_handle = 0;
|
|
s_bas_cccd_handle = 0;
|
|
ble_gattc_disc_all_chrs(conn_handle, svc->start_handle, svc->end_handle, on_disc_bas_chars, NULL);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static void ble_scan_start(void)
|
|
{
|
|
struct ble_gap_disc_params disc_params = {
|
|
.filter_duplicates = 1,
|
|
.passive = 0,
|
|
.itvl = BLE_GAP_SCAN_FAST_INTERVAL_MIN,
|
|
.window = BLE_GAP_SCAN_FAST_WINDOW,
|
|
.filter_policy = 0,
|
|
.limited = 0,
|
|
};
|
|
|
|
status_led_set_mode(LED_STATE_SCANNING);
|
|
ESP_LOGI(TAG, "Scanning for BLE gamepads (Xbox, 8BitDo, HID controllers)...");
|
|
ble_gap_disc(BLE_OWN_ADDR_PUBLIC, BLE_HS_FOREVER, &disc_params, ble_gap_event, NULL);
|
|
}
|
|
|
|
static int ble_gap_event(struct ble_gap_event *event, void *arg)
|
|
{
|
|
switch (event->type) {
|
|
case BLE_GAP_EVENT_DISC: {
|
|
struct ble_hs_adv_fields fields;
|
|
if (ble_hs_adv_parse_fields(&fields, event->disc.data, event->disc.length_data) == 0) {
|
|
char name[32] = {0};
|
|
if (fields.name != NULL && fields.name_len > 0) {
|
|
int len = (fields.name_len < sizeof(name) - 1) ? fields.name_len : sizeof(name) - 1;
|
|
memcpy(name, fields.name, len);
|
|
name[len] = '\0';
|
|
}
|
|
|
|
/* 1. Fast reconnect check: Is this advertising peer already bonded in NVS? */
|
|
ble_addr_t bonded[BLE_MAX_PEERS];
|
|
int num_bonded = 0;
|
|
ble_store_util_bonded_peers(bonded, &num_bonded, BLE_MAX_PEERS);
|
|
for (int b = 0; b < num_bonded; b++) {
|
|
if (memcmp(bonded[b].val, event->disc.addr.val, 6) == 0) {
|
|
char cached_name[32] = {0};
|
|
uint8_t cached_type = 0;
|
|
if (load_peer_meta(event->disc.addr.val, cached_name, sizeof(cached_name), &cached_type)) {
|
|
strncpy(s_device_name, cached_name, sizeof(s_device_name) - 1);
|
|
s_active_controller_type = (controller_type_t)cached_type;
|
|
} else if (name[0] != '\0') {
|
|
strncpy(s_device_name, name, sizeof(s_device_name) - 1);
|
|
} else {
|
|
strncpy(s_device_name, "Paired Controller", sizeof(s_device_name) - 1);
|
|
}
|
|
ESP_LOGI(TAG, "Recognized bonded controller '%s'. Reconnecting instantly...", s_device_name);
|
|
ble_gap_disc_cancel();
|
|
uint8_t own_addr_type;
|
|
ble_hs_id_infer_auto(0, &own_addr_type);
|
|
ble_gap_connect(own_addr_type, &event->disc.addr, 30000, NULL, ble_gap_event, NULL);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
bool match = false;
|
|
/* Check if name contains controller keywords */
|
|
if (strstr(name, "Xbox") || strstr(name, "Controller") ||
|
|
strstr(name, "Gamepad") || strstr(name, "8BitDo") ||
|
|
strstr(name, "Stadia")) {
|
|
match = true;
|
|
}
|
|
|
|
/* Check advertised 16-bit UUIDs for HID Service (0x1812) */
|
|
if (!match && fields.uuids16 != NULL) {
|
|
for (int i = 0; i < fields.num_uuids16; i++) {
|
|
if (ble_uuid_u16(&fields.uuids16[i].u) == 0x1812) {
|
|
match = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (match) {
|
|
ESP_LOGI(TAG, "Found target controller: '%s' (RSSI: %d). Connecting...", name, event->disc.rssi);
|
|
ble_gap_disc_cancel();
|
|
|
|
strncpy(s_device_name, (name[0] != '\0') ? name : "BLE Gamepad", sizeof(s_device_name) - 1);
|
|
if (strstr(s_device_name, "Xbox")) {
|
|
s_active_controller_type = CONTROLLER_TYPE_XBOX_BLE;
|
|
} else if (strstr(s_device_name, "Stadia")) {
|
|
s_active_controller_type = CONTROLLER_TYPE_STADIA;
|
|
} else if (strstr(s_device_name, "8BitDo") || strstr(s_device_name, "8bitdo") ||
|
|
strstr(s_device_name, "SN30") || strstr(s_device_name, "Pro 2") ||
|
|
strstr(s_device_name, "Lite") || strstr(s_device_name, "M30") ||
|
|
strstr(s_device_name, "Zero") || strstr(s_device_name, "Micro")) {
|
|
s_active_controller_type = CONTROLLER_TYPE_8BITDO;
|
|
} else {
|
|
s_active_controller_type = CONTROLLER_TYPE_GENERIC_HOGP;
|
|
}
|
|
|
|
uint8_t own_addr_type;
|
|
ble_hs_id_infer_auto(0, &own_addr_type);
|
|
ble_gap_connect(own_addr_type, &event->disc.addr, 30000, NULL, ble_gap_event, NULL);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
case BLE_GAP_EVENT_CONNECT:
|
|
if (event->connect.status == 0) {
|
|
s_is_connected = true;
|
|
s_conn_handle = event->connect.conn_handle;
|
|
ESP_LOGI(TAG, "Connected to '%s'! Initiating service discovery & pairing...", s_device_name);
|
|
|
|
struct ble_gap_conn_desc desc;
|
|
if (ble_gap_conn_find(event->connect.conn_handle, &desc) == 0) {
|
|
s_connected_addr = desc.peer_id_addr;
|
|
s_has_connected_addr = true;
|
|
save_peer_meta(s_connected_addr.val, s_device_name, (uint8_t)s_active_controller_type);
|
|
}
|
|
|
|
/* Initiate security / encryption (required for Xbox controllers) */
|
|
ble_gap_security_initiate(s_conn_handle);
|
|
|
|
/* Discover HID services (Battery Service discovery will follow sequentially) */
|
|
ble_gattc_disc_svc_by_uuid(s_conn_handle, &s_hid_svc_uuid.u, on_disc_svc, NULL);
|
|
|
|
/* Update LED to current profile mode */
|
|
profile_manager_refresh_led();
|
|
} else {
|
|
ESP_LOGW(TAG, "Connection failed, status=%d. Resuming scan...", event->connect.status);
|
|
s_is_connected = false;
|
|
s_has_connected_addr = false;
|
|
ble_scan_start();
|
|
}
|
|
return 0;
|
|
|
|
case BLE_GAP_EVENT_DISCONNECT:
|
|
ESP_LOGI(TAG, "Controller disconnected (reason=%d). Resuming scan...", event->disconnect.reason);
|
|
s_is_connected = false;
|
|
s_has_connected_addr = false;
|
|
s_conn_handle = BLE_HS_CONN_HANDLE_NONE;
|
|
s_output_handle_count = 0;
|
|
s_output_report_handle = 0;
|
|
s_output_report_prop = 0;
|
|
s_last_strong = 0;
|
|
s_last_weak = 0;
|
|
s_battery_level = -1;
|
|
s_bas_val_handle = 0;
|
|
s_bas_cccd_handle = 0;
|
|
controller_state_t zero_state = {0};
|
|
profile_manager_process_state(&zero_state);
|
|
ble_scan_start();
|
|
return 0;
|
|
|
|
case BLE_GAP_EVENT_NOTIFY_RX: {
|
|
struct os_mbuf *om = event->notify_rx.om;
|
|
uint16_t len = OS_MBUF_PKTLEN(om);
|
|
uint8_t buf[64];
|
|
if (len <= sizeof(buf)) {
|
|
os_mbuf_copydata(om, 0, len, buf);
|
|
if (event->notify_rx.attr_handle == s_bas_val_handle && len >= 1) {
|
|
if (buf[0] <= 100) {
|
|
s_battery_level = (int8_t)buf[0];
|
|
ESP_LOGI(TAG, "Battery level notification: %d%%", s_battery_level);
|
|
}
|
|
} else {
|
|
ESP_LOGD(TAG, "NOTIFY handle=%d len=%d", event->notify_rx.attr_handle, len);
|
|
parse_and_dispatch_report(buf, len);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
case BLE_GAP_EVENT_ENC_CHANGE:
|
|
ESP_LOGI(TAG, "Encryption changed, status=%d", event->enc_change.status);
|
|
return 0;
|
|
|
|
default:
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
static void ble_on_sync(void)
|
|
{
|
|
ESP_LOGI(TAG, "NimBLE Host synchronized.");
|
|
ble_scan_start();
|
|
}
|
|
|
|
static void ble_on_reset(int reason)
|
|
{
|
|
ESP_LOGE(TAG, "NimBLE Host reset, reason=%d", reason);
|
|
}
|
|
|
|
static void ble_host_task(void *param)
|
|
{
|
|
ESP_LOGI(TAG, "BLE Host Task running.");
|
|
nimble_port_run();
|
|
nimble_port_freertos_deinit();
|
|
}
|
|
|
|
esp_err_t ble_hid_host_init(ble_report_cb_t callback)
|
|
{
|
|
s_report_cb = callback;
|
|
|
|
esp_err_t err = nimble_port_init();
|
|
if (err != ESP_OK) {
|
|
ESP_LOGE(TAG, "Failed to init NimBLE port: %s", esp_err_to_name(err));
|
|
return err;
|
|
}
|
|
|
|
/* Configure Security Manager for pairing with BLE controllers */
|
|
ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_NO_IO;
|
|
ble_hs_cfg.sm_bonding = 1;
|
|
ble_hs_cfg.sm_mitm = 0;
|
|
ble_hs_cfg.sm_sc = 1;
|
|
ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
|
|
ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
|
|
|
|
ble_hs_cfg.sync_cb = ble_on_sync;
|
|
ble_hs_cfg.reset_cb = ble_on_reset;
|
|
|
|
/* Initialize persistent bonding storage */
|
|
ble_store_config_init();
|
|
|
|
nimble_port_freertos_init(ble_host_task);
|
|
|
|
ESP_LOGI(TAG, "BLE HID Central Host initialized.");
|
|
return ESP_OK;
|
|
}
|
|
|
|
void ble_hid_host_disconnect(void)
|
|
{
|
|
if (s_is_connected && s_conn_handle != BLE_HS_CONN_HANDLE_NONE) {
|
|
ESP_LOGI(TAG, "Disconnecting BLE controller (conn_handle=%d)...", s_conn_handle);
|
|
ble_gap_terminate(s_conn_handle, BLE_ERR_REM_USER_CONN_TERM);
|
|
}
|
|
}
|
|
|
|
void ble_hid_host_clear_bonds(void)
|
|
{
|
|
ESP_LOGI(TAG, "Clearing all BLE bonding store entries...");
|
|
if (s_is_connected && s_conn_handle != BLE_HS_CONN_HANDLE_NONE) {
|
|
ble_gap_terminate(s_conn_handle, BLE_ERR_REM_USER_CONN_TERM);
|
|
}
|
|
ble_store_clear();
|
|
nvs_handle_t h;
|
|
if (nvs_open("ble_peers", NVS_READWRITE, &h) == ESP_OK) {
|
|
nvs_erase_all(h);
|
|
nvs_commit(h);
|
|
nvs_close(h);
|
|
}
|
|
ble_scan_start();
|
|
}
|
|
|
|
int ble_hid_host_get_peers(ble_peer_info_t *out_peers, int max_peers)
|
|
{
|
|
if (!out_peers || max_peers <= 0) return 0;
|
|
|
|
ble_addr_t bonded[BLE_MAX_PEERS];
|
|
int num_bonded = 0;
|
|
ble_store_util_bonded_peers(bonded, &num_bonded, max_peers);
|
|
|
|
int count = 0;
|
|
bool found_connected = false;
|
|
|
|
for (int i = 0; i < num_bonded && count < max_peers; i++) {
|
|
mac_to_str(bonded[i].val, out_peers[count].mac_str, sizeof(out_peers[count].mac_str));
|
|
memcpy(out_peers[count].addr_val, bonded[i].val, 6);
|
|
out_peers[count].addr_type = bonded[i].type;
|
|
|
|
bool is_curr = (s_is_connected && s_has_connected_addr && memcmp(s_connected_addr.val, bonded[i].val, 6) == 0);
|
|
out_peers[count].is_connected = is_curr;
|
|
|
|
if (is_curr) {
|
|
found_connected = true;
|
|
strncpy(out_peers[count].name, s_device_name, sizeof(out_peers[count].name) - 1);
|
|
out_peers[count].controller_type = (uint8_t)s_active_controller_type;
|
|
out_peers[count].battery = s_battery_level;
|
|
} else {
|
|
char cname[32] = {0};
|
|
uint8_t ctype = 0;
|
|
if (load_peer_meta(bonded[i].val, cname, sizeof(cname), &ctype)) {
|
|
strncpy(out_peers[count].name, cname, sizeof(out_peers[count].name) - 1);
|
|
out_peers[count].controller_type = ctype;
|
|
} else {
|
|
strncpy(out_peers[count].name, "Paired Controller", sizeof(out_peers[count].name) - 1);
|
|
out_peers[count].controller_type = 0;
|
|
}
|
|
out_peers[count].battery = -1;
|
|
}
|
|
count++;
|
|
}
|
|
|
|
if (s_is_connected && s_has_connected_addr && !found_connected && count < max_peers) {
|
|
mac_to_str(s_connected_addr.val, out_peers[count].mac_str, sizeof(out_peers[count].mac_str));
|
|
memcpy(out_peers[count].addr_val, s_connected_addr.val, 6);
|
|
out_peers[count].addr_type = s_connected_addr.type;
|
|
out_peers[count].is_connected = true;
|
|
strncpy(out_peers[count].name, s_device_name, sizeof(out_peers[count].name) - 1);
|
|
out_peers[count].controller_type = (uint8_t)s_active_controller_type;
|
|
out_peers[count].battery = s_battery_level;
|
|
count++;
|
|
}
|
|
|
|
return count;
|
|
}
|
|
|
|
esp_err_t ble_hid_host_unpair_device(const char *mac_str)
|
|
{
|
|
if (!mac_str) return ESP_ERR_INVALID_ARG;
|
|
uint8_t mac_val[6];
|
|
if (!str_to_mac(mac_str, mac_val)) return ESP_ERR_INVALID_ARG;
|
|
|
|
ESP_LOGI(TAG, "Unpairing controller: %s", mac_str);
|
|
|
|
if (s_is_connected && s_has_connected_addr && memcmp(s_connected_addr.val, mac_val, 6) == 0) {
|
|
ESP_LOGI(TAG, "Disconnecting unpairing controller...");
|
|
ble_gap_terminate(s_conn_handle, BLE_ERR_REM_USER_CONN_TERM);
|
|
}
|
|
|
|
ble_addr_t addr;
|
|
memcpy(addr.val, mac_val, 6);
|
|
addr.type = BLE_ADDR_PUBLIC;
|
|
ble_gap_unpair(&addr);
|
|
addr.type = BLE_ADDR_RANDOM;
|
|
ble_gap_unpair(&addr);
|
|
|
|
erase_peer_meta(mac_val);
|
|
|
|
return ESP_OK;
|
|
}
|
|
|
|
void ble_hid_host_send_rumble(uint8_t strong, uint8_t weak)
|
|
{
|
|
if (!s_is_connected || s_conn_handle == BLE_HS_CONN_HANDLE_NONE || s_output_report_handle == 0) {
|
|
return;
|
|
}
|
|
|
|
uint32_t now = (uint32_t)(xTaskGetTickCount() * portTICK_PERIOD_MS);
|
|
if (strong == s_last_strong && weak == s_last_weak) {
|
|
return;
|
|
}
|
|
|
|
/* Rate limit to prevent saturating the BLE connection interval */
|
|
if ((strong != 0 || weak != 0) && (now - s_last_rumble_send_ticks < 20)) {
|
|
return;
|
|
}
|
|
|
|
s_last_strong = strong;
|
|
s_last_weak = weak;
|
|
s_last_rumble_send_ticks = now;
|
|
|
|
/* Feature 5: Dynamic Haptic LED Lightshow (Visual Rumble) */
|
|
if (strong > 0 || weak > 0) {
|
|
uint8_t r = (uint8_t)(((uint32_t)strong * 255) / 255);
|
|
uint8_t g = (uint8_t)(((uint32_t)weak * 80) / 255);
|
|
uint8_t b = (uint8_t)(((uint32_t)weak * 220) / 255);
|
|
status_led_flash_color(r, g, b, 120);
|
|
} else {
|
|
profile_manager_refresh_led();
|
|
}
|
|
|
|
if (s_active_controller_type == CONTROLLER_TYPE_XBOX_BLE) {
|
|
/* Authentic Xbox Wireless Controller Force Feedback Output Report */
|
|
xbox_ble_ff_report_t pkt = {0};
|
|
pkt.report_id = 0x03;
|
|
if (strong == 0 && weak == 0) {
|
|
pkt.enable = 0x0F; /* All 4 motors */
|
|
pkt.magnitude_lt = 0;
|
|
pkt.magnitude_rt = 0;
|
|
pkt.magnitude_strong = 0;
|
|
pkt.magnitude_weak = 0;
|
|
pkt.duration_10ms = 0x00; /* Instant stop */
|
|
pkt.start_delay_10ms = 0x00;
|
|
pkt.loop_count = 0x00;
|
|
} else {
|
|
pkt.enable = 0x0C; /* Enable Strong (left, bit 2) and Weak (right, bit 3) motors */
|
|
pkt.magnitude_lt = 0;
|
|
pkt.magnitude_rt = 0;
|
|
pkt.magnitude_strong = (uint8_t)(((uint32_t)strong * 100) / 255);
|
|
pkt.magnitude_weak = (uint8_t)(((uint32_t)weak * 100) / 255);
|
|
pkt.duration_10ms = 0x14; /* 200ms sustain safeguard */
|
|
pkt.start_delay_10ms = 0x00;
|
|
pkt.loop_count = 0x00;
|
|
}
|
|
|
|
if (s_output_report_prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) {
|
|
ble_gattc_write_no_rsp_flat(s_conn_handle, s_output_report_handle, &pkt, sizeof(pkt));
|
|
} else {
|
|
ble_gattc_write_flat(s_conn_handle, s_output_report_handle, &pkt, sizeof(pkt), NULL, NULL);
|
|
}
|
|
} else if (s_active_controller_type == CONTROLLER_TYPE_STADIA) {
|
|
/* Google Stadia Controller Output Report: Report ID 0x05, 16-bit Strong, 16-bit Weak */
|
|
uint16_t s16 = (uint16_t)(((uint32_t)strong * 65535) / 255);
|
|
uint16_t w16 = (uint16_t)(((uint32_t)weak * 65535) / 255);
|
|
|
|
/* 5-byte payload with Report ID 0x05 prefix (Standard USB & SDL hidapi layout) */
|
|
uint8_t pkt5[5] = {
|
|
0x05,
|
|
(uint8_t)(s16 & 0xFF),
|
|
(uint8_t)((s16 >> 8) & 0xFF),
|
|
(uint8_t)(w16 & 0xFF),
|
|
(uint8_t)((w16 >> 8) & 0xFF)
|
|
};
|
|
|
|
/* 4-byte payload without Report ID prefix (Raw HOGP Characteristic Value layout) */
|
|
uint8_t pkt4[4] = {
|
|
(uint8_t)(s16 & 0xFF),
|
|
(uint8_t)((s16 >> 8) & 0xFF),
|
|
(uint8_t)(w16 & 0xFF),
|
|
(uint8_t)((w16 >> 8) & 0xFF)
|
|
};
|
|
|
|
int handles_to_try = s_output_handle_count > 0 ? s_output_handle_count : 1;
|
|
for (int i = 0; i < handles_to_try; i++) {
|
|
uint16_t h = (s_output_handle_count > 0) ? s_output_handles[i] : s_output_report_handle;
|
|
uint8_t prop = (s_output_handle_count > 0) ? s_output_props[i] : s_output_report_prop;
|
|
if (h == 0) continue;
|
|
|
|
if (prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) {
|
|
ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt5, sizeof(pkt5));
|
|
ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt4, sizeof(pkt4));
|
|
}
|
|
if (prop & BLE_GATT_CHR_PROP_WRITE) {
|
|
ble_gattc_write_flat(s_conn_handle, h, pkt5, sizeof(pkt5), NULL, NULL);
|
|
ble_gattc_write_flat(s_conn_handle, h, pkt4, sizeof(pkt4), NULL, NULL);
|
|
}
|
|
}
|
|
} else if (s_active_controller_type == CONTROLLER_TYPE_8BITDO) {
|
|
/* 8BitDo controllers: Send standard generic HOGP and 5-byte force feedback report */
|
|
uint8_t pkt[4] = { 0x01, weak, strong, 0x00 };
|
|
uint8_t pkt5[5] = { 0x05, strong, 0x00, weak, 0x00 };
|
|
|
|
int handles_to_try = s_output_handle_count > 0 ? s_output_handle_count : 1;
|
|
for (int i = 0; i < handles_to_try; i++) {
|
|
uint16_t h = (s_output_handle_count > 0) ? s_output_handles[i] : s_output_report_handle;
|
|
uint8_t prop = (s_output_handle_count > 0) ? s_output_props[i] : s_output_report_prop;
|
|
if (h == 0) continue;
|
|
|
|
if (prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) {
|
|
ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt, sizeof(pkt));
|
|
ble_gattc_write_no_rsp_flat(s_conn_handle, h, pkt5, sizeof(pkt5));
|
|
}
|
|
if (prop & BLE_GATT_CHR_PROP_WRITE) {
|
|
ble_gattc_write_flat(s_conn_handle, h, pkt, sizeof(pkt), NULL, NULL);
|
|
ble_gattc_write_flat(s_conn_handle, h, pkt5, sizeof(pkt5), NULL, NULL);
|
|
}
|
|
}
|
|
} else {
|
|
/* Standard generic HOGP force feedback packet */
|
|
uint8_t pkt[4];
|
|
pkt[0] = 0x01;
|
|
pkt[1] = weak;
|
|
pkt[2] = strong;
|
|
pkt[3] = 0x00;
|
|
|
|
if (s_output_report_prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) {
|
|
ble_gattc_write_no_rsp_flat(s_conn_handle, s_output_report_handle, pkt, sizeof(pkt));
|
|
} else {
|
|
ble_gattc_write_flat(s_conn_handle, s_output_report_handle, pkt, sizeof(pkt), NULL, NULL);
|
|
}
|
|
}
|
|
}
|
|
|
|
typedef struct {
|
|
uint8_t strong;
|
|
uint8_t weak;
|
|
uint16_t duration_ms;
|
|
} rumble_pulse_t;
|
|
|
|
static void rumble_pulse_task(void *param)
|
|
{
|
|
rumble_pulse_t *p = (rumble_pulse_t *)param;
|
|
uint8_t strong = p->strong;
|
|
uint8_t weak = p->weak;
|
|
uint16_t dur = p->duration_ms > 0 ? p->duration_ms : 60;
|
|
free(p);
|
|
|
|
ble_hid_host_send_rumble(strong, weak);
|
|
vTaskDelay(pdMS_TO_TICKS(dur));
|
|
s_last_strong = 0xFF;
|
|
s_last_weak = 0xFF;
|
|
ble_hid_host_send_rumble(0, 0);
|
|
vTaskDelay(pdMS_TO_TICKS(20));
|
|
s_last_strong = 0xFF;
|
|
s_last_weak = 0xFF;
|
|
ble_hid_host_send_rumble(0, 0);
|
|
vTaskDelete(NULL);
|
|
}
|
|
|
|
void ble_hid_host_pulse_rumble(uint8_t strong_magnitude, uint8_t weak_magnitude, uint16_t duration_ms)
|
|
{
|
|
rumble_pulse_t *p = malloc(sizeof(rumble_pulse_t));
|
|
if (p) {
|
|
p->strong = strong_magnitude;
|
|
p->weak = weak_magnitude;
|
|
/* Pin rumble dispatch task to Core 0 (alongside NimBLE radio stack) */
|
|
xTaskCreatePinnedToCore(rumble_pulse_task, "rumble_pulse", 2048, p, 4, NULL, 0);
|
|
}
|
|
}
|
|
|
|
void ble_hid_host_test_rumble(uint16_t duration_ms)
|
|
{
|
|
if (duration_ms == 0) duration_ms = 100;
|
|
ble_hid_host_pulse_rumble(150, 150, duration_ms);
|
|
}
|
|
|
|
int8_t ble_hid_host_get_battery_level(void)
|
|
{
|
|
if (!s_is_connected) {
|
|
return -1;
|
|
}
|
|
return s_battery_level;
|
|
}
|
|
|
|
void ble_hid_host_refresh_battery(void)
|
|
{
|
|
static uint32_t last_read_ticks = 0;
|
|
uint32_t now = xTaskGetTickCount();
|
|
if (!s_is_connected || s_conn_handle == BLE_HS_CONN_HANDLE_NONE) {
|
|
return;
|
|
}
|
|
|
|
if (s_bas_val_handle == 0) {
|
|
if ((now - last_read_ticks > pdMS_TO_TICKS(5000)) || last_read_ticks == 0) {
|
|
last_read_ticks = now;
|
|
ESP_LOGI(TAG, "Discovering Battery Service on demand...");
|
|
ble_gattc_disc_svc_by_uuid(s_conn_handle, &s_bas_svc_uuid.u, on_disc_bas_svc, NULL);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if ((now - last_read_ticks > pdMS_TO_TICKS(10000)) || last_read_ticks == 0) {
|
|
last_read_ticks = now;
|
|
ble_gattc_read(s_conn_handle, s_bas_val_handle, on_bas_read, NULL);
|
|
}
|
|
}
|
|
|