aiPbMgrSendAck是一个基于 Protobuf 通信框架的确认发送函数,用于在 AI 服务与客户端之间发送响应确认消息。
1. 函数功能
向客户端发送 ACK(Acknowledgment)确认消息,通常用于:
- 响应命令接收成功
- 返回处理状态
- 确认数据接收完成
- 错误响应
函数
cpp
/**
* @brief 发送 Protobuf 确认消息
* @param ctx AI Protobuf 管理器上下文
* @param cmd 原始命令类型(用于响应关联)
* @param status 状态码(成功/错误码)
* @param msg 可选的状态消息字符串
* @return bool 发送成功返回 true,失败返回 false
*/
bool aiPbMgrSendAck(aiPbMgrCtx_t *ctx,
EnumCmd cmd,
PbAckStatus status,
const char *msg);
典型实现代码
c
#include "ai_pb_mgr.h"
#include "pb_encode.h"
bool aiPbMgrSendAck(aiPbMgrCtx_t *ctx, EnumCmd cmd, PbAckStatus status, const char *msg) {
// 1. 检查参数有效性
if (!ctx || !ctx->transport_send) {
PB_LOG_ERROR("Invalid context or transport");
return false;
}
// 2. 创建 ACK 消息
PbAck ack_msg = PbAck_init_zero;
ack_msg.cmd = cmd; // 关联原始命令
ack_msg.status = status; // 状态码
ack_msg.timestamp = pb_get_timestamp(); // 时间戳
// 3. 可选的状态消息
if (msg && strlen(msg) > 0) {
strncpy(ack_msg.message, msg, sizeof(ack_msg.message) - 1);
ack_msg.message[sizeof(ack_msg.message) - 1] = '\0';
ack_msg.has_message = true;
} else {
ack_msg.has_message = false;
}
// 4. Protobuf 编码
uint8_t tx_buffer[PB_ACK_MAX_SIZE];
pb_ostream_t stream = pb_ostream_from_buffer(tx_buffer, sizeof(tx_buffer));
if (!pb_encode(&stream, PbAck_fields, &ack_msg)) {
PB_LOG_ERROR("Failed to encode ACK message: %s", PB_GET_ERROR(&stream));
return false;
}
// 5. 通过传输层发送
size_t sent = ctx->transport_send(ctx->transport_handle,
tx_buffer,
stream.bytes_written);
if (sent != stream.bytes_written) {
PB_LOG_ERROR("Failed to send ACK, sent %zu/%zu bytes",
sent, stream.bytes_written);
return false;
}
PB_LOG_DEBUG("ACK sent for cmd %d, status %d", cmd, status);
return true;
}
对应的 Protobuf 消息定义
c
// ack.proto
syntax = "proto3";
enum PbAckStatus {
PB_ACK_OK = 0; // 成功
PB_ACK_ERROR = 1; // 通用错误
PB_ACK_BUSY = 2; // 设备忙
PB_ACK_TIMEOUT = 3; // 超时
PB_ACK_INVALID_CMD = 4; // 无效命令
PB_ACK_NO_MEMORY = 5; // 内存不足
}
message PbAck {
EnumCmd cmd = 1; // 原始命令类型
PbAckStatus status = 2; // 状态码
uint64 timestamp = 3; // 时间戳(毫秒)
optional string message = 4; // 可选状态描述
}
aiPbMgrSendAck是 AI Protobuf 通信框架中的关键响应函数,用于:
确认机制:确保命令可靠传输;
状态反馈:实时返回处理状态;
错误处理:标准化错误响应;
异步支持:分离命令接收与执行。
命令处理完成后发送成功确认;
参数错误时发送错误响应;
启动长时间操作前发送接收确认。