Python Flask App with MQTT

2019-08-24 01:56发布

I'm trying to use my Flask app as a subscriber, but it does not call the on_message callback when receiving a message. Instead, I get about like the following:

Connected with result code 0
Closing data file...
Connected with result code 0
Closing data file...

This is how I am running the Flask app:

main.py:

from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
import paho.mqtt.client as mqtt
import time

broker_address = <broker_ip>
port = 1883
timeout = 60
username = "first"
password = "last"
uuid = "1234"
topic = "mytopic"
qos = 0



def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

    client.subscribe(topic)

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload) + '\n')

def on_disconnect(client, userdata, rc):
    print("Closing data file...")

client = mqtt.Client(client_id=uuid)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.username_pw_set(username, password)

client.connect(broker_address, port, 60)
client.loop_start()

<other Flask code>

if __name__ == "__main__":
    app.run(debug=True)

I've tried using a another Python script to generate some fake data to publish to the topic, but only when that script is running to I get the output above. If that script is not running, then the main.py seems to wait for messages. This is the other script:

fake_data.py:

import paho.mqtt.client as mqtt
import time

broker_address = <broker_ip>
port = 1883
timeout = 60
username = "first"
password = "last"
uuid = "1234"
topic = "mytopic"
qos = 0



def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

client = mqtt.Client(client_id=uuid, clean_session=True)
client.on_connect = on_connect

client.username_pw_set(username, password)

client.connect(broker_address, port, 60)


client.loop_start()

while True:
    count = 0
    while count != 30:
        print("Publishing {0}".format(count))
        client.publish(topic, count, qos=0)
        count += 1
        time.sleep(1)

My question is why the Flask app keeps connecting and disconnecting endlessly without actually processing a message.

标签: flask mqtt
1条回答
唯我独甜
2楼-- · 2019-08-24 02:14

The client id needs to be different for all clients connected to a broker. In the code you've posted both the subscriber and the publisher are using the same client id (uuid=1234).

When 2 clients with the same client id connect to the broker, the broker will kick the oldest off. If this is then set to reconnect it will then kick the second one off.

Set uuid to different values.

查看更多
登录 后发表回答