Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

modifica mi codigo para que use la memoria flash antes que la ram, buscando optimizar el…

  1. User

    modifica mi codigo para que use la memoria flash antes que la ram, buscando optimizar el uso de esta al maximo, para ahorrar la memoria ram. quisiera que solo me respondieras con el codigo completo en una caja de codigo. aqui esta mi codigo: // ======================== // Proyecto ESP32 HID SIR // ========================

    // === Inclusión de Bibliotecas === #include <Arduino.h> #include <BleCompositeHID.h> #include <KeyboardDevice.h> #include <Preferences.h> #include

    // === Definición de Constantes HID Faltantes ===

    // Teclas Modificadoras #define KEY_LEFTGUI 0xE3 // Modifier Left GUI (e.g., Windows key) #define KEY_RIGHTGUI 0xE7 // Modifier Right GUI #define KEY_MEDIA_PLAYPAUSE 0xE8 // Play/Pause Media Key #define KEY_MEDIA_STOP 0xEA // Stop Media Key #define KEY_MEDIA_NEXTTRACK 0xB0 // Next Track Media Key #define KEY_MEDIA_PREVIOUSTRACK 0xB1 // Previous Track Media Key #define KEY_MEDIA_VOLUMEDOWN 0xB2 // Volume Down Media Key #define KEY_MEDIA_VOLUMEUP 0xB3 // Volume Up Media Key #define KEY_MEDIA_MUTE 0xE2 // Mute Media Key #define KEY_MEDIA_WWWHOME 0xB5 // WWW Home Media Key #define KEY_MEDIA_EMAIL_READER 0xF0 // Email Reader Media Key #define KEY_MEDIA_LOCAL_MACHINE_BROWSER 0xF1 // Local Machine Browser Media Key #define KEY_MEDIA_WWW_BOOKMARKS 0xF2 // WWW Bookmarks Media Key #define KEY_MEDIA_WWW_SEARCH 0xF3 // WWW Search Media Key #define KEY_MEDIA_WWW_STOP 0xF4 // WWW Stop Media Key #define KEY_MEDIA_WWW_BACK 0xF5 // WWW Back Media Key #define KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION 0xF6 // Consumer Control Configuration Media Key

    // === Configuración de Pines Táctiles === constexpr byte TOUCH_PINS[] = { 4, 12, 13, 14, 15, 27, 32, 33 }; constexpr byte NUM_TOUCH_PINS = sizeof(TOUCH_PINS) / sizeof(TOUCH_PINS[0]); constexpr byte TOUCH_THRESHOLDS[] = { 40, 40, 40, 40, 30, 40, 40, 50 }; // Valores normales sugeridos para umbrales: {60, 50, 55, 60, 55, 65, 65, 50}

    // === Parámetros de Gestos === constexpr unsigned int INACTIVITY_TIMEOUT = 500; // Tiempo para considerar inactividad (ms) //constexpr byte MAX_GESTURES = 20; // Número máximo de gestos almacenables //constexpr byte MAX_SEQUENCE = 20; // Longitud máxima de la secuencia de pines por gesto //constexpr byte MAX_ACTIONS = 10; // Número máximo de acciones por gesto //constexpr unsigned long GESTURE_COOLDOWN = 100; // Tiempo de enfriamiento después de ejecutar un gesto (ms)

    // === Buffers y Contadores === //byte touchBuffer[MAX_SEQUENCE]; byte touchBuffer[64]; byte bufferStart = 0; byte bufferSize = 0; byte currentGestureIndex = 0;

    // === Estructuras para Acciones y Gestos === struct Action { byte type; // Tipo de acción (0: Tecla, 1: Media Key, 2: Modificador Presionar, 3: Modificador Soltar, 4: Texto) byte parameter; // Código HID correspondiente String text; // Texto asociado (solo para tipo 4) };

    struct Gesture { byte id; // Identificador único del gesto //byte pinSequence[MAX_SEQUENCE]; byte pinSequence[32]; // Secuencia de pines que conforman el gesto //Action actions[MAX_ACTIONS]; byte length; // Longitud de la secuencia Action actions[32]; // Acciones asociadas al gesto byte actionCount; // Número de acciones };

    //Gesture gestures[MAX_GESTURES]; Gesture gestures[32]; byte gestureCount = 0;

    // === Variables de Estado === bool previousTouchState[NUM_TOUCH_PINS] = { false }; unsigned long lastTouchTime = 0; unsigned long lastGestureTime = 0; // Para cooldown

    // === Inicialización de Bluetooth, Teclado y Almacenamiento === Preferences preferences; const char* DEVICE_NAME = "ESP32 HID Controller"; const char* DEVICE_MANUFACTURER = "Mystfit"; BleCompositeHID compositeHID(DEVICE_NAME, DEVICE_MANUFACTURER, 100); KeyboardDevice* keyboard;

    // === Prototipos de Funciones === void detectTouch(); void checkGesture(); void handleSerialCommands(); bool compareSequences(const uint8_t* a, byte aLen, const uint8_t* b, byte bLen); void addGesture(const Gesture& newGesture); void deleteGesture(byte id); void loadGestures(); void saveGestures(); void clearBuffer(); void appendToBuffer(byte pin); unsigned int generateID(); byte getHIDCode(const String& action); bool needsShift(char c); char getBaseChar(char c); void logMessage(const String& message); void listGestures();

    // === Función de Configuración Inicial === void setup() { Serial.begin(115200); while (!Serial) { /* Espera a que el puerto serie esté listo */ }

    logMessage("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 (byte i = 0; i < NUM_TOUCH_PINS; i++) {
      pinMode(TOUCH_PINS[i], INPUT);
    }
    
    pinMode(LED_BUILTIN, OUTPUT);          // Configura el LED interno como salida
    preferences.begin("gestures", false);  // Inicia las preferencias sin modo de solo lectura
    
    loadGestures();  // Carga los gestos almacenados
    logMessage("Sistema listo. Esperando gestos...");
    

    }

    // === Bucle Principal === void loop() { detectTouch(); // Detecta toques en los pines táctiles

    unsigned long currentTime = millis(); // Si hubo actividad, 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 (byte i = 0; i < NUM_TOUCH_PINS; i++) { byte pin = TOUCH_PINS[i]; byte touchValue = touchRead(pin); bool isTouched = touchValue < TOUCH_THRESHOLDS[i];

    // Detecta cambios en el estado del pin (from not touched to touched)
    if (isTouched && !previousTouchState[i]) {
      appendToBuffer(pin);          // Agrega el pin al buffer si se toca
      lastTouchTime = currentTime;  // Actualiza el tiempo del último toque
    }
    
    // Actualiza el estado previo
    previousTouchState[i] = isTouched;
    

    }

    // 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(byte pin) { logMessage("Pin " + String(pin) + " añadido al buffer.");

    if (bufferSize < 255) { touchBuffer[(bufferStart + bufferSize) % 255] = pin; bufferSize++; } else { // Si el buffer está lleno, reemplaza el pin más antiguo bufferStart = (bufferStart + 1) % 255; touchBuffer[(bufferStart + bufferSize - 1) % 255] = pin; logMessage("Buffer lleno, reemplazando el pin más antiguo."); } }

    // === Limpia el Buffer Táctil === void clearBuffer() { bufferStart = 0; bufferSize = 0; logMessage("Buffer limpiado por inactividad."); }

    // === Compara Dos Secuencias de Pines === bool compareSequences(const uint8_t* a, byte aLen, const uint8_t* b, byte bLen) { if (aLen < bLen) { logMessage("Secuencia detectada es más corta que la secuencia del gesto."); return false; }

    // Compara las últimas bLen entradas de 'a' con 'b'
    for (byte i = 0; i < bLen; i++) {
      if (a[aLen - bLen + i] != b[i]) {
        return false;
      }
    }
    return true;
    

    }

    // === Verifica si el Buffer Coincide con Algún Gesto Almacenado === void checkGesture() { if (gestureCount == 0) { logMessage("No hay gestos almacenados para verificar."); return; }

    bool gestureFound = false;
    
    for (byte i = 0; i < gestureCount; ++i) {
      if (compareSequences(touchBuffer, bufferSize, gestures[i].pinSequence, gestures[i].length)) {
        logMessage("Gesto detectado: ID " + String(gestures[i].id));
    
        if (!compositeHID.isConnected()) {
          logMessage("BleKeyboard no está conectado.");
          continue;
        }
    
        if (keyboard == nullptr) {
          logMessage("El objeto keyboard no está inicializado.");
          continue;
        }
    
        // Ejecuta todas las acciones asociadas al gesto
        for (byte a = 0; a < gestures[i].actionCount; a++) {
          Action action = gestures[i].actions[a];
          switch (action.type) {
            case 0:  // Tecla normal
              keyboard->keyPress(action.parameter);
              logMessage("Enviar tecla HID code: " + String(action.parameter));
              keyboard->keyRelease(action.parameter);
              break;
            case 1:  // Media key
              keyboard->mediaKeyPress(action.parameter);
              logMessage("Enviar Media Key HID code: " + String(action.parameter));
              keyboard->mediaKeyRelease(action.parameter);
              break;
            case 2:  // Modificador (presionar)
              keyboard->modifierKeyPress(action.parameter);
              logMessage("Presionar modificador HID code: " + String(action.parameter));
              break;
            case 3:  // Modificador (soltar)
              keyboard->modifierKeyRelease(action.parameter);
              logMessage("Liberar modificador HID code: " + String(action.parameter));
              break;
            case 4:  // Enviar texto
              for (char c : action.text) {
                bool shift_needed = needsShift(c);
    
                if (shift_needed) {
                  keyboard->modifierKeyPress(KEY_LEFTSHIFT);
                }
    
                char baseChar = getBaseChar(c);
                String keyStr = String(baseChar);
                byte key = getHIDCode(keyStr);
    
                if (key != 0) {
                  keyboard->keyPress(key);
                  logMessage("Enviar tecla de texto: " + String(c));
                  keyboard->keyRelease(key);
                  delay(50);  // Pausa para evitar inundación de eventos
                } else {
                  logMessage("Caracter no soportado: " + String(c));
                }
    
                if (shift_needed) {
                  keyboard->modifierKeyRelease(KEY_LEFTSHIFT);
                }
              }
              break;
            default:
              logMessage("Tipo de acción desconocido: " + String(action.type));
              break;
          }
        }
    
        gestureFound = true;
        break;  // Sale del bucle al encontrar un gesto
      }
    }
    
    if (gestureFound) {
      logMessage("Gesto ejecutado correctamente.");
    } else {
      logMessage("No se encontró un gesto que coincida con la secuencia detectada.");
    }
    

    }

    // === Maneja Comandos Recibidos por el Puerto Serie === void handleSerialCommands() { while (Serial.available()) { // Maneja múltiples comandos a la vez String command = Serial.readStringUntil('\n'); command.trim(); logMessage("Comando recibido: " + command);

        if (command.startsWith("ADD")) {
            // Formato esperado: ADD <secuencia_pines>|<acciones>
            int delimiter = command.indexOf('|');
            if (delimiter == -1) {
                logMessage("Formato ADD incorrecto. Falta '|'.");
                return;
            }
    
            String sequenceStr = command.substring(4, delimiter);
            String actionsStr = command.substring(delimiter + 1);
            sequenceStr.trim();
            actionsStr.trim();
    
            Gesture newGesture;
            newGesture.id = generateID();
            newGesture.length = 0;
            newGesture.actionCount = 0;
    
            // Procesar secuencia de pines
            int start = 0;
            while (start < sequenceStr.length()) {
                int space = sequenceStr.indexOf(' ', start);
                String pinStr = (space == -1) ? sequenceStr.substring(start) : sequenceStr.substring(start, space);
                pinStr.trim();
    
                // Verificar si pinStr es un número válido
                bool isNumber = true;
                for (char c : pinStr) {
                    if (!isDigit(c)) {
                        isNumber = false;
                        break;
                    }
                }
    
                if (isNumber) {
                    byte pin = pinStr.toInt();
                    bool validPin = false;
                    for (byte j = 0; j < NUM_TOUCH_PINS; j++) {
                        if (pin == TOUCH_PINS[j]) {
                            newGesture.pinSequence[newGesture.length++] = pin;
                            validPin = true;
                            break;
                        }
                    }
                    if (!validPin) {
                        logMessage("Pin inválido en secuencia: " + pinStr);
                    }
                } else {
                    logMessage("Formato de pin inválido: " + pinStr);
                }
    
                if (space == -1) break;
                start = space + 1;
            }
    
            if (newGesture.length == 0) {
                logMessage("No se añadió ningún pin válido al gesto.");
                return;
            }
    
            // Procesar acciones
            start = 0;
            while (start < actionsStr.length()) {
                int space = actionsStr.indexOf(' ', start);
                String actionStr = (space == -1) ? actionsStr.substring(start) : actionsStr.substring(start, space);
                actionStr.trim();
    
                byte hidCode = getHIDCode(actionStr);
                if (hidCode != 0) {
                    // Verificar explícitamente si es un Media Key
                    bool isMediaKey = (hidCode == KEY_MEDIA_PLAYPAUSE || hidCode == KEY_MEDIA_STOP || hidCode == KEY_MEDIA_NEXTTRACK || hidCode == KEY_MEDIA_PREVIOUSTRACK || hidCode == KEY_MEDIA_VOLUMEDOWN || hidCode == KEY_MEDIA_VOLUMEUP || hidCode == KEY_MEDIA_MUTE || hidCode == KEY_MEDIA_WWWHOME || hidCode == KEY_MEDIA_EMAIL_READER || hidCode == KEY_MEDIA_LOCAL_MACHINE_BROWSER || hidCode == KEY_MEDIA_WWW_BOOKMARKS || hidCode == KEY_MEDIA_WWW_SEARCH || hidCode == KEY_MEDIA_WWW_STOP || hidCode == KEY_MEDIA_WWW_BACK || hidCode == KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION);
    
                    if (isMediaKey) {
                        newGesture.actions[newGesture.actionCount++] = { 1, hidCode, "" };
                    } else if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
                        newGesture.actions[newGesture.actionCount++] = { 2, hidCode, "" };
                    } else {
                        newGesture.actions[newGesture.actionCount++] = { 0, hidCode, "" };
                    }
                } else {
                    // Asume que es texto si no coincide con ningún código HID conocido
                    newGesture.actions[newGesture.actionCount++] = { 4, 0, actionStr };
                }
    
                if (space == -1) break;
                start = space + 1;
            }
    
            if (newGesture.actionCount == 0) {
                logMessage("No se añadieron acciones válidas al gesto.");
                return;
            }
    
            // Añadir el nuevo gesto
            gestures[currentGestureIndex++] = newGesture;
            saveGestures();
            logMessage("Gesto añadido exitosamente. ID: " + String(newGesture.id));
    
        } else if (command.startsWith("DEL")) {
            // Formato esperado: DEL <ID>
            String idStr = command.substring(4);
            idStr.trim();
            if (idStr.length() == 0) {
                logMessage("Formato DEL incorrecto. Falta ID.");
                return;
            }
            unsigned long id = idStr.toInt();
            bool found = false;
            for (byte i = 0; i < gestureCount; ++i) {
                if (gestures[i].id == id) {
                    for (byte j = i; j < gestureCount - 1; ++j) {
                        gestures[j] = gestures[j + 1];
                    }
                    --gestureCount;
                    saveGestures();
                    logMessage("Gesto con ID " + String(id) + " eliminado exitosamente.");
                    found = true;
                    break;
                }
            }
            if (!found) {
                logMessage("Gesto con ID " + String(id) + " no encontrado.");
            }
    
        } else if (command.equalsIgnoreCase("LIST")) {
            // Lista todos los gestos almacenados
            listGestures();
    
        } else if (command.equalsIgnoreCase("TEST")) {
            // Comando de prueba para verificar la memoria disponible
            logMessage("Memoria libre: " + String(ESP.getFreeHeap()) + " bytes");
    
        } else {
            logMessage("Comando desconocido: " + command);
        }
    }
    

    }

    // === Añade un Gesto a la Lista === void addGesture(const Gesture& newGesture) { gestures[gestureCount++] = newGesture; saveGestures(); logMessage("Gesto añadido. ID: " + String(newGesture.id)); }

    // === Elimina un Gesto por ID === void deleteGesture(byte id) { for (byte i = 0; i < gestureCount; ++i) { if (gestures[i].id == id) { gestures[i] = gestures[gestureCount - 1]; // Reemplaza con el último gesto gestureCount--; saveGestures(); logMessage("Gesto con ID " + String(id) + " eliminado exitosamente."); return; } } logMessage("Gesto con ID " + String(id) + " no encontrado."); }

    // === Carga los Gestos Almacenados desde las Preferencias === void loadGestures() { gestureCount = 0;

    while (true) {
      String idKey = "g" + String(gestureCount) + "_id";
      if (!preferences.isKey(idKey.c_str())) break;
    
      unsigned long id = preferences.getUInt(idKey.c_str(), 0);
      if (id == 0) break;
    
      Gesture gesture;
      gesture.id = id;
    
      // Cargar secuencia de pines
      String seqKey = "g" + String(gestureCount) + "_seq";
      String sequenceStr = preferences.getString(seqKey.c_str(), "");
      gesture.length = 0;
      int start = 0;
      int comma = sequenceStr.indexOf(',', start);
      while (comma != -1) {
        String pinStr = sequenceStr.substring(start, comma);
        pinStr.trim();
        byte pin = pinStr.toInt();
        gesture.pinSequence[gesture.length++] = pin;
        start = comma + 1;
        comma = sequenceStr.indexOf(',', start);
      }
      // Añadir el último pin después de la última coma
      if (start < sequenceStr.length()) {
        String pinStr = sequenceStr.substring(start);
        pinStr.trim();
        byte pin = pinStr.toInt();
        gesture.pinSequence[gesture.length++] = pin;
      }
    
      // Cargar acciones
      String actKey = "g" + String(gestureCount) + "_acts";
      String actionsStr = preferences.getString(actKey.c_str(), "");
      gesture.actionCount = 0;
      start = 0;
      comma = actionsStr.indexOf(';', start);
      while (comma != -1) {
        String actionStr = actionsStr.substring(start, comma);
        actionStr.trim();
        byte hidCode = getHIDCode(actionStr);
    
        if (hidCode != 0) {
          // Verificar explícitamente si es un Media Key
          bool isMediaKey = (
            hidCode == KEY_MEDIA_PLAYPAUSE ||
            hidCode == KEY_MEDIA_STOP ||
            hidCode == KEY_MEDIA_NEXTTRACK ||
            hidCode == KEY_MEDIA_PREVIOUSTRACK ||
            hidCode == KEY_MEDIA_VOLUMEDOWN ||
            hidCode == KEY_MEDIA_VOLUMEUP ||
            hidCode == KEY_MEDIA_MUTE ||
            hidCode == KEY_MEDIA_WWWHOME ||
            hidCode == KEY_MEDIA_EMAIL_READER ||
            hidCode == KEY_MEDIA_LOCAL_MACHINE_BROWSER ||
            hidCode == KEY_MEDIA_WWW_BOOKMARKS ||
            hidCode == KEY_MEDIA_WWW_SEARCH ||
            hidCode == KEY_MEDIA_WWW_STOP ||
            hidCode == KEY_MEDIA_WWW_BACK ||
            hidCode == KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION
          );
    
          if (isMediaKey) {
            gesture.actions[gesture.actionCount++] = {1, hidCode, ""};
          } 
          else if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
            gesture.actions[gesture.actionCount++] = {2, hidCode, ""};
          } 
          else {
            gesture.actions[gesture.actionCount++] = {0, hidCode, ""};
          }
        } 
        else {
          // Asume que es texto si no coincide con ningún código HID conocido
          gesture.actions[gesture.actionCount++] = {4, 0, actionStr};
        }
    
        start = comma + 1;
        comma = actionsStr.indexOf(';', start);
      }
      // Añadir la última acción después de la última coma
      if (start < actionsStr.length()) {
        String actionStr = actionsStr.substring(start);
        actionStr.trim();
        byte hidCode = getHIDCode(actionStr);
    
        if (hidCode != 0) {
          // Verificar explícitamente si es un Media Key
          bool isMediaKey = (
            hidCode == KEY_MEDIA_PLAYPAUSE ||
            hidCode == KEY_MEDIA_STOP ||
            hidCode == KEY_MEDIA_NEXTTRACK ||
            hidCode == KEY_MEDIA_PREVIOUSTRACK ||
            hidCode == KEY_MEDIA_VOLUMEDOWN ||
            hidCode == KEY_MEDIA_VOLUMEUP ||
            hidCode == KEY_MEDIA_MUTE ||
            hidCode == KEY_MEDIA_WWWHOME ||
            hidCode == KEY_MEDIA_EMAIL_READER ||
            hidCode == KEY_MEDIA_LOCAL_MACHINE_BROWSER ||
            hidCode == KEY_MEDIA_WWW_BOOKMARKS ||
            hidCode == KEY_MEDIA_WWW_SEARCH ||
            hidCode == KEY_MEDIA_WWW_STOP ||
            hidCode == KEY_MEDIA_WWW_BACK ||
            hidCode == KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION
          );
    
          if (isMediaKey) {
            gesture.actions[gesture.actionCount++] = {1, hidCode, ""};
          } 
          else if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
            gesture.actions[gesture.actionCount++] = {2, hidCode, ""};
          } 
          else {
            gesture.actions[gesture.actionCount++] = {0, hidCode, ""};
          }
        } 
        else {
          // Asume que es texto si no coincide con ningún código HID conocido
          gesture.actions[gesture.actionCount++] = {4, 0, actionStr};
        }
      }
    
      gestures[gestureCount++] = gesture;
    }
    
    logMessage("Gestos cargados: " + String(gestureCount));
    

    }

    // === Guarda los Gestos Actuales en las Preferencias === void saveGestures() { preferences.begin("gestures", false); // Inicia las preferencias sin modo de solo lectura preferences.clear(); // Limpia las preferencias antes de guardar

    for (byte i = 0; i < gestureCount; ++i) {
      // Guardar ID del gesto
      String idKey = "g" + String(i) + "_id";
      preferences.putUInt(idKey.c_str(), gestures[i].id);
    
      // Guardar secuencia de pines
      String seqKey = "g" + String(i) + "_seq";
      String sequenceStr;
      for (byte j = 0; j < gestures[i].length; j++) {
        if (j > 0) sequenceStr += ",";
        sequenceStr += String(gestures[i].pinSequence[j]);
      }
      preferences.putString(seqKey.c_str(), sequenceStr);
    
    
      // Guardar acciones
      String actKey = "g" + String(i) + "_acts";
      String actionsStr;
      for (byte a = 0; a < gestures[i].actionCount; a++) {
        if (a > 0) actionsStr += ";";
        if (gestures[i].actions[a].type == 4) {
          // Acción de texto
          actionsStr += gestures[i].actions[a].text;
        } else {
          actionsStr += String(gestures[i].actions[a].parameter);
        }
      }
      preferences.putString(actKey.c_str(), actionsStr);
    }
    
    
    logMessage("Gestos guardados en preferencias.");
    preferences.end(); // Finaliza el uso de las preferencias
    

    }

    // === Genera un ID Único para un Nuevo Gesto === unsigned int generateID() { // Busca el primer ID libre en el rango 1 a 255 for (unsigned int id = 1; id <= 255; id++) { bool exists = false; for (byte i = 0; i < gestureCount; i++) { if (gestures[i].id == id) { exists = true; break; } } if (!exists) return id; }

    logMessage("No se encontró un ID disponible."); return 0; // Retorna 0 si no hay IDs disponibles }

    // === Mapa para Convertir Acciones en Códigos HID === byte getHIDCode(const String& action) { // Crear una copia mutable de la cadena para modificarla String capAction = action; capAction.toUpperCase();

    static const std::map<String, byte> HIDMap = {
      // 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 },
      { "CALCULATOR", KEY_MEDIA_CALCULATOR },
      { "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 }
    };
    
    auto it = HIDMap.find(capAction);
    if (it != HIDMap.end()) {
      return it->second;
    }
    
    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 = "!@#$%^&*()_+{}|:\"<>?~[]\\;',./`-=";
    return strchr(symbolsRequiringShift, c) != NULL;
    

    }

    // === Función de Ayuda: Obtiene el carácter base sin Shift === char getBaseChar(char c) { // Si el carácter es mayúscula o símbolo que requiere Shift, retorna el carácter base 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 === void logMessage(const String& message) { Serial.println("[LOG] " + message); }

    // === Lista Todos los Gestos Almacenados === void listGestures() { if (gestureCount == 0) { logMessage("No hay gestos almacenados."); return; }

    Serial.println("=== Lista de Gestos ===");
    for (byte i = 0; i < gestureCount; i++) {
      Serial.print("ID: ");
      Serial.print(gestures[i].id);
      Serial.print(" | Secuencia: ");
    
      for (byte j = 0; j < gestures[i].length; j++) {
        Serial.print(gestures[i].pinSequence[j]);
        if (j < gestures[i].length - 1) {
          Serial.print(" -> ");
        }
      }
    
      Serial.print(" | Acciones: ");
      for (byte a = 0; a < gestures[i].actionCount; a++) {
        String actionType;
        switch (gestures[i].actions[a].type) {
          case 0: actionType = "Tecla"; break;
          case 1: actionType = "Media Key"; break;
          case 2: actionType = "Modificador (Presionar)"; break;
          case 3: actionType = "Modificador (Soltar)"; break;
          case 4: actionType = "Texto"; break;
          default: actionType = "Desconocido"; break;
        }
        if (gestures[i].actions[a].type != 4) {
          Serial.print(actionType + "(" + String(gestures[i].actions[a].parameter) + ")");
        } else {
          Serial.print(actionType + "(" + gestures[i].actions[a].text + ")");
        }
        if (a < gestures[i].actionCount - 1) {
          Serial.print(", ");
        }
      }
      Serial.println();  // Nueva línea al final de cada gesto
    }
    

    }

  2. Assistant
    // ========================
    // Proyecto ESP32 HID SIR Optimizado para Flash
    // ========================
    
    // === Inclusión de Bibliotecas ===
    #include <Arduino.h>
    #include <BleCompositeHID.h>
    #include <KeyboardDevice.h>
    #include <Preferences.h>
    
    // === Definición de Constantes HID Faltantes ===
    
    // Teclas Modificadoras
    #define KEY_LEFTGUI 0xE3                               // Modifier Left GUI (e.g., Windows key)
    #define KEY_RIGHTGUI 0xE7                              // Modifier Right GUI
    #define KEY_MEDIA_PLAYPAUSE 0xE8                       // Play/Pause Media Key
    #define KEY_MEDIA_STOP 0xEA                            // Stop Media Key
    #define KEY_MEDIA_NEXTTRACK 0xB0                       // Next Track Media Key
    #define KEY_MEDIA_PREVIOUSTRACK 0xB1                   // Previous Track Media Key
    #define KEY_MEDIA_VOLUMEDOWN 0xB2                      // Volume Down Media Key
    #define KEY_MEDIA_VOLUMEUP 0xB3                        // Volume Up Media Key
    #define KEY_MEDIA_MUTE 0xE2                            // Mute Media Key
    #define KEY_MEDIA_WWWHOME 0xB5                         // WWW Home Media Key
    #define KEY_MEDIA_EMAIL_READER 0xF0                    // Email Reader Media Key
    #define KEY_MEDIA_LOCAL_MACHINE_BROWSER 0xF1           // Local Machine Browser Media Key
    #define KEY_MEDIA_WWW_BOOKMARKS 0xF2                   // WWW Bookmarks Media Key
    #define KEY_MEDIA_WWW_SEARCH 0xF3                      // WWW Search Media Key
    #define KEY_MEDIA_WWW_STOP 0xF4                        // WWW Stop Media Key
    #define KEY_MEDIA_WWW_BACK 0xF5                        // WWW Back Media Key
    #define KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION 0xF6  // Consumer Control Configuration Media Key
    
    // === Configuración de Pines Táctiles ===
    static const byte TOUCH_PINS[] PROGMEM = { 4, 12, 13, 14, 15, 27, 32, 33 };
    static const byte NUM_TOUCH_PINS = sizeof(TOUCH_PINS) / sizeof(TOUCH_PINS[0]);
    static const byte TOUCH_THRESHOLDS[] PROGMEM = { 40, 40, 40, 40, 30, 40, 40, 50 };
    // Valores normales sugeridos para umbrales: {60, 50, 55, 60, 55, 65, 65, 50}
    
    // === Parámetros de Gestos ===
    static const unsigned int INACTIVITY_TIMEOUT = 500;  // Tiempo para considerar inactividad (ms)
    // constexpr byte MAX_GESTURES = 20;                 // Número máximo de gestos almacenables
    // constexpr byte MAX_SEQUENCE = 20;                 // Longitud máxima de la secuencia de pines por gesto
    // constexpr byte MAX_ACTIONS = 10;                  // Número máximo de acciones por gesto
    // constexpr unsigned long GESTURE_COOLDOWN = 100;    // Tiempo de enfriamiento después de ejecutar un gesto (ms)
    
    // === Buffers y Contadores ===
    static byte touchBuffer[64];
    static byte bufferStart = 0;
    static byte bufferSize = 0;
    static byte currentGestureIndex = 0;
    
    // === Estructuras para Acciones y Gestos ===
    struct Action {
      byte type;       // Tipo de acción (0: Tecla, 1: Media Key, 2: Modificador Presionar, 3: Modificador Soltar, 4: Texto)
      byte parameter;  // Código HID correspondiente
      String text;     // Texto asociado (solo para tipo 4)
    };
    
    struct Gesture {
      byte id;               // Identificador único del gesto
      byte pinSequence[32];  // Secuencia de pines que conforman el gesto
      byte length;           // Longitud de la secuencia
      Action actions[32];    // Acciones asociadas al gesto
      byte actionCount;      // Número de acciones
    };
    
    // static Gesture gestures[MAX_GESTURES];
    static Gesture gestures[32];
    static byte gestureCount = 0;
    
    // === Variables de Estado ===
    static bool previousTouchState[NUM_TOUCH_PINS] = { false };
    static unsigned long lastTouchTime = 0;
    static unsigned long lastGestureTime = 0;  // Para cooldown
    
    // === Inicialización de Bluetooth, Teclado y Almacenamiento ===
    static Preferences preferences;
    static const char DEVICE_NAME[] PROGMEM = "ESP32 HID Controller";
    static const char DEVICE_MANUFACTURER[] PROGMEM = "Mystfit";
    static BleCompositeHID compositeHID(DEVICE_NAME, DEVICE_MANUFACTURER, 100);
    static KeyboardDevice* keyboard;
    
    // === Prototipos de Funciones ===
    void detectTouch();
    void checkGesture();
    void handleSerialCommands();
    bool compareSequences(const uint8_t* a, byte aLen, const uint8_t* b, byte bLen);
    void addGesture(const Gesture& newGesture);
    void deleteGesture(byte id);
    void loadGestures();
    void saveGestures();
    void clearBuffer();
    void appendToBuffer(byte pin);
    unsigned int generateID();
    byte getHIDCode(const String& action);
    bool needsShift(char c);
    char getBaseChar(char c);
    void logMessage(const String& message);
    void listGestures();
    
    // === Mapa para Convertir Acciones en Códigos HID ===
    struct HIDPair {
      const char* key;
      byte value;
    };
    
    static 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 },
      { "CALCULATOR", KEY_MEDIA_CALCULATOR },
      { "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 }
    };
    static 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("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 (byte i = 0; i < NUM_TOUCH_PINS; i++) {
        byte 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
    
      loadGestures();  // Carga los gestos almacenados
      logMessage("Sistema listo. Esperando gestos...");
    }
    
    // === Bucle Principal ===
    void loop() {
      detectTouch();  // Detecta toques en los pines táctiles
    
      unsigned long currentTime = millis();
      // Si hubo actividad, 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 (byte i = 0; i < NUM_TOUCH_PINS; i++) {
        byte pin;
        memcpy_P(&pin, &TOUCH_PINS[i], sizeof(pin));
        byte touchValue = touchRead(pin);
        byte threshold;
        memcpy_P(&threshold, &TOUCH_THRESHOLDS[i], sizeof(threshold));
        bool isTouched = touchValue < threshold;
    
        // Detecta cambios en el estado del pin (from not touched to touched)
        if (isTouched && !previousTouchState[i]) {
          appendToBuffer(pin);          // Agrega el pin al buffer si se toca
          lastTouchTime = currentTime;  // Actualiza el tiempo del último toque
        }
    
        // Actualiza el estado previo
        previousTouchState[i] = isTouched;
      }
    
      // 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(byte pin) {
      logMessage("Pin " + String(pin) + " añadido al buffer.");
    
      if (bufferSize < 255) {
        touchBuffer[(bufferStart + bufferSize) % 255] = pin;
        bufferSize++;
      } else {
        // Si el buffer está lleno, reemplaza el pin más antiguo
        bufferStart = (bufferStart + 1) % 255;
        touchBuffer[(bufferStart + bufferSize - 1) % 255] = pin;
        logMessage("Buffer lleno, reemplazando el pin más antiguo.");
      }
    }
    
    // === Limpia el Buffer Táctil ===
    void clearBuffer() {
      bufferStart = 0;
      bufferSize = 0;
      logMessage("Buffer limpiado por inactividad.");
    }
    
    // === Compara Dos Secuencias de Pines ===
    bool compareSequences(const uint8_t* a, byte aLen, const uint8_t* b, byte bLen) {
      if (aLen < bLen) {
        logMessage("Secuencia detectada es más corta que la secuencia del gesto.");
        return false;
      }
    
      // Compara las últimas bLen entradas de 'a' con 'b'
      for (byte i = 0; i < bLen; i++) {
        if (a[aLen - bLen + i] != b[i]) {
          return false;
        }
      }
      return true;
    }
    
    // === Verifica si el Buffer Coincide con Algún Gesto Almacenado ===
    void checkGesture() {
      if (gestureCount == 0) {
        logMessage("No hay gestos almacenados para verificar.");
        return;
      }
    
      bool gestureFound = false;
    
      for (byte i = 0; i < gestureCount; ++i) {
        if (compareSequences(touchBuffer, bufferSize, gestures[i].pinSequence, gestures[i].length)) {
          logMessage("Gesto detectado: ID " + String(gestures[i].id));
    
          if (!compositeHID.isConnected()) {
            logMessage("BleKeyboard no está conectado.");
            continue;
          }
    
          if (keyboard == nullptr) {
            logMessage("El objeto keyboard no está inicializado.");
            continue;
          }
    
          // Ejecuta todas las acciones asociadas al gesto
          for (byte a = 0; a < gestures[i].actionCount; a++) {
            Action action = gestures[i].actions[a];
            switch (action.type) {
              case 0:  // Tecla normal
                keyboard->keyPress(action.parameter);
                logMessage("Enviar tecla HID code: " + String(action.parameter));
                keyboard->keyRelease(action.parameter);
                break;
              case 1:  // Media key
                keyboard->mediaKeyPress(action.parameter);
                logMessage("Enviar Media Key HID code: " + String(action.parameter));
                keyboard->mediaKeyRelease(action.parameter);
                break;
              case 2:  // Modificador (presionar)
                keyboard->modifierKeyPress(action.parameter);
                logMessage("Presionar modificador HID code: " + String(action.parameter));
                break;
              case 3:  // Modificador (soltar)
                keyboard->modifierKeyRelease(action.parameter);
                logMessage("Liberar modificador HID code: " + String(action.parameter));
                break;
              case 4:  // Enviar texto
                for (char c : action.text) {
                  bool shift_needed = needsShift(c);
    
                  if (shift_needed) {
                    keyboard->modifierKeyPress(KEY_LEFTSHIFT);
                  }
    
                  char baseChar = getBaseChar(c);
                  String keyStr = String(baseChar);
                  byte key = getHIDCode(keyStr);
    
                  if (key != 0) {
                    keyboard->keyPress(key);
                    logMessage("Enviar tecla de texto: " + String(c));
                    keyboard->keyRelease(key);
                    delay(50);  // Pausa para evitar inundación de eventos
                  } else {
                    logMessage("Caracter no soportado: " + String(c));
                  }
    
                  if (shift_needed) {
                    keyboard->modifierKeyRelease(KEY_LEFTSHIFT);
                  }
                }
                break;
              default:
                logMessage("Tipo de acción desconocido: " + String(action.type));
                break;
            }
          }
    
          gestureFound = true;
          break;  // Sale del bucle al encontrar un gesto
        }
      }
    
      if (gestureFound) {
        logMessage("Gesto ejecutado correctamente.");
      } else {
        logMessage("No se encontró un gesto que coincida con la secuencia detectada.");
      }
    }
    
    // === Maneja Comandos Recibidos por el Puerto Serie ===
    void handleSerialCommands() {
      while (Serial.available()) {  // Maneja múltiples comandos a la vez
          String command = Serial.readStringUntil('\n');
          command.trim();
          logMessage("Comando recibido: " + command);
    
          if (command.startsWith("ADD")) {
              // Formato esperado: ADD <secuencia_pines>|<acciones>
              int delimiter = command.indexOf('|');
              if (delimiter == -1) {
                  logMessage("Formato ADD incorrecto. Falta '|'.");
                  return;
              }
    
              String sequenceStr = command.substring(4, delimiter);
              String actionsStr = command.substring(delimiter + 1);
              sequenceStr.trim();
              actionsStr.trim();
    
              Gesture newGesture;
              newGesture.id = generateID();
              newGesture.length = 0;
              newGesture.actionCount = 0;
    
              // Procesar secuencia de pines
              int start = 0;
              while (start < sequenceStr.length()) {
                  int space = sequenceStr.indexOf(' ', start);
                  String pinStr = (space == -1) ? sequenceStr.substring(start) : sequenceStr.substring(start, space);
                  pinStr.trim();
    
                  // Verificar si pinStr es un número válido
                  bool isNumber = true;
                  for (char c : pinStr) {
                      if (!isDigit(c)) {
                          isNumber = false;
                          break;
                      }
                  }
    
                  if (isNumber) {
                      byte pin = pinStr.toInt();
                      bool validPin = false;
                      for (byte j = 0; j < NUM_TOUCH_PINS; j++) {
                          byte touchPin;
                          memcpy_P(&touchPin, &TOUCH_PINS[j], sizeof(touchPin));
                          if (pin == touchPin) {
                              newGesture.pinSequence[newGesture.length++] = pin;
                              validPin = true;
                              break;
                          }
                      }
                      if (!validPin) {
                          logMessage("Pin inválido en secuencia: " + pinStr);
                      }
                  } else {
                      logMessage("Formato de pin inválido: " + pinStr);
                  }
    
                  if (space == -1) break;
                  start = space + 1;
              }
    
              if (newGesture.length == 0) {
                  logMessage("No se añadió ningún pin válido al gesto.");
                  return;
              }
    
              // Procesar acciones
              start = 0;
              while (start < actionsStr.length()) {
                  int space = actionsStr.indexOf(' ', start);
                  String actionStr = (space == -1) ? actionsStr.substring(start) : actionsStr.substring(start, space);
                  actionStr.trim();
    
                  byte hidCode = getHIDCode(actionStr);
                  if (hidCode != 0) {
                      // Verificar explícitamente si es un Media Key
                      bool isMediaKey = false;
                      for (size_t k = 0; k < HIDMapSize; k++) {
                          HIDPair pair;
                          memcpy_P(&pair, &HIDMap[k], sizeof(pair));
                          if (strcmp(actionStr.c_str(), pair.key) == 0) {
                              if (hidCode >= 0xB0 && hidCode <= 0xF6) {
                                  isMediaKey = true;
                              }
                              break;
                          }
                      }
    
                      if (isMediaKey) {
                          newGesture.actions[newGesture.actionCount++] = { 1, hidCode, "" };
                      } else if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
                          newGesture.actions[newGesture.actionCount++] = { 2, hidCode, "" };
                      } else {
                          newGesture.actions[newGesture.actionCount++] = { 0, hidCode, "" };
                      }
                  } else {
                      // Asume que es texto si no coincide con ningún código HID conocido
                      newGesture.actions[newGesture.actionCount++] = { 4, 0, actionStr };
                  }
    
                  if (space == -1) break;
                  start = space + 1;
              }
    
              if (newGesture.actionCount == 0) {
                  logMessage("No se añadieron acciones válidas al gesto.");
                  return;
              }
    
              // Añadir el nuevo gesto
              gestures[currentGestureIndex++] = newGesture;
              gestureCount++;
              saveGestures();
              logMessage("Gesto añadido exitosamente. ID: " + String(newGesture.id));
    
          } else if (command.startsWith("DEL")) {
              // Formato esperado: DEL <ID>
              String idStr = command.substring(4);
              idStr.trim();
              if (idStr.length() == 0) {
                  logMessage("Formato DEL incorrecto. Falta ID.");
                  return;
              }
              unsigned long id = idStr.toInt();
              bool found = false;
              for (byte i = 0; i < gestureCount; ++i) {
                  if (gestures[i].id == id) {
                      for (byte j = i; j < gestureCount - 1; ++j) {
                          gestures[j] = gestures[j + 1];
                      }
                      gestureCount--;
                      saveGestures();
                      logMessage("Gesto con ID " + String(id) + " eliminado exitosamente.");
                      found = true;
                      break;
                  }
              }
              if (!found) {
                  logMessage("Gesto con ID " + String(id) + " no encontrado.");
              }
    
          } else if (command.equalsIgnoreCase("LIST")) {
              // Lista todos los gestos almacenados
              listGestures();
    
          } else if (command.equalsIgnoreCase("TEST")) {
              // Comando de prueba para verificar la memoria disponible
              logMessage("Memoria libre: " + String(ESP.getFreeHeap()) + " bytes");
    
          } else {
              logMessage("Comando desconocido: " + command);
          }
      }
    }
    
    // === Añade un Gesto a la Lista ===
    void addGesture(const Gesture& newGesture) {
      gestures[gestureCount++] = newGesture;
      saveGestures();
      logMessage("Gesto añadido. ID: " + String(newGesture.id));
    }
    
    // === Elimina un Gesto por ID ===
    void deleteGesture(byte id) {
      for (byte i = 0; i < gestureCount; ++i) {
        if (gestures[i].id == id) {
          gestures[i] = gestures[gestureCount - 1];  // Reemplaza con el último gesto
          gestureCount--;
          saveGestures();
          logMessage("Gesto con ID " + String(id) + " eliminado exitosamente.");
          return;
        }
      }
      logMessage("Gesto con ID " + String(id) + " no encontrado.");
    }
    
    // === Carga los Gestos Almacenados desde las Preferencias ===
    void loadGestures() {
      gestureCount = 0;
    
      while (true) {
        String idKey = "g" + String(gestureCount) + "_id";
        if (!preferences.isKey(idKey.c_str())) break;
    
        unsigned long id = preferences.getUInt(idKey.c_str(), 0);
        if (id == 0) break;
    
        Gesture gesture;
        gesture.id = id;
    
        // Cargar secuencia de pines
        String seqKey = "g" + String(gestureCount) + "_seq";
        String sequenceStr = preferences.getString(seqKey.c_str(), "");
        gesture.length = 0;
        int start = 0;
        int comma = sequenceStr.indexOf(',', start);
        while (comma != -1) {
          String pinStr = sequenceStr.substring(start, comma);
          pinStr.trim();
          byte pin = pinStr.toInt();
          gesture.pinSequence[gesture.length++] = pin;
          start = comma + 1;
          comma = sequenceStr.indexOf(',', start);
        }
        // Añadir el último pin después de la última coma
        if (start < sequenceStr.length()) {
          String pinStr = sequenceStr.substring(start);
          pinStr.trim();
          byte pin = pinStr.toInt();
          gesture.pinSequence[gesture.length++] = pin;
        }
    
        // Cargar acciones
        String actKey = "g" + String(gestureCount) + "_acts";
        String actionsStr = preferences.getString(actKey.c_str(), "");
        gesture.actionCount = 0;
        start = 0;
        comma = actionsStr.indexOf(';', start);
        while (comma != -1) {
          String actionStr = actionsStr.substring(start, comma);
          actionStr.trim();
          byte hidCode = getHIDCode(actionStr);
    
          if (hidCode != 0) {
            // Verificar explícitamente si es un Media Key
            bool isMediaKey = false;
            for (size_t k = 0; k < HIDMapSize; k++) {
              HIDPair pair;
              memcpy_P(&pair, &HIDMap[k], sizeof(pair));
              if (actionStr.equalsIgnoreCase(String(pair.key))) {
                if (hidCode >= 0xB0 && hidCode <= 0xF6) {
                  isMediaKey = true;
                }
                break;
              }
            }
    
            if (isMediaKey) {
              gesture.actions[gesture.actionCount++] = {1, hidCode, ""};
            } 
            else if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
              gesture.actions[gesture.actionCount++] = {2, hidCode, ""};
            } 
            else {
              gesture.actions[gesture.actionCount++] = {0, hidCode, ""};
            }
          } 
          else {
            // Asume que es texto si no coincide con ningún código HID conocido
            gesture.actions[gesture.actionCount++] = {4, 0, actionStr};
          }
    
          start = comma + 1;
          comma = actionsStr.indexOf(';', start);
        }
        // Añadir la última acción después de la última coma
        if (start < actionsStr.length()) {
          String actionStr = actionsStr.substring(start);
          actionStr.trim();
          byte hidCode = getHIDCode(actionStr);
    
          if (hidCode != 0) {
            // Verificar explícitamente si es un Media Key
            bool isMediaKey = false;
            for (size_t k = 0; k < HIDMapSize; k++) {
              HIDPair pair;
              memcpy_P(&pair, &HIDMap[k], sizeof(pair));
              if (actionStr.equalsIgnoreCase(String(pair.key))) {
                if (hidCode >= 0xB0 && hidCode <= 0xF6) {
                  isMediaKey = true;
                }
                break;
              }
            }
    
            if (isMediaKey) {
              gesture.actions[gesture.actionCount++] = {1, hidCode, ""};
            } 
            else if (hidCode == KEY_LEFTCTRL || hidCode == KEY_LEFTSHIFT || hidCode == KEY_LEFTALT || hidCode == KEY_LEFTGUI) {
              gesture.actions[gesture.actionCount++] = {2, hidCode, ""};
            } 
            else {
              gesture.actions[gesture.actionCount++] = {0, hidCode, ""};
            }
          } 
          else {
            // Asume que es texto si no coincide con ningún código HID conocido
            gesture.actions[gesture.actionCount++] = {4, 0, actionStr};
          }
        }
    
        gestures[gestureCount++] = gesture;
      }
    
      logMessage("Gestos cargados: " + String(gestureCount));
    }
    
    // === Guarda los Gestos Actuales en las Preferencias ===
    void saveGestures() {
      preferences.begin("gestures", false);  // Inicia las preferencias sin modo de solo lectura
      preferences.clear();                   // Limpia las preferencias antes de guardar
    
      for (byte i = 0; i < gestureCount; ++i) {
        // Guardar ID del gesto
        String idKey = "g" + String(i) + "_id";
        preferences.putUInt(idKey.c_str(), gestures[i].id);
    
        // Guardar secuencia de pines
        String seqKey = "g" + String(i) + "_seq";
        String sequenceStr;
        for (byte j = 0; j < gestures[i].length; j++) {
          if (j > 0) sequenceStr += ",";
          sequenceStr += String(gestures[i].pinSequence[j]);
        }
        preferences.putString(seqKey.c_str(), sequenceStr);
    
        // Guardar acciones
        String actKey = "g" + String(i) + "_acts";
        String actionsStr;
        for (byte a = 0; a < gestures[i].actionCount; a++) {
          if (a > 0) actionsStr += ";";
          if (gestures[i].actions[a].type == 4) {
            // Acción de texto
            actionsStr += gestures[i].actions[a].text;
          } else {
            actionsStr += String(gestures[i].actions[a].parameter);
          }
        }
        preferences.putString(actKey.c_str(), actionsStr);
      }
    
      logMessage("Gestos guardados en preferencias.");
      preferences.end(); // Finaliza el uso de las preferencias
    }
    
    // === Genera un ID Único para un Nuevo Gesto ===
    unsigned int generateID() {
      // Busca el primer ID libre en el rango 1 a 255
      for (unsigned int id = 1; id <= 255; id++) {
        bool exists = false;
        for (byte i = 0; i < gestureCount; i++) {
          if (gestures[i].id == id) {
            exists = true;
            break;
          }
        }
        if (!exists) return id;
      }
    
      logMessage("No se encontró un ID disponible.");
      return 0;  // Retorna 0 si no hay IDs disponibles
    }
    
    // === Función para Convertir Acciones en Códigos HID ===
    byte getHIDCode(const String& action) {
      // Crear una copia mutable de la cadena para modificarla
      String capAction = action;
      capAction.toUpperCase();
    
      for (size_t i = 0; i < HIDMapSize; i++) {
        HIDPair pair;
        memcpy_P(&pair, &HIDMap[i], sizeof(pair));
        if (capAction.equalsIgnoreCase(String(pair.key))) {
          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 = "!@#$%^&*()_+{}|:\"<>?~[]\\;',./`-=";
      return strchr(symbolsRequiringShift, c) != NULL;
    }
    
    // === Función de Ayuda: Obtiene el carácter base sin Shift ===
    char getBaseChar(char c) {
      // Si el carácter es mayúscula o símbolo que requiere Shift, retorna el carácter base
      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 ===
    void logMessage(const String& message) {
      Serial.println(F("[LOG] ") + message);
    }
    
    // === Lista Todos los Gestos Almacenados ===
    void listGestures() {
      if (gestureCount == 0) {
        logMessage("No hay gestos almacenados.");
        return;
      }
    
      Serial.println(F("=== Lista de Gestos ==="));
      for (byte i = 0; i < gestureCount; i++) {
        Serial.print(F("ID: "));
        Serial.print(gestures[i].id);
        Serial.print(F(" | Secuencia: "));
    
        for (byte j = 0; j < gestures[i].length; j++) {
          Serial.print(gestures[i].pinSequence[j]);
          if (j < gestures[i].length - 1) {
            Serial.print(F(" -> "));
          }
        }
    
        Serial.print(F(" | Acciones: "));
        for (byte a = 0; a < gestures[i].actionCount; a++) {
          String actionType;
          switch (gestures[i].actions[a].type) {
            case 0: actionType = "Tecla"; break;
            case 1: actionType = "Media Key"; break;
            case 2: actionType = "Modificador (Presionar)"; break;
            case 3: actionType = "Modificador (Soltar)"; break;
            case 4: actionType = "Texto"; break;
            default: actionType = "Desconocido"; break;
          }
          if (gestures[i].actions[a].type != 4) {
            Serial.print(actionType + "(" + String(gestures[i].actions[a].parameter) + ")");
          } else {
            Serial.print(actionType + "(" + gestures[i].actions[a].text + ")");
          }
          if (a < gestures[i].actionCount - 1) {
            Serial.print(F(", "));
          }
        }
        Serial.println();  // Nueva línea al final de cada gesto
      }
    }