meta data de esta página
Diferencias
Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anteriorRevisión previaPróxima revisión | Revisión previa | ||
| electronica:esp8266:telegram [2016/09/03 17:48] – [Enviar mensajes desde el ESP8266 mediante Telegram] lc | electronica:esp8266:telegram [2023/01/18 13:36] (actual) – editor externo 127.0.0.1 | ||
|---|---|---|---|
| Línea 1: | Línea 1: | ||
| + | {{tag> | ||
| ===== Enviar mensajes desde el ESP8266 mediante Telegram ===== | ===== Enviar mensajes desde el ESP8266 mediante Telegram ===== | ||
| Lo primero que necesitamos en crear nuestro propio bot. Para ello instalamos Telegram en nuestro móvil e iniciamos un chat con **@BotFather**. | Lo primero que necesitamos en crear nuestro propio bot. Para ello instalamos Telegram en nuestro móvil e iniciamos un chat con **@BotFather**. | ||
| - | * Escribimos **/ | + | * Escribimos **/ |
| - | * Escribimos | + | * Una vez escrito |
| - | * Ahora nos dará una dirección | + | * Ponemos un nombre de usuario que debe de terminar con **bot** |
| - | * Iniciamos un chat con nuestro | + | * Ahora nos saldrá un mensaje en el que nos dará una dirección y un token de acceso |
| - | * Escribimos **/ | + | * Iniciamos un chat con nuestro |
| - | * El bot nos responde con un mensaje | + | * Si escribimos algo y enviamos |
| + | Una vez que hemos escrito algo en nuestro chat con el bot procederemos a ver como podemos conocer el identificador (chat_id) ya que lo vamos a necesitar posteriormente . | ||
| + | Para ello abrimos nuestro navegador y escribimos lo siguiente : | ||
| + | < | ||
| + | donde token es el identificador que nos había enviado el @bootFather. | ||
| + | Un ejemplo sería : | ||
| + | < | ||
| + | < | ||
| + | " | ||
| + | donde podemos observar que el chat_id es -> | ||
| + | Una vez creado nuestro bot vamos a utilizar el mismo circuito que utilizamos para el servidor web, pero ahora haremos que nos envié la temperatura y la humedad cuando se lo pidamos mediante telegram | ||
| + | {{: | ||
| + | |||
| + | <sxh c> | ||
| + | /* Código original de https: // | ||
| + | Modificado por wiki.intrusos.info | ||
| + | */ | ||
| + | |||
| + | #include < | ||
| + | #include < | ||
| + | #include " | ||
| + | |||
| + | |||
| + | // Definimos los parámetros de conexión a la WIFI | ||
| + | const char *ssid = " | ||
| + | const char *pass = " | ||
| + | int status = WL_IDLE_STATUS; | ||
| + | |||
| + | // Datos del Bot de Telegram | ||
| + | String BOTtoken = " | ||
| + | String Chat_id = " | ||
| + | String Texto_enviar = ""; | ||
| + | String Texto_recibido = ""; | ||
| + | String Update_id = ""; | ||
| + | String anterior_upd = ""; | ||
| + | String Nueva_upd = ""; | ||
| + | String Respuesta = ""; | ||
| + | |||
| + | // Variables del codigo de tiempo | ||
| + | int Inicio; | ||
| + | int Termino; | ||
| + | int Intervalo = 15000; | ||
| + | unsigned long elapsed = 0; | ||
| + | unsigned long previous; | ||
| + | boolean respondio = false; | ||
| + | |||
| + | // Pin del ESP8266 al que está conectado. | ||
| + | // El GPIO 4 corresponde al D2 del ESP8266-12E NodeMCU v3 | ||
| + | #define DHTPIN 4 | ||
| + | |||
| + | // tipo de sensor DHT | ||
| + | #define DHTTYPE DHT11 // DHT 11 | ||
| + | |||
| + | // Inicializa el sensor | ||
| + | DHT dht(DHTPIN, DHTTYPE); | ||
| + | |||
| + | WiFiClientSecure client; // inicio del cliente seguro | ||
| + | IPAddress server(149, 154, 167, 200); // IP de api.telegram.org | ||
| + | |||
| + | |||
| + | void setup() { | ||
| + | |||
| + | Serial.begin(115200); | ||
| + | |||
| + | // Conecta a la WIFI | ||
| + | WiFi.begin(ssid, | ||
| + | /// } | ||
| + | |||
| + | while (WiFi.status() != WL_CONNECTED) { | ||
| + | delay(500); | ||
| + | Serial.print(" | ||
| + | } | ||
| + | Serial.println("" | ||
| + | Serial.println(" | ||
| + | Serial.println(" | ||
| + | Serial.println(WiFi.localIP()); | ||
| + | |||
| + | // Comprobamos la conexion a Telegram | ||
| + | if (client.connect(server, | ||
| + | Serial.println(" | ||
| + | } | ||
| + | // y enviamos el texto de inicio | ||
| + | Enviar_texto(" | ||
| + | |||
| + | // Comprobamos el ultimo mensaje | ||
| + | Ultimo_msg(); | ||
| + | previous = millis(); | ||
| + | |||
| + | } | ||
| + | |||
| + | |||
| + | void loop() { | ||
| + | elapse(); | ||
| + | Leer_msg(); // leemos el ultimo mensaje | ||
| + | |||
| + | // Comprobamos que haya pasado xx seg desde la ultima vez | ||
| + | if (elapsed > 500) { | ||
| + | |||
| + | anterior_upd = Update_id; // Guardamos la anterior Update | ||
| + | Ultimo_msg (); // comprobamos el ultimo mensaje | ||
| + | delay(1000); | ||
| + | Leer_msg(); // Leemos los datos | ||
| + | busca_upd_id(Respuesta); | ||
| + | busca_texto(Respuesta); | ||
| + | // Si ha cambiado la Update_id seguimos con el codigo | ||
| + | if (anterior_upd != Nueva_upd) { | ||
| + | // | ||
| + | Responder_mensaje(Texto_recibido); | ||
| + | } else { | ||
| + | } // No hacemos nada si es el mismo Upd_id | ||
| + | } | ||
| + | } // Fin Loop | ||
| + | |||
| + | |||
| + | // Orden para buscar el texto del mensaje | ||
| + | void busca_texto( String Rsp ) { | ||
| + | Texto_recibido = ""; | ||
| + | int start = Rsp.indexOf(" | ||
| + | int fin = Rsp.indexOf(" | ||
| + | Texto_recibido = (Rsp.substring(start, | ||
| + | } | ||
| + | |||
| + | //Orden para buscar la Update_id | ||
| + | void busca_upd_id( String Rsp ) { | ||
| + | anterior_upd = Update_id; // Guardamos la anterior Update_id para comprobar | ||
| + | int start = Rsp.indexOf(" | ||
| + | int fin = Rsp.indexOf(" | ||
| + | Update_id = Rsp.substring(start, | ||
| + | Nueva_upd = Rsp.substring(start, | ||
| + | } | ||
| + | |||
| + | // Orden para pedir el ultimo mensaje, vemos que se usa el Offset=-1& | ||
| + | void Ultimo_msg () { | ||
| + | if (client.connect(server, | ||
| + | // client.println(" | ||
| + | client.println(" | ||
| + | } | ||
| + | previous = millis(); // Guardamos los milisegundos para comprobar que haya pasado X tiempo entre lecturas | ||
| + | } | ||
| + | |||
| + | //Leemos el mensaje completo y lo añadimos a una variable caracter por caracter | ||
| + | void Leer_msg () { | ||
| + | Respuesta = ""; | ||
| + | while (client.available()) { // Mientras no lo lea todo seguira leyendo | ||
| + | char inChar = client.read(); | ||
| + | Respuesta += inChar; // Añadimos caracter a caracter el mensaje | ||
| + | } | ||
| + | } | ||
| + | |||
| + | //Orden para comprobar el tiempo entre lecturas | ||
| + | void elapse() { | ||
| + | elapsed = millis() - previous; | ||
| + | } | ||
| + | |||
| + | |||
| + | //Orden para enviar cualquier texto a Telegram | ||
| + | void Enviar_texto( String Texto_enviar ) { | ||
| + | if (client.connect(server, | ||
| + | client.println(" | ||
| + | } | ||
| + | } | ||
| + | |||
| + | //Aqui añadiremos las ordenes de respuesta del arduino | ||
| + | void Responder_mensaje ( String mensaje ) { | ||
| + | |||
| + | if (mensaje == " | ||
| + | Enviar_texto(" | ||
| + | respondio = true; | ||
| + | } | ||
| + | else if (mensaje == " | ||
| + | float t = dht.readTemperature(); | ||
| + | Enviar_texto(String(t) + " | ||
| + | respondio = true; | ||
| + | } | ||
| + | else if (mensaje == " | ||
| + | float h = dht.readHumidity(); | ||
| + | Enviar_texto(String(h) + " | ||
| + | respondio = true; | ||
| + | } | ||
| + | |||
| + | if (respondio == true) { // mostramos el texto que se ha entendio | ||
| + | Serial.println(" | ||
| + | } | ||
| + | else { | ||
| + | Serial.println(" | ||
| + | |||
| + | } | ||
| + | respondio = false ; // Dejamos en falso que entendio el mensaje | ||
| + | } | ||
| + | |||
| + | ////////// Fin del codigo | ||
| + | </ | ||
| ==== Referencias | ==== Referencias | ||
| + | * https:// | ||
| * https:// | * https:// | ||
| * https:// | * https:// | ||
| * https:// | * https:// | ||
| * http:// | * http:// | ||
| + | * http:// | ||