如何在paho-mqtt python中使用两个线程?

时间:2016-09-29 15:34:46

标签: python mqtt python-multithreading paho

我想实现一个程序,我在一个线程上接收消息,在另一个线程中我想发送消息(发送消息与接收的主题无关)我已经编写了一个示例代码,但它没有&# 39;因为我能够发布消息但无法接收订阅主题的消息。

import paho.mqtt.client as mqtt
from ConfigParser import SafeConfigParser
import sys
import time
import thread
connection="/raspberrypi"
setup="/setup"
setupIn="/raspberrypi/setup/"
slash="/"
setupTopic = "/raspberrypi/"
commands = "/commands"
setupbool=0
curr_device_id = "none"
setupcounter=0
parser = SafeConfigParser()

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(connection)
    client.subscribe(setupIn)
    try:
        thread.start_new_thread(command())
    except Exception as e:
        print "Error: unable to start thread"
        print e
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
def on_message_callback(client, userdata, msg):
    goto(msg.topic,msg.payload)

def goto(topic,message):
    global setupbool
    global curr_device_id
    global setupcounter
    parser.read('deviceInfo.ini')
    print(topic+" "+str(message))
    if(setupbool==1 and curr_device_id == topic.split('/')[2] and message !='done'):
        print "Inside setup procedure"
        if(':' in message):
            option = message.split(':')[0]
            value = message.strip(message.split(':')[0]+':')
            print option
            print value
            parser.set(curr_device_id,option,value)
            with open('deviceInfo.ini', 'w') as configfile:   
                parser.write(configfile)
            topic = slash+curr_device_id+setup
            setupcounter = setupcounter + 1
            client.publish(topic,str(setupcounter))
            return;
        else:
            print message
    if(setupbool==1 and curr_device_id == topic.split('/')[2] and message =='done'):
        print "Setup procedure complete"
        setupbool=0
        topic = slash+curr_device_id+setup
        client.publish(topic,'-1')
        setupcounter=0
        parser.set(curr_device_id,'setupStatus','Done')
        with open('deviceInfo.ini', 'w') as configfile: 
            parser.write(configfile)
        curr_device_id = 'none'#changed
        return;
    topi = message
    if(topic == connection and curr_device_id in 'none'):
        for section_name in parser.sections():
            print section_name
            if(section_name == topi):
                print parser.get(topi,'discoveryStatus')
                if(parser.get(topi, 'discoveryStatus') == "Done" and parser.get(topi,'setupStatus')=="Left"):

                    curr_device_id=topi
                    print curr_device_id
                    topi=slash+topi
                    client.publish(topi,'1')
                    setupTopic = topi + "/setup"
                    setup_topic = connection + slash + message + setup
                    client.subscribe(setup_topic) 
                    time.sleep(1)
                    client.publish(setupTopic,str(setupcounter))
                    setupbool=1
                    return;
                else:
                    print "Here"
                    topi = slash + topi
                    client.publish(topi,'1')
                    return;
        parser.add_section(topi)
        parser.set(topi,'devicetype',(message.split('0')[0]))
        parser.set(topi,'discoveryStatus','Done')
        parser.set(topi,'setupStatus','Left')
        parser.set(topi,'room','Default')
        with open('deviceInfo.ini', 'w') as configfile: 
            parser.write(configfile)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message_callback

def command():
    while True:
        parser.read('deviceInfo.ini')##put this line in new call back
        query = raw_input('Command:')
        for section_name in parser.sections():
            if((parser.get(section_name,'setupStatus')=="Done" )and (parser.get(section_name,'devicetype') in query)):
                for(each_key, each_val) in parser.items(section_name):
                    if(each_key in query):
                        print each_val
                        top = slash+section_name+commands
                        client.publish(top,each_val)
client.connect("ip", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

0 个答案:

没有答案