import time
import network
from umqtt.simple import MQTTClient
from machine import ADC, Pin
import dht

# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# HiveMQ MQTT broker information
HIVEMQ_MQTT_URL = "mqtt-dashboard.com"
#HIVEMQ_MQTT_URL = "95d8890ce7a14caaa2326295a68ec31f.s1.eu.hivemq.cloud"
HIVEMQ_MQTT_PORT = 8883
HIVEMQ_MQTT_USER = "amirsaahal"  # Your MQTT username
HIVEMQ_MQTT_PASSWORD = ""  # Your MQTT password
HIVEMQ_CHANNEL = "Project"  # Your desired MQTT topic/channel

# Initialize ADC (Analog to Digital Converter)
adc_soil_moisture = ADC(Pin(34))
adc_water_level = ADC(Pin(35))

# Initialize DHT22 sensor
dht_pin = 23
dht_sensor = dht.DHT22(Pin(dht_pin))

# Connect to WiFi
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print("Connecting to WiFi...")
        wlan.connect(WIFI_SSID, WIFI_PASSWORD)
        while not wlan.isconnected():
            pass
    print("WiFi connected:", wlan.ifconfig())

# Function to read soil moisture
def read_soil_moisture():
    sensor_value = adc_soil_moisture.read()
    moisture_percentage = (sensor_value / 4095) * 100
    return moisture_percentage

# Function to read water level
def read_water_level():
    sensor_value = adc_water_level.read()
    # Assuming a linear relationship between sensor value and water level
    # Adjust the formula based on your sensor's characteristics
    water_level_percentage = (sensor_value / 4095) * 100
    return water_level_percentage

# Function to read temperature and humidity
def read_temperature_humidity():
    dht_sensor.measure()
    temperature = dht_sensor.temperature()
    humidity = dht_sensor.humidity()
    return temperature, humidity

def main():
    
    while True:
        try:
            connect_wifi()

            # Connect to HiveMQ MQTT broker
            mqtt_client = MQTTClient(
                client_id="esp32", 
                server=HIVEMQ_MQTT_URL, 
                port=HIVEMQ_MQTT_PORT, 
                user=HIVEMQ_MQTT_USER, 
                password=HIVEMQ_MQTT_PASSWORD,
                ssl=True  # Enable SSL/TLS for secure connection
            )
            mqtt_client.connect()
            print("Connected to MQTT broker")

            while True:
                try:
                    # Read soil moisture
                    soil_moisture = read_soil_moisture()
                    print("Soil Moisture: {:.2f}%".format(soil_moisture))
                    mqtt_client.publish(HIVEMQ_CHANNEL + "/SoilMoisture", str(soil_moisture))

                    # Read water level
                    water_level = read_water_level()
                    print("Water Level: {:.2f}%".format(water_level))
                    mqtt_client.publish(HIVEMQ_CHANNEL + "/WaterLevel", str(water_level))

                    # Read temperature and humidity
                    temperature, humidity = read_temperature_humidity()
                    print("Temperature: {:.2f}°C, Humidity: {:.2f}%".format(temperature, humidity))
                    mqtt_client.publish(HIVEMQ_CHANNEL + "/Temperature", str(temperature))
                    mqtt_client.publish(HIVEMQ_CHANNEL + "/Humidity", str(humidity))

                    time.sleep(15)  # Adjust the delay as needed
                except Exception as e:
                    print("Error reading sensors or publishing: ", e)

        except Exception as e:
            print("Error connecting to WiFi or MQTT: ", e)
            time.sleep(5)  # Wait before retrying

if __name__ == "__main__":
    main()