Skip to content

Instantly share code, notes, and snippets.

@marianoguerra
Last active March 4, 2024 21:50
  • Star 17 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save marianoguerra/be216a581ef7bc23673f501fdea0e15a to your computer and use it in GitHub Desktop.
MQTT Generator Script

MQTT Generator

A simple python 3 script to generate sensor data from a config file and send it to an MQTT broker.

Usage

Download mqttgen.py and config.json files (click on the Raw button at the top right and then save the content), edit config.json to fit your needs, if you are using it to run the Event Fabric sensors dashboard then don't change the topic in config.json unless you want to change it in the dashboard too.

The script uses the python paho-mqtt library you can install it with something like sudo pip3 install paho-mqtt.

python3 mqttgen.py config.json

Configuration

Edit config.json, you can add as many sensors in the "sensors" object as you wish.

Change the values in "mqtt" section to match your MQTT broker settings.

  • password is optional if you don't need password
  • if username is missing, no authentication will be used.

Author

Mariano Guerra from Event Fabric

License

Public Domain

{
"mqtt": {
"username": "mariano",
"password": "secret",
"host": "localhost",
"port": 1883,
"topic": "sensors"
},
"misc": {
"interval_ms": 1000,
"verbose": true
},
"sensors": {
"Sensor 1": {
"lat": 10,
"lng": 10,
"unit": "C",
"type": "temperature",
"range": [0, 45],
"description": "Main Entrance"
},
"Sensor 2": {
"lat": 90,
"lng": 90,
"unit": "C",
"type": "temperature",
"range": [0, 45],
"description": "Kitchen"
},
"Sensor 3": {
"lat": 90,
"lng": 10,
"unit": "C",
"type": "temperature",
"range": [0, 45],
"description": "Deposit"
},
"Sensor 4": {
"lat": 10,
"lng": 90,
"unit": "C",
"type": "temperature",
"range": [0, 45],
"description": "Assemlby Floor"
},
"Sensor 5": {
"lat": 50,
"lng": 50,
"unit": "C",
"type": "temperature",
"range": [0, 45],
"description": "Offices"
}
}
}
#!/usr/bin/env python3
"""a simple sensor data generator that sends to an MQTT broker via paho"""
import sys
import json
import time
import random
import paho.mqtt.client as mqtt
def generate(host, port, username, password, topic, sensors, interval_ms, verbose):
"""generate data and send it to an MQTT broker"""
mqttc = mqtt.Client()
if username:
mqttc.username_pw_set(username, password)
mqttc.connect(host, port)
keys = list(sensors.keys())
interval_secs = interval_ms / 1000.0
while True:
sensor_id = random.choice(keys)
sensor = sensors[sensor_id]
min_val, max_val = sensor.get("range", [0, 100])
val = random.randint(min_val, max_val)
data = {
"id": sensor_id,
"value": val
}
for key in ["lat", "lng", "unit", "type", "description"]:
value = sensor.get(key)
if value is not None:
data[key] = value
payload = json.dumps(data)
if verbose:
print("%s: %s" % (topic, payload))
mqttc.publish(topic, payload)
time.sleep(interval_secs)
def main(config_path):
"""main entry point, load and validate config and call generate"""
try:
with open(config_path) as handle:
config = json.load(handle)
mqtt_config = config.get("mqtt", {})
misc_config = config.get("misc", {})
sensors = config.get("sensors")
interval_ms = misc_config.get("interval_ms", 500)
verbose = misc_config.get("verbose", False)
if not sensors:
print("no sensors specified in config, nothing to do")
return
host = mqtt_config.get("host", "localhost")
port = mqtt_config.get("port", 1883)
username = mqtt_config.get("username")
password = mqtt_config.get("password")
topic = mqtt_config.get("topic", "mqttgen")
generate(host, port, username, password, topic, sensors, interval_ms, verbose)
except IOError as error:
print("Error opening config file '%s'" % config_path, error)
if __name__ == '__main__':
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print("usage %s config.json" % sys.argv[0])
@ajcs3
Copy link

ajcs3 commented Feb 23, 2017

I dont have any user and password for the connection. Instead what I have is KS and TS certificates. Could you please help us how this can be used with in your framework.

@LimeBlast
Copy link

Thank you for this, it gave me the inspiration to write my own generating script (I had far simpler requirements than you).

@ApostolosLL
Copy link

Thank you, that saved me a lot of time!
However, when I ran the script, I noticed that after ~20 messages the client disconnected (or at least the sent messages never arrived at the broker).
Inserting an mqttc.loop_start() after the mqttc.connect(host, port) fixed that issue.

@LouKingFr
Copy link

hello can u explain me more how it works , when i run it i just got a 0 , how can i send a message or a simply data like temperature to a broker for example .

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