#! /usr/bin/env python
# -*- coding: utf-8 -*-

import faster_module_path

import sys

import os, time, signal
import subprocess

import platform

using_distro = False

try :
    import distro
    using_distro = True
except ImportError :
    pass
import py_fastersys

import py_n3_merger_ctrl
import py_qdc_caras_ctrl
import py_adc_mosahr_ctrl
import py_basic_trunk


from py_n3_merger_ctrl import N3_Merger_Ctrl
from py_qdc_caras_ctrl  import QDC_Caras_Ctrl
from py_adc_mosahr_ctrl import ADC_Mosahr_Ctrl
from py_basic_trunk     import Basic_Trunk

from py_qdc_caras_enum  import *
from py_adc_mosahr_enum import *
from py_fastersys_enum import *

daq_ip            = ""
daq_mac           = ""
daq_in1           = 50001

rhb_mac           = ""
rhb_ip            = ""
rhb_in            = 6666

module_ip            = ""
amc_mac           = ""

DB1_type          = ""
DB2_type          = ""
Mother_type       = ""

error             = False
channel_list      = []
number_of_channel = 0

fpga1             = None
fpga2             = None
n3tm              = None
node3_in1         = 40001
node3_in2         = 40002

trunk_ctrl        = None

faster_file       = "/tmp/test_0001.fast"
file_directory    = "/usr/share/faster/hardware_check/"

file_prefix, file_number = faster_file.split("_")
##############################################
def setup_qdc_node(node_ctrl, num, cfg_file):

     node_ctrl.Set_Cfg_File                   (cfg_file)
     node_ctrl.Restore                        ()
     node_ctrl.Node_Setup                     (module_ip, num)
     node_ctrl.Connect                        (0)
     if (module_ip == "192.168.1.204"):
         node_ctrl.Data_Base_Setup            (daq_mac, daq_ip, daq_in1)
     else:
         node_ctrl.Data_Base_Setup            (amc_mac, module_ip, node3_in1)
     node_ctrl.Intro_Base_Setup               (rhb_mac, rhb_ip, rhb_in)
     node_ctrl.Channel_Output_Switches_Setup  (1, False, True, False)
     node_ctrl.Channel_Output_Switches_Setup  (2, False, True, False)
     node_ctrl.Channel_Outputs_To_Intro_Setup (1, False, False, False)
     node_ctrl.Channel_Outputs_To_Intro_Setup (2, False, False, False)
     node_ctrl.All_Outputs_To_Data_Setup      ()
     node_ctrl.Send_Base_Setup                ()
     node_ctrl.Send_Fmin                      ()
     node_ctrl.Send_Channel_Setup             (1)
     node_ctrl.Send_Channel_Setup             (2)

##############################################
def setup_adc_node(node_ctrl, num, cfg_file):

    node_ctrl.Set_Cfg_File                   (cfg_file)
    node_ctrl.Restore                        ()
    node_ctrl.Node_Setup                     (module_ip, num)
    node_ctrl.Connect                        (0)
    if (module_ip == "192.168.1.204"):
        node_ctrl.Data_Base_Setup            (daq_mac, daq_ip, daq_in1)
    else:
        node_ctrl.Data_Base_Setup            (amc_mac, module_ip, node3_in1)
    node_ctrl.Intro_Base_Setup               (rhb_mac, rhb_ip, rhb_in)
    node_ctrl.Channel_Output_Switches_Setup  (1, False, True, False)
    node_ctrl.Channel_Output_Switches_Setup  (2, False, True, False)
    node_ctrl.Channel_Output_Switches_Setup  (3, False, True, False)
    node_ctrl.Channel_Output_Switches_Setup  (4, False, True, False)
    node_ctrl.Channel_Outputs_To_Intro_Setup (1, False, False, False)
    node_ctrl.Channel_Outputs_To_Intro_Setup (2, False, False, False)
    node_ctrl.Channel_Outputs_To_Intro_Setup (3, False, False, False)
    node_ctrl.Channel_Outputs_To_Intro_Setup (4, False, False, False)
    node_ctrl.All_Outputs_To_Data_Setup      ()
    node_ctrl.Send_Base_Setup                ()
    node_ctrl.Send_Fmin                      ()
    node_ctrl.Send_Channel_Setup             (1)
    node_ctrl.Send_Channel_Setup             (2)
    node_ctrl.Send_Channel_Setup             (3)
    node_ctrl.Send_Channel_Setup             (4)


##############################################
def exit_gracefully(signum, frame):
    fpga1.Send_Synchro_Stop ()
    fpga2.Send_Synchro_Stop ()
    n3tm.Send_Synchro_Stop  ()
    fpga1.Send_Synchro_Stop ()
    fpga2.Send_Synchro_Stop ()
    n3tm.Send_Synchro_Stop  ()
    daq.Stop                ()
    sys.exit(1)


##############################################
def signal_arm_msb_t0 (ip) :
    py_fastersys.Signal_Board_Switch (ip, Signal_Function_t.SIGNAL_ARM_MSB_T0, 1)
    py_fastersys.Signal_Board_Switch (ip, Signal_Function_t.SIGNAL_ARM_MSB_T0, 2)


##############################################
def signal_arm_start (ip) :
    py_fastersys.Signal_Board_Switch (ip, Signal_Function_t.SIGNAL_ARM_START, 1)
    py_fastersys.Signal_Board_Switch (ip, Signal_Function_t.SIGNAL_ARM_START, 2)


##############################################
def signal_arm_stop (ip) :
    py_fastersys.Signal_Board_Switch (ip, Signal_Function_t.SIGNAL_ARM_STOP, 1)
    py_fastersys.Signal_Board_Switch (ip, Signal_Function_t.SIGNAL_ARM_STOP, 2)


##############################################
def get_mac_from_ip (arg) :
    ip     = arg
    mac    = ""
    if using_distro :
        ubuntu_distribution = distro.codename ()
        if (ubuntu_distribution != "xenial") :
                cmd    = "netstat -ie | grep -F3 " + ip + " | grep ether | awk '{print $2}'"
        else :
                cmd    = "netstat -ie | grep -B1 " + ip + " | head -n1 | awk '{print $5}'"
    else :
        ubuntu_distribution = platform.dist ()
        if (ubuntu_distribution [2] != "xenial") :
                cmd    = "netstat -ie | grep -F3 " + ip + " | grep ether | awk '{print $2}'"
        else :
                cmd    = "netstat -ie | grep -B1 " + ip + " | head -n1 | awk '{print $5}'"

    answer = subprocess.check_output     (cmd, shell=True).decode ()
    if (answer.count (":") == 5) :
        mac =  answer.replace ("\n","")
    else :
        cmd = "ping -c 1 " + ip
        try :
            answer =  subprocess.check_output (cmd, shell=True).decode ()
            cmd = "arp -a | grep "+ ip + "[^0-9]| awk \'{print $4}\'"
            answer =  subprocess.check_output (cmd, shell=True).decode ()
            if (answer.count (":") == 5) :
                mac = answer.replace ("\n","")
        except :
            mac  = ""
    return mac


##############################################
def module_ping (ip) :
    answer = True
    nodes  = 0

    if (ip == "192.168.1.204"):
        nodes = 2
    else:
        nodes = 3
    for i in range (0,nodes) :
       result_ping = py_fastersys.Ping (ip , i)
       clock = result_ping          ["Clock"]
       mother= Whoswho_Mother.Image [result_ping ["Mother"]]
       node  = Whoswho_Node.Image   [result_ping ["Node"  ]]
       if (mother != "UNKNOWN") :
           if i == 0 :
              print("==> Faster Ping " + '{:14}'.format (ip))
           else :
              print('{:-<30}'.format("                |") + str(i) + " => clock : " + '{:.9f}'.format(clock) + " s  " + mother  + "   " + node)
       else :
           answer = False
           if i == 0 :
              print("Faster Ping " + '{:14}'.format (ip)  + str(i) + " => timeout")
           else :
              print('{:-<39}'.format("                |") + str (i) + " => timeout")
    return answer

##############################################
def hardware_standalone_check () :
    global DB1_type
    global Mother_type
    global module_ip
    error = False

    answer = subprocess.call (['faster_mother_board_firmware_check', module_ip, "echo_off"])
    if (answer == 1):
        print("==> Use faster_syroco_reprog to upgrade the FPGA0 firmware")
        print("")
        sys.exit (1)
    else:
        print("==> The version of the FPGA0 is Ok")
        answer = subprocess.check_output("faster_ping " + module_ip  + " 1 --verbose | awk \'{print$11}\'", shell=True).decode ()
        if (answer.count ("CARAS")) :
           if (answer.count ("QDC")):
               DB1_type = "CARAS"
           else:
               print("==> This software only check the CARAS channels with the QDC firmware !!")
               print("    Use faster_syroco_reprog  QDC_CARAS to upgrade the FPGA0 firmware")
               sys.exit(1)

        if (answer.count ("MOSAHR")):
           if (answer.count ("CRRC4")):
               DB1_type = "MOSAHR"
           else:
               print("==> This software only check the MOSAHR channels with the CRRC4 firmware !!")
               print("    Use faster_syroco_reprog  CRRC4_MOSAHR to upgrade the FPGA0 firmware")
               sys.exit(1)

##############################################
def hardware_standalone_load  () :
    global number_of_channel
    global fpga1
    global module_ip
    global daq_ip
    global daq_mac
    global daq_in1
    global rhb_mac
    global rhb_ip
    global rhb_in
    global module_mac

    if (DB1_type == "CARAS") :
        fpga1              = QDC_Caras_Ctrl          ()
        number_of_channel += 2
        setup_qdc_node        (fpga1, 1, file_directory + "ch_1_2.cfg")
        for n in range (0, number_of_channel) :
            channel_list.append ("CARAS")

    elif (DB1_type == "MOSAHR") :
        fpga1 = ADC_Mosahr_Ctrl          ()
        number_of_channel += 4
        setup_adc_node        (fpga1, 1, file_directory + "ch_1_2_3_4.cfg")
        for n in range (0, number_of_channel) :
            channel_list.append ("MOSAHR")

    else:
        print("==> " + DB1_type + "or/and " + DB2_type + " are not valid daughter-board(s)")
        sys.exit (1)

##############################################
def hardware_AMC_check () :
    global DB1_type
    global DB2_type
    global Mother_type
    global module_ip
    error = False

    try:
        M_EE        = py_fastersys.Mother_Eeprom_Read (module_ip)
        Mother_type = Whoswho_Mother.Image.index (Eeprom_Mother_Board (M_EE))
    except:
        error = True
        print("==> Mother_board eeprom read error")

    if (py_fastersys.Is_FPGA_Revision_Number_Ok (module_ip, 0)) :
        print("==> The version of the FPGA0 is Ok")
    else:
        print("==> Use faster_hardware_shell to upgrade the FPGA0 firmware")
        print("")
        sys.exit (1)

    try :

        DB_EE1      = py_fastersys.Daughter_Eeprom_Read (module_ip, 1)
        DB1_type    = Eeprom_Daughter_Board (DB_EE1)

    except :
        error = True
        print("==> Daughter_board eeprom 1 read error")

    try:

        DB_EE2      = py_fastersys.Daughter_Eeprom_Read (module_ip, 2)
        DB2_type    = Eeprom_Daughter_Board (DB_EE2)

    except :
        error = True
        print("==> Daughter_board eeprom 2 read error")

    if (DB1_type == "UNKNOWN"):
        print("==> Daughter_board 1 is missing")
        error = True

    if (DB2_type == "UNKNOWN"):
        print("==> Daughter_board 2 is missing")
        error = True

    if (error == True):
        sys.exit (1)


##############################################
def hardware_AMC_load  () :
    global number_of_channel
    global fpga1
    global fpga2
    global module_ip
    global daq_ip
    global daq_mac
    global daq_in
    global rhb_mac
    global rhb_ip
    global rhb_in
    global amc_mac
    global n3tm

    counter = 0

    if (DB1_type == "CARAS") and (DB2_type == "CARAS") :
        print("==> Downloading fpga1 ....")
        py_fastersys.Pre_Load    (Mother_type, module_ip, 1, Whoswho_Node.QDC_CARAS)
        print("==> Downloading fpga2 ....")
        py_fastersys.Pre_Load    (Mother_type, module_ip, 2, Whoswho_Node.QDC_CARAS)
        py_fastersys.Load        (module_ip)
        time.sleep               (2)
        answer = subprocess.check_output("faster_ping " + module_ip  + " 0 --verbose | awk \'{print$10}\'", shell=True).decode ()
        if (answer.count ("AMC_C5")) :
            py_fastersys.Reset_Nodes (module_ip)
            counter = 0
            time.sleep               (2)
            while ((module_ping (module_ip) == False) or (counter == 5)) :
               py_fastersys.Reset_Nodes (module_ip)
               time.sleep               (2)
               counter = counter + 1
            if (counter == 5) : sys.exit (1)

        fpga1              = QDC_Caras_Ctrl          ()
        number_of_channel += 2
        setup_qdc_node (fpga1, 1, file_directory + "ch_1_2.cfg")
        fpga2              = QDC_Caras_Ctrl          ()
        number_of_channel += 2
        setup_qdc_node (fpga2, 2, file_directory + "ch_3_4.cfg")
        for n in range (0, number_of_channel) :
            channel_list.append ("CARAS")

    elif (DB1_type == "CARAS") and (DB2_type == "MOSAHR") :
        print("==> Downloading fpga1 ....")
        py_fastersys.Pre_Load    (Mother_type, module_ip, 1, Whoswho_Node.QDC_CARAS)
        print("==> Downloading fpga2 ....")
        py_fastersys.Pre_Load    (Mother_type, module_ip, 2, Whoswho_Node.CRRC4_MOSAHR)
        py_fastersys.Load        (module_ip)
        time.sleep               (2)
        answer = subprocess.check_output("faster_ping " + module_ip  + " 0 --verbose | awk \'{print$10}\'", shell=True).decode ()
        if (answer.count ("AMC_C5")) :
            py_fastersys.Reset_Nodes (module_ip)
            counter = 0
            time.sleep               (2)
            while ((module_ping (module_ip) == False) or (counter == 5)) :
               py_fastersys.Reset_Nodes (module_ip)
               time.sleep               (2)
               counter = counter + 1
            if (counter == 5) : sys.exit (1)

        fpga1              = QDC_Caras_Ctrl          ()
        number_of_channel += 2
        for n in range (0, number_of_channel) :
            channel_list.append ("CARAS")
        setup_qdc_node (fpga1, 1, file_directory + "ch_1_2.cfg")
        fpga2 = ADC_Mosahr_Ctrl          ()
        number_of_channel += 4
        setup_adc_node (fpga2, 2, file_directory + "ch_3_4_5_6.cfg")
        for n in range (0, 4) :
            channel_list.append ("MOSAHR")


    elif (DB1_type == "MOSAHR") and (DB2_type == "MOSAHR") :
        print("==> Downloading fpga1 ....")
        py_fastersys.Pre_Load    (Mother_type, module_ip, 1, Whoswho_Node.CRRC4_MOSAHR)
        print("==> Downloading fpga2 ....")
        py_fastersys.Pre_Load    (Mother_type, module_ip, 2, Whoswho_Node.CRRC4_MOSAHR)
        py_fastersys.Load        (module_ip)
        time.sleep               (2)
        answer = subprocess.check_output("faster_ping " + module_ip  + " 0 --verbose | awk \'{print$10}\'", shell=True).decode ()
        if (answer.count ("amc_c5")) :
            py_fastersys.reset_nodes (module_ip)
            counter = 0
            time.sleep               (2)
            while ((module_ping (module_ip) == false) or (counter == 5)) :
               py_fastersys.reset_nodes (module_ip)
               time.sleep               (2)
               counter = counter + 1
            if (counter == 5) : sys.exit (1)

        fpga1 = ADC_Mosahr_Ctrl          ()
        number_of_channel += 4
        setup_adc_node (fpga1, 1, file_directory + "ch_1_2_3_4.cfg")
        fpga2 = ADC_Mosahr_Ctrl          ()
        number_of_channel += 4
        setup_adc_node (fpga2, 2, file_directory + "ch_5_6_7_8.cfg")
        for n in range (0, number_of_channel) :
            channel_list.append ("MOSAHR")

    else:
        print("==> " + DB1_type + "or/and " + DB2_type + " are not valid daughter-board(s)")
        sys.exit (1)

    n3tm = N3_Merger_Ctrl         ()
    n3tm.Set_Cfg_File             (file_directory + "n3merger.cfg")
    n3tm.Restore                  ()
    n3tm.Node_Setup               (module_ip, 3)
    n3tm.Data_Base_Setup          (daq_mac, daq_ip, daq_in1)
    n3tm.Intro_Base_Setup         (rhb_mac, rhb_ip, rhb_in)
    n3tm.Connect                  (0)
    n3tm.Send_Base_Setup          ()
    n3tm.Send_Fmin                ()
    n3tm.Send_Setup               ()


##############################################
def trunk_setup () :
    global trunk_ctrl
    global n3tm

    trunk_ctrl = Basic_Trunk             (1)

    if (module_ip == "192.168.1.204"):
        trunk_ctrl.Intro_Output_Setting      (rhb_ip, rhb_in)
        trunk_ctrl.Data_Input_Setting        (1, module_ip, 1, daq_in1)
    else:
        trunk_ctrl.Intro_Output_Setting      (n3tm.Get_Intro_IP (), n3tm.Get_Intro_Port ())
        trunk_ctrl.Data_Input_Setting        (1, n3tm.Get_IP (), n3tm.Get_Node_Num (), n3tm.Get_Data_Port ())
    trunk_ctrl.Disable_All_Inputs        ()
    trunk_ctrl.Enable_Input              (1)
    trunk_ctrl.Set_File_Prefix           (file_prefix)


##############################################
def daq_start () :
    global trunk_ctrl
    global fpga1
    global fpga2
    global n3tm

    signal_arm_start         (module_ip)
    py_fastersys.Signal      (module_ip)

    trunk_ctrl.Start         ()

    if (module_ip == "192.168.1.204"):
        fpga1.Send_Synchro_Start ()
    else:
        n3tm.Send_Synchro_Start  ()
        fpga1.Send_Synchro_Start ()
        fpga2.Send_Synchro_Start ()

    if (module_ip == "192.168.1.204"):
        fpga1.Send_Data_Start    ()
    else :
        n3tm.Send_Data_Start     ()
        fpga1.Send_Data_Start    ()
        fpga2.Send_Data_Start    ()


##############################################
def daq_stop () :
    global trunk_ctrl
    global fpga1
    global fpga2
    global n3tm
    signal_arm_stop          (module_ip)
    py_fastersys.Signal      (module_ip)

    if (module_ip == "192.168.1.204"):
        fpga1.Send_Data_Stop     ()
    else:
        fpga1.Send_Data_Stop     ()
        fpga2.Send_Data_Stop     ()
        n3tm.Send_Data_Stop      ()

    if (module_ip == "192.168.1.204"):
        fpga1.Send_Synchro_Stop  ()
    else:
        fpga1.Send_Synchro_Stop  ()
        fpga2.Send_Synchro_Stop  ()
        n3tm.Send_Synchro_Stop   ()
    time.sleep (1)
    trunk_ctrl.Stop          ()


##############################################
def display_next_channel () :
    os.system("pkill -2 oscigraph")


##############################################
def refresh_axes () :
    os.system("pkill -10 oscigraph")


##############################################
##############################################

if __name__ == "__main__":


    print("")

    if (len (sys.argv) != 2) :
        print("==> Usage :  " + sys.argv[0] + " IP_Module ")
        print("")
        sys.exit (1)

    signal.signal(signal.SIGINT, exit_gracefully)

    # DAQ Config
    error        = False
    channel_list = []
    daq_ip       = "192.168.0.1"
    daq_mac      =  get_mac_from_ip (daq_ip)

    if (daq_mac.count (":") != 5) :
        print("==> No FASTER network found, connect your hardware")
        print("")
        sys.exit (1)

    rhb_mac           = daq_mac
    rhb_ip            = daq_ip

    module_ip         = sys.argv[1]
    amc_mac           = get_mac_from_ip (module_ip)

    if (amc_mac.count (":") != 5) :
        print("==> Board IP = " + module_ip + " is unreacheable")
        print("")
        sys.exit (1)

    if (os.path.exists (faster_file) == True) :
        os.remove (faster_file)

    os.system ("mkfifo " + faster_file)

    os.system ("oscigraph -d 0.1 " + faster_file + " 2001&")

    py_qdc_caras_ctrl.initialize  ()
    py_adc_mosahr_ctrl.initialize ()
    py_n3_merger_ctrl.initialize  ()
    py_basic_trunk.initialize     ()

    if (module_ip == "192.168.1.204"):
        hardware_standalone_check ()
        hardware_standalone_load  ()
    else:
        hardware_AMC_check ()
        hardware_AMC_load  ()

    trunk_setup    ()

    daq_start ()
    #time.sleep              (20)

    print("")
    for n in range(0, number_of_channel):
        label = 2001 + n
        if (channel_list [n] == "MOSAHR") :
            print("==> MOSAHR DAUGHTER-BOARD LABEL = " + str (label))
            time.sleep (4)
        if (channel_list [n] == "CARAS") :
            if (label == 2001) :
                fpga = fpga1
                node = 1
            if (label == 2002) :
                fpga = fpga1
                node = 2
            if (label == 2003) :
                fpga = fpga2
                node = 1
            if (label == 2004) :
                fpga = fpga2
                node = 2
            print("==> CARAS DAUGHTER-BOARD LABEL = " + str (label))
            print("    Offset =  0 mv")
            fpga.Caras_Setup (INPUT_RANGE_1100_MAX, INPUT_RANGE_1100_MAX)
            fpga.Send_Caras_Input_Setup ()
            fpga.Send_Channel_Setup     (node)
            time.sleep                  (4)
            #refresh_axes                ()
            #time.sleep                  (1)
            fpga.Caras_Setup            (INPUT_RANGE_1700_MAX, INPUT_RANGE_1700_MAX)
            fpga.Send_Caras_Input_Setup ()
            fpga.Send_Channel_Setup     (node)
            print("    Offset = -600 mv")
            time.sleep                  (4)
            #refresh_axes                ()
            #time.sleep                  (1)
            fpga.Caras_Setup (INPUT_RANGE_700_MAX, INPUT_RANGE_700_MAX)
            fpga.Send_Caras_Input_Setup ()
            fpga.Send_Channel_Setup     (node)
            print("    Offset = +400 mv")
            time.sleep                  (4)
            #refresh_axes                ()
            #time.sleep                  (1)
        display_next_channel ()
        #a = raw_input("==> Use the return key to check next channel ...!")

    daq_stop ()
