Advertisement
vitareinforce

python example

May 5th, 2025 (edited)
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. import paho.mqtt.client as mqtt
  2. import time
  3.  
  4. def on_connect(client, userdata, flags, reason_code, properties):
  5.     print(f"Connected with result code {reason_code}")
  6.  
  7. def on_message(client, userdata, msg):
  8.     print(msg.topic + " " + str(msg.payload))
  9.  
  10. def publish_message(client, topic, message):
  11.     result = client.publish(topic, message)
  12.     if result.rc == mqtt.MQTT_ERR_SUCCESS:
  13.         print(f"Message {message} published to topic {topic}")
  14.  
  15. def subscribe_to_topic(client, topic):
  16.     client.subscribe(topic)
  17.     print(f"Subscribed to topic '{topic}'")
  18.  
  19. def ask_before_publish():
  20.     time.sleep(1)
  21.     message = input("Command untuk kontrol: ")
  22.     publish_message(mqttc, "LBCMH/1", message)
  23.     ask_before_publish()
  24.  
  25. mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
  26. mqttc.on_connect = on_connect
  27. mqttc.on_message = on_message
  28.  
  29. mqttc.username_pw_set(username="public", password="public")
  30. mqttc.connect("public.cloud.shiftr.io", 1883, 60)
  31.  
  32. mqttc.loop_start()
  33.  
  34. ask_before_publish()
  35.  
  36. try:
  37.     while True:
  38.         time.sleep(1)
  39. except KeyboardInterrupt:
  40.     print("Exit...")
  41. finally:
  42.     mqttc.loop_stop()
  43.     mqttc.disconnect()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement