簡體   English   中英

MQTT Sub 和 Publish 在同一個項目上

[英]MQTT Sub and Publish on same project

我在 localhost 上設計了一個 MQTT 項目,使用 Python Tkinter UI。 我在那里有一個文本框。 當我單擊發布按鈕時,我希望我的“子客戶端”訂閱定義的主題,訂閱后,我希望我的另一個客戶端“pubclient”識別消息來自 pubclient 並觸發 function。

我做錯了什么,但無法弄清楚。 沒有錯誤。

       def func_sendanswer():

            def func_on_message(client, userdata, mesaj):
                print("Gelen Mesaj:")  
                print(mesaj)
                print("")

                conn = psycopg.connect("dbname=MQTTDB user=postgres host='localhost' password='dbpassword")
                cur = conn.cursor()

                cur.execute('INSERT INTO answers(answercontent, creatorid, topicid, createddate) VALUES (%s,%s,%s,current_timestamp)', (mesaj, online_userid, topicid))
                conn.commit()
                cur.close()        
                conn.close()

                func_refreshconversation()
    
            subclient= paho.Client("subscriber") #create client object 
            subclient.on_message=func_on_message
            
            print("connecting to broker host","localhost")
            subclient.connect("localhost")#connection establishment with broker
            print("subscribing begins here")    
            subclient.subscribe(string_topicname)#subscribe topic

            def func_refreshconversation():
                conn = psycopg.connect("dbname=MQTTDB user=postgres host='localhost' password='dbpassword'")
                cur = conn.cursor()

                cur.execute("SELECT answercontent, creatorid, createddate FROM answers WHERE topicid ='"+ str(temp[0]) +"';")
                temp2 = cur.fetchall()

                text_conversation.delete("1.0","end")

                for row in temp2:
                 
                    text_conversation.insert(END, "\n" + "Kullanıcı ID: " + str(row[1]) + "\n" + "\n" + str(row[0]) +"\n" + "Tarih: " + str(row[2]) + "\n" + "___________________________________________________" + "\n")

                cur.close()        
                conn.close()

            pubclient= paho.Client("publisher") #create client object
            mesaj = text_sendmessage.get('0.0', 'end')
            ret= pubclient.publish(string_topicname,mesaj) 

首先你應該只有一個客戶端,它可以同時訂閱和發布。

其次,您需要啟動 paho 客戶端網絡循環 如果您不啟動循環,那么您將永遠不會收到任何消息或能夠發送任何大於單個數據包的消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM