#
#  Copyright (C) 2020-2021 Aloysius Indrayanto
#
#  This file is part of the eCxx library, see LICENSE file for the license details.
#

# NOTE : This script can also be used to reset Arduino Nano Every


# Import modules from the system-wide Python installation
import os
import sys
import time
import traceback

# Import the embedded pySerial module
thisDirName = os.path.dirname( ( os.path.abspath(__file__) ) )
libsDirName = os.path.abspath( os.path.join(thisDirName, "../3rd_party/tools/EspDevelopment") )

sys.path.insert(0, libsDirName)

from pyserial import serial

# The lowest possible baudrate that would still be supported on most platforms
# which is not the magic baudrate of 1200 bps
LOWEST_BAUDRATE = 2400

# Reset pulse time
RESET_PULSE_TIME = 0.25

# Check the arguments
if( len(sys.argv) != 2 ) :
    print("\n")
    print("Usage: ResetToBootloader <device>")
    print("\n")
    sys.exit(1)

# Get the serial device name
device = sys.argv[1]

# Try reset the attached AVR using the magic baudrate so it runs the bootloader
try :
    # Open and close the port using the lowest possible baudrate
    ser = serial.Serial(port=device, baudrate=LOWEST_BAUDRATE)
    ser.setRTS(True)
    ser.setDTR(True)
    ser.close()

    # Open the port at the magic baudrate of 1200 bps
    ser.baudrate = 1200
    ser.setRTS(True)
    ser.setDTR(True)
    ser.open()

    # RTS high and DTR LOW
    #     It needs a try-except block because some USB drivers may immediately reset the MCU
    #     when the host PC open the serial port (without further waiting for RTS and DTR)
    try :
        time.sleep(RESET_PULSE_TIME)
        ser.setRTS(True )
        ser.setDTR(False)
        time.sleep(RESET_PULSE_TIME)
        ser.setDTR(True )
    except :
        pass

    # Close the port
    ser.close()

    # Delay for a while
    time.sleep(RESET_PULSE_TIME * 2)

except :
    traceback.print_exc()
