import pyvisa
import sys
from time import sleep

class R6144:
    def __init__(self, rm, visaId):
        try:
            self.R6144 = rm.open_resource(visaId)    #R6144
        except:
            print("Cannot connect to R6144")
            while True:
                key = input("Press Enter to exit.")
                if not key:
                    break
            sys.exit()
        print("R6144 is ready for Voltage Output Op.")

    def sendcmd(self, cmdstr):
        self.R6144.write(cmdstr)

def VoltStr(arg1):
    if arg1[0] not in "+-":
        print("Error: argument must start with + or -")
        sys.exit(1)
    try:
        value = float(arg1)
    except ValueError:
        print("Error: invalid numeric value")
        sys.exit(1) 
    if not -2.0 <= value <= 2.0:
        print("Error: value out of range (-2 to +2)")
        sys.exit(1) 
    return format(value, "+.3f")

if len(sys.argv) < 2:
    print("Usage: python3 R6144.py [+|-] volt_val")
    sys.exit(1)

vout = VoltStr(sys.argv[1])

print(vout)

rm = pyvisa.ResourceManager()
r6144 = R6144(rm, 'GPIB0::10::INSTR')

r6144.sendcmd(f"V5 D{vout}V") # V5 can output -16 ~ +16 V

r6144.sendcmd("E")
sleep(3)
r6144.sendcmd("H")