0

I want to implement a program in which I receive messages on one thread and in the other thread I want to send messages (Sending messages are independent of the received topic) I've written a sample code but it doesn't work as I am able to publish messages but not able to receive messages on the subscribed topics.

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()
  • You running this on Linux or Windows? – DisappointedByUnaccountableMod Sep 29 '16 at 18:29
  • BTW topics shouldn't begin with /: "It is allowed to use a leading forward slash in MQTT, for example /myhome/groundfloor/livingroom. But that introduces a unnecessary topic level with a zero character at the front. That should be avoided, because it doesn’t provide any benefit and often leads to confusion." from http://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices – DisappointedByUnaccountableMod Sep 29 '16 at 18:31
  • Also, it is unusual to use the thread module - the higher-level treading module is more common. – DisappointedByUnaccountableMod Sep 29 '16 at 18:33
  • You haven't exactly posted a MVCE - see http://stackoverflow.com/help/mcve there is far too much code to spot a possible problem. Suggest you strip out the call to goto() and see if on_message_callback is called by simply printing the message/topic. Possibly, you are getting an exception, with threading they can happen invisibly unless you put some explicit try/except statements in. – DisappointedByUnaccountableMod Sep 29 '16 at 18:42

0 Answers0