45 lines
996 B
Python
45 lines
996 B
Python
import random
|
|
from paho.mqtt import client as mqtt_client
|
|
|
|
|
|
broker = '10.168.1.103'
|
|
port = 1883
|
|
topic = "/python/mqtt"
|
|
client_id = 'python_mqtt_002'
|
|
|
|
|
|
|
|
|
|
def connect_mqtt() -> mqtt_client:
|
|
def on_connect(client, userdata, flags, rc):
|
|
if rc == 0:
|
|
print("Connected to MQTT Broker!")
|
|
else:
|
|
print("Failed to connect, return code:", rc)
|
|
|
|
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1, client_id)
|
|
client.username_pw_set('test1', password='test1')
|
|
client.on_connect = on_connect
|
|
client.connect(broker, port)
|
|
return client
|
|
|
|
|
|
|
|
|
|
def subscribe(client: mqtt_client):
|
|
def on_message(client, userdata, msg):
|
|
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
|
|
|
|
client.subscribe(topic)
|
|
client.on_message = on_message
|
|
|
|
|
|
|
|
def run():
|
|
client = connect_mqtt()
|
|
subscribe(client)
|
|
client.loop_forever()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run() |