Skip to content

Code Simulators: Generating Data with Python

If you're comfortable with basic Python, these examples provide a quick and customizable way to send test data into your Machinechat JEDI instance.

Prerequisites

  • Python 3: Ensure you have Python 3 installed. If not, download it from https://www.python.org/
  • Libraries:
    • HTTP: Install the requests library: pip install requests
    • MQTT: Install the paho-mqtt library: pip install paho-mqtt

1. Sending Data Using HTTP

import requests
import json
import time

# Replace with your JEDI's IP address and the HTTP Data Collector port
url = 'http://<jedi_ip>:8100/v1/data/mc'  

while True: 
    # Sample data (adjust as needed)
    payload = {
        "context": {
            "target_id": "python_simulator",
            "target_ip": "127.0.0.1"  # Localhost 
        },
        "data": {
            "temperature": 25.5,
            "humidity": 68,
            "status": "operational" 
        }
    }

    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers)

    if response.status_code == 200:
        print('Data sent successfully')
    else:
        print('Error sending data:', response.text)

    time.sleep(5)  # Send data every 5 seconds 

2. Sending Data Using MQTT

import paho.mqtt.client as mqtt
import time
import json

# Replace with JEDI's IP address (if it has an MQTT broker running)
broker_address = "<jedi_ip>"  
client_id = "python_mqtt_simulator"  

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print("Connection Error:", rc)

client = mqtt.Client(client_id)
client.on_connect = on_connect
client.connect(broker_address) 

while True: 
    # Sample data (adjust as needed)
    payload = {
        "temperature": 25.5,
        "humidity": 68,
        "status": "operational"
    }
    client.publish("simulator/metrics", json.dumps(payload)) 
    print("Data published")
    time.sleep(5)

Important Notes:

  • Replace <jedi_ip>: Insert the actual IP address of your JEDI machine.
  • MQTT Topics: In this context, any topic works.
  • Customization: Modify the sample data and update the sending interval as needed for your simulation.
  • Data Structure: Make sure the payload structure is JSON.

Need help? Contact our support team: support@machinechat.io