When communicating directly with Azure IoT Hub using the MQTT protocol, you must correctly set the system properties of the message. These properties enable IoT Hub to understand and process messages sent to it appropriately.
1. Understanding System Properties
Azure IoT Hub system properties include:
message-id: Unique identifier for the message.correlation-id: Identifier for related messages.content-type: Type of message content, such asapplication/json.content-encoding: Encoding of the message content, such asutf-8.
2. Including System Properties in the MQTT Topic
When publishing messages to IoT Hub via MQTT, include the system properties as part of the topic name. The properties should be embedded within the topic name in the following format:
shelldevices/{device-id}/messages/events/{property_bag}
Where {property_bag} is a key-value pair list separated by &, for example:
shelldevices/mydevice/messages/events/content-type=application%2Fjson&content-encoding=utf-8
3. Publishing Messages
If you are using a MQTT client library, such as paho-mqtt for Python, the following example demonstrates how to send a message with system properties:
pythonimport paho.mqtt.client as mqtt # MQTT client setup client = mqtt.Client() client.username_pw_set(username="{iot_hub_hostname}/{device_id}/?api-version=2019-03-30", password="{sas_token}") client.connect("{iot_hub_hostname}", 8883) # MQTT topic including system properties topic = "devices/mydevice/messages/events/content-type=application%2Fjson&content-encoding=utf-8" # Message content message = '{"temperature": 22.5}' # Publish message client.publish(topic, payload=message, qos=1) client.disconnect()
4. Verification and Debugging
Verify that your device is correctly registered and authenticated with IoT Hub. Use the appropriate SAS token and device ID for connection. If messages are not processed correctly, inspect IoT Hub monitoring tools and logs to troubleshoot.
By following this approach, you can ensure that messages sent to Azure IoT Hub via MQTT carry the correct system properties, enabling them to be properly parsed and processed.