import esp, badge, ugfx, deepsleep, machine

badge.init()
ugfx.init()
ugfx.input_init()
badge.leds_init()
badge.leds_enable()

max = 6

def max_up(pressed):
  global max
  if pressed:
      max += 10
  print('New max: ' + str(max))
def max_down(pressed):
  global max
  if pressed:
      max -= 10
  print('New max: ' + str(max))

def max_left(pressed):
  global max
  if pressed:
      max -= 1
  print('New max: ' + str(max))
def max_right(pressed):
  global max
  if pressed:
      max += 1
  print('New max: ' + str(max))

def home(pressed):
  if pressed:
    deepsleep.reboot()

def get_sens():
  hall = esp.hall_sens_read()
  if hall > 32768:
    hall = hall - 65536
  return hall
    
def leds(t):
  hall = get_sens()
  print('Hall value: ' + str(hall))
    
  global max
  result = b""
  
  led_max = max / 6
  if hall > 0:
    on = hall // led_max
    for i in range(on):
      result += bytes([0, 255, 0, 0])
    result += bytes([0, int((hall%led_max)/led_max), 0, 0])
    for i in range(5 - on):
      result += bytes([0, 0, 0, 0])
  else:
    hall = -hall
    on = hall // led_max
    for i in range(on):
      result += bytes([0, 0, 255, 0])
    result += bytes([0, 0, int((hall%led_max)/led_max), 0])
    for i in range(5 - on):
      result += bytes([0, 0, 0, 0])
  
  badge.leds_send_data(result)
  
def screen(t):
  global max
  
  ugfx.clear(ugfx.WHITE)
  ugfx.string(75, 30, "Magnet reading", "Roboto_Regular22", ugfx.BLACK)
  ugfx.string(100, 60, str(get_sens()), "PermanentMarker36", ugfx.BLACK)
  ugfx.string(4,0, "max= " + str(max), "Roboto_BlackItalic12", ugfx.BLACK)
  ugfx.flush()


ugfx.input_attach(ugfx.BTN_START, home)
ugfx.input_attach(ugfx.JOY_UP, max_up)
ugfx.input_attach(ugfx.JOY_DOWN, max_down)
ugfx.input_attach(ugfx.JOY_LEFT, max_left)
ugfx.input_attach(ugfx.JOY_RIGHT, max_right)

ugfx.clear(ugfx.WHITE)
ugfx.flush(ugfx.LUT_FULL)
ugfx.set_lut(ugfx.LUT_NORMAL)

led_timer = machine.Timer(0)
led_timer.init(period=100, mode=machine.Timer.PERIODIC, callback=leds)

screen_timer = machine.Timer(1)
screen_timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=screen)