我正在运行mosca mqtt经纪人。我从python客户端使用paho-mqtt连接到它。我有两个线程在我的代码中并行运行,一个线程接收消息,另一个线程发布。
def SendCommand(rpm,valve_opening):
control_packet = {
########
}
print(control_packet)
print('sending command')
# client.publish("cmd",control_packet)
def on_connect(client, userdata, flags, rc):
if rc==0:
print("connected OK Returned code=",rc)
client.subscribe('data/#')
else:
print("Bad connection Returned code=",rc)
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
print("rc value: " + str(rc))
if rc != 0:
print('Unexpected MQTT disconnection. Will auto-reconnect')
else:
print('rc value:' + str(rc))
def on_publish(client,userdata,message):
print("published.")
def on_message(client, userdata, message):
# obs = [] calculate based on message
def Agent():
action, _states = model.predict(obs)
SendCommand(fan_rpm,chw_flow)
def Controls():
schedule.every(30).seconds.do(Agent)
while True:
schedule.run_pending()
def mqttConnection():
global client
client = mqtt.Client(client_id='Client_test', clean_session=True) #create new instance
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.on_publish = on_publish
print("connecting to broker")
client.connect(broker_address, port=port) #connect to broker
client.loop_forever() #stop the loop
#########################################################################################
import threading
t1 = threading.Thread(target=Controls)
t1.daemon = False
t1.start()
t2 = threading.Thread(target=mqttConnection)
t2.daemon = False
t2.start()
每次发布时,客户端都会断开连接。
sending command
published
Client Got Disconnected
rc value: 1
Unexpected MQTT disconnection. Will auto-reconnect
connected OK Returned code= 0
我尝试注释client.publish
行,但仍然断开连接。因此,我怀疑这种断开与多线程有关,还是与代理本身有关。有人可以帮我吗?