macvg macvg - 5 months ago 26
Node.js Question

mqtt between python and node.js sends only one message

I am new to mqtt and python system and I am trying to do some heavy computations in python and send the results to a node.js server.

Every time I run node.js script i get only one result. Here is my simple
code:

simple_mqtt.py

message = "Hello"
x=0
def add():
global x
x = x + 1

def on_publish(client, userdata, mid):
print("mid: "+str(mid))

def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("main/app")

def on_message(client, userdata, msg):
global message
message = msg.payload

client = paho.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish
client.connect("192.168.2.4", 1883)
client.loop_start()
while True:
if message=="Start":
print message
add()
client.publish("main/app",x)
elif message=="Stop":
print message
client.publish("main/app","Ended")
time.sleep(1)


and the node.js:

var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.2.4:1883');

client.on('connect', function () {
client.subscribe('main/app');
client.publish('main/app', 'Start');
});
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString());
});


What I have to modify to get continuous responses from the python until I send the message "Stop"?

Answer

You're using the same topic for both control and output.

So after receiving a message with Start your code publishes 1 to the main/app topic and this is immediately received by the python code in on_message and sets message to 1

So the next time round the loop message is 1 so none of the if statements match.

Comments