I am looking for thoughts and input on my implementation approach to MQTT.
I have 20 solenoids controlled by relays, 10 1-Wire temperature sensors and a pump controlled by a relay.
Currently this is all working as expected, controlled by a Mega r3 and an Ethernet Shield.
So to the MQTT:
I believe that the expected methodology would be to have one topic per edge device, so something like:
mySystem/valves/valve1
mySystem/valves/valve2
mySystem/temperatures/temp1
mySystem/pumps/pump1
etc.
However, it seems to me that whilst this does give clear separation of messages, it will create a lot more work in publishing and subscription.
My current plan is to have a single topic:
mSystem/controlMessages
and send a JSON string that might look like:
{“item” : “pump1”, “value”: “on”}
In this way I can parse the string and create my control actions from a single topic. Additionally, extending the number of edge devices will require no additional publishing / subscriptions, just a change to the JSON string creation.
This is a simplification of the likely final solution as I will probably end up with 2 topics: one for sending control instructions to the edge devices from a webserver and one for sending status updates and temperatures from the edge devices to the webserver.
So if anyone has any observations or thought about this approach I’d be interested to hear them.
You will find that unique topic names makes it easier to debug.
One option is to create a C++ valve class, a temperature sensor class and a pump class.
Each of these has a field to hold the the device name and method called 'send_message' which dynamically builds the topic name using the device name and whatever prefix or suffix you need.
Your code creates the list of valves, sensors and pumps devices using the appropriate class and gives each one a unique name. There after you just call the send_message and the unique topic is generated on the fly.
@mikb55 I've been looking at this and trying various options but the key (critical) flaw in my original plan is that because I only planned to have 1 topic but multiple devices sending data to that topic, the whole concept of Retained Messages falls over ... Obviously the topic only holds the very last device value.
I am now implementing a solution much as you suggested.
Retained messages are a blessing and a curse.
At system startup they help get the system working quickly, but some of that data may be hours or days old which could make your program do the wrong thing.
In my projects every sensor measurement is saved with a time stamp and a loop constantly scans those timestamps looking for measurements that haven't been 't been updated in a timely manner. If it finds one it sets a 'failed sensor' flag and the program logic decides if that warrants a shutdown.