Skip to content

Instantly share code, notes, and snippets.

@kirang89
Last active August 29, 2015 14:11
Show Gist options
  • Save kirang89/c3637c7f372c46544f1b to your computer and use it in GitHub Desktop.
Save kirang89/c3637c7f372c46544f1b to your computer and use it in GitHub Desktop.
MQTT client to interact with a broker, with user authentication, using an SSL connection
#!/usr/bin/env python
import paho.mqtt.client as mqtt
import ssl
def on_connect(client, userdata, rc):
print("Connected with result code "+str(rc))
def on_message(client, data, msg):
print(msg.topic+" "+str(msg.payload))
def on_subscribe(client, userdata, mid, granted_qos):
print "Subscribed with mid ", mid
def main():
client = mqtt.Client(client_id="p1",
clean_session=True,
protocol=mqtt.MQTTv31)
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.username_pw_set('kiran', password='meh')
client.tls_set("/Users/kiran/Workspace/ssl_test/ca.crt",
certfile="/Users/kiran/Workspace/ssl_test/client.crt",
keyfile="/Users/kiran/Workspace/ssl_test/client.key",
cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_TLSv1)
client.connect("localhost", port=8883)
client.subscribe("r/topic", qos=0)
client.loop_forever()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment