// ========================
// Proyecto ESP32 HID SIR Optimizado para Flash
// ========================
#include <Arduino.h>
#include <BleCompositeHID.h>
#include <KeyboardDevice.h>
#include <Preferences.h>
// === Definición de Constantes en PROGMEM ===
// Teclas Modificadoras
#define KEY_LEFTGUI 0xE3
#define KEY_RIGHTGUI 0xE7
#define KEY_MEDIA_PLAYPAUSE 0xE8
#define KEY_MEDIA_STOP 0xEA
#define KEY_MEDIA_NEXTTRACK 0xB0
#define KEY_MEDIA_PREVIOUSTRACK 0xB1
#define KEY_MEDIA_VOLUMEDOWN 0xB2
#define KEY_MEDIA_VOLUMEUP 0xB3
#define KEY_MEDIA_MUTE 0xE2
#define KEY_MEDIA_WWWHOME 0xB5
#define KEY_MEDIA_EMAIL_READER 0xF0
#define KEY_MEDIA_LOCAL_MACHINE_BROWSER 0xF1
#define KEY_MEDIA_WWW_BOOKMARKS 0xF2
#define KEY_MEDIA_WWW_SEARCH 0xF3
#define KEY_MEDIA_WWW_STOP 0xF4
#define KEY_MEDIA_WWW_BACK 0xF5
#define KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION 0xF6
// Pines Táctiles
const uint8_t TOUCH_PINS[] PROGMEM = {4, 12, 13, 14, 15, 27, 32, 33};
const uint8_t NUM_TOUCH_PINS = sizeof(TOUCH_PINS);
const uint8_t TOUCH_THRESHOLDS[] PROGMEM = {40, 40, 40, 40, 30, 40, 40, 50};
// Parámetros de Gestos
const uint16_t INACTIVITY_TIMEOUT = 500; // Tiempo en ms
// Buffers y Contadores
#define TOUCH_BUFFER_SIZE 100
uint8_t touchBuffer[TOUCH_BUFFER_SIZE];
uint8_t bufferStart = 0;
uint8_t bufferSize = 0;
// Estructuras Empaquetadas para Acciones y Gestos
#pragma pack(push, 1)
struct Action {
uint8_t type; // Tipo de acción
union {
uint8_t parameter; // Código HID para tipos 0-3
char text[16]; // Texto asociado (solo para tipo 4)
};
};
#pragma pack(pop)
#pragma pack(push, 1)
struct Gesture {
uint8_t id;
uint8_t length;
uint8_t actionCount;
uint8_t pinSequence[TOUCH_BUFFER_SIZE];
Action actions[TOUCH_BUFFER_SIZE];
};
#pragma pack(pop)
// Variables de Estado
uint8_t previousTouchState = 0; // Cada bit representa el estado de un pin táctil
unsigned long lastTouchTime = 0;
unsigned long lastGestureTime = 0;
// Inicialización de Bluetooth, Teclado y Almacenamiento
Preferences preferences;
const char DEVICE_NAME[] PROGMEM = "ESP32 HIDC";
const char DEVICE_MANUFACTURER[] PROGMEM = "Mystfit";
BleCompositeHID compositeHID(DEVICE_NAME, DEVICE_MANUFACTURER, 50); // Reducido
KeyboardDevice* keyboard;
// Prototipos de Funciones
void detectTouch();
void checkGesture();
void handleSerialCommands();
bool compareSequences(const uint8_t* a, uint8_t aLen, const uint8_t* b, uint8_t bLen);
bool loadGesture(uint8_t index, Gesture* gesture);
void addGesture(const Gesture& newGesture);
void deleteGesture(uint8_t id);
uint8_t generateID();
uint8_t getHIDCode(const char* action);
bool needsShift(char c);
char getBaseChar(char c);
void logMessage(const __FlashStringHelper* message);
void logMessage(const char* message);
void listGestures();
// Mapa para Convertir Acciones en Códigos HID en PROGMEM
struct HIDPair {
const char* key;
uint8_t value;
};
const HIDPair HIDMap[] PROGMEM = {
// Teclas Especiales
{"ESPACIO", KEY_SPACE},
{"ENTER", KEY_ENTER},
{"ESCAPE", KEY_ESC},
{"TAB", KEY_TAB},
{"BACKSPACE", KEY_BACKSPACE},
{"SHIFT", KEY_LEFTSHIFT},
{"CTRL", KEY_LEFTCTRL},
{"ALT", KEY_LEFTALT},
{"SUPER", KEY_LEFTGUI},
// Media Keys
{"PLAYPAUSE", KEY_MEDIA_PLAYPAUSE},
{"STOP", KEY_MEDIA_STOP},
{"NEXTTRACK", KEY_MEDIA_NEXTTRACK},
{"PREVIOUSTRACK", KEY_MEDIA_PREVIOUSTRACK},
{"VOLUMEDOWN", KEY_MEDIA_VOLUMEDOWN},
{"VOLUMEUP", KEY_MEDIA_VOLUMEUP},
{"MUTE", KEY_MEDIA_MUTE},
{"WWWHOME", KEY_MEDIA_WWWHOME},
{"EMAILREADER", KEY_MEDIA_EMAIL_READER},
{"LOCALMACHINE", KEY_MEDIA_LOCAL_MACHINE_BROWSER},
{"WWWBOOKMARKS", KEY_MEDIA_WWW_BOOKMARKS},
{"WWWSEARCH", KEY_MEDIA_WWW_SEARCH},
{"WWWSTOP", KEY_MEDIA_WWW_STOP},
{"WWWBACK", KEY_MEDIA_WWW_BACK},
{"CONSUMERCONFIGURATION", KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION},
// Números
{"0", 39}, {"1", 30}, {"2", 31}, {"3", 32}, {"4", 33},
{"5", 34}, {"6", 35}, {"7", 36}, {"8", 37}, {"9", 38},
// Letras
{"A", 4}, {"B", 5}, {"C", 6}, {"D", 7}, {"E", 8},
{"F", 9}, {"G", 10}, {"H", 11}, {"I", 12}, {"J", 13},
{"K", 14}, {"L", 15}, {"M", 16}, {"N", 17}, {"O", 18},
{"P", 19}, {"Q", 20}, {"R", 21}, {"S", 22}, {"T", 23},
{"U", 24}, {"V", 25}, {"W", 26}, {"X", 27}, {"Y", 28},
{"Z", 29},
// Símbolos
{"/", 55}, // Se maneja '?' como shift + '/'
{" ", 44}
};
const size_t HIDMapSize = sizeof(HIDMap) / sizeof(HIDMap[0]);
// Función de Configuración Inicial
void setup() {
Serial.begin(115200);
while (!Serial) { /* Espera a que el puerto serie esté listo */ }
logMessage(F("Inicializando sistema..."));
// Configuración del dispositivo de teclado
KeyboardConfiguration keyboardConfig;
keyboardConfig.setAutoReport(true); // Activa el envío automático de informes
keyboard = new KeyboardDevice(keyboardConfig); // Crea el dispositivo de teclado
compositeHID.addDevice(keyboard);
compositeHID.begin();
// Configura los pines táctiles como entradas
for (uint8_t i = 0; i < NUM_TOUCH_PINS; i++) {
uint8_t pin;
memcpy_P(&pin, &TOUCH_PINS[i], sizeof(pin));
pinMode(pin, INPUT);
}
pinMode(LED_BUILTIN, OUTPUT); // Configura el LED interno como salida
preferences.begin("gestures", false); // Inicia las preferencias sin modo de solo lectura
// Registro el número de gestos almacenados
if (!preferences.isKey("count")) {
preferences.putUInt("count", 0);
}
uint8_t gestureCount = preferences.getUInt("count", 0);
logMessage(F("Sistema listo. Esperando gestos..."));
}
// Bucle Principal
void loop() {
detectTouch(); // Detecta toques en los pines táctiles
unsigned long currentTime = millis();
// Si hubo actividad y ha pasado el tiempo de inactividad, verifica el gesto
if (bufferSize > 0 && (currentTime - lastTouchTime > INACTIVITY_TIMEOUT)) {
checkGesture();
clearBuffer();
lastGestureTime = currentTime; // Actualiza el tiempo de la última ejecución del gesto
}
// Maneja comandos recibidos por el puerto serie
if (Serial.available()) {
handleSerialCommands();
}
}
// Función para Detectar Toques en los Pines Táctiles
void detectTouch() {
unsigned long currentTime = millis();
for (uint8_t i = 0; i < NUM_TOUCH_PINS; i++) {
uint8_t pin;
memcpy_P(&pin, &TOUCH_PINS[i], sizeof(pin));
uint8_t touchValue;
memcpy_P(&touchValue, &TOUCH_THRESHOLDS[i], sizeof(touchValue));
bool isTouched = touchRead(pin) < touchValue;
// Detecta cambios en el estado del pin (de no tocado a tocado)
if (isTouched && !(previousTouchState & (1 << i))) {
appendToBuffer(pin); // Agrega el pin al buffer si se toca
lastTouchTime = currentTime; // Actualiza el tiempo del último toque
previousTouchState |= (1 << i); // Marca el pin como tocado
} else if (!isTouched && (previousTouchState & (1 << i))) {
previousTouchState &= ~(1 << i); // Marca el pin como no tocado
}
}
// Control del LED interno basado en la inactividad reciente
if (currentTime - lastTouchTime < 50) {
digitalWrite(LED_BUILTIN, HIGH);
} else if (currentTime - lastTouchTime < 100) { // 2 * 50ms
digitalWrite(LED_BUILTIN, LOW);
}
}
// Añade un Pin al Buffer Táctil
void appendToBuffer(uint8_t pin) {
if (bufferSize < TOUCH_BUFFER_SIZE) {
touchBuffer[(bufferStart + bufferSize) % TOUCH_BUFFER_SIZE] = pin;
bufferSize++;
} else {
// Si el buffer está lleno, reemplaza el pin más antiguo
bufferStart = (bufferStart + 1) % TOUCH_BUFFER_SIZE;
touchBuffer[(bufferStart + bufferSize - 1) % TOUCH_BUFFER_SIZE] = pin;
}
}
// Limpia el Buffer Táctil
void clearBuffer() {
bufferStart = 0;
bufferSize = 0;
}
// Compara Dos Secuencias de Pines
bool compareSequences(const uint8_t* a, uint8_t aLen, const uint8_t* b, uint8_t bLen) {
if (aLen < bLen) {
return false;
}
// Compara las últimas bLen entradas de 'a' con 'b'
uint8_t startA = (aLen > TOUCH_BUFFER_SIZE) ? (aLen - bLen) : 0;
for (uint8_t i = 0; i < bLen; i++) {
if (a[startA + i] != b[i]) {
return false;
}
}
return true;
}
// Carga un Gestor desde las Preferencias por Índice
bool loadGesture(uint8_t index, Gesture* gesture) {
char idKey[10];
snprintf(idKey, sizeof(idKey), "g%u_id", index);
if (!preferences.isKey(idKey)) return false;
gesture->id = (uint8_t)preferences.getUInt(idKey, 0);
if (gesture->id == 0) return false;
// Cargar secuencia de pines
char seqKey[10];
snprintf(seqKey, sizeof(seqKey), "g%u_seq", index);
String sequenceStr = preferences.getString(seqKey, "");
gesture->length = 0;
int start = 0;
while (start < sequenceStr.length() && gesture->length < TOUCH_BUFFER_SIZE) {
int comma = sequenceStr.indexOf(',', start);
String pinStr = (comma == -1) ? sequenceStr.substring(start) : sequenceStr.substring(start, comma);
pinStr.trim();
uint8_t pin = pinStr.toInt();
if (pin != 0) { // Valid pin
gesture->pinSequence[gesture->length++] = pin;
}
if (comma == -1) break;
start = comma + 1;
}
// Cargar acciones
char actKey[10];
snprintf(actKey, sizeof(actKey), "g%u_acts", index);
String actionsStr = preferences.getString(actKey, "");
gesture->actionCount = 0;
start = 0;
while (start < actionsStr.length() && gesture->actionCount < TOUCH_BUFFER_SIZE) {
int semicolon = actionsStr.indexOf(';', start);
String actionStr = (semicolon == -1) ? actionsStr.substring(start) : actionsStr.substring(start, semicolon);
actionStr.trim();
if (actionStr.length() > 0) {
Action action;
action.type = 0;
memset(action.text, 0, sizeof(action.text));
// Intentar convertir a número
uint8_t hidCode = actionStr.toInt();
if (hidCode != 0) {
// Verificar si es Media Key o Modificador
bool isMediaKey = false;
bool isModifier = false;
for (size_t k = 0; k < HIDMapSize; k++) {
HIDPair pair;
memcpy_P(&pair, &HIDMap[k], sizeof(pair));
if (hidCode == pair.value) {
if (hidCode >= 0xB0 && hidCode <= 0xF6) {
isMediaKey = true;
}
if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
isModifier = true;
}
break;
}
}
if (isMediaKey) {
action.type = 1;
action.parameter = hidCode;
}
else if (isModifier) {
action.type = 2;
action.parameter = hidCode;
}
else {
action.type = 0;
action.parameter = hidCode;
}
}
else {
// Asume que es texto
action.type = 4;
strncpy(action.text, actionStr.c_str(), sizeof(action.text) - 1);
action.text[sizeof(action.text) - 1] = '\0';
}
// Añadir acción al gesto
gesture->actions[gesture->actionCount++] = action;
}
if (semicolon == -1) break;
start = semicolon + 1;
}
return (gesture->actionCount > 0);
}
// Verifica si el Buffer Coincide con Algún Gesto Almacenado
void checkGesture() {
uint8_t gestureCount = preferences.getUInt("count", 0);
if (gestureCount == 0) {
return;
}
Gesture gesture;
for (uint8_t i = 0; i < gestureCount; ++i) {
if (!loadGesture(i, &gesture)) {
continue;
}
if (compareSequences(touchBuffer + bufferStart, bufferSize, gesture.pinSequence, gesture.length)) {
if (!compositeHID.isConnected() || keyboard == nullptr) {
continue;
}
// Ejecuta todas las acciones asociadas al gesto
for (uint8_t a = 0; a < gesture.actionCount; a++) {
Action action = gesture.actions[a];
switch (action.type) {
case 0: // Tecla normal
keyboard->keyPress(action.parameter);
keyboard->keyRelease(action.parameter);
break;
case 1: // Media key
keyboard->mediaKeyPress(action.parameter);
keyboard->mediaKeyRelease(action.parameter);
break;
case 2: // Modificador (presionar)
keyboard->modifierKeyPress(action.parameter);
break;
case 3: // Modificador (soltar)
keyboard->modifierKeyRelease(action.parameter);
break;
case 4: // Enviar texto
for (uint8_t c = 0; c < sizeof(action.text) && action.text[c] != '\0'; c++) {
bool shift_needed = needsShift(action.text[c]);
if (shift_needed) {
keyboard->modifierKeyPress(KEY_LEFTSHIFT);
}
char baseChar = getBaseChar(action.text[c]);
uint8_t key = getHIDCode(&baseChar);
if (key != 0) {
keyboard->keyPress(key);
keyboard->keyRelease(key);
}
if (shift_needed) {
keyboard->modifierKeyRelease(KEY_LEFTSHIFT);
}
}
break;
default:
break;
}
}
break; // Sal del bucle al encontrar un gesto
}
}
}
// Maneja Comandos Recibidos por el Puerto Serie
void handleSerialCommands() {
while (Serial.available()) { // Maneja múltiples comandos a la vez
char commandBuffer[256];
uint16_t len = 0;
// Lee hasta '\n' o hasta llenar el buffer
while (Serial.available() && len < sizeof(commandBuffer) - 1) {
char c = Serial.read();
if (c == '\n') break;
commandBuffer[len++] = c;
}
commandBuffer[len] = '\0';
// Procesar comando
char* command = strtok(commandBuffer, " ");
if (command == NULL) {
logMessage(F("Comando vacío."));
return;
}
if (strcmp(command, "ADD") == 0) {
// Formato esperado: ADD <secuencia_pines>|<acciones>
char* params = strtok(NULL, "\n");
if (params == NULL) {
logMessage(F("Formato ADD incorrecto. Falta '|'."));
return;
}
char* delimiter = strchr(params, '|');
if (delimiter == NULL) {
logMessage(F("Formato ADD incorrecto. Falta '|'."));
return;
}
*delimiter = '\0';
char* sequenceStr = params;
char* actionsStr = delimiter + 1;
// Crear nuevo gesto
Gesture newGesture;
memset(&newGesture, 0, sizeof(Gesture));
newGesture.id = generateID();
// Procesar secuencia de pines
char* pinToken = strtok(sequenceStr, " ");
while (pinToken != NULL && newGesture.length < TOUCH_BUFFER_SIZE) {
uint8_t pin = (uint8_t)atoi(pinToken);
// Verificar si pin es válido
bool validPin = false;
for (uint8_t j = 0; j < NUM_TOUCH_PINS; j++) {
uint8_t touchPin;
memcpy_P(&touchPin, &TOUCH_PINS[j], sizeof(touchPin));
if (pin == touchPin) {
newGesture.pinSequence[newGesture.length++] = pin;
validPin = true;
break;
}
}
if (!validPin) {
// Pin inválido, ignorar
}
pinToken = strtok(NULL, " ");
}
if (newGesture.length == 0) {
logMessage(F("No se añadió ningún pin válido al gesto."));
return;
}
// Procesar acciones
char* actionToken = strtok(actionsStr, " ");
while (actionToken != NULL && newGesture.actionCount < TOUCH_BUFFER_SIZE) {
Action action;
memset(&action, 0, sizeof(Action));
uint8_t hidCode = getHIDCode(actionToken);
if (hidCode != 0) {
// Verificar si es Media Key o Modificador
bool isMediaKey = false;
bool isModifier = false;
for (size_t k = 0; k < HIDMapSize; k++) {
HIDPair pair;
memcpy_P(&pair, &HIDMap[k], sizeof(pair));
if (strcasecmp(actionToken, pair.key) == 0) {
if (pair.value >= 0xB0 && pair.value <= 0xF6) {
isMediaKey = true;
}
if (pair.value == KEY_LEFTCTRL || pair.value == KEY_LEFTSHIFT || pair.value == KEY_LEFTALT || pair.value == KEY_LEFTGUI) {
isModifier = true;
}
break;
}
}
if (isMediaKey) {
action.type = 1;
action.parameter = hidCode;
}
else if (isModifier) {
action.type = 2;
action.parameter = hidCode;
}
else {
action.type = 0;
action.parameter = hidCode;
}
}
else {
// Asume que es texto
action.type = 4;
strncpy(action.text, actionToken, sizeof(action.text) - 1);
action.text[sizeof(action.text) - 1] = '\0';
}
newGesture.actions[newGesture.actionCount++] = action;
actionToken = strtok(NULL, " ");
}
if (newGesture.actionCount == 0) {
logMessage(F("No se añadieron acciones válidas al gesto."));
return;
}
// Añadir gesto a Preferences
uint8_t currentCount = preferences.getUInt("count", 0);
if (currentCount >= 100) {
logMessage(F("Máximo número de gestos alcanzado."));
return;
}
// Guardar ID
char idKey[10];
snprintf(idKey, sizeof(idKey), "g%u_id", currentCount);
preferences.putUInt(idKey, newGesture.id);
// Guardar secuencia de pines
char seqKey[10];
snprintf(seqKey, sizeof(seqKey), "g%u_seq", currentCount);
char seqBuffer[256];
seqBuffer[0] = '\0';
for (uint8_t j = 0; j < newGesture.length; j++) {
char pinStr[4];
snprintf(pinStr, sizeof(pinStr), "%u", newGesture.pinSequence[j]);
strcat(seqBuffer, pinStr);
if (j < newGesture.length - 1) {
strcat(seqBuffer, ",");
}
}
preferences.putString(seqKey, seqBuffer);
// Guardar acciones
char actKey[10];
snprintf(actKey, sizeof(actKey), "g%u_acts", currentCount);
char actsBuffer[1024];
actsBuffer[0] = '\0';
for (uint8_t a = 0; a < newGesture.actionCount; a++) {
if (a > 0) strcat(actsBuffer, ";");
if (newGesture.actions[a].type == 4) {
strcat(actsBuffer, newGesture.actions[a].text);
}
else {
char paramStr[4];
snprintf(paramStr, sizeof(paramStr), "%u", newGesture.actions[a].parameter);
strcat(actsBuffer, paramStr);
}
}
preferences.putString(actKey, actsBuffer);
// Actualizar cuenta de gestos
preferences.putUInt("count", currentCount + 1);
logMessage(F("Gesto añadido exitosamente."));
}
else if (strcmp(command, "DEL") == 0) {
// Formato esperado: DEL <ID>
char* idStr = strtok(NULL, " ");
if (idStr == NULL) {
logMessage(F("Formato DEL incorrecto. Falta ID."));
return;
}
uint8_t id = (uint8_t)atoi(idStr);
uint8_t gestureCount = preferences.getUInt("count", 0);
bool found = false;
for (uint8_t i = 0; i < gestureCount; i++) {
char idKey[10];
snprintf(idKey, sizeof(idKey), "g%u_id", i);
uint8_t storedId = (uint8_t)preferences.getUInt(idKey, 0);
if (storedId == id) {
// Eliminar gesto moviendo los siguientes gestos hacia atrás
for (uint8_t j = i; j < gestureCount - 1; j++) {
char srcIdKey[10], srcSeqKey[10], srcActKey[10];
snprintf(srcIdKey, sizeof(srcIdKey), "g%u_id", j + 1);
snprintf(srcSeqKey, sizeof(srcSeqKey), "g%u_seq", j + 1);
snprintf(srcActKey, sizeof(srcActKey), "g%u_acts", j + 1);
char dstIdKey[10], dstSeqKey[10], dstActKey[10];
snprintf(dstIdKey, sizeof(dstIdKey), "g%u_id", j);
snprintf(dstSeqKey, sizeof(dstSeqKey), "g%u_seq", j);
snprintf(dstActKey, sizeof(dstActKey), "g%u_acts", j);
// Mover datos
preferences.putUInt(dstIdKey, preferences.getUInt(srcIdKey, 0));
preferences.putString(dstSeqKey, preferences.getString(srcSeqKey, ""));
preferences.putString(dstActKey, preferences.getString(srcActKey, ""));
// Eliminar origen
preferences.remove(srcIdKey);
preferences.remove(srcSeqKey);
preferences.remove(srcActKey);
}
// Actualizar cuenta de gestos
preferences.putUInt("count", gestureCount - 1);
logMessage(F("Gesto eliminado exitosamente."));
found = true;
break;
}
}
if (!found) {
logMessage(F("Gesto no encontrado."));
}
}
else if (strcmp(command, "LIST") == 0) {
// Lista todos los gestos almacenados
listGestures();
}
else if (strcmp(command, "TEST") == 0) {
// Comando de prueba para verificar la memoria disponible
char bufferMsg[30];
snprintf(bufferMsg, sizeof(bufferMsg), "Memoria libre: %u bytes", ESP.getFreeHeap());
logMessage(bufferMsg); // Ahora válido gracias a la sobrecarga
}
else {
logMessage(F("Comando desconocido."));
}
}
}
// Añade un Gesto a la Lista (No usado en nueva implementación)
void addGesture(const Gesture& newGesture) {
// Esta función está integrada dentro de handleSerialCommands()
}
// Elimina un Gesto por ID (No usado en nueva implementación)
void deleteGesture(uint8_t id) {
// Esta función está integrada dentro de handleSerialCommands()
}
// Carga un Gestor desde las Preferencias por Índice (Ya implementada arriba)
// Lista Todos los Gestos Almacenados
void listGestures() {
uint8_t gestureCount = preferences.getUInt("count", 0);
if (gestureCount == 0) {
logMessage(F("No hay gestos almacenados."));
return;
}
Serial.println(F("=== Lista de Gestos ==="));
Gesture gesture;
for (uint8_t i = 0; i < gestureCount; i++) {
if (!loadGesture(i, &gesture)) {
continue;
}
Serial.print(F("ID: "));
Serial.print(gesture.id);
Serial.print(F(" | Secuencia: "));
for (uint8_t j = 0; j < gesture.length; j++) {
Serial.print(gesture.pinSequence[j]);
if (j < gesture.length - 1) {
Serial.print(F(" -> "));
}
}
Serial.print(F(" | Acciones: "));
for (uint8_t a = 0; a < gesture.actionCount; a++) {
char actionType[30];
switch (gesture.actions[a].type) {
case 0: strcpy(actionType, "Tecla"); break;
case 1: strcpy(actionType, "Media Key"); break;
case 2: strcpy(actionType, "Modificador (Presionar)"); break;
case 3: strcpy(actionType, "Modificador (Soltar)"); break;
case 4: strcpy(actionType, "Texto"); break;
default: strcpy(actionType, "Desconocido"); break;
}
if (gesture.actions[a].type != 4) {
char actionMsg[50];
snprintf(actionMsg, sizeof(actionMsg), "%s(%u)", actionType, gesture.actions[a].parameter);
Serial.print(actionMsg);
}
else {
char actionMsg[50];
snprintf(actionMsg, sizeof(actionMsg), "%s(%s)", actionType, gesture.actions[a].text);
Serial.print(actionMsg);
}
if (a < gesture.actionCount - 1) {
Serial.print(F(", "));
}
}
Serial.println(); // Nueva línea al final de cada gesto
}
}
// Genera un ID Único para un Nuevo Gesto
uint8_t generateID() {
uint8_t gestureCount = preferences.getUInt("count", 0);
for (uint16_t id = 1; id <= 255; id++) {
bool exists = false;
Gesture tempGesture;
for (uint8_t i = 0; i < gestureCount; i++) {
if (loadGesture(i, &tempGesture)) {
if (tempGesture.id == id) {
exists = true;
break;
}
}
}
if (!exists) return id;
}
return 0; // Retorna 0 si no hay IDs disponibles
}
// Función para Convertir Acciones en Códigos HID
uint8_t getHIDCode(const char* action) {
for (size_t i = 0; i < HIDMapSize; i++) {
HIDPair pair;
memcpy_P(&pair, &HIDMap[i], sizeof(pair));
if (strcasecmp(action, pair.key) == 0) {
return pair.value;
}
}
return 0; // Si no encuentra la acción, retorna 0
}
// Función de Ayuda: Determina si un carácter requiere Shift
bool needsShift(char c) {
if (isupper(c)) return true;
// Lista de símbolos que requieren Shift
const char symbolsRequiringShift[] PROGMEM = "!@#$%^&*()_+{}|:\"<>?~[]\\;',./`-=";
for (uint8_t i = 0; i < sizeof(symbolsRequiringShift) - 1; i++) {
if (c == pgm_read_byte(&symbolsRequiringShift[i])) return true;
}
return false;
}
// Función de Ayuda: Obtiene el carácter base sin Shift
char getBaseChar(char c) {
if (isupper(c)) {
return tolower(c);
}
switch (c) {
case '!': return '1';
case '@': return '2';
case '#': return '3';
case '$': return '4';
case '%': return '5';
case '^': return '6';
case '&': return '7';
case '*': return '8';
case '(': return '9';
case ')': return '0';
case '_': return '-';
case '+': return '=';
case '{': return '[';
case '}': return ']';
case '|': return '\\';
case ':': return ';';
case '"': return '\'';
case '<': return ',';
case '>': return '.';
case '?': return '/';
case '~': return '`';
default: return c;
}
}
// Registra Mensajes en el Puerto Serie
// Versión para cadenas en flash
void logMessage(const __FlashStringHelper* message) {
Serial.print(F("[LOG] "));
Serial.println(message);
}
// Versión sobrecargada para cadenas dinámicas
void logMessage(const char* message) {
Serial.print("[LOG] ");
Serial.println(message);
}
// ========================
// Proyecto ESP32 HID SIR Optimizado para Flash
// ========================
// ========================
// Inclusión de Librerías y Definiciones
// ========================
#include <Arduino.h>
#include <BleCompositeHID.h>
#include <KeyboardDevice.h>
#include <Preferences.h>
// ========================
// Definición de Constantes y Datos en PROGMEM
// ========================
// Teclas Modificadoras y Media Keys
const uint8_t KEY_LEFTGUI PROGMEM = 0xE3;
const uint8_t KEY_RIGHTGUI PROGMEM = 0xE7;
const uint8_t KEY_MEDIA_PLAYPAUSE PROGMEM = 0xE8;
const uint8_t KEY_MEDIA_STOP PROGMEM = 0xEA;
// ... (continúa para todas las teclas)
// Pines Táctiles
const uint8_t TOUCH_PINS[] PROGMEM = {4, 12, 13, 14, 15, 27, 32, 33};
const uint8_t TOUCH_THRESHOLDS[] PROGMEM = {40, 40, 40, 40, 30, 40, 40, 50};
const uint8_t NUM_TOUCH_PINS = sizeof(TOUCH_PINS) / sizeof(TOUCH_PINS[0]);
// Parámetros de Gestos
const uint16_t INACTIVITY_TIMEOUT_MS = 500; // Tiempo en ms
// Buffers y Contadores
constexpr uint8_t TOUCH_BUFFER_SIZE = 100;
uint8_t touchBuffer[TOUCH_BUFFER_SIZE];
uint8_t bufferStart = 0;
uint8_t bufferSize = 0;
// ========================
// Estructuras y Clases
// ========================
#pragma pack(push, 1)
struct Action {
uint8_t type; // Tipo de acción
union {
uint8_t parameter; // Código HID para tipos 0-3
char text[16]; // Texto asociado (solo para tipo 4)
};
};
struct Gesture {
uint8_t id;
uint8_t length;
uint8_t actionCount;
uint8_t pinSequence[TOUCH_BUFFER_SIZE];
Action actions[TOUCH_BUFFER_SIZE];
};
#pragma pack(pop)
struct HIDPair {
const char* key;
uint8_t value;
};
// ========================
// Declaración de Variables Globales
// ========================
// Variables de Estado
uint8_t previousTouchState = 0; // Cada bit representa el estado de un pin táctil
unsigned long lastTouchTime = 0;
unsigned long lastGestureTime = 0;
// Inicialización de Bluetooth, Teclado y Almacenamiento
Preferences preferences;
const char DEVICE_NAME[] PROGMEM = "ESP32 HIDC";
const char DEVICE_MANUFACTURER[] PROGMEM = "Mystfit";
BleCompositeHID compositeHID(DEVICE_NAME, DEVICE_MANUFACTURER, 50); // Reducido
KeyboardDevice* keyboard;
// Mapa para Convertir Acciones en Códigos HID en PROGMEM
const HIDPair HIDMap[] PROGMEM = {
// Teclas Especiales
{"ESPACIO", KEY_SPACE},
{"ENTER", KEY_ENTER},
{"ESCAPE", KEY_ESC},
{"TAB", KEY_TAB},
{"BACKSPACE", KEY_BACKSPACE},
{"SHIFT", KEY_LEFTSHIFT},
{"CTRL", KEY_LEFTCTRL},
{"ALT", KEY_LEFTALT},
{"SUPER", KEY_LEFTGUI},
// Media Keys
{"PLAYPAUSE", KEY_MEDIA_PLAYPAUSE},
{"STOP", KEY_MEDIA_STOP},
{"NEXTTRACK", KEY_MEDIA_NEXTTRACK},
{"PREVIOUSTRACK", KEY_MEDIA_PREVIOUSTRACK},
{"VOLUMEDOWN", KEY_MEDIA_VOLUMEDOWN},
{"VOLUMEUP", KEY_MEDIA_VOLUMEUP},
{"MUTE", KEY_MEDIA_MUTE},
{"WWWHOME", KEY_MEDIA_WWWHOME},
{"EMAILREADER", KEY_MEDIA_EMAIL_READER},
{"LOCALMACHINE", KEY_MEDIA_LOCAL_MACHINE_BROWSER},
{"WWWBOOKMARKS", KEY_MEDIA_WWW_BOOKMARKS},
{"WWWSEARCH", KEY_MEDIA_WWW_SEARCH},
{"WWWSTOP", KEY_MEDIA_WWW_STOP},
{"WWWBACK", KEY_MEDIA_WWW_BACK},
{"CONSUMERCONFIGURATION", KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION},
// Números
{"0", 39}, {"1", 30}, {"2", 31}, {"3", 32}, {"4", 33},
{"5", 34}, {"6", 35}, {"7", 36}, {"8", 37}, {"9", 38},
// Letras
{"A", 4}, {"B", 5}, {"C", 6}, {"D", 7}, {"E", 8},
{"F", 9}, {"G", 10}, {"H", 11}, {"I", 12}, {"J", 13},
{"K", 14}, {"L", 15}, {"M", 16}, {"N", 17}, {"O", 18},
{"P", 19}, {"Q", 20}, {"R", 21}, {"S", 22}, {"T", 23},
{"U", 24}, {"V", 25}, {"W", 26}, {"X", 27}, {"Y", 28},
{"Z", 29},
// Símbolos
{"/", 55}, // Se maneja '?' como shift + '/'
{" ", 44}
};
const size_t HIDMapSize = sizeof(HIDMap) / sizeof(HIDMap[0]);
// ========================
// Prototipos de Funciones
// ========================
/**
* @brief Detecta toques en los pines táctiles.
*/
void detectTouch();
/**
* @brief Verifica si se ha realizado algún gesto almacenado.
*/
void checkGesture();
/**
* @brief Gestiona los comandos recibidos por el puerto serie.
*/
void handleSerialCommands();
/**
* @brief Compara dos secuencias de pines.
*
* @param a Primera secuencia.
* @param aLen Longitud de la primera secuencia.
* @param b Segunda secuencia.
* @param bLen Longitud de la segunda secuencia.
* @return true Si las secuencias coinciden.
* @return false Si no coinciden.
*/
bool compareSequences(const uint8_t* a, uint8_t aLen, const uint8_t* b, uint8_t bLen);
/**
* @brief Carga un gesto desde las preferencias por índice.
*
* @param index Índice del gesto.
* @param gesture Puntero a la estructura Gesture.
* @return true Si se carga correctamente.
* @return false Si falla la carga.
*/
bool loadGesture(uint8_t index, Gesture* gesture);
/**
* @brief Añade un nuevo gesto.
*
* @param newGesture Referencia al gesto a añadir.
*/
void addGesture(const Gesture& newGesture);
/**
* @brief Elimina un gesto por su ID.
*
* @param id ID del gesto a eliminar.
*/
void deleteGesture(uint8_t id);
/**
* @brief Genera un ID único para un nuevo gesto.
*
* @return uint8_t ID generado.
*/
uint8_t generateID();
/**
* @brief Obtiene el código HID correspondiente a una acción.
*
* @param action Cadena de la acción.
* @return uint8_t Código HID.
*/
uint8_t getHIDCode(const char* action);
/**
* @brief Determina si un carácter requiere la tecla Shift.
*
* @param c Carácter a evaluar.
* @return true Si requiere Shift.
* @return false Si no.
*/
bool needsShift(char c);
/**
* @brief Obtiene el carácter base sin Shift.
*
* @param c Carácter a procesar.
* @return char Carácter base.
*/
char getBaseChar(char c);
/**
* @brief Registra mensajes en el puerto serie.
*
* @param message Mensaje a registrar (almacenado en flash).
*/
void logMessage(const __FlashStringHelper* message);
/**
* @brief Registra mensajes en el puerto serie.
*
* @param message Mensaje a registrar (cadena dinámica).
*/
void logMessage(const char* message);
/**
* @brief Lista todos los gestos almacenados.
*/
void listGestures();
/**
* @brief Ejecuta las acciones de un gesto.
*
* @param gesture Estructura del gesto.
*/
void executeGestureActions(const Gesture& gesture);
/**
* @brief Envía un texto a través del dispositivo de teclado.
*
* @param text Cadena de texto a enviar.
*/
void sendText(const char* text);
// ========================
// Función de Configuración Inicial
// ========================
void setup() {
Serial.begin(115200);
while (!Serial) { /* Espera a que el puerto serie esté listo */ }
logMessage(F("Inicializando sistema..."));
// Configuración del dispositivo de teclado
KeyboardConfiguration keyboardConfig;
keyboardConfig.setAutoReport(true); // Activa el envío automático de informes
keyboard = new KeyboardDevice(keyboardConfig); // Crea el dispositivo de teclado
compositeHID.addDevice(keyboard);
compositeHID.begin();
// Configura los pines táctiles como entradas
for (uint8_t i = 0; i < NUM_TOUCH_PINS; i++) {
uint8_t pin = pgm_read_byte(&TOUCH_PINS[i]);
pinMode(pin, INPUT);
}
pinMode(LED_BUILTIN, OUTPUT); // Configura el LED interno como salida
preferences.begin("gestures", false); // Inicia las preferencias sin modo de solo lectura
// Registro el número de gestos almacenados
if (!preferences.isKey("count")) {
preferences.putUInt("count", 0);
}
uint8_t gestureCount = preferences.getUInt("count", 0);
logMessage(F("Sistema listo. Esperando gestos..."));
}
// ========================
// Bucle Principal
// ========================
void loop() {
detectTouch(); // Detecta toques en los pines táctiles
unsigned long currentTime = millis();
// Si hubo actividad y ha pasado el tiempo de inactividad, verifica el gesto
if (bufferSize > 0 && (currentTime - lastTouchTime > INACTIVITY_TIMEOUT_MS)) {
checkGesture();
clearBuffer();
lastGestureTime = currentTime; // Actualiza el tiempo de la última ejecución del gesto
}
// Maneja comandos recibidos por el puerto serie
if (Serial.available()) {
handleSerialCommands();
}
}
// ========================
// Implementación de Funciones
// ========================
void detectTouch() {
unsigned long currentTime = millis();
for (uint8_t i = 0; i < NUM_TOUCH_PINS; i++) {
uint8_t pin = pgm_read_byte(&TOUCH_PINS[i]);
uint8_t threshold = pgm_read_byte(&TOUCH_THRESHOLDS[i]);
bool isTouched = touchRead(pin) < threshold;
// Detecta cambios en el estado del pin (de no tocado a tocado)
if (isTouched && !(previousTouchState & (1 << i))) {
appendToBuffer(pin); // Agrega el pin al buffer si se toca
lastTouchTime = currentTime; // Actualiza el tiempo del último toque
previousTouchState |= (1 << i); // Marca el pin como tocado
}
else if (!isTouched && (previousTouchState & (1 << i))) {
previousTouchState &= ~(1 << i); // Marca el pin como no tocado
}
}
// Control del LED interno basado en la inactividad reciente
if (currentTime - lastTouchTime < 50) {
digitalWrite(LED_BUILTIN, HIGH);
}
else if (currentTime - lastTouchTime < 100) { // 2 * 50ms
digitalWrite(LED_BUILTIN, LOW);
}
}
void appendToBuffer(uint8_t pin) {
if (bufferSize < TOUCH_BUFFER_SIZE) {
touchBuffer[(bufferStart + bufferSize) % TOUCH_BUFFER_SIZE] = pin;
bufferSize++;
}
else {
// Si el buffer está lleno, reemplaza el pin más antiguo
bufferStart = (bufferStart + 1) % TOUCH_BUFFER_SIZE;
touchBuffer[(bufferStart + bufferSize - 1) % TOUCH_BUFFER_SIZE] = pin;
}
}
void clearBuffer() {
bufferStart = 0;
bufferSize = 0;
}
bool compareSequences(const uint8_t* a, uint8_t aLen, const uint8_t* b, uint8_t bLen) {
if (aLen < bLen) {
return false;
}
// Compara las últimas bLen entradas de 'a' con 'b'
uint8_t startA = (aLen > TOUCH_BUFFER_SIZE) ? (aLen - bLen) : 0;
for (uint8_t i = 0; i < bLen; i++) {
if (a[startA + i] != b[i]) {
return false;
}
}
return true;
}
bool loadGesture(uint8_t index, Gesture* gesture) {
char idKey[10];
snprintf(idKey, sizeof(idKey), "g%u_id", index);
if (!preferences.isKey(idKey)) return false;
gesture->id = (uint8_t)preferences.getUInt(idKey, 0);
if (gesture->id == 0) return false;
// Cargar secuencia de pines
char seqKey[10];
snprintf(seqKey, sizeof(seqKey), "g%u_seq", index);
String sequenceStr = preferences.getString(seqKey, "");
gesture->length = 0;
int start = 0;
while (start < sequenceStr.length() && gesture->length < TOUCH_BUFFER_SIZE) {
int comma = sequenceStr.indexOf(',', start);
String pinStr = (comma == -1) ? sequenceStr.substring(start) : sequenceStr.substring(start, comma);
pinStr.trim();
uint8_t pin = pinStr.toInt();
if (pin != 0) { // Pin válido
gesture->pinSequence[gesture->length++] = pin;
}
if (comma == -1) break;
start = comma + 1;
}
// Cargar acciones
char actKey[10];
snprintf(actKey, sizeof(actKey), "g%u_acts", index);
String actionsStr = preferences.getString(actKey, "");
gesture->actionCount = 0;
start = 0;
while (start < actionsStr.length() && gesture->actionCount < TOUCH_BUFFER_SIZE) {
int semicolon = actionsStr.indexOf(';', start);
String actionStr = (semicolon == -1) ? actionsStr.substring(start) : actionsStr.substring(start, semicolon);
actionStr.trim();
if (actionStr.length() > 0) {
Action action;
action.type = 0;
memset(action.text, 0, sizeof(action.text));
// Intentar convertir a número
uint8_t hidCode = actionStr.toInt();
if (hidCode != 0) {
// Verificar si es Media Key o Modificador
bool isMediaKey = false;
bool isModifier = false;
for (size_t k = 0; k < HIDMapSize; k++) {
HIDPair pair;
memcpy_P(&pair, &HIDMap[k], sizeof(pair));
if (hidCode == pair.value) {
if (hidCode >= 0xB0 && hidCode <= 0xF6) {
isMediaKey = true;
}
if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
isModifier = true;
}
break;
}
}
if (isMediaKey) {
action.type = 1;
action.parameter = hidCode;
}
else if (isModifier) {
action.type = 2;
action.parameter = hidCode;
}
else {
action.type = 0;
action.parameter = hidCode;
}
}
else {
// Asume que es texto
action.type = 4;
strncpy(action.text, actionStr.c_str(), sizeof(action.text) - 1);
action.text[sizeof(action.text) - 1] = '\0';
}
// Añadir acción al gesto
gesture->actions[gesture->actionCount++] = action;
}
if (semicolon == -1) break;
start = semicolon + 1;
}
return (gesture->actionCount > 0);
}
void checkGesture() {
uint8_t gestureCount = preferences.getUInt("count", 0);
if (gestureCount == 0) {
return;
}
Gesture gesture;
for (uint8_t i = 0; i < gestureCount; ++i) {
if (!loadGesture(i, &gesture)) {
continue;
}
if (compareSequences(touchBuffer + bufferStart, bufferSize, gesture.pinSequence, gesture.length)) {
if (!compositeHID.isConnected() || keyboard == nullptr) {
continue;
}
executeGestureActions(gesture);
break; // Sal del bucle al encontrar un gesto
}
}
}
void executeGestureActions(const Gesture& gesture) {
for (uint8_t a = 0; a < gesture.actionCount; a++) {
Action action = gesture.actions[a];
switch (action.type) {
case 0: // Tecla normal
keyboard->keyPress(action.parameter);
keyboard->keyRelease(action.parameter);
break;
case 1: // Media key
keyboard->mediaKeyPress(action.parameter);
keyboard->mediaKeyRelease(action.parameter);
break;
case 2: // Modificador (presionar)
keyboard->modifierKeyPress(action.parameter);
break;
case 3: // Modificador (soltar)
keyboard->modifierKeyRelease(action.parameter);
break;
case 4: // Enviar texto
sendText(action.text);
break;
default:
break;
}
}
}
void handleSerialCommands() {
while (Serial.available()) { // Maneja múltiples comandos a la vez
char commandBuffer[256];
uint16_t len = 0;
// Lee hasta '\n' o hasta llenar el buffer
while (Serial.available() && len < sizeof(commandBuffer) - 1) {
char c = Serial.read();
if (c == '\n') break;
commandBuffer[len++] = c;
}
commandBuffer[len] = '\0';
// Procesar comando
char* command = strtok(commandBuffer, " ");
if (command == NULL) {
LOG("Comando vacío.");
return;
}
if (strcmp(command, "ADD") == 0) {
// Formato esperado: ADD <secuencia_pines>|<acciones>
char* params = strtok(NULL, "\n");
if (params == NULL) {
LOG("Formato ADD incorrecto. Falta '|'.");
return;
}
char* delimiter = strchr(params, '|');
if (delimiter == NULL) {
LOG("Formato ADD incorrecto. Falta '|'.");
return;
}
*delimiter = '\0';
char* sequenceStr = params;
char* actionsStr = delimiter + 1;
// Crear nuevo gesto
Gesture newGesture;
memset(&newGesture, 0, sizeof(Gesture));
newGesture.id = generateID();
// Procesar secuencia de pines
char* pinToken = strtok(sequenceStr, " ");
while (pinToken != NULL && newGesture.length < TOUCH_BUFFER_SIZE) {
uint8_t pin = (uint8_t)atoi(pinToken);
// Verificar si pin es válido
bool validPin = false;
for (uint8_t j = 0; j < NUM_TOUCH_PINS; j++) {
uint8_t touchPin = pgm_read_byte(&TOUCH_PINS[j]);
if (pin == touchPin) {
newGesture.pinSequence[newGesture.length++] = pin;
validPin = true;
break;
}
}
if (!validPin) {
// Pin inválido, ignorar
}
pinToken = strtok(NULL, " ");
}
if (newGesture.length == 0) {
LOG("No se añadió ningún pin válido al gesto.");
return;
}
// Procesar acciones
char* actionToken = strtok(actionsStr, " ");
while (actionToken != NULL && newGesture.actionCount < TOUCH_BUFFER_SIZE) {
Action action;
memset(&action, 0, sizeof(Action));
uint8_t hidCode = getHIDCode(actionToken);
if (hidCode != 0) {
// Verificar si es Media Key o Modificador
bool isMediaKey = false;
bool isModifier = false;
for (size_t k = 0; k < HIDMapSize; k++) {
HIDPair pair;
memcpy_P(&pair, &HIDMap[k], sizeof(pair));
if (strcasecmp(actionToken, pair.key) == 0) {
if (pair.value >= 0xB0 && pair.value <= 0xF6) {
isMediaKey = true;
}
if (pair.value == KEY_LEFTCTRL || pair.value == KEY_LEFTSHIFT || pair.value == KEY_LEFTALT || pair.value == KEY_LEFTGUI) {
isModifier = true;
}
break;
}
}
if (isMediaKey) {
action.type = 1;
action.parameter = hidCode;
}
else if (isModifier) {
action.type = 2;
action.parameter = hidCode;
}
else {
action.type = 0;
action.parameter = hidCode;
}
}
else {
// Asume que es texto
action.type = 4;
strncpy(action.text, actionToken, sizeof(action.text) - 1);
action.text[sizeof(action.text) - 1] = '\0';
}
newGesture.actions[newGesture.actionCount++] = action;
actionToken = strtok(NULL, " ");
}
if (newGesture.actionCount == 0) {
LOG("No se añadieron acciones válidas al gesto.");
return;
}
// Añadir gesto a Preferences
uint8_t currentCount = preferences.getUInt("count", 0);
if (currentCount >= 100) {
LOG("Máximo número de gestos alcanzado.");
return;
}
// Guardar ID
char idKey[10];
snprintf(idKey, sizeof(idKey), "g%u_id", currentCount);
preferences.putUInt(idKey, newGesture.id);
// Guardar secuencia de pines
char seqKey[10];
snprintf(seqKey, sizeof(seqKey), "g%u_seq", currentCount);
String seqBuffer = "";
for (uint8_t j = 0; j < newGesture.length; j++) {
seqBuffer += String(newGesture.pinSequence[j]);
if (j < newGesture.length - 1) {
seqBuffer += ",";
}
}
preferences.putString(seqKey, seqBuffer);
// Guardar acciones
char actKey[10];
snprintf(actKey, sizeof(actKey), "g%u_acts", currentCount);
String actsBuffer = "";
for (uint8_t a = 0; a < newGesture.actionCount; a++) {
if (a > 0) actsBuffer += ";";
if (newGesture.actions[a].type == 4) {
actsBuffer += String(newGesture.actions[a].text);
}
else {
actsBuffer += String(newGesture.actions[a].parameter);
}
}
preferences.putString(actKey, actsBuffer);
// Actualizar cuenta de gestos
preferences.putUInt("count", currentCount + 1);
LOG("Gesto añadido exitosamente.");
}
else if (strcmp(command, "DEL") == 0) {
// Formato esperado: DEL <ID>
char* idStr = strtok(NULL, " ");
if (idStr == NULL) {
LOG("Formato DEL incorrecto. Falta ID.");
return;
}
uint8_t id = (uint8_t)atoi(idStr);
uint8_t gestureCount = preferences.getUInt("count", 0);
bool found = false;
for (uint8_t i = 0; i < gestureCount; i++) {
char idKey[10];
snprintf(idKey, sizeof(idKey), "g%u_id", i);
uint8_t storedId = (uint8_t)preferences.getUInt(idKey, 0);
if (storedId == id) {
// Eliminar gesto moviendo los siguientes gestos hacia atrás
for (uint8_t j = i; j < gestureCount - 1; j++) {
char srcIdKey[10], srcSeqKey[10], srcActKey[10];
snprintf(srcIdKey, sizeof(srcIdKey), "g%u_id", j + 1);
snprintf(srcSeqKey, sizeof(srcSeqKey), "g%u_seq", j + 1);
snprintf(srcActKey, sizeof(srcActKey), "g%u_acts", j + 1);
char dstIdKey[10], dstSeqKey[10], dstActKey[10];
snprintf(dstIdKey, sizeof(dstIdKey), "g%u_id", j);
snprintf(dstSeqKey, sizeof(dstSeqKey), "g%u_seq", j);
snprintf(dstActKey, sizeof(dstActKey), "g%u_acts", j);
// Mover datos
preferences.putUInt(dstIdKey, preferences.getUInt(srcIdKey, 0));
preferences.putString(dstSeqKey, preferences.getString(srcSeqKey, ""));
preferences.putString(dstActKey, preferences.getString(srcActKey, ""));
// Eliminar origen
preferences.remove(srcIdKey);
preferences.remove(srcSeqKey);
preferences.remove(srcActKey);
}
// Actualizar cuenta de gestos
preferences.putUInt("count", gestureCount - 1);
LOG("Gesto eliminado exitosamente.");
found = true;
break;
}
}
if (!found) {
LOG("Gesto no encontrado.");
}
}
else if (strcmp(command, "LIST") == 0) {
// Lista todos los gestos almacenados
listGestures();
}
else if (strcmp(command, "TEST") == 0) {
// Comando de prueba para verificar la memoria disponible
char bufferMsg[30];
snprintf(bufferMsg, sizeof(bufferMsg), "Memoria libre: %u bytes", ESP.getFreeHeap());
logMessage(bufferMsg); // Ahora válido gracias a la sobrecarga
}
else {
LOG("Comando desconocido.");
}
}
}
bool loadGesture(uint8_t index, Gesture* gesture) {
// Implementación revisada previa
// ...
}
void addGesture(const Gesture& newGesture) {
// Implementado dentro de handleSerialCommands()
}
void deleteGesture(uint8_t id) {
// Implementado dentro de handleSerialCommands()
}
uint8_t generateID() {
uint8_t gestureCount = preferences.getUInt("count", 0);
for (uint16_t id = 1; id <= 255; id++) {
bool exists = false;
Gesture tempGesture;
for (uint8_t i = 0; i < gestureCount; i++) {
if (loadGesture(i, &tempGesture)) {
if (tempGesture.id == id) {
exists = true;
break;
}
}
}
if (!exists) return id;
}
return 0; // Retorna 0 si no hay IDs disponibles
}
uint8_t getHIDCode(const char* action) {
for (size_t i = 0; i < HIDMapSize; i++) {
HIDPair pair;
memcpy_P(&pair, &HIDMap[i], sizeof(pair));
if (strcasecmp(action, pair.key) == 0) {
return pair.value;
}
}
return 0; // Si no encuentra la acción, retorna 0
}
bool needsShift(char c) {
if (isupper(c)) return true;
// Lista de símbolos que requieren Shift
const char symbolsRequiringShift[] PROGMEM = "!@#$%^&*()_+{}|:\"<>?~[]\\;',./`-=";
for (uint8_t i = 0; i < sizeof(symbolsRequiringShift) - 1; i++) {
if (c == pgm_read_byte(&symbolsRequiringShift[i])) return true;
}
return false;
}
char getBaseChar(char c) {
if (isupper(c)) {
return tolower(c);
}
switch (c) {
case '!': return '1';
case '@': return '2';
case '#': return '3';
case '$': return '4';
case '%': return '5';
case '^': return '6';
case '&': return '7';
case '*': return '8';
case '(': return '9';
case ')': return '0';
case '_': return '-';
case '+': return '=';
case '{': return '[';
case '}': return ']';
case '|': return '\\';
case ':': return ';';
case '"': return '\'';
case '<': return ',';
case '>': return '.';
case '?': return '/';
case '~': return '`';
default: return c;
}
}
void logMessage(const __FlashStringHelper* message) {
Serial.print(F("[LOG] "));
Serial.println(message);
}
void logMessage(const char* message) {
Serial.print("[LOG] ");
Serial.println(message);
}
void listGestures() {
uint8_t gestureCount = preferences.getUInt("count", 0);
if (gestureCount == 0) {
logMessage(F("No hay gestos almacenados."));
return;
}
Serial.println(F("=== Lista de Gestos ==="));
Gesture gesture;
for (uint8_t i = 0; i < gestureCount; i++) {
if (!loadGesture(i, &gesture)) {
continue;
}
Serial.print(F("ID: "));
Serial.print(gesture.id);
Serial.print(F(" | Secuencia: "));
for (uint8_t j = 0; j < gesture.length; j++) {
Serial.print(gesture.pinSequence[j]);
if (j < gesture.length - 1) {
Serial.print(F(" -> "));
}
}
Serial.print(F(" | Acciones: "));
for (uint8_t a = 0; a < gesture.actionCount; a++) {
char actionType[30];
switch (gesture.actions[a].type) {
case 0: strcpy(actionType, "Tecla"); break;
case 1: strcpy(actionType, "Media Key"); break;
case 2: strcpy(actionType, "Modificador (Presionar)"); break;
case 3: strcpy(actionType, "Modificador (Soltar)"); break;
case 4: strcpy(actionType, "Texto"); break;
default: strcpy(actionType, "Desconocido"); break;
}
if (gesture.actions[a].type != 4) {
char actionMsg[50];
snprintf(actionMsg, sizeof(actionMsg), "%s(%u)", actionType, gesture.actions[a].parameter);
Serial.print(actionMsg);
}
else {
char actionMsg[50];
snprintf(actionMsg, sizeof(actionMsg), "%s(%s)", actionType, gesture.actions[a].text);
Serial.print(actionMsg);
}
if (a < gesture.actionCount - 1) {
Serial.print(F(", "));
}
}
Serial.println(); // Nueva línea al final de cada gesto
}
}
uint8_t generateID() {
uint8_t gestureCount = preferences.getUInt("count", 0);
for (uint16_t id = 1; id <= 255; id++) {
bool exists = false;
Gesture tempGesture;
for (uint8_t i = 0; i < gestureCount; i++) {
if (loadGesture(i, &tempGesture)) {
if (tempGesture.id == id) {
exists = true;
break;
}
}
}
if (!exists) return id;
}
return 0; // Retorna 0 si no hay IDs disponibles
}
void executeGestureActions(const Gesture& gesture) {
for (uint8_t a = 0; a < gesture.actionCount; a++) {
Action action = gesture.actions[a];
switch (action.type) {
case 0: // Tecla normal
keyboard->keyPress(action.parameter);
keyboard->keyRelease(action.parameter);
break;
case 1: // Media key
keyboard->mediaKeyPress(action.parameter);
keyboard->mediaKeyRelease(action.parameter);
break;
case 2: // Modificador (presionar)
keyboard->modifierKeyPress(action.parameter);
break;
case 3: // Modificador (soltar)
keyboard->modifierKeyRelease(action.parameter);
break;
case 4: // Enviar texto
sendText(action.text);
break;
default:
break;
}
}
}
void sendText(const char* text) {
for (uint8_t c = 0; c < sizeof(text) && text[c] != '\0'; c++) {
bool shift_needed = needsShift(text[c]);
if (shift_needed) {
keyboard->modifierKeyPress(KEY_LEFTSHIFT);
}
char baseChar = getBaseChar(text[c]);
uint8_t key = getHIDCode(&baseChar);
if (key != 0) {
keyboard->keyPress(key);
keyboard->keyRelease(key);
}
if (shift_needed) {
keyboard->modifierKeyRelease(KEY_LEFTSHIFT);
}
}
}