#!/usr/bin/env python
usage="""
Run RF playback system in a loop.
Note: this will not build new firmware - it will use the firmware in Builds/.

Example:
  ./diag_loop_test.py 2018-02-12-vanTest.xml,2018-08-24-vanTest.xml 10
    # where 10 is the # of times to loop

Also see http://wiki.eng.trimble.com/index.php/Spirent_RF_logger#Testing_a_set_of_files_in_a_loop
"""

import multiprocessing.connection as mp_con
import time
from pathlib import Path
import argparse

parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,description=usage)
parser.add_argument('file_list', help='List of XML files to run, separated by comma')
parser.add_argument('n_loops', help='# of times to loop the test',type=int)
args = parser.parse_args()

file_list = args.file_list + ','
n_loops = args.n_loops

msg_addr = ('localhost',5001)

def msg_send_recv( x ):
    result = {}
    try:
        client = mp_con.Client(msg_addr)
        client.send(x)
        result = client.recv()
        client.close()
    except:
        print("msg_send_recv error {}".format(x))
        pass
    return result

def msg_send( x ):
    client = mp_con.Client(msg_addr)
    client.send(x)
    client.close()

n_run = 0
while n_run < n_loops:
    d = msg_send_recv(['getRegressionInfo'])
    if n_run > 0 and d['status'].find("Error")>0:
        print("Got an error")
        break

    if d['status'] != "Running":
        n_run += 1
        print("Starting regression %d/%d" % (n_run,n_loops))
        Path('Builds/install.txt').touch()
        msg_send(['playList',file_list])
    time.sleep(120)
