首页 > 解决方案 > 为什么带有 autorun script.py 的 mqtt 无法稳定与 broker 的连接?

问题描述

我正在尝试在 python 中自动运行一个脚本。该脚本管理多个 LED 并通过 MQTT 进行通信。

如果我尝试通过 shell(没有自动运行)运行脚本,我的连接工作没有任何问题。

如果我尝试自动运行脚本,它会正确启动,但与代理的连接会在无限循环中不断上升、下降、上升、下降、上升……。它无法建立连接。

自动运行脚本加载在 /etc/profile -> sudo python3 script/path.py

什么可能导致这个问题?

def Connect(client,broker,port,keepalive,run_forever=False):
    #"""Attempts connection set delay to >1 to keep trying
    #but at longer intervals  """
    connflag=False
    delay=5

    print('--------------------------------')
    print("connecting " + client_id)
    badcount=0 # counter for bad connection attempts
    while not connflag:
        logging.info("connecting to broker "+str(broker))
        print("connecting to broker "+str(broker)+":"+str(port))
        print("Attempts ",badcount)
        try:
            res=client.connect(broker,port,keepalive)      #connect to broker
            if res==0:
                print('--------------------------------')
                print("Connection established")
                print('--------------------------------')
                connflag=True
                return 0
            else:
                logging.debug("connection failed.")
                print('--------------------------------')
                badcount += 1
                if badcount>=3 and not run_forever: 
                    raise SystemExit #give up

                elif run_forever and badcount<3:
                    delay=5
                else:
                    delay=3
[...........................................................]
[..................other stuff.................]
[...........................................................]


def on_connect(client, userdata, flags, rc):
    print('--------------------------------')
    logging.debug("Connected flags"+str(flags)+"result code "  + str(rc) + "client RPi Giulio")
    if rc == 0:
        print("Connected OK. Returned code = ", rc)
        print('--------------------------------')
        client.connected_flag  = True
        client.publish(connected_topic,1,retain=True)

    else:
        print("Bad connection. Returned code = ", rc)
        print('--------------------------------')
        client.bad_connection_flag = True

解决方案:CRONTAB https://www.dexterindustries.com/howto/auto-run-python-programs-on-the-raspberry-pi/

标签: python-3.xbashmqtt

解决方案


正如评论中所述,这纯粹是基于非常有限的可用信息的猜测。

客户端保持连接/断开连接的通常原因是因为您有多个具有相同 clientid 的客户端。

您一次只能有一个客户端连接到具有给定客户端 ID 的代理,如果第二个客户端连接,则第一个客户端将被启动。如果第一个客户端然后尝试重新连接,它将关闭第二个客户端并再次启动序列。

因为.profile它是为每个登录 shell 运行的,所以您最终可能会运行许多客户端实例。

您需要确保您只启动一个客户端副本并且它具有唯一的客户端 ID。


推荐阅读