# counts the time of the longest time duration when you do not move. This is supposed to be one R.E.M. (rad-eye movement) or deep sleep phase
# attach your card10 when going to sleep and start this app.
# author: Superwallah
# licence: GPL v3
# todo: combine with ECG to distingiush R.E.M. and deep sleep
import bhi160
import display
import utime
import buttons

sleepduration = 0
max_sleepduration = 0
sens_movement = 0.0
start_time = utime.time()
disp = display.open()
disp.print("Sleep      tracker")
disp.update()
bhi160_obj = bhi160.BHI160Accelerometer()
while True:
	sleepduration = utime.time() - start_time
	if sleepduration > max_sleepduration:
		max_sleepduration = sleepduration
	# Read and print sample
	bhi160_data = bhi160_obj.read()
	disp.print("%i" % sleepduration, posy=52)
	disp.update()	
	if len(bhi160_data) > 0:
		sens_movement = bhi160_data[0].x**2 + bhi160_data[0].y**2 + bhi160_data[0].z**2
	# whenever you move while sleeping, a new REM phase begins
	if sens_movement > 1.4:
		disp.clear()
		disp.print("longest    R.E.M.Phase")
		disp.print("{min:3.0f}min {s:2d}s".format(min=max_sleepduration/60,s=max_sleepduration%60), posy=35)
		disp.update()
		start_time = utime.time()

