Introduction

Send temperature, humidity and movement information as WhatsApp messages to your phone every half-minute through a webhook via Twilio API.


Tags

Share

WhatsApp Notification Station

Advertisement:


read_later

Read Later



read_later

Read Later

Introduction

Send temperature, humidity and movement information as WhatsApp messages to your phone every half-minute through a webhook via Twilio API.

Tags

Share





Advertisement

Advertisement



    Components :
  • [1]NodeMCU [ESP-12E]
  • [1]DHT11 Temperature and Humidity Sensor
  • [1]HC-SR04 Ultrasonic Sensor
  • [2]Mini Breadboard
  • [1]Female/Male Jumper W.
  • [1]Male/Male Jumper W.

Description

I was working with WhatsApp Business API, provided by my Twilio account and number, to create a self-replying order bot. After achieving my ostensible goal, I contemplated using Twilio WhatsApp Helper Library to send information(data packets) from a NodeMCU to my phone as WhatsApp messages by transferring information through a webhook initially. In this way, I was able to create template messages with the data coming from NodeMCU through an HTTP Get Request to send them as WhatsApp messages via Twilio API. For subscribers of my website, I implemented a new web application named WhatsApp WebHook on Dashboard, which generates a unique webhook path using your hedron, explained below. I shared the source code of this application below if you want to use the localhost or any other link provider to create a webhook, but first, you have to download Twilio Helper Library in your directory.

I wanted to obtain three variables as WhatsApp messages in every half minute – temperature, humidity, and movement. In other words, WhatsApp Notification Station sends these three variables to the webhook to be combined as a template WhatsApp message every half minute. I used a DHT11 Temperature and Humidity Sensor to elicit temperature and humidity at the same time, and an HC-SR04 Ultrasonic Sensor to detect any movement(trespassing).

First of all, download the required libraries for Arduino IDE below to continue the following steps.

Required Libraries:

For NodeMCU boards, click here.

For DHT11 Temperature and Humidity Sensor, click here.

project-image
Figure - 27.1

Twilio for WhatsApp

To send WhatsApp messages through Twilio API, the only thing you need to do is to sign up for Twilio Trial Account.

After signing up, with your SID and Auth Token, you can use Twilio API for WhatsApp without a charge. As explained on Twilio, you need to join a shared phone number with your phone in order to initiate the API and WhatsApp template messages.

For more information and learn how to activate your account, click the link below.

Go to Twilio.

project-image
Figure - 27.2


project-image
Figure - 27.3

How to create a webhook to transmit data packets

In this project, the webhook gets information from NodeMCU through an HTTP Get Request to send it to your phone via Twilio WhatsApp API.

For subscribers of my website, I created a web application, named WhatsApp WebHook, which generates a unique webhook for each account by using their hedron provided by TheAmplituhedron(my website).

By using this web application, you can connect directly to your Twilio account to send WhatsApp messages via ESP8266, Raspberry Pi, or any other device that is compatible with the operating system.

It is just a simple webhook requiring five parameters defined below.

1) Twilio Account SID

2) Twilio Account AUTH TOKEN

3) Message Body

4) From: Dedicated Business Phone Number(Shared)

5) To: Your Verified Phone Number

Note: Normally, you would have to enter the plus sign(+) and the country code, followed by the full phone number, like this +14081234567.

But, while sending information from your device to your phone through this web application(WhatsApp WebHook), enter the number like this 14081234567 without the plus sign(+).

For more information about this application and getting an auto-generated webhook, click the link below.

Go to WhatsApp WebHook.

If you want to create a webhook for this project at localhost or any other server than TheAmplituhedron, you can copy the source code of the webhook generated by TheAmplituhedron(shared at Code down below) and alter the webhook path in the code uploaded to NodeMCU.

But, to manage that, you have to download Twilio PHP Helper Library at your directory from here.

After creating a webhook and joining a shared number, when the webhook is triggered, you can transmit data packets as WhatsApp messages from NodeMCU to your verified phone.

Even though there is no restriction for the duration, I choose to send information every half-minute.

project-image-slide project-image-slide project-image-slide
Slide




project-image-slide project-image-slide
Slide


Features

NodeMCU sends three variables – Temperature, Humidity, and Movement – to the webhook to be combined as a WhatsApp template message. And, the webhook transmits that message to your verified phone as a WhatsApp message.

1) Monitor variables and whether the message is sent through the webhook successfully or not on the serial monitor.

2) Display temperature and humidity measured by DHT11 Temperature and Humidity Sensor on WhatsApp.

"Temperature: Value" and "Humidity: Value"

3) Get notified if any movement detected by HC-SR04 Ultrasonic Sensor on WhatsApp. In other words, if someone is trespassing.

"Movement: No movement detected!" or "Someone is trespassing!"

project-image
Figure - 27.4


project-image
Figure - 27.5


project-image
Figure - 27.6

Connections

NodeMCU GPIO pin connections are well-explained at the code down below. Make connections as depicted on figures below.

I just fastened all components to an old plastic box by using a hot glue gun and connect them to NodeMCU(ESP-12E).

Note: If your HC-SR04 module generates 0 as distance, feed it with an external 5V power supply.

project-image-slide project-image-slide project-image-slide project-image-slide project-image-slide
Slide




project-image
Figure - 27.7

Videos

WhatsApp Notification Station | Demonstration

WhatsApp Notification Station | Incoming WhatsApp Messages


Code

Source Code(NodeMCU)

Download



         /////////////////////////////////////////////  
        //     WhatsApp Notification Station       //
       //             (via Twilio)                //
      //          ---------------------          //
     //             NodeMCU (ESP-12E)           //           
    //            by Kutluhan Aktar            // 
   //                                         //
  /////////////////////////////////////////////

// By only subscribing to TheAmplituhedron, you will be able get your data packets from NodeMCU, or any other device that can make an HTTP GET Request, to your phone as WhatsApp messages via Twilio through TheAmplituhedron.
// You will need a Twilio account to get WhatsApp messages automatically from the webhook.
// Then, you can use the webhook including the Twilio WhatsApp API by defining these five paranaters below.
// Note: Do not use the plus sign(+) when entering the phone numbers if you are using the webhook application or source code provied by TheAmplituhedron.
// Note: You will also need your unique hedron to connect the webhook application(WhatsApp WebHook).
// Parameters:
// 1) Twilio Account SID
// 2) Twilio Account AUTH TOKEN
// 3) Message Body
// 4) From: Dedicated Business Phone Number
// 5) To: Your Verified Phone Number
// Click the links below for more information about Twilio.
// https://www.twilio.com/whatsapp
// https://www.theamplituhedron.com/dashboard/WhatsApp-Web-Hook/
//
// As a reminder, my website has SSL protection so that you need to identify your NodeMCU connection by entering TheAmplituhedron FingerPrint or ThumbPrint.
// You can learn about it more from the link below.
// https://www.theamplituhedron.com/projects/WhatsApp-Notification-Station/
//
// In this project turorial, I decided to use an HC-SR04 Ultrasonic Sensor, and a DHT11 Temperature and Humidity as data providers.
// To detect any tresspasser trespasser, I used the ultrasonic sensor which triggers the notification message: "Someone is trespassing!"
// Every half minute, the board send a message body to the webhook that transmits it to your phone as a WhatsApp message via Twilio.
// I created a free webhook application for TheAmplituhedron subscribers and used it in this project. But, if you do not want to use this service,
// you can copy the source code from the link on the top.
//
// Connections
// NodeMCU (ESP-12E) :           
//                                DHT11 Temperature and Humidity Sensor Module
// D2  --------------------------- Data
//                                HC-SR04 Ultrasonic Sensor
// D4  --------------------------- Trig
// D5  --------------------------- Echo


// Include required libraries to send data to a website, in this case TheAmplituhedron.com.
#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

// Include DHT master library to elicit information from DHT11 Temperture and Humidity Sensor.
#include "DHT.h"

// Define DHT object.
DHT dht;

// Define your WIFI settings.
const char *ssid = "";
const char *password = "";

// Create data holders to send data packets.
String temperature, humidity;
String fingerprint, WebHook, HEDRON, id, token, message, from, to, trespass;

// Define HC-SR04 pins and measurements to detect any movement.
#define trig D4
#define echo D5
long duration, distance;

void setup() {
  // Start DHT object at digital pin 2.
  dht.setup(D2);
  
  // Initiate HC-SR04 pins.
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
 
  // Wait until connected.
  delay(1000);
  Serial.begin(115200);

  // It is just for assuring connection is alive.
  WiFi.mode(WIFI_OFF);
  delay(1000);
  // This mode allows NodeMCU to connect any WiFi directly.
  WiFi.mode(WIFI_STA);        
  // Connect NodeMCU to your WiFi.
  WiFi.begin(ssid, password);
  
  Serial.print("\n\n");
  Serial.print("Try to connect to WiFi. Please wait! ");
  Serial.print("\n\n");
  // Halt the code until connected to WiFi.
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("*");
  }
 
  // If connection is successful, turn control led(if used) on and write WiFi SSID to serial monitor along with assigned IPAddress.
  Serial.print("\n\n");
  Serial.print("-------------------------------------");
  Serial.print("\n\n");
  Serial.print("Connection is successful!");
  Serial.print("\n\n");
  Serial.print("Connected WiFi SSID : ");
  Serial.print(ssid);
  Serial.print("\n\n");
  Serial.println("Connected IPAddress : ");
  Serial.println(WiFi.localIP());
  Serial.print("\n\n"); 
}

void loop() {
  // Get tenperature and humidity from DHT11. And, detect any tresspasser.
  collectData();

  // Enter the fingerprint.
  fingerprint = "46 3c 5c 2c 67 11 cd 88 b7 e9 76 74 41 34 48 bd bc a5 b9 cf";

  // Enter your hedron provided by TheAmplituhedron, Twilio Account Information, and phone numbers.
  HEDRON = "TheAmplituhedron_Hedron";
  id= "Twilio_SID";
  token = "Twilio_Token";
  from = "14151234567"; // Enter numbers.
  to = "14081234567";

  // Create message,use %0A to start a new line.
  message = "Status:+Data+Obtained+😃+👍%0A%0ATemperature:+" + temperature + "°C%0A%0AHumidity:+" + humidity + "%%0A%0AMovement:+" + trespass + "%0A%0AWaiting...";

  // Create the webhook path.
  WebHook = "https://www.theamplituhedron.com/dashboard/WhatsApp-Web-Hook/" + HEDRON + ".php?id=" + id + "&token=" + token + "&body=" + message + "&from=" + from + "&to=" + to;
  
  // Create HTTP object to make a request.
  HTTPClient http;
  
  // Send a request. 
  http.begin(WebHook, fingerprint);
  
  int httpCode = http.GET();           
  String payload = http.getString();    
 
  if(httpCode == 200){ Serial.println("\n Message Sent Successfully..."); }else{ Serial.println("\n Not Working! Error Code: " + httpCode); }
 
  // End HTTP Get Request.
  http.end(); 
  
  // Send data packets every half minute to the webhook.
  delay(30000);
 
}

  void collectData(){
      // Wait until DHT11 Temperature and Humidity Sensor became ready.
      delay(dht.getMinimumSamplingPeriod());
      // Get temperature and humidity. 
      humidity = dht.getHumidity();
      temperature = dht.getTemperature();

      // Detect any movement by using the trigger pin.
      digitalWrite(trig, LOW);
      delay(2);
      digitalWrite(trig, HIGH);
      delay(10);
      digitalWrite(trig, HIGH);
      duration = pulseIn(echo, HIGH);
      distance = (duration / 2) / 29.1;
      if(distance < 8){ trespass = "No+movement+detected!"; }else{ trespass = "Someone+is+trespassing!"; }

      // Dump data packets.
      String data = "\n Tempature: " + temperature + "\n Humidity: " + humidity + "\n Movement: " + trespass + "\n";
      Serial.print(data);
      
    }



WebHook Source Code

Download



<?php 

require_once '/path/to/vendor/autoload.php';  
 
use Twilio\Rest\Client; 

if(isset($_GET["id"]) && isset($_GET["token"]) && isset($_GET["body"]) && isset($_GET["from"]) && isset($_GET["to"])){
	$sid    = $_GET["id"]; 
    $token  = $_GET["token"];  
    $twilio = new Client($sid, $token);
	
	$to = $_GET['to'];
	$from = $_GET['from'];
	$body = $_GET['body'];
	
	$message = $twilio->messages 
                  ->create("whatsapp:+".$to, 
                           array( 
                               "from" => "whatsapp:+".$from,       
                               "body" => $body
                           ) 
                  );
    echo 'Message Send...';				  
	
}else{
	echo "There is no request yet! Copy this link(webhook) and make an HTTP Get Request from your device.";
}

?>


Schematics

project-image
Schematic - 27.1

Downloads

Fritzing File

Download