#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include "PubSubClient.h"

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "broker.emqx.io";
int port = 1883;
String stMac;
char mac[50];
char clientId[50];

WiFiClient espClient;
PubSubClient client(espClient);

LiquidCrystal_I2C lcd(0x27,16,2);

void setup()
{
  Wire.begin(23, 22);
  Serial.begin(9600);

  wifiConnect();
  stMac = WiFi.macAddress();
  stMac.replace(":", "_");

  client.setServer(mqttServer, port);
  client.setCallback(callback);

  lcd.init();
  lcd.backlight();
}

void wifiConnect() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
}

void mqttReconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    long r = random(1000);
    sprintf(clientId, "clientId-%ld", r);
    if (client.connect(clientId)) {
      Serial.print(clientId);
      Serial.println(" connected");
      // client.subscribe("topicName/led");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String stMessage;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    stMessage += (char)message[i];
  }
  Serial.println();

  if (String(topic) == "topicName/led") {
    Serial.print("Changing output to ");
    if(stMessage == "on"){
      Serial.println("on");
    }
    else if(stMessage == "off"){
      Serial.println("off");
    }
  }
}

void loop()
{
  
  if (!client.connected()) {
    mqttReconnect();
  }

  int16_t i = analogRead(34);
  String msg = i < 2165 ? "DRY" : i > 3135 ? "WET" : "OK";
  lcd.clear();
  lcd.print("Soil: ");
  lcd.print(msg);
  delay(500); 
  
  // Send soil moisture data to MQTT broker
  client.publish("soilData/humiditylevel", msg.c_str());
  client.publish("soilData/humidity", String(i).c_str());
  
  client.loop();
}
Soil SensorBreakout