问题
I have mosca mqtt broker runnning. I connect to it using paho-mqtt from a python client. I have two threads which I run parallely in my code, one to receive messages and the other to publish.
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()
Every time a publish happens client gets disconnected.
sending command
published
Client Got Disconnected
rc value: 1
Unexpected MQTT disconnection. Will auto-reconnect
connected OK Returned code= 0
I tried commenting the client.publish
line, still I then disconnection is happening. So my doubt is this disconnection something to do with multi thread or some problem with broker itself. can anyone help me with this?
来源:https://stackoverflow.com/questions/58705344/mqtt-client-gets-disconnected-frequently-when-running-on-multiple-threads