#include <Arduino.h>
#include <Preferences.h>
#include <BleCompositeHID.h>
#include <KeyboardDevice.h>
#include <esp_system.h>
// ========================
// Configuraciones y Constantes
// ========================
// Pines táctiles almacenados en PROGMEM para ahorrar RAM
const uint8_t TOUCH_PINS[] PROGMEM = {4, 12, 13, 14, 15, 27, 32, 33};
constexpr uint8_t TOUCH_PIN_COUNT = sizeof(TOUCH_PINS) / sizeof(TOUCH_PINS[0]);
// Umbrales para detectar toques en cada pin
const uint16_t TOUCH_THRESHOLDS[] PROGMEM = {60, 50, 55, 60, 55, 65, 65, 50};
// Configuraciones de gestos
constexpr unsigned long GESTURE_INACTIVITY_TIMEOUT = 2000; // 2 segundos
constexpr uint8_t MAX_GESTURES = 10;
constexpr uint8_t MAX_SEQUENCE_LENGTH = 20;
constexpr uint8_t MAX_ACTIONS_PER_GESTURE = 50;
constexpr size_t COMMAND_BUFFER_SIZE = 256;
// Enumeración para tipos de acciones
enum class ActionType {
KEY_PRESS = 0
// Future ActionTypes can be added here
};
// Estructura para definir una acción asociada a un gesto
struct Action {
ActionType type;
uint8_t parameter; // Código HID simplificado
};
// Estructura para definir un gesto
struct Gesture {
uint32_t id;
uint8_t sequenceLength;
uint8_t actionCount;
uint8_t pinSequence[MAX_SEQUENCE_LENGTH];
Action actions[MAX_ACTIONS_PER_GESTURE];
};
// ========================
// Clases de Manejo
// ========================
class GestureManager {
public:
GestureManager(Preferences& prefs)
: preferences(prefs), gestureCount(0), nextId(1) {}
bool addGesture(const Gesture& gesture) {
if (gestureCount >= MAX_GESTURES) {
logDebug("Límite de gestos alcanzado.");
return false;
}
gestures[gestureCount++] = gesture;
logDebug("Gesto añadido. ID: " + String(gesture.id));
saveGestures();
return true;
}
bool removeGesture(uint32_t id) {
for (uint8_t i = 0; i < gestureCount; ++i) {
if (gestures[i].id == id) {
gestures[i] = gestures[gestureCount - 1];
gestureCount--;
logDebug("Gesto eliminado. ID: " + String(id));
saveGestures();
return true;
}
}
logDebug("Gesto no encontrado. ID: " + String(id));
return false;
}
void listGestures() const {
Serial.println("=== Gestos Configurados ===");
for (uint8_t i = 0; i < gestureCount; ++i) {
Serial.print("ID: ");
Serial.print(gestures[i].id);
Serial.print(" | Secuencia: ");
for (uint8_t j = 0; j < gestures[i].sequenceLength; ++j) {
Serial.print("GPIO");
Serial.print(gestures[i].pinSequence[j]);
if (j < gestures[i].sequenceLength - 1) Serial.print(" -> ");
}
Serial.print(" | Acciones: ");
for (uint8_t k = 0; k < gestures[i].actionCount; ++k) {
Serial.print("[Tipo: TECLA, Código HID: ");
Serial.print(gestures[i].actions[k].parameter);
Serial.print("]");
if (k < gestures[i].actionCount - 1) Serial.print(", ");
}
Serial.println();
}
Serial.println("============================");
}
bool matchSequence(const uint8_t* buffer, uint8_t bufferLength, Gesture& matchedGesture) const {
for (uint8_t i = 0; i < gestureCount; ++i) {
if (gestures[i].sequenceLength > bufferLength) continue;
bool match = true;
for (uint8_t j = 0; j < gestures[i].sequenceLength; ++j) {
if (gestures[i].pinSequence[j] != buffer[bufferLength - gestures[i].sequenceLength + j]) {
match = false;
break;
}
}
if (match) {
matchedGesture = gestures[i];
return true;
}
}
return false;
}
uint32_t generateId() {
return nextId++;
}
void loadGestures() {
gestureCount = 0;
nextId = 1;
for (uint8_t i = 0; i < MAX_GESTURES; ++i) {
char keyId[16];
sprintf(keyId, "g%d_id", i);
if (!preferences.isKey(keyId)) break; // No más gestos almacenados
Gesture gesture;
gesture.id = preferences.getUInt(keyId, 0);
if (gesture.id == 0) continue;
char keyLen[16], keyActionCount[16];
sprintf(keyLen, "g%d_len", i);
sprintf(keyActionCount, "g%d_aLen", i);
gesture.sequenceLength = preferences.getUInt(keyLen, 0);
gesture.actionCount = preferences.getUInt(keyActionCount, 0);
// Cargar secuencia de pines
char keySeq[16];
sprintf(keySeq, "g%d_seq", i);
preferences.getBytes(keySeq, gesture.pinSequence, gesture.sequenceLength);
// Cargar acciones
for (uint8_t a = 0; a < gesture.actionCount; ++a) {
char keyActionType[24], keyActionParam[24];
sprintf(keyActionType, "g%d_a%d_type", i, a);
sprintf(keyActionParam, "g%d_a%d_param", i, a);
gesture.actions[a].type = static_cast<ActionType>(preferences.getUInt(keyActionType, 0));
uint8_t param = 0;
preferences.getBytes(keyActionParam, ¶m, 1);
gesture.actions[a].parameter = param;
}
gestures[gestureCount++] = gesture;
if (gesture.id >= nextId) nextId = gesture.id + 1;
}
logDebug("Gestos cargados desde Preferencias.");
}
void saveGestures() const {
preferences.clear();
for (uint8_t i = 0; i < gestureCount; ++i) {
char keyId[16], keyLen[16], keyActionCount[16];
sprintf(keyId, "g%d_id", i);
sprintf(keyLen, "g%d_len", i);
sprintf(keyActionCount, "g%d_aLen", i); // Corrección aplicada aquí
preferences.putUInt(keyId, gestures[i].id);
preferences.putUInt(keyLen, gestures[i].sequenceLength);
preferences.putUInt(keyActionCount, gestures[i].actionCount);
// Guardar secuencia de pines
char keySeq[16];
sprintf(keySeq, "g%d_seq", i);
preferences.putBytes(keySeq, gestures[i].pinSequence, gestures[i].sequenceLength);
// Guardar acciones
for (uint8_t a = 0; a < gestures[i].actionCount; ++a) {
char keyActionType[24], keyActionParam[24];
sprintf(keyActionType, "g%d_a%d_type", i, a);
sprintf(keyActionParam, "g%d_a%d_param", i, a);
preferences.putUInt(keyActionType, static_cast<uint8_t>(gestures[i].actions[a].type));
preferences.putBytes(keyActionParam, &gestures[i].actions[a].parameter, 1);
}
}
preferences.putUInt("next_id", nextId);
logDebug("Gestos guardados en Preferencias.");
}
private:
Preferences& preferences;
Gesture gestures[MAX_GESTURES];
uint8_t gestureCount;
uint32_t nextId;
void logDebug(const String& message) const {
Serial.printf("[GestureManager] %s\n", message.c_str());
}
};
class HIDManager {
public:
HIDManager()
: compositeHID("ESP32 HID Controller", "Mystfit", 100), keyboard(nullptr) {}
void begin() {
KeyboardConfiguration keyboardConfig;
keyboardConfig.setAutoReport(false); // Control manual de los informes de tecla
keyboard = new KeyboardDevice(keyboardConfig);
compositeHID.addDevice(keyboard);
compositeHID.begin();
logDebug("BLE HID iniciado.");
}
bool isConnected() { // Eliminado 'const' de la declaración
return compositeHID.isConnected();
}
void pressKeys(const Action* actions, uint8_t count) {
if (!keyboard || !isConnected()) return;
for (uint8_t i = 0; i < count; ++i) {
if (actions[i].type == ActionType::KEY_PRESS) {
keyboard->keyPress(actions[i].parameter);
logDebug("Tecla presionada: " + String(actions[i].parameter));
}
}
keyboard->sendKeyReport();
delay(50); // Considerar reemplazar por no bloqueante en futuras mejoras
for (uint8_t i = 0; i < count; ++i) {
if (actions[i].type == ActionType::KEY_PRESS) {
keyboard->keyRelease(actions[i].parameter);
logDebug("Tecla liberada: " + String(actions[i].parameter));
}
}
keyboard->sendKeyReport();
}
private:
BleCompositeHID compositeHID;
KeyboardDevice* keyboard;
void logDebug(const String& message) const {
Serial.printf("[HIDManager] %s\n", message.c_str());
}
};
// ========================
// Variables Globales
// ========================
Preferences preferences;
GestureManager* gestureManager = nullptr;
HIDManager* hidManager = nullptr;
// Buffer circular para almacenar toques recientes
uint8_t touchBuffer[MAX_SEQUENCE_LENGTH];
uint8_t bufferStart = 0;
uint8_t bufferSize = 0;
// Variables de tiempo
unsigned long lastTouchTime = 0;
// Estado previo de cada pin táctil
bool previousTouchState[TOUCH_PIN_COUNT] = {false};
// ========================
// Prototipos de Funciones
// ========================
void setup();
void loop();
void detectTouches();
void verifyGesture();
void handleSerialCommands();
bool compareSequences(const uint8_t *buffer, uint8_t bufferLen, const uint8_t *gestureSeq, uint8_t gestureLen);
uint8_t getHIDCode(const char* action);
void logDebug(const String& message);
// ========================
// Implementación de Funciones
// ========================
void setup() {
// Inicialización del Serial
Serial.begin(115200);
delay(1000);
logDebug("Inicialización del Serial completada.");
// Inicializar BLE HID
hidManager = new HIDManager();
hidManager->begin();
// Inicializar Preferencias
preferences.begin("gestos", false);
logDebug("Preferencias iniciadas.");
// Inicializar GestureManager
gestureManager = new GestureManager(preferences);
gestureManager->loadGestures();
// Configurar pines táctiles como entrada
logDebug("Configurando pines táctiles como INPUT.");
for (uint8_t i = 0; i < TOUCH_PIN_COUNT; ++i) {
uint8_t pin = pgm_read_byte(&TOUCH_PINS[i]);
pinMode(pin, INPUT);
Serial.printf("[Setup] Pin táctil configurado: GPIO%d\n", pin);
}
pinMode(LED_BUILTIN, OUTPUT);
Serial.printf("[Setup] LED_BUILTIN configurado como OUTPUT (GPIO%d)\n", LED_BUILTIN);
logDebug("Configuración inicial completada.");
}
void loop() {
detectTouches();
// Verificar tiempo de inactividad para reconocer gestos
if (bufferSize > 0 && (millis() - lastTouchTime) > GESTURE_INACTIVITY_TIMEOUT) {
verifyGesture();
// Limpiar buffer
bufferSize = 0;
bufferStart = 0;
logDebug("Buffer de toques limpiado por inactividad.");
}
// Manejar comandos seriales
if (Serial.available()) {
handleSerialCommands();
}
// Retardo mínimo para estabilidad
delay(10);
}
void detectTouches() {
for (uint8_t i = 0; i < TOUCH_PIN_COUNT; ++i) {
uint8_t pin = pgm_read_byte(&TOUCH_PINS[i]);
bool touched = touchRead(pin) < pgm_read_word(&TOUCH_THRESHOLDS[i]);
if (touched != previousTouchState[i] && (millis() - lastTouchTime) > 50) {
if (touched) {
// Agregar al buffer
if (bufferSize < MAX_SEQUENCE_LENGTH) {
touchBuffer[(bufferStart + bufferSize) % MAX_SEQUENCE_LENGTH] = pin;
bufferSize++;
Serial.printf("[Touch] GPIO%d TOCADO. Tamaño del buffer: %d\n", pin, bufferSize);
} else {
// Sobrescribir el más antiguo
touchBuffer[bufferStart] = pin;
bufferStart = (bufferStart + 1) % MAX_SEQUENCE_LENGTH;
Serial.printf("[Touch] Buffer lleno. Sobrescribiendo GPIO%d en posición %d con GPIO%d\n",
touchBuffer[bufferStart], bufferStart, pin);
}
lastTouchTime = millis();
// Indicar visualmente el toque
digitalWrite(LED_BUILTIN, HIGH);
digitalWrite(LED_BUILTIN, LOW);
logDebug("Pin GPIO" + String(pin) + " TOCADO y agregado al buffer.");
} else {
logDebug("Pin GPIO" + String(pin) + " LIBERADO.");
}
previousTouchState[i] = touched;
}
}
}
void verifyGesture() {
if (!hidManager->isConnected()) {
logDebug("BLE HID no está conectado. Abortando verificación de gestos.");
return;
}
Gesture matchedGesture;
if (gestureManager->matchSequence(touchBuffer, bufferSize, matchedGesture)) {
unsigned long responseTime = millis() - lastTouchTime;
logDebug("Gesto encontrado. ID: " + String(matchedGesture.id) + ", Ejecutando acciones...");
// Ejecutar acciones
hidManager->pressKeys(matchedGesture.actions, matchedGesture.actionCount);
logDebug("Gesto ID " + String(matchedGesture.id) + " ejecutado en " + String(responseTime) + " ms.");
} else {
logDebug("No se encontró ningún gesto que coincida con la secuencia actual.");
}
}
void handleSerialCommands() {
String command = Serial.readStringUntil('\n');
command.trim(); // Eliminar espacios y caracteres de fin de línea
logDebug("Comando recibido: " + command);
if (command.startsWith("ADD ")) {
// Formato: ADD <secuencia> : <acciones>
int colonIndex = command.indexOf(':');
if (colonIndex == -1) {
Serial.println("[Error] Formato ADD inválido. Uso: ADD <secuencia> : <acciones>");
logDebug("Formato ADD inválido.");
return;
}
String sequenceStr = command.substring(4, colonIndex); // Obtener la subcadena
sequenceStr.trim(); // Eliminar espacios
String actionsStr = command.substring(colonIndex + 1); // Obtener la subcadena de acciones
actionsStr.trim(); // Eliminar espacios
// Parsear secuencia de pines
Gesture newGesture;
newGesture.id = gestureManager->generateId();
newGesture.sequenceLength = 0;
newGesture.actionCount = 0;
int prevIndex = 0;
int spaceIndex = sequenceStr.indexOf(' ', prevIndex);
while (spaceIndex != -1 && newGesture.sequenceLength < MAX_SEQUENCE_LENGTH) {
String pinStr = sequenceStr.substring(prevIndex, spaceIndex);
uint8_t pin = pinStr.toInt();
bool validPin = false;
for (uint8_t i = 0; i < TOUCH_PIN_COUNT; ++i) {
if (pin == pgm_read_byte(&TOUCH_PINS[i])) {
newGesture.pinSequence[newGesture.sequenceLength++] = pin;
validPin = true;
break;
}
}
if (!validPin) {
Serial.println("[Error] Pin inválido: " + pinStr);
logDebug("Pin inválido: " + pinStr);
}
prevIndex = spaceIndex + 1;
spaceIndex = sequenceStr.indexOf(' ', prevIndex);
}
// Último pin
if (newGesture.sequenceLength < MAX_SEQUENCE_LENGTH && prevIndex < sequenceStr.length()) {
String pinStr = sequenceStr.substring(prevIndex);
uint8_t pin = pinStr.toInt();
bool validPin = false;
for (uint8_t i = 0; i < TOUCH_PIN_COUNT; ++i) {
if (pin == pgm_read_byte(&TOUCH_PINS[i])) {
newGesture.pinSequence[newGesture.sequenceLength++] = pin;
validPin = true;
break;
}
}
if (!validPin) {
Serial.println("[Error] Pin inválido: " + pinStr);
logDebug("Pin inválido: " + pinStr);
}
}
if (newGesture.sequenceLength == 0) {
Serial.println("[Error] No se añadieron pines válidos al gesto.");
logDebug("No se añadieron pines válidos al gesto.");
return;
}
// Parsear acciones
int actionsPrevIndex = 0;
int actionsSpaceIndex = actionsStr.indexOf(' ', actionsPrevIndex);
while (actionsSpaceIndex != -1 && newGesture.actionCount < MAX_ACTIONS_PER_GESTURE) {
String actionToken = actionsStr.substring(actionsPrevIndex, actionsSpaceIndex);
uint8_t hidCode = getHIDCode(actionToken.c_str());
if (hidCode != 0) {
newGesture.actions[newGesture.actionCount++] = Action{ActionType::KEY_PRESS, hidCode};
logDebug("Acción TECLA añadida: Código HID " + String(hidCode));
} else {
Serial.println("[Error] Acción no reconocida: " + actionToken);
logDebug("Acción no reconocida: " + actionToken);
}
actionsPrevIndex = actionsSpaceIndex + 1;
actionsSpaceIndex = actionsStr.indexOf(' ', actionsPrevIndex);
}
// Última acción
if (newGesture.actionCount < MAX_ACTIONS_PER_GESTURE && actionsPrevIndex < actionsStr.length()) {
String actionToken = actionsStr.substring(actionsPrevIndex);
uint8_t hidCode = getHIDCode(actionToken.c_str());
if (hidCode != 0) {
newGesture.actions[newGesture.actionCount++] = Action{ActionType::KEY_PRESS, hidCode};
logDebug("Acción TECLA añadida: Código HID " + String(hidCode));
} else {
Serial.println("[Error] Acción no reconocida: " + actionToken);
logDebug("Acción no reconocida: " + actionToken);
}
}
if (newGesture.actionCount == 0) {
Serial.println("[Error] No se añadieron acciones válidas al gesto.");
logDebug("No se añadieron acciones válidas al gesto.");
return;
}
// Añadir gesto
if (gestureManager->addGesture(newGesture)) {
Serial.println("[Info] Gesto añadido exitosamente. ID: " + String(newGesture.id));
} else {
Serial.println("[Error] No se pudo añadir el gesto. Límite alcanzado.");
}
} else if (command.startsWith("DEL ")) {
// Formato: DEL <id>
String idStr = command.substring(4); // Obtener la subcadena
idStr.trim(); // Eliminar espacios
uint32_t id = idStr.toInt();
if (gestureManager->removeGesture(id)) {
Serial.println("[Info] Gesto eliminado exitosamente. ID: " + String(id));
} else {
Serial.println("[Error] No se encontró el gesto con ID: " + String(id));
}
} else if (command.equals("LIST")) {
gestureManager->listGestures();
} else if (command.equals("TEST")) {
Serial.printf("[Info] Tiempo de respuesta: %lu ms, Memoria libre: %u bytes\n",
millis() - lastTouchTime, ESP.getFreeHeap());
logDebug("Comando TEST ejecutado.");
} else {
Serial.println("[Error] Comando desconocido.");
logDebug("Comando desconocido: " + command);
}
}
bool compareSequences(const uint8_t *buffer, uint8_t bufferLen, const uint8_t *gestureSeq, uint8_t gestureLen) {
if (gestureLen > bufferLen) return false;
for (uint8_t i = 0; i < gestureLen; ++i) {
if (buffer[bufferLen - gestureLen + i] != gestureSeq[i]) {
return false;
}
}
return true;
}
uint8_t getHIDCode(const char* action) {
// Mapeo de teclas especiales
if (strcmp(action, ".ESPACIO") == 0) return 44;
if (strcmp(action, ".ENTER") == 0) return 40;
if (strcmp(action, ".ESCAPE") == 0) return 41;
if (strcmp(action, ".TAB") == 0) return 43;
if (strcmp(action, ".BACKSPACE") == 0) return 42;
// Agrega más teclas especiales según necesites
// Mapeo de caracteres alfanuméricos
if (strlen(action) == 1) {
char c = toupper(action[0]);
if (c >= 'A' && c <= 'Z') {
return c - 'A' + 4;
}
if (c >= '1' && c <= '9') {
return c - '1' + 30;
}
if (c == '0') {
return 39;
}
// Agrega más caracteres si es necesario
}
// Acción no reconocida
return 0;
}
void logDebug(const String& message) {
Serial.printf("[Debug] %s\n", message.c_str());
}