ESP32 Lesson: Favoriot


Favoriot adalah salah satu penyedia bagi platform IOT. Melalui platform Favoriot dashboard, boleh memaparkan data dalam bentuk graf atau gauge. Selain itu, dashboard mempunyai input seperti button, switch dan slider. ESP32 menghantar data ke Favoriot melalui https request manakala ESP32 menerima data dari Favoriot melalui subcribe topic MQTT.

Berikut adalah demo Favoriot.

Video Tik Tok

@shahrulnizamcom ESP32 http request to Favoriot #esp32 #favoriot ♬ original sound – Shahrulnizam

@shahrulnizamcom ESP32 MQTT Subcribe Favoriot #esp32 #favoriot #mqtt #iot #coding ♬ original sound – Shahrulnizam

ESP32 Source Code

#include <WiFi.h>
#include <HTTPClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Adafruit_BME280.h>
#include <Adafruit_NeoPixel.h>

#define defaultssid "Your SSID Here"
#define defaultssidpass "Your Password Here"
#define LED 2

HTTPClient http;
WiFiClient mqttClient;
PubSubClient client(mqttClient);
Adafruit_BME280 bme;
Adafruit_NeoPixel strip(1, 16);

String apiKey = "Your apiKey Here";
String token = "Your Token Here";
String device_developer_id = "esp32@Shahrul";
String url = "https://apiv2.favoriot.com/v2/streams";
String broker = "mqtt.favoriot.com";
String username = token;
String password = token;
String topicIn = token + "/v2/rpc";
String title, ssid, ssidpass, ids, ip, message, temp;
float altitude, pressure, temperature, humidity;
uint8_t httpCode, rgb;
uint16_t i, counter;
uint64_t id, timer;
StaticJsonDocument<200> doc;
JsonObject obj;

void OnWiFiEvent(WiFiEvent_t event) {
  switch (event) {
    case SYSTEM_EVENT_STA_CONNECTED:
      {
        Serial.println("Wifi Connected");
        break;
      }
    case SYSTEM_EVENT_STA_DISCONNECTED:
      {
        Serial.println("Wifi Disconnected");
        WiFi.begin(ssid.c_str(), ssidpass.c_str());
        break;
      }
  }
}

void setup() {
  Serial.begin(115200);
  digitalWrite(LED, HIGH);
  strip.begin();
  strip.show();
  pinMode(LED, OUTPUT);
  if (!bme.begin()) {
    Serial.println("Failed to find Hibiscus Sense BME280 chip");
  }

  ssid = defaultssid;
  ssidpass = defaultssidpass;
  id = ESP.getEfuseMac();
  ids = String(uint32_t(id >> 32), HEX) + String(uint32_t(id), HEX);
  ids.toUpperCase();

  WiFi.begin(ssid.c_str(), ssidpass.c_str());
  client.setServer(broker.c_str(), 1883);
  client.setCallback(callback);
  WiFi.onEvent(OnWiFiEvent);
}

void loop() {
  ip = WiFi.localIP().toString();
  client.loop();
  altitude = bme.readAltitude(1013.25);   //unit m
  pressure = 0.001 * bme.readPressure();  //unit kPa
  temperature = bme.readTemperature();    //unit degC
  humidity = bme.readHumidity();          //unit %

  if (WiFi.status() == WL_CONNECTED & millis() - timer >= 10000) {
    timer = millis();
    if (!client.connected()) {
      Serial.println("Connecting to MQTT broker");

      if (client.connect(ids.c_str(), username.c_str(), password.c_str())) {
        Serial.println("Subscribe to: " + String(topicIn));
        client.subscribe(topicIn.c_str());
      } else {
        Serial.print("failed, rc=");
        Serial.print(client.state());
      }
    }
    http.begin(url);
    http.addHeader("Content-Type", "application/json");
    http.addHeader("Apikey", apiKey);
    message = "";
    JsonObject root = doc.to<JsonObject>();
    root["device_developer_id"] = device_developer_id;
    JsonObject data = root.createNestedObject("data");
    data["altitude"] = String(altitude);
    data["pressure"] = String(pressure);
    data["temperature"] = String(temperature);
    data["humidity"] = String(humidity);
    serializeJson(root, message);
    Serial.println(message);
    httpCode = http.POST(message);
    if (httpCode > 0) {
      message = http.getString();
      Serial.println(message);
      Serial.println();
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  temp = "";
  for (i = 0; i < length; i++) temp += (char)payload[i];
  Serial.println("Message Received: " + temp);

  deserializeJson(doc, temp);
  obj = doc.as<JsonObject>();
  message = obj["button"].as<String>();
  if (message == "1") {
    if (counter < 2) counter++;
    else counter = 0;
    if (counter == 0) strip.setPixelColor(0, strip.Color(rgb, 0, 0));
    if (counter == 1) strip.setPixelColor(0, strip.Color(0, rgb, 0));
    if (counter == 2) strip.setPixelColor(0, strip.Color(0, 0, rgb));
    strip.show();
  }

  message = obj["slider"].as<String>();
  if (message != "null") {
    rgb = message.toInt();
    if (counter == 0) strip.setPixelColor(0, strip.Color(rgb, 0, 0));
    if (counter == 1) strip.setPixelColor(0, strip.Color(0, rgb, 0));
    if (counter == 2) strip.setPixelColor(0, strip.Color(0, 0, rgb));
    strip.show();
  }

  message = obj["switch"].as<String>();
  if (message == "0") digitalWrite(LED, HIGH);
  if (message == "1") digitalWrite(LED, LOW);
}

Leave a Reply

Your email address will not be published. Required fields are marked *