#! /usr/bin/env python

import sys
import time
import datetime
import epics.pv
from epics.ca import ChannelAccessException
import getopt

def getRetry(Pv, PvName, retries):
    retryCount = 0
    done = False
    value = 0
    while (not done):
        value = Pv.get(None, False, True, 20)
        if (value == None):
            retryCount = retryCount + 1
            print "Retrying " + PvName + "."
            if (retryCount == retries):
                raise "Failed to retrieve " + PvName + " value."
        else:
            done = True
    return value


def testThreshold(thresPv, thresPvName, thres, statePv, statePvName, stateGoodMsg, stateGood,
                  stateBadMsg, stateBad, retries, currentLoss):
    if (extra_verbose):
        print "thresPvName=" + thresPvName

    retryCount = 0
    done = False

    while (not done):
        thresPv.put(thres)
        time.sleep(1)
        currentState = getRetry(statePv, statePvName, 10)

        if (verbose):
            sys.stdout.write(str(thresPvName) + "\t= " + str(currentLoss) + " -> " + str(thres) + "\t >>> " + statePvName + " >> ")

        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 PV " + thresPvName
                done = True
                return False

        retryCount = retryCount + 1

    return True
        
def testChannel(rootPv, thresPv, thresPvName, lossPv, lossPvName, type, signal, offset, results):
    if (verbose):
        print "==== " + rootPv + " " + type + " threshold ===="

    # Get current threshold value
    currentLoss = getRetry(lossPv, lossPvName, 10)
    currentThreshold = getRetry(thresPv, thresPvName, 10)

    # Current channel reading
    if (verbose):
        print lossPvName + "\t= " + str(currentLoss)

    # Current threshold
    if (verbose):
        print thresPvName + "\t= " + str(currentThreshold)

    # If the signal is from a PIC, remove the P1/P2/P3 from the beginning of the fault PV
    # and the name of the PV does not have '_' between the LOSS and L as in the BLM faults
    faultPvName = thresPvName
    if (faultPvName.find(':P1_') > 0):
        faultPvName = faultPvName.replace('P1_','')
        faultPvName = faultPvName.replace('LOSS_','LOSS')
        faultPvName = faultPvName.replace('1_','1')
        faultPvName = faultPvName.replace('10_','10')
        faultPvName = faultPvName.replace('30_','30')
        faultPvName = faultPvName.replace('60_','60')
    elif (faultPvName.find(':P2_') > 0):
        faultPvName = faultPvName.replace('P2_','')
        faultPvName = faultPvName.replace('LOSS_','LOSS')
        faultPvName = faultPvName.replace('1_','1')
        faultPvName = faultPvName.replace('10_','10')
        faultPvName = faultPvName.replace('30_','30')
        faultPvName = faultPvName.replace('60_','60')
    elif (faultPvName.find(':P3_') > 0):
        faultPvName = faultPvName.replace('P3_','')
        faultPvName = faultPvName.replace('LOSS_','LOSS')
        faultPvName = faultPvName.replace('1_','1')
        faultPvName = faultPvName.replace('10_','10')
        faultPvName = faultPvName.replace('30_','30')
        faultPvName = faultPvName.replace('60_','60')

    # Define if thresholds should go up or down
    if (type == "low"):
        thresBad = currentLoss + offset
        thresGood = currentLoss - offset
        linkProcessorCurrentState = faultPvName + "_MPSC"
    else:
        thresBad = currentLoss - offset
        thresGood = currentLoss + offset
        linkProcessorCurrentState = faultPvName + "_MPSC"

    # If testing High Voltage, the Link Processor PV starts with HVPS instead of BLM
    if (signal.find('HV') == 0):
        if (extra_verbose):
            print "Replacing BLM with HVPS in PV name " + linkProcessorCurrentState
        linkProcessorCurrentState = linkProcessorCurrentState.replace('BLM','HVPS')
        linkProcessorCurrentState = linkProcessorCurrentState.replace('HV_CTL_L','LOW')
        linkProcessorCurrentState = linkProcessorCurrentState.replace('HV_CTL_H','HIGH')

    if (extra_verbose):
        print "Connecting to PV " + linkProcessorCurrentState

    linkProcessorCurrentStatePv = epics.PV(linkProcessorCurrentState, None, 'native', None, None, 10, False)
    linkProcessorCurrentStatePv.wait_for_connection(60)

    result={'value':currentLoss,
            'thres_type':type,
            'thres_value':thresGood,
            'fault':'None',
            'result':'FAIL'}
            
    # Write thresholds that don't generate faults
    stateGoodMsg = "IS_OK"
    stateGood = 1

    # Exceed fault is labeled differently for PIC and BLM
    stateBadMsg = "IS_EXCEEDED (FAIL)"
    if (linkNodeType == 'PIC'):
        stateBadMsg = "EXCEEDED (FAIL)"
        
    if (signal.find('HV') == 0):
        stateBadMsg='IS_FAULTED (FAIL)'
    stateBad = 0
    if (testThreshold(thresPv, thresPvName, thresGood, linkProcessorCurrentStatePv, linkProcessorCurrentState,
                      stateGoodMsg, stateGood, stateBadMsg, stateBad, 20, currentLoss) == True):
        result['result']='PASS'
        result['fault']='IS_OK'
    else:
        result['result']='FAIL'
        result['fault']='IS_EXCEEDED'
        if (linkNodeType == 'PIC'):
            result['fault'] = "EXCEEDED"
        
        if (signal.find('HV') == 0):
            result['fault']='IS_FAULTED'

    results[thresPvName + '-in-limits-' + type] = result
    result['thres_value'] = thresBad

    # Write thresholds that genarate faults
    stateGoodMsg = "IS_EXCEEDED"
    if (linkNodeType == 'PIC'):
        stateGoodMsg = "EXCEEDED"        
    if (signal.find('HV') == 0):
        stateGoodMsg='IS_FAULTED'
    stateGood = 0
    stateBadMsg = "IS_OK (FAIL)"
    stateBad = 1
    if (testThreshold(thresPv, thresPvName, thresBad, linkProcessorCurrentStatePv, linkProcessorCurrentState,
                      stateGoodMsg, stateGood, stateBadMsg, stateBad, 20, currentLoss) == True):
        result['result']='PASS'
        result['fault']='IS_EXCEEDED'        
        if (linkNodeType == 'PIC'):
            result['fault'] = 'EXCEEDED'
        if (signal.find('HV') == 0):
            result['fault']='IS_FAULTED'
    else:
        result['result']='FAIL'
        result['fault']='IS_OK'

    results[thresPvName + '-out-limits-' + type] = result

    # Restore original threshold
    thresPv.put(currentThreshold)

    return results

def checkChannel(basePvName, signal, results, thresholdOffset):
    offset = thresholdOffset
    
    if (signal.find('HV') == 0):
        offset = 100
        signal = 'HV_CTL'
    
    if (verbose):
        print basePvName + ' ' + signal
    signalPvName = basePvName + ":" + signal
    thresPvName = signalPvName + '_L'

    if (extra_verbose):
        print "Connecting to PV " + thresPvName

    thresPv = epics.PV(thresPvName, None, 'native', None, None, 30, False)
    thresPv.wait_for_connection(60)

    if (extra_verbose):
        print "Connecting to PV " + signalPvName

    signalPv = epics.PV(signalPvName, None, 'native', None, None, 30, False)
    signalPv.wait_for_connection(60)
        
    results = testChannel(basePvName, thresPv, thresPvName, signalPv, signalPvName, "low", signal, offset, results)

    thresPvName = signalPvName + '_H'
    thresPv = epics.PV(thresPvName, None, 'native', None, None, 30, False)
    thresPv.wait_for_connection(60)
    
    results = testChannel(basePvName, thresPv, thresPvName, signalPv, signalPvName, "high", signal, offset, results)

    return results


def printResult(channel, result):
    print channel + \
          "\tvalue=" + str(result['value']) + \
          "\tthres_type=" + result['thres_type'] + \
          "\tthres_value=" + str(result['thres_value']) + \
          "\tfault=" + result['fault'] + \
          "\tresult=" + result['result']
          

def usage(cmd):
    print("Usage: %s <options>" % cmd)
    print("  -h: print this help")
    print("  -v: verbose")
    print("  -t <type>: BLM or PIC")
    print("  -f <file>: text file channels to be tested (one channel per line)")
    print("             for PIC files the PIC module must follow the channel")
    print("             e.g. \'PICM:IN20:665 1\'")
    print("  -c <channel>: channel to be tested (e.g. BLM:UND1:3021)")
    print("  -s <signal>: PED/LOSS/LOSS_1/LOSS_10/LOSS_30/LOSS_60/HV.")
    print("               If not specified all signals are tested")
    print("               PED/HV signals are not available in PIC link nodes")
    print("  -p 1,2,3: PIC module, must be specified if type is PIC")
    print("            and the -c option is used")
    print("  -o <value>: how much the threshold offset should be set (default is 1)")
    
total = len(sys.argv)
cmdargs = str(sys.argv)

try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:f:c:s:vxp:t:o:", ["help"])
except getopt.GetoptError as err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage(str(sys.argv[0]))
    sys.exit(2)
    
output = None
verbose = False
extra_verbose = False
channelFile = None
channelName = None
signalType = None
picModule = None
linkNodeType = None
thresholdOffset = 1

for o, a in opts:
    if o == "-v":
        verbose = True
    elif o == "-x":
        extra_verbose = True
    elif o in ("-h", "--help"):
        usage(str(sys.argv[0]))
        sys.exit()
    elif o in ("-o"):
        thresholdOffset = int(a)
    elif o in ("-f", "--file"):
        channelFile = a
    elif o in ("-c", "--channel"):
        channelName = a
    elif o in ("-s", "--signal"):
        signalType = a
    elif o in ("-p", "--pic"):
        picModule = a
    elif o in ("-t", "--type"):
        linkNodeType = a
    else:
        assert False, "unhandled option"
        # ...

if (linkNodeType == None):
    print("ERROR: option -t must be specified")
    usage(str(sys.argv[0]));
    sys.exit(-1)

if (linkNodeType != 'PIC' and linkNodeType != 'BLM'):
    print("ERROR: invalid link node type \'" + linkNodeType + "\'")
    usage(str(sys.argv[0]));
    sys.exit(-1)    

if (linkNodeType == 'PIC' and channelName != None and picModule == None):
    print("ERROR: please specify a PIC module with the -p <module> option")
    usage(str(sys.argv[0]));
    sys.exit(-1)    
    
if (linkNodeType == 'PIC'):
    signals=['LOSS','LOSS_1','LOSS_10','LOSS_30','LOSS_60']
    if (channelFile == None and ((int(picModule) < 1 or int(picModule) > 3))):
        print("ERROR: invalid pic module \'" + picModule + "\'")
        usage(str(sys.argv[0]));
        sys.exit(-1)            
else:
    signals=['PED','LOSS','LOSS_1','LOSS_10','LOSS_30','LOSS_60','HV']#,'TEST','TEST_1']

if (not signalType in signals and signalType != None):
    print("ERROR: invalid signal type \'" + signalType + "\'")
    usage(str(sys.argv[0]));
    sys.exit(-1)    

results={}

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

# Test multiple channels, defined in the input file
if (channelFile != None):
    print "=== Start timestamp: " + st
    f = open(channelFile, "r")
    for line in f:
        basePvName = line.strip()
        if (linkNodeType == 'PIC'):
            splitLine = basePvName.split(' ')
            if (len(splitLine) != 2):
                print("ERROR: found line \'" + line + "\', expected \'<channel> <module>\'")
                usage(str(sys.argv[0]));
                sys.exit(-1)    
            basePvName = splitLine[0]
            picModule = splitLine[1]

            if (int(picModule) < 1 or int(picModule) > 3):
                print("ERROR: found line \'" + line.strip() + "\', invalid pic module \'" + picModule + "\'")
                usage(str(sys.argv[0]));
                sys.exit(-1)    

        if (signalType == None):
            for signal in signals:
                if (picModule != None):
                    signal = 'P' + picModule + '_' + signal
                results = checkChannel(basePvName, signal, results, thresholdOffset)
        else:
            results = checkChannel(basePvName, signalType, results, thresholdOffset)
    f.close()

# Test single channel, as specified by the -c option
elif (channelName != None):
    print "=== Start timestamp: " + st
    if (signalType == None):
        for signal in signals:
            if (picModule != None):
                signal = 'P' + picModule + '_' + signal
            # Does not test HV if not specified
            if (signal != 'HV'):
                results = checkChannel(channelName, signal, results, thresholdOffset)
    else:
        if (picModule != None):
            signalType = 'P' + picModule + '_' + signalType
        results = checkChannel(channelName, signalType, results, thresholdOffset)
            
else:
    usage(str(sys.argv[0]));
    sys.exit(-1)

ts2 = time.time()
st = datetime.datetime.fromtimestamp(ts2).strftime('%Y-%m-%d %H:%M:%S')

print "=== End timestamp: " + st
print ">>> Test duration: " + str(ts2 - ts) + " seconds."
    
failures = False
for key in results.keys():
    if (results[key]['result'] == 'FAIL'):
        failures = True

if (failures == True):
    print("=== TEST FAILED: check the following channels ===")
    for key in results.keys():
        if (results[key]['result'] == 'FAIL'):
            failures = True
            printResult(key, results[key])
    sys.exit(-1)
else:
    print("=== PASSED! ===")


