Search code examples
pythonazuremqttazure-iot-hub

Azure IoTHub DeviceMessage and route filter


I use python and paho.mqtt for sending messages to cloud I set up endpoint and route. When I set query string to true, everything works fine

messageDict = {}
systemPropertiesDict = {"contentType": "application/json", "contentEncoding": "utf-8", "iothub-message-source": "deviceMessages", "iothub-enqueuedtime": "2017-05-08T18:55:31.8514657Z"}
messageDict = {"systemProperties": systemPropertiesDict}
messageDict["appProperties"] = {}
body = '{id:1}'
messageDict["body"] = body
root = {"message":messageDict}
msg = json.dumps(root, indent=2).encode('utf-8')
print("Message to send", msg)
self.client.publish(topicName, msg)

But if I set the query string to $body.id = 1, then I don't receive any messages.

Any ideas, guys?


Solution

  • The route not working because the content encoding type is not set. All the "systemProperties" in your code actually as message body not system properties. Content encoding type set by this method doesn't take effect.

    Add "$.ct=application%2Fjson&$.ce=utf-8" to the topic. Then it will look like this:

    devices/{yourDeviceId}/messages/events/$.ct=application%2Fjson&$.ce=utf-8
    

    But to make the route query works on your message you need use this query string: $body.message.body.id = 1

    Two edits to make:

    First, change body = '{id:1}' to body = {"id":1} to make the id as a string.

    Second, change topicName value to this one:

    devices/{yourDeviceId}/messages/events/$.ct=application%2Fjson&$.ce=utf-8

    If possible, it is suggesting to use Azure IoT SDK for Python to communicate with Azure IoT Hub.