
###### Init - DO NOT MODIFY THE CODE BELOW ######
global print_log, sendFeedback,  sys, inspect, os, traceback
import sys, inspect, os, traceback

def print_log(testName, DEVICE, text):
    time.ctime()
    now = time.strftime('%Y.%m.%d %H:%M:%S') 
    print now + ' ' + DEVICE + ' - ' + testName + ': ' + text    

#prepare and send feedback to calling tool   
def sendFeedback(testPath, testName, DEVICE, returnString, testPassed):
    print_log(testName, DEVICE,  'End of test. Result:')
    print_log(testName, DEVICE,  'Device:        ' + DEVICE)
    print_log(testName, DEVICE,  'Test name:     ' + testName)
    print_log(testName, DEVICE,  'Test path:     ' + testPath)
    print_log(testName, DEVICE,  'Test passed:   ' + str(testPassed))
    print_log(testName, DEVICE,  'Return string: ' + returnString)
    ret = [testPath, DEVICE, returnString, testPassed]
    set_return(ret)

def startTest(testName, DEVICE, params):
    #get the path of this script
    import inspect
    testPath = inspect.getfile(inspect.currentframe()) 
    #by default, failed 
    ret = 'Test failed'
    success = False   
    #plot name to be given to the scan. Use: scan.setPlotTitle(plotName)
    plotName = DEVICE + ' - ' + testName      
######### WRITE YOUR CODE HERE BELOW #############
    print_log(testName, DEVICE,  'testpath B: ' + testPath )
    print_log(testName, DEVICE, 'parameters:' + str( params) )
    print_log(testName, DEVICE, 'device: ' + DEVICE )
    #scan = ManualScan(['time'], ['SetVB', 'ActualVB', 'ActualIB'] , [0.0], [30.0], [20])
    scan = ManualScan(['time'], ['SetVB', 'ActualVB', 'ActualIB'] )
    scan.setPlotTitle(plotName)
    scan.start()

    #Creating channels: dimension 1
    try:
        #Ramp rate
        SetRamp = Channel(DEVICE + ':Set-RampB', type = 'd')
        #SetRamp = Channel('pw84:ai', type = 'd')
        #LinearPositioner SetVA
        SetVA = Channel(DEVICE + ':Set-VB', type = 'd')
        #SetVA = Channel('pw84:ai', type = 'd')
        #Timestamp time
        #ScalarDetector ActualVA
        ActualVA = Channel(DEVICE + ':Actual-VB', type = 'd')
        #ActualVA = Channel('pw84:ai', type = 'd')
        #ScalarDetector ActualIA
        ActualIA = Channel(DEVICE + ':Actual-IB', type = 'd')
        #ActualIA = Channel('pw84:ai', type = 'd')
    except:
        sendFeedback(testPath, testName, DEVICE, 'Unable to create channel - ' + traceback.format_exc(), False)
        return
    #Init
    SetRamp.put(10.0, timeout=None)

    #set voltage to 0
    print_log(testName, DEVICE,  'Ramping down power supply B to 0V')
    SetVA.put(0.0, timeout=None)

    #wait up to 2 minutes for voltage to be ~0
    for setpoint1 in frange(0.0, 120.0, 1.0, True):
        detector2 = ActualVA.get()
        if detector2 <= 1.0:
            break
        sleep(0.5)

    #Dimension 1
    #LinearPositioner SetVA
    print_log(testName, DEVICE,  'Ramping up power supply')
    for setpoint1 in frange(0.0, 20.0, 5.0, True): 
        if setpoint1 > 50.0 or setpoint1 < 0.0:
            break
        SetVA.put(setpoint1, timeout=None) # TODO: Set appropriate timeout
        readback1 = SetVA.get()
        if abs(readback1 - setpoint1) > 0.9 : # TODO: Check accuracy
            raise Exception('SetVB could not be set to the value ' + str(setpoint1))
            ret = 'SetVB could not be set to the value ' + str(setpoint1) + '(measured value: '+str(readback1)+')'
            success = False        
            break
        #scan quickly the output during some seconds
        for setpoint2 in range(0, 20):
            #Detector time
            detector1 = float(java.lang.System.currentTimeMillis())
            #Detector ActualVA
            detector2 = ActualVA.get()
            detector3 = ActualIA.get()
            #scan.append ([setpoint1], [readback1], [detector1, detector2])
            #append(setpoints, positions, values)
            scan.append ([detector1], [detector1], [readback1, detector2, detector3]) 
            sleep( 0.1 ) # Settling time        
        ret = 'Test ps B completed'
        success = True

    #reset output to 0V
    SetVA.put(0.0, timeout=None)
    #Closing channels
    SetVA.close()
    ActualVA.close()
    ActualIA.close()
################ END OF YOUR CODE ################
###### Final - DO NOT MODIFY THE CODE BELOW ######        
    sendFeedback(testPath, testName, DEVICE, ret, success)

#launch the test
parameters = {}
startTest(test, device, parameters)
    
