Skip to content

Instantly share code, notes, and snippets.

@jpmens
Created September 16, 2013 07:27
Show Gist options
  • Select an option

  • Save jpmens/6577606 to your computer and use it in GitHub Desktop.

Select an option

Save jpmens/6577606 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import mosquitto
import ssl
def on_connect(mosq, userdata, rc):
print("Connect: rc: "+str(rc))
def on_message(mosq, userdata, msg):
print "%s (qos=%s, r=%s) %s" % (msg.topic, str(msg.qos), msg.retain, str(msg.payload))
def on_publish(mosq, userdata, mid):
print("mid: "+str(mid))
def on_subscribe(mosq, userdata, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
def on_disconnect(mosq, userdata, rc):
print "OOOOPS! disconnect"
mqttc = mosquitto.Mosquitto('py-jp1', clean_session=True)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.tls_insecure_set(True) # optional: avoid check certificate name if true
mqttc.tls_set('root.ca',
cert_reqs=ssl.CERT_REQUIRED,
tls_version=1
)
mqttc.connect("localhost", 8883, 60)
mqttc.publish("p1", "Hi", 0)
mqttc.loop()
@matbor
Copy link

matbor commented Sep 16, 2013

Thx for that, publish it on your website, hard to find this info for novice like me to python and mosquitto.

In the end I I did have had tls_version=1 part, but was missing the cert_required part.

But after a bit of playing around with your code and still not working I found that I had to remove the tls_version=1 part from the python code because I kept getting this error;

Server log :
OpenSSL Error: error:1408A10B:SSL routines:SSL3_GET_CLIENT_HELLO:wrong version number

Python error :
ssl.SSLError: [Errno 1] _ssl.c:504: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

Even though I have the following settings in my mosquitto.conf file;

listener 8883
tls_version tlsv1
cafile /etc/mosquitto/ca.crt
certfile /etc/mosquitto/server.crt
keyfile /etc/mosquitto/server.key
require_certificate false

@jpmens
Copy link
Author

jpmens commented Sep 16, 2013

@matbor What version of Python are you running, on which platform? (python -V)

@matbor
Copy link

matbor commented Sep 18, 2013

@jpmens This was done on windows7 python 2.7.5. Didn't try it on my linux box.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment