/********************************* (C) РОТЕК ***********************************
 * @module  init_task
 * @file    init_task.c
 * @version 1.0.0
 * @date    XX.XX.XXXX
 * $brief   Инициализация всех задач.
 *******************************************************************************
 * @history     Version  Author         Comment
 * XX.XX.XXXX   1.0.0    Telenkov D.A.  First release.
 *******************************************************************************
 */
#include "init_task.h"
#include "common_config.h"
#include "wdg.h"
#include "usart.h"
//#include "port_microrl.h"
#include "led.h"
#include "rng.h"
#include "buttons.h"
#include "jumper.h"
#include "rtc.h"
#include "log.h"
#include "stm32f4x7_eth_bsp.h"
#include "netconf.h"
#include "udp_netsetting.h"
#include "snmp_api.h"
#ifdef CLI_ENABLE
#include "cli.h"
#endif
#ifdef TELNET_ENABLE
#include "telnet_server.h"
#endif
#ifdef SSH_ENABLE
#include "server.h"
#endif
#ifdef HTTP_SERVER_ENABLE
#include "http_server.h"
#endif
#ifdef SSL_SERVER_ENABLE
#include "my_ssl_server.h"
#endif
#ifdef PORTGW_ENABLE
#include "portgw.h"
#endif
#ifdef DALLAS_SENSOR_ENABLE
#include "temper.h"
#endif
#include "sntp_api.h"
#include "settings_api.h"
#include "main.h"
#include "trap_api.h"
#include "megatec.h"
#include "testing.h"
#include "ups_monitor.h"
//#include "ups_params.h"
//#include "ups_monitor.h"
#include "lwip/stats.h"
#ifdef RADIUS_SERVER_ENABLE
#include "radius_user.h"
#include "cert_req.h"
#include "parse_rsa.h"
#endif
#ifdef PRINTF_STDLIB
#include <stdio.h>
#endif
#ifdef PRINTF_CUSTOM
#include "tinystdio.h"
#endif
#include "syslog.h"
#include "FreeRTOS.h"
#include "task.h"

extern bool dhcp;

/**
  * @brief  Общая структура настроек
  */
extern SETTINGS_t sSettings;

#ifdef DEBUG_FREERTOS
static void vTaskDebug(void *pvParameters);
#endif

/**
  * @brief  Разовая синхронизация времени при старте контроллера
  */
TaskHandle_t xHandleSntpOnceSinhro = NULL;


/**
  * @brief  Задача инициализации. Запускает основные задачи девайса и умирает.
  * @retval
  */
void InitTask(void *params)
{
// -----------------------------------------------------------------------------
    InitUSART();
    log_init(false);
    ups_megatec_init();
// -----------------------------------------------------------------------------
    //SETTINGS_SetAllDefault();
    //SETTINGS_Save();
    SETTINGS_Load();

    if (set_mode_jumper()) {
        SETTINGS_SetServiceDef();
        SETTINGS_Save();
        log_event_data(LOG_PSW_CHANGE, "Сброс к заводскому");
    }
// -----------------------------------------------------------------------------
#ifdef HARDWARE_BT6703
    check_outputs_config();
#endif
// -----------------------------------------------------------------------------
#ifdef USART_DEBUG_ENABLE
    InitUSART();
    // MICRORL_Init();
#endif
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
#ifdef LED_ENABLE
    LED_Init();
    /* Простая мигалка для подтверждения живучести контроллера */
    xTaskCreate(vTaskLedBlink, "LED_Blink", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
#endif
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
#ifdef BUTTON_ENABLE
    BUTTON_Init();
    xTaskCreate(vTaskButtons, "Buttons", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
#endif
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
#ifdef RTC_ENABLE
    TM_RTC_Init(TM_RTC_ClockSource_External);
#endif
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
#ifdef UPS_ENABLE
    xTaskCreate(UPS_Monitor, "UPS_Monitor", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
#endif
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
#ifdef DALLAS_SENSOR_ENABLE
    OW_Init();
#endif
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
/* Random number generator */
    RNG_Init();
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
#ifdef NET_ENABLE
    ETH_BSP_Config();
    LwIP_Init();

#ifdef HTTP_SERVER_ENABLE
    HTTP_Init();
#endif
#ifdef SSL_SERVER_ENABLE
    HTTP_Init();
    HTTPS_Init();
    //#define SSL_TASK_PRIO   ( configMAX_PRIORITIES - 3 )
    xTaskCreate(ssl_server, "SSL", 24 * configMINIMAL_STACK_SIZE, NULL, SSL_TASK_PRIO, NULL);
#endif
// UDP for net settings
    if (strncmp(sSettings.sFlags.testState, "T2OK", 4)) {
        xTaskCreate(vTaskTesting, "Testing", 2 * configMINIMAL_STACK_SIZE,
            NULL, tskIDLE_PRIORITY, NULL);
    } else {
        UDP_netsetting_init();
    }
#ifdef CLI_ENABLE
    cli_init();
#endif
#if defined TELNET_ENABLE
    telnet_server_init();
#ifdef SSH_ENABLE
    ssh_server_init();
#endif
    openlog();
#endif
// -----------------------------------------------------------------------------
    /* SNTP */
    SNTP_Init();
    xTaskCreate(vTaskOnceSynchro, "sntpOnceSinhro", 2 * configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY,
        &xHandleSntpOnceSinhro);
    xTaskCreate(vTaskPeriodicSynchro, "sntpPeriodicSinhro", 2 * configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
// -----------------------------------------------------------------------------
#ifdef SNMP_ENABLE
    SNMP_Init();
    xTaskCreate(snmp_trap_tread, "snmpTrapTest", 4 * configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
#endif
#endif

// -----------------------------------------------------------------------------
// Прозрачный порт
#ifdef PORTGW_ENABLE
    portgw_init();
#endif

// -----------------------------------------------------------------------------
// Тестирование

// Тест таблицы трапов
    //xTaskCreate(vTestTrap, "Trap_test", 2*configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL);
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
#ifdef DEBUG_FREERTOS
   xTaskCreate(vTaskDebug, "Debug", 800, NULL, tskIDLE_PRIORITY, NULL);
#endif
// -----------------------------------------------------------------------------

    log_event_data(LOG_TURN_ON, " ");
    /* Контроль успешной загрузки. Сброс флага bootry */
    /* Сброс флага и сохранение нового значения во флеш памяти происходт после
       некоторой задержки для запуска всех задач */
    vTaskDelay(4000);

    SETTINGS_ResetBootTry();

    // Отправка трапа о перезагрузке в случае статического IP
    /* if (!dhcp)
       SNMP_SendUserTrap(DEVICE_REBOOTED);

     printf("Hello world\r\n");*/

    vTaskDelete(NULL);
    taskYIELD();
}

#ifdef DEBUG_FREERTOS
static void vTaskDebug(void *pvParameters)
{
    char msg[700];
    for (;;) {
        DBG printf("Free memory %d\n\r\r\n", xPortGetFreeHeapSize());
        DBG vTaskList(msg);
        DBG printf(msg);
        DBG printf("\n\r\r\n");
#if LWIP_STATS
        stats_display();
        DBG printf("\r\n\r\n");
#endif
        vTaskDelay(5000);
    }
}
#endif


/********************************* (C) РОТЕК **********************************/
