乐闻世界logo
搜索文章和话题

How do you set Azure IoT Hub "System Properties" using native MQTT?

1个答案

1

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 as application/json.
  • content-encoding: Encoding of the message content, such as utf-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:

shell
devices/{device-id}/messages/events/{property_bag}

Where {property_bag} is a key-value pair list separated by &, for example:

shell
devices/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:

python
import 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.

2024年8月21日 01:41 回复

你的答案