#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Adafruit_INA219.h>

// ================= WIFI =================
const char* ssid = "cuu";
const char* password = "11111111";

// ================= TELEGRAM =================
#define BOT_TOKEN "8484908633:AAHFX3qh9beCCT79QJRBd67FmR95NK20zJA"
#define CHAT_ID   "1758450850"

// ================= INA219 =================
Adafruit_INA219 ina219;

// ================= SENSOR TEGANGAN =================
#define PIN_ADC A0
float R1 = 100000.0;
float R2 = 20000.0;

// ================= TIMER =================
unsigned long lastSend = 0;
const unsigned long interval = 10000; // 10 detik

WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);

void setup() {
  Serial.begin(9600);

  Wire.begin(D2, D1);

  // INA219
  if (!ina219.begin()) {
    Serial.println("INA219 tidak terdeteksi!");
    while (1);
  }

  // WiFi
  WiFi.begin(ssid, password);
  Serial.print("Menghubungkan WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi Terhubung");

  client.setInsecure();

  bot.sendMessage(CHAT_ID, "✅ ESP8266 Monitoring Energi ONLINE", "");
}

void loop() {
  if (millis() - lastSend >= interval) {
    lastSend = millis();

    float voltage = readVoltage();
    float current = readCurrent();
    float power   = voltage * current;

    String message = formatMessage(voltage, current, power);
    bot.sendMessage(CHAT_ID, message, "");

    Serial.println(message);
  }
}

// ================= BACA TEGANGAN =================
float readVoltage() {
  int adc = analogRead(PIN_ADC);
  float vOut = adc * (3.3 / 1023.0);
  return vOut * ((R1 + R2) / R2);
}

// ================= BACA ARUS =================
float readCurrent() {
  return ina219.getCurrent_mA() / 1000.0;
}

// ================= FORMAT PESAN =================
String formatMessage(float v, float i, float p) {
  String msg = "📡 *Monitoring Energi DC*\n";
  msg += "----------------------\n";
  msg += "🔌 Tegangan : " + String(v, 2) + " V\n";
  msg += "⚡ Arus     : " + String(i, 3) + " A\n";
  msg += "🔋 Daya     : " + String(p, 2) + " W\n";
  msg += "⏱ Update   : 10 detik";
  return msg;
}
