# e-puck2 camera example: grab images and save them as BMP (24 bits) on the ESP32 filesystem.
#
# Requirements: F407 selector in position
# - 3: image requested through UART (asercom), the format can be changed with camera_set_format().
#   Three images are saved:
#   - img_color.bmp: 40x40 RGB565, zoom 4 (F407 default) => 160x160 pixels area of the sensor;
#   - img_grey.bmp:  64x64 greyscale, zoom 4 => 256x256 pixels area, more pixels in the same image size (4096 bytes);
#   - img_zoom.bmp:  40x40 RGB565, zoom 1 => only the central 40x40 pixels of the sensor, 4 times magnified
#     compared to img_color.bmp.
#   "zoom" is the subsampling factor (1, 2 or 4): the image covers (width*zoom)x(height*zoom) pixels of the
#   640x480 sensor, so a smaller zoom gives a more magnified image.
# - 15: 160x120 RGB565 image streamed to the ESP32 through SPI (fixed format): img.bmp is saved.
# Run:      mpremote run camera_save_bmp.py
# Download: mpremote cp :img_color.bmp :img_grey.bmp :img_zoom.bmp .

import epuck2
import micropython
import time

# file name: (width, height, bytes_per_pixel, zoom)
IMAGES = (
    ("img_color.bmp", (40, 40, 2, 4)),
    ("img_grey.bmp", (64, 64, 1, 4)),
    ("img_zoom.bmp", (40, 40, 2, 1)),
)


@micropython.viper
def rgb565be_to_bgr24(src: ptr8, dst: ptr8, npix: int):
    # src: RGB565 big endian (RRRRRGGG GGGBBBBB), dst: BGR 24 bits (BMP order).
    i = 0
    while i < npix:
        hi = src[2 * i]
        lo = src[2 * i + 1]
        dst[3 * i] = (lo & 0x1F) << 3
        dst[3 * i + 1] = ((hi & 0x07) << 5) | ((lo & 0xE0) >> 3)
        dst[3 * i + 2] = hi & 0xF8
        i += 1


@micropython.viper
def grey_to_bgr24(src: ptr8, dst: ptr8, npix: int):
    i = 0
    while i < npix:
        v = src[i]
        dst[3 * i] = v
        dst[3 * i + 1] = v
        dst[3 * i + 2] = v
        i += 1


def _le16(v):
    return bytes((v & 0xFF, (v >> 8) & 0xFF))


def _le32(v):
    return bytes((v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF, (v >> 24) & 0xFF))


def save_bmp(file_name, img, width, height, bpp):
    row_size = (width * 3 + 3) & ~3  # BMP rows are padded to 4 bytes.
    offset = 14 + 40
    file_size = offset + row_size * height
    convert = rgb565be_to_bgr24 if bpp == 2 else grey_to_bgr24
    with open(file_name, "wb") as f:
        # BITMAPFILEHEADER
        f.write(b"BM" + _le32(file_size) + _le32(0) + _le32(offset))
        # BITMAPINFOHEADER (height > 0 => rows stored bottom-up)
        f.write(_le32(40) + _le32(width) + _le32(height) + _le16(1) + _le16(24)
                + _le32(0) + _le32(row_size * height) + _le32(2835) + _le32(2835)
                + _le32(0) + _le32(0))
        row = bytearray(row_size)
        src = memoryview(img)
        line = width * bpp
        for y in range(height - 1, -1, -1):
            convert(src[y * line:(y + 1) * line], row, width)
            f.write(row)
    return file_size


def grab_and_save(img, file_name):
    img_id = epuck2.camera_get_image(img, 2000)
    if img_id is None:
        print("no image received (is the selector in position 3 or 15?)")
        return False
    width, height, bpp = epuck2.camera_get_format()
    t0 = time.ticks_ms()
    n = save_bmp(file_name, img, width, height, bpp)
    print("image id %d, %dx%d %s -> %s (%d bytes, %d ms)" % (
        img_id, width, height, "RGB565" if bpp == 2 else "greyscale", file_name, n,
        time.ticks_diff(time.ticks_ms(), t0)))
    return True


def main():
    print("e-puck2 API version:", epuck2.get_api_version())
    img = bytearray(epuck2.CAM_IMAGE_SIZE)

    if epuck2.get_selector() == 15:
        # SPI: the first image could have been captured before the call, so take the second one.
        if epuck2.camera_get_image(img, 2000) is not None:
            grab_and_save(img, "img.bmp")
        else:
            print("no image received")
        return

    for file_name, fmt in IMAGES:
        if not epuck2.camera_set_format(*fmt):
            print("camera_set_format%s failed" % (fmt,))
            return
        if not grab_and_save(img, file_name):
            return

    epuck2.camera_set_format(40, 40, 2, 4)  # Restore the F407 default.


main()
