python-3.x - 为什么带有 autorun script.py 的 mqtt 无法稳定与 broker 的连接?
问题描述
我正在尝试在 python 中自动运行一个脚本。该脚本管理多个 LED 并通过 MQTT 进行通信。
如果我尝试通过 shell(没有自动运行)运行脚本,我的连接工作没有任何问题。
如果我尝试自动运行脚本,它会正确启动,但与代理的连接会在无限循环中不断上升、下降、上升、下降、上升……。它无法建立连接。
自动运行脚本加载在 /etc/profile -> sudo python3 script/path.py
什么可能导致这个问题?
回顾:
通过 shell -> 一切正常,没问题
通过自动运行-> 启动正常,连接 up-down-up-down-....
python中的脚本,与代理的连接:
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
Broker 实例显示:
RPiGiulio/连接/状态 0
RPiGiulio/连接/状态 1
RPiGiulio/连接/状态 0
RPiGiulio/连接/状态 1
RPiGiulio/连接/状态 0
RPiGiulio/连接/状态 1
[.......................]
自动运行脚本命令:
写@sudo nano /etc/profile
sudo python3 /home/pi/..../main.py &
解决方案:CRONTAB https://www.dexterindustries.com/howto/auto-run-python-programs-on-the-raspberry-pi/
解决方案
正如评论中所述,这纯粹是基于非常有限的可用信息的猜测。
客户端保持连接/断开连接的通常原因是因为您有多个具有相同 clientid 的客户端。
您一次只能有一个客户端连接到具有给定客户端 ID 的代理,如果第二个客户端连接,则第一个客户端将被启动。如果第一个客户端然后尝试重新连接,它将关闭第二个客户端并再次启动序列。
因为.profile
它是为每个登录 shell 运行的,所以您最终可能会运行许多客户端实例。
您需要确保您只启动一个客户端副本并且它具有唯一的客户端 ID。
推荐阅读
- git - git pull 后的 Laravel 致命错误
- xcode - clang:错误:安装 sumo-planetsumo 时链接器命令失败,退出代码为 1
- java - Android Jetty 致命异常
- php - 数组中的查找键在存在时找不到文本
- go - 如何在 Go/Golang 中使用 map[string]string 或自定义结构?
- docker - docker-compose:找不到命令詹金斯管道
- android - 如何使用子片段管理 Backstack?
- single-sign-on - 使用 Google-Account 登录 Alfresco
- javascript - 在 Grape Js 中为子元素添加属性?
- linux - 在 Linux 系统调用序列中区分 execve() 的解释器