I am working on a project where multiple MQTT sensor devices are connected to the network. MQTT sensor devices are ESP32 devices that collect various sensor data.
The MQTT broker that I am using is Mosquitto and it is running on Ubuntu virtual machine.
Each MQTT sensor device (client) has unique identification ID that allows the MQTT master to parse the messages accordingly and know which device the data is coming from. The identification ID will tell the sensor device which topics it needs to publish.
For example, the identification ID is set to "sensor1". In that case, the sensor will publish to topics that start with : "sensor1/value", "sensor1/config", "sensor1"/ping" and etc.
My main issue:
I must ensure that it would not be possible for 2 devices with the same identification ID to be connected at once. If that happens, sensor device that connected last should be disconnected and unsubscribed to all topics (basically as if it does not exist).
UPDATE
I have recently read about MQTT client_id feature. From what I learned, this client_id allows each client to be identified and allows the broker to identify each client that connects to the network.
If two MQTT clients are connected and they both share matching client_id's, the old device will be automatically disconnected and the new device will take over its place. I have tested this myself and can confirm that it works.
However, this feature only works when auto_reconnect feature is disabled. In my case, auto_reconnect mqtt feature is enabled which means that when the sensor is Disconnected, it will attempt to reconnect every few seconds. For example, someone accidentaly unplugged the ethernet cable and the device got disconnected. When the ethernet cable is plugged back in, the device will reconnect and function normally.
This auto reconnect causes the MQTT clients with matching client_id's to keep connecting/disconnecting kicking each other from the network.