TELEBOT (Remotely Control and Monitor Your Home)

In this Instructable I'am going to tell you about how to make a complete “HOME AUTOMATION” package using some basic Electronic controllers and some Open source software.

This Project will go this way:

  • We will use Raspberry Pi as a Hub for smart home devices.
  • This Hub will be guided by the instructions received from an (Android, Ios, or Windows) device with “Telegram” installed in it.
  • The hub will then communicate Over The Air with the NodeMcu.
  • The NodeMcu will then send these signals to Relays and IR sensors according to the assigned GPIOs in the code.

TELEBOT (Remotely Control and Monitor Your Home)

The Relays here will help control the switches while the IR sensor will be used to control the TV.

Also this package includes a security feature named as “CamShot” which will click photos for you whenever a signal is send to it.

So let's get started 🙂

Step 1: Components,Tools,Services

Components,Tools,Services

Components:

  • Raspberry Pi Zero W / Raspberry Pi 3/2/1
  • Node MCU / ( Arduino + ESP8266 )
  • IR Emitter
  • Pi Camera (Pi Cam Module)
  • DHT Sensor (temperature sensor)
  • Relay Board ( Each for 1 Client )
  • Connecting Wires
  • Plastic Box (As a Case)
  • Li-Po Battery
  • Power Bank
  • Battery Adapter
  • Jumpers
  • Android / iOS / Windows Device with Telegram

Tools:

  • Cutter
  • Glue Gun
  • Knife
  • Solder Wire
  • Soldiering Iron

Software:

  • Raspbian
  • Node.js
  • Arduino IDE
  • Telegram API
  • Telegram App (Any Device)

Step 2: Install Telegram on Your Phone or Open Web Telegram

Install Telegram on Your Phone or Open Web Telegram

Go to App Store (iPhone) or Play Store (Android), download and install Telegram on your phone or Open this link here

Here we are using Telegram as a “Chat Bot” to give instructions to Raspberry Pi based on the control actions we want.

Now, you can use Telegram but not yet for the Raspberry Pi. Telegram reserves a special kind of accounts for machines, called bot accounts. As the owner of your own Pi, you have to obtain a bot account for it. So in the next step we will learn how to get your own Bot on telegram.

Step 3: Creating a Telegram BOT :

Creating a Telegram BOT
  1. Go to the Telegram app on you'r phone.
  2. Search for the “botfather” telegram bot (he’s the one that’ll assist you with creating and managing your bot).
  3. Type /help to see all the possible commands the botfather can handle.
  4. Click on or type /newbot to create a new bot.
  5. Follow instructions and make a new name for your bot.
  6. At the end when you are finished with creating the bot the bot father will give you a TOKEN.
  7. This token will be used to access the HTTP API. In this project we will mention this token in the code for raspberry pi.

Refer the pictures for better understanding 🙂

Step 4: Installing Raspbian OS on Raspberry Pi :

Installing Raspbian OS on Raspberry Pi

Steps:

  1. Downloading Raspbian and Image Writer:
  • Download the latest version of Raspbian here.
  • You can Download it via torrents or directly.
  • Now to write the downloaded OS into the SD card you will be needing a image writer. so download “win32 disk imager” here

2. Writing the image:

  • Insert the SD card into laptop/pc and run the image writer.
  • Open the Image Writer and browse for the downloaded Raspbian Image.
  • Now select the particular derive which represents the SD card. If the derive selected is incorrect than that derive may get corrupted. So be careful here.
  • Now after this click on the “write” button present at the bottom.
  • Once the OS get written on the SD card eject it and insert it in the Raspberry Pi and turn it on. It should start booting up.3. Setting up Pi:
  • Please remember that after booting up there might be some situations where the user credentials are required. Raspberry Pi comes with default username's “login” & “password”.
login: pi<br>password: raspberry
  • Now when the pi is booted for the first time, a configuration screen called “Setup Options” should appear.
  • Don't worry if you have missed this, you can still get it by typing the following command in the terminal.
sudo raspi-config<br>
  • Now that the Setup Options windows is up, we will have to set up few things. After completing each step if it asks to reboot the pi than please do so. After rebooting if you don't get the Setup option then follow the above step to get the setup option screen.a.) First thing to do : Click on the first option that is “Expand Files” and Enter. We do this to make use of full space available on the SD card as a full partition. It will expand the OS to fit in the total space available in the SD card which can than be used as a memory storage for the pi.

    b.) Second thing to do : Select the third option ” Enable boot to desktop/scratch” and enter. It will take you to another window called the “choose boot option” window. Now select the option of ” Desktop Log in as user ‘pi' at the graphical desktop and hit the enter button.Once done you will be taken back to the Setup Option window and if not then click the “ok” button present at the bottom and it will get back to the previous window.

  • Once both the steps are done, click the finish button at the bottom and then it should start rebooting automatically. If not then enter the following command in the terminal to reboot
sudo reboot
  • After the reboot from the previous stage if everything went right, you will end up on the desktop.

Once you are on the desktop, open the terminal and enter the the following command to update the firmware of the pi.

sudo rpi-update

4. conclusion:

  • So we have covered the steps to get the raspberry pi up and running.

Step 5: Installing Required Libraries to Program NodeMcu :

Installing Required Libraries to Program NodeMcu

Steps:

  1. Open the Arduino IDE first.
  2. Click on the files>prefrence.
  3. Now copy the following link in the boards managerhttp://arduino.esp8266.com/stable/package_esp8266com_index.json
  4. Click OK to close the preference tab.
  5. After completing the above steps go to Tools > Boards and then select the board manager.
  6. Navigate to esp8266 by esp8266 community and install the software for Arduino.
  7. Once all the above steps are completed we are ready to program our NodeMcu.

Step 6: Configure Your Router for Static IP Allocation to Node MCU's

Configure Your Router for Static IP Allocation to Node MCU's

To Communicate between Raspberry Pi and Node MCU we need a static IP For each NodeMcu. So Raspberry Pi can send HTTP Request to Each Module.

For that Purpose we need to configure the Router that every time any of the one Node MCU will connect to it will assign it a pre defined IP.

  1. Go to Your Router's Log In Page.
  2. Enter Your User ID and Password Details
  3. Now go to DHCP Client List and Note Down Mac Address of Each Node MCU.
  4. It will looks like image shown above.
  5. Now go to Static Assignment Option
  6. There Enter the the MAC Address and the IP You want to assign it.
  7. Now Save the settings and restart the router
  8. Note Down Both IP's which will be required in code of Raspberry Pi.

Step 7: Connecting Pi-Cam to Raspberry Pi and Required Module

Connecting Pi-Cam to Raspberry Pi and Required Module

irstly connect the pi-cam with Raspberry pi 0 using the connector cable.

Now if you are using raspberry 3 than connect the pi-cam directly with the connector which comes with it.

But if you are using Raspberry pi 0 than you will be needing a special type of connector.

Go to the raspberry pi configuration and enable camera.

Now type this command in the terminal:

npm install raspicam

Step 8: BOT CODE for Pi :

const TOKEN = process.env.TELEGRAM_TOKEN || ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const TelegramBot = require(‘node-telegram-bot-api');
const Raspistill = require(‘node-raspistill').Raspistill;
const raspistill = new Raspistill({
fileName: ‘image',
encoding: ‘jpg',
width: 640,
height: 480
});

var request = require(‘request');
const options = {
polling: true
};
const bot = new TelegramBot(TOKEN, options);
var authorized_users = [
XXXXXXXXX, //Your User Id Here
XXXXXXXXX,
XXXXXXXXX
];
const opts = {
reply_markup: JSON.stringify({
keyboard: [
[‘/switch1_on','/switch1_off'],
[‘/switch2_on','/switch2_off'],
[‘/switch3_on','/switch3_off'],
[‘/switch4_on','/switch4_off'],
[‘/switch5_on','/switch5_off'],
[‘/switch6_on','/switch6_off'],
[‘/switch7_on','/switch7_off'],
[‘/switch8_on','/switch8_off'],
[‘/all_switchon','/all_switchoff'],
[‘/hum','/temp','/getouts'],
[‘/power','/mute'],
[‘/ch_0′,'/ch_1'],
[‘/ch_2′,'/ch_3'],
[‘/ch_4′,'/ch_5'],
[‘/ch_6′,'/ch_7'],
[‘/ch_8′,'/ch_9'],
[‘/tv'],
[‘/ch_up','/ch_down'],
[‘/vol_up','/vol_down'],
[‘/camshot']
]
})
};

console.log(“BOT ready!”);

bot.onText(/\/switch1_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r1on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 1', opts);
});

bot.onText(/\/switch1_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r1off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 1', opts);
});
});

bot.onText(/\/switch2_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r2on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 2', opts);
});

bot.onText(/\/switch2_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r2off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 2', opts);
console.log(body);
});
});

bot.onText(/\/switch3_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r3on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 3', opts);
});

bot.onText(/\/switch3_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r3off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 3', opts);
console.log(body);
});
});

bot.onText(/\/switch4_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r4on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 4', opts);
});

bot.onText(/\/switch4_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r4off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 4', opts);
});
});

bot.onText(/\/switch5_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r5on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 5', opts);
});

bot.onText(/\/switch5_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r5off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 5', opts);
});
});

bot.onText(/\/switch6_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r6on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 6', opts);
});

bot.onText(/\/switch6_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r6off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 6', opts);
});
});

bot.onText(/\/switch7_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r7on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 7', opts);
});

bot.onText(/\/switch7_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r7off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 7', opts);
});
});

bot.onText(/\/switch8_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r8on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 8', opts);
});

bot.onText(/\/switch8_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r8off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 8', opts);
});
});

bot.onText(/\/switch9_on/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r9on', function (error, response, body) {
});
bot.sendMessage(msg.chat.id, ‘Switched on Relay 8', opts);
});

bot.onText(/\/switch9_off/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/r9off', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off Relay 8', opts);
});
});

bot.onText(/\/all_switchon/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/allon', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched on All Relays', opts);
});
});

bot.onText(/\/all_switchoff/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.106/alloff', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Switched off All Relays', opts);
});
});

bot.onText(/\/ch_1/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s1', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 1', opts);
});
});

bot.onText(/\/ch_2/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s2', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 2', opts);
});
});

bot.onText(/\/ch_3/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s3', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 3', opts);
});
});

bot.onText(/\/ch_4/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s4', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 4', opts);
});
});

bot.onText(/\/ch_5/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s5', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 5', opts);
});
});

bot.onText(/\/ch_6/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s6', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 6', opts);
});
});

bot.onText(/\/ch_7/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s7', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 7', opts);
});
});

bot.onText(/\/ch_8/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s8', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 8', opts);
});
});

bot.onText(/\/ch_9/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s9', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 9', opts);
});
});

bot.onText(/\/ch_0/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/s0', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Ch 0', opts);
});
});

bot.onText(/\/power/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/power', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Power Is Pressed', opts);
});
});

bot.onText(/\/mute/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/mute', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Mute', opts);
});
});

bot.onText(/\/ch_up/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/pup', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Channel Up', opts);
});
});

bot.onText(/\/ch_down/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/pdown', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Channel Down', opts);
});
});

bot.onText(/\/vol_up/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/vup', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Volume Up', opts);
});
});

bot.onText(/\/vol_down/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/vdown', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘Volume Down', opts);
});
});

bot.onText(/\/tv/, function onLoveText(msg) {
if(!isAuthorized(msg.from.id)) return;
request(‘http://192.168.1.104/tv', function (error, response, body) {
bot.sendMessage(msg.chat.id, ‘TV is Pressed', opts);
});
});

bot.onText(/\/camshot/, function onPhotoText(msg) {
if(!isAuthorized(msg.from.id)) return;
// From file path
raspistill.takePhoto()
.then((photo) => {
console.log(‘took photo', photo);
var dirname = ‘/home/pi/Desktop';
const photo = ‘/home/pi/Desktop/image.jpg';
bot.sendPhoto(msg.chat.id, photo, {
caption: “Shot From Your Home”
},opts);
})
.catch((error) => {
console.error(‘something bad happened', error);
});

});
bot.onText(/\/start/, function onPhotoText(msg) {
// From file path
bot.sendMessage(msg.chat.id, ‘Your User Id is ‘+ msg.chat.id +”, opts);

});

function isAuthorized(userid) {
for(i = 0; i < authorized_users.length; i++)
if(authorized_users[i ] == userid) return true;
return false;
}

Step 9: Notes for Bot Code and Testing It.

Notes for Bot Code and Testing It

This Bot Code is Written in node.js, So in your Raspberry Pi You Must Have Installed npm and Node.js.

First download this libraries to make this code run.

1. node-telegram-bot-api (Library For Telegram Bot API)

to install run this command into command prompt.

 npm install node-telegram-bot-api
2. node-raspistill (Library For Pi Camera )

to install run this command into command prompt.

npm install node-raspistill

Now All the libraries are set to Run the Code.

  • Now time to edit the main code file.

Code Deploy in Raspberry Pi :

  1. Go to the location where you want to place the code in the Pi. (Most Commonly Desktop)
  2. Now Create a New file there and name it App.js
  3. Then Edit this file with Text Editor and Paste the code.
  4. Then Change the API Token :
    The token which we had received from Bot Father is now have to used here.Copy that token from bot father and replace XXXXXX in the first line of the code with it.
  5. Now we have to get the User ID which can access the bot. ( Non Authorized Can't Control Your Home ).
  6. So to get the User ID of Your Phone You have to message start to the Telegram Bot.
  7. So First go to Command Prompt and typenode App.js
  8. So Now Your Bot is working.
  9. Now go to Your Phone or Laptop and open telegram app and send Start to the Bot.
  10. The if Your Bot is working Properly you will receive your User ID.
  11. Now Copy Paste This User ID in the Code.
const bot = new TelegramBot(TOKEN, options);

var authorized_users = [
	XXXXXXXXX, //Your User Id Here
	XXXXXXXXX,
	XXXXXXXXX 
];

12. Here Replace XXXX with the User ID You have received.
13. Now Restart the Code via Pressing ” CTRL + C ” and then Again ” node App.js “.

Hurray Your Bot is Working.. 🙂

Now time for Commands :

As You can See Every time user sent message to bot via bot.ontext method we detect the message and do the preferred actions.

<p>bot.onText(/\/switch1_on/, function onLoveText(msg) {

if(!isAuthorized(msg.from.id)) return;
  request('http://192.168.1.106/r1on', function (error, response, body) {
    });
  bot.sendMessage(msg.chat.id, 'Switched on Relay 1', opts);
});

Like for the given example we checked that if the message received from User is switch1_on then it will check wheter this user is authorized or not and then finally do the action by sending HTTP Request to Nod MCU on it's specific IP Address.

So if You Want to Add Your Own Cases You can add.. 🙂

(Note : After Adding the new case in Main Code add the Appropriate action for the same HTTP Request in your Node MCU Code.)

Configuring Inline Keyboard and Special Commands

We had done adding Cases for specific inputs from User. Now As you can to turn the light on or off every time you have to message specific input like /switch1_on.

But this is not convenient at all for daily use.

  • So For Your Regular Use You can set a special Keyboard For Your Bot Using Telegram API.

You don't have to do much for this, just change the switched in below code and restart the bot.and the next time bot will show the keyboard in new order and with new Switches.

<p>const opts = {

    reply_markup: JSON.stringify({
      keyboard: [
        ['/switch1_on','/switch1_off'],
        ['/switch2_on','/switch2_off'],
        ['/switch3_on','/switch3_off'],
        ['/switch4_on','/switch4_off'],
	['/switch5_on','/switch5_off'],
	['/switch6_on','/switch6_off'],
	['/switch7_on','/switch7_off'],
	['/switch8_on','/switch8_off'],
        ['/all_switchon','/all_switchoff'],
        ['/hum','/temp','/getouts'],
	['/power','/mute'],
        ['/ch_0','/ch_1'],
        ['/ch_2','/ch_3'],
        ['/ch_4','/ch_5'],
	['/ch_6','/ch_7'],
	['/ch_8','/ch_9'],
	['/tv'],
	['/ch_up','/ch_down'],
	['/vol_up','/vol_down'],
        ['/camshot']
 ]
    })
  };

As You can see by setting this opt constant you can set the Inline keyboard.

Now Specific Commands :

  • If You don't want to mess up with the code and just want to set some specific shortcuts you can set it by Using BotFather.
  1. Now Just Go to Botfather and type /mybots.
  2. Then Botfather will send you list of all your bots.
  3. Reply with the bot you want to edit.
  4. Now Select Edit Bot Option.
  5. Then Click Edit Commands.
  6. Now it will ask for all your commands.
  7. Just Reply with all your commands with Description as shown.
  8. All Done. Now Restart Your Telegram App.
  9. Go to Your Bot's chat and type ” / ” (Without “”), You can see all your commands that you set.Finally We made it convenient to use.

Step 11: Controlling Relays With NodeMCU:

Controlling Relays With NodeMCU

Connections:

The Vin and Vcc of the 8 channel relay board are connected with the positive and negative terminal of the bread board power supply.

Also to power the NodeMcu the other pair of supplies of power supply is connected with the ground and vcc.

the positive terminal all the relays are connect with D0 to D7 pins and the negative terminal is provided a common ground.

And Check Out The video How it Works…

Step 12: CODE for Relay Module:

#include <ESP8266WiFi.h>
WiFiClient client;
WiFiServer server(80);
const char* ssid = "username";
const char* password = "password";
String  command =""; // Command received from Android device

// Set Relay Pins
int relay1 = 16;
int relay2 = 5;
int relay3 = 4;
int relay4 = 0;
int relay5 = 2;
int relay6 = 14;
int relay7 = 12;
int relay8 = 13;

void setup()
{
  Serial.begin(115200);

  pinMode(relay1, OUTPUT); 
  pinMode(relay2, OUTPUT);  
  pinMode(relay3, OUTPUT);  
  pinMode(relay4, OUTPUT);  
  pinMode(relay5, OUTPUT); 
  pinMode(relay6, OUTPUT);  
  pinMode(relay7, OUTPUT);  
  pinMode(relay8, OUTPUT);  
  digitalWrite(relay1,LOW);
  digitalWrite(relay2,LOW);
  digitalWrite(relay3,LOW);
  digitalWrite(relay4,LOW);
  digitalWrite(relay5,LOW);
  digitalWrite(relay6,LOW);
  digitalWrite(relay7,LOW);
  digitalWrite(relay8,LOW);
      
  connectWiFi();
  server.begin();
}

void loop()
{
    client = server.available();
    if (!client) return; 
    command = checkClient ();

         if (command == "r1on"  )     digitalWrite(relay1,LOW);
    else if (command == "r1off" )     digitalWrite(relay1,HIGH);
    else if (command == "r2on"  )     digitalWrite(relay2,LOW);     
    else if (command == "r2off" )     digitalWrite(relay2,HIGH);
    else if (command == "r3on"  )     digitalWrite(relay3,LOW);
    else if (command == "r3off" )     digitalWrite(relay3,HIGH);
    else if (command == "r4on"  )     digitalWrite(relay4,LOW);
    else if (command == "r4off" )     digitalWrite(relay4,HIGH);
    else if (command == "r5on"  )     digitalWrite(relay5,LOW);
    else if (command == "r5off" )     digitalWrite(relay5,HIGH);
    else if (command == "r6on"  )     digitalWrite(relay6,LOW);
    else if (command == "r6off" )     digitalWrite(relay6,HIGH);
    else if (command == "r7on"  )     digitalWrite(relay7,LOW);
    else if (command == "r7off" )     digitalWrite(relay7,HIGH);
    else if (command == "r8on"  )     digitalWrite(relay8,LOW);
    else if (command == "r8off" )     digitalWrite(relay8,HIGH);
    else if (command == "alloff") 
    {
      digitalWrite(relay1,HIGH);
      digitalWrite(relay2,HIGH);
      digitalWrite(relay3,HIGH);
      digitalWrite(relay4,HIGH);
      digitalWrite(relay5,HIGH);
      digitalWrite(relay6,HIGH);
      digitalWrite(relay7,HIGH);
      digitalWrite(relay8,HIGH);
    }
    else if (command == "allon") 
    {
      digitalWrite(relay1,LOW);
      digitalWrite(relay2,LOW);
      digitalWrite(relay3,LOW);
      digitalWrite(relay4,LOW);
      digitalWrite(relay5,LOW);
      digitalWrite(relay6,LOW);
      digitalWrite(relay7,LOW);
      digitalWrite(relay8,LOW);
    }
    sendBackEcho(command); // send command echo back to android device
    command = "";
}

/* connecting WiFi */
void connectWiFi()
{
  Serial.println("Connecting to WIFI");
  WiFi.begin(ssid, password);
  while ((!(WiFi.status() == WL_CONNECTED)))
  {
    delay(300);
    Serial.print("..");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("NodeMCU Local IP is : ");
  Serial.print((WiFi.localIP()));
}

/* check command received from Pi */
String checkClient (void)
{
  while(!client.available()) delay(1); 
  String request = client.readStringUntil('\r');
  request.remove(0, 5);
  request.remove(request.length()-9,9);
  return request;
}

/* send command echo back to Pi */
void sendBackEcho(String echo)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println(echo);
  client.stop();
  delay(1);
}

Step 13: Relay Module Code Changes and Explanation

 

As Earlier we had configured the Raspberry Pi App Code to Send Request to All Node MCU According to User Input in Telegram App.

Now when that request came to Relay Module Containing Node MCU, So in this code we have to define the GPIO action to turn it on or off according to Pi's HTTP Request.

  1. First we have to download ESP8266 Library and then will upload this code to raspberry pi.
  2. Download it from Here : Click Here to Download
  3. Now Add this Library to Arduino IDE and then Open New File.
  4. Paste the Code from Last Step

Here First You have to change SSID and Password according to your Router's Credentials .

const char* ssid = "Your SSID";
const char* password = "Your Password";

5. Define Relay Pins. (Define All Your Relays in Your Order)

6. This Code Constantly Checks for HTTP Request and pass it to command.

7. Everytime any command received check it using nested if else and do proper action

if (command == "r1on"  )     digitalWrite(relay1,HIGH);
//means on receiving r1on it will up the GPIO and relay will be on.

8. Time to Upload it on the Node MCU.(Don't Forget to Download Board Manager for Node MCU as Mentioned Before. )

First Node MCU For Relay Module Done.

Step 14: Controlling IR With NodeMcu:

https://youtu.be/Ourvv-guExw

Connections:

The positive terminal of the LED is connected with D3 pin.

And the negative terminal is connected to the ground

This is IR Emiiter Which Emits the IR Singals which are used to Control Appliances which uses IR Module.

So by sending particular code to the IR LED we can control the Appliances. In this example we have showed that how you can distantly switch on and off your tv and also showed some other common features like switching over to other channels and volume options.

Step 15: CODE for IR Module:

#include <IRremoteESP8266.h>
#include <ESP8266WiFi.h>
#include <IRsend.h>
WiFiClient client;
WiFiServer server(80);
const char* ssid = "user";
const char* password = "password";
String  command =""; // Command received from Android device

IRsend irsend(0); //an IR led is connected to GPIO pin 0

void setup()
{
  irsend.begin();
  Serial.begin(9600);
  connectWiFi();
  server.begin();
}

void loop() {

  client = server.available();
    if (!client) return; 
    command = checkClient ();
// Check Which Command is received and Do Action According to It.
         if (command == "power")  irsend.sendSony(0xA90, 12, 2);
    else if (command == "s1")     irsend.sendSony(0x10, 12, 2);
    else if (command == "s2")     irsend.sendSony(0x810, 12, 2);
    else if (command == "s3")     irsend.sendSony(0x410, 12, 2);
    else if (command == "s4")     irsend.sendSony(0xc10, 12, 2);
    else if (command == "s5")     irsend.sendSony(0x210, 12, 2);
    else if (command == "s6")     irsend.sendSony(0xa10, 12, 2);
    else if (command == "s7")     irsend.sendSony(0x610, 12, 2);
    else if (command == "s8")     irsend.sendSony(0xe10, 12, 2);
    else if (command == "s9")     irsend.sendSony(0x110, 12, 2);
    else if (command == "s0")     irsend.sendSony(0x910, 12, 2);
    else if (command == "vup")    irsend.sendSony(0x490, 12, 2);
    else if (command == "vdown")  irsend.sendSony(0xc90, 12, 2);
    else if (command == "pup")    irsend.sendSony(0x90, 12, 2);
    else if (command == "pdown")  irsend.sendSony(0x890, 12, 2);
    else if (command == "tv")     irsend.sendSony(0xA50, 12, 2);
    else if (command == "mute")   irsend.sendSony(0x290, 12, 2);
    sendBackEcho(command); // send command echo back to android device
    command = "";
    Serial.println(command);
   
}

/* connecting WiFi */
void connectWiFi()
{
  Serial.println("Connecting to WIFI");
  WiFi.begin(ssid, password);
  while ((!(WiFi.status() == WL_CONNECTED)))
  {
    delay(300);
    Serial.print("..");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("NodeMCU Local IP is : ");
  Serial.print((WiFi.localIP()));
}

/* check command received from Android Device */
String checkClient (void)
{
  while(!client.available()) delay(1); 
  String request = client.readStringUntil('\r');
  request.remove(0, 5);
  request.remove(request.length()-9,9);
  return request;
}

/* send command echo back to Raspberry Pi */
void sendBackEcho(String echo)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println(echo);
  client.stop();
  delay(1);

}<br>

Step 16: IR Module Code Changes and Explanation

This Module Code is also similar to the Relay Module Code. But there is a slight change because in this Module we are using and IR Sensor. So as the command will be received from Pi it will send appropriate signal to IR Sensor using Digital Pin.

  1. First We Have to Add IRremoteESP8266 Library.
  2. Download the library from this link : Click Here to Download
  3. Include this into Arduino IDE.
  4. Now Paste the code from Last Step to Arduino IDE.
  5. Here You Also have to change the SSID and Password.
const char* ssid = "Your SSID";
const char* password = "Your Password"

6. Here Also the Module will listen for HTTP Request from Pi and Do Appropriate action.
7. Like for Power Command it will send 0xA90 to the IR and for s1 it will send 0x10.
8.So if you want to add more function just add more case in if else statement.

     if (command == "power")  irsend.sendSony(0xA90, 12, 2);
else if (command == "s1")     irsend.sendSony(0x10, 12, 2);

9. If You Do Have Sony TV You Don't have to do anything. Just Upload the code and Enjoy 🙂
10. But if You have any other TV You Have to Change the Code. Replace irsend.sendSony with your TV Company name.
11. And you also have to change the IR Codes Placed in the function. ex. 0xA90 For Power in Sony

12. You can find this codes online for any TV. Just Search for “IR Codes Samsung” or any company name.

Done Your IR Module is set up

Step 17: CamShot (security First…)

CamShot (security First...)

So its a feature which will help you get pictures of your home when you aren't present at your home.

Let see how it works:

  • you just have to leave a message using your “telebot”.
  • And the bot will respond with the pictures clicked from the very angle you kept it.
  • So that's how you can have a watch 24*7 🙂

Actually due to security concerns we hadn't shown images from proper angle but you can change the angle as your home situation.

Source: TELEBOT (Remotely Control and Monitor Your Home)


About The Author

Muhammad Bilal

I am highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Scroll to Top