天青iothub直接方法无法正常工作

时间:2019-02-26 07:13:57

标签: azure mqtt azure-iot-hub

我能够打开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()

2 个答案:

答案 0 :(得分: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/#

答案 1 :(得分:0)

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

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

固定用户名后,一切对我来说都很正常。