将paho.mqtt.python连接到mosquitto代理时出现套接字错误

问题描述 投票:0回答:1

我正在尝试从python脚本(paho.mqtt.python)连接到mosquitto broker。我可以使用以下命令从终端连接:

mosquitto_sub -h localhost -p 8883 -v -t 'owntracks/#' -u owntracks -P 12qwaszx

但是,当我尝试通过python脚本连接时,我收到错误:

Socket error on client <unknown>, disconnecting.

我正在使用的脚本是示例:(从这里:https://owntracks.org/booklet/tech/program/

import paho.mqtt.client as mqtt
import json

# The callback for when the client successfully connects to the broker
def on_connect(client, userdata, rc):
    ''' We subscribe on_connect() so that if we lose the connection
        and reconnect, subscriptions will be renewed. '''

    client.subscribe("owntracks/+/+")
    #tried also: client.subscribe("owntracks/#")
# The callback for when a PUBLISH message is received from the broker
def on_message(client, userdata, msg):

    topic = msg.topic

    try:
        data = json.loads(str(msg.payload))

        print "TID = {0} is currently at {1}, {2}".format(data['tid'], data['lat'], data['lon'])
    except:
        print "Cannot decode data on topic {0}".format(topic)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("localhost", 8883, 60)

# Blocking call which processes all network traffic and dispatches
# callbacks (see on_*() above). It also handles reconnecting.

client.loop_forever()

这是我的配置文件的内容(我从我的真实IP改变了“localhost” - 尝试了两者):

# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 8883 "localhost"
persistence true
persistence_location /var/lib/mosquitto/
persistence_file mosquitto.db
log_dest syslog
log_dest stdout
log_dest topic
log_type error
log_type warning
log_type notice
log_type information
connection_messages true
log_timestamp true
allow_anonymous false
password_file /etc/mosquitto/pwfile

任何帮助将受到高度赞赏。

python python-3.x mqtt mosquitto paho
1个回答
0
投票

您的python脚本正在尝试连接到看起来像TLS安全设置的内容,而没有准备客户端连接方法将这些详细信息应用于事务。请尝试以下方法:

def ssl_prep():
        ssl_context = ssl.create_default_context()
        ssl_context.load_verify_locations(cafile=ca)
        ssl_context.load_cert_chain(certfile=mycert, keyfile=priv)
        return  ssl_context

ca = "PATH_TO_YOUR_CA_FILE"
priv = "PATH_TO_YOUR_PEM_FILE"
mycert = "PATH_TO_YOUR_CERT_FILE"
topics = "YOUR_TOPICS"
broker = "BROKER_URL"
client = mqtt.Client()
ssl_context= ssl_prep()

client.tls_set_context(context=ssl_context)
client.username_pw_set(username="UNAME",password="PASS")
client.connect(broker, port=8883)

通过在尝试之前为连接尝试提供ssl上下文,假设您具有特定于您自己的设置的所有详细信息,则应该连接。

© www.soinside.com 2019 - 2024. All rights reserved.