from labcontrol.ea import EA_PS8080
from labcontrol.ea import EA_EL9080
from labcontrol.ea import EA_interface
import time

# Setup
maxpower    = 2000
psvolt      = 48.0
steps       = 40
settletime  = 10
measures    = 4
measuretime = .5

# defines
stepwidth = maxpower/psvolt/steps
starttime = time.time()

def identify(devlist):
    outdict = {}
    for dev in devlist:
        devid = EA_interface(dev).write(12, 0, [])
        if "PS" in devid[1]:
            devtype = "ps"
        else:
            devtype = "el"

        outdict[devtype] = {"id":devid[1][:-1], "address":dev, "type":devtype}

    return outdict

def init(tree):
    for dev, dat in tree.iteritems():
        if dat['type'] == "el":
            devobj = EA_EL9080(tree[dev]['address'])
        else:
            devobj = EA_PS8080(tree[dev]['address'])
        
        #devobj.interface.debug_output = False
        devobj.remote(True)
        time.sleep(1)
        
        if dat['type'] == "el":
            devobj.set_current(0)
            devobj.enable(True)
        else:
            devobj.set_current(maxpower/psvolt)
            devobj.set_voltage(48)
            devobj.output(True)
        
        tree[dev]['dev'] = devobj

def deinit(tree):
    for dev, dat in tree.iteritems():
        if tree[dev]['type'] == "el":
            tree[dev]['dev'].enable(False)
        else:
            tree[dev]['dev'].output(False)
        tree[dev]['dev'].remote(False)
        tree[dev]['dev'].close()

def measurement(devicetree):
    print("starting Measurement (approx {}s)".format(steps*(settletime + measures*measuretime)))
    log = "time,set_curr,set_volt,act_curr_ps,act_curr_el\n"
    devicetree['ps']['dev'].set_current(stepwidth*steps)
    for i in range(1, steps):
        steppos = i*stepwidth
        try:
            devicetree['el']['dev'].set_current(steppos)
            time.sleep(settletime)
            act_el = 0
            act_ps = 0
            for m in range(0, measures):
                act_el += devicetree['el']['dev'].get_actual_values()['i']
                act_ps += devicetree['ps']['dev'].get_actual_values()['i']
                time.sleep(measuretime)

            act_ps = act_ps/measures
            act_el = act_el/measures
            log_new= "{:.3f},{:.3f},{:.1f},{:.3f},{:.3f}\n".format(
                time.time()-starttime, 
                steppos,
                48.0, 
                act_ps,
                act_el                
            )
            log += log_new
        except Exception as e:
            print type(e)
            print e

    print(log)
    with open('./log.csv', 'w') as f:
        f.write(log)

if __name__ == "__main__":
    devicetree = identify(["/dev/ttyUSB0","/dev/ttyUSB1"])
    print(devicetree)
    init(devicetree)
    init(devicetree)
    measurement(devicetree)
    deinit(devicetree)
