#!/usr/bin/python

import sys
sys.path.append("../ei2c")
from ei2c import *
import ei2cdefine
from pulsetest import *
import binascii

if __name__ == "__main__":
    # Get the IP, user and password for the ELMA crate from ei2cdefine.py
    ip   = ei2cdefine.HNAME
    user = ei2cdefine.USER
    pwd  = ei2cdefine.PWD
    testelma = EI2C(ip, user, pwd)
    testelma.open()

    # Ask for slot number
    while 1:
        try:
            slot = raw_input("Slot no.: ")
            slot = int(slot)
            break
        except TypeError as e:
            print("Please input a decimal slot number.")
        except SlotError as e:
            print(e.strerror)
        except KeyboardInterrupt:
            sys.exit();
        except:
            print("Unexpected error: ", sys.exc_info()[0])

    # Get board ID and gateware version, fail if incorrect
    bloid = testelma.read(slot, 0x00)
    fwvers = testelma.read(slot, 0x04) & 0xFF

    if ( bloid != 0x54424c4f ):
        print("Wrong board ID (%s)" % binascii.unhexlify("%s" % \
            "{0:x}".format(bloid)))
        sys.exit(1)
    if ( fwvers != 0xff ):
        print("Wrong version number (0x%02x)" % fwvers)
        sys.exit(1)

    # Get channel counters
    i = testelma.read(slot, C1IREG)
    o = testelma.read(slot, C1OREG)
    print("CH1 / i: %d / o: %d" % (i, o))
    i = testelma.read(slot, C2IREG)
    o = testelma.read(slot, C2OREG)
    print("CH2 / i: %d / o: %d" % (i, o))
    i = testelma.read(slot, C3IREG)
    o = testelma.read(slot, C3OREG)
    print("CH3 / i: %d / o: %d" % (i, o))
    i = testelma.read(slot, C4IREG)
    o = testelma.read(slot, C4OREG)
    print("CH4 / i: %d / o: %d" % (i, o))
    i = testelma.read(slot, C5IREG)
    o = testelma.read(slot, C5OREG)
    print("CH5 / i: %d / o: %d" % (i, o))
    i = testelma.read(slot, C6IREG)
    o = testelma.read(slot, C6OREG)
    print("CH6 / i: %d / o: %d" % (i, o))
