The aim of this project is to create a very simple two state 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.
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. All other commands are ignored.
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.
- (topic prefix/)sensor-name – used to publish sensor state
- (topic prefix/)sensor-name/control/state -used to change state
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
Note: If started from the IDE it will create random sensor names.
Controlling the Sensor
You can use any MQTT client that can publish messages.
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 and can download the code here.
Related Tutorials and Resources: