This library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT v3.

For more information about MQTT, visit http://mqtt.org.

Arduino Client for MQTT

Limitations

  • Only Quality of Service (QOS) 0 messaging is supported
  • The maximum message size, including header, is 128 bytes
  • The keepalive interval is set to 15 seconds
  • Based on the official Arduino Ethernet Shield. Other shields could be supported in the future.

License

This code is released under the MIT License.

Download

Change History

1.3
  • Fixed packet reading bug
1.2
  • Fixed compile error when used with arduino-0016 or later
1.1
  • Reduced size of library
  • Added support for Will messagesClarified licensing – see LICENSE.txt
1.0
  • Only Quality of Service (QOS) 0 messaging is supported
  • The maximum message size, including header, is 128 bytes
  • The keepalive interval is set to 30 seconds
  • No support for Will messages

Example

#include <Ethernet.h>
#include <PubSubClient.h>

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 172, 16, 0, 1 };
byte server[] = { 172, 16, 0, 100 };

void callback(char* topic, byte* payload,int length) {
  // handle message arrived
}

PubSubClient client(server, 1883, callback);

void setup()
{
  Ethernet.begin(mac, ip);
  if (client.connect("arduino")) {
    client.publish("foo","hello world");
    client.subscribe("bar");
  }
}

void loop()
{
  client.loop();
}

API

Summary

PubSubClient(server, port, callback)

Description

Creates a client instance.

Parameters
  • server : the IP address of the server (array of 4 bytes)
  • port : the port to connect to (int)
  • callback : a pointer to a function called when a message arrives for a subscription created by this client. If no callback is required, set this to 0

The callback function has the following signature:

 void callback(char* topic, byte* payload,int length)

int connect(clientID)

Description

Connects the client.

Parameters
  • clientID : the client ID to use when connecting to the server. As per MQTT, this must be between 1 and 23 characters long.

Returns:

  • 0 – connection failed. To avoid flooding a server, it is recommended that a client waits for a period of time (eg 10 seconds) before attempting to reconnect.
  • 1 – connection succeeded.

int connect(clientID, willTopic, willQoS, willRetain, willMessage)

Description

Connects the client with a Will message specified.

Parameters
  • clientID : the client ID to use when connecting to the server. As per MQTT, this must be between 1 and 23 characters long.
  • willTopic : the topic to be used by the will message (string)
  • willQoS : the quality of service to be used by the will message (int : 0,1 or 2)
  • willRetain : whether the will should be published with the retain flag (int : 0 or 1)
  • willMessage : the payload of the will message (string)

Returns:

  • 0 – connection failed. To avoid flooding a server, it is recommended that a client waits for a period of time (eg 10 seconds) before attempting to reconnect.
  • 1 – connection succeeded.

void disconnect()

Description

Disconnects the client.

int publish(topic, payload)

Description

Publishes a string message to the specified topic

Parameters
  • topic – the topic to publish to (string)
  • payload – the message to publish (string)

int publish(topic, payload, length)

Description

Publishes an arbitrary message to the specified topic

Parameters
  • topic – the topic to publish to (string)
  • payload – the message to publish (byte array)
  • length – the length of the message (byte)

void subscribe(topic)

Description

Subscribes to messages published to the specified topic.

Parameters
  • topic – the topci to publish to (string)

int loop()

Description

This should be called regularly to allow the client to process incoming messages and maintain its connection to the server.
Returns:

  • 0 – the client is no longer connected
  • 1 – the client is still connected

int connected()

Description

Checks whether the client is connected to the server.
Returns:

  • 0 – the client is not connected
  • 1 – the client is connected
  1. pingback from knolleary » Blog Archive » CurrentCostuinoNovember 19, 2008

    [...] You’ll find the Client for MQTT library here. [...]

  2. pingback from knolleary » Blog Archive » Updated Client for MQTT libraryJanuary 29, 2009

    [...] the MQTT library for the arduino ethernet shield and released version 1.1. You can find the library here. I’m thinking of moving it to github or google code once I can decide which to use – any [...]

  3. pingback from Delphi can do MQTT too!February 23, 2009

    [...] O’Leary has written a very handy MQTT Client for the Arduino platform which allows my ambient orb to get the latest consumption data from the CurrentCost unit without [...]

  4. pingback from Updated Arduino MQTT client « knollearyJuly 24, 2009

    [...] ever, get the updated MQTT Arduino client from here. no comments  arduino, mqtt, [...]

  5. john cohn • January 1, 2010

    Hello and happy new year ! !. I was wondering if you’d have a few minutes to help me think through how to get your MQTT client for the arduino working wiht the Asynclabs WiShield for 802.11 (http://asynclabs.com/wiki/index.php?title=WiShield_1.0) . The WiShield uses the uip TCP/IP stack.. not the one in the standard Ethernet.h used by the Arduino ethernet shields. I’ve been fiddling with your code to see if I can map over to the different IP stack, but I’m afraid it’s a little beyond me. A few minutes of coaching from you might get me there. Please let me know if you’re available to talk. Thanks !
    -jc

  6. nickJanuary 1, 2010

    Hi John – porting this library to other shields has been on my todo list for a while; so I’m happy to help if I can.

    I’ve had a quick look and it should be possible to do. The API provided by Ethernet.h is very simple; connect, read, write, disconnect, not much else. The trick will be figuring out how the equivalent functionality is surfaced by the WiShield library. The sample apps provided with WiShield should help do this.

    I’m back in the office next week; give me a shout on Sametime and we can take a close look.

  7. john cohn • January 2, 2010

    Nick,
    Will do .. I just set up a mtg for us on Monday.. let me know if the time’s OK. I look forward to speaking with you about this and some other schemes. Thanks !
    -jc

  8. MarkJanuary 3, 2010

    Hi
    Just wanted to say thanks for creating this client. Using this I have created a small web page that shows the temperature from a network connected Arduino. It is hosted on a tiny home server, so may take a few seconds to open….
    http://metphoto.homeunix.net/met_current/cgi-bin/ardtemp.pl

    I am no programmer, so could I ask for a small example of how to decode a message from a RSMB? I just cant quite get the code right to do this.

    Thanks
    Mark

  9. JerryJanuary 25, 2010

    Thanks for the MQTT client code Nick – I’ve been experimenting with this off and on for a month or two, using it with an Arduino duemilanove to demo MQTT to colleagues as a better way to read data from sensors than using the web server/Ethernet shield examples that are getting more coverage. BTW Mark’s PDF and project (link above) is a useful worked example, demonstrates the whole thing end to end and fills in some gaps in an unassuming kind of way.

  10. Dave NiceMarch 3, 2010

    Hi Nick,

    I’ve been using the MQTT library and I’ve got a couple of questions:

    If I lose my MQTT connection (e.g. unplug the network cable and wait for the library to realise it’s been disconnected), to get reconnected I have to call client.disconnect() first. Is this expected behaviour?

    Also, I have a 250ms pause at the end of my loop function. The effect of this is that client.loop() gets called less often. In your API doc it seems to indicate that I only need to call often enough to prevent the connection timing out and maintain my own preferred level of service on time to receive a message, is this correct?

    Thanks,

    Dave

  11. nickMarch 4, 2010

    Dave,

    #1 I haven’t done much with that scenario, so I couldn’t say for sure. There is no state cleared when you call disconnect, so it shouldn’t be necessary.

    #2 250ms will be fine. For a publishing-only client, you can get away with calling loop() once every keep-alive interval (fixed at 15secs). For a subscribed client, the same is true, but you will only get a message-arrived callback whilst in a call to loop() – it is up to you how timely you want the message delivery to be.

  12. leave a comment