Git Product home page Git Product logo

mqtt-arduino_mqtt's Introduction

arduino-mqtt

Build Status GitHub release

This library bundles the lwmqtt 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 builtin Library Manager in the Arduino IDE and search for "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.

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) instead of just MQTTClient client on the top of your sketch. The passed value denotes the read and write buffer size.

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

Example

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

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

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

WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;

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("broker.shiftr.io", net);
  client.onMessage(messageReceived);

  connect();
}

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

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

  Serial.println("\nconnected!");

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

void loop() {
  client.loop();

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

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

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

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(const char hostname[], Client &client);
void begin(const char hostname[], int port, Client &client);
  • Specify port 8883 when using SSL clients for secure 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);

Set a will message (last testament) that gets registered on the broker after connecting:

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 onMessageAdvanced(MQTTClientCallbackAdvanced);
// Callback signature: void messageReceived(MQTTClient *client, char topic[], unsigned 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.

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

boolean connect(const char clientId[]);
boolean connect(const char clientId[], const char username[], const char password[]);
  • This functions returns a boolean that indicates if the connection has been established successfully.

Publishes a message to the broker with an optional payload:

boolean publish(const String &topic);
boolean publish(const char topic[]);
boolean publish(const String &topic, const String &payload);
boolean publish(const String &topic, const String &payload, bool retained, int qos);
boolean publish(const char topic[], const String &payload);
boolean publish(const char topic[], const String &payload, bool retained, int qos);
boolean publish(const char topic[], const char payload[]);
boolean publish(const char topic[], const char payload[], bool retained, int qos);
boolean publish(const char topic[], const char payload[], unsigned int length);
boolean publish(const char topic[], const char payload[], unsigned int length, bool retained, int qos);

Subscribe to a topic:

boolean subscribe(const String &topic);
boolean subscribe(const String &topic, int qos); 
boolean subscribe(const char topic[]);
boolean subscribe(const char topic[], int qos);

Unsubscribe from a topic:

boolean unsubscribe(const String &topic);
boolean unsubscribe(const char topic[]);

Sends and receives packets:

boolean loop();
  • This function should be called in every loop.

Check if the client is currently connected:

boolean connected();

Access low-level information for debugging:

lwmqtt_err_t lastError();
lwmqtt_return_code_t returnCode();

Disconnect from the broker:

boolean disconnect();

mqtt-arduino_mqtt's People

Contributors

256dpi avatar sandeepmistry avatar noelgeorgi avatar per1234 avatar

Watchers

Eric avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.