Skip to content

Commit

Permalink
pub sub example files
Browse files Browse the repository at this point in the history
  • Loading branch information
Marco Bakera committed Sep 21, 2024
1 parent f123ed3 commit d6f11a4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
18 changes: 18 additions & 0 deletions mqtt/publisher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# publisher

import paho.mqtt.client as mqtt

MQTT_BROKER = "localhost" # "test.mosquitto.org"
TOPIC = "Erdgeschoss/Wohnzimmer/Temp"

publisher = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
publisher.connect(MQTT_BROKER)
publisher.loop_start()

input("Press Enter to publish message")
publisher.publish(topic=TOPIC, payload=22)

input("Press Enter for next message")
publisher.publish(topic=TOPIC, payload="23 ret", retain=True)

input("Press Enter to exit")
23 changes: 23 additions & 0 deletions mqtt/subscriber.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# subscriber

import paho.mqtt.client as mqtt

MQTT_BROKER = "localhost" # "test.mosquitto.org"
TOPIC = "Erdgeschoss/Wohnzimmer/Temp"

def my_connect_method(client, userdata, flags, rc, properties):
print("Connected. Subscribing to topic", TOPIC)
client.subscribe(TOPIC)

def my_message_method(client, userdata, msg):
msg_str = msg.payload.decode("UTF8")
print(f"Message received. topic: {msg.topic} payload: {msg_str}")

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = my_connect_method
client.on_message = my_message_method

client.connect(MQTT_BROKER)

# client.loop_start()
client.loop_forever()

0 comments on commit d6f11a4

Please sign in to comment.