#! /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

# Read the LN_TYPE PV to make sure it agrees with the specified type
# e.g. EIOC:UND1:MP14:LN_TYPE
def checkType(location, unit, type, results):
    name = 'EIOC:'
    if (type == 'BLM'):
        name = 'BLM:'
    if (type == 'PIC'):
        name = 'PICM:'
    name = name + location + ':' + unit + ':LN_TYPE'
    if (verbose):
        print "=== Checking Link Node type (" + name + ")"
    typePv = epics.PV(name, None, 'native', None, None, 30, False)
    typePv.wait_for_connection(60)

    result={'PV':name,
            'result':'FAIL'}

    t = getRetry(typePv, name, 10)

    # If the info is not accessed, the char_value returns '1' instead of 'BLM'
    x = typePv.info
    
    if (verbose):
        print "  > " + name + ": " + typePv.char_value
        
    if (typePv.char_value == type):
        result['result'] = 'OK'

    results["TYPE"] = result

    return results

# Check heartbeats, examples:
# IOC heartbeat (EIOC:UND1:MP14:HEARTBEAT)
# QADC heartbeat (BLM:UND1:MP14:ACQ_COUNTER)
# FPGA heartbeat (BLM:UND1:MP14:EVT_COUNTER)
def checkHeartbeat(location, unit, type, counter, results):
    name = 'EIOC:'
    if (type == 'BLM' and counter != 'HEARTBEAT'):
        name = 'BLM:'
    elif (type == 'PIC' and counter != 'HEARTBEAT'):
        name = 'PICM:'
    
    result={'PV':name,
            'result':'FAIL'}

    name = name + location + ':' + unit + ':' + counter
    if (verbose):
        print "=== Checking heartbeat (" + name + ")"

    heartbeatPv = epics.PV(name, None, 'native', None, None, 30, False)
    heartbeatPv.wait_for_connection(60)

    result={'PV':name,
            'result':'FAIL'}

    first_reading = getRetry(heartbeatPv, name, 10)
    if (verbose):
        print '  > First reading of ' + name + ': ' + str(first_reading)
    time.sleep(3)

    second_reading = getRetry(heartbeatPv, name, 10)
    if (verbose):
        print '  > Second reading of ' + name + ': ' + str(second_reading)

    if (first_reading < second_reading):
        result['result'] = 'OK'

    results[counter] = result

    return results

# ID must be the same BLM:UND1:MP14:ROTARY_LN_ID == BLM:UND1:MP14:LN_ID 
def checkLinkNodeID(location, unit, type, results):
    base_name = 'EIOC:'
    if (type == 'BLM'):
        base_name = 'BLM:'
    elif (type == 'PIC'):
        base_name = 'PICM:'

    rotary_name = base_name + location + ':' + unit + ':' + 'ROTARY_LN_ID'
    id_name = base_name + location + ':' + unit + ':' + 'LN_ID'

    result={'PV':rotary_name,
            'result':'FAIL'}

    if (verbose):
        print "=== Checking Link Node IDs (" + rotary_name + ' and ' + id_name + ")"

    rotaryPv = epics.PV(rotary_name, None, 'native', None, None, 30, False)
    rotaryPv.wait_for_connection(60)

    idPv = epics.PV(id_name, None, 'native', None, None, 30, False)
    idPv.wait_for_connection(60)

    rotary_reading = getRetry(rotaryPv, rotary_name, 10)
    if (verbose):
        print '  > Rotary ID ' + rotary_name + ': ' + str(rotary_reading)

    id_reading = getRetry(idPv, id_name, 10)
    if (verbose):
        print '  > Link node ID ' + id_name + ': ' + str(id_reading)

    if (rotary_reading == id_reading):
        result['result'] = 'OK'

    results["ID"] = result

    return results


def usage(cmd):
    print("Usage: %s <options>" % cmd)
    print("  -h: print this help")
    print("  -v: verbose")
    print("  -l <location>: link node location (e.g. UND1)")
    print("  -u <unit>: link node unit (e.g. MP14)")
    print("  -t <type>: link node type (e.g. BLM, PIC, BYKIK)")
    
def printResult(channel, result):
    print channel + \
          "\tPV=" + result['PV'] + \
          "\tresult=" + result['result']

total = len(sys.argv)
cmdargs = str(sys.argv)

try:
    opts, args = getopt.getopt(sys.argv[1:], "hvl:u:t:", ["help", "output="])
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)

# List of Link Node location/units
location_units=['IN20:MP11', 'LI30:MP01', 'MCC0:MP01', 'UND1:MP01', 'UND1:MP03', 'UND1:MP04', 'UND1:MP12', 'UND1:MP13', 'UND1:MP14']
types=['BLM', 'PIC', 'BYKIK']

verbose = False
location = None
unit = None
type = None

for o, a in opts:
    if o == "-v":
        verbose = True
    elif o in ("-h", "--help"):
        usage(str(sys.argv[0]))
        sys.exit()
    elif o in ("-l", "--location"):
        location = a
    elif o in ("-u", "--unit"):
        unit = a
    elif o in ("-t", "--type"):
        type = a
    else:
        assert False, "unhandled option"
        # ...

results={}

if (location == None):
    print "ERROR: Link Node location is missing (-l <location>) option"
    sys.exit(3)

if (unit == None):
    print "ERROR: Link Node location is missing (-u <unit>) option"
    sys.exit(4)

if (type == None):
    print "Error: Link Node type is missing (-t <type>) option"
    sys.exit(7)

location_unit = location + ":" + unit
if (not location_unit in location_units):
    print "ERROR: Invalid location/unit combination \'" + location + ":" + unit
    sys.exit(5)

if (not type in types):
    print "ERROR: Invalid link node type: \'" + type + "\'"
    sys.exit(6)

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

print "=== Start timestamp: " + st

# check type (BLM:UND1:MP14:LN_TYPE)
results = checkType(location, unit, type, results)

# IOC heartbeat (EIOC:UND1:MP14:HEARTBEAT)
counter = 'HEARTBEAT'
results = checkHeartbeat(location, unit, type, counter, results)

# Only BLMs have the QADC/FPGA counters
if (type == 'BLM'):
    # QADC heartbeat (BLM:UND1:MP14:ACQ_COUNTER)
    counter = 'ACQ_COUNTER'
    results = checkHeartbeat(location, unit, type, counter, results)

    # FPGA heartbeat (BLM:UND1:MP14:EVT_COUNTER)
    counter = 'EVT_COUNTER'
    results = checkHeartbeat(location, unit, type, counter, results)

# ID must be the same BLM:UND1:MP14:ROTARY_LN_ID == BLM:UND1:MP14:LN_ID
results = checkLinkNodeID(location, unit, type, results)

# 3.3V BLM:UND1:MP14:P3D3V_MON  (more than 2.8, less than 3.8)
# 5V BLM:UND1:MP14:P5V_MON (more than 4.5 less than 5.5)
# 12V BLM:UND1:MP14:P12V_MON (more than 11, less than 13)
# 24V BLM:UND1:MP14:P24V_MON (more than 23, less than 25)

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! ===")



