与M2MQTT Paho Python客户端连接到Azure IoT中心 [英] Connecting with M2MQTT Paho Python client to Azure IoT Hub

查看:103
本文介绍了与M2MQTT Paho Python客户端连接到Azure IoT中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码尝试连接到Azure IoT中心.它使用SAS,因此不需要安全证书.我已使用C#中的相同M2MQTT库成功连接到Azure IoT中心,但是此代码失败并显示以下内容:连接失败.连接被拒绝,未经授权.错误代码= 5

I am using the following code in attempt to connect to Azure IoT Hub. It uses SAS, therefore no security certificates are needed. I am successfully connecting to Azure IoT Hub using the same M2MQTT library in C# but this code fails with: Failed to connect.Connection refused, not authorized. Error Code= 5

我尝试了任何可能的安全性参数组合,但无济于事.SAS令牌由DeviceExplorer生成.

I tried any possible combos of security parameters but at no avail. The SAS token is generated by DeviceExplorer.

#! /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.bad_connection_params = {}.format(mqtt.Client.connected_flag,mqtt.Client.bad_connection_params))而mqtt.Client.connected_flag == False和mqtt.Client.bad_connection_params == False:print(正在等待连接...");time.sleep(1)如果mqtt.Client.bad_connection_params == True:rpiclient.loop_stop()sys.exit()

mqtt.Client.bad_connection_params={}".format(mqtt.Client.connected_flag, mqtt.Client.bad_connection_params)) while mqtt.Client.connected_flag == False and mqtt.Client.bad_connection_params == False: print("Waiting for connection..."); time.sleep(1) if mqtt.Client.bad_connection_params == True: rpiclient.loop_stop() sys.exit()

except Exception as ex:
    print("Connection to MQTT Broker failed: ", ex)

rpiclient.loop_stop()

# Disconnect MQTT Client
rpiclient.disconnect()

任何建议都值得赞赏.

推荐答案

以下是使用paho.Mqtt客户端库连接到Azure IoT中心的模拟 device1 的工作示例:来自paho.mqtt的

the following is a working example of the simulated device1 connected to the Azure IoT Hub using a paho.Mqtt client library:

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

更新:

可以使用 Device Explorer 工具生成特定设备的sas_token,请参见以下屏幕片段:

The sas_token for the specific device can be generated using the Device Explorer tool, see the following screen snippet:

,输出日志应类似于以下屏幕片段:

and the output log should be looked like the following screen snippet:

这篇关于与M2MQTT Paho Python客户端连接到Azure IoT中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆