Monday, August 25, 2014

Sensor data with MQTT

Messaging protocols like MQTT makes it easy to design dynamic, scalable and modular architecture for sensor integration.

Message queues with publish/subscribe schema makes data producers and consumers independent from each other. The producer/publisher does not need to know who if any is interested in the data. Consumer can be changed in fly without any interruption to producer, and vice verse.

Pub/sub architecture
By nature, such architecture is unreliable, as producer does not get acknowledgement whether the data was received by anybody. MQTT tries to tackle that by introducing some QoS functionality;"at most once", "at least once" and "exactly once" delivery. In addition to that, publisher may define last will and retain messages. The last will will be delivered to subscribers if connection to the publisher gets broken. 

One common mistake with MQTT is to consider it as a pipe to deliver structured data in between producer and consumer.  Even if MQTT can do it, it's not according to the original design principle. The topic field of each message should contain relevant metadata about the meaning of the message. By representing the information in the payload data itself, the benefit of broker is lost. Let the broker do its job!

Let's have a practical example

Tellstick Duo
Tellstick Duo from Telldus can receive data from various wireless sensors from different vendors. In case of WT450H transmitter, an example of raw sensor event data from telldus-core driver consists of following fields:
  • class: sensor
  • protocol:mandolyn
  • id: 22
  • model: temperaturehumidity
  • temp: 22.9
  • humidity: 56 

It's feels quite natural to formulate the data as a JSON message and delivered it with topic something like /sensor/telldus. But! That's not how MQTT is supposed to be used. Better way is add the metadata in the topic and let payload only to contain the actual data. Something like:

  /sensor/temperature/<id> 22.9
  /sensor/humidity/<id> 56

Why this way?  The broker can do its job by delivering messages to those and only those who are interested in that particular message. If the topic would be just plain /sensor/telldus, every consumer would receive every message, and then in application level they should parse the message and decide whether they interested at all in it.

No comments:

Post a Comment