ESP8266 Support WIKI

User Tools

Site Tools


Table of Contents

Native MQTT for ESP8266

This is MQTT client library for ESP8266, port from: MQTT client library for Contiki



  • Support subscribing, publishing, authentication, will messages, keep alive pings and all 3 QoS levels (it should be a fully functional client).
  • Support multiple connection (to multiple hosts).
  • Support SSL connection (max 1024 bit key size)
  • Easy to setup and use


#include "ets_sys.h"
#include "driver/uart.h"
#include "osapi.h"
#include "mqtt.h"
#include "wifi.h"
#include "config.h"
#include "debug.h"
#include "gpio.h"
#include "user_interface.h"
MQTT_Client mqttClient;
void wifiConnectCb(uint8_t status)
	if(status == STATION_GOT_IP){
		MQTT_Subscribe(&mqttClient, "/test/topic");
		MQTT_Subscribe(&mqttClient, "/test2/topic");
void mqttConnectedCb(uint32_t *args)
	MQTT_Client* client = (MQTT_Client*)args;
	INFO("MQTT: Connected\r\n");
void mqttDisconnectedCb(uint32_t *args)
	MQTT_Client* client = (MQTT_Client*)args;
	INFO("MQTT: Disconnected\r\n");
void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t lengh)
	INFO("MQTT topic: %s, data: %s \r\n", topic, data);
void user_init(void)
	uart_init(BIT_RATE_115200, BIT_RATE_115200);
	MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, SEC_SSL);
	MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive);
	MQTT_OnConnected(&mqttClient, mqttConnectedCb);
	MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb);
	MQTT_OnData(&mqttClient, mqttDataCb);
	WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb);
	INFO("\r\nSystem started ...\r\n");

Default configuration

See: user_config.h and config.c

Create SSL Self sign

openssl req -x509 -newkey rsa:1024 -keyout key.pem -out cert.pem -days XXX

SSL Mqtt broker for test

var mosca = require('mosca')
var SECURE_KEY = __dirname + '/key.pem';
var SECURE_CERT = __dirname + '/cert.pem';
var ascoltatore = {
  //using ascoltatore
  type: 'mongo',
  url: 'mongodb://localhost:27017/mqtt',
  pubsubCollection: 'ascoltatori',
  mongo: {}
var moscaSettings = {
  port: 8440,
  stats: false,
  backend: ascoltatore,
  persistence: {
    factory: mosca.persistence.Mongo,
    url: 'mongodb://localhost:27017/mqtt'
  secure : {
    keyPath: SECURE_KEY,
    certPath: SECURE_CERT,
    port: 8443
var server = new mosca.Server(moscaSettings);
server.on('ready', setup);
server.on('clientConnected', function(client) {
    console.log('client connected',;
// fired when a message is received
server.on('published', function(packet, client) {
  console.log('Published', packet.payload);
// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running')

Be careful: This library is not fully supported for too long messages.


Alpha release.

MQTT Broker for test

MQTT Client for test



esp_mqtt.txt · Last modified: 2015/01/09 06:28 by admin