[text] PUB

Viewer

  1. import time
  2. import json
  3. import random
  4. import paho.mqtt.client as mqtt
  5.  
  6. # MQTT broker (change this to your broker's IP address or hostname)
  7. broker_address = "localhost"
  8. broker_port = 1883
  9.  
  10. # MQTT topic to publish to
  11. topic = "sru/nan"
  12.  
  13. # Create an MQTT client instance
  14. client = mqtt.Client("JetsonNano")
  15.  
  16. # Connect to the broker
  17. client.connect(broker_address, broker_port)
  18.  
  19. # Function to simulate sensor data
  20. def get_sensor_data():
  21.     # Replace this with actual sensor data acquisition logic
  22.     temperature = random.uniform(20.0, 30.0)
  23.     humidity = random.uniform(40.0, 60.0)
  24.     sensor_data = {
  25.         "temperature": temperature,
  26.         "humidity": humidity
  27.     }
  28.     return sensor_data
  29.  
  30. try:
  31.     while True:
  32.         # Simulate sensor data
  33.         data = get_sensor_data()
  34.  
  35.         # Convert data to JSON format
  36.         payload = json.dumps(data)
  37.  
  38.         # Publish data to MQTT broker
  39.         client.publish(topic, payload)
  40.  
  41.         print(f"Published: {payload}")
  42.  
  43.         # Wait for some time before publishing the next data
  44.         time.sleep(5)  # Change this value as per your requirement
  45.  
  46. except KeyboardInterrupt:
  47.     print("Interrupted, exiting...")
  48.     client.disconnect()
  49.  

Editor

You can edit this paste and save as new:


File Description
  • PUB
  • Paste Code
  • 03 Jul-2024
  • 1.21 Kb
You can Share it: