# e-puck2 vision example: blob following.
# The robot learns the color of an object (e.g. a ball) and then turns and moves to keep it in the middle of the
# image at a fixed distance. Works on e-puck2.0/2.1 and e-puck2.2.
#
# Requirements: F407 selector in position 15 (camera image streamed to the ESP32 through SPI).
# Run: mpremote run blob_following.py   (Ctrl-C to stop)
#
# 1) The RGB LEDs are blue: put the object in front of the camera, in the middle of the image, and press the
#    user button: the color (hue) of the central area is learned.
# 2) The robot follows the biggest blob of that color: RGB LEDs green when the object is seen, red when it is lost
#    (the robot turns in place on the side where the object was last seen).
#
# The image is requested at 80x60 RGB565, whole view (zoom 8: each pixel is the average of 2x2 pixels of the
# 160x120 stream), 9600 bytes: small enough for the e-puck2.0 RAM and 4 times faster to process.
# The color is searched by hue (HSV), which doesn't change when the object is in shadow or more illuminated.

import epuck2
import time

WIDTH, HEIGHT = 80, 60
ZOOM = 8
FMT = (WIDTH, HEIGHT, 2)

HUE_TOLERANCE = 15  # Hue range around the learned one (degrees).
MIN_SATURATION = 30  # Less saturated pixels (greyish) are ignored, 0..100.
MIN_VALUE = 10  # Darker pixels are ignored (their color is unreliable), 0..100.
MIN_PIXELS = 15  # Smaller blobs are ignored (noise).

TARGET_AREA = 0.30  # Fraction of the image covered by the object at the desired distance.
SPEED = 400  # Max forward speed (motors range -1000..1000).
TURN_GAIN = 12  # Rotation speed per pixel of horizontal error.
SEARCH_SPEED = 200  # Rotation speed while searching the object.


def set_leds(r, g, b):
    epuck2.set_all_rgb(r, g, b, r, g, b, r, g, b, r, g, b)


def clamp(v, limit):
    return max(-limit, min(limit, v))


def learn_color(img):
    hue, sat, val = epuck2.image_get_color(img, FMT, roi=(WIDTH // 2 - 5, HEIGHT // 2 - 5, 10, 10))
    print("learned color: hue %d, saturation %d, value %d" % (hue, sat, val))
    if sat < MIN_SATURATION:
        print("warning: the object is not very colorful, it could be confused with grey areas")
    # The range wraps around 0 (e.g. red: 350..10).
    return (hue - HUE_TOLERANCE) % 360, (hue + HUE_TOLERANCE) % 360


def main():
    print("e-puck2 API version:", epuck2.get_api_version())
    if epuck2.get_selector() != 15:
        print("this example needs the selector in position 15 (SPI image stream)")
        return

    epuck2.camera_set_format(WIDTH, HEIGHT, 2, ZOOM)
    img = bytearray(WIDTH * HEIGHT * 2)

    # 1) Learn the color.
    set_leds(0, 0, 50)
    print("put the object in the middle of the image and press the button")
    while not epuck2.button_pressed():
        epuck2.camera_get_image(img, 1000)  # Keep reading to have the latest image when the button is pressed.
    while epuck2.button_pressed():
        time.sleep_ms(10)
    if epuck2.camera_get_image(img, 1000) is None:
        print("no image received")
        return
    hue_min, hue_max = learn_color(img)

    # 2) Follow it.
    last_side = 1
    frames = 0
    pixels = 0
    t_print = time.ticks_ms()
    try:
        while True:
            if epuck2.camera_get_image(img, 1000) is None:
                epuck2.set_motors_speed(0, 0)
                continue
            blobs = epuck2.image_find_blobs_color(img, FMT, hue_min, hue_max, sat_min=MIN_SATURATION,
                                                  val_min=MIN_VALUE, min_pixels=MIN_PIXELS, max_blobs=1)
            if blobs:
                pixels, cx, cy, x_min, y_min, x_max, y_max = blobs[0]  # The biggest one.
                err = cx - WIDTH // 2  # < 0: object on the left.
                last_side = 1 if err > 0 else -1
                area = pixels / (WIDTH * HEIGHT)
                forward = clamp(int(SPEED * (1 - area / TARGET_AREA)), SPEED)  # Back off when too close.
                turn = TURN_GAIN * err
                epuck2.set_motors_speed(clamp(forward + turn, 1000), clamp(forward - turn, 1000))
                set_leds(0, 50, 0)
            else:
                pixels = 0
                epuck2.set_motors_speed(SEARCH_SPEED * last_side, -SEARCH_SPEED * last_side)
                set_leds(50, 0, 0)

            frames += 1
            if time.ticks_diff(time.ticks_ms(), t_print) >= 1000:
                print("%d fps, object pixels: %d" % (frames, pixels))
                frames = 0
                t_print = time.ticks_ms()
    finally:
        epuck2.set_motors_speed(0, 0)
        set_leds(0, 0, 0)


main()
