#!/usr/bin/python
#===============================================================================
# CERN (BE-CO-HT)
# Manually trigger a pulse
#===============================================================================
# author: Theodor Stana (t.stana@cern.ch)
#         Maciej Suminski (maciej.suminski@cern.ch)
#
# date of creation:
#
# version: 1.1
#
# description:
#   This script can be used to manually trigger a pulse on the CONV-TTL-BLO
#   channel of choice.
#
#===============================================================================
# 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:
#    2017-02-02    M. Suminski          Updated mem map to match v4 gateware
#    2017-02-17    M. Suminski          Use SLOT configuration from ei2cdefine
#===============================================================================
#  TODO: -
#===============================================================================
import time
import sys
import time
sys.path.append("../ei2c")
from ei2c import *
import ei2cdefine
sys.path.append("..")
import convttl_regs as regs


if __name__ == "__main__":

    # Get the IP, user and password for the ELMA crate from either user input,
    # or ei2cdefine.py
    if (ei2cdefine.ENABLED):
        ip   = ei2cdefine.HNAME
        user = ei2cdefine.USER
        pwd  = ei2cdefine.PWD
        slot = ei2cdefine.SLOT
    else:
        ip   = raw_input("ELMA crate IP or hostname : ")
        user = raw_input("ELMA crate user name      : ")
        pwd  = raw_input("ELMA crate password       : ")
        slot = int(raw_input("ELMA crate slot number    : "))
    testelma = EI2C(ip, user, pwd)
    testelma.open()

    # Print which board is detected in the selected slot
    bid = testelma.get_bid(slot)

    # Ask for which channel to trigger on
    chan = input("chan (1..6): ")

    # Send the magic sequence & the channel number
    sequence = (0xde, 0xad, 0xbe, 0xef, chan)  # password and then channel
    for b in sequence:
        testelma.write(slot, regs.CR, (b << 2) & 0x3FC)

    testelma.close()
