import display
import utime
import machine
import neopixel
import buttons


leds = 12
colors = [[0, 25, 25],[25,0,25],[8,25,8]]
no_colors = [[0, 0, 0],[0,0,0],[0,0,0]]
use = colors

def leds_on(pressed):
  global use
  use = colors

def leds_off(pressed):
  global use
  use = no_colors

def print_text(text):
  	display.drawFill(0x000000)
	display.drawText(0,0,text)
	display.flush()
	utime.sleep(0.1)

def print_nyan():
  now = utime.time()
  frac = int((now-int(now))*10)
  if frac in [1,4,7]:
	all_leds(use[0])
  elif frac in [2,5,8]:
	all_leds(use[1])
  else:
	all_leds(use[2])
  utime.sleep(0.02)

def all_leds(colors):
  temp = [colors[0], colors[1], colors[2]] * 12
  neopixel.send(bytes(temp))

buttons.attach(buttons.BTN_UP, leds_on)
buttons.attach(buttons.BTN_DOWN, leds_off)

import socket
import struct
import wifi
wifi.connect()
print_text('Connect to WiFi')
while True:
  if wifi.status():
	break
  utime.sleep(0.1)
print_text('WiFi status: %s' % wifi.status())
# Get NTP time
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1b
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
res = s.sendto(NTP_QUERY, ('95.216.138.141', 123))
r_msg = s.recv(48)
s.close()
# ntp epoch
#val = struct.unpack("!I", r_msg[40:44])[0]
# Get ntp time sec.frac
sec, frac = struct.unpack('!12I', r_msg)[10:12]
# Wait until fraction of seconds are gone
#time.sleep(1-float('0.%s' % frac))
# Set local time by seconds
tm = utime.localtime(sec)
machine.RTC().init((tm[0], tm[1], tm[2], tm[6], tm[3], tm[4], tm[5], frac))
# disconnect wifi
wifi.disconnect()
print_text('NTP time set: %s:%s' % (tm[3], tm[4]))
utime.sleep(0.5)
print_text('Start sync leds soon... By Seppos')
while True:
  if utime.mktime(machine.RTC().now()) % 2 == 0:
	break
utime.sleep(1)
while True:
  if utime.mktime(machine.RTC().now()) % 2 == 0:
	break
while True:
  print_nyan()