Accident Detection
Most ofthe accident detection system uses complex 3 axis accelerometer, gravity sensoror costly android mobile phones with complex circuitry. In this system theaccident detection method is also cheap and simple. We have used a tilt sensorto detect accident. Whenever any major accidents happens car jump or even flipover. We are detecting the amount of angle it rotated from ground. Tilt sensorcan measure a rotation of minimum +15 degree or -15 degree.
OFF
ON
This is a Mercury switch based tilt sensor module that gives high at its output pin when tilted. It requires a 5V of DC input. It’s a three-terminal device consist of input, ground, and output. It has a glass tube consist of two electrode and liquid mercury ball. The liquid mercury ball closes and opens the circuit when inclined in a particular direction. The working and internal structure of the module is given below:
Internal Structure
CASE 1: NOT TILTED
Initially, when it is in NOT tilted position as shown in the image below, it gives LOW output because of the liquid mercury complete the circuit by connecting the two electrodes. When the output is LOW on-board LED remain ON.
CASE 1: TILTED
When it is inclined in a particular direction or angle, the liquid mercury breaks the contact between the metal electrodes and the circuit gets open. Hence, we get HIGH output in this condition and the onboard LED turns off.
Mailgun is an Email automation service. It has a very powerful set of inbuilt functions for sending emails. Developers can process their email with the help of Mailgun API
So in this lesson, we will learn how to create an account on Mailgun.
Creating an account on MailgunStep 1: Open https://www.mailgun.com/ in browser.
Step 2: Click on Sign Up
button.
Step 3: Fill all the necessary details in SIGN UP form. Make sure you are unchecking the payment option. Below is the screenshot of filled sign up form.
Step 4: You will get a verification mail having a link. Click on that link to verify your mail.
Step 5: To verify they will ask for phone number. Choose India as an option in the dropdown and then enter your phone number.
Step 6: After verification, scroll down to Sandbox Domain
section. Click on Add Recipient
button.
Step 7: Click on Invite New Recipient
button.
Step 8: Enter the Receipient Email ID. In this case enter your Email ID.
Step 9: After adding Email ID a new sandbox will be generated. Click on the ID of the newly generated sandbox. Refer below image for the same.
Step 10: The new screen will have all the necessary credentials that you want for sending an email. Copy all this credentials and save in the notepad.
That's it. You have successfully created the account on Mailgun. In the next lesson, we will use Bolt Python library to create our own Email Alert system.
Please read the steps completely mentioned below to install the Ubuntu virtual machine on your local Desktop/Laptop.
Also, note that the OS which the computer is running on will NOT be affected in any way.
Minimum SpecificationsFor installing a virtual machine on your Desktop/Laptop, it should meet the minimum specifications mentioned below,
- OS - Windows 7 or Windows 10
- CPU - Dual Core 2Ghz
- RAM - 4GB
- HDD - Should have at least 10GB free space
- High-Speed Internet Access
The installation steps are mentioned in brief as below,
- Download VmWare.
- Install VmWare.
- Download Ubuntu Server image.
- Install Ubuntu Server image on VmWare.
Do note that the setup requires high-speed internet access and will download approximately 1.2GB of data.
The links to the softwares is given below:
VMWare Download link - https://my.vmware.com/web/vmware/free#desktop_end_user_computing/vmware_workstation_player/12_0
Ubuntu Server ISO link - http://releases.ubuntu.com/16.04/ubuntu-16.04.6-server-i386.iso
Setup the Bolt Python LibraryAs you have already learned about Python basics in the previous topics, Now in this section we will learn to build the IoT product with Bolt Python library. The Bolt Python library makes it easy to interact with the Bolt cloud API from your Python application.
You can control or fetch the data from Bolt cloud to your server(In this workshop Ubuntu from DigitalOcean or from VirtualMachine is your server.), as you have learned about control API and controlling LED in Module-1, but in that case every time you had to go to https://cloud.boltiot.com if you wanted to control your Bolt. What if you want to build something of your own on your own server? Then Bolt Python library will help you in building the IoT product.
Before you proceed to this step, first ssh(login) to your Ubuntu server and follow the below steps to use Bolt Python library in your code.
Step 1: Update the packages on Ubuntu
Execute the command below so that the packages on Ubuntu are updated to the latest version. If you skip this step, you may encounter an error while installing the Boltiot package.
sudo apt-get -y update
Step 2: Install python3 pip3
pip3 is a package manager for python3 used to install and manage packages and python libraries. It is system independent.
Install pip3 using the following command,
sudo apt install python3-pip
Step 3: Installing boltiot library using pip
Now we will install the boltiot python library on your Ubuntu server.
Type the below command in terminal to install boltiot python library.
sudo pip3 install boltiot
Now we are done with boltiot python library installation. In the next section, we will learn how to use the Bolt python library to check the device status and switch off the device.
TroubleshootingNote - If you are getting Python locale error: unsupported locale setting then run the following commands
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales
After typing the above command, a pop up will open. Select All locales and click enter.
And then another pop will open. Select en_US.UTF-8 and then press enter.
Note: The above settings will stop working after closing the session.
Sending an Email when sensor Crosses Threshold
In the previous lesson, we learned about Mailgun and how to create an account on Mailgun. Now we will write a program which will fetch the tilt data collected by Bolt and send an email if the tilt value exceeds the defined tilt range.
Step 1: Connect the tilt monitoring circuit - Hardware connections for sensor monitor
.
Step 2: Login into the server by entering the IP address of your digital ocean droplet. If you have not used Digital Ocean droplet, you can directly login to your Virtual Machine via VirtualBox or VMWare.
Step 3: After successful login, create a file named email_conf.py
which will store all the credentials related to Mailgun. To create a new file type sudo nano email_conf.py
in the terminal. After that write below code to save all the credentials in a single file.
MAILGUN_API_KEY = 'This is the private API key which you can find on your Mailgun Dashboard'
SANDBOX_URL= 'You can find this on your Mailgun Dashboard'
SENDER_EMAIL = 'This would be test@your SANDBOX_URL'
RECIPIENT_EMAIL = 'Enter your Email ID Here'
API_KEY = 'This is your Bolt Cloud account API key'
DEVICE_ID = 'This is the ID of your Bolt device'
Note: You have to replace all the above value with your credentials. You can find the first four value in Mailgun dashboard and the last two in Bolt Cloud dashboard.
We store all the credentials in a separate file since it is sensitive data which should not be shared with anyone. Hence it is a good practice to avoid using credentials in code directly. After replacing all the values, save the file using CTRL+X.
Step 4: Now create one more file named temp_email.py
. To do so you have to type sudo nano temp_email.py
in the terminal. Now we will write main code to collect the data from the Bolt and send Email if it crosses the threshold.
The algorithm is similar to the one where we have sent the SMS if the temperature crosses the threshold. It can be summarised into,
- Fetch the latest sensor value from the Bolt device.
- Check if the sensor value is in the range specified in our min and max values.
- If it is not in range, send the SMS.
- Wait for 10 seconds.
- Repeat from step 1.
Code Explanation
- In the code, we first have to import our email_conf file which has all the credentials. The python json and time libraries are also imported in the same line. Since we have saved our conf file with the .py extension, we can directly import it.
import email_conf, json, time
- json is a python library used for handling all operations on JSON objects. JSON is nothing but a data communication format widely used on the Internet for sending/receiving data between a client and server. More information on JSON can be found here. Remember, 'json' is the python library used for handling JSON objects and JSON is a data communication format.
- Now we will import Bolt python library which will let us fetch the data stored in Bolt Cloud. To send the email, the Email library is also imported. The below line of code imports the required libraries.
from boltiot import Email, Bolt
- In the above line, we are importing two objects. First one is Email which will be used to send email alerts and the other one is Bolt which is used for accessing data from your Bolt device like the tilt reading.
- Now we will initialize two variables which will store minimum and maximum threshold value. You can initialize any minimum and maximum integer limits to them.
- This would send an alert if the tilt reading goes below the minimum limit or goes above the maximum limit similar to the alerts on a Pharmaceutical company's manufacturing line.
minimum_limit = 15
maximum_limit = 20
- Now to fetch the data from Bolt Cloud, we will create an object called 'mybolt' using which you can access the data on your Bolt.
- For the Bolt Cloud to identify your device, you will need to provide the API key and the Device ID when creating the mybolt object. Since the conf file holds the API key and Device ID variables, you can use them as follows,
mybolt = Bolt(email_conf.API_KEY, email_conf.DEVICE_ID)
The above code will automatically fetch your API key and Device ID that you have initialized in email_conf.py
file.
- Now to send email, we will create an object of the same.
mailer = Email(email_conf.MAILGUN_API_KEY, email_conf.SANDBOX_URL, email_conf.SENDER_EMAIL, email_conf.RECIPIENT_EMAIL)
The above code will automatically fetch your MAILGUN_API_KEY, SANDBOX_URL, SENDER_EMAIL and RECIPIENT_EMAIL that you have initialized in email_conf.py
file. Make sure you have entered the correct values in email_conf.py
file.
- Since we want to continuously monitor the temperature reading, we will enclose our logic to fetch, compare and send the Email inside an infinite loop using the `while True:` statement. An infinite loop is a special loop which executes its code continuously since its exit condition is never going to be valid. To exit the loop, we will need to forcibly exit the code by holding CTRL + C.
while True:
print ("Reading sensor value")
response = mybolt.analogRead('A0')
data = json.loads(response)
print ("Sensor value is: " + str(data['value']))
try:
sensor_value = int(data['value'])
if sensor_value > maximum_limit or sensor_value < minimum_limit:
print("Making request to Mailgun to send an email")
response = mailer.send_email("Alert", "The Current sensor value is " +str(sensor_value))
response_text = json.loads(response.text)
print("Response received from Mailgun is: " + str(response_text['message']))
except Exception as e:
print ("Error occured: Below are the details")
print (e)
time.sleep(10)
- The code continuously fetches the tilt value using `analogRead` function. Since the sensor is connected to A0 pin of the Bolt, we will execute the analogRead() function on the pin A0.
- The response from the Bolt Cloud using the analogRead() function is in a JSON format, so we will need to load the JSON data sent by the cloud using Python's json library.
- The temperature value is inside a field labelled as "value" in the response. We can access the JSON values using the statement `sensor_value = int(data['value'])`. This line also converts the sensor reading to integer data type for comparing the tilt range.
- This is enclosed inside a try-except block to handle any error that may occur in the code. More explanation of try-except code block is given here.
- The next line of code checks if the temperature reading is above the maximum limit or below the minimum limit. If it exceeds, then the Email will be sent.
- The send_email function takes two parameters. First one is
Subject of the Mail
and the other one isMessage content
. - The Email to be sent will have the subject "Alert" and contain the text "The Current tilt sensor value is" followed by the tilt value as defined the send_email() function.
- The response from Mailgun will be stored inside the `response` variable.
- The text parameter from the response extracted and converted to json and the message from it is printed.
- Once the tilt reading has been sent, we will need to wait for 10 seconds to get the next reading. For this, we will put the program to sleep once every loop iteration.
- The statement `time.sleep(10)` puts the program execution on hold for 10 seconds. This means that the program would not execute for a period of 10 seconds.
Also, we are fetching the data every 10sec. You can change the value, but ideally, it should be good if the time interval between 2 data points is more than 10sec.
Below is the complete code:
import email_conf
from boltiot import Email, Bolt
import json, time
minimum_limit = 15 #the minimum threshold of light value
maximum_limit = 20 #the maximum threshold of light value
mybolt = Bolt(email_conf.API_KEY, email_conf.DEVICE_ID)
mailer = Email(email_conf.MAILGUN_API_KEY, email_conf.SANDBOX_URL, email_conf.SENDER_EMAIL, email_conf.RECIPIENT_EMAIL)
while True:
print ("Reading sensor value")
response = mybolt.analogRead('A0')
data = json.loads(response)
print ("Sensor value is: " + str(data['value']))
try:
sensor_value = int(data['value'])
if sensor_value > maximum_limit or sensor_value < minimum_limit:
print("Making request to Mailgun to send an email")
response = mailer.send_email("Alert", "The Current temperature sensor value is " +str(sensor_value))
response_text = json.loads(response.text)
print("Response received from Mailgun is: " + str(response_text['message']))
except Exception as e:
print ("Error occured: Below are the details")
print (e)
time.sleep(10)
angle = (100*sensor_value)/1024
Where sensor_value is the variable in which data obtained from the sensor is stored.
- Save the file. Time to run the code. To do so type `sudo python3 temp_email.py` in terminal
Please note that the emails will take a few minutes to be sent by Mailgun and received by your email ID. If you are still not able to receive the email, please check your configuration file and also the Mailgun Logs. Errors in sending the alert will be given in the logs.
Since we have written a couple of print statement in the code, the tilt data will get printed on the terminal. If that value falls outside the threshold range then an email will be sent to your registered Email ID.
Comments