"""
Check if sniffer_<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()

    # === flash nodes ==========================================================
    ser = {}
    info = {}
    for d in duts:
        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") + "/sniffer_%s.hex",
                      CFGDATA.getint("CONFIG", "force_flash"))

    # === start test ===========================================================
    for dut in duts:

        print "sniffer: %(boardname)s@%(port)s" % info[dut]
        ser[dut].open()
        opentmo = float(info[dut].get("opentmo", "0"))
        time.sleep(opentmo)

        # eat up trailing stuff
        ser_get_text(ser[dut], 100)

        # === test state idle ==================================================

        ser[dut].write(" ")
        rx_data = ser[dut].read(10)
        print "test state idle",
        if test_error(rx_data.find("IDLE") >= 0, "sniffer not in state idle"):
            print "RX: [%s]" % rx_data


        # === test parms ==================================================
        ser[dut].write("parms\n")
        time.sleep(.5)
        rx_data = ser[dut].read(300)
        print "test parms"
        for w in ["PLATFORM:", "SUPP_CMSK:", "CURR_CMSK:",
                  "CURR_CHAN:", "CURR_PAGE:", "CURR_RATE:", "SUPP_RATES:",
                  "TIMER_SCALE:", "TICK_NUMBER:", "CHKCRC:", "OK",
                  info[dut]['boardname']]:
            print " for %s" % w,
            if test_error(rx_data.find(w) > -1, w):
                print "RX: [%s]" % rx_data

        ser[dut].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
