#include "Display.h"
#include "Screens.h"
#include "Tasks.h"
#include "Calendar.h"
#include <WiFi.h>
#include "Chronometer.h"
// Pines
const int btnGreen = 40;
const int btnRed = 39;
const int ledPin = 48;
const int TFT_BL = 45;
// Objetos
Display display;
ScreenManager screens;
TaskManager taskManager;
CalendarManager calendarManager;
Chronometer chronometer;
// Botones
bool lastGreenState = HIGH;
bool lastRedState = HIGH;
unsigned long lastButtonTime = 0;
const unsigned long DEBOUNCE_TIME = 180;
// Monitor serie
String serialCommand = "";
// Asistente guiado para crear eventos de calendario.
enum EventCreationStep {
EVENT_NONE,
EVENT_TITLE,
EVENT_DATE,
EVENT_START,
EVENT_END,
EVENT_CONFIRM
};
EventCreationStep eventCreationStep = EVENT_NONE;
enum PomodoroSetupStep {
POMODORO_SETUP_NONE,
POMODORO_SETUP_WORK,
POMODORO_SETUP_SHORT_BREAK,
POMODORO_SETUP_LONG_BREAK,
POMODORO_SETUP_SESSIONS
};
PomodoroSetupStep pomodoroSetupStep = POMODORO_SETUP_NONE;
int pendingPomodoroWorkMinutes = 0;
int pendingPomodoroShortBreakMinutes = 0;
int pendingPomodoroLongBreakMinutes = 0;
String newEventTitle;
String newEventDate;
String newEventStart;
String newEventEnd;
// --------------------------------------------------
// VOZ SIMULADA
// --------------------------------------------------
void sayPrompt(const String& message) {
AppScreen current = screens.getCurrentScreen();
bool timeScreenVisible =
current == AppScreen::STOPWATCH ||
current == AppScreen::TIMER ||
current == AppScreen::POMODORO;
if (!timeScreenVisible) {
display.showEyes(XiaoZhiState::SPEAKING);
}
Serial.print("[XIAOZHI HABLARIA] ");
Serial.println(message);
if (!timeScreenVisible) {
display.showEyes(XiaoZhiState::LISTENING);
}
if (current == AppScreen::STOPWATCH) {
display.showStopwatch(
chronometer.getStopwatchElapsed(),
chronometer.isStopwatchRunning()
);
}
else if (current == AppScreen::TIMER) {
display.showTimer(
chronometer.getTimerRemaining(),
chronometer.getTimerDuration(),
chronometer.isTimerRunning(),
chronometer.isTimerPaused(),
chronometer.isTimerFinished()
);
}
else if (current == AppScreen::POMODORO) {
display.showPomodoro(
chronometer.getPomodoroRemaining(),
chronometer.getPomodoroDuration(),
chronometer.getPomodoroPhaseName(),
chronometer.getCurrentSession(),
chronometer.getSessionsBeforeLongBreak(),
chronometer.isPomodoroRunning(),
chronometer.isPomodoroPaused(),
chronometer.isPomodoroFinished()
);
}
}
void showTimeScreenIfNeeded(AppScreen screen) {
if (screens.getCurrentScreen() != screen) {
screens.show(screen);
}
}
// --------------------------------------------------
// NORMALIZAR TEXTO
// --------------------------------------------------
String normalizeSpokenText(String value) {
value.trim();
value.toLowerCase();
value.replace("á", "a");
value.replace("é", "e");
value.replace("í", "i");
value.replace("ó", "o");
value.replace("ú", "u");
value.replace("ü", "u");
value.replace("ñ", "n");
while (value.indexOf(" ") >= 0) {
value.replace(" ", " ");
}
return value;
}
// --------------------------------------------------
// CONVERTIR NÚMEROS EN ESPAÑOL
// --------------------------------------------------
int spanishNumber(String value) {
value = normalizeSpokenText(value);
value.trim();
if (!value.length()) return -1;
bool digits = true;
for (unsigned int i = 0; i < value.length(); ++i) {
if (!isDigit(value[i]) && value[i] != ' ') {
digits = false;
break;
}
}
if (digits) return value.toInt();
value.replace(" y ", " ");
const char* names[] = {
"cero", "uno", "una", "un", "primero",
"dos", "tres", "cuatro", "cinco",
"seis", "siete", "ocho", "nueve",
"diez", "once", "doce", "trece",
"catorce", "quince", "dieciseis",
"diecisiete", "dieciocho", "diecinueve",
"veinte", "veintiuno", "veintiun",
"veintidos", "veintitres", "veinticuatro",
"veinticinco", "veintiseis", "veintisiete",
"veintiocho", "veintinueve",
"treinta", "cuarenta", "cincuenta",
"sesenta", "setenta", "ochenta", "noventa"
};
const int vals[] = {
0, 1, 1, 1, 1,
2, 3, 4, 5,
6, 7, 8, 9,
10, 11, 12, 13,
14, 15, 16,
17, 18, 19,
20, 21, 21,
22, 23, 24,
25, 26, 27,
28, 29,
30, 40, 50,
60, 70, 80, 90
};
int total = 0;
int tokenStart = 0;
while (tokenStart < (int)value.length()) {
int tokenEnd = value.indexOf(' ', tokenStart);
if (tokenEnd < 0) {
tokenEnd = value.length();
}
String token = value.substring(tokenStart, tokenEnd);
int found = -1;
for (unsigned int i = 0; i < sizeof(vals) / sizeof(vals[0]); ++i) {
if (token == names[i]) {
found = vals[i];
break;
}
}
if (found < 0) return -1;
total += found;
tokenStart = tokenEnd + 1;
}
return total;
}
// --------------------------------------------------
// CONVERTIR DURACIONES HABLADAS A MINUTOS
// --------------------------------------------------
int parseDurationMinutes(String input) {
input = normalizeSpokenText(input);
input.trim();
// Ejemplo: hora y media.
if (input.indexOf("hora y media") >= 0) {
int hourPosition = input.indexOf("hora");
String prefix = input.substring(0, hourPosition);
prefix.trim();
// Elimina expresiones introductorias.
int lastSpace = prefix.lastIndexOf(' ');
if (lastSpace >= 0) {
prefix = prefix.substring(lastSpace + 1);
}
int hours = prefix.length() ? spanishNumber(prefix) : 1;
if (hours < 1) hours = 1;
return hours * 60 + 30;
}
int hourPosition = input.indexOf(" hora");
if (hourPosition >= 0) {
String numberText = input.substring(0, hourPosition);
int lastSpace = numberText.lastIndexOf(' ');
if (lastSpace >= 0) {
numberText = numberText.substring(lastSpace + 1);
}
int hours = spanishNumber(numberText);
if (hours < 1) return -1;
return hours * 60;
}
int minutePosition = input.indexOf(" minuto");
if (minutePosition >= 0) {
String numberText = input.substring(0, minutePosition);
int lastSpace = numberText.lastIndexOf(' ');
if (lastSpace >= 0) {
numberText = numberText.substring(lastSpace + 1);
}
return spanishNumber(numberText);
}
// También acepta simplemente "30".
return spanishNumber(input);
}
bool handlePomodoroSetupInput(const String& input) {
if (
input == "cancelar" ||
input == "cancela" ||
input == "cancelar pomodoro" ||
input == "cancela pomodoro"
) {
pomodoroSetupStep = POMODORO_SETUP_NONE;
sayPrompt("He cancelado la configuración del Pomodoro.");
return true;
}
switch (pomodoroSetupStep) {
case POMODORO_SETUP_WORK: {
int minutes = parseDurationMinutes(input);
if (minutes < 1 || minutes > 240) {
sayPrompt(
"No he entendido el tiempo. Dime la duración de la concentración en minutos."
);
return true;
}
pendingPomodoroWorkMinutes = minutes;
pomodoroSetupStep = POMODORO_SETUP_SHORT_BREAK;
sayPrompt("¿Cuánto quieres que dure el descanso corto?");
return true;
}
case POMODORO_SETUP_SHORT_BREAK: {
int minutes = parseDurationMinutes(input);
if (minutes < 1 || minutes > 120) {
sayPrompt(
"No he entendido el tiempo. Dime la duración del descanso corto en minutos."
);
return true;
}
pendingPomodoroShortBreakMinutes = minutes;
pomodoroSetupStep = POMODORO_SETUP_LONG_BREAK;
sayPrompt("¿Cuánto quieres que dure el descanso largo?");
return true;
}
case POMODORO_SETUP_LONG_BREAK: {
int minutes = parseDurationMinutes(input);
if (minutes < 1 || minutes > 180) {
sayPrompt(
"No he entendido el tiempo. Dime la duración del descanso largo en minutos."
);
return true;
}
pendingPomodoroLongBreakMinutes = minutes;
pomodoroSetupStep = POMODORO_SETUP_SESSIONS;
sayPrompt(
"¿Cuántos ciclos de concentración quieres completar antes del descanso largo final?"
);
return true;
}
case POMODORO_SETUP_SESSIONS: {
String numberText = input;
numberText.trim();
if (numberText.startsWith("quiero ")) {
numberText = numberText.substring(7);
numberText.trim();
}
while (
numberText.endsWith(".") ||
numberText.endsWith(",") ||
numberText.endsWith("?") ||
numberText.endsWith("!")
) {
numberText.remove(numberText.length() - 1);
numberText.trim();
}
const char* suffixes[] = {
" sesiones", " sesion", " ciclos", " ciclo"
};
for (
unsigned int i = 0;
i < sizeof(suffixes) / sizeof(suffixes[0]);
++i
) {
if (numberText.endsWith(suffixes[i])) {
numberText.remove(
numberText.length() - String(suffixes[i]).length()
);
numberText.trim();
break;
}
}
int sessions = spanishNumber(numberText);
if (sessions < 1 || sessions > 12) {
sayPrompt(
"Elige entre uno y doce ciclos de concentración."
);
return true;
}
chronometer.setWorkMinutes(pendingPomodoroWorkMinutes);
chronometer.setShortBreakMinutes(
pendingPomodoroShortBreakMinutes
);
chronometer.setLongBreakMinutes(
pendingPomodoroLongBreakMinutes
);
chronometer.setSessionsBeforeLongBreak(sessions);
pomodoroSetupStep = POMODORO_SETUP_NONE;
sayPrompt(
"Configuración guardada. Concentración: " +
String(chronometer.getWorkMinutes()) +
" minutos; descanso corto: " +
String(chronometer.getShortBreakMinutes()) +
" minutos; descanso largo: " +
String(chronometer.getLongBreakMinutes()) +
" minutos; ciclos de concentración: " +
String(chronometer.getSessionsBeforeLongBreak()) +
". Al terminar el descanso largo, el Pomodoro finalizará."
);
return true;
}
case POMODORO_SETUP_NONE:
default:
return false;
}
}
// --------------------------------------------------
// DETECTAR PETICION DE LOS PROXIMOS X DIAS
// --------------------------------------------------
bool parseNextDaysRequest(
const String& normalized,
int& days
) {
int position = normalized.indexOf("proximos ");
if (position < 0) {
return false;
}
// Extraer el texto que aparece después de "proximos ".
String numberText = normalized.substring(position + 9);
// Localizar la palabra día/días.
int unitPosition = numberText.indexOf(" dia");
if (unitPosition >= 0) {
numberText = numberText.substring(0, unitPosition);
}
numberText.trim();
// Eliminar puntuación final por si viene de reconocimiento de voz.
while (
numberText.endsWith(".") ||
numberText.endsWith(",") ||
numberText.endsWith("?") ||
numberText.endsWith("!")
) {
numberText.remove(numberText.length() - 1);
numberText.trim();
}
days = spanishNumber(numberText);
if (days < 1 || days > 30) {
Serial.print("[AGENDA] Numero de dias no valido: ");
Serial.println(numberText);
return false;
}
Serial.print("[AGENDA] Numero de dias detectado: ");
Serial.println(days);
return true;
}
// --------------------------------------------------
// CONVERTIR AÑO
// --------------------------------------------------
int spanishYear(String value) {
value = normalizeSpokenText(value);
value.trim();
if (value.startsWith("dos mil ")) {
int rest = spanishNumber(value.substring(8));
if (rest < 0 || rest > 999) return -1;
return 2000 + rest;
}
return spanishNumber(value);
}
// --------------------------------------------------
// CONVERTIR MES
// --------------------------------------------------
int spanishMonth(String value) {
value = normalizeSpokenText(value);
if (value == "setiembre") return 9;
const char* months[] = {
"enero", "febrero", "marzo", "abril",
"mayo", "junio", "julio", "agosto",
"septiembre", "octubre", "noviembre", "diciembre"
};
for (int i = 0; i < 12; ++i) {
if (value == months[i]) return i + 1;
}
return spanishNumber(value);
}
// --------------------------------------------------
// CONVERTIR FECHA
// --------------------------------------------------
bool normalizeEventDate(String input, String& output) {
input = normalizeSpokenText(input);
if (input == "hoy" || input == "manana") {
if (!calendarManager.connectWiFi()) return false;
time_t now = time(nullptr);
struct tm info;
localtime_r(&now, &info);
if (input == "manana") {
info.tm_mday++;
}
info.tm_hour = 12;
info.tm_min = 0;
info.tm_sec = 0;
info.tm_isdst = -1;
time_t target = mktime(&info);
localtime_r(&target, &info);
char buf[11];
snprintf(
buf,
sizeof(buf),
"%04d-%02d-%02d",
info.tm_year + 1900,
info.tm_mon + 1,
info.tm_mday
);
output = buf;
return true;
}
int y = 0;
int m = 0;
int d = 0;
if (
input.length() == 10 &&
sscanf(input.c_str(), "%4d-%2d-%2d", &y, &m, &d) == 3
) {
// YYYY-MM-DD
}
else if (
input.length() == 10 &&
sscanf(input.c_str(), "%2d/%2d/%4d", &d, &m, &y) == 3
) {
// DD/MM/YYYY
}
else {
String numeric = input;
numeric.replace(" del ", " ");
numeric.replace(" de ", " ");
numeric.replace("/", " ");
numeric.replace("-", " ");
if (sscanf(numeric.c_str(), "%d %d %d", &d, &m, &y) == 3) {
// DD MM YYYY
}
else {
if (input.startsWith("el ")) {
input = input.substring(3);
}
int firstDe = input.indexOf(" de ");
int lastDe = input.lastIndexOf(" de ");
if (firstDe < 0 || lastDe <= firstDe) return false;
String dayText = input.substring(0, firstDe);
String monthText = input.substring(
firstDe + 4,
lastDe
);
String yearText = input.substring(lastDe + 4);
d = spanishNumber(dayText);
m = spanishMonth(monthText);
y = spanishYear(yearText);
}
}
if (
y < 2024 || y > 2099 ||
m < 1 || m > 12 ||
d < 1 || d > 31
) {
return false;
}
struct tm check = {};
check.tm_year = y - 1900;
check.tm_mon = m - 1;
check.tm_mday = d;
check.tm_hour = 12;
check.tm_isdst = -1;
mktime(&check);
if (
check.tm_year != y - 1900 ||
check.tm_mon != m - 1 ||
check.tm_mday != d
) {
return false;
}
char buf[11];
snprintf(
buf,
sizeof(buf),
"%04d-%02d-%02d",
y, m, d
);
output = buf;
return true;
}
// --------------------------------------------------
// VALIDAR HORA HH:MM
// --------------------------------------------------
bool validClockTime(String value) {
int h, m;
return
value.length() == 5 &&
value.charAt(2) == ':' &&
sscanf(value.c_str(), "%2d:%2d", &h, &m) == 2 &&
h >= 0 && h <= 23 &&
m >= 0 && m <= 59;
}
// --------------------------------------------------
// CONVERTIR HORA HABLADA A HH:MM
// --------------------------------------------------
bool parseSpokenTime(String input, String& output) {
input = normalizeSpokenText(input);
input.trim();
bool afternoon = false;
bool night = false;
bool morning = false;
if (
input.indexOf("de la tarde") >= 0 ||
input.indexOf("por la tarde") >= 0 ||
input.indexOf("de tarde") >= 0
) {
afternoon = true;
input.replace("de la tarde", "");
input.replace("por la tarde", "");
input.replace("de tarde", "");
}
if (
input.indexOf("de la noche") >= 0 ||
input.indexOf("por la noche") >= 0 ||
input.indexOf("de noche") >= 0
) {
night = true;
input.replace("de la noche", "");
input.replace("por la noche", "");
input.replace("de noche", "");
}
if (
input.indexOf("de la manana") >= 0 ||
input.indexOf("por la manana") >= 0 ||
input.indexOf("de manana") >= 0
) {
morning = true;
input.replace("de la manana", "");
input.replace("por la manana", "");
input.replace("de manana", "");
}
input.trim();
input.replace("a las ", "");
input.replace("a la ", "");
input.replace("las ", "");
input.trim();
int h = -1;
int m = 0;
if (input.indexOf(':') >= 0) {
if (sscanf(input.c_str(), "%d:%d", &h, &m) != 2) {
return false;
}
}
else {
int menosPos = input.indexOf(" menos ");
int yPos = input.indexOf(" y ");
if (menosPos >= 0) {
String hourText = input.substring(0, menosPos);
String minuteText = input.substring(menosPos + 7);
h = spanishNumber(hourText);
minuteText.trim();
if (h < 0) return false;
if (minuteText == "cuarto") {
h--;
m = 45;
}
else if (minuteText == "diez") {
h--;
m = 50;
}
else if (minuteText == "veinte") {
h--;
m = 40;
}
else {
int minutes = spanishNumber(minuteText);
if (minutes < 1 || minutes > 59) return false;
h--;
m = 60 - minutes;
}
}
else if (yPos >= 0) {
String hourText = input.substring(0, yPos);
String minuteText = input.substring(yPos + 3);
h = spanishNumber(hourText);
minuteText.trim();
if (h < 0) return false;
if (
minuteText == "media" ||
minuteText == "medio"
) {
m = 30;
}
else if (minuteText == "cuarto") {
m = 15;
}
else if (minuteText == "tres cuartos") {
m = 45;
}
else {
m = spanishNumber(minuteText);
if (m < 0 || m > 59) return false;
}
}
else {
int spacePos = input.indexOf(' ');
if (spacePos >= 0) {
String hourText = input.substring(0, spacePos);
String minuteText = input.substring(spacePos + 1);
h = spanishNumber(hourText);
m = spanishNumber(minuteText);
if (
h < 0 || h > 23 ||
m < 0 || m > 59
) {
return false;
}
}
else {
h = spanishNumber(input);
m = 0;
}
}
}
if (h < 0 || h > 23 || m < 0 || m > 59) {
return false;
}
if (afternoon && h >= 1 && h <= 11) {
h += 12;
}
if (night) {
if (h >= 1 && h <= 11) {
h += 12;
}
else if (h == 12) {
h = 0;
}
}
if (morning && h == 12) {
h = 12;
}
char buffer[6];
snprintf(
buffer,
sizeof(buffer),
"%02d:%02d",
h,
m
);
output = buffer;
Serial.print("[HORA] Interpretada: ");
Serial.println(output);
return true;
}
// --------------------------------------------------
// CANCELAR CREACIÓN DE EVENTO
// --------------------------------------------------
void cancelEventCreation() {
eventCreationStep = EVENT_NONE;
newEventTitle = "";
newEventDate = "";
newEventStart = "";
newEventEnd = "";
sayPrompt("He cancelado la creación del evento.");
}
// --------------------------------------------------
// PROCESAR CONVERSACIÓN DE CREACIÓN DE EVENTOS
// --------------------------------------------------
void handleEventCreationInput(
const String& raw,
const String& normalized
) {
if (
normalized == "cancelar" ||
normalized == "cancela" ||
normalized == "salir"
) {
cancelEventCreation();
return;
}
switch (eventCreationStep) {
case EVENT_TITLE:
if (!raw.length()) {
sayPrompt("Dime el título del evento.");
return;
}
newEventTitle = raw;
eventCreationStep = EVENT_DATE;
sayPrompt(
"¿Qué día será? Puedes decir once de diciembre de dos mil veintiséis, once del doce de dos mil veintiséis, o simplemente mañana."
);
break;
case EVENT_DATE:
if (!normalizeEventDate(raw, newEventDate)) {
sayPrompt(
"No he entendido la fecha. Di, por ejemplo, once de diciembre de dos mil veintiséis."
);
return;
}
eventCreationStep = EVENT_START;
sayPrompt(
"¿A qué hora empieza? Puedes decir diez y media, cuatro de la tarde o nueve treinta."
);
break;
case EVENT_START: {
String parsedTime;
if (!parseSpokenTime(raw, parsedTime)) {
sayPrompt(
"No he entendido la hora. Puedes decir cinco de la tarde, cuatro de la tarde o nueve treinta."
);
return;
}
newEventStart = parsedTime;
eventCreationStep = EVENT_END;
sayPrompt(
"Perfecto. Empieza a las " +
newEventStart +
". ¿A qué hora termina?"
);
break;
}
case EVENT_END: {
String parsedTime;
if (!parseSpokenTime(raw, parsedTime)) {
sayPrompt(
"No he entendido la hora de fin. Puedes decir once y media o cinco de la tarde."
);
return;
}
if (parsedTime <= newEventStart) {
sayPrompt(
"La hora de fin debe ser posterior a la de inicio. ¿A qué hora termina?"
);
return;
}
newEventEnd = parsedTime;
eventCreationStep = EVENT_CONFIRM;
sayPrompt(
"Voy a crear " +
newEventTitle +
" el " +
newEventDate +
", de " +
newEventStart +
" a " +
newEventEnd +
". ¿Lo confirmas? Di sí o no."
);
break;
}
case EVENT_CONFIRM:
if (
normalized == "si" ||
normalized == "sí" ||
normalized == "confirmar" ||
normalized == "correcto"
) {
display.showEyes(XiaoZhiState::THINKING);
sayPrompt(
"Estoy guardando el evento en tu calendario Casa."
);
display.showEyes(XiaoZhiState::THINKING);
bool ok = calendarManager.createEvent(
newEventTitle,
newEventDate,
newEventStart,
newEventEnd
);
sayPrompt(
ok
? "El evento se ha creado correctamente."
: "No he podido crear el evento. Revisa el monitor serie para ver el error."
);
eventCreationStep = EVENT_NONE;
newEventTitle = "";
newEventDate = "";
newEventStart = "";
newEventEnd = "";
screens.showHome();
}
else if (normalized == "no") {
cancelEventCreation();
}
else {
sayPrompt(
"Responde sí para guardar el evento o no para cancelarlo."
);
}
break;
default:
break;
}
}
// --------------------------------------------------
// PREPARAR CONSULTA DE AGENDA
// --------------------------------------------------
void prepareAgendaLoading() {
screens.show(AppScreen::AGENDA, false);
display.showEyes(XiaoZhiState::THINKING);
}
// --------------------------------------------------
// MOSTRAR AGENDA DEFINITIVA
// --------------------------------------------------
void showLoadedAgenda() {
display.showEyes(XiaoZhiState::LISTENING);
calendarManager.showAgenda();
}
// --------------------------------------------------
// ABRIR AGENDA DE UNA FECHA CONCRETA
// --------------------------------------------------
void openDateAgenda(const String& spokenDate) {
String requestedDate;
if (!normalizeEventDate(spokenDate, requestedDate)) {
sayPrompt(
"No he entendido la fecha. Dime, por ejemplo, once de diciembre de dos mil veintiséis."
);
screens.showHome();
return;
}
Serial.println(
"[AGENDA] Consultando fecha concreta: " + requestedDate
);
prepareAgendaLoading();
if (!calendarManager.fetchDate(requestedDate)) {
Serial.println("[AGENDA] No se pudo consultar esa fecha");
screens.showHome();
sayPrompt("No he podido consultar la agenda de ese día.");
return;
}
showLoadedAgenda();
calendarManager.speakAll();
}
// --------------------------------------------------
// ABRIR AGENDA DE HOY
// --------------------------------------------------
void openTodayAgenda(bool readEvents) {
Serial.println();
Serial.println("[AGENDA] Abriendo agenda de hoy");
prepareAgendaLoading();
bool success = calendarManager.fetchToday();
if (!success) {
Serial.println("[AGENDA] No se pudo consultar el calendario");
screens.showHome();
sayPrompt("No he podido consultar la agenda de hoy.");
return;
}
showLoadedAgenda();
if (readEvents) {
calendarManager.speakAll();
}
}
// --------------------------------------------------
// ABRIR AGENDA DE MAÑANA
// --------------------------------------------------
void openTomorrowAgenda() {
Serial.println();
Serial.println("[AGENDA] Abriendo agenda de mañana");
prepareAgendaLoading();
bool success = calendarManager.fetchTomorrow();
if (!success) {
Serial.println("[AGENDA] No se pudo consultar el calendario");
screens.showHome();
sayPrompt("No he podido consultar la agenda de mañana.");
return;
}
showLoadedAgenda();
calendarManager.speakAll();
}
// --------------------------------------------------
// ABRIR AGENDA SEMANAL
// --------------------------------------------------
void openWeekAgenda() {
Serial.println();
Serial.println("[AGENDA] Abriendo agenda semanal");
prepareAgendaLoading();
bool success = calendarManager.fetchWeek();
if (!success) {
Serial.println("[AGENDA] No se pudo consultar el calendario");
screens.showHome();
sayPrompt("No he podido consultar la agenda de esta semana.");
return;
}
showLoadedAgenda();
calendarManager.speakAll();
}
// --------------------------------------------------
// AGENDA DE LA SEMANA QUE VIENE
// --------------------------------------------------
void openNextWeekAgenda() {
Serial.println(
"[AGENDA] Abriendo agenda de la semana que viene"
);
prepareAgendaLoading();
if (!calendarManager.fetchNextWeek()) {
Serial.println(
"[AGENDA] No se pudo consultar la semana que viene"
);
screens.showHome();
sayPrompt(
"No he podido consultar la agenda de la semana que viene."
);
return;
}
showLoadedAgenda();
calendarManager.speakAll();
}
// --------------------------------------------------
// AGENDA DEL MES ACTUAL
// --------------------------------------------------
void openMonthAgenda() {
Serial.println("[AGENDA] Abriendo agenda de este mes");
prepareAgendaLoading();
if (!calendarManager.fetchMonth()) {
Serial.println(
"[AGENDA] No se pudo consultar este mes"
);
screens.showHome();
sayPrompt(
"No he podido consultar la agenda de este mes."
);
return;
}
showLoadedAgenda();
calendarManager.speakAll();
}
// --------------------------------------------------
// AGENDA DE LOS PROXIMOS X DIAS
// --------------------------------------------------
void openNextDaysAgenda(int days) {
Serial.println();
Serial.printf(
"[AGENDA] Abriendo agenda de los proximos %d dias\n",
days
);
prepareAgendaLoading();
if (!calendarManager.fetchNextDays(days)) {
Serial.println(
"[AGENDA] No se pudo consultar el periodo solicitado"
);
screens.showHome();
sayPrompt(
"No he podido consultar la agenda para ese periodo."
);
return;
}
showLoadedAgenda();
// Leer todos los eventos del periodo, no solo los visibles.
calendarManager.speakAll();
}
// --------------------------------------------------
// PROCESAR ÓRDENES
// --------------------------------------------------
void processCommand(String command) {
command.trim();
String rawCommand = command;
String normalizedCommand = normalizeSpokenText(command);
Serial.print("[ORDEN] ");
Serial.println(rawCommand);
if (normalizedCommand == "salir") {
eventCreationStep = EVENT_NONE;
pomodoroSetupStep = POMODORO_SETUP_NONE;
newEventTitle = "";
newEventDate = "";
newEventStart = "";
newEventEnd = "";
screens.showHome();
return;
}
bool isQuestion =
normalizedCommand.startsWith("que ") ||
normalizedCommand.startsWith("¿que ") ||
normalizedCommand.startsWith("cuanto ") ||
normalizedCommand.startsWith("¿cuanto ") ||
normalizedCommand.startsWith("cuando ") ||
normalizedCommand.startsWith("¿cuando ") ||
normalizedCommand.startsWith("donde ") ||
normalizedCommand.startsWith("¿donde ") ||
normalizedCommand.startsWith("como ") ||
normalizedCommand.startsWith("¿como ") ||
normalizedCommand.startsWith("quien ") ||
normalizedCommand.startsWith("¿quien ") ||
normalizedCommand.startsWith("cual ") ||
normalizedCommand.startsWith("¿cual ") ||
normalizedCommand.startsWith("por que ") ||
normalizedCommand.startsWith("¿por que ") ||
normalizedCommand.startsWith("para que ") ||
normalizedCommand.startsWith("¿para que ");
if (
isQuestion &&
screens.getCurrentScreen() == AppScreen::HOME
) {
display.showEyes(XiaoZhiState::THINKING);
}
if (eventCreationStep != EVENT_NONE) {
handleEventCreationInput(
rawCommand,
normalizedCommand
);
return;
}
command = normalizedCommand;
if (pomodoroSetupStep != POMODORO_SETUP_NONE) {
handlePomodoroSetupInput(command);
return;
}
// -----------------------------------------------
// PETICIONES DE FECHAS CONCRETAS
// -----------------------------------------------
const char* datePrefixes[] = {
"muestrame la agenda del ",
"muestra la agenda del ",
"muestrame agenda del ",
"muestra agenda del ",
"agenda del ",
"agenda para el ",
"agenda para ",
"muestrame la agenda para el ",
"muestra la agenda para el "
};
for (
unsigned int i = 0;
i < sizeof(datePrefixes) / sizeof(datePrefixes[0]);
++i
) {
String prefix = datePrefixes[i];
if (command.startsWith(prefix)) {
String requestedDate = rawCommand.substring(
prefix.length()
);
requestedDate.trim();
openDateAgenda(requestedDate);
return;
}
}
// -----------------------------------------------
// AGENDA DE LOS PROXIMOS X DIAS
// -----------------------------------------------
int requestedDays = 0;
if (parseNextDaysRequest(command, requestedDays)) {
openNextDaysAgenda(requestedDays);
return;
}
// -----------------------------------------------
// CREAR EVENTO
// -----------------------------------------------
if (
command == "crear evento" ||
command == "anadir evento" ||
command == "nuevo evento" ||
command == "agregar evento"
) {
eventCreationStep = EVENT_TITLE;
newEventTitle = "";
newEventDate = "";
newEventStart = "";
newEventEnd = "";
sayPrompt(
"Vamos a crear un evento en tu calendario Casa. ¿Cómo se llama?"
);
return;
}
// -----------------------------------------------
// OJOS
// -----------------------------------------------
if (
command == "ojos" ||
command == "inicio" ||
command == "vuelve a los ojos" ||
command == "vuelve"
) {
screens.showHome();
return;
}
// -----------------------------------------------
// TAREAS
// -----------------------------------------------
// RESUMEN DE TAREAS
if (
command == "tareas" ||
command == "muestra tareas" ||
command == "vista general de tareas" ||
command == "tareas pendientes" ||
command == "resumen de tareas"
) {
screens.show(AppScreen::TASKS);
taskManager.showOverview();
return;
}
// LISTA DETALLADA
if (
command == "entra en tareas" ||
command == "abrir tareas" ||
command == "lista de tareas" ||
command == "lista tareas" ||
command == "ver tareas"
) {
screens.show(AppScreen::TASKS);
taskManager.show();
return;
}
// AÑADIR UNA TAREA
if (
command.startsWith("anade tarea ") ||
command.startsWith("anadir tarea ") ||
command.startsWith("agrega tarea ") ||
command.startsWith("agregar tarea ") ||
command.startsWith("nueva tarea ")
) {
int separator = command.indexOf(' ');
String title = command.substring(separator + 1);
// Eliminar la palabra "tarea" del principio.
int secondSeparator = title.indexOf(' ');
if (secondSeparator >= 0) {
title = title.substring(secondSeparator + 1);
}
title.trim();
if (taskManager.addTask(title)) {
screens.show(AppScreen::TASKS);
sayPrompt("Tarea añadida correctamente.");
} else {
sayPrompt("No he podido añadir la tarea. Comprueba el espacio disponible.");
}
return;
}
// ELIMINAR TAREAS COMPLETADAS
if (
command == "elimina completados" ||
command == "eliminar completados" ||
command == "borra completados" ||
command == "borrar completados" ||
command == "elimina las completadas" ||
command == "limpia completados"
) {
int removed = taskManager.deleteCompleted();
screens.show(AppScreen::TASKS);
if (removed > 0) {
sayPrompt(
"He eliminado " +
String(removed) +
(removed == 1
? " tarea completada."
: " tareas completadas.")
);
}
else {
sayPrompt("No hay tareas completadas para eliminar.");
}
return;
}
// VOLVER AL RESUMEN
if (
command == "vuelve a vista general" ||
command == "vista general" ||
command == "volver al resumen"
) {
if (
screens.getCurrentScreen() == AppScreen::TASKS
) {
taskManager.returnToOverview();
}
return;
}
// -----------------------------------------------
// SCROLL HACIA ABAJO
// -----------------------------------------------
if (
command == "baja" ||
command == "bajar" ||
command == "baja la agenda" ||
command == "baja eventos" ||
command == "siguiente" ||
command == "siguiente pagina" ||
command == "mas eventos" ||
command == "ver mas" ||
command == "desplazate abajo"
) {
if (
screens.getCurrentScreen() == AppScreen::AGENDA
) {
calendarManager.scrollDown();
}
else if (
screens.getCurrentScreen() == AppScreen::TASKS
) {
taskManager.scrollDown();
}
return;
}
// -----------------------------------------------
// SCROLL HACIA ARRIBA
// -----------------------------------------------
if (
command == "sube" ||
command == "subir" ||
command == "sube la agenda" ||
command == "sube eventos" ||
command == "anterior" ||
command == "pagina anterior" ||
command == "desplazate arriba"
) {
if (
screens.getCurrentScreen() == AppScreen::AGENDA
) {
calendarManager.scrollUp();
}
else if (
screens.getCurrentScreen() == AppScreen::TASKS
) {
taskManager.scrollUp();
}
return;
}
// -----------------------------------------------
// COMPLETAR TAREAS
// -----------------------------------------------
if (command.startsWith("tacha ")) {
String value = command.substring(6);
value.trim();
if (
value.length() > 0 &&
isDigit(value.charAt(0))
) {
taskManager.completeByNumber(value.toInt());
}
else {
taskManager.completeByText(value);
}
return;
}
// -----------------------------------------------
// CRONOMETRO
// -----------------------------------------------
if (
command == "cronometro" ||
command == "muestra cronometro" ||
command == "abre cronometro"
) {
showTimeScreenIfNeeded(AppScreen::STOPWATCH);
display.showStopwatch(
chronometer.getStopwatchElapsed(),
chronometer.isStopwatchRunning()
);
return;
}
if (
command == "inicia cronometro" ||
command == "iniciar cronometro" ||
command == "empieza cronometro" ||
command == "reanuda cronometro" ||
command == "continua cronometro"
) {
chronometer.startStopwatch();
showTimeScreenIfNeeded(AppScreen::STOPWATCH);
sayPrompt("Cronómetro en marcha.");
return;
}
if (
command == "pausa cronometro" ||
command == "pausar cronometro" ||
command == "deten cronometro"
) {
chronometer.pauseStopwatch();
showTimeScreenIfNeeded(AppScreen::STOPWATCH);
sayPrompt("Cronómetro pausado.");
return;
}
if (
command == "reinicia cronometro" ||
command == "reiniciar cronometro" ||
command == "resetea cronometro"
) {
chronometer.resetStopwatch();
showTimeScreenIfNeeded(AppScreen::STOPWATCH);
sayPrompt("Cronómetro reiniciado.");
return;
}
if (
command == "cuanto tiempo llevo" ||
command == "cuanto tiempo" ||
command == "tiempo transcurrido"
) {
unsigned long seconds =
chronometer.getStopwatchElapsed() / 1000UL;
unsigned long minutes = seconds / 60;
seconds %= 60;
sayPrompt(
"Han transcurrido " +
String(minutes) +
" minutos y " +
String(seconds) +
" segundos."
);
return;
}
// -----------------------------------------------
// CONFIGURAR POMODORO
// -----------------------------------------------
if (
command == "configura pomodoro" ||
command == "configurar pomodoro" ||
command == "configura el pomodoro" ||
command == "configurar el pomodoro"
) {
pomodoroSetupStep = POMODORO_SETUP_WORK;
pendingPomodoroWorkMinutes = chronometer.getWorkMinutes();
pendingPomodoroShortBreakMinutes =
chronometer.getShortBreakMinutes();
pendingPomodoroLongBreakMinutes =
chronometer.getLongBreakMinutes();
showTimeScreenIfNeeded(AppScreen::POMODORO);
sayPrompt(
"Vamos a configurar el Pomodoro. ¿Cuánto quieres que dure la concentración?"
);
return;
}
if (
command.startsWith("concentracion de ") ||
command.startsWith("tiempo de concentracion de ") ||
command.startsWith("cambia la concentracion a ")
) {
int position = command.lastIndexOf(" de ");
if (command.startsWith("cambia la concentracion a ")) {
position = command.lastIndexOf(" a ");
}
String durationText = command.substring(position + 4);
durationText.trim();
int minutes = parseDurationMinutes(durationText);
if (minutes >= 1 && minutes <= 240) {
chronometer.setWorkMinutes(minutes);
sayPrompt(
"El tiempo de concentración ahora es de " +
String(minutes) +
" minutos."
);
} else {
sayPrompt("No he entendido esa duración.");
}
return;
}
if (
command.startsWith("descanso corto de ") ||
command.startsWith("cambia el descanso corto a ")
) {
int position = command.lastIndexOf(" de ");
if (command.startsWith("cambia el descanso corto a ")) {
position = command.lastIndexOf(" a ");
}
String durationText = command.substring(position + 4);
durationText.trim();
int minutes = parseDurationMinutes(durationText);
if (minutes >= 1 && minutes <= 120) {
chronometer.setShortBreakMinutes(minutes);
sayPrompt(
"El descanso corto ahora es de " +
String(minutes) +
" minutos."
);
} else {
sayPrompt("No he entendido esa duración.");
}
return;
}
if (
command.startsWith("descanso largo de ") ||
command.startsWith("cambia el descanso largo a ")
) {
int position = command.lastIndexOf(" de ");
if (command.startsWith("cambia el descanso largo a ")) {
position = command.lastIndexOf(" a ");
}
String durationText = command.substring(position + 4);
durationText.trim();
int minutes = parseDurationMinutes(durationText);
if (minutes >= 1 && minutes <= 180) {
chronometer.setLongBreakMinutes(minutes);
sayPrompt(
"El descanso largo ahora es de " +
String(minutes) +
" minutos."
);
} else {
sayPrompt("No he entendido esa duración.");
}
return;
}
if (command.startsWith("cambia las repeticiones a ")) {
String numberText = command.substring(
String("cambia las repeticiones a ").length()
);
int repetitions = spanishNumber(numberText);
if (repetitions >= 1 && repetitions <= 12) {
chronometer.setSessionsBeforeLongBreak(repetitions);
sayPrompt(
"Ahora tendrás " +
String(repetitions) +
" sesiones antes del descanso largo."
);
} else {
sayPrompt("El número de sesiones debe estar entre uno y doce.");
}
return;
}
// -----------------------------------------------
// CONSULTAR CONFIGURACION POMODORO
// -----------------------------------------------
if (
command == "configuracion pomodoro" ||
command == "tiempos pomodoro"
) {
sayPrompt(
"Concentración: " +
String(chronometer.getWorkMinutes()) +
" minutos. Descanso corto: " +
String(chronometer.getShortBreakMinutes()) +
" minutos. Descanso largo: " +
String(chronometer.getLongBreakMinutes()) +
" minutos. Descanso largo cada " +
String(chronometer.getSessionsBeforeLongBreak()) +
" sesiones."
);
return;
}
// -----------------------------------------------
// POMODORO
// -----------------------------------------------
if (
command == "pomodoro" ||
command == "muestra pomodoro"
) {
showTimeScreenIfNeeded(AppScreen::POMODORO);
display.showPomodoro(
chronometer.getPomodoroRemaining(),
chronometer.getPomodoroDuration(),
chronometer.getPomodoroPhaseName(),
chronometer.getCurrentSession(),
chronometer.getSessionsBeforeLongBreak(),
chronometer.isPomodoroRunning(),
chronometer.isPomodoroPaused(),
chronometer.isPomodoroFinished()
);
return;
}
if (
command == "inicia pomodoro" ||
command == "iniciar pomodoro" ||
command == "empieza pomodoro" ||
command == "comienza pomodoro"
) {
chronometer.startPomodoro();
showTimeScreenIfNeeded(AppScreen::POMODORO);
sayPrompt(
"Comienza la concentración. Tienes " +
String(chronometer.getWorkMinutes()) +
" minutos."
);
return;
}
if (
command == "pausa pomodoro" ||
command == "pausar pomodoro"
) {
chronometer.pausePomodoro();
showTimeScreenIfNeeded(AppScreen::POMODORO);
sayPrompt("Pomodoro pausado.");
return;
}
if (
command == "reanuda pomodoro" ||
command == "continua pomodoro" ||
command == "reanudar pomodoro"
) {
chronometer.resumePomodoro();
showTimeScreenIfNeeded(AppScreen::POMODORO);
sayPrompt("Pomodoro reanudado.");
return;
}
if (
command == "deten pomodoro" ||
command == "detener pomodoro" ||
command == "para pomodoro" ||
command == "cancelar pomodoro"
) {
chronometer.stopPomodoro();
showTimeScreenIfNeeded(AppScreen::POMODORO);
sayPrompt("Pomodoro detenido.");
return;
}
// -----------------------------------------------
// TEMPORIZADOR
// -----------------------------------------------
if (
command == "pausa temporizador" ||
command == "pausar temporizador"
) {
chronometer.pauseTimer();
showTimeScreenIfNeeded(AppScreen::TIMER);
sayPrompt("Temporizador pausado.");
return;
}
if (
command == "reanuda temporizador" ||
command == "reanudar temporizador" ||
command == "continua temporizador"
) {
chronometer.resumeTimer();
showTimeScreenIfNeeded(AppScreen::TIMER);
sayPrompt("Temporizador reanudado.");
return;
}
if (
command == "deten temporizador" ||
command == "detener temporizador" ||
command == "cancela temporizador" ||
command == "cancelar temporizador"
) {
chronometer.stopTimer();
showTimeScreenIfNeeded(AppScreen::TIMER);
sayPrompt("Temporizador detenido.");
return;
}
bool mentionsTimer =
command.indexOf("temporizador") >= 0 ||
command.indexOf("cuenta atras") >= 0;
bool mentionsDuration =
command.indexOf(" minuto") >= 0 ||
command.indexOf(" hora") >= 0;
if (mentionsTimer && mentionsDuration) {
int minutes = parseDurationMinutes(command);
if (minutes < 1 || minutes > 240) {
showTimeScreenIfNeeded(AppScreen::TIMER);
sayPrompt(
"La duración debe estar entre uno y doscientos cuarenta minutos."
);
return;
}
chronometer.startTimer(minutes);
showTimeScreenIfNeeded(AppScreen::TIMER);
String durationText = minutes == 1
? "un minuto"
: String(minutes) + " minutos";
sayPrompt(
"Temporizador iniciado por " +
durationText +
"."
);
return;
}
if (
command == "inicia temporizador" ||
command == "iniciar temporizador" ||
command == "empieza temporizador" ||
command == "comienza temporizador" ||
command == "pon temporizador" ||
command == "pon un temporizador" ||
command == "ponme un temporizador" ||
command == "inicia cuenta atras" ||
command == "iniciar cuenta atras"
) {
chronometer.startTimer();
showTimeScreenIfNeeded(AppScreen::TIMER);
int minutes =
chronometer.getTimerDuration() / 60000UL;
String durationText = minutes == 1
? "un minuto"
: String(minutes) + " minutos";
sayPrompt(
"Temporizador iniciado por " +
durationText +
"."
);
return;
}
if (
command == "temporizador" ||
command == "muestra temporizador" ||
command == "cuenta atras"
) {
showTimeScreenIfNeeded(AppScreen::TIMER);
display.showTimer(
chronometer.getTimerRemaining(),
chronometer.getTimerDuration(),
chronometer.isTimerRunning(),
chronometer.isTimerPaused(),
chronometer.isTimerFinished()
);
return;
}
// -----------------------------------------------
// AGENDA DE HOY
// -----------------------------------------------
if (
command == "agenda" ||
command == "muestra agenda" ||
command == "abre agenda" ||
command == "abrir agenda"
) {
openTodayAgenda(true);
return;
}
// -----------------------------------------------
// EVENTOS DE HOY
// -----------------------------------------------
if (
command == "que tengo hoy" ||
command == "que hay hoy" ||
command == "eventos de hoy" ||
command == "agenda de hoy"
) {
openTodayAgenda(true);
return;
}
// -----------------------------------------------
// EVENTOS DE MAÑANA
// -----------------------------------------------
if (
command == "que tengo manana" ||
command == "que hay manana" ||
command == "eventos de manana" ||
command == "agenda de manana"
) {
openTomorrowAgenda();
return;
}
// -----------------------------------------------
// EVENTOS DE ESTA SEMANA
// -----------------------------------------------
if (
command == "que tengo esta semana" ||
command == "eventos de esta semana" ||
command == "agenda semanal"
) {
openWeekAgenda();
return;
}
// -----------------------------------------------
// EVENTOS DE LA SEMANA QUE VIENE
// -----------------------------------------------
if (
command == "que tengo la semana que viene" ||
command == "que tengo semana que viene" ||
command == "que tengo la proxima semana" ||
command == "eventos de la semana que viene" ||
command == "agenda de la semana que viene"
) {
openNextWeekAgenda();
return;
}
// -----------------------------------------------
// EVENTOS DEL MES ACTUAL
// -----------------------------------------------
if (
command == "que tengo este mes" ||
command == "que hay este mes" ||
command == "eventos de este mes" ||
command == "agenda de este mes"
) {
openMonthAgenda();
return;
}
// -----------------------------------------------
// LEER AGENDA
// -----------------------------------------------
if (
command == "lee agenda" ||
command == "leeme la agenda" ||
command == "lee todos los eventos"
) {
if (
screens.getCurrentScreen() == AppScreen::AGENDA
) {
calendarManager.speakAll();
}
else {
openTodayAgenda(true);
}
return;
}
// -----------------------------------------------
// LEER EVENTOS VISIBLES
// -----------------------------------------------
if (
command == "lee siguientes" ||
command == "leeme los siguientes" ||
command == "lee esta pagina"
) {
if (
screens.getCurrentScreen() == AppScreen::AGENDA
) {
calendarManager.speakVisible();
}
else {
Serial.println(
"[AGENDA] Primero abre la agenda"
);
}
return;
}
// -----------------------------------------------
// ACTUALIZAR AGENDA
// -----------------------------------------------
if (
command == "actualiza agenda" ||
command == "actualizar agenda" ||
command == "recarga agenda"
) {
openTodayAgenda(true);
return;
}
// -----------------------------------------------
// DETENER VOZ
// -----------------------------------------------
if (
command == "deja de hablar" ||
command == "para de hablar" ||
command == "deten lectura"
) {
calendarManager.stopSpeaking();
return;
}
// -----------------------------------------------
// ESTADOS XIAOZHI
// -----------------------------------------------
if (command == "escuchando") {
display.showEyes(XiaoZhiState::LISTENING);
return;
}
if (command == "pensando") {
display.showEyes(XiaoZhiState::THINKING);
return;
}
if (command == "hablando") {
display.showEyes(XiaoZhiState::SPEAKING);
return;
}
// -----------------------------------------------
// ORDEN NO RECONOCIDA
// -----------------------------------------------
Serial.println("[ORDEN] No reconocida");
if (screens.getCurrentScreen() == AppScreen::HOME) {
display.showEyes(XiaoZhiState::LISTENING);
}
}
// --------------------------------------------------
// MONITOR SERIE
// --------------------------------------------------
void readSerial() {
while (Serial.available()) {
char character = Serial.read();
if (character == '\n' || character == '\r') {
if (serialCommand.length() > 0) {
processCommand(serialCommand);
serialCommand = "";
}
}
else {
if (serialCommand.length() < 150) {
serialCommand += character;
}
}
}
}
// --------------------------------------------------
// BOTONES
// --------------------------------------------------
void handleButtons() {
bool greenState = digitalRead(btnGreen);
bool redState = digitalRead(btnRed);
unsigned long now = millis();
if (
greenState == LOW &&
lastGreenState == HIGH &&
now - lastButtonTime > DEBOUNCE_TIME
) {
AppScreen current = screens.getCurrentScreen();
if (current == AppScreen::POMODORO) {
openTodayAgenda(false);
}
else {
screens.showNext();
if (
screens.getCurrentScreen() == AppScreen::TASKS
) {
taskManager.showOverview();
}
}
lastButtonTime = now;
}
if (
redState == LOW &&
lastRedState == HIGH &&
now - lastButtonTime > DEBOUNCE_TIME
) {
screens.showHome();
lastButtonTime = now;
}
lastGreenState = greenState;
lastRedState = redState;
}
// --------------------------------------------------
// SETUP
// --------------------------------------------------
void setup() {
Serial.begin(115200);
delay(500);
Serial.println();
Serial.println("==============================");
Serial.println(" XIAOZHI ESP32");
Serial.println("==============================");
pinMode(btnGreen, INPUT_PULLUP);
pinMode(btnRed, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(TFT_BL, OUTPUT);
digitalWrite(TFT_BL, HIGH);
digitalWrite(ledPin, HIGH);
if (!display.begin()) {
Serial.println(
"[ERROR] No se pudo iniciar la pantalla"
);
while (true) {
delay(100);
}
}
screens.begin(&display);
taskManager.begin(&display);
calendarManager.begin(&display);
chronometer.begin(&display);
screens.showHome();
Serial.println();
Serial.println("XiaoZhi listo");
Serial.println("------------------------------");
Serial.println("COMANDOS DE TAREAS:");
Serial.println("tareas");
Serial.println("entra en tareas");
Serial.println("vuelve a vista general");
Serial.println("tacha comprar leche");
Serial.println("tacha 2");
Serial.println("anade tarea comprar pan");
Serial.println("anadir tarea llamar al medico");
Serial.println("elimina completados");
Serial.println();
Serial.println("COMANDOS DE AGENDA:");
Serial.println("agenda");
Serial.println("que tengo hoy");
Serial.println("que tengo manana");
Serial.println("que tengo esta semana");
Serial.println("que tengo la semana que viene");
Serial.println("que tengo este mes");
Serial.println("que tengo en los proximos 5 dias");
Serial.println("agenda para los proximos diez dias");
Serial.println("eventos de los proximos tres dias");
Serial.println("lee agenda");
Serial.println("lee siguientes");
Serial.println("actualiza agenda");
Serial.println("crear evento");
Serial.println();
Serial.println("COMANDOS DEL TEMPORIZADOR:");
Serial.println("temporizador");
Serial.println("inicia temporizador");
Serial.println("temporizador de 5 minutos");
Serial.println("pausa temporizador");
Serial.println("reanuda temporizador");
Serial.println("deten temporizador");
Serial.println();
Serial.println("COMANDOS DEL POMODORO:");
Serial.println("configura pomodoro");
Serial.println("responde a concentracion, descansos y ciclos");
Serial.println("inicia pomodoro");
Serial.println("cancelar");
Serial.println();
Serial.println("COMANDOS GENERALES:");
Serial.println("baja");
Serial.println("sube");
Serial.println("ojos");
Serial.println("deja de hablar");
Serial.println();
Serial.println("Introduce una orden y pulsa ENTER.");
Serial.println("==============================");
}
// --------------------------------------------------
// LOOP
// --------------------------------------------------
// --------------------------------------------------
// ACTUALIZAR PANTALLAS DE TIEMPO
// --------------------------------------------------
void updateTimeScreens() {
static unsigned long lastStopwatchRefresh = 0;
static unsigned long lastTimerRefresh = 0;
static unsigned long lastPomodoroRefresh = 0;
unsigned long now = millis();
if (chronometer.updateTimer()) {
sayPrompt("El temporizador ha terminado.");
}
// Comprobar las transiciones del Pomodoro continuamente.
ChronometerEvent event = chronometer.updatePomodoro();
if (event == ChronometerEvent::WORK_FINISHED) {
sayPrompt("Ha terminado la concentración. Comienza el descanso.");
}
else if (event == ChronometerEvent::SHORT_BREAK_FINISHED) {
sayPrompt("Ha terminado el descanso. Volvemos a concentrarnos.");
}
else if (event == ChronometerEvent::LONG_BREAK_FINISHED) {
sayPrompt("Pomodoro completado. Has terminado todos los ciclos.");
}
AppScreen current = screens.getCurrentScreen();
if (
current == AppScreen::STOPWATCH &&
now - lastStopwatchRefresh >= 100
) {
lastStopwatchRefresh = now;
display.showStopwatch(
chronometer.getStopwatchElapsed(),
chronometer.isStopwatchRunning()
);
}
if (
current == AppScreen::TIMER &&
now - lastTimerRefresh >= 250
) {
lastTimerRefresh = now;
display.showTimer(
chronometer.getTimerRemaining(),
chronometer.getTimerDuration(),
chronometer.isTimerRunning(),
chronometer.isTimerPaused(),
chronometer.isTimerFinished()
);
}
if (
current == AppScreen::POMODORO &&
now - lastPomodoroRefresh >= 250
) {
lastPomodoroRefresh = now;
display.showPomodoro(
chronometer.getPomodoroRemaining(),
chronometer.getPomodoroDuration(),
chronometer.getPomodoroPhaseName(),
chronometer.getCurrentSession(),
chronometer.getSessionsBeforeLongBreak(),
chronometer.isPomodoroRunning(),
chronometer.isPomodoroPaused(),
chronometer.isPomodoroFinished()
);
}
}
// --------------------------------------------------
// LOOP
// --------------------------------------------------
void loop() {
handleButtons();
readSerial();
updateTimeScreens();
if (screens.getCurrentScreen() == AppScreen::HOME) {
display.updateEyes();
}
}Loading
esp32-s3-devkitc-1
esp32-s3-devkitc-1
Loading
st7789
st7789