本帖最后由 yunqi 于 2025-7-18 18:03 编辑
[C] 纯文本查看 复制代码 // 消息类型定义
typedef enum {
MSG_SENSOR_DATA, // 传感器数据
MSG_BUTTON_EVENT, // 按钮事件
MSG_NETWORK_CMD // 网络命令
} MsgEventID;
// 统一消息头
typedef struct {
MsgEventID event_id; // 事件ID
uint32_t timestamp; // 时间戳
uint16_t src_task; // 发送方任务ID
} MsgHeader;
// 示例消息体1
typedef struct {
MsgHeader header; // 必须包含头
float temperature;
float humidity;
} SensorMsg;
// 示例消息体2
typedef struct {
MsgHeader header;
uint8_t button_id;
bool is_pressed;
} ButtonMsg;
// msg_manager.c
#define MAX_QUEUES 5
static osMessageQueueId_t msg_queues[MAX_QUEUES];
// 初始化所有消息队列
void MsgManager_Init(void) {
for (int i = 0; i < MAX_QUEUES; i++) {
msg_queues[i] = osMessageQueueNew(10, sizeof(void*), NULL);
}
}
// 发送消息(传递指针)
bool MsgManager_Send(MsgEventID id, void* msg, uint32_t timeout) {
uint32_t queue_idx = id % MAX_QUEUES; // 简单哈希分配
return osMessageQueuePut(msg_queues[queue_idx], &msg, 0, timeout) == osOK;
}
// 接收消息
bool MsgManager_Receive(osThreadId_t thread, void** msg, uint32_t timeout) {
uint32_t queue_idx = osThreadGetId() % MAX_QUEUES; // 每个线程监听固定队列
return osMessageQueueGet(msg_queues[queue_idx], msg, NULL, timeout) == osOK;
}
// mem_pool.c
#define POOL_SIZE 20
static osMemoryPoolId_t msg_pool;
void MemPool_Init(void) {
msg_pool = osMemoryPoolNew(POOL_SIZE, sizeof(SensorMsg), NULL); // 以最大消息体为准
}
void* MsgAlloc(size_t size) {
return osMemoryPoolAlloc(msg_pool, 0);
}
void MsgFree(void* msg) {
osMemoryPoolFree(msg_pool, msg);
}
[C] 纯文本查看 复制代码 // 发送方线程
void SensorThread(void *arg) {
SensorMsg* msg = MsgAlloc(sizeof(SensorMsg));
msg->header.event_id = MSG_SENSOR_DATA;
msg->temperature = 25.5f;
MsgManager_Send(MSG_SENSOR_DATA, msg, osWaitForever);
}
// 接收方线程
void ProcessThread(void *arg) {
void* received_msg;
while (1) {
if (MsgManager_Receive(osThreadGetId(), &received_msg, osWaitForever)) {
MsgHeader* header = (MsgHeader*)received_msg;
switch (header->event_id) {
case MSG_SENSOR_DATA: {
SensorMsg* sensor_msg = (SensorMsg*)received_msg;
printf("Temp: %.1f\n", sensor_msg->temperature);
break;
}
// 其他消息处理...
}
MsgFree(received_msg);
}
}
} |