/*
 * logs_hmi.c
 *
 *  Created on: 28 авг. 2024 г.
 *      Author: Evgeniy_Sokolov
 */
#include "log_to_memory.h"
#include <message_modbus.h>
#include <modbus_hmi.h>
#include <modbus_hmi_update.h>
#include <vector.h>

#include "control_station.h"
#include "global_time.h"
#include "modbus_table_v2.h"
#include "RS_modbus_pult.h"
#include "DSP281x_Device.h"
#include "MemoryFunctions.h"
#include "RS_modbus_svu.h"
#include "log_params.h"
#include "logs_hmi.h"
#include "edrk_main.h"


#pragma DATA_SECTION(log_to_HMI, ".logs");
t_Logs_with_modbus log_to_HMI = LOGS_WITH_MODBUS_DEFAULTS;


#define COUNT_FAST_DATA     300//150
#define COUNT_SLOW_DATA     300



///////////////////////////////////////////////////
///
///////////////////////////////////////////////////
#define MAX_SIZE_LOGS_HMI_FULL        (END_ADDRESS_LOGS - START_ADDRESS_LOG + 1) //262144 // 0x80000/2
#define MAX_SIZE_LOGS_HMI_SMALL       10000

#define START_ARRAY_LOG_SEND    300
#define END_ARRAY_LOG_SEND      899
#define SIZE_ARRAY_LOG_SEND     (END_ARRAY_LOG_SEND - START_ARRAY_LOG_SEND + 1)
#define SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE          120

int writeLogsArray(int flag_next)
{
    int succed = 0;
    static unsigned int old_time = 0;

    static int count_write_to_modbus = 0;
    static int cur_position_buf_modbus16 = 0;





    if (!rs_b.flag_LEADING)
    {

        ModbusRTUsetDataArrays(modbus_table_analog_in, modbus_table_analog_out);

        if (control_station.flag_waiting_answer[CONTROL_STATION_INGETEAM_PULT_RS485] == 0)
        {
            if (log_to_HMI.flag_start_log_array_sent)
            {
                cur_position_buf_modbus16 = START_ARRAY_LOG_SEND;
                log_to_HMI.flag_log_array_sended = 0;
            }
            else
            {
                if (flag_next)
                    cur_position_buf_modbus16 = cur_position_buf_modbus16 + SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE;
            }

            log_to_HMI.flag_start_log_array_sent = 0;
        }

        if (cur_position_buf_modbus16 >= END_ARRAY_LOG_SEND)
        {
            // все передали уже?
            cur_position_buf_modbus16 = START_ARRAY_LOG_SEND;
            log_to_HMI.flag_log_array_sended = 1;
    //        log_to_HMI.flag_log_array_sent_process = 0;
//            succed = 1;
            return succed;
        }

//        //Дырка в обмене. Пропускаем.
//        if ((cur_position_buf_modbus16 > ADRESS_END_FIRST_BLOCK) &&
//                (cur_position_buf_modbus16 < ADRESS_START_PROTECTION_LEVELS)) {
//            cur_position_buf_modbus16 = ADRESS_START_PROTECTION_LEVELS;
//        }

        if ((cur_position_buf_modbus16 + SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE) > (END_ARRAY_LOG_SEND+1))
            count_write_to_modbus = END_ARRAY_LOG_SEND - cur_position_buf_modbus16 + 1;
        else
            count_write_to_modbus = SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE;

        log_to_HMI.n_log_array_sended = (cur_position_buf_modbus16 - START_ARRAY_LOG_SEND)/100 + 1;
        log_to_HMI.flag_log_array_sent_process++;// = 1;

        ModbusRTUsend16(&rs_b, 2,
                        ADR_MODBUS_TABLE_REMOUTE + cur_position_buf_modbus16,
                        count_write_to_modbus);



 //       control_station.count_error_modbus_16[CONTROL_STATION_INGETEAM_PULT_RS485]++;

  //      control_station.flag_message_sent[CONTROL_STATION_INGETEAM_PULT_RS485] = 1;
        succed = count_write_to_modbus;
    }
    return succed;



/*

    unsigned long i = 0;
    int succed = 0;

//    int *p_log_data = (int*)LOG_START_ADRES;

    ModbusRTUsetDataArrays(modbus_table_analog_in, modbus_table_analog_out);
    if (!rs_b.flag_LEADING)
    {
        ModbusRTUsend16(&rs_b, 2,
                        log_to_HMI.current_address,
                                log_to_HMI.count_write_to_modbus + 1);

        if (err_send_log_16 == 0) { //prev message without errors
            log_to_HMI.current_address = log_to_HMI.current_address + SIZE_BUF_WRITE_LOG_TO_MODBUS16;
        }
        if (log_to_HMI.current_address > END_ARRAY_LOG_SEND) {
            log_to_HMI.current_address = START_ARRAY_LOG_SEND;
//            log_to_HMI.flag_end_of_log = 1;
            log_to_HMI.flag_log_array_sent = 1;
        }
        if ((log_to_HMI.current_address + SIZE_BUF_WRITE_LOG_TO_MODBUS16) > END_ARRAY_LOG_SEND) {
            log_to_HMI.count_write_to_modbus = END_ARRAY_LOG_SEND - log_to_HMI.current_address;
        } else {
            log_to_HMI.count_write_to_modbus = SIZE_BUF_WRITE_LOG_TO_MODBUS16;
        }

        err_send_log_16 += 1;
        succed = 1;

    }
    return succed;
*/
}

void prepareWriteLogsArray(void) {
//    log_to_HMI.start_log_address = logpar.addres_mem - logpar.count_log_params_fast_log * SIZE_ARRAY_LOG_SEND;
//    log_to_HMI.start_log_address = log_params.addres_mem - log_params.BlockSizeErr * SIZE_ARRAY_LOG_SEND;

    if (log_to_HMI.send_log == 1)
        log_to_HMI.start_log_address = log_params.start_address_log_slow;
    if (log_to_HMI.send_log == 2)
        log_to_HMI.start_log_address = log_params.start_address_log;
    if (log_to_HMI.send_log == 3)
        log_to_HMI.start_log_address = 0;//log_params.start_address_log;

    // - log_to_HMI.max_size_logs_hmi;

//    if (log_to_HMI.start_log_address < log_params.start_address_log) {
//        log_to_HMI.start_log_address = log_params.end_address_log - (log_params.start_address_log - log_to_HMI.start_log_address);
//    }
//    log_to_HMI.log_address_step = SIZE_ARRAY_LOG_SEND;//log_params.BlockSizeErr;
}


int fillAnalogDataArrayForLogSend(void)
{
    int i, k, n;// = START_ARRAY_LOG_SEND;
    int c_data = 0, lb = 0, type_log;
    volatile unsigned long local_pos = 0;

//    unsigned long current_address = log_to_HMI.start_log_address;// + num_of_log;

    k = 0;
    n = 0;
    for (i = START_ARRAY_LOG_SEND; i <= END_ARRAY_LOG_SEND; i++) {

//        if (log_to_HMI.count_write_to_modbus > log_to_HMI.max_size_logs_hmi)
//            break;

        n = log_to_HMI.count_write_to_modbus/SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE;

        if (k>=SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE)
            k = 0;

        if (k==0)
            modbus_table_analog_out[i].all   = LOWORD(log_to_HMI.count_write_to_modbus);
        else
        if (k==1)
            modbus_table_analog_out[i].all   = LOWORD(global_time.miliseconds);
        else
        if (k==2)
                modbus_table_analog_out[i].all   = HIWORD(log_to_HMI.start_log_address);
        else
        if (k==3)
                modbus_table_analog_out[i].all   = LOWORD(log_to_HMI.start_log_address);
        else
        if (k==SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE-1)
            modbus_table_analog_out[i].all   = log_to_HMI.tick_step;
        else
        {
            if (log_to_HMI.count_write_to_modbus > log_to_HMI.max_size_logs_hmi)
                modbus_table_analog_out[i].all   = 0;
            else
            {
//                modbus_table_analog_out[i].all   = LOWORD(log_to_HMI.start_log_address); // это для теста
                if (log_to_HMI.send_log==3)
                {
                    if (log_to_HMI.start_log_address>=(COUNT_FAST_DATA*log_params.BlockSizeErr) )
                    {
                        local_pos = log_to_HMI.max_size_logs_hmi - log_to_HMI.start_log_address;// - (COUNT_FAST_DATA*log_params.BlockSizeErr);
                        type_log = SLOW_LOG;
                    }
                    else
                    {
                        local_pos = log_to_HMI.max_size_logs_hmi - log_to_HMI.start_log_address - (COUNT_SLOW_DATA*log_params.BlockSizeErr);
                        type_log = FAST_LOG;
                    }

                    modbus_table_analog_out[i].all   = alarm_log_get_data(local_pos, type_log);
                }
                else
                    modbus_table_analog_out[i].all   = ReadMemory(log_to_HMI.start_log_address);



                log_to_HMI.start_log_address += 1;//log_to_HMI.log_address_step;
                log_to_HMI.count_write_to_modbus += 1;

            }
        }

//        modbus_table_analog_out[i+1].all = HIWORD(log_to_HMI.start_log_address);//log_to_HMI.count_write_to_modbus;//ReadMemory(log_to_HMI.start_log_address);
//        modbus_table_analog_out[i].all   = LOWORD(global_time.miliseconds);//ReadMemory(log_to_HMI.start_log_address);
//        modbus_table_analog_out[i+1].all = HIWORD(global_time.miliseconds);//log_to_HMI.count_write_to_modbus;//ReadMemory(log_to_HMI.start_log_address);

//        if (k>1 && k<SIZE_BUF_WRITE_LOGS_TO_MODBUS16_REMOUTE-1)
//        {
//            log_to_HMI.start_log_address += 1;//log_to_HMI.log_address_step;
//            log_to_HMI.count_write_to_modbus += 1;
//
//        }

        k++;
        c_data += 1;
    }
    return c_data;// сколько удалось записать

//    log_to_HMI.current_address = START_ARRAY_LOG_SEND;
    //log_to_HMI.count_write_to_modbus += num_of_log;
}




#define START_CMD_ADR_PROGRESS_DATA     192
#define LENGTH_CMD_PROGRESS_DATA        6

///////////////////////////////////////////////////
///
///////////////////////////////////////////////////
#define TIME_PAUSE_STATUS_SAVE  5000
#define MAX_WAIT_WRITE_DISCRETE 10 //10
#define MAX_WAIT_WRITE_PROGRESS 5

#define TIME_PAUSE_STATUS_SAVE1  10
#define TIME_PAUSE_STATUS_SAVE2  5000 //1000
#define TIME_PAUSE_STATUS_SAVE3  300 //
#define TIME_PAUSE_STATUS_SAVE4  700 //30
#define TIME_PAUSE_STATUS_SAVE5  30
#define TIME_PAUSE_STATUS_SAVE6  500 //150
#define TIME_PAUSE_STATUS_SAVE7  10000 //1000
#define TIME_PAUSE_STATUS_SAVE8  6000 //1000
#define TIME_PAUSE_STATUS_SAVE9  5000 //1000

//#define PLACE_STORE_LOG_PULT    2 //SD
#define PLACE_STORE_LOG_PULT    1 //USB Flash




void wdog_hmi(void)
{
    static int local_hmi_watch_dog = 0, stage = 0;




    stage = !stage;

    if (stage)
    {
        local_hmi_watch_dog = !local_hmi_watch_dog;
        setRegisterDiscreteOutput(local_hmi_watch_dog, 515);
        writeSigleDiscreteDataToRemote(515);
    }
    else
        writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);

}

int sendLogToHMI(int status_ok)
{
    int succed = 0, flag_next = 0;
    unsigned int time_finish_transmitt = 0, pause_save = 0;
    static int prev_send_log = 0, flag_one = 0;
    static int prev_status_ok = -1;
    static unsigned int count_send = 0, enable_next_step = 0;
    static unsigned int time_pause_status_save = TIME_PAUSE_STATUS_SAVE, old_time_status_save = 0,
            max_wait_write_discrete = MAX_WAIT_WRITE_DISCRETE, wait_write_discrete = 0,
            max_wait_write_progress = MAX_WAIT_WRITE_PROGRESS, wait_write_progress = 0;

    static unsigned int time_pause_status_save1 = TIME_PAUSE_STATUS_SAVE1;
    static unsigned int time_pause_status_save2 = TIME_PAUSE_STATUS_SAVE2;
    static unsigned int time_pause_status_save3 = TIME_PAUSE_STATUS_SAVE3;
    static unsigned int time_pause_status_save4 = TIME_PAUSE_STATUS_SAVE4;
    static unsigned int time_pause_status_save5 = TIME_PAUSE_STATUS_SAVE5;
    static unsigned int time_pause_status_save6 = TIME_PAUSE_STATUS_SAVE6;
    static unsigned int time_pause_status_save7 = TIME_PAUSE_STATUS_SAVE7;
    static unsigned int time_pause_status_save8 = TIME_PAUSE_STATUS_SAVE8;
    static unsigned int time_pause_status_save9 = TIME_PAUSE_STATUS_SAVE9;

//    static unsigned int place_store_log_pult = PLACE_STORE_LOG_PULT;

    static unsigned int flag_local_sended = 0, flag_local_finish = 0;



    if (log_to_HMI.send_log && prev_send_log==0)
    {
        if (log_to_HMI.max_size_logs_hmi_small == 0)

#if(_LOG_HMI_SMALL_TEST==1)
            log_to_HMI.max_size_logs_hmi_small =  MAX_SIZE_LOGS_HMI_SMALL;
#else
            log_to_HMI.max_size_logs_hmi_small =  (log_params.end_address_log_slow - log_params.start_address_log_slow + 1 ); //MAX_SIZE_LOGS_HMI_SMALL;
#endif

        if (log_to_HMI.max_size_logs_hmi_full == 0)
            log_to_HMI.max_size_logs_hmi_full = MAX_SIZE_LOGS_HMI_FULL;

//30007 - здесь 1 - это запрос на сокращенные логи, а 2 на полные.
        if (log_to_HMI.send_log == 1)
            log_to_HMI.max_size_logs_hmi = log_to_HMI.max_size_logs_hmi_small;
        if (log_to_HMI.send_log == 2)
            log_to_HMI.max_size_logs_hmi = log_to_HMI.max_size_logs_hmi_full;

        if (log_to_HMI.send_log == 3)
            log_to_HMI.max_size_logs_hmi = log_params.BlockSizeErr*(COUNT_FAST_DATA+COUNT_SLOW_DATA);//  MAX_SIZE_LOGS_HMI_SMALL;//log_to_HMI.max_size_logs_hmi_full;



        log_to_HMI.step = -1;
        enable_next_step = 1;

//      log_to_HMI.flag_data_received = 0;
        log_to_HMI.count_write_to_modbus = 0;
        log_to_HMI.flag_log_array_sended = 0;
        log_to_HMI.log_size_sent = 0;
//      log_to_HMI.current_address = 0;
//      log_to_HMI.number_of_log = 0;

        log_to_HMI.progress_bar = 0;
        log_to_HMI.enable_progress_bar = 1;
        log_to_HMI.cleanLogs = 0;
        log_to_HMI.tick_step = 0;
//        log_to_HMI.tick_finish = 0;
        log_to_HMI.saveLogsToSDCard = 0;

        log_to_HMI.flag_log_array_sent_process = 0;
        log_to_HMI.count_sended_to_pult = 0;
        log_to_HMI.ReportLogOut = log_to_HMI.send_log;

        prepareWriteLogsArray();


        //global_time.miliseconds = 0;

//      setRegisterDiscreteOutput(0, 522);
    //  control_station.flag_message_sent[CONTROL_STATION_INGETEAM_PULT_RS485] = 1;
//      return 1;
    }



    if (log_to_HMI.send_log)
    {
        // удачно передали и получили ответ на пред команду?
        if (status_ok != prev_status_ok || prev_status_ok == -1 )
        {


            if (enable_next_step)
            {
                old_time_status_save = global_time.miliseconds;
                log_to_HMI.step++;
            }

            if (log_to_HMI.flag_log_array_sended==0 && log_to_HMI.step==8)
            {
                // ложный переход идем назад на 4, т.к. не все данные уехали
                log_to_HMI.step--;
                flag_next = 1;
            }


            if ((time_pause_status_save4==0 && log_to_HMI.step==6)
                || (time_pause_status_save5==0 && log_to_HMI.step==8)
                || (time_pause_status_save6==0 && log_to_HMI.step==10))
                log_to_HMI.step++;  // пропуск шага

        }




        switch (log_to_HMI.step)
        {

            case 0:
                    if (detect_pause_milisec(time_pause_status_save1,&old_time_status_save) || time_pause_status_save1 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

                        wdog_hmi();


                    }
                    break;

            case 1:
                    log_to_HMI.cleanLogs = 1;//!log_to_HMI.tick_start;
                    update_logs_cmd_HMI();
                    writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
                    succed = 1;
                    enable_next_step = 1;
//                    log_to_HMI.step++;

                    break;

//            case 1:
//                    log_to_HMI.progress_bar = 100;
//                    log_to_HMI.enable_progress_bar = 1;
//
//                    update_logs_cmd_HMI();
//                    writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA,LENGTH_CMD_PROGRESS_DATA);
//
//                    old_time_status_save = global_time.miliseconds;
////                    log_to_HMI.step++;
//                    succed = 1;
//                    enable_next_step = 1;
//                    break;
            case 2:
                    if (detect_pause_milisec(time_pause_status_save2,&old_time_status_save) || time_pause_status_save2 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;
                        wdog_hmi();


                    }
                    break;

//            case 2:
//                    if (detect_pause_milisec(time_pause_status_save,&old_time_status_save))
//                    {
//                        succed = 1;
//                        enable_next_step = 1;
//                    }
//                    else
//                    {
//                        pause_save = get_delta_milisec(&old_time_status_save, 0);
//                        log_to_HMI.progress_bar = 100 - ((long)pause_save*100L)/(long)time_pause_status_save;
//
//                        if (log_to_HMI.progress_bar<50)
//                            log_to_HMI.tick_start = 0;
//
//                        if (flag_one)
//                        {
//                            update_logs_cmd_HMI();
//                            writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
//                        }
//                        else
//                        {
//                            setRegisterDiscreteOutput(hmi_watch_dog, 515);
//                            hmi_watch_dog = !hmi_watch_dog;
//                            writeSigleDiscreteDataToRemote(515);
//                        }
//                        flag_one = !flag_one;
//
//
//                        succed = 1;
//                        enable_next_step = 0;
//                    }
//                    break;
            case 3:
                    log_to_HMI.cleanLogs = 0;
                    log_to_HMI.progress_bar = 0;
                    log_to_HMI.enable_progress_bar = 1;
                    log_to_HMI.count_write_to_modbus = 0;


                    update_logs_cmd_HMI();
                    writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
                    succed = 1;
                    enable_next_step = 1;

//                    log_to_HMI.step++;
                    break;

            case 4:
                    if (detect_pause_milisec(time_pause_status_save3,&old_time_status_save) || time_pause_status_save3 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;

                        log_to_HMI.flag_log_array_sended = 0;
    //                    log_to_HMI.flag_log_array_sent_process = 1;
                        log_to_HMI.flag_start_log_array_sent = 1;
                        // заполним данными
    //                    log_to_HMI.number_of_log = SIZE_ARRAY_LOG_SEND;
                        log_to_HMI.tick_step++;
                        log_to_HMI.count_data_in_buf = fillAnalogDataArrayForLogSend();
                        flag_next = 0;


                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

                        wdog_hmi();

                    }
                    break;



//            case 4:
//                    log_to_HMI.flag_log_array_sended = 0;
////                    log_to_HMI.flag_log_array_sent_process = 1;
//                    log_to_HMI.flag_start_log_array_sent = 1;
//                    // заполним данными
////                    log_to_HMI.number_of_log = SIZE_ARRAY_LOG_SEND;
//                    log_to_HMI.count_data_in_buf = fillAnalogDataArrayForLogSend();
//
// //                   update_logs_cmd_HMI();
////                    writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
//                    succed = 1;
//                    enable_next_step = 1;
////                    log_to_HMI.step++;
//                    break;

            case 5:
                    if (wait_write_discrete<max_wait_write_discrete)
                    {
                        wait_write_discrete++;
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        wait_write_discrete = 0;
                        //update_tables_HMI_discrete();
                        //                        update_tables_HMI_analog();
                        wdog_hmi();

//                        setRegisterDiscreteOutput(hmi_watch_dog, 515);
//                        hmi_watch_dog = !hmi_watch_dog;
//                        writeSigleDiscreteDataToRemote(515);

//                        writeDiscreteDataToRemote();// для поднятия обмена
    //                    log_to_HMI.step++;
                        succed = 1;
                        enable_next_step = 1;
                    }
                    break;

            case 6:
                    if (detect_pause_milisec(time_pause_status_save4,&old_time_status_save) || time_pause_status_save4 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                        flag_local_finish = 0;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

                        wdog_hmi();


                    }
                    break;

            case 7:
                    // есть что отправлять?
                    if (log_to_HMI.count_data_in_buf)
                    {

//                        if (flag_next)
//                        {
//                            if (flag_local_sended)
//                            {
//                                flag_local_finish = 1;
//                                flag_local_sended = 0;
//                            }
//                            else
//                            if (flag_local_finish)
//                            {
//                                flag_local_finish = 0;
//                            }
//                        }


//                        if (flag_local_finish)
//                        {
//
//                            if (log_to_HMI.n_log_array_sended==1)
//                                log_to_HMI.tick_step++; // дернули 194 регистр
//                            else
//                            if (log_to_HMI.n_log_array_sended==2)
//                                log_to_HMI.tick_step2++; // дернули 194 регистр
//                            else
//                            if (log_to_HMI.n_log_array_sended==3)
//                                log_to_HMI.tick_step3++; // дернули 194 регистр
//                            else
//                            if (log_to_HMI.n_log_array_sended==4)
//                                log_to_HMI.tick_step4++; // дернули 194 регистр
//                            else
//                            if (log_to_HMI.n_log_array_sended==5)
//                                log_to_HMI.tick_step5++; // дернули 194 регистр
//
//
//                            update_logs_cmd_HMI();
//                            writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
//
//                            flag_next = 0;
//
//                        }
//                        else
                        {

                            // отправим в пульт все данные по блокам
                            writeLogsArray(flag_next);// тут уйдет весь буфер
                            flag_local_sended = 1;
                            flag_local_finish = 0;
                            flag_next = 0;
                        }

                        // все ушли?
                        if (log_to_HMI.flag_log_array_sended)
                        {
                            log_to_HMI.log_size_sent = log_to_HMI.count_write_to_modbus;
                            log_to_HMI.count_sended_to_pult += log_to_HMI.count_data_in_buf;
                        }
                        else
                        {
                            succed = 1;
                        }
                    }
                    else
                    {
                        status_ok = 0;
                        log_to_HMI.step += 3;
                    }
                    enable_next_step = 1;

                    break;

            case 8:
                    if (detect_pause_milisec(time_pause_status_save5,&old_time_status_save) || time_pause_status_save5 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

//                        wdog_hmi();


                    }
                    break;

            case 9:

                    if (wait_write_progress<max_wait_write_progress)
                    {
                        wait_write_progress++;
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        wait_write_progress = 0;

                        log_to_HMI.progress_bar = (log_to_HMI.count_write_to_modbus*100)/log_to_HMI.max_size_logs_hmi;

                        update_logs_cmd_HMI();
                        writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
                        succed = 1;
                        enable_next_step = 1;
                    }
                    break;

            case 10:
                    if (detect_pause_milisec(time_pause_status_save6,&old_time_status_save) || time_pause_status_save6 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

//                        wdog_hmi();


                    }
                    break;


            case 11:
//                    log_to_HMI.flag_log_array_sent_process = 0;

//                    if (log_to_HMI.flag_log_array_sent)
//                        log_to_HMI.tick_step++;

                    if (log_to_HMI.log_size_sent < log_to_HMI.max_size_logs_hmi)
//                      log_to_HMI.step++;
//                    else
                        log_to_HMI.step = 3; // передаем дальше, еще нет  log_to_HMI.max_size_logs_hmi

                    status_ok = 0;
                    succed = 1;
                    enable_next_step = 1;
                    break;

            case 12:
                    if (detect_pause_milisec(time_pause_status_save7,&old_time_status_save) || time_pause_status_save7 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

                        wdog_hmi();


                    }
                    break;


            case 13:

               //     log_to_HMI.tick_finish = place_store_log_pult;
                    log_to_HMI.saveLogsToSDCard = 3;//log_to_HMI.sdusb;
                    log_to_HMI.progress_bar = 100;

                    update_logs_cmd_HMI();
                    writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);

//                    log_to_HMI.step++;
                    succed = 1;
                    enable_next_step = 1;
                    break;

            case 14:
                    if (detect_pause_milisec(time_pause_status_save8,&old_time_status_save) || time_pause_status_save8 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

                        wdog_hmi();


                    }
                    break;

            case 15:

//                     log_to_HMI.tick_finish = 0;
                     log_to_HMI.saveLogsToSDCard = 0;

                     log_to_HMI.progress_bar = 0;
                     //log_to_HMI.enable_progress_bar = 0;
                     log_to_HMI.ReportLogOut = 255;

                     update_logs_cmd_HMI();
                     writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);

 //                    log_to_HMI.step++;
                     succed = 1;
                     enable_next_step = 1;
                     break;

            case 16:
                    if (detect_pause_milisec(time_pause_status_save9,&old_time_status_save) || time_pause_status_save9 == 0)
                    {
                        succed = 1;
                        enable_next_step = 1;
                    }
                    else
                    {
                        succed = 1;
                        enable_next_step = 0;

                        wdog_hmi();


                    }
                    break;


//            case 17:
//
//                    log_to_HMI.tick_finish = place_store_log_pult;
//                    log_to_HMI.progress_bar = 100;
//
//                    update_logs_cmd_HMI();
//                    writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
//
//                    succed = 1;
//                    enable_next_step = 1;
//                    break;
//
//            case 18:
//                    if (detect_pause_milisec(time_pause_status_save8,&old_time_status_save))
//                    {
//                        succed = 1;
//                        enable_next_step = 1;
//                    }
//                    else
//                    {
//                        succed = 1;
//                        enable_next_step = 0;
//
//                        wdog_hmi();
//
//                    }
//                    break;
//
//            case 19:
//
//                     log_to_HMI.tick_finish = 0;
//                     log_to_HMI.progress_bar = 0;
//                     log_to_HMI.enable_progress_bar = 0;
//
//                     update_logs_cmd_HMI();
//                     writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);
//
// //                    log_to_HMI.step++;
//                     succed = 1;
//                     enable_next_step = 1;
//                     break;
//
//            case 20:
//                    if (detect_pause_milisec(time_pause_status_save9,&old_time_status_save))
//                    {
//                        succed = 1;
//                        enable_next_step = 1;
//                    }
//                    else
//                    {
//                        succed = 1;
//                        enable_next_step = 0;
//
//                        wdog_hmi();
//
//                    }
//                    break;
//
//
//


            case 17:

                    log_to_HMI.ReportLogOut = 0;
                    update_logs_cmd_HMI();
//                    writeSingleAnalogDataToRemote(START_CMD_ADR_PROGRESS_DATA, LENGTH_CMD_PROGRESS_DATA);

                    log_to_HMI.send_log = 0;
                    log_to_HMI.enable_progress_bar = 0;
      //              log_to_HMI.step++;
                    succed = 0;
                    enable_next_step = 1;
                    break;


            default:
                    break;

        }

    }
    prev_send_log = log_to_HMI.send_log;
    prev_status_ok = status_ok;






//
//
//
//  if (log_to_HMI.step == 0)
//    {
////        modbus_table_analog_out[3].all = log_params.BlockSizeErr;//  logpar.count_log_params_fast_log;
//
//        if (log_to_HMI.log_size_sent == 0 &&
//            (writeSingleAnalogOutputToRemote(3) == 1))
//        {
//            log_to_HMI.log_size_sent = 1;
//            succed = 1;
//        } else if (log_to_HMI.log_size_sent == 1) {
//            log_to_HMI.step = 1;
//            log_to_HMI.flag_log_array_sent = 0;
//            prepareWriteLogsArray();
//            fillAnalogDataArrayForLogSend(log_to_HMI.number_of_log);
//        }
//    }
//  if (log_to_HMI.step == 1) {
//      if (log_to_HMI.flag_log_array_sent == 0) {
//          succed = writeLogsArray(log_to_HMI.number_of_log);
//      } else {
//          log_to_HMI.step = 2;
//          init_timer_milisec(&time_finish_transmitt);
//      }
//    }
//  if (log_to_HMI.step == 2)
//    {
//        if (detect_pause_milisec(1000, &time_finish_transmitt)) {
//            setRegisterDiscreteOutput(1, 522);
//            if (writeDiscreteDataToRemote() == 1) {
//                log_to_HMI.step = 3;
//                succed = 1;
//            }
//        } else {
//            succed = 1;
//        }
//
//    }
//  if (log_to_HMI.step == 3) {
//      succed = readAnalogDataFromRemote();
//      if (modbus_table_analog_in[8].all == 1) {
//          if (detect_pause_milisec(1000, &time_finish_transmitt)) {
//              log_to_HMI.step = 4;
//          }
//      } else {
//          init_timer_milisec(&time_finish_transmitt);
//      }
//  }
//  if (log_to_HMI.step == 4) {
//      setRegisterDiscreteOutput(0, 522);
//        if (writeDiscreteDataToRemote() == 1) {
//            log_to_HMI.step = 5;
//            succed = 1;
//        }
//  }
//  if (log_to_HMI.step == 5) {
//      succed = readAnalogDataFromRemote();
//      if (modbus_table_analog_in[8].all == 0) {
//            if (detect_pause_milisec(1000, &time_finish_transmitt) && log_to_HMI.number_of_log < (log_params.BlockSizeErr - 1)) {
//                log_to_HMI.number_of_log += 1;
//                fillAnalogDataArrayForLogSend(log_to_HMI.number_of_log);
//                log_to_HMI.flag_log_array_sent = 0;
//                log_to_HMI.step = 1;
//            } else {
//                succed = 1;
//            }
//        }
//  }

//  log_to_HMI.send_log = modbus_table_analog_in[7].all;
//  control_station.flag_message_sent[CONTROL_STATION_INGETEAM_PULT_RS485] = 1;


    return succed;
}

#define PAUSE_AUTO_SAVE_SLOW_LOG_SECONDS    300 //120 //60 // 60 sec

void run_store_slow_logs(void)
{
    static int prev_imit_save_slow_logs = 0, flag_auto_logs = 0;
    static unsigned int pause_logs = 0;

    if (pause_logs == 0)
        init_timer_sec(&pause_logs);

    flag_auto_logs = detect_pause_sec(PAUSE_AUTO_SAVE_SLOW_LOG_SECONDS, &pause_logs);


    if ((edrk.imit_save_slow_logs && prev_imit_save_slow_logs == 0) || flag_auto_logs)
    {
        if (log_to_HMI.send_log == 0)
            set_write_slow_logs(1);
    }
    else
        set_write_slow_logs(0);

    prev_imit_save_slow_logs = edrk.imit_save_slow_logs;

}



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

void fillLogArea() {
    unsigned int value = 0;
    unsigned int *p_memory = (unsigned int*)LOG_START_ADRES;
    long log_size = LOG_BUFFER_SIZE;
    while (log_size-- > 0) {
        *(p_memory++) = value;
        value += 1;
//      if (log_size % 8 == 0) {
//          value += 1;
//      }
    }
}






int alarm_log_get_data(unsigned long pos, int type_log)
{
   //unsigned int i,k;
   static volatile unsigned long cur_adr_log, end_log, start_log, addres_mem, temp_length, delta_adr;//clog //real_length
   //int *adr_finish_temp, *adr_current;


//   real_length = al->real_points * al->oscills;
  // real_adr = al->start_adr_real_logs;

   if (type_log==FAST_LOG)
   {
       temp_length = log_params.BlockSizeErr;
       cur_adr_log = log_params.addres_mem;
       end_log = log_params.end_address_log;
       start_log = log_params.start_address_log;

   }

   if (type_log==SLOW_LOG)
   {
       temp_length = log_params.BlockSizeSlow;
       cur_adr_log = log_params.addres_mem_slow;
       end_log = log_params.end_address_log_slow;
       start_log = log_params.start_address_log_slow;
   }

   // ищем точку в памяти


   addres_mem = cur_adr_log - pos;//temp_length

   // перехали начло лога?
   if (addres_mem<start_log)
   {
       delta_adr = start_log - addres_mem ;
       addres_mem = end_log - delta_adr + 1;
   }

   return ReadMemory(addres_mem);


/*

   temp_length  =  al->temp_points * al->oscills; // сколько данных надо выерезать из лога
   al->temp_log_ready = 0;


   if (al->current_adr_real_log == al->start_adr_real_logs) // мы в начале, логов нету?
       return;

   adr_current = al->current_adr_real_log; // выставили конец лога
   adr_finish_temp = al->start_adr_temp + temp_length; // тут конец лога temp
   // теперь начиная с конца adr_finish скопируем в temp_log
   // с учетом того что мы копируем из циклического буфера в обычный, нужна развертка данных
   for (clog=0; clog<temp_length ;clog++)
   {
       if ( (adr_current >= al->start_adr_real_logs) )
       {
        *adr_finish_temp = *adr_current; // скопирлвали данные
        // едем назад
        adr_current--;
       }
       else
        *adr_finish_temp = 0; // а нету данных!

       // едем назад
       adr_finish_temp--;

       // закольцевались?
       if (adr_current < al->start_adr_real_logs)
       {
           if (al->finish_adr_real_log) // лог прокручивался?
              adr_current = al->finish_adr_real_log; // перешли в конец.
           else
               adr_current = al->start_adr_real_logs - 1;
       }
   }

   al->temp_log_ready = 1;
*/

}




