#! /usr/bin/env python

#
# Execute the following shell command to get a list of channels for LN37:
#
#
#[lpiccoli@cdlx22 MPS]$ egrep -e "LOSS_L" /afs/slac/g/lcls/epics/iocTop/MachineProtection/MpsLinkNodeApp-MAIN_TRUNK/db/mpsUND1MP14.blm_template | grep Soft | cut -d" " -f23 | cut -d"," -f 1 | sort -t":" -n -k3 | grep -v ":00" > LN37.dat
# [lpiccoli@cdlx22 MPS]$ cat LN37.dat | sed -e 's/LOSS_L/LOSS_H/g' >> LN37.dat
#
import sys
import time
import epics.pv
import getopt
from epics.ca import ChannelAccessException
from epics import ca

failedChannels=[]

def testThreshold(thresPv, thres, statePv, stateGoodMsg, stateGood,
                  stateBadMsg, stateBad, retries, verbose):
    retryCount = 0
    done = False

    while (not done):
        epics.PV(thresPv).put(thres)
        ca.pend_io(60.0)
        
        time.sleep(1)
        try:
            currentState = epics.PV(statePv).get()
            ca.pend_io(60.0)
        except ChannelAccessException:
            if (verbose):
                print "Skipping channel, please repeat test..."
            failedChannels.append(thresPv)
            return

        if (verbose):
            sys.stdout.write("Threshold " + str(thres) + " MPS State (" + statePv + ") is ")
        if (currentState == stateGood):
            if (verbose):
                sys.stdout.write(stateGoodMsg)
        else:
            if (verbose):
                sys.stdout.write(stateBadMsg)
            # If epics.PV().get() returns "None" it means there was
            # some problem getting the value
            if (currentState == None):
                if (verbose):
                    sys.stdout.write(" ... failed to get PV value.")
                currentState = stateBad
            
        if (currentState == stateBad):
            if (verbose):
                print "... retry"
        else:
            done = True
            if (verbose):
                print ""

        if (not done):
            if (retryCount >= retries):
                if (verbose):
                    print "FAILED after " + str(retries) + " retries. Check PVs " + thresPv + " and " + statePv
                failedChannels.append(thresPv)
                done = True

        retryCount = retryCount + 1
        
        
def testChannel(rootPv, thresPv, lossPv, type, verbose, suffix):
    if (verbose):
        print "==== " + rootPv + " " + type + " threshold (" + suffix + ") ===="

    # Get current threshold value
    try:
        currentLoss = epics.PV(lossPv).get()
        ca.pend_io(60.0)
        currentThreshold = epics.PV(thresPv).get()
        ca.pend_io(60.0)
    except ChannelAccessException:
        if (verbose):
            print "Skipping channel, please repeat test..."
        failedChannels.append(thresPv)
        return

    if (currentLoss == None or currentThreshold == None):
        if (verbose):
            print "Skipping channel, please repeat test..."
        failedChannels.append(thresPv)
        return

    if (verbose):
        print "Current loss:      " + str(currentLoss)
        print "Current threshold: " + str(currentThreshold)
    
    # Define if thresholds should go up or down
    if (type == "low"):
        thresBad = currentLoss + 1
        thresGood = currentLoss - 1
        linkProcessorCurrentState = rootPv + ":" + suffix + "_L_MPSC"
    else:
        thresBad = currentLoss - 1
        thresGood = currentLoss + 1
        linkProcessorCurrentState = rootPv + ":" + suffix + "_H_MPSC"

    # Write thresholds that don't generate faults
    testThreshold(thresPv, thresGood, linkProcessorCurrentState,
                  "IS_OK", 1, "IS_EXCEEDED (FAIL)", 0, 4, verbose)

    # Write thresholds that genarate faults
    testThreshold(thresPv, thresBad, linkProcessorCurrentState,
                  "IS_EXCEEDED", 0, "IS_OK (FAIL)", 1, 4, verbose)

    # Restore original threshold
    epics.PV(thresPv).put(currentThreshold)
    ca.pend_io(60.0)

def isTimingChannel(rootPv):
    try:
        epics.PV(rootPv + ":TIMING").get
        ca.pend_io(60.0)
        if (x == None):
            return False
    except:
        return True
    return True

def testChannelAll(rootPv, verbose):
    failures = len(failedChannels)
    if (lossOnly or allTests):
        # High Test
        thresHighPv = rootPv + ":LOSS_H"
        lossPv = rootPv + ":LOSS"
        type = "high"
        testChannel(rootPv, thresHighPv, lossPv, type, verbose, "LOSS")

        # Low Test
        thresLowPv = rootPv + ":LOSS_L"
        lossPv = rootPv + ":LOSS"
        type = "low"
        testChannel(rootPv, thresLowPv, lossPv, type, verbose, "LOSS")

    if (pedOnly or allTests):
        # High Test (PED)
        thresHighPv = rootPv + ":PED_H"
        lossPv = rootPv + ":LOSS"
        type = "high"
        testChannel(rootPv, thresHighPv, lossPv, type, verbose, "PED")

        # Low Test (PED)
        thresLowPv = rootPv + ":PED_L"
        lossPv = rootPv + ":LOSS"
        type = "low"
        testChannel(rootPv, thresLowPv, lossPv, type, verbose, "PED")
    
    if (testOnly or allTests):
        str="TEST"
        try:
            x = epics.PV(rootPv + ":" + str).get()
            ca.pend_io(60.0)
            if (x == None):
                if (isTimingChannel(rootPv)):
                    str="TIMING"
                else:
                    str="HRTBT"
                
        except ChannelAccessException:
            if (verbose):
                print "Skipping channel, please repeat test..."
            failedChannels.append(thresPv)
            return False

        # High Test (TEST)
        thresHighPv = rootPv + ":" + str + "_H"
        lossPv = rootPv + ":LOSS"
        type = "high"
        testChannel(rootPv, thresHighPv, lossPv, type, verbose, str)

        # Low Test (TEST)
        thresLowPv = rootPv + ":" + str + "_L"
        lossPv = rootPv + ":LOSS"
        type = "low"
        testChannel(rootPv, thresLowPv, lossPv, type, verbose, str)

    if (failures != len(failedChannels)):
        return False
    else:
        return True

def unlatch(rootPv, verbose):
    if (lossOnly or allTests):
        pv = rootPv + ":LOSS_L_UNLH" 
        if (verbose):
            print "Unlatching " + pv
            epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_1_L_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_10_L_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_30_L_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_60_L_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_H_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_1_H_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_10_H_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_30_H_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":LOSS_60_H_UNLH" 
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

    if (testOnly or allTests):
        pv = rootPv + ":TEST_L_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":TEST_1_L_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":TEST_H_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":TEST_1_H_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

    if (pedOnly or allTests):
        pv = rootPv + ":PED_L_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":PED_1_L_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":PED_H_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

        pv = rootPv + ":PED_1_H_UNLH"
        if (verbose):
            print "Unlatching " + pv
        epics.PV(pv).put(1)

def usage():
    print "Usage: " + sys.argv[0] + "[opt] [-f file] [-c channel]"
    print ""
    print "Options:"
    print "  -U: unlatch faults for channel (-c option) or channels (-f option) - no TEST"
    print "  -u: unlatch faults for channels before testing"
    print "  -f <file>: file containing one channel per line (e.g. BLM:UND1:3321)"
    print "  -c <channel>: test one channel (PED,TEST,LOSS)"
    print "  -l: check LOSS PVs"
    print "  -p: check PED PVs"
    print "  -t: check TEST PVs"
    print ""
    print "Examples:"
    print "  " + sys.argv[0] + " -f LN37.dat"
    print "  " + sys.argv[0] + " -c BLM:UND1:3321"
    print "  " + sys.argv[0] + " -u -c BLM:UND1:3321"
    print "  " + sys.argv[0] + " -U -c BLM:UND1:3321"
    print "  " + sys.argv[0] + " -U -f LN37.dat"
    print "  " + sys.argv[0] + " -l -c BLM:UND1:3321"

#=======================================================================


try:
    opts, args = getopt.getopt(sys.argv[1:], 'f:hvc:uUltp', ['file=', 'help', 'verbose', 'channel=', 'unlatch', 'unlatch-only', 'loss', 'test', 'pedestal'])
except getopt.GetoptError:
    usage()
    sys.exit(-1)

fileName = ''
channel = ''
verbose = False
unlatchOnly = False
unlatchBefore = False
lossOnly = False
pedOnly = False
testOnly = False
allTests = False

for opt, arg in opts:
    if opt in ('-h', '--help'):
        usage()
        sys.exit(0)
    elif opt in ('-f', '--file'):
        fileName = arg
    elif opt in ('-v', '--verbose'):
        verbose = True
    elif opt in ('-c', '--channel'):
        channel = arg
    elif opt in ('-u', '--unlatch'):
        unlatchBefore = True
    elif opt in ('-U', '--unlatch-only'):
        unlatchOnly = True
    elif opt in ('-l', '--loss'):
        lossOnly = True
    elif opt in ('-p', '--pedestal'):
        pedOnly = True
    elif opt in ('-t', '--test'):
        testOnly = True
    else:
        usage()
        sys.exit(0)

if (lossOnly == False and
    pedOnly == False and
    testOnly == False) :
    allTests = True

if fileName == '' and channel == '':
    usage()
    sys.exit(0)

if fileName != '':
    f = open(fileName, "r")

    for line in f:
        rootPv = line.strip()

        if (unlatchOnly or unlatchBefore):
            unlatch(rootPv, verbose)
        if (unlatchOnly == False):
            if (not verbose):
                sys.stdout.write(rootPv)
            if (testChannelAll(rootPv, verbose)):
                if (not verbose):
                    print " ... OK"
            else:
                if (not verbose):
                    print " ... Failed"

    f.close()
        
    print "===="
    if len(failedChannels) > 0:
        print "Please repeat this test, these channels had problems:"
        for pv in failedChannels:
            print pv
    else:
        if (unlatchOnly == False):
            print "PASSED"

if channel != '':
    rootPv = channel.strip()
    
    if (unlatchOnly or unlatchBefore):
        unlatch(rootPv, verbose)
        if (unlatchOnly):
            sys.exit(0)
    testChannelAll(rootPv, verbose)

