macvg macvg - 2 years ago 132
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

message = "Hello"
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))

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("", 1883)
while True:
if message=="Start":
print message
elif message=="Stop":
print message

and the node.js:

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

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download