/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    can.c
  * @brief   This file provides code for the configuration
  *          of the CAN instances.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "can.h"

/* USER CODE BEGIN 0 */
#include "message.h"
#include "gpio.h"
void CAN_filterConfig(void);

CAN_TxHeaderTypeDef TxHeader;
CAN_RxHeaderTypeDef RxHeader;

CAN_FilterTypeDef sFilterConfig;

CAN_TxHeaderTypeDef msgHeaderSend;
uint8_t msgDataSend[8];
uint32_t mailBoxNum = 0;

uint8_t TxData[8];
uint8_t RxData[8];
uint32_t TxMailbox;

uint32_t  TX_box_ID = 0;
uint32_t  RX_box_ID = 0;
uint32_t  BC_box_ID = 0;

/* USER CODE END 0 */

CAN_HandleTypeDef hcan;

/* CAN init function */
void MX_CAN_Init(void)
{

  /* USER CODE BEGIN CAN_Init 0 */

  /* USER CODE END CAN_Init 0 */

  /* USER CODE BEGIN CAN_Init 1 */

  /* USER CODE END CAN_Init 1 */
  hcan.Instance = CAN1;
  hcan.Init.Prescaler = 16;
  hcan.Init.Mode = CAN_MODE_NORMAL;
  hcan.Init.SyncJumpWidth = CAN_SJW_1TQ;
  hcan.Init.TimeSeg1 = CAN_BS1_13TQ;
  hcan.Init.TimeSeg2 = CAN_BS2_2TQ;
  hcan.Init.TimeTriggeredMode = DISABLE;
  hcan.Init.AutoBusOff = DISABLE;
  hcan.Init.AutoWakeUp = DISABLE;
  hcan.Init.AutoRetransmission = DISABLE;
  hcan.Init.ReceiveFifoLocked = DISABLE;
  hcan.Init.TransmitFifoPriority = DISABLE;
  if (HAL_CAN_Init(&hcan) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN CAN_Init 2 */
  
	CAN_filterConfig();
  
//	CAN start
	if (HAL_CAN_Start(&hcan) != HAL_OK)
	{
		Error_Handler();
	}
  
//	CAN notifications (interrupts)
	if (HAL_CAN_ActivateNotification(&hcan, CAN_IT_RX_FIFO0_MSG_PENDING | CAN_IT_TX_MAILBOX_EMPTY) != HAL_OK)
	{
		Error_Handler();
	}

  /* USER CODE END CAN_Init 2 */

}

void HAL_CAN_MspInit(CAN_HandleTypeDef* canHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(canHandle->Instance==CAN1)
  {
  /* USER CODE BEGIN CAN1_MspInit 0 */

  /* USER CODE END CAN1_MspInit 0 */
    /* CAN1 clock enable */
    __HAL_RCC_CAN1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**CAN GPIO Configuration
    PA11     ------> CAN_RX
    PA12     ------> CAN_TX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_11;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_12;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* CAN1 interrupt Init */
    HAL_NVIC_SetPriority(USB_HP_CAN1_TX_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USB_HP_CAN1_TX_IRQn);
    HAL_NVIC_SetPriority(USB_LP_CAN1_RX0_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
  /* USER CODE BEGIN CAN1_MspInit 1 */

  /* USER CODE END CAN1_MspInit 1 */
  }
}

void HAL_CAN_MspDeInit(CAN_HandleTypeDef* canHandle)
{

  if(canHandle->Instance==CAN1)
  {
  /* USER CODE BEGIN CAN1_MspDeInit 0 */

  /* USER CODE END CAN1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_CAN1_CLK_DISABLE();

    /**CAN GPIO Configuration
    PA11     ------> CAN_RX
    PA12     ------> CAN_TX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_11|GPIO_PIN_12);

    /* CAN1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USB_HP_CAN1_TX_IRQn);
    HAL_NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
  /* USER CODE BEGIN CAN1_MspDeInit 1 */

  /* USER CODE END CAN1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */
void CAN_filterConfig(void)
{
	sFilterConfig.FilterBank = 0;
	sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK;
	sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;
	sFilterConfig.FilterIdHigh = 0x0000;
	sFilterConfig.FilterIdLow = 0x0000;
	sFilterConfig.FilterMaskIdHigh = 0x0000;
	sFilterConfig.FilterMaskIdLow = 0x0000;
	sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0;
	sFilterConfig.FilterActivation = ENABLE;
	sFilterConfig.SlaveStartFilterBank = 14;
	
	if (HAL_CAN_ConfigFilter(&hcan, &sFilterConfig) != HAL_OK)
	{
		Error_Handler();
}	}

void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan_i)
{
  CAN_RxHeaderTypeDef msgHeader;
  uint8_t msgData[8];

  unsigned int adr,qua;
  unsigned short Data[4];
	
  if (HAL_CAN_GetRxMessage(hcan_i, CAN_RX_FIFO0, &msgHeader, msgData) != HAL_OK)
  {
    /* Reception Error */
    Error_Handler();
  }

	if((msgHeader.ExtId & 0xFF00000)  != RX_box_ID) 
	if((msgHeader.ExtId & 0xFF00000)  != BC_box_ID)	return;

	adr	= msgHeader.ExtId & 0xFFFF;
	qua = msgHeader.DLC/2;

	Data[0] = msgData[0]; Data[0] = (Data[0]<<8) |  msgData[1];
	Data[1] = msgData[2]; Data[1] = (Data[1]<<8) |  msgData[3];
	Data[2] = msgData[4]; Data[2] = (Data[2]<<8) |  msgData[5];
	Data[3] = msgData[6]; Data[3] = (Data[3]<<8) |  msgData[7];
	
	if(qua  ) if(adr < Modbus_LEN) modbus[adr] = Data[0]; adr++;
	if(qua>1) if(adr < Modbus_LEN) modbus[adr] = Data[1]; adr++;
	if(qua>2) if(adr < Modbus_LEN) modbus[adr] = Data[2]; adr++;
	if(qua>3) if(adr < Modbus_LEN) modbus[adr] = Data[3];
	
	LED_1_TGL;
}


int CAN_send(uint16_t data[], int Addr, int Qua)
{	
  uint16_t wait = 1000;
  static uint8_t att=0;
  uint8_t i;

	while(wait-- && (HAL_CAN_GetTxMailboxesFreeLevel(&hcan) == 0));
	
	if (HAL_CAN_GetTxMailboxesFreeLevel(&hcan) != 0)
	{
		msgHeaderSend.IDE = CAN_ID_EXT;
		msgHeaderSend.ExtId	= TX_box_ID | (Addr & 0xFFFF);
		msgHeaderSend.DLC = Qua*2;
		
		msgDataSend[0] = (data[Addr  ]>>8) & 0x00ff;
		msgDataSend[1] = (data[Addr  ]   ) & 0x00ff;
		msgDataSend[2] = (data[Addr+1]>>8) & 0x00ff;
		msgDataSend[3] = (data[Addr+1]   ) & 0x00ff;
		msgDataSend[4] = (data[Addr+2]>>8) & 0x00ff;
		msgDataSend[5] = (data[Addr+2]   ) & 0x00ff;
		msgDataSend[6] = (data[Addr+3]>>8) & 0x00ff;
		msgDataSend[7] = (data[Addr+3]   ) & 0x00ff;
   
		HAL_CAN_AddTxMessage(&hcan, &msgHeaderSend, msgDataSend, &mailBoxNum);
		
		att=0;
		
		return 1;
	}
	else 
	{	
		if(att>=3)
		{
			MX_CAN_Init();	
		
			LED_0_OFF;
			LED_1_OFF;
			for(i=0;i<8;i++)
			{
				LED_1_TGL;	HAL_Delay(30);
				LED_1_TGL;	HAL_Delay(30);
				LED_0_TGL;	HAL_Delay(30);
				LED_0_TGL;	HAL_Delay(30);
		}	}
		else
		{
			att++;

			HAL_CAN_Stop(&hcan);
			HAL_CAN_Start(&hcan);

			LED_0_OFF;
			LED_1_OFF;
			for(i=0;i<10;i++)
			{
				LED_0_TGL;
				LED_1_TGL;	HAL_Delay(30);
		}	}

		return 0;
}	}

void Setup_CAN_addr(uint8_t mode)
{
  	BC_box_ID = 0x9F<<20;
	RX_box_ID = (0x80+mode)<<20;
	TX_box_ID = RX_box_ID | (1L<<28);
}
// Успешная отправка - моргание диодом
void HAL_CAN_TxMailbox0CompleteCallback(CAN_HandleTypeDef *hcan)
{
		LED_0_TGL;
}
void HAL_CAN_TxMailbox1CompleteCallback(CAN_HandleTypeDef *hcan)
{
		LED_0_TGL;
}
void HAL_CAN_TxMailbox2CompleteCallback(CAN_HandleTypeDef *hcan)
{
		LED_0_TGL;
}
// Ошибки: выключение диода
void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan)
{
		LED_0_OFF;
}
/* USER CODE END 1 */
