Mqtt broker connection with username and password - python

It's my first time trying to connect to a mqtt broker and it's not really going great. I've been trying to get data from the broker but am unable to figure out how to connect. I've been handed a username, password, port and encrypted port aswell as "Topics. When trying to connect the "client.connect"-line responds with "0". I changed the username and password and I still get the same result so there is something wrong with my configuration. Any help would be much appreciated!
I'm running python 3.6.5
import paho.mqtt.client as mqtt
import time
username="temp"
password="temp"
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("extapi/data/esm")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username, password)
client.connect("example.io", 1883, 60)

Related

Connection is established, but unable to retrieve message payload on paho mqtt client

My client is unable to receive message payload from the MQTT server. I had set mosquitto on my PC to act as both the server and publisher and execute the following command:
mosquitto_pub -h 192.168.1.2 -t topic/test -m "testing" -i simulator -d
Subscribing myself works and payload is received.
However, my client which is using paho mqtt only received successful connection without the payload message. So i have the following code here:
def on_connect(client, userdata, flags, rc):
print("connection ok")
client.subscribe("topic/test")
def on_message(client, userdata, msg):
print("Message received! " + str(msg.payload))
if msg.payload == "testing":
print("Message received")
# Do something
...
def main():
#MQTT
broker = "192.168.1.2" #broker ip
client = mqtt.Client("simulator")
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker, 1883, 60)
client.loop_start()
while(1):
...
So it did managed to print "connection ok", but not "Messaged received! ..."
You are using the same client-id (simulator) with mosquitto_pub and in your python. As per the spec:
If the ClientId represents a Client already connected to the Server then the Server MUST disconnect the existing Client
So what is happening is:
Python client connects and subscribes.
mosquitto_pub connects, broker disconnects python client.
mosquitto_pub publishes the message (but as nothing is subscribed the QOS 0 message will be dropped by the broker).
Python client reconnects and subscribes again.
Try using a different client-id with mosquitto_pub (your code works fine when I test it in that way - added a time.sleep(1) in the while(1)).

Python/paho MQTT - not receiving messages

I am new to using MQTT and I would like to run two Python programs simultaneously: one to publish messages to a topic and the other to print out the messages as they are published to the topic. However, the callback function to print out the message isn't working for me.
These are the two programs I have:
Publish messages:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected! Result code: " + str(rc))
client = mqtt.Client(client_id="clientID")
client.on_connect = on_connect
client.username_pw_set(username="username", password="password")
client.loop_start()
client.connect("node02.myqtthub.com", 1883)
while True:
client.publish("my/topic", "test")
Subscribe to and print messages:
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
print(msg.payload.decode())
def on_connect(client, userdata, flags, rc):
print("Connected! Result code: " + str(rc))
client.subscribe("my/topic")
client = mqtt.Client(client_id="clientID")
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username="username", password="password")
client.connect("node02.myqtthub.com", 1883)
client.loop_forever()
Could someone help me fix this issue?
Both programs are using client_id="clientID"; the mqtt spec states
If the ClientId represents a Client already connected to the Server then the Server MUST disconnect the existing Client [MQTT-3.1.4-2].
So whichever app connects second will cause the first to be disconnected. To fix this change the client id in one of the apps.
Note: This is a comment on something obviously wrong. When asking a question please state what you see happening (any output, errors, what you have tried etc) because there may be another problem.

Not receiving expected message from the broker using paho-mqtt python

This is my code
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc): # The callback for when the client connects to the broker
print("Connected with result code {0}".format(str(rc))) # Print result of connection attempt
def on_message(client, userdata, message): # The callback for when a PUBLISH message is received from the server.
print("message received " ,str(message.payload.decode("utf-8")))
print("message topic=",message.topic)
print("message qos=",message.qos)
print("message retain flag=",message.retain)
#creating client instance
client = mqtt.Client(client_id="random_id_name")
print("client created ......")
client.on_connect = on_connect # Define callback function for successful connection
client.on_message = on_message # Define callback function for receipt of a message
#connecting to broker/server
hostname = "hostname_I_am_trying_to_connect" #give the host/server/broker name
portnumber = **random_port_number_as_integer_value** #give the port number
client.username_pw_set("username", "password") #give the username and password for the broker/server/host
client.connect(host= hostname ,port= portnumber)
print("client connected to- ",hostname," on port_number:",portnumber)
client.subscribe("login")
print("subscribed to the topic")
client.publish("login","some_message")
print("message published")
client.loop_forever() # Start networking daemon
Here I am expecting to receive some_message/unique_id from the broker , i.e. 1234/1234_qyehfj_1234_jfjfj.
Instead, I am receiving some random numbers. See the screenshot:
What is the problem here? Is the problem in my code or something wrong with the broker I am sending messages to?
If something is wrong with the code please let me know how to fix this.
I solved the problem last night. So here I am going to explain what happened.
I subscribed to the wrong topic, that's why I was receiving everything that other people may or may not have published on that particular topic.
In the future, if anyone is facing the same problem, double-check if you are subscribed to the right topic.

How to test the python paho mqtt with mosquitto?

I want to test the mosquitto MQTT Python client ports.
import json
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
"""Called when connected to MQTT broker."""
client.subscribe("hermes/intent/#")
client.subscribe("hermes/nlu/intentNotRecognized")
print("Connected. Waiting for intents.")
def on_disconnect(client, userdata, flags, rc):
"""Called when disconnected from MQTT broker."""
client.reconnect()
def on_message(client, userdata, msg):
"""Called each time a message is received on a subscribed topic."""
nlu_payload = json.loads(msg.payload)
if msg.topic == "hermes/nlu/intentNotRecognized":
sentence = "Unrecognized command!"
print("Recognition failure")
else:
# Intent
print("Got intent:", nlu_payload["intent"]["intentName"])
# Speak the text from the intent
sentence = nlu_payload["input"]
site_id = nlu_payload["siteId"]
client.publish("hermes/tts/say", json.dumps({"text": sentence, "siteId": site_id}))
# Create MQTT client and connect to broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.connect("localhost", 1883)
client.loop_forever()
I run it with the command
$ python script.py`
Connected. Waiting for intents.
Does mosquitto send a POST request? or do I have to start a request with mosquitto? How should I create a request so that I get
Got intent: SetTimer
MQTT is not HTTP, POST is a HTTP verb that has no meaning in a MQTT context.
MQTT is a pub/sub protocol, where as HTTP is a request/response protocol.
The code you have posted only subscribes to 2 topics, it doesn't publish anything (until it receives a message). So unless you have another application that will publish a message to 1 of the 2 topics the python code has subscribed to it will just sit there and wait for a message.
You can use the mosquitto command line tools to send a message if needed. e.g.
mosquitto_pub -t hermes/intent/foo -m '{"intent": { "intentName": "SetTimer"}}'

MQTT Client not receiving messages

I'm using the following code from MQTT Paho project to subscribe to messages from my mqtt broker. I tested the connection using mosquitto_sub and I receive the messages there. However, when I run the following code it doesn't receive any messages and no output is printed. I checked the topic and host.
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("test")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_forever()
The following error is logged by the broker:
Invalid protocol "MQTT" in CONNECT from ::1.
Socket read error on client (null), disconnecting.
EDIT Thanks to #hardillb for pointing out the outdated MQTT version.
Everything worked after I did the following:
sudo apt-get purge mosquitto
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
sudo apt-get install mosquitto
This is most likely because you are using an old version of mosquitto and the python is expecting a newer build that supports MQTT 3.1.1
Try changing the code as shown:
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("test")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# Change made HERE
client = mqtt.Client(protocol=MQTTv31)
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_forever()
You should also upgrade your broker as soon as possible, that version is incredibly out of date and has a number of known issues, the current version is 1.4.10

Categories

Resources