implement code for receiving events
[project/ubus.git] / listener.c
1 #include "libubus.h"
2
3 static struct ubus_context *ctx;
4 struct blob_buf b;
5
6 static const struct ubus_signature test_object_sig[] = {
7         UBUS_METHOD_START("hello"),
8           UBUS_ARRAY("test"),
9                 UBUS_TABLE_START(NULL),
10                   UBUS_FIELD(INT32, "id"),
11                   UBUS_FIELD(STRING, "msg"),
12                 UBUS_TABLE_END(),
13         UBUS_METHOD_END(),
14 };
15
16 static struct ubus_object_type test_object_type =
17         UBUS_OBJECT_TYPE("test", test_object_sig);
18
19 static int test_hello(struct ubus_context *ctx, struct ubus_object *obj,
20                       struct ubus_request_data *req, const char *method,
21                       struct blob_attr *msg)
22 {
23         char *strbuf;
24
25         blob_buf_init(&b, 0);
26         strbuf = blobmsg_alloc_string_buffer(&b, "message", 64 + strlen(obj->name));
27         sprintf(strbuf, "%s: Hello, world\n", obj->name);
28         blobmsg_add_string_buffer(&b);
29         ubus_send_reply(ctx, req, b.head);
30         return 0;
31 }
32
33 static const struct ubus_method test_methods[] = {
34         { .name = "hello", .handler = test_hello },
35 };
36
37 static struct ubus_object test_object = {
38         .name = "test",
39         .type = &test_object_type,
40         .methods = test_methods,
41         .n_methods = ARRAY_SIZE(test_methods),
42 };
43
44 static struct ubus_object test_object2 = {
45         .name = "test2",
46         .type = &test_object_type,
47         .methods = test_methods,
48         .n_methods = ARRAY_SIZE(test_methods),
49 };
50
51 int main(int argc, char **argv)
52 {
53         int ret;
54
55         ctx = ubus_connect(NULL);
56         if (!ctx) {
57                 fprintf(stderr, "Failed to connect to ubus\n");
58                 return -1;
59         }
60
61         fprintf(stderr, "Connected as ID 0x%08x\n", ctx->local_id);
62
63         fprintf(stderr, "Publishing object\n");
64         ret = ubus_publish(ctx, &test_object);
65         if (ret)
66                 fprintf(stderr, "Failed to publish object: %s\n", ubus_strerror(ret));
67         else {
68                 fprintf(stderr, "Object ID: %08x\n", test_object.id);
69                 fprintf(stderr, "Object Type ID: %08x\n", test_object.type->id);
70         }
71
72         fprintf(stderr, "Publishing object\n");
73         ret = ubus_publish(ctx, &test_object2);
74         if (ret)
75                 fprintf(stderr, "Failed to publish object: %s\n", ubus_strerror(ret));
76         else {
77                 fprintf(stderr, "Object ID: %08x\n", test_object2.id);
78                 fprintf(stderr, "Object Type ID: %08x\n", test_object2.type->id);
79         }
80         uloop_init();
81         ubus_add_uloop(ctx);
82         uloop_run();
83
84         ubus_free(ctx);
85         return 0;
86 }