#!/bin/bash
# To be executed at RASPs

source Commons.sh

whoami="Devices/RASPs/Charger/Bt_Ecd"
DirToDischargeParams=$SHM0/`dirname $whoami`


COMMAND="netcat -w 1 ChargerOsc 5555"
TheOscilloscope=ChargerOsc

Drivers="Devices/uControllers/Drivers/UniPi"

source Drivers/UniPi/driver.sh


#Function test, see http://golem.fjfi.cvut.cz/shots/33132/


function HVon()
{
    $LogFunctionPassing

    Relax
    #HV Ostry rezim:
    # ???? Mas URCITE odpojeny LV zdroj ??
    # ====================================
    PowerSupplyHVfansON
    HVlightON
    PowerSupplyHVcontactorON
    #LV Tupy rezim:
    # see Devices/PowerSupplies/RigolPS831A-a/HVsubstitute.sh
#    echo ":INST CH3;:CURR 0.1;:VOLT -30;:OUTP CH3,ON"|netcat -w 1 HVsubstitute 5555
    Relax
}	


function HVoff()
{
    PowerSupplyHVcontactorOFF # Ostry rezim
    # see Devices/PowerSupplies/RigolPS831A-a/HVsubstitute.sh# Tupy rezim
#    echo ":OUTP CH3,OFF"|netcat -w 1 HVsubstitute 5555 # Tests on RigolPS

    $LogFunctionPassing
    HVlightOFF
    mRelax
	ChargingResistorsAllON
	
}


function ScopeConfiguration()
{
    SCALE=300
    OFFSET=-400
    PROBE=100
    #LV test setup
    #==============
    #SCALE=9
    #OFFSET=0
    #PROBE=100
    #==============
    echo "
    CHANnel1:DISPlay ON;CHANnel1:PROBe $PROBE;CHANnel1:SCALe $SCALE;CHANnel1:OFFSet $OFFSET;
    CHANnel2:DISPlay ON;CHANnel2:PROBe 1;CHANnel2:SCALe 0.5;CHANnel2:OFFSet -4.3;
    CHANnel3:DISPlay ON;CHANnel3:PROBe $PROBE;CHANnel3:SCALe $SCALE;CHANnel3:OFFSet $OFFSET;
    CHANnel4:DISPlay ON;CHANnel4:PROBe $PROBE;CHANnel4:SCALe $SCALE;CHANnel4:OFFSet $OFFSET;
    TIMebase:DELay:ENABle OFF;TIMebase:MAIN:SCALe 10;TIMebase:MAIN:OFFSet 49;
    :STOP;:CLEAR;
    :SYSTem:KEY:PRESs MOFF"|$COMMAND
}


function PrepareSessionEnv@SHM()
{
    MountCentralSHMEnvironment
    ScopeConfiguration
}	


function UpperShortCircuitsEngage() { RelayON 3; }	 #obsolete
function UpperShortCircuitsDisEngage() { RelayOFF 3; } #obsolete

#function LowerShortCircuitsDisEngage() { RelayON 13; } #Before 062021 reconstruction
#function LowerShortCircuitsEngage() { RelayOFF 13; } #Before 062021 reconstruction

function LowerShortCircuitsDisEngage() { echo "*B1OS5H"|telnet 192.168.2.248 10001 1>&- 2>&-; }
function LowerShortCircuitsEngage() { echo "*B1OS5L"|telnet 192.168.2.248 10001 1>&- 2>&-; }

function HVlightON() { RelayON 14; }
function HVlightOFF() { RelayOFF 14; }	
function ConnectOscill() { RelayON 12; }
function DisConnectOscill() { RelayOFF 12; }


#****************************************
#function PowerSupplyHVcontactorON() { RelayON 16; }	#Before 062021 reconstruction
#function PowerSupplyHVcontactorOFF() { RelayOFF 16; } #Before 062021 reconstruction

function PowerSupplyHVcontactorON() { echo "*B1OS4H"|telnet 192.168.2.248 10001 1>&- 2>&-; }	
function PowerSupplyHVcontactorOFF() { echo "*B1OS4L"|telnet 192.168.2.248 10001 1>&- 2>&-; }

#function PowerSupplyHVcontactorON() { RelayON 13; } #Test na Gabove Zdroji	
#function PowerSupplyHVcontactorOFF() { RelayOFF 13; } #Test na Gabove Zdroji
#****************************************

function PowerSupplyHVfansON() { echo "*B1OS6H"|telnet 192.168.2.248 10001 1>&- 2>&-; }	
function PowerSupplyHVfansOFF() { echo "*B1OS6L"|telnet 192.168.2.248 10001 1>&- 2>&-; }

function BtHVrelayON() { RelayON 4 ; }
function BtHVrelayOFF() { RelayOFF 4 ; }
function BtCommutatorClockWise() { RelayON 5 ;mRelax; RelayOFF 5; }
function BtCommutatorAntiClockWise() { RelayON 6 ;mRelax; RelayOFF 6; }

function BtChargeCommutatorClockWise() { RelayON 7 ;mRelax; RelayOFF 7; }
function BtChargeCommutatorAntiClockWise() { RelayON 8 ;mRelax; RelayOFF 8; }



function CdHVrelayON() { RelayON 2 ; }
function CdHVrelayOFF() { RelayOFF 2 ; }
function EtCommutatorClockWise() { RelayON 9 ;mRelax; RelayOFF 9; }
function EtCommutatorOFF() { RelayON 10 ;mRelax; RelayOFF 10; }
function EtCommutatorAntiClockWise() { RelayON 11 ;mRelax; RelayOFF 11; }


function ChargingResistor_I_DisEngage() { RelayON 15 ; }
function ChargingResistor_I_Engage() { RelayOFF 15 ; }

#function ChargingResistor_II_DisEngage() { RelayON 6 ; }
#function ChargingResistor_II_Engage() { RelayOFF 6 ; }


ChargingFlag=0
ChargingResistors=0



#./Dirigent.sh --discharge --UBt 20 --TBt 1000 --Ucd 10 --Tcd 2000 --preionization 1 --gas H --pressure 0 --comment "LV test discharge"

function GetReadyTheDischarge()
{
local UBt=`cat $SHMP/UBt`
local Ucd=`cat $SHMP/Ucd`
local comment=`cat $SHMP/comment`

    $LogFunctionStart
    
    
    if [ -e $SHMP/Bt_orientation ]; 
    then    
        Bt_orientation_request=`cat $SHMP/Bt_orientation`
    else
        LogIt "No request for Bt orientation, therefore Discharge with default Bt orientation"
        Bt_orientation_request=`cat $SHM/Management/DefaultParameters/Bt_orientation`
        cp $SHM/Management/DefaultParameters/Bt_orientation $SHMP/Bt_orientation

    fi    
    echo $Bt_orientation_request > $DirToDischargeParams/Bt_orientation_request
    LogIt "Going with Bt_orientation $Bt_orientation_request"
    
      case $Bt_orientation_request in 
            CW)
                LogIt "Discharge with Bt CW request"
                BtCommutatorClockWise
                ;;
            ACW)
                LogIt "Discharge with Bt ACW request"
                BtCommutatorAntiClockWise
                ;;
        esac

        
     if [ -e $SHMP/CD_orientation ]; 
    then    
        CD_orientation_request=`cat $SHMP/CD_orientation`
    else
        LogIt "No request for Bt orientation, therefore Discharge with default Bt orientation"
        CD_orientation_request=`cat $SHM/Management/DefaultParameters/CD_orientation`
        cp $SHM/Management/DefaultParameters/CD_orientation $SHMP/CD_orientation

    fi    
    echo $CD_orientation_request > $DirToDischargeParams/CD_orientation_request
    LogIt "Going with CD_orientation $CD_orientation_request"
    
      case $CD_orientation_request in 
            CW)
                LogIt "Discharge with CD CW request"
                EtCommutatorClockWise
                ;;
            ACW)
                LogIt "Discharge with CD ACW request"
                EtCommutatorAntiClockWise
                ;;
        esac
       
        



    echo $Ucd > $DirToDischargeParams/U_cd_discharge_request
    echo $UBt > $DirToDischargeParams/U_bt_discharge_request
    if [ "$comment" != "Dummy test discharge" ]; then 
        OpenOscDVMchannel  1
        if [ $UBt -gt 0 ]; then 
            BtStatus=Charging;
            ShortCircuitsDisEngage;
            BtHVrelayON;
            Relax;HVon;Relax
            LogIt "Bt capacitor charging started"
            else
            LogIt "Bt capacitor charging not requested"
            BtStatus=Charged;
        fi 
        if [ $Ucd -gt 0 ]; then 
            CdStatus=Charging;
            ShortCircuitsDisEngage; 
            CdHVrelayON;
            Relax;HVon;Relax
            LogIt "Cd capacitor charging started"
            else
            LogIt "Cd capacitor charging not requested"
            CdStatus=Charged;
        fi
        if [ $UBt -gt 100 ]; then  ChargingResistorsAllOFF; fi
        #BtSlowLine=`echo "0.01725*$UBt + 76.43956"|bc|xargs printf '%4.0f\n'`
        BtSlowLine=98
        LogIt "U_Bt: $UBt, Hrana: $BtSlowLine"
        CdSlowLine=98 
        LogIt "U_Et: $Ucd, Hrana: $CdSlowLine"
        while [ $BtStatus == Charging ] || [ $CdStatus == Charging ]; do
            PowSupVoltage=`ReadDVMOscilloscope RigolMSO5104Charger`
            LogIt "Charging ... HV=$PowSupVoltage V"
            echo -n $PowSupVoltage > $SHML/U_power_supply_now

            # record current voltage for remote status
            # ASSUMES that the same power supply voltage is on all capacitors
            # while they are being charged
            if [ "$BtStatus" = "Charging" ]; then
                cp $SHML/U_power_supply_now $SHML/U_Bt_now
            fi
            if [ "$CdStatus" = "Charging" ]; then
                cp $SHML/U_power_supply_now $SHML/U_CD_now
            fi
            if [ $PowSupVoltage -ge $UBt ] && [ "$BtStatus" = "Charging" ]; then 
                if [ "$CdStatus" = "Charged" ]; then HVoff; mRelax; fi
                BtHVrelayOFF;
                BtStatus=Charged;
                LogIt "Bt capacitor charging finished @ $PowSupVoltage V"
            fi
            if [ $PowSupVoltage -ge $Ucd ] && [ "$CdStatus" = "Charging" ]; then 
                if [ "$BtStatus" = "Charged" ]; then HVoff; mRelax; fi
                CdStatus=Charged;
                CdHVrelayOFF;
                LogIt "Cd capacitor charging finished @ $PowSupVoltage V"
            fi
            if [ $PowSupVoltage -gt $(($UBt*$BtSlowLine/100)) ] && [           $ChargingResistors == 0  ] && [ "$BtStatus" = "Charging" ]; then LogIt "Bt slow PowSup";ChargingResistorsAllON;
            fi
            if [ $CdStatus == Charging ] && [ $PowSupVoltage -gt $(($Ucd*$CdSlowLine/100)) ] && [ $ChargingResistors == 0  ] && [ "$CdStatus" = "Charging" ]; then LogIt "Cd slow PowSup";ChargingResistorsAllON;fi
            if [ "$CdStatus" = "Charged" ] && [ $ChargingResistors == 1  ] && [ $PowSupVoltage -lt $(($UBt*$BtSlowLine/100)) ]; then LogIt "Bt boost PowSup";ChargingResistorsAllOFF;fi
            echo -n $CdStatus > $SHML/status_CD
            echo -n $CdStatus > $SHML/status_Bt

            sleep 0.1;
            
        done    
        HVoff
    else
        LogIt "It is a dummy discharge - without Charger action";
        for i in `seq 1 5`; do echo DD charging ... $i;sleep 1; done
        
    fi
    cp $SHML/U_Bt_now $DirToDischargeParams/U_Bt_final
    cp $SHML/U_CD_now $DirToDischargeParams/U_CD_final
    $LogFunctionEnd
}    




function SecurePostDischargeState()
{
    GoToSafeState
    DVMDisable
    # ASSUMES it is off
    echo -n 0 > $SHML/U_power_supply_now
    # ASSUMES they are discharged and short-circuited
    echo -n 0 > $SHML/U_Bt_now
    echo -n 0 > $SHML/U_CD_now
    killall netcat 
    PowerSupplyHVfansOFF
    $LogFunctionGoingThrough
}

function WebRecord()
{
    echo $1 >> $DirToDischargeParams/$ThisDev.html
}

function Web()
{

    cp $SHM/Management/imgs/Charger.jpg  $DirToDischargeParams/
    
    
    WebRecord "<html><body><h1>$ThisDev</h1>"
    WebRecord "<img src='Charger.jpg' width='50%'/><br></br>"
    WebRecord "<html><body><h1>Charger Oscilloscope</h1>"
    WebRecord "<img src='ScreenShot.png'/><br/>"
    WebRecord "<a href='http://192.168.2.78'>Charger Oscilloscope (admin:rigol)</a>"
    #<hr/>`ping -c 1 $ThisDev|head -1|awk '{print $2  $3}'`
    WebRecord "</body></html>"
    
}    

function PostDischargeFinals()
{
    $LogFunctionGoingThrough
    Web
    
    GetOscScreenShot > $DirToDischargeParams/ScreenShot.bmp
    convert $DirToDischargeParams/ScreenShot.bmp $DirToDischargeParams/ScreenShot.png
    convert -resize $icon_size $DirToDischargeParams/ScreenShot.png $DirToDischargeParams/graph.png
    convert /$SHM/Management/imgs/Charger_icon.jpg -gravity center $DirToDischargeParams/graph.png -gravity center +append $DirToDischargeParams/icon_.png
    convert -bordercolor Black -border 2x2 $DirToDischargeParams/icon_.png $DirToDischargeParams/icon.png

#    cp *.png $SHM0/RASPs/Charger/
    rm $DirToDischargeParams/ScreenShot.bmp
    PowerSupplyHVfansOFF
        
    echo OK
}

function GetOscScreenShot()
{
	echo ":SYSTem:KEY:PRESs MOFF"|$COMMAND
	mRelax
    #echo ":DISPLAY:DATA?  ON,OFF,PNG"|$COMMAND|tail -c +12 #uz nefunguje ..
    echo ":DISPLAY:DATA?  ON,OFF,BMP"|$COMMAND|tail -c +12
}

function ShortCircuitsDisEngage()
{
    LowerShortCircuitsDisEngage
}

function ShortCircuitsEngage()
{
    LowerShortCircuitsEngage
}

function GoToSafeState()
{
    HVoff; 
    CdHVrelayOFF;
    BtHVrelayOFF;
    Relax;
    ShortCircuitsEngage;
    HVlightOFF
}

function Emergency()
{
    GoToSafeState
}	





function ChargingResistorsAllOFF()
{
    $LogFunctionStart
    ChargingResistors=0
    ChargingResistor_I_DisEngage
    #ChargingResistor_II_DisEngage
    echo "Fast">$SHM/Charging
}	

function ChargingResistorsAllON()
{
    $LogFunctionStart
    ChargingResistors=1
    ChargingResistor_I_Engage
    #ChargingResistor_II_Engage
    echo "Slow">$SHM/Charging
}


function OpenOscDVMchannel()
{
    ConnectOscill # and connect Osclilloscope channels to the system
    echo ":DVM:ENABle ON;:DVM:SOURce CHANnel$1;DVM:MODE DC"|$COMMAND
    mRelax
    echo ":STOP;:CLEAR;:TRIGger:SWEEp AUTO;RUN"|$COMMAND
    mkdir -p /dev/shm/$TheOscilloscope
    touch /dev/shm/$TheOscilloscope/OscRequestStream
    tail -f /dev/shm/$TheOscilloscope/OscRequestStream|netcat -N $TheOscilloscope 5555 >> /dev/shm/$TheOscilloscope/OscRespondStream &
}


function ReadDVMOscilloscope()
{
    echo ":SYSTem:TIME?">> /dev/shm/$TheOscilloscope/OscRequestStream;mRelax
    echo ":DVM:CURRENT?">> /dev/shm/$TheOscilloscope/OscRequestStream;mRelax
    echo `tail -1 /dev/shm/$TheOscilloscope/OscRespondStream|xargs printf '%4.0f\n'`
}

function DVMDisable()
{
    echo ":STOP;:DVM:ENABle OFF"|$COMMAND
    DisConnectOscill # and disconnect Osclilloscope channels from the system
}



#Bt Et tests s 18 V zdrojem misto HV, see 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# *http://golem.fjfi.cvut.cz/shots/33132/
#./Dirigent.sh --discharge --UBt 25 --TBt 0 --Ucd 25 --Tcd 0 --preionization 1 --gas H --pressure 20 --comment "Bt Et tests s 30 V zdrojem misto HV"
# *http://golem.fjfi.cvut.cz/shots/33337/RASPs/Charger/Charger.html

#Et tests s 18 V zdrojem misto HV, see 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#./Dirigent.sh --discharge --UBt 0 --TBt 0 --Ucd 25 --Tcd 0 --preionization 1 --gas H --pressure 20 --comment "Et tests s 30 V zdrojem misto HV"
#Et tests s 30 V zdrojem misto HV, see http://golem.fjfi.cvut.cz/shots/33334/RASPs/Charger/Charger.html
#Dgrs;./Dirigent.sh -r "Charger EtTest"

#LV test setup
    #==============
    #SCALE=9
    #OFFSET=0
    #PROBE=100
    #==============

function EtTest()
{
   #SCALE=10 #LV PS
    SCALE=300 #HV PS
    OFFSET=-30
    echo "CHANnel1:DISPlay ON;CHANnel1:PROBe 100;CHANnel1:SCALe $SCALE;CHANnel1:OFFSet $OFFSET"|$COMMAND #HV PowSup
    echo "CHANnel3:DISPlay ON;CHANnel3:PROBe 100;CHANnel3:SCALe $SCALE;CHANnel3:OFFSet $OFFSET"|$COMMAND #Bt
    echo "CHANnel4:DISPlay ON;CHANnel4:PROBe 100;CHANnel4:SCALe $SCALE;CHANnel4:OFFSet $OFFSET"|$COMMAND #Et
DischargeFunction EngageBats >/dev/null
OpenOscDVMchannel  1
echo ":STOP;:CLEAR;:TRIGger:SWEEp AUTO;RUN"|$COMMAND;Relax
ChargingResistorsAllON;Relax
#ChargingResistor_I_DisEngage;mRelax # # Bacha, muze najizdet hrozne rychle
ShortCircuitsDisEngage;Relax
CdHVrelayON;Relax
HVon # Lze 2kV nebo 60V@Rigol
for i in `seq 1 4`; do
    PowSupVoltage=`ReadDVMOscilloscope RigolMSO5104Charger`
    LogIt "Charging ... HV=$PowSupVoltage V"
    sleep 1
done
HVoff;Relax
CdHVrelayOFF;
sleep 3
echo "FPANEL:PRESS SINGLESEQ"|netcat -q 1 StandardDAS 4000 #TektrMSO56 SingleSeq
mRelax
Discharge Trigger
sleep 2
ShortCircuitsEngage;mRelax
ChargingResistor_I_Engage
Discharge DisEngageBats >/dev/null
sleep 3
echo ":STOP;:DVM:ENABle OFF"|$COMMAND
killall netcat 
DisConnectOscill
}

#Bt tests s 18 V zdrojem misto HV, see 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Dgrs;./Dirigent.sh -r "Charger BtTest"
#./Dirigent.sh --discharge --UBt 25 --TBt 0 --Ucd  --Tcd 0 --preionization 1 --gas H --pressure 20 --comment "Bt tests s 30 V zdrojem misto HV"
# see http://golem.fjfi.cvut.cz/shots/33335/RASPs/Charger/Charger.html

function BtTest()
{
   #SCALE=10 #LV PS
    SCALE=300 #HV PS
    OFFSET=-30
    echo "CHANnel1:DISPlay ON;CHANnel1:PROBe 100;CHANnel1:SCALe $SCALE;CHANnel1:OFFSet $OFFSET"|$COMMAND #HV PowSup
    echo "CHANnel3:DISPlay ON;CHANnel3:PROBe 100;CHANnel3:SCALe $SCALE;CHANnel3:OFFSet $OFFSET"|$COMMAND #Bt
    echo "CHANnel4:DISPlay ON;CHANnel4:PROBe 100;CHANnel4:SCALe $SCALE;CHANnel4:OFFSet $OFFSET"|$COMMAND #Et

Discharge EngageBats >/dev/null
OpenOscDVMchannel  1
echo ":STOP;:CLEAR;:TRIGger:SWEEp AUTO;RUN"|$COMMAND;Relax
ChargingResistorsAllON;Relax
#ChargingResistor_I_DisEngage;mRelax # Bacha, muze najizdet hrozne rychle
ShortCircuitsDisEngage;Relax
BtHVrelayON;Relax
HVon # Lze 2kV nebo 60V@Rigol
for i in `seq 1 5`; do
    PowSupVoltage=`ReadDVMOscilloscope RigolMSO5104Charger`
    LogIt "Charging ... HV=$PowSupVoltage V"
    sleep 1
done
HVoff;Relax
BtHVrelayOFF
sleep 3
echo "FPANEL:PRESS SINGLESEQ"|netcat -q 1 StandardDAS 4000 #TektrMSO56a SingleSeq
mRelax
Discharge Trigger
sleep 2
ShortCircuitsEngage;mRelax
ChargingResistor_I_Engage
Discharge DisEngageBats >/dev/null
sleep 3
echo ":STOP;:DVM:ENABle OFF"|$COMMAND
killall netcat 
DisConnectOscill
}


function Sandbox()
{
    echo $RASPs
}
