Azure IoTHub DeviceMessage and route filter

2019-09-01 15:48发布

问题:

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?

回答1:

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.



回答2:

the following links help you with properties when a direct MQTT protocol is used:

Using the MQTT protocol directly

IoT Hub message routing: now with routing on message body

Using the MQTT protocol directly with property_bag

Azure IoT Hub Tester

.Net Reflector on the Microsoft.Azure.Devices.Client assembly

From the current version of the Microsoft.Azure.Device.Client (version 1.17.0):