ubus通信中 发布订阅模式的举例测试代码
时间: 2024-02-25 09:52:37 浏览: 238
好的,以下是一个简单的发布订阅模式的ubus通信测试代码,你可以参考一下:
服务端代码:
```c
#include <libubox/uloop.h>
#include <libubus.h>
static struct ubus_context *ctx;
static void test_subscribe_handler(struct ubus_context *ctx,
struct ubus_object *obj,
struct ubus_request_data *req,
const char *method,
struct blob_attr *msg)
{
const char *data = blobmsg_get_string(msg, "data");
printf("Received data: %s\n", data);
}
static const struct ubus_method test_methods[] = {
{ .name = "subscribe", .handler = test_subscribe_handler },
};
static struct ubus_object_type test_object_type =
UBUS_OBJECT_TYPE("test", test_methods);
static struct ubus_object test_object = {
.name = "test",
.type = &test_object_type,
.methods = test_methods,
.n_methods = ARRAY_SIZE(test_methods),
};
static void test_notify_handler(struct ubus_context *ctx,
struct ubus_subscriber *sub,
uint32_t id,
struct blob_attr *msg)
{
const char *data = blobmsg_get_string(msg, "data");
printf("Received data: %s\n", data);
}
int main(int argc, char **argv)
{
ctx = ubus_connect(NULL);
if (!ctx) {
fprintf(stderr, "Failed to connect to ubus\n");
return -1;
}
ubus_add_uloop(ctx);
if (ubus_add_object(ctx, &test_object) != 0) {
fprintf(stderr, "Failed to add ubus object\n");
ubus_free(ctx);
return -1;
}
struct ubus_subscriber subscriber;
memset(&subscriber, 0, sizeof(subscriber));
subscriber.cb = test_notify_handler;
if (ubus_subscribe(ctx, &subscriber, "test.subscribe") != 0) {
fprintf(stderr, "Failed to subscribe\n");
ubus_free(ctx);
return -1;
}
uloop_run();
return 0;
}
```
客户端代码:
```c
#include <libubox/uloop.h>
#include <libubus.h>
static struct ubus_context *ctx;
static void test_notify_handler(struct ubus_context *ctx,
struct ubus_subscriber *sub,
uint32_t id,
struct blob_attr *msg)
{
const char *data = blobmsg_get_string(msg, "data");
printf("Received data: %s\n", data);
}
int main(int argc, char **argv)
{
ctx = ubus_connect(NULL);
if (!ctx) {
fprintf(stderr, "Failed to connect to ubus\n");
return -1;
}
ubus_add_uloop(ctx);
struct ubus_subscriber subscriber;
memset(&subscriber, 0, sizeof(subscriber));
subscriber.cb = test_notify_handler;
if (ubus_subscribe(ctx, &subscriber, "test.subscribe") != 0) {
fprintf(stderr, "Failed to subscribe\n");
ubus_free(ctx);
return -1;
}
struct blob_buf buf;
blob_buf_init(&buf, 0);
blobmsg_add_string(&buf, "data", "Hello, world!");
if (ubus_notify(ctx, "test.subscribe", buf.head, 0, NULL) != 0) {
fprintf(stderr, "Failed to send notification\n");
ubus_free(ctx);
return -1;
}
uloop_run();
return 0;
}
```
这个例子中,服务端会创建一个ubus对象并添加到ubus上下文中,同时会添加一个订阅处理函数和一个订阅者。当客户端发送一个通知时,服务端订阅处理函数会被调用,并且订阅者也会收到通知。客户端会先订阅test.subscribe事件,然后发送一条带有"data"字段的通知。
阅读全文