Merge pull request #6 from tkummermehr/UCS_Interface_Cleanup
[apps/agl-service-unicens.git] / ucs2-afb / ucs_binding.c
1 /*
2  * Copyright (C) 2016 "IoT.bzh"
3  * Author Fulup Ar Foll <fulup@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  * references:
18  *   https://gist.github.com/ghedo/963382
19  *   http://alsa-utils.sourcearchive.com/documentation/1.0.15/aplay_8c-source.html
20  */
21
22 #define _GNU_SOURCE
23
24 #define BUFFER_FRAME_COUNT 10 /* max frames in buffer */
25 #define WAIT_TIMER_US 1000000 /* default waiting timer 1s */
26
27 #include <systemd/sd-event.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <stdio.h>
31 #include <fcntl.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <time.h>
35 #include <assert.h>
36 #include <errno.h>
37
38 #include "ucs_binding.h"
39 #include "ucs_interface.h"
40
41
42
43 #define MAX_FILENAME_LEN (100)
44 #define RX_BUFFER (64)
45
46 /** Internal structure, enabling multiple instances of this component.
47  * \note Do not access any of this variables.
48  *  */
49 typedef struct {
50     int fileHandle;
51     int fileFlags;
52     char fileName[MAX_FILENAME_LEN];
53     uint8_t rxBuffer[RX_BUFFER];
54     uint32_t rxLen;
55 } CdevData_t;
56
57
58 typedef struct {
59   CdevData_t rx;
60   CdevData_t tx;
61   UCSI_Data_t ucsiData;
62   UCSI_channelsT *channels;
63 } ucsContextT;
64
65 static ucsContextT *ucsContextS;
66
67 PUBLIC void UcsXml_CB_OnError(const char format[], uint16_t vargsCnt, ...) {
68     /*DEBUG (afbIface, format, args); */
69     va_list args;
70     va_start (args, vargsCnt);
71     vfprintf (stderr, format, args);
72     va_end(args);
73 }
74
75 PUBLIC uint16_t UCSI_CB_OnGetTime(void *pTag) {
76     struct timespec currentTime;
77     uint16_t timer;
78     pTag = pTag;
79
80     if (clock_gettime(CLOCK_MONOTONIC_RAW, &currentTime))   {
81         assert(false);
82         return 0;
83     }
84
85     timer = (uint16_t) ((currentTime.tv_sec * 1000 ) + ( currentTime.tv_nsec / 1000000 ));
86     return(timer);
87 }
88
89 STATIC int onTimerCB (sd_event_source* source,uint64_t timer, void* pTag) {
90     ucsContextT *ucsContext = (ucsContextT*) pTag;
91
92     sd_event_source_unref(source);
93     UCSI_Timeout(&ucsContext->ucsiData);
94
95     return 0;
96 }
97
98 /* UCS2 Interface Timer Callback */
99 PUBLIC void UCSI_CB_OnSetServiceTimer(void *pTag, uint16_t timeout) {
100   uint64_t usec;
101   /* set a timer with  250ms accuracy */
102   sd_event_now(afb_daemon_get_event_loop(afbIface->daemon), CLOCK_BOOTTIME, &usec);
103   sd_event_add_time(afb_daemon_get_event_loop(afbIface->daemon), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, onTimerCB, pTag);
104
105 }
106
107 /**
108  * \brief Callback when ever an Unicens forms a human readable message.
109  *        This can be error events or when enabled also debug messages.
110  * \note This function must be implemented by the integrator
111  * \param pTag - Pointer given by the integrator by UCSI_Init
112  * \param format - Zero terminated format string (following printf rules)
113  * \param vargsCnt - Amount of parameters stored in "..."
114  */
115 void UCSI_CB_OnUserMessage(void *pTag, bool isError, const char format[],
116     uint16_t vargsCnt, ...) {
117     va_list argptr;
118     char outbuf[300];
119     pTag = pTag;
120     va_start(argptr, vargsCnt);
121     vsprintf(outbuf, format, argptr);
122     va_end(argptr);
123     if (isError)
124         NOTICE (afbIface, outbuf);
125 }
126
127 /** UCSI_Service cannot be called directly within UNICENS context, need to service stack through mainloop */
128 STATIC int OnServiceRequiredCB (sd_event_source *source, uint64_t usec, void *pTag) {
129     ucsContextT *ucsContext = (ucsContextT*) pTag;
130
131     sd_event_source_unref(source);
132     UCSI_Service(&ucsContext->ucsiData);
133     return (0);
134 }
135
136 /* UCS Callback fire when ever UNICENS needs to be serviced */
137 PUBLIC void UCSI_CB_OnServiceRequired(void *pTag) {
138
139    /* push an asynchronous request for loopback to call UCSI_Service */
140    sd_event_add_time(afb_daemon_get_event_loop(afbIface->daemon), NULL, CLOCK_MONOTONIC, 0, 0, OnServiceRequiredCB, pTag);
141 }
142
143 /* Callback when ever this UNICENS wants to send a message to INIC. */
144 PUBLIC void UCSI_CB_OnTxRequest(void *pTag, const uint8_t *pData, uint32_t len) {
145     ucsContextT *ucsContext = (ucsContextT*) pTag;
146     CdevData_t *cdevTx = &ucsContext->tx;
147     uint32_t total = 0;
148
149     if (NULL == pData || 0 == len) return;
150
151     if (O_RDONLY == cdevTx->fileFlags) return;
152     if (-1 == cdevTx->fileHandle)
153         cdevTx->fileHandle = open(cdevTx->fileName, cdevTx->fileFlags);
154     if (-1 == cdevTx->fileHandle)
155         return;
156
157     while(total < len) {
158         ssize_t written = write(cdevTx->fileHandle, &pData[total], (len - total));
159         if (0 >= written)
160         {
161             /* Silently ignore write error (only occur in non-blocking mode) */
162             break;
163         }
164         total += (uint32_t) written;
165     }
166 }
167
168 /**
169  * \brief Callback when UNICENS instance has been stopped.
170  * \note This event can be used to free memory holding the resources
171  *       passed with UCSI_NewConfig
172  * \note This function must be implemented by the integrator
173  * \param pTag - Pointer given by the integrator by UCSI_Init
174  */
175 void UCSI_CB_OnStop(void *pTag) {
176     NOTICE (afbIface, "UNICENS stopped");
177
178 }
179
180 /** This callback will be raised, when ever an applicative message on the control channel arrived */
181 void UCSI_CB_OnAmsMessageReceived(void *pTag)
182 {
183         /* If not interested, just ignore this event.
184            Otherwise UCSI_GetAmsMessage may now be called asynchronous (mainloop) to get the content. 
185            Don't forget to call UCSI_ReleaseAmsMessage after that */
186 }
187
188 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
189 {
190     if (NULL == d || NULL == fileName)  goto OnErrorExit;
191
192     memset(d, 0, sizeof(CdevData_t));
193     strncpy(d->fileName, fileName, MAX_FILENAME_LEN);
194     d->fileHandle = -1;
195
196     if (read && write)
197         d->fileFlags = O_RDWR | O_NONBLOCK;
198     else if (read)
199         d->fileFlags = O_RDONLY | O_NONBLOCK;
200     else if (write)
201         d->fileFlags = O_WRONLY | O_NONBLOCK;
202
203     /* open file to enable event loop */
204     d->fileHandle = open(d->fileName, d->fileFlags);
205     if (d->fileHandle  <= 0) goto OnErrorExit;
206
207     return true;
208
209  OnErrorExit:
210     return false;
211 }
212
213 static bool InitializeCdevs(ucsContextT *ucsContext)
214 {
215     if(!Cdev_Init(&ucsContext->tx, CONTROL_CDEV_TX, false, true))
216         return false;
217     if(!Cdev_Init(&ucsContext->rx, CONTROL_CDEV_RX, true, false))
218         return false;
219     return true;
220 }
221
222 /* Callback fire when something is avaliable on MOST cdev */
223 int onReadCB (sd_event_source* src, int fileFd, uint32_t revents, void* pTag) {
224     ucsContextT *ucsContext =( ucsContextT*) pTag;
225     ssize_t len;
226     uint8_t pBuffer[RX_BUFFER];
227     int ok;
228
229     len = read (ucsContext->rx.fileHandle, &pBuffer, sizeof(pBuffer));
230     if (0 == len)
231         return 0;
232     ok= UCSI_ProcessRxData(&ucsContext->ucsiData, pBuffer, (uint16_t)len);
233     if (!ok) {
234         DEBUG (afbIface, "Buffer overrun (not handle)");
235         /* Buffer overrun could replay pBuffer */
236     }
237     return 0;
238 }
239
240 STATIC UcsXmlVal_t* ParseFile(struct afb_req request) {
241     char *xmlBuffer;
242     ssize_t readSize;
243     int fdHandle ;
244     struct stat fdStat;
245     UcsXmlVal_t* ucsConfig;
246
247     const char *filename = afb_req_value(request, "filename");
248     if (!filename) {
249         afb_req_fail_f (request, "filename-missing", "No filename given");
250         goto OnErrorExit;
251     }
252
253     fdHandle = open(filename, O_RDONLY);
254     if (fdHandle <= 0) {
255         afb_req_fail_f (request, "fileread-error", "File not accessible: '%s' err=%s", filename, strerror(fdHandle));
256         goto OnErrorExit;
257     }
258
259     /* read file into buffer as a \0 terminated string */
260     fstat(fdHandle, &fdStat);
261     xmlBuffer = (char*)alloca(fdStat.st_size + 1);
262     readSize = read(fdHandle, xmlBuffer, fdStat.st_size);
263     close(fdHandle);
264     xmlBuffer[readSize] = '\0'; /* In any case, terminate it. */
265
266     if (readSize != fdStat.st_size)  {
267         afb_req_fail_f (request, "fileread-fail", "File to read fullfile '%s' size(%d!=%d)", filename, readSize, fdStat.st_size);
268         goto OnErrorExit;
269     }
270
271     ucsConfig = UcsXml_Parse(xmlBuffer);
272     if (!ucsConfig)  {
273         afb_req_fail_f (request, "filexml-error", "File XML invalid: '%s'", filename);
274         goto OnErrorExit;
275     }
276
277     return (ucsConfig);
278
279  OnErrorExit:
280     return NULL;
281 }
282
283 STATIC int volOnSvcCB (sd_event_source* source,uint64_t timer, void* pTag) {
284     ucsContextT *ucsContext = (ucsContextT*) pTag;
285
286     sd_event_source_unref(source);
287     UCSI_Vol_Service(&ucsContext->ucsiData);
288
289     return 0;
290 }
291
292 /* This callback is fire each time an volume event wait in the queue */
293 void volumeCB (uint16_t timeout) {
294     uint64_t usec;
295     sd_event_now(afb_daemon_get_event_loop(afbIface->daemon), CLOCK_BOOTTIME, &usec);
296     sd_event_add_time(afb_daemon_get_event_loop(afbIface->daemon), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, volOnSvcCB, ucsContextS);
297 }
298
299 STATIC int volSndCmd (struct afb_req request, struct json_object *commandJ, ucsContextT *ucsContext) {
300     int numid, vol, err;
301     struct json_object *nameJ, *channelJ, *volJ;
302
303     enum json_type jtype= json_object_get_type(commandJ);
304     switch (jtype) {
305         case json_type_array:
306             if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 0)), "%d", &numid)) {
307                 afb_req_fail_f (request, "channel-invalid","command=%s channel is not an integer", json_object_get_string (channelJ));
308                 goto OnErrorExit;
309             }
310             if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 1)), "%d", &vol)) {
311                 afb_req_fail_f (request, "vol-invalid","command=%s vol is not an integer", json_object_get_string (channelJ));
312                 goto OnErrorExit;
313             }
314             break;
315
316         case json_type_object:
317             if (json_object_object_get_ex (commandJ, "numid", &channelJ)) {
318                 if (!sscanf (json_object_get_string (channelJ), "%d", &numid)) {
319                     afb_req_fail_f (request, "channel-invalid","command=%s numid is not an integer", json_object_get_string (channelJ));
320                     goto OnErrorExit;
321                 }
322             } else {
323                 if (json_object_object_get_ex (commandJ, "channel", &nameJ)) {
324                     int idx;
325                     const char *name = json_object_get_string(nameJ);
326
327                     for (idx =0; ucsContext->channels[idx].name != NULL; idx++) {
328                         if (!strcasecmp(ucsContext->channels[idx].name, name)) {
329                             numid = ucsContext->channels[idx].numid;
330                             break;
331                         }
332                     }
333                     if (ucsContext->channels[idx].name == NULL) {
334                         afb_req_fail_f (request, "channel-invalid","command=%s channel name does not exist", name);
335                         goto OnErrorExit;
336                     }
337                 } else {
338                     afb_req_fail_f (request, "channel-invalid","command=%s no valid channel name or channel", json_object_get_string(commandJ));
339                     goto OnErrorExit;
340                 };
341             }
342
343             if (!json_object_object_get_ex (commandJ, "volume", &volJ)) {
344                 afb_req_fail_f (request, "vol-missing","command=%s vol not present", json_object_get_string (commandJ));
345                 goto OnErrorExit;
346             }
347
348             if (!sscanf (json_object_get_string (volJ), "%d", &vol)) {
349                 afb_req_fail_f (request, "vol-invalid","command=%s vol:%s is not an integer", json_object_get_string (commandJ), json_object_get_string (volJ));
350                 goto OnErrorExit;
351             }
352
353             break;
354
355         default:
356             afb_req_fail_f (request, "setvol-invalid","command=%s not valid JSON Volume Command", json_object_get_string(commandJ));
357             goto OnErrorExit;
358     }
359
360
361     /* Fulup what's append when channel or vol are invalid ??? */
362     err = UCSI_Vol_Set  (&ucsContext->ucsiData, numid, (uint8_t) vol);
363     if (err) {
364         /* Fulup this might only be a warning (not sure about it) */
365         afb_req_fail_f (request, "vol-refused","command=%s vol was refused by UNICENS", json_object_get_string (volJ));
366         goto OnErrorExit;
367     }
368
369     return 0;
370
371   OnErrorExit:
372     return 1;
373 }
374
375
376 PUBLIC void ucs2SetVol (struct afb_req request) {
377     struct json_object *queryJ;
378     int err;
379
380     /* check UNICENS is initialised */
381     if (!ucsContextS) {
382         afb_req_fail_f (request, "UNICENS-init","Should Load Config before using setvol");
383         goto OnErrorExit;
384     }
385
386     queryJ = afb_req_json(request);
387     if (!queryJ) {
388         afb_req_fail_f (request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
389         goto OnErrorExit;
390     };
391
392     enum json_type jtype= json_object_get_type(queryJ);
393     switch (jtype) {
394         case json_type_array:
395             for (int idx=0; idx < json_object_array_length (queryJ); idx ++) {
396                err= volSndCmd (request, json_object_array_get_idx (queryJ, idx), ucsContextS);
397                if (err) goto OnErrorExit;
398             }
399             break;
400
401         case json_type_object:
402             err = volSndCmd (request, queryJ, ucsContextS);
403             if (err) goto OnErrorExit;
404             break;
405
406         default:
407             afb_req_fail_f (request, "query-notarray","query=%s not valid JSON Volume Command Array", afb_req_value(request,""));
408             goto OnErrorExit;
409     }
410
411
412     afb_req_success(request,NULL,NULL);
413
414  OnErrorExit:
415     return;
416 }
417
418
419 PUBLIC void ucs2Init (struct afb_req request) {
420     static UcsXmlVal_t *ucsConfig;
421     static ucsContextT ucsContext;
422
423     sd_event_source *evtSource;
424     int err;
425
426     /* Read and parse XML file */
427     ucsConfig = ParseFile (request);
428     if (NULL == ucsConfig) goto OnErrorExit;
429
430     /* When ucsContextS is set, do not initalize UNICENS, CDEVs or system hooks, just load new XML */
431     if (!ucsContextS)
432     {
433         if (!ucsContextS && !InitializeCdevs(&ucsContext))  {
434             afb_req_fail_f (request, "devnit-error", "Fail to initialise device [rx=%s tx=%s]", CONTROL_CDEV_RX, CONTROL_CDEV_TX);
435             goto OnErrorExit;
436         }
437
438         /* Initialise UNICENS Config Data Structure */
439         UCSI_Init(&ucsContext.ucsiData, &ucsContext);
440
441         /* register aplayHandle file fd into binder mainloop */
442         err = sd_event_add_io(afb_daemon_get_event_loop(afbIface->daemon), &evtSource, ucsContext.rx.fileHandle, EPOLLIN, onReadCB, &ucsContext);
443         if (err < 0) {
444             afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop");
445             goto OnErrorExit;
446         }
447
448         /* init UNICENS Volume Library */
449         ucsContext.channels = UCSI_Vol_Init (&ucsContext.ucsiData, volumeCB);
450         if (!ucsContext.channels) {
451             afb_req_fail_f (request, "register-volume", "Could not enqueue new Unicens config");
452             goto OnErrorExit;
453         }
454         /* save this in a statical variable until ucs2vol move to C */
455         ucsContextS = &ucsContext;
456     }
457     /* Initialise UNICENS with parsed config */
458     if (!UCSI_NewConfig(&ucsContext.ucsiData, ucsConfig))   {
459         afb_req_fail_f (request, "UNICENS-init", "Fail to initialize UNICENS");
460         goto OnErrorExit;
461     }
462
463     afb_req_success(request,NULL,"UNICENS-active");
464
465  OnErrorExit:
466     return;
467 }