Simple Python MQTT Sensor Simulator

light-bulbs-sensorsIf you are trying to learn MQTT or are working on a MQTT prject then having access to real time data is very important.

The aim of this project is to create a very simple two state binary sensor, that can be controlled externally using MQTT.

The sensor could be used to simulate real world objects like lights, doors etc that have two states on or off, open or closed etc in IOT projects.

IOT Sensors

Currently real world objects like light bulbs are controlled by a switch.

There is no feedback from the light bulb, that it is on or off, other than the obvious.

However someone in another room wouldn’t know the state of the light bulb .

Because IOT light bulbs will be controllable from anywhere then the state of the bulb should also be available from anywhere.

MQTT is ideal in this scenario as it allows the sensor to be controlled from multiple locations/clients and each one will be aware of the current state.

MQTT Sensor Overview

The sensor subscribes to a control topic and sits in a loop publishing it’s current state, and waiting for a command.

The commands accepted are:

on and off which turn the light on and off.  or

Open and Closed if functioning as door sensor

All other commands are ignored and commands are not case sensitive.

The sensor changes its state according to the command, and publishes its current state.

The sensor can operate in:

  • Chatty mode were it publishes data at regular intervals.
  • Non Chatty were it publishes data only when its status has changed.

It will also publish data on a keep alive interval which is set to be every 5 minutes.

Topics used:

  • topic prefix/sensor-name – used to publish sensor state
  • topic prefix/sensor-name/control/  -used to change state
  • topic prefix/connected/sensor-name/ – Used to indicated connection status 0=disconnected and 1=connected

The sensor can be called from the command line . Common arguments to pass are:

  • sensor name
  • topic prefix (optional)
  • broker address
  • broker port
  • chatty or not chatty
  • sensor type light or door
  • publish interval default =10 seconds in chatty mode

Note: If started from the Python IDE it will create random sensor names.

The sensor publishes with the retain message flag set to True.

Controlling the Sensor

You can use any MQTT client that can publish messages.

The MQTT lens client is ideal for this purpose and so is the MQTT dashboard client (Android APP) as they let you see the messages published by the sender as well as sending messages to the sensor.

I use the mosqquitto_pub tool in the examples below.

Example Usage

Note: You may not need to use the python prefix or may need to use python3 (Linux)

Use defaults with ip address

python simple-sensor -b

Use defaults with name

python simple-sensor -b ws4

Use Chatty mode -v option don’t need yes or no:

python -b -v

Publish every 20 seconds -i option

python -b -v -i 20

Set client name to testclient

python -b  -n testclient

To use as a door sensor open/closed use -s option

python -b -n testclient -s

Controlling the sensor using mosquitto_pub tool.

If using as a light sensor.

mosquitto_pub -h sensors/testclient/control -m on

If using as a door sensor

mosquitto_pub -h sensors/testclient/control -m open

Demo Shots

In the screen shot below I ran the sensor and controlled it using the MQTT dashboard App on my Android tablet.




If you find it useful you are free to use the code in your own projects.


The zip package contains a single file

Comments and Feedback

Was there enough detail in this tutorial for you to follow?

Please help me improve these tutorials by leaving your comments,rating them,asking questions.

Related Tutorials and Resources:




Please rate? And use Comments to let me know more


  1. If I change this code bloc it is ok ?

    def update_status(client,status):
    if status==states[0]: #Valid status ON
    # insert code for ON
    client.sensor_status=status #update
    print(“ON -> updating status “,client.sensor_status)
    if status==states[1]: #Valid status OFF
    # insert code for OFF
    client.sensor_status=status #update
    print(“OFF-> updating status “,client.sensor_status)

    1. Hi
      Not sure as the simulator is for receiving commands not sending them. If you send the the code you have using the ask steve page I will take a look

      1. Hi Steve,
        Just to let you know that I succeed to solve it with your original code and just few changes; inserting the commands – for rpi gpio pins relays on/off – and also adding another 2 command states for request just update the sensor status when relays are triggered by another script. It seem all it is working OK.
        I wanted to send you the new code but I can’t find attachment options.
        Thank you for your super good tutorials, it keeps me busy on computer learning and experimenting all day&night long.
        Best Regards

  2. Still some remarks about something unclear:
    you talk about sensors and if used as a door contact with open/closed, it sure is a sensor, but in switching a lamp with on/off, it is an actuator.
    So do I understand correctly this can be used as input as well as output?
    and…… which I/O pin in fact is switched? Or did I completely misunderstand?

    1. It is a simulator. In the real world you would have a light switch here you use the mosquitto_pub tool to send the command. The sensor is the light that turns on or off.

  3. I have an additional question:
    The program simple-sensor is using a module “mqtt_functions”
    I get an error on that. Trying to find anything of the existence of such a module (so I can install it) renders nothing, no info at all.
    Where can I find that module?

    1. The zip file should include two scripts and both files in the same directory and it should be ok. Please let me know if you have any problems.
      I have updated it so you may want to download the newer version. I’ve also changed the tutorial to reflect your earlier comments. Tks again

  4. Though your scripts are very good, I do have some suggestions for your tutorials (you asked).
    I think in its current form the examples may leave the beginner with a lot of questions.
    If I look at the “simple controllable mqtt sensor” once one goes to the download to look at the discussd python program, there are in fact two programs. Ofcourse it isnt so hard to find out which the proper one is but tehn where does the other one come in?
    In your tutorial you write that the command line can take several parameters, but you do not really make clear how.
    One can see it is -b -p -t -v -h -c -d -n client ID -i loop interval -s -u username -p Password
    but, it is not fully clear on how to supply those.
    Take for instance the broker, shousl that be the full IP, between quotes or not, or should it be the index in the array that is in the program. should the topic be between quotes or not? Ditto for say password and username.
    How to set chatty mode? or is that the ‘verbose’ output?
    Anyway, I think you get my point.
    I think just giving an actual command line example would greatly improve the tutorial, something along the lines of:
    python -b 1 -p 1883 -t “home/sensor” -v yes
    Please do not get my remark wrong, your programs are great and useful, but maybe a bit too much is expected from the beginner

    1. Tks
      A very helpful comment. It is always difficult to know how well the tutorial described what it was supposed to without good feedback.
      I will take it onboard- many tks

Leave a Reply

Your email address will not be published. Required fields are marked *