132 lines
2.8 KiB
C
132 lines
2.8 KiB
C
/*
|
||
* event_handler.c
|
||
*
|
||
* Created on: 2026-03-04
|
||
* Author: RT-Thread
|
||
*
|
||
* 功能: 事件处理器模块实现
|
||
* 依赖: RT-Thread Nano, osal, event_queue
|
||
* 跨平台适配: 基于RT-Thread Nano,使用标准API
|
||
*/
|
||
|
||
#include <rtthread.h>
|
||
#include "osal.h"
|
||
#include "event_queue.h"
|
||
#include "event_handler.h"
|
||
|
||
/* 事件处理器数组 */
|
||
static event_handler_t g_event_handlers[EVENT_TYPE_MAX];
|
||
|
||
/**
|
||
* @brief 初始化事件处理器
|
||
* @return 0 成功,非0 失败
|
||
*/
|
||
int event_handler_init(void)
|
||
{
|
||
/* 初始化事件处理器数组 */
|
||
for (int i = 0; i < EVENT_TYPE_MAX; i++)
|
||
{
|
||
g_event_handlers[i].handler = NULL;
|
||
g_event_handlers[i].user_data = NULL;
|
||
}
|
||
|
||
osal_log_i("Event handler initialized");
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* @brief 注册事件处理器
|
||
* @param type 事件类型
|
||
* @param handler 事件处理函数
|
||
* @param user_data 用户数据
|
||
* @return 0 成功,非0 失败
|
||
*/
|
||
int event_handler_register(event_type_t type, event_handler_func_t handler, void *user_data)
|
||
{
|
||
if (type < 0 || type >= EVENT_TYPE_MAX)
|
||
{
|
||
return -1;
|
||
}
|
||
|
||
if (handler == NULL)
|
||
{
|
||
return -1;
|
||
}
|
||
|
||
g_event_handlers[type].handler = handler;
|
||
g_event_handlers[type].user_data = user_data;
|
||
|
||
osal_log_i("Event handler registered for type %d", type);
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* @brief 注销事件处理器
|
||
* @param type 事件类型
|
||
* @return 0 成功,非0 失败
|
||
*/
|
||
int event_handler_unregister(event_type_t type)
|
||
{
|
||
if (type < 0 || type >= EVENT_TYPE_MAX)
|
||
{
|
||
return -1;
|
||
}
|
||
|
||
g_event_handlers[type].handler = NULL;
|
||
g_event_handlers[type].user_data = NULL;
|
||
|
||
osal_log_i("Event handler unregistered for type %d", type);
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* @brief 处理事件
|
||
* @param event 事件指针
|
||
* @return 0 成功,非0 失败
|
||
*/
|
||
int event_handler_process(event_t *event)
|
||
{
|
||
if (event == NULL)
|
||
{
|
||
return -1;
|
||
}
|
||
|
||
event_type_t type = event->type;
|
||
if (type < 0 || type >= EVENT_TYPE_MAX)
|
||
{
|
||
osal_log_w("Invalid event type: %d", type);
|
||
return -1;
|
||
}
|
||
|
||
event_handler_t *handler = &g_event_handlers[type];
|
||
if (handler->handler != NULL)
|
||
{
|
||
osal_log_d("Processing event type %d", type);
|
||
return handler->handler(event, handler->user_data);
|
||
}
|
||
else
|
||
{
|
||
osal_log_d("No handler registered for event type %d", type);
|
||
return -1;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @brief 事件分发线程
|
||
* @param parameter 线程参数
|
||
*/
|
||
void event_dispatch_thread(void *parameter)
|
||
{
|
||
event_t event;
|
||
|
||
while (1)
|
||
{
|
||
/* 从事件队列中获取事件 */
|
||
if (event_queue_pop(&event, OSAL_WAIT_FOREVER) == 0)
|
||
{
|
||
/* 处理事件 */
|
||
event_handler_process(&event);
|
||
}
|
||
}
|
||
}
|