/*
 * Energy Prioritizer — two-load EDUCATIONAL demonstration.
 * Classic ESP32 Dev Module; Arduino ESP32 3.x; ArduinoJson 7.
 * Libraries: PubSubClient and PZEM004Tv30.
 * Compile with placeholders, then fill secrets.h before use.
 * Aggregate metering and estimated allocation are NOT electrical protection.
 * Do not use for safety-critical loads. Mains work requires qualified personnel.
 */
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <PZEM004Tv30.h>
#include <time.h>
#include <math.h>

#if __has_include("secrets.h")
#include "secrets.h"
#else
#include "secrets.example.h"
#endif

// Adapt signal pins, polarity, ratings and switching hardware to your rig.
constexpr uint8_t RELAY_PINS[] = {26, 27};
constexpr uint8_t RELAY_ON = LOW;
constexpr uint8_t RELAY_OFF = HIGH;
constexpr uint8_t PZEM_RX = 16, PZEM_TX = 17;
constexpr float ESTIMATED_WATTS[] = {100.0f, 40.0f};
constexpr uint32_t SENSOR_INTERVAL_MS = 1000;
constexpr uint32_t RETRY_INTERVAL_MS = 5000;
constexpr uint32_t TELEMETRY_STALE_MS = 3000;
constexpr uint32_t MIN_SWITCH_INTERVAL_MS = 2000;

WiFiClientSecure tls;
PubSubClient mqtt(tls);
PZEM004Tv30 pzem(Serial2, PZEM_RX, PZEM_TX);
bool requested[] = {false, false};
bool output[] = {false, false};
bool sensorValid = false, measuredHold = false;
int budget = 200;
float watts = NAN, volts = NAN, amps = NAN, pf = NAN;
float hz = NAN, energy = NAN;
uint32_t lastSample = 0, lastGoodSample = 0;
uint32_t lastMqttTry = 0, lastWifiTry = 0, lastSwitch[] = {0, 0};
String telemetryTopic, statusTopic, controlPrefix, clientId;

bool configured() {
  return !String(WIFI_SSID).startsWith("YOUR_") &&
         !String(MQTT_HOST).startsWith("YOUR_") &&
         !String(MQTT_USERNAME).startsWith("YOUR_") &&
         !String(MQTT_PASSWORD).startsWith("YOUR_") &&
         String(ROOT_CA).indexOf("YOUR_") < 0;
}
void writeOutput(uint8_t n, bool on, bool immediateOff = false) {
  if (output[n] == on) return;
  const uint32_t now = millis();
  // OFF always acts immediately. Minimum switching interval delays only ON.
  if (on && !immediateOff && now - lastSwitch[n] < MIN_SWITCH_INTERVAL_MS) return;
  digitalWrite(RELAY_PINS[n], on ? RELAY_ON : RELAY_OFF);
  output[n] = on;
  lastSwitch[n] = now;
}
void allOff() { for (uint8_t n = 0; n < 2; n++) writeOutput(n, false, true); }
void allocate() {
  if (!sensorValid || measuredHold || !mqtt.connected() ||
      WiFi.status() != WL_CONNECTED || millis() - lastGoodSample > TELEMETRY_STALE_MS) {
    allOff(); return;
  }
  bool desired[2] = {false, false};
  float remaining = budget;
  for (uint8_t n = 0; n < 2; n++) {
    desired[n] = requested[n] && ESTIMATED_WATTS[n] <= remaining;
    if (desired[n]) remaining -= ESTIMATED_WATTS[n];
  }
  // Shed before enabling another load to avoid transitional overlap.
  for (uint8_t n = 0; n < 2; n++) if (!desired[n]) writeOutput(n, false);
  for (uint8_t n = 0; n < 2; n++) if (desired[n]) writeOutput(n, true);
}
void readMeter() {
  volts = pzem.voltage(); amps = pzem.current(); watts = pzem.power();
  energy = pzem.energy(); hz = pzem.frequency(); pf = pzem.pf();
  sensorValid = isfinite(volts) && isfinite(amps) && isfinite(watts) &&
                isfinite(energy) && isfinite(hz) && isfinite(pf) &&
                volts > 0 && amps >= 0 && watts >= 0;
  if (sensorValid) {
    lastGoodSample = millis();
    // Hold all outputs off until a new operator command clears the hold.
    // This deliberate simplification is not a circuit breaker or protection.
    if (watts > budget && (output[0] || output[1])) measuredHold = true;
  }
  allocate();
}
void publishTelemetry() {
  if (!mqtt.connected()) return;
  JsonDocument doc;
  doc["budget"] = budget;
  if (sensorValid) {
    doc["w"] = watts; doc["v"] = volts; doc["i"] = amps;
    doc["pf"] = pf; doc["hz"] = hz; doc["kwh"] = energy;
    doc["va"] = volts * amps;
  } else {
    for (const char* key : {"w", "v", "i", "pf", "hz", "kwh", "va"}) doc[key] = nullptr;
  }
  doc["l1"] = output[0]; doc["l2"] = output[1];
  doc["r1"] = requested[0]; doc["r2"] = requested[1];
  doc["e1"] = ESTIMATED_WATTS[0]; doc["e2"] = ESTIMATED_WATTS[1];
  doc["status"] = !sensorValid ? "PZEM unavailable; outputs held off" :
                  measuredHold ? "Measured power hold; inspect rig and send a new command" :
                  "Live PZEM telemetry";
  char payload[640];
  const size_t length = serializeJson(doc, payload, sizeof(payload));
  if (length < sizeof(payload)) mqtt.publish(telemetryTopic.c_str(), payload, false);
}
void onMessage(char* topic, byte* payload, unsigned int length) {
  // Strict integer parsing: refuse empty, signed, fractional or extra characters.
  if (length == 0 || length > 3) return;
  unsigned int value = 0;
  for (unsigned int k = 0; k < length; k++) {
    if (payload[k] < '0' || payload[k] > '9') return;
    value = value * 10 + payload[k] - '0';
  }
  const String name(topic);
  if (name == controlPrefix + "budget" && value <= 300) budget = value;
  else if (name == controlPrefix + "load1" && value <= 1) requested[0] = value == 1;
  else if (name == controlPrefix + "load2" && value <= 1) requested[1] = value == 1;
  else return;
  measuredHold = false;
  allocate(); publishTelemetry();
}
void maintainNetwork() {
  const uint32_t now = millis();
  if (WiFi.status() != WL_CONNECTED) {
    allOff();
    if (mqtt.connected()) mqtt.disconnect();
    if (now - lastWifiTry >= RETRY_INTERVAL_MS) { lastWifiTry = now; WiFi.reconnect(); }
    return;
  }
  // Certificate validation needs a plausible clock. Never call setInsecure().
  if (time(nullptr) < 1700000000) { allOff(); return; }
  if (!mqtt.connected()) {
    allOff();
    if (now - lastMqttTry < RETRY_INTERVAL_MS) return;
    lastMqttTry = now;
    if (mqtt.connect(clientId.c_str(), MQTT_USERNAME, MQTT_PASSWORD,
                     statusTopic.c_str(), 1, true, "offline")) {
      // Retained controls are not used by this app. Clear old retained control
      // messages in the broker before commissioning the device.
      requested[0] = requested[1] = false;
      mqtt.subscribe((controlPrefix + "+").c_str(), 0);
      mqtt.publish(statusTopic.c_str(), "online", true);
    }
  }
}
void setup() {
  Serial.begin(115200);
  for (uint8_t n = 0; n < 2; n++) {
    digitalWrite(RELAY_PINS[n], RELAY_OFF);
    pinMode(RELAY_PINS[n], OUTPUT);
  }
  telemetryTopic = String(TOPIC_PREFIX) + "telemetry";
  statusTopic = String(TOPIC_PREFIX) + "status";
  controlPrefix = String(TOPIC_PREFIX) + "control/";
  clientId = "ep-esp32-" + String((uint32_t)ESP.getEfuseMac(), HEX);
  if (!configured()) { Serial.println("Fill secrets.h placeholders before using the device. Outputs remain OFF."); return; }
  tls.setCACert(ROOT_CA);
  tls.setHandshakeTimeout(5);
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
  mqtt.setCallback(onMessage);
  mqtt.setBufferSize(1024);
  mqtt.setSocketTimeout(3);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  configTime(0, 0, "pool.ntp.org", "time.nist.gov");
}
void loop() {
  if (!configured()) { allOff(); delay(50); return; }
  maintainNetwork();
  mqtt.loop();
  if (millis() - lastSample >= SENSOR_INTERVAL_MS) {
    lastSample = millis(); readMeter(); publishTelemetry();
  }
  allocate();
  delay(5);
}
