How do Thingsboard MQTT API works internally?

I've been trying to understand how the thingsboard MQTT API works internally, however I can't figure it out.

Given two devices, A and B:

Both devices are subscribed to the following topic:

v1/devices/me/attributes

Then, for the device A when I add an attribute key1 with value value1 in the Thingsboard UI, the device A receives the following message:

{"key1":"value1"}

Which is the expected behavior according to the documentation, however the device B doesn't receive any message even though it is subscribed to the following topics:

- #
- v1/devices/me/attributes

I can't understand how it is possible that client A receives the message and client B doesn't, even though they are connected to the same topic, and device B is also subscribed to # topic.

This is not the way MQTT topics normally work, and I'd like to know if someone can tell me how thingsboard implements this behavior, since I find it really useful, since only one of the devices receives a response message, but only one topic is used.

Upvotes: 3

Views: 1016

Answers (2)

devaskim
devaskim

Reputation: 559

All magic happens in MqttTransportHandler. Each time new MQTT Connect appears, TB server will create new session object based on auth token, IP address and other unique data. In this way server knows owner of pushed data and destination where to send response.

Upvotes: 3

mdeuchert
mdeuchert

Reputation: 356

The topic v1/devices/me/attributes is used for all devices. To select one particular device, you have to enter it's ACCESS_TOKEN has username of the MQTT client (default authentication option):

We will use access token device credentials in this article and they will be referred to later as $ACCESS_TOKEN. The application needs to send MQTT CONNECT message with username that contains $ACCESS_TOKEN.

See more details here: https://thingsboard.io/docs/pe/reference/mqtt-api/

So with this approach it is not possible to have one MQTT client for sending data to both Devices A and B. You would have to initialize two MQTT clients for that.

If you are not using ThingsBoard PE with MQTT Integration/Data Converter, I can recommend trying the MQTT Gateway API: https://thingsboard.io/docs/pe/reference/gateway-mqtt-api/

There you set up one Gateway device which is capable of handling payloads for multiple devices with one MQTT client. It can also automatically create new devices.

Upvotes: 0

Related Questions