Controlando dispositivos IoT por meio de e-mails sobre protocolo IMAP – IOT Parte 48

Controlling IoT devices through emails over IMAP protocol – IOT Part 48

In the previous tutorial, it was mentioned that IMAP protocol is a standard email protocol used to store email messages and retrieve them. It was also mentioned that the IMAP protocol can be used in IoT applications where commands can be passed to IoT devices via email. This can be very useful in certain situations, such as when security may be the main concern. Furthermore, emails can be sent over any network without any special application or permission. IoT devices can receive emails as email clients, where they can read emails and process the information contained in them.
In this project, a Raspberry Pi is used as an IoT device that acts as an email client. The Raspberry Pi is interfaced with an LED that is controlled by sending emails to the Pi. The Pi receives emails via the IoT network (internet) and controls the LED according to the data received in the body of the email. It interprets the email body only when the email subject matches a predetermined name. Emails to pass LED control commands can be sent from any device such as Laptop, PC, Tablet or Smart Phone. The Raspberry Pi receives these emails via the Internet Message Access Protocol (IMAP).
Required components –
1) Raspberry Pi 3
2) LED
3) 1KΩ resistor
4) Jumper wires
Required software –
1) Raspbian OS
2) Leafpad/GNU Nano/Python 3 IDLE (for writing python scripts)
Block diagram –
Diagrama de blocos do cliente de e-mail Raspberry Pi IoT IMAP
Figure 1: Block diagram of the Raspberry Pi IoT IMAP email client
Circuit Connections –
A simple IOT device is designed in this project. It has an LED connected to the Raspberry Pi 3. The device is designed by assembling the following components.
Raspberry Pi 3 – Raspberry Pi 3 is the third generation Raspberry Pi. It's a miniature marvel, packing considerable computing power into a space no bigger than a credit card. The Raspberry Pi system's central processor is a Broadcom BCM2837 system-on-chip (SoC) that houses a 1.2 GHz Quad Core ARM Cortex-A53 processor. The vast majority of the system's components, including its central and graphics processing units, along with the audio and communications hardware are built into this single component, along with the 1GB LPDDR2 memory chip at the center of the board. It's not just this SoC design that makes the BCM2837 different from the processor found in a typical desktop or laptop; however, it also uses a different instruction set architecture (ISA) known as ARM.
The Pi comes equipped with an integrated 10/100 BaseT Ethernet socket, composite HDMI and RCA port for video, 3.5mm audio output jack, 15-pin MIPI camera serial interface (CSI-2), display serial interface , Bluetooth 4.1, 802.11 b/g/n Wireless LAN, Micro SDIO to Micro SD card, 4 USB 2.0 connectors, 40-pin connector containing 27 GPIO pins and Micro USB socket for power supply.
The Raspberry Pi is a single-board computer designed to run an operating system called GNU/Linux Raspbian. Hereinafter referred to simply as Linux. Unlike Windows or OS X, Linux is open source, so you can download the source code for the entire operating system and make any changes you want. The Raspberry Pi 3 can also run Windows 10 IoT and many other embedded operating systems, many of which are derived from Linux. The operating system must be loaded onto a MicroSD card and booted from it. With powerful computing capabilities, large number of multimedia interfaces and GPIO pins, Raspberry Pi 3 is a suitable choice for running a complex software-driven IoT or Embedded project that requires sufficient computing power as well as large-scale sensor connectivity. With built-in Bluetooth and Wi-Fi, this 3rd generation Pi can be easily deployed in an IoT network. The main specifications of the Raspberry Pi 3 are summarized in the following table –
Tabela de listagem de especificações técnicas do Raspberry Pi 3
Figure 2: Table listing the technical specifications of the Raspberry Pi 3

The 40-pin header on Raspberry Pi 3 has the following pin configuration –

Tabela de listagem de configuração de pinos do cabeçalho de 40 pinos do Raspberry Pi
Fig. 3: Table listing the pin configuration of the Raspberry Pi 40-pin header
Tabela de listagem de configuração de pinos do cabeçalho de 40 pinos do Raspberry Pi
Fig. 4: Table listing the pin configuration of the Raspberry Pi 40-pin header
In this project, an LED interfaces with the Raspberry Pi's GPIO18 pin. The board is powered by a USB adapter.
LED – An LED is connected to GPIO18 of the Raspberry Pi. Its anode is connected to the Raspberry Pi pin and the cathode is connected to ground. The LED is connected to the Pi via a 1K ohm pull-up resistor in series.
Power supply – The power supply is connected to the Raspberry Pi. The Pi must be powered by a 5V adapter with 2.5A current output. The adapter can be plugged into the Micro USB socket.
How the circuit works –
The IoT device designed here is simply a Raspberry Pi 3 controlling an LED. To control the LED, a python script is written that retrieves emails and if the subject of the email matches a pre-determined text, it reads the body of the email containing the control command.
First of all, the Raspberry Pi needs to be loaded with an operating system. The official Raspberry Pi operating system – Linux Raspbian – is installed here. During operating system installation, the Raspberry Pi must be connected to a monitor using an HDMI cable and a keyboard and mouse via USB ports.
To install Raspbian OS on MicroSD card, first download the latest Raspbian OS image from the Raspberry Pi website at the following link –
Raspbian Operating System
Copy the latest Raspbian operating system image to the MicroSD card. If the MicroSD card used is 32 GB or less, it must be formatted to FAT32 (file system) before copying the image, or if the MicroSD card is more than 32 GB, it must be formatted to exFAT before copying the image. Extract the operating system Zip and copy it to the MicroSD card. The image can be written to the card by connecting it to a laptop or PC using a MicroSD card reader. After copying the extracted image, insert the card into the MicroSD slot as shown below –
Imagem típica do slot para cartão MicroSD Raspberry Pi 3
Fig. 5: Typical image of the Raspberry Pi 3 MicroSD card slot
Connect the Raspberry Pi to a monitor using an HDMI cable, a keyboard, and a mouse. Power the card by connecting it to a power adapter. The red LED on the board will begin blinking and the operating system will begin booting from the MicroSD card. The boot process will be displayed on the monitor and once the boot is complete, the green LED will light up on the Raspberry Pi. After successfully installing Raspbian OS on Raspberry Pi, it is recommended to perform a software update. This can be done by running the following Linux commands in the Linux Terminal –
$ sudo apt-get update
$ sudo apt-get update
After installing Raspbian, it's time to write and run python scripts on Raspbian. A python script can be written in Raspbian using a text editor like Leafpad or GNU Nano. Python script can also be written using standard python IDE such as Python 2 IDLE or Python 3 IDLE. Open Python 3 IDLE by navigating through Menu -> Programming -> Python 3 IDLE. A window called Python 3.4.2 Shell will open. Write the python scripts and save them in a directory.
The python script written for this project must be run at startup when the Pi 3 is turned on. The script runs an infinite loop so it never ends. There are a few methods by which the Raspberry Pi can be configured to run a python script at startup. Any of the following methods can be used –
1) Editing rc.local –
Commands can be added to the /etc/rc.local file to run a program or command when the Raspberry Pi boots. This is especially useful if the Pi needs to be plugged into headless power and run a program without manual configuration or initialization. The file must be edited with root by running the following commands in the Linux Terminal –
sudo nano /etc/rc.local
Now add commands to run the python script using the full file path and add an ampersand at the end of the command so that the script runs in a separate process and initialization can continue. The following command must be added where the python script is saved as IMAP.py –
sudo python /home/pi/IMAP.py &
output 0
The command must be added just before the exit 0 line in the rc.local file.
2) Editing .bashrc –
The .bashrc is a hidden file in the home folder that contains user configuration options. Open the .bshrc file by running the following commands in the Linux terminal –
sudo nano /home/pi/.bashrc
Add the following lines after the last line of the file –
echo Running at startup
sudo python /home/pi/IMAP.py
3) Adding script to init.d directory –
The init.d directory contains the scripts that are launched during the boot process (additionally, all programs here run when the Pi is turned off or rebooted). Add the script to be run at startup to the init.d directory using the following commands –
sudo cp /home/pi/securitysystem.py /etc/init.d/
Go to the init directory and open the python script by running the following commands –
cd /etc/init.d
sudo nano IMAP.py
Add the following lines to the python script to make it a Linux Standard Base (LSB) –
# /etc/init.d/sample.py
### STARTING INFORMATION
# Provide: sample.py
# Mandatory start: $remote_fs $syslog
# Mandatory stop: $remote_fs $syslog
# Default start: 2 3 4 5
# Default stop: 0 1 6
# Short description: Start daemon at boot time
# Description: Enables the service provided by the daemon.
### END START INFORMATION
Make the python script in the init directory executable by changing its permission by running the following command –
sudo chmod +x IMAP.py
Then run the following command –
sudo update-rc.d defaults IMAP.py
Then restart the Pi by running the following command –
sudo restart
Any of the above methods can be used to run the python script at startup. Now the Pi 3 can be disconnected from the monitor, keyboard and mouse. Connect the LED to the Raspberry Pi and turn it on.
Now when the Pi turns on it will run the python script on startup. The Python script will read emails from our Gmail account using the IMAP protocol. The script will only read emails from specific subjects, like in this case “pi” is the subject, for which emails will be read by the script. Now the body is read into a string and this string is compared with a set of commands, predefined in the script. Each command has its own functionality, like if the “on” command matches the body of the email, the light will be on (LED connected to raspberry pi). An email can also be received for each command as feedback, but this will require implementation in the SMTP protocol.
Programming guide –
The implementation of this project can be done in any programming language like C, Java but python is used in this case. There are simple libraries used for raspberry pi GPIO and IMPLIB for IMAP.
The python script can be divided into the following parts –
1. Importing important libraries
2. Log in to the mailbox (Gmail)
3. Searching email from specific subject “pi”
4. Comparing the email body with predefined command sets
5. Marking the email as seen
1. Importing important libraries: To carry out the project first, you need to collect the necessary tools such as the required standard libraries.
For IMAP implementation, the “IMAPLIB” library is used and for GPIO interaction, the “RPI.GPIO” library is used.
import imaplib
import RPi.GPIO as GPIO
2. Log in to the mailbox: Once you have what you need now, it's time to log in to the mailbox using credentials and selecting INBOX. The connection is simply stored in the “conn” object and then IMAP commands are used to interact with the mailbox.
connection = imaplib.IMAP4_SSL(“imap.gmail.com”, 993)
conn.login(gmail_user, gmail_pwd)
Now the location where the email is categorized is selected, which in this case is INBOX. This can be done using the select command from the IMAP library.
conn.select (“INBOX”)
3. Searching for email of specific subject “pi”: Now after selecting the mailbox folder using the select command, the search command can be used to search for the email with specific subject “pi”. To check if the email is new, the code also checks for unseen messages.
typ, data = conn.search(None, '(SUBJECT NOT SEEN “pi”)')
This command must be executed within a loop so that when any email is received at any time it is checked.
4. Comparing the email body with predefined command sets: Now, after receiving the email, the email body must be read first.
Note: Send the emails by selecting plain text in Gmail's sending options.
body = extract_body (payload)
Using the body extract function, it is possible to obtain only the body of the email in a string variable.
Now, after getting the message body into a variable, it can be compared with the command sets.
if(body.strip ==”on”):
GPIO.output (LED, True)
elif(body.strip ==”off”):
GPIO.output(LED, False)
Using the raspberry pi GPIO command it is possible to control any GPIO output state, as if the 'on' command is received, the GPIO pin connection LED can be turned on using the “True” flag.
5. Marking the email as seen: After reading the email and executing the command, the email needs to be marked as read so that the script does not repeat this command.
type, response = conn.store(num, '+FLAGS', r'(Seen)')
This can also be done using the IMAP “store” command. So now again the script is ready to receive new emails with the subject “pi”. The while script function must be executed in a loop and errors and warnings must be handled so that the process does not stop.
while True:
to try:
check email
except Exception like and:
print and
So, this is how the IMAP protocol can be used to command an IOT device/application. Check out the python code and quickly try it out on a Raspberry Pi.
In the next tutorial, the SMTP protocol will be discussed.

Project source code

 ###



 //Program to


 
#!/usr/bin/env python import RPi.GPIO as GPIO import picamera import subprocess import imaplib GPIO.setwarnings(False) LED = 24 GPIO.setmode(GPIO.BCM) GPIO.setup(LED,GPIO.OUT) GPIO. output(TRIG, False) def extract_body(payload): if isinstance(payload,str): return payload else: return 'n'.join((extract_body(part.get_payload ) for part in payload)) def check_email conn = imaplib. IMAP4_SSL("imap.gmail.com", 993) conn.login(gmail_user, gmail_pwd) conn.select("INBOX") typ, data = conn.search(None, '(UNSEEN SUBJECT "pi")') try: for num in data(0).split : typ, msg_data = conn.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part(1)) subject=msg('subject') payload=msg.get_payload body=extract_body(payload) print(body.strip ) #things to do when somehthing received if(body.strip =="on"): GPIO.output(LED, True) elif(body.strip =="off"): GPIO.output(LED, False) typ, response = conn.store(num, '+FLAGS', r'(Seen)') finally: try: conn. close except Exception as e: print e conn.logout while true: try: check_email except Exception as e: print e

###

Related Content

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.