from hcsr04 import HCSR04 
import time
from time import sleep
from pump import PUMP
from dhtc22 import DHT22
from cistern import CISTERN
import dht
from machine import Pin, PWM,
import ujson
import network
from ldr import LDR
from umqtt.simple import MQTTClient

# MQTT Server Parameters
MQTT_CLIENT_ID = "gruppo09"
MQTT_BROKER    = "test.mosquitto.org"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_DHT22     = "SmartGreenhouse/dht22"
MQTT_PUMP = b'SmartGreenhouse/pump'
MQTT_LED_ZONE1 = b'SmartGreenhouse/ledZone1'
MQTT_PHOTORESISTOR = "SmartGreenhous/luxValue"

CRITICAL_CISTERN_LEVEL = 10
HUMIDITY_CRITICAL_LEVEL = 10
ACTIVE_PUMP = True
BLOCK_IRRIGATION_FOR_CRITICAL_CISTERN_LEVEL = False
ACTIVE_LED_ZONE1 = False

cistern = CISTERN(26,25, 30)
pump = PUMP(27)
sensor_umidity_temperature = DHT22(4)
photo_resistor = LDR(35, 0, 1023)
led_zone_1 = PWM(Pin(13, Pin.OUT), freq=50)
led_zone_1.duty(0)

# IMPORTED IN THE BOOT FILE
try:
    print("Connecting to WiFi", end="")
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('Wokwi-GUEST', '')
    while not sta_if.isconnected():
        print(".", end="")
        time.sleep(0.1)
    print(" Connected!")
except OSError as ex:
    print("Failure connecting to WiFi!!")

# DEFINE THE CALLBACK PROCEDURE FOR THE RECIVED MSG FROM THE BROKER

def subCallback(topic, msg):
    global ACTIVE_PUMP 
    global ACTIVE_LED_ZONE1
    if topic == MQTT_PUMP:
        if msg == b'ON_PUMP':
            ACTIVE_PUMP = True
        elif msg == b'OFF_PUMP':
            ACTIVE_PUMP = False
    if topic == MQTT_LED_ZONE1:
        if msg == b'ON_LED1':
            ACTIVE_LED_ZONE1 = True
        elif msg == b'OFF_LED1':
            ACTIVE_LED_ZONE1 = False


# PROCEDURE OF CONNECTION TO THE MQTT SERVER
try:
    print("Connecting to MQTT server... ", end="")
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
    client.set_callback(subCallback)
    client.connect()
    client.subscribe(MQTT_PUMP)
    client.subscribe(MQTT_LED_ZONE1)
    print("Connected")
except OSError as ex:
    print("Failure connecting to MQTT server!!")

def pump_cicle():
    print(" Pump activated")
    pump.pump_cicle(1)
    sleep(2)

while True:
    try:
        print("Reading sensors values...")
        dht22_msg = sensor_umidity_temperature.get_ujson_mesure()
        ldr_msg = photo_resistor.ujson_value()
        ldr_value = photo_resistor.read()
        temp_value = sensor_umidity_temperature.get_last_temperature()
        humidity_value = sensor_umidity_temperature.get_last_humidity()
    except OSError as e:
        print("Error while reading the sensors values:", e)
    
    print(dht22_msg)
    print(ldr_msg)

    try:
        print("Checking messages from the broker...")
        client.check_msg()
    except OSError as e:
        print("Checking masseges from the broker fail: ", e)
    
    try:
        print("publication of the sensors data...")
        client.publish(MQTT_DHT22, dht22_msg)
        client.publish(MQTT_PHOTORESISTOR, ldr_msg)
    except OSError as e:
        print("Error during the sensors data pubblication: ", e)


    if cistern.level() < CRITICAL_CISTERN_LEVEL:
        print("Livello di cisterna critico, ricarica il serbatoio per proseguire l'irrigazione")
        BLOCK_IRRIGATION_FOR_CRITICAL_CISTERN_LEVEL = True
    
    if cistern.level() > CRITICAL_CISTERN_LEVEL and BLOCK_IRRIGATION_FOR_CRITICAL_CISTERN_LEVEL:
        print("Sistema di irrigazione ripristinato")
        BLOCK_IRRIGATION_FOR_CRITICAL_CISTERN_LEVEL = False
    
    if sensor_umidity_temperature.read_humidity() < HUMIDITY_CRITICAL_LEVEL and ACTIVE_PUMP and not BLOCK_IRRIGATION_FOR_CRITICAL_CISTERN_LEVEL:
        print("Starting pump...", end="")
        pump_cicle()
        #print("Livello cisterna: ", cistern.level())
    
    time.sleep(1)





$abcdeabcde151015202530354045505560fghijfghij