Friday, January 27, 2023

Telegram messenger for IOT

 For an index to all my stories click this text

Short intro:
This story explains how I am going to send messages from Telegram to set a led on or off on an ESP8266 or ESP32.
I have been neglecting this for far to long, but now IFTTT is making things difficult for its users I was looking for another service that allowed me to send notifications to my phone.

Whatsapp would be nice cause all my friends, relatives, collegues at work and fellow board members of the Art Club (I am the treasurer) are using this. I am not particular fond of it but to stay in touch during this Corona crisis it was indispensable.

Whatsapp lacks only one very important thing: there is no direct API for us mortals. So I can not reach it through my computer. And more important I can not send or receive messages to/from it with my ESP's I could use Callmebot for sending messages to Whatsapp but alas that is no longer a free service if you use it regularly. It is cheap however (just 4 usd pro year) but hey: I am Dutch.............

In comes Telegram Messenger.

Telegram messenger is available for Android and IOS phones and tablets. Thats no different from whatsapp. But Telegram messenger is also available as a Desktop program for your windows machine or Apple. And there is a web-version. You can even run it on a Raspberry. You do need a smartphone to register, but then you can use it almost everywhere.

Telegram has been around for a while and basically offers for the average user the same as Whatsapp. You can send messages, photo's, video's and files. You can start groups and you can make voice and video calls.

Telegram has some nice extra features. You can join channels. Channels are open groups. You can find groups on Arduino, ESP32, ESP8266, Domoticz, Raspberry Pi etc. etc. etc. There is a lot of information to be found.

And the most important part is that there are ESP8266 and ESP32 libraries available.

I am going to use the AsyncTelegram library whose latest version is even capable of sending foto's to telegram. But that is for later. Let us start with sending messages from Telegram to an ESP8266 or ESP32 to set a led on or off.

Install the App.

To use Telegram Messenger on Android you need to install the app from Googles Play-store . You can find it here: https://play.google.com/store/apps/details?id=org.telegram.messenger&hl=nl&gl=US

To use Telegram messenger on an Apple iPhone install it from the App Store with this link: https://apps.apple.com/app/telegram-messenger/id686449807

Talk to the BotFather

To have Telegram Messenger communicate with your ESP we have to activate a so-called Bot. To build a bot we have to talk to the Botfather.


 

Start with pressing the looking glass on the right side of your screen and search for BotFather.



 

The BotFather greets you with the standard message.



 

To give the BotFather a command just type your text in the bottom of the screen just like wit any messenger program. To begin type /start. This will give you a list of commands.



 

Like said we need to build a Bot for communication with our ESP. The command /mybots shows that you have no bots. So let us build on. First you need to choose a name and next a username. It is the username that will show up in your contactlist so choose wise.


 

Now we have created a Bot the BotFather gives us a token. Store this somewhere safe and accessible cause you will need this to talk to your ESP.



 

If you ever need your token again just ask it from the BotFather with the command /mybots. You will get a list of your bots and click on the one you need the details from.



 

You can see that my Bot is called Myhome.



 

As you can see from the list the Bot Myhome is ready for use.
And the Telegram setup is now complete.Over to programming the ESP.

Arduino program.

We are going to start with something simple. The program that is listed here will put a simple menu on the Bot's screen. In Telegram in the Bot's screen you can then send a command to set the ESP's build-in led on or of.

This program will work on both ESP8266 and ESP32. For testing I used a Wemos D1 Esp8266 board and a DOIT ESP32 DEVKIT V1 board.



 

To use this program you will need two libraries. The first is the ArduinoJson library by Benoit Blanchon which you can install right from the Library Manager in the IDE. If you install a different version the next library probable won't work so make sure you install this one.



 

The other required library is the AsyncTelegram by Tolentino Cotesta which also can be found in the Library manager and otherwise can be downloaded from here: 

https://github.com/cotestatnt/asynctelegram

And here is the program.

/*
Name:                     Ledcommand
Library and demo Author:  Tolentino Cotesta <cotestatnt@yahoo.com>

Adapted by:               Luc Volders
                          http://lucstechblog.blogspot.com/
*/

#include <Arduino.h>
#include "AsyncTelegram.h"
AsyncTelegram myBot;

const char* ssid = "YOUR-ROUTERNAME-HERE";
const char* pass = "PASSWORD";
const char* token = "YOUR-TELEGRAM-TOKEN-HERE";    

int led = LED_BUILTIN; 

void setup() 
{
  // initialize the Serial
  Serial.begin(115200);
  Serial.println("Starting TelegramBot...");

  WiFi.setAutoConnect(true);   
  WiFi.mode(WIFI_STA);
  
  WiFi.begin(ssid, pass);
  delay(500);
  while (WiFi.status() != WL_CONNECTED) 
  {
  Serial.print('.');
  delay(500);
  }

  myBot.setUpdateTime(1000);
  myBot.setTelegramToken(token);
  
  Serial.print("\nTest Telegram connection... ");
  myBot.begin() ? Serial.println("OK") : Serial.println("NOK");

  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH); 
}

void loop() 
{
  TBMessage msg;

  if (myBot.getNewMessage(msg)) 
  {
    if (msg.text.equalsIgnoreCase("Lon")) 
    {      
      digitalWrite(led, LOW);                          
      myBot.sendMessage(msg, "Light is now ON");        
    }
    else if (msg.text.equalsIgnoreCase("Loff")) 
    {       
      digitalWrite(led, HIGH);                         
      myBot.sendMessage(msg, "Light is now OFF");      
    }
    else 
    {                                                  
      // generate the message for the sender
      String reply;
      reply = "Welcome ESP8266 number 1\n" ;
      reply += "You can use these commands :\n" ;
      reply += "============================\n\n" ;
      //reply += msg.sender.username;
      reply += ". Mancave Light on = Lon\n";
      reply += ". Mancave Light off = Loff\n";
      myBot.sendMessage(msg, reply);
    }
  } 
}

 

I will highlight some parts here.

const char* ssid = "YOUR-ROUTERNAME-HERE";
const char* pass = "PASSWORD";
const char* token = "YOUR-TELEGRAM-TOKEN-HERE";    

Obvious but put your credentails in here. This is the part where you need to put in the Telegram token which you got earlier from the BotFather.

In the setup() you can find the following line:

myBot.begin() ? Serial.println("OK") : Serial.println("NOK");

This is a special language construction which is the same as an if-then statement.

if myBot.begin() is true then Serial.println("OK")
else Serial.println("NOK")


This kind of stetement is often used in Javascript. It is called a ternary operator. You do not see this often in Arduino programs.
 

TBMessage msg;

if (myBot.getNewMessage(msg))


In the loop() a new variable is created called msg, and then the program checks wether the Bot has send a message.

if (msg.text.equalsIgnoreCase("Lon"))

Here we check wether the text "Lon" is received. I check for "Lon"as I am a lazy typer. But alter this to your own liking.
The good part is that here also is a statement that you do not see often in Arduino programs: equalsIgnoreCase This is a nice feature that allows you to lype Lon, LON, lon, lOn or any other combination.

On my android phone the first word I type is always with a capital letter. On my PC a capital is only typed when you push shift at the same time. So this makes that I dont have to think when on my PC or Android Phone.

{      
  digitalWrite(led, LOW);                          
  myBot.sendMessage(msg, "Light is now ON");        
}


The led is set ON because LOW is the ON value for the build-in led. And a message is send back to the Telegram Bot that confirms that the action succeeded.

// generate the message for the sender
String reply;
reply = "Welcome ESP8266 number 1\n" ;
reply += "You can use these commands :\n" ;
reply += "============================\n\n" ;
//reply += msg.sender.username;
reply += ". Mancave Light on = Lon\n";
reply += ". Mancave Light off = Loff\n";
myBot.sendMessage(msg, reply);

This part generates the menu for Telegram Messenger. You can put any text in what you like. I use it to show the commands that my ESP listens to.

The \n code at the end of each line makes each line of the text being printed on a new line.

Back to Telegram Messenger

Make sure the ESP is up and running and connected to your router. Look in the Serial Monitor to see if the connection with Telegram has been made.

Now switch over to your phones screen and open the communication screen with your Bot.



Start with typing /start and you can see the start menu you created in the ESP's program. You can use this command at any time if you forgotten which commands to send to the ESP.

Then just type lon (or Lon or LON etc) and the led on the ESP will go on. Type loff and it will go off again. Each time you will get a message back from the ESP to verify that the command has been issued and accepted by the ESP.

Nice !!!

The answer is YES

Telegram is not only great as a messaging system and a very good replacement for Whatsapp but it also is a good companion for your home automation. Now if I just could get all my friends and relatives to switch over.......

The next steps

I have done a lot with Telegram Messenger lately. The next part in this series shows how you can send sensor readings to Telegram Messenger. Then we have a two way communication: sending commands to the ESP and getting readings from the ESP.

And off course I am going to show you how to send notifications from your ESP to Telegram Messenger. Then we can dump IFTTT.

I'll show you how to test things with the web-app so you do not have to type everything on your phone. Programming the ESP is done on your PC and it is nice to have a screen with Telegram Messenger open on that same PC.

My home automation system Domoticz can send notifications to Telegram Messenger. But I can not send messages from Telegram Messager to Domitcz. I have a fair idea on how to do that. An upcoming story will cover that.

My 3D printer is controlled by Octoprint. I am checking on how to send commands from Octoprint to Telegram. Keep tuned.

That's it for now. Something great to play with !!
Have fun, till next time

Luc Volders