Files
433_STM32/Core/Src/main.c

551 lines
16 KiB
C
Raw Normal View History

/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2024 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, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "rf433.h"
#include "rf433_config.h"
#include "rf433_hal.h"
/* 应用层模块头文件 */
#include "uart2_print.h"
#include "io_monitor.h"
#include "cmd_parser.h"
#include "relay_control.h"
/* 多通信接口统一指令处理系统模块 */
#include "multi_uart_router.h"
#include "cmd_router.h"
#include "debug_log.h"
/* W5500 Ethernet模块头文件 */
#if USE_W5500
#include "user_main.h"
#include "wiz_platform.h"
#include "wiz_interface.h"
#include "wizchip_conf.h"
#include "loopback.h"
#endif
extern void wiz_timer_handler(void);
#if (RF433_MODE == RF433_MODE_TX) || (RF433_MODE == RF433_MODE_BOTH)
#include "rf433_tx_app.h"
#endif
#if (RF433_MODE == RF433_MODE_RX) || (RF433_MODE == RF433_MODE_BOTH)
#include "rf433_rx_app.h"
#endif
/* 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 ---------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
static uint8_t uart2_rx_byte = 0;
static uint8_t uart3_rx_byte = 0;
/* === 433 模块的接收缓存 (UART1) === */
static uint8_t u1_rx_buffer[256];
static volatile uint16_t u1_rx_len = 0;
static volatile uint32_t u1_last_rx_time = 0;
/* === 485 设备的接收缓存 (UART3) === */
static uint8_t u3_rx_buffer[512];
static volatile uint16_t u3_rx_len = 0;
static volatile uint32_t u3_last_rx_time = 0;
2026-05-07 17:47:52 +08:00
static volatile uint32_t u3_ignore_until = 0;
/* === 协议处理全局变量 === */
static uint16_t g_hb_seq = 0; /* 心跳序列号 */
static uint32_t g_last_hb_tick = 0; /* 上次心跳时间 */
static uint8_t g_last_io_state = 0xFF; /* 上次记录的 IO 状态,用于变化检测 */
/* === W5500 外部变量声明 === */
#if USE_W5500
extern uint16_t local_port;
extern uint8_t ethernet_buf[];
#endif
/**
* @brief 433
* @return bool: true=(), false=
*/
bool RF433_UART_Is_Busy(void)
{
// 仅查询 UART1 的引擎状态,不关心模块 AUX
return MultiUART_IsBusy(PORT_433);
}
/**
* @brief RF433
* @param type: (0x10, 0x55, 0x48, 0xAA)
* @param payload:
* @param len:
*/
void RF433_SendPacket(uint8_t type, const uint8_t *payload, uint8_t len)
{
uint8_t frame[260];
uint16_t frame_idx = 0;
uint8_t checksum = 0;
frame[frame_idx++] = PROTO_START_BYTE; // AA
frame[frame_idx++] = type; // TYPE
frame[frame_idx++] = (uint8_t)(len + 1 + 1); // LEN (ID + Payload + SUM)
frame[frame_idx++] = MY_DEVICE_ID; // ID
if (len > 0 && payload != NULL) {
memcpy(&frame[frame_idx], payload, len);
frame_idx += len;
}
/* 计算校验和 (Sum8) */
for (uint16_t i = 0; i < frame_idx; i++) {
checksum += frame[i];
}
frame[frame_idx++] = checksum;
/* 通过 MultiUART 发送 */
MultiUART_Send(PORT_433, frame, frame_idx);
}
/**
* @brief 433 线 ()
* @return bool: true=(), false=
*/
bool RF433_Is_Air_Busy(void)
{
return (HAL_GPIO_ReadPin(AUX_GPIO_Port, AUX_Pin) == GPIO_PIN_RESET);
}
/**
* @brief 4 DI
* @return uint8_t: Bit0-3 DI1-4
*/
uint8_t IO_Get_Current_State(void)
{
uint8_t state = 0;
if (HAL_GPIO_ReadPin(MCU_DI1_GPIO_Port, MCU_DI1_Pin) == GPIO_PIN_SET) state |= (1 << 0);
if (HAL_GPIO_ReadPin(MCU_DI2_GPIO_Port, MCU_DI2_Pin) == GPIO_PIN_SET) state |= (1 << 1);
if (HAL_GPIO_ReadPin(MCU_DI3_GPIO_Port, MCU_DI3_Pin) == GPIO_PIN_SET) state |= (1 << 2);
if (HAL_GPIO_ReadPin(MCU_DI4_GPIO_Port, MCU_DI4_Pin) == GPIO_PIN_SET) state |= (1 << 3);
return state;
}
/* W5500 variables */
#if USE_W5500
#define SOCKET_ID 0
#define ETHERNET_BUF_MAX_SIZE 2048
static uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {0};
static uint16_t local_port = 8000;
#endif
/* 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 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* 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_USART1_UART_Init();
MX_SPI2_Init();
MX_USART2_UART_Init();
MX_USART3_UART_Init();
MX_TIM2_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_Base_Start_IT(&htim2);
/* 初始化应用层模块 */
UART2_Print_Init();
IO_Monitor_Init();
CmdParser_Init();
Relay_Init();
/* 初始化多通信接口统一指令处理系统 */
MultiUART_Init();
CmdRouter_Init();
DebugLog_Init();
/* ============================================================== */
/* 🚀 【核心修复】将全局日志门槛提高到 INFO 级别,屏蔽所有底层 DEBUG 噪音 */
DebugLog_SetLevel(LOG_LEVEL_INFO);
/* ============================================================== */
printf("\r\n[DEBUG] 1. 启动 TIM2 中断\r\n");
HAL_TIM_Base_Start_IT(&htim2);
/* 启动UART2接收中断 */
HAL_UART_Receive_IT(&huart2, &uart2_rx_byte, 1);
/* 启动UART3接收中断 - RS485接口 */
#if USE_RS485
HAL_UART_Receive_IT(&huart3, &uart3_rx_byte, 1);
#endif
/* 初始化RF433模块 - 使用默认配置 */
rf433_init(NULL);
/* 启动UART1接收 - 使用rf433_hal中的临时变量 */
HAL_UART_Receive_IT(&huart1, &rf433_uart_rx_tmp, 1);
#if USE_W5500
printf("[DEBUG] 2. 进入 wizchip_initialize()\r\n");
wizchip_initialize();
printf("[DEBUG] 3. wizchip_initialize() 成功返回!\r\n");
printf("[DEBUG] 4. 进入 network_init()\r\n");
network_init(ethernet_buf, &default_net_info);
printf("[DEBUG] 5. network_init() 成功返回!\r\n");
printf("wizchip UDP example started\r\n");
#endif
/* ======================================= */
/* 根据配置模式初始化TX/RX应用层 */
#if (RF433_MODE == RF433_MODE_TX) || (RF433_MODE == RF433_MODE_BOTH)
/* TX模式初始化 */
rf433_tx_app_init(NULL);
rf433_tx_app_start(RF433_DEFAULT_TX_COUNT, RF433_DEFAULT_TX_INTERVAL);
#endif
#if (RF433_MODE == RF433_MODE_RX) || (RF433_MODE == RF433_MODE_BOTH)
/* RX模式初始化 */
rf433_rx_app_init(NULL);
rf433_rx_app_start();
#endif
/* 打印启动信息 */
printf("\r\n========================================\r\n");
printf("E32-433TBH-SC Application Started\r\n");
printf("System Clock: %d MHz\r\n", SystemCoreClock / 1000000);
printf("========================================\r\n");
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
#if (RF433_MODE == RF433_MODE_TX) || (RF433_MODE == RF433_MODE_BOTH)
/* TX任务 */
rf433_tx_app_task();
#endif
#if (RF433_MODE == RF433_MODE_RX) || (RF433_MODE == RF433_MODE_BOTH)
/* RX任务 */
rf433_rx_app_task();
#endif
/* W5500 UDP回环任务 */
#if USE_W5500
loopback_udps(SOCKET_ID, ethernet_buf, local_port);
#endif
2026-05-07 17:47:52 +08:00
/* Infinite loop */
2026-05-07 17:47:52 +08:00
/* USER CODE BEGIN WHILE */
while (1)
{
/* === 1. 核心通信驱动引擎 (最高优先级) === */
2026-05-07 17:47:52 +08:00
UART2_Print_Task();
MultiUART_Task();
/* === 2. 无线接收透传 (433 -> 485/Debug) === */
#if (RF433_MODE == RF433_MODE_RX) || (RF433_MODE == RF433_MODE_BOTH)
// 如果 433 收到无线数据,直接透传输出,不进行解码
if (u1_rx_len > 0 && (HAL_GetTick() - u1_last_rx_time > 20))
{
__disable_irq();
2026-05-07 17:47:52 +08:00
uint16_t len = u1_rx_len;
u1_rx_len = 0;
2026-05-07 17:47:52 +08:00
__enable_irq();
MultiUART_Send(PORT_RS485, (uint8_t*)u1_rx_buffer, len);
MultiUART_Send(PORT_DEBUG, (uint8_t*)u1_rx_buffer, len);
}
#endif
2026-05-07 17:47:52 +08:00
/* === 3. 核心发送保护区 (TX 优先调度) === */
// 只有当我们单片机正在往 433 模块灌数时,才进行避让
// 只要单片机串口引擎一空闲,主循环就立刻开始处理后续采集任务
if (RF433_UART_Is_Busy()) {
continue;
}
/* === 4. 实时数据采集与上报 (仅在非发射状态运行) === */
// (A) 485 来源数据处理 (Type 0x48)
#if USE_RS485
if (u3_rx_len > 0 && (HAL_GetTick() - u3_last_rx_time > 20))
{
2026-05-07 17:47:52 +08:00
static uint8_t temp_buf3[512];
__disable_irq();
uint16_t len = u3_rx_len;
memcpy(temp_buf3, (uint8_t*)u3_rx_buffer, len);
u3_rx_len = 0;
__enable_irq();
RF433_SendPacket(PROTO_TYPE_485, temp_buf3, len);
}
#endif
2026-05-07 17:47:52 +08:00
// (B) I/O 状态监控与变化上报 (Type 0x10)
#if USE_IO_MONITOR
IO_Monitor_Task(); // 执行去抖扫描
uint8_t current_io = IO_Monitor_GetAllStates();
if (current_io != g_last_io_state) {
if (g_last_io_state == 0xFF) {
g_last_io_state = current_io;
} else {
g_last_io_state = current_io;
RF433_SendPacket(PROTO_TYPE_IO, &current_io, 1);
}
}
#endif
// (C) 30秒系统心跳包 (Type 0xAA)
#if USE_IO_MONITOR
if (HAL_GetTick() - g_last_hb_tick >= 30000) {
g_last_hb_tick = HAL_GetTick();
uint8_t hb_payload[3];
hb_payload[0] = IO_Monitor_GetAllStates();
hb_payload[1] = (uint8_t)(g_hb_seq >> 8);
hb_payload[2] = (uint8_t)(g_hb_seq & 0xFF);
g_hb_seq++;
RF433_SendPacket(PROTO_TYPE_HB, hb_payload, 3);
}
#endif
// (D) W5500 以太网轮询处理 (Type 0x55)
#if USE_W5500
loopback_udps(SOCKET_ID, ethernet_buf, local_port);
#endif
/* USER CODE END WHILE */
}
2026-05-08 16:14:00 +08:00
}
/* 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_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
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_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
/**
* @brief UART接收完成中断回调函数
* @note UART1(RF433)UART2()UART3(RS485)
* @param huart: UART句柄指针
* @retval
*/
/* USER CODE BEGIN 4 */
/* USER CODE BEGIN 4 */
/* USER CODE BEGIN 4 */
/* USER CODE BEGIN 4 */
2026-05-07 17:47:52 +08:00
/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart->Instance == USART1) {
if (u1_rx_len < sizeof(u1_rx_buffer)) u1_rx_buffer[u1_rx_len++] = rf433_uart_rx_tmp;
u1_last_rx_time = HAL_GetTick();
HAL_UART_Receive_IT(&huart1, &rf433_uart_rx_tmp, 1);
}
else if (huart->Instance == USART3) {
2026-05-07 17:47:52 +08:00
/* 🚀 核心生效区:只有当单片机没有在发送数据时(度过屏蔽期),才允许接收 */
if (HAL_GetTick() >= u3_ignore_until) {
if (u3_rx_len < sizeof(u3_rx_buffer)) u3_rx_buffer[u3_rx_len++] = uart3_rx_byte;
u3_last_rx_time = HAL_GetTick();
}
HAL_UART_Receive_IT(&huart3, &uart3_rx_byte, 1);
}
else if (huart->Instance == USART2) {
HAL_UART_Receive_IT(&huart2, &uart2_rx_byte, 1);
}
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
/* 彻底清除所有硬件锁死标志 */
__HAL_UART_CLEAR_OREFLAG(huart);
__HAL_UART_CLEAR_NEFLAG(huart);
__HAL_UART_CLEAR_FEFLAG(huart);
if (huart->Instance == USART1) HAL_UART_Receive_IT(&huart1, &rf433_uart_rx_tmp, 1);
else if (huart->Instance == USART3) HAL_UART_Receive_IT(&huart3, &uart3_rx_byte, 1);
else if (huart->Instance == USART2) HAL_UART_Receive_IT(&huart2, &uart2_rx_byte, 1);
}
/* USER CODE END 4 */
/* 后面原有的 HAL_UART_TxCpltCallback 保留不动... */
/**
* @brief UART发送完成中断回调函数
* @note UART1/UART2/UART3发送完成
* @param huart: UART句柄指针
* @retval
*/
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart->Instance == USART1)
{
/* 调用多UART路由器的UART1发送完成回调 */
MultiUART_TxCpltCallback(PORT_433);
}
else if (huart->Instance == USART2)
{
/* 调用UART2打印模块的发送完成回调 */
UART2_Print_TxCpltCallback();
}
else if (huart->Instance == USART3)
{
/* 调用多UART路由器的UART3发送完成回调 */
MultiUART_TxCpltCallback(PORT_RS485);
}
}
/* 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: usb_printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */