#!/usr/bin/python
#===============================================================================
# CERN (BE-CO-HT)
# High frequency Pulse test script
#===============================================================================
# author: denia Bouhired (denia.bouhired@cern.ch)
#
# date of creation: 26 October 2016
#
# version: 1.1
#
# description:
#   This script works in conjunction with the pulsetest (v15.15) FPGA gateware
#   and drives the pulse generators to generate pulses as per the user's desire.
#   It is a modified version of  pulsetest.py, in that it allows for pulse width
#   selection and stops after a set number of pulses, not after a predefined time.
#
#===============================================================================
# GNU LESSER GENERAL PUBLIC LICENSE
#===============================================================================
# This source file is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version. This source is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details. You should have
# received a copy of the GNU Lesser General Public License along with this
# source; if not, download it from http://www.gnu.org/licenses/lgpl-2.1.html
#===============================================================================
# last changes:
#    2016-10-26    Denia Bouhired
#===============================================================================
#  TODO: -
#===============================================================================
import time
import sys
import time
sys.path.append("../ei2c")
from ei2c import *
import ei2cdefine
import binascii

#Define pulsetest gateware FPGA memory space

IDREG = 0x00
FWVREG = 0x04
C1IREG = 0x100
C1OREG = 0x104
C2IREG = 0x108
C2OREG = 0x10C
C3IREG = 0x110
C3OREG = 0x114
C4IREG = 0x118
C4OREG = 0x11C
C5IREG = 0x120
C5OREG = 0x124
C6IREG = 0x128
C6OREG = 0x12C
CNTRST = 0X130
CHENREG = 0x200
C1DELREG = 0x204
C2DELREG = 0x208
C3DELREG = 0x20C
C4DELREG = 0x210
C5DELREG = 0x214
C6DELREG = 0x218
C1WDTHREG = 0x21C
C2WDTHREG = 0x220
C3WDTHREG = 0x224
C4WDTHREG = 0x228
C5WDTHREG = 0x22C
C6WDTHREG = 0x230
C1FREQREG = 0x234
C2FREQREG = 0x238
C3FREQREG = 0x23C
C4FREQREG = 0x240
C5FREQREG = 0x244
C6FREQREG = 0x248

CTB_CLK_PER = 50*(10**(-9))             # 50ns clock period
MAXFREQ = 500000                        # Modified to 500kHz

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)

    # Reset chan. counters
    testelma.write(slot, CHENREG, 0x00);
    testelma.write(slot, CNTRST, 1);
    testelma.write(slot, CNTRST, 0);

    # First, setup the channel enable variable
    chen = 0x00;
    
    # Setup channel output pulse widths to 1.2us
    pwidth = 0.25
    testelma.write(slot, C1WDTHREG, pwidth*(10**(-6))/CTB_CLK_PER)
    testelma.write(slot, C2WDTHREG, pwidth*(10**(-6))/CTB_CLK_PER)
    testelma.write(slot, C3WDTHREG, pwidth*(10**(-6))/CTB_CLK_PER)
    testelma.write(slot, C4WDTHREG, pwidth*(10**(-6))/CTB_CLK_PER)
    testelma.write(slot, C5WDTHREG, pwidth*(10**(-6))/CTB_CLK_PER)
    testelma.write(slot, C6WDTHREG, pwidth*(10**(-6))/CTB_CLK_PER)

    # Setup channel delays and frequencies
    farr = [0,0,0,0,0,0]

    print("")
    while 1:
        try:
            channum = input ("Output channel (1 to 6): ")
            
            freq = input("Channel freq (Hz): ")
            if (freq == 0):
                    print("  Channel not enabled")
            else
                    chen |= (1 << 0)
                    if (freq > MAXFREQ):
                            freq = MAXFREQ
                            print("  Automatically setting channel frequency to %d Hz" % MAXFREQ)
                    farr[0] = freq
                    freq = 1/(freq * CTB_CLK_PER)

                    if channum = 1
                            testelma.write(slot, C1FREQREG, int(freq))
                    elif channum = 2
                            testelma.write(slot, C2FREQREG, int(freq))
                    elif channum = 3
                            testelma.write(slot, C3FREQREG, int(freq))
                    elif channum = 4
                            testelma.write(slot, C4FREQREG, int(freq))
                    elif channum = 5
                            testelma.write(slot, C5FREQREG, int(freq))
                    elif channum = 6
                            testelma.write(slot, C6FREQREG, int(freq))
                    else
                            raise Exception
                    break
            except KeyboardInterrupt:
                sys.exit()
            except:
                print("    There are only 6 output channels, select an integer between 1 and 6 !")
            
        #print(freq)
        #print(hex(int(freq)))

                
# Ask how long to run the test
    print("")
    print("How many pulses would you like to generate?")
    while 1:
        try:
            ptotal = raw_input("  Number of pulses: ")
            ptotal = int(ptotal)
            if (ptotal < 0):
                raise Exception
            break
        except KeyboardInterrupt:
            sys.exit()
        except:
            print("    Number of pulses is a decimal >=1")


       while 1:

                    if channum = 1
                            pcnt=testelma.read(slot, C1IREG)
                    elif channum = 2
                            pcnt=testelma.read(slot, C2IREG)
                    elif channum = 3
                            pcnt=testelma.read(slot, C3IREG)
                    elif channum = 4
                            pcnt=testelma.read(slot, C4IREG)
                    elif channum = 5
                            pcnt=testelma.read(slot, C5IREG)
                    elif channum = 6
                            pcnt=testelma.read(slot, C6IREG)
                    else
                            raise Exception
                    break
                
                    if ptotal=pcnt
                    
                
           testelma.read(slot, C1IREG)



