Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import random
import time
import paho.mqtt.client as mqtt_client
broker = '127.0.0.1'
port = 1883
topic = "testtopic/#"
# generate client ID with sub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'
# EMQ X WebSocket configuration
websocket_path = "/mqtt"
username = "123"
password = "123"
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
# Subscribe to topic when connected
client.subscribe(topic)
else:
print(f"Failed to connect, return code {rc}\n")
def on_message(client, userdata, msg):
print(f"Received message: {msg.payload.decode()} from topic {msg.topic}")
client = mqtt_client.Client(client_id)
client.username_pw_set(username, password)
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker, port)
return client
def run_subscriber():
client = connect_mqtt()
client.loop_forever()
if __name__ == '__main__':
run_subscriber()