# Test name: Betriebsmode (old caRPSTest test #1)
# betriebsmode
# 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
    # 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:
        test = TestingTool(testName, testPath, DEVICE, params)

################ END OF Init #####################
######### WRITE YOUR CODE HERE BELOW #############

        """
        All the code in this section # WRITE YOUR CODE HERE BELOW # is just an example and can be modified/deleted.
        It must be indented to the same level as this comment.
        -----------------------------------
                   GETTING INPUTS:
        -----------------------------------
        If needed, the following methods are available:

        test.getPath()        string, path of this test file
        test.getName()        string, name of this test
        test.getDeviceName()  string, device for which the test must run (typically it is the beginning of a process variable name)
        test.getPlotName()    string, name to be given to the plot when using setPlotTitle(). Example: scan.setPlotTitle(test.getPlotName())
        -----------------------------------
                   GETTING TEST PARAMETERS:
        -----------------------------------
        if you need to get parameters for the test, use:

        myParamValue = test.getParam('myParamName')

        the calls to getParam are added to the code automatically, one per parameter, when creating the new test.
        NOTE:  Casting may be necessary.
        See the test config for the list of parameters specific to the test.
        -----------------------------------
                   SETTING OUTPUTS:
        -----------------------------------
        When the test has ended (error or success), this method must be called in order to return to pshell:

        test.sendFeedback(ret,success)

        ret        string,   a text summarizing the result of the test.
        success    bool,     True = test successful. False = test failed.
        -----------------------------------
                   LOG INFO:
        -----------------------------------
        when some information must be shown on the log on pshell, use the following line:
        test.log('text to log')
        """


        # print the list of parameters passed. If any error, stop and send feedback.
        test.log("Test " + test.getName() + " for " + test.getDeviceName() )
        try:
            test.log("Running test with the following parameters:")
            test.printParams()
            # fetch paramenters
            rpsChName14   = (test.getParam('rpsCh14')) 
            rpsChName58   = (test.getParam('rpsCh58')) 
            expectedVal14 = (test.getParam('expectedVal14')) 
            expectedVal58 = (test.getParam('expectedVal58')) 
            mode          = (test.getParam('mode')) 
            setGetDelay   = float(test.getParam('setGetDelay')) ; 
        except:
            import traceback
            # test failed, write the report into the variables ret and success and send feedback:
            ret = 'Could not retrieve testing parameters - ' + traceback.format_exc()
            success = False
            test.sendFeedback(ret, success)
            return

        # now try with data from real device: this part will most probably fail: correct the PV names with existing ones.
        rpsMask14 = 0x4440  # mask for outputs 2-4
        rpsMask58 = 0x0004  # mask for output 5        
        ilk = Interlock()
        ilk.setInterlockMode(mode)
        sleep(setGetDelay)
        ilk.masterReset()
        sleep(setGetDelay)
        modeRead = ilk.getInterlockMode();
        if not modeRead:
            ret = 'No mode received'
            success = False
            test.sendFeedback(ret, success)
            return   
        try:
            modePresent = modeRead.index(mode)
        except:
            modePresent = -1
            ret = 'Could not set mode ' + mode
            success = False
            test.sendFeedback(ret, success)
            return 
        try:
            # set up connection to channels. "type" of data can be "d" (= double), "l" (= long).
            # outputs 1-4
            rpsCh14 = Channel(rpsChName14, type='d')
            # outputs 5-8
            rpsCh58 = Channel(rpsChName58, type='d')
            
            rpsVal14 = rpsCh14.get()
            rpsVal58 = rpsCh58.get()
            
            success = True
            if ((rpsVal14 & rpsMask14) == expectedVal14):
                ret = 'Interlocks outputs (1-4) of ' + rpsChName14 + ': ' + rpsVal14 + ' as expected'
            else: 
                ret = 'Interlocks outputs (1-4) of ' + rpsChName14 + ': ' + rpsVal14 + ' was expected: ' + expectedVal14
                success = False

            if ((rpsVal58 & rpsMask58) == expectedVal58):
                ret = ret + '\nInterlocks outputs (5-8) of ' + rpsChName58 + ': ' + rpsVal58 + ' as expected'
            else: 
                ret = ret + '\nInterlocks outputs (5-8) of ' + rpsChName58 + ': ' + rpsVal58 + ' was expected: ' + expectedVal58
                success = False
        except:
            import traceback
            # prepare return information: return text:
            ret = 'Unable to connect to channel - ' + traceback.format_exc()
            # prepare return information: return success:
            success = False
            # send return information:
            test.sendFeedback(ret, success)
            return

        # Closing channels: all channels that were opened with Channel() must be closed before exit:
        rpsCh14.close()
        rpsCh58.close()

        # once the test is finished, no need to do anything. The code below yours will do the rest.

################ 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 ####
# Indent to end left
# def yourCustomFunction:
