#Test name: test without ioc
#test that does not use any connection to IOC. It is useful to test pure pshell graphical features.

###### Init - DO NOT MODIFY THE CODE BELOW ######
global sys, inspect, os, traceback
import sys, inspect, os, traceback
    
def startTest(testName, DEVICE, params):
    #by default, assume the test failed 
    ret = 'Test failed'
    success = 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)
    
######### WRITE YOUR CODE HERE BELOW #############

        #All the code in this section ## ..YOUR CODE.. ## can be modified/deleted. 
        #It must be indented at the same level as this comment
        #-----------------------------------
        #           GETTING INPUTS:
        #If needed, the following variables are available:
        #testPath   string, path of this test file
        #testName   string, name of this test
        #DEVICE     string, device for which the test must run (typically it is the beginning of a process variable name)
        #-----------------------------------
        #           GETTING TEST PARAMETERS:
        #if you need to get parameters for the test, use (casting may be necessary):
        #myParamValue = test.getParam('myParamName')
        #see the test config for the list of parameters specific to the test.
        #-----------------------------------
        #           SETTING OUTPUTS:
        #ret        string, a text summarizing the result of the test. It must be set before the end of your code.
        #success    bool, True = test successful. It must be set before the end of your code.
        #test.sendFeedback(ret,success) method that ends the testing script and gives the report to the calling application.
        #Examples:
        #
        #whenever the code must quit (i.e. after an error), you must end with:
        #ret = 'here is some info on what failed on the test'
        #success = false
        #test.sendFeedback(ret, success)
        #
        #whenever the code is finished successfully, you must end with:
        #ret = 'here is some info on the success of the test'
        #success = true
        #test.sendFeedback(ret, success)           
        #-----------------------------------
        #           LOG INFO:
        #when some information must be shown on the log, use:
        #test.log('test to log')
      
        ########## Example (can be removed) ######    
        #print the list of parameters passed. If any error, stop and send feedback
        test.log("Example - Test name:   "+testName)
        test.log("Example - Device name: "+DEVICE)
        try:
            test.log("Running test Initialise with the following parameters:")
            test.log(params )
            #If present, use the parameters here below for your test script
            repeatTimes = int(test.getParam('repeatTimes')) ; howManySamples = int(test.getParam('howManySamples')) ; delayBetweenSampleS = float(test.getParam('delayBetweenSampleS')) ; 
        except:
            ret = 'Could not retrieve testing parameters - ' + traceback.format_exc()
            success = False
            test.sendFeedback( ret, success)
            return 
            
        #loop to read channels for a while and plot the channels values.
        
        #initialise plot tab with 2 plots
        scan = ManualScan(['sample'], ['Motor Status (MSTA)', 'Motor Position (VAL)'] )
        #set plot name(tab title)
        scan.setPlotTitle(plotName + " Manual Scan")
        #start plots. See further below how to add points to the plots
        scan.start()
        
        #in this example we initialise also a plot type to show how to add several curves on the same plot
        p1 = plot(None,name="motor_msta", context = plotName + " Multi curves")[0]
        #opionally set plot ranges
        #p1.getAxis(p1.AxisId.X).setRange(0.0,80.0)
        #p1.getAxis(p1.AxisId.Y).setRange(0.0,70.0)
        p1.addSeries(LinePlotSeries("motor_val"))
        
        motor_msta = 0
        motor_val = 50
        increment = 1
        
        max = -1
        maxPos = 0
        min = 1000000000000
        minPos = 0
        from math import sin
        for sample in range(0, howManySamples):
            readback1 = sample
            sleep( delayBetweenSampleS ) # Settling time
            #here we simulate getting values
            #just draw a saw
            motor_msta = motor_msta + increment
            #just draw a nice sinusoid
            motor_val = sin(float(sample)/10.0)*10.0-10.0
            if abs(motor_msta) >= 50:
                increment = -1 * increment
            #add values to manual scan
            scan.append ([sample], [readback1], [motor_msta, motor_val] )
            #add values to plot
            p1.getSeries(0).appendData(sample, motor_msta)    
            p1.getSeries(1).appendData(sample, motor_val ) 
            #compute min and max differences
            if abs(motor_msta - motor_val) > max:
                max = abs(motor_msta - motor_val)
                maxPos = sample
            if abs(motor_msta - motor_val) < min:
                min = abs(motor_msta - motor_val)
                minPos = sample
            
        #show differences in the plot
        import java.awt.Color
        p1.addMarker(maxPos, None, "Max=" + str(max), java.awt.Color.LIGHT_GRAY)
        p1.addMarker(minPos, None, "Min=" + str(min), java.awt.Color.LIGHT_GRAY)
        
#        plots[0].addMarker(25, None, "Mark", java.awt.Color.LIGHT_GRAY)        
        
        #IMPORTANT: if the test was successful, write the report into the variables ret and success.
        #for example, write the following:
        ret = "Example Test successful"
        success = True        
        #once the test is finished, no need to do anything. The code below yours will do the rest. 
        ################ End of Example ##########
      
################ 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
        ret = 'Test stopped by user.'
        success = False
        test.sendFeedback(ret, success)
    except:
        #generic error handler
        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 ####
