#!/usr/bin/env python3

import os
import sys
import time
import subprocess
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.vid == 4292 and p.pid == 60000)
    ]
    devices.sort()
    return devices[0]


class ESP32(DeviceUnderTestAeadUARTP):

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

        self.uart_device = get_serial()
        devname = os.path.basename(self.uart_device)
        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.pio_packages_path = "/home/tester/.platformio/packages/"
        self.esptoolpy_path = os.path.join(
            self.pio_packages_path, "tool-esptoolpy/esptool.py")

        self.partitionspath = os.path.join(build_dir, 'partitions.bin')
        self.firmware_path = os.path.join(build_dir, 'firmware.bin')

        # Convert elf to bin
        cmd = ['python3', self.esptoolpy_path]
        cmd += ['--chip', 'esp32']
        cmd += ['elf2image', os.path.join(build_dir, 'firmware.elf')]
        subprocess.check_call(cmd)

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

    def reset(self):
        self.ser.setDTR(False)  # IO0=HIGH
        self.ser.setRTS(True)   # EN=LOW, chip in reset1
        time.sleep(0.1)
        self.ser.setDTR(False)  # IO0=HIGH
        self.ser.setRTS(False)  # EN=HIGH, chip out of reset
        time.sleep(1)

    def flash(self):
        arduinoespressif32_path = os.path.join(
            self.pio_packages_path, "framework-arduinoespressif32/")
        boot_app0_path = os.path.join(
            arduinoespressif32_path,
            "tools/partitions/boot_app0.bin")
        bootloader_path = os.path.join(
            arduinoespressif32_path,
            "tools/sdk/bin/bootloader_dio_80m.bin")

        partitions = [
            (0xe000, boot_app0_path),
            (0x1000, bootloader_path),
            (0x10000, self.firmware_path),
            (0x8000, self.partitionspath)
        ]

        cmd = ['python3', self.esptoolpy_path]
        cmd += ['--chip', 'esp32']
        cmd += ['--before', 'default_reset', '--after', 'hard_reset']
        cmd += ['--port', self.uart_device]
        cmd += ['write_flash', '-z']
        for addr, path in partitions:
            cmd += ['0x%x' % addr, path]
        subprocess.check_call(cmd)

        eprint("Firmware flashed.")

        self.ser = serial.Serial(
            self.uart_device,
            baudrate=500000,
            timeout=5)
        self.reset()

    def dump_ram(self):
        return None


if __name__ == "__main__":
    sys.exit(test_main(ESP32, 0x0020, sys.argv))
