CMAKE: refactor options
[src/app-framework-binder.git] / bindings / samples / ave.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 #define _GNU_SOURCE
18 #include <stdio.h>
19 #include <string.h>
20 #include <pthread.h>
21
22 #include <json-c/json.h>
23
24 #define AFB_BINDING_VERSION 0
25 #include <afb/afb-binding.h>
26
27 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
28
29 struct event
30 {
31         struct event *next;
32         afb_eventid *eventid;
33         char tag[1];
34 };
35
36 static struct event *events = 0;
37
38 /* searchs the event of tag */
39 static struct event *event_get(const char *tag)
40 {
41         struct event *e = events;
42         while(e && strcmp(e->tag, tag))
43                 e = e->next;
44         return e;
45 }
46
47 /* deletes the event of tag */
48 static int event_del(const char *tag)
49 {
50         struct event *e, **p;
51
52         /* check exists */
53         e = event_get(tag);
54         if (!e) return -1;
55
56         /* unlink */
57         p = &events;
58         while(*p != e) p = &(*p)->next;
59         *p = e->next;
60
61         /* destroys */
62         afb_eventid_unref(e->eventid);
63         free(e);
64         return 0;
65 }
66
67 /* creates the event of tag */
68 static int event_add(afb_dynapi *dynapi, const char *tag, const char *name)
69 {
70         struct event *e;
71
72         /* check valid tag */
73         e = event_get(tag);
74         if (e) return -1;
75
76         /* creation */
77         e = malloc(strlen(tag) + sizeof *e);
78         if (!e) return -1;
79         strcpy(e->tag, tag);
80
81         /* make the event */
82         e->eventid = afb_dynapi_make_eventid(dynapi, name);
83         if (!e->eventid) { free(e); return -1; }
84
85         /* link */
86         e->next = events;
87         events = e;
88         return 0;
89 }
90
91 static int event_subscribe(afb_request *request, const char *tag)
92 {
93         struct event *e;
94         e = event_get(tag);
95         return e ? afb_request_subscribe(request, e->eventid) : -1;
96 }
97
98 static int event_unsubscribe(afb_request *request, const char *tag)
99 {
100         struct event *e;
101         e = event_get(tag);
102         return e ? afb_request_unsubscribe(request, e->eventid) : -1;
103 }
104
105 static int event_push(struct json_object *args, const char *tag)
106 {
107         struct event *e;
108         e = event_get(tag);
109         return e ? afb_eventid_push(e->eventid, json_object_get(args)) : -1;
110 }
111
112 static int event_broadcast(struct json_object *args, const char *tag)
113 {
114         struct event *e;
115         e = event_get(tag);
116         return e ? afb_eventid_broadcast(e->eventid, json_object_get(args)) : -1;
117 }
118
119 // Sample Generic Ping Debug API
120 static void ping(afb_request *request, json_object *jresp, const char *tag)
121 {
122         static int pingcount = 0;
123         json_object *query = afb_request_json(request);
124         afb_request_success_f(request, jresp, "Ping Binder Daemon tag=%s count=%d query=%s", tag, ++pingcount, json_object_to_json_string(query));
125 }
126
127 static void pingSample (afb_request *request)
128 {
129         ping(request, json_object_new_string ("Some String"), "pingSample");
130 }
131
132 static void pingFail (afb_request *request)
133 {
134         afb_request_fail(request, "failed", "Ping Binder Daemon fails");
135 }
136
137 static void pingNull (afb_request *request)
138 {
139         ping(request, NULL, "pingNull");
140 }
141
142 static void pingBug (afb_request *request)
143 {
144         ping(NULL, NULL, "pingBug");
145 }
146
147 static void pingEvent(afb_request *request)
148 {
149         json_object *query = afb_request_json(request);
150         afb_dynapi_broadcast_event(request->dynapi, "event", json_object_get(query));
151         ping(request, json_object_get(query), "event");
152 }
153
154
155 // For samples https://linuxprograms.wordpress.com/2010/05/20/json-c-libjson-tutorial/
156 static void pingJson (afb_request *request) {
157     json_object *jresp, *embed;
158
159     jresp = json_object_new_object();
160     json_object_object_add(jresp, "myString", json_object_new_string ("Some String"));
161     json_object_object_add(jresp, "myInt", json_object_new_int (1234));
162
163     embed  = json_object_new_object();
164     json_object_object_add(embed, "subObjString", json_object_new_string ("Some String"));
165     json_object_object_add(embed, "subObjInt", json_object_new_int (5678));
166
167     json_object_object_add(jresp,"eobj", embed);
168
169     ping(request, jresp, "pingJson");
170 }
171
172 static void subcallcb (void *closure, int status, json_object *object, afb_request *request)
173 {
174         if (status < 0)
175                 afb_request_fail(request, "failed", json_object_to_json_string(object));
176         else
177                 afb_request_success(request, json_object_get(object), NULL);
178 }
179
180 static void subcall (afb_request *request)
181 {
182         const char *api = afb_request_value(request, "api");
183         const char *verb = afb_request_value(request, "verb");
184         const char *args = afb_request_value(request, "args");
185         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
186
187         if (object == NULL)
188                 afb_request_fail(request, "failed", "bad arguments");
189         else
190                 afb_request_subcall(request, api, verb, object, subcallcb, NULL);
191 }
192
193 static void subcallsync (afb_request *request)
194 {
195         int rc;
196         const char *api = afb_request_value(request, "api");
197         const char *verb = afb_request_value(request, "verb");
198         const char *args = afb_request_value(request, "args");
199         json_object *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
200
201         if (object == NULL)
202                 afb_request_fail(request, "failed", "bad arguments");
203         else {
204                 rc = afb_request_subcall_sync(request, api, verb, object, &result);
205                 if (rc >= 0)
206                         afb_request_success(request, result, NULL);
207                 else {
208                         afb_request_fail(request, "failed", json_object_to_json_string(result));
209                         json_object_put(result);
210                 }
211         }
212 }
213
214 static void eventadd (afb_request *request)
215 {
216         const char *tag = afb_request_value(request, "tag");
217         const char *name = afb_request_value(request, "name");
218
219         pthread_mutex_lock(&mutex);
220         if (tag == NULL || name == NULL)
221                 afb_request_fail(request, "failed", "bad arguments");
222         else if (0 != event_add(request->dynapi, tag, name))
223                 afb_request_fail(request, "failed", "creation error");
224         else
225                 afb_request_success(request, NULL, NULL);
226         pthread_mutex_unlock(&mutex);
227 }
228
229 static void eventdel (afb_request *request)
230 {
231         const char *tag = afb_request_value(request, "tag");
232
233         pthread_mutex_lock(&mutex);
234         if (tag == NULL)
235                 afb_request_fail(request, "failed", "bad arguments");
236         else if (0 != event_del(tag))
237                 afb_request_fail(request, "failed", "deletion error");
238         else
239                 afb_request_success(request, NULL, NULL);
240         pthread_mutex_unlock(&mutex);
241 }
242
243 static void eventsub (afb_request *request)
244 {
245         const char *tag = afb_request_value(request, "tag");
246
247         pthread_mutex_lock(&mutex);
248         if (tag == NULL)
249                 afb_request_fail(request, "failed", "bad arguments");
250         else if (0 != event_subscribe(request, tag))
251                 afb_request_fail(request, "failed", "subscription error");
252         else
253                 afb_request_success(request, NULL, NULL);
254         pthread_mutex_unlock(&mutex);
255 }
256
257 static void eventunsub (afb_request *request)
258 {
259         const char *tag = afb_request_value(request, "tag");
260
261         pthread_mutex_lock(&mutex);
262         if (tag == NULL)
263                 afb_request_fail(request, "failed", "bad arguments");
264         else if (0 != event_unsubscribe(request, tag))
265                 afb_request_fail(request, "failed", "unsubscription error");
266         else
267                 afb_request_success(request, NULL, NULL);
268         pthread_mutex_unlock(&mutex);
269 }
270
271 static void eventpush (afb_request *request)
272 {
273         const char *tag = afb_request_value(request, "tag");
274         const char *data = afb_request_value(request, "data");
275         json_object *object = data ? json_tokener_parse(data) : NULL;
276
277         pthread_mutex_lock(&mutex);
278         if (tag == NULL)
279                 afb_request_fail(request, "failed", "bad arguments");
280         else if (0 > event_push(object, tag))
281                 afb_request_fail(request, "failed", "push error");
282         else
283                 afb_request_success(request, NULL, NULL);
284         pthread_mutex_unlock(&mutex);
285         json_object_put(object);
286 }
287
288 static void callcb (void *prequest, int status, json_object *object, afb_dynapi *dynapi)
289 {
290         afb_request *request = prequest;
291         if (status < 0)
292                 afb_request_fail(request, "failed", json_object_to_json_string(object));
293         else
294                 afb_request_success(request, json_object_get(object), NULL);
295         afb_request_unref(request);
296 }
297
298 static void call (afb_request *request)
299 {
300         const char *api = afb_request_value(request, "api");
301         const char *verb = afb_request_value(request, "verb");
302         const char *args = afb_request_value(request, "args");
303         json_object *object = api && verb && args ? json_tokener_parse(args) : NULL;
304
305         if (object == NULL)
306                 afb_request_fail(request, "failed", "bad arguments");
307         else
308                 afb_dynapi_call(request->dynapi, api, verb, object, callcb, afb_request_addref(request));
309 }
310
311 static void callsync (afb_request *request)
312 {
313         int rc;
314         const char *api = afb_request_value(request, "api");
315         const char *verb = afb_request_value(request, "verb");
316         const char *args = afb_request_value(request, "args");
317         json_object *result, *object = api && verb && args ? json_tokener_parse(args) : NULL;
318
319         if (object == NULL)
320                 afb_request_fail(request, "failed", "bad arguments");
321         else {
322                 rc = afb_dynapi_call_sync(request->dynapi, api, verb, object, &result);
323                 if (rc >= 0)
324                         afb_request_success(request, result, NULL);
325                 else {
326                         afb_request_fail(request, "failed", json_object_to_json_string(result));
327                         json_object_put(result);
328                 }
329         }
330 }
331
332 static void verbose (afb_request *request)
333 {
334         int level = 5;
335         json_object *query = afb_request_json(request), *l;
336
337         if (json_object_is_type(query,json_type_int))
338                 level = json_object_get_int(query);
339         else if (json_object_object_get_ex(query, "level", &l) && json_object_is_type(l, json_type_int))
340                 level = json_object_get_int(l);
341
342         if (!json_object_object_get_ex(query,"message",&l))
343                 l = query;
344
345         AFB_REQUEST_VERBOSE(request, level, "verbose called for %s", json_object_get_string(l));
346         afb_request_success(request, NULL, NULL);
347 }
348
349 static void exitnow (afb_request *request)
350 {
351         int code = 0;
352         json_object *query = afb_request_json(request), *l;
353
354         if (json_object_is_type(query,json_type_int))
355                 code = json_object_get_int(query);
356         else if (json_object_object_get_ex(query, "code", &l) && json_object_is_type(l, json_type_int))
357                 code = json_object_get_int(l);
358
359         if (!json_object_object_get_ex(query,"reason",&l))
360                 l = NULL;
361
362         AFB_REQUEST_NOTICE(request, "in phase of exiting with code %d, reason: %s", code, l ? json_object_get_string(l) : "unknown");
363         afb_request_success(request, NULL, NULL);
364         exit(code);
365 }
366
367 static void broadcast(afb_request *request)
368 {
369         const char *tag = afb_request_value(request, "tag");
370         const char *name = afb_request_value(request, "name");
371         const char *data = afb_request_value(request, "data");
372         json_object *object = data ? json_tokener_parse(data) : NULL;
373
374         if (tag != NULL) {
375                 pthread_mutex_lock(&mutex);
376                 if (0 > event_broadcast(object, tag))
377                         afb_request_fail(request, "failed", "broadcast error");
378                 else
379                         afb_request_success(request, NULL, NULL);
380                 pthread_mutex_unlock(&mutex);
381         } else if (name != NULL) {
382                 if (0 > afb_dynapi_broadcast_event(request->dynapi, name, object))
383                         afb_request_fail(request, "failed", "broadcast error");
384                 else
385                         afb_request_success(request, NULL, NULL);
386         } else {
387                 afb_request_fail(request, "failed", "bad arguments");
388         }
389         json_object_put(object);
390 }
391
392 static void hasperm (afb_request *request)
393 {
394         const char *perm = afb_request_value(request, "perm");
395         if (afb_request_has_permission(request, perm))
396                 afb_request_success_f(request, NULL, "permission %s granted", perm?:"(null)");
397         else
398                 afb_request_fail_f(request, "not-granted", "permission %s NOT granted", perm?:"(null)");
399 }
400
401 static void appid (afb_request *request)
402 {
403         char *aid = afb_request_get_application_id(request);
404         afb_request_success_f(request, aid ? json_object_new_string(aid) : NULL, "application is %s", aid?:"?");
405         free(aid);
406 }
407
408 static int init(afb_dynapi *dynapi)
409 {
410         AFB_DYNAPI_NOTICE(dynapi, "dynamic binding AVE(%s) starting", (const char*)dynapi->userdata);
411         return 0;
412 }
413
414 static void onevent(afb_dynapi *dynapi, const char *event, struct json_object *object)
415 {
416         AFB_DYNAPI_NOTICE(dynapi, "received event %s(%s) by AVE(%s)",
417                         event, json_object_to_json_string(object),
418                         (const char*)afb_dynapi_get_userdata(dynapi));
419 }
420
421 // NOTE: this sample does not use session to keep test a basic as possible
422 //       in real application most APIs should be protected with AFB_SESSION_CHECK
423 static const struct {
424         const char *verb;
425         void (*callback)(afb_request*); } verbs[] =
426 {
427   { .verb="ping",        .callback=pingSample },
428   { .verb="pingfail",    .callback=pingFail },
429   { .verb="pingnull",    .callback=pingNull },
430   { .verb="pingbug",     .callback=pingBug },
431   { .verb="pingJson",    .callback=pingJson },
432   { .verb="pingevent",   .callback=pingEvent },
433   { .verb="subcall",     .callback=subcall },
434   { .verb="subcallsync", .callback=subcallsync },
435   { .verb="eventadd",    .callback=eventadd },
436   { .verb="eventdel",    .callback=eventdel },
437   { .verb="eventsub",    .callback=eventsub },
438   { .verb="eventunsub",  .callback=eventunsub },
439   { .verb="eventpush",   .callback=eventpush },
440   { .verb="call",        .callback=call },
441   { .verb="callsync",    .callback=callsync },
442   { .verb="verbose",     .callback=verbose },
443   { .verb="broadcast",   .callback=broadcast },
444   { .verb="hasperm",     .callback=hasperm },
445   { .verb="appid",       .callback=appid },
446   { .verb="exit",        .callback=exitnow },
447   { .verb=NULL}
448 };
449
450 static void pingoo(afb_req req)
451 {
452         json_object *args = afb_req_json(req);
453         afb_req_success_f(req, json_object_get(args), "You reached pingoo \\o/ nice args: %s", json_object_to_json_string(args));
454 }
455
456 static const afb_verb_v2 verbsv2[]= {
457   { .verb="pingoo",      .callback=pingoo },
458   { .verb="ping",      .callback=pingoo },
459   { .verb=NULL}
460 };
461
462 static const char *apis[] = { "ave", "hi", "salut", NULL };
463
464 static int build_api(void *closure, afb_dynapi *dynapi)
465 {
466         int i, rc;
467
468         afb_dynapi_set_userdata(dynapi, closure);
469         AFB_DYNAPI_NOTICE(dynapi, "dynamic binding AVE(%s) comes to live", (const char*)afb_dynapi_get_userdata(dynapi));
470         afb_dynapi_on_init(dynapi, init);
471         afb_dynapi_on_event(dynapi, onevent);
472
473         rc = afb_dynapi_set_verbs_v2(dynapi, verbsv2);
474         for (i = rc = 0; verbs[i].verb && rc >= 0 ; i++) {
475                 rc = afb_dynapi_add_verb(dynapi, verbs[i].verb, NULL, verbs[i].callback, (void*)(intptr_t)i, NULL, 0);
476         }
477         afb_dynapi_seal(dynapi);
478         return rc;
479 }
480
481 int afbBindingVdyn(afb_dynapi *dynapi)
482 {
483         int i, rc;
484
485         for (i = 0; apis[i] ; i++) {
486                 rc = afb_dynapi_new_api(dynapi, apis[i], NULL, 0, build_api, (void*)apis[i]);
487                 if (rc < 0)
488                         AFB_DYNAPI_ERROR(dynapi, "can't create API %s", apis[i]);
489         }
490         return 0;
491 }
492