Python paho-mqtt Connect to MQTT broker - python

I'm using this python script to implement a Paho(MQTT) subscriber but i am unable get any responce messages.i am able to subscribe mqtt brokerin command prompt by using mosquitto_sub -t "" -d -h -p 8883 --psk foo --psk-identity bar --insecure --tls-version tlsv1
import paho.mqtt.client as mqtt
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("*********")
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("*********", 8883, 60)
client.loop_forever()
When I run above python script then it does not respond any error or message but keep going with loop , I also run it line by line and when I run client.connect("*********", 8883, 60) then it shows only 0 . please note here without psk and psk-identity we cannot connect to broker.
Thanks

Please check with your topic carefully, sometimes missing of / or # cause this problem.
or
Try This
def on_message(client, userdata, msg):
print("Message Recieved from broker: " + msg.payload.decode())

Related

Error 128 (0x80) while trying to subscribe to topic with paho-mqtt

I'm using hbmqtt 0.9.6 as a broker and paho-mqtt 1.5.1 as a client. Both of them support MQTT v3.1.1.
Broker configuration:
listeners:
default:
type: tcp
halp:
max-connections: 33
bind: 127.0.0.3:1883
topic-check:
enabled: false
auth:
allow-anonymous: true
Client code:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe('abc')
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
def on_subscribe(mosq, obj, mid, qos):
print("Subscribed: " + str(mid))
print("Granted QoS: " + str(qos[0]))
client = mqtt.Client(client_id="subscriber", transport="tcp")
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.connect("127.0.0.3", 1883)
client.loop_forever()
The client establishes a connection to the broker correctly and can send messages to the broker without any problems. But when I try to subscribe to a topic, I receive Granted QoS: 128. What can cause that kind of problem?
What I've tried:
Change topic name
Change IP address and port
Change transport from TCP to ws
Change OS (tried on Armbian and Ubuntu)
Use authentication with login:password
Fraschbi was right. The problem was with the specified version of hbmqtt: it ignored permission configurations. A workaround is to specify what topics the client can subscribe to.

python paho mqtt can not connect to mqtts with username and password

The following python code on my raspberrypi doesn't connect to my mqtt broker, it just hangs after printing Connecting...:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client(client_id="",clean_session=True,userdata=None,protocol=mqtt.MQTTv311,transport="tcp")
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username="stackoverflow",password="stackoverflow")
print("Connecting...")
client.connect("learn.evermight.net", 9101, 10)
client.loop_forever()
What did I do wrong with my Python code?
Command Line Success
I confirmed that my mqtt does work because I can subscribe from terminal with this command:
mosquitto_sub -h learn.evermight.net -p 9101 -t "test" -u "stackoverflow" -P "stackoverflow" --capath /etc/ssl/certs/
And I will see messages in my terminal as soon as I run this command from another terminal
mosquitto_pub -h learn.evermight.net -p 9101 -t "test" -u "stackoverflow" -P "stackoverflow" -m "hello world" --capath /etc/ssl/certs/
What is wrong with my python code?
NodeJS Success
Additionally, the following NodeJS code also works for connecting and publishing to my MQTT server.
const mqtt = require('async-mqtt');
try{
const client = await mqtt.connectAsync("mqtts://learn.evermight.net",{
port:9101,
host:"mqtts://learn.evermight.net",
username:"stackoverflow",
password:"stackoverflow",
connectTimeout:5000,
protocolId:"MQIsdp",
protocolVersion:3,
encoding:"utf8",
keepalive: 60
});
await client.publish("test","hello world");
await client.end();
} catch(e) {
console.log(e);
}
Website JavaScript Success
And the following code can also connect to a websocket port via web browser javascript website, subscribe to the test topic and receive published messages (note that my websockets use port 9102)
import Paho from "paho-mqtt";
const client = new Paho.Client("learn.evermight.net",9102,"WebBrowser");
client.onConnectionLost = response=>console.log("lostMQTTConnection: " +(response.errorCode !== 0 ? response.errorMessage : "Unknown MQTT Error" ));
client.onMessageArrived = message=>console.log(message.payloadString);
client.connect({
onSuccess:_=>client.subscribe("test"),
useSSL:true,
userName:"stackoverflow",
password:"stackoverflow",
});
I found that I can connect if I add this command without arguments
client.tls_set()
In paho documentation at the end of description for tls_set() you can see
Must be called before connect*().
but it works for me even after client.connect()
In the same domentation you can see that without arguments it uses defult system settings
By default, on Python 2.7.9+ or 3.4+,
the default certification authority of the system is used.
On older Python version this parameter is mandatory.
It is needed only if mosquitto_sub/mosquitto_pub needs --capath /etc/ssl/certs/.
If mosquitto_sub/mosquitto_pub works without --capath /etc/ssl/certs/ then don't use it.
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code", rc)
client.subscribe("test")
def on_message(client, userdata, msg):
print(msg.topic, msg.payload)
client = mqtt.Client(client_id="", clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")
client.on_connect = on_connect
client.on_message = on_message
client.tls_set() # <--- even without arguments
client.username_pw_set(username="stackoverflow", password="stackoverflow")
print("Connecting...")
client.connect("learn.evermight.net", 9101, 10)
client.loop_forever()

MQTT broker for testing

Trying to create a Python script that subscribes to an MQTT broker and works with the data. However, the MQTT broker is so far not receiving any data, which makes it difficult to test.
I found the following script to subscribe to a topic and print out the payloads, but it doesn't seem like I can connect to the test broker:
import paho.mqtt.client as mqtt
broker_url = "iot.eclipse.org"
broker_port = 1883
def on_connect(client, userdata, flags, rc):
print("Connected With Result Code "+rc)
def on_message(client, userdata, message):
print("Message Recieved: "+message.payload.decode())
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker_url, broker_port)
client.subscribe("TestingTopic", qos=1)
client.publish(topic="TestingTopic", payload="TestingPayload", qos=1, retain=False)
client.loop_forever()
So I would need some MQTT broker and topic that I can subscribe to in order to test my script. Any recommendations how I can find one?
There are two options:
Create local broker, so install on your PC - example https://mosquitto.org/download/
Use one online free broker like I am using now: https://www.cloudmqtt.com/

Can't connect to mqtt broker

I installed MQTT broker Mosquitto on my pi and are having some problems getting it to work with boxes in my network. Locally, if I putty in to the RPi running the Mosquitto MQTT broker everything is OK. I can use the client commands (mosquitto_sub, mosquitto_pub) to subscribe and publish to topics, no problem. BUT, if I try to connect from another box, Win2k12 server with a python script it states it cant connect.
I've tried turning the firewall off in my router
I've tried turning the firewall off on my Win2k12 server
I've added TCP 1883 to allowed ports outbound from my Win2k12 server
The Python script:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
client.publish("test_mqtt", "test")
client.subscribe("test")
def on_disconnect(client, userdata, rc):
print("Disconnect, reason: " + str(rc))
print("Disconnect, reason: " + str(client))
client = mqtt.Client("testclient")
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.connect("192.168.1.20", 1883, 60)
client.loop_forever()
The output here is
Disconnect, reason: <paho.mqtt.client.Client object at 0x01F41EF0>
Disconnect, reason: 1
I've tried to have a look at the documentation but it only mentioned the flags, not defining what they are.
The raspberry pi that is running Mosquitto is also running Node-red. It has no problem connecting to the MQTT broker (both of them are running on the same rpi)
Has enyone set up MQTT on Raspberry Pi and got it to work with other devices? I want it to work with a NodeMCU thingy, but when I had problems I started working on a python script to further debug the problem.
You can force the paho client to use the 3.1 level of the protocol by adding an option to the mqtt.Client constuctor:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
client.publish("test_mqtt", "test")
client.subscribe("test")
def on_disconnect(client, userdata, rc):
print("Disconnect, reason: " + str(rc))
print("Disconnect, reason: " + str(client))
client = mqtt.Client("testclient", protocol=mqtt.MQTTv31)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.connect("192.168.1.20", 1883, 60)
client.loop_forever()
First you have to make sure that you can connect to the Raspberry Pi. You can try using libraries other than Paho or using one MQTT client:
http://www.hivemq.com/blog/seven-best-mqtt-client-tools
The other thing you can try is setting both client and broker to use port 80 to see if they can communicate through that port.

Publish data to RabbitMQ server via Mqtt

I wrote a simple python program to connect RabbitMqtt server and hope to generate a queue and publish messages. However, after building the connection and creating a queue, the message was not published successfully (when I check the information of message, I cannot find any records and data). I wonder I miss some parameters or setting in client.publish(), but I do not know how to figure it out.
import paho.mqtt.client as mqtt
# 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('SEEDQ')
client.publish('SEEDQ', 'deqwdqwefqwefwefqwefqwe', 0, False)
# 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("15.78.xx.xx", 1883, 60)
client.loop_forever()
The problem is that you are calling client.publish() before the connection is complete. Move the client.publish into the on_connect function, AFTER client.subscribe('SEEDQ') and it will work.
# 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("$SYS/#")
client.subscribe('SEEDQ')
client.publish('SEEDQ', 111, 0, False)
Output:
Connected with result code 0
SEEDQ 111
FYI I used the public test server at iot.eclipse.org, port 1883.
FYI there is a very useful browser client HERE -using this and the public test server messagesight.demos.ibm.com port 1883 you can subscribe to SEEDQ and see your python script publish, and also using the browser client you can publish to SEEDQ from your browser and your script will display the message while it is in the loop_forever(). Obviously using these test servers is public visible.
UPDATE here is the complete code - this works against the public servers I show above.
import paho.mqtt.client as mqtt
# 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("$SYS/#")
client.subscribe('SEEDQ')
client.publish('SEEDQ', 111, 0, False)
# 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('15.xx.xx.xx', 1883, 60)
#client.connect("iot.eclipse.org", 1883, 60)
client.connect("messagesight.demos.ibm.com", 1883, 60)
#client.publish('SEEDQ', 111, 0, False)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

Categories