from time import sleep
from machine import SoftI2C, Pin, ADC
from i2c_lcd import I2cLcd
from simple import MQTTClient
import network
import ujson

# Setup I2C and LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)

# Turbidity sensor using potentiometer 
turbidity_pin = 26
turbidity_adc = ADC(Pin(turbidity_pin))

# pH sensor using potentiometer 
ph_pin = 27
ph_adc = ADC(Pin(ph_pin))

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

# MQTT Server Parameters
MQTT_CLIENT_ID = ""
MQTT_BROKER = "test.mosquitto.org"
MQTT_PORT = 1883
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "water_quality"

print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
while not sta_if.isconnected():
    print(".", end="")
    sleep(0.1)
print(" Connected!")

# Connecting to the MQTT Broker server
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected")

# Main Function
water_quality = ""
while True: 
    # Read turbidity level
    turbidity_value = turbidity_adc.read_u16()
    print("Turbidity Level:", turbidity_value)
    
    # Read pH level
    ph_value = ph_adc.read_u16()
    print("pH Level:", ph_value)
    
    # Create JSON message with both readings
    message = ujson.dumps({
        "Turbidity level": turbidity_value,
        "pH level": ph_value
    })
    
    # Publish message if there is a change
    if message != water_quality:
        print("Updated")
        print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
        client.publish(MQTT_TOPIC, message)
        water_quality = message
    else: 
        print("No change")
    
    # Display on LCD
    lcd.clear()
    lcd.move_to(0, 0)
    lcd.putstr(f"Turbidity: {turbidity_value}")
    if turbidity_value > 50000:
        print("Water is dirty")
        lcd.move_to(0, 1)
        lcd.putstr("Water is dirty")
    else:
        print("Water is pure")
        lcd.move_to(0, 1)
        lcd.putstr("Water is pure")
    
    sleep(5)
    
    lcd.clear()
    lcd.move_to(0, 0)
    lcd.putstr(f"pH Value: {ph_value}")
    if ph_value > 30000:
        print("pH acceptable")
        lcd.move_to(0, 1)
        lcd.putstr("pH acceptable")
    else:
        print("pH unacceptable")
        lcd.move_to(0, 1)
        lcd.putstr("pH unacceptable")
    
    sleep(8)  # Wait for a few seconds before the next loop









    
$abcdeabcde151015202530fghijfghij