/************************************************************************************//**
* \file         Demo/ARMCM0_STM32G0_Nucleo_G071RB_CubeIDE/Prog/App/app.c
* \brief        User program application source file.
* \ingroup      Prog_ARMCM0_STM32G0_Nucleo_G071RB_CubeIDE
* \internal
*----------------------------------------------------------------------------------------
*                          C O P Y R I G H T
*----------------------------------------------------------------------------------------
*   Copyright (c) 2020  by Feaser    http://www.feaser.com    All rights reserved
*
*----------------------------------------------------------------------------------------
*                            L I C E N S E
*----------------------------------------------------------------------------------------
* This file is part of OpenBLT. OpenBLT is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OpenBLT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You have received a copy of the GNU General Public License along with OpenBLT. It
* should be located in ".\Doc\license.html". If not, contact Feaser to obtain a copy.
*
* \endinternal
****************************************************************************************/

/****************************************************************************************
* Include files
****************************************************************************************/
extern "C" {
    #include "header.h"                                    /* generic header               */
    #include "vl6180_app.h"
}

#include <cstring>
#include "uart_bridge.hpp"
#include "tim.h"

UartBridge bridge(true, USART1, USART2, 9600, 9600);
void zummerOff (void);
void zummerOn (void);
void lightingOn (void);
void lightingOff (void);
/************************************************************************************//**
** \brief     Initializes the user program application. Should be called once during
**            software program initialization.
** \return    none.
**
****************************************************************************************/
void AppInit(void)
{
  /* Initialize the timer driver. */
  TimerInit();
  vl6180_init();
  /* Initialize the led driver. */
  LedInit();
  /* initialize the bootloader interface */
  bridge.init();
  zummerOff();
  lightingOff();
/*
  BootComInit();

*/
} /*** end of AppInit ***/


/************************************************************************************//**
** \brief     Task function of the user program application. Should be called
**            continuously in the program loop.
** \return    none.
**
****************************************************************************************/

uint32_t controlPinMs = 0;
uint8_t controlPinFlag = 0;
uint32_t controlPinDetectedMs = 0;
uint8_t updateMode = 0;



void zummerOff (void)
{
    HAL_TIM_Base_Stop(&htimZummer);
    HAL_TIM_PWM_Stop(&htimZummer, TIM_CHANNEL_2);
}
void zummerOn (void)
{
    HAL_TIM_Base_Start(&htimZummer);
    HAL_TIM_PWM_Start(&htimZummer, TIM_CHANNEL_2);
}
void lightingOn (void)
{
    HAL_TIM_Base_Start(&htimLighitng);
    HAL_TIM_PWM_Start(&htimLighitng, TIM_CHANNEL_1);
}
void lightingOff (void)
{
    HAL_TIM_Base_Stop(&htimLighitng);
    HAL_TIM_PWM_Stop(&htimLighitng, TIM_CHANNEL_1);
}

uint8_t proximityCompleteMessure = 0;
void proximityMessureCompleted (void)
{
    proximityCompleteMessure = 1;
}


VL6180_RangeData_t VL6180_Range;
uint32_t waitAnswerFromReaderMs = 0;
#define MAX_WAIT_ANSWER_FROM_GM60 30000
#define DATA_TIMEOUT 500

uint32_t lightStartMs = 0;
uint8_t uart1Buf[1024];
uint8_t uart2Buf[1024];
uint8_t uartTask (void) // return 0 if data received , otherwise return 1
{

    if (waitAnswerFromReaderMs != 0)
    {
        if (HAL_GetTick() - waitAnswerFromReaderMs >= MAX_WAIT_ANSWER_FROM_GM60 )
        {
            HAL_GPIO_WritePin(READER_EN_GPIO_Port, READER_EN_Pin, GPIO_PIN_SET );
            HAL_Delay(500);
            HAL_GPIO_WritePin(READER_EN_GPIO_Port, READER_EN_Pin, GPIO_PIN_RESET );
            waitAnswerFromReaderMs = 0;
        }
    }

    if (!bridge.uart1Buf->is_empty() && bridge.getHuart2()->gState == 0x20) {
        HAL_UART_Abort(bridge.getHuart1());
        HAL_UARTEx_ReceiveToIdle_IT(bridge.getHuart1(),(uint8_t*)bridge.dataFromUart1, BUF_SIZE );
        waitAnswerFromReaderMs = HAL_GetTick();
        std::string_view stringView{bridge.uart1Buf->dequeue()};
        uint32_t size = stringView.size();
        if (size > 4)
        {
            stringView.copy(reinterpret_cast<char *>(uart1Buf), size, 0);
            if (stringView.find("FIRMWARE_UPDATE") != std::string::npos)
            {
                HAL_UART_DeInit(bridge.getHuart1());
                BootComInit();
                zummerOff();
                lightingOff();
            }
            else if (stringView.find("ZOOMER_ON") != std::string::npos)
            {
                zummerOn();
            }
            else if (stringView.find("ZOOMER_OFF") != std::string::npos)
            {
                zummerOff();
            }
            else
            {
                HAL_UART_Transmit_IT(bridge.getHuart2(), (const uint8_t*) uart1Buf, size);
            }
        }
        return 0;
    }

    if (!bridge.uart2Buf->is_empty() && bridge.getHuart1()->gState == 0x20) {
        waitAnswerFromReaderMs = 0;
        std::string_view stringView{bridge.uart2Buf->dequeue()};
        uint32_t size = stringView.size();
        if (size  > 4)
        {
            stringView.copy(reinterpret_cast<char *>(uart2Buf), size, 0);
            HAL_UART_Transmit_IT(bridge.getHuart1(), (const uint8_t*) uart2Buf, size);
            return 0;
        }
    }
    return 1;
}
void AppTask(void)
{
    if (!updateMode) {
            uartTask();
        if (HAL_GetTick() - lightStartMs >= 10000 && lightStartMs > 0)
        {
            lightStartMs = 0;
            lightingOff();
        }
        if (bridge.uart1Buf->is_empty() && bridge.uart2Buf->is_empty())
        {
            if (proximityCompleteMessure == 1)
            {
                proximityCompleteMessure = 0;
                if (getRange(&VL6180_Range) == 0)
                {
                    if (VL6180_Range.range_mm > 0 && lightStartMs == 0)
                    {
                        lightStartMs = uwTick;
                        lightingOn();
                    }
                }
            }
        }
    }
    else
    {
        BootComCheckActivationRequest();
    }
}


 /*** end of AppTask ***/

/*********************************** end of app.c **************************************/

//////////// FINALLY NEED TO UNCOMMENT BootComCheckActivationRequest and BootComInit for success firmwaare update from HOST