/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "can.h"
#include "iwdg.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include "package.h"
#include "message.h"
#include "lampa.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
FLAG flag;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

static long Falling_asleep;
uint8_t CanGO=0, timGo=0;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

int Isit(int num, int i, int z)
{
  int res, pls;

	if((num<0)||(num>=0x80)) return 0;
	res = Maska[i][num/0x10];
	res &= (1<<(num&0x0F));
	
	if(z)
	{
		pls = (espero[num]>CanRestart[i]/2);
		pls = pls || county[num];
		res = res && pls;
	}

	return res;
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  static int i,j,n,z,mask,qua;
  static int cancount[2]={1,2},cancell[2]={0,0},candid[2]={0,0};
  static unsigned int masca[8];
  static uint16_t precom=0;

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
 MX_IWDG_Init();
  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_CAN_Init();
  MX_TIM4_Init();
 // MX_IWDG_Init();
  /* USER CODE BEGIN 2 */

  LED_0_ON;
	LED_1_OFF;
	LED_2_ON;
	LED_3_OFF;

	for(i=0;i<10;i++)
	{
		LED_0_TGL;
		LED_1_TGL;
		LED_2_TGL;
		LED_3_TGL;	HAL_Delay(50);
	}

  	Mode = ReadJumpers()+1;
	Setup_CAN_addr(Mode-1);
	Load_params();	
	LastMode = Mode;
	Protokol = PROTOKOL;
	
	command=0;
	
	for(i=0;i<0x80;i++)
	county[i]=1;
	for(i=0;i<8;i++)
	masca[i]=0;
	for(i=0;i<2;i++)
	CanRound[i]=
	CanCycle[i]=0;

	timGo=1;

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
	while (1)
	{
		if (flag.force_pause)
		{
		__disable_irq();	
			for(int i=0;i<flag.pause;i++);
		__enable_irq();	
		}
			
		if( CanGO)
		{	CanGO=0;
			
			for(i=0;i<0x80;i++)
			if(espero[i]<30000) espero[i]++;
				
			for(i=0;i<2;i++)
			if(cancount[i]) cancount[i]--;
			else cancell[i] = 0;
		}
			
		for(i=0;i<2;i++)
		if( Cancount[i])
		if(!cancount[i]) 
		{
			while(1)
			{
				if( cancell[i]>= 0x80)
				{	cancell[i]=0;

					if( candid[i])
					{	candid[i]=0;
						CanCycle[i]++;
						cancount[i] = CanWait[i];
						goto Next;
				}	}	
				
				mask = Maska[i][cancell[i]/0x10] >> (cancell[i]&0x0F);
				if(!mask) cancell[i] = (cancell[i] + 0x10) & 0xFFF0 ;
				else
				{
					while(!(mask & 1))
					{
						cancell[i]++; mask >>= 1;
					}
					break;
			}	}
				
			z=1;
			if(espero[cancell[i]]>CanRestart[i])
			{
				county[cancell[i]]=1;
				z=0;
			}
			
			if(modbus[cancell[i]] != archiv[cancell[i]])
			{	
				if(cancell[i]==keys)
				for(j=0;j<CanRptLen;j++)
				county[cancell[i]+j] = CanRptVez;
				else	
				county[cancell[i]] = 1;
			}

			if (county[cancell[i]])
			{
				for(j=  3; j>0 && !Isit(cancell[i]+j,i,z); j--);
				for(n=j-3; n<0 && !Isit(cancell[i]+n,i,1); n++);

				qua = 1 + j - n;
				cancell[i]+= n;

				for(j=0;j<qua;j++)
				{
					n=cancell[i]+j;
					archiv[n]= modbus[n]; 
					espero[n]= 0;
					
					if( county[n])
					{	county[n]--;
						if(!county[n] && n != cancyclo+i)	candid[i]=1;
					}	
					if(!county[n]) masca[n/0x10] |= (1<<(n&0x0F));
				}	

				CAN_send(archiv,cancell[i],qua);

				cancount[i] = Cancount[i];
				cancell[i]+=qua; 

				for(j=0;j<8;j++)
				if((masca[j] & Maska[i][j]) != Maska[i][j]) break;
				if(j==8)
				{
					for(j=0;j<8;j++) masca[j]&=~Maska[i][j];
					CanRound[i]++;
				}

				if( Cancount[i]>1)
				if(!cancount[!i])
					cancount[!i]=1;
			}
			else	
				cancell[i]++; 
		}
	  
		Next:
		
		ReadEnteres();	
		
		if(Errors.all|Alarms.all)
						Pvt4_OFF;
		else			Pvt4_ON;	//	сигнал "Система ВЭП в норме"
			
		if(Errors.all)	Pvt3_ON;	//	сигнал "Авария системы ВЭП"
		else			Pvt3_OFF;
			
		if(Falling_asleep)	Pvt2_ON;		//	Пока не спим, это замкнуто
		else				Pvt2_OFF;		//	сигнал "Управление сетью 24В"


		if(Commands!=precom)
		{
			command= (~precom|command) & Commands;
		}
		precom = Commands;
		
		if(cDefParam)
		{
			cDefParam=0;
			Default_params();
		}

		if(cSaveParam)
		{
			cSaveParam=0;
			Save_params();
		}

		if(cLoadParam)
		{
			cLoadParam=0;
			Load_params();
		}

		if(cCanReset)
		{
			cCanReset=0;

			for(i=0;i<0x80;i++)
			county[i]=1;
			for(i=0;i<2;i++)
			CanCycle[i]=
			CanRound[i]=
			cancount[i]=
			cancell[i]=0;
			for(i=0;i<8;i++)
			masca[i]=0;
}	}	}
	
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		
void Millisecond()
{
  static int CanPowse;
	
  static unsigned int
  count_blink=0, count_bright=0, count_mode, 
  blink_over, blink_alarm, power_lamp, work_diod, norm_diod;
  static int preTest;
  int TST;

#define CANPOWSE 10		//	10 msec
#define BLINK_TIME 250	//	.25 sec

  	if(!cReset)
	 IWDG->KR = 0xAAAA;//HAL_IWDG_Refresh(&hiwdg);
  
	if(!timGo) return;

	Jumpers.byt.byte_1 = ReadJumpers();
	Jumpers.bit.bit0 = 
	Buttons.bit.bit0 = TestJumper();
  
	if(++CanPowse >= CANPOWSE)
	{
		CanPowse = 0;	CanGO = 1;
	}
	
	if(Alarms.bit.bit8)	//	Разряд батареи
	{
		if (Falling_asleep) Falling_asleep--;
	}
	else	Falling_asleep = 1000L * Sleep_time;
	
	TST = TestJumper() | cTestLamp;
	
	if(TST & !preTest)
	{
		count_blink = BLINK_TIME;
		count_mode = 0;
	}
	preTest = TST;

	if(++count_blink >= BLINK_TIME)
	{
		count_blink=0;
		count_mode++;
		blink_over  = (count_mode & 1)?1:0;
		blink_alarm = (count_mode & 7)?1:0;
	}

	power_lamp= 1;
	norm_diod = 1;
	work_diod =!blink_over;
	
	if(TST)
	{
		power_lamp	= blink_over;
		norm_diod	= blink_over;
		work_diod	= blink_over;
	}
	else
	if(Lightness)
	{
		power_lamp	= norm_diod	= 0;
		if(Lightness==2) power_lamp	= norm_diod	= 1;
		if(Lightness==3) power_lamp	= norm_diod	= blink_over;
		if(Lightness==4) power_lamp	= norm_diod	= blink_alarm;
		if(Lightness==5) power_lamp	= norm_diod	= !blink_alarm;
	}
	else
	if(Errors.all)
	{
		power_lamp	= blink_over;
		norm_diod	= blink_over;
	}	
	else
	if(Alarms.all)
	{
		power_lamp	= blink_alarm;
		norm_diod	= blink_alarm;
	}
	
	if(++count_bright == 10) //maximum_bright
	{	 count_bright  = 0 ;

		if(power_lamp)	Pvt1_ON;
		else			Pvt1_OFF;
	}
	
	if(count_bright == Brightness)
	if(!TST)	Pvt1_OFF;         //отключение лампочки
	
	if(work_diod)	LED_2_ON;
	else			LED_2_OFF;

	if(norm_diod)	LED_3_ON;
	else			LED_3_OFF;
	
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  HAL_RCC_MCOConfig(RCC_MCO, RCC_MCO1SOURCE_HSI, RCC_MCODIV_1);
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM8 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM8) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
