InIt Demo

This commit is contained in:
sityliu 2024-04-16 01:01:16 +08:00
commit 0e8d372693
2 changed files with 97 additions and 0 deletions

52
pub_mqtt.py Normal file
View File

@ -0,0 +1,52 @@
from paho.mqtt import client as mqtt_client
import random
import time
broker = '10.168.1.103'
port = 1883
topic = "/python/mqtt"
client_id = 'python_mqtt_001'
def connect_mqtt():
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('admin', password='admin')
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
msg_count = 0
while True:
time.sleep(1)
msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
exit()
msg_count += 1
client = connect_mqtt()
client.loop_start()
publish(client)

45
sub_mqtt.py Normal file
View File

@ -0,0 +1,45 @@
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()