import argparse
import sys
import pyvisa
import re
import time
from sys import exit

if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='SCPI device programmer ',
                                     description='Tool for writing device model and serial number')
    parser.add_argument('number_of_switches', metavar = 's', type = int, nargs = '+',
                        help = 'serial number for device')
    #parser.add_argument('model', metavar = 'm', type = int, nargs = '+',
    #                    help = 'device model')
    args = parser.parse_args()

    isRequest = False

    rm = pyvisa.ResourceManager()

    print('Число переключений: {0}'.format(args.number_of_switches[0]))

    VID = '0x2226'
    PID = '0x0065'
    for device in rm.list_resources():
        try:
            instr = rm.open_resource(device)
            if VID in device and PID in device:
                #Device detected and it's switchboard
                print('Device detected and its switchboard')
                print(instr.query('*IDN?'))
                print("Start test")

                experiment_start_time = time.time_ns()
                connectedPortIndex = 0
                connectedPortIndex2 = 1
                number_of_switches = args.number_of_switches[0]
                for i in range(number_of_switches):
                    #print("Номер итерации: ", i)
                    #print('CTRL:PORT {0},{1}'.format(connectedPortIndex, 0))
                    instr.write('CTRL:PORT {0},{1}'.format(connectedPortIndex, connectedPortIndex2))
                    if isRequest:
                        nums = instr.query('CTRL:PORT?')
                        portIndexes = re.findall(r'\d+', nums)
                        #print(portIndexes)
                        if(connectedPortIndex != int(portIndexes[0])):
                            print("Порт не успел скоммутироваться!")
                            break
                    #print("Коммутируем порт: ", connectedPortIndex, connectedPortIndex2)
                    connectedPortIndex += 1
                    connectedPortIndex2 += 1
                    if(connectedPortIndex > 12):
                        connectedPortIndex = 0
                    if(connectedPortIndex2 > 12):
                        connectedPortIndex2 = 0
                    time.sleep(10/1000)
            experiment_end_time = time.time_ns();
            experiment_time = experiment_end_time - experiment_start_time
            print("Затраченное время на эксперимент, мс: ", experiment_time / 1e6)
            print("Время переключения порта, мс: ", experiment_time / number_of_switches / 1e6)
            break;
        except:
            continue
            #print("Not connected device")

    rm.close()
    exit(0)
