簡體   English   中英

使用Paho庫通過MQTT協議將消息發送到Azure IOT集線器

[英]Sending messages to Azure IOT hub through MQTT protocol using Paho library

大家好,

我正在嘗試通過使用Paho庫通過MQTT協議( 使用Python )將遙測消息發送到Azure IOT集線器 我已參考https://docs.microsoft.com/zh-cn/azure/iot-hub/iot-hub-mqtt-support(Microsoft Docs),並遵循與該文檔完全相同的步驟。 但是,我在運行代碼時遇到錯誤。

下面是python代碼

from paho.mqtt import client as mqtt
import ssl

path_to_root_cert = "C:\Python_Files\Digicert_Cert.txt"
device_id = "MyDeviceName"
sas_token = "SharedAccessSignature sr=MyHubName.azure-devices.net&sig=UclWeYtF5WSy4QUvTQvDF1ml2fVze0VFpv4e7YLFdQE%3D&se=1567761926&skn=iothubowner"
iot_hub_name = "MyHubName"

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")

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.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.publish("devices/" + device_id + "/messages/events/", "{id=123}", qos=1)
client.loop_forever()

運行python代碼時出現以下錯誤

Traceback (most recent call last):
  File "C:\Python_Files\Python Script.py", line 27, in <module>
    client.connect(iot_hub_name+".azure-devices.net", port=8883)
  File "C:\Python27\lib\site-packages\paho\mqtt\client.py", line 839, in connect
    return self.reconnect()
  File "C:\Python27\lib\site-packages\paho\mqtt\client.py", line 962, in reconnect
    sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
  File "C:\Python27\lib\socket.py", line 575, in create_connection
    raise err
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

我正在使用設備資源管理器工具生成SAS令牌。 以下是相同的屏幕截圖 在此處輸入圖片說明

我在代碼中使用的SAS令牌是

sas_token ="SharedAccessSignature sr=PuneODCIOTHub.azure-devices.net%2Fdevices%2FMyDotnetDevice&sig=KqyeH0n2kez3Zyz3%2BnVnOVyAsG%2F65MYO95%2FrgdJjBzI%3D&se=1536300480"

任何幫助將不勝感激。 提前致謝。

似乎sas_token在您的帖子中不正確,它不包含%2Fdevices%2F{deviceid} 我不知道如何獲得令牌,但是我認為您可以使用Device Explorer工具生成SAS令牌。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM