/* 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 "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 */

/* 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;
int CanGO=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 res, pls;

	if((num<0)||(num>=0x80)) return 0;
	res = Maska[0][num/0x10];	if(i)
	res|= Maska[1][num/0x10];
	res &= (1<<(num&0x0F));
	pls = (espero[num]>CanRestart[i]/3);
	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 */

  int i,j,n,mask,qua;
  static int cancount[2]={1,2},cancell[2]={0,0},candid[2]={0,0};
  static unsigned int masca[8];
		
  /* USER CODE END 1 */

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

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

  /* USER CODE BEGIN 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();
  /* USER CODE BEGIN 2 */
    
  	Mode = ReadJumpers();
	Setup_CAN_addr(Mode);
	LastMode = Mode;
	Load_params();	

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
	while (1)
	{
		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]--;
		}
			
		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];
						continue;
				}	}

				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;
			}	}
				
				
			if(espero[cancell[i]]>CanRestart[i])
			county[cancell[i]]=1;

			if(modbus[cancell[i]] != archiv[cancell[i]])

			county[cancell[i]] = (cancell[i]==keys) ? CanRepeat:1;

			if (county[cancell[i]])
			{
				for(j=  3; j>0 && !Isit(cancell[i]+j,i); j--);
				for(n=j-3; n<0 && !Isit(cancell[i]+n,i); 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])
					cancount[!i]=1;	// ????? ?? ?????
			}
			else	cancell[i]++; 
		}	
	  
		ReadEnteres();	
		
//		ReadSeanus();
			
		if(Alarms.all)	Pvt4_OFF;	//	сигнал "Система ВЭП в норме"
		else			Pvt4_ON;
			
		if(Errors.all)	Pvt3_ON;	//	сигнал "Авария системы ВЭП"
		else			Pvt3_OFF;
			
		if(Inputs.bit.bit9)	Pvt2_OFF;		//	?????? ? ???? 24 ?
		else				Pvt2_ON;		//	?????? "?????????? ????? 24?"
		
		if (Falling_asleep)	Pvt2_ON;		//	Пока не спим, это замкнуто
		else				Pvt2_OFF;		//	сигнал "Управление сетью 24В"
		

		if(cDefParam)
		{
			cDefParam=0;
			Default_params();
		}

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

		if(cLoadParam)
		{
			cLoadParam=0;
			Load_params();
}	}	}
	
    /* 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
  
//	ReadSeanus();
  
	Jumpers.byt.byte_1 = ReadJumpers();
	Jumpers.bit.bit0 = TestJumper();
	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;
	
	if(work_diod)	LED_2_ON;
	else			LED_2_OFF;

	if(norm_diod)	LED_3_ON;
	else			LED_3_OFF;
	
	TST = TestJumper() | cTestLamp;
	
	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(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 = 1;
	
	if(TST)
	{
		power_lamp= blink_over;
		norm_diod= blink_over;
		work_diod= !blink_over;
	}
	else
	{
		if(Alarms.all)
		{
			norm_diod= blink_alarm;
			power_lamp=blink_alarm;
		}
		if(Errors.all)
		{
			power_lamp= blink_over;
			norm_diod= blink_over;
	}	}	
  /* 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_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL10;
  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_1) != HAL_OK)
  {
    Error_Handler();
  }
  HAL_RCC_MCOConfig(RCC_MCO, RCC_MCO1SOURCE_SYSCLK, RCC_MCODIV_1);
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @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 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
