# e-puck2 camera example: measure the image frame rate of the SPI stream (160x120 RGB565).
#
# Requirements: F407 selector in position 15 (camera image streamed continuously to the ESP32 through SPI).
# With the other selector positions (e.g. 3) every camera_get_image() call requests an image through UART,
# so the frame rate is simply 1 / duration of the call: measure it directly in your application loop.
# Run: mpremote run camera_fps.py
#
# Two measurements:
# 1) "SPI": images received by the ESP32 (F407 capture + SPI transfer), counted with camera_get_stats()
#    while MicroPython is idle.
# 2) "app": images read by a MicroPython loop with camera_get_image() (adds the copy of 38400 bytes
#    from the ESP32 image buffer into the MicroPython bytearray). The images lost by the loop (skipped)
#    and the time spent inside camera_get_image() (wait + copy) are also reported.

import epuck2
import time

DURATION_S = 10


def measure_spi(duration_s):
    epuck2.camera_reset_stats()
    t0 = time.ticks_ms()
    time.sleep(duration_s)
    dt = time.ticks_diff(time.ticks_ms(), t0) / 1000
    frames, errors = epuck2.camera_get_stats()
    return frames / dt, frames, errors


def measure_app(duration_s):
    buf = bytearray(epuck2.CAM_IMAGE_SIZE)
    epuck2.camera_get_image(buf, 2000)  # Sync with the stream.
    epuck2.camera_reset_stats()
    n = 0
    timeouts = 0
    skipped = 0
    get_us = 0
    get_max_us = 0
    last_id = None
    t0 = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), t0) < duration_s * 1000:
        t = time.ticks_us()
        img_id = epuck2.camera_get_image(buf, 1000)
        dt_us = time.ticks_diff(time.ticks_us(), t)
        if img_id is None:
            timeouts += 1
            continue
        get_us += dt_us
        get_max_us = max(get_max_us, dt_us)
        if last_id is not None and img_id > last_id + 1:
            skipped += img_id - last_id - 1
        last_id = img_id
        n += 1
    dt = time.ticks_diff(time.ticks_ms(), t0) / 1000
    frames, errors = epuck2.camera_get_stats()
    return n / dt, n, timeouts, skipped, (get_us // n if n else 0), get_max_us, frames / dt, errors


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
    if epuck2.camera_get_image(bytearray(epuck2.CAM_IMAGE_SIZE), 3000) is None:
        print("no image received")
        return
    width, height, bpp = epuck2.camera_get_format()
    print("image %dx%d RGB565, %d bytes, %d s per test" % (width, height, width * height * bpp, DURATION_S))

    fps, frames, errors = measure_spi(DURATION_S)
    print("SPI : %.2f fps (%d images, %d errors)" % (fps, frames, errors))

    fps, n, timeouts, skipped, avg_us, max_us, spi_fps, errors = measure_app(DURATION_S)
    print("app : %.2f fps (%d images read, %d skipped, %d timeouts)" % (fps, n, skipped, timeouts))
    print("      camera_get_image(): avg %d us, max %d us (wait for the next image + copy)" % (avg_us, max_us))
    print("      SPI during the app test: %.2f fps, %d errors" % (spi_fps, errors))


main()
