import usocket, appglue, badge, wifi, utime, uos, ugfx

badge.init()
badge.leds_init()
badge.leds_enable()
ugfx.init()
ugfx.input_init()



def btn_start(pressed):
    if (pressed==False):
        return
    appglue.home()

def draw_msg(title, desc):
    ugfx.clear(ugfx.WHITE)
    ugfx.string(0, 0, title, "PermanentMarker22", ugfx.BLACK)
    ugfx.string(0, 25, desc, "Roboto_Regular12", ugfx.BLACK)
    ugfx.set_lut(ugfx.LUT_FASTER)
    ugfx.flush()

ugfx.input_attach(ugfx.BTN_START, btn_start)

def randomint():
  ranbytes = uos.urandom(2)
  return ranbytes[0] >> 8 | ranbytes[1]

prev_pos = 10
while True:
  wifi.init()
  
  ssid = badge.nvs_get_str('badge', 'wifi.ssid', 'SHA2017-insecure')
  draw_msg("Loading...", "WiFi: connecting to '"+ssid+"'...")
  timeout = 100
  while not wifi.sta_if.isconnected():
    utime.sleep(0.1)
    timeout = timeout - 1
    if (timeout<1):
        draw_msg("Error", "Timeout while connecting!")
        utime.sleep(5)
        appglue.home()
        break
    else:
        pass

  sock = usocket.socket()
  addr = usocket.getaddrinfo("151.216.93.210", 2342)
  try:
    sock.connect(addr[0][-1])
  except:
    sock.close()
    break
    
  font = "Roboto_Regular12"
  ugfx.clear(ugfx.WHITE)
  ugfx.string(5,50,"Find the LEDs with colour #FFAA5E",font,ugfx.BLACK)
  ugfx.string(40,110,"[Start: exit]",font,ugfx.BLACK)
  ugfx.flush()

  while True:
    ledinfo = [0] * 24;
    pos = randomint() % 5
    if pos >= prev_pos:
  	  pos = pos + 1
    prev_pos = pos
    pos = pos * 4
    ledinfo[pos+1] = 0xFF
    ledinfo[pos] = 0xAA
    ledinfo[pos+2] = 0x5E
    badge.leds_send_data(bytes(ledinfo), 24)
    for j in range(0, 1000):
      x = randomint() % 480
      y = randomint() % 264
      try:
        sock.send("PX {:d} {:d} FFAA5E\n".format(x,y).encode('utf-8'))
      except:
        draw_msg("Error", "Connection loss")
        utime.sleep(1)
        break
  sock.close()

badge.leds_disable()
appglue.home()