简体   繁体   中英

MQTT Sub and Publish on same project

I designed a MQTT project on localhost, with Python Tkinter UI. I have a textbox there. When I click publish button, I want my "subclient" to subscribe the defined topic, and after subscribing, i want my another client "pubclient" to recognize the message comes from pubclient and trigger a function.

I did something wrong but cant figuere out. No errors.

       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) 

First you should only have one client, it can both subscribe and publish at the same time.

Second you need to start the paho client network loop . If you don't start the loop then you will never receive any messages or be able to send any message larger than a single packet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM