import network
import socket
from time import sleep, time

from machine import Pin, SPI
import vga1_8x8 as font1
import vga1_16x16 as font2
import st7789

#Konfiguration/Initialisierung Display
spi = SPI(2, baudrate=20000000, polarity=1, sck=Pin(18), mosi=Pin(19))
display = st7789.ST7789(spi, 135, 240,  reset=Pin(23, Pin.OUT), cs=Pin(5, Pin.OUT), dc=Pin(16, Pin.OUT), backlight=Pin(4, Pin.OUT), rotation=3)
# Landscape
display.init()
display.fill(0)  # loeschen; Bildschirm schwarz
display.text(font1,'WLAN-Time-Client',2,10,st7789.YELLOW)
display.text(font1,'Receives time from FU Berlin',2,30,st7789.YELLOW)
display.text(font1,'Refreshs after ca. 20 seconds',2,40,st7789.YELLOW)

# Konfiguration
station = network.WLAN(network.STA_IF) # network interface configuration
station.active(True)
station.connect('mipa_devolo', 'asdfghjkl1234')
# station.connect('mipamipa', 'Asdfghjkl1234')
# Nach Änderung des AP ist (noch) ein Hard-Reset erforderlich

time0 = time()
while (station.isconnected() == False) and (time() - time0 < 5):  
  pass

# Verbinden mit Time-Server
if station.isconnected():
  addr = ('time.fu-berlin.de', 13)
  while True:
    try:  
      client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      client.connect(addr)
      # keine Daten senden (nicht erforderlich)
      # Daten empfangen und auf Display ausgeben
      data = client.recv(1024) # max. Anz. der Zeichen
      data_str = str(data,'UTF-8') # ggf. noch nl und cr beseitigen!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      day_str = data_str[0:-15]
      time_str = data_str[-14:-6]
      # display.fill_rect(0,75,210,20,st7789.color565(255,0,0))
      display.text(font2,day_str,2,80,st7789.GREEN)
      display.text(font2,time_str,2,100,st7789.GREEN)
      # client schließen
      client.close()
      sleep(20)
    except:
      print('Disconnected') # nur zum Testen
      break
      
# keine Verbindung:
station.active(False)
display.fill_rect(0,77,220,40,st7789.color565(255,0,0))
display.text(font2,'Disconnected!',5,90,st7789.BLUE)






