#include <281xEvTimersInit.h>
#include <adc_tools.h>
#include <alg_simple_scalar.h>
#include <break_regul.h>
#include <calc_rms_vals.h>
#include <calc_tempers.h>
#include <can_bs2bs.h>
#include <detect_errors.h>
#include <detect_errors_adc.h>
#include <detect_overload.h>
#include <detect_overload.h>
#include <edrk_main.h>
//#include <log_to_mem.h>
#include <math.h> 
#include <message_modbus.h>
#include <modbus_hmi.h>
#include <modbus_hmi_update.h>
#include <modbus_svu_update.h>
#include <optical_bus.h>
#include <overheat_limit.h>
#include <params.h>
#include <params_alg.h>
#include <params_norma.h>
#include <params_pwm24.h>
#include <params_temper_p.h>
#include <project.h>
#include <pump_control.h>
#include <PWMTMSHandle.h>
#include <PWMTools.h>
#include <sync_tools.h>
#include <v_rotor.h>
#include <vector.h>

#include "mathlib.h"
#include "params_hwp.h"

//#include "modbus_fill_table.h"

#include "big_dsp_module.h"
#include "control_station.h"
#include "CAN_Setup.h"

#include "global_time.h"
#include "IQmathLib.h"
#include "mathlib.h"

#include "modbus_table_v2.h"
#include "oscil_can.h"
#include "DSP281x_Examples.h"   // DSP281x Examples Include File
#include "DSP281x_SWPrioritizedIsrLevels.h"   // DSP281x Examples Include File
#include "DSP281x_Device.h"
#include "alg_pll.h"
#include "vector_control.h"
#include "CRC_Functions.h"
#include "RS_Functions.h"
#include "xp_project.h"
#include "sbor_shema.h"
#include "alarm_log_can.h"
#include "pwm_test_lines.h"
#include "master_slave.h"
#include "xp_write_xpwm_time.h"
#include "v_rotor_22220.h"
#include "log_to_memory.h"
#include "log_params.h"
#include "build_version.h"
#include "profile_interrupt.h"
#include "limit_power.h"
#include "pwm_logs.h"
#include "logs_hmi.h"
#include "alarm_log.h"
#include "can_protocol_ukss.h"

#include "ukss_tools.h"
#include "another_bs.h"
#include "temper_p_tools.h"
#include "digital_filters.h"
#include "pll_tools.h"
#include "ramp_zadanie_tools.h"
#include "uom_tools.h"
#include "synhro_tools.h"

#if (_SIMULATE_AC==1)
#include "sim_model.h"
#endif
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
//#pragma DATA_SECTION(ccc, ".slow_vars")
//int ccc[40] = {0,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1};



#pragma DATA_SECTION(f, ".slow_vars")
FLAG f = FLAG_DEFAULTS;

int cur1=0;
int cur2=0;

unsigned int old_time_edrk1 = 0, old_time_edrk2 = 0, prev_flag_special_mode_rs = 0;

#pragma DATA_SECTION(edrk, ".slow_vars")
EDRK edrk = EDRK_DEFAULT;




////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// задание оборотов от Задатчика PLUS, MINUS
// если выбран нужный режим
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
void set_oborots_from_zadat4ik(void)
{
static unsigned int old_time_edrk3 = 0, prev_PROVOROT;


  if (!(detect_pause_milisec(100,&old_time_edrk3)))
  return;

}


//////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// считываем цифровые входы
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
#define RASCEPITEL_MANUAL_ALWAYS_ON_2           1       // 1
#define TIME_ON_OFF_FOR_IMITATION_RASCEPITEL    50      // 5 сек.
#define TIME_FILTER_UMP_SIGNALS                 5       // 0.5 сек
#define TIME_FILTER_ALL_SIGNALS                 5       // 0.5 сек


#pragma DATA_SECTION(count_wait_filter, ".slow_vars")
unsigned int count_wait_filter[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0};
unsigned int counter_imit_rascepitel = 0;

void update_input_edrk(void)
{
    static unsigned int flag_imit_rascepitel = 0;
    static int st1=0;

// ANOTHER PCH
    edrk.from_second_pch.bits.RASCEPITEL = !FROM_ING_ANOTHER_RASCEPITEL;
    edrk.from_second_pch.bits.MASTER = FROM_ING_ANOTHER_MASTER_PCH;


// ING
#if (_FLOOR6==1)

	if (st1==0)
	{
	    edrk.from_zadat4ik.all = 0;
	    edrk.from_vpu.all = 0;

        edrk.from_ing1.bits.ALL_KNOPKA_AVARIA  = 0;//!FROM_ALL_KNOPKA_AVARIA;
        edrk.from_ing1.bits.BLOCK_IZOL_AVARIA  = 0;//!FROM_ING_BLOCK_IZOL_AVARIA;
        edrk.from_ing1.bits.BLOCK_IZOL_NORMA   = 1;//!FROM_ING_BLOCK_IZOL_NORMA;
        edrk.from_ing1.bits.LOCAL_REMOUTE      = 1;//0;//!FROM_ING_LOCAL_REMOUTE;
        edrk.from_ing1.bits.NAGREV_ON          = 1;//!FROM_ING_NAGREV_ON;
        edrk.from_ing1.bits.NASOS_NORMA        = 1;//!FROM_ING_NASOS_NORMA;
        edrk.from_ing1.bits.NASOS_ON           = 0;//!FROM_ING_NASOS_ON;
        edrk.from_ing1.bits.OHLAD_UTE4KA_WATER = 0;//!FROM_ING_OHLAD_UTE4KA_WATER;
        edrk.from_ing1.bits.UPC_24V_NORMA      = 1;//!FROM_ING_UPC_24V_NORMA;
        edrk.from_ing1.bits.OP_PIT_NORMA       = 1;//!FROM_ING_OP_PIT_NORMA;
        edrk.from_ing1.bits.VENTIL_ON          = 0;//!FROM_ING_VENTIL_ON;
        edrk.from_ing1.bits.VIPR_PREDOHR_NORMA = 1;//!FROM_ING_VIPR_PREDOHR_NORMA;

        edrk.from_ing1.bits.ZARYAD_ON          = 0;//!FROM_ING_ZARYAD_ON;
        edrk.from_ing1.bits.ZAZEML_OFF         = 1;//!FROM_ING_ZAZEML_OFF;
        edrk.from_ing1.bits.ZAZEML_ON          = 0;//!FROM_ING_ZAZEML_ON;

        edrk.from_ing2.bits.KEY_MINUS          = 0;//FROM_ING_OBOROTS_MINUS;
        edrk.from_ing2.bits.KEY_PLUS           = 0;//!FROM_ING_OBOROTS_PLUS;
        edrk.from_ing2.bits.KEY_KVITIR         = 0;//FROM_ING_LOCAL_KVITIR;

        edrk.from_ing2.bits.KEY_SBOR           = 0;//FROM_ING_SBOR_SHEMA;
        edrk.from_ing2.bits.KEY_RAZBOR         = 0;//FROM_ING_RAZBOR_SHEMA;

    //    edrk.from_ing1.bits.RASCEPITEL_ON      = 0;//FROM_ING_RASCEPITEL_ON_OFF;

 //       edrk.from_ing2.bits.SOST_ZAMKA         = !edrk.to_ing.bits.BLOCK_KEY_OFF;//1;//!FROM_ING_SOST_ZAMKA;


    // SHEMA
        edrk.from_shema.bits.RAZBOR_SHEMA      = 0;//FROM_BSU_RAZBOR_SHEMA;
        edrk.from_shema.bits.SBOR_SHEMA        = 0;//FROM_BSU_SBOR_SHEMA;

        edrk.from_shema.bits.ZADA_DISPLAY      = 0;//!FROM_BSU_ZADA_DISPLAY;
        edrk.from_shema.bits.SVU               = 0;//!FROM_BSU_SVU;
    //  edrk.from_shema.bits.KNOPKA_AVARIA     = FROM_ALL_KNOPKA_AVARIA;
        edrk.from_shema.bits.QTV_ON_OFF        = 0;//!FROM_SHEMA_QTV_ON_OFF;
        edrk.from_shema.bits.UMP_ON_OFF        = 0;//!FROM_SHEMA_UMP_ON_OFF;
        edrk.from_shema.bits.READY_UMP         = 1;//!FROM_SHEMA_READY_UMP;
        edrk.from_shema.bits.SVU_BLOCK_QTV     = 0;//!FROM_SVU_BLOCK_QTV;
        st1 = 1;
	}

	// имитация расцепителя
	if (edrk.to_ing.bits.RASCEPITEL_ON)
	    flag_imit_rascepitel = 1;
    if (edrk.to_ing.bits.RASCEPITEL_OFF)
        flag_imit_rascepitel = 0;

	 edrk.from_ing1.bits.RASCEPITEL_ON = imit_signals_rascepitel(&counter_imit_rascepitel, TIME_ON_OFF_FOR_IMITATION_RASCEPITEL, flag_imit_rascepitel, 0);
	/////


	edrk.from_ing2.bits.SOST_ZAMKA         = !edrk.to_ing.bits.BLOCK_KEY_OFF;
	if (edrk.to_ing.bits.NASOS_2_ON || edrk.to_ing.bits.NASOS_1_ON)
	{
	    edrk.from_ing1.bits.VENTIL_ON          =  1;
	    edrk.from_ing1.bits.NASOS_ON           =  1;
	}
	else
	{
	    edrk.from_ing1.bits.VENTIL_ON          =  0;
        edrk.from_ing1.bits.NASOS_ON           =  0;
	}
#else


	// ZADAT4IK
	    if (control_station.alive_control_station[CONTROL_STATION_ZADATCHIK_CAN])
	       edrk.from_zadat4ik.all = Unites[ZADATCHIK_CAN][16];
	    else
	        edrk.from_zadat4ik.all = 0;

	    if (control_station.alive_control_station[CONTROL_STATION_VPU_CAN])
	       edrk.from_vpu.all = Unites[VPU_CAN][16];
	    else
	        edrk.from_vpu.all = 0;



	edrk.from_ing1.bits.ALL_KNOPKA_AVARIA  = !FROM_ALL_KNOPKA_AVARIA;
	edrk.from_ing1.bits.BLOCK_IZOL_AVARIA  = !FROM_ING_BLOCK_IZOL_AVARIA;
	edrk.from_ing1.bits.BLOCK_IZOL_NORMA   = !FROM_ING_BLOCK_IZOL_NORMA;
	edrk.from_ing1.bits.LOCAL_REMOUTE 	   = !FROM_ING_LOCAL_REMOUTE;
	edrk.from_ing1.bits.NAGREV_ON 		   = !FROM_ING_NAGREV_ON;
	edrk.from_ing1.bits.NASOS_NORMA        = !FROM_ING_NASOS_NORMA;
	edrk.from_ing1.bits.NASOS_ON 		   = !FROM_ING_NASOS_ON;
	edrk.from_ing1.bits.OHLAD_UTE4KA_WATER = !FROM_ING_OHLAD_UTE4KA_WATER;
	edrk.from_ing1.bits.UPC_24V_NORMA 	   = !FROM_ING_UPC_24V_NORMA;
	edrk.from_ing1.bits.OP_PIT_NORMA 	   = !FROM_ING_OP_PIT_NORMA;
	edrk.from_ing1.bits.VENTIL_ON 		   = !FROM_ING_VENTIL_ON;
	edrk.from_ing1.bits.VIPR_PREDOHR_NORMA = !FROM_ING_VIPR_PREDOHR_NORMA;

	edrk.from_ing1.bits.ZARYAD_ON 		   = !FROM_ING_ZARYAD_ON;
	edrk.from_ing1.bits.ZAZEML_OFF 		   = !FROM_ING_ZAZEML_OFF;
	edrk.from_ing1.bits.ZAZEML_ON 		   = !FROM_ING_ZAZEML_ON;

    edrk.from_ing2.bits.KEY_MINUS          = FROM_ING_OBOROTS_MINUS;
    edrk.from_ing2.bits.KEY_PLUS           = !FROM_ING_OBOROTS_PLUS;
    edrk.from_ing2.bits.KEY_KVITIR         = FROM_ING_LOCAL_KVITIR;

    edrk.from_ing2.bits.KEY_SBOR           = FROM_ING_SBOR_SHEMA;
    edrk.from_ing2.bits.KEY_RAZBOR         = FROM_ING_RAZBOR_SHEMA;

#if(RASCEPITEL_MANUAL_ALWAYS_ON_2)

    // имитация расцепителя
    if (edrk.to_ing.bits.RASCEPITEL_ON)
        flag_imit_rascepitel = 1;
    if (edrk.to_ing.bits.RASCEPITEL_OFF)
        flag_imit_rascepitel = 0;

     edrk.from_ing1.bits.RASCEPITEL_ON = imit_signals_rascepitel(&counter_imit_rascepitel, TIME_ON_OFF_FOR_IMITATION_RASCEPITEL, flag_imit_rascepitel, 0);

#else
    edrk.from_ing1.bits.RASCEPITEL_ON      = FROM_ING_RASCEPITEL_ON_OFF;
#endif
    edrk.from_ing2.bits.SOST_ZAMKA         = !FROM_ING_SOST_ZAMKA;


// SHEMA
	edrk.from_shema.bits.RAZBOR_SHEMA	   = FROM_BSU_RAZBOR_SHEMA;
	edrk.from_shema.bits.SBOR_SHEMA        = FROM_BSU_SBOR_SHEMA;

	if (edrk.from_shema.bits.RAZBOR_SHEMA==1 && edrk.from_shema.bits.SBOR_SHEMA)
	{
	    // защита от замыкания и одновременного нажатия
	    edrk.from_shema.bits.RAZBOR_SHEMA = 0;
	    edrk.from_shema.bits.SBOR_SHEMA = 0;
	}
    edrk.from_shema_filter.bits.RAZBOR_SHEMA = filter_digital_input( edrk.from_shema_filter.bits.RAZBOR_SHEMA,
                                                                     &count_wait_filter[0],
                                                                     TIME_FILTER_ALL_SIGNALS,
                                                                     edrk.from_shema.bits.RAZBOR_SHEMA);


    edrk.from_shema_filter.bits.SBOR_SHEMA = filter_digital_input( edrk.from_shema_filter.bits.SBOR_SHEMA,
                                                                     &count_wait_filter[1],
                                                                     TIME_FILTER_ALL_SIGNALS,
                                                                     edrk.from_shema.bits.SBOR_SHEMA);

	edrk.from_shema.bits.ZADA_DISPLAY 	   = !FROM_BSU_ZADA_DISPLAY;
    edrk.from_shema_filter.bits.ZADA_DISPLAY = filter_digital_input( edrk.from_shema_filter.bits.ZADA_DISPLAY,
                                                                     &count_wait_filter[2],
                                                                     TIME_FILTER_ALL_SIGNALS,
                                                                     edrk.from_shema.bits.ZADA_DISPLAY);

	edrk.from_shema.bits.SVU 			   = !FROM_BSU_SVU;
    edrk.from_shema_filter.bits.SVU = filter_digital_input( edrk.from_shema_filter.bits.SVU,
                                                                     &count_wait_filter[3],
                                                                     TIME_FILTER_ALL_SIGNALS,
                                                                     edrk.from_shema.bits.SVU);


//	edrk.from_shema.bits.KNOPKA_AVARIA 	   = FROM_ALL_KNOPKA_AVARIA;
	edrk.from_shema.bits.QTV_ON_OFF		   = !FROM_SHEMA_QTV_ON_OFF;
    edrk.from_shema_filter.bits.QTV_ON_OFF = filter_digital_input( edrk.from_shema_filter.bits.QTV_ON_OFF,
                                                                     &count_wait_filter[4],
                                                                     TIME_FILTER_ALL_SIGNALS,
                                                                     edrk.from_shema.bits.QTV_ON_OFF);



	/// фильтрация FROM_SHEMA_UMP_ON_OFF
//	edrk.local_ump_on_off                  = !FROM_SHEMA_UMP_ON_OFF;
//
//	if (edrk.local_ump_on_off)
//	{
//	    if (edrk.local_ump_on_off_count>=TIME_FILTER_UMP_SIGNALS)
//	        edrk.from_shema.bits.UMP_ON_OFF  = 1;
//	    else
//	        edrk.local_ump_on_off_count++;
//	}
//	else
//	{
//        if (edrk.local_ump_on_off_count==0)
//            edrk.from_shema.bits.UMP_ON_OFF  = 0;
//        else
//            edrk.local_ump_on_off_count--;
//	}
//
//
	edrk.from_shema.bits.UMP_ON_OFF        = !FROM_SHEMA_UMP_ON_OFF;
    edrk.from_shema_filter.bits.UMP_ON_OFF = filter_digital_input( edrk.from_shema_filter.bits.UMP_ON_OFF,
                                                                     &count_wait_filter[5],
                                                                     TIME_FILTER_UMP_SIGNALS,
                                                                     edrk.from_shema.bits.UMP_ON_OFF);






	/// фильтрация FROM_SHEMA_READY_UMP
//	edrk.local_ready_ump                  = !FROM_SHEMA_READY_UMP;
//
//    if (edrk.local_ready_ump)
//    {
//        if (edrk.local_ready_ump_count>=TIME_FILTER_UMP_SIGNALS)
//            edrk.from_shema.bits.READY_UMP  = 1;
//        else
//            edrk.local_ready_ump_count++;
//    }
//    else
//    {
//        if (edrk.local_ready_ump_count==0)
//            edrk.from_shema.bits.READY_UMP  = 0;
//        else
//            edrk.local_ready_ump_count--;
//    }
//

	edrk.from_shema.bits.READY_UMP         = !FROM_SHEMA_READY_UMP;
    edrk.from_shema_filter.bits.READY_UMP = filter_digital_input( edrk.from_shema_filter.bits.READY_UMP,
                                                                     &count_wait_filter[6],
                                                                     TIME_FILTER_UMP_SIGNALS,
                                                                     edrk.from_shema.bits.READY_UMP);



	edrk.from_shema.bits.SVU_BLOCK_QTV     = !FROM_SVU_BLOCK_QTV;
    edrk.from_shema_filter.bits.SVU_BLOCK_QTV = filter_digital_input( edrk.from_shema_filter.bits.SVU_BLOCK_QTV,
                                                                     &count_wait_filter[7],
                                                                     TIME_FILTER_ALL_SIGNALS,
                                                                     edrk.from_shema.bits.SVU_BLOCK_QTV);

#endif
}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// определение откуда получать задачу на обороты
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
void get_where_oborots(void)
{

////	if (CAN_timeout[get_real_out_mbox(MPU_TYPE_BOX,0)-1]==0)
//    if (CAN_timeout[get_real_in_mbox(MPU_TYPE_BOX,0)]==0)
//	{
//	  edrk.W_from_SVU = modbus_table_can_in[14].all;
//      edrk.W_from_DISPLAY = modbus_table_can_in[16].all;
//	}
//	else
//	{
//	  edrk.W_from_SVU = 0;
//	  edrk.W_from_DISPLAY = 0;
//	}
//
//
//
//
//	if (edrk.from_shema.bits.SVU)
//	{
//	 edrk.W_from_all = edrk.W_from_SVU;
//	 edrk.W_from_ZADAT4IK = edrk.W_from_all;
//	}
//	else
//	{
//	  if (edrk.from_shema.bits.ZADA_DISPLAY)
//	  {
//	   edrk.W_from_all = edrk.W_from_DISPLAY;
//	   edrk.W_from_ZADAT4IK = edrk.W_from_all;
//	  }
//	  else
//	   edrk.W_from_all = edrk.W_from_ZADAT4IK;
//	}

}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

unsigned int toggle_status_lamp(unsigned int bb1, unsigned int flag)
{

    if (bb1==1 && flag==0)
    {
        return 0;
    }

    if (bb1==0 && flag==0)
    {
        return 0;
    }

    if (bb1==1 && flag==1)
    {
            return 0;
    }

    if (bb1==0 && flag==1)
    {
            return 1;
    }
    return 0;
}

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// записываем цифровые выходы
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
void update_output_edrk(void)
{
    unsigned int b;
    static unsigned int time_toggle1=0,time_toggle2=0;

//to ingetim

	TO_ING_NAGREV_OFF					= !edrk.to_ing.bits.NAGREV_OFF;
	TO_ING_NASOS_1_ON					= !edrk.to_ing.bits.NASOS_1_ON;
	TO_ING_NASOS_2_ON					= !edrk.to_ing.bits.NASOS_2_ON;
  //	TO_ING_RESET_BLOCK_IZOL				= !edrk.to_ing.bits.RESET_BLOCK_IZOL;
	TO_ING_SMALL_LAMPA_AVARIA			= edrk.to_ing.bits.SMALL_LAMPA_AVARIA;

	if (edrk.disable_rascepitel_work)
	{

	}
	else
	{
	    TO_ING_RASCEPITEL_OFF               = !edrk.to_ing.bits.RASCEPITEL_OFF;
	    TO_ING_RASCEPITEL_ON                = !edrk.to_ing.bits.RASCEPITEL_ON;
	}

// ANOTHER PCH
    TO_SECOND_PCH_MASTER                = edrk.to_second_pch.bits.MASTER;
    TO_SECOND_PCH_ALARM                 = !edrk.to_second_pch.bits.ALARM;



//to_shema
//
//#if (ENABLE_USE_QTV==1)
//	TO_STEND_QM_ON_INVERS				= !edrk.to_shema.bits.QTV_ON;
//#endif


        TO_ING_LAMPA_ZARYAD                 = !edrk.Status_Ready.bits.Batt;
        TO_ING_ZARYAD_ON                    = !edrk.to_ing.bits.ZARYAD_ON;
        TO_ING_BLOCK_KEY_OFF                = !edrk.to_ing.bits.BLOCK_KEY_OFF;

#if (MODE_QTV_UPRAVLENIE==1)
        TO_SHEMA_QTV_ON_OFF                     = !edrk.to_shema.bits.QTV_ON_OFF;
#endif


#if (MODE_QTV_UPRAVLENIE==2)
        TO_SHEMA_QTV_OFF                        = !edrk.to_shema.bits.QTV_OFF;
        TO_SHEMA_QTV_ON                         = !edrk.to_shema.bits.QTV_ON;
#endif

        TO_SHEMA_ENABLE_QTV                     = !edrk.to_shema.bits.ENABLE_QTV;
        TO_SHEMA_UMP_ON_OFF                     = !edrk.to_shema.bits.UMP_ON_OFF;







//lamps APL
//	if (edrk.Sbor)// && edrk.from_ing.bits2.GED_NAMAGNI4EN==0)
//	{
//	    if (edrk.Status_Ready.bits.ready5==0)
//		  edrk.to_zadat4ik.APL_LAMS0.bits.SBOR_SIL_SHEMA = 1;
//		else
//		  edrk.to_zadat4ik.APL_LAMS0.bits.SBOR_SIL_SHEMA = 0;
//	}
//	else
//	{
//		edrk.to_zadat4ik.APL_LAMS0.bits.SBOR_SIL_SHEMA = 0;
//	}



	edrk.to_vpu.BIG_LAMS.bits.GOTOV2 =  edrk.Status_Ready.bits.ready_final;
	edrk.to_vpu.BIG_LAMS.bits.PEREGRUZKA = edrk.to_zadat4ik.BIG_LAMS.bits.OGRAN_POWER;
	edrk.to_vpu.BIG_LAMS.bits.PODDERG_OBOROTS = 0;//
	edrk.to_vpu.BIG_LAMS.bits.VPU = edrk.to_zadat4ik.APL_LAMS0.bits.OBOROT_VPU;

}


///////////////////////////////////////////////
///////////////////////////////////////////////
// ОсновнаЯ программа 
///////////////////////////////////////////////
///////////////////////////////////////////////

///////////////////////////////////////////////
void update_lamp_alarm(void)
{
	if ((edrk.errors.e0.all)
	   || (edrk.errors.e1.all)
	   || (edrk.errors.e2.all)
	   || (edrk.errors.e3.all)
	   || (edrk.errors.e4.all)
	   || (edrk.errors.e5.all)
	   || (edrk.errors.e6.all)
	   || (edrk.errors.e7.all)
	   || (edrk.errors.e8.all)
	   || (edrk.errors.e9.all)
       || (edrk.errors.e10.all)
       || (edrk.errors.e11.all)
	   || (edrk.errors.e12.all)
	   )
    {
 	  edrk.to_ing.bits.SMALL_LAMPA_AVARIA = 1;
 //	  edrk.to_second_pch.bits.ALARM = 1;
	  edrk.summ_errors = 1;
	  edrk.Stop |= 1;
	}
	else
	{
	  edrk.to_ing.bits.SMALL_LAMPA_AVARIA = 0;
	  edrk.to_second_pch.bits.ALARM = 0;
	  edrk.summ_errors = 0;
	}

}
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////




///////////////////////////////////////////////
///////////////////////////////////////////////
#define TIME_WAIT_RELE_QTV_ON 30 //2 sec
#define TIME_WAIT_RELE_QTV_OFF 30 //2 sec

#define TIME_WAIT_ANSWER_QTV_ON     TIME_WAIT_ERROR_QTV //150 //15 sec
#define TIME_WAIT_ANSWER_QTV_OFF    50 //4 sec

///////////////////////////////////////////////
int qtv_on_off(unsigned int flag)
{
static unsigned int time_wait_rele_on_qtv=0;
static unsigned int time_wait_rele_off_qtv=0;
static unsigned int time_wait_answer_on_qtv=0;
static unsigned int time_wait_answer_off_qtv=0;
static unsigned int count_err_on = 0;


int cmd_qtv=0;//,cmd_p2=0;
static int QTV_Ok = 0;
static int prev_error = 0;


   cmd_qtv = 0;
//   cmd_p2 = 0;

   if ( flag==1 && edrk.summ_errors==0)	
   {
	   cmd_qtv = 1;
   }
   else
   {
	   cmd_qtv = 0;
   }



   edrk.cmd_to_qtv = cmd_qtv;

   if (cmd_qtv)
   {   
        edrk.to_shema.bits.ENABLE_QTV = 1;
        edrk.to_shema.bits.QTV_OFF = 1;

        if ((pause_detect_error(&time_wait_rele_on_qtv,TIME_WAIT_RELE_QTV_ON,1)==0) && edrk.from_shema_filter.bits.QTV_ON_OFF==0)
        {
#if (MODE_QTV_UPRAVLENIE==2)
		  edrk.to_shema.bits.QTV_ON = 1;
#endif
#if (MODE_QTV_UPRAVLENIE==1)
		  edrk.to_shema.bits.QTV_ON_OFF = 1;
#endif
        }
		else
		  edrk.to_shema.bits.QTV_ON = 0;


		if (pause_detect_error(&time_wait_answer_on_qtv,TIME_WAIT_ANSWER_QTV_ON,1)==0)
		{

		   if (edrk.from_shema_filter.bits.QTV_ON_OFF==1)
  			  QTV_Ok = 1;

		}
		else
		{

		    // была команда на вкл, но сухой контакт не пришел
			if (edrk.from_shema_filter.bits.QTV_ON_OFF==0)
			{
#if (WORK_ON_STEND_D)
			  if (pause_detect_error(&count_err_on,TIME_WAIT_ANSWER_QTV_ON,1))
			  {
			      edrk.errors.e6.bits.QTV_ERROR_NOT_ANSWER |= 1;
			      QTV_Ok = 0;
			  }
#else
			  edrk.errors.e6.bits.QTV_ERROR_NOT_ANSWER |= 1;
			  QTV_Ok = 0;
#endif
			}
			else
			    count_err_on = 0;

		}

		time_wait_rele_off_qtv = 0;
		time_wait_answer_off_qtv = 0;
   }
   else
   {
		QTV_Ok = 0;
		edrk.to_shema.bits.ENABLE_QTV = 0;
        time_wait_rele_on_qtv = 0;
		time_wait_answer_on_qtv = 0;

		edrk.to_shema.bits.QTV_ON = 0;

		edrk.to_shema.bits.QTV_ON_OFF = 0;

//        if (pause_detect_error(&time_wait_rele_off_qtv,TIME_WAIT_RELE_QTV_OFF,1)==0)
//		  edrk.to_shema.bits.QTV_OFF = 1;
//		else
		  edrk.to_shema.bits.QTV_OFF = 0;
		

		if (pause_detect_error(&time_wait_answer_off_qtv,TIME_WAIT_ANSWER_QTV_OFF,1)==0)
		{
			
		}
		else
		{
			if (edrk.from_shema_filter.bits.QTV_ON_OFF==1)
			  edrk.errors.e6.bits.QTV_ERROR_NOT_ANSWER |= 1;
		}


		if (prev_error!=edrk.summ_errors && edrk.summ_errors)
		{
		  if (pause_detect_error(&time_wait_rele_off_qtv,TIME_WAIT_RELE_QTV_OFF,1)==1)
		     time_wait_rele_off_qtv = 0; 
		}


   }

   prev_error = edrk.summ_errors;
   return (QTV_Ok);


}
///////////////////////////////////////////////
///////////////////////////////////////////////

///////////////////////////////////////////////
void detect_kvitir_from_all(void)
{

  static int prev_kvitir=0;

  edrk.Kvitir = control_station.active_array_cmd[CONTROL_STATION_CMD_CHECKBACK]
                                                 || edrk.from_ing2.bits.KEY_KVITIR
                                                 || edrk.from_zadat4ik.bits.KVITIR;

 /*
  if (edrk.RemouteFromRS)
    edrk.Kvitir = edrk.KvitirRS;

  if (edrk.RemouteFromVPU)
    edrk.Kvitir = edrk.KvitirVPU;

  if (edrk.RemouteFromDISPLAY)
    edrk.Kvitir = edrk.from_display.bits.KVITIR;//edrk.KvitirDISPLAY;

  if (edrk.RemouteFromMPU)
    edrk.Kvitir = edrk.KvitirMPU;
*/

  if (edrk.Kvitir==1 && prev_kvitir==0)
  {

    if (edrk.Status_Ready.bits.ready_final==0 && edrk.Go==0 && edrk.Stop == 1)
	{
      edrk.KvitirProcess = 1;
	  project.clear_errors_all_plates();
	  clear_errors();
      edrk.KvitirProcess = 0;
	}
    clear_warnings();
 /*   edrk.KvitirDISPLAY = 0;
	edrk.KvitirVPU = 0;
	edrk.KvitirMPU = 0;
	edrk.KvitirSVU = 0;
	edrk.KvitirRS = 0;
	*/
  }

  prev_kvitir = edrk.Kvitir;
}

///////////////////////////////////////////////
unsigned int get_ready_1(void)
{
    unsigned int r1, r2;



    if (project.cds_in[0].status == component_Ready
            && project.cds_in[1].status == component_Ready
              && project.cds_out[0].status == component_Ready
              && project.cds_tk[0].status == component_Ready
              && project.cds_tk[1].status == component_Ready
              && project.cds_tk[2].status == component_Ready
              && project.cds_tk[3].status == component_Ready
              && project.adc[0].status == component_Ready
              && project.adc[1].status == component_Ready
              && project.hwp[0].status == component_Ready
              )
      r2 = 1;
    else
      r2 = 0;


    r1 = (edrk.ms.ready1 && edrk.from_ing1.bits.NASOS_NORMA
            && edrk.from_ing1.bits.ZAZEML_ON==0 && edrk.from_ing1.bits.ZAZEML_OFF==1
            && edrk.from_ing1.bits.VIPR_PREDOHR_NORMA
            && edrk.from_ing1.bits.BLOCK_IZOL_NORMA
            && edrk.from_ing1.bits.OP_PIT_NORMA
            && edrk.from_ing1.bits.UPC_24V_NORMA
            && r2);

    return r1;


}
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////



void set_zadanie_u_charge(void)
{

//	edrk.ZadanieU_Charge = edrk.ZadanieU_Charge_RS;

//	edrk.iq_ZadanieU_Charge = _IQ(edrk.ZadanieU_Charge/NORMA_ACP);

    if (edrk.zadanie.ZadanieU_Charge<=100)
    {
        edrk.iqMIN_U_ZPT = _IQ(-50.0/NORMA_ACP);
        edrk.iqMIN_U_IN  = _IQ(-50.0/NORMA_ACP);
    }
    else
    {

        edrk.iqMIN_U_ZPT = _IQ(edrk.zadanie.ZadanieU_Charge*MIN_U_PROC/NORMA_ACP);
        edrk.iqMIN_U_IN  = _IQ(edrk.zadanie.ZadanieU_Charge*MIN_U_PROC/NORMA_ACP);

    }

    if (edrk.zadanie.ZadanieU_Charge<LEVEL_DETECT_U_SMALL)
    {
	  edrk.iqMAX_U_ZPT_Predzaryad = _IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC_SMALL/NORMA_ACP);
	  edrk.iqMAX_U_ZPT_Global = edrk.iqMAX_U_ZPT_Predzaryad + _IQ(ADD_U_MAX_GLOBAL_SMALL/NORMA_ACP); // +500V

    }
    else
    {
      edrk.iqMAX_U_ZPT_Predzaryad = _IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC/NORMA_ACP);
      edrk.iqMAX_U_ZPT_Global = edrk.iqMAX_U_ZPT_Predzaryad + _IQ(ADD_U_MAX_GLOBAL/NORMA_ACP); // +200V

      if (edrk.iqMAX_U_ZPT_Global>U_D_MAX_ERROR_GLOBAL)
          edrk.iqMAX_U_ZPT_Global = U_D_MAX_ERROR_GLOBAL;
    }

    edrk.iqMAX_U_ZPT = edrk.iqMAX_U_ZPT_Global;//_IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC/NORMA_ACP);
    edrk.iqMAX_U_IN = _IQ(edrk.zadanie.ZadanieU_Charge*MAX_U_PROC/NORMA_ACP);

    edrk.zadanie.iq_set_break_level = _IQ(NOMINAL_U_BREAK_LEVEL/NORMA_ACP);

}


///////////////////////////////////////////////
///////////////////////////////////////////////
// ОсновнаЯ программа 
///////////////////////////////////////////////
///////////////////////////////////////////////

////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
#define TIME_WAIT_SBOR_1  1
#define TIME_WAIT_SBOR_2  3

void get_sumsbor_command(void)
{
    static unsigned int prev_SBOR_SHEMA = 0;
    static unsigned int prev_SBOR_SHEMA_ANOTHER_BS = 0;
    unsigned int SBOR_SHEMA_ANOTHER_BS = 0;
    static unsigned int Sbor, first=1, w_sbor = 0, Sbor_f = 0;

    Sbor = edrk.SumSbor;

    if (Sbor == 0)
        edrk.run_razbor_shema = 0;

    SBOR_SHEMA_ANOTHER_BS = read_cmd_sbor_from_bs();

    // есть команда сбор схемы с активного пульта
    if (edrk.Status_Ready.bits.ImitationReady2==0 &&
            control_station.active_array_cmd[CONTROL_STATION_CMD_CHARGE]==1 && (prev_SBOR_SHEMA==0)
            && edrk.from_ing1.bits.ALL_KNOPKA_AVARIA==0 && edrk.summ_errors==0
            && control_station.active_array_cmd[CONTROL_STATION_CMD_UNCHARGE]==0
            )
    {
            Sbor = 1;
    }

    if (control_station.active_array_cmd[CONTROL_STATION_CMD_UNCHARGE]==1
          //  || edrk.from_shema_filter.bits.RAZBOR_SHEMA // подключили разбор по кнопке с ЗО минуя активный пост управления
            )
    {
        edrk.run_razbor_shema = 1;
 //       Sbor = 0;
    }


    if (edrk.StartGEDfromZadanie==0 && edrk.run_razbor_shema)
        Sbor = 0;


// разбор этого БС по разбору другого БС?
    if (SBOR_SHEMA_ANOTHER_BS==0 && prev_SBOR_SHEMA_ANOTHER_BS==1)
    {
        Sbor = 0;
    }

    prev_SBOR_SHEMA = control_station.active_array_cmd[CONTROL_STATION_CMD_CHARGE];

    prev_SBOR_SHEMA_ANOTHER_BS = SBOR_SHEMA_ANOTHER_BS;


    // разбор по аварии и кнопке!
    if (edrk.from_ing1.bits.ALL_KNOPKA_AVARIA || edrk.summ_errors)
    {
        Sbor = 0;
    }

    if (Sbor)
    {
//        if (edrk.flag_second_PCH == 0)
//        {
//            if (w_sbor<TIME_WAIT_SBOR_1)
//                w_sbor++;
//            else
//                Sbor_f = 1;
//        }
//        else
//        {
//            if (w_sbor<TIME_WAIT_SBOR_2)
//                w_sbor++;
//            else
//                Sbor_f = 1;
//        }
        Sbor_f = 1;
    }
    else
    {
        Sbor_f = 0;
        w_sbor = 0;

    }

    /////////////////////////////////
    /////////////////////////////////
    /////////////////////////////////

    if (Sbor_f)
    {
        if (first)
        {
            if (optical_read_data.data.cmd.bit.ready_cmd==CODE_READY_CMD_READY1TO2) // другой ПЧ уже поехал собираться
                edrk.flag_another_bs_first_ready12 = 1;
            else
                edrk.flag_this_bs_first_ready12 = 1;
        }
        first = 0;
    }
    else
    {
        edrk.flag_another_bs_first_ready12 = 0;
        edrk.flag_this_bs_first_ready12 = 0;
        first = 1;
    }

    edrk.SumSbor = Sbor_f;

}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////



void edrk_init(void)
{

    edrk.Uzad_max = _IQ(K_STATOR_MAX); // макс амплитуда в Км для минимального импульса = DEF_PERIOD_MIN_MKS
    edrk.iq_bpsi_normal = _IQ(BPSI_NORMAL/NORMA_FROTOR);
 //   edrk.iq_bpsi_max = _IQ(BPSI_MAXIMAL/NORMA_FROTOR);
//    edrk.iq_f_provorot = _IQ(F_PROVOROT/NORMA_FROTOR);

    init_simple_scalar();

    edrk.flag_enable_update_hmi = 1;


    edrk.zadanie.ZadanieU_Charge = NOMINAL_U_ZARYAD;
    edrk.zadanie.iq_ZadanieU_Charge = _IQ(NOMINAL_U_ZARYAD/NORMA_ACP);

    edrk.zadanie.iq_set_break_level = _IQ(NOMINAL_U_BREAK_LEVEL/NORMA_ACP);

    control_station.setup_time_detect_active[CONTROL_STATION_TERMINAL_RS232] = 50;

#if (_SIMULATE_AC==1)
    sim_model_init();
#endif

}

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////


void edrk_init_variables(void) {
    unsigned int i = 0, size_data_logs = 0;


    int *pf = (int*)&f;
    for (i = 0; i < sizeof(f) / sizeof(int); i++) {
        *(pf + i) = 0;
    }


    init_profile_interrupt();
    edrk_clear_cmd_ukss();

    edrk.flag_second_PCH = get_adr_pcb_controller();

    edrk.number_can_box_terminal_cmd = 1;
    edrk.number_can_box_terminal_oscil = 0;

    edrk.buildDay = build_day;
    edrk.buildMonth = build_month;
    edrk.buildYear = build_year;


/*    if (edrk.flag_second_PCH==0)
    {
      edrk.number_can_box_terminal_cmd = 1;
      edrk.number_can_box_terminal_oscil = 0;
    }
    else
    {
      edrk.number_can_box_terminal_cmd = 3;
      edrk.number_can_box_terminal_oscil = 2;
    }
*/

//  clear_all_i_phase();
#if(SENSOR_ALG==SENSOR_ALG_23550)
    rotorInit();
#endif
#if(SENSOR_ALG==SENSOR_ALG_22220)
// 22220 
    rotorInit_22220();
#endif
    clear_table_remoute();
    initModbusTable();
    clear_modbus_table_in();
    clear_modbus_table_out();
//    init_global_time_struct(FREQ_PWM);
 //   fillLogArea();

    oscil_can.clear(&oscil_can);
    oscil_can.number_can_box_terminal_oscil = edrk.number_can_box_terminal_oscil;
    oscil_can.number_can_box_terminal_cmd   = edrk.number_can_box_terminal_cmd;


    control_station.clear(&control_station);

    init_detect_overloads();
    edrk_init();
    size_data_logs = prepare_data_to_logs();
    initLogSize(size_data_logs, size_data_logs  );

    init_ramp_all_zadanie();
    init_analog_protect_levels();
    init_detect_overloads();
    init_50hz_input_net50hz();
    init_all_limit_koeffs();



    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_IZAD] = NOMINAL_SET_IZAD;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_KM]  = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_U_ZARYAD] = NOMINAL_U_ZARYAD;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_K_U_DISBALANCE] = NOMINAL_SET_K_U_DISBALANCE;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_K_PLUS_U_DISBALANCE] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SET_LIMIT_POWER] = NOMINAL_SET_LIMIT_POWER;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_UFCONST_VECTOR] = 1;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_SCALAR_FOC] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_ENABLE_ON_CHARGE] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_GO] = 1;

    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_ON_PUMP] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_ENABLE_ON_CHARGE] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_ON_QTV] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_ON_UMP] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_MANUAL_DISCHARGE] = 0;

    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_ROTOR_POWER] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_INTERRUPT_SYNC] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_DISABLE_INTERRUPT_TIMER2] = 0;
    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_STOP_LOGS] = 0;

    control_station.array_cmd[CONTROL_STATION_INGETEAM_PULT_RS485][CONTROL_STATION_CMD_SET_U_ZARYAD] = NOMINAL_U_ZARYAD;
    control_station.array_cmd[CONTROL_STATION_MPU_SVU_CAN][CONTROL_STATION_CMD_SET_U_ZARYAD] = NOMINAL_U_ZARYAD;

    control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_WDOG_OFF] = 0;


    for (i=0;i<CONTROL_STATION_CMD_LAST;i++)
        control_station.array_cmd[CONTROL_STATION_TERMINAL_CAN][i] = control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][i];


    ramp_all_zadanie(2);

    set_zadanie_u_charge();
    init_Uin_rms();
}


//////////////////////////////////////////////////////////
void edrk_init_before_loop(void)
{
#if (MODE_DISABLE_ENABLE_WDOG==1)
    stop_wdog();
#else

#if (_FLOOR6==1)
#else
    start_wdog();
#endif

#endif

    disable_flag_special_mode_rs = 0;
}
//////////////////////////////////////////////////////////

#define FREQ_TIMER_3    (FREQ_PWM*2)

void edrk_init_before_main(void)
{
    static int f_cmd1 = 0;
    static int f_cmd2 = 0;
    static int f_cmd3 = 0;
    static int p_f_cmd1 = 0;
    static int p_f_cmd2 = 0;
    static int p_f_cmd3 = 0;


    volatile int final_code = 0;
    int i = 0, k = 0;

    setup_sync_line();
    edrk.disable_interrupt_sync = -1;

    edrk_init_variables();

////////////////////////////////////////
// global timer
////////////////////////////////////////
    init_global_time_struct(FREQ_TIMER_3);
    init_evb_timer3(FREQ_TIMER_3,&global_time_interrupt);
    start_evb_timer3();// run global_time_interrupt
///////////////////////////////////////

    /// для теста 2
/*
    while(1)
    {
       static int f_s_set = 0;
       static int f_s_read = 0;


       if (f_s_set)
           i_sync_pin_on();
       else
           i_sync_pin_off();

       f_s_read = get_status_sync_line();
    }
    */


/// для теста 1
/*
    project.enable_all_interrupt();

    //start_sync_interrupt();

    while(1)
    {
       static int f_s_set = 0;
       static int f_s_read = 0;


       if (f_s_set)
           i_sync_pin_on();
       else
           i_sync_pin_off();

       f_s_read = get_status_sync_line();

       if (f_cmd1 != p_f_cmd1)
       {
           if (f_cmd1)
           {
               start_evb_timer3();
           }
           else
           {
               stop_evb_timer3();
           }
           p_f_cmd1 = f_cmd1;
       }

       if (f_cmd2 != p_f_cmd2)
       {
           if (f_cmd2)
           {
               start_eva_timer2();
           }
           else
           {
               stop_eva_timer2();
           }
           p_f_cmd2 = f_cmd2;
       }

       if (f_cmd3 != p_f_cmd3)
       {
           if (f_cmd3)
           {
               start_sync_interrupt();
           }
           else
           {
               stop_sync_interrupt();
           }
           p_f_cmd3 = f_cmd3;
       }

    }
    /// конец теста
*/
    project.enable_all_interrupt();

    final_code = update_progress_load_hmi(1);

    project.disable_all_interrupt();

    InitXilinxSpartan2E(&PWM_interrupt_main);

    project.enable_all_interrupt();

    final_code = update_progress_load_hmi(2);

    init_can_box_between_bs1_bs2();

    initVectorControl();


/////////////////////////////
    if (edrk.flag_second_PCH==0)
        InitCan(CAN_BASE_ADR_UNITS_PCH_1, CAN_BASE_ADR_MPU_PCH_1, CAN_BASE_ADR_ALARM_LOG_PCH_1, CAN_BASE_ADR_TERMINAL_PCH_1);
    else
        InitCan(CAN_BASE_ADR_UNITS_PCH_2, CAN_BASE_ADR_MPU_PCH_2, CAN_BASE_ADR_ALARM_LOG_PCH_2, CAN_BASE_ADR_TERMINAL_PCH_2);
/////////////////////////////

    KickDog();

  //  clear_mem(FAST_LOG);

/*
    //TODO: remove (for test)
    logpar.start_write_fast_log = 1;

    for (k = 0; k < 7000; k++) {
        for (i = 0; i < 21; i++) {
            if (i==0)
//                write_to_mem(FAST_LOG, k);
            write_to_mem(FAST_LOG, 0);
            else
//                write_to_mem(FAST_LOG, 10 + i);
            write_to_mem(FAST_LOG, 0);
        }
        if (logpar.start_write_fast_log) {
            get_log_params_count();
            logpar.start_write_fast_log = 0;
        }
    }

    //END for test
*/

    //Init ADC
//  Init_Adc_Variables();
//  init_eva_timer2(1000, acp_Handler);

    final_code = update_progress_load_hmi(3);

/////////////////////////////////////////
    project.read_errors_controller(); // чтение ADR_ERRORS_TOTAL_INFO

    project.init();
//    project_prepare_config();

    final_code = update_progress_load_hmi(4);

//  initRotPlane();

//    project_prepare_config();
// Загрузка CDS, ADC, HWP и т.д.
    project.reload_all_plates_with_reset();
// поиск отключенных плат
  //  project.find_all_cds();

    project_prepare_config();
    project_run_init_all_plates();

    project.load_cfg_to_plates();

    project.clear_errors_all_plates();


    final_code = update_progress_load_hmi(5);

/////////////////////////////////////////////
    enable_er0_control();


    project.read_errors_controller();

    project_read_errors_controller(); // чтение ADR_ERRORS_TOTAL_INFO
    if(project.controller.read.errors.all || project.controller.read.errors_buses.all)
    {
        xerror(main_er_ID(3),(void *)0);
    }

    final_code = update_progress_load_hmi(6);

////////////////////////////////////////////
    project.reset_errors_controller();
    project.read_errors_controller();
    project.start_parallel_bus();
    project.read_errors_controller();
    project.reset_errors_controller();
    project.read_errors_controller();

    project.stop_parallel_bus();

    project.reset_errors_controller();
    project.read_errors_controller();

    project.start_parallel_bus();
    project.read_errors_controller();

    final_code = update_progress_load_hmi(7);
////////////////////////////////////////////////



#if (TMSPWMGEN==1)
    setup_pwm_out();// назначаем соответствующие ноги как выходы ШИМ
    setup_pwm_int(FREQ_PWM, 0 ,0);
#else //TMSPWMGEN

#if (XPWMGEN==1)
    InitXPWM(FREQ_PWM);
    stop_wdog();
#else

    #error "Ошибка настройки проекта. Не выбран тип ШИМа!!!"

#endif //XPWMGEN
#endif //TMSPWMGEN

    InitPWM_Variables(edrk.flag_second_PCH);

    break_resistor_managment_init(FREQ_PWM);

//    start_int13_interrupt();


// Настроили SYNC
    setup_sync_int(); //use timer4
    //start_sync_interrupt();
    edrk.disable_interrupt_sync = 0;


 //   pause_1000(100000);
    final_code = update_progress_load_hmi(8);

//  project.enable_all_interrupt();
//  status_interrupts = __enable_interrupts();

//  pause_1000(100000);


      project.read_errors_controller();
      x_parallel_bus_project.read_status(&x_parallel_bus_project);

//    err_main = ReadMemory(ADR_ERRORS_TOTAL_INFO);
//    if(enable_er0_control() || err_main)
      if (project.controller.read.errors.bit.error_pbus
              || project.controller.read.errors_buses.bit.slave_addr_error
                       || project.controller.read.errors_buses.bit.count_error_pbus)
      {
        xerror(xparall_bus_er_ID(2),(void *)0);

        project.stop_parallel_bus();

        project.reset_errors_controller();
        project.read_errors_controller();

        project.start_parallel_bus();
        project.read_errors_controller();
      }

/*
      while(1)
      {
          project.adc[0].read_pbus(&project.adc[0]);
//          project.adc[1].read_pbus(&project.adc[1]);
          project.cds_tk[3].read_pbus(&project.cds_tk[3]);
          project.read_errors_controller();
      }
*/
//    project_stop_parallel_bus();


    project.start_parallel_bus();
    x_parallel_bus_project.read_status(&x_parallel_bus_project);

// Надо только после запуска PBUS иначе не будет данных длЯ детекта нулЯ
    Init_Adc_Variables();
    final_code = update_progress_load_hmi(9);


/////////////////////////////
// optical bus timer
/////////////////////////////
    if (edrk.flag_second_PCH==0)
        init_eva_timer2(FREQ_PWM*20*2, &optical_bus_read_write_interrupt);
    if (edrk.flag_second_PCH==1)
        init_eva_timer2(FREQ_PWM*20*2, &optical_bus_read_write_interrupt);

    //start_eva_timer2();// run global_time_interrupt
/////////////////////////////

    /////////////////////////////
    // add bus timer
    init_eva_timer1(FREQ_PWM*50,&async_pwm_ext_interrupt);
    start_eva_timer1();// run global_time_interrupt
    /////////////////////////////


    run_can_from_mpu();

    i_led1_on_off(1);
    i_led2_on_off(0);

    final_code = update_progress_load_hmi(10);

#if (XPWMGEN==1)
    project.enable_int13();
#endif

    start_int13_interrupt();

    pause_1000(10000);



//      project.enable_all_interrupt();


//#if (MODE_DISABLE_ENABLE_WDOG==1)
//    stop_wdog();
//#else
//    start_wdog();
//#endif
//    static unsigned int ccc = 0;
//    static STATUS_DATA_READ_OPT_BUS optbus_status = {0};
//
//    project.disable_all_interrupt();
//    while(1)
//    {
//
//
//        if (edrk.flag_second_PCH==1)
//        {
//            project.cds_tk[3].read_pbus(&project.cds_tk[3]);
//            optbus_status = optical_bus_get_status_and_read();
//        }
//        if (edrk.flag_second_PCH==0)
//        {
//
//            ccc++;
//            optical_write_data.data.angle_pwm = ccc;
//
//            optical_bus_write();
//
//        }
//    }


    start_sync_interrupt(); // запустили детект SYNC
    start_eva_timer2();// run global_time_interrupt optical_bus_read_write_interrupt
    start_can_interrupt();

    prev_flag_special_mode_rs = flag_special_mode_rs;

}

//////////////////////////////////////////////////////////
void edrk_go_main(void)
{
    static int disable_can=0;
    static int pbus_cmd=1;
    static int prev_pbus_cmd=1;

    static int f_reset = 0;
    static int np_reset = 0;
    static int level_go_main = 0;


    if(f_reset)
    {
        ResetNPeriphPlane(np_reset);
        f_reset = 0;
    }



#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_21_ON;
#endif

//    new_fifo_calc_load();
#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_ON;
#endif

    project.read_errors_controller();

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_OFF;
#endif

//      project.read_all_pbus();
//      project.read_all_hwp();

    if (edrk.flag_slow_in_main==0 ||  level_go_main==0)
        project.read_all_sbus(); //22 msec

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_ON;
#endif

    x_parallel_bus_project.read_status(&x_parallel_bus_project);

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_OFF;
#endif

//      project.write_all_sbus();




//////////////////////
      if ((prev_pbus_cmd != pbus_cmd) && pbus_cmd==0)
      {
//        project.disable_int13();
        project.stop_parallel_bus();
      }

      if ((prev_pbus_cmd != pbus_cmd) && pbus_cmd==1)
      {
//        project.enable_int13();
        project.start_parallel_bus();
      }
      prev_pbus_cmd = pbus_cmd;

    prev_flag_special_mode_rs = flag_special_mode_rs;
/////////////////////

    if (flag_special_mode_rs==0)
    {
        xpwm_time.disable_sync_out = 0;

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_22_ON;
#endif

//        if (level_go_main==1)
            project.read_all_hwp(); //800 mks

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_ON;
#endif

        if (edrk.flag_slow_in_main==0 ||  level_go_main==20)
            project.write_all_sbus(); //5msec

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_22_OFF;
#endif

        run_edrk();

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_ON;
#endif

//        if (at==1)
//        {
//          SendAll2SecondBS();
//          oscil_can.send(&oscil_can);
//          at=0;
//        }

        //Обмен по CAN
        if (disable_can==0)
            CAN_may_be_send_cycle_fifo();

    }
    else
    {
        xpwm_time.disable_sync_out = 1;
        project.read_all_pbus();
        project.read_all_hwp();
        project.write_all_sbus();
//          project.disable_int13();

        RS232_WorkingWith(0,1,0);
    }

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_23_OFF;
#endif

#if(_ENABLE_PWM_LINES_FOR_TESTS_RS)
    PWM_LINES_TK_21_OFF;
#endif

    level_go_main++;
    if (level_go_main>=40)
        level_go_main = 0;


}
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//#pragma CODE_SECTION(get_start_ged_from_zadanie,".fast_run");
int get_start_ged_from_zadanie(void)
{

    // uf const
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_UF_CONST)
    {
        if (edrk.zadanie.iq_fzad_rmp!=0 && edrk.zadanie.iq_kzad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    // scalar oborots
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_SCALAR_OBOROTS)
    {
        if (edrk.MasterSlave==MODE_SLAVE)
        {
            if (edrk.zadanie.iq_Izad_rmp!=0
                    && edrk.zadanie.iq_limit_power_zad_rmp!=0)
                return 1;
            else
                return 0;
        }
        else
        {
            if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                    && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
                return 1;
            else
                return 0;
        }
    }
    else
    // scalar power
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_SCALAR_POWER)
    {
        if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    // foc oborots
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_OBOROTS)
    {
        if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    // foc power
    if (edrk.Mode_ScalarVectorUFConst == ALG_MODE_FOC_POWER)
    {
        if (edrk.zadanie.iq_oborots_zad_hz_rmp!=0 && edrk.zadanie.iq_Izad_rmp!=0
                && edrk.zadanie.iq_power_zad_rmp!=0 && edrk.zadanie.iq_limit_power_zad_rmp!=0)
            return 1;
        else
            return 0;
    }
    else
    {
        return 0;
    }

}
//////////////////////////////////////////////////////////


void cross_stend_automats(void)
{
    unsigned int g;

        edrk.to_shema.bits.CROSS_UMP_ON_OFF = 0;
        edrk.to_shema.bits.CROSS_QTV_ON_OFF = 0;

}




#define MAX_ERRORS_DETECT_CHANGE_ACTIVE_CONTROL 50
void check_change_post_upravl(void)
{
  static int prev_active_post_upravl = -1, prev_active_post_upravl_another_bs = -1;
  int active_post_upravl = -1, active_post_upravl_another_bs = -1;
  static unsigned int count_err = 0;


  active_post_upravl = get_code_active_post_upravl();
  active_post_upravl_another_bs = edrk.active_post_upravl_another_bs;


  if (edrk.Status_Ready.bits.ready_final && edrk.Ready2_another_bs)
  {
      if ((active_post_upravl_another_bs==0 || active_post_upravl==0) && (active_post_upravl==2 || active_post_upravl_another_bs==2))
      {
        // если какой-то БС в СВУ а другой в МЕСТНОЕ
          edrk.errors.e9.bits.CHANGE_ACTIVE_CONTROL_TO_LOCAL_FROM_SVU |=
                          filter_err_count(&count_err,
                           MAX_ERRORS_DETECT_CHANGE_ACTIVE_CONTROL,
                           1,
                           0);
      }
      else
          count_err = 0;
  }


  prev_active_post_upravl = active_post_upravl;
  prev_active_post_upravl_another_bs = active_post_upravl_another_bs;

  edrk.active_post_upravl = active_post_upravl;
}


int get_code_active_post_upravl(void)
{

    if (control_station.active_control_station[CONTROL_STATION_TERMINAL_RS232])
        return 3;
    else
    if (control_station.active_control_station[CONTROL_STATION_TERMINAL_CAN])
        return 4;
    else
    if (control_station.active_control_station[CONTROL_STATION_INGETEAM_PULT_RS485])//(edrk.RemouteFromDISPLAY)
        return 0;
    else
    if (control_station.active_control_station[CONTROL_STATION_MPU_KEY_CAN])
        return 5;
    else
    if (control_station.active_control_station[CONTROL_STATION_ZADATCHIK_CAN])
        return 6;
    else
    if (control_station.active_control_station[CONTROL_STATION_VPU_CAN])
        return 1;
    else
    if (control_station.active_control_station[CONTROL_STATION_MPU_SVU_CAN])
        return 2;
    else
        return 10; //error
}




#define MAX_COUNT_DETECTS_ZERO_U_ZPT    5

void auto_detect_zero_u_zpt(void)
{
    static unsigned int old_time_u_zpt1=0, count_detects = 0, flag_detect_zero_u_zpt = 0;

    static _iq prev_uzpt1=0;
    static _iq prev_uzpt2=0;
    static _iq delta_u = _IQ(3.0/NORMA_ACP);
    static _iq minimal_detect_u = _IQ(40.0/NORMA_ACP);



    if (edrk.SumSbor==0 && flag_detect_zero_u_zpt==0)
    {
        // нет сбора, значит можем искать ноль Uzpt
        if (detect_pause_sec(5,&old_time_u_zpt1))
        {
            if (    filter.iqU_1_long>=minimal_detect_u ||
                    filter.iqU_2_long>=minimal_detect_u ||
                    (prev_uzpt1-filter.iqU_1_long)>=delta_u ||
                    (prev_uzpt2-filter.iqU_2_long)>=delta_u )
            {
                // напряжение еще падает
                count_detects = 0;
            }
            else
            {
                if (count_detects<MAX_COUNT_DETECTS_ZERO_U_ZPT)
                    count_detects++;
                else
                {
                    if (flag_detect_zero_u_zpt==0)
                    {
                        if (filter.iqU_1_long<=minimal_detect_u &&
                                filter.iqU_2_long<=minimal_detect_u)
                        {
                          analog_zero.iqU_1 = filter.iqU_1_long;
                          analog_zero.iqU_2 = filter.iqU_2_long;
                        }
                    }
                    flag_detect_zero_u_zpt = 1;

                }

            }

            prev_uzpt1 = filter.iqU_1_long;
            prev_uzpt2 = filter.iqU_2_long;
        }  // 1 sec end
    }
    else
    {
        if (flag_detect_zero_u_zpt)
        {
            if (filter.iqU_1_long<-delta_u || filter.iqU_2_long<-delta_u)
            {
                // слишком рано была произведена коррекция, надо бы повторить
                flag_detect_zero_u_zpt = 0;
                analog_zero.iqU_1 = 0;
                analog_zero.iqU_2 = 0;
            }

        }
        count_detects = 0;
    }

}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
// для инита переменных перед сбором схемы
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
void reinit_before_sbor(void)
{
    static unsigned int prev_sbor = 0;

    if (edrk.SumSbor && edrk.SumSbor!=prev_sbor )
    {
        init_50hz_input_net50hz();
        init_all_limit_koeffs();
    }
    prev_sbor = edrk.SumSbor;
}

////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
#define MINIMAL_POWER_TO_DISPLAY    10 // минимум 10 кВт

#define PAUSE_COMUNICATION      100
void run_edrk(void)
{
 //   static unsigned int prev_SumSbor = 0, prev_AllStart = 0, prev_VozbudOnOff = 0, prev_SBOR_SHEMA_VPU = 0,prev_SBOR_SHEMA_RS=0, prev_SBOR_SHEMA_DISPLAY = 0;

    int ff =0;
    static unsigned int filter_count_error_control_station_select_active = 0;
    static int flag_enable_update_mpu = 1;
    static unsigned int external_cmd_alarm_log = 0;
    static int prev_enable_pwm_test_lines=0;
    int power_kw_full = 0;

    float max_oborots, local_oborots, local_power, max_power;
    static float float_oborots = 0, koef_p1 = 0, koef_p2 = 0, koef_p3 = 27.391304347826086956521739130435;

    static unsigned int prev_rs_a_count_recive_ok = 0;
    static unsigned int pause_comunication = PAUSE_COMUNICATION;
    static unsigned int time_pause_modbus_can_zadatchik_vpu = TIME_PAUSE_MODBUS_CAN_ZADATCHIK_VPU;
    static unsigned int time_pause_modbus_can_ukss_setup = TIME_PAUSE_MODBUS_CAN_UKSS_SETUP;
    static unsigned int time_pause_modbus_can_bs2bs = TIME_PAUSE_MODBUS_CAN_BS2BS;
    static int fa_0 = 1;
    static int fa_1 = 1;
    static int fa_2 = 1;

    static int prev_cmd_very_slow_start = 0;


//    static float fff = 0;

    reinit_before_sbor();

    if (edrk.SumSbor || edrk.Status_Ready.bits.ready_final)
    {
        disable_flag_special_mode_rs = 1;
    }
    else
        disable_flag_special_mode_rs = 0;

    if (f.Prepare || f.terminal_prepare) {
        project.clear_errors_all_plates();
    }

//    fff = my_satur_float(fff,MAX_ZADANIE_LIMIT_POWER, MIN_ZADANIE_LIMIT_POWER, 0);
 //   slow_vector_update();

    read_plane_errors();

//    if (flag_enable_update_hmi)
//       update_tables_HMI();
//    if (flag_enable_update_mpu)
//       update_modbus_table();
//    modbusNetworkSharing(1);
//    get_command_HMI();

//    return;

//    i_led1_on_off(1);
    if (edrk.flag_disable_pult_485==0)
    {
        i_led2_on_off(1);
        modbusNetworkSharing(0);

    }
//    i_led1_on_off(0);

//    if (ccc[0])
//    {
//        i_led2_on_off(0);
//        return;
//    }

    if (!(detect_pause_milisec(pause_comunication, &old_time_edrk2)))
       return;


    if (edrk.get_new_data_from_hmi2)
    {
          get_command_HMI();
          edrk.get_new_data_from_hmi2 = 0;
    }



    ////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////
    //  Дальше код запускается раз в 100 мсек.
    ////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////


    // external_cmd_alarm_log = modbus_table_can_in[11].all;
    //  test_send_alarm_log(external_cmd_alarm_log);

    //  modbusNetworkSharing(0);

    //    i_led2_on_off(1);

    modbusNetworkSharingCAN();

    #if (ENABLE_CAN_SEND_TO_UKSS_FROM_MAIN)
    // пишем в задатчик
    update_ukss_can(time_pause_modbus_can_zadatchik_vpu);
    update_ukss_can_moment_kgnc(time_pause_modbus_can_zadatchik_vpu*3);


    update_ukss_setup(time_pause_modbus_can_ukss_setup);
    #endif

    #if (ENABLE_CAN_SEND_TO_ANOTHER_BSU_FROM_MAIN)
// пишем в задатчик
    update_bsu_can(time_pause_modbus_can_bs2bs);
    #endif

    check_all_power_limits();

    calc_p_water_edrk();
    calc_temper_edrk();
    calc_temper_acdrive();

    // читаем цифр входы
    update_input_edrk();

    detect_kvitir_from_all();

    detect_error_all();

    calc_limit_overheat();

    calc_RMS_values_main();

    update_lamp_alarm();

    set_zadanie_u_charge();

    reinit_protect_I_and_U_settings();

    nagrev_auto_on_off();

    auto_block_key_on_off();


    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    edrk.f_rotor_hz = _IQtoF(edrk.iq_f_rotor_hz) * NORMA_FROTOR;



    if (edrk.Status_Ready.bits.ImitationReady2)
    {
//        edrk.oborots = edrk.zadanie.oborots_zad;
//        koef_p1 = 54.78260869565217391304347826087/(edrk.count_bs_work+1);
//        koef_p2 = 54.78260869565217391304347826087/4;

        koef_p3 = 27.39130;

        if (control_station.active_array_cmd[CONTROL_STATION_CMD_ROTOR_POWER]==0) // по оборотам
        {

            if (edrk.count_bs_work==0)
                max_power = my_satur_float(edrk.zadanie.limit_power_zad, MAX_ZADANIE_POWER/2, MIN_ZADANIE_POWER/2, 0);
            else
                max_power = my_satur_float(edrk.zadanie.limit_power_zad, MAX_ZADANIE_POWER, MIN_ZADANIE_POWER, 0);

            max_oborots = max_power/koef_p3;
            if (edrk.count_bs_work==0)
                max_oborots = my_satur_float(max_oborots,MAX_ZADANIE_OBOROTS_ROTOR/2,MIN_ZADANIE_OBOROTS_ROTOR/2, 0);
            else
                max_oborots = my_satur_float(max_oborots,MAX_ZADANIE_OBOROTS_ROTOR,MIN_ZADANIE_OBOROTS_ROTOR, 0);

            local_oborots =  fast_round(_IQtoF(edrk.zadanie.iq_oborots_zad_hz)*60.0*NORMA_FROTOR);
            if (local_oborots>=0)
                        {
                            if (local_oborots>max_oborots)
                                local_oborots = max_oborots;
                        }
                        else
                        {
                            if (local_oborots<-max_oborots)
                                local_oborots = -max_oborots;
                        }

            float_oborots = zad_intensiv(1.0, 1.0, float_oborots,  local_oborots);

            edrk.oborots = float_oborots;
            edrk.power_kw =  edrk.oborots * koef_p3/(edrk.count_bs_work+1);




//
//            max_oborots = edrk.zadanie.limit_power_zad/koef_p2;
//            max_oborots = my_satur_float(max_oborots,MAX_ZADANIE_OBOROTS_ROTOR,MIN_ZADANIE_OBOROTS_ROTOR, 0);
//
//            local_oborots =  fast_round(_IQtoF(edrk.zadanie.rmp_oborots_imitation_rmp)*60.0*NORMA_FROTOR);
//            if (local_oborots>=0)
//            {
//                if (local_oborots>max_oborots)
//                    local_oborots = max_oborots;
//            }
//            else
//            {
//                if (local_oborots<-max_oborots)
//                    local_oborots = -max_oborots;
//            }

        }
        else
        {

            local_power = fast_round(_IQtoF(edrk.zadanie.iq_power_zad_rmp) * NORMA_ACP * NORMA_ACP / 1000.0);
            if (edrk.count_bs_work==0)
                local_power = my_satur_float(local_power, MAX_ZADANIE_POWER/2, MIN_ZADANIE_POWER/2, 0);
            else
                local_power = my_satur_float(local_power, MAX_ZADANIE_POWER, MIN_ZADANIE_POWER, 0);

            local_oborots = local_power/koef_p3;
            float_oborots = zad_intensiv(1.0, 1.0, float_oborots,  local_oborots);
            edrk.oborots = float_oborots;
            edrk.power_kw =  local_power/(edrk.count_bs_work+1);//edrk.oborots * koef_p3;

//            local_power = fast_round(_IQtoF(edrk.zadanie.iq_power_zad_rmp) * NORMA_ACP * NORMA_ACP / 1000.0);
//            local_oborots = local_power/koef_p1;
        }


//        float_oborots = zad_intensiv(0.5, 0.5, float_oborots,  local_oborots);
//        edrk.oborots = float_oborots;
//
//        if (edrk.oborots>=0)
//            edrk.power_kw =  edrk.oborots * koef_p2;
//        else
//            edrk.power_kw =  edrk.oborots * koef_p2;

//
//
//
//        if (edrk.oborots>=0)
//            edrk.power_kw =  edrk.oborots * koef_p;
//        else
//            edrk.power_kw =  edrk.oborots * (+koef_p);
    }
    else
    {
        edrk.oborots =  fast_round(_IQtoF(WRotor.iqWRotorSumFilter3)*60.0*NORMA_FROTOR);
//        local_power = fast_round(_IQtoF(filter.PowerScalarFilter2) * NORMA_ACP * NORMA_ACP / 1000.0);
//
//        if (edrk.oborots>=0)
//                    edrk.power_kw =  local_power;
//        else
//                    edrk.power_kw =  -local_power;

        edrk.power_kw = fast_round(_IQtoF(edrk.iq_power_kw_one_filter_znak) * NORMA_ACP * NORMA_ACP / 1000.0);
    }

    power_kw_full = edrk.power_kw + edrk.power_kw_another_bs;

//    if (power_kw_full < MINIMAL_POWER_TO_DISPLAY)
//        edrk.power_kw_full = 0;
//    else
    edrk.power_kw_full = power_kw_full;
    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////



    edrk.Status_Ready.bits.ready1 = get_ready_1();

    pump_control();


    if (control_station_select_active())
    {

        if (filter_count_error_control_station_select_active<30)
            filter_count_error_control_station_select_active++;
        else
            edrk.errors.e7.bits.NOT_VALID_CONTROL_STATION |= 1;
    }
    else
        filter_count_error_control_station_select_active = 0;

    edrk.current_active_control = get_current_station_control();

    if (edrk.current_active_control<CONTROL_STATION_LAST)
    {
          // есть активный пост управления
    }


    // разбираем все данные со всех возможных постов управления
    parse_parameters_from_all_control_station();
    //копируем данные из активного поста в текущий
    load_parameters_from_active_control_station(edrk.current_active_control);

    // если мы slave то часть данных берем с мастера по CAN и замещаем в active_control_station
    parse_data_from_master_to_alg();


    ff = control_station.active_array_cmd[CONTROL_STATION_CMD_SET_ROTOR];
    control_station.array_cmd[CONTROL_STATION_INGETEAM_PULT_RS485][CONTROL_STATION_CMD_SET_ROTOR] = ff;
    control_station.array_cmd[CONTROL_STATION_VPU_CAN][CONTROL_STATION_CMD_SET_ROTOR] = ff;
    control_station.array_cmd[CONTROL_STATION_ZADATCHIK_CAN][CONTROL_STATION_CMD_SET_ROTOR] = ff;

    ff = control_station.active_array_cmd[CONTROL_STATION_CMD_SET_POWER];
    control_station.array_cmd[CONTROL_STATION_INGETEAM_PULT_RS485][CONTROL_STATION_CMD_SET_POWER] = ff;


    if (control_station.active_array_cmd[CONTROL_STATION_CMD_ROTOR_POWER])
    {
          control_station.array_cmd[CONTROL_STATION_ZADATCHIK_CAN][CONTROL_STATION_CMD_SET_ROTOR] = 0;
          control_station.array_cmd[CONTROL_STATION_VPU_CAN][CONTROL_STATION_CMD_SET_ROTOR] = 0;
    }

    // для стенда, при пуске только одного БС, на другом мы должны включить разрешающие сигналы для автоматов,
    // т.к. сигналы управления QTV и QPU включены последовательно.
//  cross_stend_automats();

    // обработка данных от другого БС по CAN
    read_data_from_bs();

    //конвертим аналоговые данные из текущего поста управления в структуру edrk.
    parse_analog_data_from_active_control_station_to_alg();

    //  if (flag_enable_update_hmi)
    //     update_tables_HMI();
    if (flag_enable_update_mpu)
    {
        update_svu_modbus_table();
    }

     // modbusNetworkSharing(0);



    if (flag_enable_can_from_mpu)
    {

    //          write_all_data_to_mpu_485(0);
    //          read_all_data_from_mpu_485(0);
    //          write_all_data_to_mpu_can(1);
    //          test_rs_can_with_svu_mpu();
    }

    //

    if (edrk.test_mode)
    {
        return;
    }

    get_sumsbor_command();

    sbor_shema(edrk.SumSbor);

    auto_select_master_slave();

    who_select_sync_signal();

    check_change_post_upravl();

    get_freq_50hz_float();

    auto_detect_zero_u_zpt();


    if (detect_pause_sec(2,&old_time_edrk1))
    {
        update_nPCH();

        if (control_station.array_cmd[CONTROL_STATION_TERMINAL_RS232][CONTROL_STATION_CMD_WDOG_OFF])
            stop_wdog();
        else
            start_wdog();


        if (rs_a.count_recive_ok != prev_rs_a_count_recive_ok)
            control_station.time_detect_active[CONTROL_STATION_TERMINAL_RS232] = 0;
        prev_rs_a_count_recive_ok = rs_a.count_recive_ok;
    }  // 1 sec end

    update_zadat4ik();

//    update_uom();

    calc_count_build_revers();

    run_store_slow_logs();
    prepare_logger_pult();
    update_LoggerParams();

    send_alarm_log_pult();

    ////////////////////////////////////////////////////////////
    //  пишем цифровые выходы
    ////////////////////////////////////////////////////////////
    update_output_edrk();


    read_can_error();

    check_temper_break();
    check_breaker_ged();




    // change_ramp_zadanie
    if (edrk.cmd_very_slow_start != prev_cmd_very_slow_start)
    {
        change_ramp_zadanie();
    }
    prev_cmd_very_slow_start = edrk.cmd_very_slow_start;


    //    i_led2_on_off(0);




#if (_ENABLE_PWM_LINES_FOR_TESTS==1 \
            || _ENABLE_PWM_LINES_FOR_TESTS_ROTOR==1 \
            || _ENABLE_PWM_LINES_FOR_TESTS_PWM==1 \
            || _ENABLE_PWM_LINES_FOR_TESTS_RS \
            || _ENABLE_PWM_LINES_FOR_TESTS_SYNC \
            || _ENABLE_PWM_LINES_FOR_TESTS_GO)

    if (edrk.enable_pwm_test_lines != prev_enable_pwm_test_lines)
    {
        if (edrk.enable_pwm_test_lines)
            pwm_test_lines_start();
        else
            pwm_test_lines_stop();
    }
    prev_enable_pwm_test_lines = edrk.enable_pwm_test_lines;

#endif


#if (_FLOOR6==1)
    if (fa_0)
    {
        // имитация живости пульта ЗО
        control_station.time_detect_active[7] = 0;
        control_station.alive_control_station[7] = 1;
    }

    if (fa_1)
    {
        control_station.time_detect_active[CONTROL_STATION_MPU_SVU_CAN] = 0;
        control_station.alive_control_station[CONTROL_STATION_MPU_SVU_CAN] = 1;
    }

    if (fa_2)
    {
        control_station.time_detect_active[CONTROL_STATION_MPU_KEY_CAN] = 0;
        control_station.alive_control_station[CONTROL_STATION_MPU_KEY_CAN] = 1;
    }

#endif


    i_led2_on_off(0);

}


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
void run_can_from_mpu(void)
{
    int i;

    for (i=0;i<MPU_UNIT_QUA_UNITS;i++)
        mpu_can_setup.adr_detect_refresh[i] = 123 - 1;


    flag_enable_can_from_mpu = 1;



}




void update_maz_level_i_af(int n_af, unsigned int new_maz_level)
{
#if (USE_HWP_0)
    if (n_af == 0)
    {
        project.hwp[0].write.values[2].plus = new_maz_level;
        project.hwp[0].write.values[2].minus = new_maz_level;
        project.hwp[0].write.values[3].plus = new_maz_level;
        project.hwp[0].write.values[3].minus = new_maz_level;
        project.hwp[0].write.values[4].plus = new_maz_level;
        project.hwp[0].write.values[4].minus = new_maz_level;
        project.hwp[0].write.values[5].plus = new_maz_level;
        project.hwp[0].write.values[5].minus = new_maz_level;
        project.hwp[0].write.values[6].plus = new_maz_level;
        project.hwp[0].write.values[6].minus = new_maz_level;
        project.hwp[0].write.values[7].plus = new_maz_level;
        project.hwp[0].write.values[7].minus = new_maz_level;
    }
    else
    {

    }
#endif
}


void set_new_level_i_protect(int n_af, int level)
{
    static int i_af_protect_d = 0, prev_level_all = 0, prev_level_2 = 0;

    if (level>LEVEL_HWP_I_AF) level = LEVEL_HWP_I_AF;
    if (level<0) level = 0;

    if (n_af == 0)
    {
        if (level != prev_level_all)
        {
            i_af_protect_d = convert_real_to_mv_hwp(2,level);
            if (i_af_protect_d>1500) i_af_protect_d = 1500; // max 1500 mV

            update_maz_level_i_af(n_af, i_af_protect_d);
            project.write_all_hwp();
        }
        prev_level_all = level;
    }
//    else
//    {
//        if (level != prev_level_2)
//        {
//            i_af_protect_d = convert_real_to_mv_hwp(4,level);
//            if (i_af_protect_d>1500) i_af_protect_d = 1500; // max 1500 mV
//
//            update_maz_level_i_af(n_af, i_af_protect_d);
//            project.write_all_hwp();
//        }
//        prev_level_2 = level;
//
//    }
}


void calc_count_build_revers(void)
{
    static unsigned int prev_b = 0, prev_r = 0;

    if (edrk.Status_Ready.bits.ImitationReady2)
    {
        detect_work_revers(((edrk.oborots>=0) ? 1 : -1), edrk.zadanie.iq_oborots_zad_hz_rmp, edrk.oborots);
    }
    else
        detect_work_revers(WRotor.RotorDirectionSlow, edrk.zadanie.iq_oborots_zad_hz_rmp, WRotor.iqWRotorSumFilter2);

    if (edrk.count_revers != prev_r)
        inc_count_revers();

    if (edrk.count_sbor != prev_b)
        inc_count_build();

    prev_r = edrk.count_revers;
    prev_b = edrk.count_sbor;

}


void prepare_logger_pult(void)
{

    edrk.pult_data.logger_params[0] = fast_round(_IQtoF(simple_scalar1.iq_decr_mzz_power_filter)*1000.0);//edrk.zadanie.oborots_zad;
    edrk.pult_data.logger_params[1] = fast_round(_IQtoF(edrk.Kplus)*1000.0);
    edrk.pult_data.logger_params[2] = fast_round(_IQtoF(pll1.vars.pll_Ud)*NORMA_ACP);
    edrk.pult_data.logger_params[3] = fast_round(_IQtoF(edrk.f_stator)*NORMA_FROTOR*100.0);
    edrk.pult_data.logger_params[4] = fast_round(_IQtoF(edrk.k_stator1)*10000.0);
    edrk.pult_data.logger_params[5] = fast_round(_IQtoF(pll1.vars.pll_Uq)*NORMA_ACP);
    edrk.pult_data.logger_params[6] = edrk.period_calc_pwm_int2;
    edrk.pult_data.logger_params[7] = fast_round(_IQtoF(simple_scalar1.pidF.OutMax)*NORMA_ACP);//edrk.power_kw_full;
    edrk.pult_data.logger_params[8] = edrk.Sbor_Mode;
    edrk.pult_data.logger_params[9] = edrk.Stage_Sbor;
    edrk.pult_data.logger_params[10] = fast_round(_IQtoF(edrk.Izad_out)*NORMA_ACP);
    edrk.pult_data.logger_params[11] = edrk.period_calc_pwm_int1;
    edrk.pult_data.logger_params[12] = fast_round(_IQtoF(simple_scalar1.pidF.Out)*NORMA_ACP);
    edrk.pult_data.logger_params[13] = fast_round(_IQtoF(simple_scalar1.pidF.OutMin)*NORMA_ACP);
    edrk.pult_data.logger_params[14] = fast_round(_IQtoF(simple_scalar1.pidPower.Out)*NORMA_ACP);
    edrk.pult_data.logger_params[15] = fast_round(_IQtoF(simple_scalar1.pidPower.OutMax)*NORMA_ACP);
    edrk.pult_data.logger_params[16] = fast_round(_IQtoF(simple_scalar1.pidF.Ref)*NORMA_FROTOR*1000.0);// //modbus_table_can_in[123].all;//Управление (По мощности, По оборотам)
    edrk.pult_data.logger_params[17] = modbus_table_can_in[124].all;//Обороты (заданные)
    edrk.pult_data.logger_params[18] = modbus_table_can_in[125].all;//Мощность (заданная)
    edrk.pult_data.logger_params[19] = modbus_table_can_in[134].all;//запас мощности
    edrk.pult_data.logger_params[20] = fast_round(_IQtoF(simple_scalar1.bpsi_curent)*NORMA_FROTOR*1000.0);
    edrk.pult_data.logger_params[21] = fast_round(_IQtoF(edrk.from_uom.iq_level_value_kwt)*NORMA_ACP*NORMA_ACP/1000.0);
    edrk.pult_data.logger_params[22] = fast_round(_IQtoF(simple_scalar1.iqKoefOgran)*1000.0);//fast_round(_IQtoF(rotor_22220.iqFout)*NORMA_FROTOR*1000.0);
    edrk.pult_data.logger_params[23] = fast_round(_IQtoF(simple_scalar1.iqKoefOgranIzad)*1000.0);   //fast_round(_IQtoF(edrk.zadanie.iq_limit_power_zad)*NORMA_ACP*NORMA_ACP/1000.0);
    edrk.pult_data.logger_params[24] = fast_round(_IQtoF(edrk.all_limit_koeffs.sum_limit)*1000.0);
    edrk.pult_data.logger_params[25] = fast_round(_IQtoF(edrk.all_limit_koeffs.uom_limit)*1000.0);
    edrk.pult_data.logger_params[26] = fast_round(_IQtoF(edrk.all_limit_koeffs.uin_freq_limit)*1000.0);
    edrk.pult_data.logger_params[27] = fast_round(_IQtoF(simple_scalar1.pidF.Fdb)*NORMA_FROTOR*1000.0);                 //


}


int calc_auto_moto_pump(void)
{
    volatile long sum_minutes_pump1, sum_minutes_pump2, set_delta_minutes, cur_delta_minutes;


    sum_minutes_pump1 = 0;
    if (edrk.pult_data.data_from_pult.moto[12]>=0)
        sum_minutes_pump1 += edrk.pult_data.data_from_pult.moto[12] * 1440;
    if (edrk.pult_data.data_from_pult.moto[3]>=0)
        sum_minutes_pump1 += edrk.pult_data.data_from_pult.moto[3];

    sum_minutes_pump2 = 0;
    if (edrk.pult_data.data_from_pult.moto[13]>=0)
        sum_minutes_pump2 += edrk.pult_data.data_from_pult.moto[13] * 1440;
    if (edrk.pult_data.data_from_pult.moto[4]>=0)
        sum_minutes_pump2 += edrk.pult_data.data_from_pult.moto[4];

    cur_delta_minutes = sum_minutes_pump1 - sum_minutes_pump2;

    set_delta_minutes = edrk.pult_data.data_to_pult.TimeToChangePump;

    if (set_delta_minutes==0)
    {
        return 0;
    }


    if (cur_delta_minutes>set_delta_minutes)
    {
        return 2;
    }
    else
    if (cur_delta_minutes<-set_delta_minutes)
    {
        return 1;
    }
    else
    if (edrk.pult_data.data_from_pult.LastWorkPump==0)
    {
        if (cur_delta_minutes>0)
        {
            return 1;
        }
        else
        if (cur_delta_minutes<=0)
        {
            return 2;
        }
        else
            return 0;
    }
    else
    {
        if (edrk.pult_data.data_from_pult.LastWorkPump == 1)
            return 1;
        else
        if (edrk.pult_data.data_from_pult.LastWorkPump == 2)
            return 2;
        else
            return 0;
    }
//
//
//    if (cur_delta_minutes>0)
//    {
//        //T1>T2
//        if (_IQabs(cur_delta_minutes) >= set_delta_minutes)
//        {
//            // T1+delta>T2
//            return 2;
//        }
//        else
//            return 1;
//    }
//    else
//    {
//        //T2>T1
//        if (_IQabs(cur_delta_minutes) >= set_delta_minutes)
//        {
//            //T2+delta>T1
//            return 1;
//        }
//        else
//            return 2;
//    }

//    if (_IQabs(cur_delta_minutes) > set_delta_minutes)
//    {
//        if (cur_delta_minutes>)
//            return 2;
//        else
//            return 1;
//
//
//    }
//    if (cur_delta_minutes>=0)
//    {
//        if (_IQabs(cur_delta_minutes) > set_delta_minutes)
//            return 2;
//        else
//            return 1;
//    }
//    else
//    {
//        if (_IQabs(cur_delta_minutes) > set_delta_minutes)
//            return 1;
//        else
//            return 2;
//    }



}



void read_can_error(void)
{
    EALLOW;
    edrk.canes_reg = ECanaRegs.CANES.all;
    edrk.canrec_reg = ECanaRegs.CANREC.all;
    edrk.cantec_reg = ECanaRegs.CANTEC.all;
    EDIS;

    cmd_clear_can_error();

}


void clear_can_error(void)
{
  //  EALLOW;

   // ECanaRegs.CANES.all=0xffffffff;
    InitCanSoft();

    //EDIS;

}

void cmd_clear_can_error(void)
{
    static int prev_cmd_clear_can_error = 0;

    if (edrk.cmd_clear_can_error && prev_cmd_clear_can_error==0)
    {
        clear_can_error();
    }
    prev_cmd_clear_can_error = edrk.cmd_clear_can_error;

}


void check_temper_break(void)
{

    if ( (edrk.break_tempers[0] > ABNORMAL_TEMPER_BREAK_INT)
            || (edrk.break_tempers[1] > ABNORMAL_TEMPER_BREAK_INT)
            || (edrk.break_tempers[2] > ABNORMAL_TEMPER_BREAK_INT)
            || (edrk.break_tempers[3] > ABNORMAL_TEMPER_BREAK_INT)
            )
        edrk.warnings.e9.bits.BREAK_TEMPER_WARNING = 1;
    else
    {
        if ( (edrk.break_tempers[0] < ABNORMAL_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                && (edrk.break_tempers[1] < ABNORMAL_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                && (edrk.break_tempers[2] < ABNORMAL_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                && (edrk.break_tempers[3] < ABNORMAL_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                )
        edrk.warnings.e9.bits.BREAK_TEMPER_WARNING = 0;
    }


    if ( (edrk.break_tempers[0] > ALARM_TEMPER_BREAK_INT)
            || (edrk.break_tempers[1] > ALARM_TEMPER_BREAK_INT)
            || (edrk.break_tempers[2] > ALARM_TEMPER_BREAK_INT)
            || (edrk.break_tempers[3] > ALARM_TEMPER_BREAK_INT)
            )
        edrk.warnings.e9.bits.BREAK_TEMPER_ALARM = 1;
    else
    {
        //DELTA_TEMPER_BREAK_INT
        if ( (edrk.break_tempers[0] < ALARM_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                && (edrk.break_tempers[1] < ALARM_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                && (edrk.break_tempers[2] < ALARM_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                && (edrk.break_tempers[3] < ALARM_TEMPER_BREAK_INT-DELTA_TEMPER_BREAK_INT)
                )
        edrk.warnings.e9.bits.BREAK_TEMPER_ALARM = 0;
    }

}

#define TIME_FILTER_BREAKER_SIGNALS     10

void check_breaker_ged(void)
{
    static  unsigned int count_wait_breaker = 0;

    edrk.warnings.e9.bits.BREAKER_GED_ON = filter_digital_input( edrk.warnings.e9.bits.BREAKER_GED_ON,
                                                                     &count_wait_breaker,
                                                                     TIME_FILTER_BREAKER_SIGNALS,
                                                                     edrk.breaker_on);

//     if (edrk.breaker_on)
//         edrk.warnings.e9.bits.BREAKER_GED_ON = 1;
//     else
//         edrk.warnings.e9.bits.BREAKER_GED_ON = 0;

}
