TCAE System

System Online

Scanning for ESP Devices...

Device Connection Guide

Waiting for ESP...

Upload this snippet to your ESP8266/ESP32 to automatically connect it to this dashboard. Make sure to replace the WiFi credentials.

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

// Replace with your EC2 API URL (or local IP for testing)
const char* apiBaseURL = "https://test.biofeed.danielmello.store"; 
String deviceId = "";
String deviceToken = "";

unsigned long lastReportTime = 0;
const unsigned long reportInterval = 5000; // 5 seconds interval

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("
Connected to WiFi");
  
  // Register Device
  registerDevice();
}

void loop() {
  if (WiFi.status() == WL_CONNECTED && deviceId != "") {
    unsigned long currentMillis = millis();
    
    // Non-blocking report loop
    if (currentMillis - lastReportTime >= reportInterval) {
      lastReportTime = currentMillis;
      sendReport();
      fetchCommands();
    }
  }
}

void registerDevice() {
  WiFiClientSecure client;
  client.setInsecure(); // Bypass SSL certificate verification for simplicity
  HTTPClient http;
  
  String url = String(apiBaseURL) + "/device/register";
  http.begin(client, url);
  http.addHeader("Content-Type", "application/json");

  // Create JSON Payload
  StaticJsonDocument<200> doc;
  doc["name"] = "esp32-real-01";
  String requestBody;
  serializeJson(doc, requestBody);

  int httpCode = http.POST(requestBody);
  if (httpCode == 200) {
    String payload = http.getString();
    
    // Parse response
    StaticJsonDocument<256> resDoc;
    deserializeJson(resDoc, payload);
    
    deviceId = resDoc["id"].as<String>();
    deviceToken = resDoc["token"].as<String>(); // Token is saved for future secure use
    
    Serial.println("Registered successfully!");
    Serial.println("ID: " + deviceId);
  } else {
    Serial.println("Failed to register. HTTP Code: " + String(httpCode));
  }
  http.end();
}

// -----------------------------------------
// 1. Send Telemetry
// -----------------------------------------
void sendReport() {
  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;
  
  String url = String(apiBaseURL) + "/device/" + deviceId + "/report";
  http.begin(client, url);
  http.addHeader("Content-Type", "application/json");

  // Mock sensor reading (Use actual DHT11/BME280 etc in production)
  float t = 25.0 + random(0, 50) / 10.0;
  float h = 50.0 + random(0, 100) / 10.0;

  StaticJsonDocument<200> doc;
  doc["temperature"] = t;
  doc["humidity"] = h;
  String requestBody;
  serializeJson(doc, requestBody);

  int httpCode = http.POST(requestBody);
  if (httpCode != 200) {
    Serial.println("Report failed. Code: " + String(httpCode));
  }
  http.end();
}

// -----------------------------------------
// 2. Fetch Commands
// -----------------------------------------
void fetchCommands() {
  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;
  
  String url = String(apiBaseURL) + "/device/" + deviceId + "/commands";
  http.begin(client, url);
  
  int httpCode = http.GET();
  if (httpCode == 200) {
    String payload = http.getString();
    
    // DynamicJsonDocument because payload size varies depending on number of pending commands
    DynamicJsonDocument doc(1024);
    DeserializationError error = deserializeJson(doc, payload);

    if (!error) {
      JsonArray array = doc.as<JsonArray>();
      for (JsonObject cmd : array) {
        int cmdId = cmd["id"];
        String cmdType = cmd["type"].as<String>();
        
        Serial.printf("
Executing Command ID: %d | Type: %s
", cmdId, cmdType.c_str());
        
        // --- PUT YOUR DEVICE LOGIC HERE ---
        if (cmdType == "FEED") {
          int duration = cmd["payload"]["duration"];
          Serial.printf("Feeding for %d ms...
", duration);
          // digitalWrite(RELAY_PIN, HIGH); delay; digitalWrite(RELAY_PIN, LOW);
        } else if (cmdType == "TOGGLE_RELAY") {
          Serial.println("Toggling relay...");
        }

        // --- RESPOND ---
        sendCommandResponse(cmdId, "done");
      }
    }
  }
  http.end();
}

// -----------------------------------------
// 3. Send Response
// -----------------------------------------
void sendCommandResponse(int commandId, String status) {
  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;
  
  String url = String(apiBaseURL) + "/device/" + deviceId + "/command-response";
  http.begin(client, url);
  http.addHeader("Content-Type", "application/json");

  StaticJsonDocument<200> doc;
  doc["command_id"] = commandId;
  doc["status"] = status;
  String requestBody;
  serializeJson(doc, requestBody);

  http.POST(requestBody);
  http.end();
}