ESP8266 and Telegram Bot: Home Automation
Learn more about home automation with Telegram Bot.
Join the DZone community and get the full member experience.
Join For FreeThis tutorial describes how to use ESP8266 with Telegram bot to automate tasks in your home. In more detail, we want to create a bot based on Telegram that uses an ESP8266 to control peripherals such as LEDs or to turn on or off an external device automating some home tasks. We can integrate ESP8266 and Telegram Bot in two different steps:
- Define a bot in Telegram
- Build an ESP8266 sketch that handles bot commands and controls external peripherals
Where can you use this project? There are several ways to use ESP8266 and Telegram bot, for example, to automate tasks using simple commands or to remotely control devices. For example, home automation is one of the most simple use cases where this project can be applied. We can use this project to turn on or off lights in our home or some appliances, making the first step in home automation.
During this tutorial, you will learn:
- How to connect ESP8266 to Telegram
- How to use Telegram bot library for ESP8266
- How to implement Telegram bot commands to control the ESP8266
How to Configure a Telegram Bot
In this first step, we will create and configure a Telegram bot so that we can use it to send commands to the ESP8266 once they are connected. You can use the following link to start using Telegram:
Let us start a chat with @BotFather:
Now, you can start creating a new bot using /newbot
. The video below shows how to do it:
Our Telegram bot is named ESP_IoTBot
while it has SwA_IoT_bot
as a nickname. Once you have created the bot, you will get an API token that we will use later when we will connect the ESP8266 to a Telegram bot. By now, you should have saved the API token somewhere.
ESP8266 with Firebase realtime database: IoT Controlled
ESP8266 with Firebase realtime database: IoT Controlled RGB LEDs
Connecting ESP8266 to the Telegram Bot
Now it is time to connect the ESP8266 to the Telegram bot. To do it, we will use the ESP8266-Telegrambot library. You can import it directly from the Arduino IDE using the Library Manager.
First, let's create the function to connect to the Wi-Fi:
void connect2Wifi() {
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pwd);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("\nWifi connected");
}
Where
char ssid[] = "your_ssid";
char pwd[] = "Wifi password";
Now, it is time to initialize the library that helps us to connect ESP8266 to Telegram:
#include <ESP8266TelegramBOT.h>
#define BOT_TOKEN "Token_API"
TelegramBOT bot(BOT_TOKEN, "ESP_IoTBot", "ESP_IoTBot");
void setup() {
Serial.begin(115200);
connect2Wifi();
bot.begin();
}
Remember to replace the Token_API
with the token you get when you have created your bot in Telegram. Now, we are ready to check if new messages are present.
Checking Telegram Bot Messages
To check if new messages are present, it is necessary to keep on polling, verifying if a new message is available:
uint32_t lastTime;
void checkMessages() {
uint32_t now = millis();
if (now - lastTime < 1000) {
//Serial.println("Checking new messages....");
bot.getUpdates(bot.message[0][1]);
int numNewMessages = bot.message[0][0].toInt() + 1;
for (int i = 1; i < numNewMessages; i++) {
// Get the next message
String chatId = bot.message[i][4];
String message = bot.message[i][5];
handleMessage(message, chatId);
}
}
lastTime = now;
}
The code uses getUpdates
to verify if a new message exists. Next, we start retrieving these messages. In more detail, we get the real message content and the chatId
. Finally, the code handles the message; we will see later how to do it.
Implementing the Telegram Bot Commands to Control ESP8266
How to implement the Telegram bot commands? We can do it in handleMessage
, where we will handle commands as turning on or off the LEDs. Let's add this code:
void handleMessage(String message, String chatId) {
if (message.equalsIgnoreCase("/start"))
sendMessage(handleStartCommand(), chatId);
else if (message.equalsIgnoreCase("/yel_on"))
digitalWrite(YELLOW_LED_PIN, HIGH);
else if (message.equalsIgnoreCase("/yel_off"))
digitalWrite(YELLOW_LED_PIN, LOW);
else if (message.equalsIgnoreCase("/blue_on"))
digitalWrite(BLUE_LED_PIN, HIGH);
else if (message.equalsIgnoreCase("/blue_off"))
digitalWrite(BLUE_LED_PIN, LOW);
bot.message[0][0] = "";
}
The bot handles the /start
command too. Using these commands, the bot will return all the available commands:
String handleStartCommand() {
String response = "Available commands:";
response += "Yel_on Turns on the Yellow LED\n\r";
response += "Yel_off Turns off the Blue LED\n\r";
response += "Blue_on Turns on the Blue LED\n\r";
response += "Blue_off Turns off the Blue LED\n\r";
response += "Temperature Returns the current temperature\n";
response += "Humidity Returns the current humidity\n";
return response;
}
To send a message back to the client, the bot uses the chatId
to identify the chat where to send the message. The chatId
is a parameter we obtain from the incoming message:
void sendMessage(String message, String chatId) {
Serial.println("Sending message...");
Serial.print(chatId);
Serial.print("----");
Serial.println(message);
bot.sendMessage(chatId, message, "");
}
It is time to create the sketch using ESP8266.
Home Automation Using ESP8266 and Telegram Bot
Once the code is ready, we can connect ESP8266 to the components that emulate our peripherals in our home. We can suppose we want to control some LEDs light connected to the ESP8266. To make things simple, we will use two LEDs, but you can use other components too and extend this project using other kinds of peripherals. The sketch is shown below:
The code simply turns on or two pins on ESP8266.
Summary
At the end of this tutorial, we have discovered how to integrate ESP8266 with Telegram and how to send commands to ESP8266 using a Telegram bot. We have discovered how to automate some tasks using bots. You can use this project in home automation to control remotely appliances or home lights.
Further Reading
Published at DZone with permission of Francesco Azzola, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments