Estoy buscando una revisión exhaustiva y una mejora completa de mi código desarrollado…
- User
**Estoy buscando una revisión exhaustiva y una mejora completa de mi código desarrollado para un ESP32 utilizando el Arduino IDE. Mi objetivo es llevar el código a un nivel profesional y más allá, alcanzando una eficiencia y calidad superiores. Deseo optimizar cada aspecto del desarrollo, asegurándome de que se implementen todas las mejores prácticas modernas de la industria específicas para trabajar con microcontroladores, especialmente el ESP32.
Esto incluye, pero no se limita a, la correcta estructuración del código, la modularización y documentación detallada, el uso eficiente de los recursos del ESP32, y la aplicación de patrones de diseño adecuados para sistemas embebidos. Quiero que el código sea escalable, mantenible y fácilmente comprensible para cualquier desarrollador que trabaje con el ESP32 y el Arduino IDE.
Estoy interesado en realizar una revisión profunda que considere la legibilidad del código, la eliminación de redundancias, la mejora del rendimiento y la seguridad en el contexto de dispositivos IoT y integraciones con hardware. No deseo dejar ningún detalle sin pulir.
Busco sugerencias de mejoras específicas y soluciones innovadoras adaptadas al entorno del ESP32 que puedan ser aplicadas para refinar aún más el código, asegurándome de aprovechar las últimas capacidades y técnicas disponibles para este microcontrolador. Mi meta es que el código no solo cumpla con los estándares profesionales actuales, sino que lo supere, preparándose para futuras necesidades tecnológicas y desafíos potenciales.
Estoy abierto a recibir críticas constructivas y recomendaciones detalladas que me permitan transformar mi código en un modelo de excelencia en la programación para sistemas embebidos con el ESP32. debes tener en cuenta que una de las limitaciones que tengo a la hora de codificar en arduino, es utilizar un unico fichero.**
MI CODIGO ACTUAL:
// ======================== // Proyecto ESP32 HID 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 // ======================== // Prefijos para evitar conflictos const uint8_t MY_KEY_LEFTGUI PROGMEM = 0xE3; const uint8_t MY_KEY_RIGHTGUI PROGMEM = 0xE7; const uint8_t MY_KEY_MEDIA_PLAYPAUSE PROGMEM = 0xE8; const uint8_t MY_KEY_MEDIA_STOP PROGMEM = 0xEA; const uint8_t MY_KEY_MEDIA_NEXTTRACK PROGMEM = 0xB0; const uint8_t MY_KEY_MEDIA_PREVIOUSTRACK PROGMEM = 0xB1; const uint8_t MY_KEY_MEDIA_VOLUMEDOWN PROGMEM = 0xB2; const uint8_t MY_KEY_MEDIA_VOLUMEUP PROGMEM = 0xB3; const uint8_t MY_KEY_MEDIA_MUTE PROGMEM = 0xE2; const uint8_t MY_KEY_MEDIA_WWWHOME PROGMEM = 0xB5; const uint8_t MY_KEY_MEDIA_EMAIL_READER PROGMEM = 0xF0; const uint8_t MY_KEY_MEDIA_LOCAL_MACHINE_BROWSER PROGMEM = 0xF1; const uint8_t MY_KEY_MEDIA_WWW_BOOKMARKS PROGMEM = 0xF2; const uint8_t MY_KEY_MEDIA_WWW_SEARCH PROGMEM = 0xF3; const uint8_t MY_KEY_MEDIA_WWW_STOP PROGMEM = 0xF4; const uint8_t MY_KEY_MEDIA_WWW_BACK PROGMEM = 0xF5; const uint8_t MY_KEY_MEDIA_CONSUMER_CONTROL_CONFIGURATION PROGMEM = 0xF6; // 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", MY_KEY_LEFTGUI}, // Usando prefijo // Media Keys {"PLAYPAUSE", MY_KEY_MEDIA_PLAYPAUSE}, {"STOP", MY_KEY_MEDIA_STOP}, {"NEXTTRACK", MY_KEY_MEDIA_NEXTTRACK}, {"PREVIOUSTRACK", MY_KEY_MEDIA_PREVIOUSTRACK}, {"VOLUMEDOWN", MY_KEY_MEDIA_VOLUMEDOWN}, {"VOLUMEUP", MY_KEY_MEDIA_VOLUMEUP}, {"MUTE", MY_KEY_MEDIA_MUTE}, {"WWWHOME", MY_KEY_MEDIA_WWWHOME}, {"EMAILREADER", MY_KEY_MEDIA_EMAIL_READER}, {"LOCALMACHINE", MY_KEY_MEDIA_LOCAL_MACHINE_BROWSER}, {"WWWBOOKMARKS", MY_KEY_MEDIA_WWW_BOOKMARKS}, {"WWWSEARCH", MY_KEY_MEDIA_WWW_SEARCH}, {"WWWSTOP", MY_KEY_MEDIA_WWW_STOP}, {"WWWBACK", MY_KEY_MEDIA_WWW_BACK}, {"CONSUMERCONFIGURATION", MY_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 // ======================== 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(char action); // Cambiado para aceptar un solo char bool needsShift(char c); char getBaseChar(char c); void logMessage(const __FlashStringHelper* message); void logMessage(const char* message); void listGestures(); void executeGestureActions(const Gesture& gesture); void sendText(const char* text); void appendToBuffer(uint8_t pin); void clearBuffer(); // ======================== // 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 if (!compositeHID.addDevice(keyboard)) { logMessage(F("Error al añadir el dispositivo de teclado.")); while (1); // Bloquear el programa si ocurre un error crítico } 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); // Indicar que la configuración ha finalizado digitalWrite(LED_BUILTIN, HIGH); delay(1000); // Mantener el LED encendido por 1 segundo digitalWrite(LED_BUILTIN, LOW); 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 == MY_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; } // Validaciones adicionales if (gesture->length == 0) { logMessage(F("Secuencia de pines inválida.")); return false; } if (gesture->actionCount == 0) { logMessage(F("No se cargaron acciones para el gesto.")); return false; } return true; } 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) { 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 = pgm_read_byte(&TOUCH_PINS[j]); if (pin == touchPin) { newGesture.pinSequence[newGesture.length++] = pin; validPin = true; break; } } if (!validPin) { // Pin inválido, ignorar logMessage(F("Pin inválido ignorado en la secuencia.")); } 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); // Cambiado para pasar un solo char 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[0], pair.key) == 0) { // Corregido para comparar cadenas completas if (pair.value >= 0xB0 && pair.value <= 0xF6) { isMediaKey = true; } if (pair.value == KEY_LEFTCTRL || pair.value == KEY_LEFTSHIFT || pair.value == KEY_LEFTALT || pair.value == MY_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); 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); 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); } else { logMessage(F("Comando desconocido.")); } } } 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(char action) { char charStr[2] = {action, '\0'}; // Construir una cadena de un solo carácter for (size_t i = 0; i < HIDMapSize; i++) { HIDPair pair; memcpy_P(&pair, &HIDMap[i], sizeof(pair)); if (strcasecmp(charStr, 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 } } void sendText(const char* text) { for (int c = 0; 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); // Cambiado a pasar un solo char if (key != 0) { keyboard->keyPress(key); keyboard->keyRelease(key); } if (shift_needed) { keyboard->modifierKeyRelease(KEY_LEFTSHIFT); } } } - Assistant