Python

Getting Started

Before getting started, make sure that Python and required libraries are installed by visiting the setup page

Import Libraries

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

Define Variables

broker_host = "PASTE_HOST_HERE"
broker_port = 1883 | 8883
device_id = "PASTE_DEVICE_ID_HERE"
device_token = "PASTE_DEVICE_TOKEN_HERE"

Define Callbacks

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

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

Setup MQTT Client

Basic
TLS
Basic
client = mqtt.Client(client_id=device_id)
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()
TLS
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
}

Examples

Publish

Qubitro MQTT Publish Example

Subscribe

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)

Message

Qubitro MQTT Message Example

Log

Qubitro MQTT Log Example

Disconnect

Qubitro MQTT Disconnect Example