MQTT program with Boron

Hi Guys,
I am new to Boron 2G/3G. Can anyone help me how can we publish data to MQTT broker.

Have you tried the MQTT library available in Web IDE?

Hi I am trying to ise ubidosts MQtt broker for pub and sub . but its not working. please find the code below

/****************************************
 * Include Libraries
 ****************************************/

#include "UbidotsMQTT.h"

/****************************************
 * Define Constants
 ****************************************/

#ifndef TOKEN
#define TOKEN "BBFF-fdxKVadBcUqfyZRCl57voPBldco2KT"  // Add here your Ubidots TOKEN
#endif


/****************************************
 * Auxiliar Functions
 ****************************************/

void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);
    Serial.print("] ");
    Serial.println("payload obtained from server:");
    for (int i=0;i<length;i++) {
        Serial.print((char)payload[i]); // prints the answer of the broker for debug purpose
    }
    // Some stuff to make with the payload obtained
        //
   //
    Serial.println();
}

/****************************************
 * Instances
 ****************************************/

UbidotsMQTT client(TOKEN, callback);

/****************************************
 * Main Functions
 ****************************************/

void setup() {
    Serial.begin(115200); 

    // Uncomment this line if you have an Ubidots account
    client.ubidotsSetBroker("industrial.api.ubidots.com");

    //client.initialize();

    if(client.isConnected()){
        // Insert as first parameter the device to subscribe and as second the variable label
        client.ubidotsSubscribe("Abdul Sheikh", "Abdul Sheikh"); 
    }
}

void loop() {
    if(!client.isConnected()){
        //client.reconnect();
    }
// Publish routine, if the device and variables are not created they will be created
    float value = 1;
    Serial.println("Sending value");
    client.add("test-var-1", value); // Insert as first parameter your variable label
    client.add("test-var-2", value, "\"lat\":10.302, \"lng\":2.9384"); //Adds value with context
    client.add("test-var-3", value, NULL, 1492445109); // Adds value with custom timestamp
    client.ubidotsPublish("Abdul Sheikh"); // Insert your device label where the values will be stored in Ubidots

    // Client loop for publishing and to maintain the connection
    client.loop();
    delay(1000);
}

In your original post you didn’t mention anything about using their service.
The library you are using is particularly targeted at their service.
When you want to target any arbitrary MQTT broker you’d probably better served with this library
https://build.particle.io/libs/MQTT/0.4.29/tab/example/mqtttest.ino

On the other hand, when you want to send data to Ubidots, I’d not go the MQTT route but rather their standard library
https://build.particle.io/libs/Ubidots/3.1.4/tab/UbiParticle.h

Thanks.
I test the code “mqtttest.ino” as an example with broker.hivemq.com. but it make the boron to look for internet for a while and go to sleep. Even it doesn’t respond with iot.eclipse.org
https://build.particle.io/build/5f7afc4a5e1db50009c58ee7

Thank You. I test the code with the same topic name in publish and subscribe. Now its working. Thank you so much for your help.

1 Like

i have used this Sample code test.
it works for 1 Publishing and stops responding afterwards and i have to hard reset.
Please help me out
Thanks

That was a non-shareable link.
If you want to create a shareable one you need to use the SHARE THIS REVISION feature.

Sorry, Please find the link

First thing I’d do would be to get rid of the delay(1000) in the callback function.
Then in addition to that you may want to add a reconnect logic in the else branch of the if() statement in loop().

This should always be on of the primary debugging steps: Follow all possible code paths and see whether they execute as intended.

Hi,
I have check the code with reconnect logic. There is no defined "reconnect " function in <MQTT.h>. The one thing that i find is the "int keep alive" argument in the MQTT function. should we have to give particular value to keepalive argument. I want to add the code in which boron wakeup after user defined time, post data over MQTT and then goes back to sleep and wakeup after the time period. However, With that code, i have to do hard reset everytime.
Please find the MQTT.h code.

MQTT::MQTT(char* domain, uint16_t port, void (callback)(char,uint8_t*,unsigned int)) {
this->initialize(domain, NULL, port, MQTT_DEFAULT_KEEPALIVE, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(char* domain, uint16_t port, void (callback)(char,uint8_t*,unsigned int), int maxpacketsize) {
this->initialize(domain, NULL, port, MQTT_DEFAULT_KEEPALIVE, callback, maxpacketsize);
}

MQTT::MQTT(uint8_t ip, uint16_t port, void (callback)(char,uint8_t,unsigned int)) {
this->initialize(NULL, ip, port, MQTT_DEFAULT_KEEPALIVE, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(uint8_t ip, uint16_t port, void (callback)(char,uint8_t,unsigned int), int maxpacketsize) {
this->initialize(NULL, ip, port, MQTT_DEFAULT_KEEPALIVE, callback, maxpacketsize);
}

MQTT::MQTT(char* domain, uint16_t port, int keepalive, void (callback)(char,uint8_t*,unsigned int)) {
this->initialize(domain, NULL, port, keepalive, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(char* domain, uint16_t port, int keepalive, void (callback)(char,uint8_t*,unsigned int), int maxpacketsize) {
this->initialize(domain, NULL, port, keepalive, callback, maxpacketsize);
}

MQTT::MQTT(uint8_t ip, uint16_t port, int keepalive, void (callback)(char,uint8_t,unsigned int)) {
this->initialize(NULL, ip, port, keepalive, callback, MQTT_MAX_PACKET_SIZE);
}

MQTT::MQTT(uint8_t ip, uint16_t port, int keepalive, void (callback)(char,uint8_t,unsigned int), int maxpacketsize) {
this->initialize(NULL, ip, port, keepalive, callback, maxpacketsize);

void MQTT::initialize(char* domain, uint8_t ip, uint16_t port, int keepalive, void (callback)(char,uint8_t,unsigned int), int maxpacketsize) {
this->callback = callback;
this->qoscallback = NULL;
if (ip != NULL)
this->ip = ip;
if (domain != NULL)
this->domain = domain;
this->port = port;
this->keepalive = keepalive;

// if maxpacketsize is over MQTT_MAX_PACKET_SIZE.
this->maxpacketsize = (maxpacketsize <= MQTT_MAX_PACKET_SIZE ? MQTT_MAX_PACKET_SIZE : maxpacketsize);
if (buffer != NULL)
  delete[] buffer;
buffer = new uint8_t[this->maxpacketsize];

}

Blockquote

Sorry, for the confusion, but when you call client.connect() again once your code realizes that it is not connected, then this is a reconnect. You don't need a function that is called reconnect() when you can just connect() again :wink:

BTW, what device OS version are you targeting?

1 Like

Working on 1.5.4-rc.1

With the changes in loop(); it shows still the same thing.

1 Like

That’s not quite what I meant :upside_down_face:

Try this instead (I also added a Particle.function() to test the code)

#include "MQTT.h"

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

MQTT client("broker.hivemq.com", 1883, callback);

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

    RGB.control(true);
    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 {
        Serial.printlnf("Unknown message: %s", p);
        RGB.control(false);                         // give up RGB control
    }
}

bool mqttConnect() {                                // one simple function to easily (re)connect at multiple places in code
    client.connect("sparkclient");
    if (client.isConnected()) {
        client.subscribe("outTopic/message");
        return true;
    }
    
    return false;
}

void setup() {
    Particle.function("mqttPub", mqttPub);          // test function (send RED, GREEN, BLUE via console)
    mqttConnect();                                  // initial connection
}

void loop() {
    if (client.isConnected()) 
        client.loop();
    else {                                          // when connection is lost, tell us so and reconnect
        Serial.println("connection lost - reconnect");
        mqttConnect();
    }
}

int mqttPub(const char* msg) {
    if (client.isConnected()) { 
        client.publish("outTopic/message", msg);
        return strlen(msg);                         // success: report length of received message
    }
    
    return -1;                                      // failure: return -1
}
2 Likes

Sorry for confusion. It worked now. Thank you for your time and help. :slight_smile:

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.