I'm new to MQTT: but I have got some basic Python programs working where sensor readings can be published to a particular topic: and other clients can then subscribe to get the temperature on a event-driven basis.
But when it comes to sending commands; I'm a little stuck on the best to do this.
So for example: take a 'countdown timer' connected to mqtt.
This timer has two states: 'stopped' and 'started'. It will initialize itself into the 'stopped' state and wait for a 'start' command; and then will count down; publishing the current countdown to a topic. When the countdown reaches zero; it will switch its state to 'stopped' again, and wait for another 'start' command.
If it receives a 'stop' command (over mqtt); it should also go into the 'stopped' state.
So perhaps I could create topics something like:
countdown_timer/command
countdown_timer/state
countdown_timer/value
And the countdown device could subscribe to 'command' and react by publishing to 'state'. ('stopped' or 'started'?)
But should the client somehow 'consume' the 'command' topic value once it has processed it ?
Or would it better to have something like:
countdown_timer/send_command
countdown_timer/command_result
Where the controller would send a command, the subscribed-device would carry-out the command and put 'ok' or 'error' on the 'command_result' topic ?
In general, both approaches that you describe are valid MQTT patterns. You choose what is most appropriate for your application. Here are some comments:
countdown/state
and countdown/value
, you may want to make these publish messages retained. This will ensure that newly subscribed clients will immediately receive the latest value.countdown_timer/command
--- but sometimes it makes sense when a server process can fail, restart and reconnect to just continue with the last command.send_command
and command_result
pattern is common for MQTT when one client speaks to one server and receives one answer for each question. This doesn't seem to fit this current example well: You don't have one specific answer to respond to for each command.server/command
and each client subscribes to a separate channel: client/1
, client/2
, client/3
etc. When a client sends a command to the server, it includes its client id --- and the server responds on the corresponding channel.service/1
, service/2
etc. The first clients publishes to service/1
and subscribes to client/1
. The second client publishes to service/2
and subscribes to client/2
. The server subscribes to service/#
, extracts the client id from the topic name of the received message and responds to the corresponding client channel.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With