What is MQTT?

MQTT is one of the most popular M2M protocols and stand for Message Queuing Telemetry Transport. It is so sought after because its simplicity, the fact that it’s lightweight and publish/subscribe. It’s low-bandwidth, high latency and was developed for unreliable networks. So, if you are working in a resource-constrained network, it provides a simple way to distribute telemetry information. It’s been around since 1999 when it was developed by Dr Andy Stanford-Clark of IBM and Arlen Nipper. And, you’ll find it in applications like Facebook Messenger and Amazon Web Services amongst others.

Why is MQTT important for connectivity?

MQTT aims to deliver reliability and a degree of assurance of delivery when network bandwidth and resource requirements like we described above are scarce. It makes it plain to see, why M2M first and now the IoT have adopted this messaging protocol as one of the most popular options. Have a look at some of its benefits:

Lightweight: simple binary protocol, small overhead, built for small devices.

Simple: you can actually read the spec.

Standard: born at IBM, now MQTT is an OASIS standard. There are a bunch of different implementations of MQTT server and client libraries, with good interoperability.

Pub/Sub: the underlying communication model is that of message queues and the publish-subscribe paradigm.

MQTT client example

Create listening connection:

struct mg_mqtt_opts opts;                       // MQTT connection options
memset(&opts, 0, sizeof(opts));                 // Set MQTT options
opts.qos = 1;                                   // Set QoS to 1
opts.will_topic = mg_str(s_topic);              // Set last will topic
opts.will_message = mg_str("goodbye");          // And last will message
mg_mqtt_connect(&mgr, s_url, &opts, fn, NULL);  // Create client connection

An handle MQTT events:

static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  if (ev == MG_EV_MQTT_MSG) {
    struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
See full MQTT client example.

Full list of examples