# Test name: playground-pw84
# on dir playground, iocsh pw84.db
# Copyright (c) 2015 Paul Scherrer Institute. All rights reserved.

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


def startTest(testName, DEVICE, params):
    """
    Main method running the test
    """
    # by default, assume the test failed
    ret = 'Test failed'
    status = False
    # plot name to be given to the scan. Use: scan.setPlotTitle(plotName)
    plotName = DEVICE + ' - ' + testName
    # put the whole custom code under try/catch
    try:
        # get the path of this script
        testPath = inspect.getfile(inspect.currentframe())
        # init the testing tool class. It can be sued in the following ways:
        test = TestingTool(testName, testPath, DEVICE, params)

################ END OF Init #####################
######### WRITE YOUR CODE HERE BELOW #############
        test.log( 'testpath A: ' + testPath )
        test.log( 'parameters: '  + str(params) )
        test.log( 'device: ' + DEVICE  )
        #scan = ManualScan(['time'], ['SetV', 'ActualV', 'ActualI'] , [0.0], [30.0], [20])
        scan = ManualScan(['time'], ['SetV', 'ActualV', 'ActualI'])
        scan.setPlotTitle(plotName)
        scan.start()

        try:
            #Creating channels: dimension 1
            #Ramp rate
            #SetRamp = Channel(DEVICE + ':Set-RampA', type = 'd')
            SetRamp = Channel('pw84:ai', type = 'd')
            #LinearPositioner SetV
            #SetV = Channel(DEVICE + ':Set-VA', type = 'd')
            SetV = Channel('pw84:ai', type = 'd')
            #Timestamp time
            #ScalarDetector ActualV
            #ActualV = Channel(DEVICE + ':Actual-VA', type = 'd')
            ActualV = Channel('pw84:ai', type = 'd')
            #ScalarDetector ActualI
            #ActualI = Channel(DEVICE + ':Actual-IA', type = 'd')
            ActualI = Channel('pw84:ai', type = 'd')
        except:
            import traceback
            test.sendFeedback( 'Unable to create channel - ' + traceback.format_exc(), False)
            #raise Exception('Unable to create channel - ' + traceback.format_exc())   
            return

        #Init
        SetRamp.put(10.0, timeout=None)

        #set voltage to 0
        test.log(  'Ramping down power supply A to 0V' )
        SetV.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 = ActualV.get()
            if detector2 <= 1.0:
                break
            sleep(0.5)

        #Dimension 1
        #LinearPositioner SetV
        test.log(  'Ramping up power supply A' )
        for setpoint1 in frange(0.0, 20.0, 5.0, True): 
            if setpoint1 > 50.0 or setpoint1 < 0.0:
                break
            SetV.put(setpoint1, timeout=None) # TODO: Set appropriate timeout
            readback1 = SetV.get()
            if abs(readback1 - setpoint1) > 0.9 : # TODO: Check accuracy
                raise Exception('SetV could not be set to the value ' + str(setpoint1))
                ret = 'SetV 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 ActualV
                detector2 = ActualV.get()
                detector3 = ActualI.get()
                #scan.append ([setpoint1], [readback1], [detector1, detector2])
                #append(setpoints, positions, values)
                scan.append ([detector1], [detector1], [readback1, detector2, detector3]) 
                sleep( 0.1 ) # Settling time        

        #reset output to 0V
        SetV.put(0.0, timeout=None)
        #Closing channels
        SetV.close()
        ActualV.close()
        ActualI.close()

        scan.end()
        ret = 'Test ps A completed'
        success = True      
################ END OF YOUR CODE ################
###### Final - DO NOT MODIFY THE CODE BELOW ######

        # just in case the feedback was forgotten
        test.sendFeedback(ret, success)
    except (KeyboardInterrupt):
        # user stop error handler
        import traceback
        ret = 'Test stopped by user.'
        success = False
        test.sendFeedback(ret, success)
    except:
        # generic error handler
        import traceback
        ret = traceback.format_exc()
        success = False
        test.sendFeedback(ret, success)


# launch the test
startTest(test, device, parameters)

################ END OF Final ####################
#### IF NEEDED, ADD YOUR FUNCTIONS HERE BELOW ####
# def yourCustomFunction:
