MQTT: Connection to Azure IoT Hub (Micropython)

141 Views Asked by At

I'm unable to connect to Azure IoT Hub using the umqtt.simple2 library with SSL using MicroPython v1.22.2.

from umqtt.simple2 import MQTTClient

HUB_HOSTNAME = "AzureIoTHubHostName"
PORT = 8883
CLIENT_ID = "DeviceId"
USERNAME = f"{HUB_HOSTNAME}/{CLIENT_ID}/?api-version=2021-04-12"
PASSWORD = "SASToken"
TOPIC = f"devices/{CLIENT_ID}/messages/events/"
MESSAGE = b"Hello Azure IoT Hub!"
CADATA_PATH = "cadata_path"

with open(CADATA_PATH, "rb") as f:
    cadata = f.read()

ssl_params = {"cert_reqs": ussl.CERT_NONE, "cadata": cadata}

client = MQTTClient(
    CLIENT_ID,
    HUB_HOSTNAME,
    port=PORT,
    user=USERNAME,
    password=PASSWORD,
    ssl=True,
    ssl_params=ssl_params,
)

client.connect()

client.publish(TOPIC, MESSAGE)

client.disconnect()

No error message is provided by the connect method, making it difficult to diagnose the issue further (it fails on line 267 in simple2, when wrapping the socket --> self.sock = ussl.wrap_socket(self.sock_raw, **self.ssl_params))

I have tested my certificate file with openssl to check if the handshake occurs (openssl s_client -connect), and it works ok.

Could anyone advise on how to resolve this connectivity issue with Azure IoT Hub using MicroPython? Any guidance would be greatly appreciated.

1

There are 1 best solutions below

2
Sampath On

The code below is used to connect a device to Azure IoT Hub using MQTT with Python. It sets up a connection to Azure IoT Hub using the umqtt.simple2 library and publishes some telemetry data.

  • I followed IoTMQTTSample python
  • MicroPython on ESP32 sends telemetry to Azure IoT Hub with MQTT.
IOT_HUB_NAME = "{iothub_name}"
IOT_HUB_DEVICE_ID = "{device_id}"
IOT_HUB_SAS_TOKEN = "{sas_token}"

def on_connect(client, userdata, flags, rc):
    print("connect: " + str(rc))

def on_publish(client, userdata, mid):
    print("publish: " + str(mid))

# Create an MQTT client instance
mqtt_client = MQTTClient(client_id=IOT_HUB_DEVICE_ID, server=IOT_HUB_NAME + ".azure-devices.net", port=8883)

# Set the connection callback
mqtt_client.on_connect = on_connect

# Set the publish callback
mqtt_client.on_publish = on_publish

# Set username and password
mqtt_client.username_pw_set(username=IOT_HUB_NAME + ".azure-devices.net/" + IOT_HUB_DEVICE_ID + "/?api-version=2021-04-12", 
                            password=IOT_HUB_SAS_TOKEN)




messages = ["Accio", "Aguamenti", "Alarte Ascendare", "Expecto Patronum", "Homenum Revelio"]
for i in range(len(messages)):
    print("sending message[" + str(i) + "]: " + messages[i])
    mqtt_client.publish("devices/" + IOT_HUB_DEVICE_ID + "/messages/events/", payload=messages[i], qos=1)
  • Connect to Azure IoT Hub using MQTT
az iot hub generate-sas-token --connection-string  "HostName=<your-hub-name>.azure-devices.net;DeviceId=<your-device-id>;SharedAccessKey=<your-shared-access-key>"

Output: enter image description here