Hi there
I wonder if someone could help me with publishing messages on mqtt. I'm totally confused -
The relevant bit of my code is below:-
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisisthekey'
#CORS(app, resources={r"/*": {"origins": "*"}})
auth = HTTPBasicAuth()
app.config['MQTT_BROKER_URL'] = 'test.mosquitto.org'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = '' # Set this item when you need to verify username and password
app.config['MQTT_PASSWORD'] = '' # Set this item when you need to verify username and password
app.config['MQTT_KEEPALIVE'] = 5 # Set KeepAlive time in seconds
app.config['MQTT_TLS_ENABLED'] = False # If your server supports TLS, set it True
topic = 'test111'
mqtt_client = Mqtt(app)
@mqtt_client.on_connect()
def handle_connect(client, userdata, flags, rc):
if rc == 0:
print('Connected successfully')
mqtt_client.subscribe(topic) # subscribe topic
else:
print('Bad connection. Code:', rc)
@mqtt_client.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
print('Received message on topic: {topic} with payload: {payload}'.format(**data))
@app.route('/publish', methods=['GET', 'POST'])
def publish_message():
#mqtt_topic = request.args.get('topic')
#mqtt_message = request.args.get('message')
#complete_message = jsonify(topic= mqtt_topic, message = mqtt_message)
mqtt_client.publish('home/mytopic', 'hellow world')
#print(jsonify({'code': publish_result[0]}))
return (mqtt_topic + mqtt_message)
I have fiddled about quite a lot; sending url arguments / putting the message into json format etc... , but eventually just to check if it basically functions the route just publishes 'home/mytopic', 'hellow world'.
It receives messages fine, but if I try to publish something, there is no error, but it doesn't seem to get published (I am subscribed to the topic in an mqtt node in Node Red ) I can send messages from Node Red, but can't receive them.
Is there something obvious I'm missing?
Any help would be much appreciated.
Kind regards
Paul.