Advertisement
mudhita_triari

ESP32 MQTT - Python Publisher

Mar 24th, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | Source Code | 0 0
  1. import paho.mqtt.client as mqtt
  2. import time
  3.  
  4. mqtt_broker = "free.mqtt.iyoti.id"
  5. port = 1883
  6. topic_sub = 'robotikid/pub'
  7. topic_pub = 'robotikid/sub'
  8. time_interval = 1
  9.  
  10. #callback jika sukses terhubung
  11. def on_connect(client, userdata, flags, rc):
  12.     print('Connected with result code '+str(rc))
  13.     client.subscribe(topic_sub)
  14.  
  15. # callback menerima pesan
  16. def on_message(client, userdata, msg):
  17.     print("Terima Dari: {}, Nilai: {}".format(msg.topic, msg.payload))
  18.  
  19. client = mqtt.Client()
  20.  
  21. # setting fungsi callback
  22. client.on_connect = on_connect
  23. client.on_message = on_message
  24.  
  25. # menghubungkan
  26. client.connect(mqtt_broker, port)
  27.  
  28. # Publish a message
  29. client.publish(topic_pub, payload='Mulai Dari Laptop')
  30. # client.loop_forever()
  31.  
  32.  
  33. _time_0 = time.time()
  34. cnt = 0
  35. while True:
  36.     client.loop()
  37.     if client.is_connected():
  38.         if time.time()-_time_0 >= time_interval:
  39.             pesan = 'Dari Laptop {}'.format(cnt)
  40.             print(pesan)
  41.             client.publish(topic_pub, payload = pesan)
  42.  
  43.             cnt+=1
  44.             _time_0 = time.time()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement