Two ways to talk to Azure IoT Hub

This article lists down 2 ways to communicate with Azure IoT hub :

  1. An insecure method using a standalone java client
  2. A secure certificates based method using a standalone python client

Most of these instructions can be found on the Azure site but is scattered all over the place.

This code has been been run and tested locally and guaranteed to be bug free.

Connecting to Azure IoT hub using Java client (unsecure)

Step 1: Create an IoT hub

From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

Select IoT Hub from the search results, and then select Create.

Step 2 : Register a device

Run the following command in Azure Cloud Shell to create the device identity.

az iot hub device-identity create --hub-name {YourIoTHubName} --device-id MyJavaDevice

Run the following command in Azure Cloud Shell to get the device connection string for the device you just registered:

az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyJavaDevice --output table

Incase you plan to build REST api later to retrieve messages ingested into IoT hub , you will need the following details :

Event Hubs-compatible endpointEvent Hubs-compatible path, and service primary key. The following commands retrieve these values for your IoT hub:

az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {YourIoTHubName}

az iot hub show --query properties.eventHubEndpoints.events.path --name {YourIoTHubName}

az iot hub policy show --name service --query primaryKey --hub-name {YourIoTHubName}

Step 3 : Send simulated telemetry

Download the test java client from : https://github.com/Azure-Samples/azure-iot-samples-java/archive/master.zip

  1. In a local terminal window, navigate to the root folder of the sample Java project. Then navigate to the iot-hub\Quickstarts\simulated-device folder.
  2. Open the src/main/java/com/microsoft/docs/iothub/samples/SimulatedDevice.java file in a text editor of your choice.

Replace the value of the connString variable with the device connection string you made a note of earlier in step 2 above. Then save your changes to SimulatedDevice.java.

  • In the local terminal window, run the following commands to install the required libraries and build the simulated device application:
mvn clean package

  • In the local terminal window, run the following commands to run the simulated device application:
java -jar target/simulated-device-1.0.0-with-deps.jar


Connecting to Azure IoT hub using Python client and device certificates (secure)

Step 0 – Get X.509 CA certificates

This section describes how to create your own X.509 certificates using a third-party tool such as OpenSSL.

Git clone https://github.com/Azure/azure-iot-sdk-c.git

Step 1 – Initial Setup

At linux prompt.

cd <path>\azure-iot-sdk-c\tools\CACertificates\

chmod 700 certGen.sh

Step 2 – Create the certificate chain

./certGen.sh create_root_and_intermediate

This will create azure-iot-test-only.root.ca.cert.pem

Next, go to Azure IoT Hub and navigate to Certificates. Add a new certificate, providing the root CA file when prompted.

Step 3 – Proof of Possession

Select the new certificate that you’ve created in IoT Hub and navigate to and select “Generate Verification Code”. This will give you a verification string you will need to place as the subject name of a certificate that you need to sign. Highlighted below to be replaced.

./certGen.sh create_verification_certificate 106A5SD242AF512B3498BD6098C4941E66R34H268DDB3288

the script will output the name of the file containing "CN=106A5SD242AF512B3498BD6098C4941E66R34H268DDB3288" to the console.

Upload this file to IoT Hub (in the same UX that had the “Generate Verification Code”) and select “Verify”.

Step 4 – Create a new device

On Azure IoT Hub, navigate to the IoT Devices section, or launch Azure IoT Explorer.

Add a new device (e.g. avengersDevice), and for its authentication type chose “X.509 CA Signed”. 

Run the below line  to create the new device certificate.

./certGen.sh create_device_certificate avengersDevice

This will create

/certs/new-device.cert.pem and

/private/new-device.key.pem

cd ./certs && cat new-device.cert.pem azure-iot-test-only.intermediate.cert.pem azure-iot-test-only.root.ca.cert.pem > new-device-full-chain.cert.pem

 to get the public key.

Step 5 – Authenticate your X.509 device with the X.509 certificates

pip install paho-mqtt

Kindly note : in the code snippet below the certificate mentioned in the line :

path_to_root_cert = "/home/ubuntu/azure/digicert.cer"

Is DigiCert’s Baltimore Root certificate.

You can create this file by copying the certificate information from certs.c in the Azure IoT SDK for C. <path>\azure-iot-sdk-c\certs\certs.c

Include the lines -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----, remove the " marks at the beginning and end of every line, and remove the \r\n characters at the end of every line.

Use the following python code to connect : python-cert-device-client.py

from paho.mqtt import client as mqtt
import ssl

#path_to_root_cert = "/home/ubuntu/azure/certs/certs/azure-iot-test-only.root.ca.cert.pem"
path_to_root_cert = "/home/ubuntu/azure/digicert.cer"
device_id = "avengersDevice"
sas_token = "<generated SAS token>"
iot_hub_name = "AvengersHub"


def on_connect(client, userdata, flags, rc):
    print("Device connected with result code: " + str(rc))


def on_disconnect(client, userdata, rc):
    print("Device disconnected with result code: " + str(rc))


def on_publish(client, userdata, mid):
    print("Device sent message")


client = mqtt.Client(client_id=device_id, protocol=mqtt.MQTTv311)

client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish

# Set the username but not the password on your client
client.username_pw_set(username=iot_hub_name+".azure-devices.net/" +
                       device_id + "/?api-version=2018-06-30", password=None)

# Set the certificate and key paths on your client
cert_file = "/home/ubuntu/azure/certs/certs/new-device.cert.pem"
key_file = "/home/ubuntu/azure/certs/private/new-device.key.pem"
client.tls_set(ca_certs=path_to_root_cert, certfile=cert_file, keyfile=key_file,
               cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
client.tls_insecure_set(False)

client.connect(iot_hub_name+".azure-devices.net", port=8883)

client.publish("devices/" + device_id + "/messages/events/", "{id=123}", qos=1)
client.loop_forever()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: