Fork me on GitHub

Generic MQTT server

This library provides MQTT protocol API that allows devices to talk to MQTT servers.

Mongoose OS implements MQTT 3.1.1 client functionality, and works with all popular MQTT server implementations, like AWS IoT, Google IoT Core, Microsoft Azure, IBM Watson, HiveMQ, Mosquitto, etc.

In order to talk to an MQTT server, configure MQTT server settings - see Configuration section below. Once configured, Mongoose OS keeps that connection alive by reconnecting and re-subscribing to all topics after disconnections - you do not need to implement the reconnection logic.

If you want to use TLS, set mqtt.ssl_ca_cert=ca.pem. Make sure that ca.pem file has required CA certificates. If you want to use mutual TLS, set mqtt.ssl_cert=CLIENT_CERT.pem and mqtt.ssl_key=PRIVATE_KEY.pem.

See example video (don't forget to set mqtt.enable=true before you try it):


The MQTT library adds mqtt section to the device configuration:

  "clean_session": true,        // Clean session info stored on server 
  "client_id": "",              // If not set, is used
  "enable": false,              // Enable MQTT functionality
  "keep_alive": 60,             // How often to send PING messages in seconds
  "pass": "",                   // User password
  "reconnect_timeout_max": 60,  // Maximum reconnection timeout in seconds
  "reconnect_timeout_min": 2,   // Minimum reconnection timeout in seconds
  "server": "",    // SERVER:PORT to connect to
  "ssl_ca_cert": "",            // Set this to file name with CA certs to enable TLS
  "ssl_cert": "",               // Client certificate for mutual TLS
  "ssl_cipher_suites": "",      // TLS cipher suites
  "ssl_key": "",                // Private key for the client certificate
  "ssl_psk_identity": "",       // If set, a preshared key auth is used
  "ssl_psk_key": "",            // Preshared key
  "user": "",                   // MQTT user name, if MQTT auth is used
  "will_message": "",           // MQTT last will message
  "will_topic": ""              // MQTT last will topic

C API Reference mgos_mqtt.h

#include "mgos_mqtt.h"

Initialises global MQTT connection

bool mgos_mqtt_init(void);

Initialises global MQTT connection

void mgos_mqtt_global_subscribe(const struct mg_str topic,
                                mg_event_handler_t handler, void *ud);

Subscribe to a specific topic. This handler will receive SUBACK - when first subscribed to the topic, PUBLISH - for messages published to this topic, PUBACK - acks for PUBLISH requests. MG_EV_CLOSE - when connection is closed.

void mgos_mqtt_add_global_handler(mg_event_handler_t handler, void *ud);

Registers a mongoose handler to be invoked on the global MQTT connection

typedef void (*mgos_mqtt_auth_callback_t)(char **client_id, char **user,
                                          char **pass, void *arg);

Set authentication callback. It is invoked when CONNECT message is about to be sent, values from user and pass, if non-NULL, will be sent along. Note: user and pass must be heap-allocated and will be free()d.

void mgos_mqtt_set_auth_callback(mgos_mqtt_auth_callback_t cb, void *cb_arg);

struct mg_connection *mgos_mqtt_get_global_conn(void);

Returns current MQTT connection if it is established; otherwise returns NULL

bool mgos_mqtt_global_connect(void);

Attempt MQTT connection now (if enabled and not already connected). Normally MQTT will try to connect in the background, at certain interval. This function will force immediate connection attempt.

bool mgos_mqtt_pub(const char *topic, const void *message, size_t len, int qos,
                   bool retain);

Publish message to the configured MQTT server, to the given MQTT topic. Return value will be true if there is a connection to the server and the message has been queued for sending. In case of QoS 1 return value does not indicate that PUBACK has been received; there is currently no way to check for that.

typedef void (*sub_handler_t)(struct mg_connection *nc, const char *topic,
                              int topic_len, const char *msg, int msg_len,
                              void *ud);

void mgos_mqtt_sub(const char *topic, sub_handler_t, void *ud);

Subscribe on a topic on a configured MQTT server.

size_t mgos_mqtt_num_unsent_bytes(void);

uint16_t mgos_mqtt_get_packet_id(void);

JAVASCRIPT API Reference api_mqtt.js


MQTT.sub(topic, handler)

Subscribe to a topic, and call given handler function when message arrives. A handler receives 4 parameters: MQTT connection, topic name, message, and userdata. Return value: none.


MQTT.sub('my/topic/#', function(conn, topic, msg) {
  print('Topic:', topic, 'message:', msg);
}, null);, message, qos)

Publish message to a topic. QoS defaults to 0. Return value: 0 on failure (e.g. no connection to server), 1 on success.

Example - send MQTT message on button press:

let pin = 0, topic = 'my/topic';
GPIO.set_button_handler(pin, GPIO.PULL_UP, GPIO.INT_EDGE_NEG, 200, function() {
  let res ='my/topic', JSON.stringify({ a: 1, b: 2 }), 1, false);
  print('Published:', res ? 'yes' : 'no');
}, null);

MQTT.setEventHandler(handler, userdata)

Set MQTT connection event handler. Event handler is ev_handler(conn, ev, edata), where conn is an opaque connection handle, ev is an event number, edata is an event-specific data. ev values could be low-level network events, like Net.EV_CLOSE or Net.EV_POLL, or MQTT specific events, like MQTT.EV_CONNACK.


MQTT.setEventHandler(function(conn, ev, edata) {
  if (ev !== 0) print('MQTT event handler: got', ev);
}, null);