#!/bin/bash

BasePath=../..;source $BasePath/Commons.sh
source Universals.sh


DirToDischargeParams=$SHM0/Operation/Discharge


#WG PowSup for piezoelectric valve:
PowSup4PiezoValve=$SHMS/Devices/PowerSupplies/GWInstekPSW-a


function H2Engage() { Call $RelayBoards H2-pipe@Vacuum ON; }
function HeEngage() { Call $RelayBoards He-pipe@Vacuum ON; }
function DisEngage() { Call $RelayBoards H2-pipe@Vacuum OFF;Call $RelayBoards He-pipe@Vacuum OFF; }

U_nzc_kickoff=23 # non zero callibration kickoff
t_nzc_relax=1 # non zero callibration kickoff


function OpenSession(){
    LogItColor 1 "Uvodni (fake) WG calibration ... "
    cp $SW/Infrastructure/WorkingGas/CalibrationDepot/WG_calibration_table4H2.default $SHM/ActualSession/SessionLogBook/WG_calibration_table4H2
}

function SetVoltage@GasValveTo ()
{
local Voltage=$1
    Call  $PowSup4PiezoValve GasFlowSetup "$Voltage"
}

function SetVoltage@GasValveOFF()
{
    SetVoltage@GasValveTo "0"
    DisEngage
}

## pressure PID regulatro pid file 
PressurePIDFILE="/tmp/pressure_pid_ctrl.pid"

function StopPIDRegulator() {
    if [ -f "$PressurePIDFILE" ]; then
        pid=$(cat $PressurePIDFILE)
        kill -SIGINT $pid
        rm "$PressurePIDFILE"
    fi
}

function StartPIDRegulator() {
    local p_request="$1"
                
    # Stop PID regulatro if already runnig
    StopPIDRegulator
    python3 pressure_PID_controller.py $p_request &
    echo $! > $PressurePIDFILE
}

function GetReadyTheDischarge()
{ 


    GeneralTableUpdateAtDischargeBeginning

        p_working_gas_type_request=$(<$SHM0/Infrastructure/WorkingGas/Parameters/s_gas)
        
        
    echo $p_working_gas_type_request > $DirToDischargeParams/X_working_gas_discharge_request
    LogIt "Going with gas type $p_working_gas_type_request"
        
    cp $SHML/ActualChamberPressuremPa $DirToDischargeParams/p_chamber_pressure_before_discharge
    UpdateCurrentShotDataBase "p_chamber_pressure_before_discharge=$(< $DirToDischargeParams/p_chamber_pressure_before_discharge)"

    cp $SHML/WG_calibration_table4H2 $DirToDischargeParams/ #Save Actual used valve calibration
    
    if [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'vacuum' ]] 
    then 
        LogIt "Vacuum discharge !"
    else
        echo "Discharge Preparation" >>$SHML/PressureLog

        if [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_gas) == 'H' ]]; then H2Engage; fi
        if [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_gas) == 'He' ]]; then HeEngage; fi

        if [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'p_wg-zmb' ]]; then
            p_working_gas_discharge_request=$(<$SHM0/Infrastructure/WorkingGas/Parameters/p_h)
            echo $p_working_gas_discharge_request > $DirToDischargeParams/p_working_gas_discharge_request
    LogIt "Going with gas pressure $p_working_gas_discharge_request"
            ValveVoltage=`python3 -c "from numpy import loadtxt;from scipy.interpolate import interp1d;CalData = loadtxt('/dev/shm/golem/ActualSession/SessionLogBook/WG_calibration_table4H2');Voltage=CalData[:,1];pressure=CalData[:,0];print(interp1d(Voltage,pressure)("$p_working_gas_discharge_request"))"`
            SetVoltage@GasValveTo $ValveVoltage
        elif [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'p_wg' ]]; then
            p_working_gas_discharge_request=$(<$SHM0/Infrastructure/WorkingGas/Parameters/p_h)
            echo $p_working_gas_discharge_request > $DirToDischargeParams/p_working_gas_discharge_request
    LogIt "Setting kick-off voltage $U_nzc_kickoff V for non zero calibration pressure regime"
    SetVoltage@GasValveTo $U_nzc_kickoff
    sleep $t_nzc_relax
    LogIt "Going with gas pressure $p_working_gas_discharge_request"
            ValveVoltage=`python3 -c "from numpy import loadtxt;from scipy.interpolate import interp1d;CalData = loadtxt('/dev/shm/golem/ActualSession/SessionLogBook/WG_calibration_table4H2');Voltage=CalData[:,1];pressure=CalData[:,0];print(interp1d(Voltage,pressure)("$p_working_gas_discharge_request"))"`
            SetVoltage@GasValveTo $ValveVoltage
        elif [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'p_pid'   ]]; then
            p_working_gas_discharge_request=$(<$SHM0/Infrastructure/WorkingGas/Parameters/p_h)
            echo $p_working_gas_discharge_request > $DirToDischargeParams/p_working_gas_discharge_request
            LogIt "Going with gas pressure $p_working_gas_discharge_request via p_pid request"

            StartPIDRegulator $p_working_gas_discharge_request

        elif [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'U_v' ]]; then
            p_working_gas_discharge_request=-1 #HotFix
            echo -1 > $DirToDischargeParams/p_working_gas_discharge_request
            LogIt "Going with gas pressure requested via U_v request"

            echo $p_working_gas_discharge_request > $DirToDischargeParams/p_working_gas_discharge_request

            ValveVoltage=$(<$SHM0/Infrastructure/WorkingGas/Parameters/u_v)
            SetVoltage@GasValveTo $ValveVoltage 
        fi
        sleep 5 
        #echo "From this WG calibr"
        #cat /dev/shm/golem/ActualSession/SessionLogBook/WG_calibration_table4H2
        LogIt "We have got $ValveVoltage V for $p_working_gas_discharge_request mPa request"
        #SetVoltage@GasValveTo 20; sleep 5 # pouzit primy zpusob nastaveni  napeti na ventilu
    fi
    

    
    $LogFunctionPassing;
}

function LogActualChamberPressure
{
    cp $SHML/ActualChamberPressuremPa $DirToDischargeParams/p_chamber_pressure_predischarge
    UpdateCurrentShotDataBase "p_chamber_pressure_predischarge=$(< $DirToDischargeParams/p_chamber_pressure_predischarge)"
    echo $(<$SHM0/Infrastructure/WorkingGas/Parameters/u_v) '    ' $(<$SHML/ActualChamberPressuremPa) >> $SHMS/SessionLogBook/p_chamber_pressure_predischarge.log


}

function WGtest
{
local Voltage=$1
local Relax=$2

    $LogFunctionStart
    H2Engage
    echo "WGtest start" >>$SHML/PressureLog
    SetVoltage@GasValveTo $Voltage; sleep $Relax
    SetVoltage@GasValveOFF
    echo "WGtest end" >>$SHML/PressureLog
    DisEngage
    $LogFunctionEnd
}


function SecurePostDischargeState()
{
    if [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'p_pid' ]]; then
        StopPIDRegulator
        sleep 2
    fi

    SetVoltage@GasValveOFF
    DisEngage
    
    if [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'p_wg' ]]  || [[ $(<$SHM0/Infrastructure/WorkingGas/Parameters/s_mode) == 'p_pid' ]]; then
        LogIt "WG resumé:"
        LogIt "Request: $(<$SHM0/Infrastructure/WorkingGas/Parameters/p_h)"
        LogIt "Achievement: $(<$SHM0/Operation/Discharge/p_chamber_pressure_predischarge)"
        Difference=`echo "($(<$SHM0/Infrastructure/WorkingGas/Parameters/p_h)-$(<$SHM0/Operation/Discharge/p_chamber_pressure_predischarge)+0.5)/1"|bc|tr -d -`;
        LogIt "Difference:$Difference" 
        
        for i in 10 5 2; do 
            if [[ $Difference -gt $i ]]; 
            then 
                if [[ $(<$SHM0/Operation/Dirigent/HigherPower/Parameters/wg_voice) != 'off' ]]; 
                then 
                    Speaker Problems/The-difference-in-WG-over-"$i"-mPa;
                fi
                LogIt "WG Difference over "$i" mPa"
                return
            fi
        done
        LogIt "WG Difference OK"
    fi
    
}


function PostDischargeAnalysis()
{
    local cesta=Infrastructure/$instrument
   GenerateDiagWWWs
}

function GenerateDiagWWWs
{

echo "<h3>Working gas</h3>
Parameters <a href=$diagpath/Parameters/ title="Parameters">$parametersicon</a>:`cat $SHM0/Production/Parameters/infrastructure.workinggas`" >include.html;

echo "<table><tr>

<td><a href=$cesta/port_$port.jpg title="Infrastructure placement"><img src=$cesta/port_$port.jpg width='$iconsize'/></a></td>
<td><img src="$cesta/setup.png" width="$iconsize"></td>

<td><a href=https://www.dropbox.com/$DropBox title="Photogallery@DropBox"><img src=$cesta/Overview-thumb.jpg /></a></td>


<td><a href="Infrastructure/Chamber/SessionChamber_p_T_Logbook.jpg"><img src="Infrastructure/Chamber/SessionChamber_p_T_Logbook.jpg" width="$iconsize"></a></td>

</tr></table>" >> include.html

}




function H2Calibration()
{
local LowerVoltageLimit=$1
local Step=$2
local UpperPressureLimit=$3
local RelaxTime=$4

UpperVoltageLimit=50

    $psql_password;psql -c "INSERT into Infrastructure.chamber (event,date,time, shot_no, session_id, chamber_pressure,  forvacuum_pressure, temperature) VALUES ('H2 valve calibration:do','`date '+%y-%m-%d'`','`date '+%H:%M:%S'`', `cat $SHM/shot_no`, `cat $SHM/session_id`,`cat $SHML/ActualChamberPressuremPa`,`cat $SHML/ActualForVacuumPressurePa`, `cat $SHML/ActualChamberTemperature`) " -q -U golem golem_database
    rm -f $SHML/WG_calibration_table4H2
    rm -f $SHML/WG_calibration_table4H2
    rm -f $SHML/WG_PID_calibration_table4H2

    SetVoltage@GasValveTo "0";
    sleep $RelaxTime
    H2Engage
    #for i in `seq 15 0.4 29`; do
    for i in `seq $LowerVoltageLimit $Step $UpperVoltageLimit|sed 's/,/\./g'`; do
    #for i in `seq 27 0.2 34`; do 
        SetVoltage@GasValveTo "$i";
        sleep $RelaxTime
        echo Calibrating at $i V \($LowerVoltageLimit V, po $Step V, do  $UpperPressureLimit mPa\): `cat $SHML/ActualChamberPressuremPa` mPa
        echo $i "  "  $(< $SHML/ActualChamberPressuremPa)  >> $SHML/WG_calibration_table4H2
        if (( $(echo "$(< $SHML/ActualChamberPressuremPa) > $UpperPressureLimit" |bc -l) )); then
            break
        fi
        SetVoltage@GasValveTo "0";
        sleep $RelaxTime
    done
    cp $SHML/WG_calibration_table4H2 /golem/Dirigent/Infrastructure/WorkingGas/CalibrationDepot/WG_calibration_table4H2_`date "+%d%m%y-%H:%M"`_$LowerVoltageLimit-$Step-$UpperPressureLimit-$RelaxTime-_`head -1 $SHML/WG_calibration_table4H2|sed 's/\./p/g;s/\ \ \ \ /V/g'`mPa-`tail -1 $SHML/WG_calibration_table4H2|sed 's/\./p/g;s/\ \ \ \ /V/g'`mPa

    SetVoltage@GasValveTo "0";

    read -p "Do you want to continue with PID calibration? (yes/no or y/n): " user_input

    case "$user_input" in
           yes|y)
                   sleep $RelaxTime
                   # Run PID calibration
                   python3 PID_calibration.py
                   cp $SHML/WG_PID_calibration_table4H2 /golem/Dirigent/Infrastructure/WorkingGas/CalibrationDepot/WG_PID_calibration_table4H2_`date "+%d%m%y-%H:%M"`

               ;;
           no|n)
               echo "Exiting."
               ;;
           *)
               echo "Invalid input. Please enter 'yes', 'no', 'y', or 'n'."
    esac

    SetVoltage@GasValveOFF
    Relax
    DisEngage


}

function H2Calibration-nz()
{
local LowerVoltageLimit=$1
local Step=$2
local UpperPressureLimit=$3
local RelaxTime=$4

UpperVoltageLimit=50

    $psql_password;psql -c "INSERT into Infrastructure.chamber (event,date,time, shot_no, session_id, chamber_pressure,  forvacuum_pressure, temperature) VALUES ('H2 valve calibration:do','`date '+%y-%m-%d'`','`date '+%H:%M:%S'`', `cat $SHM/shot_no`, `cat $SHM/session_id`,`cat $SHML/ActualChamberPressuremPa`,`cat $SHML/ActualForVacuumPressurePa`, `cat $SHML/ActualChamberTemperature`) " -q -U golem golem_database
    rm -f $SHML/WG_calibration_table4H2
    rm -f $SHML/WG_calibration_table4H2
    SetVoltage@GasValveTo "0";
    sleep $RelaxTime
    H2Engage
    #for i in `seq 15 0.4 29`; do
    for i in `seq $LowerVoltageLimit $Step $UpperVoltageLimit|sed 's/,/\./g'`; do
    #for i in `seq 27 0.2 34`; do
        SetVoltage@GasValveTo $U_nzc_kickoff;
        sleep $t_nzc_relax
        SetVoltage@GasValveTo "$i";
        sleep $RelaxTime
        echo Calibrating at $i V \($LowerVoltageLimit V, po $Step V, do  $UpperPressureLimit mPa\): `cat $SHML/ActualChamberPressuremPa` mPa
        echo $i "  "  $(< $SHML/ActualChamberPressuremPa)  >> $SHML/WG_calibration_table4H2
        if (( $(echo "$(< $SHML/ActualChamberPressuremPa) > $UpperPressureLimit" |bc -l) )); then
            break
        fi
        SetVoltage@GasValveTo 0;
        sleep $RelaxTime
    done
    cp $SHML/WG_calibration_table4H2 /golem/Dirigent/Infrastructure/WorkingGas/CalibrationDepot/WG_calibration_table4H2_`date "+%d%m%y-%H:%M"`_$LowerVoltageLimit-$Step-$UpperPressureLimit-$RelaxTime-_`head -1 $SHML/WG_calibration_table4H2|sed 's/\./p/g;s/\ \ \ \ /V/g'`mPa-`tail -1 $SHML/WG_calibration_table4H2|sed 's/\./p/g;s/\ \ \ \ /V/g'`mPa

    SetVoltage@GasValveTo "0";

    read -p "Do you want to continue with PID calibration? (yes/no or y/n): " user_input

    case "$user_input" in
           yes|y)

                   sleep $RelaxTime
                   # Run PID calibration
                   python3 PID_calibration.py -k
                   cp $SHML/WG_PID_calibration_table4H2 /golem/Dirigent/Infrastructure/WorkingGas/CalibrationDepot/WG_PID_calibration_table4H2_`date "+%d%m%y-%H:%M"`
               ;;
           no|n)
               echo "Exiting."
               ;;
           *)
               echo "Invalid input. Please enter 'yes', 'no', 'y', or 'n'."
               ;;
    esac



    SetVoltage@GasValveOFF
    Relax
    DisEngage

}

