from doctor_color_grove_i2c_color_sensor_tcs34725 import tcs34725
from machine import I2C, Pin
import ugfx, time,math,badge,appglue

ugfx.init()
ugfx.clear(ugfx.WHITE)




ugfx.string(0,25,"Initializing device...","PermanentMarker22",ugfx.BLACK)
ugfx.flush()



ugfx.string(0,50,"Done!","PermanentMarker22",ugfx.BLACK)

ugfx.flush()


ugfx.input_init()
ugfx.input_attach(ugfx.BTN_B, lambda pressed: appglue.home())

badge.leds_init()
badge.leds_enable()
time.sleep(1)
i2c = I2C(  sda=Pin(26), scl=Pin(27), freq=200000 )
sensor = tcs34725.TCS34725(i2c)

time.sleep(3)


while True:

  values = sensor.getRawValues()
  ugfx.clear(ugfx.WHITE)
  ugfx.string(0,0,"Red: " + str(values[0]),"PermanentMarker22",ugfx.BLACK)
  ugfx.string(0,25,"Green: " + str(values[1]),"PermanentMarker22",ugfx.BLACK)
  ugfx.string(0,50,"Blue: " + str(values[2]),"PermanentMarker22",ugfx.BLACK)
  ugfx.string(0,75,"Clear: " + str(values[3]),"PermanentMarker22",ugfx.BLACK)
  ugfx.flush()  

  values[0] = math.sqrt(values[0])
  values[1] = math.sqrt(values[1])
  values[2] = math.sqrt(values[2])
  values[3] = math.sqrt(values[3])

  lowestValue = min(values[0:3])
  values[0] = values[0]-lowestValue
  values[1] = values[1]-lowestValue
  values[2] = values[2]-lowestValue

  highestValue = max(values[0:3]) if max(values[0:3]) >0 else 0.1
  leds= bytearray(24)

  #red indicator LED
  leds[1]=round(values[0]/highestValue*255.0)

  #green indicator LED
  leds[4]=round(values[1]/highestValue*255.0)

  #blue indicator LED
  leds[10]=round(values[2]/highestValue*255.0)

  #clear indicator LED
  leds[12]=round(values[3])
  leds[13]=round(values[3])
  leds[14]=round(values[3])

  #color indicator LED
  leds[17]=round(values[0])
  leds[16]=round(values[1])
  leds[18]=round(values[2])

  badge.leds_send_data(bytes(leds), 24)

  time.sleep(0.1)