import machine, neopixel, uos, buttons, system, time, display, gc, rtc, wifi
import i2c as sysi2c

def read_sensor(cb):
  global num_data
  r = i2c.readfrom(64, 2)
  val = ((r[0] << 6) | (r[1] >> 2)) - 8000
  
  if num_file:
    f.write('{}\n'.format(val))
    num_data = num_data + 1
  else:
	print(val)

  if brightness:
	reverse_flow = val < 0
	if reverse_flow:
	  val = -val

	on = val // per_led
	led_array = []
	for led in range(on):
	  led_array.extend([0, brightness, 0, 0])
	led_array.extend([0, int((val%per_led)/per_led*brightness), 0, 0])
	for led in range((num_leds - 1) - on):
	  led_array.extend([0, 0, 0, 0])

	if reverse_flow:
	  # flip
	  led_array = led_array[::-1]

	err = neopixel.send(bytes(led_array))
  
  
def stop_btn(prsd):
  global run
  if prsd:
	run = 0

def up_btn(prsd):
  global brightness
  if (prsd and brightness < 250):
	print('U')
	print(brightness)
	brightness = brightness + 10
	
def down_btn(prsd):
  global brightness
  if (prsd and brightness > 0):
	print('D')
	print(brightness)
	brightness = brightness - 10
	
def left_btn(prsd):
  global max_light, per_led, num_leds
  if (prsd and max_light > 0):
	print('L')
	max_light = max_light - 10
	per_led = int(max_light * 35 / num_leds)
	
def right_btn(prsd):
  global max_light, per_led, num_leds
  if (prsd and max_light < 250):
	print('R')
	max_light = max_light + 10
	per_led = int(max_light * 35 / num_leds)

def a_btn(prsd):
  global max_light, per_led, brightness, num_leds
  if prsd:
	print('A')
	brightness = 100
	max_light = 200
	per_led = int(max_light * 35 / num_leds)

def b_btn(prsd):
  global brightness
  if prsd:
	print('B')
	brightness = 0


# Init hardware
i2c = machine.I2C(sda=machine.Pin(17), scl=machine.Pin(16), freq=sysi2c.SPEED)
neopixel.enable()
buttons.detach(buttons.BTN_START)
buttons.attach(buttons.BTN_UP, up_btn)
buttons.attach(buttons.BTN_DOWN, down_btn)
buttons.attach(buttons.BTN_LEFT, left_btn)
buttons.attach(buttons.BTN_RIGHT, right_btn)
buttons.attach(buttons.BTN_A, a_btn)
buttons.attach(buttons.BTN_B, b_btn)
display.drawFill(display.WHITE)
display.drawText(20, 0, 'SFM3000 sensor logger', display.BLACK, 'roboto_regular22')
display.drawText(10, 40, 'A/B: start / stop LEDs', display.BLACK, 'roboto_regular12')
display.drawText(10, 55, 'UP/DOWN: brightness', display.BLACK, 'roboto_regular12')
display.drawText(10, 70, 'LEFT/RIGHT: SFM scale', display.BLACK, 'roboto_regular12')
display.drawText(10, 95, 'SFM / 35', display.BLACK, 'roboto_regular18')
display.drawText(10, 115, '100hz signed int ASCII \\n sep', display.BLACK, 'roboto_regular12')
display.drawText(175, 45, 'RECORDING:', display.BLACK, 'roboto_regular18')

# Init sensor
if 64 in (i2c.scan()):
  print('Bingo!')
  i2c.writeto(64, b'\x10\x00')
else:
  print('Boomer')
  system.home()

# config me
max_light = 200 # slm
num_leds = 6 # leds
brightness = 100 # 0-255

per_led = int(max_light * 35 / num_leds)

# Config RTC
if not rtc.isSet():
  print('Connecting to Wi-Fi')
  wifi.connect()
  wifi.wait()
  print('Connected! Getting time')
  rtc.configure()
  time.sleep_ms(2000)
  wifi.stop()
print(rtc.time.localtime())

# Write SD log
try:
  dirname = '/sd/' + time.strftime('%d-%m-%y_%H-%M-%S')
  uos.mkdir(dirname)
  uos.chdir(dirname)
  print(dirname)
  num_data = 1
  num_file = 1
  f = open('{}.txt'.format(num_file), 'w')
  buttons.attach(buttons.BTN_FLASH, stop_btn)
  display.drawText(175, 65, time.strftime(' SD \n %d-%m \n  %H:%M:%S'), display.BLACK, 'roboto_regular18')
except:
  num_data = 0
  num_file = 0
  display.drawText(175, 65, ' Serial', display.BLACK, 'roboto_regular18')


display.flush(display.FLAG_FULL)
time.sleep_ms(1000)

# GO!
run = 1
next_us = time.ticks_add(time.ticks_us(), 10000)
while run:
  t = time.ticks_diff(next_us, time.ticks_us())
  if t <= 0:
	print(t)
	read_sensor(t)
	next_us = time.ticks_add(next_us, 10000)
  elif t > 4000:
    if num_data > 60000:
	  f.close()
	  num_file = num_file + 1
	  num_data = 1
	  f = open('{}.txt'.format(num_file), 'w')
	  print(num_file)
    else:
	  gc.collect()
  else:
	time.sleep_us(t)
	read_sensor(0)
	next_us = time.ticks_add(next_us, 10000)
  
print('stop')
time.sleep_ms(1000)
print('close')
f.close()
time.sleep_ms(1000)
print('umount')
uos.umountsd()
time.sleep_ms(1000)
print('home')
system.home()