The challenge of handling a single MQTT topic containing payloads from multiple devices is explored in this thread:
It offers two strategies for handling the situation. The first is the one you’ve already employed. The sensor’s value_template
inspects the received payload and either extracts the value or, if the payload was not intended for it, simply reports its existing state
value.
The second strategy is more efficient when there are many sensors involved (> 3). It uses a simple automation to demultiplex the single MQTT topic into multiple topics, namely one unique topic per device. This greatly simplifies the configuration of each individual sensor.