Skip to content

Instantly share code, notes, and snippets.

@petterpet
Last active March 4, 2021 13:28
Show Gist options
  • Save petterpet/2031023ee6916ab730e5cb1e61eb1deb to your computer and use it in GitHub Desktop.
Save petterpet/2031023ee6916ab730e5cb1e61eb1deb to your computer and use it in GitHub Desktop.
Python MQTT
import time
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client = mqtt.Client()
client.on_connect = on_connect
client.connect("<IP>", 1883, 60)
client.loop_start()
while True:
time.sleep(2)
client.publish("testTopic", "testPayLoad")
import time
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("test/#")
def on_message(client, userdata, msg):
msg_len = (len(str(msg.payload)))-3
message = ""
for i in range(msg_len):
message = message + str(msg.payload)[2+i]
print(msg.topic + ":", message)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("<IP>", 1883, 60)
client.loop_forever()
@petterpet
Copy link
Author

Some simple Python Scripts for MQTT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment