0

我有 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条线,但我仍然在断开连接。所以我怀疑这种断开与多线程或代理本身的一些问题有关。谁能帮我这个?

4

0 回答 0