#
# bollerwagen.py for card10
#
# WHATIS
#
# - interactive light for your bollerwagen or other gefährt
# - signals stop via red light
# - signals movement via green light
# - signals turns by flashing yellow light
#
# HOWTO
#
# - mount vertically onto your bollerwagen
# - use at least two card10s for two sides of your bollerwagen :-)
# - use bottom right switch to change between right and left turn indicator
#

import bhi160
import utime
import buttons
import leds
import color

MOTION_THRESHOLD = 7
BLINKER_TIME = 4

STILL  = 1
RIGHT  = 2
LEFT   = 3
MOVING = 4

listen = LEFT

col = color.WHITE

state  = 0
newstate1 = STILL
newstate2 = STILL

sensor = 2
sensors = [
    {"sensor": bhi160.BHI160Orientation(), "name": "Orientation"},
    {"sensor": bhi160.BHI160Accelerometer(), "name": "Accelerometer"},
    {"sensor": bhi160.BHI160Gyroscope(), "name": "Gyroscope"},
]

blinker = 0

def abs(x):
    if x >= 0:
        return x
    return -x

def set_all(col):
    leds.set_all([col, col, col, col, col, col, col, col, col, col, col])

def turning_light_on():
    if state == listen:
        set_all(color.COMMYELLOW)
    else:
        leds.clear()

def turning_light_off():
    leds.clear()

leds.set_powersave(True)
while True:
    # read gyro sensor
    samples = sensors[sensor]["sensor"].read()
    if len(samples) > 0:
        sample = samples[0]
        newstate2 = newstate1
        if abs(sample.x) + abs(sample.y) + abs(sample.z) < MOTION_THRESHOLD:
            newstate1 = STILL
        elif sample.y >  MOTION_THRESHOLD:
            newstate1 = RIGHT
        elif sample.y < -MOTION_THRESHOLD:
            newstate1 = LEFT
        else:
            newstate1 = MOVING

    # choose the state
    if newstate1 == newstate2:
        if newstate1 != state:
            state = newstate1
            if state == STILL:
                set_all(color.RED)
            elif state == MOVING:
                set_all(color.CAMPGREEN)
            else:
                turning_light_on()

    # flash the turning light
    if state == LEFT or state == RIGHT:
        blinker = blinker + 1
        if blinker == BLINKER_TIME:
            turning_light_off()
        elif blinker == BLINKER_TIME * 2:
            turning_light_on()
            blinker = 0
            
    # read button with Prellschutz
    v = buttons.read(buttons.BOTTOM_RIGHT)
    if v == 0:
        button_pressed = False

    if not button_pressed and v & buttons.BOTTOM_RIGHT != 0:
        button_pressed = True
        if listen == LEFT:
            listen = RIGHT
        else:
            listen = LEFT

    utime.sleep(0.1)