"""
Check if wuart_<board>.hex works
"""
import time, random
import serial, time, os, sys
import programming as prg
from   utilities import *

VERSION = "0.1"
PROG_NAME = os.path.basename(sys.argv[0])

def ser_get_text(sport, n = 1):
    rv = sport.read(n)
    while sport.inWaiting():
        rv += sport.read()
    return rv

if __name__ == '__main__':

    CFGDATA = test_init(__doc__, VERSION)
    if not CFGDATA:
        sys.exit(1)

    prg.announce_config(CFGDATA)
    duts = CFGDATA.get(PROG_NAME, "duts").split()
    peers = CFGDATA.get(PROG_NAME, "peers").split()

    # === flash nodes ==========================================================
    ser = {}
    info = {}
    for d in list(set(duts + peers)):
        ser[d] = serial.Serial(port = CFGDATA.get(d,"port"),
                      baudrate = CFGDATA.get(d,"baudrate"),
                      timeout = 2)
        ser[d].close()
        info[d] = dict(CFGDATA.items(d))
        # flash firmware
        prg.load_firmware(d,
                      CFGDATA.get("CONFIG", "bin_dir") + "/wuart_%s.hex",
                      CFGDATA.getint("CONFIG", "force_flash"))

    # === start test ===========================================================
    for dut,peer in zip(duts,peers):

        print "dut:  %(boardname)s@%(port)s" % info[dut]
        print "peer: %(boardname)s@%(port)s" % info[peer]

        ser[dut].open()
        ser_get_text(ser[dut],200)

        opentmo = float(info[dut].get("opentmo", "0"))
        time.sleep(opentmo)

        ser[peer].open()
        ser_get_text(ser[peer],200)
        opentmo = float(info[peer].get("opentmo", "0"))
        time.sleep(opentmo)
        # === test string tx/rx data ===========================================
        tx_data = "howdy peer"
        ser[dut].write(tx_data)
        ser[dut].flush()
        time.sleep(2)
        rx_data = ser_get_text(ser[peer], len(tx_data))

        print "test %s" % tx_data,
        if test_error(rx_data == tx_data, "data error"):
            print " - TX:", len(tx_data)   #, map(ord, tx_data)
            print " - RX:", len(rx_data)   #map(ord, rx_data)


        # === test QBF tx/rx data ===========================================
        tx_data = 'THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG'\
                  'thequickbrownfoxjumpsoverthelazydog'\
                  '1234567890_-{}[]()'
        ser[dut].write(tx_data)
        ser[dut].flush()
        time.sleep(2)
        rx_data = ser_get_text(ser[peer], len(tx_data))

        print "test QBF sz=%d" % len(tx_data),
        if test_error(rx_data == tx_data, "data error"):
            print " - TX:", len(tx_data)   #, map(ord, tx_data)
            print " - RX:", len(rx_data)   #map(ord, rx_data)


        # === test random tx/rx data ===========================================
        for chsz in [1, 11, 127, 175, 191]:
            tx_data = "".join(map(chr, [random.randint(0, 255) for i in range(chsz)]))
            print "test chunk size %d" % len(tx_data),
            ser[dut].write(tx_data)
            ser[dut].flush()
            time.sleep(2)
            rx_data = ser_get_text(ser[peer], len(tx_data))

            if test_error(rx_data == tx_data, "data error"):
                print " - TX:", len(tx_data)   #, map(ord, tx_data)
                print " - RX:", len(rx_data)   #map(ord, rx_data)

        # === test escape sequence =============================================
        time.sleep(.5)
        ser[dut].write("+++")
        ser[dut].flush()
        time.sleep(.5)
        rx_data = ser_get_text(ser[dut], 64)
        print "test enter +++ menu",

        if test_error(rx_data.find("MENU:") >=0, "no escape menu"):
            print " - ESCAPE:", rx_data

        #exit menue
        ser[dut].write("q")

        # check if howdy is received
        tx_data = "howdy peer"
        ser[dut].write(tx_data)
        ser[dut].flush()
        time.sleep(2)
        rx_data = ser_get_text(ser[peer], len(tx_data))
        print "test exit +++ menu",
        if test_error(rx_data == tx_data, "exit from escape menu"):
            print " - TX:", len(tx_data)   #, map(ord, tx_data)
            print " - RX:", len(rx_data)   #map(ord, rx_data)


        ser[dut].close()
        ser[peer].close()



    nb_errors = test_get_errors()
    if nb_errors == 0:
        print "%s pass" % PROG_NAME
    else:
        print "%s fail" % PROG_NAME
    sys.exit(nb_errors)

# EOF
