/*
 * main.c
 *
 *  Created on: 12 апр. 2021 г.
 *      Author: ZavyalovRA
 */

#include "main.h"

uint8_t flg_powerState = 0;
void checkButtons(void);

int main(void)
{
// добавляем громкость при начале воспроизведения
  tmp_VolIncFlag = 0;

  HAL_Init();
  SystemClock_Config();

  GPIO_Config();
  //TIM3_Config();
  //TIM4_Config();

  RCC->APB1ENR |= RCC_APB1ENR_TIM4EN;
  initAVCLAN();
  initButtons();

  doRegister();

  while (1) {

	  // if message from some device on AVCLan begin
	  if (RCV_BIT) AVCLan_Read_Message();

	  // HandleEvent
	  switch (answerReq) {
	    case cmNextTrack:	answerReq = cmNull;
	      //ClearEvents();
	      setNextTrack();
	      break;
	    case cmPrevTrack:	answerReq = cmNull;
	      //ClearEvents();
	      setPrevTrack();
	      break;
	    case cmNextDisc:	answerReq = cmNull;
	      //ClearEvents();
	      setNextTrack();
	      break;
	    case cmPrevDisc:	answerReq = cmNull;
	      //ClearEvents();
	      setPrevTrack();
	      break;
	  }

	  // если не обработали сообщения - идём отвечаем дальше
	  if(answerReq) AVCLan_SendAnswer();

	  if(CD_Mode == stPlay && flg_sysTickMarked) {
	    flg_sysTickMarked = 0;
	    AVCLan_Send_Status();
	    cd_Time_Sec = HexInc(cd_Time_Sec);
	    if(cd_Time_Sec == 0x60) {
	      cd_Time_Sec = 0;
	      cd_Time_Min = HexInc(cd_Time_Min);
	      if(cd_Time_Min == 0xA0) {
	        cd_Time_Min=0x0;
	        cd_Time_Min = 0;
	        cd_Time_Sec = 0;
	      }
	    }
	  }

	  if(tmp_VolIncFlag) {
	    if(tmp_VolIncCounter > 0) {
	      tmp_VolIncCounter--;
	      BUTT1_PREV_UP;
	    } else {
	      tmp_VolIncFlag = 0;
	      BUTT1_PREV_DN;
	    }
	  }

	  // вкл-выкл питание
	  if(CD_Mode == stPlay && flg_powerState == 0) {
	    setPowerOn();
	    flg_powerState = 1;
	  }

	  if(CD_Mode == stStop && flg_powerState == 1) {
	    setPowerOff();
	    flg_powerState = 0;
	  }
  }
}

void checkButtons() {
  if(flg_ButtonNext) {
    clickButtonNext();
    flg_ButtonNext--;
  }
}



void TIM3_IRQHandler(void)
{
	HAL_TIM_IRQHandler(&htim3);
}

void TIM4_IRQHandler(void)
{
	HAL_TIM_IRQHandler(&htim4);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Instance == TIM1) {
    HAL_IncTick();
  }
}

void Error_Handler(void)
{

}

#ifdef  USE_FULL_ASSERT

void assert_failed(uint8_t *file, uint32_t line)
{ 

}
#endif
