hirotakaster / MQTT

MQTT for Photon, Spark Core
Other
217 stars 118 forks source link

MQTT for Photon, Spark Core

MQTT publish/subscribe library for Photon, Argon, Tracker One...etc version 0.4.32.

Source Code

This lightweight library source code is only 2 files. firmware -> MQTT.cpp, MQTT.h.

The application can use QoS 0, 1, 2 and the retain flag when publishing a message.

Example

Some sample sketches for Spark Core and Photon included (firmware/examples/).

developer examples

some applications use MQTT with Photon. here are developer's reference examples.

sample source

#include "application.h"
#include "MQTT.h"

void callback(char* topic, byte* payload, unsigned int length);
MQTT client("iot.eclipse.org", 1883, callback);

// recieve message
void callback(char* topic, byte* payload, unsigned int length) {
    char p[length + 1];
    memcpy(p, payload, length);
    p[length] = NULL;

    if (!strcmp(p, "RED"))
        RGB.color(255, 0, 0);
    else if (!strcmp(p, "GREEN"))
        RGB.color(0, 255, 0);
    else if (!strcmp(p, "BLUE"))
        RGB.color(0, 0, 255);
    else
        RGB.color(255, 255, 255);
    delay(1000);
}

void setup() {
    RGB.control(true);

    // connect to the server(unique id by Time.now())
    client.connect("sparkclient_" + String(Time.now()));

    // publish/subscribe
    if (client.isConnected()) {
        client.publish("outTopic/message","hello world");
        client.subscribe("inTopic/message");
    }
}

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

FAQ

Can't connect/publish/subscribe to the MQTT server?

I want to change MQTT keepalive timeout.

MQTT keepalive timeout is defined "MQTT_DEFAULT_KEEPALIVE 15"(15 sec) in header file. You can change the keepalive timeout in constructor.

    MQTT client("server_name", 1883, callback); // default: send keepalive packet to MQTT server every 15sec.
    MQTT client("server_name", 1883, 256, 30, callback); // keepalive timeout is 30 seconds, default message size also added to be able to access correct constructor 

Want to use over the 255 byte message size.

In this library, the maximum MQTT message size is defined as "MQTT_MAX_PACKET_SIZE 255" in the header file. If you want to use over 255 bytes, use the constructor's last argument.

    MQTT client("server_name", 1883, callback);      // default 255 bytes
    MQTT client("server_name", 1883, 512, callback); // max 512 bytes

Can I use on old firmware?

No, use the default latest firmware. I tested this library on the default latest firmware or the latest pre-release version. If you use an old firmware it may not work well and is not supported.

Bug or Problem?

First, check the Particle community site. But if your problem is not resolved, please create an issue with the problem details.

Pull Request

If you have a bug fix or feature, please send a pull request. Thanks for all developers' pull requests!