← 全部文章

OpenWrt ubus C API(3):写一个最小 server 和 client

在练习中成长

不用等读完,先测一下

命令行的 ubus call 很方便,但真正集成要写 C。 这篇从一个对象、一个方法开始,把 ubus_add_object 到 ubus_invoke 的最小闭环跑通。

先看闭环

server: ubus_connect → ubus_add_uloop → ubus_add_object → uloop_run
client: ubus_connect → ubus_lookup_id → ubus_invoke → callback
对象:   name + methods[] + policy
载荷:   blob_buf / blobmsg

三件事分开看:

  • 连接:ubus_connect(socket) 连到 ubusd;
  • 对象:server 把对象和方法注册到总线;
  • 调用:client 按对象名查 id,再按方法名发 blobmsg。

最小 server

这个例子注册 demo 对象,方法 hello 接收 {"name":"openwrt"},回复 {"message":"hello, openwrt"}。

#include <stdio.h>
#include <string.h>
#include <libubox/blobmsg.h>
#include <libubox/blobmsg_json.h>
#include <libubus.h>

static struct ubus_context *ctx;
static struct blob_buf b;

enum { DEMO_NAME, __DEMO_MAX };
static const struct blobmsg_policy demo_policy[__DEMO_MAX] = {
    [DEMO_NAME] = { .name = "name", .type = BLOBMSG_TYPE_STRING },
};

static int demo_hello(struct ubus_context *ctx, struct ubus_object *obj,
                      struct ubus_request_data *req, const char *method,
                      struct blob_attr *msg)
{
    struct blob_attr *tb[__DEMO_MAX];
    const char *name = "world";
    char reply[128];

    blobmsg_parse(demo_policy, __DEMO_MAX, tb, blob_data(msg), blob_len(msg));
    if (tb[DEMO_NAME])
        name = blobmsg_get_string(tb[DEMO_NAME]);

    snprintf(reply, sizeof(reply), "hello, %s", name);
    blob_buf_init(&b, 0);
    blobmsg_add_string(&b, "message", reply);
    ubus_send_reply(ctx, req, b.head);
    return 0;
}

static const struct ubus_method demo_methods[] = {
    UBUS_METHOD("hello", demo_hello, demo_policy),
};
static struct ubus_object_type demo_type = UBUS_OBJECT_TYPE("demo", demo_methods);
static struct ubus_object demo_obj = {
    .name = "demo",
    .type = &demo_type,
    .methods = demo_methods,
    .n_methods = ARRAY_SIZE(demo_methods),
};

int main(int argc, char **argv)
{
    ctx = ubus_connect(argc > 1 ? argv[1] : NULL);
    if (!ctx) {
        fprintf(stderr, "connect failed\n");
        return 1;
    }
    ubus_add_uloop(ctx);
    if (ubus_add_object(ctx, &demo_obj)) {
        fprintf(stderr, "add object failed\n");
        ubus_free(ctx);
        return 1;
    }
    uloop_run();
    ubus_free(ctx);
    uloop_done();
    return 0;
}

几个关键点:

  • ubus_connect(NULL) 用默认 socket;传路径可连独立 ubusd,PC 调试很方便;
  • ubus_add_uloop(ctx) 把 ubus fd 挂到 uloop,否则收不到请求;
  • ubus_add_object 失败通常不是代码问题,而是 ACL/权限;
  • handler 返回 0 表示成功,其他值用 UBUS_STATUS_*,不要混用 errno;
  • blobmsg_parse 只按 policy 找字段,缺字段要自己给默认值。

最小 client

#include <stdio.h>
#include <stdlib.h>
#include <libubox/blobmsg.h>
#include <libubox/blobmsg_json.h>
#include <libubus.h>

static void reply_cb(struct ubus_request *req, int type, struct blob_attr *msg)
{
    char *s = blobmsg_format_json(msg, true);
    if (s) {
        puts(s);
        free(s);
    }
}

int main(int argc, char **argv)
{
    struct ubus_context *ctx = ubus_connect(argc > 1 ? argv[1] : NULL);
    uint32_t id;
    struct blob_buf b = {0};

    if (!ctx) return 1;
    if (ubus_lookup_id(ctx, "demo", &id)) return 2;

    blob_buf_init(&b, 0);
    blobmsg_add_string(&b, "name", argc > 2 ? argv[2] : "openwrt");

    int ret = ubus_invoke(ctx, id, "hello", b.head, reply_cb, NULL, 1000);
    blob_buf_free(&b);
    ubus_free(ctx);
    return ret;
}

ubus_invoke 的最后一个参数是超时毫秒数;它返回 UBUS_STATUS_*,不是 HTTP 状态码。同步调用适合 CLI/短请求,长时间操作要用 ubus_invoke_async 和 ubus_complete_deferred_request,官方 examples/client.c 里的 hello 就是异步 + fd 传递。

编译与运行

有 pkg-config 的环境:

cc demo-server.c -o demo-server $(pkg-config --cflags --libs libubus libubox libblobmsg-json)
cc demo-client.c -o demo-client $(pkg-config --cflags --libs libubus libubox libblobmsg-json)

没有 pkg-config 时,显式给头和库路径(按你的 SDK 调整):

cc demo-server.c -o demo-server \
  -I/usr/local/include -L/usr/local/lib \
  -lubus -lubox -lblobmsg_json

在 OpenWrt package 里,依赖写成 +libubus +libubox +libblobmsg-json,用 SDK 的 $(TARGET_CC) 交叉编译。

跑起来(独立 socket,避免碰系统总线):

sudo ubusd -s /tmp/ubus.sock
sudo ./demo-server /tmp/ubus.sock
sudo ubus -s /tmp/ubus.sock list -v
./demo-client /tmp/ubus.sock openwrt

本机实测输出:

'demo' @3227dc21
	"hello":{"name":"String"}
{"message":"hello, openwrt"}

@3227dc21 是对象 id,每次启动会变;list -v 里的 name: String 来自 policy,不是从代码里猜的。

ACL:最常见的“代码没错但跑不起来”

非 root 进程默认不能随便注册对象。典型现象:

Failed to add object: Invalid argument

先用 root 跑通,确认代码和 API 没问题,再配 ACL。生产环境不要长期用 root 跑业务进程;OpenWrt 的 ubus ACL 按用户/组限制对象和方法,需要同时放行 ubus_add_object 和目标方法。

边界

  • ubus 是瞬时 RPC,不持久化对象,也不提供事务;
  • policy 只做 name + type,不校验范围/默认值/跨字段;
  • 复杂数据用 blobmsg_open_table/blobmsg_open_array,别把 JSON 字符串再塞一层;
  • 需要配置/状态模型时看 UCI 或 AMX/TR-181,不要拿 ubus 当数据库。

验证状态(本站宗旨)

  • ✅ 源码:openwrt/ubus 414c60a 的 libubus.h、examples/server.c、examples/client.c;
  • ✅ 本机编译:上面的 server/client 用 cc -Wall -Wextra 编译通过;
  • ✅ 本机实跑:独立 ubusd + /tmp/ubus.sock,ubus list -v 与 demo-client 的 invoke 均返回预期结果;
  • ⚠️ 环境差异:未在物理 OpenWrt 设备上交叉编译;ACL 配置随固件/用户组变化;
  • ❓ 未覆盖:异步 fd 传递的完整代码、并发/超时/断线重连。

一句话

server 的重点是“对象 + policy + uloop”,client 的重点是“lookup + invoke + callback”;先把这条最小闭环跑通,再谈异步和 ACL。


源码:openwrt/ubus(414c60a) 系列:OpenWrt ubus 官方例子解读 · 上一篇:ubus 命令实战 · 下一篇:用 ustream 管 socket · 数据模型:blob、blobmsg 与 policy

本页练习

觉得有用?

我持续记录 AI Agent × 嵌入式 / 边缘 AI 的实践。订阅更新,或来邮件交流一个具体问题。

去留言板 →订阅 RSS赞助

评论 0

还没有评论,来抢沙发~

无需登录即可评论;昵称可选。