###########################################################################################################
###########################################################################################################
#SCHEDULED PLANT WATERING by Leon Thorn
###########################################################################################################
import network
import socket
import time
import struct

from machine import ADC, Pin

NTP_DELTA = 2208988800
host = "pool.ntp.org"

led = Pin("LED", Pin.OUT)


############################################################################################################
#SETTINGS
############################################################################################################
ssid = 'ssid'
password = 'password'


scheduled = 06 #SELECT TIME FOR ACTIVATION
scheduled2 = 18 #YOU CAN ADD MORE SCHEDULES IF YOU DESIRE
duration = 5 #HOW LONG TO PUMP WATER
time_val = 5 #SECOND [5], MINUTE [4], HOUR [3].
pump_pin = Pin(16, Pin.OUT)#Select pin to activate.

############################################################################################################
#SETTINGS
############################################################################################################


############################################################################################################
#WLAN CODE
############################################################################################################
def set_time():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1B
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.settimeout(1)
        res = s.sendto(NTP_QUERY, addr)
        msg = s.recv(48)
    finally:
        s.close()
    val = struct.unpack("!I", msg[40:44])[0]
    t = val - NTP_DELTA    
    tm = time.gmtime(t)
    machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

max_wait = 10
while max_wait > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    max_wait -= 1
    print('waiting for connection...')
    time.sleep(1)

if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('connected')
    status = wlan.ifconfig()
    print( 'ip = ' + status[0] )


set_time()#This was missing.
pump_pin.value(0)#Set relay to "off state"
############################################################################################################
#WLAN CODE
############################################################################################################


############################################################################################################
#PUMP FUNCTION
############################################################################################################
def pump():    
    led.on()#TURN ON
    pump_pin.value(1)#Turn Pump Off
    time.sleep(duration)#Do Nothing for duration...
    pump_pin.value(0)#Turn Pump On
    led.off()#TURN OFF
############################################################################################################
#PUMP FUNCTION
############################################################################################################
    
    
############################################################################################################
#TIME CHECK
############################################################################################################
while True:
    t = time.localtime()
    hour = t[3] + 1 #I did this as an easy way to get the correct time on the device. Might have to be manually changed in event of a time change...Im not sure.
    time.sleep(1)
    #print(hour, ":", t[4], ":", t[5])
    if hour == scheduled and t[4] == 0 and t[5] == 0: # or hour == scheduled2 and t[4] == 0 and t[5] == 0:#If the time meets the scheduled value...
        pump()#Activate Pump.
    else:pump_pin.value(0)#Set relay to "off state"
        
############################################################################################################
#TIME CHECK
############################################################################################################



###########################################################################################################
#SCHEDULED PLANT WATERING
###########################################################################################################    
###########################################################################################################        
        
        

    

