Thursday, May 2, 2019

Getting Started with Twilio and Raspberry pi for SMS Notification

Lab 4A (Twilio)

Getting Started with Twilio and Raspberry pi for SMS Notification

objective :

In this we are going to Learn how to use Twilio API with Python and Raspberry to Send SMS when Event is Occured. Event can be When Temperature Exceeds more than Specified Value it shall send a SMS to a contact numnber.

Step 1: Create a Account on Twilio

Go to Twilio Website and Create a Accout.

In [9]:
%%html
<img src="https://res.cloudinary.com/practicaldev/image/fetch/s--I4VN8Rfx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/3tsely1znv7u92l01647.png" , width=600, height=200>

Step 2: Get Twilo Phone Number

After you have created a accout. go ahead and get a Twilio Phone Number and also we would require Twilio AUTH KEY and SSID go ahead and get the Twilio Number.

In [11]:
%%html
<img src="https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/Screen_Shot_2017-11-30_at_8.49.18_AM.width-800.png" , width=600, height=600>

After you get Twilo Number you should see a screen like this

In [12]:
%%html
<img src="https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/dashboard.width-800.png" , width=600, height=4b00>
In [13]:
%%html
<img src="https://s3.amazonaws.com/com.twilio.prod.twilio-docs/original_images/eBMxWC5Lo1przAn0FGj6X7koCAEP02GZsl8J8-FOEhAD5Mbc6nRMfw-RItPqhcNFn5zef5yYxd.png" , width=600, height=4b00>

Step 3: Download Python Library for Twilio

pip install twilio.rest if pip install didnt work for you go ahead to google and and read the doccumentaion on downloading TWILIO for Python 3 +

Step 4 : Lets Code .........

Import the library

In [ ]:
from twilio.rest import Client

Define a Function to send SMS

Make sure to use try and except Block to Avoid Errors Add you SSID and AUTH Token.

In [ ]:
def send_sms_alert():

    try:
        # Define your body
        my_body='Yo'
        # define client
        client = Client('SSID GOES HERE XXX ','AUTH TOKEN XX ')
        client.messages.create(to='+ TO XXXX ',
                               from_= '+TWILIO NUMBER XXX',
                               body=my_body)
    except:
        print('Cannot send Sms!')

Putting all Together

In [ ]:
from twilio.rest import Client


def send_sms_alert():

    try:
        # Define your body
        my_body='Yo'
        # define client
        client = Client('SSID GOES HERE XXX ','AUTH TOKEN XX ')
        client.messages.create(to='+ TO XXXX ',
                               from_= '+TWILIO NUMBER XXX',
                               body=my_body)
    except:
        print('Cannot send Sms!')

send_sms_alert()

If you have Error make sure you have entered correct SSID and AUTH key. After that Make sure you have entered correct Phone Number Make sure to senter your number in to as we are suing Trial Account wont be able to send sms to other people as its a premuim Features.

Congrulations You just sent a SMS using Python

Practical Example

objective:-

Let us send an SMS when Temparature is High than Normal

Interfacing DHT-11/ DHT-22 Sensor with Raspberry Pi

In [14]:
%%html
<img src="http://www.circuitbasics.com/wp-content/uploads/2015/12/How-to-Setup-the-DHT11-on-the-Raspberry-Pi-Three-pin-DHT11-Wiring-Diagram.png" , width=600, height=300>
In [15]:
%%html
<img src="http://www.circuitbasics.com/wp-content/uploads/2015/12/DHT11-Pinout-for-three-pin-and-four-pin-types-2.jpg" , width=600, height=300>

Please follow complete Steps on how to install the Library on following link

https://github.com/adafruit/Adafruit_Python_DHT

Installation Steps: -

Python library to read the DHT series of humidity and temperature sensors on a Raspberry Pi or Beaglebone Black. Designed specifically to work with the Adafruit DHT series sensors ----> https://www.adafruit.com/products/385 Currently the library is tested with Python 2.6, 2.7, 3.3 and 3.4. It should work with Python greater than 3.4, too Dependencies

For all platforms (Raspberry Pi and Beaglebone Black) make sure your system is able to compile and download Python extensions with pip:

On Raspbian or Beaglebone Black's Debian/Ubuntu image you can ensure your system is ready by running one or two of the following sets of commands

Python 2: sudo apt-get update sudo apt-get install python-pip sudo python -m pip install --upgrade pip setuptools wheel

Python 3: sudo apt-get update sudo apt-get install python3-pip sudo python3 -m pip install --upgrade pip setuptools wheel

Install with pip Use pip to install from PyPI.

Python 2: sudo pip install Adafruit_DHT

Python 3: sudo pip3 install Adafruit_DHT

Compile and install from the repository First download the library source code from the GitHub releases page, unzipping the archive, and execute: Python 2: cd Adafruit_Python_DHT sudo python setup.py install

Python 3: cd Adafruit_Python_DHT sudo python3 setup.py install

You may also git clone the repository if you want to test an unreleased version: git clone https://github.com/adafruit/Adafruit_Python_DHT.git

In [ ]:
import Adafruit_DHT
from twilio.rest import Client

pin = 4
sensor = Adafruit_DHT.DHT22

def main():

    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
        if humidity >34:
            print("Alert ")
            send_sms_alert(' High Temperature Alert Warning ')
    else:
        print('Failed to get reading. Try again!')
        
def send_sms_alert(text='Python'):

    try:
        # Define your body
        my_body = text
        # define client
        client = Client('SSID GOES HERE XXX ','AUTH TOKEN XX ')
        client.messages.create(to='+ TO XXXX ',
                               from_= '+TWILIO NUMBER XXX',
                               body=my_body)
    except:
        print('Cannot send Sms!')

if __name__ == "__main__":
    while True:
        main()
      

Small Application where i used Twilio

In [16]:
from IPython.display import YouTubeVideo
YouTubeVideo('lrSUts2hNlw')
Out[16]:
In [19]:
from IPython.display import YouTubeVideo
YouTubeVideo('hT4zp-mGFkE')
Out[19]:

No comments:

Post a Comment

How to Use Publish-Audit-Merge Workflow in Apache Iceberg: A Beginner’s Guide

publish How to Use Publish-Audit-Merge Workflow in Apache Iceberg: A Beginner’s Guide ¶ In [24]: from ...