Introduction
In the following tutorial we will learn how to use the Microsoft Azure Cloud service in our IoT projects. We will be using the Azure IoT Hub, Stream Analytics Jobs & an SQL database to store our data. This will be a step by step tutorial and almost every step has an image associated with it to make it easier to follow.
Contents
Setting Up a Resource Group
- When You first log in to the Azure portal, you will see a screen like this. Click on the
Resource groups
button.
- Next select
Add
- Enter the name of your
Resource Group
and then click theReview + Create
- Then click
create
Setting Up Azure IoT Hub
- Select
IoT Hub
in the Azure services list or look for it in the search bar. - Next, select
Add
on the top left of your screen
- Next, fill in the data similar to the ones shown in the image below and then click
Review + Create
- Then select
Create
- Now we have to create a
device
. For this select yourtemperaturedata
in the IoT Hub page
- Next, from the list select
IoT devices
underExplorers
and then selectNew
- Enter a desired
Device ID
and then clickSave
- Now open this device and copy the
primary connection string
this is required to authenticate your requests created from your python code.
Setting Up SQL Database
- Select
SQL databases
in the Azure services list or look for it in the search bar. - Then select add from the SQL dashboard
- Fill in the required details
- Before you are able to review and create you also have to create a new server
- Enter the details as per your requirements and then select
OK
- Now you can click on
Create + Review
and thenCreate
. - Next lets create the table where we are going to store our data. For this open the dashboard of your database and select
Query editor
- While logging in you may face an issue where your IP hasn’t been authorized, click on
Set server firewall
- In that page you should see a button that says
Add Client IP
select that. - Now we have to write a simple SQL query to create our table.
CREATE TABLE [dbo].[temperature](
[temp] [float] NULL,
)
Setting Up Stream Analytics
- Select
Stream Analytics jobs
in the Azure services list or look for it in the search bar. - Next, click on the
Add
button in this page
- Fill in the details as shown below and click
create
.
- Now open your Stream analytics dashboard and select
input
from theJob topology
sub-menu
- Now choose
+ Add stream input
and chooseIoT Hub
from the drop down - You will have to enter an input alias and leave everything else as the defaults and click
save
.
- Now open your Stream analytics dashboard and select
output
from theJob topology
sub-menu - Select
+Add
and chooseSQL Database
form the drop-down. - Enter your table’s name which is
temperature
in our case.
- Now open your Stream analytics dashboard and select
Query
from theJob topology
sub-menu - Enter the Query as shown below
- Click on
Save Query
- Finally go to the
Overview
page and click onStart
NOTE :- In case everything seems to be working fine yet there are no entries in your SQL database check if you have whitelisted the IP (in the SQL server) assigned to your stream analytics process
Code Explanation
import random
import time
import threading
# Using the Python Device SDK for IoT Hub:
# https://github.com/Azure/azure-iot-sdk-python
# The sample connects to a device-specific MQTT endpoint on your IoT Hub.
from azure.iot.device import IoTHubDeviceClient, Message, MethodResponse
# The device connection string to authenticate the device with your IoT hub.
# Using the Azure CLI:
# az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyNodeDevice --output table
CONNECTION_STRING = <your connection string of the iothub device>
# Define the JSON message to send to IoT Hub.
TEMPERATURE = 20.0
HUMIDITY = 60
MSG_TXT = '{{"temp": {temperature}}}'
INTERVAL = 1
def iothub_client_init():
# Create an IoT Hub client
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
return client
def device_method_listener(device_client):
global INTERVAL
while True:
method_request = device_client.receive_method_request()
print (
"\nMethod callback called with:\nmethodName = {method_name}\npayload = {payload}".format(
method_name=method_request.name,
payload=method_request.payload
)
)
if method_request.name == "SetTelemetryInterval":
try:
INTERVAL = int(method_request.payload)
except ValueError:
response_payload = {"Response": "Invalid parameter"}
response_status = 400
else:
response_payload = {"Response": "Executed direct method {}".format(method_request.name)}
response_status = 200
else:
response_payload = {"Response": "Direct method {} not defined".format(method_request.name)}
response_status = 404
method_response = MethodResponse(method_request.request_id, response_status, payload=response_payload)
device_client.send_method_response(method_response)
def iothub_client_telemetry_sample_run():
try:
client = iothub_client_init()
print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )
# Start a thread to listen
device_method_thread = threading.Thread(target=device_method_listener, args=(client,))
device_method_thread.daemon = True
device_method_thread.start()
while True:
# Build the message with simulated telemetry values.
temperature = TEMPERATURE + (random.random() * 15)
msg_txt_formatted = MSG_TXT.format(temperature=temperature)
message = Message(msg_txt_formatted)
# Add a custom application property to the message.
# An IoT hub can filter on these properties without access to the message body.
if temperature > 30:
message.custom_properties["temperatureAlert"] = "true"
else:
message.custom_properties["temperatureAlert"] = "false"
# Send the message.
print( "Sending message: {}".format(message) )
client.send_message(message)
print( "Message sent" )
time.sleep(INTERVAL)
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
if __name__ == '__main__':
print ( "IoT Hub Quickstart #2 - Simulated device" )
print ( "Press Ctrl-C to exit" )
iothub_client_telemetry_sample_run()
- This is a code block provided by azure on their GitHub page. You can find it here. Their README file will give a comprehensive explanation of the code.
- In line 13 you will have to type in the connection string that you had copied earlier.
- This program generates random float (as shown in line 68) values to act as temperature to simulate a sensor. You can also write a function for any sensor you wish to and send that data.
Output
- Open the Query editor for the database that you had created earlier.
- Run the following query
SELECT * FROM [dbo].[temperature]
- If everything goes according to plan you should see something like this
Conclusion
I hope you all learnt the basics of Azure IoTHub and how we can use it to store data into an SQL database. Feel free to leave your questions and suggestions in the comments below I will get back to them as soon as possible.
Happy Learning 😀