• Stars
    star
    1,004
  • Rank 45,731 (Top 1.0 %)
  • Language
    C
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

MQTT library for Arduino

arduino-mqtt

Test GitHub release

This library bundles the lwmqtt MQTT 3.1.1 client and adds a thin wrapper to get an Arduino like API.

Download the latest version from the release section. Or even better use the built-in Library Manager in the Arduino IDE and search for "lwmqtt".

The library is also available on PlatformIO. You can install it by running: pio lib install "256dpi/MQTT".

Compatibility

The following examples show how you can use the library with various Arduino compatible hardware:

Other shields and boards should also work if they provide a Client based network implementation.

Check out the Wiki to find more examples.

Notes

  • The maximum size for packets being published and received is set by default to 128 bytes. To change the buffer sizes, you need to use MQTTClient client(256) or MQTTClient client(256, 512) instead of just MQTTClient client at the top of your sketch. A single value denotes both the read and write buffer size, two values specify them separately. Beginning with version 2.6, the message payload is sent directly during publishing. Therefore, the write buffer is only needed to encode the packet header and topic, for which the default 128 bytes should be enough. However, the receiving of messages is still fully constrained by the read buffer, which may be increased if necessary.

  • On the ESP8266 it has been reported that an additional delay(10); after client.loop(); fixes many stability issues with WiFi connections.

  • To use the library with shiftr.io, you need to provide the instance name (username) and token secret (password) as the second and third argument to client.connect(client_id, username, password).

Example

The following example uses an Arduino MKR1000 to connect to the public shiftr.io instance. You can check on your device after a successful connection here: https://www.shiftr.io/try.

#include <SPI.h>
#include <WiFi101.h>
#include <MQTT.h>

const char ssid[] = "ssid";
const char pass[] = "pass";

WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;

void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("arduino", "public", "public")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("/hello");
  // client.unsubscribe("/hello");
}

void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);

  // Note: Do not use the client in the callback to publish, subscribe or
  // unsubscribe as it may cause deadlocks when other things arrive while
  // sending and receiving acknowledgments. Instead, change a global variable,
  // or push to a queue and handle it in the loop after calling `client.loop()`.
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pass);

  // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported
  // by Arduino. You need to set the IP address directly.
  client.begin("public.cloud.shiftr.io", net);
  client.onMessage(messageReceived);

  connect();
}

void loop() {
  client.loop();

  if (!client.connected()) {
    connect();
  }

  // publish a message roughly every second.
  if (millis() - lastMillis > 1000) {
    lastMillis = millis();
    client.publish("/hello", "world");
  }
}

API

Initialize the object using the hostname of the broker, the brokers port (default: 1883) and the underlying Client class for network transport:

void begin(Client &client);
void begin(const char hostname[], Client &client);
void begin(const char hostname[], int port, Client &client);
void begin(IPAddress address, Client &client);
void begin(IPAddress address, int port, Client &client);
  • Specify port 8883 when using secure clients for encrypted connections.
  • Local domain names (e.g. Computer.local on OSX) are not supported by Arduino. You need to set the IP address directly.

The hostname and port can also be changed after calling begin():

void setHost(const char hostname[]);
void setHost(const char hostname[], int port);
void setHost(IPAddress address);
void setHost(IPAddress address, int port);

Set a will message (last testament) that gets registered on the broker after connecting. setWill() has to be called before calling connect():

void setWill(const char topic[]);
void setWill(const char topic[], const char payload[]);
void setWill(const char topic[], const char payload[], bool retained, int qos);
void clearWill();

Register a callback to receive messages:

void onMessage(MQTTClientCallbackSimple);
// Callback signature: void messageReceived(String &topic, String &payload) {}

void onMessage(MQTTClientCallbackSimpleFunction cb);
// Callback signature: std::function<void(String &topic, String &payload)>

void onMessageAdvanced(MQTTClientCallbackAdvanced);
// Callback signature: void messageReceived(MQTTClient *client, char topic[], char bytes[], int length) {}

void onMessageAdvanced(MQTTClientCallbackAdvancedFunction cb);
// Callback signature: std::function<void(MQTTClient *client, char topic[], char bytes[], int length)>
  • The set callback is mostly called during a call to loop() but may also be called during a call to subscribe(), unsubscribe() or publish() // QoS > 0 if messages have been received before receiving the required acknowledgement. Therefore, it is strongly recommended to not call subscribe(), unsubscribe() or publish() // QoS > 0 directly in the callback.
  • In case you need a reference to an object that manages the client, use the void * ref property on the client to store a pointer, and access it directly from the advanced callback.
  • If the platform supports <functional> you can directly register a function wrapper.

Set more advanced options:

void setKeepAlive(int keepAlive);
void setCleanSession(bool cleanSession);
void setTimeout(int timeout);
void setOptions(int keepAlive, bool cleanSession, int timeout);
  • The keepAlive option controls the keep alive interval in seconds (default: 10).
  • The cleanSession option controls the session retention on the broker side (default: true).
  • The timeout option controls the default timeout for all commands in milliseconds (default: 1000).

Set a custom clock source "custom millis" callback to enable deep sleep applications:

void setClockSource(MQTTClientClockSource);
// Callback signature: uint32_t clockSource() {}
  • The specified callback is used by the internal timers to get a monotonic time in milliseconds. Since the clock source for the built-in millis is stopped when the Arduino goes into deep sleep, you need to provide a custom callback that first syncs with a built-in or external Real Time Clock (RTC). You can pass NULL to reset to the default implementation.

Connect to broker using the supplied client ID and an optional username and password:

bool connect(const char clientID[], bool skip = false);
bool connect(const char clientID[], const char username[], bool skip = false);
bool connect(const char clientID[], const char username[], const char password[], bool skip = false);
  • If password is present but username is absent, the client will fall back to an empty username.
  • If the skip option is set to true, the client will skip the network level connection and jump to the MQTT level connection. This option can be used in order to establish and verify TLS connections manually before giving control to the MQTT client.
  • The functions return a boolean that indicates if the connection has been established successfully (true).

Publish a message to the broker with an optional payload, which can be a string or binary:

bool publish(const String &topic);
bool publish(const char topic[]);
bool publish(const String &topic, const String &payload);
bool publish(const String &topic, const String &payload, bool retained, int qos);
bool publish(const char topic[], const String &payload);
bool publish(const char topic[], const String &payload, bool retained, int qos);
bool publish(const char topic[], const char payload[]);
bool publish(const char topic[], const char payload[], bool retained, int qos);
bool publish(const char topic[], const char payload[], int length);
bool publish(const char topic[], const char payload[], int length, bool retained, int qos);
  • Beginning with version 2.6, payloads of arbitrary length may be published, see Notes.
  • The functions return a boolean that indicates if the publishing has been successful (true).

Obtain the last used packet ID and prepare the publication of a duplicate message using the specified packet ID:

uint16_t lastPacketID();
void prepareDuplicate(uint16_t packetID);
  • These functions may be used to implement a retry logic for failed publications of QoS1 and QoS2 messages.
  • The lastPacketID() function can be used after calling publish() to obtain the used packet ID.
  • The prepareDuplicate() function may be called before publish() to temporarily change the next used packet ID and flag the message as a duplicate.

Subscribe to a topic:

bool subscribe(const String &topic);
bool subscribe(const String &topic, int qos); 
bool subscribe(const char topic[]);
bool subscribe(const char topic[], int qos);
  • The functions return a boolean that indicates if the subscription has been successful (true).

Unsubscribe from a topic:

bool unsubscribe(const String &topic);
bool unsubscribe(const char topic[]);
  • The functions return a boolean that indicates if the unsubscription has been successful (true).

Sends and receives packets:

bool loop();
  • This function should be called in every loop.
  • The function returns a boolean that indicates if the loop has been successful (true).

Check if the client is currently connected:

bool connected();

Check whether a session was present at the time of the last connect:

bool sessionPresent();

Configure dropping of overflowing messages (exceeding read buffer) and checking the count of dropped messages:

void dropOverflow(bool enabled);
uint32_t droppedMessages();

Access low-level information for debugging:

lwmqtt_err_t lastError();
lwmqtt_return_code_t returnCode();
  • The error codes can be found here.
  • The return codes can be found here.

Disconnect from the broker:

bool disconnect();
  • The function returns a boolean that indicates if the disconnect has been successful (true).

Release Management

  • Update version in library.properties.
  • Create release on GitHub.

More Repositories

1

lungo

A MongoDB compatible embeddable database and toolkit for Go.
Go
454
star
2

lwmqtt

a light weight MQTT implementation
C
106
star
3

gomqtt

Go packages for working with the MQTT protocol
Go
105
star
4

esp-mqtt

MQTT component for esp-idf projects based on the lwmqtt library
C
97
star
5

processing-mqtt

MQTT library for Processing based on the Eclipse Paho project
Java
75
star
6

fire

An idiomatic micro-framework for building Ember.js compatible APIs with Go.
Go
57
star
7

gov

A simple prometheus metrics and pprof profile viewer.
Go
47
star
8

newdns

A library for building custom DNS servers in Go.
Go
44
star
9

gcode

g-code parser and generator for go
Go
31
star
10

ofxMQTT

MQTT addon for openframeworks based on libmosquitto
C
28
star
11

OSCKit

objc OSC protocol implementation
C++
28
star
12

dokku-haproxy

haproxy tcp load balancer for dokku
Shell
18
star
13

max-mqtt

MQTT for Max
Max
17
star
14

jsonapi

A fundamental and extendable JSON API library for Go.
Go
12
star
15

quasar

A library that implements a family of low-level tools to build persistent messaging systems.
Go
12
star
16

embed

A small tool for embedding files in a Go source file.
Makefile
11
star
17

middleman-lunr

middleman extension for a static indexed search using lunr.js
Ruby
11
star
18

naos

The Networked Artifacts Operating System.
C
9
star
19

ThroughMomentum

An interactive kinetic light installation.
C
6
star
20

depthstream

stream kinect's depth image to websocket clients
Go
6
star
21

max-go

Toolkit for building Max externals with Go.
C
5
star
22

mobiledoc

Go package for handling the mobiledoc format
Go
5
star
23

oauth2

A fundamental and extendable OAuth2 library for Go.
Go
5
star
24

bespoke-app

desktop app for presenting bespoke.js presentations
JavaScript
4
star
25

mercury

an asynchronously flushing buffered writer for Go
Go
4
star
26

mgots

a wrapper for mgo that turns MongoDB into a time series database
Go
4
star
27

kiosk

a simple cocoa application for showing a website fullscreen
Objective-C
4
star
28

kiesel

Package with tools for working with the pebble embedded database engine.
Go
3
star
29

cloudpose

Processing
3
star
30

pdfkit

Easy PDF printing via the Chrome DevTools Protocol.
Go
3
star
31

application_buildpack

deploys and configures apps using heroku buildpacks
Ruby
2
star
32

grasshopper-mqtt

A grasshopper component that can connect to a MQTT broker.
C#
2
star
33

forge

A toolkit for managing long-running tasks in Go.
Go
2
star
34

fpack

A functional approach to encoding and decoding byte sequences.
Go
2
star
35

pulsar

Go
2
star
36

gcra-redis

a library for go-redis that implements the GCRA rate limit algorithm
Go
2
star
37

thermo

Go
2
star
38

mediakit

A media detection, analysis, conversion and extraction library for Go.
Go
2
star
39

mgojq

a wrapper for mgo that turns MongoDB into a job queue
Go
2
star
40

autolock

Package autolock implements a small wrapper over github.com/bsm/redis-lock to automatically refresh locks.
Go
2
star
41

gcra

Package gcra implements the generic cell rate algorithm
Go
2
star
42

sentry

a small tool to upload crash reports of failing programs
Go
2
star
43

turing

Go
1
star
44

serve

A collection of basic tools for building Go based APIs
Go
1
star
45

remote-iot

JavaScript
1
star
46

derive

A small utility for building derivatives.
Go
1
star
47

max-tools

A collection of max externals developed using max-go.
Go
1
star
48

aureus

a rails admin template
Ruby
1
star
49

madek

A Go library and command line tool that simplifies accessing the Madek API.
Go
1
star
50

mqtt-ml

MQTT and Tensorflow.js examples
JavaScript
1
star
51

ember

Provides tools to serve Ember.js apps from Go HTTP handlers.
Go
1
star
52

sentinel

Kubernetes Event Reporter for Sentry
Go
1
star
53

hanya

a rapid php website engine
PHP
1
star
54

verne

a markdown files driven wiki engine
Ruby
1
star
55

xo

A configuration, logging, reporting and tracing framework for Go applications.
Go
1
star
56

ember-fire

This add-on provides a set of tools to integrate ember with the fire framework.
JavaScript
1
star
57

middleman-headless

middleman extension for headless
Ruby
1
star
58

art32

an esp-idf component that provides useful functions
C
1
star
59

esp-osc

OSC component for esp-idf projects based on the tinyosc library
C
1
star
60

stack

abort and resume execution of a goroutine
Go
1
star
61

god

A small tool for simplifying debugging of go applications.
Go
1
star