Akshayan SinhaCETECH11
Published © LGPL

Qubitro Device Data | IoT Platform Series - 8

Guide to an Ultimate IoT Application Platform. Easy for starters, and smart for Experts. Even better with smooth User Interface ❤

BeginnerProtip1 hour109
Qubitro Device Data | IoT Platform Series - 8

Things used in this project

Hardware components

Espressif ESP32 Development Board - Developer Edition
Espressif ESP32 Development Board - Developer Edition
×1

Software apps and online services

Qubitro
Qubitro

Story

Read more

Code

ESP32_MQTT_Qubitro

Arduino
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

// WiFi SSID and Password
const char* ssid = "xxxxxxxxx";
const char* password = "xxxxxxxxx";
String topic = "xxxxx";
String mqtt_server = "broker.qubitro.com";
String mqttuser = "xxxxxxxxxxxxxxxxxxxxxx";
String mqttpass = "xxxxxxxxxxxxxxxxxxxxxx";
String clientId = "xxxxxxxxxxxxxxxxxxxxxx";

WiFiClientSecure espClient;
PubSubClient client(espClient);

float humidity = 0;
float temp = 0;



#define MSG_BUFFER_SIZE (500)
char msg[MSG_BUFFER_SIZE];
char output[MSG_BUFFER_SIZE];

void device_setup() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password); 

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}

void reconnect() {
  // Loop until we’re reconnected
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection…");
     
    if (client.connect(clientId.c_str(), mqttuser.c_str(), mqttpass.c_str())) {
      Serial.print("MQTT connected");
    } else {
      Serial.print("failed, rc = ");
      Serial.print(client.state());
      Serial.println(", try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  delay(500);
  // When opening the Serial Monitor, select 9600 Baud
  Serial.begin(115200);
  delay(500);
  device_setup();
  espClient.setInsecure();//skip verification
  //Serial.println(mqtt_server);
  client.setServer(mqtt_server.c_str(), 8883);
}

void loop() {
  
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  temp = random(20,30);
  humidity = random(60,70);
  
  StaticJsonDocument<200> doc;
  doc["Temperature"] = temp;
  doc["Humidity"] = humidity;
  serializeJson(doc, output);
  doc.garbageCollect();

  client.publish(topic.c_str(), output);
  Serial.println(output);
    
  delay(1000);
}

Credits

Akshayan Sinha
28 projects • 28 followers
Robotics Software Engineer with a makermind.
Contact
CETECH11
64 projects • 15 followers
Contact

Comments

Please log in or sign up to comment.