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

source Rasp-Commons.sh


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

Drivers="Devices/uControllers/Drivers/UniPi"

source Drivers/UniPi/driver.sh

DirToDischargeParams=$SHM0/Operation/Discharge



function ShortCircuitsDisEngage()
{
    CallCentralFunction $RelayBoards ShortCircuits@PowerSupplies ON;
}

function ShortCircuitsEngage()
{
    CallCentralFunction $RelayBoards ShortCircuits@PowerSupplies OFF;
    
}

function CdcontactorON() { RelayON 13; }
function CdcontactorOFF() { RelayOFF 13; }	

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

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 PS_Commutator_ON() { RelayON 1 ; }
function PS_Commutator_OFF() { RelayOFF 1 ; }

function LV_PS_test_ON() { RelayON 3 ; }
function LV_PS_test_OFF() { RelayOFF 3 ; }

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 test, see http://golem.fjfi.cvut.cz/shots/33132/

function PrepareSessionEnv@SHM()
{
    MountCentralSHMEnvironment 
}

#LowVoltagePowerSupplyFlag=0 #NE! na to je Rasp-Bt_Ecd-Tests.sh !!

function HVon()
{
    $LogFunctionPassing

    Relax
    HVlightON
    CallCentralFunction $RelayBoards PowerSupplyHVcontactor@PowerSupplies ON;
    Relax
}	


function HVoff()
{

    HVlightOFF
    CallCentralFunction $RelayBoards PowerSupplyHVcontactor@PowerSupplies OFF;
    $LogFunctionPassing
    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 ChargingResistor_II_DisEngage() { RelayON 6 ; }
#function ChargingResistor_II_Engage() { RelayOFF 6 ; }


ChargingFlag=0
ChargingResistors=0




function GetReadyTheDischarge()
{
local UBt=$(<$SHM0/Infrastructure/Bt_Ecd/Parameters/u_bt)
local Ucd=$(<$SHM0/Infrastructure/Bt_Ecd/Parameters/u_cd)
local comment=`cat $SHMP/comment`

    $LogFunctionStart
    
    
      case $(<$SHM0/Infrastructure/Bt_Ecd/Parameters/o_bt) in 
            CW)
                LogIt "Discharge with Bt CW request"
                BtCommutatorClockWise
                ;;
            ACW)
                LogIt "Discharge with Bt ACW request"
                BtCommutatorAntiClockWise
                ;;
        esac

    
    case $(<$SHM0/Infrastructure/Bt_Ecd/Parameters/o_cd) in 
            CW)
                LogIt "Discharge with CD CW request"
                EtCommutatorClockWise
                ;;
            ACW)
                LogIt "Discharge with CD ACW request"
                EtCommutatorAntiClockWise
                ;;
        esac
       
        
    CdcontactorON #HotFix kvuli vypekani 11/23


    echo $Ucd > $DirToDischargeParams/U_cd_discharge_request
    echo $UBt > $DirToDischargeParams/U_bt_discharge_request
    if [[ $(<$SHM0/Operation/Discharge/Parameters/style) != 'dummy' ]]; 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 /$UBt V@UBt & $Ucd V@Ucd"
            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
                ChargingResistorsAllON;mRelax # In strange case Ucd>UBt
                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";
        CountDown $DummyDischargeCountDown "Dummy Discharge"
        
    fi
    cp $SHML/U_Bt_now $DirToDischargeParams/U_Bt_final
    cp $SHML/U_CD_now $DirToDischargeParams/U_CD_final
    $LogFunctionEnd
}    




function SecurePostDischargeState()
{
    GoToSafeState
    CountDown 5 "waiting to see discharging capacitors on the screen"
    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 
    $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
    
    
    
    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 GoToSafeState()
{
    HVoff; 
    CdHVrelayOFF;
    CdcontactorOFF; #HotFix kvuli vypekani 11/23
    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
}

