# Provide a list of IP addresses of PRC-style FPGAs on the command line.
# This program will check their crc_errors counters twice, one second apart.
# It returns success if those counters are unchanging, considered strong
# evidence that the links (as used for field control) are working.
import time
import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), "../submodules/FEED/src/python"))


def crc_checkn_run(devs):

    crcs = []

    for dev in devs:
        crcs.append(dev.reg_read([('crc_errors')])[0])

    time.sleep(1)

    fail = False

    for idx, dev in enumerate(devs):
        crc2 = dev.reg_read([('crc_errors')])[0]
        fault = crc2 != crcs[idx]
        if fault:
            fail = True
        print("CRC check %s: %s %s%s" % (dev.dest, crcs[idx], crc2, " FAULT" if fault else ""))

    if fail is False:
        print("CRC test OK")
    else:
        exit(fail)


if __name__ == "__main__":

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("ips", help="IP addresses of PRC and RFS(s)", nargs='+')
    args = parser.parse_args()

    import sys
    import os
    sys.path.append(os.path.join(os.path.dirname(__file__), "../submodules/FEED/src/python"))
    import leep

    devs = []
    for ip in args.ips:
        print('Carrier board URL %s' % ip)
        devs.append(leep.open('leep://'+ip, instance=[]))

    print("CRC Checks")
    crc_checkn_run(devs)
