This project has a real-time example, which is in a pharmaceutical company, where medicines are stored at standard temperature and here IOT can be used to get notified if the temperature crosses the limit for any reason. and by this, we can take recovery steps for the future. I have created my project on IOT where I have made temperature monitoring system which will alert us whenever any disturbance takes place in temperature. That means we will easily get notified whenever the temperature crosses the limit of required temperature, through any means like email, SMS.So, the project on the Internet of Things seems to be one of the most interesting for all.
Steps for Building This Project
We need the following components to build the whole project:
i.Bolt WiFi module
ii. LM35 Temperature sensor
iii. 3Jumper wires ( Male to Female )
iv. Micro-USB cable ( mobile charger can also be used )
v. Power Source ( power bank can also be used )
Step 2. Hardware ConfigurationThe bolt Wifi module is connected to theLM35 temperature sensor through jumper wires.
- Using male to the female wire we will connect the 3 pins of the LM35 to the Bolt Wifi Module as follows:
- VCC pin of the LM35 is connected to 5v of the Bolt Wifi module.
The output pin of the LM35 is connected to A0 (Analog input pin) of the Bolt Wifi module.
- GND pin of the LM35 is connected to the GND.
First, we need to create a digital ocean account. Please click here https://m.do.co/c/5ea366f842e6 and create a new account. Type email id and password for Signing up and we will receive an account verification email. Open the email and click on the link to confirm our account.
After confirming your account, we need to add billing.
In this step, we will choose the appropriate image(version and type of OS) of droplet for this training. First, click on theCreate button and choose Droplet from the drop-down menu and the 'Create droplet' screen will appear. At the time of this writing, the 64-bit Ubuntu 18.10 image is selected by default and we will use the same version for this training.
In this step, we will choose the size of the droplet i.e. the amount of RAM and storage space it should have.
Datacenter region is the place where our droplet will be deployed. It's like someone has bought a computer for you in that place. For the best performance, choose the data centre nearest to us and our users. More distant server locations may increase the server's latency without providing any practical benefits. I am from India, so I kept Bangalore as the default datacenter region.
- Once we have selected our options, click Create.
after creating adroplet, we will receive a mail where we will get our IP address and login password.
We created a droplet and got the login credentials and server IP over emails. Now, we will learn about tools/software for ssh(login to the server) into our server. for windows os we can use putty to write the code and to execute for mac we will use the terminal for writing as well as running the code.
We will log in through the terminal to Digital ocean server.
3h.Then type password and press enter. Password won’t be visible and we will have to type the same password for the first time, which is mailed to us from DigitalOcean.
3i. After this, we are asked to change our password and we need to type our current password. And then we are asked to enter our new password twice for confirmation. Keep this password somewhere safe, because next time we have to type this new password.
The Bolt Python library makes it easy to interact with the Bolt cloud API from our Python application.
We can control or fetch the data from Bolt cloud to our server(Here Ubuntu from DigitalOcean ), Bolt Python library will help us in building the IoT product.
Before we proceed to this step, first ssh(login) to theUbuntu server and follow the below steps to use Bolt Python library in code.
Update the packages on UbuntuExecute the command below so that the packages on Ubuntu are updated to the latest version.sudo apt-get -y update
sudo apt install python3-pip
sudo
pip3 install boltiot
Twilio is a third-party SMS functionality provider. It is a cloud communications platform as a service (PaaS) company. Twilio allows software developers to programmatically make and receive phone calls and also send and receive text messages using its web service APIs.
Creating an account on Twilio
a. Open https://www.twilio.com/ in browser.
b. Click on Get a Free API Key button to sign up.
c. Fill all the necessary details in SIGN UP form. Below is the screenshot of filled sign up form.
d. To verify they will ask for our phone number. Choose India as an option in the dropdown and then enter our phone number
e. After verification, we will redirect to our dashboard and we will need to Create New Project.
f. Click on "Products" as shown on the screen below, and enable the SMS services by clicking on two checkboxes for Programmable SMS and Phone Numbers as shown below. Once you have done this, scroll to the bottom of the screen and click on "Continue".
g. Now, we will need to give a name for our project. I have given the name as My Project. Click on "Continue" once we have entered the project name.
h. Click on "Skip this step" when it asks to Invite a Teammate.
i. Our project should be created at this point. Click on "Project Info" to view the account credentials which is required for our projects
j. We can view the Account SID and Auth Token on this page. The Auth token is not visible by default, we can click on the"view" button to make the Auth token visible as shown below. Copy both and save them somewhere securely.
k. From the drop-down menu, choose "Programmable SMS". Now click on the get Started button to generate phone number.
l. Click on Get a number button. Then a popup will appear which will have the final number
m. Click on Choose this number button to finalise this number.
n. By this method, we can generate several numbers and we can see these numbers in Active Numbers area.
o. To check whether this is working or not, we have to go to Build with Programmable SMS and send a message to our given phone number. if everything is ok then it ill work, but if the message has not received, then we have to again set up from the beginning.NoteAll screenshots are here(related to Twilio)
Step 6. Preparation to code
a) Connect the temperature monitoring circuit as we have done in the previous lesson -Hardware connections for temperature monitor
.
b) Login into the putty by entering the IP address of your digital ocean droplet.
c) After successful login, create a file named conf.py
which will store all the credentials related to Twilio. To create a new file type sudo nano conf.py
in the terminal. After that write below code to save all the credentials in a single file.
SID = 'You can find SID in your Twilio Dashboard'
AUTH_TOKEN = 'You can find on your Twilio Dashboard'
FROM_NUMBER = 'This is the no. generated by Twilio. You can find this on your Twilio Dashboard'
TO_NUMBER = 'This is your number. Make sure you are adding +91 in beginning'
API_KEY = 'This is your Bolt Cloud accout 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 Twilio 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.
d) Now create one more file named temp_sms.py
. To do so you have to type sudo nano temp_sms.py
in the terminal. Now we will write the main code to collect the data from the Bolt and send SMS if it crosses the threshold.
The algorithm for the code can be broken down into the following steps -
- 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.
Step 7. Code Explanation
- In the code, we first have to import our 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 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 a 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 the Bolt python library which will let us fetch the data stored in Bolt Cloud. To send the SMS, the Sms library is also imported. The below line of code imports the required libraries.
from boltiot import Sms, Bolt
- In the above line, we are importing two objects. First one is SMS which will be used to send SMS alerts and the other one is Bolt which is used for accessing data from your Bolt device like the temperature 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 temperature 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 = 300
maximum_limit = 600
- 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(conf.API_KEY, conf.DEVICE_ID)
The above code will automatically fetch your API key and Device ID that you have initialized in conf.py
file.
- Now to send an SMS, we will create an object of the same.
sms = Sms(conf.SID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)
The above code will automatically fetch your SID, AUTH_TOKEN, TO_NUMBER and FROM_NUMBER that you have initialized in conf.py
file. Make sure you have given correct value in conf.py
file.
- Since we want to continuously monitor the temperature reading, we will enclose our logic to fetch, compare and send the SMS 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 Twilio to send a SMS")
response = sms.send_sms("The Current temperature sensor value is " +str(sensor_value))
print("Response received from Twilio is: " + str(response))
print("Status of SMS at Twilio is :" + str(response.status))
except Exception as e:
print ("Error occured: Below are the details")
print (e)
time.sleep(10)
- The code continuously fetches the temperature 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 the integer data type for comparing the temperature 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 SMS will be sent.
- The SMS to be sent will contain the text "The Current temperature sensor value is" followed by the temperature value.
- The response from Twilio will be stored inside the `response` variable.
- Once the temperature 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.
In the above code, 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 conf
from boltiot import Sms, Bolt
import json, time
minimum_limit = 300
maximum_limit = 600
mybolt = Bolt(conf.API_KEY, conf.DEVICE_ID)
sms = Sms(conf.SID, conf.AUTH_TOKEN, conf.TO_NUMBER, conf.FROM_NUMBER)
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 Twilio to send a SMS")
response = sms.send_sms("The Current temperature sensor value is " +str(sensor_value))
print("Response received from Twilio is: " + str(response))
print("Status of SMS at Twilio is :" + str(response.status))
except Exception as e:
print ("Error occured: Below are the details")
print (e)
time.sleep(10)
Note: The above "sensor_value" is the raw temperature reading, obtained from the LM35 sensor. In case you want to convert this value to the temperature in degree Celsius, use the formula:
Temperature=(100*sensor_value)/1024
Where sensor_value is the variable in which data obtained from the LM35 sensor is stored.
- Save the file. Time to run the code. To do so type `sudo python3 temp_sms.py` in terminal
Since we have written a couple of print statement in the code. So the temperature data will get printed on the terminal. If that value falls outside the threshold range then SMS will be sent to your registered number. The screenshot for the SMS sent is given below:
Now that we have written the code for anomaly detection lets run the code.Once that is done, run the anomaly detection code using the following command.
After about 100 seconds (10 seconds delay with a frame size of 10), the system will start printing the values, as per the following image
Precautionsa) If Bolt WiFi module is offline then it will show the result like this "You are offline"
Make sure you are online.b) If you are windows user then run your code on PuTTY.
Comments
Please log in or sign up to comment.