Permalink
Cannot retrieve contributors at this time
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?
WHW/2
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
40 lines (33 sloc)
1.05 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |