Sample code for connecting HiveMQ Cloud with Python Paho MQTT Client
The following sample code has been tried and tested. Please note the fields e.g. Cluster URL, username and password that need to be updated.
import time
import paho.mqtt.client as paho
from paho import mqtt
import ssl
import socket
import random
import json
import os
# setting callbacks for different events to see if it works, print the message etc.
def on_connect(client, userdata, flags, rc, properties=None):
print("CONNACK received with code %s." % rc)
# with this callback you can see if your publish was successful
def on_publish(client, userdata, mid, properties=None):
print("mid: " + str(mid))
# print which topic was subscribed to
def on_subscribe(client, userdata, mid, granted_qos, properties=None):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
# print message, useful for checking if it was successful
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
# using MQTT version 5 here, for 3.1.1: MQTTv311, 3.1: MQTTv31
# userdata is user defined data of any type, updated by user_data_set()
client = paho.Client(client_id="paho-client-test", userdata=None, protocol=paho.MQTTv5)
# setting callbacks, use separate functions like above for better visibility
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.on_message = on_message
client.on_publish = on_publish
# enable TLS for secure connection
client.tls_set(tls_version=mqtt.client.ssl.PROTOCOL_TLS)
# set username and password
client.username_pw_set("TYPE_USERNAME", "TYPE_PASSWORD")
# connect to HiveMQ Cloud on port 8883 (default for MQTT)
client.connect("TYPE_CLUSTER_URL", 8883)
client.loop_start()
# subscribe to all topics of sensor by using the wildcard "#"
client.subscribe("sensor/#", qos=0)
# single publish
temp = random.randint(10, 33)
print(f"The temperature is {temp}")
client.publish("sensor/temperature", payload=(temp), qos=1)
client.loop_stop()
client.disconnect()
Please reach out to HiveMQ Support team in case of further questions or issues.