Skip to content

07 · C 协议插件开发手册 ​

面对包含变长嵌套、动态多级中继路由、跨包粘包拆包或多设备型号差异的嵌入式私有协议,直接在 protocols/ 目录下编写 C 语言协议插件是最直接、最准确的方式——你可以直接把下位机固件里的帧头宏、位域解析和 CRC 函数搬过来使用,无需学习复杂的自定义配置语法。


1. 目录结构与命名规范 ​

在 CommDesk.exe 同级的 protocols/ 目录下,每种协议建立一个独立的 snake_case(小写字母加下划线)子文件夹:

text
protocols/
└── my_bus/
    ├── my_bus.c          # 主入口文件(必须包含 main() 函数,文件名 my_bus 即为界面显示的协议名)
    ├── my_bus.h          # 可选:帧结构、CRC 等头文件(协议列表中自动隐藏,编辑协议时在左侧文件树可见)
    └── my_bus_payload.h  # 可选:业务子表解析辅助文件
  • 在左侧活动栏打开 协议:首次展开某个协议时,软件会自动编译并执行一次 main() 获取该协议注册的产品型号列表。
  • 右键协议名称点击 编辑协议 可在独立编辑器中修改所有 .c / .h 文件(支持 F12 跨文件跳转);保存修改后重新展开或点击产品右侧 ▶ 即可生效。

2. 协议插件的三个标准函数(<commdesk_protocol.h>) ​

你的协议入口 .c 文件只需 #include <commdesk_protocol.h>,按需实现以下三个固定名字的函数(除 main 必填外,其余两个均可按需选填):

固定函数签名何时被调用?作用说明
int main(void)展开协议或启动解析时初始化调用调用 register_product(id, name) 注册 1–32 个设备型号,注册完直接 return 0;
int protocol_on_parse(const unsigned char *buf, int count)粘贴 HEX 点击解析、在监视器右键某行选“按协议解析”、点击左侧解析历史记录时调用校验并解析单帧字节(1..1024 B),调用 protocol_field(...) 输出字段,成功返回 1、失败返回 0
void protocol_on_receive(const unsigned char *buf, int count)点击产品右侧 ▶ 激活实时接收后,每收到一块串口 RX 原始字节自动调用使用 static 缓存自行完成跨包半帧拼接、连续多帧切分与噪声剔除

关键隔离特性:手动粘贴解析与右键单帧解析每次都在独立进程中单独运行 protocol_on_parse,绝不会打乱或污染正在后台运行的 protocol_on_receive 实时接收静态缓存!


3. 输出字段与历史帧 API 一览 ​

c
/* 1. 在 main() 中注册产品型号(成功返回 1,失败返回 0) */
int register_product(const char *id, const char *name);

/* 2. 获取用户在界面当前选中的产品 ID(只读字符串,切勿修改) */
const char *protocol_product_id(void);

/* 3. 向右侧解析结果表添加一行(依次为:字段名、备注列、鼠标悬停提示、printf 格式串及参数) */
void protocol_field(const char *name, const char *note, const char *tooltip, const char *format, ...);

/* 4. 快捷将一段原始字节格式化为大写 HEX 字符串行输出 */
void protocol_hex_field(const char *name, const char *note, const char *tooltip, const unsigned char *buf, int count);

/* 5. 可选:在字段表格上方展示去除前后噪声后的干净单帧字节(1..1024 B) */
int protocol_show_bytes(const unsigned char *buf, int count);

/* 6. 记录解析失败原因并固定返回 0(可直接写 return protocol_error("CRC 错误");) */
int protocol_error(const char *format, ...);

/* 7. 清空当前输出区的字段与展示字节(进入 protocol_on_parse 时会自动清空;在 protocol_on_receive 中如需替换显示可手动调用) */
void protocol_clear(void);

/* 8. 实时接收高级接口:读取当前 RX 块的时间戳与原始序号上下文,并向左侧发布一条拼好的完整历史帧 */
const ProtocolPacket *protocol_receive_context(void);
int protocol_show_frame(const ProtocolPacket *frame, const char *title);

4. 从零编写一个完整 C 协议插件模板 ​

下面是一份可直接放入 protocols/demo_proto/demo_proto.c 运行的标准协议模板(假设帧格式为:AA 55 | 长度(1B, 含头尾总长) | 命令码(1B) | 载荷... | 累加和(1B)):

c
#include <commdesk_protocol.h>
#include <string.h>

static unsigned char calc_sum(const unsigned char *data, int len)
{
    unsigned int sum = 0;
    for (int i = 0; i < len; i++) sum += data[i];
    return (unsigned char)(sum & 0xFF);
}

/* 一、注册支持的产品型号 */
int main(void)
{
    if (!register_product("std", "标准传感器节点")) return 1;
    if (!register_product("pro", "高精度扩展节点")) return 1;
    return 0;
}

/* 二、单帧解析入口(右键报文、粘贴 HEX、点击历史记录均走这里) */
int protocol_on_parse(const unsigned char *buf, int count)
{
    if (count < 5) return protocol_error("帧长不足 5 字节(实际 %d 字节)", count);
    if (buf[0] != 0xAA || buf[1] != 0x55) return protocol_error("帧头不是 AA 55");

    int declared_len = buf[2];
    if (declared_len != count) {
        return protocol_error("长度字段(%d)与实际输入字节数(%d)不一致", declared_len, count);
    }
    unsigned char expected = calc_sum(buf, count - 1);
    if (buf[count - 1] != expected) {
        return protocol_error("校验和错误:报文 0x%02X,应为 0x%02X", buf[count - 1], expected);
    }

    protocol_show_bytes(buf, count);
    protocol_field("产品配置", "", "当前选中的产品型号 ID", "%s", protocol_product_id());
    protocol_field("命令码", "CMD", "业务指令字", "0x%02X", buf[3]);

    int payload_len = count - 5;
    if (buf[3] == 0x01 && payload_len >= 2) {
        int raw_temp = (buf[4] << 8) | buf[5];
        protocol_field("温度", "0.1°C", "大端有符号 16 位温度值", "%.1f °C", raw_temp / 10.0);
        if (strcmp(protocol_product_id(), "pro") == 0 && payload_len >= 4) {
            int humidity = (buf[6] << 8) | buf[7];
            protocol_field("湿度", "0.1%RH", "仅扩展节点包含湿度字段", "%.1f %%RH", humidity / 10.0);
        }
    } else if (payload_len > 0) {
        protocol_hex_field("业务载荷", "HEX", "未细分命令的原始载荷", buf + 4, payload_len);
    }
    protocol_field("校验和", "通过", "单字节累加和校验通过", "0x%02X", buf[count - 1]);
    return 1;
}

/* 三、实时流式接收拼帧入口(点击产品右侧 ▶ 激活后长驻运行) */
static unsigned char g_rx_cache[4096];
static int g_rx_len = 0;
static uint64_t g_first_seq = 0;

void protocol_on_receive(const unsigned char *buf, int count)
{
    const ProtocolPacket *ctx = protocol_receive_context();
    if (count <= 0) return;

    if (g_rx_len == 0 && ctx) g_first_seq = ctx->first_sequence;
    if (g_rx_len + count > (int)sizeof(g_rx_cache)) {
        g_rx_len = 0; /* 防止异常噪声塞满缓冲区 */
    }
    if (count <= (int)sizeof(g_rx_cache) - g_rx_len) {
        memcpy(g_rx_cache + g_rx_len, buf, (size_t)count);
        g_rx_len += count;
    }

    int offset = 0;
    while (g_rx_len - offset >= 5) {
        /* 1. 查找帧头 AA 55 */
        if (g_rx_cache[offset] != 0xAA || g_rx_cache[offset + 1] != 0x55) {
            offset++;
            continue;
        }
        int frame_len = g_rx_cache[offset + 2];
        if (frame_len < 5 || frame_len > 256) {
            offset++; /* 非法长度,跳过伪帧头继续向后搜寻 */
            continue;
        }
        if (g_rx_len - offset < frame_len) {
            break; /* 半帧尚未收齐,保留剩余字节等待下一个串口接收块! */
        }
        /* 2. 校验完整单帧并发布到左侧历史记录 + 右侧主动输出区 */
        const unsigned char *frame = g_rx_cache + offset;
        if (calc_sum(frame, frame_len - 1) == frame[frame_len - 1]) {
            if (ctx) {
                ProtocolPacket pkt = {
                    .data = frame,
                    .length = frame_len,
                    .direction = PROTOCOL_RX,
                    .first_sequence = g_first_seq,
                    .last_sequence = ctx->last_sequence,
                    .timestamp = ctx->timestamp,
                };
                protocol_show_frame(&pkt, "传感器上报帧");
            }
            protocol_on_parse(frame, frame_len);
            offset += frame_len;
            if (ctx) g_first_seq = ctx->last_sequence;
        } else {
            offset++; /* 校验未过,仅滑过 1 字节防止漏掉紧随其后的真帧头 */
        }
    }

    if (offset > 0) {
        memmove(g_rx_cache, g_rx_cache + offset, (size_t)(g_rx_len - offset));
        g_rx_len -= offset;
    }
}

5. 编写协议插件的实用经验与运行上限 ​

  1. 避免未对齐指针强转:从字节缓冲区读取 uint16_t、uint32_t、float 时,推荐按字节移位拼装或 memcpy 到局部变量,不要直接写 *(float *)(buf + 3),既避免字节序混淆又防止未对齐访问问题。
  2. 严格检查长度边界:任何依据报文内部“通道数 N / 声明长度 L”循环读取的代码,务必先检查 offset + needed <= count,截断帧直接 return protocol_error(...)。
  3. 运行上限说明:单个协议最多注册 32 个产品,单次手动/历史解析帧长 1..1024 字节,单次最多输出 512 个字段(总文本上限 64 KiB)。更复杂的工业级多级中继实例可直接参考自带的 protocols/unibus/ 目录源码。

保持好奇,不断进步