【问题标题】:azure iothub direct method not working as expectedazure iothub 直接方法未按预期工作
【发布时间】:2019-03-28 15:08:31
【问题描述】:

我能够在 iothub 消息(从云到设备的消息)上打开一个侦听器,但我无法订阅直接方法。我正在尝试使用 mqtt 支持,而不是 iothub 库

我关注了https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-direct-methods#mqtt 但肯定有一个小细节我还没有做好

这是我的代码(python)

from paho.mqtt import client as mqtt
import ssl
import token_generator #a script that exports the token , it is working fine for device messages

path_to_root_cert = "cert.cer"
device_id = "mydevice_id "
endpoint ="myiot_hub_name.azure-devices.net/devices/mydevice_id "
policyKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
sas_token =  token_generator.generate_sas_token(endpoint ,policyKey ,None)
iot_hub_name = "myiot_hub_name"

def on_connect(client, userdata, flags, rc):
  print ("Device connected with result code: " + str(rc))
def on_disconnect(client, userdata, rc):
  print ("Device disconnected with result code: " + str(rc))
def on_publish(client, userdata, mid):
  print ("Device sent message")
def on_message(client, userdata, msg):
    print("Message received at: " + msg.topic+" with payload: "+str(msg.payload))

client = mqtt.Client(client_id=device_id, protocol=mqtt.MQTTv311)

client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish
client.on_message = on_message

client.username_pw_set(username=iot_hub_name+".azure-devices.net/" + device_id, password=sas_token)

client.tls_set(ca_certs=path_to_root_cert, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1, ciphers=None)
client.tls_insecure_set(False)

client.connect(iot_hub_name+".azure-devices.net", port=8883 )

client.subscribe("iothub/methods/POST/")

client.loop_forever()

【问题讨论】:

    标签: azure mqtt azure-iot-hub


    【解决方案1】:

    客户应订阅该主题:

    $iothub/methods/POST/#
    

    以下是其他订阅主题:

    $iothub/twin/res/#
    $iothub/twin/PATCH/properties/desired/#
    devices/{myDeviceId}/messages/devicebound/#
    devices/{myDeviceId}/modules/{myModuleId}/messages/devicebound/#
    

    对于设备流(目前处于预览阶段)

    $iothub/streams/POST/#
    

    【讨论】:

    • 我也尝试更改为 client.subscribe("$iothub/methods/POST/#") 遗憾的是到目前为止没有成功,我认为错误在其他地方
    • 调用者的错误代码是什么。如果您的设备已连接且未订阅方法,则错误消息为:“等待设备订阅超时。”,您可以使用设备资源管理器工具进行测试。
    • 使用mqtt方法时出现的错误是“Timed out waiting for the device to connect”
    • 但它适用于 python iothub 包,但我需要它在 mqtt 上运行
    • 您的设备似乎未连接到 Azure IoT 中心。尝试使用工具,例如:MQTTBox 客户端或 MQTT.fx 客户端,用于连接、订阅、发布等测试目的。
    【解决方案2】:

    我也遇到过这样的问题。花了一些时间后,我发现实际问题出在 python 示例中。

    根据documentation,用户名应该是 {iothubhostname}/{device_id}/?api-version=2018-06-30 但在示例中缺少版本。因此,如果您尝试订阅从 $iothub 开始的任何主题,则它不起作用。

    修改用户名后,我一切正常。

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 2019-04-22
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 2023-02-08
      • 1970-01-01
      相关资源
      最近更新 更多