import sys
import pyvisa

if len(sys.argv) <= 1:
    print("Error: Specify a serial number to process")
    exit()

serialNumber = sys.argv[1]
print(serialNumber)

if len(sys.argv) == 3:
    deviceId = sys.argv[2]
    print(sys.argv[2])


rm = pyvisa.ResourceManager()

VID = '0x2226'
PID = '0x0065'
for device in rm.list_resources():
    print(device)
    print(rm.resource_info(device, extended = True))
    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?'))
            #Is Device in service mode?
            print(instr.query('SERVICE:STATE 1'))
            ansver = str(instr.query('SERVICE:STATE?'))
            print(ansver)
            if ansver != str('ENABLE\n'):
                print('SERVICE MODE DISABLED!')
                break;

            #Send serial to device
            print('Send command: ' + 'SERVICE:SERIAL ' + str(sys.argv[1]))
            instr.query('SERVICE:SERIAL ' + str(sys.argv[1]))
            if len(sys.argv) == 3:
                print('Send command: ' + 'SERVICE:MODEL ' + str(sys.argv[2]))
                print(instr.query('SERVICE:MODEL ' + str(sys.argv[2])))

            #Disable service mode
            #print(instr.query('SERVICE:STATE 0'))
            #ansver = str(instr.query('SERVICE:STATE?'))
            #print(ansver)
            #if ansver != str('DISABLE\n'):
            #    print('WARNING: DEVICE STILL IN SERVICE MODE')
                
            #Set device default parameters
            print(instr.query('*RST'))
            #Reboot device 
            print(instr.query('SERVICE:REBOOT?'))       
            break
    except:
        print("Not connected device")

rm.close()
sys.exit([-1, 2])
