将M2MQTT Paho Python客户端连接到Azure IoT中心
我正在使用以下代码尝试连接Azure IoT Hub。它使用SAS,因此不需要安全证书。我正在使用C#中相同的M2MQTT库成功连接到Azure IoT Hub,但此代码在以下情况下失败: 连接失败。连接被拒绝,未授权。错误代码=5 我尝试了所有可能的安全参数组合,但没有成功。SAS令牌由DeviceExplorer生成将M2MQTT Paho Python客户端连接到Azure IoT中心,python,iot,azure-iot-hub,paho,Python,Iot,Azure Iot Hub,Paho,我正在使用以下代码尝试连接Azure IoT Hub。它使用SAS,因此不需要安全证书。我正在使用C#中相同的M2MQTT库成功连接到Azure IoT Hub,但此代码在以下情况下失败: 连接失败。连接被拒绝,未授权。错误代码=5 我尝试了所有可能的安全参数组合,但没有成功。SAS令牌由DeviceExplorer生成 #! /usr/bin/python3.5 import serial import time import datetime import os import socket
#! /usr/bin/python3.5
import serial
import time
import datetime
import os
import socket
import ssl
import logging
import paho.mqtt.client as mqtt
import sys
print(sys.executable)
def on_disconnect(client, userdata, rc):
if rc==0:
print("client disconnected OK")
client.connected_flag=False
def on_connect(client, userdata, flags, rc):
if rc==0:
print("Connected OK")
mqtt.Client.connected_flag=True
mqtt.Client.bad_connection_params=False
else:
mqtt.Client.bad_connection_params=True
if rc==1:
print("Failed to connect. Connection refused, unacceptable
protocol version. Error Code=", rc)
elif rc==2:
print("Failed to connect.Connection refused, identifier
rejected. Error Code=", rc)
elif rc==3:
print("Failed to connect.Connection refused, server unavailable. Error Code=", rc)
elif rc==4:
print("Failed to connect.Connection refused, bad user name or password. Error Code=", rc)
elif rc==5:
print("Failed to connect.Connection refused, not authorized. Error Code=", rc)
def on_publish(client, userdata, mid):
if rc==0:
print("Data published OK: ", userdata)
else:
print("Failed to publish data. MessageID=", mid)
pass
broker="myIoTHubName.azure-devices.net"
port=8883
DeviceID="MasterTag"
DeviceKey="myDeviceKey"
IoTHubName="myIoTHubName"
SasToken="SharedAccessSignature sr=myIoTHubName.azure-devices.net&sig=..."
# Create client object
# 4 stands for MQTTv311
rpiclient = mqtt.Client("PahoClient-on-RPi-Gateway2", clean_session=True, userdata=None, protocol=4, transport="tcp")
usernameFormat="{}{}{}"
username=usernameFormat.format(IoTHubName, ".azure-devices.net/", DeviceID)
password=SasToken
rpiclient.username_pw_set(username, password)
rpiclient.tls_set(tls_version=ssl.PROTOCOL_TLSv1_2)
rpiclient.tls_insecure_set(True)
# connection flag indicates that connection was made or not
mqtt.Client.connected_flag = False
# connection parameters are incorrect: ip address, port, authentication, etc
mqtt.Client.bad_connection_params=False
#assign function to callback
rpiclient.on_connect = on_connect
#assign function to callback
rpiclient.on_publish = on_publish
# bind the disconnect callback
rpiclient.on_disconnect = on_disconnect
rpiclient.loop_start()
rpiclient.will_set("dwm/position", "Client PahoClient-on-RPi2 had unexpectedly disconnected", 1, True)
try:
print("Connecting to MQTT broker ",broker)
# Connect to the MQTT Broker
rpiclient.connect(broker, port)
time.sleep(1)
# Wait in a loop until we are connected
print("mqtt.Client.connected_flag={},
格式(mqtt.Client.connected_标志,mqtt.Client.bad_连接_参数))
而mqtt.Client.connected_标志==False和mqtt.Client.bad_连接_参数==False:
打印(“等待连接…”);
时间。睡眠(1)
如果mqtt.Client.bad_connection_params==True:
rpiclient.loop_stop()
sys.exit()
非常感谢您的建议。当您使用MQTT直接连接Azure IoT集线器时,您需要通过TLS/SSL进行连接。为了建立TLS连接,您可能需要下载并引用DigiCert Baltimore根证书,然后为TLS/SSL连接设置证书。请参阅文档
当您使用MQTT直接连接Azure IoT集线器时,您需要通过TLS/SSL进行连接。为了建立TLS连接,您可能需要下载并引用DigiCert Baltimore根证书,然后为TLS/SSL连接设置证书。请参阅文档
以下是使用paho.Mqtt客户端库连接到Azure IoT集线器的模拟设备1的工作示例:
from paho.mqtt import client as mqtt
import time
import ssl
def on_subscribe(client, userdata, mid, granted_qos):
print('Subscribed for m' + str(mid))
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_message(client, userdata, message):
print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos))
def on_log(client, userdata, level, buf):
print("log: ",buf)
device_id = "device1"
iot_hub_name = "myIoTHub"
sas_token = "SharedAccessSignature sr=myIoTHub.azure-devices.net%2Fdevices%2Fdevice1&sig=****&se=1586926815"
client = mqtt.Client(client_id=device_id, protocol=mqtt.MQTTv311, clean_session=False)
client.on_log = on_log
client.tls_set_context(context=None)
# Set up client credentials
username = "{}.azure-devices.net/{}/api-version=2018-06-30".format(iot_hub_name, device_id)
client.username_pw_set(username=username, password=sas_token)
# Connect to the Azure IoT Hub
client.on_connect = on_connect
client.connect(iot_hub_name+".azure-devices.net", port=8883)
# Publish
client.publish("devices/{device_id}/messages/events/".format(device_id=device_id), payload="{}", qos=0, retain=False)
# Subscribing on the topic ,
client.on_message = on_message
client.on_subscribe = on_subscribe
client.subscribe("devices/{device_id}/messages/devicebound/#".format(device_id=device_id))
client.subscribe("$iothub/twin/PATCH/properties/desired/#")
client.subscribe("$iothub/methods/POST/#")
client.loop_forever()
更新:
可以使用设备资源管理器工具生成特定设备的sas_令牌,请参阅以下屏幕片段:
输出日志应如以下屏幕片段所示:
以下是使用paho.Mqtt客户端库连接到Azure IoT集线器的模拟设备1的工作示例:
from paho.mqtt import client as mqtt
import time
import ssl
def on_subscribe(client, userdata, mid, granted_qos):
print('Subscribed for m' + str(mid))
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_message(client, userdata, message):
print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos))
def on_log(client, userdata, level, buf):
print("log: ",buf)
device_id = "device1"
iot_hub_name = "myIoTHub"
sas_token = "SharedAccessSignature sr=myIoTHub.azure-devices.net%2Fdevices%2Fdevice1&sig=****&se=1586926815"
client = mqtt.Client(client_id=device_id, protocol=mqtt.MQTTv311, clean_session=False)
client.on_log = on_log
client.tls_set_context(context=None)
# Set up client credentials
username = "{}.azure-devices.net/{}/api-version=2018-06-30".format(iot_hub_name, device_id)
client.username_pw_set(username=username, password=sas_token)
# Connect to the Azure IoT Hub
client.on_connect = on_connect
client.connect(iot_hub_name+".azure-devices.net", port=8883)
# Publish
client.publish("devices/{device_id}/messages/events/".format(device_id=device_id), payload="{}", qos=0, retain=False)
# Subscribing on the topic ,
client.on_message = on_message
client.on_subscribe = on_subscribe
client.subscribe("devices/{device_id}/messages/devicebound/#".format(device_id=device_id))
client.subscribe("$iothub/twin/PATCH/properties/desired/#")
client.subscribe("$iothub/methods/POST/#")
client.loop_forever()
更新:
可以使用设备资源管理器工具生成特定设备的sas_令牌,请参阅以下屏幕片段:
输出日志应如以下屏幕片段所示:
我刚刚运行了我的代码,并对我在查看您的代码时发现的差异进行了所有调整。我现在得到的信息是:“连接失败。连接被拒绝,服务器不可用。”。错误代码=3“。如果你的代码真的有效,我看到的唯一区别就是SAS。我使用DeviceExplorer生成了我的。你是如何产生你的?我的格式为:SharedAccessSignature sr=myIotHub IoTHub.azure devices.net&sig=***%2Fxxxxxxxxxx%3D&se=1595980678,因此,我确实看到了格式上的差异,不仅仅是内容上的差异……请参阅我的更新。看起来您没有为设备生成sas_令牌。因此,当我成功连接到Azure时,您所指的sas方法可以工作。我在DeviceExplorer中生成的SAS在格式上仍然与您的不同(但我可以接受;-)我的下一个任务是连接到AWS IoT工作,这是我几天来一直在努力的事情…请查看此文档以生成SAS令牌:,还有一个云资源管理器工具,我刚刚运行了我的代码,对我在查看您的代码时发现的差异进行了所有调整。我现在看到:“连接失败。连接被拒绝,服务器不可用。错误代码=3”。如果你的代码真的有效,我看到的唯一区别就是SAS。我使用DeviceExplorer生成了我的。你是如何产生你的?我的格式为:SharedAccessSignature sr=myIotHub IoTHub.azure devices.net&sig=***%2Fxxxxxxxxxx%3D&se=1595980678,因此,我确实看到了格式上的差异,不仅仅是内容上的差异……请参阅我的更新。看起来您没有为设备生成sas_令牌。因此,当我成功连接到Azure时,您所指的sas方法可以工作。我在DeviceExplorer中生成的SAS在格式上仍然与您的不同(但我可以接受;-)我的下一个任务是连接到AWS IoT工作,这是我几天来一直在努力的事情…请查看此文档以生成SAS令牌:,还有一个云资源管理工具,我很难处理您有争议的文档。您提到的同一文档(论坛上的其他团队成员也这么说)说:“如果您使用X.509证书身份验证,则不需要SAS令牌密码。有关更多信息,请参阅在Azure IoT中心中设置X.509安全性”。顺便说一句,假设你是对的:我过去也尝试过这种方法——使用证书和密码——但没有用……如果你想,我可以发布整个源代码。好的,我不是一名科学家,但我确实遵循系统方法,所以我回到了使用您建议的方法的脚本版本,并在不做任何更改的情况下运行了它:……奇迹般地,它成功了!因此,我对您的咆哮表示歉意,但您仍然需要清理您的文档,这些文档当时非常混乱…我必须纠正自己-成功的代码是一个使用SAS方法的代码。在这段代码中,我删除了对证书的所有引用。因此,我的第一点是正确的-在SAS方法中不需要证书。我不确定vise versa是否正确-使用证书是否需要密码…这将是我的下一步…我很难处理您有争议的文档。您提到的同一文档(论坛上的其他团队成员也这么说)说:“如果您使用X.509证书身份验证,则不需要SAS令牌密码。有关更多信息,请参阅在Azure IoT中心中设置X.509安全性”。顺便说一句,假设你是对的:我过去也尝试过这种方法——使用证书和密码——但没有任何效果……如果你愿意,我可以发布整个源代码。好吧,我不是科学家,但我遵循系统方法,所以我回到了使用appr的脚本版本
from paho.mqtt import client as mqtt
import time
import ssl
def on_subscribe(client, userdata, mid, granted_qos):
print('Subscribed for m' + str(mid))
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_message(client, userdata, message):
print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos))
def on_log(client, userdata, level, buf):
print("log: ",buf)
device_id = "device1"
iot_hub_name = "myIoTHub"
sas_token = "SharedAccessSignature sr=myIoTHub.azure-devices.net%2Fdevices%2Fdevice1&sig=****&se=1586926815"
client = mqtt.Client(client_id=device_id, protocol=mqtt.MQTTv311, clean_session=False)
client.on_log = on_log
client.tls_set_context(context=None)
# Set up client credentials
username = "{}.azure-devices.net/{}/api-version=2018-06-30".format(iot_hub_name, device_id)
client.username_pw_set(username=username, password=sas_token)
# Connect to the Azure IoT Hub
client.on_connect = on_connect
client.connect(iot_hub_name+".azure-devices.net", port=8883)
# Publish
client.publish("devices/{device_id}/messages/events/".format(device_id=device_id), payload="{}", qos=0, retain=False)
# Subscribing on the topic ,
client.on_message = on_message
client.on_subscribe = on_subscribe
client.subscribe("devices/{device_id}/messages/devicebound/#".format(device_id=device_id))
client.subscribe("$iothub/twin/PATCH/properties/desired/#")
client.subscribe("$iothub/methods/POST/#")
client.loop_forever()