Ayuda con mensaje vía telegram en Arduino esp32

Estimados todos,

estoy realizando para mi casa un sistema domotizado, para control de encendido de luces a través de msje por telegram, al cual más adelante le agregaré sensores que verán si una ventana de la casa se abre, entre otras cuestiones, actualmente tiene agregado un control remoto básico, de esos que venden en china, con 4 salidas, una por canal como si fueran inputs, en fin.

Les escribo, pq tengo un pequeño "detalle" al realizar esto algunas cosas, que no logro comprender del todo, la mayoría copio y pego, algo analizo y llevo a cabo, les dejo el código, y los detalles al final.

#include <WiFi.h>
#include <WiFiClientSecure.h>
//#include <WiFiMulti.h>
//#include "BluetoothSerial.h"
//BluetoothSerial ESP_BT;
//WiFiMulti wifiMulti;
const uint32_t TiempoEsperaWifi = 5000;
#include <UniversalTelegramBot.h>
// Reemplazar con los datos de tu red wifi
#define WIFI_SSID "*************"
#define WIFI_PASSWORD "*********"
//Token de Telegram BOT se obtenienen desde Botfather en telegram
#define BOT_TOKEN "***********************"
const unsigned long tiempo = 1000; //tiempo medio entre mensajes de escaneo
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long tiempoAnterior; //última vez que se realizó el análisis de mensajes
const int ledwifi = 2;
const int ledv = 26;
const int ledf = 25;
const int leda = 17;
const int led16 = 16;
const int led27 = 27;
const int lede = 14;
int boton1 = 23;
int boton2 = 5;
int boton3 = 13;
int boton4 = 12;
int estadowifi = 0;
int estadoLedv = 0;
int estadoLedf = 0;
int estadoLeda = 0;
int estadoLed16 = 0;
int estadoLed27 = 0;
int estadoLede = 0;
int inicio = 1;
String chat_id;
#define ID_Chat "*********"//ID_Chat se obtiene de telegram
void mensajesNuevos(int numerosMensajes){
  for (int i = 0; i < numerosMensajes; i++){
    String chat_id = bot.messages[i].chat_id;
    String text = bot.messages[i].text;
//////////Luz virgencita en el pin 26//////
    if (text == "von"){
      digitalWrite(ledv, LOW); // 
      estadoLedv = 1;
      bot.sendMessage(chat_id, "Luz Virgencita prendida", "");
    }

    if (text == "voff"){
      estadoLedv = 0;
      digitalWrite(ledv, HIGH); // 
      bot.sendMessage(chat_id, "Luz Virgencita apagada", "");
    }
//////////Luz farol en el pin 25//////
    if (text == "fon"){
      digitalWrite(ledf, LOW); 
      estadoLedf = 1;
      bot.sendMessage(chat_id, "Luz Farol prendida", "");
    }

    if (text == "foff"){
      estadoLedf = 0;
      digitalWrite(ledf, HIGH); 
      bot.sendMessage(chat_id, "Luz Farol apagada", "");
    }  
//////////Luz Alero en pin 17/////////////
    if (text == "aon"){
      digitalWrite(leda, LOW); 
      estadoLeda = 1;
      bot.sendMessage(chat_id, "Luz alero prendida", "");
    }

    if (text == "aoff"){
      estadoLeda = 0;
      digitalWrite(leda, HIGH); 
      bot.sendMessage(chat_id, "Luz alero apagada", "");
    }
////////Luz en pin 16///////////
    if (text == "fpon"){
      digitalWrite(led16, LOW); 
      estadoLed16 = 1;
      bot.sendMessage(chat_id, "Farol patio prendida", "");
    }

    if (text == "fpoff") {
      estadoLed16 = 0;
      digitalWrite(led16, HIGH); 
      bot.sendMessage(chat_id, "Farol patio apagada", "");
    }
///////Luz en pin 27/////////////
    if (text == "con"){
      digitalWrite(led27, LOW); 
      estadoLed27 = 1;
      bot.sendMessage(chat_id, "Luz cobertizo prendida", "");
    }

    if (text == "coff"){
      estadoLed27 = 0;
      digitalWrite(led27, HIGH); 
      bot.sendMessage(chat_id, "Luz cobertizo apagada", "");
    }
///////Luz en pin 14 ////////////
    if (text == "eon"){
      digitalWrite(lede, LOW); 
      estadoLede = 1;
      bot.sendMessage(chat_id, "Luz escalera prendida", "");
    }

    if (text == "eoff"){
      estadoLede = 0;
      digitalWrite(lede, HIGH); 
      bot.sendMessage(chat_id, "Luz escalera apagada", "");
    }
    
////////Estado de las luces  ///////     

    if (text == "Estado"){
      ////Estado luz virgencita////
      if (estadoLedv){
        bot.sendMessage(chat_id, "Luz Virgencita prendida", "");
      }
      else{
        bot.sendMessage(chat_id, "Luz Virgencita apagada", "");
      }
      ////Estado luz farol////
      if (estadoLedf){
        bot.sendMessage(chat_id, "Luz Farol prendida", "");
      }
      else{
        bot.sendMessage(chat_id, "Luz Farol apagada", "");
      }
      ////Estado luz 16////
      if (estadoLed16){
        bot.sendMessage(chat_id, "Luz Farol patio prendida", "");
      }
      else{
        bot.sendMessage(chat_id, "Luz Farol patio apagada", "");
      }
      ////Estado Led 27////
      if (estadoLed27){
        bot.sendMessage(chat_id, "Luz Cobertizo prendida", "");
      }
      else{
        bot.sendMessage(chat_id, "Luz Cobertizo apagada", "");
      }
      ////Estado Led 14////
      if (estadoLede){
        bot.sendMessage(chat_id, "Luz escalera prendida", "");
      }
      else{
        bot.sendMessage(chat_id, "Luz escalera apagada", "");
      }
      ////Estado luz alero////
      if (estadoLeda){
        bot.sendMessage(chat_id, "Luz Alero prendida", "");
      }
      else{
        bot.sendMessage(chat_id, "Luz Alero apagada", "");
      }
      /////Estado WIFI
      if (estadowifi){
        bot.sendMessage(chat_id, "Conectado a red "+WiFi.SSID(), "");
      }
      //else{
      //  bot.sendMessage(chat_id, "Luz Farol apagada", "");
      //}
    }

    if (text == "Ayuda" or text == "ayuda"){
      String ayuda = "Sistema de encendido de luces vía Telegram" ".\n";
      ayuda += "De nuestra casa.\n\n";
      ayuda += "Estas son las opciones.\n\n";
      ayuda += "von: para encender Luz Gruta \n";
      ayuda += "voff: para apagar Luz Gruta \n";
      ayuda += "fon: para encender Farol \n";
      ayuda += "foff: para apagar Farol \n";
      ayuda += "aon: para encender Luz Alero \n";
      ayuda += "aoff: para apagar Luz Alero \n";
      ayuda += "fpon: para encender Farol patio \n";
      ayuda += "fpoff: para apagar Farol patio \n";
      ayuda += "con: para encender Cobertizo \n";
      ayuda += "coff: para apagar Cobertizo \n";
      ayuda += "eon: para encender Escalera \n";
      ayuda += "eoff: para apagar Escalera \n";
      ayuda += "Estado : devuelve el estado actual de las luces\n";
      ayuda += "Ayuda: Imprime este menú \n";
      ayuda += "El sistema distingue entre mayúculas y minúsculas \n";
      bot.sendMessage(chat_id, ayuda, "");
    }    
  }
}

void setup(){
  //ESP_BT.begin("CASA5339");
  Serial.begin(115200);
  pinMode(ledv, OUTPUT); //inicializar  pin 12 digital como salida.
  pinMode(ledf, OUTPUT); //inicializar pin 14 digital como salida.
  pinMode(leda, OUTPUT); //inicializar pin 14 digital como salida.
  pinMode(led16, OUTPUT);
  pinMode(led27, OUTPUT);
  pinMode(lede, OUTPUT);
  pinMode(ledwifi, OUTPUT); //inicializa el led de wifi
  pinMode(boton1, INPUT_PULLUP);
  pinMode(boton2, INPUT_PULLUP);
  pinMode(boton3, INPUT_PULLUP);
  pinMode(boton4, INPUT_PULLUP);
  digitalWrite(ledwifi, LOW);
  digitalWrite(ledv, HIGH); //
  digitalWrite(ledf, HIGH);
  digitalWrite(leda, HIGH);
  digitalWrite(led16, HIGH);
  digitalWrite(led27, HIGH);
  digitalWrite(lede, HIGH);
  
  // Intenta conectarse a la red wifi
  Serial.print(F("Conectando a la red "));
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); //Agregar certificado raíz para api.telegram.org
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
  Serial.print(F("\nConectado a la red wifi. Dirección IP: "));
  Serial.println(WiFi.localIP());
   if(inicio == 1){
    Serial.println(F("Sistema listo"));
    bot.sendMessage(chat_id, "Sistema preparado!!!, escribe Ayuda para ver las opciones", "");//Enviamos un mensaje a telegram para informar que el sistema está listo
//ESTE MENSAJE NO LO ENVÍA, NO ENTIENDO PQ RAZON NO LO ENVÍA
    inicio = 0;
    }
}

void loop(){
  //ActualizarWifi();
  if (WiFi.status() == WL_CONNECTED){
    digitalWrite(ledwifi, HIGH);
    estadowifi = 1;
  }else{
    digitalWrite(ledwifi, LOW);
    estadowifi = 0;
  }
  //Verifica si hay datos nuevos en telegram cada 1 segundo
  if (millis() - tiempoAnterior > tiempo){
    int numerosMensajes = bot.getUpdates(bot.last_message_received + 1);
    while (numerosMensajes){
      Serial.println(F("Comando recibido"));
      mensajesNuevos(numerosMensajes);
      numerosMensajes = bot.getUpdates(bot.last_message_received + 1);
    }
    tiempoAnterior = millis();
  }
  inputs();
}

/*void ActualizarWifi(){
  if (wifiMulti.run(TiempoEsperaWifi) != WL_CONNECTED){
    Serial.println("No conectado a WiFi!");
  }
}*/

void inputs(){
  if ((digitalRead(boton1) == HIGH) && (estadoLede == 0)){
      Serial.println("ESCALERA ENCENDIDA");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz de la escalera encendida", "");
//ESTOS MENSAJES TAMPOCO LOS ENVÍA
      estadoLede = 1;
      digitalWrite(lede, LOW);
    } 
    if ((digitalRead(boton1) == HIGH) && (estadoLede == 1)){
      Serial.println("ESCALERA APAGADA");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz de la escalera apagada", "");
      estadoLede = 0;
      digitalWrite(lede, HIGH);
    }


    if ((digitalRead(boton2) == HIGH) && (estadoLedv == 0)){
      Serial.println("VIRGENCITA ENCENDIDA");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz Virgencita encendidaa", "");
      estadoLedv = 1;
      digitalWrite(ledv, LOW);
    } 
    if ((digitalRead(boton2) == HIGH) && (estadoLedv == 1)){
      Serial.println("VIRGENCITA APAGADA");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz Virgencita apagada", "");
      estadoLedv = 0;
      digitalWrite(ledv, HIGH);
    }


    if ((digitalRead(boton3) == HIGH) && (estadoLed27 == 0)){
      Serial.println("COBERTIZO ENCENDIDA");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz del cobertizo encendida", "");
      estadoLed27 = 1;
      digitalWrite(led27, LOW);
    } 
    if ((digitalRead(boton3) == HIGH) && (estadoLed27 == 1)){
      Serial.println("COBERTIZO APAGADA");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz del cobertizo apagada", "");
      estadoLed27 = 0;
      digitalWrite(led27, HIGH);
    }

    if ((digitalRead(boton4) == HIGH) && (estadoLedf == 0)){
      Serial.println("FAROL ENCENDIDO");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz del farol delantero encendida", "");
      estadoLedf = 1;
      digitalWrite(ledf, LOW);
    } 
    if ((digitalRead(boton4) == HIGH) && (estadoLedf == 1)){
      Serial.println("FAROL APAGADO");
      //digitalWrite(2, HIGH);
      delay(1000);
      //digitalWrite(2, LOW);
      bot.sendMessage(chat_id, "Luz del farol delantero apagada", "");
      estadoLedf = 0;
      digitalWrite(ledf, HIGH);
    }
}

DEJÉ mencionado en el código los detalles, pero, son estos:

bot.sendMessage(chat_id, "Sistema preparado!!!, escribe Ayuda para ver las opciones", "");//Enviamos un mensaje a telegram para informar que el sistema está listo

ese mensaje que está dentro del Setup() no lo envía, afuera arriba si envía los mensajes, y, más abajo tampoco los envía, los que están en el void inputs()

de primera, me interesaba compartirles el código, si está bueno o no, da lo mismo, les puede servir, pero desde ya, les agradezco cualquier otra ayuda!, gracias a todos.

No conozco la librería pero veo en UniversalTelegramBot.h que tiene modo debug, prueba a activarlo a ver si te ayuda.

//#define TELEGRAM_DEBUG 1
//#define _debug

Moderador:
Por favor, lee las Normas del foro y edita tu título de acuerdo al punto 5 de las normas. Cómo poner un título en este foro.

Si no quieres tener problemas, cambia la librería de telegram a CTBot. Búscala en el administrador de librerías. En los ejemplos podrás ver como funciona y es muy sencillo

Saludos

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.