#include <Arduino.h>
// ------------------------------------------------------------
// Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
// PSUT IoT Engineering Learning Platform
// ------------------------------------------------------------
// ---- Example 1: ESP32 greenhouse node (Wokwi) → MQTT broker
// Every 10 s: read the DHT22 and the soil probe (a potentiometer in Wokwi),
// build one JSON message and publish it to YOUR topic on the local broker.
// Libraries (Wokwi Library Manager): PubSubClient, DHT sensor library for ESPx

#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"

// ---- Settings: use profile values; never use a university ID on a public broker
const char* WIFI_SSID   = "Wokwi-GUEST";          // Wokwi's simulated Wi-Fi, no password
const char* WIFI_PASS   = "";
const char* BROKER      = "host.wokwi.internal";     // local WSL broker via Wokwi gateway
const int   BROKER_PORT = 1884;
const char* STUDENT_ID  = "lab-local";               // session label; not authentication
const char* NODE        = "esp32-01";               // this device's name

// ---- Pins
const int DHT_PIN  = 15;                            // DHT22 data
const int SOIL_PIN = 34;                            // potentiometer wiper = soil probe (ADC1)
const int LED_PIN  = 2;                             // blinks on every publish

DHTesp dht;
WiFiClient net;
PubSubClient mqtt(net);
char topic[96];
unsigned long lastSend = 0;

// ---- Connect (or reconnect) to the broker with a unique client ID
void connectMqtt() {
  while (!mqtt.connected()) {
    String id = String("psut-") + STUDENT_ID + "-" + NODE + "-" + String((uint32_t)esp_random(), HEX);
    Serial.print("MQTT connecting as "); Serial.println(id);
    if (mqtt.connect(id.c_str())) {
      Serial.println("MQTT connected");
    } else {
      Serial.print("failed, state="); Serial.println(mqtt.state());
      delay(2000);                                  // wait, then try again
    }
  }
}

void setup() {
  Serial.begin(115200);
  if (strcmp(BROKER, "broker.hivemq.com") == 0) {
    String session = STUDENT_ID;
    bool valid = session.startsWith("demo-") && session.length() == 21;
    for (unsigned int i=5; i<session.length(); i++) {
      char c=session[i]; valid = valid && ((c>='0' && c<='9') || (c>='a' && c<='f'));
    }
    if (!valid) { Serial.println("Generate a HiveMQ demo session first"); while(true) delay(1000); }
  }
  pinMode(LED_PIN, OUTPUT);
  dht.setup(DHT_PIN, DHTesp::DHT22);
  snprintf(topic, sizeof(topic), "psut/iot/%s/greenhouse/%s/telemetry", STUDENT_ID, NODE);

  WiFi.begin(WIFI_SSID, WIFI_PASS);                 // ---- Wi-Fi first
  Serial.print("Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); }
  Serial.println(" connected");

  mqtt.setServer(BROKER, BROKER_PORT);              // ---- then the broker
  connectMqtt();
  Serial.print("Publishing to "); Serial.println(topic);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) { WiFi.reconnect(); delay(1000); return; }
  if (!mqtt.connected()) connectMqtt();
  mqtt.loop();                                      // keep the MQTT connection alive

  if (millis() - lastSend >= 10000) {               // ---- one reading every 10 s
    lastSend = millis();
    TempAndHumidity th = dht.getTempAndHumidity();
    if (isnan(th.temperature) || isnan(th.humidity)) { Serial.println("DHT22 read failed"); return; }
    float soil = analogRead(SOIL_PIN) * 100.0 / 4095.0;   // 0–4095 → 0–100 %

    // ---- JSON payload: the keys become InfluxDB fields through Telegraf
    char payload[128];
    snprintf(payload, sizeof(payload),
             "{\"source\":\"wokwi\",\"temperature\":%.1f,\"humidity\":%.1f,\"soil_moisture\":%.1f}",
             th.temperature, th.humidity, soil);
    bool ok = mqtt.publish(topic, payload);
    Serial.print(ok ? "sent " : "NOT sent "); Serial.println(payload);
    digitalWrite(LED_PIN, HIGH); delay(50); digitalWrite(LED_PIN, LOW);
  }
}
