/*************************************************************
  Download latest ERa library here:
    https://github.com/eoh-jsc/era-lib/releases/latest
    https://www.arduino.cc/reference/en/libraries/era
    https://registry.platformio.org/libraries/eoh-ltd/ERa/installation

    ERa website:                https://e-ra.io
    ERa blog:                   https://iotasia.org
    ERa forum:                  https://forum.eoh.io
    Follow us:                  https://www.fb.com/EoHPlatform
 *************************************************************/

// Enable debug console
// Set CORE_DEBUG_LEVEL = 3 first
#define ERA_DEBUG

// You should get Auth Token in the ERa App or ERa Dashboard
#define ERA_AUTH_TOKEN "1efecbc4-3cf4-40b3-8593-741827b2026f"

#include <Arduino.h>
#include <ERa.hpp>
#include <ERa/ERaTimer.hpp>
#include <WiFiClientSecure.h>

const char ssid[] = "Wokwi-GUEST";
const char pass[] = "";

ERaTimer timer;
WiFiClientSecure client;
const char*  server = "www.howsmyssl.com";  // Server URL

/* This function print uptime every second */
void timerEvent() {
    //ERA_LOG("Timer", "Uptime: %d", ERaMillis() / 1000L);
    static bool done = false;

    if ( done == false) {
      // done = true;
      Serial.println("Sending string to Era");
      ERa.virtualWrite(V1, "Hi, I'm ERa");
    }
}

ERA_WRITE(V4) {
    // Kiểm tra có phải chuỗi hay không
    if (!param.isNumber()) {
      Serial.println("Không phải số!");
        return;
    }

    // 1. Lấy chuỗi C-style strings
    int data = param.getInt();

    // Dùng 1 trong 4 cách trên để lấy dữ liệu chuỗi
    // Xử lý chuỗi (ví dụ với cách 2)
    Serial.print("Nhận được: "); Serial.println(data);
    ERa.virtualWrite(V4, data? 0 : 1);
}

void setup() {
    /* Setup debug console */
    Serial.begin(115200);

    Serial.println("Begin E-Ra...");
    ERa.begin(ssid, pass);
    Serial.println("Done!");
}

void loop() {
    ERa.run();

  Serial.println("\nStarting connection to server...");
  client.setInsecure();
  if (!client.connect(server, 443))
    Serial.println("Connection failed!");
  else {
    Serial.println("Connected to server!");
    // Make a HTTP request:
    client.println("GET https://www.howsmyssl.com/a/check HTTP/1.0");
    client.println("Host: www.howsmyssl.com");
    client.println("Connection: close");
    client.println();

    while (client.connected()) {
      String line = client.readStringUntil('\n');
      if (line == "\r") {
        Serial.println("headers received");
        break;
      }
    }
    // if there are incoming bytes available
    // from the server, read them and print them:
    while (client.available()) {
      char c = client.read();
      Serial.write(c);
    }

    client.stop();
  }

  delay(5000);
}