Python

​ Getting Started

pip3 install paho-mqtt

Import Libraries

import paho.mqtt.client as mqtt
import json
import ssl

Define Variables

broker_host = "broker.qubitro.com"
broker_port = 8883
device_id = "PASTE_DEVICE_ID_HERE"
device_token = "PASTE_DEVICE_TOKEN_HERE"

Setup MQTT Client

client = mqtt.Client(client_id=device_id)
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
client.tls_set_context(context)
client.username_pw_set(username=device_id, password=device_token)
client.connect(broker_host, broker_port, 60)
client.on_connect = on_connect
# Set additional callbacks here
client.loop_start()

Prepare Data

data = {
"Key1": 30,
"Key2": 30.5
}

Define Callbacks

Define callbacks depending on your scenario. See examples below or visit the Paho MQTT Python GitHub repository. Example callback:

def on_connect(client, userdata, flags, rc):
print("Connection result code: " + str(rc))

Examples

Publish

An example of publishing data.

Qubitro MQTT Publish Example

Subscribe

An example of subscribing to a topic and receiving the message.

Qubitro MQTT Subscribe Example

QoS Options

QoS 0
QoS 1
QoS 2
QoS 0
client.subscribe(device_id, 0)
QoS 1
client.subscribe(device_id, 1)
QoS 2
client.subscribe(device_id, 2)

Log

Qubitro MQTT Log Example

Disconnect

Qubitro MQTT Disconnect Example