Azure IoT Hub / Raspberry Pi IoT Project – Connecting Pi and Azure (Raspberry Pi / Python)

I have looked at the best Raspberry Pi & sensor for my IoT Temperature Project, setup the hardware, took measurements and outputted them to a Twitter bot. Then yesterday I created an Azure IoT Hub, which means I now need to connect the Raspberry Pi to the Azure IoT Hub.

The first step is to register the Pi in the Azure IoT hub. Whilst logged into the Azure portal look towards the top of the screen for >_ icon. This is the Command Line Interface (CLI).

>_ CLI - Command Line Interface
>_ CLI – Command Line Interface

Click the CLI to open it and with the CLI open we can register a device via the following commands:

  • az extension add –name azure-cli-iot-ext
  • az iot hub device-identity create –hub-name YourIoTHubName –device-id MyPythonDevice

Replacing YourIoTHubName with the name of your IoT Hub and optionally replacing MyPythonDevice with the name of your device. Then enter:

  • az iot hub device-identity show-connection-string –hub-name YourIoTHubName –device-id MyPythonDevice –output table

This command will output a string containing the device connection details, I would recommend copying and pasting it into a text file as it is needed later.

My Connection string looks like this (I’ve replaced some characters with ?’s):

CONNECTION_STRING = “HostName=GeekTechStuff-IoT-Temperature.azure-devices.net;DeviceId=MyPythonDevice;SharedAccessKey=?????????????????????????????????=”

 

Now to the Raspberry Pi. On the Raspberry Pi open terminal and prepare to enter some commands.

Whilst trying to connect I ran into a few issues which I think were based around pip installing modules for Python 2 rather than Python 3 (which I currently use).  So:

Python 2

sudo pip install azure-iothub-device-client

sudo pip install azure-iothub-service-client

Python 3

sudo pip3 install azure-iothub-device-client

sudo pip3 install azure-iothub-service-client

And this should mean the Pi is ready to do a test connection to Azure. During my initial testing I hit two issues.

1.  A libboost-all-dev error along the lines of “ImportError: libboost_python-py27.so.1.55.0: cannot open shared object file: No such file or directory on raspbian“. Basically due to a missing dependency, this if fixed with the following command which installs missing dependency:

  • sudo apt-get install libboost-all-dev

2. A error message in my Python script that was Azure responding to say there was an error. This error messages said BECAUSE_DESTROY and has instantly become my favourite error message. I imagine it being said by a Decepticon from Transformers or Magneto in the early 1990’s X-Men arcade game (where the classic line, “Welcome to die!” was said). For me this error was caused by my connection string missing a closing speech mark.

Microsoft offer some template test files (located at: https://github.com/Azure-Samples/azure-iot-samples-python/archive/master.zip ) but to keep inline with my IoT project I decided to modify one of these with the functions I created/used previously to take measurements from the temperature sensor. I’ve put my changes in green below:

==================

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

import random
import time
import sys

# imports the modules for the sensor
from bmp280 import BMP280
try:
from smbus2 import SMBus
except ImportError:
from smbus import SMBus

bus=SMBus(1)
bmp280 = BMP280(i2c_dev=bus)

def get_temp():
temperature = bmp280.get_temperature()
temperature = temperature – 2.00
return(temperature)

def get_pressure():
pressure = bmp280.get_pressure()
return(pressure)

# 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.
import iothub_client
# pylint: disable=E0611
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult
from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError, DeviceMethodReturnValue

# 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 = “HostName=GeekTechStuff-IoT-Temperature.azure-devices.net;DeviceId=MyPythonDevice;SharedAccessKey=XXXXXXXXXXXXXXXXXXXXXXX”

# Using the MQTT protocol.
PROTOCOL = IoTHubTransportProvider.MQTT
MESSAGE_TIMEOUT = 10000

# Define the JSON message to send to IoT Hub.
TEMPERATURE = get_temp()
PRESSURE = get_pressure()
MSG_TXT = “{\”temperature\”: %.2f,\“pressure\“: %.2f}”

def send_confirmation_callback(message, result, user_context):
print ( “IoT Hub responded to message with status: %s” % (result) )

def iothub_client_init():
# Create an IoT Hub client
client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
return client

def iothub_client_telemetry_sample_run():

try:
client = iothub_client_init()
print ( “IoT Hub device sending periodic messages, press Ctrl-C to exit” )

while True:
# Build the message with simulated telemetry values.
temperature = TEMPERATURE
pressure = PRESSURE
msg_txt_formatted = MSG_TXT % (temperature, pressure)
message = IoTHubMessage(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.
prop_map = message.properties()
if temperature > 30:
prop_map.add(“temperatureAlert”, “true”)
else:
prop_map.add(“temperatureAlert”, “false”)

# Send the message.
print( “GeekTechStuff Azure Sending Message: %s” % message.get_string() )
client.send_event_async(message, send_confirmation_callback, None)
time.sleep(300)

except IoTHubError as iothub_error:
print ( “Unexpected error %s from IoTHub” % iothub_error )
return
except KeyboardInterrupt:
print ( “IoTHubClient sample stopped” )

if __name__ == ‘__main__’:
print ( “IoT Hub Quickstart #1 – Simulated device” )
print ( “Press Ctrl-C to exit” )
iothub_client_telemetry_sample_run()

=======================

With the program running on the Pi it is time to jump back into Azure.

With the Azure CLI enter the command:

  • az iot hub monitor-events –hub-name YourIoTHubName –device-id MyPythonDevice

Again replaying YourIoTHubName with the IoT Hub Name you are using and if you used a different name for your Python device then change MyPythonDevice to the that now.

Hopefully after a few minutes (if you’ve used my script it sends a signal every 300 seconds, aka 5 minutes) the Azure CLI should show some data coming through.

Azure and Raspberry Pi successfully communicating
Azure and Raspberry Pi successfully communicating

I’ve saved my modified Azure Python file at:

https://github.com/geektechdude/temperature_project

9 responses to “Azure IoT Hub / Raspberry Pi IoT Project – Connecting Pi and Azure (Raspberry Pi / Python)”

  1. Azure IoT Hub / Raspberry Pi IoT Project – Connecting Pi, Azure and Power BI. – Geek Tech Stuff Avatar

    […] the Pi successfully reading temperature and pressure from the sensor, and connecting successfully to Azure it left one more step in my project – outputting the data in a meaningful way.  For this […]

    Like

  2. Pascal Mzk Avatar
    Pascal Mzk

    Cheers Mate,

    thank you for this awesome tutorial. I’m currently writing my bachelor thesis about Digital Twins and I really struggled to get my sensor connected to Azure.

    Your script is working, but when I touch the BMP180 the temperature, which is send to Azure, won’t raise, so the script is constantly sending the same temperature and pressure data to Azure.

    When I use your normal temperature reading script the sensor works just fine.

    Do you have any quick solution this problem?

    Thank you and greets from Germany!
    Regards,
    Pascal.

    Like

  3. Geek_Dude Avatar

    Hi Pascal,

    The above has this line:

    time.sleep(300)

    Which causes the a delay between readings sent to Azure (e.g. a reading is sent, the program waits 300 seconds, another reading is sent, the program waits 300 seconds etc..).

    If you reduce this figure and cause the temperature to rise on the sensor does Azure show the rise?

    Also note that the code only prints the first 2 digits of the temperature after the floating point. To be more accurate change the line:

    MSG_TXT = “{\”temperature\”: %.2f,\”pressure\”: %.2f}”

    to a larger number (e.g. %.2f is the first 2 digits after the point, %.4f would be the first 4 digits after the point), which help show the temperature change faster.

    Like

    1. Pascal Mzk Avatar
      Pascal Mzk

      Hey!
      That worked just fine, thank you!

      You don’t happened to have a tutorial on visualizing the temperature und pressure Data in Power BI or something do you?

      I assumed that the tutorials on the windows website would work with your skript too, but unfortunately I can’t save or reroute the received messages.

      Thank you for your help, mate!

      Like

  4. Pascal Mzk Avatar
    Pascal Mzk

    I followed your instructions and when i go to querry (to select where the input comes from and where the output goes) i get the warning:

    For your input: “Temperature” is no data available.

    My Azure Skript is running and the IoT Hub is showing that it is receiving them.
    Any Ideas?

    Thank you again for your help. Unfortunately there my Thesis Supervisor does not have any knowledge on Azure.

    Like

    1. Geek_Dude Avatar

      Hi Pascal,

      When you set up the “stream analytics” job is there an option to “Select IoT Hub from your subscriptions”?

      The Azure portal options can change regularly which makes maintaining notes on them a little hard at times.

      Like

  5. Pascal Mzk Avatar
    Pascal Mzk

    I got it now! The typical “have you tried turning it on and off again?” worked and I can now export and save me Data into Power BI.
    Next step would be priniting the Temperature and Pressure into an Excel Sheet for a CAD CFD Simulation.
    But you got a tutorial on that too, so again:
    Thank you! You just saved my guts!

    Greets from Germany and keep up the good work!

    Like

    1. Geek_Dude Avatar

      Glad it’s all working 🙂

      Like

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect