Arduino Client for MQTT

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.

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 30 seconds
  • No support for Will messages

Download

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

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.

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