I was using mosquito broker with user name and password authentication. Broker URL is made public so that it can be accessed by a Django web site and raspberry pi
now am trying to implement ssl certificate authentication. but am getting errors like
unknown ca, [Win Error 10054] An existing connection was forcibly closed by the remote host ,
hand shake failed
how to resolve this.
http://www.steves-internet-guide.com/mosquitto-tls/
am following this article to create ssl certificate.
any issue in using self signed certificate in mqtt broker wth public url?
my mosquitto.conf file looks like this
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 8883
use_identity_as_username true
cafile /etc/mosquitto/ca_certificates/ca.crt
keyfile /etc/mosquitto/certs/server.key
certfile /etc/mosquitto/certs/server.crt
require_certificate true
calling the broker from rasberry pi like this
client.tls_set(ca_certs = "certificate path")
client.tls_insecure_set(True)
import time
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/#")
# 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
broker = "broker name"
#mqtt_port = 1883
mqtt_port = 8883
client = mqtt.Client(str(int(time.time()))) # create client object
client.tls_set("./ca.crt")
client.tls_insecure_set(True)
client.connect(broker, mqtt_port)
client.loop_start()
First, you should remove the following lines from the mosquitto.conf
use_identity_as_username true
require_certificate true
They are only used when you are using client side certificates which you are not in the code provided.
Second, assuming that the file ca.crt is in the same directory as the script and where you are starting the following should work. (It also assumes that the broker certificate has a matching CA/SAN entry to match the broker hostname/IP address)
...
client.tls_set_context()
client.tls_set(ca_path="./ca.crt")
client.connect(broker, mqtt_port)
client.loop_start()
Another option is this which will disable checking that the broker's certificate is signed by any CA and that it's CA/SAN matches the hostname used to access the broker.
...
client.tls_set_context()
client.tls_insecure_set(True)
client.connect(broker, mqtt_port)
client.loop_start()
Related
python code
import time
broker = "test.mosquitto.org"
port=8884
conn_flag= False
def on_connect(client, userdata, flags, rc):
global conn_flag
conn_flag=True
print("connected",conn_flag)
conn_flag=True
def on_log(client, userdata, level, buf):
print("buffer", buf)
def on_disconnect(client, userdata, rc):
print("client disconnected ok")
client1= paho.Client("control")
client1.on_log=on_log
client1.tls_set('C:\etc\mosquitto\certs\mosquitto.org.crt')
client1.on_connect = on_connect
client1.on_disconnect = on_disconnect
client1.connect(broker,port)
while not conn_flag:
time.sleep(1)
print("waiting", conn_flag)
client1.loop()
time.sleep(3)
print("publishing")
client1.publish("house/bulb", "Test")
time.sleep(2)
client1.loop()
time.sleep(2)
client1.disconnect()
I am using the mosquitto.org.crt (PEM format) file gave by test.mosquitto.org, currently can't get to connect on port 8884, conn_flag is always false what should I do?
As per http://test.mosquitto.org the ports are:
8883 : MQTT, encrypted, unauthenticated
8884 : MQTT, encrypted, client certificate required
In your code client1.tls_set('C:\etc\mosquitto\certs\mosquitto.org.crt') you are setting the ca_cert - the params being:
tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLS, ciphers=None)
This would be sufficient to connect to port 8883 (and your code connects to that port successfully for me). A connection to port 8883 will be encrypted and the client can confirm the identify of the server; however the client does not have to provide a client certificate (to identify itself).
To connect to port 8884 you have to provide a client certificate (used to authenticate the client) - i.e. the certfile and keyfile arguments. An appropriate certificate can be requested here.
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)
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)).
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.
Hi I have a mqtt broker up and running. I am connecting to it from python using paho-mqtt.
Code
def on_connect(client, userdata, flags, rc):
if rc==0:
print("connected OK Returned code=",rc)
else:
print("Bad connection Returned code=",rc)
print("Subscribing to topic","data/#")
client.subscribe("data/#")
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
if rc != 0:
print('Unexpected MQTT disconnection. Will auto-reconnect')
else:
print('rc value:' + str(rc))
broker_address="ip"
port = 'port'
print("creating new instance")
client = mqtt.Client(clean_session=True) #create new instance
client.on_connect = on_connect
client.on_message = on_message #attach function to callback
client.on_disconnect = on_disconnect
print("connecting to broker")
client.connect(broker_address, port=port,) #connect to broker
client.loop_forever() #stop the loop
I am using the same code in multiple scripts ,connecting to broker and subscribing to a topic. The frequency of disconnection was less when there were 5-6 scripts. I have around 12-13 scripts connecting to the broker and frequency of disconnects has increased significantly. Is there some thing wrong with the connection in the scripts or its about the broker. Can someone help me with this?
My guess though is your broker does not like the fact that the Python client defaults to a null clientid. As per the spec it should treat this as an indication it must assign a unique id to your client, but it may be implementing the spec improperly?
Please try passing a randomly generated / unique client id in your connect(), as this will guarantee your clients are all unique, rather than all having the same id which for your broker means it's kicking out any connected client when a new one with the same id tries to connect.