【问题标题】:Azure IoTHub DeviceMessage and route filterAzure IoT 中心设备消息和路由筛选器
【发布时间】:2018-07-03 17:22:38
【问题描述】:

我使用 pythonpaho.mqtt 将消息发送到云端 我设置了端点和路由。当我将查询字符串设置为 true 时,一切正常

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)

但是如果我将查询字符串设置为$body.id = 1,那么我就不会收到任何消息。

有什么想法吗,伙计们?

【问题讨论】:

  • 你好放大器,你可以试试答案的解决方案,看看它是否有效。它对我有用。

标签: python azure mqtt azure-iot-hub


【解决方案1】:

由于未设置内容编码类型,路由无法正常工作。代码中的所有“systemProperties”实际上是消息体而不是系统属性。该方法设置的内容编码类型不生效。

在主题中添加“$.ct=application%2Fjson&$.ce=utf-8”。然后它看起来像这样:

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

但要使路由查询适用于您的消息,您需要使用以下查询字符串:$body.message.body.id = 1

要做两个修改:

首先,将body = '{id:1}' 更改为body = {"id":1} 以使id 为字符串。

其次,将topicName的值改为这个:

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

如果可能,建议使用Azure IoT SDK for Python 与 Azure IoT Hub 进行通信。

【讨论】:

  • 嗨!所以你的意思是我需要删除 systemPropertiesDict 并只留下正文部分(当然还要在查询中添加 $.ct=application%2Fjson&$.ce=utf-8 )?
  • @amplifier 我用你需要做的两个编辑来更新我的答案。您可以检查并尝试一下。至于代码中的 systemProperties,如果不需要,可以将其删除。如果它不起作用,请随时告诉我。
  • @Rite Han 你太棒了!有用! body = '{id:1, "text":"hello!!!"}' print("Message to send", body) self.client.publish(topicName, body) 顺便说一句,我不需要 id 引号(无论如何它都有效)
  • @Rite Han Azure SDK 很棒,但目前的要求是仅限 mqtt 方式。您在哪里找到关于 $.ct=application%2Fjson&$.ce=utf-8 的文档?
  • @amplifier 我没有在文档中找到这个。您可以向this document 提出问题。这就是 Roman Kiss 的发现。请查看this thread
【解决方案2】:

如果您使用第三方库(如 paho-mqtt),您必须指定消息的内容类型和编码。 IoT 中心路由内容类型为“application/json”且内容编码为“utf-8”或“utf-16”或“utf-32”的消息。 使用 MQTT 协议,您可以使用 $.ct 和 $.ce 设置此信息。

主题示例:

devices/{MY_DEVICE_ID}/messages/events/%24.ct=application%2fjson&%24.ce=utf-8

网址编码

devices/{MY_DEVICE_ID}/messages/events/$.ct=application/json&$.ce=utf-8

您可以在这里找到更多信息: https://azure.microsoft.com/it-it/blog/iot-hub-message-routing-now-with-routing-on-message-body/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    相关资源
    最近更新 更多