Skip to content

Instantly share code, notes, and snippets.

@ahmedalkabir
Created May 23, 2023 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedalkabir/3f3a129f7db6b8851f12a31d71220e2f to your computer and use it in GitHub Desktop.
Save ahmedalkabir/3f3a129f7db6b8851f12a31d71220e2f to your computer and use it in GitHub Desktop.
#include <Arduino.h>
#include <WiFi.h>
#include <MQTT.h>
#include <ArduinoJson.h>
char tago_buffer[500];
StaticJsonDocument<500> tago_json;
MQTTClient mqtt_client;
WiFiClient net;
const char *id = "esp32";
const char *username = "Token";
const char *pass = "db8ad28c-71c7-4c49-9a19-a18c0267e7aa";
void setup()
{
delay(3000);
pinMode(45, OUTPUT);
digitalWrite(45, LOW);
Serial.begin(115200);
Serial.println("[ESP32-S3 MQTT LAMP Controller]");
// wait until to connect to the broker
// connecto to wifi network first
Serial.println("[connect to wifi network]");
WiFi.begin("Mi 10T", "password1");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
// WiFi.begin("Mi 10T", "password1"); // tidious right!!, but sometimes doesn't connect well to the network
}
Serial.println("\n[connected to wifi network]");
mqtt_client.begin("mqtt.tago.io", net);
// it's supposed to pass lambda function to onMessage method but I guess there's a
// bug within a compiler
std::function<void(String & topic, String & payload)> fb = [](String &topic, String &payload)
{
Serial.println("=====================================");
Serial.printf("[Message from %s - %s]\n", topic.c_str(), payload.c_str());
deserializeJson(tago_json, payload.c_str());
// we will receive lamp_1 variable
auto status = tago_json["value"].as<bool>();
if(status){
Serial.println("[lamp on]");
digitalWrite(45, HIGH);
} else {
Serial.println("[lamp off]");
digitalWrite(45, LOW);
}
};
mqtt_client.onMessage(fb);
Serial.println("[connect to mqtt tago io]");
while (!mqtt_client.connect(id, username, pass))
{
Serial.print(".");
vTaskDelay(pdMS_TO_TICKS(500));
}
mqtt_client.subscribe("/control");
Serial.println("[mqtt connected to broker]");
}
void loop()
{
// put your main code here, to run repeatedly:
mqtt_client.loop();
if (!mqtt_client.connected())
{
Serial.println("[connect to mqtt tago io]");
while (!mqtt_client.connect(id, username, pass))
{
Serial.print(".");
vTaskDelay(pdMS_TO_TICKS(500));
}
mqtt_client.subscribe("/control");
Serial.println("[mqtt connected to broker]");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment