Argon MQTT Example

Here is an example of how to make an mqtt connection with argon using json, with the help of the ArduinoJson and PubSubClient libraries.

The argon sends simulated sensor information to the Beebotte platform for visualizing in a dashboard

Here´s the code used

/*
 * Project WifiSensor
 * Description:
 * Author: NPC
 * Date: 15/05/2020
 */
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <spark_wiring_tcpclient.h>

int led = D7;

//MQTT Connection
#define mqttServer "mqtt.beebotte.com"
#define mqttPort 1883
#define mqttChannel "yourchannelname"
#define mqttChannelToken "yourchanneltoken"
#define mqttTemperature "yourchannelresource#1"
#define mqttHumidity "yourchannelresource#2"
#define mqttControlVentilador "yourchannelresource#3"
#define PERSIST_DATA true   //for saving the data to beebotte database

//interval for sending data 30000 ms = 30 seconds
const long DATA_INTERVAL=30000;

//for using milis function instead of delay
unsigned long lastReadingMillis = 0;

//tcp client containing the argon wifi connection
TCPClient _client;

//client for connecting to mqtt server
PubSubClient mqttClient(_client); 

//function for receiving messages from the suscribed topics
void onMessage(char* topic, byte* payload, unsigned int length) {
  StaticJsonDocument<128> jsonOutBuffer;

  char array[128];
  strcpy(array, (char*)payload);

  DeserializationError error = deserializeJson(jsonOutBuffer, payload);
  if (error) {
    Serial.print(F("deserializeJson() failed with code "));
    Serial.println(error.c_str());
    return;
  }

  bool data = jsonOutBuffer["data"];

  digitalWrite(led, data ? HIGH : LOW);

  Serial.print("Received message of length ");
  Serial.print(length);
  Serial.println();
  Serial.print("data ");
  Serial.print(data);
  Serial.println();  
}

// setup() runs once, when the device is first turned on.
void setup() {
  // Put initialization like pinMode and begin functions here.
  Serial.begin(115200);
  Serial.println("Welcome Argon");

  pinMode(led,OUTPUT);
  digitalWrite(led,LOW);

  mqttClient.setServer(mqttServer, mqttPort);
  mqttClient.setCallback(onMessage);
}

//function for sending message to suscribers in the topic
void publish(const char* resource, float data, bool persist) {
  StaticJsonDocument<128> jsonOutBuffer;
  JsonObject root = jsonOutBuffer.to<JsonObject>();
  root["channel"] = mqttChannel;
  root["resource"] = resource;
  if (persist) {
    root["write"] = true;
  }
  root["data"] = data;

  //{"channel":"","resource":"","write":"true","data":""}
  char buffer[128];
  serializeJson(root, buffer, sizeof(buffer));

  char topic[64];
  sprintf(topic, "%s/%s", mqttChannel, resource);

  mqttClient.publish(topic, buffer);
}

//function for reconnecting to Mqtt Server
boolean reconnect() {
  if (mqttClient.connect("argonmqtt1", mqttChannelToken, "")) {
    char topic[64];

    //controlcuarto/controlventilador
    sprintf(topic, "%s/%s", mqttChannel, mqttControlVentilador);
    mqttClient.subscribe(topic);
    
    Serial.println("Connected to Beebotte MQTT");
  }
  
  return mqttClient.connected();
}

// loop() runs over and over again, as quickly as it can execute.
void loop() {
  // The core of your code will likely live here.
  if (!mqttClient.connected()) {
    reconnect();
  } else {
    unsigned long currentMillis = millis();
    
    if (currentMillis - lastReadingMillis >= DATA_INTERVAL) {
      lastReadingMillis = currentMillis;
      float t = random(40)+1.25;
      float h = random(70)+1.25;
      publish(mqttTemperature, t, PERSIST_DATA);
      Serial.print("Enviando temperatura: ");
      Serial.println(t);
      publish(mqttHumidity, h, PERSIST_DATA);
      Serial.print("Enviando humedad: ");
      Serial.println(h);
    }
  }
  
  mqttClient.loop();   
}
1 Like

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