import machine, badge, ugfx, deepsleep

badge.init()
ugfx.init()
ugfx.input_init()
badge.leds_init()
badge.leds_enable()

ecg = machine.ADC(machine.Pin(33))
ecg.atten(ecg.ATTN_11DB)
ecg.width(ecg.WIDTH_12BIT)
badge.power_sdcard_enable()

data = [0] * 340
i = 0

rr = [1000] * 10
j = 0
last = 0
ovflw = 0

brightness = 30

def up(pressed):
  global brightness
  if pressed:
      brightness += 1
  print('New max: ' + str(brightness))
def down(pressed):
  global brightness
  if pressed:
      brightness -= 1
  print('New max: ' + str(brightness))
def home(pressed):
  if pressed:
    deepsleep.reboot()

def draw_ecg():
  global data, rr
  
  hr = int(60 / (sum(rr) / 800 ))
  ugfx.fill_rounded_box(16,38,75,36,1,ugfx.WHITE)
  ugfx.string(28, 38, str(hr), "PermanentMarker36", ugfx.BLACK)
  
  ugfx.line(126, 40, 126, 127, ugfx.BLACK)
  ugfx.line(126, 127, 296, 127, ugfx.BLACK)

  ugfx.flush()
  ugfx.fill_rounded_box(126, 40, 170, 88, 1, ugfx.WHITE)
  
def ecg_data(t):
  global i, j, ovflw, last, brightness
  
  s = ecg.read()
  data[i] = s
  
  if i == 339:
    i = 0
    ovflw = 1
    draw_ecg()
  else:
    i = i + 1
  
  hi = 3500
  lo = 1500
  t = 2500 - lo
  
  if s < lo:
    p = 0
    y = 1
  elif s > hi:
    p = 1
    y = 88
  else:
    s = s - lo
    hilo = hi - lo
    p = s / hilo
    y = int(p * 88)
    
  if s > t:
    if ovflw:
      fi = i + 340
      ovflw = 0
    else:
      fi = i
      
    if (fi - last) > 20:
      rr[j] = fi - last
      
      if j == 9:
        j = 0
      else:
        j = j + 1
        
      last = i
  
  scaling = 0.18
  on = p // scaling
  result = b""
  for ii in range(on):
    result += bytes([0, brightness, 0, 0])
  result += bytes([0, int((p%scaling)/scaling*brightness), 0, 0])
  for ii in range(5 - on):
    result += bytes([0, 0, 0, 0])
    
  badge.leds_send_data(result)
  
  x = 126 + int(i/2)
  ugfx.line(x, 128 - y, x, 128, ugfx.BLACK)
  

ugfx.input_attach(ugfx.BTN_START, home)
ugfx.input_attach(ugfx.JOY_UP, up)
ugfx.input_attach(ugfx.JOY_DOWN, down)

ugfx.clear(ugfx.WHITE)
ugfx.string(130, 1, "Roosted", "PermanentMarker36", ugfx.BLACK)
badge.eink_png(0, 0, '/lib/ecg/hearth.png')
ugfx.flush(ugfx.LUT_FULL)
ugfx.set_lut(ugfx.LUT_FULL)

t = machine.Timer(-1)
t.init(period=8, mode=machine.Timer.PERIODIC, callback=ecg_data)