MQTT CLIENT AND SERVER

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 and Mongoose Embedded Web Server

Mongoose makes MQTT easy for both; an embedded MQTT server and MQTT client.

All you need to do is call mg_set_protocol_mqtt - and your connection is MQTT connection. You can publish and subscribe with these simple functions: mg_mqtt_publish, mg_mqtt_subscribe.

If you require an embedded MQTT server you can simply call mg_mqtt_broker_init.

Mongoose Embedded Web Server ships with examples for both client and broker - take a look, you will see that we’ve maintained the simplicity intended by this protocol.

MQTT server example

Create listening connection:

mg_mgr_init(&mgr, NULL);
c = mg_bind(&mgr, "1883", mg_mqtt_broker);
mg_mqtt_broker_init(&brk, NULL);
c->user_data = &brk;
mg_set_protocol_mqtt(c);

An handle MQTT events:

void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  switch (ev) {
    case MG_EV_MQTT_CONNECT:
      ...
See full MQTT server example.

MQTT client example

Create MQTT connection:

c = mg_connect(&mgr, "server:1883", ev_handler);
mg_set_protocol_mqtt(c);

And handle MQTT events:

void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
  switch (ev) {
    case MG_EV_CONNECT:
      mg_send_mqtt_handshake_opt(c, "me!", opts);
      break;
    case MG_EV_MQTT_CONNACK:
      ...
See full MQTT client example.

All examples

SEE ALL EXAMPLES DOWNLOAD SOURCE CODE