#!/usr/bin/env python3

import os
import sys
import pylink
import serial.tools.list_ports
from test_common import (
    DeviceUnderTestAeadUARTP,
    eprint,
    test_main,
    FileMutex
)


def get_serial():
    ports = serial.tools.list_ports.comports()
    devices = [
        p.device
        for p in ports
        if p.serial_number == '00000000'
    ]
    devices.sort()
    return devices[0]


class F7(DeviceUnderTestAeadUARTP):
    RAM_SIZE = 0x50000

    def __init__(self, build_dir):
        DeviceUnderTestAeadUARTP.__init__(self)

        self.uart_device = get_serial()
        devname = os.path.basename(self.uart_device)
        self.ser = serial.Serial(
            self.uart_device,
            baudrate=115200,
            timeout=5)
        self.lock = FileMutex('/var/lock/lwc-compare.%s.lock' % devname)
        self.build_dir = build_dir
        self.template_path = os.path.dirname(sys.argv[0])

        self.jlink = pylink.JLink()
        self.jlink.open(779340002)

        self.firmware_path = os.path.join(
            build_dir, 'f7.bin')
        self.ram_pattern_path = os.path.join(
            self.template_path, 'ram_pattern.bin')

    def firmware_size(self):
        return os.stat(self.firmware_path).st_size

    def flash(self):
        jlink = self.jlink
        jlink.connect('STM32F746ZG')
        jlink.flash_file(self.firmware_path, 0x8000000)
        eprint("Firmware flashed.")
        jlink.flash_file(self.ram_pattern_path, 0x20000000)
        eprint("RAM flashed.")
        jlink.reset()
        jlink.restart()

    def dump_ram(self):
        jlink = self.jlink
        return bytes(jlink.memory_read8(0x20000000, F7.RAM_SIZE))


if __name__ == "__main__":
    sys.exit(test_main(F7, 0x0008, sys.argv))
