import pylink
try:
    import StringIO
except ImportError:
    import io as StringIO
import string
import sys
from sys import exit
import time
import subprocess
import jlinkhelper
from datetime import datetime
from jlinkhelper import *

print("===========================================================")
print("SWO Logger, Ambiq Inc\nwww.ambiq.com\n")
print("Version 2.2, 2022-05-12")
print("===========================================================")
device_choice = input("Please select connected device:\n1.Apollo\n2.Apollo2 Family\n3.Apollo3 Family\n4.Apollo4 Family\n")

if device_choice == "1":
    device = "APOLLO512-KBR"
elif device_choice == "2":
    device = "AMAPH1KK-KBR"
elif device_choice == "3":
    device = "AMA3B1KK-KBR"
elif device_choice == "4":
    device = "AMAP42KK-KBR"

log_path = input("Please input SWO log file name: (Press ENTER for default file name)")

if log_path == "":
    timestr = datetime.now().strftime("%Y%m%d-%H-%M-%S")
    log_path = "swo_log_" + timestr + ".txt"


# To solve terminal print crush in Windows
sys.stdout = StringIO.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# exit(serial_wire_viewer(device, log_path))
serial_wire_viewer(device, log_path)
print("You may now close the window...")
sys.stdout.flush()
while True: # keep the app window for user to close
    try:
        continue
    except KeyboardInterrupt:
        exit()