from machine import I2C, Pin, Timer
from esp8266_i2c_lcd import I2cLcd
import network, ntptime, utime, gc

def lcd_show(text, clear=True):
    if clear:
        lcd.clear()
    lcd.move_to(0, 0)
    lcd.putstr(text)

def time_update(timer):
    while True:
        try:
            ntptime.settime()
            break
        except:
            utime.sleep(10)

def time_display(timer):
    led.value(not wifi.isconnected())
    dt = list(utime.localtime(utime.time() + tz_hour * 3600))
    dt[6] = wday[dt[6]]
    output = ' {0:4d}-{1:02d}-{2:02d} {6}\n   {3:02d}:{4:02d}:{5:02d}'
    lcd_show(output.format(*dt), clear=False)

gc.enable()
tz_hour = 8
DEFAULT_I2C_ADDR = 0x27
hw_i2c0 = I2C(1,freq=200000)
lcd = I2cLcd(hw_i2c0,DEFAULT_I2C_ADDR,2,16)
led = Pin(2,Pin.OUT,value=1)
wday = ('Mon','Tue','Wed','Thu','Fri','Sat','Sun')

lcd_show('connecting to\n Wifi...')
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect('Wokwi-GUEST','')
while not wifi.isconnected():
    pass
lcd_show('Wifi was connected')


time_update(None)
timer_ntp,timer_display = Timer(-1),Timer(-1)
timer_ntp.init(mode=Timer.PERIODIC,period=900000,callback=time_update)
timer_display.init(mode=Timer.PERIODIC,period=100, callback=time_display)