openwrt ubus blob_buf結構體的使用

參考 libubus - tyheist - SegmentFault

還參考了openwrt軟件包裏的procd源代碼


blob二進制對象



blob消息對象



定義blob變量時:

static struct blob_buf b;
void *c;
blob_buf_init(&b, 0);
blobmsg_add_u32(&b, "uptime", info.uptime); //或 blobmsg_add_string
c = blobmsg_open_array(&b, "load");
blobmsg_add_u32(&b, NULL, info.loads[0]);
blobmsg_add_u32(&b, NULL, info.loads[1]);
blobmsg_add_u32(&b, NULL, info.loads[2]);
blobmsg_close_array(&b, c);
c = blobmsg_open_table(&b, "memory");
blobmsg_add_u64(&b, "total",    info.mem_unit * info.totalram);
blobmsg_add_u64(&b, "free",     info.mem_unit * info.freeram);
blobmsg_add_u64(&b, "shared",   info.mem_unit * info.sharedram);
blobmsg_add_u64(&b, "buffered", info.mem_unit * info.bufferram);
blobmsg_close_table(&b, c);
ubus_send_reply(ctx, req, b.head); //發送json消息體

最後顯示如下:

        "uptime": 434867,
        "load": [
                6560,
                11264,
                10272
        ],
        "memory": {
                "total": 129445888,
                "free": 47714304,
                "shared": 0,
                "buffered": 9179136
        },

	if (ubus_lookup_id(ctx, "system", &id)) {
		fprintf(stderr, "Failed to look up test object\n");
		return -1;
	}
	
	blob_buf_init(&b, 0);
	blobmsg_add_string(&b, "word", "hello");
	
	ubus_invoke_async(ctx, id, "info", b.head, &req);   //發起訂閱


調用別人給的blob變量:

enum {
	HE_WORD,
	__HE_MAX
};

static const struct blobmsg_policy re_policy[__HE_MAX] = {
	[HE_WORD] = { .name = "word", .type = BLOBMSG_TYPE_STRING },
};

static int test_notify(struct ubus_context *ctx, struct ubus_object *obj,
			      struct ubus_request_data *req,
			      const char *method, struct blob_attr *msg)
{
	fprintf(stderr, "receive notify\n");

	struct blob_attr *tb[__HE_MAX];

	if (!msg)
		return UBUS_STATUS_INVALID_ARGUMENT;
	blobmsg_parse(re_policy, __HE_MAX, tb, blob_data(msg), blob_len(msg));
	
	fprintf(stderr, "we receive :%s\n", blobmsg_get_string(tb[HE_WORD]));
	
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章